Skip to content

Commit

Permalink
Merge pull request #155 from jediswaplabs/swap-fixes-v2
Browse files Browse the repository at this point in the history
Swap fixes v2
  • Loading branch information
vnaysngh-mudrex authored Feb 13, 2024
2 parents c852b61 + 2491493 commit 61a9008
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 90 deletions.
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -213,11 +213,11 @@
"@visx/react-spring": "^2.12.2",
"@visx/responsive": "^2.10.0",
"@visx/shape": "^2.11.1",
"@vnaysn/jediswap-router-sdk": "^12.0.0",
"@vnaysn/jediswap-sdk-core": "^9.3.0",
"@vnaysn/jediswap-router-sdk": "^13.0.0",
"@vnaysn/jediswap-sdk-core": "^10.3.0",
"@vnaysn/jediswap-sdk-v2": "^8.0.0",
"@vnaysn/jediswap-sdk-v3": "^16.0.0",
"@vnaysn/jediswap-universal-router-sdk": "^9.0.0",
"@vnaysn/jediswap-sdk-v3": "^18.0.0",
"@vnaysn/jediswap-universal-router-sdk": "^11.0.0",
"@web3-react/coinbase-wallet": "^8.2.3",
"@web3-react/core": "^8.2.3",
"@web3-react/eip1193": "^8.2.3",
Expand Down
20 changes: 0 additions & 20 deletions src/components/swap/SwapLineItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import { SlippageTolerance } from 'state/user/types'
import { ExternalLink, ThemedText } from 'theme/components'
import { NumberType, useFormatter } from 'utils/formatNumbers'
import { getPriceImpactColor } from 'utils/prices'
import { GasBreakdownTooltip } from './GasBreakdownTooltip'
import { MaxSlippageTooltip } from './MaxSlippageTooltip'
import { RoutingTooltip, SwapRoute } from './SwapRoute'
import TradePrice from './TradePrice'
Expand Down Expand Up @@ -143,25 +142,6 @@ function useLineItem(props: SwapLineItemProps): LineItemData | undefined {
Value: () => <TradePrice price={trade.executionPrice} />,
TooltipBody: !isPreview ? () => <RoutingTooltip trade={trade} /> : undefined,
}
case SwapLineItemType.NETWORK_COST:
if (!SUPPORTED_GAS_ESTIMATE_CHAIN_IDS.includes(chainId)) {
return
}
return {
Label: () => <Trans>Network cost</Trans>,
TooltipBody: () => <GasBreakdownTooltip trade={trade} />,
Value: () => {
if (isPreview) {
return <Loading />
}
return (
<Row gap="4px">
<ChainLogo chainId={chainId} />
{formatNumber({ input: trade.totalGasUseEstimateUSD, type: NumberType.FiatGasPrice })}
</Row>
)
},
}
case SwapLineItemType.PRICE_IMPACT:
return {
Label: () => <Trans>Price impact</Trans>,
Expand Down
52 changes: 33 additions & 19 deletions src/hooks/useBestV3Trade.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ import useTransactionDeadline from './useTransactionDeadline'
import { useQuery } from 'react-query'
// import { useV3Quoter } from './useContract'
import ERC20_ABI from 'abis/erc20.json'

const provider = new RpcProvider({
nodeUrl: 'https://starknet-testnet.public.blastapi.io/rpc/v0_6',
})
import { providerInstance } from 'utils/getLibrary'

export enum V3TradeState {
LOADING,
Expand Down Expand Up @@ -61,7 +58,6 @@ export function useBestV3TradeExactIn(
amountIn?: any,
currencyOut?: Currency
): { state: TradeState; trade: any | null } {
const deadline = useTransactionDeadline()
const { routes, loading: routesLoading } = useAllV3Routes(allPools, amountIn?.currency, currencyOut)
// State to store the resolved result

Expand All @@ -73,6 +69,7 @@ export function useBestV3TradeExactIn(

const { account, address, chainId, connector } = useAccountDetails()
const swapRouterAddress = SWAP_ROUTER_ADDRESS[chainId ?? DEFAULT_CHAIN_ID]
const deadline = useTransactionDeadline()

const quoteExactInInputs = useMemo(() => {
if (routesLoading || !amountIn || !address || !routes || !routes.length || !deadline) return
Expand Down Expand Up @@ -146,7 +143,7 @@ export function useBestV3TradeExactIn(
return call
}
})
}, [routes, amountIn, address])
}, [routes, amountIn, address, currencyOut, deadline])

