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

test(fiatAmount): test UsdPricesUpdater #3091

Merged
merged 52 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
0436ad0
refactor: remove usd amount calc based ony CowSwap quote
shoom3301 Aug 22, 2023
76925b3
refactor: move useHigherUSDValue hook to fiatAmount module
shoom3301 Aug 22, 2023
3ff2993
refactor: calculate priceImpact only basing on Coingecko
shoom3301 Aug 22, 2023
36931aa
refactor: request fiat amounts only when trade is ready
shoom3301 Aug 23, 2023
315d15a
refactor: deprecate parsePrice
shoom3301 Aug 23, 2023
32affd6
feat: use native price api for fiat amounts
shoom3301 Aug 23, 2023
007afd6
feat: module for fiat prices
shoom3301 Aug 24, 2023
cc1298a
chore: remove unused file
shoom3301 Aug 24, 2023
3409abb
chore: simplify code
shoom3301 Aug 25, 2023
639f220
docs: fiat price module diagram
shoom3301 Aug 25, 2023
6e6eba5
chore: fix import
shoom3301 Aug 25, 2023
e8ab945
chore: rename
shoom3301 Aug 25, 2023
245409d
chore: remove error field from price impact
shoom3301 Aug 25, 2023
7f353e3
chore: fix build
shoom3301 Aug 25, 2023
4eb1f6d
chore: fix build
shoom3301 Aug 25, 2023
1b339f5
Merge branch 'fix/fiat-amount-api' of https://github.com/cowprotocol/…
shoom3301 Aug 25, 2023
d0019d6
fix: display price impact unknown warning only when fiat amounts are …
shoom3301 Aug 28, 2023
3795e7d
Merge branch 'develop' of https://github.com/cowprotocol/cowswap into…
shoom3301 Aug 28, 2023
7274ad1
Merge branch 'fix/fiat-amount-api' of https://github.com/cowprotocol/…
shoom3301 Aug 28, 2023
960c22b
chore: rename var
shoom3301 Aug 28, 2023
6e3b193
chore: rename const
shoom3301 Aug 28, 2023
da2b879
chore: clean up env files
shoom3301 Aug 28, 2023
22ed725
chore: clean up code
shoom3301 Aug 28, 2023
40ac98c
chore: refactor fetchCurrencyFiatPrice
shoom3301 Aug 28, 2023
3601d0f
fix: fix UnknownImpactWarning displaying conditions
shoom3301 Aug 28, 2023
e97a8e6
chore: fix naming
shoom3301 Aug 28, 2023
1e18bbd
fix: request USDC native price on demand
shoom3301 Aug 28, 2023
e5b0a4e
fix: fix calc
shoom3301 Aug 28, 2023
dc2b958
fix: fix errors catching in fetchCurrencyFiatPrice
shoom3301 Aug 28, 2023
1554ecd
chore: additional check for zero
shoom3301 Aug 29, 2023
b4e7224
chore: fix comment
shoom3301 Aug 29, 2023
c95e7de
chore: refactor useFiatValuePriceImpact
shoom3301 Aug 29, 2023
9fc2797
chore: rename getCoingeckoFiatPrice
shoom3301 Aug 29, 2023
0ca263b
chore: rename usdc -> usd
shoom3301 Aug 29, 2023
fa035e8
chore: simplify useUsdPrice
shoom3301 Aug 29, 2023
4955667
chore: rename fiat -> usd
shoom3301 Aug 29, 2023
04908d6
chore: rename fiat -> usd globally
shoom3301 Aug 29, 2023
ff84560
Merge branch 'fix/fiat-amount-api-unit-tests' of https://github.com/c…
shoom3301 Aug 29, 2023
355671f
chore: simplify useTradeUsdAmounts
shoom3301 Aug 29, 2023
45b0615
chore: coingecko fetch rate limitter and backOff
shoom3301 Aug 30, 2023
7dea62f
Merge branch 'fix/fiat-amount-api-2' of https://github.com/cowprotoco…
shoom3301 Aug 30, 2023
10cc765
test(fiatAmount): test UsdPricesUpdater
shoom3301 Aug 30, 2023
d5ef158
chore: revert
shoom3301 Aug 30, 2023
f24b689
chore: fix SWR cache cleaning
shoom3301 Aug 30, 2023
ed61077
chore: fix code style
shoom3301 Aug 30, 2023
1263764
chore: comment
shoom3301 Aug 30, 2023
3f4db54
chore: remove unused const
shoom3301 Aug 30, 2023
dddc86b
test: test useUsdAmount
shoom3301 Aug 30, 2023
2bc7e50
chore: fix circular dependency
shoom3301 Aug 30, 2023
04a1791
Merge branch 'develop' of https://github.com/cowprotocol/cowswap into…
shoom3301 Aug 31, 2023
6ac4d6f
Merge branch 'fix/fiat-amount-api-2' of https://github.com/cowprotoco…
shoom3301 Aug 31, 2023
3a56435
Merge branch 'develop' of https://github.com/cowprotocol/cowswap into…
shoom3301 Aug 31, 2023
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
2 changes: 1 addition & 1 deletion apps/cowswap-frontend/src/legacy/state/swap/hooks.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { parse } from 'qs'

