This repository has been archived by the owner on Sep 21, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
hooks.ts
363 lines (317 loc) · 12.2 KB
/
hooks.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
import { useCallback, useEffect, useState, useMemo, useRef } from 'react'
import { useWeb3React } from '@web3-react/core'
import { Token, Route, WETH, Pair, ChainId, TokenAmount, TradeType, Trade, Fraction, JSBI } from '@uniswap/sdk'
import { injected } from './connectors'
import { useReserves, useBlockNumber } from './data'
import { Contract, ContractInterface } from '@ethersproject/contracts'
import { useRouter } from 'next/router'
import { QueryParameters } from './constants'
import { getAddress } from '@ethersproject/address'
import { responseInterface } from 'swr'
import { DAI, USDC } from './tokens'
export function useWindowSize(): { width: number | undefined; height: number | undefined } {
function getSize(): ReturnType<typeof useWindowSize> {
const isClient = typeof window === 'object'
return {
width: isClient ? window.innerWidth : undefined,
height: isClient ? window.innerHeight : undefined,
}
}
const [windowSize, setWindowSize] = useState(getSize())
useEffect(() => {
const handleResize = (): void => {
setWindowSize(getSize())
}
window.addEventListener('resize', handleResize)
return (): void => {
window.removeEventListener('resize', handleResize)
}
}, [])
return windowSize
}
// https://usehooks.com/useDebounce/
export function useDefaultedDebounce<T>(value: T, initialValue: T, delay: number): T {
const [defaultedDebounce, setDefaultedDebounce] = useState(initialValue)
useEffect(() => {
const handler = setTimeout(() => {
setDefaultedDebounce(value)
}, delay)
return (): void => {
clearTimeout(handler)
setDefaultedDebounce(initialValue)
}
}, [value, initialValue, delay])
return defaultedDebounce
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useBodyKeyDown(targetKey: string, onKeyDown: (event?: any) => void, suppress = false): void {
const downHandler = useCallback(
(event) => {
if (
!suppress &&
event.key === targetKey &&
event.target.tagName === 'BODY' &&
!event.altKey &&
!event.ctrlKey &&
!event.metaKey &&
!event.shiftKey
) {
onKeyDown(event)
}
},
[suppress, targetKey, onKeyDown]
)
useEffect(() => {
window.addEventListener('keydown', downHandler)
return (): void => {
window.removeEventListener('keydown', downHandler)
}
}, [suppress, targetKey, downHandler])
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function useKeepSWRDataLiveAsBlocksArrive(mutate: responseInterface<any, any>['mutate']): void {
// because we don't care about the referential identity of mutate, just bind it to a ref
const mutateRef = useRef(mutate)
useEffect(() => {
mutateRef.current = mutate
})
// then, whenever a new block arrives, trigger a mutation
const { data } = useBlockNumber()
useEffect(() => {
mutateRef.current()
}, [data])
}
export function useEagerConnect(): boolean {
const { activate, active } = useWeb3React()
const [tried, setTried] = useState(false)
useEffect(() => {
injected.isAuthorized().then((isAuthorized: boolean) => {
if (isAuthorized) {
activate(injected, undefined, true).catch(() => {
setTried(true)
})
} else {
setTried(true)
}
})
}, [activate])
// if the connection worked, wait until we get confirmation of that to flip the flag
useEffect(() => {
if (!tried && active) {
setTried(true)
}
}, [tried, active])
return tried
}
const chainMappings: { [key: string]: number } = {
'1': 1,
mainnet: 1,
'3': 3,
ropsten: 3,
'4': 4,
rinkeby: 4,
'5': 5,
görli: 5,
goerli: 5,
'42': 42,
kovan: 42,
}
export function useQueryParameters(): {
[QueryParameters.CHAIN]: number | undefined
[QueryParameters.INPUT]: string | undefined
[QueryParameters.OUTPUT]: string | undefined
} {
const { query } = useRouter()
let candidateChainId: number | undefined
try {
candidateChainId = chainMappings[query[QueryParameters.CHAIN] as string]
} catch {}
const chainId =
!!injected.supportedChainIds &&
typeof candidateChainId === 'number' &&
injected.supportedChainIds.includes(candidateChainId)
? candidateChainId
: undefined
let input: string | undefined
try {
if (typeof query[QueryParameters.INPUT] === 'string') input = getAddress(query[QueryParameters.INPUT] as string)
} catch {}
let output: string | undefined
try {
if (typeof query[QueryParameters.OUTPUT] === 'string') output = getAddress(query[QueryParameters.OUTPUT] as string)
} catch {}
return useMemo(
() => ({
[QueryParameters.CHAIN]: chainId,
[QueryParameters.INPUT]: input,
[QueryParameters.OUTPUT]: output,
}),
[chainId, input, output]
)
}
function useDirectPair(inputToken?: Token, outputToken?: Token): Pair | undefined | null {
const { data: pair } = useReserves(inputToken, outputToken)
if (!!inputToken && !!outputToken && inputToken.equals(outputToken)) {
return null
}
return pair
}
export function useRoute(inputToken?: Token, outputToken?: Token): [undefined | Route | null, Pair[]] {
// direct pair
const directPair = useDirectPair(inputToken, outputToken)
// WETH pairs
const WETHInputPair = useDirectPair(inputToken ? WETH[inputToken.chainId] : undefined, inputToken)
const WETHOutputPair = useDirectPair(outputToken ? WETH[outputToken.chainId] : undefined, outputToken)
// DAI pairs
const DAIInputPair = useDirectPair(inputToken?.chainId === ChainId.MAINNET ? DAI : undefined, inputToken)
const DAIOutputPair = useDirectPair(outputToken?.chainId === ChainId.MAINNET ? DAI : undefined, outputToken)
// USDC pairs
const USDCInputPair = useDirectPair(inputToken?.chainId === ChainId.MAINNET ? USDC : undefined, inputToken)
const USDCOutputPair = useDirectPair(outputToken?.chainId === ChainId.MAINNET ? USDC : undefined, outputToken)
// connecting pairs
const DAIWETH = useDirectPair(inputToken?.chainId === ChainId.MAINNET ? DAI : undefined, WETH[DAI.chainId])
const USDCWETH = useDirectPair(inputToken?.chainId === ChainId.MAINNET ? USDC : undefined, WETH[USDC.chainId])
const DAIUSDC = useDirectPair(
inputToken?.chainId === ChainId.MAINNET ? DAI : undefined,
inputToken?.chainId === ChainId.MAINNET ? USDC : undefined
)
const pairs: Pair[] = [
directPair,
WETHInputPair,
WETHOutputPair,
DAIInputPair,
DAIOutputPair,
USDCInputPair,
USDCOutputPair,
DAIWETH,
USDCWETH,
DAIUSDC,
].filter((p, i, pairs) => {
// filter out invalid pairs or pairs whose data hasn't been fetched yet
if (!!!p) {
return false
} else {
return i === pairs.findIndex((pair) => pair?.liquidityToken?.address === p.liquidityToken.address)
}
}) as Pair[]
const directRoute = useMemo(
() => (directPair && inputToken ? new Route([directPair], inputToken) : directPair === null ? null : undefined),
[directPair, inputToken]
)
const WETHRoute = useMemo(
() =>
WETHInputPair && WETHOutputPair && inputToken
? new Route([WETHInputPair, WETHOutputPair], inputToken)
: WETHInputPair === null || WETHOutputPair === null
? null
: undefined,
[WETHInputPair, WETHOutputPair, inputToken]
)
const DAIRoute = useMemo(
() =>
DAIInputPair && DAIOutputPair && inputToken
? new Route([DAIInputPair, DAIOutputPair], inputToken)
: DAIInputPair === null || DAIOutputPair === null
? null
: undefined,
[DAIInputPair, DAIOutputPair, inputToken]
)
const USDCRoute = useMemo(
() =>
USDCInputPair && USDCOutputPair && inputToken
? new Route([USDCInputPair, USDCOutputPair], inputToken)
: USDCInputPair === null || USDCOutputPair === null
? null
: undefined,
[USDCInputPair, USDCOutputPair, inputToken]
)
const routes = [directRoute, WETHRoute, DAIRoute, USDCRoute]
return [
routes.filter((route) => !!route).length > 0
? routes.filter((route) => !!route)[0]
: routes.some((route) => route === undefined)
? undefined
: null,
pairs,
]
}
export function useTrade(
inputToken: Token | undefined,
outputToken: Token | undefined,
pairs: Pair[],
independentAmount: TokenAmount,
tradeType: TradeType
): undefined | Trade {
const canCompute = !!inputToken && !!outputToken && pairs.length > 0 && !!independentAmount
let trade: undefined | Trade
if (canCompute) {
if (tradeType === TradeType.EXACT_INPUT) {
trade = Trade.bestTradeExactIn(pairs, independentAmount, outputToken, { maxNumResults: 1 })[0]
} else {
trade = Trade.bestTradeExactOut(pairs, inputToken, independentAmount, { maxNumResults: 1 })[0]
}
}
return trade
}
export function useContract(address?: string, ABI?: ContractInterface, withSigner = false): Contract | undefined {
const { library, account } = useWeb3React()
return useMemo(
() =>
!!address && !!ABI && !!library
? new Contract(address, ABI, withSigner ? library.getSigner(account).connectUnchecked() : library)
: undefined,
[address, ABI, withSigner, library, account]
)
}
export function useUSDETHPrice(): Fraction | undefined {
const { chainId } = useWeb3React()
const DAIWETH = useDirectPair(chainId === ChainId.MAINNET ? DAI : undefined, WETH[ChainId.MAINNET])
const USDCWETH = useDirectPair(chainId === ChainId.MAINNET ? USDC : undefined, WETH[ChainId.MAINNET])
const price = useMemo(() => {
const priceFractions = [
DAIWETH && new Route([DAIWETH], WETH[ChainId.MAINNET])?.midPrice?.adjusted,
USDCWETH && new Route([USDCWETH], WETH[ChainId.MAINNET])?.midPrice?.adjusted,
].filter((price) => !!price)
return (priceFractions as Fraction[])
.reduce((accumulator, priceFraction) => accumulator.add(priceFraction), new Fraction('0'))
.divide(priceFractions.length.toString())
}, [DAIWETH, USDCWETH])
return price.equalTo('0') ? undefined : price
}
export function useUSDTokenPrice(token?: Token): Fraction | undefined {
const USDETHPrice = useUSDETHPrice()
const DAIWETH = useDirectPair(USDETHPrice ? DAI : undefined, WETH[ChainId.MAINNET])
const USDCWETH = useDirectPair(USDETHPrice ? USDC : undefined, WETH[ChainId.MAINNET])
const tokenWETH = useDirectPair(token?.chainId === ChainId.MAINNET ? token : undefined, WETH[ChainId.MAINNET])
const tokenDAI = useDirectPair(token?.chainId === ChainId.MAINNET ? token : undefined, DAI)
const tokenUSDC = useDirectPair(token?.chainId === ChainId.MAINNET ? token : undefined, USDC)
const price = useMemo(() => {
// early return if the token is WETH
if (token && token.equals(WETH[ChainId.MAINNET])) {
return USDETHPrice || new Fraction('0')
}
let priceFractions = []
// if the token has a WETH pair with at least 5 ETH
if (token && USDETHPrice && tokenWETH && tokenWETH.reserveOf(WETH[ChainId.MAINNET]).greaterThan(JSBI.BigInt(5))) {
const ETHTokenPrice = new Route([tokenWETH], token).midPrice.adjusted
priceFractions.push(USDETHPrice.multiply(ETHTokenPrice))
}
// if DAIWETH pair exists and the token has a DAI pair with at least 1000 DAI
if (token && USDETHPrice && DAIWETH && tokenDAI && tokenDAI.reserveOf(DAI).greaterThan(JSBI.BigInt(1000))) {
const WETHDAIPrice = new Route([DAIWETH], DAI).midPrice.adjusted
const DAITokenPrice = new Route([tokenDAI], token).midPrice.adjusted
priceFractions.push(USDETHPrice.multiply(WETHDAIPrice).multiply(DAITokenPrice))
}
// if USDCWETH pair exists and the token has a USDC pair with at least 1000 USDC
if (token && USDETHPrice && USDCWETH && tokenUSDC && tokenUSDC.reserveOf(USDC).greaterThan(JSBI.BigInt(1000))) {
const WETHUSDCPrice = new Route([USDCWETH], USDC).midPrice.adjusted
const USDCTokenPrice = new Route([tokenUSDC], token).midPrice.adjusted
priceFractions.push(USDETHPrice.multiply(WETHUSDCPrice).multiply(USDCTokenPrice))
}
priceFractions = priceFractions.filter((price) => !!price)
return priceFractions
.reduce((accumulator, priceFraction) => accumulator.add(priceFraction), new Fraction('0'))
.divide(priceFractions.length.toString())
}, [tokenWETH, token, USDETHPrice, DAIWETH, tokenDAI, USDCWETH, tokenUSDC])
return price.equalTo('0') ? undefined : price
}