@latticexyz/common 2.2.21-b18c0ef0edeab2378b08d9f4a328a5d0d817f6bf → 2.2.21-c67535174198d5cace8b7fdafaaff54a580f128a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/actions.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  writeContract
3
- } from "./chunk-324BIDBP.js";
3
+ } from "./chunk-ZRFZXVEA.js";
4
4
  import {
5
5
  sendTransaction
6
- } from "./chunk-5Q2OTK63.js";
6
+ } from "./chunk-HFWOVFQU.js";
7
7
  import "./chunk-73UWXFXB.js";
8
8
 
9
9
  // src/actions/transactionQueue.ts
@@ -105,11 +105,6 @@ async function getNonceManager({
105
105
  return nonceManager;
106
106
  }
107
107
 
108
- // src/sendTransaction.ts
109
- import { sendTransaction as viem_sendTransaction } from "viem/actions";
110
- import pRetry from "p-retry";
111
- import { parseAccount } from "viem/accounts";
112
-
113
108
  // src/getFeeRef.ts
114
109
  import { getChainId as getChainId2 } from "viem/actions";
115
110
 
@@ -118,13 +113,13 @@ import { estimateFeesPerGas } from "viem/actions";
118
113
  import { getAction as getAction3 } from "viem/utils";
119
114
  async function createFeeRef({ client, args, refreshInterval }) {
120
115
  const feeRef = { fees: {}, lastUpdatedTimestamp: 0 };
116
+ await updateFees();
117
+ setInterval(updateFees, refreshInterval);
121
118
  async function updateFees() {
122
119
  const fees = await getAction3(client, estimateFeesPerGas, "estimateFeesPerGas")(args);
123
120
  feeRef.fees = fees;
124
121
  feeRef.lastUpdatedTimestamp = Date.now();
125
122
  }
126
- setInterval(updateFees, refreshInterval);
127
- await updateFees();
128
123
  return feeRef;
129
124
  }
130
125
 
@@ -143,6 +138,9 @@ async function getFeeRef(opts) {
143
138
  }
144
139
 
145
140
  // src/sendTransaction.ts
141
+ import { sendTransaction as viem_sendTransaction } from "viem/actions";
142
+ import pRetry from "p-retry";
143
+ import { parseAccount } from "viem/accounts";
146
144
  import { getAction as getAction5 } from "viem/utils";
147
145
  var debug3 = debug.extend("sendTransaction");
148
146
  async function sendTransaction(client, request, opts = {}) {
@@ -205,4 +203,4 @@ export {
205
203
  getFeeRef,
206
204
  sendTransaction
207
205
  };
208
- //# sourceMappingURL=chunk-5Q2OTK63.js.map
206
+ //# sourceMappingURL=chunk-HFWOVFQU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/getNonceManagerId.ts","../src/findCause.ts","../src/createNonceManager.ts","../src/getNonceManager.ts","../src/getFeeRef.ts","../src/createFeeRef.ts","../src/sendTransaction.ts"],"sourcesContent":["import { BlockTag, Client, Hex, getAddress } from \"viem\";\nimport { getChainId } from \"viem/actions\";\nimport { getAction } from \"viem/utils\";\n\nexport async function getNonceManagerId({\n client,\n address,\n blockTag,\n}: {\n client: Client;\n address: Hex;\n blockTag: BlockTag;\n}): Promise<string> {\n // TODO: improve this so we don't have to call getChainId every time\n const chainId = client.chain?.id ?? (await getAction(client, getChainId, \"getChainId\")({}));\n return `mud:createNonceManager:${chainId}:${getAddress(address)}:${blockTag}`;\n}\n","export function findCause(error: Error, fn?: (error: Error) => boolean): Error | null {\n if (fn?.(error)) return error;\n if (error.cause instanceof Error) return findCause(error.cause, fn);\n return fn ? null : error;\n}\n","import { BlockTag, Client, Hex } from \"viem\";\nimport { debug as parentDebug } from \"./debug\";\nimport { getNonceManagerId } from \"./getNonceManagerId\";\nimport { getTransactionCount } from \"viem/actions\";\nimport PQueue from \"p-queue\";\nimport { getAction } from \"viem/utils\";\nimport { findCause } from \"./findCause\";\n\nconst debug = parentDebug.extend(\"createNonceManager\");\n\nexport type CreateNonceManagerOptions = {\n client: Client;\n address: Hex;\n blockTag?: BlockTag;\n broadcastChannelName?: string;\n queueConcurrency?: number;\n};\n\nexport type CreateNonceManagerResult = {\n hasNonce: () => boolean;\n getNonce: () => number;\n nextNonce: () => number;\n resetNonce: () => Promise<void>;\n shouldResetNonce: (error: Error) => boolean;\n mempoolQueue: PQueue;\n};\n\nexport function createNonceManager({\n client,\n address, // TODO: rename to account?\n blockTag = \"latest\",\n broadcastChannelName,\n queueConcurrency = 1,\n}: CreateNonceManagerOptions): CreateNonceManagerResult {\n const ref = { nonce: -1, noncePromise: null as Promise<void> | null };\n let channel: BroadcastChannel | null = null;\n\n if (typeof BroadcastChannel !== \"undefined\") {\n const channelName = broadcastChannelName\n ? Promise.resolve(broadcastChannelName)\n : getNonceManagerId({ client, address, blockTag });\n channelName.then((name) => {\n channel = new BroadcastChannel(name);\n // TODO: emit some sort of \"connected\" event so other channels can broadcast current nonce\n channel.addEventListener(\"message\", (event) => {\n const nonce = JSON.parse(event.data);\n debug(\"got nonce from broadcast channel\", nonce);\n ref.nonce = nonce;\n });\n });\n }\n\n function hasNonce(): boolean {\n return ref.nonce >= 0;\n }\n\n function getNonce(): number {\n if (!hasNonce()) throw new Error(\"call resetNonce before using getNonce\");\n return ref.nonce;\n }\n\n function nextNonce(): number {\n if (!hasNonce()) throw new Error(\"call resetNonce before using nextNonce\");\n const nonce = ref.nonce++;\n channel?.postMessage(JSON.stringify(ref.nonce));\n return nonce;\n }\n\n async function resetNonce(): Promise<void> {\n ref.noncePromise ??= (async (): Promise<void> => {\n ref.nonce = await getAction(client, getTransactionCount, \"getTransactionCount\")({ address, blockTag });\n ref.noncePromise = null;\n channel?.postMessage(JSON.stringify(ref.nonce));\n debug(\"reset nonce to\", ref.nonce);\n })();\n await ref.noncePromise;\n }\n\n function shouldResetNonce(error: Error): boolean {\n const nonceError = findCause(error, ({ name }) => name === \"NonceTooLowError\" || name === \"NonceTooHighError\");\n return nonceError != null;\n }\n\n const mempoolQueue = new PQueue({ concurrency: queueConcurrency });\n\n return {\n hasNonce,\n getNonce,\n nextNonce,\n resetNonce,\n shouldResetNonce,\n mempoolQueue,\n };\n}\n","import { CreateNonceManagerOptions, CreateNonceManagerResult, createNonceManager } from \"./createNonceManager\";\nimport { getNonceManagerId } from \"./getNonceManagerId\";\n\nconst nonceManagers = new Map<string, CreateNonceManagerResult>();\n\nexport async function getNonceManager({\n client,\n address, // TODO: rename to account?\n blockTag = \"latest\",\n ...opts\n}: CreateNonceManagerOptions): Promise<CreateNonceManagerResult> {\n const id = await getNonceManagerId({ client, address, blockTag });\n\n const nonceManager = nonceManagers.get(id) ?? createNonceManager({ client, address, blockTag, ...opts });\n if (!nonceManagers.has(id)) {\n nonceManagers.set(id, nonceManager);\n }\n\n if (!nonceManager.hasNonce()) {\n await nonceManager.resetNonce();\n }\n\n return nonceManager;\n}\n","import { getChainId } from \"viem/actions\";\nimport { CreateFeeRefOptions, FeeRef, createFeeRef } from \"./createFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst feeRefs = new Map<number, FeeRef>();\n\nexport async function getFeeRef(opts: CreateFeeRefOptions): Promise<FeeRef> {\n const chainId =\n opts.args?.chain?.id ?? opts.client.chain?.id ?? (await getAction(opts.client, getChainId, \"getChainId\")({}));\n\n const existingFeeRef = feeRefs.get(chainId);\n if (existingFeeRef) {\n return existingFeeRef;\n }\n\n const feeRef = await createFeeRef(opts);\n feeRefs.set(chainId, feeRef);\n return feeRef;\n}\n","import { EstimateFeesPerGasParameters, Client, EstimateFeesPerGasReturnType } from \"viem\";\nimport { estimateFeesPerGas } from \"viem/actions\";\nimport { getAction } from \"viem/utils\";\n\nexport type CreateFeeRefOptions = {\n client: Client;\n refreshInterval: number;\n args?: EstimateFeesPerGasParameters;\n};\n\nexport type FeeRef = {\n fees: EstimateFeesPerGasReturnType;\n lastUpdatedTimestamp: number;\n};\n\n/** Update fee values once every `refreshInterval` instead of right before every request */\nexport async function createFeeRef({ client, args, refreshInterval }: CreateFeeRefOptions): Promise<FeeRef> {\n const feeRef: FeeRef = { fees: {} as never, lastUpdatedTimestamp: 0 };\n await updateFees();\n setInterval(updateFees, refreshInterval);\n\n async function updateFees(): Promise<void> {\n const fees = await getAction(client, estimateFeesPerGas, \"estimateFeesPerGas\")(args);\n feeRef.fees = fees;\n feeRef.lastUpdatedTimestamp = Date.now();\n }\n\n return feeRef;\n}\n","import {\n Account,\n Chain,\n Client,\n SendTransactionParameters,\n Transport,\n SendTransactionReturnType,\n SendTransactionRequest,\n} from \"viem\";\nimport { sendTransaction as viem_sendTransaction } from \"viem/actions\";\nimport pRetry from \"p-retry\";\nimport { debug as parentDebug } from \"./debug\";\nimport { getNonceManager } from \"./getNonceManager\";\nimport { parseAccount } from \"viem/accounts\";\nimport { getFeeRef } from \"./getFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst debug = parentDebug.extend(\"sendTransaction\");\n\nexport type SendTransactionExtraOptions<chain extends Chain | undefined> = {\n /**\n * `publicClient` can be provided to be used in place of the extended viem client for making public action calls\n * (`getChainId`, `getTransactionCount`, `call`). This helps in cases where the extended\n * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),\n * where the transport is the bundler, not an RPC.\n */\n publicClient?: Client<Transport, chain>;\n /**\n * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered\n * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions\n * arriving out of order, but this may be an acceptable trade-off for some applications that can safely retry.\n * @default 1\n */\n queueConcurrency?: number;\n};\n\n/** @deprecated Use `walletClient.extend(transactionQueue())` instead. */\nexport async function sendTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends SendTransactionRequest<chain, chainOverride>,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n request: SendTransactionParameters<chain, account, chainOverride, request>,\n opts: SendTransactionExtraOptions<chain> = {},\n): Promise<SendTransactionReturnType> {\n const rawAccount = request.account ?? client.account;\n if (!rawAccount) {\n // TODO: replace with viem AccountNotFoundError once its exported\n throw new Error(\"No account provided\");\n }\n const account = parseAccount(rawAccount);\n const chain = client.chain;\n\n const nonceManager = await getNonceManager({\n client: opts.publicClient ?? client,\n address: account.address,\n queueConcurrency: opts.queueConcurrency,\n });\n\n const feeRef = await getFeeRef({\n client: opts.publicClient ?? client,\n refreshInterval: 10000,\n args: { chain },\n });\n\n return await nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n const nonce = nonceManager.nextNonce();\n const params = {\n // viem_sendTransaction internally estimates gas, which we want to happen on the pending block\n blockTag: \"pending\",\n ...feeRef.fees,\n ...request,\n nonce,\n } as const satisfies SendTransactionParameters<chain, account, chainOverride, request>;\n debug(\"sending tx to\", request.to, \"with nonce\", nonce);\n return await getAction(client, viem_sendTransaction, \"sendTransaction\")(params as never);\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // in case this tx failed before hitting the mempool (i.e. gas estimation error), reset nonce so we don't skip past the unused nonce\n debug(\"failed, resetting nonce\");\n await nonceManager.resetNonce();\n // retry nonce errors\n // TODO: upgrade p-retry and move this to shouldRetry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n return;\n }\n\n if (String(error).includes(\"transaction underpriced\")) {\n debug(\"got transaction underpriced error, retrying\", error.message);\n return;\n }\n\n throw error;\n },\n },\n ),\n { throwOnTimeout: true },\n );\n}\n"],"mappings":";;;;;AAAA,SAAgC,kBAAkB;AAClD,SAAS,kBAAkB;AAC3B,SAAS,iBAAiB;AAE1B,eAAsB,kBAAkB;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AACF,GAIoB;AAElB,QAAM,UAAU,OAAO,OAAO,MAAO,MAAM,UAAU,QAAQ,YAAY,YAAY,EAAE,CAAC,CAAC;AACzF,SAAO,0BAA0B,OAAO,IAAI,WAAW,OAAO,CAAC,IAAI,QAAQ;AAC7E;;;AChBO,SAAS,UAAU,OAAc,IAA8C;AACpF,MAAI,KAAK,KAAK,EAAG,QAAO;AACxB,MAAI,MAAM,iBAAiB,MAAO,QAAO,UAAU,MAAM,OAAO,EAAE;AAClE,SAAO,KAAK,OAAO;AACrB;;;ACDA,SAAS,2BAA2B;AACpC,OAAO,YAAY;AACnB,SAAS,aAAAA,kBAAiB;AAG1B,IAAMC,SAAQ,MAAY,OAAO,oBA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AAA,MACA;AAAA,QACE,SAAS;AAAA,QACT,iBAAiB,OAAO,UAAU;AAEhC,UAAAC,OAAM,yBAAyB;AAC/B,gBAAM,aAAa,WAAW;AAG9B,cAAI,aAAa,iBAAiB,KAAK,GAAG;AACxC,YAAAA,OAAM,6BAA6B,MAAM,OAAO;AAChD;AAAA,UACF;AAEA,cAAI,OAAO,KAAK,EAAE,SAAS,yBAAyB,GAAG;AACrD,YAAAA,OAAM,+CAA+C,MAAM,OAAO;AAClE;AAAA,UACF;AAEA,gBAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAAA,IACF,EAAE,gBAAgB,KAAK;AAAA,EACzB;AACF;","names":["getAction","debug","getAction","getChainId","getAction","getAction","getChainId","getAction","debug"]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  getFeeRef,
3
3
  getNonceManager
4
- } from "./chunk-5Q2OTK63.js";
4
+ } from "./chunk-HFWOVFQU.js";
5
5
  import {
6
6
  debug
7
7
  } from "./chunk-73UWXFXB.js";
