@latticexyz/common 2.2.12-main-60c1f80bb2b40fcf8b8e1a558ee5136a2d2aa84a → 2.2.12-main-fe98442d7ee82f0d41ba10f05a4ee1bafea69d48
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,2 +1,2 @@
|
|
|
1
|
-
import{d as o,e as a}from"./chunk-
|
|
1
|
+
import{d as o,e as a}from"./chunk-24YWZ2XF.js";import"./chunk-TCWGPC6G.js";function m(n={}){return r=>({writeContract:t=>o(r,t,n),sendTransaction:t=>a(r,t,n)})}import{getAction as s}from"viem/utils";import{writeContract as u}from"viem/actions";function h({onWrite:n}){let r=0;return t=>({writeContract:e=>{let i=s(t,u,"writeContract")(e),c=`${t.chain.id}:${t.account.address}:${r++}`;return n({id:c,request:e,result:i}),i}})}export{m as transactionQueue,h as writeObserver};
|
|
2
2
|
//# sourceMappingURL=actions.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as m}from"./chunk-TCWGPC6G.js";import{getAddress as v}from"viem";import{getChainId as O}from"viem/actions";import{getAction as A}from"viem/utils";async function p({client:e,address:r,blockTag:t}){return`mud:createNonceManager:${e.chain?.id??await A(e,O,"getChainId")({})}:${v(r)}:${t}`}import{BaseError as E,NonceTooHighError as I,NonceTooLowError as S}from"viem";import{getTransactionCount as k}from"viem/actions";import q from"p-queue";import{getAction as B}from"viem/utils";var w=m.extend("createNonceManager");function y({client:e,address:r,blockTag:t="latest",broadcastChannelName:o,queueConcurrency:i=1}){let n={nonce:-1,noncePromise:null},c=null;typeof BroadcastChannel<"u"&&(o?Promise.resolve(o):p({client:e,address:r,blockTag:t})).then(f=>{c=new BroadcastChannel(f),c.addEventListener("message",M=>{let b=JSON.parse(M.data);w("got nonce from broadcast channel",b),n.nonce=b})});function s(){return n.nonce>=0}function a(){if(!s())throw new Error("call resetNonce before using getNonce");return n.nonce}function u(){if(!s())throw new Error("call resetNonce before using nextNonce");let d=n.nonce++;return c?.postMessage(JSON.stringify(n.nonce)),d}async function R(){n.noncePromise??=(async()=>{n.nonce=await B(e,k,"getTransactionCount")({address:r,blockTag:t}),n.noncePromise=null,c?.postMessage(JSON.stringify(n.nonce)),w("reset nonce to",n.nonce)})(),await n.noncePromise}function P(d){return d instanceof E&&d.walk(f=>f instanceof S||f instanceof I)!=null}let F=new q({concurrency:i});return{hasNonce:s,getNonce:a,nextNonce:u,resetNonce:R,shouldResetNonce:P,mempoolQueue:F}}var N=new Map;async function g({client:e,address:r,blockTag:t="latest",...o}){let i=await p({client:e,address:r,blockTag:t}),n=N.get(i)??y({client:e,address:r,blockTag:t,...o});return N.has(i)||N.set(i,n),n.hasNonce()||await n.resetNonce(),n}import{writeContract as D}from"viem/actions";import J from"p-retry";import{parseAccount as U}from"viem/accounts";import{getChainId as Q}from"viem/actions";import{estimateFeesPerGas as W}from"viem/actions";import{getAction as G}from"viem/utils";async function x({client:e,args:r,refreshInterval:t}){let o={fees:{},lastUpdatedTimestamp:0};async function i(){let n=await G(e,W,"estimateFeesPerGas")(r);o.fees=n,o.lastUpdatedTimestamp=Date.now()}return setInterval(i,t),await i(),o}import{getAction as H}from"viem/utils";var T=new Map;async function l(e){let r=e.args?.chain?.id??e.client.chain?.id??await H(e.client,Q,"getChainId")({}),t=T.get(r);if(t)return t;let o=await x(e);return T.set(r,o),o}import{getAction as $}from"viem/utils";var h=m.extend("writeContract");async function Se(e,r,t={}){let o=r.account??e.account;if(!o)throw new Error("No account provided");let i=U(o),n=e.chain,c=await g({client:t.publicClient??e,address:i.address,queueConcurrency:t.queueConcurrency}),s=await l({client:t.publicClient??e,refreshInterval:1e4,args:{chain:n}});return c.mempoolQueue.add(()=>J(async()=>{let a=c.nextNonce(),u={blockTag:"pending",...r,nonce:a
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as m}from"./chunk-TCWGPC6G.js";import{getAddress as v}from"viem";import{getChainId as O}from"viem/actions";import{getAction as A}from"viem/utils";async function p({client:e,address:r,blockTag:t}){return`mud:createNonceManager:${e.chain?.id??await A(e,O,"getChainId")({})}:${v(r)}:${t}`}import{BaseError as E,NonceTooHighError as I,NonceTooLowError as S}from"viem";import{getTransactionCount as k}from"viem/actions";import q from"p-queue";import{getAction as B}from"viem/utils";var w=m.extend("createNonceManager");function y({client:e,address:r,blockTag:t="latest",broadcastChannelName:o,queueConcurrency:i=1}){let n={nonce:-1,noncePromise:null},c=null;typeof BroadcastChannel<"u"&&(o?Promise.resolve(o):p({client:e,address:r,blockTag:t})).then(f=>{c=new BroadcastChannel(f),c.addEventListener("message",M=>{let b=JSON.parse(M.data);w("got nonce from broadcast channel",b),n.nonce=b})});function s(){return n.nonce>=0}function a(){if(!s())throw new Error("call resetNonce before using getNonce");return n.nonce}function u(){if(!s())throw new Error("call resetNonce before using nextNonce");let d=n.nonce++;return c?.postMessage(JSON.stringify(n.nonce)),d}async function R(){n.noncePromise??=(async()=>{n.nonce=await B(e,k,"getTransactionCount")({address:r,blockTag:t}),n.noncePromise=null,c?.postMessage(JSON.stringify(n.nonce)),w("reset nonce to",n.nonce)})(),await n.noncePromise}function P(d){return d instanceof E&&d.walk(f=>f instanceof S||f instanceof I)!=null}let F=new q({concurrency:i});return{hasNonce:s,getNonce:a,nextNonce:u,resetNonce:R,shouldResetNonce:P,mempoolQueue:F}}var N=new Map;async function g({client:e,address:r,blockTag:t="latest",...o}){let i=await p({client:e,address:r,blockTag:t}),n=N.get(i)??y({client:e,address:r,blockTag:t,...o});return N.has(i)||N.set(i,n),n.hasNonce()||await n.resetNonce(),n}import{writeContract as D}from"viem/actions";import J from"p-retry";import{parseAccount as U}from"viem/accounts";import{getChainId as Q}from"viem/actions";import{estimateFeesPerGas as W}from"viem/actions";import{getAction as G}from"viem/utils";async function x({client:e,args:r,refreshInterval:t}){let o={fees:{},lastUpdatedTimestamp:0};async function i(){let n=await G(e,W,"estimateFeesPerGas")(r);o.fees=n,o.lastUpdatedTimestamp=Date.now()}return setInterval(i,t),await i(),o}import{getAction as H}from"viem/utils";var T=new Map;async function l(e){let r=e.args?.chain?.id??e.client.chain?.id??await H(e.client,Q,"getChainId")({}),t=T.get(r);if(t)return t;let o=await x(e);return T.set(r,o),o}import{getAction as $}from"viem/utils";var h=m.extend("writeContract");async function Se(e,r,t={}){let o=r.account??e.account;if(!o)throw new Error("No account provided");let i=U(o),n=e.chain,c=await g({client:t.publicClient??e,address:i.address,queueConcurrency:t.queueConcurrency}),s=await l({client:t.publicClient??e,refreshInterval:1e4,args:{chain:n}});return c.mempoolQueue.add(()=>J(async()=>{let a=c.nextNonce(),u={blockTag:"pending",...s.fees,...r,nonce:a};return h("calling",u.functionName,"at",u.address,"with nonce",a),await $(e,D,"writeContract")(u)},{retries:3,onFailedAttempt:async a=>{if(h("failed, resetting nonce"),await c.resetNonce(),c.shouldResetNonce(a)){h("got nonce error, retrying",a.message);return}if(String(a).includes("transaction underpriced")){h("got transaction underpriced error, retrying",a.message);return}throw a}}),{throwOnTimeout:!0})}import{sendTransaction as L}from"viem/actions";import _ from"p-retry";import{parseAccount as j}from"viem/accounts";import{getAction as z}from"viem/utils";var C=m.extend("sendTransaction");async function Je(e,r,t={}){let o=r.account??e.account;if(!o)throw new Error("No account provided");let i=j(o),n=e.chain,c=await g({client:t.publicClient??e,address:i.address,queueConcurrency:t.queueConcurrency}),s=await l({client:t.publicClient??e,refreshInterval:1e4,args:{chain:n}});return await c.mempoolQueue.add(()=>_(async()=>{let a=c.nextNonce(),u={blockTag:"pending",...s.fees,...r,nonce:a};return C("sending tx to",r.to,"with nonce",a),await z(e,L,"sendTransaction")(u)},{retries:3,onFailedAttempt:async a=>{if(C("failed, resetting nonce"),await c.resetNonce(),c.shouldResetNonce(a)){C("got nonce error, retrying",a.message);return}if(String(a).includes("transaction underpriced")){C("got transaction underpriced error, retrying",a.message);return}throw a}}),{throwOnTimeout:!0})}export{p as a,y as b,g as c,Se as d,Je as e};
|
|
2
|
+
//# sourceMappingURL=chunk-24YWZ2XF.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/getNonceManagerId.ts","../src/createNonceManager.ts","../src/getNonceManager.ts","../src/writeContract.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","import { BaseError, BlockTag, Client, Hex, NonceTooHighError, NonceTooLowError } 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\";\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: unknown) => 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: unknown): boolean {\n return (\n error instanceof BaseError &&\n error.walk((e) => e instanceof NonceTooLowError || e instanceof NonceTooHighError) != null\n );\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 Abi,\n Account,\n Chain,\n Client,\n Transport,\n WriteContractParameters,\n WriteContractReturnType,\n ContractFunctionName,\n ContractFunctionArgs,\n PublicClient,\n} from \"viem\";\nimport { writeContract as viem_writeContract } 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(\"writeContract\");\n\nexport type WriteContractExtraOptions<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`, `simulateContract`). 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?: PublicClient<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 writeContract<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, \"nonpayable\" | \"payable\">,\n args extends ContractFunctionArgs<abi, \"nonpayable\" | \"payable\", functionName>,\n chainOverride extends Chain | undefined,\n>(\n client: Client<Transport, chain, account>,\n request: WriteContractParameters<abi, functionName, args, chain, account, chainOverride>,\n opts: WriteContractExtraOptions<chain> = {},\n): Promise<WriteContractReturnType> {\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 nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n const nonce = nonceManager.nextNonce();\n const params = {\n // viem_writeContract internally estimates gas, which we want to happen on the pending block\n blockTag: \"pending\",\n ...request,\n nonce,\n ...feeRef.fees,\n } as const satisfies WriteContractParameters<abi, functionName, args, chain, account, chainOverride>;\n debug(\"calling\", params.functionName, \"at\", params.address, \"with nonce\", nonce);\n return await getAction(client, viem_writeContract, \"writeContract\")(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, refreshInterval);\n await updateFees();\n\n return feeRef;\n}\n","import {\n Account,\n Chain,\n Client,\n SendTransactionParameters,\n Transport,\n SendTransactionReturnType,\n PublicClient,\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?: PublicClient<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 ...request,\n nonce,\n ...feeRef.fees,\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":"wCAAA,OAAgC,cAAAA,MAAkB,OAClD,OAAS,cAAAC,MAAkB,eAC3B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AAGZ,EACH,MAAAW,EACA,GAAGH,EAAO,IACZ,EACA,OAAAX,EAAM,gBAAiBG,EAAQ,GAAI,aAAcW,CAAK,EAC/C,MAAMf,EAAUG,EAAQc,EAAsB,iBAAiB,EAAED,CAAe,CACzF,EACA,CACE,QAAS,EACT,gBAAiB,MAAOE,GAAU,CAMhC,GAJAjB,EAAM,yBAAyB,EAC/B,MAAMS,EAAa,WAAW,EAG1BA,EAAa,iBAAiBQ,CAAK,EAAG,CACxCjB,EAAM,4BAA6BiB,EAAM,OAAO,EAChD,OAGF,GAAI,OAAOA,CAAK,EAAE,SAAS,yBAAyB,EAAG,CACrDjB,EAAM,8CAA+CiB,EAAM,OAAO,EAClE,OAGF,MAAMA,CACR,CACF,CACF,EACF,CAAE,eAAgB,EAAK,CACzB,CACF","names":["getAddress","getChainId","getAction","getNonceManagerId","client","address","blockTag","BaseError","NonceTooHighError","NonceTooLowError","getTransactionCount","PQueue","getAction","debug","createNonceManager","client","address","blockTag","broadcastChannelName","queueConcurrency","ref","channel","getNonceManagerId","name","event","nonce","hasNonce","getNonce","nextNonce","resetNonce","shouldResetNonce","error","BaseError","e","NonceTooLowError","NonceTooHighError","mempoolQueue","nonceManagers","getNonceManager","client","address","blockTag","opts","id","getNonceManagerId","nonceManager","createNonceManager","viem_writeContract","pRetry","parseAccount","getChainId","estimateFeesPerGas","getAction","createFeeRef","client","args","refreshInterval","feeRef","updateFees","fees","getAction","feeRefs","getFeeRef","opts","chainId","getChainId","existingFeeRef","feeRef","createFeeRef","getAction","debug","writeContract","client","request","opts","rawAccount","account","parseAccount","chain","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_writeContract","error","viem_sendTransaction","pRetry","parseAccount","getAction","debug","sendTransaction","client","request","opts","rawAccount","account","parseAccount","chain","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_sendTransaction","error"]}
|
|
1
|
+
{"version":3,"sources":["../src/getNonceManagerId.ts","../src/createNonceManager.ts","../src/getNonceManager.ts","../src/writeContract.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","import { BaseError, BlockTag, Client, Hex, NonceTooHighError, NonceTooLowError } 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\";\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: unknown) => 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: unknown): boolean {\n return (\n error instanceof BaseError &&\n error.walk((e) => e instanceof NonceTooLowError || e instanceof NonceTooHighError) != null\n );\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 Abi,\n Account,\n Chain,\n Client,\n Transport,\n WriteContractParameters,\n WriteContractReturnType,\n ContractFunctionName,\n ContractFunctionArgs,\n PublicClient,\n} from \"viem\";\nimport { writeContract as viem_writeContract } 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(\"writeContract\");\n\nexport type WriteContractExtraOptions<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`, `simulateContract`). 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?: PublicClient<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 writeContract<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, \"nonpayable\" | \"payable\">,\n args extends ContractFunctionArgs<abi, \"nonpayable\" | \"payable\", functionName>,\n chainOverride extends Chain | undefined,\n>(\n client: Client<Transport, chain, account>,\n request: WriteContractParameters<abi, functionName, args, chain, account, chainOverride>,\n opts: WriteContractExtraOptions<chain> = {},\n): Promise<WriteContractReturnType> {\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 nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n const nonce = nonceManager.nextNonce();\n const params = {\n // viem_writeContract 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 WriteContractParameters<abi, functionName, args, chain, account, chainOverride>;\n debug(\"calling\", params.functionName, \"at\", params.address, \"with nonce\", nonce);\n return await getAction(client, viem_writeContract, \"writeContract\")(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, refreshInterval);\n await updateFees();\n\n return feeRef;\n}\n","import {\n Account,\n Chain,\n Client,\n SendTransactionParameters,\n Transport,\n SendTransactionReturnType,\n PublicClient,\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?: PublicClient<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":"wCAAA,OAAgC,cAAAA,MAAkB,OAClD,OAAS,cAAAC,MAAkB,eAC3B,OAAS,aAAAC,MAAiB,aAE1B,eAAsBC,EAAkB,CACtC,OAAAC,EACA,QAAAC,EACA,SAAAC,CACF,EAIoB,CAGlB,MAAO,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f,EAAUG,EAAQc,EAAsB,iBAAiB,EAAED,CAAe,CACzF,EACA,CACE,QAAS,EACT,gBAAiB,MAAOE,GAAU,CAMhC,GAJAjB,EAAM,yBAAyB,EAC/B,MAAMS,EAAa,WAAW,EAG1BA,EAAa,iBAAiBQ,CAAK,EAAG,CACxCjB,EAAM,4BAA6BiB,EAAM,OAAO,EAChD,OAGF,GAAI,OAAOA,CAAK,EAAE,SAAS,yBAAyB,EAAG,CACrDjB,EAAM,8CAA+CiB,EAAM,OAAO,EAClE,OAGF,MAAMA,CACR,CACF,CACF,EACF,CAAE,eAAgB,EAAK,CACzB,CACF","names":["getAddress","getChainId","getAction","getNonceManagerId","client","address","blockTag","BaseError","NonceTooHighError","NonceTooLowError","getTransactionCount","PQueue","getAction","debug","createNonceManager","client","address","blockTag","broadcastChannelName","queueConcurrency","ref","channel","getNonceManagerId","name","event","nonce","hasNonce","getNonce","nextNonce","resetNonce","shouldResetNonce","error","BaseError","e","NonceTooLowError","NonceTooHighError","mempoolQueue","nonceManagers","getNonceManager","client","address","blockTag","opts","id","getNonceManagerId","nonceManager","createNonceManager","viem_writeContract","pRetry","parseAccount","getChainId","estimateFeesPerGas","getAction","createFeeRef","client","args","refreshInterval","feeRef","updateFees","fees","getAction","feeRefs","getFeeRef","opts","chainId","getChainId","existingFeeRef","feeRef","createFeeRef","getAction","debug","writeContract","client","request","opts","rawAccount","account","parseAccount","chain","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_writeContract","error","viem_sendTransaction","pRetry","parseAccount","getAction","debug","sendTransaction","client","request","opts","rawAccount","account","parseAccount","chain","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_sendTransaction","error"]}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as K,b as $,c as q,d as p,e as _}from"./chunk-
|
|
1
|
+
import{a as K,b as $,c as q,d as p,e as _}from"./chunk-24YWZ2XF.js";import{a as B,b as D,c as x,d as L,e as m}from"./chunk-DDEUATTE.js";import{a as l}from"./chunk-TCWGPC6G.js";import h from"debug";var T=h("mud:benchmark");T.log=console.info.bind(console);function U(e){let r=T.extend(e),t=performance.now();return o=>{let n=(performance.now()-t)/1e3;r("%s: +%ds",o,n),t=performance.now()}}import{privateKeyToAccount as P}from"viem/accounts";function Q(e){return{...P(e)}}import{getContract as w}from"viem";function H(e){let r=e.length&&Array.isArray(e[0]),t=r?e[0]:[],o=(r?e[1]:e[0])??{};return{args:t,options:o}}function d({abi:e,address:r,client:{public:t,wallet:o},onWrite:n}){let i=w({abi:e,address:r,client:{public:t,wallet:o}});if(i.write){let s=0;i.write=new Proxy({},{get(F,C){return(...g)=>{let{args:A,options:k}=H(g),c={abi:e,address:r,functionName:C,args:A,...k,onWrite:n},u=p(o,c,{publicClient:t}),y=`${o.chain.id}:${o.account.address}:${s++}`;return n?.({id:y,request:c,result:u}),u}}})}return i}import{generatePrivateKey as v,privateKeyToAccount as f}from"viem/accounts";import{isHex as W}from"viem";function O(e,r){if(!W(e))throw console.error("Private key found in cache is not valid hex",{privateKey:e,cacheKey:r}),new Error(`Private key found in cache (${r}) is not valid hex`);f(e)}function Te(e="mud:burnerWallet"){let r=localStorage.getItem(e);if(r!=null)return O(r,e),r;let t=v();return console.log("New burner wallet created:",f(t)),localStorage.setItem(e,t),t}function fe(e,r){return e.blockNumber===r.blockNumber?e.logIndex===r.logIndex?0:e.logIndex==null?1:r.logIndex==null?-1:e.logIndex-r.logIndex:e.blockNumber==null?1:r.blockNumber==null?-1:e.blockNumber>r.blockNumber?1:e.blockNumber<r.blockNumber?-1:0}var b=class extends Map{maxSize;constructor(r){super(),this.maxSize=r}set(r,t){return super.set(r,t),this.maxSize&&this.size>this.maxSize&&this.delete(this.keys().next().value),this}};function a(e,r,t){return`0x${e.replace(/^0x/,"").slice(r*2,t!=null?t*2:void 0).padEnd(((t??r)-r)*2,"0")}`}function Ae(e){return"ok"in e}function I(e){return"error"in e}function ke(e){if(I(e))throw e.error;return e.ok}import{concatHex as N}from"viem";function He(e,r,t=0,o="0x"){return N([a(e,0,r),o,a(e,r+t)])}import{keccak256 as E}from"viem";var R=l.extend("transportObserver");function Ee(e){return r=>{let t=e(r);return{...t,request:async n=>{if(n.method==="eth_sendRawTransaction"&&n.params instanceof Array){let i=n.params.map(s=>E(s));R("saw txs",i)}return t.request(n)}}}}var S=d;var G=x;var z=m;export{b as LruMap,U as createBenchmark,Q as createBurnerAccount,S as createContract,$ as createNonceManager,Te as getBurnerPrivateKey,d as getContract,q as getNonceManager,K as getNonceManagerId,m as hexToResource,z as hexToResourceId,I as isError,Ae as isOk,fe as logSort,a as readHex,G as resourceIdToHex,x as resourceToHex,L as resourceToLabel,D as resourceTypeIds,B as resourceTypes,_ as sendTransaction,He as spliceHex,Ee as transportObserver,ke as unwrap,p as writeContract};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@latticexyz/common",
|
|
3
|
-
"version": "2.2.12-main-
|
|
3
|
+
"version": "2.2.12-main-fe98442d7ee82f0d41ba10f05a4ee1bafea69d48",
|
|
4
4
|
"description": "Common low level logic shared between packages",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
"prettier": "3.2.5",
|
|
67
67
|
"prettier-plugin-solidity": "1.3.1",
|
|
68
68
|
"viem": "2.21.19",
|
|
69
|
-
"@latticexyz/schema-type": "2.2.12-main-
|
|
69
|
+
"@latticexyz/schema-type": "2.2.12-main-fe98442d7ee82f0d41ba10f05a4ee1bafea69d48"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
72
|
"@types/debug": "^4.1.7",
|