@latticexyz/common 2.2.4-main-784e5a98e679388ad6bc941cd1bc9b6486cf276d → 2.2.4-main-2f935cfd3fbc62f3c304e470751a26189523fcd2

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-JQHDLHUT.js";import"./chunk-TCWGPC6G.js";function p(r={}){return n=>({writeContract:t=>o(n,t,r),sendTransaction:t=>a(n,t,r)})}import{getAction as s}from"viem/utils";import{writeContract as u}from"viem/actions";function h({onWrite:r}){let n=0;return t=>({writeContract:e=>{let i=s(t,u,"writeContract")(e),c=`${t.chain.id}:${t.account.address}:${n++}`;return r({id:c,request:e,result:i}),i}})}export{p as transactionQueue,h as writeObserver};
1
+ import{d as o,e as a}from"./chunk-3XILP7OL.js";import"./chunk-TCWGPC6G.js";function p(r={}){return n=>({writeContract:t=>o(n,t,r),sendTransaction:t=>a(n,t,r)})}import{getAction as s}from"viem/utils";import{writeContract as u}from"viem/actions";function h({onWrite:r}){let n=0;return t=>({writeContract:e=>{let i=s(t,u,"writeContract")(e),c=`${t.chain.id}:${t.account.address}:${n++}`;return r({id:c,request:e,result:i}),i}})}export{p as transactionQueue,h as writeObserver};
2
2
  //# sourceMappingURL=actions.js.map
package/dist/chains.d.ts CHANGED
@@ -1,7 +1,7 @@
1
+ import * as viem_chains from 'viem/chains';
1
2
  import { Chain } from 'viem/chains';
2
3
  import * as viem from 'viem';
3
4
  import * as viem_experimental from 'viem/experimental';
4
- import * as viem_op_stack from 'viem/op-stack';
5
5
 
