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
/
useEventListener.ts
79 lines (74 loc) 路 2.38 KB
/
useEventListener.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
import { EventFilter, BaseContract } from 'ethers';
import { Result } from 'ethers/lib/utils';
import { useEffect } from 'react';
import { useQuery } from 'react-query';
import { contractKey, mergeDefaultUpdateOptions, processQueryOptions, TRequiredKeys } from '~~/functions';
import { const_blockNumberIntervalMedium, THookResult, TUpdateOptions, TypedEvent } from '~~/models';
import { keyNamespace } from '~~/models/constants';
const queryKey: TRequiredKeys = { namespace: keyNamespace.contracts, key: 'useEventListener' } as const;
/**
* #### Summary
* Tracks the events of associated with a contract
*
* ##### 鉁忥笍 Notes
* - updates triggered through ethers event listener
* - uses the current provider {@link ethersProvider} from {@link useEthersContext}
*
* @category Hooks
*
* @param contract ethers.Contract
* @param eventName
* @param startBlock
* @returns
*/
export const useEventListener = <GTypedEvent extends TypedEvent<Result>>(
contract: BaseContract | undefined,
eventFilter: string | EventFilter | undefined,
startBlock: number,
toBlock: number | undefined = undefined,
options: TUpdateOptions<GTypedEvent[]> = mergeDefaultUpdateOptions(const_blockNumberIntervalMedium)
): THookResult<GTypedEvent[]> => {
const keys = [
{
...queryKey,
...contractKey(contract),
},
{
eventFilter,
startBlock,
toBlock,
},
] as const;
const { data, refetch, status } = useQuery(
keys,
async (keys): Promise<GTypedEvent[]> => {
{
const { eventFilter: eventFilter_, startBlock: startBlock_, toBlock: toBlock_ } = keys.queryKey[1];
const result = await contract?.queryFilter(eventFilter_ as EventFilter, startBlock_, toBlock_);
return (result as GTypedEvent[]) ?? [];
}
},
{
...processQueryOptions<GTypedEvent[]>(options),
}
);
// update the result when ethers calls the event listner
useEffect(() => {
if (eventFilter != null) {
const listener = (): void => {
void refetch();
};
try {
contract?.on(eventFilter, listener);
return (): void => {
contract?.off(eventFilter, listener);
};
} catch (e) {
console.log(e);
}
}
}, [contract, eventFilter, refetch]);
// const blockNumber = useBlockNumberContext();
// useEthersUpdater(refetch, blockNumber, options);
return [data ?? [], refetch, status];
};