Skip to content

Commit

Permalink
chore: change sell/buy id
Browse files Browse the repository at this point in the history
  • Loading branch information
stackchain committed Oct 8, 2023
1 parent d5d36ef commit 1f8c8d8
Show file tree
Hide file tree
Showing 14 changed files with 98 additions and 69 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export const AmountCard = ({
<Spacer height={4} />

<Text style={styles.errorText}>
{orderData.calculatedPool === undefined
{orderData.selectedPoolCalculation === undefined
? strings.noPool
: isSell
? strings.notEnoughBalance
Expand Down
2 changes: 1 addition & 1 deletion apps/wallet-mobile/src/features/Swap/common/useSwapTx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {splitStringInto64CharArray} from '../../../yoroi-wallets/utils'

export const useSwapTx = (options?: UseMutationOptions<YoroiUnsignedTx, Error, {entry: YoroiEntry; datum: Datum}>) => {
const {orderData} = useSwap()
const pool = orderData.calculatedPool?.pool
const pool = orderData.selectedPoolCalculation?.pool
const metadata = [
{
label: '674',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const ConfirmTxScreen = () => {
signTx: {useErrorBoundary: true},
submitTx: {
onSuccess: () => {
if (orderData.calculatedPool === undefined) return
if (orderData.selectedPoolCalculation === undefined) return
track.swapOrderSubmitted({
from_asset: [
{asset_name: sellTokenInfo.name, asset_ticker: sellTokenInfo.ticker, policy_id: sellTokenInfo.group},
Expand All @@ -63,8 +63,8 @@ export const ConfirmTxScreen = () => {
slippage_tolerance: orderData.slippage,
from_amount: orderData.amounts.sell.quantity,
to_amount: orderData.amounts.buy.quantity,
pool_source: orderData.calculatedPool.pool.provider,
swap_fees: Number(orderData.calculatedPool.cost.batcherFee),
pool_source: orderData.selectedPoolCalculation.pool.provider,
swap_fees: Number(orderData.selectedPoolCalculation.cost.batcherFee),
})

navigate.submittedTx()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const TransactionSummary = () => {
const wallet = useSelectedWallet()
const {numberLocale} = useLanguage()
const {orderData} = useSwap()
const {amounts, calculatedPool} = orderData
const {amounts, selectedPoolCalculation} = orderData

const buyTokenInfo = useTokenInfo({wallet, tokenId: amounts.buy.tokenId})
const tokenToBuyName = buyTokenInfo.ticker ?? buyTokenInfo.name
Expand All @@ -32,7 +32,7 @@ export const TransactionSummary = () => {
{
label: strings.swapMinAdaTitle,
value: `${Quantities.format(
calculatedPool?.cost?.deposit?.quantity ?? Quantities.zero,
selectedPoolCalculation?.cost?.deposit?.quantity ?? Quantities.zero,
Number(wallet.primaryTokenInfo.decimals),
)} ${wallet.primaryTokenInfo.ticker}`,
info: strings.swapMinAda,
Expand All @@ -50,7 +50,7 @@ export const TransactionSummary = () => {
{
label: strings.swapFeesTitle,
value: `${Quantities.format(
calculatedPool?.cost?.batcherFee?.quantity ?? Quantities.zero, // TODO: Show all fees
selectedPoolCalculation?.cost?.batcherFee?.quantity ?? Quantities.zero, // TODO: Show all fees
Number(wallet.primaryTokenInfo.decimals),
)} ${wallet.primaryTokenInfo.ticker}`,
info: strings.swapFees,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {makeLimitOrder, makePossibleMarketOrder, useSwap, useSwapCreateOrder, useSwapPoolsByPair} from '@yoroi/swap'
import {makeLimitOrder, makePossibleMarketOrder, useSwap, useSwapCreateOrder} from '@yoroi/swap'
import {Swap} from '@yoroi/types'
import BigNumber from 'bignumber.js'
import React, {useEffect, useState} from 'react'
Expand Down Expand Up @@ -31,7 +31,7 @@ const LIMIT_PRICE_WARNING_THRESHOLD = 0.1 // 10%
export const CreateOrder = () => {
const strings = useStrings()
const navigation = useNavigateTo()
const {orderData, poolPairsChanged, unsignedTxChanged} = useSwap()
const {orderData, unsignedTxChanged} = useSwap()
const wallet = useSelectedWallet()
const {track} = useMetrics()

Expand All @@ -45,18 +45,10 @@ export const CreateOrder = () => {
})
const [showLimitPriceWarning, setShowLimitPriceWarning] = useState(false)
const {isBuyTouched, isSellTouched, poolDefaulted} = useSwapTouched()
const {poolList} = useSwapPoolsByPair({
tokenA: orderData.amounts.sell.tokenId ?? '',
tokenB: orderData.amounts.buy.tokenId ?? '',
})

useEffect(() => {
poolPairsChanged(poolList ?? [])
}, [poolPairsChanged, poolList])

useEffect(() => {
if (orderData.selectedPoolId === orderData.bestPool?.pool.poolId) poolDefaulted()
}, [orderData.selectedPoolId, orderData.bestPool, poolDefaulted])
if (orderData.selectedPoolId === orderData.bestPoolCalculation?.pool.poolId) poolDefaulted()
}, [orderData.selectedPoolId, orderData.bestPoolCalculation, poolDefaulted])

const {createUnsignedTx, isLoading} = useSwapTx({
onSuccess: (yoroiUnsignedTx) => {
Expand All @@ -71,15 +63,15 @@ export const CreateOrder = () => {

const {createOrderData} = useSwapCreateOrder({
onSuccess: (data: Swap.CreateOrderResponse) => {
if (data?.contractAddress !== undefined && orderData.calculatedPool?.pool !== undefined) {
const {amounts, limitPrice, slippage, calculatedPool} = orderData
if (data?.contractAddress !== undefined && orderData.selectedPoolCalculation?.pool !== undefined) {
const {amounts, limitPrice, slippage, selectedPoolCalculation} = orderData
const entry = createYoroiEntry(
{
amounts,
limitPrice,
address: data.contractAddress,
slippage,
selectedPool: calculatedPool.pool,
selectedPool: selectedPoolCalculation.pool,
},
data.contractAddress,
wallet,
Expand All @@ -101,7 +93,7 @@ export const CreateOrder = () => {
(orderData.type === 'limit' && orderData.limitPrice !== undefined && Quantities.isZero(orderData.limitPrice))

const swap = () => {
if (orderData.calculatedPool === undefined) return
if (orderData.selectedPoolCalculation === undefined) return
track.swapOrderSelected({
from_asset: [
{asset_name: sellTokenInfo.name, asset_ticker: sellTokenInfo.ticker, policy_id: sellTokenInfo.group},
Expand All @@ -111,10 +103,10 @@ export const CreateOrder = () => {
slippage_tolerance: orderData.slippage,
from_amount: orderData.amounts.sell.quantity,
to_amount: orderData.amounts.buy.quantity,
pool_source: orderData.calculatedPool.pool.provider,
pool_source: orderData.selectedPoolCalculation.pool.provider,
swap_fees: Number(
Quantities.denominated(
orderData.calculatedPool.pool.batcherFee.quantity,
orderData.selectedPoolCalculation.pool.batcherFee.quantity,
Number(wallet.primaryTokenInfo.decimals),
),
),
Expand All @@ -128,7 +120,7 @@ export const CreateOrder = () => {
sell: orderData.amounts.sell,
buy: orderData.amounts.buy,
pools: orderData.pools,
selectedPool: orderData.calculatedPool?.pool,
selectedPool: orderData.selectedPoolCalculation?.pool,
slippage: orderData.slippage,
address: wallet.externalAddresses[0],
}
Expand Down Expand Up @@ -171,9 +163,9 @@ export const CreateOrder = () => {
}

const handleOnSwap = () => {
if (orderData.calculatedPool === undefined) return
if (orderData.selectedPoolCalculation === undefined) return
if (orderData.type === 'limit' && orderData.limitPrice !== undefined) {
const marketPrice = new BigNumber(orderData.calculatedPool.prices.market)
const marketPrice = new BigNumber(orderData.selectedPoolCalculation.prices.market)
const limitPrice = new BigNumber(orderData.limitPrice)

if (limitPrice.isGreaterThan(marketPrice.times(1 + LIMIT_PRICE_WARNING_THRESHOLD))) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const EditBuyAmount = () => {

const {orderData, buyQuantityChanged} = useSwap()
const {isBuyTouched} = useSwapTouched()
const pool = orderData.calculatedPool?.pool
const pool = orderData.selectedPoolCalculation?.pool
const {tokenId, quantity} = orderData.amounts.buy
const tokenInfo = useTokenInfo({wallet, tokenId})
const {decimals} = tokenInfo
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {FlashList} from '@shopify/flash-list'
import {useSwap, useSwapPoolsByPair, useSwapTokensByPairToken} from '@yoroi/swap'
import {Balance} from '@yoroi/types'
import React from 'react'
import {StyleSheet, TouchableOpacity, View} from 'react-native'
import {InteractionManager, StyleSheet, TouchableOpacity, View} from 'react-native'
import {SafeAreaView} from 'react-native-safe-area-context'

import {Boundary, Icon, Spacer, Text} from '../../../../../../../components'
Expand Down Expand Up @@ -178,19 +178,30 @@ const TokenList = () => {
type SelectableTokenProps = {disabled?: boolean; tokenForList: TokenForList; wallet: YoroiWallet}
const SelectableToken = ({tokenForList, wallet}: SelectableTokenProps) => {
const {closeSearch} = useSearch()
const {buyTokenIdChanged, orderData} = useSwap()
const {buyTokenIdChanged, poolPairsChanged, orderData} = useSwap()
const {buyTouched} = useSwapTouched()
const {refetch} = useSwapPoolsByPair(
{
tokenA: orderData.amounts.buy.tokenId,
tokenB: orderData.amounts.sell.tokenId,
},
{
useErrorBoundary: true,
enabled: false,
onSuccess: (pools) => {
buyTouched()
closeSearch()
poolPairsChanged(pools)

InteractionManager.runAfterInteractions(() => {
navigateTo.startSwap()
})
},
},
)

React.useEffect(() => {
console.log('refetch')
refetch()
}, [refetch, orderData.amounts.buy.tokenId])

const navigateTo = useNavigateTo()
Expand All @@ -201,10 +212,7 @@ const SelectableToken = ({tokenForList, wallet}: SelectableTokenProps) => {
track.swapAssetToChanged({
to_asset: [{asset_name: tokenForList.name, asset_ticker: tokenForList.ticker, policy_id: tokenForList.group}],
})
buyTouched()
buyTokenIdChanged({tokenId: tokenForList.id, pools: []})
navigateTo.startSwap()
closeSearch()
buyTokenIdChanged(tokenForList.id)
}

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ export const EditLimitPrice = () => {
if (orderData.type === 'limit') {
setText(Quantities.format(orderData.limitPrice ?? Quantities.zero, denomination, PRECISION))
} else {
setText(Quantities.format(orderData.calculatedPool?.prices.market ?? Quantities.zero, denomination, PRECISION))
setText(
Quantities.format(orderData.selectedPoolCalculation?.prices.market ?? Quantities.zero, denomination, PRECISION),
)
}
}, [orderData.type, orderData.limitPrice, orderData.amounts.sell, denomination, orderData.calculatedPool])
}, [orderData.type, orderData.limitPrice, orderData.amounts.sell, denomination, orderData.selectedPoolCalculation])

const onChange = (text: string) => {
const [formattedPrice, price] = Quantities.parseFromText(text, PRECISION, numberLocale)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,30 +26,33 @@ export const ShowPoolActions = () => {
const {orderData} = useSwap()
const strings = useStrings()
const {isBuyTouched, isSellTouched, isPoolTouched} = useSwapTouched()
const {calculatedPool, amounts} = orderData
const {selectedPoolCalculation, amounts} = orderData
const wallet = useSelectedWallet()
const buyTokenInfo = useTokenInfo({wallet, tokenId: amounts.buy.tokenId})
const sellTokenInfo = useTokenInfo({wallet, tokenId: amounts.sell.tokenId})
const buyTokenName = buyTokenInfo.ticker ?? buyTokenInfo.name
const sellTokenName = sellTokenInfo.ticker ?? sellTokenInfo.name
const [hiddenInfoOpenId, setHiddenInfoOpenId] = React.useState<string | null>(null)

if (!isBuyTouched || !isSellTouched || calculatedPool === undefined) {
if (!isBuyTouched || !isSellTouched || selectedPoolCalculation === undefined) {
return <></>
}

const totalFees = Quantities.format(
Quantities.sum([calculatedPool.cost.batcherFee.quantity, calculatedPool.cost.frontendFeeInfo.fee.quantity]),
Quantities.sum([
selectedPoolCalculation.cost.batcherFee.quantity,
selectedPoolCalculation.cost.frontendFeeInfo.fee.quantity,
]),
Number(wallet.primaryTokenInfo.decimals),
)
const header = `${strings.total}: ${Quantities.format(
amounts.sell.quantity,
sellTokenInfo.decimals ?? 0,
)} ${sellTokenName} + ${totalFees} ${wallet.primaryTokenInfo.ticker}`
const id = calculatedPool.pool.poolId
const id = selectedPoolCalculation.pool.poolId
const expanded = id === hiddenInfoOpenId

const poolProviderFormatted = capitalize(calculatedPool.pool.provider)
const poolProviderFormatted = capitalize(selectedPoolCalculation.pool.provider)
const poolStatus = orderData.type === 'limit' && isPoolTouched ? '' : ` ${strings.autoPool}`
const poolTitle = `${poolProviderFormatted}${poolStatus}`

Expand All @@ -59,7 +62,7 @@ export const ShowPoolActions = () => {
<View>
<View style={[styles.flex, styles.between]}>
<View style={styles.flex}>
<PoolIcon size={25} providerId={calculatedPool.pool.provider} />
<PoolIcon size={25} providerId={selectedPoolCalculation.pool.provider} />

<Spacer width={10} />

Expand All @@ -85,7 +88,7 @@ export const ShowPoolActions = () => {
info={
<HiddenInfo
totalFees={Quantities.format(
calculatedPool.pool.batcherFee.quantity,
selectedPoolCalculation.pool.batcherFee.quantity,
Number(wallet.primaryTokenInfo.decimals),
)}
minReceived={getMinAdaReceiveAfterSlippage(
Expand All @@ -94,12 +97,15 @@ export const ShowPoolActions = () => {
buyTokenInfo.decimals ?? 0,
numberLocale,
)}
minAda={Quantities.format(calculatedPool.pool.deposit.quantity, Number(wallet.primaryTokenInfo.decimals))}
minAda={Quantities.format(
selectedPoolCalculation.pool.deposit.quantity,
Number(wallet.primaryTokenInfo.decimals),
)}
buyTokenName={buyTokenName}
sellTokenName={sellTokenName}
liquidityFee={calculatedPool.pool.fee}
liquidityFee={selectedPoolCalculation.pool.fee}
liquidityFeeValue={Quantities.format(
calculatedPool.cost.liquidityFee.quantity,
selectedPoolCalculation.cost.liquidityFee.quantity,
sellTokenInfo.decimals ?? 0,
)}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ export const EditSellAmount = () => {
navigateTo={navigate.selectSellToken}
touched={isSellTouched}
inputRef={inputRef}
inputEditable={orderData.calculatedPool?.pool !== undefined}
inputEditable={orderData.selectedPoolCalculation?.pool !== undefined}
/>
)
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {FlashList} from '@shopify/flash-list'
import {useSwap} from '@yoroi/swap'
import {useSwap, useSwapPoolsByPair} from '@yoroi/swap'
import {Balance} from '@yoroi/types'
import React from 'react'
import {StyleSheet, TouchableOpacity, View} from 'react-native'
import {InteractionManager, StyleSheet, TouchableOpacity, View} from 'react-native'
import {SafeAreaView} from 'react-native-safe-area-context'

import {Boundary, Spacer, Text} from '../../../../../../../components'
Expand Down Expand Up @@ -83,21 +83,42 @@ const TokenList = () => {
type SelectableTokenProps = {disabled?: boolean; tokenInfo: Balance.TokenInfo; wallet: YoroiWallet}
const SelectableToken = ({tokenInfo, wallet}: SelectableTokenProps) => {
const {closeSearch} = useSearch()
const {sellTokenIdChanged} = useSwap()
const {sellTokenIdChanged, poolPairsChanged, orderData} = useSwap()
const {sellTouched} = useSwapTouched()
const navigateTo = useNavigateTo()
const {track} = useMetrics()

const {refetch} = useSwapPoolsByPair(
{
tokenA: orderData.amounts.buy.tokenId,
tokenB: orderData.amounts.sell.tokenId,
},
{
useErrorBoundary: true,
enabled: false,
onSuccess: (pools) => {
sellTouched()
closeSearch()
poolPairsChanged(pools)

InteractionManager.runAfterInteractions(() => {
navigateTo.startSwap()
})
},
},
)

React.useEffect(() => {
refetch()
}, [refetch, orderData.amounts.sell.tokenId])

const balanceAvailable = useBalance({wallet, tokenId: tokenInfo.id})

const onSelect = () => {
track.swapAssetFromChanged({
from_asset: [{asset_name: tokenInfo.name, asset_ticker: tokenInfo.ticker, policy_id: tokenInfo.group}],
})
sellTouched()
sellTokenIdChanged({tokenId: tokenInfo.id, pools: []})
navigateTo.startSwap()
closeSearch()
sellTokenIdChanged(tokenInfo.id)
}

return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const LimitPriceWarning = ({open, onClose, onSubmit}: LimitPriceWarningPr
const {numberLocale} = useLanguage()
const strings = useStrings()
const limitPrice = new BigNumber(orderData.limitPrice ?? 0).toFormat(numberLocale)
const marketPrice = new BigNumber(orderData.calculatedPool?.prices.market ?? 0).toFormat(numberLocale)
const marketPrice = new BigNumber(orderData.selectedPoolCalculation?.prices.market ?? 0).toFormat(numberLocale)
const wallet = useSelectedWallet()

const tokenToSellInfo = useTokenInfo({wallet, tokenId: orderData.amounts.sell.tokenId})
Expand Down
Loading

0 comments on commit 1f8c8d8

Please sign in to comment.