const approveSelector = useMemo(() => {
if (!amountIn) return
Expand Down Expand Up @@ -186,21 +183,28 @@ export function useBestV3TradeExactIn(
})

const privateKey = '0x1234567890987654321'

const message: BigNumberish[] = [1, 128, 18, 14]

const msgHash = hash.computeHashOnElements(message)
const signature: WeierstrassSignatureType = ec.starkCurve.sign(msgHash, privateKey)

// const fetchResults = useFetchResults(account, blockNumber, callsArr)
const amountOutResults = useQuery({
queryKey: ['get_simulation', address, amountIn],
queryKey: ['get_simulation', address, amountIn, nonce_results?.data, currencyOut?.symbol],
queryFn: async () => {
if (!address || !account || !approveSelector || !quoteExactInInputs || !connector || !nonce_results) return
if (
!address ||
!account ||
!approveSelector ||
!quoteExactInInputs ||
!connector ||
!nonce_results ||
!chainId ||
!deadline
)
return
const nonce = Number(nonce_results.data)
const callPromises = quoteExactInInputs.map(async (call: any) => {
const isConnectorBraavos = connector.id === 'braavos'

const provider = providerInstance(chainId)
if (!provider) return
const payload = isConnectorBraavos
? {
contractAddress: address,
Expand Down Expand Up @@ -356,10 +360,10 @@ export function useBestV3TradeExactOut(
): { state: TradeState; trade: any | null } {
// : { state: V3TradeState; trade: any | null }
// const quoter = useV3Quoter()
const deadline = useTransactionDeadline()
const { routes, loading: routesLoading } = useAllV3Routes(allPools, currencyIn, amountOut?.currency)
const { address, account, chainId, connector } = useAccountDetails()
const swapRouterAddress = SWAP_ROUTER_ADDRESS[chainId ?? DEFAULT_CHAIN_ID]
const deadline = useTransactionDeadline()

const quoteExactOutInputs = useMemo(() => {
if (routesLoading || !amountOut || !address || !routes || !routes.length || !deadline) return
Expand Down Expand Up @@ -435,7 +439,7 @@ export function useBestV3TradeExactOut(
return call
}
})
}, [routes && routes.length, amountOut])
}, [routes, amountOut, address, currencyIn, deadline])

const approveSelector = useMemo(() => {
if (!currencyIn) return
Expand Down Expand Up @@ -480,16 +484,26 @@ export function useBestV3TradeExactOut(

const msgHash = hash.computeHashOnElements(message)
const signature: WeierstrassSignatureType = ec.starkCurve.sign(msgHash, privateKey)

const amountInResults = useQuery({
queryKey: [address, amountOut],
queryKey: ['get_simulation', address, amountOut, nonce_results?.data, chainId, currencyIn?.symbol],
queryFn: async () => {
if (!address || !account || !quoteExactOutInputs || !approveSelector || !connector || !nonce_results) return
if (
!address ||
!account ||
!quoteExactOutInputs ||
!approveSelector ||
!connector ||
!nonce_results ||
!chainId ||
!deadline
)
return
const nonce = Number(nonce_results.data)

const callPromises = quoteExactOutInputs.map(async (call: any) => {
const isConnectorBraavos = connector.id === 'braavos'

const provider = providerInstance(chainId)
if (!provider) return
const payload = isConnectorBraavos
? {
contractAddress: address,
Expand Down
7 changes: 3 additions & 4 deletions src/hooks/usePools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,7 @@ export function usePools(
})

const tickCurrent = useMemo(() => {
if (tick) return toInt(tick)
return undefined
return toInt(tick)
}, [tick])

const { data: liquidity } = useContractRead({
Expand Down Expand Up @@ -192,7 +191,7 @@ export function usePools(
const tokens = poolTokens[index]
if (!tokens) return [PoolState.INVALID, null]
const [token0, token1, fee] = tokens
if (!tickCurrent || !liquidityHex || !sqrtPriceHex) return [PoolState.NOT_EXISTS, null]
if (!liquidityHex || !sqrtPriceHex) return [PoolState.NOT_EXISTS, null]
try {
const pool = PoolCache.getPool(token0, token1, fee, sqrtPriceHex, liquidityHex, tickCurrent)
return [PoolState.EXISTS, pool]
Expand All @@ -211,7 +210,7 @@ export function usePoolsForSwap(results: any): [PoolState, Pool | null][] {
const sqrtPriceHex = sqrtPriceX96 && JSBI.BigInt(num.toHex(sqrtPriceX96 as BigNumberish))
const liquidityHex = Boolean(liquidity) ? JSBI.BigInt(num.toHex(liquidity as BigNumberish)) : JSBI.BigInt('0x0')

if (!tickCurrent || !liquidityHex || !sqrtPriceHex) return [PoolState.NOT_EXISTS, null]
if (!liquidityHex || !sqrtPriceHex) return [PoolState.NOT_EXISTS, null]
try {
const pool = PoolCache.getPool(token0, token1, fee, sqrtPriceHex, liquidityHex, tickCurrent)
return [PoolState.EXISTS, pool]
Expand Down
4 changes: 2 additions & 2 deletions src/hooks/useTransactionDeadline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useAccountDetails } from 'hooks/starknet-react'
import { L2_DEADLINE_FROM_NOW } from 'constants/misc'
import { useMemo } from 'react'
import { useAppSelector } from 'state/hooks'
import { useContractRead } from '@starknet-react/core'
import { useBlock, useContractRead } from '@starknet-react/core'
import MultiContractABI from 'contracts/multicall/abi.json'
import { MULTICALL_NETWORKS } from 'contracts/multicall'
import { DEFAULT_CHAIN_ID } from 'constants/tokens'
Expand All @@ -14,7 +14,6 @@ export default function useTransactionDeadline(): BigNumber | undefined {
const ttl = useAppSelector((state) => state.user.userDeadline)
const blockTimestamp = useCurrentBlockTimestamp()
return useMemo(() => {
if (blockTimestamp && chainId) return BigNumber.from(blockTimestamp).add(L2_DEADLINE_FROM_NOW)
if (blockTimestamp && ttl) return BigNumber.from(blockTimestamp).add(ttl)
return undefined
}, [blockTimestamp, chainId, ttl])
Expand All @@ -29,6 +28,7 @@ const useCurrentBlockTimestamp = () => {
address: MULTICALL_NETWORKS[chainId ?? DEFAULT_CHAIN_ID],
watch: true,
})

if (!blockTimeStamp) return undefined
const { block_timestamp } = blockTimeStamp as any

Expand Down
10 changes: 4 additions & 6 deletions src/hooks/useV3PositionFees.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ import POOL_ABI from 'contracts/pool/abi.json'
import { toI32 } from 'utils/toI32'
import { useAccountDetails } from './starknet-react'
import { useQuery } from 'react-query'

const provider = new RpcProvider({
nodeUrl: 'https://starknet-testnet.public.blastapi.io/rpc/v0_6',
})
import { providerInstance } from 'utils/getLibrary'

// compute current + counterfactual fees for a v3 position
export function useV3PositionFees(
Expand Down Expand Up @@ -141,12 +138,13 @@ export const useStaticFeeResults = (
const fee_results = useQuery({
queryKey: [`fee/${address}/${nonce_results.data}/${parsedTokenId}`],
queryFn: async () => {
if (!account || !address || !nonce_results || !parsedTokenId || !connector || !collectSelector) return
if (!account || !address || !nonce_results || !parsedTokenId || !connector || !collectSelector || !chainId) return
const nonce_data = nonce_results.data
if (!nonce_data) return undefined
const nonce = Number(nonce_data)
const isConnectorBraavos = connector.id === 'braavos'

const provider = providerInstance(chainId)
if (!provider) return
const collect_call_data = {
tokenId: cairo.uint256(parsedTokenId),
recipient: address,
Expand Down
3 changes: 1 addition & 2 deletions src/hooks/useV3SwapPools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,7 @@ const getPoolProps = (address: string) => {
})

const tickCurrent = useMemo(() => {
if (tick) return toInt(tick)
return undefined
return toInt(tick)
}, [tick])

const { data: liquidity } = useContractRead({
Expand Down
13 changes: 12 additions & 1 deletion src/utils/getLibrary.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { jsonRpcProvider } from '@starknet-react/core'
import { ChainId } from '@vnaysn/jediswap-sdk-core'
import { RpcProvider } from 'starknet'

interface NetworkTypes {
[key: string]: string
Expand All @@ -18,7 +20,7 @@ const provider = jsonRpcProvider({
if (chainType === 'sepolia') {
nodeUrl = 'https://starknet-sepolia.public.blastapi.io'
} else if (chainType === 'mainnet') {
nodeUrl = 'https://rpc-proxy.jediswap.xyz/api/'
nodeUrl = 'https://starknet-mainnet-rpc.dwellir.com/dd28e566-3260-4d8d-8180-6ef1a161e41c'
} else if (chainType === 'goerli') {
nodeUrl = 'https://rpc.starknet-testnet.lava.build/'
}
Expand All @@ -32,4 +34,13 @@ const provider = jsonRpcProvider({
},
})

export const providerInstance = (chainId: string) => {
return new RpcProvider({
nodeUrl:
chainId === ChainId.GOERLI
? 'https://starknet-testnet.public.blastapi.io/rpc/v0_6'
: 'https://starknet-mainnet-rpc.dwellir.com/dd28e566-3260-4d8d-8180-6ef1a161e41c',
})
}

export default provider
Loading

0 comments on commit 61a9008

Please sign in to comment.