@latticexyz/common 2.2.15-c93db3b213e0a6f29f4a6959fcf3871a9a4935ff → 2.2.15-d368857657aeb4bd63a3ce49e059e4e588c240aa

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.d.ts CHANGED
@@ -1,14 +1,14 @@
1
- import { Chain, PublicClient, Transport, Account, Client, WalletActions } from 'viem';
1
+ import { Chain, Client, Transport, Account, WalletActions } from 'viem';
2
2
  import { C as ContractWrite } from './getContract-93922960.js';
3
3
 
4
- type TransactionQueueOptions<chain extends Chain> = {
4
+ type TransactionQueueOptions<chain extends Chain | undefined> = {
5
5
  /**
6
6
  * `publicClient` can be provided to be used in place of the extended viem client for making public action calls
7
7
  * (`getChainId`, `getTransactionCount`, `simulateContract`, `call`). This helps in cases where the extended
8
8
  * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),
9
9
  * where the transport is the bundler, not an RPC.
10
10
  */
11
- publicClient?: PublicClient<Transport, chain>;
11
+ publicClient?: Client<Transport, chain>;
12
12
  /**
13
13
  * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered
14
14
  * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions
@@ -17,7 +17,7 @@ type TransactionQueueOptions<chain extends Chain> = {
17
17
  */
18
18
  queueConcurrency?: number;
19
19
  };
20
- declare function transactionQueue<chain extends Chain>(opts?: TransactionQueueOptions<chain>): <transport extends Transport, account extends Account | undefined = Account | undefined>(client: Client<transport, chain, account>) => Pick<WalletActions<chain, account>, "writeContract" | "sendTransaction">;
20
+ declare function transactionQueue<chain extends Chain | undefined>(opts?: TransactionQueueOptions<chain>): <transport extends Transport, account extends Account | undefined = Account | undefined>(client: Client<transport, chain, account>) => Pick<WalletActions<chain, account>, "writeContract" | "sendTransaction">;
21
21
 
22
22
  type WriteObserverParameters = {
23
23
  onWrite: (write: ContractWrite) => void;
package/dist/actions.js CHANGED
@@ -1,2 +1,2 @@
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};
1
+ import{d as o,e as a}from"./chunk-YK6YDQFD.js";import"./chunk-TCWGPC6G.js";function d(n={}){return e=>({writeContract:t=>o(e,t,n),sendTransaction:t=>a(e,t,n)})}import{getAction as s}from"viem/utils";import{writeContract as u}from"viem/actions";function f({onWrite:n}){let e=0;return t=>({writeContract:r=>{let i=s(t,u,"writeContract")(r),c=`${t.chain.id}:${t.account.address}:${e++}`;return n({id:c,request:r,result:i}),i}})}export{d as transactionQueue,f as writeObserver};
2
2
  //# sourceMappingURL=actions.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/actions/transactionQueue.ts","../src/actions/writeObserver.ts"],"sourcesContent":["import type { Transport, Chain, Account, WalletActions, Client, PublicClient } from \"viem\";\nimport { writeContract as mud_writeContract } from \"../writeContract\";\nimport { sendTransaction as mud_sendTransaction } from \"../sendTransaction\";\n\nexport type TransactionQueueOptions<chain extends Chain> = {\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`, `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\nexport function transactionQueue<chain extends Chain>(\n opts: TransactionQueueOptions<chain> = {},\n): <transport extends Transport, account extends Account | undefined = Account | undefined>(\n client: Client<transport, chain, account>,\n) => Pick<WalletActions<chain, account>, \"writeContract\" | \"sendTransaction\"> {\n return (client) => ({\n // Applies to: `client.writeContract`, `getContract(client, ...).write`\n writeContract: (args) => mud_writeContract(client, args, opts),\n // Applies to: `client.sendTransaction`\n sendTransaction: (args) => mud_sendTransaction(client, args, opts),\n });\n}\n","import type {\n WriteContractParameters,\n Transport,\n Chain,\n Account,\n WalletActions,\n WriteContractReturnType,\n Client,\n} from \"viem\";\nimport { getAction } from \"viem/utils\";\nimport { writeContract } from \"viem/actions\";\nimport { type ContractWrite } from \"../getContract\";\n\ntype WriteObserverParameters = { onWrite: (write: ContractWrite) => void };\n\nexport function writeObserver<TChain extends Chain, TAccount extends Account>({\n onWrite,\n}: WriteObserverParameters): (\n client: Client<Transport, TChain, TAccount>,\n) => Pick<WalletActions<TChain, TAccount>, \"writeContract\"> {\n let nextWriteId = 0;\n\n return (client) => ({\n // Applies to: `client.writeContract`, `getContract(client, ...).write`\n writeContract: (args): Promise<WriteContractReturnType> => {\n const result = getAction(client, writeContract, \"writeContract\")(args);\n\n const id = `${client.chain.id}:${client.account.address}:${nextWriteId++}`;\n onWrite({ id, request: args as WriteContractParameters, result });\n\n return result;\n },\n });\n}\n"],"mappings":"2EAqBO,SAASA,EACdC,EAAuC,CAAC,EAGoC,CAC5E,OAAQC,IAAY,CAElB,cAAgBC,GAASC,EAAkBF,EAAQC,EAAMF,CAAI,EAE7D,gBAAkBE,GAASE,EAAoBH,EAAQC,EAAMF,CAAI,CACnE,EACF,CCvBA,OAAS,aAAAK,MAAiB,aAC1B,OAAS,iBAAAC,MAAqB,eAKvB,SAASC,EAA8D,CAC5E,QAAAC,CACF,EAE4D,CAC1D,IAAIC,EAAc,EAElB,OAAQC,IAAY,CAElB,cAAgBC,GAA2C,CACzD,IAAMC,EAASP,EAAUK,EAAQJ,EAAe,eAAe,EAAEK,CAAI,EAE/DE,EAAK,GAAGH,EAAO,MAAM,MAAMA,EAAO,QAAQ,WAAWD,MAC3D,OAAAD,EAAQ,CAAE,GAAAK,EAAI,QAASF,EAAiC,OAAAC,CAAO,CAAC,EAEzDA,CACT,CACF,EACF","names":["transactionQueue","opts","client","args","writeContract","sendTransaction","getAction","writeContract","writeObserver","onWrite","nextWriteId","client","args","result","id"]}
1
+ {"version":3,"sources":["../src/actions/transactionQueue.ts","../src/actions/writeObserver.ts"],"sourcesContent":["import type { Transport, Chain, Account, WalletActions, Client } from \"viem\";\nimport { writeContract as mud_writeContract } from \"../writeContract\";\nimport { sendTransaction as mud_sendTransaction } from \"../sendTransaction\";\n\nexport type TransactionQueueOptions<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`, `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\nexport function transactionQueue<chain extends Chain | undefined>(\n opts: TransactionQueueOptions<chain> = {},\n): <transport extends Transport, account extends Account | undefined = Account | undefined>(\n client: Client<transport, chain, account>,\n) => Pick<WalletActions<chain, account>, \"writeContract\" | \"sendTransaction\"> {\n return (client) => ({\n // Applies to: `client.writeContract`, `getContract(client, ...).write`\n writeContract: (args) => mud_writeContract(client, args, opts),\n // Applies to: `client.sendTransaction`\n sendTransaction: (args) => mud_sendTransaction(client, args, opts),\n });\n}\n","import type {\n WriteContractParameters,\n Transport,\n Chain,\n Account,\n WalletActions,\n WriteContractReturnType,\n Client,\n} from \"viem\";\nimport { getAction } from \"viem/utils\";\nimport { writeContract } from \"viem/actions\";\nimport { type ContractWrite } from \"../getContract\";\n\ntype WriteObserverParameters = { onWrite: (write: ContractWrite) => void };\n\nexport function writeObserver<TChain extends Chain, TAccount extends Account>({\n onWrite,\n}: WriteObserverParameters): (\n client: Client<Transport, TChain, TAccount>,\n) => Pick<WalletActions<TChain, TAccount>, \"writeContract\"> {\n let nextWriteId = 0;\n\n return (client) => ({\n // Applies to: `client.writeContract`, `getContract(client, ...).write`\n writeContract: (args): Promise<WriteContractReturnType> => {\n const result = getAction(client, writeContract, \"writeContract\")(args);\n\n const id = `${client.chain.id}:${client.account.address}:${nextWriteId++}`;\n onWrite({ id, request: args as WriteContractParameters, result });\n\n return result;\n },\n });\n}\n"],"mappings":"2EAqBO,SAASA,EACdC,EAAuC,CAAC,EAGoC,CAC5E,OAAQC,IAAY,CAElB,cAAgBC,GAASC,EAAkBF,EAAQC,EAAMF,CAAI,EAE7D,gBAAkBE,GAASE,EAAoBH,EAAQC,EAAMF,CAAI,CACnE,EACF,CCvBA,OAAS,aAAAK,MAAiB,aAC1B,OAAS,iBAAAC,MAAqB,eAKvB,SAASC,EAA8D,CAC5E,QAAAC,CACF,EAE4D,CAC1D,IAAIC,EAAc,EAElB,OAAQC,IAAY,CAElB,cAAgBC,GAA2C,CACzD,IAAMC,EAASP,EAAUK,EAAQJ,EAAe,eAAe,EAAEK,CAAI,EAE/DE,EAAK,GAAGH,EAAO,MAAM,MAAMA,EAAO,QAAQ,WAAWD,MAC3D,OAAAD,EAAQ,CAAE,GAAAK,EAAI,QAASF,EAAiC,OAAAC,CAAO,CAAC,EAEzDA,CACT,CACF,EACF","names":["transactionQueue","opts","client","args","writeContract","sendTransaction","getAction","writeContract","writeObserver","onWrite","nextWriteId","client","args","result","id"]}
@@ -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",...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
+ 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 y=m.extend("createNonceManager");function b({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 w=JSON.parse(M.data);y("got nonce from broadcast channel",w),n.nonce=w})});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)),y("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)??b({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,b,g as c,Se as d,Je as e};
2
+ //# sourceMappingURL=chunk-YK6YDQFD.js.map
@@ -0,0 +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} 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?: 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 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 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":"wCAAA,OAAgC,cAAAA,MAAkB,OAClD,OAAS,c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CAEb,SAAU,UACV,GAAGJ,EAAO,KACV,GAAGR,EACH,MAAAW,CACF,EACA,OAAAd,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"]}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Hex, PrivateKeyAccount, Client, BlockTag, Chain, PublicClient, 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 } from 'viem';
2
2
  import PQueue from 'p-queue';