import { Field } from './actions'
import { queryParametersToSwapState } from './hooks'
import { queryParametersToSwapState } from './utils'

jest.mock('legacy/components/analytics/hooks/useAnalyticsReporter.ts')

Expand Down
70 changes: 0 additions & 70 deletions apps/cowswap-frontend/src/legacy/state/swap/hooks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { SupportedChainId } from '@cowprotocol/cow-sdk'
import { Currency, CurrencyAmount, Percent } from '@uniswap/sdk-core'

import { t } from '@lingui/macro'
import { ParsedQs } from 'qs'

import { changeSwapAmountAnalytics, switchTokensAnalytics } from 'legacy/components/analytics'
import { FEE_SIZE_THRESHOLD } from 'legacy/constants'
Expand Down Expand Up @@ -34,46 +33,13 @@ import tryParseCurrencyAmount from 'lib/utils/tryParseCurrencyAmount'
import { formatSymbol } from 'utils/format'

import { Field, setRecipient, switchCurrencies, typeInput } from './actions'
import { SwapState } from './reducer'

import { TOKEN_SHORTHANDS } from '../../constants/tokens'

export const BAD_RECIPIENT_ADDRESSES: { [address: string]: true } = {
'0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f': true, // v2 factory
'0xf164fC0Ec4E93095b804a4795bBe1e041497b92a': true, // v2 router 01
'0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D': true, // v2 router 02
}

export function parseCurrencyFromURLParameter(urlParam: ParsedQs[string]): string {
if (typeof urlParam === 'string') {
const valid = isAddress(urlParam)
if (valid) return valid
const upper = urlParam.toUpperCase()
if (upper === 'ETH') return 'ETH'
if (upper in TOKEN_SHORTHANDS) return upper
}
return ''
}

export function parseTokenAmountURLParameter(urlParam: any): string {
return typeof urlParam === 'string' && !isNaN(parseFloat(urlParam)) ? urlParam : ''
}

export function parseIndependentFieldURLParameter(urlParam: any): Field {
return typeof urlParam === 'string' && urlParam.toLowerCase() === 'output' ? Field.OUTPUT : Field.INPUT
}

const ENS_NAME_REGEX = /^[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)?$/
const ADDRESS_REGEX = /^0x[a-fA-F0-9]{40}$/
export function validatedRecipient(recipient: any): string | null {
if (typeof recipient !== 'string') return null
const address = isAddress(recipient)
if (address) return address
if (ENS_NAME_REGEX.test(recipient)) return recipient
if (ADDRESS_REGEX.test(recipient)) return recipient
return null
}

export function useSwapState(): AppState['swap'] {
const isProviderNetworkUnsupported = useIsProviderNetworkUnsupported()

Expand Down Expand Up @@ -402,42 +368,6 @@ export function useDerivedSwapInfo(): DerivedSwapInfo {
)
}

export function queryParametersToSwapState(
parsedQs: ParsedQs,
defaultInputCurrency = '',
chainId: number | null
): SwapState {
let inputCurrency = parseCurrencyFromURLParameter(parsedQs.inputCurrency)
let outputCurrency = parseCurrencyFromURLParameter(parsedQs.outputCurrency)
const typedValue = parseTokenAmountURLParameter(parsedQs.exactAmount)
const independentField = parseIndependentFieldURLParameter(parsedQs.exactField)

if (inputCurrency === '' && outputCurrency === '' && typedValue === '' && independentField === Field.INPUT) {
// Defaults to having the wrapped native currency selected
inputCurrency = defaultInputCurrency // 'ETH' // mod
} else if (inputCurrency === outputCurrency) {
// clear output if identical
outputCurrency = ''
}

const recipient = validatedRecipient(parsedQs.recipient)
const recipientAddress = validatedRecipient(parsedQs.recipientAddress)

return {
chainId: chainId || null,
[Field.INPUT]: {
currencyId: inputCurrency === '' ? null : inputCurrency ?? null,
},
[Field.OUTPUT]: {
currencyId: outputCurrency === '' ? null : outputCurrency ?? null,
},
typedValue,
independentField,
recipient,
recipientAddress,
}
}

