Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: wire up limit orders UI to RTK query #8052

Merged
merged 5 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/caip/src/assetId/assetId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ type FromAssetIdReturn = {
chainReference: ChainReference
chainId: ChainId
assetNamespace: AssetNamespace
assetReference: AssetReference | string
assetReference: AssetReference
}

export type FromAssetId = (assetId: AssetId) => FromAssetIdReturn
Expand Down Expand Up @@ -171,7 +171,7 @@ export const fromAssetId: FromAssetId = (assetId: string) => {
chainNamespace: chainNamespace as ChainNamespace,
chainReference: chainReference as ChainReference,
assetNamespace: assetNamespace as AssetNamespace,
assetReference: assetReferenceNormalized,
assetReference: assetReferenceNormalized as AssetReference,
}
}

Expand Down
1 change: 1 addition & 0 deletions packages/caip/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export const foxatarAssetId: AssetId =
export const foxyAssetId: AssetId = 'eip155:1/erc20:0xdc49108ce5c57bc3408c3a5e95f3d864ec386ed3'

export const usdtAssetId: AssetId = 'eip155:1/erc20:0xdac17f958d2ee523a2206206994597c13d831ec7'
export const usdcAssetId: AssetId = 'eip155:1/erc20:0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48'

export const cosmosAssetId: AssetId = 'cosmos:cosmoshub-4/slip44:118'
export const thorchainAssetId: AssetId = 'cosmos:thorchain-1/slip44:931'
Expand Down
1 change: 1 addition & 0 deletions packages/swapper/src/swappers/CowSwapper/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ export const cowApi: SwapperApi = {
const { appData, appDataHash } = await getFullAppData(
slippageTolerancePercentageDecimal,
affiliateAppDataFragment,
'market',
)
// https://api.cow.fi/docs/#/default/post_api_v1_quote
const maybeQuoteResponse = await cowService.post<CowSwapQuoteResponse>(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ async function _getCowSwapTradeQuote(
const { appData, appDataHash } = await getFullAppData(
slippageTolerancePercentageDecimal,
affiliateAppDataFragment,
'market',
)

// https://api.cow.fi/docs/#/default/post_api_v1_quote
Expand Down Expand Up @@ -204,6 +205,7 @@ async function _getCowSwapTradeRate(
const { appData, appDataHash } = await getFullAppData(
slippageTolerancePercentageDecimal,
affiliateAppDataFragment,
'market',
)

// https://api.cow.fi/docs/#/default/post_api_v1_quote
Expand Down
6 changes: 4 additions & 2 deletions packages/swapper/src/swappers/CowSwapper/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@ export type CowSwapQuoteResponse = {
}

// Most likely non-exhaustive, see https://github.com/cowprotocol/contracts/blob/aaffdc55b2a13738b7c32de96f487d3eb5b4f8c6/src/ts/api.ts#L110
// But we only handle SellAmountDoesNotCoverFee for now so that's fine. Add other errors here as needed.
enum CowSwapQuoteErrorType {
// But we only handle a few of them for now so that's fine. Add other errors here as needed.
export enum CowSwapQuoteErrorType {
SellAmountDoesNotCoverFee = 'SellAmountDoesNotCoverFee',
NoLiquidity = 'NoLiquidity',
ZeroAmount = 'ZeroAmount',
UnsupportedToken = 'UnsupportedToken',
}

export type CowSwapQuoteError = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ describe('utils', () => {
const slippageTolerancePercentage = '0.005' // 0.5%
const affiliateAppDataFragment = {} // no affiliate fee

const result = await getFullAppData(slippageTolerancePercentage, affiliateAppDataFragment)
const result = await getFullAppData(
slippageTolerancePercentage,
affiliateAppDataFragment,
'market',
)

expect(result).toHaveProperty('appDataHash')
expect(result).toHaveProperty('appData')
Expand All @@ -60,7 +64,11 @@ describe('utils', () => {
},
}

const result = await getFullAppData(slippageTolerancePercentage, affiliateAppDataFragment)
const result = await getFullAppData(
slippageTolerancePercentage,
affiliateAppDataFragment,
'market',
)

expect(result).toHaveProperty('appDataHash')
expect(result).toHaveProperty('appData')
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { LatestAppDataDocVersion } from '@cowprotocol/app-data'
import { MetadataApi, stringifyDeterministic } from '@cowprotocol/app-data'
import type { OrderClass } from '@cowprotocol/app-data/dist/generatedTypes/v0.9.0'
import type { OrderClass, OrderClass1 } from '@cowprotocol/app-data/dist/generatedTypes/v0.9.0'
import type { ChainId } from '@shapeshiftoss/caip'
import { fromAssetId } from '@shapeshiftoss/caip'
import type { Asset } from '@shapeshiftoss/types'
Expand Down Expand Up @@ -262,9 +262,10 @@ const metadataApi = new MetadataApi()
export const getFullAppData = async (
slippageTolerancePercentage: string,
affiliateAppDataFragment: AffiliateAppDataFragment,
orderClass1: OrderClass1,
) => {
const APP_CODE = 'shapeshift'
const orderClass: OrderClass = { orderClass: 'market' }
const orderClass: OrderClass = { orderClass: orderClass1 }
const quote = {
slippageBips: convertDecimalPercentageToBasisPoints(slippageTolerancePercentage).toString(),
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import { Divider, Stack } from '@chakra-ui/react'
import { ethAssetId, foxAssetId } from '@shapeshiftoss/caip'
import { skipToken } from '@reduxjs/toolkit/query'
import { foxAssetId, fromAccountId, usdcAssetId } from '@shapeshiftoss/caip'
import { isLedger } from '@shapeshiftoss/hdwallet-ledger'
import { SwapperName } from '@shapeshiftoss/swapper'
import type { Asset } from '@shapeshiftoss/types'
import { bnOrZero } from '@shapeshiftoss/utils'
import { bnOrZero, toBaseUnit } from '@shapeshiftoss/utils'
import { noop } from 'lodash'
import type { FormEvent } from 'react'
import { useCallback, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useFormContext } from 'react-hook-form'
import { useHistory } from 'react-router'
import type { Address } from 'viem'
import { WarningAcknowledgement } from 'components/Acknowledgement/Acknowledgement'
import { useReceiveAddress } from 'components/MultiHopTrade/hooks/useReceiveAddress'
import { TradeInputTab } from 'components/MultiHopTrade/types'
Expand All @@ -17,6 +19,7 @@ import { useErrorHandler } from 'hooks/useErrorToast/useErrorToast'
import { useWallet } from 'hooks/useWallet/useWallet'
import { localAssetData } from 'lib/asset-service'
import type { ParameterModel } from 'lib/fees/parameters/types'
import { useQuoteLimitOrderQuery } from 'state/apis/limit-orders/limitOrderApi'
import { selectIsSnapshotApiQueriesPending, selectVotingPower } from 'state/apis/snapshot/selectors'
import { defaultAsset } from 'state/slices/assetsSlice/assetsSlice'
import {
Expand Down Expand Up @@ -65,7 +68,7 @@ export const LimitOrderInput = ({
fetchUnchainedAddress: Boolean(wallet && isLedger(wallet)),
})

const [sellAsset, setSellAsset] = useState(localAssetData[ethAssetId] ?? defaultAsset)
const [sellAsset, setSellAsset] = useState(localAssetData[usdcAssetId] ?? defaultAsset)
const [buyAsset, setBuyAsset] = useState(localAssetData[foxAssetId] ?? defaultAsset)

const defaultAccountId = useAppSelector(state =>
Expand Down Expand Up @@ -199,7 +202,55 @@ export const LimitOrderInput = ({
[handleFormSubmit],
)

const sellAmountCryptoBaseUnit = useMemo(() => {
return toBaseUnit(sellAmountCryptoPrecision, sellAsset.precision)
}, [sellAmountCryptoPrecision, sellAsset.precision])

const sellAccountAddress = useMemo(() => {
if (!sellAssetAccountId) return

return fromAccountId(sellAssetAccountId).account as Address
}, [sellAssetAccountId])

const limitOrderQuoteParams = useMemo(() => {
// Return skipToken if any required params are missing
if (bnOrZero(sellAmountCryptoBaseUnit).isZero()) {
return skipToken
}

return {
sellAssetId: sellAsset.assetId,
buyAssetId: buyAsset.assetId,
chainId: sellAsset.chainId,
slippageTolerancePercentageDecimal: '0', // TODO: wire this up!
affiliateBps: '0', // TODO: wire this up!
sellAccountAddress,
sellAmountCryptoBaseUnit,
}
}, [
buyAsset.assetId,
sellAccountAddress,
sellAmountCryptoBaseUnit,
sellAsset.assetId,
sellAsset.chainId,
])

const { data, error } = useQuoteLimitOrderQuery(limitOrderQuoteParams)

useEffect(() => {
/*
This is the quote only, not the limit order. The quote is used to determine the market price.
When submitting a limit order, the buyAmount is (optionally) modified based on the user input,
and then re-attached to the `LimitOrder` before signing and submitting via our
`placeLimitOrder` endpoint in limitOrderApi
*/
console.log('limit order quote response:', data)
console.log('limit order quote error:', error)
}, [data, error])

const marketPriceBuyAssetCryptoPrecision = '123423'

// TODO: debounce this with `useDebounce` when including in the query
const [limitPriceBuyAssetCryptoPrecision, setLimitPriceBuyAssetCryptoPrecision] = useState(
marketPriceBuyAssetCryptoPrecision,
)
Expand Down
Loading
Loading