|
1 | 1 | /* eslint-disable no-console */
|
| 2 | +import { sha256 } from '@dm3-org/dm3-lib-shared'; |
2 | 3 | import { ethers } from 'ethers';
|
| 4 | +import { keccak256 } from 'viem'; |
3 | 5 |
|
4 | 6 | export const getCachedProvider = (
|
5 | 7 | provider: ethers.providers.JsonRpcProvider,
|
6 | 8 | ) => {
|
7 | 9 | const cache = new Map<string, any>();
|
| 10 | + |
| 11 | + const unique = new Set(); |
8 | 12 | const cacheHandler: ProxyHandler<ethers.providers.JsonRpcProvider> = {
|
9 | 13 | get: (target, fnSig, receiver) => {
|
10 | 14 | if (fnSig === 'send') {
|
11 | 15 | return async (method: string, ...args: any[]) => {
|
12 | 16 | //Simpy caching chainId safes 10 sek of initial load time
|
13 | 17 | if (method === 'eth_chainId') {
|
| 18 | + console.log(method); |
14 | 19 | const key = `${fnSig}-${method}`;
|
15 | 20 | if (cache.has(key)) {
|
| 21 | + console.log('cache hit ', key); |
16 | 22 | return cache.get(key);
|
17 | 23 | }
|
| 24 | + |
| 25 | + console.log( |
| 26 | + 'chain id cache miss ', |
| 27 | + sha256(method + fnSig), |
| 28 | + ); |
18 | 29 | //@ts-ignore
|
19 | 30 | const result = await target[fnSig](method);
|
20 | 31 | cache.set(key, result);
|
21 | 32 | return result;
|
22 | 33 | }
|
23 | 34 |
|
| 35 | + if (method === 'eth_call') { |
| 36 | + const [[{ data, to }]] = args; |
| 37 | + const key = `${fnSig}-${method}-${sha256(to)}-${sha256( |
| 38 | + data, |
| 39 | + )}`; |
| 40 | + if (cache.has(key)) { |
| 41 | + console.log('eth_call cache hit '); |
| 42 | + return cache.get(key); |
| 43 | + } |
| 44 | + |
| 45 | + console.log( |
| 46 | + 'ethcall cache miss ', |
| 47 | + sha256(method + fnSig), |
| 48 | + ); |
| 49 | + |
| 50 | + //@ts-ignore |
| 51 | + const result = await target[fnSig](method, ...args); |
| 52 | + cache.set(key, result); |
| 53 | + return result; |
| 54 | + } |
| 55 | + |
| 56 | + console.log('send cache miss ', sha256(method + fnSig)); |
| 57 | + |
24 | 58 | //@ts-ignore
|
25 | 59 | return target[fnSig](method, ...args);
|
26 | 60 | };
|
27 | 61 | }
|
28 |
| - //TODO figure out how to cache inner call |
29 |
| - /* if (fnSig === 'getResolver') { |
30 |
| - return async (address: string) => { |
31 |
| - const key = `${fnSig}-${address}`; |
32 |
| - if (cache.has(key)) { |
33 |
| - console.log('cache hit ', key); |
34 |
| - return cache.get(key); |
35 |
| - } |
36 |
| - //@ts-ignore |
37 |
| - const result = await target[fnSig](address); |
38 |
| - //@ts-ignore |
39 |
| - cache.set(key, result); |
40 |
| - return result; |
41 |
| - }; |
42 |
| - } */ |
| 62 | + |
43 | 63 | //@ts-ignore
|
44 | 64 | return target[fnSig];
|
45 | 65 | },
|
|
0 commit comments