export function useIsFeeGreaterThanInput({
address,
chainId,
Expand Down
3 changes: 2 additions & 1 deletion apps/cowswap-frontend/src/legacy/state/swap/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ import {
switchCurrencies,
typeInput,
} from 'legacy/state/swap/actions'
import { queryParametersToSwapState } from 'legacy/state/swap/hooks'
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here I broke Circular dependency.
reducer and hooks were in a circle


import { getIsNativeToken } from 'utils/getIsNativeToken'
import { getIsWrapOrUnwrap } from 'utils/getIsWrapOrUnwrap'

import { queryParametersToSwapState } from './utils'

export interface SwapState {
// Mod: added chainId
chainId: number | null
Expand Down
113 changes: 71 additions & 42 deletions apps/cowswap-frontend/src/legacy/state/swap/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { SupportedChainId } from '@cowprotocol/cow-sdk'
import { Currency, Percent, TradeType } from '@uniswap/sdk-core'
import { Currency } from '@uniswap/sdk-core'

import { WRAPPED_NATIVE_CURRENCY } from 'legacy/constants/tokens'
import { ParsedQs } from 'qs'

import TradeGp from './TradeGp'
import { TOKEN_SHORTHANDS, WRAPPED_NATIVE_CURRENCY } from 'legacy/constants/tokens'
import { isAddress } from 'legacy/utils'

import { Field } from './actions'
import { SwapState } from './reducer'

export function isWrappingTrade(
sellCurrency: Currency | null | undefined,
Expand All @@ -20,44 +24,69 @@ export function isWrappingTrade(
)
}

export function logTradeDetails(trade: TradeGp | undefined, allowedSlippage: Percent) {
// don't do anything outside of dev env
if (!trade || process.env.NODE_ENV !== 'development') return

const exactIn = trade.tradeType === TradeType.EXACT_INPUT

// Log Exact In Trade info
if (exactIn) {
console.debug(
`[SwapMod::[SELL] Trade Constructed]`,
`
Type: SELL
==========
Input Amount: ${trade.inputAmount.toExact()}
Output Amount: ${trade.outputAmount.toExact()}
==========
Fee Amount [as SELL]: ${trade.fee?.feeAsCurrency?.toExact()} ${trade.inputAmount.currency.symbol}
Fee Amount [as BUY]: ${
trade.outputAmountWithoutFee && trade.outputAmountWithoutFee.subtract(trade.outputAmount).toExact()
} ${trade.outputAmount.currency.symbol}
==========
Minimum Received: ${trade.minimumAmountOut(allowedSlippage).toExact()}
`
)
} else {
// Log Exact Out Trade info
console.debug(
`[SwapMod::[BUY] Trade Constructed]`,
`
Type: BUY
=========
Input Amount [w/FEE]: ${trade.inputAmountWithFee.toExact()}
Output Amount: ${trade.outputAmount.toExact()}
=========
Fee Amount [as SELL]: ${trade.fee?.feeAsCurrency?.toExact()} ${trade.inputAmount.currency.symbol}
=========
Maximum Sold: ${trade.fee?.feeAsCurrency && trade.maximumAmountIn(allowedSlippage).toExact()}
`
)
function parseIndependentFieldURLParameter(urlParam: any): Field {
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just moved functions from hooks.tsx using auto refactoring.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To fix circular dependency problem

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you mean by auto refactoring?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

image

return typeof urlParam === 'string' && urlParam.toLowerCase() === 'output' ? Field.OUTPUT : Field.INPUT
}

export function parseCurrencyFromURLParameter(urlParam: ParsedQs[string]): string {
if (typeof urlParam === 'string') {
const valid = isAddress(urlParam)
if (valid) return valid
const upper = urlParam.toUpperCase()
if (upper === 'ETH') return 'ETH'
if (upper in TOKEN_SHORTHANDS) return upper
}
return ''
}

export function parseTokenAmountURLParameter(urlParam: any): string {
return typeof urlParam === 'string' && !isNaN(parseFloat(urlParam)) ? urlParam : ''
}

const ENS_NAME_REGEX = /^[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)?$/
const ADDRESS_REGEX = /^0x[a-fA-F0-9]{40}$/

export function validatedRecipient(recipient: any): string | null {
if (typeof recipient !== 'string') return null
const address = isAddress(recipient)
if (address) return address
if (ENS_NAME_REGEX.test(recipient)) return recipient
if (ADDRESS_REGEX.test(recipient)) return recipient
return null
}

export function queryParametersToSwapState(
parsedQs: ParsedQs,
defaultInputCurrency = '',
chainId: number | null
): SwapState {
let inputCurrency = parseCurrencyFromURLParameter(parsedQs.inputCurrency)
let outputCurrency = parseCurrencyFromURLParameter(parsedQs.outputCurrency)
const typedValue = parseTokenAmountURLParameter(parsedQs.exactAmount)
const independentField = parseIndependentFieldURLParameter(parsedQs.exactField)

if (inputCurrency === '' && outputCurrency === '' && typedValue === '' && independentField === Field.INPUT) {
// Defaults to having the wrapped native currency selected
inputCurrency = defaultInputCurrency // 'ETH' // mod
} else if (inputCurrency === outputCurrency) {
// clear output if identical
outputCurrency = ''
}

const recipient = validatedRecipient(parsedQs.recipient)
const recipientAddress = validatedRecipient(parsedQs.recipientAddress)

return {
chainId: chainId || null,
[Field.INPUT]: {
currencyId: inputCurrency === '' ? null : inputCurrency ?? null,
},
[Field.OUTPUT]: {
currencyId: outputCurrency === '' ? null : outputCurrency ?? null,
},
typedValue,
independentField,
recipient,
recipientAddress,
}
}
Loading