|
1 | 1 | import { type Abi, formatAbi, parseAbi } from "abitype"; |
2 | 2 | import { download } from "../../storage/download.js"; |
3 | 3 | import { getClientFetch } from "../../utils/fetch.js"; |
| 4 | +import { withCache } from "../../utils/promise/withCache.js"; |
4 | 5 | import { type ThirdwebContract, getContract } from "../contract.js"; |
5 | 6 |
|
6 | | -const ABI_RESOLUTION_CACHE = new WeakMap<ThirdwebContract<Abi>, Promise<Abi>>(); |
7 | | - |
8 | 7 | /** |
9 | 8 | * Resolves the ABI (Application Binary Interface) for a given contract. |
10 | 9 | * If the ABI is already cached, it returns the cached value. |
@@ -32,31 +31,34 @@ export function resolveContractAbi<abi extends Abi>( |
32 | 31 | contract: ThirdwebContract<abi>, |
33 | 32 | contractApiBaseUrl = "https://contract.thirdweb.com/abi", |
34 | 33 | ): Promise<abi> { |
35 | | - if (ABI_RESOLUTION_CACHE.has(contract)) { |
36 | | - return ABI_RESOLUTION_CACHE.get(contract) as Promise<abi>; |
37 | | - } |
38 | | - |
39 | | - const prom = (async () => { |
40 | | - // if the contract already HAS a user defined we always use that! |
41 | | - if (contract.abi) { |
42 | | - return contract.abi as abi; |
43 | | - } |
| 34 | + return withCache( |
| 35 | + async () => { |
| 36 | + // if the contract already HAS a user defined we always use that! |
| 37 | + if (contract.abi) { |
| 38 | + return contract.abi as abi; |
| 39 | + } |
44 | 40 |
|
45 | | - // for local chains, we need to resolve the composite abi from bytecode |
46 | | - if (contract.chain.id === 31337 || contract.chain.id === 1337) { |
47 | | - return await resolveCompositeAbi(contract as ThirdwebContract); |
48 | | - } |
| 41 | + // for local chains, we need to resolve the composite abi from bytecode |
| 42 | + if (contract.chain.id === 31337 || contract.chain.id === 1337) { |
| 43 | + return (await resolveCompositeAbi(contract as ThirdwebContract)) as abi; |
| 44 | + } |
49 | 45 |
|
50 | | - // try to get it from the api |
51 | | - try { |
52 | | - return await resolveAbiFromContractApi(contract, contractApiBaseUrl); |
53 | | - } catch { |
54 | | - // if that fails, try to resolve it from the bytecode |
55 | | - return await resolveCompositeAbi(contract as ThirdwebContract); |
56 | | - } |
57 | | - })(); |
58 | | - ABI_RESOLUTION_CACHE.set(contract, prom); |
59 | | - return prom as Promise<abi>; |
| 46 | + // try to get it from the api |
| 47 | + try { |
| 48 | + return (await resolveAbiFromContractApi( |
| 49 | + contract, |
| 50 | + contractApiBaseUrl, |
| 51 | + )) as abi; |
| 52 | + } catch { |
| 53 | + // if that fails, try to resolve it from the bytecode |
| 54 | + return (await resolveCompositeAbi(contract as ThirdwebContract)) as abi; |
| 55 | + } |
| 56 | + }, |
| 57 | + { |
| 58 | + cacheKey: `${contract.chain.id}-${contract.address}`, |
| 59 | + cacheTime: 1000 * 60 * 60 * 1, // 1 hour |
| 60 | + }, |
| 61 | + ); |
60 | 62 | } |
61 | 63 |
|
62 | 64 | /** |
|
0 commit comments