@@ -67,4 +67,4 @@ async function writeContract(client, request, opts = {}) {
67
67
  export {
68
68
  writeContract
69
69
  };
70
- //# sourceMappingURL=chunk-324BIDBP.js.map
70
+ //# sourceMappingURL=chunk-ZRFZXVEA.js.map
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Hex, PrivateKeyAccount, Client, BlockTag, Chain, Transport, Account, SendTransactionRequest, SendTransactionParameters, SendTransactionReturnType, Abi, ContractFunctionName, ContractFunctionArgs, WriteContractParameters, WriteContractReturnType } from 'viem';
1
+ import { Hex, PrivateKeyAccount, Client, BlockTag, Chain, Transport, Account, SendTransactionRequest, SendTransactionParameters, SendTransactionReturnType, Abi, ContractFunctionName, ContractFunctionArgs, WriteContractParameters, WriteContractReturnType, EstimateFeesPerGasParameters, EstimateFeesPerGasReturnType } from 'viem';
2
2
  import PQueue from 'p-queue';
3
3
  import { g as getContract } from './getContract-CA0EdVg6.js';
4
4
  export { C as ContractWrite, G as GetContractOptions } from './getContract-CA0EdVg6.js';
@@ -148,6 +148,18 @@ type WriteContractExtraOptions<chain extends Chain | undefined> = {
148
148
  /** @deprecated Use `walletClient.extend(transactionQueue())` instead. */
149
149
  declare function writeContract<chain extends Chain | undefined, account extends Account | undefined, const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName<abi, "nonpayable" | "payable">, args extends ContractFunctionArgs<abi, "nonpayable" | "payable", functionName>, chainOverride extends Chain | undefined>(client: Client<Transport, chain, account>, request: WriteContractParameters<abi, functionName, args, chain, account, chainOverride>, opts?: WriteContractExtraOptions<chain>): Promise<WriteContractReturnType>;
150
150
 
151
+ type CreateFeeRefOptions = {
152
+ client: Client;
153
+ refreshInterval: number;
154
+ args?: EstimateFeesPerGasParameters;
155
+ };
156
+ type FeeRef = {
157
+ fees: EstimateFeesPerGasReturnType;
158
+ lastUpdatedTimestamp: number;
159
+ };
160
+
161
+ declare function getFeeRef(opts: CreateFeeRefOptions): Promise<FeeRef>;
162
+
151
163
  /** @deprecated use `getContract` instead */
152
164
  declare const createContract: typeof getContract;
153
165
 
@@ -157,4 +169,6 @@ declare const resourceIdToHex: typeof resourceToHex;
157
169
  /** @deprecated use `hexToResource` instead */
158
170
  declare const hexToResourceId: typeof hexToResource;
159
171
 
160
- export { type CreateNonceManagerOptions, type CreateNonceManagerResult, LruMap, type Resource, type ResourceLabel, type ResourceType, type Result, type SendTransactionExtraOptions, type WriteContractExtraOptions, createBenchmark, createBurnerAccount, createContract, createNonceManager, findCause, getBurnerPrivateKey, getContract, getNonceManager, getNonceManagerId, hexToResource, hexToResourceId, isError, isOk, logSort, readHex, resourceIdToHex, resourceToHex, resourceToLabel, resourceTypeIds, resourceTypes, sendTransaction, spliceHex, transportObserver, unwrap, writeContract };
172
+ declare const internal_getFeeRef: typeof getFeeRef;
173
+
174
+ export { type CreateNonceManagerOptions, type CreateNonceManagerResult, LruMap, type Resource, type ResourceLabel, type ResourceType, type Result, type SendTransactionExtraOptions, type WriteContractExtraOptions, createBenchmark, createBurnerAccount, createContract, createNonceManager, findCause, getBurnerPrivateKey, getContract, getNonceManager, getNonceManagerId, hexToResource, hexToResourceId, internal_getFeeRef, isError, isOk, logSort, readHex, resourceIdToHex, resourceToHex, resourceToLabel, resourceTypeIds, resourceTypes, sendTransaction, spliceHex, transportObserver, unwrap, writeContract };
package/dist/index.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import {
2
2
  writeContract
3
- } from "./chunk-324BIDBP.js";
3
+ } from "./chunk-ZRFZXVEA.js";
4
4
  import {
5
5
  createNonceManager,
6
6
  findCause,
7
+ getFeeRef,
7
8
  getNonceManager,
8
9
  getNonceManagerId,
9
10
  sendTransaction
10
- } from "./chunk-5Q2OTK63.js";
11
+ } from "./chunk-HFWOVFQU.js";
11
12
  import {
12
13
  hexToResource,
13
14
  resourceToHex,
@@ -203,6 +204,9 @@ var resourceIdToHex = resourceToHex;
203
204
 
204
205
  // src/deprecated/hexToResourceId.ts
205
206
  var hexToResourceId = hexToResource;
207
+
208
+ // src/index.ts
209
+ var internal_getFeeRef = getFeeRef;
206
210
  export {
207
211
  LruMap,
208
212
  createBenchmark,
@@ -216,6 +220,7 @@ export {
216
220
  getNonceManagerId,
217
221
  hexToResource,
218
222
  hexToResourceId,
223
+ internal_getFeeRef,
219
224
  isError,
220
225
  isOk,
221
226
  logSort,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/createBenchmark.ts","../src/createBurnerAccount.ts","../src/getBurnerPrivateKey.ts","../src/getContract.ts","../src/logSort.ts","../src/LruMap.ts","../src/readHex.ts","../src/result.ts","../src/spliceHex.ts","../src/transportObserver.ts","../src/deprecated/createContract.ts","../src/deprecated/resourceIdToHex.ts","../src/deprecated/hexToResourceId.ts"],"sourcesContent":["import createDebug from \"debug\";\n\nconst parentDebug = createDebug(\"mud:benchmark\");\n\n// Pipe debug output to stdout instead of stderr\nparentDebug.log = console.info.bind(console);\n\nexport function createBenchmark(namespace: string): (stepName: string) => void {\n const debug = parentDebug.extend(namespace);\n let lastStep = performance.now();\n\n return (stepName: string) => {\n const secondsSinceLastStep = (performance.now() - lastStep) / 1000;\n debug(\"%s: +%ds\", stepName, secondsSinceLastStep);\n lastStep = performance.now();\n };\n}\n","import { Hex, PrivateKeyAccount } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nexport function createBurnerAccount(privateKey: Hex): PrivateKeyAccount {\n const account = privateKeyToAccount(privateKey);\n // We may override account features here\n return {\n ...account,\n };\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\";\nimport { isHex, Hex } from \"viem\";\n\nfunction assertPrivateKey(privateKey: string, cacheKey: string): asserts privateKey is Hex {\n if (!isHex(privateKey)) {\n console.error(\"Private key found in cache is not valid hex\", { privateKey, cacheKey });\n throw new Error(`Private key found in cache (${cacheKey}) is not valid hex`);\n }\n // ensure we can extract address from private key\n // this should throw on bad private keys\n privateKeyToAccount(privateKey);\n}\n\nexport function getBurnerPrivateKey(cacheKey = \"mud:burnerWallet\"): Hex {\n const cachedPrivateKey = localStorage.getItem(cacheKey);\n\n if (cachedPrivateKey != null) {\n assertPrivateKey(cachedPrivateKey, cacheKey);\n return cachedPrivateKey;\n }\n\n const privateKey = generatePrivateKey();\n console.log(\"New burner wallet created:\", privateKeyToAccount(privateKey));\n localStorage.setItem(cacheKey, privateKey);\n return privateKey;\n}\n","import {\n Abi,\n Account,\n Address,\n Chain,\n GetContractParameters,\n GetContractReturnType,\n Hex,\n PublicClient,\n Transport,\n WalletClient,\n WriteContractParameters,\n type ContractFunctionName,\n type ContractFunctionArgs,\n getContract as viem_getContract,\n} from \"viem\";\nimport { UnionOmit } from \"./type-utils/common\";\nimport { writeContract } from \"./writeContract\";\n\n// copied from viem because this isn't exported\n// TODO: import from viem?\nfunction getFunctionParameters(values: [args?: readonly unknown[], options?: object]): {\n args: readonly unknown[];\n options: object;\n} {\n const hasArgs = values.length && Array.isArray(values[0]);\n const args = hasArgs ? values[0]! : [];\n const options = (hasArgs ? values[1] : values[0]) ?? {};\n return { args, options };\n}\n\nexport type ContractWrite = {\n id: string;\n request: WriteContractParameters;\n result: Promise<Hex>;\n};\n\nexport type GetContractOptions<\n TTransport extends Transport,\n TAddress extends Address,\n TAbi extends Abi,\n TChain extends Chain,\n TAccount extends Account,\n TPublicClient extends PublicClient<TTransport, TChain>,\n TWalletClient extends WalletClient<TTransport, TChain, TAccount>,\n> = GetContractParameters<\n TTransport,\n TChain,\n TAccount,\n TAbi,\n { public: TPublicClient; wallet: TWalletClient },\n TAddress\n> & {\n onWrite?: (write: ContractWrite) => void;\n};\n\n// TODO: migrate away from this approach once we can hook into viem: https://github.com/wagmi-dev/viem/discussions/1230\n\n/** @deprecated Use `walletClient.extend(transactionQueue()).extend(writeObserver({ onWrite }))` and viem's `getContract` instead. */\nexport function getContract<\n TTransport extends Transport,\n TAddress extends Address,\n TAbi extends Abi,\n TChain extends Chain,\n TAccount extends Account,\n TPublicClient extends PublicClient<TTransport, TChain>,\n TWalletClient extends WalletClient<TTransport, TChain, TAccount>,\n>({\n abi,\n address,\n client: { public: publicClient, wallet: walletClient },\n onWrite,\n}: GetContractOptions<\n TTransport,\n TAddress,\n TAbi,\n TChain,\n TAccount,\n TPublicClient,\n TWalletClient\n>): GetContractReturnType<TAbi, { public: TPublicClient; wallet: TWalletClient }, TAddress> {\n const contract: GetContractReturnType<TAbi, { public: TPublicClient; wallet: TWalletClient }, TAddress> & {\n write: unknown;\n } = viem_getContract({\n abi,\n address,\n client: {\n public: publicClient,\n wallet: walletClient,\n },\n }) as never;\n\n if (contract.write) {\n // Replace write calls with our own. Implemented ~the same as viem, but adds better handling of nonces (via queue + retries).\n let nextWriteId = 0;\n contract.write = new Proxy(\n {},\n {\n get(_, functionName: string) {\n return (\n ...parameters: [\n args?: readonly unknown[],\n options?: UnionOmit<WriteContractParameters, \"abi\" | \"address\" | \"functionName\" | \"args\">,\n ]\n ) => {\n const { args, options } = getFunctionParameters(parameters);\n const request: WriteContractParameters<\n TAbi,\n ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\">,\n TChain,\n TAccount\n > = {\n abi,\n address,\n functionName,\n args,\n ...options,\n onWrite,\n } as never;\n const result = writeContract(walletClient, request, { publicClient }) as never;\n\n const id = `${walletClient.chain.id}:${walletClient.account.address}:${nextWriteId++}`;\n onWrite?.({\n id,\n request: request as WriteContractParameters,\n result,\n });\n\n return result;\n };\n },\n },\n );\n }\n\n return contract;\n}\n","type PartialLog = { readonly blockNumber: bigint | null; readonly logIndex: number | null };\n\nexport function logSort(a: PartialLog, b: PartialLog): number {\n if (a.blockNumber === b.blockNumber) {\n if (a.logIndex === b.logIndex) return 0;\n if (a.logIndex == null) return 1;\n if (b.logIndex == null) return -1;\n return a.logIndex - b.logIndex;\n }\n\n if (a.blockNumber == null) return 1;\n if (b.blockNumber == null) return -1;\n if (a.blockNumber > b.blockNumber) return 1;\n if (a.blockNumber < b.blockNumber) return -1;\n return 0;\n}\n","/**\n * Map with a LRU (least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n * @link https://github.com/wevm/viem/blob/0fa08e113a890e6672fdc64fa7a2206a840611ab/src/utils/lru.ts\n */\nexport class LruMap<key, value> extends Map<key, value> {\n maxSize: number;\n\n constructor(size: number) {\n super();\n this.maxSize = size;\n }\n\n override set(key: key, value: value): this {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n this.delete(this.keys().next().value);\n }\n return this;\n }\n}\n","import { Hex } from \"viem\";\n\n/**\n * Get the hex value at start/end positions. This will always return a valid hex string.\n *\n * If `start` is out of range, this returns `\"0x\"`.\n *\n * If `end` is specified and out of range, the result is right zero-padded to the desired length (`end - start`).\n */\nexport function readHex(data: Hex, start: number, end?: number): Hex {\n return `0x${data\n .replace(/^0x/, \"\")\n .slice(start * 2, end != null ? end * 2 : undefined)\n .padEnd(((end ?? start) - start) * 2, \"0\")}`;\n}\n","// Inspired by https://doc.rust-lang.org/std/result/\nexport type Result<Ok, Err = unknown> = { ok: Ok } | { error: Err };\n\nexport function isOk<Ok, Err>(result: Result<Ok, Err>): result is { ok: Ok } {\n return \"ok\" in result;\n}\n\nexport function isError<Ok, Err>(result: Result<Ok, Err>): result is { error: Err } {\n return \"error\" in result;\n}\n\nexport function unwrap<Ok, Err>(result: Result<Ok, Err>): Ok {\n if (isError(result)) {\n throw result.error;\n }\n return result.ok;\n}\n","import { Hex, concatHex } from \"viem\";\nimport { readHex } from \"./readHex\";\n\nexport function spliceHex(data: Hex, start: number, deleteCount = 0, newData: Hex = \"0x\"): Hex {\n return concatHex([readHex(data, 0, start), newData, readHex(data, start + deleteCount)]);\n}\n","import { Hex, Transport, keccak256 } from \"viem\";\nimport { debug as parentDebug } from \"./debug\";\n\nconst debug = parentDebug.extend(\"transportObserver\");\n\nexport function transportObserver<TTransport extends Transport>(transport: TTransport): TTransport {\n return ((opts) => {\n const result = transport(opts);\n const request: typeof result.request = async (req) => {\n if (req.method === \"eth_sendRawTransaction\" && req.params instanceof Array) {\n const txs = req.params.map((data: Hex) => keccak256(data));\n debug(\"saw txs\", txs);\n // TODO: pass these tx hashes into dev tools\n }\n // TODO: add support for `eth_sendTransaction`\n return result.request(req);\n };\n return {\n ...result,\n request,\n };\n }) as TTransport;\n}\n","import { getContract } from \"../getContract\";\n\n/** @deprecated use `getContract` instead */\nexport const createContract = getContract;\n","import { resourceToHex } from \"../resourceToHex\";\n\n/** @deprecated use `resourceToHex` instead */\nexport const resourceIdToHex = resourceToHex;\n","import { hexToResource } from \"../hexToResource\";\n\n/** @deprecated use `hexToResource` instead */\nexport const hexToResourceId = hexToResource;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,iBAAiB;AAExB,IAAM,cAAc,YAAY,eAAe;AAG/C,YAAY,MAAM,QAAQ,KAAK,KAAK,OAAO;AAEpC,SAAS,gBAAgB,WAA+C;AAC7E,QAAMA,SAAQ,YAAY,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IAC3B;AACA,WAAO;AAAA,MACL,GAAG;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;;;ACnBO,IAAM,iBAAiB;;;ACAvB,IAAM,kBAAkB;;;ACAxB,IAAM,kBAAkB;","names":["debug","privateKeyToAccount","debug"]}
1
+ {"version":3,"sources":["../src/createBenchmark.ts","../src/createBurnerAccount.ts","../src/getBurnerPrivateKey.ts","../src/getContract.ts","../src/logSort.ts","../src/LruMap.ts","../src/readHex.ts","../src/result.ts","../src/spliceHex.ts","../src/transportObserver.ts","../src/deprecated/createContract.ts","../src/deprecated/resourceIdToHex.ts","../src/deprecated/hexToResourceId.ts","../src/index.ts"],"sourcesContent":["import createDebug from \"debug\";\n\nconst parentDebug = createDebug(\"mud:benchmark\");\n\n// Pipe debug output to stdout instead of stderr\nparentDebug.log = console.info.bind(console);\n\nexport function createBenchmark(namespace: string): (stepName: string) => void {\n const debug = parentDebug.extend(namespace);\n let lastStep = performance.now();\n\n return (stepName: string) => {\n const secondsSinceLastStep = (performance.now() - lastStep) / 1000;\n debug(\"%s: +%ds\", stepName, secondsSinceLastStep);\n lastStep = performance.now();\n };\n}\n","import { Hex, PrivateKeyAccount } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nexport function createBurnerAccount(privateKey: Hex): PrivateKeyAccount {\n const account = privateKeyToAccount(privateKey);\n // We may override account features here\n return {\n ...account,\n };\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\";\nimport { isHex, Hex } from \"viem\";\n\nfunction assertPrivateKey(privateKey: string, cacheKey: string): asserts privateKey is Hex {\n if (!isHex(privateKey)) {\n console.error(\"Private key found in cache is not valid hex\", { privateKey, cacheKey });\n throw new Error(`Private key found in cache (${cacheKey}) is not valid hex`);\n }\n // ensure we can extract address from private key\n // this should throw on bad private keys\n privateKeyToAccount(privateKey);\n}\n\nexport function getBurnerPrivateKey(cacheKey = \"mud:burnerWallet\"): Hex {\n const cachedPrivateKey = localStorage.getItem(cacheKey);\n\n if (cachedPrivateKey != null) {\n assertPrivateKey(cachedPrivateKey, cacheKey);\n return cachedPrivateKey;\n }\n\n const privateKey = generatePrivateKey();\n console.log(\"New burner wallet created:\", privateKeyToAccount(privateKey));\n localStorage.setItem(cacheKey, privateKey);\n return privateKey;\n}\n","import {\n Abi,\n Account,\n Address,\n Chain,\n GetContractParameters,\n GetContractReturnType,\n Hex,\n PublicClient,\n Transport,\n WalletClient,\n WriteContractParameters,\n type ContractFunctionName,\n type ContractFunctionArgs,\n getContract as viem_getContract,\n} from \"viem\";\nimport { UnionOmit } from \"./type-utils/common\";\nimport { writeContract } from \"./writeContract\";\n\n// copied from viem because this isn't exported\n// TODO: import from viem?\nfunction getFunctionParameters(values: [args?: readonly unknown[], options?: object]): {\n args: readonly unknown[];\n options: object;\n} {\n const hasArgs = values.length && Array.isArray(values[0]);\n const args = hasArgs ? values[0]! : [];\n const options = (hasArgs ? values[1] : values[0]) ?? {};\n return { args, options };\n}\n\nexport type ContractWrite = {\n id: string;\n request: WriteContractParameters;\n result: Promise<Hex>;\n};\n\nexport type GetContractOptions<\n TTransport extends Transport,\n TAddress extends Address,\n TAbi extends Abi,\n TChain extends Chain,\n TAccount extends Account,\n TPublicClient extends PublicClient<TTransport, TChain>,\n TWalletClient extends WalletClient<TTransport, TChain, TAccount>,\n> = GetContractParameters<\n TTransport,\n TChain,\n TAccount,\n TAbi,\n { public: TPublicClient; wallet: TWalletClient },\n TAddress\n> & {\n onWrite?: (write: ContractWrite) => void;\n};\n\n// TODO: migrate away from this approach once we can hook into viem: https://github.com/wagmi-dev/viem/discussions/1230\n\n/** @deprecated Use `walletClient.extend(transactionQueue()).extend(writeObserver({ onWrite }))` and viem's `getContract` instead. */\nexport function getContract<\n TTransport extends Transport,\n TAddress extends Address,\n TAbi extends Abi,\n TChain extends Chain,\n TAccount extends Account,\n TPublicClient extends PublicClient<TTransport, TChain>,\n TWalletClient extends WalletClient<TTransport, TChain, TAccount>,\n>({\n abi,\n address,\n client: { public: publicClient, wallet: walletClient },\n onWrite,\n}: GetContractOptions<\n TTransport,\n TAddress,\n TAbi,\n TChain,\n TAccount,\n TPublicClient,\n TWalletClient\n>): GetContractReturnType<TAbi, { public: TPublicClient; wallet: TWalletClient }, TAddress> {\n const contract: GetContractReturnType<TAbi, { public: TPublicClient; wallet: TWalletClient }, TAddress> & {\n write: unknown;\n } = viem_getContract({\n abi,\n address,\n client: {\n public: publicClient,\n wallet: walletClient,\n },\n }) as never;\n\n if (contract.write) {\n // Replace write calls with our own. Implemented ~the same as viem, but adds better handling of nonces (via queue + retries).\n let nextWriteId = 0;\n contract.write = new Proxy(\n {},\n {\n get(_, functionName: string) {\n return (\n ...parameters: [\n args?: readonly unknown[],\n options?: UnionOmit<WriteContractParameters, \"abi\" | \"address\" | \"functionName\" | \"args\">,\n ]\n ) => {\n const { args, options } = getFunctionParameters(parameters);\n const request: WriteContractParameters<\n TAbi,\n ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\">,\n TChain,\n TAccount\n > = {\n abi,\n address,\n functionName,\n args,\n ...options,\n onWrite,\n } as never;\n const result = writeContract(walletClient, request, { publicClient }) as never;\n\n const id = `${walletClient.chain.id}:${walletClient.account.address}:${nextWriteId++}`;\n onWrite?.({\n id,\n request: request as WriteContractParameters,\n result,\n });\n\n return result;\n };\n },\n },\n );\n }\n\n return contract;\n}\n","type PartialLog = { readonly blockNumber: bigint | null; readonly logIndex: number | null };\n\nexport function logSort(a: PartialLog, b: PartialLog): number {\n if (a.blockNumber === b.blockNumber) {\n if (a.logIndex === b.logIndex) return 0;\n if (a.logIndex == null) return 1;\n if (b.logIndex == null) return -1;\n return a.logIndex - b.logIndex;\n }\n\n if (a.blockNumber == null) return 1;\n if (b.blockNumber == null) return -1;\n if (a.blockNumber > b.blockNumber) return 1;\n if (a.blockNumber < b.blockNumber) return -1;\n return 0;\n}\n","/**\n * Map with a LRU (least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n * @link https://github.com/wevm/viem/blob/0fa08e113a890e6672fdc64fa7a2206a840611ab/src/utils/lru.ts\n */\nexport class LruMap<key, value> extends Map<key, value> {\n maxSize: number;\n\n constructor(size: number) {\n super();\n this.maxSize = size;\n }\n\n override set(key: key, value: value): this {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n this.delete(this.keys().next().value);\n }\n return this;\n }\n}\n","import { Hex } from \"viem\";\n\n/**\n * Get the hex value at start/end positions. This will always return a valid hex string.\n *\n * If `start` is out of range, this returns `\"0x\"`.\n *\n * If `end` is specified and out of range, the result is right zero-padded to the desired length (`end - start`).\n */\nexport function readHex(data: Hex, start: number, end?: number): Hex {\n return `0x${data\n .replace(/^0x/, \"\")\n .slice(start * 2, end != null ? end * 2 : undefined)\n .padEnd(((end ?? start) - start) * 2, \"0\")}`;\n}\n","// Inspired by https://doc.rust-lang.org/std/result/\nexport type Result<Ok, Err = unknown> = { ok: Ok } | { error: Err };\n\nexport function isOk<Ok, Err>(result: Result<Ok, Err>): result is { ok: Ok } {\n return \"ok\" in result;\n}\n\nexport function isError<Ok, Err>(result: Result<Ok, Err>): result is { error: Err } {\n return \"error\" in result;\n}\n\nexport function unwrap<Ok, Err>(result: Result<Ok, Err>): Ok {\n if (isError(result)) {\n throw result.error;\n }\n return result.ok;\n}\n","import { Hex, concatHex } from \"viem\";\nimport { readHex } from \"./readHex\";\n\nexport function spliceHex(data: Hex, start: number, deleteCount = 0, newData: Hex = \"0x\"): Hex {\n return concatHex([readHex(data, 0, start), newData, readHex(data, start + deleteCount)]);\n}\n","import { Hex, Transport, keccak256 } from \"viem\";\nimport { debug as parentDebug } from \"./debug\";\n\nconst debug = parentDebug.extend(\"transportObserver\");\n\nexport function transportObserver<TTransport extends Transport>(transport: TTransport): TTransport {\n return ((opts) => {\n const result = transport(opts);\n const request: typeof result.request = async (req) => {\n if (req.method === \"eth_sendRawTransaction\" && req.params instanceof Array) {\n const txs = req.params.map((data: Hex) => keccak256(data));\n debug(\"saw txs\", txs);\n // TODO: pass these tx hashes into dev tools\n }\n // TODO: add support for `eth_sendTransaction`\n return result.request(req);\n };\n return {\n ...result,\n request,\n };\n }) as TTransport;\n}\n","import { getContract } from \"../getContract\";\n\n/** @deprecated use `getContract` instead */\nexport const createContract = getContract;\n","import { resourceToHex } from \"../resourceToHex\";\n\n/** @deprecated use `resourceToHex` instead */\nexport const resourceIdToHex = resourceToHex;\n","import { hexToResource } from \"../hexToResource\";\n\n/** @deprecated use `hexToResource` instead */\nexport const hexToResourceId = hexToResource;\n","export * from \"./common\";\nexport * from \"./createBenchmark\";\nexport * from \"./createBurnerAccount\";\nexport * from \"./createNonceManager\";\nexport * from \"./findCause\";\nexport * from \"./getBurnerPrivateKey\";\nexport * from \"./getContract\";\nexport * from \"./getNonceManager\";\nexport * from \"./getNonceManagerId\";\nexport * from \"./hexToResource\";\nexport * from \"./logSort\";\nexport * from \"./LruMap\";\nexport * from \"./readHex\";\nexport * from \"./resourceToLabel\";\nexport * from \"./resourceToHex\";\nexport * from \"./resourceTypes\";\nexport * from \"./result\";\nexport * from \"./sendTransaction\";\nexport * from \"./spliceHex\";\nexport * from \"./transportObserver\";\nexport * from \"./writeContract\";\nimport { getFeeRef } from \"./getFeeRef\";\nexport const internal_getFeeRef = getFeeRef;\n\n/** @deprecated use `getContract` instead */\nexport { createContract } from \"./deprecated/createContract\";\n/** @deprecated use `resourceToHex` instead */\nexport { resourceIdToHex } from \"./deprecated/resourceIdToHex\";\n/** @deprecated use `hexToResource` instead */\nexport { hexToResourceId } from \"./deprecated/hexToResourceId\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,iBAAiB;AAExB,IAAM,cAAc,YAAY,eAAe;AAG/C,YAAY,MAAM,QAAQ,KAAK,KAAK,OAAO;AAEpC,SAAS,gBAAgB,WAA+C;AAC7E,QAAMA,SAAQ,YAAY,OAAO,SAAS;AAC1C,MAAI,WAAW,YA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;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;;;ACnBO,IAAM,iBAAiB;;;ACAvB,IAAM,kBAAkB;;;ACAxB,IAAM,kBAAkB;;;ACmBxB,IAAM,qBAAqB;","names":["debug","privateKeyToAccount","debug"]}
package/dist/internal.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  sendTransaction
3
- } from "./chunk-5Q2OTK63.js";
3
+ } from "./chunk-HFWOVFQU.js";
4
4
  import {
5
5
  debug
6
6
  } from "./chunk-73UWXFXB.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@latticexyz/common",
3
- "version": "2.2.21-b18c0ef0edeab2378b08d9f4a328a5d0d817f6bf",
3
+ "version": "2.2.21-c67535174198d5cace8b7fdafaaff54a580f128a",
4
4
  "description": "Common low level logic shared between packages",
5
5
  "repository": {
6
6
  "type": "git",
@@ -69,7 +69,7 @@
69
69
  "p-retry": "^5.1.2",
70
70
  "prettier": "3.2.5",
71
71
  "prettier-plugin-solidity": "1.3.1",
72
- "@latticexyz/schema-type": "2.2.21-b18c0ef0edeab2378b08d9f4a328a5d0d817f6bf"
72
+ "@latticexyz/schema-type": "2.2.21-c67535174198d5cace8b7fdafaaff54a580f128a"
73
73
  },
74
74
  "devDependencies": {
75
75
  "@types/debug": "^4.1.7",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/getNonceManagerId.ts","../src/findCause.ts","../src/createNonceManager.ts","../src/getNonceManager.ts","../src/sendTransaction.ts","../src/getFeeRef.ts","../src/createFeeRef.ts"],"sourcesContent":["import { BlockTag, Client, Hex, getAddress } from \"viem\";\nimport { getChainId } from \"viem/actions\";\nimport { getAction } from \"viem/utils\";\n\nexport async function getNonceManagerId({\n client,\n address,\n blockTag,\n}: {\n client: Client;\n address: Hex;\n blockTag: BlockTag;\n}): Promise<string> {\n // TODO: improve this so we don't have to call getChainId every time\n const chainId = client.chain?.id ?? (await getAction(client, getChainId, \"getChainId\")({}));\n return `mud:createNonceManager:${chainId}:${getAddress(address)}:${blockTag}`;\n}\n","export function findCause(error: Error, fn?: (error: Error) => boolean): Error | null {\n if (fn?.(error)) return error;\n if (error.cause instanceof Error) return findCause(error.cause, fn);\n return fn ? null : error;\n}\n","import { BlockTag, Client, Hex } from \"viem\";\nimport { debug as parentDebug } from \"./debug\";\nimport { getNonceManagerId } from \"./getNonceManagerId\";\nimport { getTransactionCount } from \"viem/actions\";\nimport PQueue from \"p-queue\";\nimport { getAction } from \"viem/utils\";\nimport { findCause } from \"./findCause\";\n\nconst debug = parentDebug.extend(\"createNonceManager\");\n\nexport type CreateNonceManagerOptions = {\n client: Client;\n address: Hex;\n blockTag?: BlockTag;\n broadcastChannelName?: string;\n queueConcurrency?: number;\n};\n\nexport type CreateNonceManagerResult = {\n hasNonce: () => boolean;\n getNonce: () => number;\n nextNonce: () => number;\n resetNonce: () => Promise<void>;\n shouldResetNonce: (error: Error) => boolean;\n mempoolQueue: PQueue;\n};\n\nexport function createNonceManager({\n client,\n address, // TODO: rename to account?\n blockTag = \"latest\",\n broadcastChannelName,\n queueConcurrency = 1,\n}: CreateNonceManagerOptions): CreateNonceManagerResult {\n const ref = { nonce: -1, noncePromise: null as Promise<void> | null };\n let channel: BroadcastChannel | null = null;\n\n if (typeof BroadcastChannel !== \"undefined\") {\n const channelName = broadcastChannelName\n ? Promise.resolve(broadcastChannelName)\n : getNonceManagerId({ client, address, blockTag });\n channelName.then((name) => {\n channel = new BroadcastChannel(name);\n // TODO: emit some sort of \"connected\" event so other channels can broadcast current nonce\n channel.addEventListener(\"message\", (event) => {\n const nonce = JSON.parse(event.data);\n debug(\"got nonce from broadcast channel\", nonce);\n ref.nonce = nonce;\n });\n });\n }\n\n function hasNonce(): boolean {\n return ref.nonce >= 0;\n }\n\n function getNonce(): number {\n if (!hasNonce()) throw new Error(\"call resetNonce before using getNonce\");\n return ref.nonce;\n }\n\n function nextNonce(): number {\n if (!hasNonce()) throw new Error(\"call resetNonce before using nextNonce\");\n const nonce = ref.nonce++;\n channel?.postMessage(JSON.stringify(ref.nonce));\n return nonce;\n }\n\n async function resetNonce(): Promise<void> {\n ref.noncePromise ??= (async (): Promise<void> => {\n ref.nonce = await getAction(client, getTransactionCount, \"getTransactionCount\")({ address, blockTag });\n ref.noncePromise = null;\n channel?.postMessage(JSON.stringify(ref.nonce));\n debug(\"reset nonce to\", ref.nonce);\n })();\n await ref.noncePromise;\n }\n\n function shouldResetNonce(error: Error): boolean {\n const nonceError = findCause(error, ({ name }) => name === \"NonceTooLowError\" || name === \"NonceTooHighError\");\n return nonceError != null;\n }\n\n const mempoolQueue = new PQueue({ concurrency: queueConcurrency });\n\n return {\n hasNonce,\n getNonce,\n nextNonce,\n resetNonce,\n shouldResetNonce,\n mempoolQueue,\n };\n}\n","import { CreateNonceManagerOptions, CreateNonceManagerResult, createNonceManager } from \"./createNonceManager\";\nimport { getNonceManagerId } from \"./getNonceManagerId\";\n\nconst nonceManagers = new Map<string, CreateNonceManagerResult>();\n\nexport async function getNonceManager({\n client,\n address, // TODO: rename to account?\n blockTag = \"latest\",\n ...opts\n}: CreateNonceManagerOptions): Promise<CreateNonceManagerResult> {\n const id = await getNonceManagerId({ client, address, blockTag });\n\n const nonceManager = nonceManagers.get(id) ?? createNonceManager({ client, address, blockTag, ...opts });\n if (!nonceManagers.has(id)) {\n nonceManagers.set(id, nonceManager);\n }\n\n if (!nonceManager.hasNonce()) {\n await nonceManager.resetNonce();\n }\n\n return nonceManager;\n}\n","import {\n Account,\n Chain,\n Client,\n SendTransactionParameters,\n Transport,\n SendTransactionReturnType,\n SendTransactionRequest,\n} from \"viem\";\nimport { sendTransaction as viem_sendTransaction } from \"viem/actions\";\nimport pRetry from \"p-retry\";\nimport { debug as parentDebug } from \"./debug\";\nimport { getNonceManager } from \"./getNonceManager\";\nimport { parseAccount } from \"viem/accounts\";\nimport { getFeeRef } from \"./getFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst debug = parentDebug.extend(\"sendTransaction\");\n\nexport type SendTransactionExtraOptions<chain extends Chain | undefined> = {\n /**\n * `publicClient` can be provided to be used in place of the extended viem client for making public action calls\n * (`getChainId`, `getTransactionCount`, `call`). This helps in cases where the extended\n * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),\n * where the transport is the bundler, not an RPC.\n */\n publicClient?: Client<Transport, chain>;\n /**\n * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered\n * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions\n * arriving out of order, but this may be an acceptable trade-off for some applications that can safely retry.\n * @default 1\n */\n queueConcurrency?: number;\n};\n\n/** @deprecated Use `walletClient.extend(transactionQueue())` instead. */\nexport async function sendTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends SendTransactionRequest<chain, chainOverride>,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n request: SendTransactionParameters<chain, account, chainOverride, request>,\n opts: SendTransactionExtraOptions<chain> = {},\n): Promise<SendTransactionReturnType> {\n const rawAccount = request.account ?? client.account;\n if (!rawAccount) {\n // TODO: replace with viem AccountNotFoundError once its exported\n throw new Error(\"No account provided\");\n }\n const account = parseAccount(rawAccount);\n const chain = client.chain;\n\n const nonceManager = await getNonceManager({\n client: opts.publicClient ?? client,\n address: account.address,\n queueConcurrency: opts.queueConcurrency,\n });\n\n const feeRef = await getFeeRef({\n client: opts.publicClient ?? client,\n refreshInterval: 10000,\n args: { chain },\n });\n\n return await nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n const nonce = nonceManager.nextNonce();\n const params = {\n // viem_sendTransaction internally estimates gas, which we want to happen on the pending block\n blockTag: \"pending\",\n ...feeRef.fees,\n ...request,\n nonce,\n } as const satisfies SendTransactionParameters<chain, account, chainOverride, request>;\n debug(\"sending tx to\", request.to, \"with nonce\", nonce);\n return await getAction(client, viem_sendTransaction, \"sendTransaction\")(params as never);\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // in case this tx failed before hitting the mempool (i.e. gas estimation error), reset nonce so we don't skip past the unused nonce\n debug(\"failed, resetting nonce\");\n await nonceManager.resetNonce();\n // retry nonce errors\n // TODO: upgrade p-retry and move this to shouldRetry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n return;\n }\n\n if (String(error).includes(\"transaction underpriced\")) {\n debug(\"got transaction underpriced error, retrying\", error.message);\n return;\n }\n\n throw error;\n },\n },\n ),\n { throwOnTimeout: true },\n );\n}\n","import { getChainId } from \"viem/actions\";\nimport { CreateFeeRefOptions, FeeRef, createFeeRef } from \"./createFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst feeRefs = new Map<number, FeeRef>();\n\nexport async function getFeeRef(opts: CreateFeeRefOptions): Promise<FeeRef> {\n const chainId =\n opts.args?.chain?.id ?? opts.client.chain?.id ?? (await getAction(opts.client, getChainId, \"getChainId\")({}));\n\n const existingFeeRef = feeRefs.get(chainId);\n if (existingFeeRef) {\n return existingFeeRef;\n }\n\n const feeRef = await createFeeRef(opts);\n feeRefs.set(chainId, feeRef);\n return feeRef;\n}\n","import { EstimateFeesPerGasParameters, Client, EstimateFeesPerGasReturnType } from \"viem\";\nimport { estimateFeesPerGas } from \"viem/actions\";\nimport { getAction } from \"viem/utils\";\n\nexport type CreateFeeRefOptions = {\n client: Client;\n refreshInterval: number;\n args?: EstimateFeesPerGasParameters;\n};\n\nexport type FeeRef = {\n fees: EstimateFeesPerGasReturnType | {};\n lastUpdatedTimestamp: number;\n};\n\n/** Update fee values once every `refreshInterval` instead of right before every request */\nexport async function createFeeRef({ client, args, refreshInterval }: CreateFeeRefOptions): Promise<FeeRef> {\n const feeRef: FeeRef = { fees: {}, lastUpdatedTimestamp: 0 };\n\n async function updateFees(): Promise<void> {\n const fees = await getAction(client, estimateFeesPerGas, \"estimateFeesPerGas\")(args);\n feeRef.fees = fees;\n feeRef.lastUpdatedTimestamp = Date.now();\n }\n\n setInterval(updateFees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QAAM,QAAQ,OAAO;AAErB,QAAM,eAAe,MAAM,gBAAgB;AAAA,IACzC,QAAQ,KAAK,gBAAgB;AAAA,IAC7B,SAAS,QAAQ;AAAA,IACjB,kBAAkB,KAAK;AAAA,EACzB,CAAC;AAED,QAAM,SAAS,MAAM,UAAU;AAAA,IAC7B,QAAQ,KAAK,gBAAgB;AAAA,IAC7B,iBAAiB;AAAA,IACjB,MAAM,EAAE,MAAM;AAAA,EAChB,CAAC;AAED,SAAO,MAAM,aAAa,aAAa;AAAA,IACrC,MACE;AAAA,MACE,YAAY;AACV,cAAM,QAAQ,aAAa,UAAU;AACrC,cAAM,SAAS;AAAA;AAAA,UAEb,UAAU;AAAA,UACV,GAAG,OAAO;AAAA,UACV,GAAG;AAAA,UACH;AAAA,QACF;AACA,QAAAA,OAAM,iBAAiB,QAAQ,IAAI,cAAc,KAAK;AACtD,eAAO,MAAMD,WAAU,QAAQ,sBAAsB,iBAAiB,EAAE,MAAe;AAAA,MACzF;AAAA,MACA;AAAA,QACE,SAAS;AAAA,QACT,iBAAiB,OAAO,UAAU;AAEhC,UAAAC,OAAM,yBAAyB;AAC/B,gBAAM,aAAa,WAAW;AAG9B,cAAI,aAAa,iBAAiB,KAAK,GAAG;AACxC,YAAAA,OAAM,6BAA6B,MAAM,OAAO;AAChD;AAAA,UACF;AAEA,cAAI,OAAO,KAAK,EAAE,SAAS,yBAAyB,GAAG;AACrD,YAAAA,OAAM,+CAA+C,MAAM,OAAO;AAClE;AAAA,UACF;AAEA,gBAAM;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAAA,IACF,EAAE,gBAAgB,KAAK;AAAA,EACzB;AACF;","names":["getAction","debug","getAction","getChainId","getAction","getAction","getChainId","getAction","debug"]}