@latticexyz/common 2.2.18-8d0ce55e964e646a1c804c401df01c4deb866f30 → 2.2.18-9fa07c8489f1fbf167d0db01cd9aaa645a29c8e2

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.
Files changed (67) hide show
  1. package/dist/actions.cjs +334 -0
  2. package/dist/actions.cjs.map +1 -0
  3. package/dist/actions.d.cts +27 -0
  4. package/dist/actions.js +39 -1
  5. package/dist/actions.js.map +1 -1
  6. package/dist/chains.cjs +106 -0
  7. package/dist/chains.cjs.map +1 -0
  8. package/dist/chains.d.cts +968 -0
  9. package/dist/chains.js +75 -1
  10. package/dist/chains.js.map +1 -1
  11. package/dist/chunk-D4GDXAMP.js +64 -0
  12. package/dist/{chunk-ZIUX7JCQ.js.map → chunk-D4GDXAMP.js.map} +1 -1
  13. package/dist/chunk-IYZZFDNO.js +16 -0
  14. package/dist/{chunk-ZV2KGJCD.js.map → chunk-IYZZFDNO.js.map} +1 -1
  15. package/dist/chunk-MF5NFUW7.js +12 -0
  16. package/dist/{chunk-QQCZY3XJ.js.map → chunk-MF5NFUW7.js.map} +1 -1
  17. package/dist/chunk-MK6UECU7.js +11 -0
  18. package/dist/{chunk-TCWGPC6G.js.map → chunk-MK6UECU7.js.map} +1 -1
  19. package/dist/chunk-MYWRXQQH.js +208 -0
  20. package/dist/{chunk-6FIKI2CG.js.map → chunk-MYWRXQQH.js.map} +1 -1
  21. package/dist/chunk-Z6SVAIZN.js +70 -0
  22. package/dist/{chunk-DPUUE7NM.js.map → chunk-Z6SVAIZN.js.map} +1 -1
  23. package/dist/codegen.cjs +889 -0
  24. package/dist/codegen.cjs.map +1 -0
  25. package/dist/codegen.d.cts +228 -0
  26. package/dist/codegen.js +706 -49
  27. package/dist/codegen.js.map +1 -1
  28. package/dist/errors.cjs +38 -0
  29. package/dist/errors.cjs.map +1 -0
  30. package/dist/errors.d.cts +5 -0
  31. package/dist/errors.js +6 -1
  32. package/dist/foundry.cjs +105 -0
  33. package/dist/foundry.cjs.map +1 -0
  34. package/dist/foundry.d.cts +69 -0
  35. package/dist/foundry.js +71 -2
  36. package/dist/foundry.js.map +1 -1
  37. package/dist/getContract-CA0EdVg6.d.cts +20 -0
  38. package/dist/index.cjs +597 -0
  39. package/dist/index.cjs.map +1 -0
  40. package/dist/index.d.cts +160 -0
  41. package/dist/index.js +233 -1
  42. package/dist/index.js.map +1 -1
  43. package/dist/internal.cjs +459 -0
  44. package/dist/internal.cjs.map +1 -0
  45. package/dist/internal.d.cts +36 -0
  46. package/dist/internal.js +205 -9
  47. package/dist/internal.js.map +1 -1
  48. package/dist/kms.cjs +204 -0
  49. package/dist/kms.cjs.map +1 -0
  50. package/dist/kms.d.cts +18 -0
  51. package/dist/kms.js +168 -1
  52. package/dist/kms.js.map +1 -1
  53. package/dist/type-utils.cjs +19 -0
  54. package/dist/type-utils.cjs.map +1 -0
  55. package/dist/type-utils.d.cts +19 -0
  56. package/dist/utils.cjs +174 -0
  57. package/dist/utils.cjs.map +1 -0
  58. package/dist/utils.d.cts +40 -0
  59. package/dist/utils.js +122 -1
  60. package/dist/utils.js.map +1 -1
  61. package/package.json +102 -12
  62. package/dist/chunk-6FIKI2CG.js +0 -2
  63. package/dist/chunk-DPUUE7NM.js +0 -2
  64. package/dist/chunk-QQCZY3XJ.js +0 -2
  65. package/dist/chunk-TCWGPC6G.js +0 -2
  66. package/dist/chunk-ZIUX7JCQ.js +0 -2
  67. package/dist/chunk-ZV2KGJCD.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/foundry/index.ts"],"sourcesContent":["import { execa, Options } from \"execa\";\n\nexport interface ForgeConfig {\n // project\n src: string;\n test: string;\n script: string;\n out: string;\n libs: string[];\n cache: boolean;\n cache_path: string;\n eth_rpc_url: string | null;\n\n // compiler\n remappings: string[];\n\n // all unspecified keys (this interface is far from comprehensive)\n [key: string]: unknown;\n}\n\n/**\n * Get forge config as a parsed json object.\n */\nexport async function getForgeConfig(profile?: string): Promise<ForgeConfig> {\n const { stdout } = await execa(\"forge\", [\"config\", \"--json\"], {\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env: { FOUNDRY_PROFILE: profile },\n });\n\n return JSON.parse(stdout) as ForgeConfig;\n}\n\n/**\n * Get the value of \"src\" from forge config.\n * The path to the contract sources relative to the root of the project.\n */\nexport async function getSrcDirectory(profile?: string): Promise<string> {\n return (await getForgeConfig(profile)).src;\n}\n\n/**\n * Get the value of \"script\" from forge config.\n * The path to the contract sources relative to the root of the project.\n */\nexport async function getScriptDirectory(profile?: string): Promise<string> {\n return (await getForgeConfig(profile)).script;\n}\n\n/**\n * Get the value of \"test\" from forge config.\n * The path to the test contract sources relative to the root of the project.\n */\nexport async function getTestDirectory(profile?: string): Promise<string> {\n return (await getForgeConfig(profile)).test;\n}\n\n/**\n * Get the value of \"out\" from forge config.\n * The path to put contract artifacts in, relative to the root of the project.\n */\nexport async function getOutDirectory(profile?: string): Promise<string> {\n return (await getForgeConfig(profile)).out;\n}\n\n/**\n * Get the value of \"eth_rpc_url\" from forge config, default to \"http://127.0.0.1:8545\"\n * @param profile The foundry profile to use\n * @returns The rpc url\n */\nexport async function getRpcUrl(profile?: string): Promise<string> {\n return (\n process.env.FOUNDRY_ETH_RPC_URL ||\n process.env.RPC_HTTP_URL ||\n process.env.RPC_URL ||\n (await getForgeConfig(profile)).eth_rpc_url ||\n \"http://127.0.0.1:8545\"\n );\n}\n\n/**\n * Execute a forge command\n * @param args The arguments to pass to forge\n * @param options { profile?: The foundry profile to use; silent?: If true, nothing will be logged to the console }\n */\nexport async function forge(\n args: string[],\n options?: { profile?: string; silent?: boolean; env?: NodeJS.ProcessEnv; cwd?: string },\n): Promise<void> {\n const execOptions = {\n env: { FOUNDRY_PROFILE: options?.profile, ...options?.env },\n stdout: \"inherit\",\n stderr: \"pipe\",\n cwd: options?.cwd,\n } satisfies Options;\n\n await (options?.silent ? execa(\"forge\", args, execOptions) : execLog(\"forge\", args, execOptions));\n}\n\n/**\n * Execute a cast command\n * @param args The arguments to pass to cast\n * @returns Stdout of the command\n */\nexport async function cast(args: string[], options?: { profile?: string }): Promise<string> {\n return execLog(\"cast\", args, {\n env: { FOUNDRY_PROFILE: options?.profile },\n });\n}\n\n/**\n * Start an anvil chain\n * @param args The arguments to pass to anvil\n * @returns Stdout of the command\n */\nexport async function anvil(args: string[]): Promise<string> {\n return execLog(\"anvil\", args);\n}\n\n/**\n * Executes the given command, returns the stdout, and logs the command to the console.\n * Throws an error if the command fails.\n * @param command The command to execute\n * @param args The arguments to pass to the command\n * @returns The stdout of the command\n */\nasync function execLog(command: string, args: string[], options?: Options): Promise<string> {\n const commandString = `${command} ${args.join(\" \")}`;\n try {\n console.log(`running \"${commandString}\"`);\n const { stdout } = await execa(command, args, {\n ...options,\n stdout: \"pipe\",\n stderr: \"pipe\",\n lines: false,\n encoding: \"utf8\",\n });\n return stdout;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n let errorMessage = error?.stderr || error?.message || \"\";\n errorMessage += `\\nError running \"${commandString}\"`;\n throw new Error(errorMessage);\n }\n}\n"],"mappings":"AAAA,OAAS,SAAAA,MAAsB,QAuB/B,eAAsBC,EAAeC,EAAwC,CAC3E,GAAM,CAAE,OAAAC,CAAO,EAAI,MAAMH,EAAM,QAAS,CAAC,SAAU,QAAQ,EAAG,CAC5D,MAAO,CAAC,UAAW,OAAQ,MAAM,EACjC,IAAK,CAAE,gBAAiBE,CAAQ,CAClC,CAAC,EAED,OAAO,KAAK,MAAMC,CAAM,CAC1B,CAMA,eAAsBC,EAAgBF,EAAmC,CACvE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,GACzC,CAMA,eAAsBG,EAAmBH,EAAmC,CAC1E,OAAQ,MAAMD,EAAeC,CAAO,GAAG,MACzC,CAMA,eAAsBI,EAAiBJ,EAAmC,CACxE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,IACzC,CAMA,eAAsBK,EAAgBL,EAAmC,CACvE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,GACzC,CAOA,eAAsBM,EAAUN,EAAmC,CACjE,OACE,QAAQ,IAAI,qBACZ,QAAQ,IAAI,cACZ,QAAQ,IAAI,UACX,MAAMD,EAAeC,CAAO,GAAG,aAChC,uBAEJ,CAOA,eAAsBO,EACpBC,EACAC,EACe,CACf,IAAMC,EAAc,CAClB,IAAK,CAAE,gBAAiBD,GAAS,QAAS,GAAGA,GAAS,GAAI,EAC1D,OAAQ,UACR,OAAQ,OACR,IAAKA,GAAS,GAChB,EAEA,MAAOA,GAAS,OAASX,EAAM,QAASU,EAAME,CAAW,EAAIC,EAAQ,QAASH,EAAME,CAAW,EACjG,CAOA,eAAsBE,EAAKJ,EAAgBC,EAAiD,CAC1F,OAAOE,EAAQ,OAAQH,EAAM,CAC3B,IAAK,CAAE,gBAAiBC,GAAS,OAAQ,CAC3C,CAAC,CACH,CAOA,eAAsBI,EAAML,EAAiC,CAC3D,OAAOG,EAAQ,QAASH,CAAI,CAC9B,CASA,eAAeG,EAAQG,EAAiBN,EAAgBC,EAAoC,CAC1F,IAAMM,EAAgB,GAAGD,CAAO,IAAIN,EAAK,KAAK,GAAG,CAAC,GAClD,GAAI,CACF,QAAQ,IAAI,YAAYO,CAAa,GAAG,EACxC,GAAM,CAAE,OAAAd,CAAO,EAAI,MAAMH,EAAMgB,EAASN,EAAM,CAC5C,GAAGC,EACH,OAAQ,OACR,OAAQ,OACR,MAAO,GACP,SAAU,MACZ,CAAC,EACD,OAAOR,CAET,OAASe,EAAY,CACnB,IAAIC,EAAeD,GAAO,QAAUA,GAAO,SAAW,GACtD,MAAAC,GAAgB;AAAA,iBAAoBF,CAAa,IAC3C,IAAI,MAAME,CAAY,CAC9B,CACF","names":["execa","getForgeConfig","profile","stdout","getSrcDirectory","getScriptDirectory","getTestDirectory","getOutDirectory","getRpcUrl","forge","args","options","execOptions","execLog","cast","anvil","command","commandString","error","errorMessage"]}
