Skip to content

Commit

Permalink
Add completed orders and remove mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeljscript committed Sep 10, 2023
1 parent 73eecee commit 9dd7d29
Show file tree
Hide file tree
Showing 11 changed files with 194 additions and 141 deletions.
Original file line number Diff line number Diff line change
@@ -1,56 +1,100 @@
import {useOrderByStatusCompleted} from '@yoroi/swap'
import _ from 'lodash'
import React from 'react'
import {useIntl} from 'react-intl'
import {Linking, ScrollView, StyleSheet, TouchableOpacity, View} from 'react-native'

import {
ExpandableInfoCard,
ExpandableInfoCardSkeleton,
HeaderWrapper,
HiddenInfoWrapper,
Icon,
MainInfoWrapper,
Spacer,
Text,
TokenIcon,
} from '../../../../../components'
import {useLanguage} from '../../../../../i18n'
import {useSearch} from '../../../../../Search/SearchContext'
import {useSelectedWallet} from '../../../../../SelectedWallet'
import {COLORS} from '../../../../../theme'
import {useTokenInfos, useTransactionInfos} from '../../../../../yoroi-wallets/hooks'
import {Counter} from '../../../common/Counter/Counter'
import {PoolIcon} from '../../../common/PoolIcon/PoolIcon'
import {useStrings} from '../../../common/strings'
import {OrderProps} from './mapOrders'
import {getMockOrders} from './mocks'
import {mapOrders} from './mapOrders'