6
6
  type MUDChain = Chain & {
7
7
  iconUrls?: readonly string[];
@@ -83,21 +83,8 @@ declare const latticeTestnet: {
83
83
  };
84
84
 
85
85
  declare const garnet: {
86
- readonly id: 17069;
87
- readonly sourceId: 17000;
88
- readonly name: "Garnet Holesky";
89
- readonly testnet: true;
90
- readonly nativeCurrency: {
91
- readonly name: "Ether";
92
- readonly symbol: "ETH";
93
- readonly decimals: 18;
94
- };
95
- readonly rpcUrls: {
96
- readonly default: {
97
- readonly http: readonly ["https://rpc.garnetchain.com"];
98
- readonly webSocket: readonly ["wss://rpc.garnetchain.com"];
99
- };
100
- };
86
+ readonly iconUrls: readonly ["https://redstone.xyz/chain-icons/garnet.png"];
87
+ readonly indexerUrl: "https://indexer.mud.garnetchain.com";
101
88
  readonly blockExplorers: {
102
89
  readonly default: {
103
90
  readonly name: "Blockscout";
@@ -145,12 +132,27 @@ declare const garnet: {
145
132
  readonly address: "0x4200000000000000000000000000000000000016";
146
133
  };
147
134
  };
148
- readonly iconUrls: readonly ["https://redstone.xyz/chain-icons/garnet.png"];
149
- readonly indexerUrl: "https://indexer.mud.garnetchain.com";
135
+ readonly id: 17069;
136
+ readonly name: "Garnet Testnet";
137
+ readonly nativeCurrency: {
138
+ readonly name: "Ether";
139
+ readonly symbol: "ETH";
140
+ readonly decimals: 18;
141
+ };
142
+ readonly rpcUrls: {
143
+ readonly default: {
144
+ readonly http: readonly ["https://rpc.garnetchain.com"];
145
+ readonly webSocket: readonly ["wss://rpc.garnetchain.com"];
146
+ };
147
+ };
148
+ readonly sourceId: 17000;
149
+ readonly testnet: true;
150
+ readonly custom?: Record<string, unknown> | undefined;
151
+ readonly fees?: viem.ChainFees<undefined> | undefined;
150
152
  readonly formatters: {
151
153
  readonly block: {
152
154
  exclude: [] | undefined;
153
- format: (args: viem_op_stack.OpStackRpcBlock<viem.BlockTag, boolean>) => {
155
+ format: (args: viem_chains.OpStackRpcBlock<viem.BlockTag, boolean>) => {
154
156
  baseFeePerGas: bigint | null;
155
157
  blobGasUsed: bigint;
156
158
  difficulty: bigint;
@@ -172,7 +174,7 @@ declare const garnet: {
172
174
  stateRoot: `0x${string}`;
173
175
  timestamp: bigint;
174
176
  totalDifficulty: bigint | null;
175
- transactions: `0x${string}`[] | viem_op_stack.OpStackTransaction<boolean>[];
177
+ transactions: `0x${string}`[] | viem_chains.OpStackTransaction<boolean>[];
176
178
  transactionsRoot: `0x${string}`;
177
179
  uncles: `0x${string}`[];
178
180
  withdrawals?: viem.Withdrawal[] | undefined;
@@ -182,7 +184,7 @@ declare const garnet: {
182
184
  };
183
185
  readonly transaction: {
184
186
  exclude: [] | undefined;
185
- format: (args: viem_op_stack.OpStackRpcTransaction<boolean>) => {
187
+ format: (args: viem_chains.OpStackRpcTransaction<boolean>) => {
186
188
  blockHash: `0x${string}` | null;
187
189
  blockNumber: bigint | null;
188
190
  from: `0x${string}`;
@@ -351,7 +353,7 @@ declare const garnet: {
351
353
  };
352
354
  readonly transactionReceipt: {
353
355
  exclude: [] | undefined;
354
- format: (args: viem_op_stack.OpStackRpcTransactionReceipt) => {
356
+ format: (args: viem_chains.OpStackRpcTransactionReceipt) => {
355
357
  blobGasPrice?: bigint | undefined;
356
358
  blobGasUsed?: bigint | undefined;
357
359
  blockHash: `0x${string}`;
@@ -378,25 +380,13 @@ declare const garnet: {
378
380
  };
379
381
  };
380
382
  readonly serializers: {
381
- readonly transaction: typeof viem_op_stack.serializeTransaction;
383
+ readonly transaction: typeof viem_chains.serializeTransactionOpStack;
382
384
  };
383
385
  };
384
386
 
385
387
  declare const redstone: {
386
- readonly id: 690;
387
- readonly sourceId: 1;
388
- readonly name: "Redstone";
389
- readonly nativeCurrency: {
390
- readonly name: "Ether";
391
- readonly symbol: "ETH";
392
- readonly decimals: 18;
393
- };
394
- readonly rpcUrls: {
395
- readonly default: {
396
- readonly http: readonly ["https://rpc.redstonechain.com"];
397
- readonly webSocket: readonly ["wss://rpc.redstonechain.com"];
398
- };
399
- };
388
+ readonly iconUrls: readonly ["https://redstone.xyz/chain-icons/redstone.png"];
389
+ readonly indexerUrl: "https://indexer.mud.redstonechain.com";
400
390
  readonly blockExplorers: {
401
391
  readonly default: {
402
392
  readonly name: "Blockscout";
@@ -444,12 +434,27 @@ declare const redstone: {
444
434
  readonly address: "0x4200000000000000000000000000000000000016";
445
435
  };
446
436
  };
447
- readonly iconUrls: readonly ["https://redstone.xyz/chain-icons/redstone.png"];
448
- readonly indexerUrl: "https://indexer.mud.redstonechain.com";
437
+ readonly id: 690;
438
+ readonly name: "Redstone";
439
+ readonly nativeCurrency: {
440
+ readonly decimals: 18;
441
+ readonly name: "Ether";
442
+ readonly symbol: "ETH";
443
+ };
444
+ readonly rpcUrls: {
445
+ readonly default: {
446
+ readonly http: readonly ["https://rpc.redstonechain.com"];
447
+ readonly webSocket: readonly ["wss://rpc.redstonechain.com"];
448
+ };
449
+ };
450
+ readonly sourceId: 1;
451
+ readonly testnet?: boolean | undefined;
452
+ readonly custom?: Record<string, unknown> | undefined;
453
+ readonly fees?: viem.ChainFees<undefined> | undefined;
449
454
  readonly formatters: {
450
455
  readonly block: {
451
456
  exclude: [] | undefined;
452
- format: (args: viem_op_stack.OpStackRpcBlock<viem.BlockTag, boolean>) => {
457
+ format: (args: viem_chains.OpStackRpcBlock<viem.BlockTag, boolean>) => {
453
458
  baseFeePerGas: bigint | null;
454
459
  blobGasUsed: bigint;
455
460
  difficulty: bigint;
@@ -471,7 +476,7 @@ declare const redstone: {
471
476
  stateRoot: `0x${string}`;
472
477
  timestamp: bigint;
473
478
  totalDifficulty: bigint | null;
474
- transactions: `0x${string}`[] | viem_op_stack.OpStackTransaction<boolean>[];
479
+ transactions: `0x${string}`[] | viem_chains.OpStackTransaction<boolean>[];
475
480
  transactionsRoot: `0x${string}`;
476
481
  uncles: `0x${string}`[];
477
482
  withdrawals?: viem.Withdrawal[] | undefined;
@@ -481,7 +486,7 @@ declare const redstone: {
481
486
  };
482
487
  readonly transaction: {
483
488
  exclude: [] | undefined;
484
- format: (args: viem_op_stack.OpStackRpcTransaction<boolean>) => {
489
+ format: (args: viem_chains.OpStackRpcTransaction<boolean>) => {
485
490
  blockHash: `0x${string}` | null;
486
491
  blockNumber: bigint | null;
487
492
  from: `0x${string}`;
@@ -650,7 +655,7 @@ declare const redstone: {
650
655
  };
651
656
  readonly transactionReceipt: {
652
657
  exclude: [] | undefined;
653
- format: (args: viem_op_stack.OpStackRpcTransactionReceipt) => {
658
+ format: (args: viem_chains.OpStackRpcTransactionReceipt) => {
654
659
  blobGasPrice?: bigint | undefined;
655
660
  blobGasUsed?: bigint | undefined;
656
661
  blockHash: `0x${string}`;
@@ -677,7 +682,7 @@ declare const redstone: {
677
682
  };
678
683
  };
679
684
  readonly serializers: {
680
- readonly transaction: typeof viem_op_stack.serializeTransaction;
685
+ readonly transaction: typeof viem_chains.serializeTransactionOpStack;
681
686
  };
682
687
  };
683
688
 
package/dist/chains.js CHANGED
@@ -1,2 +1,2 @@
1
- import{foundry as s}from"viem/chains";var o={...s,fees:{defaultPriorityFee:0n}};var n={name:"Lattice Testnet",id:4242,nativeCurrency:{decimals:18,name:"Ether",symbol:"ETH"},rpcUrls:{default:{http:["https://follower.testnet-chain.linfra.xyz"],webSocket:["wss://follower.testnet-chain.linfra.xyz"]},public:{http:["https://follower.testnet-chain.linfra.xyz"],webSocket:["wss://follower.testnet-chain.linfra.xyz"]}},blockExplorers:{default:{name:"Otterscan",url:"https://explorer.testnet-chain.linfra.xyz"}},faucetUrl:"https://faucet.testnet-mud-services.linfra.xyz"};import{chainConfig as r}from"viem/op-stack";var e=17e3,c={...r,id:17069,sourceId:e,name:"Garnet Holesky",testnet:!0,nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.garnetchain.com"],webSocket:["wss://rpc.garnetchain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.garnetchain.com"}},contracts:{...r.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11"},portal:{[e]:{address:"0x57ee40586fbE286AfC75E67cb69511A6D9aF5909",blockCreated:1274684}},l2OutputOracle:{[e]:{address:"0xCb8E7AC561b8EF04F2a15865e9fbc0766FEF569B",blockCreated:1274684}},l1StandardBridge:{[e]:{address:"0x09bcDd311FE398F80a78BE37E489f5D440DB95DE",blockCreated:1274684}}},iconUrls:["https://redstone.xyz/chain-icons/garnet.png"],indexerUrl:"https://indexer.mud.garnetchain.com"};import{chainConfig as a}from"viem/op-stack";var t=1,i={...a,id:690,sourceId:t,name:"Redstone",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://rpc.redstonechain.com"],webSocket:["wss://rpc.redstonechain.com"]}},blockExplorers:{default:{name:"Blockscout",url:"https://explorer.redstone.xyz"}},contracts:{...a.contracts,multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11"},portal:{[t]:{address:"0xC7bCb0e8839a28A1cFadd1CF716de9016CdA51ae",blockCreated:19578329}},l2OutputOracle:{[t]:{address:"0xa426A052f657AEEefc298b3B5c35a470e4739d69",blockCreated:19578337}},l1StandardBridge:{[t]:{address:"0xc473ca7E02af24c129c2eEf51F2aDf0411c1Df69",blockCreated:19578331}}},iconUrls:["https://redstone.xyz/chain-icons/redstone.png"],indexerUrl:"https://indexer.mud.redstonechain.com"};export{c as garnet,n as latticeTestnet,o as mudFoundry,i as redstone};
1
+ import{foundry as t}from"viem/chains";var e={...t,fees:{defaultPriorityFee:0n}};var r={name:"Lattice Testnet",id:4242,nativeCurrency:{decimals:18,name:"Ether",symbol:"ETH"},rpcUrls:{default:{http:["https://follower.testnet-chain.linfra.xyz"],webSocket:["wss://follower.testnet-chain.linfra.xyz"]},public:{http:["https://follower.testnet-chain.linfra.xyz"],webSocket:["wss://follower.testnet-chain.linfra.xyz"]}},blockExplorers:{default:{name:"Otterscan",url:"https://explorer.testnet-chain.linfra.xyz"}},faucetUrl:"https://faucet.testnet-mud-services.linfra.xyz"};import{garnet as n}from"viem/chains";var s={...n,iconUrls:["https://redstone.xyz/chain-icons/garnet.png"],indexerUrl:"https://indexer.mud.garnetchain.com"};import{redstone as o}from"viem/chains";var i={...o,iconUrls:["https://redstone.xyz/chain-icons/redstone.png"],indexerUrl:"https://indexer.mud.redstonechain.com"};export{s as garnet,r as latticeTestnet,e as mudFoundry,i as redstone};
2
2
  //# sourceMappingURL=chains.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/chains/mudFoundry.ts","../src/chains/latticeTestnet.ts","../src/chains/garnet.ts","../src/chains/redstone.ts"],"sourcesContent":["import { foundry } from \"viem/chains\";\nimport { MUDChain } from \"./types\";\n\nexport const mudFoundry = {\n ...foundry,\n fees: {\n defaultPriorityFee: 0n,\n },\n} as const satisfies MUDChain;\n","import type { MUDChain } from \"./types\";\n\n/** @deprecated This chain is deprecated and will be going offline soon. Please switch to Garnet! */\nexport const latticeTestnet = {\n name: \"Lattice Testnet\",\n id: 4242,\n nativeCurrency: { decimals: 18, name: \"Ether\", symbol: \"ETH\" },\n rpcUrls: {\n default: {\n http: [\"https://follower.testnet-chain.linfra.xyz\"],\n webSocket: [\"wss://follower.testnet-chain.linfra.xyz\"],\n },\n public: {\n http: [\"https://follower.testnet-chain.linfra.xyz\"],\n webSocket: [\"wss://follower.testnet-chain.linfra.xyz\"],\n },\n },\n blockExplorers: {\n default: {\n name: \"Otterscan\",\n url: \"https://explorer.testnet-chain.linfra.xyz\",\n },\n },\n faucetUrl: \"https://faucet.testnet-mud-services.linfra.xyz\",\n} as const satisfies MUDChain;\n","import { chainConfig } from \"viem/op-stack\";\nimport type { MUDChain } from \"./types\";\n\nconst sourceId = 17000; // Holesky\n\nexport const garnet = {\n ...chainConfig,\n id: 17069,\n sourceId,\n name: \"Garnet Holesky\",\n testnet: true,\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: {\n default: {\n http: [\"https://rpc.garnetchain.com\"],\n webSocket: [\"wss://rpc.garnetchain.com\"],\n },\n },\n blockExplorers: {\n default: {\n name: \"Blockscout\",\n url: \"https://explorer.garnetchain.com\",\n },\n },\n contracts: {\n ...chainConfig.contracts,\n multicall3: {\n address: \"0xca11bde05977b3631167028862be2a173976ca11\",\n },\n portal: {\n [sourceId]: {\n address: \"0x57ee40586fbE286AfC75E67cb69511A6D9aF5909\",\n blockCreated: 1274684,\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: \"0xCb8E7AC561b8EF04F2a15865e9fbc0766FEF569B\",\n blockCreated: 1274684,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: \"0x09bcDd311FE398F80a78BE37E489f5D440DB95DE\",\n blockCreated: 1274684,\n },\n },\n },\n iconUrls: [\"https://redstone.xyz/chain-icons/garnet.png\"],\n indexerUrl: \"https://indexer.mud.garnetchain.com\",\n} as const satisfies MUDChain;\n","import { chainConfig } from \"viem/op-stack\";\nimport type { MUDChain } from \"./types\";\n\nconst sourceId = 1; // Ethereum mainnet\n\nexport const redstone = {\n ...chainConfig,\n id: 690,\n sourceId,\n name: \"Redstone\",\n nativeCurrency: { name: \"Ether\", symbol: \"ETH\", decimals: 18 },\n rpcUrls: {\n default: {\n http: [\"https://rpc.redstonechain.com\"],\n webSocket: [\"wss://rpc.redstonechain.com\"],\n },\n },\n blockExplorers: {\n default: {\n name: \"Blockscout\",\n url: \"https://explorer.redstone.xyz\",\n },\n },\n contracts: {\n ...chainConfig.contracts,\n multicall3: {\n address: \"0xca11bde05977b3631167028862be2a173976ca11\",\n },\n portal: {\n [sourceId]: {\n address: \"0xC7bCb0e8839a28A1cFadd1CF716de9016CdA51ae\",\n blockCreated: 19578329,\n },\n },\n l2OutputOracle: {\n [sourceId]: {\n address: \"0xa426A052f657AEEefc298b3B5c35a470e4739d69\",\n blockCreated: 19578337,\n },\n },\n l1StandardBridge: {\n [sourceId]: {\n address: \"0xc473ca7E02af24c129c2eEf51F2aDf0411c1Df69\",\n blockCreated: 19578331,\n },\n },\n },\n iconUrls: [\"https://redstone.xyz/chain-icons/redstone.png\"],\n indexerUrl: \"https://indexer.mud.redstonechain.com\",\n} as const satisfies MUDChain;\n"],"mappings":"AAAA,OAAS,WAAAA,MAAe,cAGjB,IAAMC,EAAa,CACxB,GAAGD,EACH,KAAM,CACJ,mBAAoB,EACtB,CACF,ECLO,IAAME,EAAiB,CAC5B,KAAM,kBACN,GAAI,KACJ,eA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CACT,GAAGD,EAAY,UACf,WAAY,CACV,QAAS,4CACX,EACA,OAAQ,CACN,CAACC,CAAQ,EAAG,CACV,QAAS,6CACT,aAAc,QAChB,CACF,EACA,eAAgB,CACd,CAACA,CAAQ,EAAG,CACV,QAAS,6CACT,aAAc,QAChB,CACF,EACA,iBAAkB,CAChB,CAACA,CAAQ,EAAG,CACV,QAAS,6CACT,aAAc,QAChB,CACF,CACF,EACA,SAAU,CAAC,+CAA+C,EAC1D,WAAY,uCACd","names":["foundry","mudFoundry","latticeTestnet","chainConfig","sourceId","garnet","chainConfig","sourceId","redstone"]}
1
+ {"version":3,"sources":["../src/chains/mudFoundry.ts","../src/chains/latticeTestnet.ts","../src/chains/garnet.ts","../src/chains/redstone.ts"],"sourcesContent":["import { foundry } from \"viem/chains\";\nimport { MUDChain } from \"./types\";\n\nexport const mudFoundry = {\n ...foundry,\n fees: {\n defaultPriorityFee: 0n,\n },\n} as const satisfies MUDChain;\n","import type { MUDChain } from \"./types\";\n\n/** @deprecated This chain is deprecated and will be going offline soon. Please switch to Garnet! */\nexport const latticeTestnet = {\n name: \"Lattice Testnet\",\n id: 4242,\n nativeCurrency: { decimals: 18, name: \"Ether\", symbol: \"ETH\" },\n rpcUrls: {\n default: {\n http: [\"https://follower.testnet-chain.linfra.xyz\"],\n webSocket: [\"wss://follower.testnet-chain.linfra.xyz\"],\n },\n public: {\n http: [\"https://follower.testnet-chain.linfra.xyz\"],\n webSocket: [\"wss://follower.testnet-chain.linfra.xyz\"],\n },\n },\n blockExplorers: {\n default: {\n name: \"Otterscan\",\n url: \"https://explorer.testnet-chain.linfra.xyz\",\n },\n },\n faucetUrl: \"https://faucet.testnet-mud-services.linfra.xyz\",\n} as const satisfies MUDChain;\n","import { garnet as garnetConfig } from \"viem/chains\";\nimport type { MUDChain } from \"./types\";\n\nexport const garnet = {\n ...garnetConfig,\n iconUrls: [\"https://redstone.xyz/chain-icons/garnet.png\"],\n indexerUrl: \"https://indexer.mud.garnetchain.com\",\n} as const satisfies MUDChain;\n","import { redstone as redstoneConfig } from \"viem/chains\";\nimport type { MUDChain } from \"./types\";\n\nexport const redstone = {\n ...redstoneConfig,\n iconUrls: [\"https://redstone.xyz/chain-icons/redstone.png\"],\n indexerUrl: \"https://indexer.mud.redstonechain.com\",\n} as const satisfies MUDChain;\n"],"mappings":"AAAA,OAAS,WAAAA,MAAe,cAGjB,IAAMC,EAAa,CACxB,GAAGD,EACH,KAAM,CACJ,mBAAoB,EACtB,CACF,ECLO,IAAME,EAAiB,CAC5B,KAAM,kBACN,GAAI,KACJ,eAAgB,CAAE,SAAU,GAAI,KAAM,QAAS,OAAQ,KAAM,EAC7D,QAAS,CACP,QAAS,CACP,KAAM,CAAC,2CAA2C,EAClD,UAAW,CAAC,yCAAyC,CACvD,EACA,OAAQ,CACN,KAAM,CAAC,2CAA2C,EAClD,UAAW,CAAC,yCAAyC,CACvD,CACF,EACA,eAAgB,CACd,QAAS,CACP,KAAM,YACN,IAAK,2CACP,CACF,EACA,UAAW,gDACb,ECxBA,OAAS,UAAUC,MAAoB,cAGhC,IAAMC,EAAS,CACpB,GAAGD,EACH,SAAU,CAAC,6CAA6C,EACxD,WAAY,qCACd,ECPA,OAAS,YAAYE,MAAsB,cAGpC,IAAMC,EAAW,CACtB,GAAGD,EACH,SAAU,CAAC,+CAA+C,EAC1D,WAAY,uCACd","names":["foundry","mudFoundry","latticeTestnet","garnetConfig","garnet","redstoneConfig","redstone"]}
@@ -0,0 +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,...s.fees};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",...r,nonce:a,...s.fees};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-3XILP7OL.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 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,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,oB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BA,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 N,b as $,c as q,d as x,e as j}from"./chunk-JQHDLHUT.js";import{a as B,b as D,c as l,d as _,e as m}from"./chunk-DDEUATTE.js";import{a as p}from"./chunk-TCWGPC6G.js";import k from"debug";var T=k("mud:benchmark");T.log=console.info.bind(console);function J(e){let t=T.extend(e),r=performance.now();return o=>{let n=(performance.now()-r)/1e3;t("%s: +%ds",o,n),r=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 t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],o=(t?e[1]:e[0])??{};return{args:r,options:o}}function d({abi:e,address:t,client:{public:r,wallet:o},onWrite:n}){let s=w({abi:e,address:t,client:{public:r,wallet:o}});if(s.write){let i=0;s.write=new Proxy({},{get(K,b){return(...A)=>{let{args:g,options:h}=H(A),c={abi:e,address:t,functionName:b,args:g,...h,onWrite:n},u=x(o,c,{publicClient:r}),y=`${o.chain.id}:${o.account.address}:${i++}`;return n?.({id:y,request:c,result:u}),u}}})}return s}import{generatePrivateKey as v,privateKeyToAccount as f}from"viem/accounts";import{isHex as W}from"viem";function O(e,t){if(!W(e))throw console.error("Private key found in cache is not valid hex",{privateKey:e,cacheKey:t}),new Error(`Private key found in cache (${t}) is not valid hex`);f(e)}function Te(e="mud:burnerWallet"){let t=localStorage.getItem(e);if(t!=null)return O(t,e),t;let r=v();return console.log("New burner wallet created:",f(r)),localStorage.setItem(e,r),r}var C=class extends Map{maxSize;constructor(t){super(),this.maxSize=t}set(t,r){return super.set(t,r),this.maxSize&&this.size>this.maxSize&&this.delete(this.keys().next().value),this}};function a(e,t,r){return`0x${e.replace(/^0x/,"").slice(t*2,r!=null?r*2:void 0).padEnd(((r??t)-t)*2,"0")}`}function be(e){return"ok"in e}function E(e){return"error"in e}function Ae(e){if(E(e))throw e.error;return e.ok}import{concatHex as R}from"viem";function Pe(e,t,r=0,o="0x"){return R([a(e,0,t),o,a(e,t+r)])}import{keccak256 as S}from"viem";var G=p.extend("transportObserver");function Ee(e){return t=>{let r=e(t);return{...r,request:async n=>{if(n.method==="eth_sendRawTransaction"&&n.params instanceof Array){let s=n.params.map(i=>S(i));G("saw txs",s)}return r.request(n)}}}}var I=d;var z=l;var F=m;export{C as LruMap,J as createBenchmark,Q as createBurnerAccount,I as createContract,$ as createNonceManager,Te as getBurnerPrivateKey,d as getContract,q as getNonceManager,N as getNonceManagerId,m as hexToResource,F as hexToResourceId,E as isError,be as isOk,a as readHex,z as resourceIdToHex,l as resourceToHex,_ as resourceToLabel,D as resourceTypeIds,B as resourceTypes,j as sendTransaction,Pe as spliceHex,Ee as transportObserver,Ae as unwrap,x as writeContract};
1
+ import{a as N,b as $,c as q,d as x,e as j}from"./chunk-3XILP7OL.js";import{a as B,b as D,c as l,d as _,e as m}from"./chunk-DDEUATTE.js";import{a as p}from"./chunk-TCWGPC6G.js";import k from"debug";var T=k("mud:benchmark");T.log=console.info.bind(console);function J(e){let t=T.extend(e),r=performance.now();return o=>{let n=(performance.now()-r)/1e3;t("%s: +%ds",o,n),r=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 t=e.length&&Array.isArray(e[0]),r=t?e[0]:[],o=(t?e[1]:e[0])??{};return{args:r,options:o}}function d({abi:e,address:t,client:{public:r,wallet:o},onWrite:n}){let s=w({abi:e,address:t,client:{public:r,wallet:o}});if(s.write){let i=0;s.write=new Proxy({},{get(K,b){return(...A)=>{let{args:g,options:h}=H(A),c={abi:e,address:t,functionName:b,args:g,...h,onWrite:n},u=x(o,c,{publicClient:r}),y=`${o.chain.id}:${o.account.address}:${i++}`;return n?.({id:y,request:c,result:u}),u}}})}return s}import{generatePrivateKey as v,privateKeyToAccount as f}from"viem/accounts";import{isHex as W}from"viem";function O(e,t){if(!W(e))throw console.error("Private key found in cache is not valid hex",{privateKey:e,cacheKey:t}),new Error(`Private key found in cache (${t}) is not valid hex`);f(e)}function Te(e="mud:burnerWallet"){let t=localStorage.getItem(e);if(t!=null)return O(t,e),t;let r=v();return console.log("New burner wallet created:",f(r)),localStorage.setItem(e,r),r}var C=class extends Map{maxSize;constructor(t){super(),this.maxSize=t}set(t,r){return super.set(t,r),this.maxSize&&this.size>this.maxSize&&this.delete(this.keys().next().value),this}};function a(e,t,r){return`0x${e.replace(/^0x/,"").slice(t*2,r!=null?r*2:void 0).padEnd(((r??t)-t)*2,"0")}`}function be(e){return"ok"in e}function E(e){return"error"in e}function Ae(e){if(E(e))throw e.error;return e.ok}import{concatHex as R}from"viem";function Pe(e,t,r=0,o="0x"){return R([a(e,0,t),o,a(e,t+r)])}import{keccak256 as S}from"viem";var G=p.extend("transportObserver");function Ee(e){return t=>{let r=e(t);return{...r,request:async n=>{if(n.method==="eth_sendRawTransaction"&&n.params instanceof Array){let s=n.params.map(i=>S(i));G("saw txs",s)}return r.request(n)}}}}var I=d;var z=l;var F=m;export{C as LruMap,J as createBenchmark,Q as createBurnerAccount,I as createContract,$ as createNonceManager,Te as getBurnerPrivateKey,d as getContract,q as getNonceManager,N as getNonceManagerId,m as hexToResource,F as hexToResourceId,E as isError,be as isOk,a as readHex,z as resourceIdToHex,l as resourceToHex,_ as resourceToLabel,D as resourceTypeIds,B as resourceTypes,j as sendTransaction,Pe as spliceHex,Ee as transportObserver,Ae as unwrap,x 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.4-main-784e5a98e679388ad6bc941cd1bc9b6486cf276d",
3
+ "version": "2.2.4-main-2f935cfd3fbc62f3c304e470751a26189523fcd2",
4
4
  "description": "Common low level logic shared between packages",
5
5
  "repository": {
6
6
  "type": "git",
@@ -64,8 +64,8 @@
64
64
  "p-retry": "^5.1.2",
65
65
  "prettier": "3.2.5",
66
66
  "prettier-plugin-solidity": "1.3.1",
67
- "viem": "2.19.8",
68
- "@latticexyz/schema-type": "2.2.4-main-784e5a98e679388ad6bc941cd1bc9b6486cf276d"
67
+ "viem": "2.21.6",
68
+ "@latticexyz/schema-type": "2.2.4-main-2f935cfd3fbc62f3c304e470751a26189523fcd2"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@types/debug": "^4.1.7",
@@ -1,2 +0,0 @@
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 g({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 x({client:e,address:r,blockTag:t="pending",broadcastChannelName:o,queueConcurrency:i=1}){let n={nonce:-1,noncePromise:null},s=null;typeof BroadcastChannel<"u"&&(o?Promise.resolve(o):g({client:e,address:r,blockTag:t})).then(p=>{s=new BroadcastChannel(p),s.addEventListener("message",M=>{let w=JSON.parse(M.data);y("got nonce from broadcast channel",w),n.nonce=w})});function c(){return n.nonce>=0}function d(){if(!c())throw new Error("call resetNonce before using getNonce");return n.nonce}function a(){if(!c())throw new Error("call resetNonce before using nextNonce");let f=n.nonce++;return s?.postMessage(JSON.stringify(n.nonce)),f}async function u(){n.noncePromise??=(async()=>{n.nonce=await B(e,k,"getTransactionCount")({address:r,blockTag:t}),n.noncePromise=null,s?.postMessage(JSON.stringify(n.nonce)),y("reset nonce to",n.nonce)})(),await n.noncePromise}function P(f){return f instanceof E&&f.walk(p=>p instanceof S||p instanceof I)!=null}let F=new q({concurrency:i});return{hasNonce:c,getNonce:d,nextNonce:a,resetNonce:u,shouldResetNonce:P,mempoolQueue:F}}var C=new Map;async function l({client:e,address:r,blockTag:t="pending",...o}){let i=await g({client:e,address:r,blockTag:t}),n=C.get(i)??x({client:e,address:r,blockTag:t,...o});return C.has(i)||C.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 T({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 R=new Map;async function h(e){let r=e.args?.chain?.id??e.client.chain?.id??await H(e.client,Q,"getChainId")({}),t=R.get(r);if(t)return t;let o=await T(e);return R.set(r,o),o}import{getAction as $}from"viem/utils";var N=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,s="pending",c=await l({client:t.publicClient??e,address:i.address,blockTag:s,queueConcurrency:t.queueConcurrency}),d=await h({client:t.publicClient??e,refreshInterval:1e4,args:{chain:n}});return c.mempoolQueue.add(()=>J(async()=>{let a=c.nextNonce(),u={blockTag:s,...r,nonce:a,...d.fees};return N("calling",u.functionName,"at",u.address,"with nonce",a),await $(e,D,"writeContract")(u)},{retries:3,onFailedAttempt:async a=>{if(N("failed, resetting nonce"),await c.resetNonce(),c.shouldResetNonce(a)){N("got nonce 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 b=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,s="pending",c=await l({client:t.publicClient??e,address:i.address,blockTag:s,queueConcurrency:t.queueConcurrency}),d=await h({client:t.publicClient??e,refreshInterval:1e4,args:{chain:n}});return await c.mempoolQueue.add(()=>_(async()=>{let a=c.nextNonce(),u={blockTag:s,...r,nonce:a,...d.fees};return b("sending tx to",r.to,"with nonce",a),await z(e,L,"sendTransaction")(u)},{retries:3,onFailedAttempt:async a=>{if(b("failed, resetting nonce"),await c.resetNonce(),c.shouldResetNonce(a)){b("got nonce error, retrying",a.message);return}throw a}}),{throwOnTimeout:!0})}export{g as a,x as b,l as c,Se as d,Je as e};
2
- //# sourceMappingURL=chunk-JQHDLHUT.js.map
@@ -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 = \"pending\",\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 = \"pending\",\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 blockTag = \"pending\";\n const nonceManager = await getNonceManager({\n client: opts.publicClient ?? client,\n address: account.address,\n blockTag,\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 blockTag,\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 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 blockTag = \"pending\";\n const nonceManager = await getNonceManager({\n client: opts.publicClient ?? client,\n address: account.address,\n blockTag,\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 blockTag,\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 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,O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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","blockTag","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_writeContract","error","viem_sendTransaction","pRetry","parseAccount","getAction","debug","sendTransaction","client","request","opts","rawAccount","account","parseAccount","chain","blockTag","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_sendTransaction","error"]}