From b9d8d72a00ae63adcf3219ae8b636bbe92a41aa8 Mon Sep 17 00:00:00 2001
From: Achthar <69119535+Achthar@users.noreply.github.com>
Date: Tue, 13 Aug 2024 12:29:39 +0200
Subject: [PATCH] ad builds
---
dist/abi/InterfaceMulticall.d.ts | 70 +
dist/constants.d.ts | 10 +
dist/context.d.ts | 5 +
dist/create.d.ts | 43 +
dist/hooks.d.ts | 13 +
dist/index.d.ts | 3 +
dist/integration-tests/App.d.ts | 2 +
dist/integration-tests/MultichainApp.d.ts | 2 +
dist/integration-tests/Updater.d.ts | 9 +
dist/integration-tests/consts.d.ts | 9 +
dist/integration-tests/erc20.d.ts | 168 ++
dist/integration-tests/hooks.d.ts | 893 +++++++++
dist/integration-tests/multicall.d.ts | 41 +
dist/integration-tests/store.d.ts | 8 +
dist/integration-tests/utils.d.ts | 1 +
dist/redux-multicall-viem.cjs.development.js | 1628 +++++++++++++++++
...edux-multicall-viem.cjs.development.js.map | 1 +
...redux-multicall-viem.cjs.production.min.js | 2 +
...x-multicall-viem.cjs.production.min.js.map | 1 +
dist/redux-multicall-viem.esm.js | 1612 ++++++++++++++++
dist/redux-multicall-viem.esm.js.map | 1 +
dist/slice.d.ts | 11 +
dist/types.d.ts | 78 +
dist/updater.d.ts | 31 +
dist/utils/callKeys.d.ts | 5 +
dist/utils/callState.d.ts | 4 +
dist/utils/chunkCalls.d.ts | 9 +
dist/utils/retry.d.ts | 22 +
dist/utils/useDebounce.d.ts | 1 +
dist/validation.d.ts | 4 +
30 files changed, 4687 insertions(+)
create mode 100644 dist/abi/InterfaceMulticall.d.ts
create mode 100644 dist/constants.d.ts
create mode 100644 dist/context.d.ts
create mode 100644 dist/create.d.ts
create mode 100644 dist/hooks.d.ts
create mode 100644 dist/index.d.ts
create mode 100644 dist/integration-tests/App.d.ts
create mode 100644 dist/integration-tests/MultichainApp.d.ts
create mode 100644 dist/integration-tests/Updater.d.ts
create mode 100644 dist/integration-tests/consts.d.ts
create mode 100644 dist/integration-tests/erc20.d.ts
create mode 100644 dist/integration-tests/hooks.d.ts
create mode 100644 dist/integration-tests/multicall.d.ts
create mode 100644 dist/integration-tests/store.d.ts
create mode 100644 dist/integration-tests/utils.d.ts
create mode 100644 dist/redux-multicall-viem.cjs.development.js
create mode 100644 dist/redux-multicall-viem.cjs.development.js.map
create mode 100644 dist/redux-multicall-viem.cjs.production.min.js
create mode 100644 dist/redux-multicall-viem.cjs.production.min.js.map
create mode 100644 dist/redux-multicall-viem.esm.js
create mode 100644 dist/redux-multicall-viem.esm.js.map
create mode 100644 dist/slice.d.ts
create mode 100644 dist/types.d.ts
create mode 100644 dist/updater.d.ts
create mode 100644 dist/utils/callKeys.d.ts
create mode 100644 dist/utils/callState.d.ts
create mode 100644 dist/utils/chunkCalls.d.ts
create mode 100644 dist/utils/retry.d.ts
create mode 100644 dist/utils/useDebounce.d.ts
create mode 100644 dist/validation.d.ts
diff --git a/dist/abi/InterfaceMulticall.d.ts b/dist/abi/InterfaceMulticall.d.ts
new file mode 100644
index 0000000..80b993a
--- /dev/null
+++ b/dist/abi/InterfaceMulticall.d.ts
@@ -0,0 +1,70 @@
+declare const _default: readonly [{
+ readonly inputs: readonly [];
+ readonly name: "getCurrentBlockTimestamp";
+ readonly outputs: readonly [{
+ readonly internalType: "uint256";
+ readonly name: "timestamp";
+ readonly type: "uint256";
+ }];
+ readonly stateMutability: "view";
+ readonly type: "function";
+}, {
+ readonly inputs: readonly [{
+ readonly internalType: "address";
+ readonly name: "addr";
+ readonly type: "address";
+ }];
+ readonly name: "getEthBalance";
+ readonly outputs: readonly [{
+ readonly internalType: "uint256";
+ readonly name: "balance";
+ readonly type: "uint256";
+ }];
+ readonly stateMutability: "view";
+ readonly type: "function";
+}, {
+ readonly inputs: readonly [{
+ readonly components: readonly [{
+ readonly internalType: "address";
+ readonly name: "target";
+ readonly type: "address";
+ }, {
+ readonly internalType: "uint256";
+ readonly name: "gasLimit";
+ readonly type: "uint256";
+ }, {
+ readonly internalType: "bytes";
+ readonly name: "callData";
+ readonly type: "bytes";
+ }];
+ readonly internalType: "struct PancakeInterfaceMulticall.Call[]";
+ readonly name: "calls";
+ readonly type: "tuple[]";
+ }];
+ readonly name: "multicall";
+ readonly outputs: readonly [{
+ readonly internalType: "uint256";
+ readonly name: "blockNumber";
+ readonly type: "uint256";
+ }, {
+ readonly components: readonly [{
+ readonly internalType: "bool";
+ readonly name: "success";
+ readonly type: "bool";
+ }, {
+ readonly internalType: "uint256";
+ readonly name: "gasUsed";
+ readonly type: "uint256";
+ }, {
+ readonly internalType: "bytes";
+ readonly name: "returnData";
+ readonly type: "bytes";
+ }];
+ readonly internalType: "struct PancakeInterfaceMulticall.Result[]";
+ readonly name: "returnData";
+ readonly type: "tuple[]";
+ }];
+ readonly stateMutability: "nonpayable";
+ readonly type: "function";
+}];
+export default _default;
diff --git a/dist/constants.d.ts b/dist/constants.d.ts
new file mode 100644
index 0000000..1599407
--- /dev/null
+++ b/dist/constants.d.ts
@@ -0,0 +1,10 @@
+import type { CallResult, CallState, ListenerOptions } from './types';
+export declare const DEFAULT_BLOCKS_PER_FETCH = 1;
+export declare const DEFAULT_CALL_GAS_REQUIRED = 1000000;
+export declare const DEFAULT_CHUNK_GAS_REQUIRED = 200000;
+export declare const CHUNK_GAS_LIMIT = 100000000;
+export declare const CONSERVATIVE_BLOCK_GAS_LIMIT = 10000000;
+export declare const INVALID_RESULT: CallResult;
+export declare const NEVER_RELOAD: ListenerOptions;
+export declare const INVALID_CALL_STATE: CallState;
+export declare const LOADING_CALL_STATE: CallState;
diff --git a/dist/context.d.ts b/dist/context.d.ts
new file mode 100644
index 0000000..1b7abde
--- /dev/null
+++ b/dist/context.d.ts
@@ -0,0 +1,5 @@
+import type { MulticallActions } from './slice';
+export interface MulticallContext {
+ reducerPath: string;
+ actions: MulticallActions;
+}
diff --git a/dist/create.d.ts b/dist/create.d.ts
new file mode 100644
index 0000000..656a218
--- /dev/null
+++ b/dist/create.d.ts
@@ -0,0 +1,43 @@
+///
+export interface MulticallOptions {
+ reducerPath?: string;
+}
+export declare function createMulticall(options?: MulticallOptions): {
+ reducerPath: string;
+ reducer: import("redux").Reducer;
+ actions: import("@reduxjs/toolkit").CaseReducerActions<{
+ addMulticallListeners: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("./types").MulticallListenerPayload;
+ type: string;
+ }) => void;
+ removeMulticallListeners: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("./types").MulticallListenerPayload;
+ type: string;
+ }) => void;
+ fetchingMulticallResults: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("./types").MulticallFetchingPayload;
+ type: string;
+ }) => void;
+ errorFetchingMulticallResults: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("./types").MulticallFetchingPayload;
+ type: string;
+ }) => void;
+ updateMulticallResults: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("./types").MulticallResultsPayload;
+ type: string;
+ }) => void;
+ updateListenerOptions: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("./types").MulticallListenerOptionsPayload;
+ type: string;
+ }) => void;
+ }, string>;
+ hooks: {
+ useMultipleContractSingleData: (chainId: number | undefined, latestBlockNumber: number | undefined, addresses: (string | undefined)[], contractInterface: import("abitype").AbiFunction[], methodName: string, callInputs?: (string | number | BigInt | import("./validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => import("./types").CallState[];
+ useSingleContractMultipleData: (chainId: number | undefined, latestBlockNumber: number | undefined, contract: import("./types").ContractInfo | null | undefined, methodName: string, callInputs: ((string | number | BigInt | import("./validation").MethodArg[] | undefined)[] | undefined)[], options?: Partial | undefined) => import("./types").CallState[];
+ useSingleContractWithCallData: (chainId: number | undefined, latestBlockNumber: number | undefined, contract: import("./types").ContractInfo | null | undefined, callDatas: string[], options?: Partial | undefined) => import("./types").CallState[];
+ useSingleCallResult: (chainId: number | undefined, latestBlockNumber: number | undefined, contract: import("./types").ContractInfo | null | undefined, methodName: string, inputs?: (string | number | BigInt | import("./validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => import("./types").CallState;
+ useMultiChainMultiContractSingleData: (chainToBlockNumber: Record, chainToAddresses: Record, contractInterface: import("abitype").AbiFunction[], methodName: string, callInputs?: (string | number | BigInt | import("./validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => Record;
+ useMultiChainSingleContractSingleData: (chainToBlockNumber: Record, chainToAddress: Record, contractInterface: import("abitype").AbiFunction[], methodName: string, callInputs?: (string | number | BigInt | import("./validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => Record;
+ };
+ Updater: (props: Pick) => import("react").JSX.Element;
+};
diff --git a/dist/hooks.d.ts b/dist/hooks.d.ts
new file mode 100644
index 0000000..2a7e25d
--- /dev/null
+++ b/dist/hooks.d.ts
@@ -0,0 +1,13 @@
+import type { MulticallContext } from './context';
+import type { Call, CallResult, CallState, ContractInfo, ListenerOptions, ListenerOptionsWithGas } from './types';
+import { MethodArg } from './validation';
+import { AbiFunction } from 'viem';
+declare type OptionalMethodInputs = Array | undefined;
+export declare function useCallsDataSubscription(context: MulticallContext, chainId: number | undefined, calls: Array, listenerOptions?: ListenerOptions): CallResult[];
+export declare function useSingleContractMultipleData(context: MulticallContext, chainId: number | undefined, latestBlockNumber: number | undefined, contract: ContractInfo | null | undefined, methodName: string, callInputs: OptionalMethodInputs[], options?: Partial): CallState[];
+export declare function useMultipleContractSingleData(context: MulticallContext, chainId: number | undefined, latestBlockNumber: number | undefined, addresses: (string | undefined)[], contractInterface: AbiFunction[], methodName: string, callInputs?: OptionalMethodInputs, options?: Partial): CallState[];
+export declare function useSingleCallResult(context: MulticallContext, chainId: number | undefined, latestBlockNumber: number | undefined, contract: ContractInfo | null | undefined, methodName: string, inputs?: OptionalMethodInputs, options?: Partial): CallState;
+export declare function useSingleContractWithCallData(context: MulticallContext, chainId: number | undefined, latestBlockNumber: number | undefined, contract: ContractInfo | null | undefined, callDatas: string[], options?: Partial): CallState[];
+export declare function useMultiChainMultiContractSingleData(context: MulticallContext, chainToBlockNumber: Record, chainToAddresses: Record>, contractInterface: AbiFunction[], methodName: string, callInputs?: OptionalMethodInputs, options?: Partial): Record;
+export declare function useMultiChainSingleContractSingleData(context: MulticallContext, chainToBlockNumber: Record, chainToAddress: Record, contractInterface: AbiFunction[], methodName: string, callInputs?: OptionalMethodInputs, options?: Partial): Record;
+export {};
diff --git a/dist/index.d.ts b/dist/index.d.ts
new file mode 100644
index 0000000..3cf59a0
--- /dev/null
+++ b/dist/index.d.ts
@@ -0,0 +1,3 @@
+export * from './constants';
+export * from './create';
+export * from './types';
diff --git a/dist/integration-tests/App.d.ts b/dist/integration-tests/App.d.ts
new file mode 100644
index 0000000..377078c
--- /dev/null
+++ b/dist/integration-tests/App.d.ts
@@ -0,0 +1,2 @@
+import React from 'react';
+export declare function App(): React.JSX.Element;
diff --git a/dist/integration-tests/MultichainApp.d.ts b/dist/integration-tests/MultichainApp.d.ts
new file mode 100644
index 0000000..a2829cb
--- /dev/null
+++ b/dist/integration-tests/MultichainApp.d.ts
@@ -0,0 +1,2 @@
+import React from 'react';
+export declare function MultichainApp(): React.JSX.Element;
diff --git a/dist/integration-tests/Updater.d.ts b/dist/integration-tests/Updater.d.ts
new file mode 100644
index 0000000..d356054
--- /dev/null
+++ b/dist/integration-tests/Updater.d.ts
@@ -0,0 +1,9 @@
+import React from 'react';
+import { ChainId } from './consts';
+interface Props {
+ chainId: ChainId;
+ blockNumber: number | undefined;
+ blocksPerFetch?: number;
+}
+export declare function Updater({ chainId, blockNumber, blocksPerFetch }: Props): React.JSX.Element;
+export {};
diff --git a/dist/integration-tests/consts.d.ts b/dist/integration-tests/consts.d.ts
new file mode 100644
index 0000000..4025db7
--- /dev/null
+++ b/dist/integration-tests/consts.d.ts
@@ -0,0 +1,9 @@
+export declare const NULL_ADDRESS = "0x0000000000000000000000000000000000000000";
+export declare const MULTICALL_ADDRESS = "0x1F98415757620B543A52E61c46B32eB19261F984";
+export declare const DAI_ADDRESS = "0x6B175474E89094C44Da98b954EedeAC495271d0F";
+export declare const USDC_ADDRESS = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
+export declare const USDT_ADDRESS = "0xdAC17F958D2ee523a2206206994597C13D831ec7";
+export declare enum ChainId {
+ MAINNET = 1,
+ SEPOLIA = 11155111
+}
diff --git a/dist/integration-tests/erc20.d.ts b/dist/integration-tests/erc20.d.ts
new file mode 100644
index 0000000..c6feef7
--- /dev/null
+++ b/dist/integration-tests/erc20.d.ts
@@ -0,0 +1,168 @@
+export declare const ERC20_ABI: readonly [{
+ readonly constant: true;
+ readonly inputs: readonly [];
+ readonly name: "name";
+ readonly outputs: readonly [{
+ readonly name: "";
+ readonly type: "string";
+ }];
+ readonly payable: false;
+ readonly stateMutability: "view";
+ readonly type: "function";
+}, {
+ readonly constant: false;
+ readonly inputs: readonly [{
+ readonly name: "_spender";
+ readonly type: "address";
+ }, {
+ readonly name: "_value";
+ readonly type: "uint256";
+ }];
+ readonly name: "approve";
+ readonly outputs: readonly [{
+ readonly name: "";
+ readonly type: "bool";
+ }];
+ readonly payable: false;
+ readonly stateMutability: "nonpayable";
+ readonly type: "function";
+}, {
+ readonly constant: true;
+ readonly inputs: readonly [];
+ readonly name: "totalSupply";
+ readonly outputs: readonly [{
+ readonly name: "";
+ readonly type: "uint256";
+ }];
+ readonly payable: false;
+ readonly stateMutability: "view";
+ readonly type: "function";
+}, {
+ readonly constant: false;
+ readonly inputs: readonly [{
+ readonly name: "_from";
+ readonly type: "address";
+ }, {
+ readonly name: "_to";
+ readonly type: "address";
+ }, {
+ readonly name: "_value";
+ readonly type: "uint256";
+ }];
+ readonly name: "transferFrom";
+ readonly outputs: readonly [{
+ readonly name: "";
+ readonly type: "bool";
+ }];
+ readonly payable: false;
+ readonly stateMutability: "nonpayable";
+ readonly type: "function";
+}, {
+ readonly constant: true;
+ readonly inputs: readonly [];
+ readonly name: "decimals";
+ readonly outputs: readonly [{
+ readonly name: "";
+ readonly type: "uint8";
+ }];
+ readonly payable: false;
+ readonly stateMutability: "view";
+ readonly type: "function";
+}, {
+ readonly constant: true;
+ readonly inputs: readonly [{
+ readonly name: "_owner";
+ readonly type: "address";
+ }];
+ readonly name: "balanceOf";
+ readonly outputs: readonly [{
+ readonly name: "balance";
+ readonly type: "uint256";
+ }];
+ readonly payable: false;
+ readonly stateMutability: "view";
+ readonly type: "function";
+}, {
+ readonly constant: true;
+ readonly inputs: readonly [];
+ readonly name: "symbol";
+ readonly outputs: readonly [{
+ readonly name: "";
+ readonly type: "string";
+ }];
+ readonly payable: false;
+ readonly stateMutability: "view";
+ readonly type: "function";
+}, {
+ readonly constant: false;
+ readonly inputs: readonly [{
+ readonly name: "_to";
+ readonly type: "address";
+ }, {
+ readonly name: "_value";
+ readonly type: "uint256";
+ }];
+ readonly name: "transfer";
+ readonly outputs: readonly [{
+ readonly name: "";
+ readonly type: "bool";
+ }];
+ readonly payable: false;
+ readonly stateMutability: "nonpayable";
+ readonly type: "function";
+}, {
+ readonly constant: true;
+ readonly inputs: readonly [{
+ readonly name: "_owner";
+ readonly type: "address";
+ }, {
+ readonly name: "_spender";
+ readonly type: "address";
+ }];
+ readonly name: "allowance";
+ readonly outputs: readonly [{
+ readonly name: "";
+ readonly type: "uint256";
+ }];
+ readonly payable: false;
+ readonly stateMutability: "view";
+ readonly type: "function";
+}, {
+ readonly payable: true;
+ readonly stateMutability: "payable";
+ readonly type: "fallback";
+}, {
+ readonly anonymous: false;
+ readonly inputs: readonly [{
+ readonly indexed: true;
+ readonly name: "owner";
+ readonly type: "address";
+ }, {
+ readonly indexed: true;
+ readonly name: "spender";
+ readonly type: "address";
+ }, {
+ readonly indexed: false;
+ readonly name: "value";
+ readonly type: "uint256";
+ }];
+ readonly name: "Approval";
+ readonly type: "event";
+}, {
+ readonly anonymous: false;
+ readonly inputs: readonly [{
+ readonly indexed: true;
+ readonly name: "from";
+ readonly type: "address";
+ }, {
+ readonly indexed: true;
+ readonly name: "to";
+ readonly type: "address";
+ }, {
+ readonly indexed: false;
+ readonly name: "value";
+ readonly type: "uint256";
+ }];
+ readonly name: "Transfer";
+ readonly type: "event";
+}];
diff --git a/dist/integration-tests/hooks.d.ts b/dist/integration-tests/hooks.d.ts
new file mode 100644
index 0000000..ee0d931
--- /dev/null
+++ b/dist/integration-tests/hooks.d.ts
@@ -0,0 +1,893 @@
+import { ChainId } from './consts';
+import { MulticallInfo } from '../src';
+import { PublicClient } from 'viem';
+export declare function useMulticallContract(chainId: ChainId): MulticallInfo;
+export declare function useLatestBlock(provider: PublicClient): number | undefined;
+export declare function useCurrentBlockTimestamp(chainId: ChainId, blockNumber: number | undefined): string | undefined;
+export declare function useCurrentBlockTimestampMultichain(chainIds: ChainId[], blockNumbers: Array): Array;
+export declare function useMaxTokenBalance(chainId: ChainId, blockNumber: number | undefined): string | undefined;
+export declare function getProvider(chainId: ChainId): any;
+export declare function getInfuraChainName(chainId: ChainId): "homestead" | "sepolia";
+export declare function getViemChain(chainId: ChainId): {
+ chain: {
+ blockExplorers: {
+ readonly default: {
+ readonly name: "Etherscan";
+ readonly url: "https://etherscan.io";
+ readonly apiUrl: "https://api.etherscan.io/api";
+ };
+ };
+ contracts: {
+ readonly ensRegistry: {
+ readonly address: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";
+ };
+ readonly ensUniversalResolver: {
+ readonly address: "0xce01f8eee7E479C928F8919abD53E553a36CeF67";
+ readonly blockCreated: 19258213;
+ };
+ readonly multicall3: {
+ readonly address: "0xca11bde05977b3631167028862be2a173976ca11";
+ readonly blockCreated: 14353601;
+ };
+ };
+ id: 1;
+ name: "Ethereum";
+ nativeCurrency: {
+ readonly name: "Ether";
+ readonly symbol: "ETH";
+ readonly decimals: 18;
+ };
+ rpcUrls: {
+ readonly default: {
+ readonly http: readonly ["https://cloudflare-eth.com"];
+ };
+ };
+ sourceId?: number | undefined;
+ testnet?: boolean | undefined;
+ custom?: Record | undefined;
+ fees?: import("viem").ChainFees | undefined;
+ formatters?: undefined;
+ serializers?: import("viem").ChainSerializers[] | undefined;
+ blobs?: readonly any[] | readonly Uint8Array[] | undefined;
+ blobVersionedHashes: readonly any[];
+ kzg?: undefined;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs: readonly any[] | readonly Uint8Array[];
+ blobVersionedHashes?: readonly any[] | undefined;
+ kzg: import("viem").Kzg;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs?: readonly any[] | readonly Uint8Array[] | undefined;
+ blobVersionedHashes: readonly any[];
+ kzg?: undefined;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs: readonly any[] | readonly Uint8Array[];
+ blobVersionedHashes?: readonly any[] | undefined;
+ kzg: import("viem").Kzg;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs?: readonly any[] | readonly Uint8Array[] | undefined;
+ blobVersionedHashes: readonly any[];
+ kzg?: undefined;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs: readonly any[] | readonly Uint8Array[];
+ blobVersionedHashes?: readonly any[] | undefined;
+ kzg: import("viem").Kzg;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip7702" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ authorizationList: import("viem/experimental").SignedAuthorizationList;
+ chainId: number;
+ blobVersionedHashes?: undefined;
+ blobs?: undefined;
+ kzg?: undefined;
+ sidecars?: undefined;
+ } | {
+ type?: "eip7702" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ authorizationList: import("viem/experimental").SignedAuthorizationList;
+ chainId: number;
+ blobVersionedHashes?: undefined;
+ blobs?: undefined;
+ kzg?: undefined;
+ sidecars?: undefined;
+ } | {
+ type?: "eip7702" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ authorizationList: import("viem/experimental").SignedAuthorizationList;
+ chainId: number;
+ blobVersionedHashes?: undefined;
+ blobs?: undefined;
+ kzg?: undefined;
+ sidecars?: undefined;
+ }> | undefined;
+ };
+ transport: import("viem").Transport<"http", {
+ fetchOptions?: Pick | undefined;
+ url?: string | undefined;
+ }, import("viem").EIP1193RequestFn>;
+} | {
+ chain: {
+ blockExplorers: {
+ readonly default: {
+ readonly name: "Etherscan";
+ readonly url: "https://sepolia.etherscan.io";
+ readonly apiUrl: "https://api-sepolia.etherscan.io/api";
+ };
+ };
+ contracts: {
+ readonly multicall3: {
+ readonly address: "0xca11bde05977b3631167028862be2a173976ca11";
+ readonly blockCreated: 751532;
+ };
+ readonly ensRegistry: {
+ readonly address: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e";
+ };
+ readonly ensUniversalResolver: {
+ readonly address: "0xc8Af999e38273D658BE1b921b88A9Ddf005769cC";
+ readonly blockCreated: 5317080;
+ };
+ };
+ id: 11155111;
+ name: "Sepolia";
+ nativeCurrency: {
+ readonly name: "Sepolia Ether";
+ readonly symbol: "ETH";
+ readonly decimals: 18;
+ };
+ rpcUrls: {
+ readonly default: {
+ readonly http: readonly ["https://rpc.sepolia.org"];
+ };
+ };
+ sourceId?: number | undefined;
+ testnet: true;
+ custom?: Record | undefined;
+ fees?: import("viem").ChainFees | undefined;
+ formatters?: undefined;
+ serializers?: import("viem").ChainSerializers[] | undefined;
+ blobs?: readonly any[] | readonly Uint8Array[] | undefined;
+ blobVersionedHashes: readonly any[];
+ kzg?: undefined;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs: readonly any[] | readonly Uint8Array[];
+ blobVersionedHashes?: readonly any[] | undefined;
+ kzg: import("viem").Kzg;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs?: readonly any[] | readonly Uint8Array[] | undefined;
+ blobVersionedHashes: readonly any[];
+ kzg?: undefined;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs: readonly any[] | readonly Uint8Array[];
+ blobVersionedHashes?: readonly any[] | undefined;
+ kzg: import("viem").Kzg;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs?: readonly any[] | readonly Uint8Array[] | undefined;
+ blobVersionedHashes: readonly any[];
+ kzg?: undefined;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip4844" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: bigint | undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ chainId: number;
+ sidecars?: false | readonly import("viem").BlobSidecar[] | undefined;
+ blobs: readonly any[] | readonly Uint8Array[];
+ blobVersionedHashes?: readonly any[] | undefined;
+ kzg: import("viem").Kzg;
+ authorizationList?: undefined;
+ } | {
+ type?: "eip7702" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ authorizationList: import("viem/experimental").SignedAuthorizationList;
+ chainId: number;
+ blobVersionedHashes?: undefined;
+ blobs?: undefined;
+ kzg?: undefined;
+ sidecars?: undefined;
+ } | {
+ type?: "eip7702" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ authorizationList: import("viem/experimental").SignedAuthorizationList;
+ chainId: number;
+ blobVersionedHashes?: undefined;
+ blobs?: undefined;
+ kzg?: undefined;
+ sidecars?: undefined;
+ } | {
+ type?: "eip7702" | undefined;
+ data?: any;
+ gas?: bigint | undefined;
+ nonce?: number | undefined;
+ to?: any;
+ value?: bigint | undefined;
+ r?: any;
+ s?: any;
+ v?: bigint | undefined;
+ yParity?: number | undefined;
+ gasPrice?: undefined;
+ maxFeePerBlobGas?: undefined;
+ maxFeePerGas?: bigint | undefined;
+ maxPriorityFeePerGas?: bigint | undefined;
+ accessList?: import("viem").AccessList | undefined;
+ authorizationList: import("viem/experimental").SignedAuthorizationList;
+ chainId: number;
+ blobVersionedHashes?: undefined;
+ blobs?: undefined;
+ kzg?: undefined;
+ sidecars?: undefined;
+ }> | undefined;
+ };
+ transport: import("viem").Transport<"http", {
+ fetchOptions?: Pick | undefined;
+ url?: string | undefined;
+ }, import("viem").EIP1193RequestFn>;
+};
diff --git a/dist/integration-tests/multicall.d.ts b/dist/integration-tests/multicall.d.ts
new file mode 100644
index 0000000..37d61b6
--- /dev/null
+++ b/dist/integration-tests/multicall.d.ts
@@ -0,0 +1,41 @@
+///
+export declare const multicall: {
+ reducerPath: string;
+ reducer: import("redux").Reducer;
+ actions: import("@reduxjs/toolkit").CaseReducerActions<{
+ addMulticallListeners: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("../src").MulticallListenerPayload;
+ type: string;
+ }) => void;
+ removeMulticallListeners: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("../src").MulticallListenerPayload;
+ type: string;
+ }) => void;
+ fetchingMulticallResults: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("../src").MulticallFetchingPayload;
+ type: string;
+ }) => void;
+ errorFetchingMulticallResults: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("../src").MulticallFetchingPayload;
+ type: string;
+ }) => void;
+ updateMulticallResults: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("../src").MulticallResultsPayload;
+ type: string;
+ }) => void;
+ updateListenerOptions: (state: import("immer/dist/internal").WritableDraft, action: {
+ payload: import("../src").MulticallListenerOptionsPayload;
+ type: string;
+ }) => void;
+ }, string>;
+ hooks: {
+ useMultipleContractSingleData: (chainId: number | undefined, latestBlockNumber: number | undefined, addresses: (string | undefined)[], contractInterface: import("abitype").AbiFunction[], methodName: string, callInputs?: (string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => import("../src").CallState[];
+ useSingleContractMultipleData: (chainId: number | undefined, latestBlockNumber: number | undefined, contract: import("../src").ContractInfo | null | undefined, methodName: string, callInputs: ((string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined)[], options?: Partial | undefined) => import("../src").CallState[];
+ useSingleContractWithCallData: (chainId: number | undefined, latestBlockNumber: number | undefined, contract: import("../src").ContractInfo | null | undefined, callDatas: string[], options?: Partial | undefined) => import("../src").CallState[];
+ useSingleCallResult: (chainId: number | undefined, latestBlockNumber: number | undefined, contract: import("../src").ContractInfo | null | undefined, methodName: string, inputs?: (string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => import("../src").CallState;
+ useMultiChainMultiContractSingleData: (chainToBlockNumber: Record, chainToAddresses: Record, contractInterface: import("abitype").AbiFunction[], methodName: string, callInputs?: (string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => Record;
+ useMultiChainSingleContractSingleData: (chainToBlockNumber: Record, chainToAddress: Record, contractInterface: import("abitype").AbiFunction[], methodName: string, callInputs?: (string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => Record;
+ };
+ Updater: (props: Pick) => import("react").JSX.Element;
+};
+export declare const useMultipleContractSingleData: (chainId: number | undefined, latestBlockNumber: number | undefined, addresses: (string | undefined)[], contractInterface: import("abitype").AbiFunction[], methodName: string, callInputs?: (string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => import("../src").CallState[], useSingleCallResult: (chainId: number | undefined, latestBlockNumber: number | undefined, contract: import("../src").ContractInfo | null | undefined, methodName: string, inputs?: (string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => import("../src").CallState, useSingleContractMultipleData: (chainId: number | undefined, latestBlockNumber: number | undefined, contract: import("../src").ContractInfo | null | undefined, methodName: string, callInputs: ((string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined)[], options?: Partial | undefined) => import("../src").CallState[], useSingleContractWithCallData: (chainId: number | undefined, latestBlockNumber: number | undefined, contract: import("../src").ContractInfo | null | undefined, callDatas: string[], options?: Partial | undefined) => import("../src").CallState[], useMultiChainMultiContractSingleData: (chainToBlockNumber: Record, chainToAddresses: Record, contractInterface: import("abitype").AbiFunction[], methodName: string, callInputs?: (string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => Record, useMultiChainSingleContractSingleData: (chainToBlockNumber: Record, chainToAddress: Record, contractInterface: import("abitype").AbiFunction[], methodName: string, callInputs?: (string | number | BigInt | import("../src/validation").MethodArg[] | undefined)[] | undefined, options?: Partial | undefined) => Record;
diff --git a/dist/integration-tests/store.d.ts b/dist/integration-tests/store.d.ts
new file mode 100644
index 0000000..4b95d6b
--- /dev/null
+++ b/dist/integration-tests/store.d.ts
@@ -0,0 +1,8 @@
+export declare const rootReducer: import("redux").Reducer, import("redux").AnyAction>;
+export declare const store: import("@reduxjs/toolkit/dist/configureStore").ToolkitStore, import("redux").AnyAction, [import("@reduxjs/toolkit").ThunkMiddleware, import("redux").AnyAction, undefined>]>;
diff --git a/dist/integration-tests/utils.d.ts b/dist/integration-tests/utils.d.ts
new file mode 100644
index 0000000..6b29a07
--- /dev/null
+++ b/dist/integration-tests/utils.d.ts
@@ -0,0 +1 @@
+export declare function sleep(milliseconds: number): Promise;
diff --git a/dist/redux-multicall-viem.cjs.development.js b/dist/redux-multicall-viem.cjs.development.js
new file mode 100644
index 0000000..9c4a64e
--- /dev/null
+++ b/dist/redux-multicall-viem.cjs.development.js
@@ -0,0 +1,1628 @@
+'use strict';
+
+Object.defineProperty(exports, '__esModule', { value: true });
+
+function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
+
+var React = require('react');
+var React__default = _interopDefault(React);
+var reactRedux = require('react-redux');
+var viem = require('viem');
+var toolkit = require('@reduxjs/toolkit');
+
+var DEFAULT_BLOCKS_PER_FETCH = 1;
+var DEFAULT_CALL_GAS_REQUIRED = 1000000;
+var DEFAULT_CHUNK_GAS_REQUIRED = 200000;
+var CHUNK_GAS_LIMIT = 100000000;
+var CONSERVATIVE_BLOCK_GAS_LIMIT = 10000000; // conservative, hard-coded estimate of the current block gas limit
+// Consts for hooks
+var INVALID_RESULT = {
+ valid: false,
+ blockNumber: undefined,
+ data: undefined
+};
+var NEVER_RELOAD = {
+ blocksPerFetch: Infinity
+};
+var INVALID_CALL_STATE = {
+ valid: false,
+ result: undefined,
+ loading: false,
+ syncing: false,
+ error: false
+};
+var LOADING_CALL_STATE = {
+ valid: true,
+ result: undefined,
+ loading: true,
+ syncing: true,
+ error: false
+};
+
+function _arrayLikeToArray(r, a) {
+ (null == a || a > r.length) && (a = r.length);
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
+ return n;
+}
+function asyncGeneratorStep(n, t, e, r, o, a, c) {
+ try {
+ var i = n[a](c),
+ u = i.value;
+ } catch (n) {
+ return void e(n);
+ }
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
+}
+function _asyncToGenerator(n) {
+ return function () {
+ var t = this,
+ e = arguments;
+ return new Promise(function (r, o) {
+ var a = n.apply(t, e);
+ function _next(n) {
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
+ }
+ function _throw(n) {
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
+ }
+ _next(void 0);
+ });
+ };
+}
+function _construct(t, e, r) {
+ if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
+ var o = [null];
+ o.push.apply(o, e);
+ var p = new (t.bind.apply(t, o))();
+ return r && _setPrototypeOf(p, r.prototype), p;
+}
+function _createForOfIteratorHelperLoose(r, e) {
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
+ if (t) return (t = t.call(r)).next.bind(t);
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
+ t && (r = t);
+ var o = 0;
+ return function () {
+ return o >= r.length ? {
+ done: !0
+ } : {
+ done: !1,
+ value: r[o++]
+ };
+ };
+ }
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+}
+function _extends() {
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
+ for (var e = 1; e < arguments.length; e++) {
+ var t = arguments[e];
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
+ }
+ return n;
+ }, _extends.apply(null, arguments);
+}
+function _getPrototypeOf(t) {
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
+ return t.__proto__ || Object.getPrototypeOf(t);
+ }, _getPrototypeOf(t);
+}
+function _inheritsLoose(t, o) {
+ t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
+}
+function _isNativeFunction(t) {
+ try {
+ return -1 !== Function.toString.call(t).indexOf("[native code]");
+ } catch (n) {
+ return "function" == typeof t;
+ }
+}
+function _isNativeReflectConstruct() {
+ try {
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
+ } catch (t) {}
+ return (_isNativeReflectConstruct = function () {
+ return !!t;
+ })();
+}
+function _regeneratorRuntime() {
+ _regeneratorRuntime = function () {
+ return e;
+ };
+ var t,
+ e = {},
+ r = Object.prototype,
+ n = r.hasOwnProperty,
+ o = Object.defineProperty || function (t, e, r) {
+ t[e] = r.value;
+ },
+ i = "function" == typeof Symbol ? Symbol : {},
+ a = i.iterator || "@@iterator",
+ c = i.asyncIterator || "@@asyncIterator",
+ u = i.toStringTag || "@@toStringTag";
+ function define(t, e, r) {
+ return Object.defineProperty(t, e, {
+ value: r,
+ enumerable: !0,
+ configurable: !0,
+ writable: !0
+ }), t[e];
+ }
+ try {
+ define({}, "");
+ } catch (t) {
+ define = function (t, e, r) {
+ return t[e] = r;
+ };
+ }
+ function wrap(t, e, r, n) {
+ var i = e && e.prototype instanceof Generator ? e : Generator,
+ a = Object.create(i.prototype),
+ c = new Context(n || []);
+ return o(a, "_invoke", {
+ value: makeInvokeMethod(t, r, c)
+ }), a;
+ }
+ function tryCatch(t, e, r) {
+ try {
+ return {
+ type: "normal",
+ arg: t.call(e, r)
+ };
+ } catch (t) {
+ return {
+ type: "throw",
+ arg: t
+ };
+ }
+ }
+ e.wrap = wrap;
+ var h = "suspendedStart",
+ l = "suspendedYield",
+ f = "executing",
+ s = "completed",
+ y = {};
+ function Generator() {}
+ function GeneratorFunction() {}
+ function GeneratorFunctionPrototype() {}
+ var p = {};
+ define(p, a, function () {
+ return this;
+ });
+ var d = Object.getPrototypeOf,
+ v = d && d(d(values([])));
+ v && v !== r && n.call(v, a) && (p = v);
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
+ function defineIteratorMethods(t) {
+ ["next", "throw", "return"].forEach(function (e) {
+ define(t, e, function (t) {
+ return this._invoke(e, t);
+ });
+ });
+ }
+ function AsyncIterator(t, e) {
+ function invoke(r, o, i, a) {
+ var c = tryCatch(t[r], t, o);
+ if ("throw" !== c.type) {
+ var u = c.arg,
+ h = u.value;
+ return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
+ invoke("next", t, i, a);
+ }, function (t) {
+ invoke("throw", t, i, a);
+ }) : e.resolve(h).then(function (t) {
+ u.value = t, i(u);
+ }, function (t) {
+ return invoke("throw", t, i, a);
+ });
+ }
+ a(c.arg);
+ }
+ var r;
+ o(this, "_invoke", {
+ value: function (t, n) {
+ function callInvokeWithMethodAndArg() {
+ return new e(function (e, r) {
+ invoke(t, n, e, r);
+ });
+ }
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
+ }
+ });
+ }
+ function makeInvokeMethod(e, r, n) {
+ var o = h;
+ return function (i, a) {
+ if (o === f) throw Error("Generator is already running");
+ if (o === s) {
+ if ("throw" === i) throw a;
+ return {
+ value: t,
+ done: !0
+ };
+ }
+ for (n.method = i, n.arg = a;;) {
+ var c = n.delegate;
+ if (c) {
+ var u = maybeInvokeDelegate(c, n);
+ if (u) {
+ if (u === y) continue;
+ return u;
+ }
+ }
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
+ if (o === h) throw o = s, n.arg;
+ n.dispatchException(n.arg);
+ } else "return" === n.method && n.abrupt("return", n.arg);
+ o = f;
+ var p = tryCatch(e, r, n);
+ if ("normal" === p.type) {
+ if (o = n.done ? s : l, p.arg === y) continue;
+ return {
+ value: p.arg,
+ done: n.done
+ };
+ }
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
+ }
+ };
+ }
+ function maybeInvokeDelegate(e, r) {
+ var n = r.method,
+ o = e.iterator[n];
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
+ var i = tryCatch(o, e.iterator, r.arg);
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
+ var a = i.arg;
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
+ }
+ function pushTryEntry(t) {
+ var e = {
+ tryLoc: t[0]
+ };
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
+ }
+ function resetTryEntry(t) {
+ var e = t.completion || {};
+ e.type = "normal", delete e.arg, t.completion = e;
+ }
+ function Context(t) {
+ this.tryEntries = [{
+ tryLoc: "root"
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
+ }
+ function values(e) {
+ if (e || "" === e) {
+ var r = e[a];
+ if (r) return r.call(e);
+ if ("function" == typeof e.next) return e;
+ if (!isNaN(e.length)) {
+ var o = -1,
+ i = function next() {
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
+ return next.value = t, next.done = !0, next;
+ };
+ return i.next = i;
+ }
+ }
+ throw new TypeError(typeof e + " is not iterable");
+ }
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
+ value: GeneratorFunctionPrototype,
+ configurable: !0
+ }), o(GeneratorFunctionPrototype, "constructor", {
+ value: GeneratorFunction,
+ configurable: !0
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
+ var e = "function" == typeof t && t.constructor;
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
+ }, e.mark = function (t) {
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
+ }, e.awrap = function (t) {
+ return {
+ __await: t
+ };
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
+ return this;
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
+ void 0 === i && (i = Promise);
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
+ return t.done ? t.value : a.next();
+ });
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
+ return this;
+ }), define(g, "toString", function () {
+ return "[object Generator]";
+ }), e.keys = function (t) {
+ var e = Object(t),
+ r = [];
+ for (var n in e) r.push(n);
+ return r.reverse(), function next() {
+ for (; r.length;) {
+ var t = r.pop();
+ if (t in e) return next.value = t, next.done = !1, next;
+ }
+ return next.done = !0, next;
+ };
+ }, e.values = values, Context.prototype = {
+ constructor: Context,
+ reset: function (e) {
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
+ },
+ stop: function () {
+ this.done = !0;
+ var t = this.tryEntries[0].completion;
+ if ("throw" === t.type) throw t.arg;
+ return this.rval;
+ },
+ dispatchException: function (e) {
+ if (this.done) throw e;
+ var r = this;
+ function handle(n, o) {
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
+ }
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
+ var i = this.tryEntries[o],
+ a = i.completion;
+ if ("root" === i.tryLoc) return handle("end");
+ if (i.tryLoc <= this.prev) {
+ var c = n.call(i, "catchLoc"),
+ u = n.call(i, "finallyLoc");
+ if (c && u) {
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
+ } else if (c) {
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
+ } else {
+ if (!u) throw Error("try statement without catch or finally");
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
+ }
+ }
+ }
+ },
+ abrupt: function (t, e) {
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
+ var o = this.tryEntries[r];
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
+ var i = o;
+ break;
+ }
+ }
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
+ var a = i ? i.completion : {};
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
+ },
+ complete: function (t, e) {
+ if ("throw" === t.type) throw t.arg;
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
+ },
+ finish: function (t) {
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
+ var r = this.tryEntries[e];
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
+ }
+ },
+ catch: function (t) {
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
+ var r = this.tryEntries[e];
+ if (r.tryLoc === t) {
+ var n = r.completion;
+ if ("throw" === n.type) {
+ var o = n.arg;
+ resetTryEntry(r);
+ }
+ return o;
+ }
+ }
+ throw Error("illegal catch attempt");
+ },
+ delegateYield: function (e, r, n) {
+ return this.delegate = {
+ iterator: values(e),
+ resultName: r,
+ nextLoc: n
+ }, "next" === this.method && (this.arg = t), y;
+ }
+ }, e;
+}
+function _setPrototypeOf(t, e) {
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
+ return t.__proto__ = e, t;
+ }, _setPrototypeOf(t, e);
+}
+function _unsupportedIterableToArray(r, a) {
+ if (r) {
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
+ var t = {}.toString.call(r).slice(8, -1);
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
+ }
+}
+function _wrapNativeSuper(t) {
+ var r = "function" == typeof Map ? new Map() : void 0;
+ return _wrapNativeSuper = function (t) {
+ if (null === t || !_isNativeFunction(t)) return t;
+ if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
+ if (void 0 !== r) {
+ if (r.has(t)) return r.get(t);
+ r.set(t, Wrapper);
+ }
+ function Wrapper() {
+ return _construct(t, arguments, _getPrototypeOf(this).constructor);
+ }
+ return Wrapper.prototype = Object.create(t.prototype, {
+ constructor: {
+ value: Wrapper,
+ enumerable: !1,
+ writable: !0,
+ configurable: !0
+ }
+ }), _setPrototypeOf(Wrapper, t);
+ }, _wrapNativeSuper(t);
+}
+
+function toCallKey(call) {
+ var key = call.address + "-" + call.callData;
+ if (call.gasRequired) {
+ if (!Number.isSafeInteger(call.gasRequired)) {
+ throw new Error("Invalid number: " + call.gasRequired);
+ }
+ key += "-" + call.gasRequired;
+ }
+ return key;
+}
+function parseCallKey(callKey) {
+ var pcs = callKey.split('-');
+ if (![2, 3].includes(pcs.length)) {
+ throw new Error("Invalid call key: " + callKey);
+ }
+ return _extends({
+ address: pcs[0],
+ callData: pcs[1]
+ }, pcs[2] ? {
+ gasRequired: Number.parseInt(pcs[2])
+ } : {});
+}
+function callsToCallKeys(calls) {
+ var _calls$filter$map$sor, _calls$filter;
+ return (_calls$filter$map$sor = calls == null || (_calls$filter = calls.filter(function (c) {
+ return Boolean(c);
+ })) == null || (_calls$filter = _calls$filter.map(toCallKey)) == null ? void 0 : _calls$filter.sort()) != null ? _calls$filter$map$sor : [];
+}
+function callKeysToCalls(callKeys) {
+ if (!(callKeys != null && callKeys.length)) return null;
+ return callKeys.map(function (key) {
+ return parseCallKey(key);
+ });
+}
+
+// Converts CallResult[] to CallState[], only updating if call states have changed.
+// Ensures that CallState results remain referentially stable when unchanged, preventing
+// spurious re-renders which would otherwise occur because mapping always creates a new object.
+function useCallStates(results, contractInterface, fragment, latestBlockNumber) {
+ // Avoid refreshing the results with every changing block number (eg latestBlockNumber).
+ // Instead, only refresh the results if they need to be synced - if there is a result which is stale, for which blockNumber < latestBlockNumber.
+ var syncingBlockNumber = React.useMemo(function () {
+ var lowestBlockNumber = results.reduce(function (memo, result) {
+ return result.blockNumber ? Math.min(memo != null ? memo : result.blockNumber, result.blockNumber) : memo;
+ }, undefined);
+ return Math.max(lowestBlockNumber != null ? lowestBlockNumber : 0, latestBlockNumber != null ? latestBlockNumber : 0);
+ }, [results, latestBlockNumber]);
+ return React.useMemo(function () {
+ return results.map(function (result, i) {
+ var resultFragment = typeof fragment === 'function' ? fragment(i) : fragment;
+ return toCallState(result, contractInterface, resultFragment, syncingBlockNumber);
+ });
+ }, [contractInterface, fragment, results, syncingBlockNumber]);
+}
+function toCallState(callResult, contractInterface, fragment, syncingBlockNumber) {
+ if (!callResult || !callResult.valid) {
+ return INVALID_CALL_STATE;
+ }
+ var data = callResult.data,
+ blockNumber = callResult.blockNumber;
+ if (!blockNumber || !contractInterface || !fragment || !syncingBlockNumber) {
+ return LOADING_CALL_STATE;
+ }
+ var success = data && data.length > 2;
+ var syncing = blockNumber < syncingBlockNumber;
+ var result = undefined;
+ if (success && data) {
+ try {
+ result = viem.decodeFunctionResult({
+ abi: contractInterface,
+ functionName: fragment,
+ data: data
+ });
+ } catch (error) {
+ console.debug('Result data parsing failed', fragment, data);
+ return {
+ valid: true,
+ loading: false,
+ error: true,
+ syncing: syncing,
+ result: result
+ };
+ }
+ }
+ return {
+ valid: true,
+ loading: false,
+ syncing: syncing,
+ result: result,
+ error: !success
+ };
+}
+
+function isMethodArg(x) {
+ return x === null || x === undefined ? false : typeof BigInt(x) === 'bigint' || ['string', 'number'].indexOf(typeof x) !== -1;
+}
+function isValidMethodArgs(x) {
+ return x === undefined || Array.isArray(x) && x.every(function (xi) {
+ return isMethodArg(xi) || Array.isArray(xi) && xi.every(isMethodArg);
+ });
+}
+
+// the lowest level call for subscribing to contract data
+function useCallsDataSubscription(context, chainId, calls, listenerOptions) {
+ var reducerPath = context.reducerPath,
+ actions = context.actions;
+ var callResults = reactRedux.useSelector(function (state) {
+ return state[reducerPath].callResults;
+ });
+ var defaultListenerOptions = reactRedux.useSelector(function (state) {
+ return state[reducerPath].listenerOptions;
+ });
+ var dispatch = reactRedux.useDispatch();
+ var serializedCallKeys = React.useMemo(function () {
+ return JSON.stringify(callsToCallKeys(calls));
+ }, [calls]);
+ // update listeners when there is an actual change that persists for at least 100ms
+ React.useEffect(function () {
+ var _chainId, _ref, _listenerOptions$bloc;
+ var callKeys = JSON.parse(serializedCallKeys);
+ var calls = callKeysToCalls(callKeys);
+ if (!chainId || !calls) return;
+ var blocksPerFetchFromState = (_chainId = (defaultListenerOptions != null ? defaultListenerOptions : {})[chainId]) == null ? void 0 : _chainId.blocksPerFetch;
+ var blocksPerFetchForChain = (_ref = (_listenerOptions$bloc = listenerOptions == null ? void 0 : listenerOptions.blocksPerFetch) != null ? _listenerOptions$bloc : blocksPerFetchFromState) != null ? _ref : DEFAULT_BLOCKS_PER_FETCH;
+ dispatch(actions.addMulticallListeners({
+ chainId: chainId,
+ calls: calls,
+ options: {
+ blocksPerFetch: blocksPerFetchForChain
+ }
+ }));
+ return function () {
+ dispatch(actions.removeMulticallListeners({
+ chainId: chainId,
+ calls: calls,
+ options: {
+ blocksPerFetch: blocksPerFetchForChain
+ }
+ }));
+ };
+ }, [actions, chainId, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions]);
+ var lastResults = React.useRef([]);
+ return React.useMemo(function () {
+ var isChanged = lastResults.current.length !== calls.length;
+ // Construct results using a for-loop to handle sparse arrays.
+ // Array.prototype.map would skip empty entries.
+ var results = [];
+ for (var i = 0; i < calls.length; ++i) {
+ var call = calls[i];
+ var result = INVALID_RESULT;
+ if (chainId && call) {
+ var _callResults$chainId;
+ var callResult = (_callResults$chainId = callResults[chainId]) == null ? void 0 : _callResults$chainId[toCallKey(call)];
+ result = {
+ valid: true,
+ data: callResult != null && callResult.data && callResult.data !== '0x' ? callResult.data : undefined,
+ blockNumber: callResult == null ? void 0 : callResult.blockNumber
+ };
+ }
+ isChanged = isChanged || !areCallResultsEqual(result, lastResults.current[i]);
+ results.push(result);
+ }
+ // Force the results to be referentially stable if they have not changed.
+ // This is necessary because *all* callResults are passed as deps when initially memoizing the results.
+ if (isChanged) {
+ lastResults.current = results;
+ }
+ return lastResults.current;
+ }, [callResults, calls, chainId]);
+}
+function areCallResultsEqual(a, b) {
+ return a.valid === b.valid && a.data === b.data && a.blockNumber === b.blockNumber;
+}
+// Similar to useCallsDataSubscription above but for subscribing to
+// calls to multiple chains at once
+function useMultichainCallsDataSubscription(context, chainToCalls, listenerOptions) {
+ var reducerPath = context.reducerPath,
+ actions = context.actions;
+ var callResults = reactRedux.useSelector(function (state) {
+ return state[reducerPath].callResults;
+ });
+ var defaultListenerOptions = reactRedux.useSelector(function (state) {
+ return state[reducerPath].listenerOptions;
+ });
+ var dispatch = reactRedux.useDispatch();
+ var serializedCallKeys = React.useMemo(function () {
+ var sortedChainIds = getChainIds(chainToCalls).sort();
+ var chainCallKeysTuple = sortedChainIds.map(function (chainId) {
+ var calls = chainToCalls[chainId];
+ var callKeys = callsToCallKeys(calls);
+ // Note, using a tuple to ensure consistent order when serialized
+ return [chainId, callKeys];
+ });
+ return JSON.stringify(chainCallKeysTuple);
+ }, [chainToCalls]);
+ React.useEffect(function () {
+ var chainCallKeysTuples = JSON.parse(serializedCallKeys);
+ if (!(chainCallKeysTuples != null && chainCallKeysTuples.length)) return;
+ reactRedux.batch(function () {
+ for (var _iterator = _createForOfIteratorHelperLoose(chainCallKeysTuples), _step; !(_step = _iterator()).done;) {
+ var _chainId2, _ref2, _listenerOptions$bloc2;
+ var _step$value = _step.value,
+ chainId = _step$value[0],
+ callKeys = _step$value[1];
+ var calls = callKeysToCalls(callKeys);
+ if (!(calls != null && calls.length)) continue;
+ var blocksPerFetchFromState = (_chainId2 = (defaultListenerOptions != null ? defaultListenerOptions : {})[chainId]) == null ? void 0 : _chainId2.blocksPerFetch;
+ var blocksPerFetchForChain = (_ref2 = (_listenerOptions$bloc2 = listenerOptions == null ? void 0 : listenerOptions.blocksPerFetch) != null ? _listenerOptions$bloc2 : blocksPerFetchFromState) != null ? _ref2 : DEFAULT_BLOCKS_PER_FETCH;
+ dispatch(actions.addMulticallListeners({
+ chainId: chainId,
+ calls: calls,
+ options: {
+ blocksPerFetch: blocksPerFetchForChain
+ }
+ }));
+ }
+ });
+ return function () {
+ reactRedux.batch(function () {
+ for (var _iterator2 = _createForOfIteratorHelperLoose(chainCallKeysTuples), _step2; !(_step2 = _iterator2()).done;) {
+ var _chainId3, _ref3, _listenerOptions$bloc3;
+ var _step2$value = _step2.value,
+ chainId = _step2$value[0],
+ callKeys = _step2$value[1];
+ var calls = callKeysToCalls(callKeys);
+ if (!(calls != null && calls.length)) continue;
+ var blocksPerFetchFromState = (_chainId3 = (defaultListenerOptions != null ? defaultListenerOptions : {})[chainId]) == null ? void 0 : _chainId3.blocksPerFetch;
+ var blocksPerFetchForChain = (_ref3 = (_listenerOptions$bloc3 = listenerOptions == null ? void 0 : listenerOptions.blocksPerFetch) != null ? _listenerOptions$bloc3 : blocksPerFetchFromState) != null ? _ref3 : DEFAULT_BLOCKS_PER_FETCH;
+ dispatch(actions.removeMulticallListeners({
+ chainId: chainId,
+ calls: calls,
+ options: {
+ blocksPerFetch: blocksPerFetchForChain
+ }
+ }));
+ }
+ });
+ };
+ }, [actions, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions]);
+ return React.useMemo(function () {
+ return getChainIds(chainToCalls).reduce(function (result, chainId) {
+ var calls = chainToCalls[chainId];
+ result[chainId] = calls.map(function (call) {
+ var _callResults$chainId2;
+ if (!chainId || !call) return INVALID_RESULT;
+ var result = (_callResults$chainId2 = callResults[chainId]) == null ? void 0 : _callResults$chainId2[toCallKey(call)];
+ var data = result != null && result.data && result.data !== '0x' ? result.data : undefined;
+ return {
+ valid: true,
+ data: data,
+ blockNumber: result == null ? void 0 : result.blockNumber
+ };
+ });
+ return result;
+ }, {});
+ }, [callResults, chainToCalls]);
+}
+// formats many calls to a single function on a single contract, with the function name and inputs specified
+function useSingleContractMultipleData(context, chainId, latestBlockNumber, contract, methodName, callInputs, options) {
+ var _ref4 = options != null ? options : {},
+ gasRequired = _ref4.gasRequired;
+ // Create ethers function fragment
+ var fragment = React.useMemo(function () {
+ var _getAbiItem;
+ return contract && ((_getAbiItem = viem.getAbiItem({
+ abi: contract.abi,
+ name: methodName
+ })) == null ? void 0 : _getAbiItem.name);
+ }, [contract, methodName]);
+ // Get encoded call data. Note can't use useCallData below b.c. this is for a list of CallInputs
+ var callDatas = React.useMemo(function () {
+ if (!contract || !fragment) return [];
+ return callInputs.map(function (callInput) {
+ return isValidMethodArgs(callInput) ? viem.encodeFunctionData({
+ abi: contract.abi,
+ functionName: fragment,
+ args: callInput
+ }) : undefined;
+ });
+ }, [callInputs, contract, fragment]);
+ // Create call objects
+ var calls = React.useMemo(function () {
+ if (!contract) return [];
+ return callDatas.map(function (callData) {
+ if (!callData) return undefined;
+ return {
+ address: contract.address,
+ callData: callData,
+ gasRequired: gasRequired
+ };
+ });
+ }, [contract, callDatas, gasRequired]);
+ // Subscribe to call data
+ var results = useCallsDataSubscription(context, chainId, calls, options);
+ return useCallStates(results, contract == null ? void 0 : contract.abi, fragment, latestBlockNumber);
+}
+function useMultipleContractSingleData(context, chainId, latestBlockNumber, addresses, contractInterface, methodName, callInputs, options) {
+ var _ref5 = options != null ? options : {},
+ gasRequired = _ref5.gasRequired;
+ var _useCallData = useCallData(methodName, contractInterface, callInputs),
+ fragment = _useCallData.fragment,
+ callData = _useCallData.callData;
+ // Create call objects
+ var calls = React.useMemo(function () {
+ if (!callData) return [];
+ return addresses.map(function (address) {
+ if (!address) return undefined;
+ return {
+ address: address,
+ callData: callData,
+ gasRequired: gasRequired
+ };
+ });
+ }, [addresses, callData, gasRequired]);
+ // Subscribe to call data
+ var results = useCallsDataSubscription(context, chainId, calls, options);
+ return useCallStates(results, contractInterface, fragment, latestBlockNumber);
+}
+function useSingleCallResult(context, chainId, latestBlockNumber, contract, methodName, inputs, options) {
+ var _useSingleContractMul;
+ var callInputs = React.useMemo(function () {
+ return [inputs];
+ }, [inputs]);
+ return (_useSingleContractMul = useSingleContractMultipleData(context, chainId, latestBlockNumber, contract, methodName, callInputs, options)[0]) != null ? _useSingleContractMul : INVALID_CALL_STATE;
+}
+// formats many calls to any number of functions on a single contract, with only the calldata specified
+function useSingleContractWithCallData(context, chainId, latestBlockNumber, contract, callDatas, options) {
+ var _ref6 = options != null ? options : {},
+ gasRequired = _ref6.gasRequired;
+ // Create call objects
+ var calls = React.useMemo(function () {
+ if (!contract) return [];
+ return callDatas.map(function (callData) {
+ return {
+ address: contract.address,
+ callData: callData,
+ gasRequired: gasRequired
+ };
+ });
+ }, [callDatas, contract, gasRequired]);
+ // Subscribe to call data
+ var results = useCallsDataSubscription(context, chainId, calls, options);
+ var fragment = React.useCallback(function (i) {
+ var _getAbiItem2;
+ return (_getAbiItem2 = viem.getAbiItem({
+ abi: contract == null ? void 0 : contract.abi,
+ name: callDatas[i].substring(0, 10)
+ })) == null ? void 0 : _getAbiItem2.name;
+ }, [callDatas, contract]);
+ return useCallStates(results, contract == null ? void 0 : contract.abi, fragment, latestBlockNumber);
+}
+// Similar to useMultipleContractSingleData but instead of multiple contracts on one chain,
+// this is for querying compatible contracts on multiple chains
+function useMultiChainMultiContractSingleData(context, chainToBlockNumber, chainToAddresses, contractInterface, methodName, callInputs, options) {
+ var _ref7 = options != null ? options : {},
+ gasRequired = _ref7.gasRequired;
+ var _useCallData2 = useCallData(methodName, contractInterface, callInputs),
+ fragment = _useCallData2.fragment,
+ callData = _useCallData2.callData;
+ // Create call objects
+ var chainToCalls = React.useMemo(function () {
+ if (!callData || !chainToAddresses) return {};
+ return getChainIds(chainToAddresses).reduce(function (result, chainId) {
+ var addresses = chainToAddresses[chainId];
+ var calls = addresses.map(function (address) {
+ if (!address) return undefined;
+ return {
+ address: address,
+ callData: callData,
+ gasRequired: gasRequired
+ };
+ });
+ result[chainId] = calls;
+ return result;
+ }, {});
+ }, [chainToAddresses, callData, gasRequired]);
+ // Subscribe to call data
+ var chainIdToResults = useMultichainCallsDataSubscription(context, chainToCalls, options);
+ // TODO(WEB-2097): Multichain states are not referentially stable, because they cannot use the
+ // same codepath (eg useCallStates).
+ return React.useMemo(function () {
+ return getChainIds(chainIdToResults).reduce(function (combinedResults, chainId) {
+ var latestBlockNumber = chainToBlockNumber == null ? void 0 : chainToBlockNumber[chainId];
+ var results = chainIdToResults[chainId];
+ combinedResults[chainId] = results.map(function (result) {
+ return toCallState(result, contractInterface, fragment, latestBlockNumber);
+ });
+ return combinedResults;
+ }, {});
+ }, [fragment, contractInterface, chainIdToResults, chainToBlockNumber]);
+}
+// Similar to useSingleCallResult but instead of one contract on one chain,
+// this is for querying a contract on multiple chains
+function useMultiChainSingleContractSingleData(context, chainToBlockNumber, chainToAddress, contractInterface, methodName, callInputs, options) {
+ // This hook uses the more flexible useMultiChainMultiContractSingleData internally,
+ // but transforms the inputs and outputs for convenience
+ var chainIdToAddresses = React.useMemo(function () {
+ return getChainIds(chainToAddress).reduce(function (result, chainId) {
+ result[chainId] = [chainToAddress[chainId]];
+ return result;
+ }, {});
+ }, [chainToAddress]);
+ var multiContractResults = useMultiChainMultiContractSingleData(context, chainToBlockNumber, chainIdToAddresses, contractInterface, methodName, callInputs, options);
+ return React.useMemo(function () {
+ return getChainIds(chainToAddress).reduce(function (result, chainId) {
+ var _multiContractResults, _multiContractResults2;
+ result[chainId] = (_multiContractResults = (_multiContractResults2 = multiContractResults[chainId]) == null ? void 0 : _multiContractResults2[0]) != null ? _multiContractResults : INVALID_CALL_STATE;
+ return result;
+ }, {});
+ }, [chainToAddress, multiContractResults]);
+}
+function useCallData(methodName, contractInterface, callInputs) {
+ // Create ethers function fragment
+ var fragment = React.useMemo(function () {
+ var _getAbiItem3;
+ return contractInterface && ((_getAbiItem3 = viem.getAbiItem({
+ abi: contractInterface,
+ name: methodName
+ })) == null ? void 0 : _getAbiItem3.name);
+ }, [contractInterface, methodName]);
+ // Get encoded call data
+ var callData = React.useMemo(function () {
+ return fragment && isValidMethodArgs(callInputs) ? viem.encodeFunctionData({
+ abi: contractInterface,
+ functionName: fragment,
+ args: callInputs
+ }) : undefined;
+ }, [callInputs, contractInterface, fragment]);
+ return {
+ fragment: fragment,
+ callData: callData
+ };
+}
+function getChainIds(chainIdMap) {
+ return Object.keys(chainIdMap).map(function (c) {
+ return parseInt(c, 10);
+ });
+}
+
+var initialState = {
+ callResults: {}
+};
+function createMulticallSlice(reducerPath) {
+ return toolkit.createSlice({
+ name: reducerPath,
+ initialState: initialState,
+ reducers: {
+ addMulticallListeners: function addMulticallListeners(state, action) {
+ var _listeners$chainId;
+ var _action$payload = action.payload,
+ calls = _action$payload.calls,
+ chainId = _action$payload.chainId,
+ blocksPerFetch = _action$payload.options.blocksPerFetch;
+ var listeners = state.callListeners ? state.callListeners : state.callListeners = {};
+ listeners[chainId] = (_listeners$chainId = listeners[chainId]) != null ? _listeners$chainId : {};
+ calls.forEach(function (call) {
+ var _listeners$chainId$ca, _listeners$chainId$ca2;
+ var callKey = toCallKey(call);
+ listeners[chainId][callKey] = (_listeners$chainId$ca = listeners[chainId][callKey]) != null ? _listeners$chainId$ca : {};
+ listeners[chainId][callKey][blocksPerFetch] = ((_listeners$chainId$ca2 = listeners[chainId][callKey][blocksPerFetch]) != null ? _listeners$chainId$ca2 : 0) + 1;
+ });
+ },
+ removeMulticallListeners: function removeMulticallListeners(state, action) {
+ var _action$payload2 = action.payload,
+ calls = _action$payload2.calls,
+ chainId = _action$payload2.chainId,
+ blocksPerFetch = _action$payload2.options.blocksPerFetch;
+ var listeners = state.callListeners ? state.callListeners : state.callListeners = {};
+ if (!listeners[chainId]) return;
+ calls.forEach(function (call) {
+ var callKey = toCallKey(call);
+ if (!listeners[chainId][callKey]) return;
+ if (!listeners[chainId][callKey][blocksPerFetch]) return;
+ if (listeners[chainId][callKey][blocksPerFetch] === 1) {
+ delete listeners[chainId][callKey][blocksPerFetch];
+ } else {
+ listeners[chainId][callKey][blocksPerFetch]--;
+ }
+ });
+ },
+ fetchingMulticallResults: function fetchingMulticallResults(state, action) {
+ var _state$callResults$ch;
+ var _action$payload3 = action.payload,
+ chainId = _action$payload3.chainId,
+ fetchingBlockNumber = _action$payload3.fetchingBlockNumber,
+ calls = _action$payload3.calls;
+ state.callResults[chainId] = (_state$callResults$ch = state.callResults[chainId]) != null ? _state$callResults$ch : {};
+ calls.forEach(function (call) {
+ var callKey = toCallKey(call);
+ var current = state.callResults[chainId][callKey];
+ if (!current) {
+ state.callResults[chainId][callKey] = {
+ fetchingBlockNumber: fetchingBlockNumber
+ };
+ } else {
+ var _current$fetchingBloc;
+ if (((_current$fetchingBloc = current.fetchingBlockNumber) != null ? _current$fetchingBloc : 0) >= fetchingBlockNumber) return;
+ state.callResults[chainId][callKey].fetchingBlockNumber = fetchingBlockNumber;
+ }
+ });
+ },
+ errorFetchingMulticallResults: function errorFetchingMulticallResults(state, action) {
+ var _state$callResults$ch2;
+ var _action$payload4 = action.payload,
+ chainId = _action$payload4.chainId,
+ fetchingBlockNumber = _action$payload4.fetchingBlockNumber,
+ calls = _action$payload4.calls;
+ state.callResults[chainId] = (_state$callResults$ch2 = state.callResults[chainId]) != null ? _state$callResults$ch2 : {};
+ calls.forEach(function (call) {
+ var callKey = toCallKey(call);
+ var current = state.callResults[chainId][callKey];
+ if (!current || typeof current.fetchingBlockNumber !== 'number') return; // only should be dispatched if we are already fetching
+ if (current.fetchingBlockNumber <= fetchingBlockNumber) {
+ delete current.fetchingBlockNumber;
+ current.data = null;
+ current.blockNumber = fetchingBlockNumber;
+ }
+ });
+ },
+ updateMulticallResults: function updateMulticallResults(state, action) {
+ var _state$callResults$ch3;
+ var _action$payload5 = action.payload,
+ chainId = _action$payload5.chainId,
+ results = _action$payload5.results,
+ blockNumber = _action$payload5.blockNumber;
+ state.callResults[chainId] = (_state$callResults$ch3 = state.callResults[chainId]) != null ? _state$callResults$ch3 : {};
+ Object.keys(results).forEach(function (callKey) {
+ var _current$blockNumber;
+ var current = state.callResults[chainId][callKey];
+ if (((_current$blockNumber = current == null ? void 0 : current.blockNumber) != null ? _current$blockNumber : 0) > blockNumber) return;
+ if ((current == null ? void 0 : current.data) === results[callKey] && (current == null ? void 0 : current.blockNumber) === blockNumber) return;
+ state.callResults[chainId][callKey] = {
+ data: results[callKey],
+ blockNumber: blockNumber
+ };
+ });
+ },
+ updateListenerOptions: function updateListenerOptions(state, action) {
+ var _state$listenerOption;
+ var _action$payload6 = action.payload,
+ chainId = _action$payload6.chainId,
+ listenerOptions = _action$payload6.listenerOptions;
+ state.listenerOptions = (_state$listenerOption = state.listenerOptions) != null ? _state$listenerOption : {};
+ state.listenerOptions[chainId] = listenerOptions;
+ }
+ }
+ });
+}
+
+/**
+ * Tries to pack a list of items into as few bins as possible using the first-fit bin packing algorithm
+ * @param calls the calls to chunk
+ * @param chunkGasLimit the gas limit of any one chunk of calls, i.e. bin capacity
+ * @param defaultGasRequired the default amount of gas an individual call should cost if not specified
+ */
+function chunkCalls(calls, chunkGasLimit, defaultGasRequired) {
+ if (defaultGasRequired === void 0) {
+ defaultGasRequired = DEFAULT_CHUNK_GAS_REQUIRED;
+ }
+ return calls
+ // first sort by gas required
+ .sort(function (c1, c2) {
+ var _c2$gasRequired, _c1$gasRequired;
+ return ((_c2$gasRequired = c2.gasRequired) != null ? _c2$gasRequired : defaultGasRequired) - ((_c1$gasRequired = c1.gasRequired) != null ? _c1$gasRequired : defaultGasRequired);
+ })
+ // then bin the calls according to the first fit algorithm
+ .reduce(function (bins, call) {
+ var _call$gasRequired;
+ var gas = (_call$gasRequired = call.gasRequired) != null ? _call$gasRequired : defaultGasRequired;
+ for (var _iterator = _createForOfIteratorHelperLoose(bins), _step; !(_step = _iterator()).done;) {
+ var bin = _step.value;
+ if (bin.cumulativeGasLimit + gas <= chunkGasLimit) {
+ bin.calls.push(call);
+ bin.cumulativeGasLimit += gas;
+ return bins;
+ }
+ }
+ // didn't find a bin for the call, make a new bin
+ bins.push({
+ calls: [call],
+ cumulativeGasLimit: gas
+ });
+ return bins;
+ }, [])
+ // pull out just the calls from each bin
+ .map(function (b) {
+ return b.calls;
+ });
+}
+
+// TODO de-duplicate this file with web interface
+// https://github.com/Uniswap/interface/blob/main/src/utils/retry.ts
+function wait(ms) {
+ return new Promise(function (resolve) {
+ return setTimeout(resolve, ms);
+ });
+}
+function waitRandom(min, max) {
+ return wait(min + Math.round(Math.random() * Math.max(0, max - min)));
+}
+/**
+ * This error is thrown if the function is cancelled before completing
+ */
+var CancelledError = /*#__PURE__*/function (_Error) {
+ function CancelledError() {
+ var _this;
+ _this = _Error.call(this, 'Cancelled') || this;
+ _this.isCancelledError = true;
+ return _this;
+ }
+ _inheritsLoose(CancelledError, _Error);
+ return CancelledError;
+}( /*#__PURE__*/_wrapNativeSuper(Error));
+/**
+ * Throw this error if the function should retry
+ */
+var RetryableError = /*#__PURE__*/function (_Error2) {
+ function RetryableError() {
+ var _this2;
+ _this2 = _Error2.apply(this, arguments) || this;
+ _this2.isRetryableError = true;
+ return _this2;
+ }
+ _inheritsLoose(RetryableError, _Error2);
+ return RetryableError;
+}( /*#__PURE__*/_wrapNativeSuper(Error));
+/**
+ * Retries the function that returns the promise until the promise successfully resolves up to n retries
+ * @param fn function to retry
+ * @param n how many times to retry
+ * @param minWait min wait between retries in ms
+ * @param maxWait max wait between retries in ms
+ */
+function retry(fn, _ref) {
+ var n = _ref.n,
+ minWait = _ref.minWait,
+ maxWait = _ref.maxWait;
+ var completed = false;
+ var rejectCancelled;
+ var promise = new Promise( /*#__PURE__*/function () {
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(resolve, reject) {
+ var result;
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
+ while (1) switch (_context.prev = _context.next) {
+ case 0:
+ rejectCancelled = reject;
+ case 1:
+ result = void 0;
+ _context.prev = 3;
+ _context.next = 6;
+ return fn();
+ case 6:
+ result = _context.sent;
+ if (!completed) {
+ resolve(result);
+ completed = true;
+ }
+ return _context.abrupt("break", 24);
+ case 11:
+ _context.prev = 11;
+ _context.t0 = _context["catch"](3);
+ if (!completed) {
+ _context.next = 15;
+ break;
+ }
+ return _context.abrupt("break", 24);
+ case 15:
+ if (!(n <= 0 || !_context.t0.isRetryableError)) {
+ _context.next = 19;
+ break;
+ }
+ reject(_context.t0);
+ completed = true;
+ return _context.abrupt("break", 24);
+ case 19:
+ n--;
+ case 20:
+ _context.next = 22;
+ return waitRandom(minWait, maxWait);
+ case 22:
+ _context.next = 1;
+ break;
+ case 24:
+ case "end":
+ return _context.stop();
+ }
+ }, _callee, null, [[3, 11]]);
+ }));
+ return function (_x, _x2) {
+ return _ref2.apply(this, arguments);
+ };
+ }());
+ return {
+ promise: promise,
+ cancel: function cancel() {
+ if (completed) return;
+ completed = true;
+ rejectCancelled(new CancelledError());
+ }
+ };
+}
+
+// TODO de-duplicate this file with web interface
+// modified from https://usehooks.com/useDebounce/
+function useDebounce(value, delay) {
+ var _useState = React.useState(value),
+ debouncedValue = _useState[0],
+ setDebouncedValue = _useState[1];
+ React.useEffect(function () {
+ // Update debounced value after delay
+ var handler = setTimeout(function () {
+ setDebouncedValue(value);
+ }, delay);
+ // Cancel the timeout if value changes (also on delay change or unmount)
+ // This is how we prevent debounced value from updating if value is changed ...
+ // .. within the delay period. Timeout gets cleared and restarted.
+ return function () {
+ clearTimeout(handler);
+ };
+ }, [value, delay]);
+ return debouncedValue;
+}
+
+var IMulticallABI = [{
+ inputs: [],
+ name: 'getCurrentBlockTimestamp',
+ outputs: [{
+ internalType: 'uint256',
+ name: 'timestamp',
+ type: 'uint256'
+ }],
+ stateMutability: 'view',
+ type: 'function'
+}, {
+ inputs: [{
+ internalType: 'address',
+ name: 'addr',
+ type: 'address'
+ }],
+ name: 'getEthBalance',
+ outputs: [{
+ internalType: 'uint256',
+ name: 'balance',
+ type: 'uint256'
+ }],
+ stateMutability: 'view',
+ type: 'function'
+}, {
+ inputs: [{
+ components: [{
+ internalType: 'address',
+ name: 'target',
+ type: 'address'
+ }, {
+ internalType: 'uint256',
+ name: 'gasLimit',
+ type: 'uint256'
+ }, {
+ internalType: 'bytes',
+ name: 'callData',
+ type: 'bytes'
+ }],
+ internalType: 'struct PancakeInterfaceMulticall.Call[]',
+ name: 'calls',
+ type: 'tuple[]'
+ }],
+ name: 'multicall',
+ outputs: [{
+ internalType: 'uint256',
+ name: 'blockNumber',
+ type: 'uint256'
+ }, {
+ components: [{
+ internalType: 'bool',
+ name: 'success',
+ type: 'bool'
+ }, {
+ internalType: 'uint256',
+ name: 'gasUsed',
+ type: 'uint256'
+ }, {
+ internalType: 'bytes',
+ name: 'returnData',
+ type: 'bytes'
+ }],
+ internalType: 'struct PancakeInterfaceMulticall.Result[]',
+ name: 'returnData',
+ type: 'tuple[]'
+ }],
+ stateMutability: 'nonpayable',
+ type: 'function'
+}];
+
+var FETCH_RETRY_CONFIG = {
+ n: Infinity,
+ minWait: 1000,
+ maxWait: 2500
+};
+/**
+ * Fetches a chunk of calls, enforcing a minimum block number constraint
+ * @param multicall multicall contract to fetch against
+ * @param chunk chunk of calls to make
+ * @param blockNumber block number passed as the block tag in the eth_call
+ */
+function fetchChunk(_x, _x2, _x3, _x4) {
+ return _fetchChunk.apply(this, arguments);
+}
+/**
+ * From the current all listeners state, return each call key mapped to the
+ * minimum number of blocks per fetch. This is how often each key must be fetched.
+ * @param allListeners the all listeners state
+ * @param chainId the current chain id
+ */
+function _fetchChunk() {
+ _fetchChunk = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(multicallInfo, chunk, blockNumber, isDebug) {
+ var _yield$multicallInfo$, _yield$multicallInfo$2, returnData, _error$message, _error$message2, error, half, _yield$Promise$all, c0, c1;
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
+ while (1) switch (_context.prev = _context.next) {
+ case 0:
+ console.debug('Fetching chunk', chunk, blockNumber, chunk.map(function (obj) {
+ var _obj$gasRequired;
+ return {
+ target: obj.address,
+ callData: obj.callData,
+ gasLimit: (_obj$gasRequired = obj.gasRequired) != null ? _obj$gasRequired : DEFAULT_CALL_GAS_REQUIRED
+ };
+ }));
+ _context.prev = 1;
+ _context.next = 4;
+ return multicallInfo.provider.simulateContract({
+ abi: IMulticallABI,
+ address: multicallInfo.address,
+ functionName: 'multicall',
+ args: [chunk.map(function (obj) {
+ var _obj$gasRequired2;
+ return {
+ target: obj.address,
+ callData: obj.callData,
+ gasLimit: (_obj$gasRequired2 = obj.gasRequired) != null ? _obj$gasRequired2 : DEFAULT_CALL_GAS_REQUIRED
+ };
+ })],
+ // we aren't passing through the block gas limit we used to create the chunk, because it causes a problem with the integ tests
+ blockNumber: BigInt(blockNumber)
+ });
+ case 4:
+ _yield$multicallInfo$ = _context.sent;
+ _yield$multicallInfo$2 = _yield$multicallInfo$.result;
+ returnData = _yield$multicallInfo$2[1];
+ if (isDebug) {
+ returnData.forEach(function (_ref, i) {
+ var _chunk$i$gasRequired;
+ var gasUsed = _ref.gasUsed,
+ returnData = _ref.returnData,
+ success = _ref.success;
+ if (!success && returnData.length === 2 && gasUsed >= Math.floor(((_chunk$i$gasRequired = chunk[i].gasRequired) != null ? _chunk$i$gasRequired : DEFAULT_CALL_GAS_REQUIRED) * 0.95)) {
+ var _chunk$i$gasRequired2;
+ console.warn("A call failed due to requiring " + gasUsed.toString() + " vs. allowed " + ((_chunk$i$gasRequired2 = chunk[i].gasRequired) != null ? _chunk$i$gasRequired2 : DEFAULT_CALL_GAS_REQUIRED), chunk[i]);
+ }
+ });
+ }
+ return _context.abrupt("return", returnData);
+ case 11:
+ _context.prev = 11;
+ _context.t0 = _context["catch"](1);
+ error = _context.t0;
+ if (!(error.code === -32000 || ((_error$message = error.message) == null ? void 0 : _error$message.indexOf('header not found')) !== -1)) {
+ _context.next = 18;
+ break;
+ }
+ throw new RetryableError("header not found for block number " + blockNumber);
+ case 18:
+ if (!(error.code === -32603 || ((_error$message2 = error.message) == null ? void 0 : _error$message2.indexOf('execution ran out of gas')) !== -1)) {
+ _context.next = 28;
+ break;
+ }
+ if (!(chunk.length > 1)) {
+ _context.next = 28;
+ break;
+ }
+ {
+ console.debug('Splitting a chunk in 2', chunk);
+ }
+ half = Math.floor(chunk.length / 2);
+ _context.next = 24;
+ return Promise.all([fetchChunk(multicallInfo, chunk.slice(0, half), blockNumber), fetchChunk(multicallInfo, chunk.slice(half, chunk.length), blockNumber)]);
+ case 24:
+ _yield$Promise$all = _context.sent;
+ c0 = _yield$Promise$all[0];
+ c1 = _yield$Promise$all[1];
+ return _context.abrupt("return", c0.concat(c1));
+ case 28:
+ console.error('Failed to fetch chunk', error);
+ throw error;
+ case 30:
+ case "end":
+ return _context.stop();
+ }
+ }, _callee, null, [[1, 11]]);
+ }));
+ return _fetchChunk.apply(this, arguments);
+}
+function activeListeningKeys(allListeners, chainId) {
+ if (!allListeners || !chainId) return {};
+ var listeners = allListeners[chainId];
+ if (!listeners) return {};
+ return Object.keys(listeners).reduce(function (memo, callKey) {
+ var keyListeners = listeners[callKey];
+ memo[callKey] = Object.keys(keyListeners).filter(function (key) {
+ var blocksPerFetch = parseInt(key);
+ if (blocksPerFetch <= 0) return false;
+ return keyListeners[blocksPerFetch] > 0;
+ }).reduce(function (previousMin, current) {
+ return Math.min(previousMin, parseInt(current));
+ }, Infinity);
+ return memo;
+ }, {});
+}
+/**
+ * Return the keys that need to be refetched
+ * @param callResults current call result state
+ * @param listeningKeys each call key mapped to how old the data can be in blocks
+ * @param chainId the current chain id
+ * @param latestBlockNumber the latest block number
+ */
+function outdatedListeningKeys(callResults, listeningKeys, chainId, latestBlockNumber) {
+ if (!chainId || !latestBlockNumber) return [];
+ var results = callResults[chainId];
+ // no results at all, load everything
+ if (!results) return Object.keys(listeningKeys);
+ return Object.keys(listeningKeys).filter(function (callKey) {
+ var blocksPerFetch = listeningKeys[callKey];
+ var data = callResults[chainId][callKey];
+ // no data, must fetch
+ if (!data) return true;
+ var minDataBlockNumber = latestBlockNumber - (blocksPerFetch - 1);
+ // already fetching it for a recent enough block, don't refetch it
+ if (data.fetchingBlockNumber && data.fetchingBlockNumber >= minDataBlockNumber) return false;
+ // if data is older than minDataBlockNumber, fetch it
+ return !data.blockNumber || data.blockNumber < minDataBlockNumber;
+ });
+}
+function onFetchChunkSuccess(context, chunk, result) {
+ var actions = context.actions,
+ dispatch = context.dispatch,
+ chainId = context.chainId,
+ latestBlockNumber = context.latestBlockNumber,
+ isDebug = context.isDebug;
+ // split the returned slice into errors and results
+ var _chunk$reduce = chunk.reduce(function (memo, call, i) {
+ if (result[i].success) {
+ var _result$i$returnData;
+ memo.results[toCallKey(call)] = (_result$i$returnData = result[i].returnData) != null ? _result$i$returnData : null;
+ } else {
+ memo.erroredCalls.push(call);
+ }
+ return memo;
+ }, {
+ erroredCalls: [],
+ results: {}
+ }),
+ erroredCalls = _chunk$reduce.erroredCalls,
+ results = _chunk$reduce.results;
+ // dispatch any new results
+ if (Object.keys(results).length > 0) dispatch(actions.updateMulticallResults({
+ chainId: chainId,
+ results: results,
+ blockNumber: latestBlockNumber
+ }));
+ // dispatch any errored calls
+ if (erroredCalls.length > 0) {
+ if (isDebug) {
+ result.forEach(function (returnData, ix) {
+ if (!returnData.success) {
+ console.debug('Call failed', chunk[ix], returnData);
+ }
+ });
+ } else {
+ console.debug('Calls errored in fetch', erroredCalls);
+ }
+ dispatch(actions.errorFetchingMulticallResults({
+ calls: erroredCalls,
+ chainId: chainId,
+ fetchingBlockNumber: latestBlockNumber
+ }));
+ }
+}
+function onFetchChunkFailure(context, chunk, error) {
+ var actions = context.actions,
+ dispatch = context.dispatch,
+ chainId = context.chainId,
+ latestBlockNumber = context.latestBlockNumber;
+ if (error.isCancelledError) {
+ console.debug('Cancelled fetch for blockNumber', latestBlockNumber, chunk, chainId);
+ return;
+ }
+ console.error('Failed to fetch multicall chunk', chunk, chainId, error);
+ dispatch(actions.errorFetchingMulticallResults({
+ calls: chunk,
+ chainId: chainId,
+ fetchingBlockNumber: latestBlockNumber
+ }));
+}
+function Updater(props) {
+ var context = props.context,
+ chainId = props.chainId,
+ latestBlockNumber = props.latestBlockNumber,
+ multicallInfo = props.multicallInfo,
+ isDebug = props.isDebug,
+ listenerOptions = props.listenerOptions;
+ var actions = context.actions,
+ reducerPath = context.reducerPath;
+ var dispatch = reactRedux.useDispatch();
+ // set user configured listenerOptions in state for given chain ID.
+ React.useEffect(function () {
+ if (chainId && listenerOptions) {
+ dispatch(actions.updateListenerOptions({
+ chainId: chainId,
+ listenerOptions: listenerOptions
+ }));
+ }
+ }, [chainId, listenerOptions, actions, dispatch]);
+ var state = reactRedux.useSelector(function (state) {
+ return state[reducerPath];
+ });
+ // wait for listeners to settle before triggering updates
+ var debouncedListeners = useDebounce(state.callListeners, 100);
+ var cancellations = React.useRef();
+ var listeningKeys = React.useMemo(function () {
+ return activeListeningKeys(debouncedListeners, chainId);
+ }, [debouncedListeners, chainId]);
+ var serializedOutdatedCallKeys = React.useMemo(function () {
+ var outdatedCallKeys = outdatedListeningKeys(state.callResults, listeningKeys, chainId, latestBlockNumber);
+ return JSON.stringify(outdatedCallKeys.sort());
+ }, [chainId, state.callResults, listeningKeys, latestBlockNumber]);
+ React.useEffect(function () {
+ if (!latestBlockNumber || !chainId || !multicallInfo) return;
+ var outdatedCallKeys = JSON.parse(serializedOutdatedCallKeys);
+ if (outdatedCallKeys.length === 0) return;
+ var calls = outdatedCallKeys.map(function (key) {
+ return parseCallKey(key);
+ });
+ var chunkedCalls = chunkCalls(calls, CHUNK_GAS_LIMIT);
+ if (cancellations.current && cancellations.current.blockNumber !== latestBlockNumber) {
+ cancellations.current.cancellations.forEach(function (c) {
+ return c();
+ });
+ }
+ dispatch(actions.fetchingMulticallResults({
+ calls: calls,
+ chainId: chainId,
+ fetchingBlockNumber: latestBlockNumber
+ }));
+ var fetchChunkContext = {
+ actions: actions,
+ dispatch: dispatch,
+ chainId: chainId,
+ latestBlockNumber: latestBlockNumber,
+ isDebug: isDebug
+ };
+ // Execute fetches and gather cancellation callbacks
+ var newCancellations = chunkedCalls.map(function (chunk) {
+ var _retry = retry(function () {
+ return fetchChunk(multicallInfo, chunk, latestBlockNumber, isDebug);
+ }, FETCH_RETRY_CONFIG),
+ cancel = _retry.cancel,
+ promise = _retry.promise;
+ promise.then(function (result) {
+ return onFetchChunkSuccess(fetchChunkContext, chunk, result);
+ })["catch"](function (error) {
+ return onFetchChunkFailure(fetchChunkContext, chunk, error);
+ });
+ return cancel;
+ });
+ cancellations.current = {
+ blockNumber: latestBlockNumber,
+ cancellations: newCancellations
+ };
+ }, [actions, chainId, multicallInfo, dispatch, serializedOutdatedCallKeys, latestBlockNumber, isDebug]);
+ return null;
+}
+function createUpdater(context) {
+ var UpdaterContextBound = function UpdaterContextBound(props) {
+ return React__default.createElement(Updater, Object.assign({
+ context: context
+ }, props));
+ };
+ return UpdaterContextBound;
+}
+
+// Inspired by RTK Query's createApi
+function createMulticall(options) {
+ var _options$reducerPath;
+ var reducerPath = (_options$reducerPath = options == null ? void 0 : options.reducerPath) != null ? _options$reducerPath : 'multicall';
+ var slice = createMulticallSlice(reducerPath);
+ var actions = slice.actions,
+ reducer = slice.reducer;
+ var context = {
+ reducerPath: reducerPath,
+ actions: actions
+ };
+ var useMultipleContractSingleData$1 = function useMultipleContractSingleData$1() {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+ return useMultipleContractSingleData.apply(void 0, [context].concat(args));
+ };
+ var useSingleContractMultipleData$1 = function useSingleContractMultipleData$1() {
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+ return useSingleContractMultipleData.apply(void 0, [context].concat(args));
+ };
+ var useSingleContractWithCallData$1 = function useSingleContractWithCallData$1() {
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
+ args[_key3] = arguments[_key3];
+ }
+ return useSingleContractWithCallData.apply(void 0, [context].concat(args));
+ };
+ var useSingleCallResult$1 = function useSingleCallResult$1() {
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
+ args[_key4] = arguments[_key4];
+ }
+ return useSingleCallResult.apply(void 0, [context].concat(args));
+ };
+ var useMultiChainMultiContractSingleData$1 = function useMultiChainMultiContractSingleData$1() {
+ for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
+ args[_key5] = arguments[_key5];
+ }
+ return useMultiChainMultiContractSingleData.apply(void 0, [context].concat(args));
+ };
+ var useMultiChainSingleContractSingleData$1 = function useMultiChainSingleContractSingleData$1() {
+ for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
+ args[_key6] = arguments[_key6];
+ }
+ return useMultiChainSingleContractSingleData.apply(void 0, [context].concat(args));
+ };
+ var hooks = {
+ useMultipleContractSingleData: useMultipleContractSingleData$1,
+ useSingleContractMultipleData: useSingleContractMultipleData$1,
+ useSingleContractWithCallData: useSingleContractWithCallData$1,
+ useSingleCallResult: useSingleCallResult$1,
+ useMultiChainMultiContractSingleData: useMultiChainMultiContractSingleData$1,
+ useMultiChainSingleContractSingleData: useMultiChainSingleContractSingleData$1
+ };
+ var Updater = createUpdater(context);
+ return {
+ reducerPath: reducerPath,
+ reducer: reducer,
+ actions: actions,
+ hooks: hooks,
+ Updater: Updater
+ };
+}
+
+exports.CHUNK_GAS_LIMIT = CHUNK_GAS_LIMIT;
+exports.CONSERVATIVE_BLOCK_GAS_LIMIT = CONSERVATIVE_BLOCK_GAS_LIMIT;
+exports.DEFAULT_BLOCKS_PER_FETCH = DEFAULT_BLOCKS_PER_FETCH;
+exports.DEFAULT_CALL_GAS_REQUIRED = DEFAULT_CALL_GAS_REQUIRED;
+exports.DEFAULT_CHUNK_GAS_REQUIRED = DEFAULT_CHUNK_GAS_REQUIRED;
+exports.INVALID_CALL_STATE = INVALID_CALL_STATE;
+exports.INVALID_RESULT = INVALID_RESULT;
+exports.LOADING_CALL_STATE = LOADING_CALL_STATE;
+exports.NEVER_RELOAD = NEVER_RELOAD;
+exports.createMulticall = createMulticall;
+//# sourceMappingURL=redux-multicall-viem.cjs.development.js.map
diff --git a/dist/redux-multicall-viem.cjs.development.js.map b/dist/redux-multicall-viem.cjs.development.js.map
new file mode 100644
index 0000000..8f720fc
--- /dev/null
+++ b/dist/redux-multicall-viem.cjs.development.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"redux-multicall-viem.cjs.development.js","sources":["../src/constants.ts","../src/utils/callKeys.ts","../src/utils/callState.ts","../src/validation.ts","../src/hooks.ts","../src/slice.ts","../src/utils/chunkCalls.ts","../src/utils/retry.ts","../src/utils/useDebounce.ts","../src/abi/InterfaceMulticall.ts","../src/updater.tsx","../src/create.ts"],"sourcesContent":["import type { CallResult, CallState, ListenerOptions } from './types'\n\nexport const DEFAULT_BLOCKS_PER_FETCH = 1\nexport const DEFAULT_CALL_GAS_REQUIRED = 1_000_000\nexport const DEFAULT_CHUNK_GAS_REQUIRED = 200_000\nexport const CHUNK_GAS_LIMIT = 100_000_000\nexport const CONSERVATIVE_BLOCK_GAS_LIMIT = 10_000_000 // conservative, hard-coded estimate of the current block gas limit\n\n// Consts for hooks\nexport const INVALID_RESULT: CallResult = { valid: false, blockNumber: undefined, data: undefined }\nexport const NEVER_RELOAD: ListenerOptions = {\n blocksPerFetch: Infinity,\n}\n\nexport const INVALID_CALL_STATE: CallState = {\n valid: false,\n result: undefined,\n loading: false,\n syncing: false,\n error: false,\n}\nexport const LOADING_CALL_STATE: CallState = {\n valid: true,\n result: undefined,\n loading: true,\n syncing: true,\n error: false,\n}\n","import { Call } from '../types'\n\nexport function toCallKey(call: Call): string {\n let key = `${call.address}-${call.callData}`\n if (call.gasRequired) {\n if (!Number.isSafeInteger(call.gasRequired)) {\n throw new Error(`Invalid number: ${call.gasRequired}`)\n }\n key += `-${call.gasRequired}`\n }\n return key\n}\n\nexport function parseCallKey(callKey: string): Call {\n const pcs = callKey.split('-')\n if (![2, 3].includes(pcs.length)) {\n throw new Error(`Invalid call key: ${callKey}`)\n }\n return {\n address: pcs[0],\n callData: pcs[1],\n ...(pcs[2] ? { gasRequired: Number.parseInt(pcs[2]) } : {}),\n }\n}\n\nexport function callsToCallKeys(calls?: Array) {\n return (\n calls\n ?.filter((c): c is Call => Boolean(c))\n ?.map(toCallKey)\n ?.sort() ?? []\n )\n}\n\nexport function callKeysToCalls(callKeys: string[]) {\n if (!callKeys?.length) return null\n return callKeys.map((key) => parseCallKey(key))\n}\n","import { useMemo } from 'react'\nimport { INVALID_CALL_STATE, LOADING_CALL_STATE } from '../constants'\nimport type { CallResult, CallState, CallStateResult } from '../types'\nimport { AbiFunction, decodeFunctionResult } from 'viem'\n\n// Converts CallResult[] to CallState[], only updating if call states have changed.\n// Ensures that CallState results remain referentially stable when unchanged, preventing\n// spurious re-renders which would otherwise occur because mapping always creates a new object.\nexport function useCallStates(\n results: CallResult[],\n contractInterface: AbiFunction[] | undefined,\n fragment: ((i: number) => string | undefined) | string | undefined,\n latestBlockNumber: number | undefined\n): CallState[] {\n // Avoid refreshing the results with every changing block number (eg latestBlockNumber).\n // Instead, only refresh the results if they need to be synced - if there is a result which is stale, for which blockNumber < latestBlockNumber.\n const syncingBlockNumber = useMemo(() => {\n const lowestBlockNumber = results.reduce(\n (memo, result) => (result.blockNumber ? Math.min(memo ?? result.blockNumber, result.blockNumber) : memo),\n undefined\n )\n return Math.max(lowestBlockNumber ?? 0, latestBlockNumber ?? 0)\n }, [results, latestBlockNumber])\n\n return useMemo(() => {\n return results.map((result, i) => {\n const resultFragment = typeof fragment === 'function' ? fragment(i) : fragment\n return toCallState(result, contractInterface, resultFragment, syncingBlockNumber)\n })\n }, [contractInterface, fragment, results, syncingBlockNumber])\n}\n\nexport function toCallState(\n callResult: CallResult | undefined,\n contractInterface: AbiFunction[] | undefined,\n fragment: string | undefined,\n syncingBlockNumber: number | undefined\n): CallState {\n if (!callResult || !callResult.valid) {\n return INVALID_CALL_STATE\n }\n\n const { data, blockNumber } = callResult\n if (!blockNumber || !contractInterface || !fragment || !syncingBlockNumber) {\n return LOADING_CALL_STATE\n }\n\n const success = data && data.length > 2\n const syncing = blockNumber < syncingBlockNumber\n let result: CallStateResult | undefined = undefined\n if (success && data) {\n try {\n result = (decodeFunctionResult as any)({\n abi: contractInterface,\n functionName: fragment,\n data: data as any,\n }) as any\n } catch (error) {\n console.debug('Result data parsing failed', fragment, data)\n return {\n valid: true,\n loading: false,\n error: true,\n syncing,\n result,\n }\n }\n }\n return {\n valid: true,\n loading: false,\n syncing,\n result,\n error: !success,\n }\n}\n","export type MethodArg = string | number | BigInt\nexport type MethodArgs = Array\n\nexport function isMethodArg(x: unknown): x is MethodArg {\n return (x === null || x === undefined) ? false : typeof BigInt(x as any) === 'bigint' || ['string', 'number'].indexOf(typeof x) !== -1\n}\n\nexport function isValidMethodArgs(x: unknown): x is MethodArgs | undefined {\n return (\n x === undefined ||\n (Array.isArray(x) && x.every((xi) => isMethodArg(xi) || (Array.isArray(xi) && xi.every(isMethodArg))))\n )\n}\n","import { useCallback, useEffect, useMemo, useRef } from 'react'\nimport { batch, useDispatch, useSelector } from 'react-redux'\nimport { INVALID_CALL_STATE, INVALID_RESULT, DEFAULT_BLOCKS_PER_FETCH } from './constants'\nimport type { MulticallContext } from './context'\nimport type {\n Call,\n CallResult,\n CallState,\n ContractInfo,\n ListenerOptions,\n ListenerOptionsWithGas,\n WithMulticallState,\n} from './types'\nimport { callKeysToCalls, callsToCallKeys, toCallKey } from './utils/callKeys'\nimport { toCallState, useCallStates } from './utils/callState'\nimport { isValidMethodArgs, MethodArg } from './validation'\nimport { AbiFunction, encodeFunctionData, getAbiItem } from 'viem'\n\ntype OptionalMethodInputs = Array | undefined\n\n// the lowest level call for subscribing to contract data\nexport function useCallsDataSubscription(\n context: MulticallContext,\n chainId: number | undefined,\n calls: Array,\n listenerOptions?: ListenerOptions\n): CallResult[] {\n const { reducerPath, actions } = context\n const callResults = useSelector((state: WithMulticallState) => state[reducerPath].callResults)\n const defaultListenerOptions = useSelector((state: WithMulticallState) => state[reducerPath].listenerOptions)\n const dispatch = useDispatch()\n const serializedCallKeys: string = useMemo(() => JSON.stringify(callsToCallKeys(calls)), [calls])\n\n // update listeners when there is an actual change that persists for at least 100ms\n useEffect(() => {\n const callKeys: string[] = JSON.parse(serializedCallKeys)\n const calls = callKeysToCalls(callKeys)\n if (!chainId || !calls) return\n const blocksPerFetchFromState = (defaultListenerOptions ?? {})[chainId]?.blocksPerFetch\n const blocksPerFetchForChain =\n listenerOptions?.blocksPerFetch ?? blocksPerFetchFromState ?? DEFAULT_BLOCKS_PER_FETCH\n\n dispatch(\n actions.addMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n\n return () => {\n dispatch(\n actions.removeMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n }\n }, [actions, chainId, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions])\n\n const lastResults = useRef([])\n return useMemo(() => {\n let isChanged = lastResults.current.length !== calls.length\n\n // Construct results using a for-loop to handle sparse arrays.\n // Array.prototype.map would skip empty entries.\n let results: CallResult[] = []\n for (let i = 0; i < calls.length; ++i) {\n const call = calls[i]\n let result = INVALID_RESULT\n if (chainId && call) {\n const callResult = callResults[chainId]?.[toCallKey(call)]\n result = {\n valid: true,\n data: callResult?.data && callResult.data !== '0x' ? callResult.data : undefined,\n blockNumber: callResult?.blockNumber,\n }\n }\n\n isChanged = isChanged || !areCallResultsEqual(result, lastResults.current[i])\n results.push(result)\n }\n\n // Force the results to be referentially stable if they have not changed.\n // This is necessary because *all* callResults are passed as deps when initially memoizing the results.\n if (isChanged) {\n lastResults.current = results\n }\n return lastResults.current\n }, [callResults, calls, chainId])\n}\n\nfunction areCallResultsEqual(a: CallResult, b: CallResult) {\n return a.valid === b.valid && a.data === b.data && a.blockNumber === b.blockNumber\n}\n\n// Similar to useCallsDataSubscription above but for subscribing to\n// calls to multiple chains at once\nfunction useMultichainCallsDataSubscription(\n context: MulticallContext,\n chainToCalls: Record>,\n listenerOptions?: ListenerOptions\n): Record {\n const { reducerPath, actions } = context\n const callResults = useSelector((state: WithMulticallState) => state[reducerPath].callResults)\n const defaultListenerOptions = useSelector((state: WithMulticallState) => state[reducerPath].listenerOptions)\n const dispatch = useDispatch()\n\n const serializedCallKeys: string = useMemo(() => {\n const sortedChainIds = getChainIds(chainToCalls).sort()\n const chainCallKeysTuple = sortedChainIds.map((chainId) => {\n const calls = chainToCalls[chainId]\n const callKeys = callsToCallKeys(calls)\n // Note, using a tuple to ensure consistent order when serialized\n return [chainId, callKeys]\n })\n return JSON.stringify(chainCallKeysTuple)\n }, [chainToCalls])\n\n useEffect(() => {\n const chainCallKeysTuples: Array<[number, string[]]> = JSON.parse(serializedCallKeys)\n if (!chainCallKeysTuples?.length) return\n\n batch(() => {\n for (const [chainId, callKeys] of chainCallKeysTuples) {\n const calls = callKeysToCalls(callKeys)\n if (!calls?.length) continue\n const blocksPerFetchFromState = (defaultListenerOptions ?? {})[chainId]?.blocksPerFetch\n const blocksPerFetchForChain =\n listenerOptions?.blocksPerFetch ?? blocksPerFetchFromState ?? DEFAULT_BLOCKS_PER_FETCH\n\n dispatch(\n actions.addMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n }\n })\n\n return () => {\n batch(() => {\n for (const [chainId, callKeys] of chainCallKeysTuples) {\n const calls = callKeysToCalls(callKeys)\n if (!calls?.length) continue\n const blocksPerFetchFromState = (defaultListenerOptions ?? {})[chainId]?.blocksPerFetch\n const blocksPerFetchForChain =\n listenerOptions?.blocksPerFetch ?? blocksPerFetchFromState ?? DEFAULT_BLOCKS_PER_FETCH\n dispatch(\n actions.removeMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n }\n })\n }\n }, [actions, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions])\n\n return useMemo(\n () =>\n getChainIds(chainToCalls).reduce((result, chainId) => {\n const calls = chainToCalls[chainId]\n result[chainId] = calls.map((call) => {\n if (!chainId || !call) return INVALID_RESULT\n const result = callResults[chainId]?.[toCallKey(call)]\n const data = result?.data && result.data !== '0x' ? result.data : undefined\n return { valid: true, data, blockNumber: result?.blockNumber }\n })\n return result\n }, {} as Record),\n [callResults, chainToCalls]\n )\n}\n\n// formats many calls to a single function on a single contract, with the function name and inputs specified\nexport function useSingleContractMultipleData(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n contract: ContractInfo | null | undefined,\n methodName: string,\n callInputs: OptionalMethodInputs[],\n options?: Partial\n): CallState[] {\n const { gasRequired } = options ?? {}\n\n // Create ethers function fragment\n const fragment = useMemo(\n () => contract && ((getAbiItem as any)({ abi: contract.abi, name: methodName } as any) as any)?.name,\n [contract, methodName]\n )\n\n // Get encoded call data. Note can't use useCallData below b.c. this is for a list of CallInputs\n const callDatas = useMemo(() => {\n if (!contract || !fragment) return []\n return callInputs.map((callInput) =>\n isValidMethodArgs(callInput)\n ? (encodeFunctionData as any)({\n abi: contract.abi,\n functionName: fragment,\n args: callInput,\n })\n : undefined\n )\n }, [callInputs, contract, fragment])\n\n // Create call objects\n const calls = useMemo(() => {\n if (!contract) return []\n return callDatas.map((callData) => {\n if (!callData) return undefined\n return {\n address: contract.address,\n callData,\n gasRequired,\n }\n })\n }, [contract, callDatas, gasRequired])\n\n // Subscribe to call data\n const results = useCallsDataSubscription(context, chainId, calls, options as ListenerOptions)\n return useCallStates(results, contract?.abi, fragment, latestBlockNumber)\n}\n\nexport function useMultipleContractSingleData(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n addresses: (string | undefined)[],\n contractInterface: AbiFunction[],\n methodName: string,\n callInputs?: OptionalMethodInputs,\n options?: Partial\n): CallState[] {\n const { gasRequired } = options ?? {}\n\n const { fragment, callData } = useCallData(methodName, contractInterface, callInputs)\n\n // Create call objects\n const calls = useMemo(() => {\n if (!callData) return []\n return addresses.map((address) => {\n if (!address) return undefined\n return { address, callData, gasRequired }\n })\n }, [addresses, callData, gasRequired])\n\n // Subscribe to call data\n const results = useCallsDataSubscription(context, chainId, calls, options as ListenerOptions)\n return useCallStates(results, contractInterface, fragment, latestBlockNumber)\n}\n\nexport function useSingleCallResult(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n contract: ContractInfo | null | undefined,\n methodName: string,\n inputs?: OptionalMethodInputs,\n options?: Partial\n): CallState {\n const callInputs = useMemo(() => [inputs], [inputs])\n return (\n useSingleContractMultipleData(context, chainId, latestBlockNumber, contract, methodName, callInputs, options)[0] ??\n INVALID_CALL_STATE\n )\n}\n\n// formats many calls to any number of functions on a single contract, with only the calldata specified\nexport function useSingleContractWithCallData(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n contract: ContractInfo | null | undefined,\n callDatas: string[],\n options?: Partial\n): CallState[] {\n const { gasRequired } = options ?? {}\n\n // Create call objects\n const calls = useMemo(() => {\n if (!contract) return []\n return callDatas.map((callData) => ({\n address: contract.address,\n callData,\n gasRequired,\n }))\n }, [callDatas, contract, gasRequired])\n\n // Subscribe to call data\n const results = useCallsDataSubscription(context, chainId, calls, options as ListenerOptions)\n const fragment = useCallback(\n (i: number) => ((getAbiItem as any)({ abi: contract?.abi as any, name: callDatas[i].substring(0, 10) }) as any)?.name,\n [callDatas, contract]\n )\n return useCallStates(results, contract?.abi, fragment, latestBlockNumber)\n}\n\n// Similar to useMultipleContractSingleData but instead of multiple contracts on one chain,\n// this is for querying compatible contracts on multiple chains\nexport function useMultiChainMultiContractSingleData(\n context: MulticallContext,\n chainToBlockNumber: Record,\n chainToAddresses: Record>,\n contractInterface: AbiFunction[],\n methodName: string,\n callInputs?: OptionalMethodInputs,\n options?: Partial\n): Record {\n const { gasRequired } = options ?? {}\n\n const { fragment, callData } = useCallData(methodName, contractInterface, callInputs)\n\n // Create call objects\n const chainToCalls = useMemo(() => {\n if (!callData || !chainToAddresses) return {}\n return getChainIds(chainToAddresses).reduce((result, chainId) => {\n const addresses = chainToAddresses[chainId]\n const calls = addresses.map((address) => {\n if (!address) return undefined\n return { address, callData, gasRequired }\n })\n result[chainId] = calls\n return result\n }, {} as Record>)\n }, [chainToAddresses, callData, gasRequired])\n\n // Subscribe to call data\n const chainIdToResults = useMultichainCallsDataSubscription(context, chainToCalls, options as ListenerOptions)\n\n // TODO(WEB-2097): Multichain states are not referentially stable, because they cannot use the\n // same codepath (eg useCallStates).\n return useMemo(() => {\n return getChainIds(chainIdToResults).reduce((combinedResults, chainId) => {\n const latestBlockNumber = chainToBlockNumber?.[chainId]\n const results = chainIdToResults[chainId]\n combinedResults[chainId] = results.map((result) =>\n toCallState(result, contractInterface, fragment, latestBlockNumber)\n )\n return combinedResults\n }, {} as Record)\n }, [fragment, contractInterface, chainIdToResults, chainToBlockNumber])\n}\n\n// Similar to useSingleCallResult but instead of one contract on one chain,\n// this is for querying a contract on multiple chains\nexport function useMultiChainSingleContractSingleData(\n context: MulticallContext,\n chainToBlockNumber: Record,\n chainToAddress: Record,\n contractInterface: AbiFunction[],\n methodName: string,\n callInputs?: OptionalMethodInputs,\n options?: Partial\n): Record {\n // This hook uses the more flexible useMultiChainMultiContractSingleData internally,\n // but transforms the inputs and outputs for convenience\n const chainIdToAddresses = useMemo(() => {\n return getChainIds(chainToAddress).reduce((result, chainId) => {\n result[chainId] = [chainToAddress[chainId]]\n return result\n }, {} as Record>)\n }, [chainToAddress])\n\n const multiContractResults = useMultiChainMultiContractSingleData(\n context,\n chainToBlockNumber,\n chainIdToAddresses,\n contractInterface,\n methodName,\n callInputs,\n options\n )\n\n return useMemo(() => {\n return getChainIds(chainToAddress).reduce((result, chainId) => {\n result[chainId] = multiContractResults[chainId]?.[0] ?? INVALID_CALL_STATE\n return result\n }, {} as Record)\n }, [chainToAddress, multiContractResults])\n}\n\nfunction useCallData(\n methodName: string,\n contractInterface: AbiFunction[] | null | undefined,\n callInputs: OptionalMethodInputs | undefined\n) {\n // Create ethers function fragment\n const fragment = useMemo(\n () => contractInterface && ((getAbiItem as any)({ abi: contractInterface as any, name: methodName }) as any)?.name,\n [contractInterface, methodName]\n )\n // Get encoded call data\n const callData: string | undefined = useMemo(\n () =>\n fragment && isValidMethodArgs(callInputs)\n ? (encodeFunctionData as any)({\n abi: contractInterface as any,\n functionName: fragment,\n args: callInputs as unknown as any[],\n })\n : undefined,\n [callInputs, contractInterface, fragment]\n )\n return { fragment, callData }\n}\n\nfunction getChainIds(chainIdMap: Record) {\n return Object.keys(chainIdMap).map((c) => parseInt(c, 10))\n}\n","import { createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport {\n MulticallFetchingPayload,\n MulticallListenerPayload,\n MulticallResultsPayload,\n MulticallState,\n MulticallListenerOptionsPayload,\n} from './types'\nimport { toCallKey } from './utils/callKeys'\n\nconst initialState: MulticallState = {\n callResults: {},\n}\n\nexport function createMulticallSlice(reducerPath: string) {\n return createSlice({\n name: reducerPath,\n initialState,\n reducers: {\n addMulticallListeners: (state, action: PayloadAction) => {\n const {\n calls,\n chainId,\n options: { blocksPerFetch },\n } = action.payload\n const listeners: MulticallState['callListeners'] = state.callListeners\n ? state.callListeners\n : (state.callListeners = {})\n listeners[chainId] = listeners[chainId] ?? {}\n calls.forEach((call) => {\n const callKey = toCallKey(call)\n listeners[chainId][callKey] = listeners[chainId][callKey] ?? {}\n listeners[chainId][callKey][blocksPerFetch] = (listeners[chainId][callKey][blocksPerFetch] ?? 0) + 1\n })\n },\n\n removeMulticallListeners: (state, action: PayloadAction) => {\n const {\n calls,\n chainId,\n options: { blocksPerFetch },\n } = action.payload\n const listeners: MulticallState['callListeners'] = state.callListeners\n ? state.callListeners\n : (state.callListeners = {})\n\n if (!listeners[chainId]) return\n calls.forEach((call) => {\n const callKey = toCallKey(call)\n if (!listeners[chainId][callKey]) return\n if (!listeners[chainId][callKey][blocksPerFetch]) return\n\n if (listeners[chainId][callKey][blocksPerFetch] === 1) {\n delete listeners[chainId][callKey][blocksPerFetch]\n } else {\n listeners[chainId][callKey][blocksPerFetch]--\n }\n })\n },\n\n fetchingMulticallResults: (state, action: PayloadAction) => {\n const { chainId, fetchingBlockNumber, calls } = action.payload\n state.callResults[chainId] = state.callResults[chainId] ?? {}\n calls.forEach((call) => {\n const callKey = toCallKey(call)\n const current = state.callResults[chainId][callKey]\n if (!current) {\n state.callResults[chainId][callKey] = {\n fetchingBlockNumber,\n }\n } else {\n if ((current.fetchingBlockNumber ?? 0) >= fetchingBlockNumber) return\n state.callResults[chainId][callKey].fetchingBlockNumber = fetchingBlockNumber\n }\n })\n },\n\n errorFetchingMulticallResults: (state, action: PayloadAction) => {\n const { chainId, fetchingBlockNumber, calls } = action.payload\n state.callResults[chainId] = state.callResults[chainId] ?? {}\n calls.forEach((call) => {\n const callKey = toCallKey(call)\n const current = state.callResults[chainId][callKey]\n if (!current || typeof current.fetchingBlockNumber !== 'number') return // only should be dispatched if we are already fetching\n if (current.fetchingBlockNumber <= fetchingBlockNumber) {\n delete current.fetchingBlockNumber\n current.data = null\n current.blockNumber = fetchingBlockNumber\n }\n })\n },\n\n updateMulticallResults: (state, action: PayloadAction) => {\n const { chainId, results, blockNumber } = action.payload\n state.callResults[chainId] = state.callResults[chainId] ?? {}\n Object.keys(results).forEach((callKey) => {\n const current = state.callResults[chainId][callKey]\n if ((current?.blockNumber ?? 0) > blockNumber) return\n if (current?.data === results[callKey] && current?.blockNumber === blockNumber) return\n state.callResults[chainId][callKey] = {\n data: results[callKey],\n blockNumber,\n }\n })\n },\n\n updateListenerOptions: (state, action: PayloadAction) => {\n const { chainId, listenerOptions } = action.payload\n state.listenerOptions = state.listenerOptions ?? {}\n state.listenerOptions[chainId] = listenerOptions\n },\n },\n })\n}\n\nexport type MulticallActions = ReturnType['actions']\n","import { DEFAULT_CHUNK_GAS_REQUIRED } from '../constants'\n\ninterface Bin {\n calls: T[]\n cumulativeGasLimit: number\n}\n\n/**\n * Tries to pack a list of items into as few bins as possible using the first-fit bin packing algorithm\n * @param calls the calls to chunk\n * @param chunkGasLimit the gas limit of any one chunk of calls, i.e. bin capacity\n * @param defaultGasRequired the default amount of gas an individual call should cost if not specified\n */\nexport default function chunkCalls(\n calls: T[],\n chunkGasLimit: number,\n defaultGasRequired: number = DEFAULT_CHUNK_GAS_REQUIRED\n): T[][] {\n return (\n calls\n // first sort by gas required\n .sort((c1, c2) => (c2.gasRequired ?? defaultGasRequired) - (c1.gasRequired ?? defaultGasRequired))\n // then bin the calls according to the first fit algorithm\n .reduce[]>((bins, call) => {\n const gas = call.gasRequired ?? defaultGasRequired\n for (const bin of bins) {\n if (bin.cumulativeGasLimit + gas <= chunkGasLimit) {\n bin.calls.push(call)\n bin.cumulativeGasLimit += gas\n return bins\n }\n }\n // didn't find a bin for the call, make a new bin\n bins.push({\n calls: [call],\n cumulativeGasLimit: gas,\n })\n return bins\n }, [])\n // pull out just the calls from each bin\n .map((b) => b.calls)\n )\n}\n","// TODO de-duplicate this file with web interface\n// https://github.com/Uniswap/interface/blob/main/src/utils/retry.ts\n\nfunction wait(ms: number): Promise {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction waitRandom(min: number, max: number): Promise {\n return wait(min + Math.round(Math.random() * Math.max(0, max - min)))\n}\n\n/**\n * This error is thrown if the function is cancelled before completing\n */\nclass CancelledError extends Error {\n public isCancelledError: true = true\n constructor() {\n super('Cancelled')\n }\n}\n\n/**\n * Throw this error if the function should retry\n */\nexport class RetryableError extends Error {\n public isRetryableError: true = true\n}\n\nexport interface RetryOptions {\n n: number\n minWait: number\n maxWait: number\n}\n\n/**\n * Retries the function that returns the promise until the promise successfully resolves up to n retries\n * @param fn function to retry\n * @param n how many times to retry\n * @param minWait min wait between retries in ms\n * @param maxWait max wait between retries in ms\n */\nexport function retry(\n fn: () => Promise,\n { n, minWait, maxWait }: RetryOptions\n): { promise: Promise; cancel: () => void } {\n let completed = false\n let rejectCancelled: (error: Error) => void\n const promise = new Promise(async (resolve, reject) => {\n rejectCancelled = reject\n while (true) {\n let result: T\n try {\n result = await fn()\n if (!completed) {\n resolve(result)\n completed = true\n }\n break\n } catch (error) {\n if (completed) {\n break\n }\n if (n <= 0 || !(error as any).isRetryableError) {\n reject(error)\n completed = true\n break\n }\n n--\n }\n await waitRandom(minWait, maxWait)\n }\n })\n return {\n promise,\n cancel: () => {\n if (completed) return\n completed = true\n rejectCancelled(new CancelledError())\n },\n }\n}\n","// TODO de-duplicate this file with web interface\n// https://github.com/Uniswap/interface/blob/main/src/hooks/useDebounce.ts\n\nimport { useEffect, useState } from 'react'\n\n// modified from https://usehooks.com/useDebounce/\nexport default function useDebounce(value: T, delay: number): T {\n const [debouncedValue, setDebouncedValue] = useState(value)\n\n useEffect(() => {\n // Update debounced value after delay\n const handler = setTimeout(() => {\n setDebouncedValue(value)\n }, delay)\n\n // Cancel the timeout if value changes (also on delay change or unmount)\n // This is how we prevent debounced value from updating if value is changed ...\n // .. within the delay period. Timeout gets cleared and restarted.\n return () => {\n clearTimeout(handler)\n }\n }, [value, delay])\n\n return debouncedValue\n}\n","export default [\n {\n inputs: [],\n name: 'getCurrentBlockTimestamp',\n outputs: [\n {\n internalType: 'uint256',\n name: 'timestamp',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n ],\n name: 'getEthBalance',\n outputs: [\n {\n internalType: 'uint256',\n name: 'balance',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n components: [\n {\n internalType: 'address',\n name: 'target',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'gasLimit',\n type: 'uint256',\n },\n {\n internalType: 'bytes',\n name: 'callData',\n type: 'bytes',\n },\n ],\n internalType: 'struct PancakeInterfaceMulticall.Call[]',\n name: 'calls',\n type: 'tuple[]',\n },\n ],\n name: 'multicall',\n outputs: [\n {\n internalType: 'uint256',\n name: 'blockNumber',\n type: 'uint256',\n },\n {\n components: [\n {\n internalType: 'bool',\n name: 'success',\n type: 'bool',\n },\n {\n internalType: 'uint256',\n name: 'gasUsed',\n type: 'uint256',\n },\n {\n internalType: 'bytes',\n name: 'returnData',\n type: 'bytes',\n },\n ],\n internalType: 'struct PancakeInterfaceMulticall.Result[]',\n name: 'returnData',\n type: 'tuple[]',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n] as const\n","import React, { Dispatch, useEffect, useMemo, useRef } from 'react'\nimport { useDispatch, useSelector } from 'react-redux'\nimport { CHUNK_GAS_LIMIT, DEFAULT_CALL_GAS_REQUIRED } from './constants'\nimport type { MulticallContext } from './context'\nimport type { MulticallActions } from './slice'\nimport type { Call, MulticallState, WithMulticallState, ListenerOptions, MulticallInfo } from './types'\nimport { parseCallKey, toCallKey } from './utils/callKeys'\nimport chunkCalls from './utils/chunkCalls'\nimport { retry, RetryableError } from './utils/retry'\nimport useDebounce from './utils/useDebounce'\nimport IMulticallABI from './abi/InterfaceMulticall'\n\nconst FETCH_RETRY_CONFIG = {\n n: Infinity,\n minWait: 1000,\n maxWait: 2500,\n}\n\n/**\n * Fetches a chunk of calls, enforcing a minimum block number constraint\n * @param multicall multicall contract to fetch against\n * @param chunk chunk of calls to make\n * @param blockNumber block number passed as the block tag in the eth_call\n */\nasync function fetchChunk(\n multicallInfo: MulticallInfo,\n chunk: Call[],\n blockNumber: number,\n isDebug?: boolean\n): Promise {\n console.debug('Fetching chunk', chunk, blockNumber, chunk.map((obj) => ({\n target: obj.address,\n callData: obj.callData,\n gasLimit: obj.gasRequired ?? DEFAULT_CALL_GAS_REQUIRED,\n })))\n try {\n const {\n result: [, returnData], // [blockNumber, results]\n }: { result: [any, any[]] } = await (multicallInfo.provider as any).simulateContract({\n abi: IMulticallABI,\n address: multicallInfo.address,\n functionName: 'multicall',\n args: [\n chunk.map((obj) => ({\n target: obj.address,\n callData: obj.callData,\n gasLimit: obj.gasRequired ?? DEFAULT_CALL_GAS_REQUIRED,\n }))\n ],\n // we aren't passing through the block gas limit we used to create the chunk, because it causes a problem with the integ tests\n blockNumber: BigInt(blockNumber)\n }\n )\n if (isDebug) {\n returnData.forEach(({ gasUsed, returnData, success }, i) => {\n if (\n !success &&\n returnData.length === 2 &&\n gasUsed >= (Math.floor((chunk[i].gasRequired ?? DEFAULT_CALL_GAS_REQUIRED) * 0.95))\n ) {\n console.warn(\n `A call failed due to requiring ${gasUsed.toString()} vs. allowed ${chunk[i].gasRequired ?? DEFAULT_CALL_GAS_REQUIRED\n }`,\n chunk[i]\n )\n }\n })\n }\n\n return returnData\n } catch (e) {\n const error = e as any\n if (error.code === -32000 || error.message?.indexOf('header not found') !== -1) {\n throw new RetryableError(`header not found for block number ${blockNumber}`)\n } else if (error.code === -32603 || error.message?.indexOf('execution ran out of gas') !== -1) {\n if (chunk.length > 1) {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Splitting a chunk in 2', chunk)\n }\n const half = Math.floor(chunk.length / 2)\n const [c0, c1] = await Promise.all([\n fetchChunk(multicallInfo, chunk.slice(0, half), blockNumber),\n fetchChunk(multicallInfo, chunk.slice(half, chunk.length), blockNumber),\n ])\n return c0.concat(c1)\n }\n }\n console.error('Failed to fetch chunk', error)\n throw error\n }\n}\n\n/**\n * From the current all listeners state, return each call key mapped to the\n * minimum number of blocks per fetch. This is how often each key must be fetched.\n * @param allListeners the all listeners state\n * @param chainId the current chain id\n */\nexport function activeListeningKeys(\n allListeners: MulticallState['callListeners'],\n chainId?: number\n): { [callKey: string]: number } {\n if (!allListeners || !chainId) return {}\n const listeners = allListeners[chainId]\n if (!listeners) return {}\n\n return Object.keys(listeners).reduce<{ [callKey: string]: number }>((memo, callKey) => {\n const keyListeners = listeners[callKey]\n\n memo[callKey] = Object.keys(keyListeners)\n .filter((key) => {\n const blocksPerFetch = parseInt(key)\n if (blocksPerFetch <= 0) return false\n return keyListeners[blocksPerFetch] > 0\n })\n .reduce((previousMin, current) => {\n return Math.min(previousMin, parseInt(current))\n }, Infinity)\n return memo\n }, {})\n}\n\n/**\n * Return the keys that need to be refetched\n * @param callResults current call result state\n * @param listeningKeys each call key mapped to how old the data can be in blocks\n * @param chainId the current chain id\n * @param latestBlockNumber the latest block number\n */\nexport function outdatedListeningKeys(\n callResults: MulticallState['callResults'],\n listeningKeys: { [callKey: string]: number },\n chainId: number | undefined,\n latestBlockNumber: number | undefined\n): string[] {\n if (!chainId || !latestBlockNumber) return []\n const results = callResults[chainId]\n // no results at all, load everything\n if (!results) return Object.keys(listeningKeys)\n\n return Object.keys(listeningKeys).filter((callKey) => {\n const blocksPerFetch = listeningKeys[callKey]\n\n const data = callResults[chainId][callKey]\n // no data, must fetch\n if (!data) return true\n\n const minDataBlockNumber = latestBlockNumber - (blocksPerFetch - 1)\n\n // already fetching it for a recent enough block, don't refetch it\n if (data.fetchingBlockNumber && data.fetchingBlockNumber >= minDataBlockNumber) return false\n\n // if data is older than minDataBlockNumber, fetch it\n return !data.blockNumber || data.blockNumber < minDataBlockNumber\n })\n}\n\ninterface FetchChunkContext {\n actions: MulticallActions\n dispatch: Dispatch\n chainId: number\n latestBlockNumber: number\n isDebug?: boolean\n}\n\nfunction onFetchChunkSuccess(\n context: FetchChunkContext,\n chunk: Call[],\n result: readonly { success: boolean; returnData: string }[]\n) {\n const { actions, dispatch, chainId, latestBlockNumber, isDebug } = context\n\n // split the returned slice into errors and results\n const { erroredCalls, results } = chunk.reduce<{\n erroredCalls: Call[]\n results: { [callKey: string]: string | null }\n }>(\n (memo, call, i) => {\n if (result[i].success) {\n memo.results[toCallKey(call)] = result[i].returnData ?? null\n } else {\n memo.erroredCalls.push(call)\n }\n return memo\n },\n { erroredCalls: [], results: {} }\n )\n\n // dispatch any new results\n if (Object.keys(results).length > 0)\n dispatch(\n actions.updateMulticallResults({\n chainId,\n results,\n blockNumber: latestBlockNumber,\n })\n )\n\n // dispatch any errored calls\n if (erroredCalls.length > 0) {\n if (isDebug) {\n result.forEach((returnData, ix) => {\n if (!returnData.success) {\n console.debug('Call failed', chunk[ix], returnData)\n }\n })\n } else {\n console.debug('Calls errored in fetch', erroredCalls)\n }\n dispatch(\n actions.errorFetchingMulticallResults({\n calls: erroredCalls,\n chainId,\n fetchingBlockNumber: latestBlockNumber,\n })\n )\n }\n}\n\nfunction onFetchChunkFailure(context: FetchChunkContext, chunk: Call[], error: any) {\n const { actions, dispatch, chainId, latestBlockNumber } = context\n\n if (error.isCancelledError) {\n console.debug('Cancelled fetch for blockNumber', latestBlockNumber, chunk, chainId)\n return\n }\n console.error('Failed to fetch multicall chunk', chunk, chainId, error)\n dispatch(\n actions.errorFetchingMulticallResults({\n calls: chunk,\n chainId,\n fetchingBlockNumber: latestBlockNumber,\n })\n )\n}\n\nexport interface UpdaterProps {\n context: MulticallContext\n chainId: number | undefined // For now, one updater is required for each chainId to be watched\n latestBlockNumber: number | undefined\n multicallInfo: MulticallInfo\n isDebug?: boolean\n listenerOptions?: ListenerOptions\n}\n\nfunction Updater(props: UpdaterProps): null {\n const { context, chainId, latestBlockNumber, multicallInfo, isDebug, listenerOptions } = props\n const { actions, reducerPath } = context\n const dispatch = useDispatch()\n\n // set user configured listenerOptions in state for given chain ID.\n useEffect(() => {\n if (chainId && listenerOptions) {\n dispatch(actions.updateListenerOptions({ chainId, listenerOptions }))\n }\n }, [chainId, listenerOptions, actions, dispatch])\n\n const state = useSelector((state: WithMulticallState) => state[reducerPath])\n\n // wait for listeners to settle before triggering updates\n const debouncedListeners = useDebounce(state.callListeners, 100)\n const cancellations = useRef<{ blockNumber: number; cancellations: (() => void)[] }>()\n\n const listeningKeys: { [callKey: string]: number } = useMemo(() => {\n return activeListeningKeys(debouncedListeners, chainId)\n }, [debouncedListeners, chainId])\n\n const serializedOutdatedCallKeys = useMemo(() => {\n const outdatedCallKeys = outdatedListeningKeys(state.callResults, listeningKeys, chainId, latestBlockNumber)\n return JSON.stringify(outdatedCallKeys.sort())\n }, [chainId, state.callResults, listeningKeys, latestBlockNumber])\n\n useEffect(() => {\n if (!latestBlockNumber || !chainId || !multicallInfo) return\n\n const outdatedCallKeys: string[] = JSON.parse(serializedOutdatedCallKeys)\n if (outdatedCallKeys.length === 0) return\n const calls = outdatedCallKeys.map((key) => parseCallKey(key))\n\n const chunkedCalls = chunkCalls(calls, CHUNK_GAS_LIMIT)\n\n if (cancellations.current && cancellations.current.blockNumber !== latestBlockNumber) {\n cancellations.current.cancellations.forEach((c) => c())\n }\n\n dispatch(\n actions.fetchingMulticallResults({\n calls,\n chainId,\n fetchingBlockNumber: latestBlockNumber,\n })\n )\n\n const fetchChunkContext = {\n actions,\n dispatch,\n chainId,\n latestBlockNumber,\n isDebug,\n }\n // Execute fetches and gather cancellation callbacks\n const newCancellations = chunkedCalls.map((chunk) => {\n const { cancel, promise } = retry(\n () => fetchChunk(multicallInfo, chunk, latestBlockNumber, isDebug),\n FETCH_RETRY_CONFIG\n )\n promise\n .then((result) => onFetchChunkSuccess(fetchChunkContext, chunk, result))\n .catch((error) => onFetchChunkFailure(fetchChunkContext, chunk, error))\n return cancel\n })\n\n cancellations.current = {\n blockNumber: latestBlockNumber,\n cancellations: newCancellations,\n }\n }, [actions, chainId, multicallInfo, dispatch, serializedOutdatedCallKeys, latestBlockNumber, isDebug])\n\n return null\n}\n\nexport function createUpdater(context: MulticallContext) {\n const UpdaterContextBound = (props: Omit) => {\n return \n }\n return UpdaterContextBound\n}\n","import type { MulticallContext } from './context'\nimport {\n useMultiChainMultiContractSingleData as _useMultiChainMultiContractSingleData,\n useMultiChainSingleContractSingleData as _useMultiChainSingleContractSingleData,\n useMultipleContractSingleData as _useMultipleContractSingleData,\n useSingleCallResult as _useSingleCallResult,\n useSingleContractMultipleData as _useSingleContractMultipleData,\n useSingleContractWithCallData as _useSingleContractWithCallData,\n} from './hooks'\nimport { createMulticallSlice } from './slice'\nimport { createUpdater } from './updater'\n\ntype RemoveFirstFromTuple = T['length'] extends 0\n ? undefined\n : ((...b: T) => void) extends (a: any, ...b: infer I) => void\n ? I\n : []\ntype ParamsWithoutContext any> = RemoveFirstFromTuple>\n\nexport interface MulticallOptions {\n reducerPath?: string\n // More options can be added here as multicall's capabilities are extended\n}\n\n// Inspired by RTK Query's createApi\nexport function createMulticall(options?: MulticallOptions) {\n const reducerPath = options?.reducerPath ?? 'multicall'\n const slice = createMulticallSlice(reducerPath)\n const { actions, reducer } = slice\n const context: MulticallContext = { reducerPath, actions }\n\n const useMultipleContractSingleData = (...args: ParamsWithoutContext) =>\n _useMultipleContractSingleData(context, ...args)\n const useSingleContractMultipleData = (...args: ParamsWithoutContext) =>\n _useSingleContractMultipleData(context, ...args)\n const useSingleContractWithCallData = (...args: ParamsWithoutContext) =>\n _useSingleContractWithCallData(context, ...args)\n const useSingleCallResult = (...args: ParamsWithoutContext) =>\n _useSingleCallResult(context, ...args)\n const useMultiChainMultiContractSingleData = (\n ...args: ParamsWithoutContext\n ) => _useMultiChainMultiContractSingleData(context, ...args)\n const useMultiChainSingleContractSingleData = (\n ...args: ParamsWithoutContext\n ) => _useMultiChainSingleContractSingleData(context, ...args)\n const hooks = {\n useMultipleContractSingleData,\n useSingleContractMultipleData,\n useSingleContractWithCallData,\n useSingleCallResult,\n useMultiChainMultiContractSingleData,\n useMultiChainSingleContractSingleData,\n }\n\n const Updater = createUpdater(context)\n\n return {\n reducerPath,\n reducer,\n actions,\n hooks,\n Updater,\n }\n}\n"],"names":["DEFAULT_BLOCKS_PER_FETCH","DEFAULT_CALL_GAS_REQUIRED","DEFAULT_CHUNK_GAS_REQUIRED","CHUNK_GAS_LIMIT","CONSERVATIVE_BLOCK_GAS_LIMIT","INVALID_RESULT","valid","blockNumber","undefined","data","NEVER_RELOAD","blocksPerFetch","Infinity","INVALID_CALL_STATE","result","loading","syncing","error","LOADING_CALL_STATE","toCallKey","call","key","address","callData","gasRequired","Number","isSafeInteger","Error","parseCallKey","callKey","pcs","split","includes","length","_extends","parseInt","callsToCallKeys","calls","_calls$filter$map$sor","_calls$filter","filter","c","Boolean","map","sort","callKeysToCalls","callKeys","useCallStates","results","contractInterface","fragment","latestBlockNumber","syncingBlockNumber","useMemo","lowestBlockNumber","reduce","memo","Math","min","max","i","resultFragment","toCallState","callResult","success","decodeFunctionResult","abi","functionName","console","debug","isMethodArg","x","BigInt","indexOf","isValidMethodArgs","Array","isArray","every","xi","useCallsDataSubscription","context","chainId","listenerOptions","reducerPath","actions","callResults","useSelector","state","defaultListenerOptions","dispatch","useDispatch","serializedCallKeys","JSON","stringify","useEffect","parse","blocksPerFetchFromState","_chainId","blocksPerFetchForChain","_ref","_listenerOptions$bloc","addMulticallListeners","options","removeMulticallListeners","lastResults","useRef","isChanged","current","_callResults$chainId","areCallResultsEqual","push","a","b","useMultichainCallsDataSubscription","chainToCalls","sortedChainIds","getChainIds","chainCallKeysTuple","chainCallKeysTuples","batch","_iterator","_createForOfIteratorHelperLoose","_step","done","_chainId2","_ref2","_listenerOptions$bloc2","_step$value","value","_iterator2","_step2","_chainId3","_ref3","_listenerOptions$bloc3","_step2$value","_callResults$chainId2","useSingleContractMultipleData","contract","methodName","callInputs","_ref4","_getAbiItem","getAbiItem","name","callDatas","callInput","encodeFunctionData","args","useMultipleContractSingleData","addresses","_ref5","_useCallData","useCallData","useSingleCallResult","inputs","_useSingleContractMul","useSingleContractWithCallData","_ref6","useCallback","_getAbiItem2","substring","useMultiChainMultiContractSingleData","chainToBlockNumber","chainToAddresses","_ref7","_useCallData2","chainIdToResults","combinedResults","useMultiChainSingleContractSingleData","chainToAddress","chainIdToAddresses","multiContractResults","_multiContractResults","_multiContractResults2","_getAbiItem3","chainIdMap","Object","keys","initialState","createMulticallSlice","createSlice","reducers","action","_action$payload","payload","listeners","callListeners","_listeners$chainId","forEach","_listeners$chainId$ca","_listeners$chainId$ca2","_action$payload2","fetchingMulticallResults","_action$payload3","fetchingBlockNumber","_state$callResults$ch","_current$fetchingBloc","errorFetchingMulticallResults","_action$payload4","_state$callResults$ch2","updateMulticallResults","_action$payload5","_state$callResults$ch3","_current$blockNumber","updateListenerOptions","_action$payload6","_state$listenerOption","chunkCalls","chunkGasLimit","defaultGasRequired","c1","c2","_c2$gasRequired","_c1$gasRequired","bins","gas","_call$gasRequired","bin","cumulativeGasLimit","wait","ms","Promise","resolve","setTimeout","waitRandom","round","random","CancelledError","_Error","_this","_inheritsLoose","_wrapNativeSuper","RetryableError","_Error2","_this2","retry","fn","n","minWait","maxWait","completed","rejectCancelled","promise","_asyncToGenerator","_regeneratorRuntime","mark","_callee","reject","wrap","_callee$","_context","prev","next","sent","abrupt","t0","isRetryableError","stop","_x","_x2","apply","arguments","cancel","useDebounce","delay","_useState","useState","debouncedValue","setDebouncedValue","handler","clearTimeout","outputs","internalType","type","stateMutability","components","FETCH_RETRY_CONFIG","fetchChunk","_x3","_x4","_fetchChunk","multicallInfo","chunk","isDebug","_yield$multicallInfo$","_yield$multicallInfo$2","returnData","_error$message","_error$message2","half","_yield$Promise$all","c0","obj","_obj$gasRequired","target","gasLimit","provider","simulateContract","IMulticallABI","_obj$gasRequired2","gasUsed","floor","_chunk$i$gasRequired","_chunk$i$gasRequired2","warn","toString","code","message","all","slice","concat","activeListeningKeys","allListeners","keyListeners","previousMin","outdatedListeningKeys","listeningKeys","minDataBlockNumber","onFetchChunkSuccess","_chunk$reduce","_result$i$returnData","erroredCalls","ix","onFetchChunkFailure","isCancelledError","Updater","props","debouncedListeners","cancellations","serializedOutdatedCallKeys","outdatedCallKeys","chunkedCalls","fetchChunkContext","newCancellations","_retry","then","createUpdater","UpdaterContextBound","React","createMulticall","_options$reducerPath","reducer","_len","_key","_useMultipleContractSingleData","_len2","_key2","_useSingleContractMultipleData","_len3","_key3","_useSingleContractWithCallData","_len4","_key4","_useSingleCallResult","_len5","_key5","_useMultiChainMultiContractSingleData","_len6","_key6","_useMultiChainSingleContractSingleData","hooks"],"mappings":";;;;;;;;;;;;IAEaA,wBAAwB,GAAG;IAC3BC,yBAAyB,GAAG;IAC5BC,0BAA0B,GAAG;IAC7BC,eAAe,GAAG;IAClBC,4BAA4B,GAAG,SAAU;AAEtD;IACaC,cAAc,GAAe;EAAEC,KAAK,EAAE,KAAK;EAAEC,WAAW,EAAEC,SAAS;EAAEC,IAAI,EAAED;;IAC3EE,YAAY,GAAoB;EAC3CC,cAAc,EAAEC;;IAGLC,kBAAkB,GAAc;EAC3CP,KAAK,EAAE,KAAK;EACZQ,MAAM,EAAEN,SAAS;EACjBO,OAAO,EAAE,KAAK;EACdC,OAAO,EAAE,KAAK;EACdC,KAAK,EAAE;;IAEIC,kBAAkB,GAAc;EAC3CZ,KAAK,EAAE,IAAI;EACXQ,MAAM,EAAEN,SAAS;EACjBO,O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CAAApO,MAAA,EACtCkH,IAAyE,OAAAxE,KAAA,CAAA0R,KAAA,GAAAC,KAAA,MAAAA,KAAA,GAAAD,KAAA,EAAAC,KAAA;MAAzEnN,IAAyE,CAAAmN,KAAA,IAAAjG,SAAA,CAAAiG,KAAA;;IAAA,OACzEC,qCAAsC,CAAAnG,KAAA,UAACpL,OAAO,EAAAsO,MAAA,CAAKnK,IAAI,EAAC;;EAC7D,IAAMqN,KAAK,GAAG;IACZpN,6BAA6B,EAA7BA,+BAA6B;IAC7BZ,6BAA6B,EAA7BA,+BAA6B;IAC7BoB,6BAA6B,EAA7BA,+BAA6B;IAC7BH,mBAAmB,EAAnBA,qBAAmB;IACnBQ,oCAAoC,EAApCA,sCAAoC;IACpCO,qCAAqC,EAArCA;GACD;EAED,IAAM6J,OAAO,GAAGW,aAAa,CAAChQ,OAAO,CAAC;EAEtC,OAAO;IACLG,WAAW,EAAXA,WAAW;IACXkQ,OAAO,EAAPA,OAAO;IACPjQ,OAAO,EAAPA,OAAO;IACPoR,KAAK,EAALA,KAAK;IACLnC,OAAO,EAAPA;GACD;AACH;;;;;;;;;;;;;"}
\ No newline at end of file
diff --git a/dist/redux-multicall-viem.cjs.production.min.js b/dist/redux-multicall-viem.cjs.production.min.js
new file mode 100644
index 0000000..a0105ed
--- /dev/null
+++ b/dist/redux-multicall-viem.cjs.production.min.js
@@ -0,0 +1,2 @@
+"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=require("react"),r=(t=e)&&"object"==typeof t&&"default"in t?t.default:t,n=require("react-redux"),a=require("viem"),u=require("@reduxjs/toolkit"),o={valid:!1,blockNumber:void 0,data:void 0},i={valid:!1,result:void 0,loading:!1,syncing:!1,error:!1},l={valid:!0,result:void 0,loading:!0,syncing:!0,error:!1};function c(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=Array(e);r=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function h(){return(h=Object.assign?Object.assign.bind():function(t){for(var e=1;e=0;--u){var o=this.tryEntries[u],i=o.completion;if("root"===o.tryLoc)return a("end");if(o.tryLoc<=this.prev){var l=n.call(o,"catchLoc"),c=n.call(o,"finallyLoc");if(l&&c){if(this.prev=0;--r){var a=this.tryEntries[r];if(a.tryLoc<=this.prev&&n.call(a,"finallyLoc")&&this.prev=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),I(r),v}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var a=n.arg;I(r)}return a}}throw Error("illegal catch attempt")},delegateYield:function(e,r,n){return this.delegate={iterator:_(e),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=t),v}},e}function g(t,e){return(g=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t})(t,e)}function k(t){var e="function"==typeof Map?new Map:void 0;return(k=function(t){if(null===t||!function(t){try{return-1!==Function.toString.call(t).indexOf("[native code]")}catch(e){return"function"==typeof t}}(t))return t;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,r)}function r(){return d(t,arguments,v(this).constructor)}return r.prototype=Object.create(t.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),g(r,t)})(t)}function w(t){var e=t.address+"-"+t.callData;if(t.gasRequired){if(!Number.isSafeInteger(t.gasRequired))throw new Error("Invalid number: "+t.gasRequired);e+="-"+t.gasRequired}return e}function N(t){var e=t.split("-");if(![2,3].includes(e.length))throw new Error("Invalid call key: "+t);return h({address:e[0],callData:e[1]},e[2]?{gasRequired:Number.parseInt(e[2])}:{})}function L(t){var e,r;return null!=(e=null==t||null==(r=t.filter((function(t){return Boolean(t)})))||null==(r=r.map(w))?void 0:r.sort())?e:[]}function x(t){return null!=t&&t.length?t.map((function(t){return N(t)})):null}function E(t,r,n,a){var u=e.useMemo((function(){var e=t.reduce((function(t,e){return e.blockNumber?Math.min(null!=t?t:e.blockNumber,e.blockNumber):t}),void 0);return Math.max(null!=e?e:0,null!=a?a:0)}),[t,a]);return e.useMemo((function(){return t.map((function(t,e){var a="function"==typeof n?n(e):n;return O(t,r,a,u)}))}),[r,n,t,u])}function O(t,e,r,n){if(!t||!t.valid)return i;var u=t.data,o=t.blockNumber;if(!(o&&e&&r&&n))return l;var c=u&&u.length>2,s=o=Math.floor(.95*(null!=(n=r[e].gasRequired)?n:1e6))&&console.warn("A call failed due to requiring "+u.toString()+" vs. allowed "+(null!=(a=r[e].gasRequired)?a:1e6),r[e])})),t.abrupt("return",u);case 11:if(t.prev=11,t.t0=t.catch(1),-32e3!==(l=t.t0).code&&-1===(null==(o=l.message)?void 0:o.indexOf("header not found"))){t.next=18;break}throw new G("header not found for block number "+n);case 18:if(-32603!==l.code&&-1===(null==(i=l.message)?void 0:i.indexOf("execution ran out of gas"))){t.next=28;break}if(!(r.length>1)){t.next=28;break}return c=Math.floor(r.length/2),t.next=24,Promise.all([V(e,r.slice(0,c),n),V(e,r.slice(c,r.length),n)]);case 24:return t.abrupt("return",(s=t.sent)[0].concat(s[1]));case 28:throw console.error("Failed to fetch chunk",l),l;case 30:case"end":return t.stop()}}),t,null,[[1,11]])})))).apply(this,arguments)}function K(t){var r=t.context,a=t.chainId,u=t.latestBlockNumber,o=t.multicallInfo,i=t.isDebug,l=t.listenerOptions,c=r.actions,s=r.reducerPath,d=n.useDispatch();e.useEffect((function(){a&&l&&d(c.updateListenerOptions({chainId:a,listenerOptions:l}))}),[a,l,c,d]);var h,v,m,y,g=n.useSelector((function(t){return t[s]})),k=(m=(v=e.useState(h=g.callListeners))[0],y=v[1],e.useEffect((function(){var t=setTimeout((function(){y(h)}),100);return function(){clearTimeout(t)}}),[h,100]),m),L=e.useRef(),x=e.useMemo((function(){return function(t,e){if(!t||!e)return{};var r=t[e];return r?Object.keys(r).reduce((function(t,e){var n=r[e];return t[e]=Object.keys(n).filter((function(t){var e=parseInt(t);return!(e<=0)&&n[e]>0})).reduce((function(t,e){return Math.min(t,parseInt(e))}),Infinity),t}),{}):{}}(k,a)}),[k,a]),E=e.useMemo((function(){var t=function(t,e,r,n){return r&&n?t[r]?Object.keys(e).filter((function(a){var u=t[r][a];if(!u)return!0;var o=n-(e[a]-1);return!(u.fetchingBlockNumber&&u.fetchingBlockNumber>=o)&&(!u.blockNumber||u.blockNumber0&&a(n.updateMulticallResults({chainId:u,results:s,blockNumber:o})),c.length>0&&(i?r.forEach((function(t,r){t.success||console.debug("Call failed",e[r],t)})):console.debug("Calls errored in fetch",c),a(n.errorFetchingMulticallResults({calls:c,chainId:u,fetchingBlockNumber:o})))}(n,t,e)})).catch((function(e){return function(t,e,r){var n=t.actions,a=t.dispatch,u=t.chainId,o=t.latestBlockNumber;r.isCancelledError?console.debug("Cancelled fetch for blockNumber",o,e,u):(console.error("Failed to fetch multicall chunk",e,u,r),a(n.errorFetchingMulticallResults({calls:e,chainId:u,fetchingBlockNumber:o})))}(n,t,e)})),h}));L.current={blockNumber:u,cancellations:l}}}}),[c,a,o,d,E,u,i]),null}function H(t){return function(e){return r.createElement(K,Object.assign({context:t},e))}}exports.CHUNK_GAS_LIMIT=1e8,exports.CONSERVATIVE_BLOCK_GAS_LIMIT=1e7,exports.DEFAULT_BLOCKS_PER_FETCH=1,exports.DEFAULT_CALL_GAS_REQUIRED=1e6,exports.DEFAULT_CHUNK_GAS_REQUIRED=2e5,exports.INVALID_CALL_STATE=i,exports.INVALID_RESULT=o,exports.LOADING_CALL_STATE=l,exports.NEVER_RELOAD={blocksPerFetch:Infinity},exports.createMulticall=function(t){var e,r=null!=(e=null==t?void 0:t.reducerPath)?e:"multicall",n=function(t){return u.createSlice({name:t,initialState:F,reducers:{addMulticallListeners:function(t,e){var r,n=e.payload,a=n.calls,u=n.chainId,o=n.options.blocksPerFetch,i=t.callListeners?t.callListeners:t.callListeners={};i[u]=null!=(r=i[u])?r:{},a.forEach((function(t){var e,r,n=w(t);i[u][n]=null!=(e=i[u][n])?e:{},i[u][n][o]=(null!=(r=i[u][n][o])?r:0)+1}))},removeMulticallListeners:function(t,e){var r=e.payload,n=r.calls,a=r.chainId,u=r.options.blocksPerFetch,o=t.callListeners?t.callListeners:t.callListeners={};o[a]&&n.forEach((function(t){var e=w(t);o[a][e]&&o[a][e][u]&&(1===o[a][e][u]?delete o[a][e][u]:o[a][e][u]--)}))},fetchingMulticallResults:function(t,e){var r,n=e.payload,a=n.chainId,u=n.fetchingBlockNumber,o=n.calls;t.callResults[a]=null!=(r=t.callResults[a])?r:{},o.forEach((function(e){var r=w(e),n=t.callResults[a][r];if(n){var o;if((null!=(o=n.fetchingBlockNumber)?o:0)>=u)return;t.callResults[a][r].fetchingBlockNumber=u}else t.callResults[a][r]={fetchingBlockNumber:u}}))},errorFetchingMulticallResults:function(t,e){var r,n=e.payload,a=n.chainId,u=n.fetchingBlockNumber,o=n.calls;t.callResults[a]=null!=(r=t.callResults[a])?r:{},o.forEach((function(e){var r=w(e),n=t.callResults[a][r];n&&"number"==typeof n.fetchingBlockNumber&&n.fetchingBlockNumber<=u&&(delete n.fetchingBlockNumber,n.data=null,n.blockNumber=u)}))},updateMulticallResults:function(t,e){var r,n=e.payload,a=n.chainId,u=n.results,o=n.blockNumber;t.callResults[a]=null!=(r=t.callResults[a])?r:{},Object.keys(u).forEach((function(e){var r,n=t.callResults[a][e];(null!=(r=null==n?void 0:n.blockNumber)?r:0)>o||(null==n?void 0:n.data)===u[e]&&(null==n?void 0:n.blockNumber)===o||(t.callResults[a][e]={data:u[e],blockNumber:o})}))},updateListenerOptions:function(t,e){var r,n=e.payload,a=n.chainId,u=n.listenerOptions;t.listenerOptions=null!=(r=t.listenerOptions)?r:{},t.listenerOptions[a]=u}}})}(r),a=n.actions,o={reducerPath:r,actions:a};return{reducerPath:r,reducer:n.reducer,actions:a,hooks:{useMultipleContractSingleData:function(){for(var t=arguments.length,e=new Array(t),r=0;r) {\n return (\n calls\n ?.filter((c): c is Call => Boolean(c))\n ?.map(toCallKey)\n ?.sort() ?? []\n )\n}\n\nexport function callKeysToCalls(callKeys: string[]) {\n if (!callKeys?.length) return null\n return callKeys.map((key) => parseCallKey(key))\n}\n","import { useMemo } from 'react'\nimport { INVALID_CALL_STATE, LOADING_CALL_STATE } from '../constants'\nimport type { CallResult, CallState, CallStateResult } from '../types'\nimport { AbiFunction, decodeFunctionResult } from 'viem'\n\n// Converts CallResult[] to CallState[], only updating if call states have changed.\n// Ensures that CallState results remain referentially stable when unchanged, preventing\n// spurious re-renders which would otherwise occur because mapping always creates a new object.\nexport function useCallStates(\n results: CallResult[],\n contractInterface: AbiFunction[] | undefined,\n fragment: ((i: number) => string | undefined) | string | undefined,\n latestBlockNumber: number | undefined\n): CallState[] {\n // Avoid refreshing the results with every changing block number (eg latestBlockNumber).\n // Instead, only refresh the results if they need to be synced - if there is a result which is stale, for which blockNumber < latestBlockNumber.\n const syncingBlockNumber = useMemo(() => {\n const lowestBlockNumber = results.reduce(\n (memo, result) => (result.blockNumber ? Math.min(memo ?? result.blockNumber, result.blockNumber) : memo),\n undefined\n )\n return Math.max(lowestBlockNumber ?? 0, latestBlockNumber ?? 0)\n }, [results, latestBlockNumber])\n\n return useMemo(() => {\n return results.map((result, i) => {\n const resultFragment = typeof fragment === 'function' ? fragment(i) : fragment\n return toCallState(result, contractInterface, resultFragment, syncingBlockNumber)\n })\n }, [contractInterface, fragment, results, syncingBlockNumber])\n}\n\nexport function toCallState(\n callResult: CallResult | undefined,\n contractInterface: AbiFunction[] | undefined,\n fragment: string | undefined,\n syncingBlockNumber: number | undefined\n): CallState {\n if (!callResult || !callResult.valid) {\n return INVALID_CALL_STATE\n }\n\n const { data, blockNumber } = callResult\n if (!blockNumber || !contractInterface || !fragment || !syncingBlockNumber) {\n return LOADING_CALL_STATE\n }\n\n const success = data && data.length > 2\n const syncing = blockNumber < syncingBlockNumber\n let result: CallStateResult | undefined = undefined\n if (success && data) {\n try {\n result = (decodeFunctionResult as any)({\n abi: contractInterface,\n functionName: fragment,\n data: data as any,\n }) as any\n } catch (error) {\n console.debug('Result data parsing failed', fragment, data)\n return {\n valid: true,\n loading: false,\n error: true,\n syncing,\n result,\n }\n }\n }\n return {\n valid: true,\n loading: false,\n syncing,\n result,\n error: !success,\n }\n}\n","export type MethodArg = string | number | BigInt\nexport type MethodArgs = Array\n\nexport function isMethodArg(x: unknown): x is MethodArg {\n return (x === null || x === undefined) ? false : typeof BigInt(x as any) === 'bigint' || ['string', 'number'].indexOf(typeof x) !== -1\n}\n\nexport function isValidMethodArgs(x: unknown): x is MethodArgs | undefined {\n return (\n x === undefined ||\n (Array.isArray(x) && x.every((xi) => isMethodArg(xi) || (Array.isArray(xi) && xi.every(isMethodArg))))\n )\n}\n","import { useCallback, useEffect, useMemo, useRef } from 'react'\nimport { batch, useDispatch, useSelector } from 'react-redux'\nimport { INVALID_CALL_STATE, INVALID_RESULT, DEFAULT_BLOCKS_PER_FETCH } from './constants'\nimport type { MulticallContext } from './context'\nimport type {\n Call,\n CallResult,\n CallState,\n ContractInfo,\n ListenerOptions,\n ListenerOptionsWithGas,\n WithMulticallState,\n} from './types'\nimport { callKeysToCalls, callsToCallKeys, toCallKey } from './utils/callKeys'\nimport { toCallState, useCallStates } from './utils/callState'\nimport { isValidMethodArgs, MethodArg } from './validation'\nimport { AbiFunction, encodeFunctionData, getAbiItem } from 'viem'\n\ntype OptionalMethodInputs = Array | undefined\n\n// the lowest level call for subscribing to contract data\nexport function useCallsDataSubscription(\n context: MulticallContext,\n chainId: number | undefined,\n calls: Array,\n listenerOptions?: ListenerOptions\n): CallResult[] {\n const { reducerPath, actions } = context\n const callResults = useSelector((state: WithMulticallState) => state[reducerPath].callResults)\n const defaultListenerOptions = useSelector((state: WithMulticallState) => state[reducerPath].listenerOptions)\n const dispatch = useDispatch()\n const serializedCallKeys: string = useMemo(() => JSON.stringify(callsToCallKeys(calls)), [calls])\n\n // update listeners when there is an actual change that persists for at least 100ms\n useEffect(() => {\n const callKeys: string[] = JSON.parse(serializedCallKeys)\n const calls = callKeysToCalls(callKeys)\n if (!chainId || !calls) return\n const blocksPerFetchFromState = (defaultListenerOptions ?? {})[chainId]?.blocksPerFetch\n const blocksPerFetchForChain =\n listenerOptions?.blocksPerFetch ?? blocksPerFetchFromState ?? DEFAULT_BLOCKS_PER_FETCH\n\n dispatch(\n actions.addMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n\n return () => {\n dispatch(\n actions.removeMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n }\n }, [actions, chainId, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions])\n\n const lastResults = useRef([])\n return useMemo(() => {\n let isChanged = lastResults.current.length !== calls.length\n\n // Construct results using a for-loop to handle sparse arrays.\n // Array.prototype.map would skip empty entries.\n let results: CallResult[] = []\n for (let i = 0; i < calls.length; ++i) {\n const call = calls[i]\n let result = INVALID_RESULT\n if (chainId && call) {\n const callResult = callResults[chainId]?.[toCallKey(call)]\n result = {\n valid: true,\n data: callResult?.data && callResult.data !== '0x' ? callResult.data : undefined,\n blockNumber: callResult?.blockNumber,\n }\n }\n\n isChanged = isChanged || !areCallResultsEqual(result, lastResults.current[i])\n results.push(result)\n }\n\n // Force the results to be referentially stable if they have not changed.\n // This is necessary because *all* callResults are passed as deps when initially memoizing the results.\n if (isChanged) {\n lastResults.current = results\n }\n return lastResults.current\n }, [callResults, calls, chainId])\n}\n\nfunction areCallResultsEqual(a: CallResult, b: CallResult) {\n return a.valid === b.valid && a.data === b.data && a.blockNumber === b.blockNumber\n}\n\n// Similar to useCallsDataSubscription above but for subscribing to\n// calls to multiple chains at once\nfunction useMultichainCallsDataSubscription(\n context: MulticallContext,\n chainToCalls: Record>,\n listenerOptions?: ListenerOptions\n): Record {\n const { reducerPath, actions } = context\n const callResults = useSelector((state: WithMulticallState) => state[reducerPath].callResults)\n const defaultListenerOptions = useSelector((state: WithMulticallState) => state[reducerPath].listenerOptions)\n const dispatch = useDispatch()\n\n const serializedCallKeys: string = useMemo(() => {\n const sortedChainIds = getChainIds(chainToCalls).sort()\n const chainCallKeysTuple = sortedChainIds.map((chainId) => {\n const calls = chainToCalls[chainId]\n const callKeys = callsToCallKeys(calls)\n // Note, using a tuple to ensure consistent order when serialized\n return [chainId, callKeys]\n })\n return JSON.stringify(chainCallKeysTuple)\n }, [chainToCalls])\n\n useEffect(() => {\n const chainCallKeysTuples: Array<[number, string[]]> = JSON.parse(serializedCallKeys)\n if (!chainCallKeysTuples?.length) return\n\n batch(() => {\n for (const [chainId, callKeys] of chainCallKeysTuples) {\n const calls = callKeysToCalls(callKeys)\n if (!calls?.length) continue\n const blocksPerFetchFromState = (defaultListenerOptions ?? {})[chainId]?.blocksPerFetch\n const blocksPerFetchForChain =\n listenerOptions?.blocksPerFetch ?? blocksPerFetchFromState ?? DEFAULT_BLOCKS_PER_FETCH\n\n dispatch(\n actions.addMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n }\n })\n\n return () => {\n batch(() => {\n for (const [chainId, callKeys] of chainCallKeysTuples) {\n const calls = callKeysToCalls(callKeys)\n if (!calls?.length) continue\n const blocksPerFetchFromState = (defaultListenerOptions ?? {})[chainId]?.blocksPerFetch\n const blocksPerFetchForChain =\n listenerOptions?.blocksPerFetch ?? blocksPerFetchFromState ?? DEFAULT_BLOCKS_PER_FETCH\n dispatch(\n actions.removeMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n }\n })\n }\n }, [actions, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions])\n\n return useMemo(\n () =>\n getChainIds(chainToCalls).reduce((result, chainId) => {\n const calls = chainToCalls[chainId]\n result[chainId] = calls.map((call) => {\n if (!chainId || !call) return INVALID_RESULT\n const result = callResults[chainId]?.[toCallKey(call)]\n const data = result?.data && result.data !== '0x' ? result.data : undefined\n return { valid: true, data, blockNumber: result?.blockNumber }\n })\n return result\n }, {} as Record),\n [callResults, chainToCalls]\n )\n}\n\n// formats many calls to a single function on a single contract, with the function name and inputs specified\nexport function useSingleContractMultipleData(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n contract: ContractInfo | null | undefined,\n methodName: string,\n callInputs: OptionalMethodInputs[],\n options?: Partial\n): CallState[] {\n const { gasRequired } = options ?? {}\n\n // Create ethers function fragment\n const fragment = useMemo(\n () => contract && ((getAbiItem as any)({ abi: contract.abi, name: methodName } as any) as any)?.name,\n [contract, methodName]\n )\n\n // Get encoded call data. Note can't use useCallData below b.c. this is for a list of CallInputs\n const callDatas = useMemo(() => {\n if (!contract || !fragment) return []\n return callInputs.map((callInput) =>\n isValidMethodArgs(callInput)\n ? (encodeFunctionData as any)({\n abi: contract.abi,\n functionName: fragment,\n args: callInput,\n })\n : undefined\n )\n }, [callInputs, contract, fragment])\n\n // Create call objects\n const calls = useMemo(() => {\n if (!contract) return []\n return callDatas.map((callData) => {\n if (!callData) return undefined\n return {\n address: contract.address,\n callData,\n gasRequired,\n }\n })\n }, [contract, callDatas, gasRequired])\n\n // Subscribe to call data\n const results = useCallsDataSubscription(context, chainId, calls, options as ListenerOptions)\n return useCallStates(results, contract?.abi, fragment, latestBlockNumber)\n}\n\nexport function useMultipleContractSingleData(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n addresses: (string | undefined)[],\n contractInterface: AbiFunction[],\n methodName: string,\n callInputs?: OptionalMethodInputs,\n options?: Partial\n): CallState[] {\n const { gasRequired } = options ?? {}\n\n const { fragment, callData } = useCallData(methodName, contractInterface, callInputs)\n\n // Create call objects\n const calls = useMemo(() => {\n if (!callData) return []\n return addresses.map((address) => {\n if (!address) return undefined\n return { address, callData, gasRequired }\n })\n }, [addresses, callData, gasRequired])\n\n // Subscribe to call data\n const results = useCallsDataSubscription(context, chainId, calls, options as ListenerOptions)\n return useCallStates(results, contractInterface, fragment, latestBlockNumber)\n}\n\nexport function useSingleCallResult(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n contract: ContractInfo | null | undefined,\n methodName: string,\n inputs?: OptionalMethodInputs,\n options?: Partial\n): CallState {\n const callInputs = useMemo(() => [inputs], [inputs])\n return (\n useSingleContractMultipleData(context, chainId, latestBlockNumber, contract, methodName, callInputs, options)[0] ??\n INVALID_CALL_STATE\n )\n}\n\n// formats many calls to any number of functions on a single contract, with only the calldata specified\nexport function useSingleContractWithCallData(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n contract: ContractInfo | null | undefined,\n callDatas: string[],\n options?: Partial\n): CallState[] {\n const { gasRequired } = options ?? {}\n\n // Create call objects\n const calls = useMemo(() => {\n if (!contract) return []\n return callDatas.map((callData) => ({\n address: contract.address,\n callData,\n gasRequired,\n }))\n }, [callDatas, contract, gasRequired])\n\n // Subscribe to call data\n const results = useCallsDataSubscription(context, chainId, calls, options as ListenerOptions)\n const fragment = useCallback(\n (i: number) => ((getAbiItem as any)({ abi: contract?.abi as any, name: callDatas[i].substring(0, 10) }) as any)?.name,\n [callDatas, contract]\n )\n return useCallStates(results, contract?.abi, fragment, latestBlockNumber)\n}\n\n// Similar to useMultipleContractSingleData but instead of multiple contracts on one chain,\n// this is for querying compatible contracts on multiple chains\nexport function useMultiChainMultiContractSingleData(\n context: MulticallContext,\n chainToBlockNumber: Record,\n chainToAddresses: Record>,\n contractInterface: AbiFunction[],\n methodName: string,\n callInputs?: OptionalMethodInputs,\n options?: Partial\n): Record {\n const { gasRequired } = options ?? {}\n\n const { fragment, callData } = useCallData(methodName, contractInterface, callInputs)\n\n // Create call objects\n const chainToCalls = useMemo(() => {\n if (!callData || !chainToAddresses) return {}\n return getChainIds(chainToAddresses).reduce((result, chainId) => {\n const addresses = chainToAddresses[chainId]\n const calls = addresses.map((address) => {\n if (!address) return undefined\n return { address, callData, gasRequired }\n })\n result[chainId] = calls\n return result\n }, {} as Record>)\n }, [chainToAddresses, callData, gasRequired])\n\n // Subscribe to call data\n const chainIdToResults = useMultichainCallsDataSubscription(context, chainToCalls, options as ListenerOptions)\n\n // TODO(WEB-2097): Multichain states are not referentially stable, because they cannot use the\n // same codepath (eg useCallStates).\n return useMemo(() => {\n return getChainIds(chainIdToResults).reduce((combinedResults, chainId) => {\n const latestBlockNumber = chainToBlockNumber?.[chainId]\n const results = chainIdToResults[chainId]\n combinedResults[chainId] = results.map((result) =>\n toCallState(result, contractInterface, fragment, latestBlockNumber)\n )\n return combinedResults\n }, {} as Record)\n }, [fragment, contractInterface, chainIdToResults, chainToBlockNumber])\n}\n\n// Similar to useSingleCallResult but instead of one contract on one chain,\n// this is for querying a contract on multiple chains\nexport function useMultiChainSingleContractSingleData(\n context: MulticallContext,\n chainToBlockNumber: Record,\n chainToAddress: Record,\n contractInterface: AbiFunction[],\n methodName: string,\n callInputs?: OptionalMethodInputs,\n options?: Partial\n): Record {\n // This hook uses the more flexible useMultiChainMultiContractSingleData internally,\n // but transforms the inputs and outputs for convenience\n const chainIdToAddresses = useMemo(() => {\n return getChainIds(chainToAddress).reduce((result, chainId) => {\n result[chainId] = [chainToAddress[chainId]]\n return result\n }, {} as Record>)\n }, [chainToAddress])\n\n const multiContractResults = useMultiChainMultiContractSingleData(\n context,\n chainToBlockNumber,\n chainIdToAddresses,\n contractInterface,\n methodName,\n callInputs,\n options\n )\n\n return useMemo(() => {\n return getChainIds(chainToAddress).reduce((result, chainId) => {\n result[chainId] = multiContractResults[chainId]?.[0] ?? INVALID_CALL_STATE\n return result\n }, {} as Record)\n }, [chainToAddress, multiContractResults])\n}\n\nfunction useCallData(\n methodName: string,\n contractInterface: AbiFunction[] | null | undefined,\n callInputs: OptionalMethodInputs | undefined\n) {\n // Create ethers function fragment\n const fragment = useMemo(\n () => contractInterface && ((getAbiItem as any)({ abi: contractInterface as any, name: methodName }) as any)?.name,\n [contractInterface, methodName]\n )\n // Get encoded call data\n const callData: string | undefined = useMemo(\n () =>\n fragment && isValidMethodArgs(callInputs)\n ? (encodeFunctionData as any)({\n abi: contractInterface as any,\n functionName: fragment,\n args: callInputs as unknown as any[],\n })\n : undefined,\n [callInputs, contractInterface, fragment]\n )\n return { fragment, callData }\n}\n\nfunction getChainIds(chainIdMap: Record) {\n return Object.keys(chainIdMap).map((c) => parseInt(c, 10))\n}\n","import { createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport {\n MulticallFetchingPayload,\n MulticallListenerPayload,\n MulticallResultsPayload,\n MulticallState,\n MulticallListenerOptionsPayload,\n} from './types'\nimport { toCallKey } from './utils/callKeys'\n\nconst initialState: MulticallState = {\n callResults: {},\n}\n\nexport function createMulticallSlice(reducerPath: string) {\n return createSlice({\n name: reducerPath,\n initialState,\n reducers: {\n addMulticallListeners: (state, action: PayloadAction) => {\n const {\n calls,\n chainId,\n options: { blocksPerFetch },\n } = action.payload\n const listeners: MulticallState['callListeners'] = state.callListeners\n ? state.callListeners\n : (state.callListeners = {})\n listeners[chainId] = listeners[chainId] ?? {}\n calls.forEach((call) => {\n const callKey = toCallKey(call)\n listeners[chainId][callKey] = listeners[chainId][callKey] ?? {}\n listeners[chainId][callKey][blocksPerFetch] = (listeners[chainId][callKey][blocksPerFetch] ?? 0) + 1\n })\n },\n\n removeMulticallListeners: (state, action: PayloadAction) => {\n const {\n calls,\n chainId,\n options: { blocksPerFetch },\n } = action.payload\n const listeners: MulticallState['callListeners'] = state.callListeners\n ? state.callListeners\n : (state.callListeners = {})\n\n if (!listeners[chainId]) return\n calls.forEach((call) => {\n const callKey = toCallKey(call)\n if (!listeners[chainId][callKey]) return\n if (!listeners[chainId][callKey][blocksPerFetch]) return\n\n if (listeners[chainId][callKey][blocksPerFetch] === 1) {\n delete listeners[chainId][callKey][blocksPerFetch]\n } else {\n listeners[chainId][callKey][blocksPerFetch]--\n }\n })\n },\n\n fetchingMulticallResults: (state, action: PayloadAction) => {\n const { chainId, fetchingBlockNumber, calls } = action.payload\n state.callResults[chainId] = state.callResults[chainId] ?? {}\n calls.forEach((call) => {\n const callKey = toCallKey(call)\n const current = state.callResults[chainId][callKey]\n if (!current) {\n state.callResults[chainId][callKey] = {\n fetchingBlockNumber,\n }\n } else {\n if ((current.fetchingBlockNumber ?? 0) >= fetchingBlockNumber) return\n state.callResults[chainId][callKey].fetchingBlockNumber = fetchingBlockNumber\n }\n })\n },\n\n errorFetchingMulticallResults: (state, action: PayloadAction) => {\n const { chainId, fetchingBlockNumber, calls } = action.payload\n state.callResults[chainId] = state.callResults[chainId] ?? {}\n calls.forEach((call) => {\n const callKey = toCallKey(call)\n const current = state.callResults[chainId][callKey]\n if (!current || typeof current.fetchingBlockNumber !== 'number') return // only should be dispatched if we are already fetching\n if (current.fetchingBlockNumber <= fetchingBlockNumber) {\n delete current.fetchingBlockNumber\n current.data = null\n current.blockNumber = fetchingBlockNumber\n }\n })\n },\n\n updateMulticallResults: (state, action: PayloadAction) => {\n const { chainId, results, blockNumber } = action.payload\n state.callResults[chainId] = state.callResults[chainId] ?? {}\n Object.keys(results).forEach((callKey) => {\n const current = state.callResults[chainId][callKey]\n if ((current?.blockNumber ?? 0) > blockNumber) return\n if (current?.data === results[callKey] && current?.blockNumber === blockNumber) return\n state.callResults[chainId][callKey] = {\n data: results[callKey],\n blockNumber,\n }\n })\n },\n\n updateListenerOptions: (state, action: PayloadAction) => {\n const { chainId, listenerOptions } = action.payload\n state.listenerOptions = state.listenerOptions ?? {}\n state.listenerOptions[chainId] = listenerOptions\n },\n },\n })\n}\n\nexport type MulticallActions = ReturnType['actions']\n","// TODO de-duplicate this file with web interface\n// https://github.com/Uniswap/interface/blob/main/src/utils/retry.ts\n\nfunction wait(ms: number): Promise {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction waitRandom(min: number, max: number): Promise {\n return wait(min + Math.round(Math.random() * Math.max(0, max - min)))\n}\n\n/**\n * This error is thrown if the function is cancelled before completing\n */\nclass CancelledError extends Error {\n public isCancelledError: true = true\n constructor() {\n super('Cancelled')\n }\n}\n\n/**\n * Throw this error if the function should retry\n */\nexport class RetryableError extends Error {\n public isRetryableError: true = true\n}\n\nexport interface RetryOptions {\n n: number\n minWait: number\n maxWait: number\n}\n\n/**\n * Retries the function that returns the promise until the promise successfully resolves up to n retries\n * @param fn function to retry\n * @param n how many times to retry\n * @param minWait min wait between retries in ms\n * @param maxWait max wait between retries in ms\n */\nexport function retry(\n fn: () => Promise,\n { n, minWait, maxWait }: RetryOptions\n): { promise: Promise; cancel: () => void } {\n let completed = false\n let rejectCancelled: (error: Error) => void\n const promise = new Promise(async (resolve, reject) => {\n rejectCancelled = reject\n while (true) {\n let result: T\n try {\n result = await fn()\n if (!completed) {\n resolve(result)\n completed = true\n }\n break\n } catch (error) {\n if (completed) {\n break\n }\n if (n <= 0 || !(error as any).isRetryableError) {\n reject(error)\n completed = true\n break\n }\n n--\n }\n await waitRandom(minWait, maxWait)\n }\n })\n return {\n promise,\n cancel: () => {\n if (completed) return\n completed = true\n rejectCancelled(new CancelledError())\n },\n }\n}\n","export default [\n {\n inputs: [],\n name: 'getCurrentBlockTimestamp',\n outputs: [\n {\n internalType: 'uint256',\n name: 'timestamp',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'addr',\n type: 'address',\n },\n ],\n name: 'getEthBalance',\n outputs: [\n {\n internalType: 'uint256',\n name: 'balance',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n components: [\n {\n internalType: 'address',\n name: 'target',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'gasLimit',\n type: 'uint256',\n },\n {\n internalType: 'bytes',\n name: 'callData',\n type: 'bytes',\n },\n ],\n internalType: 'struct PancakeInterfaceMulticall.Call[]',\n name: 'calls',\n type: 'tuple[]',\n },\n ],\n name: 'multicall',\n outputs: [\n {\n internalType: 'uint256',\n name: 'blockNumber',\n type: 'uint256',\n },\n {\n components: [\n {\n internalType: 'bool',\n name: 'success',\n type: 'bool',\n },\n {\n internalType: 'uint256',\n name: 'gasUsed',\n type: 'uint256',\n },\n {\n internalType: 'bytes',\n name: 'returnData',\n type: 'bytes',\n },\n ],\n internalType: 'struct PancakeInterfaceMulticall.Result[]',\n name: 'returnData',\n type: 'tuple[]',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n] as const\n","import React, { Dispatch, useEffect, useMemo, useRef } from 'react'\nimport { useDispatch, useSelector } from 'react-redux'\nimport { CHUNK_GAS_LIMIT, DEFAULT_CALL_GAS_REQUIRED } from './constants'\nimport type { MulticallContext } from './context'\nimport type { MulticallActions } from './slice'\nimport type { Call, MulticallState, WithMulticallState, ListenerOptions, MulticallInfo } from './types'\nimport { parseCallKey, toCallKey } from './utils/callKeys'\nimport chunkCalls from './utils/chunkCalls'\nimport { retry, RetryableError } from './utils/retry'\nimport useDebounce from './utils/useDebounce'\nimport IMulticallABI from './abi/InterfaceMulticall'\n\nconst FETCH_RETRY_CONFIG = {\n n: Infinity,\n minWait: 1000,\n maxWait: 2500,\n}\n\n/**\n * Fetches a chunk of calls, enforcing a minimum block number constraint\n * @param multicall multicall contract to fetch against\n * @param chunk chunk of calls to make\n * @param blockNumber block number passed as the block tag in the eth_call\n */\nasync function fetchChunk(\n multicallInfo: MulticallInfo,\n chunk: Call[],\n blockNumber: number,\n isDebug?: boolean\n): Promise {\n console.debug('Fetching chunk', chunk, blockNumber, chunk.map((obj) => ({\n target: obj.address,\n callData: obj.callData,\n gasLimit: obj.gasRequired ?? DEFAULT_CALL_GAS_REQUIRED,\n })))\n try {\n const {\n result: [, returnData], // [blockNumber, results]\n }: { result: [any, any[]] } = await (multicallInfo.provider as any).simulateContract({\n abi: IMulticallABI,\n address: multicallInfo.address,\n functionName: 'multicall',\n args: [\n chunk.map((obj) => ({\n target: obj.address,\n callData: obj.callData,\n gasLimit: obj.gasRequired ?? DEFAULT_CALL_GAS_REQUIRED,\n }))\n ],\n // we aren't passing through the block gas limit we used to create the chunk, because it causes a problem with the integ tests\n blockNumber: BigInt(blockNumber)\n }\n )\n if (isDebug) {\n returnData.forEach(({ gasUsed, returnData, success }, i) => {\n if (\n !success &&\n returnData.length === 2 &&\n gasUsed >= (Math.floor((chunk[i].gasRequired ?? DEFAULT_CALL_GAS_REQUIRED) * 0.95))\n ) {\n console.warn(\n `A call failed due to requiring ${gasUsed.toString()} vs. allowed ${chunk[i].gasRequired ?? DEFAULT_CALL_GAS_REQUIRED\n }`,\n chunk[i]\n )\n }\n })\n }\n\n return returnData\n } catch (e) {\n const error = e as any\n if (error.code === -32000 || error.message?.indexOf('header not found') !== -1) {\n throw new RetryableError(`header not found for block number ${blockNumber}`)\n } else if (error.code === -32603 || error.message?.indexOf('execution ran out of gas') !== -1) {\n if (chunk.length > 1) {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Splitting a chunk in 2', chunk)\n }\n const half = Math.floor(chunk.length / 2)\n const [c0, c1] = await Promise.all([\n fetchChunk(multicallInfo, chunk.slice(0, half), blockNumber),\n fetchChunk(multicallInfo, chunk.slice(half, chunk.length), blockNumber),\n ])\n return c0.concat(c1)\n }\n }\n console.error('Failed to fetch chunk', error)\n throw error\n }\n}\n\n/**\n * From the current all listeners state, return each call key mapped to the\n * minimum number of blocks per fetch. This is how often each key must be fetched.\n * @param allListeners the all listeners state\n * @param chainId the current chain id\n */\nexport function activeListeningKeys(\n allListeners: MulticallState['callListeners'],\n chainId?: number\n): { [callKey: string]: number } {\n if (!allListeners || !chainId) return {}\n const listeners = allListeners[chainId]\n if (!listeners) return {}\n\n return Object.keys(listeners).reduce<{ [callKey: string]: number }>((memo, callKey) => {\n const keyListeners = listeners[callKey]\n\n memo[callKey] = Object.keys(keyListeners)\n .filter((key) => {\n const blocksPerFetch = parseInt(key)\n if (blocksPerFetch <= 0) return false\n return keyListeners[blocksPerFetch] > 0\n })\n .reduce((previousMin, current) => {\n return Math.min(previousMin, parseInt(current))\n }, Infinity)\n return memo\n }, {})\n}\n\n/**\n * Return the keys that need to be refetched\n * @param callResults current call result state\n * @param listeningKeys each call key mapped to how old the data can be in blocks\n * @param chainId the current chain id\n * @param latestBlockNumber the latest block number\n */\nexport function outdatedListeningKeys(\n callResults: MulticallState['callResults'],\n listeningKeys: { [callKey: string]: number },\n chainId: number | undefined,\n latestBlockNumber: number | undefined\n): string[] {\n if (!chainId || !latestBlockNumber) return []\n const results = callResults[chainId]\n // no results at all, load everything\n if (!results) return Object.keys(listeningKeys)\n\n return Object.keys(listeningKeys).filter((callKey) => {\n const blocksPerFetch = listeningKeys[callKey]\n\n const data = callResults[chainId][callKey]\n // no data, must fetch\n if (!data) return true\n\n const minDataBlockNumber = latestBlockNumber - (blocksPerFetch - 1)\n\n // already fetching it for a recent enough block, don't refetch it\n if (data.fetchingBlockNumber && data.fetchingBlockNumber >= minDataBlockNumber) return false\n\n // if data is older than minDataBlockNumber, fetch it\n return !data.blockNumber || data.blockNumber < minDataBlockNumber\n })\n}\n\ninterface FetchChunkContext {\n actions: MulticallActions\n dispatch: Dispatch\n chainId: number\n latestBlockNumber: number\n isDebug?: boolean\n}\n\nfunction onFetchChunkSuccess(\n context: FetchChunkContext,\n chunk: Call[],\n result: readonly { success: boolean; returnData: string }[]\n) {\n const { actions, dispatch, chainId, latestBlockNumber, isDebug } = context\n\n // split the returned slice into errors and results\n const { erroredCalls, results } = chunk.reduce<{\n erroredCalls: Call[]\n results: { [callKey: string]: string | null }\n }>(\n (memo, call, i) => {\n if (result[i].success) {\n memo.results[toCallKey(call)] = result[i].returnData ?? null\n } else {\n memo.erroredCalls.push(call)\n }\n return memo\n },\n { erroredCalls: [], results: {} }\n )\n\n // dispatch any new results\n if (Object.keys(results).length > 0)\n dispatch(\n actions.updateMulticallResults({\n chainId,\n results,\n blockNumber: latestBlockNumber,\n })\n )\n\n // dispatch any errored calls\n if (erroredCalls.length > 0) {\n if (isDebug) {\n result.forEach((returnData, ix) => {\n if (!returnData.success) {\n console.debug('Call failed', chunk[ix], returnData)\n }\n })\n } else {\n console.debug('Calls errored in fetch', erroredCalls)\n }\n dispatch(\n actions.errorFetchingMulticallResults({\n calls: erroredCalls,\n chainId,\n fetchingBlockNumber: latestBlockNumber,\n })\n )\n }\n}\n\nfunction onFetchChunkFailure(context: FetchChunkContext, chunk: Call[], error: any) {\n const { actions, dispatch, chainId, latestBlockNumber } = context\n\n if (error.isCancelledError) {\n console.debug('Cancelled fetch for blockNumber', latestBlockNumber, chunk, chainId)\n return\n }\n console.error('Failed to fetch multicall chunk', chunk, chainId, error)\n dispatch(\n actions.errorFetchingMulticallResults({\n calls: chunk,\n chainId,\n fetchingBlockNumber: latestBlockNumber,\n })\n )\n}\n\nexport interface UpdaterProps {\n context: MulticallContext\n chainId: number | undefined // For now, one updater is required for each chainId to be watched\n latestBlockNumber: number | undefined\n multicallInfo: MulticallInfo\n isDebug?: boolean\n listenerOptions?: ListenerOptions\n}\n\nfunction Updater(props: UpdaterProps): null {\n const { context, chainId, latestBlockNumber, multicallInfo, isDebug, listenerOptions } = props\n const { actions, reducerPath } = context\n const dispatch = useDispatch()\n\n // set user configured listenerOptions in state for given chain ID.\n useEffect(() => {\n if (chainId && listenerOptions) {\n dispatch(actions.updateListenerOptions({ chainId, listenerOptions }))\n }\n }, [chainId, listenerOptions, actions, dispatch])\n\n const state = useSelector((state: WithMulticallState) => state[reducerPath])\n\n // wait for listeners to settle before triggering updates\n const debouncedListeners = useDebounce(state.callListeners, 100)\n const cancellations = useRef<{ blockNumber: number; cancellations: (() => void)[] }>()\n\n const listeningKeys: { [callKey: string]: number } = useMemo(() => {\n return activeListeningKeys(debouncedListeners, chainId)\n }, [debouncedListeners, chainId])\n\n const serializedOutdatedCallKeys = useMemo(() => {\n const outdatedCallKeys = outdatedListeningKeys(state.callResults, listeningKeys, chainId, latestBlockNumber)\n return JSON.stringify(outdatedCallKeys.sort())\n }, [chainId, state.callResults, listeningKeys, latestBlockNumber])\n\n useEffect(() => {\n if (!latestBlockNumber || !chainId || !multicallInfo) return\n\n const outdatedCallKeys: string[] = JSON.parse(serializedOutdatedCallKeys)\n if (outdatedCallKeys.length === 0) return\n const calls = outdatedCallKeys.map((key) => parseCallKey(key))\n\n const chunkedCalls = chunkCalls(calls, CHUNK_GAS_LIMIT)\n\n if (cancellations.current && cancellations.current.blockNumber !== latestBlockNumber) {\n cancellations.current.cancellations.forEach((c) => c())\n }\n\n dispatch(\n actions.fetchingMulticallResults({\n calls,\n chainId,\n fetchingBlockNumber: latestBlockNumber,\n })\n )\n\n const fetchChunkContext = {\n actions,\n dispatch,\n chainId,\n latestBlockNumber,\n isDebug,\n }\n // Execute fetches and gather cancellation callbacks\n const newCancellations = chunkedCalls.map((chunk) => {\n const { cancel, promise } = retry(\n () => fetchChunk(multicallInfo, chunk, latestBlockNumber, isDebug),\n FETCH_RETRY_CONFIG\n )\n promise\n .then((result) => onFetchChunkSuccess(fetchChunkContext, chunk, result))\n .catch((error) => onFetchChunkFailure(fetchChunkContext, chunk, error))\n return cancel\n })\n\n cancellations.current = {\n blockNumber: latestBlockNumber,\n cancellations: newCancellations,\n }\n }, [actions, chainId, multicallInfo, dispatch, serializedOutdatedCallKeys, latestBlockNumber, isDebug])\n\n return null\n}\n\nexport function createUpdater(context: MulticallContext) {\n const UpdaterContextBound = (props: Omit) => {\n return \n }\n return UpdaterContextBound\n}\n","// TODO de-duplicate this file with web interface\n// https://github.com/Uniswap/interface/blob/main/src/hooks/useDebounce.ts\n\nimport { useEffect, useState } from 'react'\n\n// modified from https://usehooks.com/useDebounce/\nexport default function useDebounce(value: T, delay: number): T {\n const [debouncedValue, setDebouncedValue] = useState(value)\n\n useEffect(() => {\n // Update debounced value after delay\n const handler = setTimeout(() => {\n setDebouncedValue(value)\n }, delay)\n\n // Cancel the timeout if value changes (also on delay change or unmount)\n // This is how we prevent debounced value from updating if value is changed ...\n // .. within the delay period. Timeout gets cleared and restarted.\n return () => {\n clearTimeout(handler)\n }\n }, [value, delay])\n\n return debouncedValue\n}\n","import { DEFAULT_CHUNK_GAS_REQUIRED } from '../constants'\n\ninterface Bin {\n calls: T[]\n cumulativeGasLimit: number\n}\n\n/**\n * Tries to pack a list of items into as few bins as possible using the first-fit bin packing algorithm\n * @param calls the calls to chunk\n * @param chunkGasLimit the gas limit of any one chunk of calls, i.e. bin capacity\n * @param defaultGasRequired the default amount of gas an individual call should cost if not specified\n */\nexport default function chunkCalls(\n calls: T[],\n chunkGasLimit: number,\n defaultGasRequired: number = DEFAULT_CHUNK_GAS_REQUIRED\n): T[][] {\n return (\n calls\n // first sort by gas required\n .sort((c1, c2) => (c2.gasRequired ?? defaultGasRequired) - (c1.gasRequired ?? defaultGasRequired))\n // then bin the calls according to the first fit algorithm\n .reduce[]>((bins, call) => {\n const gas = call.gasRequired ?? defaultGasRequired\n for (const bin of bins) {\n if (bin.cumulativeGasLimit + gas <= chunkGasLimit) {\n bin.calls.push(call)\n bin.cumulativeGasLimit += gas\n return bins\n }\n }\n // didn't find a bin for the call, make a new bin\n bins.push({\n calls: [call],\n cumulativeGasLimit: gas,\n })\n return bins\n }, [])\n // pull out just the calls from each bin\n .map((b) => b.calls)\n )\n}\n","import type { MulticallContext } from './context'\nimport {\n useMultiChainMultiContractSingleData as _useMultiChainMultiContractSingleData,\n useMultiChainSingleContractSingleData as _useMultiChainSingleContractSingleData,\n useMultipleContractSingleData as _useMultipleContractSingleData,\n useSingleCallResult as _useSingleCallResult,\n useSingleContractMultipleData as _useSingleContractMultipleData,\n useSingleContractWithCallData as _useSingleContractWithCallData,\n} from './hooks'\nimport { createMulticallSlice } from './slice'\nimport { createUpdater } from './updater'\n\ntype RemoveFirstFromTuple = T['length'] extends 0\n ? undefined\n : ((...b: T) => void) extends (a: any, ...b: infer I) => void\n ? I\n : []\ntype ParamsWithoutContext any> = RemoveFirstFromTuple>\n\nexport interface MulticallOptions {\n reducerPath?: string\n // More options can be added here as multicall's capabilities are extended\n}\n\n// Inspired by RTK Query's createApi\nexport function createMulticall(options?: MulticallOptions) {\n const reducerPath = options?.reducerPath ?? 'multicall'\n const slice = createMulticallSlice(reducerPath)\n const { actions, reducer } = slice\n const context: MulticallContext = { reducerPath, actions }\n\n const useMultipleContractSingleData = (...args: ParamsWithoutContext) =>\n _useMultipleContractSingleData(context, ...args)\n const useSingleContractMultipleData = (...args: ParamsWithoutContext) =>\n _useSingleContractMultipleData(context, ...args)\n const useSingleContractWithCallData = (...args: ParamsWithoutContext) =>\n _useSingleContractWithCallData(context, ...args)\n const useSingleCallResult = (...args: ParamsWithoutContext) =>\n _useSingleCallResult(context, ...args)\n const useMultiChainMultiContractSingleData = (\n ...args: ParamsWithoutContext\n ) => _useMultiChainMultiContractSingleData(context, ...args)\n const useMultiChainSingleContractSingleData = (\n ...args: ParamsWithoutContext\n ) => _useMultiChainSingleContractSingleData(context, ...args)\n const hooks = {\n useMultipleContractSingleData,\n useSingleContractMultipleData,\n useSingleContractWithCallData,\n useSingleCallResult,\n useMultiChainMultiContractSingleData,\n useMultiChainSingleContractSingleData,\n }\n\n const Updater = createUpdater(context)\n\n return {\n reducerPath,\n reducer,\n actions,\n hooks,\n Updater,\n }\n}\n"],"names":["INVALID_RESULT","valid","blockNumber","undefined","data","INVALID_CALL_STATE","result","loading","syncing","error","LOADING_CALL_STATE","toCallKey","call","key","address","callData","gasRequired","Number","isSafeInteger","Error","parseCallKey","callKey","pcs","split","includes","length","_extends","parseInt","callsToCallKeys","calls","_calls$filter$map$sor","_calls$filter","filter","c","Boolean","map","sort","callKeysToCalls","callKeys","useCallStates","results","contractInterface","fragment","latestBlockNumber","syncingBlockNumber","useMemo","lowestBlockNumber","reduce","memo","Math","min","max","i","resultFragment","toCallState","callResult","success","decodeFunctionResult","abi","functionName","console","debug","isMethodArg","x","BigInt","indexOf","isValidMethodArgs","Array","isArray","every","xi","useCallsDataSubscription","context","chainId","listenerOptions","reducerPath","actions","callResults","useSelector","state","defaultListenerOptions","dispatch","useDispatch","serializedCallKeys","JSON","stringify","useEffect","parse","blocksPerFetchFromState","_chainId","blocksPerFetch","blocksPerFetchForChain","_ref","_listenerOptions$bloc","addMulticallListeners","options","removeMulticallListeners","lastResults","useRef","a","b","isChanged","current","_callResults$chainId","push","useSingleContractMultipleData","contract","methodName","callInputs","_getAbiItem","getAbiItem","name","callDatas","callInput","encodeFunctionData","args","useMultipleContractSingleData","addresses","_useCallData","useCallData","useSingleCallResult","inputs","_useSingleContractMul","useSingleContractWithCallData","useCallback","_getAbiItem2","substring","useMultiChainMultiContractSingleData","chainToBlockNumber","chainToAddresses","_useCallData2","chainIdToResults","chainToCalls","chainCallKeysTuple","getChainIds","chainCallKeysTuples","batch","_step","_iterator","_createForOfIteratorHelperLoose","done","_chainId2","_ref2","_listenerOptions$bloc2","_step$value","value","_step2","_iterator2","_chainId3","_ref3","_listenerOptions$bloc3","_step2$value","_callResults$chainId2","useMultichainCallsDataSubscription","combinedResults","useMultiChainSingleContractSingleData","chainToAddress","multiContractResults","_multiContractResults","_multiContractResults2","_getAbiItem3","chainIdMap","Object","keys","initialState","waitRandom","ms","round","random","Promise","resolve","setTimeout","CancelledError","_Error","_this","_inheritsLoose","_wrapNativeSuper","RetryableError","_Error2","_this2","outputs","internalType","type","stateMutability","components","FETCH_RETRY_CONFIG","n","Infinity","minWait","maxWait","fetchChunk","_x","_x2","_x3","_x4","_fetchChunk","apply","arguments","_asyncToGenerator","_regeneratorRuntime","mark","_callee","multicallInfo","chunk","isDebug","returnData","_error$message","_error$message2","half","_yield$Promise$all","wrap","_context","prev","next","obj","_obj$gasRequired","target","gasLimit","provider","simulateContract","IMulticallABI","_obj$gasRequired2","sent","forEach","_chunk$i$gasRequired2","gasUsed","floor","_chunk$i$gasRequired","warn","toString","abrupt","t0","code","message","all","slice","concat","stop","Updater","props","updateListenerOptions","_useState","debouncedValue","setDebouncedValue","debouncedListeners","useState","callListeners","handler","clearTimeout","cancellations","listeningKeys","allListeners","listeners","keyListeners","previousMin","activeListeningKeys","serializedOutdatedCallKeys","outdatedCallKeys","minDataBlockNumber","fetchingBlockNumber","outdatedListeningKeys","chunkedCalls","chunkGasLimit","defaultGasRequired","c1","c2","_c2$gasRequired","_c1$gasRequired","bins","gas","_call$gasRequired","bin","cumulativeGasLimit","chunkCalls","fetchingMulticallResults","fetchChunkContext","newCancellations","fn","rejectCancelled","completed","_retry","promise","reject","isRetryableError","cancel","then","_chunk$reduce","_result$i$returnData","erroredCalls","updateMulticallResults","ix","errorFetchingMulticallResults","onFetchChunkSuccess","isCancelledError","onFetchChunkFailure","createUpdater","React","_options$reducerPath","createSlice","reducers","action","_action$payload","payload","_listeners$chainId","_listeners$chainId$ca","_listeners$chainId$ca2","_action$payload2","_action$payload3","_state$callResults$ch","_current$fetchingBloc","_action$payload4","_state$callResults$ch2","_action$payload5","_state$callResults$ch3","_current$blockNumber","_action$payload6","_state$listenerOption","createMulticallSlice","reducer","hooks","_len","_key","_useMultipleContractSingleData","_len2","_key2","_useSingleContractMultipleData","_len3","_key3","_useSingleContractWithCallData","_len4","_key4","_useSingleCallResult","_len5","_key5","_useMultiChainMultiContractSingleData","_len6","_key6","_useMultiChainSingleContractSingleData"],"mappings":"6NASaA,EAA6B,CAAEC,OAAO,EAAOC,iBAAaC,EAAWC,UAAMD,GAK3EE,EAAgC,CAC3CJ,OAAO,EACPK,YAAQH,EACRI,SAAS,EACTC,SAAS,EACTC,OAAO,GAEIC,EAAgC,CAC3CT,OAAO,EACPK,YAAQH,EACRI,SAAS,EACTC,SAAS,EACTC,OAAO,q1RCxBOE,EAAUC,GACxB,IAAIC,EAASD,EAAKE,YAAWF,EAAKG,SAClC,GAAIH,EAAKI,YAAa,CACpB,IAAKC,OAAOC,cAAcN,EAAKI,aAC7B,MAAM,IAAIG,yBAAyBP,EAAKI,aAE1CH,OAAWD,EAAKI,YAElB,OAAOH,WAGOO,EAAaC,GAC3B,IAAMC,EAAMD,EAAQE,MAAM,KAC1B,IAAK,CAAC,EAAG,GAAGC,SAASF,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IAAAA,EAAAD,EAAAC,IAAjEpN,EAAiEoN,GAAAlI,UAAAkI,GAAA,OACzGC,EAA8BpI,cAAC5H,GAAOoK,OAAKzH,KAa3CK,oBAZ0B,WAAH,QAAAiN,EAAApI,UAAA5K,OAAO0F,MAAuDhD,MAAAsQ,GAAAC,IAAAA,EAAAD,EAAAC,IAAvDvN,EAAuDuN,GAAArI,UAAAqI,GAAA,OACrFC,EAAoBvI,cAAC5H,GAAOoK,OAAKzH,KAYjCY,qCAX2C,WAAH,QAAA6M,EAAAvI,UAAA5K,OACrC0F,MAAwEhD,MAAAyQ,GAAAC,IAAAA,EAAAD,EAAAC,IAAxE1N,EAAwE0N,GAAAxI,UAAAwI,GAAA,OACxEC,EAAqC1I,cAAC5H,GAAOoK,OAAKzH,KAUrDwC,sCAT4C,WAAH,QAAAoL,EAAA1I,UAAA5K,OACtC0F,MAAyEhD,MAAA4Q,GAAAC,IAAAA,EAAAD,EAAAC,IAAzE7N,EAAyE6N,GAAA3I,UAAA2I,GAAA,OACzEC,EAAsC7I,cAAC5H,GAAOoK,OAAKzH,MAiBtD2H,QAPcyD,EAAc/N"}
\ No newline at end of file
diff --git a/dist/redux-multicall-viem.esm.js b/dist/redux-multicall-viem.esm.js
new file mode 100644
index 0000000..2d07246
--- /dev/null
+++ b/dist/redux-multicall-viem.esm.js
@@ -0,0 +1,1612 @@
+import React, { useMemo, useCallback, useEffect, useRef, useState } from 'react';
+import { useSelector, useDispatch, batch } from 'react-redux';
+import { decodeFunctionResult, getAbiItem, encodeFunctionData } from 'viem';
+import { createSlice } from '@reduxjs/toolkit';
+
+var DEFAULT_BLOCKS_PER_FETCH = 1;
+var DEFAULT_CALL_GAS_REQUIRED = 1000000;
+var DEFAULT_CHUNK_GAS_REQUIRED = 200000;
+var CHUNK_GAS_LIMIT = 100000000;
+var CONSERVATIVE_BLOCK_GAS_LIMIT = 10000000; // conservative, hard-coded estimate of the current block gas limit
+// Consts for hooks
+var INVALID_RESULT = {
+ valid: false,
+ blockNumber: undefined,
+ data: undefined
+};
+var NEVER_RELOAD = {
+ blocksPerFetch: Infinity
+};
+var INVALID_CALL_STATE = {
+ valid: false,
+ result: undefined,
+ loading: false,
+ syncing: false,
+ error: false
+};
+var LOADING_CALL_STATE = {
+ valid: true,
+ result: undefined,
+ loading: true,
+ syncing: true,
+ error: false
+};
+
+function _arrayLikeToArray(r, a) {
+ (null == a || a > r.length) && (a = r.length);
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
+ return n;
+}
+function asyncGeneratorStep(n, t, e, r, o, a, c) {
+ try {
+ var i = n[a](c),
+ u = i.value;
+ } catch (n) {
+ return void e(n);
+ }
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
+}
+function _asyncToGenerator(n) {
+ return function () {
+ var t = this,
+ e = arguments;
+ return new Promise(function (r, o) {
+ var a = n.apply(t, e);
+ function _next(n) {
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
+ }
+ function _throw(n) {
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
+ }
+ _next(void 0);
+ });
+ };
+}
+function _construct(t, e, r) {
+ if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
+ var o = [null];
+ o.push.apply(o, e);
+ var p = new (t.bind.apply(t, o))();
+ return r && _setPrototypeOf(p, r.prototype), p;
+}
+function _createForOfIteratorHelperLoose(r, e) {
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
+ if (t) return (t = t.call(r)).next.bind(t);
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
+ t && (r = t);
+ var o = 0;
+ return function () {
+ return o >= r.length ? {
+ done: !0
+ } : {
+ done: !1,
+ value: r[o++]
+ };
+ };
+ }
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
+}
+function _extends() {
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
+ for (var e = 1; e < arguments.length; e++) {
+ var t = arguments[e];
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
+ }
+ return n;
+ }, _extends.apply(null, arguments);
+}
+function _getPrototypeOf(t) {
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
+ return t.__proto__ || Object.getPrototypeOf(t);
+ }, _getPrototypeOf(t);
+}
+function _inheritsLoose(t, o) {
+ t.prototype = Object.create(o.prototype), t.prototype.constructor = t, _setPrototypeOf(t, o);
+}
+function _isNativeFunction(t) {
+ try {
+ return -1 !== Function.toString.call(t).indexOf("[native code]");
+ } catch (n) {
+ return "function" == typeof t;
+ }
+}
+function _isNativeReflectConstruct() {
+ try {
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
+ } catch (t) {}
+ return (_isNativeReflectConstruct = function () {
+ return !!t;
+ })();
+}
+function _regeneratorRuntime() {
+ _regeneratorRuntime = function () {
+ return e;
+ };
+ var t,
+ e = {},
+ r = Object.prototype,
+ n = r.hasOwnProperty,
+ o = Object.defineProperty || function (t, e, r) {
+ t[e] = r.value;
+ },
+ i = "function" == typeof Symbol ? Symbol : {},
+ a = i.iterator || "@@iterator",
+ c = i.asyncIterator || "@@asyncIterator",
+ u = i.toStringTag || "@@toStringTag";
+ function define(t, e, r) {
+ return Object.defineProperty(t, e, {
+ value: r,
+ enumerable: !0,
+ configurable: !0,
+ writable: !0
+ }), t[e];
+ }
+ try {
+ define({}, "");
+ } catch (t) {
+ define = function (t, e, r) {
+ return t[e] = r;
+ };
+ }
+ function wrap(t, e, r, n) {
+ var i = e && e.prototype instanceof Generator ? e : Generator,
+ a = Object.create(i.prototype),
+ c = new Context(n || []);
+ return o(a, "_invoke", {
+ value: makeInvokeMethod(t, r, c)
+ }), a;
+ }
+ function tryCatch(t, e, r) {
+ try {
+ return {
+ type: "normal",
+ arg: t.call(e, r)
+ };
+ } catch (t) {
+ return {
+ type: "throw",
+ arg: t
+ };
+ }
+ }
+ e.wrap = wrap;
+ var h = "suspendedStart",
+ l = "suspendedYield",
+ f = "executing",
+ s = "completed",
+ y = {};
+ function Generator() {}
+ function GeneratorFunction() {}
+ function GeneratorFunctionPrototype() {}
+ var p = {};
+ define(p, a, function () {
+ return this;
+ });
+ var d = Object.getPrototypeOf,
+ v = d && d(d(values([])));
+ v && v !== r && n.call(v, a) && (p = v);
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
+ function defineIteratorMethods(t) {
+ ["next", "throw", "return"].forEach(function (e) {
+ define(t, e, function (t) {
+ return this._invoke(e, t);
+ });
+ });
+ }
+ function AsyncIterator(t, e) {
+ function invoke(r, o, i, a) {
+ var c = tryCatch(t[r], t, o);
+ if ("throw" !== c.type) {
+ var u = c.arg,
+ h = u.value;
+ return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
+ invoke("next", t, i, a);
+ }, function (t) {
+ invoke("throw", t, i, a);
+ }) : e.resolve(h).then(function (t) {
+ u.value = t, i(u);
+ }, function (t) {
+ return invoke("throw", t, i, a);
+ });
+ }
+ a(c.arg);
+ }
+ var r;
+ o(this, "_invoke", {
+ value: function (t, n) {
+ function callInvokeWithMethodAndArg() {
+ return new e(function (e, r) {
+ invoke(t, n, e, r);
+ });
+ }
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
+ }
+ });
+ }
+ function makeInvokeMethod(e, r, n) {
+ var o = h;
+ return function (i, a) {
+ if (o === f) throw Error("Generator is already running");
+ if (o === s) {
+ if ("throw" === i) throw a;
+ return {
+ value: t,
+ done: !0
+ };
+ }
+ for (n.method = i, n.arg = a;;) {
+ var c = n.delegate;
+ if (c) {
+ var u = maybeInvokeDelegate(c, n);
+ if (u) {
+ if (u === y) continue;
+ return u;
+ }
+ }
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
+ if (o === h) throw o = s, n.arg;
+ n.dispatchException(n.arg);
+ } else "return" === n.method && n.abrupt("return", n.arg);
+ o = f;
+ var p = tryCatch(e, r, n);
+ if ("normal" === p.type) {
+ if (o = n.done ? s : l, p.arg === y) continue;
+ return {
+ value: p.arg,
+ done: n.done
+ };
+ }
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
+ }
+ };
+ }
+ function maybeInvokeDelegate(e, r) {
+ var n = r.method,
+ o = e.iterator[n];
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
+ var i = tryCatch(o, e.iterator, r.arg);
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
+ var a = i.arg;
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
+ }
+ function pushTryEntry(t) {
+ var e = {
+ tryLoc: t[0]
+ };
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
+ }
+ function resetTryEntry(t) {
+ var e = t.completion || {};
+ e.type = "normal", delete e.arg, t.completion = e;
+ }
+ function Context(t) {
+ this.tryEntries = [{
+ tryLoc: "root"
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
+ }
+ function values(e) {
+ if (e || "" === e) {
+ var r = e[a];
+ if (r) return r.call(e);
+ if ("function" == typeof e.next) return e;
+ if (!isNaN(e.length)) {
+ var o = -1,
+ i = function next() {
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
+ return next.value = t, next.done = !0, next;
+ };
+ return i.next = i;
+ }
+ }
+ throw new TypeError(typeof e + " is not iterable");
+ }
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
+ value: GeneratorFunctionPrototype,
+ configurable: !0
+ }), o(GeneratorFunctionPrototype, "constructor", {
+ value: GeneratorFunction,
+ configurable: !0
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
+ var e = "function" == typeof t && t.constructor;
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
+ }, e.mark = function (t) {
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
+ }, e.awrap = function (t) {
+ return {
+ __await: t
+ };
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
+ return this;
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
+ void 0 === i && (i = Promise);
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
+ return t.done ? t.value : a.next();
+ });
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
+ return this;
+ }), define(g, "toString", function () {
+ return "[object Generator]";
+ }), e.keys = function (t) {
+ var e = Object(t),
+ r = [];
+ for (var n in e) r.push(n);
+ return r.reverse(), function next() {
+ for (; r.length;) {
+ var t = r.pop();
+ if (t in e) return next.value = t, next.done = !1, next;
+ }
+ return next.done = !0, next;
+ };
+ }, e.values = values, Context.prototype = {
+ constructor: Context,
+ reset: function (e) {
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
+ },
+ stop: function () {
+ this.done = !0;
+ var t = this.tryEntries[0].completion;
+ if ("throw" === t.type) throw t.arg;
+ return this.rval;
+ },
+ dispatchException: function (e) {
+ if (this.done) throw e;
+ var r = this;
+ function handle(n, o) {
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
+ }
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
+ var i = this.tryEntries[o],
+ a = i.completion;
+ if ("root" === i.tryLoc) return handle("end");
+ if (i.tryLoc <= this.prev) {
+ var c = n.call(i, "catchLoc"),
+ u = n.call(i, "finallyLoc");
+ if (c && u) {
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
+ } else if (c) {
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
+ } else {
+ if (!u) throw Error("try statement without catch or finally");
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
+ }
+ }
+ }
+ },
+ abrupt: function (t, e) {
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
+ var o = this.tryEntries[r];
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
+ var i = o;
+ break;
+ }
+ }
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
+ var a = i ? i.completion : {};
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
+ },
+ complete: function (t, e) {
+ if ("throw" === t.type) throw t.arg;
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
+ },
+ finish: function (t) {
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
+ var r = this.tryEntries[e];
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
+ }
+ },
+ catch: function (t) {
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
+ var r = this.tryEntries[e];
+ if (r.tryLoc === t) {
+ var n = r.completion;
+ if ("throw" === n.type) {
+ var o = n.arg;
+ resetTryEntry(r);
+ }
+ return o;
+ }
+ }
+ throw Error("illegal catch attempt");
+ },
+ delegateYield: function (e, r, n) {
+ return this.delegate = {
+ iterator: values(e),
+ resultName: r,
+ nextLoc: n
+ }, "next" === this.method && (this.arg = t), y;
+ }
+ }, e;
+}
+function _setPrototypeOf(t, e) {
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
+ return t.__proto__ = e, t;
+ }, _setPrototypeOf(t, e);
+}
+function _unsupportedIterableToArray(r, a) {
+ if (r) {
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
+ var t = {}.toString.call(r).slice(8, -1);
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
+ }
+}
+function _wrapNativeSuper(t) {
+ var r = "function" == typeof Map ? new Map() : void 0;
+ return _wrapNativeSuper = function (t) {
+ if (null === t || !_isNativeFunction(t)) return t;
+ if ("function" != typeof t) throw new TypeError("Super expression must either be null or a function");
+ if (void 0 !== r) {
+ if (r.has(t)) return r.get(t);
+ r.set(t, Wrapper);
+ }
+ function Wrapper() {
+ return _construct(t, arguments, _getPrototypeOf(this).constructor);
+ }
+ return Wrapper.prototype = Object.create(t.prototype, {
+ constructor: {
+ value: Wrapper,
+ enumerable: !1,
+ writable: !0,
+ configurable: !0
+ }
+ }), _setPrototypeOf(Wrapper, t);
+ }, _wrapNativeSuper(t);
+}
+
+function toCallKey(call) {
+ var key = call.address + "-" + call.callData;
+ if (call.gasRequired) {
+ if (!Number.isSafeInteger(call.gasRequired)) {
+ throw new Error("Invalid number: " + call.gasRequired);
+ }
+ key += "-" + call.gasRequired;
+ }
+ return key;
+}
+function parseCallKey(callKey) {
+ var pcs = callKey.split('-');
+ if (![2, 3].includes(pcs.length)) {
+ throw new Error("Invalid call key: " + callKey);
+ }
+ return _extends({
+ address: pcs[0],
+ callData: pcs[1]
+ }, pcs[2] ? {
+ gasRequired: Number.parseInt(pcs[2])
+ } : {});
+}
+function callsToCallKeys(calls) {
+ var _calls$filter$map$sor, _calls$filter;
+ return (_calls$filter$map$sor = calls == null || (_calls$filter = calls.filter(function (c) {
+ return Boolean(c);
+ })) == null || (_calls$filter = _calls$filter.map(toCallKey)) == null ? void 0 : _calls$filter.sort()) != null ? _calls$filter$map$sor : [];
+}
+function callKeysToCalls(callKeys) {
+ if (!(callKeys != null && callKeys.length)) return null;
+ return callKeys.map(function (key) {
+ return parseCallKey(key);
+ });
+}
+
+// Converts CallResult[] to CallState[], only updating if call states have changed.
+// Ensures that CallState results remain referentially stable when unchanged, preventing
+// spurious re-renders which would otherwise occur because mapping always creates a new object.
+function useCallStates(results, contractInterface, fragment, latestBlockNumber) {
+ // Avoid refreshing the results with every changing block number (eg latestBlockNumber).
+ // Instead, only refresh the results if they need to be synced - if there is a result which is stale, for which blockNumber < latestBlockNumber.
+ var syncingBlockNumber = useMemo(function () {
+ var lowestBlockNumber = results.reduce(function (memo, result) {
+ return result.blockNumber ? Math.min(memo != null ? memo : result.blockNumber, result.blockNumber) : memo;
+ }, undefined);
+ return Math.max(lowestBlockNumber != null ? lowestBlockNumber : 0, latestBlockNumber != null ? latestBlockNumber : 0);
+ }, [results, latestBlockNumber]);
+ return useMemo(function () {
+ return results.map(function (result, i) {
+ var resultFragment = typeof fragment === 'function' ? fragment(i) : fragment;
+ return toCallState(result, contractInterface, resultFragment, syncingBlockNumber);
+ });
+ }, [contractInterface, fragment, results, syncingBlockNumber]);
+}
+function toCallState(callResult, contractInterface, fragment, syncingBlockNumber) {
+ if (!callResult || !callResult.valid) {
+ return INVALID_CALL_STATE;
+ }
+ var data = callResult.data,
+ blockNumber = callResult.blockNumber;
+ if (!blockNumber || !contractInterface || !fragment || !syncingBlockNumber) {
+ return LOADING_CALL_STATE;
+ }
+ var success = data && data.length > 2;
+ var syncing = blockNumber < syncingBlockNumber;
+ var result = undefined;
+ if (success && data) {
+ try {
+ result = decodeFunctionResult({
+ abi: contractInterface,
+ functionName: fragment,
+ data: data
+ });
+ } catch (error) {
+ console.debug('Result data parsing failed', fragment, data);
+ return {
+ valid: true,
+ loading: false,
+ error: true,
+ syncing: syncing,
+ result: result
+ };
+ }
+ }
+ return {
+ valid: true,
+ loading: false,
+ syncing: syncing,
+ result: result,
+ error: !success
+ };
+}
+
+function isMethodArg(x) {
+ return x === null || x === undefined ? false : typeof BigInt(x) === 'bigint' || ['string', 'number'].indexOf(typeof x) !== -1;
+}
+function isValidMethodArgs(x) {
+ return x === undefined || Array.isArray(x) && x.every(function (xi) {
+ return isMethodArg(xi) || Array.isArray(xi) && xi.every(isMethodArg);
+ });
+}
+
+// the lowest level call for subscribing to contract data
+function useCallsDataSubscription(context, chainId, calls, listenerOptions) {
+ var reducerPath = context.reducerPath,
+ actions = context.actions;
+ var callResults = useSelector(function (state) {
+ return state[reducerPath].callResults;
+ });
+ var defaultListenerOptions = useSelector(function (state) {
+ return state[reducerPath].listenerOptions;
+ });
+ var dispatch = useDispatch();
+ var serializedCallKeys = useMemo(function () {
+ return JSON.stringify(callsToCallKeys(calls));
+ }, [calls]);
+ // update listeners when there is an actual change that persists for at least 100ms
+ useEffect(function () {
+ var _chainId, _ref, _listenerOptions$bloc;
+ var callKeys = JSON.parse(serializedCallKeys);
+ var calls = callKeysToCalls(callKeys);
+ if (!chainId || !calls) return;
+ var blocksPerFetchFromState = (_chainId = (defaultListenerOptions != null ? defaultListenerOptions : {})[chainId]) == null ? void 0 : _chainId.blocksPerFetch;
+ var blocksPerFetchForChain = (_ref = (_listenerOptions$bloc = listenerOptions == null ? void 0 : listenerOptions.blocksPerFetch) != null ? _listenerOptions$bloc : blocksPerFetchFromState) != null ? _ref : DEFAULT_BLOCKS_PER_FETCH;
+ dispatch(actions.addMulticallListeners({
+ chainId: chainId,
+ calls: calls,
+ options: {
+ blocksPerFetch: blocksPerFetchForChain
+ }
+ }));
+ return function () {
+ dispatch(actions.removeMulticallListeners({
+ chainId: chainId,
+ calls: calls,
+ options: {
+ blocksPerFetch: blocksPerFetchForChain
+ }
+ }));
+ };
+ }, [actions, chainId, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions]);
+ var lastResults = useRef([]);
+ return useMemo(function () {
+ var isChanged = lastResults.current.length !== calls.length;
+ // Construct results using a for-loop to handle sparse arrays.
+ // Array.prototype.map would skip empty entries.
+ var results = [];
+ for (var i = 0; i < calls.length; ++i) {
+ var call = calls[i];
+ var result = INVALID_RESULT;
+ if (chainId && call) {
+ var _callResults$chainId;
+ var callResult = (_callResults$chainId = callResults[chainId]) == null ? void 0 : _callResults$chainId[toCallKey(call)];
+ result = {
+ valid: true,
+ data: callResult != null && callResult.data && callResult.data !== '0x' ? callResult.data : undefined,
+ blockNumber: callResult == null ? void 0 : callResult.blockNumber
+ };
+ }
+ isChanged = isChanged || !areCallResultsEqual(result, lastResults.current[i]);
+ results.push(result);
+ }
+ // Force the results to be referentially stable if they have not changed.
+ // This is necessary because *all* callResults are passed as deps when initially memoizing the results.
+ if (isChanged) {
+ lastResults.current = results;
+ }
+ return lastResults.current;
+ }, [callResults, calls, chainId]);
+}
+function areCallResultsEqual(a, b) {
+ return a.valid === b.valid && a.data === b.data && a.blockNumber === b.blockNumber;
+}
+// Similar to useCallsDataSubscription above but for subscribing to
+// calls to multiple chains at once
+function useMultichainCallsDataSubscription(context, chainToCalls, listenerOptions) {
+ var reducerPath = context.reducerPath,
+ actions = context.actions;
+ var callResults = useSelector(function (state) {
+ return state[reducerPath].callResults;
+ });
+ var defaultListenerOptions = useSelector(function (state) {
+ return state[reducerPath].listenerOptions;
+ });
+ var dispatch = useDispatch();
+ var serializedCallKeys = useMemo(function () {
+ var sortedChainIds = getChainIds(chainToCalls).sort();
+ var chainCallKeysTuple = sortedChainIds.map(function (chainId) {
+ var calls = chainToCalls[chainId];
+ var callKeys = callsToCallKeys(calls);
+ // Note, using a tuple to ensure consistent order when serialized
+ return [chainId, callKeys];
+ });
+ return JSON.stringify(chainCallKeysTuple);
+ }, [chainToCalls]);
+ useEffect(function () {
+ var chainCallKeysTuples = JSON.parse(serializedCallKeys);
+ if (!(chainCallKeysTuples != null && chainCallKeysTuples.length)) return;
+ batch(function () {
+ for (var _iterator = _createForOfIteratorHelperLoose(chainCallKeysTuples), _step; !(_step = _iterator()).done;) {
+ var _chainId2, _ref2, _listenerOptions$bloc2;
+ var _step$value = _step.value,
+ chainId = _step$value[0],
+ callKeys = _step$value[1];
+ var calls = callKeysToCalls(callKeys);
+ if (!(calls != null && calls.length)) continue;
+ var blocksPerFetchFromState = (_chainId2 = (defaultListenerOptions != null ? defaultListenerOptions : {})[chainId]) == null ? void 0 : _chainId2.blocksPerFetch;
+ var blocksPerFetchForChain = (_ref2 = (_listenerOptions$bloc2 = listenerOptions == null ? void 0 : listenerOptions.blocksPerFetch) != null ? _listenerOptions$bloc2 : blocksPerFetchFromState) != null ? _ref2 : DEFAULT_BLOCKS_PER_FETCH;
+ dispatch(actions.addMulticallListeners({
+ chainId: chainId,
+ calls: calls,
+ options: {
+ blocksPerFetch: blocksPerFetchForChain
+ }
+ }));
+ }
+ });
+ return function () {
+ batch(function () {
+ for (var _iterator2 = _createForOfIteratorHelperLoose(chainCallKeysTuples), _step2; !(_step2 = _iterator2()).done;) {
+ var _chainId3, _ref3, _listenerOptions$bloc3;
+ var _step2$value = _step2.value,
+ chainId = _step2$value[0],
+ callKeys = _step2$value[1];
+ var calls = callKeysToCalls(callKeys);
+ if (!(calls != null && calls.length)) continue;
+ var blocksPerFetchFromState = (_chainId3 = (defaultListenerOptions != null ? defaultListenerOptions : {})[chainId]) == null ? void 0 : _chainId3.blocksPerFetch;
+ var blocksPerFetchForChain = (_ref3 = (_listenerOptions$bloc3 = listenerOptions == null ? void 0 : listenerOptions.blocksPerFetch) != null ? _listenerOptions$bloc3 : blocksPerFetchFromState) != null ? _ref3 : DEFAULT_BLOCKS_PER_FETCH;
+ dispatch(actions.removeMulticallListeners({
+ chainId: chainId,
+ calls: calls,
+ options: {
+ blocksPerFetch: blocksPerFetchForChain
+ }
+ }));
+ }
+ });
+ };
+ }, [actions, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions]);
+ return useMemo(function () {
+ return getChainIds(chainToCalls).reduce(function (result, chainId) {
+ var calls = chainToCalls[chainId];
+ result[chainId] = calls.map(function (call) {
+ var _callResults$chainId2;
+ if (!chainId || !call) return INVALID_RESULT;
+ var result = (_callResults$chainId2 = callResults[chainId]) == null ? void 0 : _callResults$chainId2[toCallKey(call)];
+ var data = result != null && result.data && result.data !== '0x' ? result.data : undefined;
+ return {
+ valid: true,
+ data: data,
+ blockNumber: result == null ? void 0 : result.blockNumber
+ };
+ });
+ return result;
+ }, {});
+ }, [callResults, chainToCalls]);
+}
+// formats many calls to a single function on a single contract, with the function name and inputs specified
+function useSingleContractMultipleData(context, chainId, latestBlockNumber, contract, methodName, callInputs, options) {
+ var _ref4 = options != null ? options : {},
+ gasRequired = _ref4.gasRequired;
+ // Create ethers function fragment
+ var fragment = useMemo(function () {
+ var _getAbiItem;
+ return contract && ((_getAbiItem = getAbiItem({
+ abi: contract.abi,
+ name: methodName
+ })) == null ? void 0 : _getAbiItem.name);
+ }, [contract, methodName]);
+ // Get encoded call data. Note can't use useCallData below b.c. this is for a list of CallInputs
+ var callDatas = useMemo(function () {
+ if (!contract || !fragment) return [];
+ return callInputs.map(function (callInput) {
+ return isValidMethodArgs(callInput) ? encodeFunctionData({
+ abi: contract.abi,
+ functionName: fragment,
+ args: callInput
+ }) : undefined;
+ });
+ }, [callInputs, contract, fragment]);
+ // Create call objects
+ var calls = useMemo(function () {
+ if (!contract) return [];
+ return callDatas.map(function (callData) {
+ if (!callData) return undefined;
+ return {
+ address: contract.address,
+ callData: callData,
+ gasRequired: gasRequired
+ };
+ });
+ }, [contract, callDatas, gasRequired]);
+ // Subscribe to call data
+ var results = useCallsDataSubscription(context, chainId, calls, options);
+ return useCallStates(results, contract == null ? void 0 : contract.abi, fragment, latestBlockNumber);
+}
+function useMultipleContractSingleData(context, chainId, latestBlockNumber, addresses, contractInterface, methodName, callInputs, options) {
+ var _ref5 = options != null ? options : {},
+ gasRequired = _ref5.gasRequired;
+ var _useCallData = useCallData(methodName, contractInterface, callInputs),
+ fragment = _useCallData.fragment,
+ callData = _useCallData.callData;
+ // Create call objects
+ var calls = useMemo(function () {
+ if (!callData) return [];
+ return addresses.map(function (address) {
+ if (!address) return undefined;
+ return {
+ address: address,
+ callData: callData,
+ gasRequired: gasRequired
+ };
+ });
+ }, [addresses, callData, gasRequired]);
+ // Subscribe to call data
+ var results = useCallsDataSubscription(context, chainId, calls, options);
+ return useCallStates(results, contractInterface, fragment, latestBlockNumber);
+}
+function useSingleCallResult(context, chainId, latestBlockNumber, contract, methodName, inputs, options) {
+ var _useSingleContractMul;
+ var callInputs = useMemo(function () {
+ return [inputs];
+ }, [inputs]);
+ return (_useSingleContractMul = useSingleContractMultipleData(context, chainId, latestBlockNumber, contract, methodName, callInputs, options)[0]) != null ? _useSingleContractMul : INVALID_CALL_STATE;
+}
+// formats many calls to any number of functions on a single contract, with only the calldata specified
+function useSingleContractWithCallData(context, chainId, latestBlockNumber, contract, callDatas, options) {
+ var _ref6 = options != null ? options : {},
+ gasRequired = _ref6.gasRequired;
+ // Create call objects
+ var calls = useMemo(function () {
+ if (!contract) return [];
+ return callDatas.map(function (callData) {
+ return {
+ address: contract.address,
+ callData: callData,
+ gasRequired: gasRequired
+ };
+ });
+ }, [callDatas, contract, gasRequired]);
+ // Subscribe to call data
+ var results = useCallsDataSubscription(context, chainId, calls, options);
+ var fragment = useCallback(function (i) {
+ var _getAbiItem2;
+ return (_getAbiItem2 = getAbiItem({
+ abi: contract == null ? void 0 : contract.abi,
+ name: callDatas[i].substring(0, 10)
+ })) == null ? void 0 : _getAbiItem2.name;
+ }, [callDatas, contract]);
+ return useCallStates(results, contract == null ? void 0 : contract.abi, fragment, latestBlockNumber);
+}
+// Similar to useMultipleContractSingleData but instead of multiple contracts on one chain,
+// this is for querying compatible contracts on multiple chains
+function useMultiChainMultiContractSingleData(context, chainToBlockNumber, chainToAddresses, contractInterface, methodName, callInputs, options) {
+ var _ref7 = options != null ? options : {},
+ gasRequired = _ref7.gasRequired;
+ var _useCallData2 = useCallData(methodName, contractInterface, callInputs),
+ fragment = _useCallData2.fragment,
+ callData = _useCallData2.callData;
+ // Create call objects
+ var chainToCalls = useMemo(function () {
+ if (!callData || !chainToAddresses) return {};
+ return getChainIds(chainToAddresses).reduce(function (result, chainId) {
+ var addresses = chainToAddresses[chainId];
+ var calls = addresses.map(function (address) {
+ if (!address) return undefined;
+ return {
+ address: address,
+ callData: callData,
+ gasRequired: gasRequired
+ };
+ });
+ result[chainId] = calls;
+ return result;
+ }, {});
+ }, [chainToAddresses, callData, gasRequired]);
+ // Subscribe to call data
+ var chainIdToResults = useMultichainCallsDataSubscription(context, chainToCalls, options);
+ // TODO(WEB-2097): Multichain states are not referentially stable, because they cannot use the
+ // same codepath (eg useCallStates).
+ return useMemo(function () {
+ return getChainIds(chainIdToResults).reduce(function (combinedResults, chainId) {
+ var latestBlockNumber = chainToBlockNumber == null ? void 0 : chainToBlockNumber[chainId];
+ var results = chainIdToResults[chainId];
+ combinedResults[chainId] = results.map(function (result) {
+ return toCallState(result, contractInterface, fragment, latestBlockNumber);
+ });
+ return combinedResults;
+ }, {});
+ }, [fragment, contractInterface, chainIdToResults, chainToBlockNumber]);
+}
+// Similar to useSingleCallResult but instead of one contract on one chain,
+// this is for querying a contract on multiple chains
+function useMultiChainSingleContractSingleData(context, chainToBlockNumber, chainToAddress, contractInterface, methodName, callInputs, options) {
+ // This hook uses the more flexible useMultiChainMultiContractSingleData internally,
+ // but transforms the inputs and outputs for convenience
+ var chainIdToAddresses = useMemo(function () {
+ return getChainIds(chainToAddress).reduce(function (result, chainId) {
+ result[chainId] = [chainToAddress[chainId]];
+ return result;
+ }, {});
+ }, [chainToAddress]);
+ var multiContractResults = useMultiChainMultiContractSingleData(context, chainToBlockNumber, chainIdToAddresses, contractInterface, methodName, callInputs, options);
+ return useMemo(function () {
+ return getChainIds(chainToAddress).reduce(function (result, chainId) {
+ var _multiContractResults, _multiContractResults2;
+ result[chainId] = (_multiContractResults = (_multiContractResults2 = multiContractResults[chainId]) == null ? void 0 : _multiContractResults2[0]) != null ? _multiContractResults : INVALID_CALL_STATE;
+ return result;
+ }, {});
+ }, [chainToAddress, multiContractResults]);
+}
+function useCallData(methodName, contractInterface, callInputs) {
+ // Create ethers function fragment
+ var fragment = useMemo(function () {
+ var _getAbiItem3;
+ return contractInterface && ((_getAbiItem3 = getAbiItem({
+ abi: contractInterface,
+ name: methodName
+ })) == null ? void 0 : _getAbiItem3.name);
+ }, [contractInterface, methodName]);
+ // Get encoded call data
+ var callData = useMemo(function () {
+ return fragment && isValidMethodArgs(callInputs) ? encodeFunctionData({
+ abi: contractInterface,
+ functionName: fragment,
+ args: callInputs
+ }) : undefined;
+ }, [callInputs, contractInterface, fragment]);
+ return {
+ fragment: fragment,
+ callData: callData
+ };
+}
+function getChainIds(chainIdMap) {
+ return Object.keys(chainIdMap).map(function (c) {
+ return parseInt(c, 10);
+ });
+}
+
+var initialState = {
+ callResults: {}
+};
+function createMulticallSlice(reducerPath) {
+ return createSlice({
+ name: reducerPath,
+ initialState: initialState,
+ reducers: {
+ addMulticallListeners: function addMulticallListeners(state, action) {
+ var _listeners$chainId;
+ var _action$payload = action.payload,
+ calls = _action$payload.calls,
+ chainId = _action$payload.chainId,
+ blocksPerFetch = _action$payload.options.blocksPerFetch;
+ var listeners = state.callListeners ? state.callListeners : state.callListeners = {};
+ listeners[chainId] = (_listeners$chainId = listeners[chainId]) != null ? _listeners$chainId : {};
+ calls.forEach(function (call) {
+ var _listeners$chainId$ca, _listeners$chainId$ca2;
+ var callKey = toCallKey(call);
+ listeners[chainId][callKey] = (_listeners$chainId$ca = listeners[chainId][callKey]) != null ? _listeners$chainId$ca : {};
+ listeners[chainId][callKey][blocksPerFetch] = ((_listeners$chainId$ca2 = listeners[chainId][callKey][blocksPerFetch]) != null ? _listeners$chainId$ca2 : 0) + 1;
+ });
+ },
+ removeMulticallListeners: function removeMulticallListeners(state, action) {
+ var _action$payload2 = action.payload,
+ calls = _action$payload2.calls,
+ chainId = _action$payload2.chainId,
+ blocksPerFetch = _action$payload2.options.blocksPerFetch;
+ var listeners = state.callListeners ? state.callListeners : state.callListeners = {};
+ if (!listeners[chainId]) return;
+ calls.forEach(function (call) {
+ var callKey = toCallKey(call);
+ if (!listeners[chainId][callKey]) return;
+ if (!listeners[chainId][callKey][blocksPerFetch]) return;
+ if (listeners[chainId][callKey][blocksPerFetch] === 1) {
+ delete listeners[chainId][callKey][blocksPerFetch];
+ } else {
+ listeners[chainId][callKey][blocksPerFetch]--;
+ }
+ });
+ },
+ fetchingMulticallResults: function fetchingMulticallResults(state, action) {
+ var _state$callResults$ch;
+ var _action$payload3 = action.payload,
+ chainId = _action$payload3.chainId,
+ fetchingBlockNumber = _action$payload3.fetchingBlockNumber,
+ calls = _action$payload3.calls;
+ state.callResults[chainId] = (_state$callResults$ch = state.callResults[chainId]) != null ? _state$callResults$ch : {};
+ calls.forEach(function (call) {
+ var callKey = toCallKey(call);
+ var current = state.callResults[chainId][callKey];
+ if (!current) {
+ state.callResults[chainId][callKey] = {
+ fetchingBlockNumber: fetchingBlockNumber
+ };
+ } else {
+ var _current$fetchingBloc;
+ if (((_current$fetchingBloc = current.fetchingBlockNumber) != null ? _current$fetchingBloc : 0) >= fetchingBlockNumber) return;
+ state.callResults[chainId][callKey].fetchingBlockNumber = fetchingBlockNumber;
+ }
+ });
+ },
+ errorFetchingMulticallResults: function errorFetchingMulticallResults(state, action) {
+ var _state$callResults$ch2;
+ var _action$payload4 = action.payload,
+ chainId = _action$payload4.chainId,
+ fetchingBlockNumber = _action$payload4.fetchingBlockNumber,
+ calls = _action$payload4.calls;
+ state.callResults[chainId] = (_state$callResults$ch2 = state.callResults[chainId]) != null ? _state$callResults$ch2 : {};
+ calls.forEach(function (call) {
+ var callKey = toCallKey(call);
+ var current = state.callResults[chainId][callKey];
+ if (!current || typeof current.fetchingBlockNumber !== 'number') return; // only should be dispatched if we are already fetching
+ if (current.fetchingBlockNumber <= fetchingBlockNumber) {
+ delete current.fetchingBlockNumber;
+ current.data = null;
+ current.blockNumber = fetchingBlockNumber;
+ }
+ });
+ },
+ updateMulticallResults: function updateMulticallResults(state, action) {
+ var _state$callResults$ch3;
+ var _action$payload5 = action.payload,
+ chainId = _action$payload5.chainId,
+ results = _action$payload5.results,
+ blockNumber = _action$payload5.blockNumber;
+ state.callResults[chainId] = (_state$callResults$ch3 = state.callResults[chainId]) != null ? _state$callResults$ch3 : {};
+ Object.keys(results).forEach(function (callKey) {
+ var _current$blockNumber;
+ var current = state.callResults[chainId][callKey];
+ if (((_current$blockNumber = current == null ? void 0 : current.blockNumber) != null ? _current$blockNumber : 0) > blockNumber) return;
+ if ((current == null ? void 0 : current.data) === results[callKey] && (current == null ? void 0 : current.blockNumber) === blockNumber) return;
+ state.callResults[chainId][callKey] = {
+ data: results[callKey],
+ blockNumber: blockNumber
+ };
+ });
+ },
+ updateListenerOptions: function updateListenerOptions(state, action) {
+ var _state$listenerOption;
+ var _action$payload6 = action.payload,
+ chainId = _action$payload6.chainId,
+ listenerOptions = _action$payload6.listenerOptions;
+ state.listenerOptions = (_state$listenerOption = state.listenerOptions) != null ? _state$listenerOption : {};
+ state.listenerOptions[chainId] = listenerOptions;
+ }
+ }
+ });
+}
+
+/**
+ * Tries to pack a list of items into as few bins as possible using the first-fit bin packing algorithm
+ * @param calls the calls to chunk
+ * @param chunkGasLimit the gas limit of any one chunk of calls, i.e. bin capacity
+ * @param defaultGasRequired the default amount of gas an individual call should cost if not specified
+ */
+function chunkCalls(calls, chunkGasLimit, defaultGasRequired) {
+ if (defaultGasRequired === void 0) {
+ defaultGasRequired = DEFAULT_CHUNK_GAS_REQUIRED;
+ }
+ return calls
+ // first sort by gas required
+ .sort(function (c1, c2) {
+ var _c2$gasRequired, _c1$gasRequired;
+ return ((_c2$gasRequired = c2.gasRequired) != null ? _c2$gasRequired : defaultGasRequired) - ((_c1$gasRequired = c1.gasRequired) != null ? _c1$gasRequired : defaultGasRequired);
+ })
+ // then bin the calls according to the first fit algorithm
+ .reduce(function (bins, call) {
+ var _call$gasRequired;
+ var gas = (_call$gasRequired = call.gasRequired) != null ? _call$gasRequired : defaultGasRequired;
+ for (var _iterator = _createForOfIteratorHelperLoose(bins), _step; !(_step = _iterator()).done;) {
+ var bin = _step.value;
+ if (bin.cumulativeGasLimit + gas <= chunkGasLimit) {
+ bin.calls.push(call);
+ bin.cumulativeGasLimit += gas;
+ return bins;
+ }
+ }
+ // didn't find a bin for the call, make a new bin
+ bins.push({
+ calls: [call],
+ cumulativeGasLimit: gas
+ });
+ return bins;
+ }, [])
+ // pull out just the calls from each bin
+ .map(function (b) {
+ return b.calls;
+ });
+}
+
+// TODO de-duplicate this file with web interface
+// https://github.com/Uniswap/interface/blob/main/src/utils/retry.ts
+function wait(ms) {
+ return new Promise(function (resolve) {
+ return setTimeout(resolve, ms);
+ });
+}
+function waitRandom(min, max) {
+ return wait(min + Math.round(Math.random() * Math.max(0, max - min)));
+}
+/**
+ * This error is thrown if the function is cancelled before completing
+ */
+var CancelledError = /*#__PURE__*/function (_Error) {
+ function CancelledError() {
+ var _this;
+ _this = _Error.call(this, 'Cancelled') || this;
+ _this.isCancelledError = true;
+ return _this;
+ }
+ _inheritsLoose(CancelledError, _Error);
+ return CancelledError;
+}( /*#__PURE__*/_wrapNativeSuper(Error));
+/**
+ * Throw this error if the function should retry
+ */
+var RetryableError = /*#__PURE__*/function (_Error2) {
+ function RetryableError() {
+ var _this2;
+ _this2 = _Error2.apply(this, arguments) || this;
+ _this2.isRetryableError = true;
+ return _this2;
+ }
+ _inheritsLoose(RetryableError, _Error2);
+ return RetryableError;
+}( /*#__PURE__*/_wrapNativeSuper(Error));
+/**
+ * Retries the function that returns the promise until the promise successfully resolves up to n retries
+ * @param fn function to retry
+ * @param n how many times to retry
+ * @param minWait min wait between retries in ms
+ * @param maxWait max wait between retries in ms
+ */
+function retry(fn, _ref) {
+ var n = _ref.n,
+ minWait = _ref.minWait,
+ maxWait = _ref.maxWait;
+ var completed = false;
+ var rejectCancelled;
+ var promise = new Promise( /*#__PURE__*/function () {
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(resolve, reject) {
+ var result;
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
+ while (1) switch (_context.prev = _context.next) {
+ case 0:
+ rejectCancelled = reject;
+ case 1:
+ result = void 0;
+ _context.prev = 3;
+ _context.next = 6;
+ return fn();
+ case 6:
+ result = _context.sent;
+ if (!completed) {
+ resolve(result);
+ completed = true;
+ }
+ return _context.abrupt("break", 24);
+ case 11:
+ _context.prev = 11;
+ _context.t0 = _context["catch"](3);
+ if (!completed) {
+ _context.next = 15;
+ break;
+ }
+ return _context.abrupt("break", 24);
+ case 15:
+ if (!(n <= 0 || !_context.t0.isRetryableError)) {
+ _context.next = 19;
+ break;
+ }
+ reject(_context.t0);
+ completed = true;
+ return _context.abrupt("break", 24);
+ case 19:
+ n--;
+ case 20:
+ _context.next = 22;
+ return waitRandom(minWait, maxWait);
+ case 22:
+ _context.next = 1;
+ break;
+ case 24:
+ case "end":
+ return _context.stop();
+ }
+ }, _callee, null, [[3, 11]]);
+ }));
+ return function (_x, _x2) {
+ return _ref2.apply(this, arguments);
+ };
+ }());
+ return {
+ promise: promise,
+ cancel: function cancel() {
+ if (completed) return;
+ completed = true;
+ rejectCancelled(new CancelledError());
+ }
+ };
+}
+
+// TODO de-duplicate this file with web interface
+// modified from https://usehooks.com/useDebounce/
+function useDebounce(value, delay) {
+ var _useState = useState(value),
+ debouncedValue = _useState[0],
+ setDebouncedValue = _useState[1];
+ useEffect(function () {
+ // Update debounced value after delay
+ var handler = setTimeout(function () {
+ setDebouncedValue(value);
+ }, delay);
+ // Cancel the timeout if value changes (also on delay change or unmount)
+ // This is how we prevent debounced value from updating if value is changed ...
+ // .. within the delay period. Timeout gets cleared and restarted.
+ return function () {
+ clearTimeout(handler);
+ };
+ }, [value, delay]);
+ return debouncedValue;
+}
+
+var IMulticallABI = [{
+ inputs: [],
+ name: 'getCurrentBlockTimestamp',
+ outputs: [{
+ internalType: 'uint256',
+ name: 'timestamp',
+ type: 'uint256'
+ }],
+ stateMutability: 'view',
+ type: 'function'
+}, {
+ inputs: [{
+ internalType: 'address',
+ name: 'addr',
+ type: 'address'
+ }],
+ name: 'getEthBalance',
+ outputs: [{
+ internalType: 'uint256',
+ name: 'balance',
+ type: 'uint256'
+ }],
+ stateMutability: 'view',
+ type: 'function'
+}, {
+ inputs: [{
+ components: [{
+ internalType: 'address',
+ name: 'target',
+ type: 'address'
+ }, {
+ internalType: 'uint256',
+ name: 'gasLimit',
+ type: 'uint256'
+ }, {
+ internalType: 'bytes',
+ name: 'callData',
+ type: 'bytes'
+ }],
+ internalType: 'struct PancakeInterfaceMulticall.Call[]',
+ name: 'calls',
+ type: 'tuple[]'
+ }],
+ name: 'multicall',
+ outputs: [{
+ internalType: 'uint256',
+ name: 'blockNumber',
+ type: 'uint256'
+ }, {
+ components: [{
+ internalType: 'bool',
+ name: 'success',
+ type: 'bool'
+ }, {
+ internalType: 'uint256',
+ name: 'gasUsed',
+ type: 'uint256'
+ }, {
+ internalType: 'bytes',
+ name: 'returnData',
+ type: 'bytes'
+ }],
+ internalType: 'struct PancakeInterfaceMulticall.Result[]',
+ name: 'returnData',
+ type: 'tuple[]'
+ }],
+ stateMutability: 'nonpayable',
+ type: 'function'
+}];
+
+var FETCH_RETRY_CONFIG = {
+ n: Infinity,
+ minWait: 1000,
+ maxWait: 2500
+};
+/**
+ * Fetches a chunk of calls, enforcing a minimum block number constraint
+ * @param multicall multicall contract to fetch against
+ * @param chunk chunk of calls to make
+ * @param blockNumber block number passed as the block tag in the eth_call
+ */
+function fetchChunk(_x, _x2, _x3, _x4) {
+ return _fetchChunk.apply(this, arguments);
+}
+/**
+ * From the current all listeners state, return each call key mapped to the
+ * minimum number of blocks per fetch. This is how often each key must be fetched.
+ * @param allListeners the all listeners state
+ * @param chainId the current chain id
+ */
+function _fetchChunk() {
+ _fetchChunk = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(multicallInfo, chunk, blockNumber, isDebug) {
+ var _yield$multicallInfo$, _yield$multicallInfo$2, returnData, _error$message, _error$message2, error, half, _yield$Promise$all, c0, c1;
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
+ while (1) switch (_context.prev = _context.next) {
+ case 0:
+ console.debug('Fetching chunk', chunk, blockNumber, chunk.map(function (obj) {
+ var _obj$gasRequired;
+ return {
+ target: obj.address,
+ callData: obj.callData,
+ gasLimit: (_obj$gasRequired = obj.gasRequired) != null ? _obj$gasRequired : DEFAULT_CALL_GAS_REQUIRED
+ };
+ }));
+ _context.prev = 1;
+ _context.next = 4;
+ return multicallInfo.provider.simulateContract({
+ abi: IMulticallABI,
+ address: multicallInfo.address,
+ functionName: 'multicall',
+ args: [chunk.map(function (obj) {
+ var _obj$gasRequired2;
+ return {
+ target: obj.address,
+ callData: obj.callData,
+ gasLimit: (_obj$gasRequired2 = obj.gasRequired) != null ? _obj$gasRequired2 : DEFAULT_CALL_GAS_REQUIRED
+ };
+ })],
+ // we aren't passing through the block gas limit we used to create the chunk, because it causes a problem with the integ tests
+ blockNumber: BigInt(blockNumber)
+ });
+ case 4:
+ _yield$multicallInfo$ = _context.sent;
+ _yield$multicallInfo$2 = _yield$multicallInfo$.result;
+ returnData = _yield$multicallInfo$2[1];
+ if (isDebug) {
+ returnData.forEach(function (_ref, i) {
+ var _chunk$i$gasRequired;
+ var gasUsed = _ref.gasUsed,
+ returnData = _ref.returnData,
+ success = _ref.success;
+ if (!success && returnData.length === 2 && gasUsed >= Math.floor(((_chunk$i$gasRequired = chunk[i].gasRequired) != null ? _chunk$i$gasRequired : DEFAULT_CALL_GAS_REQUIRED) * 0.95)) {
+ var _chunk$i$gasRequired2;
+ console.warn("A call failed due to requiring " + gasUsed.toString() + " vs. allowed " + ((_chunk$i$gasRequired2 = chunk[i].gasRequired) != null ? _chunk$i$gasRequired2 : DEFAULT_CALL_GAS_REQUIRED), chunk[i]);
+ }
+ });
+ }
+ return _context.abrupt("return", returnData);
+ case 11:
+ _context.prev = 11;
+ _context.t0 = _context["catch"](1);
+ error = _context.t0;
+ if (!(error.code === -32000 || ((_error$message = error.message) == null ? void 0 : _error$message.indexOf('header not found')) !== -1)) {
+ _context.next = 18;
+ break;
+ }
+ throw new RetryableError("header not found for block number " + blockNumber);
+ case 18:
+ if (!(error.code === -32603 || ((_error$message2 = error.message) == null ? void 0 : _error$message2.indexOf('execution ran out of gas')) !== -1)) {
+ _context.next = 28;
+ break;
+ }
+ if (!(chunk.length > 1)) {
+ _context.next = 28;
+ break;
+ }
+ if (process.env.NODE_ENV === 'development') {
+ console.debug('Splitting a chunk in 2', chunk);
+ }
+ half = Math.floor(chunk.length / 2);
+ _context.next = 24;
+ return Promise.all([fetchChunk(multicallInfo, chunk.slice(0, half), blockNumber), fetchChunk(multicallInfo, chunk.slice(half, chunk.length), blockNumber)]);
+ case 24:
+ _yield$Promise$all = _context.sent;
+ c0 = _yield$Promise$all[0];
+ c1 = _yield$Promise$all[1];
+ return _context.abrupt("return", c0.concat(c1));
+ case 28:
+ console.error('Failed to fetch chunk', error);
+ throw error;
+ case 30:
+ case "end":
+ return _context.stop();
+ }
+ }, _callee, null, [[1, 11]]);
+ }));
+ return _fetchChunk.apply(this, arguments);
+}
+function activeListeningKeys(allListeners, chainId) {
+ if (!allListeners || !chainId) return {};
+ var listeners = allListeners[chainId];
+ if (!listeners) return {};
+ return Object.keys(listeners).reduce(function (memo, callKey) {
+ var keyListeners = listeners[callKey];
+ memo[callKey] = Object.keys(keyListeners).filter(function (key) {
+ var blocksPerFetch = parseInt(key);
+ if (blocksPerFetch <= 0) return false;
+ return keyListeners[blocksPerFetch] > 0;
+ }).reduce(function (previousMin, current) {
+ return Math.min(previousMin, parseInt(current));
+ }, Infinity);
+ return memo;
+ }, {});
+}
+/**
+ * Return the keys that need to be refetched
+ * @param callResults current call result state
+ * @param listeningKeys each call key mapped to how old the data can be in blocks
+ * @param chainId the current chain id
+ * @param latestBlockNumber the latest block number
+ */
+function outdatedListeningKeys(callResults, listeningKeys, chainId, latestBlockNumber) {
+ if (!chainId || !latestBlockNumber) return [];
+ var results = callResults[chainId];
+ // no results at all, load everything
+ if (!results) return Object.keys(listeningKeys);
+ return Object.keys(listeningKeys).filter(function (callKey) {
+ var blocksPerFetch = listeningKeys[callKey];
+ var data = callResults[chainId][callKey];
+ // no data, must fetch
+ if (!data) return true;
+ var minDataBlockNumber = latestBlockNumber - (blocksPerFetch - 1);
+ // already fetching it for a recent enough block, don't refetch it
+ if (data.fetchingBlockNumber && data.fetchingBlockNumber >= minDataBlockNumber) return false;
+ // if data is older than minDataBlockNumber, fetch it
+ return !data.blockNumber || data.blockNumber < minDataBlockNumber;
+ });
+}
+function onFetchChunkSuccess(context, chunk, result) {
+ var actions = context.actions,
+ dispatch = context.dispatch,
+ chainId = context.chainId,
+ latestBlockNumber = context.latestBlockNumber,
+ isDebug = context.isDebug;
+ // split the returned slice into errors and results
+ var _chunk$reduce = chunk.reduce(function (memo, call, i) {
+ if (result[i].success) {
+ var _result$i$returnData;
+ memo.results[toCallKey(call)] = (_result$i$returnData = result[i].returnData) != null ? _result$i$returnData : null;
+ } else {
+ memo.erroredCalls.push(call);
+ }
+ return memo;
+ }, {
+ erroredCalls: [],
+ results: {}
+ }),
+ erroredCalls = _chunk$reduce.erroredCalls,
+ results = _chunk$reduce.results;
+ // dispatch any new results
+ if (Object.keys(results).length > 0) dispatch(actions.updateMulticallResults({
+ chainId: chainId,
+ results: results,
+ blockNumber: latestBlockNumber
+ }));
+ // dispatch any errored calls
+ if (erroredCalls.length > 0) {
+ if (isDebug) {
+ result.forEach(function (returnData, ix) {
+ if (!returnData.success) {
+ console.debug('Call failed', chunk[ix], returnData);
+ }
+ });
+ } else {
+ console.debug('Calls errored in fetch', erroredCalls);
+ }
+ dispatch(actions.errorFetchingMulticallResults({
+ calls: erroredCalls,
+ chainId: chainId,
+ fetchingBlockNumber: latestBlockNumber
+ }));
+ }
+}
+function onFetchChunkFailure(context, chunk, error) {
+ var actions = context.actions,
+ dispatch = context.dispatch,
+ chainId = context.chainId,
+ latestBlockNumber = context.latestBlockNumber;
+ if (error.isCancelledError) {
+ console.debug('Cancelled fetch for blockNumber', latestBlockNumber, chunk, chainId);
+ return;
+ }
+ console.error('Failed to fetch multicall chunk', chunk, chainId, error);
+ dispatch(actions.errorFetchingMulticallResults({
+ calls: chunk,
+ chainId: chainId,
+ fetchingBlockNumber: latestBlockNumber
+ }));
+}
+function Updater(props) {
+ var context = props.context,
+ chainId = props.chainId,
+ latestBlockNumber = props.latestBlockNumber,
+ multicallInfo = props.multicallInfo,
+ isDebug = props.isDebug,
+ listenerOptions = props.listenerOptions;
+ var actions = context.actions,
+ reducerPath = context.reducerPath;
+ var dispatch = useDispatch();
+ // set user configured listenerOptions in state for given chain ID.
+ useEffect(function () {
+ if (chainId && listenerOptions) {
+ dispatch(actions.updateListenerOptions({
+ chainId: chainId,
+ listenerOptions: listenerOptions
+ }));
+ }
+ }, [chainId, listenerOptions, actions, dispatch]);
+ var state = useSelector(function (state) {
+ return state[reducerPath];
+ });
+ // wait for listeners to settle before triggering updates
+ var debouncedListeners = useDebounce(state.callListeners, 100);
+ var cancellations = useRef();
+ var listeningKeys = useMemo(function () {
+ return activeListeningKeys(debouncedListeners, chainId);
+ }, [debouncedListeners, chainId]);
+ var serializedOutdatedCallKeys = useMemo(function () {
+ var outdatedCallKeys = outdatedListeningKeys(state.callResults, listeningKeys, chainId, latestBlockNumber);
+ return JSON.stringify(outdatedCallKeys.sort());
+ }, [chainId, state.callResults, listeningKeys, latestBlockNumber]);
+ useEffect(function () {
+ if (!latestBlockNumber || !chainId || !multicallInfo) return;
+ var outdatedCallKeys = JSON.parse(serializedOutdatedCallKeys);
+ if (outdatedCallKeys.length === 0) return;
+ var calls = outdatedCallKeys.map(function (key) {
+ return parseCallKey(key);
+ });
+ var chunkedCalls = chunkCalls(calls, CHUNK_GAS_LIMIT);
+ if (cancellations.current && cancellations.current.blockNumber !== latestBlockNumber) {
+ cancellations.current.cancellations.forEach(function (c) {
+ return c();
+ });
+ }
+ dispatch(actions.fetchingMulticallResults({
+ calls: calls,
+ chainId: chainId,
+ fetchingBlockNumber: latestBlockNumber
+ }));
+ var fetchChunkContext = {
+ actions: actions,
+ dispatch: dispatch,
+ chainId: chainId,
+ latestBlockNumber: latestBlockNumber,
+ isDebug: isDebug
+ };
+ // Execute fetches and gather cancellation callbacks
+ var newCancellations = chunkedCalls.map(function (chunk) {
+ var _retry = retry(function () {
+ return fetchChunk(multicallInfo, chunk, latestBlockNumber, isDebug);
+ }, FETCH_RETRY_CONFIG),
+ cancel = _retry.cancel,
+ promise = _retry.promise;
+ promise.then(function (result) {
+ return onFetchChunkSuccess(fetchChunkContext, chunk, result);
+ })["catch"](function (error) {
+ return onFetchChunkFailure(fetchChunkContext, chunk, error);
+ });
+ return cancel;
+ });
+ cancellations.current = {
+ blockNumber: latestBlockNumber,
+ cancellations: newCancellations
+ };
+ }, [actions, chainId, multicallInfo, dispatch, serializedOutdatedCallKeys, latestBlockNumber, isDebug]);
+ return null;
+}
+function createUpdater(context) {
+ var UpdaterContextBound = function UpdaterContextBound(props) {
+ return React.createElement(Updater, Object.assign({
+ context: context
+ }, props));
+ };
+ return UpdaterContextBound;
+}
+
+// Inspired by RTK Query's createApi
+function createMulticall(options) {
+ var _options$reducerPath;
+ var reducerPath = (_options$reducerPath = options == null ? void 0 : options.reducerPath) != null ? _options$reducerPath : 'multicall';
+ var slice = createMulticallSlice(reducerPath);
+ var actions = slice.actions,
+ reducer = slice.reducer;
+ var context = {
+ reducerPath: reducerPath,
+ actions: actions
+ };
+ var useMultipleContractSingleData$1 = function useMultipleContractSingleData$1() {
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+ return useMultipleContractSingleData.apply(void 0, [context].concat(args));
+ };
+ var useSingleContractMultipleData$1 = function useSingleContractMultipleData$1() {
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+ return useSingleContractMultipleData.apply(void 0, [context].concat(args));
+ };
+ var useSingleContractWithCallData$1 = function useSingleContractWithCallData$1() {
+ for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
+ args[_key3] = arguments[_key3];
+ }
+ return useSingleContractWithCallData.apply(void 0, [context].concat(args));
+ };
+ var useSingleCallResult$1 = function useSingleCallResult$1() {
+ for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
+ args[_key4] = arguments[_key4];
+ }
+ return useSingleCallResult.apply(void 0, [context].concat(args));
+ };
+ var useMultiChainMultiContractSingleData$1 = function useMultiChainMultiContractSingleData$1() {
+ for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
+ args[_key5] = arguments[_key5];
+ }
+ return useMultiChainMultiContractSingleData.apply(void 0, [context].concat(args));
+ };
+ var useMultiChainSingleContractSingleData$1 = function useMultiChainSingleContractSingleData$1() {
+ for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
+ args[_key6] = arguments[_key6];
+ }
+ return useMultiChainSingleContractSingleData.apply(void 0, [context].concat(args));
+ };
+ var hooks = {
+ useMultipleContractSingleData: useMultipleContractSingleData$1,
+ useSingleContractMultipleData: useSingleContractMultipleData$1,
+ useSingleContractWithCallData: useSingleContractWithCallData$1,
+ useSingleCallResult: useSingleCallResult$1,
+ useMultiChainMultiContractSingleData: useMultiChainMultiContractSingleData$1,
+ useMultiChainSingleContractSingleData: useMultiChainSingleContractSingleData$1
+ };
+ var Updater = createUpdater(context);
+ return {
+ reducerPath: reducerPath,
+ reducer: reducer,
+ actions: actions,
+ hooks: hooks,
+ Updater: Updater
+ };
+}
+
+export { CHUNK_GAS_LIMIT, CONSERVATIVE_BLOCK_GAS_LIMIT, DEFAULT_BLOCKS_PER_FETCH, DEFAULT_CALL_GAS_REQUIRED, DEFAULT_CHUNK_GAS_REQUIRED, INVALID_CALL_STATE, INVALID_RESULT, LOADING_CALL_STATE, NEVER_RELOAD, createMulticall };
+//# sourceMappingURL=redux-multicall-viem.esm.js.map
diff --git a/dist/redux-multicall-viem.esm.js.map b/dist/redux-multicall-viem.esm.js.map
new file mode 100644
index 0000000..103739f
--- /dev/null
+++ b/dist/redux-multicall-viem.esm.js.map
@@ -0,0 +1 @@
+{"version":3,"file":"redux-multicall-viem.esm.js","sources":["../src/constants.ts","../src/utils/callKeys.ts","../src/utils/callState.ts","../src/validation.ts","../src/hooks.ts","../src/slice.ts","../src/utils/chunkCalls.ts","../src/utils/retry.ts","../src/utils/useDebounce.ts","../src/abi/InterfaceMulticall.ts","../src/updater.tsx","../src/create.ts"],"sourcesContent":["import type { CallResult, CallState, ListenerOptions } from './types'\n\nexport const DEFAULT_BLOCKS_PER_FETCH = 1\nexport const DEFAULT_CALL_GAS_REQUIRED = 1_000_000\nexport const DEFAULT_CHUNK_GAS_REQUIRED = 200_000\nexport const CHUNK_GAS_LIMIT = 100_000_000\nexport const CONSERVATIVE_BLOCK_GAS_LIMIT = 10_000_000 // conservative, hard-coded estimate of the current block gas limit\n\n// Consts for hooks\nexport const INVALID_RESULT: CallResult = { valid: false, blockNumber: undefined, data: undefined }\nexport const NEVER_RELOAD: ListenerOptions = {\n blocksPerFetch: Infinity,\n}\n\nexport const INVALID_CALL_STATE: CallState = {\n valid: false,\n result: undefined,\n loading: false,\n syncing: false,\n error: false,\n}\nexport const LOADING_CALL_STATE: CallState = {\n valid: true,\n result: undefined,\n loading: true,\n syncing: true,\n error: false,\n}\n","import { Call } from '../types'\n\nexport function toCallKey(call: Call): string {\n let key = `${call.address}-${call.callData}`\n if (call.gasRequired) {\n if (!Number.isSafeInteger(call.gasRequired)) {\n throw new Error(`Invalid number: ${call.gasRequired}`)\n }\n key += `-${call.gasRequired}`\n }\n return key\n}\n\nexport function parseCallKey(callKey: string): Call {\n const pcs = callKey.split('-')\n if (![2, 3].includes(pcs.length)) {\n throw new Error(`Invalid call key: ${callKey}`)\n }\n return {\n address: pcs[0],\n callData: pcs[1],\n ...(pcs[2] ? { gasRequired: Number.parseInt(pcs[2]) } : {}),\n }\n}\n\nexport function callsToCallKeys(calls?: Array) {\n return (\n calls\n ?.filter((c): c is Call => Boolean(c))\n ?.map(toCallKey)\n ?.sort() ?? []\n )\n}\n\nexport function callKeysToCalls(callKeys: string[]) {\n if (!callKeys?.length) return null\n return callKeys.map((key) => parseCallKey(key))\n}\n","import { useMemo } from 'react'\nimport { INVALID_CALL_STATE, LOADING_CALL_STATE } from '../constants'\nimport type { CallResult, CallState, CallStateResult } from '../types'\nimport { AbiFunction, decodeFunctionResult } from 'viem'\n\n// Converts CallResult[] to CallState[], only updating if call states have changed.\n// Ensures that CallState results remain referentially stable when unchanged, preventing\n// spurious re-renders which would otherwise occur because mapping always creates a new object.\nexport function useCallStates(\n results: CallResult[],\n contractInterface: AbiFunction[] | undefined,\n fragment: ((i: number) => string | undefined) | string | undefined,\n latestBlockNumber: number | undefined\n): CallState[] {\n // Avoid refreshing the results with every changing block number (eg latestBlockNumber).\n // Instead, only refresh the results if they need to be synced - if there is a result which is stale, for which blockNumber < latestBlockNumber.\n const syncingBlockNumber = useMemo(() => {\n const lowestBlockNumber = results.reduce(\n (memo, result) => (result.blockNumber ? Math.min(memo ?? result.blockNumber, result.blockNumber) : memo),\n undefined\n )\n return Math.max(lowestBlockNumber ?? 0, latestBlockNumber ?? 0)\n }, [results, latestBlockNumber])\n\n return useMemo(() => {\n return results.map((result, i) => {\n const resultFragment = typeof fragment === 'function' ? fragment(i) : fragment\n return toCallState(result, contractInterface, resultFragment, syncingBlockNumber)\n })\n }, [contractInterface, fragment, results, syncingBlockNumber])\n}\n\nexport function toCallState(\n callResult: CallResult | undefined,\n contractInterface: AbiFunction[] | undefined,\n fragment: string | undefined,\n syncingBlockNumber: number | undefined\n): CallState {\n if (!callResult || !callResult.valid) {\n return INVALID_CALL_STATE\n }\n\n const { data, blockNumber } = callResult\n if (!blockNumber || !contractInterface || !fragment || !syncingBlockNumber) {\n return LOADING_CALL_STATE\n }\n\n const success = data && data.length > 2\n const syncing = blockNumber < syncingBlockNumber\n let result: CallStateResult | undefined = undefined\n if (success && data) {\n try {\n result = (decodeFunctionResult as any)({\n abi: contractInterface,\n functionName: fragment,\n data: data as any,\n }) as any\n } catch (error) {\n console.debug('Result data parsing failed', fragment, data)\n return {\n valid: true,\n loading: false,\n error: true,\n syncing,\n result,\n }\n }\n }\n return {\n valid: true,\n loading: false,\n syncing,\n result,\n error: !success,\n }\n}\n","export type MethodArg = string | number | BigInt\nexport type MethodArgs = Array\n\nexport function isMethodArg(x: unknown): x is MethodArg {\n return (x === null || x === undefined) ? false : typeof BigInt(x as any) === 'bigint' || ['string', 'number'].indexOf(typeof x) !== -1\n}\n\nexport function isValidMethodArgs(x: unknown): x is MethodArgs | undefined {\n return (\n x === undefined ||\n (Array.isArray(x) && x.every((xi) => isMethodArg(xi) || (Array.isArray(xi) && xi.every(isMethodArg))))\n )\n}\n","import { useCallback, useEffect, useMemo, useRef } from 'react'\nimport { batch, useDispatch, useSelector } from 'react-redux'\nimport { INVALID_CALL_STATE, INVALID_RESULT, DEFAULT_BLOCKS_PER_FETCH } from './constants'\nimport type { MulticallContext } from './context'\nimport type {\n Call,\n CallResult,\n CallState,\n ContractInfo,\n ListenerOptions,\n ListenerOptionsWithGas,\n WithMulticallState,\n} from './types'\nimport { callKeysToCalls, callsToCallKeys, toCallKey } from './utils/callKeys'\nimport { toCallState, useCallStates } from './utils/callState'\nimport { isValidMethodArgs, MethodArg } from './validation'\nimport { AbiFunction, encodeFunctionData, getAbiItem } from 'viem'\n\ntype OptionalMethodInputs = Array | undefined\n\n// the lowest level call for subscribing to contract data\nexport function useCallsDataSubscription(\n context: MulticallContext,\n chainId: number | undefined,\n calls: Array,\n listenerOptions?: ListenerOptions\n): CallResult[] {\n const { reducerPath, actions } = context\n const callResults = useSelector((state: WithMulticallState) => state[reducerPath].callResults)\n const defaultListenerOptions = useSelector((state: WithMulticallState) => state[reducerPath].listenerOptions)\n const dispatch = useDispatch()\n const serializedCallKeys: string = useMemo(() => JSON.stringify(callsToCallKeys(calls)), [calls])\n\n // update listeners when there is an actual change that persists for at least 100ms\n useEffect(() => {\n const callKeys: string[] = JSON.parse(serializedCallKeys)\n const calls = callKeysToCalls(callKeys)\n if (!chainId || !calls) return\n const blocksPerFetchFromState = (defaultListenerOptions ?? {})[chainId]?.blocksPerFetch\n const blocksPerFetchForChain =\n listenerOptions?.blocksPerFetch ?? blocksPerFetchFromState ?? DEFAULT_BLOCKS_PER_FETCH\n\n dispatch(\n actions.addMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n\n return () => {\n dispatch(\n actions.removeMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n }\n }, [actions, chainId, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions])\n\n const lastResults = useRef([])\n return useMemo(() => {\n let isChanged = lastResults.current.length !== calls.length\n\n // Construct results using a for-loop to handle sparse arrays.\n // Array.prototype.map would skip empty entries.\n let results: CallResult[] = []\n for (let i = 0; i < calls.length; ++i) {\n const call = calls[i]\n let result = INVALID_RESULT\n if (chainId && call) {\n const callResult = callResults[chainId]?.[toCallKey(call)]\n result = {\n valid: true,\n data: callResult?.data && callResult.data !== '0x' ? callResult.data : undefined,\n blockNumber: callResult?.blockNumber,\n }\n }\n\n isChanged = isChanged || !areCallResultsEqual(result, lastResults.current[i])\n results.push(result)\n }\n\n // Force the results to be referentially stable if they have not changed.\n // This is necessary because *all* callResults are passed as deps when initially memoizing the results.\n if (isChanged) {\n lastResults.current = results\n }\n return lastResults.current\n }, [callResults, calls, chainId])\n}\n\nfunction areCallResultsEqual(a: CallResult, b: CallResult) {\n return a.valid === b.valid && a.data === b.data && a.blockNumber === b.blockNumber\n}\n\n// Similar to useCallsDataSubscription above but for subscribing to\n// calls to multiple chains at once\nfunction useMultichainCallsDataSubscription(\n context: MulticallContext,\n chainToCalls: Record>,\n listenerOptions?: ListenerOptions\n): Record {\n const { reducerPath, actions } = context\n const callResults = useSelector((state: WithMulticallState) => state[reducerPath].callResults)\n const defaultListenerOptions = useSelector((state: WithMulticallState) => state[reducerPath].listenerOptions)\n const dispatch = useDispatch()\n\n const serializedCallKeys: string = useMemo(() => {\n const sortedChainIds = getChainIds(chainToCalls).sort()\n const chainCallKeysTuple = sortedChainIds.map((chainId) => {\n const calls = chainToCalls[chainId]\n const callKeys = callsToCallKeys(calls)\n // Note, using a tuple to ensure consistent order when serialized\n return [chainId, callKeys]\n })\n return JSON.stringify(chainCallKeysTuple)\n }, [chainToCalls])\n\n useEffect(() => {\n const chainCallKeysTuples: Array<[number, string[]]> = JSON.parse(serializedCallKeys)\n if (!chainCallKeysTuples?.length) return\n\n batch(() => {\n for (const [chainId, callKeys] of chainCallKeysTuples) {\n const calls = callKeysToCalls(callKeys)\n if (!calls?.length) continue\n const blocksPerFetchFromState = (defaultListenerOptions ?? {})[chainId]?.blocksPerFetch\n const blocksPerFetchForChain =\n listenerOptions?.blocksPerFetch ?? blocksPerFetchFromState ?? DEFAULT_BLOCKS_PER_FETCH\n\n dispatch(\n actions.addMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n }\n })\n\n return () => {\n batch(() => {\n for (const [chainId, callKeys] of chainCallKeysTuples) {\n const calls = callKeysToCalls(callKeys)\n if (!calls?.length) continue\n const blocksPerFetchFromState = (defaultListenerOptions ?? {})[chainId]?.blocksPerFetch\n const blocksPerFetchForChain =\n listenerOptions?.blocksPerFetch ?? blocksPerFetchFromState ?? DEFAULT_BLOCKS_PER_FETCH\n dispatch(\n actions.removeMulticallListeners({\n chainId,\n calls,\n options: { blocksPerFetch: blocksPerFetchForChain },\n })\n )\n }\n })\n }\n }, [actions, dispatch, listenerOptions, serializedCallKeys, defaultListenerOptions])\n\n return useMemo(\n () =>\n getChainIds(chainToCalls).reduce((result, chainId) => {\n const calls = chainToCalls[chainId]\n result[chainId] = calls.map((call) => {\n if (!chainId || !call) return INVALID_RESULT\n const result = callResults[chainId]?.[toCallKey(call)]\n const data = result?.data && result.data !== '0x' ? result.data : undefined\n return { valid: true, data, blockNumber: result?.blockNumber }\n })\n return result\n }, {} as Record),\n [callResults, chainToCalls]\n )\n}\n\n// formats many calls to a single function on a single contract, with the function name and inputs specified\nexport function useSingleContractMultipleData(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n contract: ContractInfo | null | undefined,\n methodName: string,\n callInputs: OptionalMethodInputs[],\n options?: Partial\n): CallState[] {\n const { gasRequired } = options ?? {}\n\n // Create ethers function fragment\n const fragment = useMemo(\n () => contract && ((getAbiItem as any)({ abi: contract.abi, name: methodName } as any) as any)?.name,\n [contract, methodName]\n )\n\n // Get encoded call data. Note can't use useCallData below b.c. this is for a list of CallInputs\n const callDatas = useMemo(() => {\n if (!contract || !fragment) return []\n return callInputs.map((callInput) =>\n isValidMethodArgs(callInput)\n ? (encodeFunctionData as any)({\n abi: contract.abi,\n functionName: fragment,\n args: callInput,\n })\n : undefined\n )\n }, [callInputs, contract, fragment])\n\n // Create call objects\n const calls = useMemo(() => {\n if (!contract) return []\n return callDatas.map((callData) => {\n if (!callData) return undefined\n return {\n address: contract.address,\n callData,\n gasRequired,\n }\n })\n }, [contract, callDatas, gasRequired])\n\n // Subscribe to call data\n const results = useCallsDataSubscription(context, chainId, calls, options as ListenerOptions)\n return useCallStates(results, contract?.abi, fragment, latestBlockNumber)\n}\n\nexport function useMultipleContractSingleData(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n addresses: (string | undefined)[],\n contractInterface: AbiFunction[],\n methodName: string,\n callInputs?: OptionalMethodInputs,\n options?: Partial\n): CallState[] {\n const { gasRequired } = options ?? {}\n\n const { fragment, callData } = useCallData(methodName, contractInterface, callInputs)\n\n // Create call objects\n const calls = useMemo(() => {\n if (!callData) return []\n return addresses.map((address) => {\n if (!address) return undefined\n return { address, callData, gasRequired }\n })\n }, [addresses, callData, gasRequired])\n\n // Subscribe to call data\n const results = useCallsDataSubscription(context, chainId, calls, options as ListenerOptions)\n return useCallStates(results, contractInterface, fragment, latestBlockNumber)\n}\n\nexport function useSingleCallResult(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n contract: ContractInfo | null | undefined,\n methodName: string,\n inputs?: OptionalMethodInputs,\n options?: Partial\n): CallState {\n const callInputs = useMemo(() => [inputs], [inputs])\n return (\n useSingleContractMultipleData(context, chainId, latestBlockNumber, contract, methodName, callInputs, options)[0] ??\n INVALID_CALL_STATE\n )\n}\n\n// formats many calls to any number of functions on a single contract, with only the calldata specified\nexport function useSingleContractWithCallData(\n context: MulticallContext,\n chainId: number | undefined,\n latestBlockNumber: number | undefined,\n contract: ContractInfo | null | undefined,\n callDatas: string[],\n options?: Partial\n): CallState[] {\n const { gasRequired } = options ?? {}\n\n // Create call objects\n const calls = useMemo(() => {\n if (!contract) return []\n return callDatas.map((callData) => ({\n address: contract.address,\n callData,\n gasRequired,\n }))\n }, [callDatas, contract, gasRequired])\n\n // Subscribe to call data\n const results = useCallsDataSubscription(context, chainId, calls, options as ListenerOptions)\n const fragment = useCallback(\n (i: number) => ((getAbiItem as any)({ abi: contract?.abi as any, name: callDatas[i].substring(0, 10) }) as any)?.name,\n [callDatas, contract]\n )\n return useCallStates(results, contract?.abi, fragment, latestBlockNumber)\n}\n\n// Similar to useMultipleContractSingleData but instead of multiple contracts on one chain,\n// this is for querying compatible contracts on multiple chains\nexport function useMultiChainMultiContractSingleData(\n context: MulticallContext,\n chainToBlockNumber: Record,\n chainToAddresses: Record>,\n contractInterface: AbiFunction[],\n methodName: string,\n callInputs?: OptionalMethodInputs,\n options?: Partial\n): Record {\n const { gasRequired } = options ?? {}\n\n const { fragment, callData } = useCallData(methodName, contractInterface, callInputs)\n\n // Create call objects\n const chainToCalls = useMemo(() => {\n if (!callData || !chainToAddresses) return {}\n return getChainIds(chainToAddresses).reduce((result, chainId) => {\n const addresses = chainToAddresses[chainId]\n const calls = addresses.map((address) => {\n if (!address) return undefined\n return { address, callData, gasRequired }\n })\n result[chainId] = calls\n return result\n }, {} as Record>)\n }, [chainToAddresses, callData, gasRequired])\n\n // Subscribe to call data\n const chainIdToResults = useMultichainCallsDataSubscription(context, chainToCalls, options as ListenerOptions)\n\n // TODO(WEB-2097): Multichain states are not referentially stable, because they cannot use the\n // same codepath (eg useCallStates).\n return useMemo(() => {\n return getChainIds(chainIdToResults).reduce((combinedResults, chainId) => {\n const latestBlockNumber = chainToBlockNumber?.[chainId]\n const results = chainIdToResults[chainId]\n combinedResults[chainId] = results.map((result) =>\n toCallState(result, contractInterface, fragment, latestBlockNumber)\n )\n return combinedResults\n }, {} as Record)\n }, [fragment, contractInterface, chainIdToResults, chainToBlockNumber])\n}\n\n// Similar to useSingleCallResult but instead of one contract on one chain,\n// this is for querying a contract on multiple chains\nexport function useMultiChainSingleContractSingleData(\n context: MulticallContext,\n chainToBlockNumber: Record,\n chainToAddress: Record