export const CompletedOrders = () => {
const strings = useStrings()
const {search} = useSearch()
const wallet = useSelectedWallet()
const [hiddenInfoOpenId, setHiddenInfoOpenId] = React.useState<string | null>(null)

const orders = getMockOrders().filter(
({assetFromLabel, assetToLabel}) =>
assetFromLabel.toLocaleLowerCase().includes(search.toLocaleLowerCase()) ||
assetToLabel.toLocaleLowerCase().includes(search.toLocaleLowerCase()),
)
const transactionsInfos = useTransactionInfos(wallet)
const {search} = useSearch()
const {numberLocale} = useLanguage()
const intl = useIntl()

const orders = useOrderByStatusCompleted({
queryKey: [wallet.id, 'completed-orders'],
onError: (err) => {
console.log(err)
},
})
const tokenIds = _.uniq(orders.flatMap((o) => [o.from.tokenId, o.to.tokenId]))

const tokenInfos = useTokenInfos({wallet, tokenIds: tokenIds})

const normalizedOrders = mapOrders(orders, tokenInfos, numberLocale, Object.values(transactionsInfos))

const searchLower = search.toLocaleLowerCase()

const filteredOrders = normalizedOrders.filter((order) => {
return (
order.assetFromLabel.toLocaleLowerCase().includes(searchLower) ||
order.assetToLabel.toLocaleLowerCase().includes(searchLower)
)
})

return (
<>
<ScrollView style={styles.container}>
{orders.map((order) => {
{filteredOrders.map((order) => {
const id = `${order.assetFromLabel}-${order.assetToLabel}-${order.date}`
const extended = id === hiddenInfoOpenId
const liquidityPoolIcon = <PoolIcon size={32} providerId={order.provider} />
const fromIcon = <TokenIcon wallet={wallet} tokenId={order.fromTokenInfo?.id ?? ''} variant="swap" />
const toIcon = <TokenIcon wallet={wallet} tokenId={order.toTokenInfo?.id ?? ''} variant="swap" />
return (
<ExpandableInfoCard
key={`${order.assetFromLabel}-${order.assetToLabel}-${order.date}`}
adornment={<HiddenInfo id={id} order={order} />}
adornment={
<HiddenInfo
txId={order.txId}
total={`${order.total} ${order.assetFromLabel}`}
txLink={order.txLink}
date={intl.formatDate(new Date(order.date), {dateStyle: 'short', timeStyle: 'short'})}
liquidityPoolIcon={liquidityPoolIcon}
liquidityPoolName={order.provider}
poolUrl={order.poolUrl}
/>
}
header={
<Header
onPress={() => setHiddenInfoOpenId(hiddenInfoOpenId !== id ? id : null)}
assetFromLabel={order.assetFromLabel}
assetToLabel={order.assetToLabel}
assetFromIcon={fromIcon}
assetToIcon={toIcon}
extended={extended}
/>
}
extended={extended}
withBoxShadow
>
<MainInfo order={order} />
<MainInfo
tokenAmount={`${order.tokenAmount} ${order.assetToLabel}`}
tokenPrice={`${order.tokenPrice} ${order.assetFromLabel}`}
/>
</ExpandableInfoCard>
)
})}
Expand All @@ -64,18 +108,22 @@ export const CompletedOrders = () => {
const Header = ({
assetFromLabel,
assetToLabel,
assetFromIcon,
assetToIcon,
extended,
onPress,
}: {
assetFromLabel: string
assetToLabel: string
assetFromIcon: React.ReactNode
assetToIcon: React.ReactNode
extended: boolean
onPress: () => void
}) => {
return (
<HeaderWrapper extended={extended} onPress={onPress}>
<View style={styles.label}>
<Icon.YoroiNightly size={24} />
{assetFromIcon}

<Spacer width={4} />

Expand All @@ -85,7 +133,7 @@ const Header = ({

<Spacer width={4} />

<Icon.Assets size={24} />
{assetToIcon}

<Spacer width={4} />

Expand All @@ -95,32 +143,48 @@ const Header = ({
)
}

const HiddenInfo = ({order}: {id: string; order: OrderProps}) => {
const HiddenInfo = ({
total,
liquidityPoolIcon,
liquidityPoolName,
poolUrl,
date,
txId,
txLink,
}: {
total: string
liquidityPoolIcon: React.ReactNode
liquidityPoolName: string
poolUrl: string
date: string
txId: string
txLink: string
}) => {
const strings = useStrings()
return (
<View>
{[
{
label: strings.listOrdersTotal,
value: order.total,
value: total,
},
{
label: strings.listOrdersLiquidityPool,
value: (
<LiquidityPool
liquidityPoolIcon={order.liquidityPoolIcon}
liquidityPoolName={order.liquidityPoolName}
poolUrl={order.poolUrl}
liquidityPoolIcon={liquidityPoolIcon}
liquidityPoolName={liquidityPoolName}
poolUrl={poolUrl}
/>
),
},
{
label: strings.listOrdersTimeCreated,
value: order.date,
value: date,
},
{
label: strings.listOrdersTxId,
value: <TxLink txId={order.txId} txLink={order.txLink} />,
value: <TxLink txId={txId} txLink={txLink} />,
},
].map((item) => (
<HiddenInfoWrapper key={item.label} value={item.value} label={item.label} />
Expand All @@ -129,13 +193,13 @@ const HiddenInfo = ({order}: {id: string; order: OrderProps}) => {
)
}

const MainInfo = ({order}: {order: OrderProps}) => {
const MainInfo = ({tokenPrice, tokenAmount}: {tokenPrice: string; tokenAmount: string}) => {
const strings = useStrings()
return (
<View>
{[
{label: strings.listOrdersSheetAssetPrice, value: order.tokenPrice},
{label: strings.listOrdersSheetAssetAmount, value: order.tokenAmount},
{label: strings.listOrdersSheetAssetPrice, value: tokenPrice},
{label: strings.listOrdersSheetAssetAmount, value: tokenAmount},
].map((item, index) => (
<MainInfoWrapper key={index} label={item.label} value={item.value} isLast={index === 1} />
))}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export const OpenOrders = () => {
const {search} = useSearch()

const orders = useOrderByStatusOpen({
queryKey: [wallet.id, 'open-orders'],
onError: (err) => {
console.log(err)
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,12 @@ import {Balance} from '@yoroi/types'
import {SwapOrder} from '@yoroi/types/lib/swap/order'
import {isString} from '@yoroi/wallets'
import BigNumber from 'bignumber.js'
import React from 'react'

import {NumberLocale} from '../../../../../i18n/languages'
import {TransactionInfo} from '../../../../../yoroi-wallets/types'
import {Quantities} from '../../../../../yoroi-wallets/utils'

export type OrderProps = {
tokenPrice: string
tokenAmount: string
assetFromLabel: string
assetFromIcon: React.ReactNode
assetToLabel: string
assetToIcon: React.ReactNode
date: string
liquidityPoolIcon: React.ReactNode
liquidityPoolName: string
txId: string
total: string
poolUrl: string
txLink: string
}
const MAX_DECIMALS = 10

export const mapOrders = (
orders: Array<SwapOrder>,
Expand All @@ -37,15 +22,19 @@ export const mapOrders = (
const id = `${order.from.tokenId}-${order.to.tokenId}-${order.utxo}`
const fromLabel = fromTokenInfo?.ticker ?? fromTokenInfo?.name ?? '-'
const toLabel = toTokenInfo?.ticker ?? toTokenInfo?.name ?? '-'
const tokenAmount = BigNumber(Quantities.denominated(order.to.quantity, toTokenInfo?.decimals ?? 0)).toFormat(
numberLocale,
)
const tokenAmount = BigNumber(Quantities.denominated(order.to.quantity, toTokenInfo?.decimals ?? 0))
.decimalPlaces(MAX_DECIMALS)
.toFormat({
...numberLocale,
})
const tokenPrice = BigNumber(
Quantities.quotient(
Quantities.denominated(order.from.quantity, fromTokenInfo?.decimals ?? 0),
Quantities.denominated(order.to.quantity, toTokenInfo?.decimals ?? 0),
),
).toFormat(numberLocale)
)
.decimalPlaces(MAX_DECIMALS)
.toFormat(numberLocale)
const txId = order.utxo.split('#')[0]
const total = BigNumber(Quantities.denominated(order.from.quantity, fromTokenInfo?.decimals ?? 0)).toFormat(
numberLocale,
Expand Down

This file was deleted.

8 changes: 8 additions & 0 deletions packages/openswap/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {AxiosInstance} from 'axios'
import {
cancelOrder, // returns an unsigned transaction to cancel the order.
createOrder, // returns a datum and a contract address to create the order transaction.
getCompletedOrders,
getOrders, // returns all orders for a given stake key hash.
} from './orders'
import {getPools} from './pools'
Expand Down Expand Up @@ -43,6 +44,13 @@ export class OpenSwapApi {
)
}

public async getCompletedOrders(stakeKeyHash: string) {
return getCompletedOrders(
{network: this.network, client: this.client},
{stakeKeyHash},
)
}

public async getPools({
tokenA,
tokenB,
Expand Down
2 changes: 2 additions & 0 deletions packages/openswap/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export const SWAP_API_ENDPOINTS = {
mainnet: {
getPools: 'https://onchain2.muesliswap.com/pools/pair',
getOrders: 'https://onchain2.muesliswap.com/orders/all/',
getCompletedOrders: 'https://api.muesliswap.com/orders/v2',
getTokens: 'https://api.muesliswap.com/list',
constructSwapDatum: 'https://aggregator.muesliswap.com/constructSwapDatum',
cancelSwapTransaction:
Expand All @@ -12,6 +13,7 @@ export const SWAP_API_ENDPOINTS = {
preprod: {
getPools: 'https://preprod.pools.muesliswap.com/pools/pair',
getOrders: 'https://preprod.pools.muesliswap.com/orders/all/',
getCompletedOrders: 'https://api.muesliswap.com/orders/v2',
getTokens: 'https://preprod.api.muesliswap.com/list',
constructSwapDatum:
'https://aggregator.muesliswap.com/constructTestnetSwapDatum',
Expand Down
41 changes: 41 additions & 0 deletions packages/openswap/src/orders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
CreateOrderRequest,
CreateOrderResponse,
Order,
ApiV2Order,
} from './types'

export async function createOrder(
Expand Down Expand Up @@ -89,3 +90,43 @@ export async function getOrders(

return response.data
}

export async function getCompletedOrders(
deps: ApiDeps,
args: {stakeKeyHash: string},
): Promise<Order[]> {
const {network, client} = deps
const {stakeKeyHash} = args
const apiUrl = SWAP_API_ENDPOINTS[network].getCompletedOrders
const response = await client.get<ApiV2Order[]>(apiUrl, {
params: {
'stake-key-hash': stakeKeyHash,
'canceled': 'n',
'open': 'n',
'matched': 'y',
'v2_only': 'y',
},
})

if (response.status !== 200) {
throw new Error(`Failed to get orders for ${stakeKeyHash}`, {
cause: response.data,
})
}

return response.data
.filter((order) => order.status === 'matched')
.map((order) => ({
provider: 'muesliswap_v4', // https://api.muesliswap.com/orders/v2 does not respond with the `provider` yet
utxo: order.txHash,
from: {
amount: order.fromAmount,
token: `${order.fromToken.address.policyId}.${order.fromToken.address.name}`,
},
to: {
amount: order.toAmount,
token: `${order.toToken.address.policyId}.${order.toToken.address.name}`,
},
deposit: '0', // https://api.muesliswap.com/orders/v2 does not respond with the `deposit` yet
}))
}
Loading

0 comments on commit 9dd7d29

Please sign in to comment.