1
+ {"version":3,"sources":["../src/foundry/index.ts"],"sourcesContent":["import { execa, Options } from \"execa\";\n\nexport interface ForgeConfig {\n // project\n src: string;\n test: string;\n script: string;\n out: string;\n libs: string[];\n cache: boolean;\n cache_path: string;\n eth_rpc_url: string | null;\n\n // compiler\n remappings: string[];\n\n // all unspecified keys (this interface is far from comprehensive)\n [key: string]: unknown;\n}\n\n/**\n * Get forge config as a parsed json object.\n */\nexport async function getForgeConfig(profile?: string): Promise<ForgeConfig> {\n const { stdout } = await execa(\"forge\", [\"config\", \"--json\"], {\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env: { FOUNDRY_PROFILE: profile },\n });\n\n return JSON.parse(stdout) as ForgeConfig;\n}\n\n/**\n * Get the value of \"src\" from forge config.\n * The path to the contract sources relative to the root of the project.\n */\nexport async function getSrcDirectory(profile?: string): Promise<string> {\n return (await getForgeConfig(profile)).src;\n}\n\n/**\n * Get the value of \"script\" from forge config.\n * The path to the contract sources relative to the root of the project.\n */\nexport async function getScriptDirectory(profile?: string): Promise<string> {\n return (await getForgeConfig(profile)).script;\n}\n\n/**\n * Get the value of \"test\" from forge config.\n * The path to the test contract sources relative to the root of the project.\n */\nexport async function getTestDirectory(profile?: string): Promise<string> {\n return (await getForgeConfig(profile)).test;\n}\n\n/**\n * Get the value of \"out\" from forge config.\n * The path to put contract artifacts in, relative to the root of the project.\n */\nexport async function getOutDirectory(profile?: string): Promise<string> {\n return (await getForgeConfig(profile)).out;\n}\n\n/**\n * Get the value of \"eth_rpc_url\" from forge config, default to \"http://127.0.0.1:8545\"\n * @param profile The foundry profile to use\n * @returns The rpc url\n */\nexport async function getRpcUrl(profile?: string): Promise<string> {\n return (\n process.env.FOUNDRY_ETH_RPC_URL ||\n process.env.RPC_HTTP_URL ||\n process.env.RPC_URL ||\n (await getForgeConfig(profile)).eth_rpc_url ||\n \"http://127.0.0.1:8545\"\n );\n}\n\n/**\n * Execute a forge command\n * @param args The arguments to pass to forge\n * @param options { profile?: The foundry profile to use; silent?: If true, nothing will be logged to the console }\n */\nexport async function forge(\n args: string[],\n options?: { profile?: string; silent?: boolean; env?: NodeJS.ProcessEnv; cwd?: string },\n): Promise<void> {\n const execOptions = {\n env: { FOUNDRY_PROFILE: options?.profile, ...options?.env },\n stdout: \"inherit\",\n stderr: \"pipe\",\n cwd: options?.cwd,\n } satisfies Options;\n\n await (options?.silent ? execa(\"forge\", args, execOptions) : execLog(\"forge\", args, execOptions));\n}\n\n/**\n * Execute a cast command\n * @param args The arguments to pass to cast\n * @returns Stdout of the command\n */\nexport async function cast(args: string[], options?: { profile?: string }): Promise<string> {\n return execLog(\"cast\", args, {\n env: { FOUNDRY_PROFILE: options?.profile },\n });\n}\n\n/**\n * Start an anvil chain\n * @param args The arguments to pass to anvil\n * @returns Stdout of the command\n */\nexport async function anvil(args: string[]): Promise<string> {\n return execLog(\"anvil\", args);\n}\n\n/**\n * Executes the given command, returns the stdout, and logs the command to the console.\n * Throws an error if the command fails.\n * @param command The command to execute\n * @param args The arguments to pass to the command\n * @returns The stdout of the command\n */\nasync function execLog(command: string, args: string[], options?: Options): Promise<string> {\n const commandString = `${command} ${args.join(\" \")}`;\n try {\n console.log(`running \"${commandString}\"`);\n const { stdout } = await execa(command, args, {\n ...options,\n stdout: \"pipe\",\n stderr: \"pipe\",\n lines: false,\n encoding: \"utf8\",\n });\n return stdout;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n let errorMessage = error?.stderr || error?.message || \"\";\n errorMessage += `\\nError running \"${commandString}\"`;\n throw new Error(errorMessage);\n }\n}\n"],"mappings":";AAAA,SAAS,aAAsB;AAuB/B,eAAsB,eAAe,SAAwC;AAC3E,QAAM,EAAE,OAAO,IAAI,MAAM,MAAM,SAAS,CAAC,UAAU,QAAQ,GAAG;AAAA,IAC5D,OAAO,CAAC,WAAW,QAAQ,MAAM;AAAA,IACjC,KAAK,EAAE,iBAAiB,QAAQ;AAAA,EAClC,CAAC;AAED,SAAO,KAAK,MAAM,MAAM;AAC1B;AAMA,eAAsB,gBAAgB,SAAmC;AACvE,UAAQ,MAAM,eAAe,OAAO,GAAG;AACzC;AAMA,eAAsB,mBAAmB,SAAmC;AAC1E,UAAQ,MAAM,eAAe,OAAO,GAAG;AACzC;AAMA,eAAsB,iBAAiB,SAAmC;AACxE,UAAQ,MAAM,eAAe,OAAO,GAAG;AACzC;AAMA,eAAsB,gBAAgB,SAAmC;AACvE,UAAQ,MAAM,eAAe,OAAO,GAAG;AACzC;AAOA,eAAsB,UAAU,SAAmC;AACjE,SACE,QAAQ,IAAI,uBACZ,QAAQ,IAAI,gBACZ,QAAQ,IAAI,YACX,MAAM,eAAe,OAAO,GAAG,eAChC;AAEJ;AAOA,eAAsB,MACpB,MACA,SACe;AACf,QAAM,cAAc;AAAA,IAClB,KAAK,EAAE,iBAAiB,SAAS,SAAS,GAAG,SAAS,IAAI;AAAA,IAC1D,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,KAAK,SAAS;AAAA,EAChB;AAEA,SAAO,SAAS,SAAS,MAAM,SAAS,MAAM,WAAW,IAAI,QAAQ,SAAS,MAAM,WAAW;AACjG;AAOA,eAAsB,KAAK,MAAgB,SAAiD;AAC1F,SAAO,QAAQ,QAAQ,MAAM;AAAA,IAC3B,KAAK,EAAE,iBAAiB,SAAS,QAAQ;AAAA,EAC3C,CAAC;AACH;AAOA,eAAsB,MAAM,MAAiC;AAC3D,SAAO,QAAQ,SAAS,IAAI;AAC9B;AASA,eAAe,QAAQ,SAAiB,MAAgB,SAAoC;AAC1F,QAAM,gBAAgB,GAAG,OAAO,IAAI,KAAK,KAAK,GAAG,CAAC;AAClD,MAAI;AACF,YAAQ,IAAI,YAAY,aAAa,GAAG;AACxC,UAAM,EAAE,OAAO,IAAI,MAAM,MAAM,SAAS,MAAM;AAAA,MAC5C,GAAG;AAAA,MACH,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,UAAU;AAAA,IACZ,CAAC;AACD,WAAO;AAAA,EAET,SAAS,OAAY;AACnB,QAAI,eAAe,OAAO,UAAU,OAAO,WAAW;AACtD,oBAAgB;AAAA,iBAAoB,aAAa;AACjD,UAAM,IAAI,MAAM,YAAY;AAAA,EAC9B;AACF;","names":[]}
@@ -0,0 +1,20 @@
1
+ import { WriteContractParameters, Hex, Transport, Address, Abi, Chain, Account, PublicClient, WalletClient, GetContractParameters, GetContractReturnType } from 'viem';
2
+
3
+ type ContractWrite = {
4
+ id: string;
5
+ request: WriteContractParameters;
6
+ result: Promise<Hex>;
7
+ };
8
+ type GetContractOptions<TTransport extends Transport, TAddress extends Address, TAbi extends Abi, TChain extends Chain, TAccount extends Account, TPublicClient extends PublicClient<TTransport, TChain>, TWalletClient extends WalletClient<TTransport, TChain, TAccount>> = GetContractParameters<TTransport, TChain, TAccount, TAbi, {
9
+ public: TPublicClient;
10
+ wallet: TWalletClient;
11
+ }, TAddress> & {
12
+ onWrite?: (write: ContractWrite) => void;
13
+ };
14
+ /** @deprecated Use `walletClient.extend(transactionQueue()).extend(writeObserver({ onWrite }))` and viem's `getContract` instead. */
15
+ declare function getContract<TTransport extends Transport, TAddress extends Address, TAbi extends Abi, TChain extends Chain, TAccount extends Account, TPublicClient extends PublicClient<TTransport, TChain>, TWalletClient extends WalletClient<TTransport, TChain, TAccount>>({ abi, address, client: { public: publicClient, wallet: walletClient }, onWrite, }: GetContractOptions<TTransport, TAddress, TAbi, TChain, TAccount, TPublicClient, TWalletClient>): GetContractReturnType<TAbi, {
16
+ public: TPublicClient;
17
+ wallet: TWalletClient;
18
+ }, TAddress>;
19
+
20
+ export { type ContractWrite as C, type GetContractOptions as G, getContract as g };
package/dist/index.cjs ADDED
@@ -0,0 +1,597 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ LruMap: () => LruMap,
34
+ createBenchmark: () => createBenchmark,
35
+ createBurnerAccount: () => createBurnerAccount,
36
+ createContract: () => createContract,
37
+ createNonceManager: () => createNonceManager,
38
+ findCause: () => findCause,
39
+ getBurnerPrivateKey: () => getBurnerPrivateKey,
40
+ getContract: () => getContract,
41
+ getNonceManager: () => getNonceManager,
42
+ getNonceManagerId: () => getNonceManagerId,
43
+ hexToResource: () => hexToResource,
44
+ hexToResourceId: () => hexToResourceId,
45
+ isError: () => isError,
46
+ isOk: () => isOk,
47
+ logSort: () => logSort,
48
+ readHex: () => readHex,
49
+ resourceIdToHex: () => resourceIdToHex,
50
+ resourceToHex: () => resourceToHex,
51
+ resourceToLabel: () => resourceToLabel,
52
+ resourceTypeIds: () => resourceTypeIds,
53
+ resourceTypes: () => resourceTypes,
54
+ sendTransaction: () => sendTransaction,
55
+ spliceHex: () => spliceHex,
56
+ transportObserver: () => transportObserver,
57
+ unwrap: () => unwrap,
58
+ writeContract: () => writeContract
59
+ });
60
+ module.exports = __toCommonJS(src_exports);
61
+
62
+ // src/createBenchmark.ts
63
+ var import_debug = __toESM(require("debug"), 1);
64
+ var parentDebug = (0, import_debug.default)("mud:benchmark");
65
+ parentDebug.log = console.info.bind(console);
66
+ function createBenchmark(namespace) {
67
+ const debug6 = parentDebug.extend(namespace);
68
+ let lastStep = performance.now();
69
+ return (stepName) => {
70
+ const secondsSinceLastStep = (performance.now() - lastStep) / 1e3;
71
+ debug6("%s: +%ds", stepName, secondsSinceLastStep);
72
+ lastStep = performance.now();
73
+ };
74
+ }
75
+
76
+ // src/createBurnerAccount.ts
77
+ var import_accounts = require("viem/accounts");
78
+ function createBurnerAccount(privateKey) {
79
+ const account = (0, import_accounts.privateKeyToAccount)(privateKey);
80
+ return {
81
+ ...account
82
+ };
83
+ }
84
+
85
+ // src/debug.ts
86
+ var import_debug2 = __toESM(require("debug"), 1);
87
+ var debug = (0, import_debug2.default)("mud:common");
88
+ var error = (0, import_debug2.default)("mud:common");
89
+ debug.log = console.debug.bind(console);
90
+ error.log = console.error.bind(console);
91
+
92
+ // src/getNonceManagerId.ts
93
+ var import_viem = require("viem");
94
+ var import_actions = require("viem/actions");
95
+ var import_utils = require("viem/utils");
96
+ async function getNonceManagerId({
97
+ client,
98
+ address,
99
+ blockTag
100
+ }) {
101
+ const chainId = client.chain?.id ?? await (0, import_utils.getAction)(client, import_actions.getChainId, "getChainId")({});
102
+ return `mud:createNonceManager:${chainId}:${(0, import_viem.getAddress)(address)}:${blockTag}`;
103
+ }
104
+
105
+ // src/createNonceManager.ts
106
+ var import_actions2 = require("viem/actions");
107
+ var import_p_queue = __toESM(require("p-queue"), 1);
108
+ var import_utils2 = require("viem/utils");
109
+
110
+ // src/findCause.ts
111
+ function findCause(error2, fn) {
112
+ if (fn?.(error2)) return error2;
113
+ if (error2.cause instanceof Error) return findCause(error2.cause, fn);
114
+ return fn ? null : error2;
115
+ }
116
+
117
+ // src/createNonceManager.ts
118
+ var debug2 = debug.extend("createNonceManager");
119
+ function createNonceManager({
120
+ client,
121
+ address,
122
+ // TODO: rename to account?
123
+ blockTag = "latest",
124
+ broadcastChannelName,
125
+ queueConcurrency = 1
126
+ }) {
127
+ const ref = { nonce: -1, noncePromise: null };
128
+ let channel = null;
129
+ if (typeof BroadcastChannel !== "undefined") {
130
+ const channelName = broadcastChannelName ? Promise.resolve(broadcastChannelName) : getNonceManagerId({ client, address, blockTag });
131
+ channelName.then((name) => {
132
+ channel = new BroadcastChannel(name);
133
+ channel.addEventListener("message", (event) => {
134
+ const nonce = JSON.parse(event.data);
135
+ debug2("got nonce from broadcast channel", nonce);
136
+ ref.nonce = nonce;
137
+ });
138
+ });
139
+ }
140
+ function hasNonce() {
141
+ return ref.nonce >= 0;
142
+ }
143
+ function getNonce() {
144
+ if (!hasNonce()) throw new Error("call resetNonce before using getNonce");
145
+ return ref.nonce;
146
+ }
147
+ function nextNonce() {
148
+ if (!hasNonce()) throw new Error("call resetNonce before using nextNonce");
149
+ const nonce = ref.nonce++;
150
+ channel?.postMessage(JSON.stringify(ref.nonce));
151
+ return nonce;
152
+ }
153
+ async function resetNonce() {
154
+ ref.noncePromise ??= (async () => {
155
+ ref.nonce = await (0, import_utils2.getAction)(client, import_actions2.getTransactionCount, "getTransactionCount")({ address, blockTag });
156
+ ref.noncePromise = null;
157
+ channel?.postMessage(JSON.stringify(ref.nonce));
158
+ debug2("reset nonce to", ref.nonce);
159
+ })();
160
+ await ref.noncePromise;
161
+ }
162
+ function shouldResetNonce(error2) {
163
+ const nonceError = findCause(error2, ({ name }) => name === "NonceTooLowError" || name === "NonceTooHighError");
164
+ return nonceError != null;
165
+ }
166
+ const mempoolQueue = new import_p_queue.default({ concurrency: queueConcurrency });
167
+ return {
168
+ hasNonce,
169
+ getNonce,
170
+ nextNonce,
171
+ resetNonce,
172
+ shouldResetNonce,
173
+ mempoolQueue
174
+ };
175
+ }
176
+
177
+ // src/getBurnerPrivateKey.ts
178
+ var import_accounts2 = require("viem/accounts");
179
+ var import_viem2 = require("viem");
180
+ function assertPrivateKey(privateKey, cacheKey) {
181
+ if (!(0, import_viem2.isHex)(privateKey)) {
182
+ console.error("Private key found in cache is not valid hex", { privateKey, cacheKey });
183
+ throw new Error(`Private key found in cache (${cacheKey}) is not valid hex`);
184
+ }
185
+ (0, import_accounts2.privateKeyToAccount)(privateKey);
186
+ }
187
+ function getBurnerPrivateKey(cacheKey = "mud:burnerWallet") {
188
+ const cachedPrivateKey = localStorage.getItem(cacheKey);
189
+ if (cachedPrivateKey != null) {
190
+ assertPrivateKey(cachedPrivateKey, cacheKey);
191
+ return cachedPrivateKey;
192
+ }
193
+ const privateKey = (0, import_accounts2.generatePrivateKey)();
194
+ console.log("New burner wallet created:", (0, import_accounts2.privateKeyToAccount)(privateKey));
195
+ localStorage.setItem(cacheKey, privateKey);
196
+ return privateKey;
197
+ }
198
+
199
+ // src/getContract.ts
200
+ var import_viem3 = require("viem");
201
+
202
+ // src/writeContract.ts
203
+ var import_actions5 = require("viem/actions");
204
+ var import_p_retry = __toESM(require("p-retry"), 1);
205
+
206
+ // src/getNonceManager.ts
207
+ var nonceManagers = /* @__PURE__ */ new Map();
208
+ async function getNonceManager({
209
+ client,
210
+ address,
211
+ // TODO: rename to account?
212
+ blockTag = "latest",
213
+ ...opts
214
+ }) {
215
+ const id = await getNonceManagerId({ client, address, blockTag });
216
+ const nonceManager = nonceManagers.get(id) ?? createNonceManager({ client, address, blockTag, ...opts });
217
+ if (!nonceManagers.has(id)) {
218
+ nonceManagers.set(id, nonceManager);
219
+ }
220
+ if (!nonceManager.hasNonce()) {
221
+ await nonceManager.resetNonce();
222
+ }
223
+ return nonceManager;
224
+ }
225
+
226
+ // src/writeContract.ts
227
+ var import_accounts3 = require("viem/accounts");
228
+
229
+ // src/getFeeRef.ts
230
+ var import_actions4 = require("viem/actions");
231
+
232
+ // src/createFeeRef.ts
233
+ var import_actions3 = require("viem/actions");
234
+ var import_utils3 = require("viem/utils");
235
+ async function createFeeRef({ client, args, refreshInterval }) {
236
+ const feeRef = { fees: {}, lastUpdatedTimestamp: 0 };
237
+ async function updateFees() {
238
+ const fees = await (0, import_utils3.getAction)(client, import_actions3.estimateFeesPerGas, "estimateFeesPerGas")(args);
239
+ feeRef.fees = fees;
240
+ feeRef.lastUpdatedTimestamp = Date.now();
241
+ }
242
+ setInterval(updateFees, refreshInterval);
243
+ await updateFees();
244
+ return feeRef;
245
+ }
246
+
247
+ // src/getFeeRef.ts
248
+ var import_utils4 = require("viem/utils");
249
+ var feeRefs = /* @__PURE__ */ new Map();
250
+ async function getFeeRef(opts) {
251
+ const chainId = opts.args?.chain?.id ?? opts.client.chain?.id ?? await (0, import_utils4.getAction)(opts.client, import_actions4.getChainId, "getChainId")({});
252
+ const existingFeeRef = feeRefs.get(chainId);
253
+ if (existingFeeRef) {
254
+ return existingFeeRef;
255
+ }
256
+ const feeRef = await createFeeRef(opts);
257
+ feeRefs.set(chainId, feeRef);
258
+ return feeRef;
259
+ }
260
+
261
+ // src/writeContract.ts
262
+ var import_utils5 = require("viem/utils");
263
+ var debug3 = debug.extend("writeContract");
264
+ async function writeContract(client, request, opts = {}) {
265
+ const rawAccount = request.account ?? client.account;
266
+ if (!rawAccount) {
267
+ throw new Error("No account provided");
268
+ }
269
+ const account = (0, import_accounts3.parseAccount)(rawAccount);
270
+ const chain = client.chain;
271
+ const nonceManager = await getNonceManager({
272
+ client: opts.publicClient ?? client,
273
+ address: account.address,
274
+ queueConcurrency: opts.queueConcurrency
275
+ });
276
+ const feeRef = await getFeeRef({
277
+ client: opts.publicClient ?? client,
278
+ refreshInterval: 1e4,
279
+ args: { chain }
280
+ });
281
+ return nonceManager.mempoolQueue.add(
282
+ () => (0, import_p_retry.default)(
283
+ async () => {
284
+ const nonce = nonceManager.nextNonce();
285
+ const params = {
286
+ // viem_writeContract internally estimates gas, which we want to happen on the pending block
287
+ blockTag: "pending",
288
+ ...feeRef.fees,
289
+ ...request,
290
+ nonce
291
+ };
292
+ debug3("calling", params.functionName, "at", params.address, "with nonce", nonce);
293
+ return await (0, import_utils5.getAction)(client, import_actions5.writeContract, "writeContract")(params);
294
+ },
295
+ {
296
+ retries: 3,
297
+ onFailedAttempt: async (error2) => {
298
+ debug3("failed, resetting nonce");
299
+ await nonceManager.resetNonce();
300
+ if (nonceManager.shouldResetNonce(error2)) {
301
+ debug3("got nonce error, retrying", error2.message);
302
+ return;
303
+ }
304
+ if (String(error2).includes("transaction underpriced")) {
305
+ debug3("got transaction underpriced error, retrying", error2.message);
306
+ return;
307
+ }
308
+ throw error2;
309
+ }
310
+ }
311
+ ),
312
+ { throwOnTimeout: true }
313
+ );
314
+ }
315
+
316
+ // src/getContract.ts
317
+ function getFunctionParameters(values) {
318
+ const hasArgs = values.length && Array.isArray(values[0]);
319
+ const args = hasArgs ? values[0] : [];
320
+ const options = (hasArgs ? values[1] : values[0]) ?? {};
321
+ return { args, options };
322
+ }
323
+ function getContract({
324
+ abi,
325
+ address,
326
+ client: { public: publicClient, wallet: walletClient },
327
+ onWrite
328
+ }) {
329
+ const contract = (0, import_viem3.getContract)({
330
+ abi,
331
+ address,
332
+ client: {
333
+ public: publicClient,
334
+ wallet: walletClient
335
+ }
336
+ });
337
+ if (contract.write) {
338
+ let nextWriteId = 0;
339
+ contract.write = new Proxy(
340
+ {},
341
+ {
342
+ get(_, functionName) {
343
+ return (...parameters) => {
344
+ const { args, options } = getFunctionParameters(parameters);
345
+ const request = {
346
+ abi,
347
+ address,
348
+ functionName,
349
+ args,
350
+ ...options,
351
+ onWrite
352
+ };
353
+ const result = writeContract(walletClient, request, { publicClient });
354
+ const id = `${walletClient.chain.id}:${walletClient.account.address}:${nextWriteId++}`;
355
+ onWrite?.({
356
+ id,
357
+ request,
358
+ result
359
+ });
360
+ return result;
361
+ };
362
+ }
363
+ }
364
+ );
365
+ }
366
+ return contract;
367
+ }
368
+
369
+ // src/hexToResource.ts
370
+ var import_viem5 = require("viem");
371
+
372
+ // src/resourceTypes.ts
373
+ var resourceTypes = ["table", "offchainTable", "namespace", "system"];
374
+
375
+ // src/resourceToHex.ts
376
+ var import_viem4 = require("viem");
377
+ var resourceTypeIds = {
378
+ // keep these in sync with storeResourceTypes.sol
379
+ table: "tb",
380
+ offchainTable: "ot",
381
+ // keep these in sync with worldResourceTypes.sol
382
+ namespace: "ns",
383
+ system: "sy"
384
+ };
385
+ function resourceToHex(resource) {
386
+ const typeId = resourceTypeIds[resource.type];
387
+ if (resource.namespace.length > 14) {
388
+ throw new Error(`Namespaces must fit into \`bytes14\`, but "${resource.namespace}" is too long.`);
389
+ }
390
+ return (0, import_viem4.concatHex)([
391
+ (0, import_viem4.stringToHex)(typeId, { size: 2 }),
392
+ (0, import_viem4.stringToHex)(resource.namespace, { size: 14 }),
393
+ (0, import_viem4.stringToHex)(resource.name.slice(0, 16), { size: 16 })
394
+ ]);
395
+ }
396
+
397
+ // src/resourceToLabel.ts
398
+ var rootNamespace = "";
399
+ function resourceToLabel({
400
+ namespace,
401
+ name
402
+ }) {
403
+ return namespace === rootNamespace ? name : `${namespace}__${name}`;
404
+ }
405
+
406
+ // src/hexToResource.ts
407
+ var resourceTypeIdToType = Object.fromEntries(
408
+ Object.entries(resourceTypeIds).map(([key, value]) => [value, key])
409
+ );
410
+ function getResourceType(resourceTypeId) {
411
+ const type = resourceTypeIdToType[resourceTypeId];
412
+ if (resourceTypes.includes(type)) {
413
+ return type;
414
+ }
415
+ }
416
+ function hexToResource(hex) {
417
+ const resourceTypeId = (0, import_viem5.hexToString)((0, import_viem5.sliceHex)(hex, 0, 2)).replace(/\0+$/, "");
418
+ const type = getResourceType(resourceTypeId);
419
+ const namespace = (0, import_viem5.hexToString)((0, import_viem5.sliceHex)(hex, 2, 16)).replace(/\0+$/, "");
420
+ const name = (0, import_viem5.hexToString)((0, import_viem5.sliceHex)(hex, 16, 32)).replace(/\0+$/, "");
421
+ if (!type) {
422
+ throw new Error(`Unknown type (${resourceTypeId}) for resource (${resourceToLabel({ namespace, name })})`);
423
+ }
424
+ return { resourceId: hex, type, namespace, name };
425
+ }
426
+
427
+ // src/logSort.ts
428
+ function logSort(a, b) {
429
+ if (a.blockNumber === b.blockNumber) {
430
+ if (a.logIndex === b.logIndex) return 0;
431
+ if (a.logIndex == null) return 1;
432
+ if (b.logIndex == null) return -1;
433
+ return a.logIndex - b.logIndex;
434
+ }
435
+ if (a.blockNumber == null) return 1;
436
+ if (b.blockNumber == null) return -1;
437
+ if (a.blockNumber > b.blockNumber) return 1;
438
+ if (a.blockNumber < b.blockNumber) return -1;
439
+ return 0;
440
+ }
441
+
442
+ // src/LruMap.ts
443
+ var LruMap = class extends Map {
444
+ constructor(size) {
445
+ super();
446
+ this.maxSize = size;
447
+ }
448
+ set(key, value) {
449
+ super.set(key, value);
450
+ if (this.maxSize && this.size > this.maxSize) {
451
+ this.delete(this.keys().next().value);
452
+ }
453
+ return this;
454
+ }
455
+ };
456
+
457
+ // src/readHex.ts
458
+ function readHex(data, start, end) {
459
+ return `0x${data.replace(/^0x/, "").slice(start * 2, end != null ? end * 2 : void 0).padEnd(((end ?? start) - start) * 2, "0")}`;
460
+ }
461
+
462
+ // src/result.ts
463
+ function isOk(result) {
464
+ return "ok" in result;
465
+ }
466
+ function isError(result) {
467
+ return "error" in result;
468
+ }
469
+ function unwrap(result) {
470
+ if (isError(result)) {
471
+ throw result.error;
472
+ }
473
+ return result.ok;
474
+ }
475
+
476
+ // src/sendTransaction.ts
477
+ var import_actions6 = require("viem/actions");
478
+ var import_p_retry2 = __toESM(require("p-retry"), 1);
479
+ var import_accounts4 = require("viem/accounts");
480
+ var import_utils6 = require("viem/utils");
481
+ var debug4 = debug.extend("sendTransaction");
482
+ async function sendTransaction(client, request, opts = {}) {
483
+ const rawAccount = request.account ?? client.account;
484
+ if (!rawAccount) {
485
+ throw new Error("No account provided");
486
+ }
487
+ const account = (0, import_accounts4.parseAccount)(rawAccount);
488
+ const chain = client.chain;
489
+ const nonceManager = await getNonceManager({
490
+ client: opts.publicClient ?? client,
491
+ address: account.address,
492
+ queueConcurrency: opts.queueConcurrency
493
+ });
494
+ const feeRef = await getFeeRef({
495
+ client: opts.publicClient ?? client,
496
+ refreshInterval: 1e4,
497
+ args: { chain }
498
+ });
499
+ return await nonceManager.mempoolQueue.add(
500
+ () => (0, import_p_retry2.default)(
501
+ async () => {
502
+ const nonce = nonceManager.nextNonce();
503
+ const params = {
504
+ // viem_sendTransaction internally estimates gas, which we want to happen on the pending block
505
+ blockTag: "pending",
506
+ ...feeRef.fees,
507
+ ...request,
508
+ nonce
509
+ };
510
+ debug4("sending tx to", request.to, "with nonce", nonce);
511
+ return await (0, import_utils6.getAction)(client, import_actions6.sendTransaction, "sendTransaction")(params);
512
+ },
513
+ {
514
+ retries: 3,
515
+ onFailedAttempt: async (error2) => {
516
+ debug4("failed, resetting nonce");
517
+ await nonceManager.resetNonce();
518
+ if (nonceManager.shouldResetNonce(error2)) {
519
+ debug4("got nonce error, retrying", error2.message);
520
+ return;
521
+ }
522
+ if (String(error2).includes("transaction underpriced")) {
523
+ debug4("got transaction underpriced error, retrying", error2.message);
524
+ return;
525
+ }
526
+ throw error2;
527
+ }
528
+ }
529
+ ),
530
+ { throwOnTimeout: true }
531
+ );
532
+ }
533
+
534
+ // src/spliceHex.ts
535
+ var import_viem6 = require("viem");
536
+ function spliceHex(data, start, deleteCount = 0, newData = "0x") {
537
+ return (0, import_viem6.concatHex)([readHex(data, 0, start), newData, readHex(data, start + deleteCount)]);
538
+ }
539
+
540
+ // src/transportObserver.ts
541
+ var import_viem7 = require("viem");
542
+ var debug5 = debug.extend("transportObserver");
543
+ function transportObserver(transport) {
544
+ return (opts) => {
545
+ const result = transport(opts);
546
+ const request = async (req) => {
547
+ if (req.method === "eth_sendRawTransaction" && req.params instanceof Array) {
548
+ const txs = req.params.map((data) => (0, import_viem7.keccak256)(data));
549
+ debug5("saw txs", txs);
550
+ }
551
+ return result.request(req);
552
+ };
553
+ return {
554
+ ...result,
555
+ request
556
+ };
557
+ };
558
+ }
559
+
560
+ // src/deprecated/createContract.ts
561
+ var createContract = getContract;
562
+
563
+ // src/deprecated/resourceIdToHex.ts
564
+ var resourceIdToHex = resourceToHex;
565
+
566
+ // src/deprecated/hexToResourceId.ts
567
+ var hexToResourceId = hexToResource;
568
+ // Annotate the CommonJS export names for ESM import in node:
569
+ 0 && (module.exports = {
570
+ LruMap,
571
+ createBenchmark,
572
+ createBurnerAccount,
573
+ createContract,
574
+ createNonceManager,
575
+ findCause,
576
+ getBurnerPrivateKey,
577
+ getContract,
578
+ getNonceManager,
579
+ getNonceManagerId,
580
+ hexToResource,
581
+ hexToResourceId,
582
+ isError,
583
+ isOk,
584
+ logSort,
585
+ readHex,
586
+ resourceIdToHex,
587
+ resourceToHex,
588
+ resourceToLabel,
589
+ resourceTypeIds,
590
+ resourceTypes,
591
+ sendTransaction,
592
+ spliceHex,
593
+ transportObserver,
594
+ unwrap,
595
+ writeContract
596
+ });
597
+ //# sourceMappingURL=index.cjs.map