Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
jorbuedo committed Dec 10, 2024
1 parent e34a490 commit 1d2a245
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 34 deletions.
99 changes: 78 additions & 21 deletions apps/wallet-mobile/src/features/Swap/common/SwapProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {primaryTokenId} from '@yoroi/portfolio'
import {swapManagerMaker, swapStorageMaker} from '@yoroi/swap'
import {Portfolio, Swap} from '@yoroi/types'
import {Api, Portfolio, Swap} from '@yoroi/types'
import {produce} from 'immer'
import React from 'react'
import {TextInput} from 'react-native'
Expand Down Expand Up @@ -63,6 +63,42 @@ export const SwapProvider = ({children}: {children: React.ReactNode}) => {
*/
const [state, dispatch] = React.useReducer(swapReducer, defaultState)

React.useEffect(() => {
if (state.reqres === 'response') return

if (state.tokenInInput.tokenId === undefined || state.tokenOutInput.tokenId === undefined) return

console.log('Running effect', {
slippage: state.slippageInput.value,
tokenIn: state.tokenInInput.tokenId,
tokenOut: state.tokenOutInput.tokenId,
amountIn: Number(state.tokenInInput.value),
// amountOut: Number(state.tokenOutInput:value),
blacklistedDexes: [],
dex: state.selectedDex.value,
wantedPrice: Number(state.wantedPrice),
})

swapManager.api
.estimate({
slippage: state.slippageInput.value,
tokenIn: state.tokenInInput.tokenId,
tokenOut: state.tokenOutInput.tokenId,
amountIn: Number(state.tokenInInput.value),
// amountOut: Number(state.tokenOutInput:value),
blacklistedDexes: [],
dex: state.selectedDex.value,
// wantedPrice: Number(state.wantedPrice),
})
.then((response) => {
if (response.tag === 'left') {
dispatch({type: SwapAction.EstimateError, value: response.error})
} else {
dispatch({type: SwapAction.EstimateResponse, value: response.value.data})
}
})
}, [state, swapManager.api])

const context = React.useMemo(
() => ({
...state,
Expand All @@ -71,31 +107,33 @@ export const SwapProvider = ({children}: {children: React.ReactNode}) => {
tokenInInputRef,
wantedPriceInputRef,
slippageInputRef,
api: swapManager.api,
orders,
dispatch,
}),
[state, swapManager.api, orders, tokenInfos],
[state, orders, tokenInfos],
)

return <SwapContext.Provider value={context}>{children}</SwapContext.Provider>
}

const swapReducer = (state: SwapState, action: SwapAction) => {
return produce(state, (draft) => {
draft.reqres = 'request'
draft.lastInputTouched = 'in'

switch (action.type) {
case SwapAction.ChangeOrderType:
draft.orderType = action.value
break
case SwapAction.TokenInInputTouched:
draft.tokenInInput.isTouched = true
draft.tokenInInput.displayValue = ''
draft.tokenInInput.value = ''
draft.tokenInInput.error = undefined

break
case SwapAction.TokenOutInputTouched:
draft.tokenOutInput.isTouched = true
draft.tokenOutInput.displayValue = ''
draft.tokenOutInput.value = ''
draft.tokenOutInput.error = undefined

break
Expand All @@ -108,11 +146,12 @@ const swapReducer = (state: SwapState, action: SwapAction) => {

break
case SwapAction.TokenInAmountChanged:
draft.tokenInInput.displayValue = action.value
draft.tokenInInput.value = action.value

break
case SwapAction.TokenOutAmountChanged:
draft.tokenOutInput.displayValue = action.value
draft.tokenOutInput.value = action.value
draft.lastInputTouched = 'out'

break
case SwapAction.TokenInErrorChanged:
Expand All @@ -124,30 +163,31 @@ const swapReducer = (state: SwapState, action: SwapAction) => {

break
case SwapAction.SlippageInputChanged:
draft.slippageInput.displayValue = String(action.value)
draft.slippageInput.value = action.value

break
case SwapAction.WantedPriceInputChanged:
draft.wantedPrice.displayValue = action.value
draft.wantedPrice.value = action.value
draft.lastInputTouched = 'limit'

break
case SwapAction.SwitchTouched:
draft.tokenOutInput.isTouched = state.tokenInInput.isTouched
draft.tokenOutInput.tokenId = state.tokenInInput.tokenId
draft.tokenOutInput.displayValue = ''
draft.tokenOutInput.value = ''
draft.tokenOutInput.error = undefined

draft.tokenInInput.isTouched = state.tokenOutInput.isTouched
draft.tokenInInput.tokenId = state.tokenOutInput.tokenId
draft.tokenInInput.displayValue = ''
draft.tokenInInput.value = ''
draft.tokenInInput.error = undefined

break
case SwapAction.DexSelectorTouched:
break
case SwapAction.ResetAmounts:
draft.tokenInInput.displayValue = ''
draft.tokenOutInput.displayValue = ''
draft.tokenInInput.value = ''
draft.tokenOutInput.value = ''

draft.tokenInInput.error = undefined
draft.tokenOutInput.error = undefined
Expand All @@ -156,6 +196,13 @@ const swapReducer = (state: SwapState, action: SwapAction) => {
case SwapAction.ResetForm:
draft = defaultState
break
case SwapAction.EstimateResponse:
draft.reqres = 'response'
draft.tokenOutInput.value = String(action.value.totalOutputWithoutSlippage ?? 0)
break
case SwapAction.EstimateError:
console.log(' SwapAction.EstimateError ', action.value)
break
default:
throw new Error(`swapReducer invalid action`)
}
Expand All @@ -178,6 +225,8 @@ export const SwapAction = {
DexSelectorTouched: 'DexSelectorTouched',
ResetAmounts: 'ResetAmounts',
ResetForm: 'ResetForm',
EstimateResponse: 'EstimateResponse',
EstimateError: 'EstimateError',
} as const

type SwapActionValueMap = {
Expand All @@ -196,6 +245,8 @@ type SwapActionValueMap = {
DexSelectorTouched: undefined
ResetAmounts: undefined
ResetForm: undefined
EstimateResponse: Swap.EstimateResponse
EstimateError: Api.ResponseError
}

export type SwapAction = {
Expand All @@ -205,58 +256,64 @@ export type SwapAction = {
}[keyof SwapActionValueMap]

const defaultState: SwapState = Object.freeze({
reqres: 'response',
orderType: 'market',
lastInputTouched: 'in',
tokenInInput: {
isTouched: true,
tokenId: primaryTokenId,
disabled: false,
error: undefined,
displayValue: '',
value: '',
},
tokenOutInput: {
isTouched: false,
tokenId: undefined,
disabled: false,
error: undefined,
displayValue: '',
value: '',
},
slippageInput: {
displayValue: '1',
value: 1,
},
selectedDex: {
isTouched: false,
value: undefined,
},
wantedPrice: {
displayValue: '',
value: '',
},
canSwap: false,
estimate: undefined,
} as const)

type SwapState = {
reqres: 'request' | 'response'
orderType: 'market' | 'limit'
lastInputTouched: 'in' | 'out' | 'limit'
tokenInInput: {
isTouched: boolean
tokenId?: Portfolio.Token.Id
disabled: boolean
error: string | undefined
displayValue: string
value: string
}
tokenOutInput: {
isTouched: boolean
tokenId?: Portfolio.Token.Id
disabled: boolean
error: string | undefined
displayValue: string
value: string
}
slippageInput: {
displayValue: string
value: number
}
selectedDex: {
isTouched: boolean
value?: Swap.Provider
}
wantedPrice: {
displayValue: string
value: string
}
canSwap: boolean
estimate?: Swap.EstimateResponse
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const EditPrice = () => {
<TextInput
keyboardType="numeric"
autoComplete="off"
value={disabled ? String(swapForm.estimate?.netPrice ?? 0) : swapForm.wantedPrice.displayValue}
value={disabled ? String(swapForm.estimate?.netPrice ?? 0) : swapForm.wantedPrice.value}
placeholder="0"
onChangeText={(value) => swapForm.dispatch({type: 'WantedPriceInputChanged', value})}
allowFontScaling
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,9 @@ export const EditSlippageScreen = () => {
const {styles, colors} = useStyles()

const swapForm = useSwap()
const defaultSelectedChoice = getChoiceBySlippage(Number(swapForm.slippageInput.displayValue), numberLocale)
const defaultSelectedChoice = getChoiceBySlippage(Number(swapForm.slippageInput.value), numberLocale)
const defaultInputValue =
defaultSelectedChoice.label === 'Manual'
? new BigNumber(swapForm.slippageInput.displayValue).toFormat(numberLocale)
: ''
defaultSelectedChoice.label === 'Manual' ? new BigNumber(swapForm.slippageInput.value).toFormat(numberLocale) : ''

const [selectedChoiceLabel, setSelectedChoiceLabel] = React.useState<ChoiceKind>(defaultSelectedChoice.label)
const [inputValue, setInputValue] = React.useState(defaultInputValue)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ export const StartSwapOrderScreen = () => {
<AmountCard
label={strings.swapFrom}
onChange={(value) => swapForm.dispatch({type: 'TokenInAmountChanged', value})}
value={swapForm.tokenInInput.displayValue}
value={swapForm.tokenInInput.value}
amount={balances.records.get(swapForm.tokenInInput.tokenId ?? 'unknown.')}
wallet={wallet}
navigateTo={navigate.selectSellToken}
Expand Down Expand Up @@ -338,7 +338,7 @@ export const StartSwapOrderScreen = () => {
<AmountCard
label={strings.swapTo}
onChange={(value) => swapForm.dispatch({type: 'TokenOutAmountChanged', value})}
value={swapForm.tokenOutInput.displayValue}
value={swapForm.tokenOutInput.value}
amount={balances.records.get(swapForm.tokenOutInput.tokenId ?? 'unknown.')}
wallet={wallet}
navigateTo={navigate.selectBuyToken}
Expand Down Expand Up @@ -372,7 +372,7 @@ export const StartSwapOrderScreen = () => {
fontOverride={atoms.heading_3_regular}
onPress={navigate.editSlippage}
type={ButtonType.SecondaryText}
title={`${swapForm.slippageInput.displayValue}%`}
title={`${swapForm.slippageInput.value}%`}
rightIcon
icon={Icon.Edit}
/>
Expand Down
3 changes: 1 addition & 2 deletions packages/swap/src/adapters/api/dexhunter/transformers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import {
} from './types'
import {isPrimaryToken} from '@yoroi/portfolio'
import {DexhunterApiConfig} from './api-maker'
import {SwapProvider} from '@yoroi/types/lib/typescript/swap/api'

const tokenIdToDexhunter = (tokenId: Portfolio.Token.Id) =>
isPrimaryToken(tokenId) ? 'ADA' : tokenId.replace('.', '')
Expand Down Expand Up @@ -237,7 +236,7 @@ export const transformersMaker = ({
request: ({
amountIn,
blacklistedDexes,
dex = SwapProvider.Splash_v1,
dex = Swap.Provider.Splash_v1,
multiples,
tokenIn,
tokenOut,
Expand Down
2 changes: 2 additions & 0 deletions packages/swap/src/adapters/api/muesliswap/api-maker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ export const muesliswapApiMaker = (
async estimate(body: Swap.EstimateRequest) {
const params = transformers.quote.request(body)

console.log({params})

const response = await request<QuoteResponse>(
{
method: 'get',
Expand Down
5 changes: 2 additions & 3 deletions packages/swap/src/adapters/api/muesliswap/transformers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
} from './types'
import {MuesliswapApiConfig} from './api-maker'
import {asTokenFingerprint, asTokenName} from '../../../helpers/transformers'
import {SwapProvider} from '@yoroi/types/lib/typescript/swap/api'

export const transformersMaker = ({
primaryTokenInfo,
Expand Down Expand Up @@ -134,7 +133,7 @@ export const transformersMaker = ({
},
quote: {
request: ({
dex = SwapProvider.Muesliswap_v2,
dex = Swap.Provider.Muesliswap_v2,
blacklistedDexes,
tokenIn,
tokenOut,
Expand Down Expand Up @@ -228,7 +227,7 @@ export const transformersMaker = ({
},
createLimit: {
request: ({
dex = SwapProvider.Muesliswap_v2,
dex = Swap.Provider.Muesliswap_v2,
tokenIn,
tokenOut,
amountIn,
Expand Down

0 comments on commit 1d2a245

Please sign in to comment.