This repository has been archived by the owner on Jun 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
/
useBlockNumberContext.tsx
51 lines (45 loc) 路 1.88 KB
/
useBlockNumberContext.tsx
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
import { useEffect } from 'react';
import { invariant } from 'ts-invariant';
import { useEthersAppContext } from '~~/context';
import { useEthersAppStore } from '~~/context/EthersAppStore';
import { useBlockNumber } from '~~/hooks';
import { TOverride } from '~~/models';
/**
* #### Summary
* A hook that gets you the current blocknumber and saves it to the store
* - can be shared by your whole app.
*
* ##### 鉂擴se
* Make sure to wrap your main app with the {@link EthersAppContext}.
* - See [scaffold-eth-typescript example](https://github.com/scaffold-eth/scaffold-eth-typescript/blob/next/packages/vite-app-ts/src/components/routes/App.tsx#L38)
*
*
* ##### 鉁忥笍 Notes
* - this extensively used by eth-hooks to trigger hooks when a new block arrives
* - uses the current provider {@link ethersProvider} from {@link useEthersContext}
*
* @category EthersAppContext
*
* @returns current block number
*/
export const useBlockNumberContext = (chainId?: number, override?: TOverride): number => {
const ethersContext = useEthersAppContext(override?.alternateContextKey);
const blockNumberState = useEthersAppStore((state) => state.blockNumberState);
const setBlockNumber = useEthersAppStore((state) => state.setBlockNumber);
let result: number | undefined = undefined;
[result] = useBlockNumber(ethersContext.provider);
useEffect(() => {
if (ethersContext.chainId && result != null && result !== blockNumberState[ethersContext.chainId]) {
setBlockNumber(result, ethersContext.chainId);
}
}, [blockNumberState, ethersContext.chainId, result, setBlockNumber]);
if (chainId && chainId !== ethersContext.chainId) {
if (blockNumberState[chainId] == null)
invariant.log(
'blockNumberState[chainId] in the store is null, make sure to have a provider for this chain',
chainId
);
result = blockNumberState[chainId] ?? 0;
}
return result;
};