3
3
  import { g as getContract } from './getContract-93922960.js';
4
4
  export { C as ContractWrite, G as GetContractOptions } from './getContract-93922960.js';
@@ -111,7 +111,7 @@ type SendTransactionExtraOptions<chain extends Chain | undefined> = {
111
111
  * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),
112
112
  * where the transport is the bundler, not an RPC.
113
113
  */
114
- publicClient?: PublicClient<Transport, chain>;
114
+ publicClient?: Client<Transport, chain>;
115
115
  /**
116
116
  * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered
117
117
  * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions
@@ -134,7 +134,7 @@ type WriteContractExtraOptions<chain extends Chain | undefined> = {
134
134
  * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),
135
135
  * where the transport is the bundler, not an RPC.
136
136
  */
137
- publicClient?: PublicClient<Transport, chain>;
137
+ publicClient?: Client<Transport, chain>;
138
138
  /**
139
139
  * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered
140
140
  * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions
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-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};
1
+ import{a as K,b as $,c as q,d as p,e as _}from"./chunk-YK6YDQFD.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.15-c93db3b213e0a6f29f4a6959fcf3871a9a4935ff",
3
+ "version": "2.2.15-d368857657aeb4bd63a3ce49e059e4e588c240aa",
4
4
  "description": "Common low level logic shared between packages",
5
5
  "repository": {
6
6
  "type": "git",
@@ -65,19 +65,20 @@
65
65
  "p-retry": "^5.1.2",
66
66
  "prettier": "3.2.5",
67
67
  "prettier-plugin-solidity": "1.3.1",
68
- "viem": "2.21.19",
69
- "@latticexyz/schema-type": "2.2.15-c93db3b213e0a6f29f4a6959fcf3871a9a4935ff"
68
+ "@latticexyz/schema-type": "2.2.15-d368857657aeb4bd63a3ce49e059e4e588c240aa"
70
69
  },
71
70
  "devDependencies": {
72
71
  "@types/debug": "^4.1.7",
73
72
  "@types/node": "^18.15.11",
74
73
  "@viem/anvil": "^0.0.7",
75
74
  "tsup": "^6.7.0",
75
+ "viem": "2.21.19",
76
76
  "vitest": "0.34.6"
77
77
  },
78
78
  "peerDependencies": {
79
79
  "@aws-sdk/client-kms": "3.x",
80
- "asn1.js": "5.x"
80
+ "asn1.js": "5.x",
81
+ "viem": "2.x"
81
82
  },
82
83
  "peerDependenciesMeta": {
83
84
  "@aws-sdk/client-kms": {
@@ -1 +0,0 @@
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,0BADSF,EAAO,OAAO,IAAO,MAAMF,EAAUE,EAAQH,EAAY,YAAY,EAAE,CAAC,CAAC,KAC7CD,EAAWK,CAAO,KAAKC,GACrE,CChBA,OAAS,aAAAC,EAAkC,qBAAAC,EAAmB,oBAAAC,MAAwB,OAGtF,OAAS,uBAAAC,MAA2B,eACpC,OAAOC,MAAY,UACnB,OAAS,aAAAC,MAAiB,aAE1B,IAAMC,EAAQA,EAAY,OAAO,oBAAoB,EAmB9C,SAASC,EAAmB,CACjC,OAAAC,EACA,QAAAC,EACA,SAAAC,EAAW,SACX,qBAAAC,EACA,iBAAAC,EAAmB,CACrB,EAAwD,CACtD,IAAMC,EAAM,CAAE,MAAO,GAAI,aAAc,IAA6B,EAChEC,EAAmC,KAEnC,OAAO,iBAAqB,MACVH,EAChB,QAAQ,QAAQA,CAAoB,EACpCI,EAAkB,CAAE,OAAAP,EAAQ,Q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QA,EAAY,OAAO,iBAAiB,EAoBlD,eAAsBC,GAMpBC,EACAC,EACAC,EAA2C,CAAC,EACR,CACpC,IAAMC,EAAaF,EAAQ,SAAWD,EAAO,QAC7C,GAAI,CAACG,EAEH,MAAM,IAAI,MAAM,qBAAqB,EAEvC,IAAMC,EAAUC,EAAaF,CAAU,EACjCG,EAAQN,EAAO,MAEfO,EAAe,MAAMC,EAAgB,CACzC,OAAQN,EAAK,cAAgBF,EAC7B,QAASI,EAAQ,QACjB,iBAAkBF,EAAK,gBACzB,CAAC,EAEKO,EAAS,MAAMC,EAAU,CAC7B,OAAQR,EAAK,cAAgBF,EAC7B,gBAAiB,IACjB,KAAM,CAAE,MAAAM,CAAM,CAChB,CAAC,EAED,OAAO,MAAMC,EAAa,aAAa,IACrC,IACEI,EACE,SAAY,CACV,IAAMC,EAAQL,EAAa,UAAU,EAC/BM,EAAS,CAEb,SAAU,UACV,GAAGJ,EAAO,KACV,GAAGR,EACH,MAAAW,CACF,EACA,OAAAd,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"]}