@latticexyz/common 2.2.15 → 2.2.16-59389b1e37bc84664972231989ce7fdc739cce42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/actions.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Chain, Client, Transport, Account, WalletActions } from 'viem';
2
- import { C as ContractWrite } from './getContract-93922960.js';
2
+ import { C as ContractWrite } from './getContract-CA0EdVg6.js';
3
3
 
4
4
  type TransactionQueueOptions<chain extends Chain | undefined> = {
5
5
  /**
@@ -24,4 +24,4 @@ type WriteObserverParameters = {
24
24
  };
25
25
  declare function writeObserver<TChain extends Chain, TAccount extends Account>({ onWrite, }: WriteObserverParameters): (client: Client<Transport, TChain, TAccount>) => Pick<WalletActions<TChain, TAccount>, "writeContract">;
26
26
 
27
- export { TransactionQueueOptions, transactionQueue, writeObserver };
27
+ export { type TransactionQueueOptions, transactionQueue, writeObserver };
package/dist/actions.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as o}from"./chunk-WSHEKFYD.js";import{e as a}from"./chunk-RCAJ6T6T.js";import"./chunk-TCWGPC6G.js";function d(n={}){return e=>({writeContract:t=>o(e,t,n),sendTransaction:t=>a(e,t,n)})}import{getAction as s}from"viem/utils";import{writeContract as u}from"viem/actions";function f({onWrite:n}){let e=0;return t=>({writeContract:r=>{let i=s(t,u,"writeContract")(r),c=`${t.chain.id}:${t.account.address}:${e++}`;return n({id:c,request:r,result:i}),i}})}export{d as transactionQueue,f as writeObserver};
1
+ import{a as o}from"./chunk-Q7HNDKVJ.js";import{e as a}from"./chunk-GUEDVXKC.js";import"./chunk-TCWGPC6G.js";function d(n={}){return e=>({writeContract:t=>o(e,t,n),sendTransaction:t=>a(e,t,n)})}import{getAction as s}from"viem/utils";import{writeContract as u}from"viem/actions";function f({onWrite:n}){let e=0;return t=>({writeContract:r=>{let i=s(t,u,"writeContract")(r),c=`${t.chain.id}:${t.account.address}:${e++}`;return n({id:c,request:r,result:i}),i}})}export{d as transactionQueue,f as writeObserver};
2
2
  //# sourceMappingURL=actions.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/actions/transactionQueue.ts","../src/actions/writeObserver.ts"],"sourcesContent":["import type { Transport, Chain, Account, WalletActions, Client } from \"viem\";\nimport { writeContract as mud_writeContract } from \"../writeContract\";\nimport { sendTransaction as mud_sendTransaction } from \"../sendTransaction\";\n\nexport type TransactionQueueOptions<chain extends Chain | undefined> = {\n /**\n * `publicClient` can be provided to be used in place of the extended viem client for making public action calls\n * (`getChainId`, `getTransactionCount`, `simulateContract`, `call`). This helps in cases where the extended\n * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),\n * where the transport is the bundler, not an RPC.\n */\n publicClient?: Client<Transport, chain>;\n /**\n * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered\n * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions\n * arriving out of order, but this may be an acceptable trade-off for some applications that can safely retry.\n * @default 1\n */\n queueConcurrency?: number;\n};\n\nexport function transactionQueue<chain extends Chain | undefined>(\n opts: TransactionQueueOptions<chain> = {},\n): <transport extends Transport, account extends Account | undefined = Account | undefined>(\n client: Client<transport, chain, account>,\n) => Pick<WalletActions<chain, account>, \"writeContract\" | \"sendTransaction\"> {\n return (client) => ({\n // Applies to: `client.writeContract`, `getContract(client, ...).write`\n writeContract: (args) => mud_writeContract(client, args, opts),\n // Applies to: `client.sendTransaction`\n sendTransaction: (args) => mud_sendTransaction(client, args, opts),\n });\n}\n","import type {\n WriteContractParameters,\n Transport,\n Chain,\n Account,\n WalletActions,\n WriteContractReturnType,\n Client,\n} from \"viem\";\nimport { getAction } from \"viem/utils\";\nimport { writeContract } from \"viem/actions\";\nimport { type ContractWrite } from \"../getContract\";\n\ntype WriteObserverParameters = { onWrite: (write: ContractWrite) => void };\n\nexport function writeObserver<TChain extends Chain, TAccount extends Account>({\n onWrite,\n}: WriteObserverParameters): (\n client: Client<Transport, TChain, TAccount>,\n) => Pick<WalletActions<TChain, TAccount>, \"writeContract\"> {\n let nextWriteId = 0;\n\n return (client) => ({\n // Applies to: `client.writeContract`, `getContract(client, ...).write`\n writeContract: (args): Promise<WriteContractReturnType> => {\n const result = getAction(client, writeContract, \"writeContract\")(args);\n\n const id = `${client.chain.id}:${client.account.address}:${nextWriteId++}`;\n onWrite({ id, request: args as WriteContractParameters, result });\n\n return result;\n },\n });\n}\n"],"mappings":"4GAqBO,SAASA,EACdC,EAAuC,CAAC,EAGoC,CAC5E,OAAQC,IAAY,CAElB,cAAgBC,GAASC,EAAkBF,EAAQC,EAAMF,CAAI,EAE7D,gBAAkBE,GAASE,EAAoBH,EAAQC,EAAMF,CAAI,CACnE,EACF,CCvBA,OAAS,aAAAK,MAAiB,aAC1B,OAAS,iBAAAC,MAAqB,eAKvB,SAASC,EAA8D,CAC5E,QAAAC,CACF,EAE4D,CAC1D,IAAIC,EAAc,EAElB,OAAQC,IAAY,CAElB,cAAgBC,GAA2C,CACzD,IAAMC,EAASP,EAAUK,EAAQJ,EAAe,eAAe,EAAEK,CAAI,EAE/DE,EAAK,GAAGH,EAAO,MAAM,MAAMA,EAAO,QAAQ,WAAWD,MAC3D,OAAAD,EAAQ,CAAE,GAAAK,EAAI,QAASF,EAAiC,OAAAC,CAAO,CAAC,EAEzDA,CACT,CACF,EACF","names":["transactionQueue","opts","client","args","writeContract","sendTransaction","getAction","writeContract","writeObserver","onWrite","nextWriteId","client","args","result","id"]}
1
+ {"version":3,"sources":["../src/actions/transactionQueue.ts","../src/actions/writeObserver.ts"],"sourcesContent":["import type { Transport, Chain, Account, WalletActions, Client } from \"viem\";\nimport { writeContract as mud_writeContract } from \"../writeContract\";\nimport { sendTransaction as mud_sendTransaction } from \"../sendTransaction\";\n\nexport type TransactionQueueOptions<chain extends Chain | undefined> = {\n /**\n * `publicClient` can be provided to be used in place of the extended viem client for making public action calls\n * (`getChainId`, `getTransactionCount`, `simulateContract`, `call`). This helps in cases where the extended\n * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),\n * where the transport is the bundler, not an RPC.\n */\n publicClient?: Client<Transport, chain>;\n /**\n * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered\n * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions\n * arriving out of order, but this may be an acceptable trade-off for some applications that can safely retry.\n * @default 1\n */\n queueConcurrency?: number;\n};\n\nexport function transactionQueue<chain extends Chain | undefined>(\n opts: TransactionQueueOptions<chain> = {},\n): <transport extends Transport, account extends Account | undefined = Account | undefined>(\n client: Client<transport, chain, account>,\n) => Pick<WalletActions<chain, account>, \"writeContract\" | \"sendTransaction\"> {\n return (client) => ({\n // Applies to: `client.writeContract`, `getContract(client, ...).write`\n writeContract: (args) => mud_writeContract(client, args, opts),\n // Applies to: `client.sendTransaction`\n sendTransaction: (args) => mud_sendTransaction(client, args, opts),\n });\n}\n","import type {\n WriteContractParameters,\n Transport,\n Chain,\n Account,\n WalletActions,\n WriteContractReturnType,\n Client,\n} from \"viem\";\nimport { getAction } from \"viem/utils\";\nimport { writeContract } from \"viem/actions\";\nimport { type ContractWrite } from \"../getContract\";\n\ntype WriteObserverParameters = { onWrite: (write: ContractWrite) => void };\n\nexport function writeObserver<TChain extends Chain, TAccount extends Account>({\n onWrite,\n}: WriteObserverParameters): (\n client: Client<Transport, TChain, TAccount>,\n) => Pick<WalletActions<TChain, TAccount>, \"writeContract\"> {\n let nextWriteId = 0;\n\n return (client) => ({\n // Applies to: `client.writeContract`, `getContract(client, ...).write`\n writeContract: (args): Promise<WriteContractReturnType> => {\n const result = getAction(client, writeContract, \"writeContract\")(args);\n\n const id = `${client.chain.id}:${client.account.address}:${nextWriteId++}`;\n onWrite({ id, request: args as WriteContractParameters, result });\n\n return result;\n },\n });\n}\n"],"mappings":"4GAqBO,SAASA,EACdC,EAAuC,CAAC,EAGoC,CAC5E,OAAQC,IAAY,CAElB,cAAgBC,GAASC,EAAkBF,EAAQC,EAAMF,CAAI,EAE7D,gBAAkBE,GAASE,EAAoBH,EAAQC,EAAMF,CAAI,CACnE,EACF,CCvBA,OAAS,aAAAK,MAAiB,aAC1B,OAAS,iBAAAC,MAAqB,eAKvB,SAASC,EAA8D,CAC5E,QAAAC,CACF,EAE4D,CAC1D,IAAIC,EAAc,EAElB,OAAQC,IAAY,CAElB,cAAgBC,GAA2C,CACzD,IAAMC,EAASP,EAAUK,EAAQJ,EAAe,eAAe,EAAEK,CAAI,EAE/DE,EAAK,GAAGH,EAAO,MAAM,EAAE,IAAIA,EAAO,QAAQ,OAAO,IAAID,GAAa,GACxE,OAAAD,EAAQ,CAAE,GAAAK,EAAI,QAASF,EAAiC,OAAAC,CAAO,CAAC,EAEzDA,CACT,CACF,EACF","names":["transactionQueue","opts","client","args","writeContract","sendTransaction","getAction","writeContract","writeObserver","onWrite","nextWriteId","client","args","result","id"]}
package/dist/chains.d.ts CHANGED
@@ -961,4 +961,4 @@ declare const rhodolite: {
961
961
  };
962
962
  };
963
963
 
964
- export { MUDChain, garnet, mudFoundry, redstone, rhodolite };
964
+ export { type MUDChain, garnet, mudFoundry, redstone, rhodolite };
@@ -1,2 +1,2 @@
1
1
  import{a as d}from"./chunk-TCWGPC6G.js";import{getAddress as F}from"viem";import{getChainId as O}from"viem/actions";import{getAction as v}from"viem/utils";async function f({client:e,address:t,blockTag:o}){return`mud:createNonceManager:${e.chain?.id??await v(e,O,"getChainId")({})}:${F(t)}:${o}`}import{BaseError as E,NonceTooHighError as I,NonceTooLowError as S}from"viem";import{getTransactionCount as A}from"viem/actions";import k from"p-queue";import{getAction as B}from"viem/utils";var N=d.extend("createNonceManager");function C({client:e,address:t,blockTag:o="latest",broadcastChannelName:r,queueConcurrency:a=1}){let n={nonce:-1,noncePromise:null},i=null;typeof BroadcastChannel<"u"&&(r?Promise.resolve(r):f({client:e,address:t,blockTag:o})).then(m=>{i=new BroadcastChannel(m),i.addEventListener("message",M=>{let h=JSON.parse(M.data);N("got nonce from broadcast channel",h),n.nonce=h})});function s(){return n.nonce>=0}function c(){if(!s())throw new Error("call resetNonce before using getNonce");return n.nonce}function p(){if(!s())throw new Error("call resetNonce before using nextNonce");let u=n.nonce++;return i?.postMessage(JSON.stringify(n.nonce)),u}async function y(){n.noncePromise??=(async()=>{n.nonce=await B(e,A,"getTransactionCount")({address:t,blockTag:o}),n.noncePromise=null,i?.postMessage(JSON.stringify(n.nonce)),N("reset nonce to",n.nonce)})(),await n.noncePromise}function P(u){return u instanceof E&&u.walk(m=>m instanceof S||m instanceof I)!=null}let b=new k({concurrency:a});return{hasNonce:s,getNonce:c,nextNonce:p,resetNonce:y,shouldResetNonce:P,mempoolQueue:b}}var l=new Map;async function R({client:e,address:t,blockTag:o="latest",...r}){let a=await f({client:e,address:t,blockTag:o}),n=l.get(a)??C({client:e,address:t,blockTag:o,...r});return l.has(a)||l.set(a,n),n.hasNonce()||await n.resetNonce(),n}import{sendTransaction as D}from"viem/actions";import J from"p-retry";import{parseAccount as U}from"viem/accounts";import{getChainId as H}from"viem/actions";import{estimateFeesPerGas as q}from"viem/actions";import{getAction as G}from"viem/utils";async function T({client:e,args:t,refreshInterval:o}){let r={fees:{},lastUpdatedTimestamp:0};async function a(){let n=await G(e,q,"estimateFeesPerGas")(t);r.fees=n,r.lastUpdatedTimestamp=Date.now()}return setInterval(a,o),await a(),r}import{getAction as Q}from"viem/utils";var w=new Map;async function x(e){let t=e.args?.chain?.id??e.client.chain?.id??await Q(e.client,H,"getChainId")({}),o=w.get(t);if(o)return o;let r=await T(e);return w.set(t,r),r}import{getAction as $}from"viem/utils";var g=d.extend("sendTransaction");async function Oe(e,t,o={}){let r=t.account??e.account;if(!r)throw new Error("No account provided");let a=U(r),n=e.chain,i=await R({client:o.publicClient??e,address:a.address,queueConcurrency:o.queueConcurrency}),s=await x({client:o.publicClient??e,refreshInterval:1e4,args:{chain:n}});return await i.mempoolQueue.add(()=>J(async()=>{let c=i.nextNonce(),p={blockTag:"pending",...s.fees,...t,nonce:c};return g("sending tx to",t.to,"with nonce",c),await $(e,D,"sendTransaction")(p)},{retries:3,onFailedAttempt:async c=>{if(g("failed, resetting nonce"),await i.resetNonce(),i.shouldResetNonce(c)){g("got nonce error, retrying",c.message);return}if(String(c).includes("transaction underpriced")){g("got transaction underpriced error, retrying",c.message);return}throw c}}),{throwOnTimeout:!0})}export{f as a,C as b,R as c,x as d,Oe as e};
2
- //# sourceMappingURL=chunk-RCAJ6T6T.js.map
2
+ //# sourceMappingURL=chunk-GUEDVXKC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/getNonceManagerId.ts","../src/createNonceManager.ts","../src/getNonceManager.ts","../src/sendTransaction.ts","../src/getFeeRef.ts","../src/createFeeRef.ts"],"sourcesContent":["import { BlockTag, Client, Hex, getAddress } from \"viem\";\nimport { getChainId } from \"viem/actions\";\nimport { getAction } from \"viem/utils\";\n\nexport async function getNonceManagerId({\n client,\n address,\n blockTag,\n}: {\n client: Client;\n address: Hex;\n blockTag: BlockTag;\n}): Promise<string> {\n // TODO: improve this so we don't have to call getChainId every time\n const chainId = client.chain?.id ?? (await getAction(client, getChainId, \"getChainId\")({}));\n return `mud:createNonceManager:${chainId}:${getAddress(address)}:${blockTag}`;\n}\n","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 Account,\n Chain,\n Client,\n SendTransactionParameters,\n Transport,\n SendTransactionReturnType,\n SendTransactionRequest,\n} from \"viem\";\nimport { sendTransaction as viem_sendTransaction } from \"viem/actions\";\nimport pRetry from \"p-retry\";\nimport { debug as parentDebug } from \"./debug\";\nimport { getNonceManager } from \"./getNonceManager\";\nimport { parseAccount } from \"viem/accounts\";\nimport { getFeeRef } from \"./getFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst debug = parentDebug.extend(\"sendTransaction\");\n\nexport type SendTransactionExtraOptions<chain extends Chain | undefined> = {\n /**\n * `publicClient` can be provided to be used in place of the extended viem client for making public action calls\n * (`getChainId`, `getTransactionCount`, `call`). This helps in cases where the extended\n * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),\n * where the transport is the bundler, not an RPC.\n */\n publicClient?: Client<Transport, chain>;\n /**\n * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered\n * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions\n * arriving out of order, but this may be an acceptable trade-off for some applications that can safely retry.\n * @default 1\n */\n queueConcurrency?: number;\n};\n\n/** @deprecated Use `walletClient.extend(transactionQueue())` instead. */\nexport async function sendTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends SendTransactionRequest<chain, chainOverride>,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n request: SendTransactionParameters<chain, account, chainOverride, request>,\n opts: SendTransactionExtraOptions<chain> = {},\n): Promise<SendTransactionReturnType> {\n const rawAccount = request.account ?? client.account;\n if (!rawAccount) {\n // TODO: replace with viem AccountNotFoundError once its exported\n throw new Error(\"No account provided\");\n }\n const account = parseAccount(rawAccount);\n const chain = client.chain;\n\n const nonceManager = await getNonceManager({\n client: opts.publicClient ?? client,\n address: account.address,\n queueConcurrency: opts.queueConcurrency,\n });\n\n const feeRef = await getFeeRef({\n client: opts.publicClient ?? client,\n refreshInterval: 10000,\n args: { chain },\n });\n\n return await nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n const nonce = nonceManager.nextNonce();\n const params = {\n // viem_sendTransaction internally estimates gas, which we want to happen on the pending block\n blockTag: \"pending\",\n ...feeRef.fees,\n ...request,\n nonce,\n } as const satisfies SendTransactionParameters<chain, account, chainOverride, request>;\n debug(\"sending tx to\", request.to, \"with nonce\", nonce);\n return await getAction(client, viem_sendTransaction, \"sendTransaction\")(params as never);\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // in case this tx failed before hitting the mempool (i.e. gas estimation error), reset nonce so we don't skip past the unused nonce\n debug(\"failed, resetting nonce\");\n await nonceManager.resetNonce();\n // retry nonce errors\n // TODO: upgrade p-retry and move this to shouldRetry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n return;\n }\n\n if (String(error).includes(\"transaction underpriced\")) {\n debug(\"got transaction underpriced error, retrying\", error.message);\n return;\n }\n\n throw error;\n },\n },\n ),\n { throwOnTimeout: true },\n );\n}\n","import { getChainId } from \"viem/actions\";\nimport { CreateFeeRefOptions, FeeRef, createFeeRef } from \"./createFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst feeRefs = new Map<number, FeeRef>();\n\nexport async function getFeeRef(opts: CreateFeeRefOptions): Promise<FeeRef> {\n const chainId =\n opts.args?.chain?.id ?? opts.client.chain?.id ?? (await getAction(opts.client, getChainId, \"getChainId\")({}));\n\n const existingFeeRef = feeRefs.get(chainId);\n if (existingFeeRef) {\n return existingFeeRef;\n }\n\n const feeRef = await createFeeRef(opts);\n feeRefs.set(chainId, feeRef);\n return feeRef;\n}\n","import { EstimateFeesPerGasParameters, Client, EstimateFeesPerGasReturnType } from \"viem\";\nimport { estimateFeesPerGas } from \"viem/actions\";\nimport { getAction } from \"viem/utils\";\n\nexport type CreateFeeRefOptions = {\n client: Client;\n refreshInterval: number;\n args?: EstimateFeesPerGasParameters;\n};\n\nexport type FeeRef = {\n fees: EstimateFeesPerGasReturnType | {};\n lastUpdatedTimestamp: number;\n};\n\n/** Update fee values once every `refreshInterval` instead of right before every request */\nexport async function createFeeRef({ client, args, refreshInterval }: CreateFeeRefOptions): Promise<FeeRef> {\n const feeRef: FeeRef = { fees: {}, lastUpdatedTimestamp: 0 };\n\n async function updateFees(): Promise<void> {\n const fees = await getAction(client, estimateFeesPerGas, \"estimateFeesPerGas\")(args);\n feeRef.fees = fees;\n feeRef.lastUpdatedTimestamp = Date.now();\n }\n\n setInterval(updateFees, refreshInterval);\n await updateFees();\n\n return feeRef;\n}\n"],"mappings":"wCAAA,OAAgC,cAAAA,MAAkB,OAClD,OAAS,cAAAC,MAAkB,eAC3B,OAAS,aAAAC,MAAiB,aAE1B,eAAsBC,EAAkB,CACtC,OAAAC,EACA,QAAAC,EACA,SAAAC,CACF,EAIoB,CAGlB,MAAO,0BADSF,EAAO,OAAO,IAAO,MAAMF,EAAUE,EAAQH,EAAY,YAAY,EAAE,CAAC,CAAC,KAC7CD,EAAWK,CAAO,KAAKC,GACrE,CChBA,OAAS,aAAAC,EAAkC,qBAAAC,EAAmB,oBAAAC,MAAwB,OAGtF,OAAS,uBAAAC,MAA2B,eACpC,OAAOC,MAAY,UACnB,OAAS,aAAAC,MAAiB,aAE1B,IAAMC,EAAQA,EAAY,OAAO,oBAAoB,EAmB9C,SAASC,EAAmB,CACjC,OAAAC,EACA,QAAAC,EACA,SAAAC,EAAW,SACX,qBAAAC,EACA,iBAAAC,EA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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_sendTransaction","pRetry","parseAccount","getChainId","estimateFeesPerGas","getAction","createFeeRef","client","args","refreshInterval","feeRef","updateFees","fees","getAction","feeRefs","getFeeRef","opts","chainId","getChainId","existingFeeRef","feeRef","createFeeRef","getAction","debug","sendTransaction","client","request","opts","rawAccount","account","parseAccount","chain","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_sendTransaction","error"]}
1
+ {"version":3,"sources":["../src/getNonceManagerId.ts","../src/createNonceManager.ts","../src/getNonceManager.ts","../src/sendTransaction.ts","../src/getFeeRef.ts","../src/createFeeRef.ts"],"sourcesContent":["import { BlockTag, Client, Hex, getAddress } from \"viem\";\nimport { getChainId } from \"viem/actions\";\nimport { getAction } from \"viem/utils\";\n\nexport async function getNonceManagerId({\n client,\n address,\n blockTag,\n}: {\n client: Client;\n address: Hex;\n blockTag: BlockTag;\n}): Promise<string> {\n // TODO: improve this so we don't have to call getChainId every time\n const chainId = client.chain?.id ?? (await getAction(client, getChainId, \"getChainId\")({}));\n return `mud:createNonceManager:${chainId}:${getAddress(address)}:${blockTag}`;\n}\n","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 Account,\n Chain,\n Client,\n SendTransactionParameters,\n Transport,\n SendTransactionReturnType,\n SendTransactionRequest,\n} from \"viem\";\nimport { sendTransaction as viem_sendTransaction } from \"viem/actions\";\nimport pRetry from \"p-retry\";\nimport { debug as parentDebug } from \"./debug\";\nimport { getNonceManager } from \"./getNonceManager\";\nimport { parseAccount } from \"viem/accounts\";\nimport { getFeeRef } from \"./getFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst debug = parentDebug.extend(\"sendTransaction\");\n\nexport type SendTransactionExtraOptions<chain extends Chain | undefined> = {\n /**\n * `publicClient` can be provided to be used in place of the extended viem client for making public action calls\n * (`getChainId`, `getTransactionCount`, `call`). This helps in cases where the extended\n * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),\n * where the transport is the bundler, not an RPC.\n */\n publicClient?: Client<Transport, chain>;\n /**\n * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered\n * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions\n * arriving out of order, but this may be an acceptable trade-off for some applications that can safely retry.\n * @default 1\n */\n queueConcurrency?: number;\n};\n\n/** @deprecated Use `walletClient.extend(transactionQueue())` instead. */\nexport async function sendTransaction<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const request extends SendTransactionRequest<chain, chainOverride>,\n chainOverride extends Chain | undefined = undefined,\n>(\n client: Client<Transport, chain, account>,\n request: SendTransactionParameters<chain, account, chainOverride, request>,\n opts: SendTransactionExtraOptions<chain> = {},\n): Promise<SendTransactionReturnType> {\n const rawAccount = request.account ?? client.account;\n if (!rawAccount) {\n // TODO: replace with viem AccountNotFoundError once its exported\n throw new Error(\"No account provided\");\n }\n const account = parseAccount(rawAccount);\n const chain = client.chain;\n\n const nonceManager = await getNonceManager({\n client: opts.publicClient ?? client,\n address: account.address,\n queueConcurrency: opts.queueConcurrency,\n });\n\n const feeRef = await getFeeRef({\n client: opts.publicClient ?? client,\n refreshInterval: 10000,\n args: { chain },\n });\n\n return await nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n const nonce = nonceManager.nextNonce();\n const params = {\n // viem_sendTransaction internally estimates gas, which we want to happen on the pending block\n blockTag: \"pending\",\n ...feeRef.fees,\n ...request,\n nonce,\n } as const satisfies SendTransactionParameters<chain, account, chainOverride, request>;\n debug(\"sending tx to\", request.to, \"with nonce\", nonce);\n return await getAction(client, viem_sendTransaction, \"sendTransaction\")(params as never);\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // in case this tx failed before hitting the mempool (i.e. gas estimation error), reset nonce so we don't skip past the unused nonce\n debug(\"failed, resetting nonce\");\n await nonceManager.resetNonce();\n // retry nonce errors\n // TODO: upgrade p-retry and move this to shouldRetry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n return;\n }\n\n if (String(error).includes(\"transaction underpriced\")) {\n debug(\"got transaction underpriced error, retrying\", error.message);\n return;\n }\n\n throw error;\n },\n },\n ),\n { throwOnTimeout: true },\n );\n}\n","import { getChainId } from \"viem/actions\";\nimport { CreateFeeRefOptions, FeeRef, createFeeRef } from \"./createFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst feeRefs = new Map<number, FeeRef>();\n\nexport async function getFeeRef(opts: CreateFeeRefOptions): Promise<FeeRef> {\n const chainId =\n opts.args?.chain?.id ?? opts.client.chain?.id ?? (await getAction(opts.client, getChainId, \"getChainId\")({}));\n\n const existingFeeRef = feeRefs.get(chainId);\n if (existingFeeRef) {\n return existingFeeRef;\n }\n\n const feeRef = await createFeeRef(opts);\n feeRefs.set(chainId, feeRef);\n return feeRef;\n}\n","import { EstimateFeesPerGasParameters, Client, EstimateFeesPerGasReturnType } from \"viem\";\nimport { estimateFeesPerGas } from \"viem/actions\";\nimport { getAction } from \"viem/utils\";\n\nexport type CreateFeeRefOptions = {\n client: Client;\n refreshInterval: number;\n args?: EstimateFeesPerGasParameters;\n};\n\nexport type FeeRef = {\n fees: EstimateFeesPerGasReturnType | {};\n lastUpdatedTimestamp: number;\n};\n\n/** Update fee values once every `refreshInterval` instead of right before every request */\nexport async function createFeeRef({ client, args, refreshInterval }: CreateFeeRefOptions): Promise<FeeRef> {\n const feeRef: FeeRef = { fees: {}, lastUpdatedTimestamp: 0 };\n\n async function updateFees(): Promise<void> {\n const fees = await getAction(client, estimateFeesPerGas, \"estimateFeesPerGas\")(args);\n feeRef.fees = fees;\n feeRef.lastUpdatedTimestamp = Date.now();\n }\n\n setInterval(updateFees, refreshInterval);\n await updateFees();\n\n return feeRef;\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,CACjD,IAAID,EAAWK,CAAO,CAAC,IAAIC,CAAQ,EAC7E,CChBA,O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AOE,GAAU,CAMhC,GAJAjB,EAAM,yBAAyB,EAC/B,MAAMS,EAAa,WAAW,EAG1BA,EAAa,iBAAiBQ,CAAK,EAAG,CACxCjB,EAAM,4BAA6BiB,EAAM,OAAO,EAChD,MACF,CAEA,GAAI,OAAOA,CAAK,EAAE,SAAS,yBAAyB,EAAG,CACrDjB,EAAM,8CAA+CiB,EAAM,OAAO,EAClE,MACF,CAEA,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_sendTransaction","pRetry","parseAccount","getChainId","estimateFeesPerGas","getAction","createFeeRef","client","args","refreshInterval","feeRef","updateFees","fees","getAction","feeRefs","getFeeRef","opts","chainId","getChainId","existingFeeRef","feeRef","createFeeRef","getAction","debug","sendTransaction","client","request","opts","rawAccount","account","parseAccount","chain","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_sendTransaction","error"]}
@@ -1,2 +1,2 @@
1
- import{c as u,d}from"./chunk-RCAJ6T6T.js";import{a as s}from"./chunk-TCWGPC6G.js";import{writeContract as f}from"viem/actions";import g from"p-retry";import{parseAccount as h}from"viem/accounts";import{getAction as l}from"viem/utils";var r=s.extend("writeContract");async function T(e,c,a={}){let i=c.account??e.account;if(!i)throw new Error("No account provided");let m=h(i),p=e.chain,t=await u({client:a.publicClient??e,address:m.address,queueConcurrency:a.queueConcurrency}),C=await d({client:a.publicClient??e,refreshInterval:1e4,args:{chain:p}});return t.mempoolQueue.add(()=>g(async()=>{let n=t.nextNonce(),o={blockTag:"pending",...C.fees,...c,nonce:n};return r("calling",o.functionName,"at",o.address,"with nonce",n),await l(e,f,"writeContract")(o)},{retries:3,onFailedAttempt:async n=>{if(r("failed, resetting nonce"),await t.resetNonce(),t.shouldResetNonce(n)){r("got nonce error, retrying",n.message);return}if(String(n).includes("transaction underpriced")){r("got transaction underpriced error, retrying",n.message);return}throw n}}),{throwOnTimeout:!0})}export{T as a};
2
- //# sourceMappingURL=chunk-WSHEKFYD.js.map
1
+ import{c as u,d}from"./chunk-GUEDVXKC.js";import{a as s}from"./chunk-TCWGPC6G.js";import{writeContract as f}from"viem/actions";import g from"p-retry";import{parseAccount as h}from"viem/accounts";import{getAction as l}from"viem/utils";var r=s.extend("writeContract");async function T(e,c,a={}){let i=c.account??e.account;if(!i)throw new Error("No account provided");let m=h(i),p=e.chain,t=await u({client:a.publicClient??e,address:m.address,queueConcurrency:a.queueConcurrency}),C=await d({client:a.publicClient??e,refreshInterval:1e4,args:{chain:p}});return t.mempoolQueue.add(()=>g(async()=>{let n=t.nextNonce(),o={blockTag:"pending",...C.fees,...c,nonce:n};return r("calling",o.functionName,"at",o.address,"with nonce",n),await l(e,f,"writeContract")(o)},{retries:3,onFailedAttempt:async n=>{if(r("failed, resetting nonce"),await t.resetNonce(),t.shouldResetNonce(n)){r("got nonce error, retrying",n.message);return}if(String(n).includes("transaction underpriced")){r("got transaction underpriced error, retrying",n.message);return}throw n}}),{throwOnTimeout:!0})}export{T as a};
2
+ //# sourceMappingURL=chunk-Q7HNDKVJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/writeContract.ts"],"sourcesContent":["import {\n Abi,\n Account,\n Chain,\n Client,\n Transport,\n WriteContractParameters,\n WriteContractReturnType,\n ContractFunctionName,\n ContractFunctionArgs,\n} from \"viem\";\nimport { writeContract as viem_writeContract } from \"viem/actions\";\nimport pRetry from \"p-retry\";\nimport { debug as parentDebug } from \"./debug\";\nimport { getNonceManager } from \"./getNonceManager\";\nimport { parseAccount } from \"viem/accounts\";\nimport { getFeeRef } from \"./getFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst debug = parentDebug.extend(\"writeContract\");\n\nexport type WriteContractExtraOptions<chain extends Chain | undefined> = {\n /**\n * `publicClient` can be provided to be used in place of the extended viem client for making public action calls\n * (`getChainId`, `getTransactionCount`, `simulateContract`). This helps in cases where the extended\n * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),\n * where the transport is the bundler, not an RPC.\n */\n publicClient?: Client<Transport, chain>;\n /**\n * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered\n * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions\n * arriving out of order, but this may be an acceptable trade-off for some applications that can safely retry.\n * @default 1\n */\n queueConcurrency?: number;\n};\n\n/** @deprecated Use `walletClient.extend(transactionQueue())` instead. */\nexport async function writeContract<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, \"nonpayable\" | \"payable\">,\n args extends ContractFunctionArgs<abi, \"nonpayable\" | \"payable\", functionName>,\n chainOverride extends Chain | undefined,\n>(\n client: Client<Transport, chain, account>,\n request: WriteContractParameters<abi, functionName, args, chain, account, chainOverride>,\n opts: WriteContractExtraOptions<chain> = {},\n): Promise<WriteContractReturnType> {\n const rawAccount = request.account ?? client.account;\n if (!rawAccount) {\n // TODO: replace with viem AccountNotFoundError once its exported\n throw new Error(\"No account provided\");\n }\n const account = parseAccount(rawAccount);\n const chain = client.chain;\n\n const nonceManager = await getNonceManager({\n client: opts.publicClient ?? client,\n address: account.address,\n queueConcurrency: opts.queueConcurrency,\n });\n\n const feeRef = await getFeeRef({\n client: opts.publicClient ?? client,\n refreshInterval: 10000,\n args: { chain },\n });\n\n return nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n const nonce = nonceManager.nextNonce();\n const params = {\n // viem_writeContract internally estimates gas, which we want to happen on the pending block\n blockTag: \"pending\",\n ...feeRef.fees,\n ...request,\n nonce,\n } as const satisfies WriteContractParameters<abi, functionName, args, chain, account, chainOverride>;\n debug(\"calling\", params.functionName, \"at\", params.address, \"with nonce\", nonce);\n return await getAction(client, viem_writeContract, \"writeContract\")(params as never);\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // in case this tx failed before hitting the mempool (i.e. gas estimation error), reset nonce so we don't skip past the unused nonce\n debug(\"failed, resetting nonce\");\n await nonceManager.resetNonce();\n // retry nonce errors\n // TODO: upgrade p-retry and move this to shouldRetry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n return;\n }\n\n if (String(error).includes(\"transaction underpriced\")) {\n debug(\"got transaction underpriced error, retrying\", error.message);\n return;\n }\n\n throw error;\n },\n },\n ),\n { throwOnTimeout: true },\n );\n}\n"],"mappings":"kFAWA,OAAS,iBAAiBA,MAA0B,eACpD,OAAOC,MAAY,UAGnB,OAAS,gBAAAC,MAAoB,gBAE7B,OAAS,aAAAC,MAAiB,aAE1B,IAAMC,EAAQA,EAAY,OAAO,eAAe,EAoBhD,eAAsBC,EAQpBC,EACAC,EACAC,EAAyC,CAAC,EACR,CAClC,IAAMC,EAAaF,EAAQ,SAAWD,EAAO,QAC7C,GAAI,CAACG,EAEH,MAAM,IAAI,MAAM,qBAAqB,EAEvC,IAAMC,EAAUC,EAAaF,CAAU,EACjCG,EAAQN,EAAO,MAEfO,EAAe,MAAMC,EAAgB,CACzC,OAAQN,EAAK,cAAgBF,EAC7B,QAASI,EAAQ,QACjB,iBAAkBF,EAAK,gBACzB,CAAC,EAEKO,EAAS,MAAMC,EAAU,CAC7B,OAAQR,EAAK,cAAgBF,EAC7B,gBAAiB,IACjB,KAAM,CAAE,MAAAM,CAAM,CAChB,CAAC,EAED,OAAOC,EAAa,aAAa,IAC/B,IACEI,EACE,SAAY,CACV,IAAMC,EAAQL,EAAa,UAAU,EAC/BM,EAAS,CAEb,SAAU,UACV,GAAGJ,EAAO,KACV,GAAGR,EACH,MAAAW,CACF,EACA,OAAAd,EAAM,UAAWe,EAAO,aAAc,KAAMA,EAAO,QAAS,aAAcD,CAAK,EACxE,MAAMf,EAAUG,EAAQc,EAAoB,eAAe,EAAED,CAAe,CACrF,EACA,CACE,QAAS,EACT,gBAAiB,MAAOE,GAAU,CAMhC,GAJAjB,EAAM,yBAAyB,EAC/B,MAAMS,EAAa,WAAW,EAG1BA,EAAa,iBAAiBQ,CAAK,EAAG,CACxCjB,EAAM,4BAA6BiB,EAAM,OAAO,EAChD,OAGF,GAAI,OAAOA,CAAK,EAAE,SAAS,yBAAyB,EAAG,CACrDjB,EAAM,8CAA+CiB,EAAM,OAAO,EAClE,OAGF,MAAMA,CACR,CACF,CACF,EACF,CAAE,eAAgB,EAAK,CACzB,CACF","names":["viem_writeContract","pRetry","parseAccount","getAction","debug","writeContract","client","request","opts","rawAccount","account","parseAccount","chain","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_writeContract","error"]}
1
+ {"version":3,"sources":["../src/writeContract.ts"],"sourcesContent":["import {\n Abi,\n Account,\n Chain,\n Client,\n Transport,\n WriteContractParameters,\n WriteContractReturnType,\n ContractFunctionName,\n ContractFunctionArgs,\n} from \"viem\";\nimport { writeContract as viem_writeContract } from \"viem/actions\";\nimport pRetry from \"p-retry\";\nimport { debug as parentDebug } from \"./debug\";\nimport { getNonceManager } from \"./getNonceManager\";\nimport { parseAccount } from \"viem/accounts\";\nimport { getFeeRef } from \"./getFeeRef\";\nimport { getAction } from \"viem/utils\";\n\nconst debug = parentDebug.extend(\"writeContract\");\n\nexport type WriteContractExtraOptions<chain extends Chain | undefined> = {\n /**\n * `publicClient` can be provided to be used in place of the extended viem client for making public action calls\n * (`getChainId`, `getTransactionCount`, `simulateContract`). This helps in cases where the extended\n * viem client is a smart account client, like in [permissionless.js](https://github.com/pimlicolabs/permissionless.js),\n * where the transport is the bundler, not an RPC.\n */\n publicClient?: Client<Transport, chain>;\n /**\n * Adjust the number of concurrent calls to the mempool. This defaults to `1` to ensure transactions are ordered\n * and nonces are handled properly. Any number greater than that is likely to see nonce errors and/or transactions\n * arriving out of order, but this may be an acceptable trade-off for some applications that can safely retry.\n * @default 1\n */\n queueConcurrency?: number;\n};\n\n/** @deprecated Use `walletClient.extend(transactionQueue())` instead. */\nexport async function writeContract<\n chain extends Chain | undefined,\n account extends Account | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, \"nonpayable\" | \"payable\">,\n args extends ContractFunctionArgs<abi, \"nonpayable\" | \"payable\", functionName>,\n chainOverride extends Chain | undefined,\n>(\n client: Client<Transport, chain, account>,\n request: WriteContractParameters<abi, functionName, args, chain, account, chainOverride>,\n opts: WriteContractExtraOptions<chain> = {},\n): Promise<WriteContractReturnType> {\n const rawAccount = request.account ?? client.account;\n if (!rawAccount) {\n // TODO: replace with viem AccountNotFoundError once its exported\n throw new Error(\"No account provided\");\n }\n const account = parseAccount(rawAccount);\n const chain = client.chain;\n\n const nonceManager = await getNonceManager({\n client: opts.publicClient ?? client,\n address: account.address,\n queueConcurrency: opts.queueConcurrency,\n });\n\n const feeRef = await getFeeRef({\n client: opts.publicClient ?? client,\n refreshInterval: 10000,\n args: { chain },\n });\n\n return nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n const nonce = nonceManager.nextNonce();\n const params = {\n // viem_writeContract internally estimates gas, which we want to happen on the pending block\n blockTag: \"pending\",\n ...feeRef.fees,\n ...request,\n nonce,\n } as const satisfies WriteContractParameters<abi, functionName, args, chain, account, chainOverride>;\n debug(\"calling\", params.functionName, \"at\", params.address, \"with nonce\", nonce);\n return await getAction(client, viem_writeContract, \"writeContract\")(params as never);\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // in case this tx failed before hitting the mempool (i.e. gas estimation error), reset nonce so we don't skip past the unused nonce\n debug(\"failed, resetting nonce\");\n await nonceManager.resetNonce();\n // retry nonce errors\n // TODO: upgrade p-retry and move this to shouldRetry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n return;\n }\n\n if (String(error).includes(\"transaction underpriced\")) {\n debug(\"got transaction underpriced error, retrying\", error.message);\n return;\n }\n\n throw error;\n },\n },\n ),\n { throwOnTimeout: true },\n );\n}\n"],"mappings":"kFAWA,OAAS,iBAAiBA,MAA0B,eACpD,OAAOC,MAAY,UAGnB,OAAS,gBAAAC,MAAoB,gBAE7B,OAAS,aAAAC,MAAiB,aAE1B,IAAMC,EAAQA,EAAY,OAAO,eAAe,EAoBhD,eAAsBC,EAQpBC,EACAC,EACAC,EAAyC,CAAC,EACR,CAClC,IAAMC,EAAaF,EAAQ,SAAWD,EAAO,QAC7C,GAAI,CAACG,EAEH,MAAM,IAAI,MAAM,qBAAqB,EAEvC,IAAMC,EAAUC,EAAaF,CAAU,EACjCG,EAAQN,EAAO,MAEfO,EAAe,MAAMC,EAAgB,CACzC,OAAQN,EAAK,cAAgBF,EAC7B,QAASI,EAAQ,QACjB,iBAAkBF,EAAK,gBACzB,CAAC,EAEKO,EAAS,MAAMC,EAAU,CAC7B,OAAQR,EAAK,cAAgBF,EAC7B,gBAAiB,IACjB,KAAM,CAAE,MAAAM,CAAM,CAChB,CAAC,EAED,OAAOC,EAAa,aAAa,IAC/B,IACEI,EACE,SAAY,CACV,IAAMC,EAAQL,EAAa,UAAU,EAC/BM,EAAS,CAEb,SAAU,UACV,GAAGJ,EAAO,KACV,GAAGR,EACH,MAAAW,CACF,EACA,OAAAd,EAAM,UAAWe,EAAO,aAAc,KAAMA,EAAO,QAAS,aAAcD,CAAK,EACxE,MAAMf,EAAUG,EAAQc,EAAoB,eAAe,EAAED,CAAe,CACrF,EACA,CACE,QAAS,EACT,gBAAiB,MAAOE,GAAU,CAMhC,GAJAjB,EAAM,yBAAyB,EAC/B,MAAMS,EAAa,WAAW,EAG1BA,EAAa,iBAAiBQ,CAAK,EAAG,CACxCjB,EAAM,4BAA6BiB,EAAM,OAAO,EAChD,MACF,CAEA,GAAI,OAAOA,CAAK,EAAE,SAAS,yBAAyB,EAAG,CACrDjB,EAAM,8CAA+CiB,EAAM,OAAO,EAClE,MACF,CAEA,MAAMA,CACR,CACF,CACF,EACF,CAAE,eAAgB,EAAK,CACzB,CACF","names":["viem_writeContract","pRetry","parseAccount","getAction","debug","writeContract","client","request","opts","rawAccount","account","parseAccount","chain","nonceManager","getNonceManager","feeRef","getFeeRef","pRetry","nonce","params","viem_writeContract","error"]}
@@ -0,0 +1,2 @@
1
+ var r=class extends Error{constructor(){super(...arguments);this.name="MUDError"}};export{r as a};
2
+ //# sourceMappingURL=chunk-QQCZY3XJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors/MUDError.ts"],"sourcesContent":["export class MUDError extends Error {\n name = \"MUDError\";\n}\n"],"mappings":"AAAO,IAAMA,EAAN,cAAuB,KAAM,CAClC,KAAO,UACT","names":["MUDError"]}
1
+ {"version":3,"sources":["../src/errors/MUDError.ts"],"sourcesContent":["export class MUDError extends Error {\n name = \"MUDError\";\n}\n"],"mappings":"AAAO,IAAMA,EAAN,cAAuB,KAAM,CAA7B,kCACL,UAAO,WACT","names":["MUDError"]}
@@ -1,2 +1,2 @@
1
1
  var m=["table","offchainTable","namespace","system"];import{stringToHex as s,concatHex as u}from"viem";var o={table:"tb",offchainTable:"ot",namespace:"ns",system:"sy"};function x(e){let r=o[e.type];if(e.namespace.length>14)throw new Error(`Namespaces must fit into \`bytes14\`, but "${e.namespace}" is too long.`);return u([s(r,{size:2}),s(e.namespace,{size:14}),s(e.name.slice(0,16),{size:16})])}var y="";function i({namespace:e,name:r}){return e===y?r:`${e}__${r}`}import{hexToString as t,sliceHex as n}from"viem";var f=Object.fromEntries(Object.entries(o).map(([e,r])=>[r,e]));function T(e){let r=f[e];if(m.includes(r))return r}function _(e){let r=t(n(e,0,2)).replace(/\0+$/,""),c=T(r),a=t(n(e,2,16)).replace(/\0+$/,""),p=t(n(e,16,32)).replace(/\0+$/,"");if(!c)throw new Error(`Unknown type (${r}) for resource (${i({namespace:a,name:p})})`);return{resourceId:e,type:c,namespace:a,name:p}}export{m as a,o as b,x as c,i as d,_ as e};
2
- //# sourceMappingURL=chunk-DDEUATTE.js.map
2
+ //# sourceMappingURL=chunk-ZIUX7JCQ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/resourceTypes.ts","../src/resourceToHex.ts","../src/resourceToLabel.ts","../src/hexToResource.ts"],"sourcesContent":["export const resourceTypes = [\"table\", \"offchainTable\", \"namespace\", \"system\"] as const;\n\nexport type ResourceType = (typeof resourceTypes)[number];\n","import { Hex, stringToHex, concatHex } from \"viem\";\nimport { Resource } from \"./common\";\nimport { ResourceType } from \"./resourceTypes\";\n\n/** @internal */\nexport const resourceTypeIds = {\n // keep these in sync with storeResourceTypes.sol\n table: \"tb\",\n offchainTable: \"ot\",\n // keep these in sync with worldResourceTypes.sol\n namespace: \"ns\",\n system: \"sy\",\n} as const satisfies Record<ResourceType, string>;\n\nexport function resourceToHex(resource: Omit<Resource, \"resourceId\">): Hex {\n const typeId = resourceTypeIds[resource.type];\n // Because namespaces are tied to access control, it's not safe to automatically truncate. Instead, we'll throw an error.\n if (resource.namespace.length > 14) {\n throw new Error(`Namespaces must fit into \\`bytes14\\`, but \"${resource.namespace}\" is too long.`);\n }\n return concatHex([\n stringToHex(typeId, { size: 2 }),\n stringToHex(resource.namespace, { size: 14 }),\n stringToHex(resource.name.slice(0, 16), { size: 16 }),\n ]);\n}\n","const rootNamespace = \"\";\n\nexport type ResourceLabel<\n namespace extends string = string,\n name extends string = string,\n> = namespace extends typeof rootNamespace ? name : `${namespace}__${name}`;\n\nexport function resourceToLabel<namespace extends string, name extends string>({\n namespace,\n name,\n}: {\n readonly namespace: namespace;\n readonly name: name;\n}): ResourceLabel<namespace, name> {\n return (namespace === rootNamespace ? name : `${namespace}__${name}`) as ResourceLabel<namespace, name>;\n}\n","import { Hex, hexToString, sliceHex } from \"viem\";\nimport { Resource } from \"./common\";\nimport { ResourceType, resourceTypes } from \"./resourceTypes\";\nimport { resourceTypeIds } from \"./resourceToHex\";\nimport { ReverseMap } from \"./type-utils/common\";\nimport { resourceToLabel } from \"./resourceToLabel\";\n\nconst resourceTypeIdToType = Object.fromEntries(\n Object.entries(resourceTypeIds).map(([key, value]) => [value, key]),\n) as ReverseMap<typeof resourceTypeIds>;\n\nfunction getResourceType(resourceTypeId: string): ResourceType | undefined {\n // TODO: replace Partial with `noUncheckedIndexedAccess`\n const type = (resourceTypeIdToType as Partial<Record<string, ResourceType>>)[resourceTypeId];\n if (resourceTypes.includes(type as ResourceType)) {\n return type;\n }\n}\n\nexport function hexToResource(hex: Hex): Resource {\n const resourceTypeId = hexToString(sliceHex(hex, 0, 2)).replace(/\\0+$/, \"\");\n const type = getResourceType(resourceTypeId);\n const namespace = hexToString(sliceHex(hex, 2, 16)).replace(/\\0+$/, \"\");\n const name = hexToString(sliceHex(hex, 16, 32)).replace(/\\0+$/, \"\");\n\n if (!type) {\n throw new Error(`Unknown type (${resourceTypeId}) for resource (${resourceToLabel({ namespace, name })})`);\n }\n\n return { resourceId: hex, type, namespace, name };\n}\n"],"mappings":"AAAO,IAAMA,EAAgB,CAAC,QAAS,gBAAiB,YAAa,QAAQ,ECA7E,OAAc,eAAAC,EAAa,aAAAC,MAAiB,OAKrC,IAAMC,EAAkB,CAE7B,MAAO,KACP,cAAe,KAEf,UAAW,KACX,OAAQ,IACV,EAEO,SAASC,EAAcC,EAA6C,CACzE,IAAMC,EAASH,EAAgBE,EAAS,IAAI,EAE5C,GAAIA,EAAS,UAAU,OAAS,GAC9B,MAAM,IAAI,MAAM,8CAA8CA,EAAS,yBAAyB,EAElG,OAAOH,EAAU,CACfD,EAAYK,EAAQ,CAAE,KAAM,CAAE,CAAC,EAC/BL,EAAYI,EAAS,UAAW,CAAE,KAAM,EAAG,CAAC,EAC5CJ,EAAYI,EAAS,KAAK,MAAM,EAAG,EAAE,EAAG,CAAE,KAAM,EAAG,CAAC,CACtD,CAAC,CACH,CCzBA,IAAME,EAAgB,GAOf,SAASC,EAA+D,CAC7E,UAAAC,EACA,KAAAC,CACF,EAGmC,CACjC,OAAQD,IAAcF,EAAgBG,EAAO,GAAGD,MAAcC,GAChE,CCfA,OAAc,eAAAC,EAAa,YAAAC,MAAgB,OAO3C,IAAMC,EAAuB,OAAO,YAClC,OAAO,QAAQC,CAAe,EAAE,IAAI,CAAC,CAACC,EAAKC,CAAK,IAAM,CAACA,EAAOD,CAAG,CAAC,CACpE,EAEA,SAASE,EAAgBC,EAAkD,CAEzE,IAAMC,EAAQN,EAA+DK,CAAc,EAC3F,GAAIE,EAAc,SAASD,CAAoB,EAC7C,OAAOA,CAEX,CAEO,SAASE,EAAcC,EAAoB,CAChD,IAAMJ,EAAiBK,EAAYC,EAASF,EAAK,EAAG,CAAC,CAAC,EAAE,QAAQ,OAAQ,EAAE,EACpEH,EAAOF,EAAgBC,CAAc,EACrCO,EAAYF,EAAYC,EAASF,EAAK,EAAG,EAAE,CAAC,EAAE,QAAQ,OAAQ,EAAE,EAChEI,EAAOH,EAAYC,EAASF,EAAK,GAAI,EAAE,CAAC,EAAE,QAAQ,OAAQ,EAAE,EAElE,GAAI,CAACH,EACH,MAAM,IAAI,MAAM,iBAAiBD,oBAAiCS,EAAgB,CAAE,UAAAF,EAAW,KAAAC,CAAK,CAAC,IAAI,EAG3G,MAAO,CAAE,WAAYJ,EAAK,KAAAH,EAAM,UAAAM,EAAW,KAAAC,CAAK,CAClD","names":["resourceTypes","stringToHex","concatHex","resourceTypeIds","resourceToHex","resource","typeId","rootNamespace","resourceToLabel","namespace","name","hexToString","sliceHex","resourceTypeIdToType","resourceTypeIds","key","value","getResourceType","resourceTypeId","type","resourceTypes","hexToResource","hex","hexToString","sliceHex","namespace","name","resourceToLabel"]}
1
+ {"version":3,"sources":["../src/resourceTypes.ts","../src/resourceToHex.ts","../src/resourceToLabel.ts","../src/hexToResource.ts"],"sourcesContent":["export const resourceTypes = [\"table\", \"offchainTable\", \"namespace\", \"system\"] as const;\n\nexport type ResourceType = (typeof resourceTypes)[number];\n","import { Hex, stringToHex, concatHex } from \"viem\";\nimport { Resource } from \"./common\";\nimport { ResourceType } from \"./resourceTypes\";\n\n/** @internal */\nexport const resourceTypeIds = {\n // keep these in sync with storeResourceTypes.sol\n table: \"tb\",\n offchainTable: \"ot\",\n // keep these in sync with worldResourceTypes.sol\n namespace: \"ns\",\n system: \"sy\",\n} as const satisfies Record<ResourceType, string>;\n\nexport function resourceToHex(resource: Omit<Resource, \"resourceId\">): Hex {\n const typeId = resourceTypeIds[resource.type];\n // Because namespaces are tied to access control, it's not safe to automatically truncate. Instead, we'll throw an error.\n if (resource.namespace.length > 14) {\n throw new Error(`Namespaces must fit into \\`bytes14\\`, but \"${resource.namespace}\" is too long.`);\n }\n return concatHex([\n stringToHex(typeId, { size: 2 }),\n stringToHex(resource.namespace, { size: 14 }),\n stringToHex(resource.name.slice(0, 16), { size: 16 }),\n ]);\n}\n","const rootNamespace = \"\";\n\nexport type ResourceLabel<\n namespace extends string = string,\n name extends string = string,\n> = namespace extends typeof rootNamespace ? name : `${namespace}__${name}`;\n\nexport function resourceToLabel<namespace extends string, name extends string>({\n namespace,\n name,\n}: {\n readonly namespace: namespace;\n readonly name: name;\n}): ResourceLabel<namespace, name> {\n return (namespace === rootNamespace ? name : `${namespace}__${name}`) as ResourceLabel<namespace, name>;\n}\n","import { Hex, hexToString, sliceHex } from \"viem\";\nimport { Resource } from \"./common\";\nimport { ResourceType, resourceTypes } from \"./resourceTypes\";\nimport { resourceTypeIds } from \"./resourceToHex\";\nimport { ReverseMap } from \"./type-utils/common\";\nimport { resourceToLabel } from \"./resourceToLabel\";\n\nconst resourceTypeIdToType = Object.fromEntries(\n Object.entries(resourceTypeIds).map(([key, value]) => [value, key]),\n) as ReverseMap<typeof resourceTypeIds>;\n\nfunction getResourceType(resourceTypeId: string): ResourceType | undefined {\n // TODO: replace Partial with `noUncheckedIndexedAccess`\n const type = (resourceTypeIdToType as Partial<Record<string, ResourceType>>)[resourceTypeId];\n if (resourceTypes.includes(type as ResourceType)) {\n return type;\n }\n}\n\nexport function hexToResource(hex: Hex): Resource {\n const resourceTypeId = hexToString(sliceHex(hex, 0, 2)).replace(/\\0+$/, \"\");\n const type = getResourceType(resourceTypeId);\n const namespace = hexToString(sliceHex(hex, 2, 16)).replace(/\\0+$/, \"\");\n const name = hexToString(sliceHex(hex, 16, 32)).replace(/\\0+$/, \"\");\n\n if (!type) {\n throw new Error(`Unknown type (${resourceTypeId}) for resource (${resourceToLabel({ namespace, name })})`);\n }\n\n return { resourceId: hex, type, namespace, name };\n}\n"],"mappings":"AAAO,IAAMA,EAAgB,CAAC,QAAS,gBAAiB,YAAa,QAAQ,ECA7E,OAAc,eAAAC,EAAa,aAAAC,MAAiB,OAKrC,IAAMC,EAAkB,CAE7B,MAAO,KACP,cAAe,KAEf,UAAW,KACX,OAAQ,IACV,EAEO,SAASC,EAAcC,EAA6C,CACzE,IAAMC,EAASH,EAAgBE,EAAS,IAAI,EAE5C,GAAIA,EAAS,UAAU,OAAS,GAC9B,MAAM,IAAI,MAAM,8CAA8CA,EAAS,SAAS,gBAAgB,EAElG,OAAOH,EAAU,CACfD,EAAYK,EAAQ,CAAE,KAAM,CAAE,CAAC,EAC/BL,EAAYI,EAAS,UAAW,CAAE,KAAM,EAAG,CAAC,EAC5CJ,EAAYI,EAAS,KAAK,MAAM,EAAG,EAAE,EAAG,CAAE,KAAM,EAAG,CAAC,CACtD,CAAC,CACH,CCzBA,IAAME,EAAgB,GAOf,SAASC,EAA+D,CAC7E,UAAAC,EACA,KAAAC,CACF,EAGmC,CACjC,OAAQD,IAAcF,EAAgBG,EAAO,GAAGD,CAAS,KAAKC,CAAI,EACpE,CCfA,OAAc,eAAAC,EAAa,YAAAC,MAAgB,OAO3C,IAAMC,EAAuB,OAAO,YAClC,OAAO,QAAQC,CAAe,EAAE,IAAI,CAAC,CAACC,EAAKC,CAAK,IAAM,CAACA,EAAOD,CAAG,CAAC,CACpE,EAEA,SAASE,EAAgBC,EAAkD,CAEzE,IAAMC,EAAQN,EAA+DK,CAAc,EAC3F,GAAIE,EAAc,SAASD,CAAoB,EAC7C,OAAOA,CAEX,CAEO,SAASE,EAAcC,EAAoB,CAChD,IAAMJ,EAAiBK,EAAYC,EAASF,EAAK,EAAG,CAAC,CAAC,EAAE,QAAQ,OAAQ,EAAE,EACpEH,EAAOF,EAAgBC,CAAc,EACrCO,EAAYF,EAAYC,EAASF,EAAK,EAAG,EAAE,CAAC,EAAE,QAAQ,OAAQ,EAAE,EAChEI,EAAOH,EAAYC,EAASF,EAAK,GAAI,EAAE,CAAC,EAAE,QAAQ,OAAQ,EAAE,EAElE,GAAI,CAACH,EACH,MAAM,IAAI,MAAM,iBAAiBD,CAAc,mBAAmBS,EAAgB,CAAE,UAAAF,EAAW,KAAAC,CAAK,CAAC,CAAC,GAAG,EAG3G,MAAO,CAAE,WAAYJ,EAAK,KAAAH,EAAM,UAAAM,EAAW,KAAAC,CAAK,CAClD","names":["resourceTypes","stringToHex","concatHex","resourceTypeIds","resourceToHex","resource","typeId","rootNamespace","resourceToLabel","namespace","name","hexToString","sliceHex","resourceTypeIdToType","resourceTypeIds","key","value","getResourceType","resourceTypeId","type","resourceTypes","hexToResource","hex","hexToString","sliceHex","namespace","name","resourceToLabel"]}
@@ -1,2 +1,2 @@
1
1
  function o(l,n){let e=new Map;for(let a of l){let u=n(a);e.has(u)||e.set(u,a)}return Array.from(e.values())}export{o as a};
2
- //# sourceMappingURL=chunk-Y4MH6TRP.js.map
2
+ //# sourceMappingURL=chunk-ZV2KGJCD.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/uniqueBy.ts"],"sourcesContent":["export function uniqueBy<value, key>(values: readonly value[], getKey: (value: value) => key): readonly value[] {\n const map = new Map<key, value>();\n for (const value of values) {\n const key = getKey(value);\n if (!map.has(key)) {\n map.set(key, value);\n }\n }\n return Array.from(map.values());\n}\n"],"mappings":"AAAO,SAASA,EAAqBC,EAA0BC,EAAiD,CAC9G,IAAMC,EAAM,IAAI,IAChB,QAAWC,KAASH,EAAQ,CAC1B,IAAMI,EAAMH,EAAOE,CAAK,EACnBD,EAAI,IAAIE,CAAG,GACdF,EAAI,IAAIE,EAAKD,CAAK,EAGtB,OAAO,MAAM,KAAKD,EAAI,OAAO,CAAC,CAChC","names":["uniqueBy","values","getKey","map","value","key"]}
1
+ {"version":3,"sources":["../src/utils/uniqueBy.ts"],"sourcesContent":["export function uniqueBy<value, key>(values: readonly value[], getKey: (value: value) => key): readonly value[] {\n const map = new Map<key, value>();\n for (const value of values) {\n const key = getKey(value);\n if (!map.has(key)) {\n map.set(key, value);\n }\n }\n return Array.from(map.values());\n}\n"],"mappings":"AAAO,SAASA,EAAqBC,EAA0BC,EAAiD,CAC9G,IAAMC,EAAM,IAAI,IAChB,QAAWC,KAASH,EAAQ,CAC1B,IAAMI,EAAMH,EAAOE,CAAK,EACnBD,EAAI,IAAIE,CAAG,GACdF,EAAI,IAAIE,EAAKD,CAAK,CAEtB,CACA,OAAO,MAAM,KAAKD,EAAI,OAAO,CAAC,CAChC","names":["uniqueBy","values","getKey","map","value","key"]}
package/dist/codegen.d.ts CHANGED
@@ -225,4 +225,4 @@ declare function formatAndWriteSolidity(output: string, fullOutputPath: string,
225
225
  */
226
226
  declare function formatAndWriteTypescript(output: string, fullOutputPath: string, logPrefix: string): Promise<void>;
227
227
 
228
- export { AbiToInterfaceOptions, ContractInterfaceError, ContractInterfaceFunction, ImportDatum, RenderDynamicField, RenderEnum, RenderField, RenderFieldTypeWrappingData, RenderKeyTuple, RenderStaticField, RenderType, StaticResourceData, abiToInterface, contractToInterface, findContractNode, formatAndWriteSolidity, formatAndWriteTypescript, formatSolidity, formatTypescript, getLeftPaddingBits, isLeftAligned, renderArguments, renderCommonData, renderEnums, renderImportPath, renderImports, renderList, renderTableId, renderTypeHelpers, renderValueTypeToBytes32, renderWithFieldSuffix, renderWithStore, renderedSolidityHeader, schemaTypesToRecsTypeStrings };
228
+ export { type AbiToInterfaceOptions, type ContractInterfaceError, type ContractInterfaceFunction, type ImportDatum, type RenderDynamicField, type RenderEnum, type RenderField, type RenderFieldTypeWrappingData, type RenderKeyTuple, type RenderStaticField, type RenderType, type StaticResourceData, abiToInterface, contractToInterface, findContractNode, formatAndWriteSolidity, formatAndWriteTypescript, formatSolidity, formatTypescript, getLeftPaddingBits, isLeftAligned, renderArguments, renderCommonData, renderEnums, renderImportPath, renderImports, renderList, renderTableId, renderTypeHelpers, renderValueTypeToBytes32, renderWithFieldSuffix, renderWithStore, renderedSolidityHeader, schemaTypesToRecsTypeStrings };
package/dist/codegen.js CHANGED
@@ -1,4 +1,4 @@
1
- import{c as _,e as A}from"./chunk-DDEUATTE.js";import{a as f}from"./chunk-TCWGPC6G.js";import{a as R}from"./chunk-UPQEB2HW.js";import{formatAbiItem as H,formatAbiParameter as K}from"abitype";import B from"node:path";function b(t){return t.replaceAll(B.win32.sep,B.posix.sep)}function h(t,...r){let n=B.posix.join(b(t),...r.map(b)).replace(/\/$/,"");return t.startsWith(".")?("./"+n).replace(/^(\.\/)+\./,"."):n}var u=`// SPDX-License-Identifier: MIT
1
+ import{c as _,e as A}from"./chunk-ZIUX7JCQ.js";import{a as f}from"./chunk-TCWGPC6G.js";import{a as R}from"./chunk-QQCZY3XJ.js";import{formatAbiItem as H,formatAbiParameter as K}from"abitype";import B from"node:path";function b(t){return t.replaceAll(B.win32.sep,B.posix.sep)}function h(t,...r){let n=B.posix.join(b(t),...r.map(b)).replace(/\/$/,"");return t.startsWith(".")?("./"+n).replace(/^(\.\/)+\./,"."):n}var u=`// SPDX-License-Identifier: MIT
2
2
  pragma solidity >=0.8.24;
3
3
 
4
4
  /* Autogenerated file. Do not edit manually. */`;function L(t,r){return E("",t,r)}function O(t){let r=t.filter(n=>n!==void 0&&n!=="");return E(",",r,n=>n)}function se({staticResourceData:t,keyTuple:r}){let n=t?"":"ResourceId _tableId",i=O(r.map(({name:a,typeWithLocation:o})=>`${o} ${a}`)),s=`
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/codegen/render-solidity/abiToInterface.ts","../src/codegen/render-solidity/renderImportPath.ts","../src/codegen/render-solidity/common.ts","../src/codegen/render-solidity/renderEnums.ts","../src/codegen/render-solidity/renderTypeHelpers.ts","../src/codegen/render-typescript/schemaTypesToRecsTypeStrings.ts","../src/codegen/utils/contractToInterface.ts","../src/codegen/utils/format.ts","../src/codegen/utils/formatAndWrite.ts","../src/codegen/debug.ts"],"sourcesContent":["import { AbiParameter, Hex } from \"viem\";\nimport { Abi, AbiError, AbiFunction, formatAbiItem, formatAbiParameter } from \"abitype\";\nimport { renderedSolidityHeader } from \"./common\";\nimport { hexToResource } from \"../../hexToResource\";\n\nfunction formatParam(param: AbiParameter): string {\n // return param.type === \"string\" || param.type === \"bytes\" || param.type === \"tuple\" || param.type.endsWith(\"]\")\n // ? `${formatAbiParameter(param)} memory`\n // : formatAbiParameter(param);\n return formatAbiParameter(param);\n}\n\nfunction formatFunction(item: AbiFunction): string {\n const params = item.inputs.map(formatParam).join(\", \");\n const returns = item.outputs.map(formatParam).join(\", \");\n return `function ${item.name}(${params}) external${returns.length ? ` returns (${returns})` : \"\"}`;\n}\n\nfunction formatSystemId(systemId: Hex): string {\n const resource = hexToResource(systemId);\n return `\n // equivalent to \\`WorldResourceIdLib.encode({ namespace: ${JSON.stringify(\n resource.namespace,\n )}, name: ${JSON.stringify(resource.name)}, typeId: RESOURCE_SYSTEM });\\`\n ResourceId constant systemId = ResourceId.wrap(${systemId});\n `;\n}\n\nexport type AbiToInterfaceOptions = {\n name: string;\n systemId?: Hex;\n abi: Abi;\n};\n\nexport function abiToInterface({ name, systemId, abi }: AbiToInterfaceOptions): string {\n const imports = systemId ? [`{ ResourceId } from \"@latticexyz/store/src/ResourceId.sol\"`] : [];\n const errors = abi.filter((item): item is AbiError => item.type === \"error\");\n const functions = abi.filter((item): item is AbiFunction => item.type === \"function\");\n\n return `\n ${renderedSolidityHeader}\n\n ${imports.map((item) => `import ${item};`).join(\"\\n\")}\n\n ${systemId ? formatSystemId(systemId) : \"\"}\n\n interface ${name} {\n ${errors.map((item) => `${formatAbiItem(item)};`).join(\"\\n\")}\n\n ${functions\n .map((item) => {\n if ([...item.inputs, ...item.outputs].some((param) => param.type.startsWith(\"tuple\"))) {\n return `// TODO: replace tuple with struct\\n// ${formatFunction(item)};`;\n }\n return `${formatFunction(item)};`;\n })\n .join(\"\\n\")}\n }\n `;\n}\n","import path from \"node:path\";\n\n// This will probably break for backslash-escaped POSIX paths,\n// but we'll worry about that later.\nfunction winToPosix(segment: string): string {\n return segment.replaceAll(path.win32.sep, path.posix.sep);\n}\n\nexport function renderImportPath(basePath: string, ...segments: readonly string[]): string {\n // Solidity compiler expects POSIX paths\n const fullPath = path.posix\n .join(winToPosix(basePath), ...segments.map(winToPosix))\n // remove trailing slash\n .replace(/\\/$/, \"\");\n\n // `path.join` strips the leading `./`\n // so if we started with a relative path, make it relative again\n if (basePath.startsWith(\".\")) {\n const relativePath = \"./\" + fullPath;\n return relativePath.replace(/^(\\.\\/)+\\./, \".\");\n }\n\n return fullPath;\n}\n","import { ImportDatum, StaticResourceData, RenderKeyTuple, RenderType } from \"./types\";\nimport { resourceToHex } from \"../../resourceToHex\";\nimport { hexToResource } from \"../../hexToResource\";\nimport { renderImportPath } from \"./renderImportPath\";\n\n/**\n * Common header for all codegenerated solidity files\n */\nexport const renderedSolidityHeader = `// SPDX-License-Identifier: MIT\npragma solidity >=0.8.24;\n\n/* Autogenerated file. Do not edit manually. */`;\n\n/**\n * Renders a list of lines\n */\nexport function renderList<T>(list: T[], renderItem: (item: T, index: number) => string): string {\n return internalRenderList(\"\", list, renderItem);\n}\n\n/**\n * Renders a comma-separated list of arguments for solidity functions, ignoring empty and undefined ones\n */\nexport function renderArguments(args: (string | undefined)[]): string {\n const filteredArgs = args.filter((arg) => arg !== undefined && arg !== \"\") as string[];\n return internalRenderList(\",\", filteredArgs, (arg) => arg);\n}\n\ninterface RenderedCommonData {\n /** `_tableId` variable prefixed with its type (empty string if absent) */\n _typedTableId: string;\n /** Comma-separated table key names prefixed with their types (empty string if 0 keys) */\n _typedKeyArgs: string;\n /** Definition and initialization of the dynamic `_keyTuple` bytes32 array */\n _keyTupleDefinition: string;\n}\n\n/**\n * Renders some solidity statements commonly used within table libraries\n * @param param0.staticResourceData static data about the table library\n * @param param0.keyTuple key tuple of the table library\n * @returns Rendered statement strings\n */\nexport function renderCommonData({\n staticResourceData,\n keyTuple,\n}: {\n staticResourceData?: StaticResourceData;\n keyTuple: RenderKeyTuple[];\n}): RenderedCommonData {\n // static resource means static tableId as well, and no tableId arguments\n const _typedTableId = staticResourceData ? \"\" : \"ResourceId _tableId\";\n const _typedKeyArgs = renderArguments(keyTuple.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));\n\n const _keyTupleDefinition = `\n bytes32[] memory _keyTuple = new bytes32[](${keyTuple.length});\n ${renderList(keyTuple, (key, index) => `_keyTuple[${index}] = ${renderValueTypeToBytes32(key.name, key)};`)}\n `;\n\n return {\n _typedTableId,\n _typedKeyArgs,\n _keyTupleDefinition,\n };\n}\n\n/**\n * Aggregates, deduplicates and renders imports for symbols per path.\n * Identical symbols from different paths are NOT handled, they should be checked before rendering.\n */\nexport function renderImports(imports: ImportDatum[]): string {\n // Aggregate symbols by import path, also deduplicating them\n const aggregatedImports = new Map<string, Set<string>>();\n for (const { symbol, path } of imports) {\n if (!aggregatedImports.has(path)) {\n aggregatedImports.set(path, new Set());\n }\n aggregatedImports.get(path)?.add(symbol);\n }\n // Render imports\n const renderedImports = [];\n for (const [path, symbols] of aggregatedImports) {\n const renderedSymbols = [...symbols].join(\", \");\n renderedImports.push(`import { ${renderedSymbols} } from \"${renderImportPath(path)}\";`);\n }\n return renderedImports.join(\"\\n\");\n}\n\ninterface RenderWithStoreCallbackData {\n /** `_store` variable prefixed with its type (undefined if library name) */\n _typedStore: string | undefined;\n /** `_store` variable (undefined if library name) */\n _store: string;\n /** Empty string if storeArgument is false, otherwise `\" (using the specified store)\"` */\n _commentSuffix: string;\n /** Prefix to differentiate different kinds of store usage within methods */\n _methodNamePrefix: string;\n /** Whether FieldLayout variable should be passed to store methods */\n _useExplicitFieldLayout?: boolean;\n}\n\n/**\n * Renders several versions of the callback's result, which access Store in different ways\n * @param storeArgument whether to render a version with `IStore _store` as an argument\n * @param callback renderer for a method which uses store\n * @returns Concatenated results of all callback calls\n */\nexport function renderWithStore(\n storeArgument: boolean,\n callback: (data: RenderWithStoreCallbackData) => string,\n): string {\n let result = \"\";\n result += callback({ _typedStore: undefined, _store: \"StoreSwitch\", _commentSuffix: \"\", _methodNamePrefix: \"\" });\n result += callback({\n _typedStore: undefined,\n _store: \"StoreCore\",\n _commentSuffix: \"\",\n _methodNamePrefix: \"_\",\n _useExplicitFieldLayout: true,\n });\n\n if (storeArgument) {\n result +=\n \"\\n\" +\n callback({\n _typedStore: \"IStore _store\",\n _store: \"_store\",\n _commentSuffix: \" (using the specified store)\",\n _methodNamePrefix: \"\",\n });\n }\n\n return result;\n}\n\n/**\n * Renders several versions of the callback's result, which have different method name suffixes\n * @param withSuffixlessFieldMethods whether to render methods with an empty suffix\n * @param fieldName name of the field which the methods access, used for a suffix\n * @param callback renderer for a method to be suffixed\n * @returns Concatenated results of all callback calls\n */\nexport function renderWithFieldSuffix(\n withSuffixlessFieldMethods: boolean,\n fieldName: string,\n callback: (_methodNameSuffix: string) => string,\n): string {\n const methodNameSuffix = `${fieldName[0].toUpperCase()}${fieldName.slice(1)}`;\n let result = \"\";\n result += callback(methodNameSuffix);\n\n if (withSuffixlessFieldMethods) {\n result += \"\\n\" + callback(\"\");\n }\n\n return result;\n}\n\n/**\n * Renders `_tableId` definition of the given table.\n * @param param0 static resource data needed to construct the table ID\n */\nexport function renderTableId({\n namespace,\n name,\n offchainOnly,\n}: Pick<StaticResourceData, \"namespace\" | \"name\" | \"offchainOnly\">): string {\n const tableId = resourceToHex({\n type: offchainOnly ? \"offchainTable\" : \"table\",\n namespace,\n name,\n });\n // turn table ID back into arguments that would be valid in `WorldResourceIdLib.encode` (like truncated names)\n const resource = hexToResource(tableId);\n return `\n // Hex below is the result of \\`WorldResourceIdLib.encode({ namespace: ${JSON.stringify(\n resource.namespace,\n )}, name: ${JSON.stringify(resource.name)}, typeId: ${offchainOnly ? \"RESOURCE_OFFCHAIN_TABLE\" : \"RESOURCE_TABLE\"} });\\`\n ResourceId constant _tableId = ResourceId.wrap(${tableId});\n `;\n}\n\n/**\n * Renders solidity typecasts to get from the given type to `bytes32`\n * @param name variable name to be typecasted\n * @param param1 type data\n */\nexport function renderValueTypeToBytes32(\n name: string,\n { typeUnwrap, internalTypeId }: Pick<RenderType, \"typeUnwrap\" | \"internalTypeId\">,\n): string {\n const innerText = typeUnwrap.length ? `${typeUnwrap}(${name})` : name;\n\n if (internalTypeId === \"bytes32\") {\n return innerText;\n } else if (/^bytes\\d{1,2}$/.test(internalTypeId)) {\n return `bytes32(${innerText})`;\n } else if (/^uint\\d{1,3}$/.test(internalTypeId)) {\n return `bytes32(uint256(${innerText}))`;\n } else if (/^int\\d{1,3}$/.test(internalTypeId)) {\n return `bytes32(uint256(int256(${innerText})))`;\n } else if (internalTypeId === \"address\") {\n return `bytes32(uint256(uint160(${innerText})))`;\n } else if (internalTypeId === \"bool\") {\n return `_boolToBytes32(${innerText})`;\n } else {\n throw new Error(`Unknown value type id ${internalTypeId}`);\n }\n}\n\n/**\n * Whether the storage representation of the given solidity type is left aligned\n */\nexport function isLeftAligned(field: Pick<RenderType, \"internalTypeId\">): boolean {\n return /^bytes\\d{1,2}$/.test(field.internalTypeId);\n}\n\n/**\n * The number of padding bits in the storage representation of a right-aligned solidity type\n */\nexport function getLeftPaddingBits(field: Pick<RenderType, \"internalTypeId\" | \"staticByteLength\">): number {\n if (isLeftAligned(field)) {\n return 0;\n } else {\n return 256 - field.staticByteLength * 8;\n }\n}\n\n/**\n * Internal helper to render `lineTerminator`-separated list of items mapped by `renderItem`\n */\nfunction internalRenderList<T>(\n lineTerminator: string,\n list: T[],\n renderItem: (item: T, index: number) => string,\n): string {\n return list\n .map((item, index) => renderItem(item, index) + (index === list.length - 1 ? \"\" : lineTerminator))\n .join(\"\\n\");\n}\n","import { renderedSolidityHeader } from \"./common\";\n\n// importing this from config or store would be a cyclic dependency :(\ntype Enums = {\n readonly [name: string]: readonly [string, ...string[]];\n};\n\n/**\n * Render a list of enum data as solidity enum definitions\n */\nexport function renderEnums(enums: Enums): string {\n const enumDefinitions = Object.entries(enums).map(\n ([name, values]) => `\n enum ${name} {\n ${values.join(\", \")}\n }\n `,\n );\n\n return `\n ${renderedSolidityHeader}\n ${enumDefinitions.join(\"\")}\n `;\n}\n","import { RenderField, RenderKeyTuple, RenderType } from \"./types\";\n\n/**\n * Renders the necessary helper functions to typecast to/from the types of given fields and keys\n */\nexport function renderTypeHelpers(options: { fields: RenderField[]; keyTuple: RenderKeyTuple[] }): string {\n const { fields, keyTuple } = options;\n\n let result = \"\";\n\n for (const wrappingHelper of getWrappingHelpers([...fields, ...keyTuple])) {\n result += wrappingHelper;\n }\n\n // bool is special - it's the only primitive value type that can't be typecasted to/from\n if (fields.some(({ internalTypeId }) => internalTypeId.match(\"bool\"))) {\n result += `\n /**\n * @notice Cast a value to a bool.\n * @dev Boolean values are encoded as uint8 (1 = true, 0 = false), but Solidity doesn't allow casting between uint8 and bool.\n * @param value The uint8 value to convert.\n * @return result The boolean value.\n */\n function _toBool(uint8 value) pure returns (bool result) {\n assembly {\n result := value\n }\n }\n `;\n }\n if (keyTuple.some(({ internalTypeId }) => internalTypeId.match(\"bool\"))) {\n result += `\n /**\n * @notice Cast a bool to a bytes32.\n * @dev The boolean value is casted to a bytes32 value with 0 or 1 at the least significant bit.\n */\n function _boolToBytes32(bool value) pure returns (bytes32 result) {\n assembly {\n result := value\n }\n }\n `;\n }\n\n return result;\n}\n\nfunction getWrappingHelpers(array: RenderType[]): string[] {\n const wrappers = new Map<string, string>();\n const unwrappers = new Map<string, string>();\n for (const { typeWrappingData, typeWrap, typeUnwrap, internalTypeId } of array) {\n if (!typeWrappingData) continue;\n const { kind } = typeWrappingData;\n\n if (kind === \"staticArray\") {\n const { elementType, staticLength } = typeWrappingData;\n wrappers.set(typeWrap, renderWrapperStaticArray(typeWrap, elementType, staticLength, internalTypeId));\n unwrappers.set(typeUnwrap, renderUnwrapperStaticArray(typeUnwrap, elementType, staticLength, internalTypeId));\n }\n }\n\n return [...wrappers.values(), ...unwrappers.values()];\n}\n\n/**\n * Renders a function to cast a dynamic array to a static array.\n * @param functionName name of the function to be rendered\n * @param elementType type of the array's element\n * @param staticLength length of the static array\n * @param internalTypeId solidity type name of the dynamic array\n * @returns\n */\nfunction renderWrapperStaticArray(\n functionName: string,\n elementType: string,\n staticLength: number,\n internalTypeId: string,\n): string {\n // WARNING: ensure this still works if changing major solidity versions!\n // (the memory layout for static arrays may change)\n return `\n /**\n * @notice Cast a dynamic array to a static array.\n * @dev In memory static arrays are just dynamic arrays without the 32 length bytes,\n * so this function moves the pointer to the first element of the dynamic array.\n * If the length of the dynamic array is smaller than the static length,\n * the function returns an uninitialized array to avoid memory corruption.\n * @param _value The dynamic array to cast.\n * @return _result The static array.\n */\n function ${functionName}(\n ${internalTypeId} memory _value\n ) pure returns (\n ${elementType}[${staticLength}] memory _result\n ) {\n if (_value.length < ${staticLength}) {\n // return an uninitialized array if the length is smaller than the fixed length to avoid memory corruption\n return _result;\n } else {\n // in memory static arrays are just dynamic arrays without the 32 length bytes\n // (without the length check this could lead to memory corruption)\n assembly {\n _result := add(_value, 0x20)\n }\n }\n }\n `;\n}\n\n/**\n * Renders a function to cast a static array to a dynamic array.\n * @param functionName name of the function to be rendered\n * @param elementType type of the array's element\n * @param staticLength length of the static array\n * @param internalTypeId solidity type name of the dynamic array\n * @returns\n */\nfunction renderUnwrapperStaticArray(\n functionName: string,\n elementType: string,\n staticLength: number,\n internalTypeId: string,\n): string {\n // byte length for memory copying (more efficient than a loop)\n const byteLength = staticLength * 32;\n // TODO to optimize memory usage consider generalizing TightEncoder to a render-time utility\n return `\n /**\n * @notice Copy a static array to a dynamic array.\n * @dev Static arrays don't have a length prefix, so this function copies the memory from the static array to a new dynamic array.\n * @param _value The static array to copy.\n * @return _result The dynamic array.\n */ \n function ${functionName}(\n ${elementType}[${staticLength}] memory _value\n ) pure returns (\n ${internalTypeId} memory _result\n ) {\n _result = new ${internalTypeId}(${staticLength});\n uint256 fromPointer;\n uint256 toPointer;\n assembly {\n fromPointer := _value\n toPointer := add(_result, 0x20)\n }\n Memory.copy(fromPointer, toPointer, ${byteLength});\n }\n `;\n}\n","import { SchemaType } from \"@latticexyz/schema-type/deprecated\";\n\nexport const schemaTypesToRecsTypeStrings: Record<SchemaType, string> = {\n [SchemaType.UINT8]: \"RecsType.Number\",\n [SchemaType.UINT16]: \"RecsType.Number\",\n [SchemaType.UINT24]: \"RecsType.Number\",\n [SchemaType.UINT32]: \"RecsType.Number\",\n [SchemaType.UINT40]: \"RecsType.Number\",\n [SchemaType.UINT48]: \"RecsType.Number\",\n [SchemaType.UINT56]: \"RecsType.BigInt\",\n [SchemaType.UINT64]: \"RecsType.BigInt\",\n [SchemaType.UINT72]: \"RecsType.BigInt\",\n [SchemaType.UINT80]: \"RecsType.BigInt\",\n [SchemaType.UINT88]: \"RecsType.BigInt\",\n [SchemaType.UINT96]: \"RecsType.BigInt\",\n [SchemaType.UINT104]: \"RecsType.BigInt\",\n [SchemaType.UINT112]: \"RecsType.BigInt\",\n [SchemaType.UINT120]: \"RecsType.BigInt\",\n [SchemaType.UINT128]: \"RecsType.BigInt\",\n [SchemaType.UINT136]: \"RecsType.BigInt\",\n [SchemaType.UINT144]: \"RecsType.BigInt\",\n [SchemaType.UINT152]: \"RecsType.BigInt\",\n [SchemaType.UINT160]: \"RecsType.BigInt\",\n [SchemaType.UINT168]: \"RecsType.BigInt\",\n [SchemaType.UINT176]: \"RecsType.BigInt\",\n [SchemaType.UINT184]: \"RecsType.BigInt\",\n [SchemaType.UINT192]: \"RecsType.BigInt\",\n [SchemaType.UINT200]: \"RecsType.BigInt\",\n [SchemaType.UINT208]: \"RecsType.BigInt\",\n [SchemaType.UINT216]: \"RecsType.BigInt\",\n [SchemaType.UINT224]: \"RecsType.BigInt\",\n [SchemaType.UINT232]: \"RecsType.BigInt\",\n [SchemaType.UINT240]: \"RecsType.BigInt\",\n [SchemaType.UINT248]: \"RecsType.BigInt\",\n [SchemaType.UINT256]: \"RecsType.BigInt\",\n [SchemaType.INT8]: \"RecsType.Number\",\n [SchemaType.INT16]: \"RecsType.Number\",\n [SchemaType.INT24]: \"RecsType.Number\",\n [SchemaType.INT32]: \"RecsType.Number\",\n [SchemaType.INT40]: \"RecsType.Number\",\n [SchemaType.INT48]: \"RecsType.Number\",\n [SchemaType.INT56]: \"RecsType.BigInt\",\n [SchemaType.INT64]: \"RecsType.BigInt\",\n [SchemaType.INT72]: \"RecsType.BigInt\",\n [SchemaType.INT80]: \"RecsType.BigInt\",\n [SchemaType.INT88]: \"RecsType.BigInt\",\n [SchemaType.INT96]: \"RecsType.BigInt\",\n [SchemaType.INT104]: \"RecsType.BigInt\",\n [SchemaType.INT112]: \"RecsType.BigInt\",\n [SchemaType.INT120]: \"RecsType.BigInt\",\n [SchemaType.INT128]: \"RecsType.BigInt\",\n [SchemaType.INT136]: \"RecsType.BigInt\",\n [SchemaType.INT144]: \"RecsType.BigInt\",\n [SchemaType.INT152]: \"RecsType.BigInt\",\n [SchemaType.INT160]: \"RecsType.BigInt\",\n [SchemaType.INT168]: \"RecsType.BigInt\",\n [SchemaType.INT176]: \"RecsType.BigInt\",\n [SchemaType.INT184]: \"RecsType.BigInt\",\n [SchemaType.INT192]: \"RecsType.BigInt\",\n [SchemaType.INT200]: \"RecsType.BigInt\",\n [SchemaType.INT208]: \"RecsType.BigInt\",\n [SchemaType.INT216]: \"RecsType.BigInt\",\n [SchemaType.INT224]: \"RecsType.BigInt\",\n [SchemaType.INT232]: \"RecsType.BigInt\",\n [SchemaType.INT240]: \"RecsType.BigInt\",\n [SchemaType.INT248]: \"RecsType.BigInt\",\n [SchemaType.INT256]: \"RecsType.BigInt\",\n [SchemaType.BYTES1]: \"RecsType.String\",\n [SchemaType.BYTES2]: \"RecsType.String\",\n [SchemaType.BYTES3]: \"RecsType.String\",\n [SchemaType.BYTES4]: \"RecsType.String\",\n [SchemaType.BYTES5]: \"RecsType.String\",\n [SchemaType.BYTES6]: \"RecsType.String\",\n [SchemaType.BYTES7]: \"RecsType.String\",\n [SchemaType.BYTES8]: \"RecsType.String\",\n [SchemaType.BYTES9]: \"RecsType.String\",\n [SchemaType.BYTES10]: \"RecsType.String\",\n [SchemaType.BYTES11]: \"RecsType.String\",\n [SchemaType.BYTES12]: \"RecsType.String\",\n [SchemaType.BYTES13]: \"RecsType.String\",\n [SchemaType.BYTES14]: \"RecsType.String\",\n [SchemaType.BYTES15]: \"RecsType.String\",\n [SchemaType.BYTES16]: \"RecsType.String\",\n [SchemaType.BYTES17]: \"RecsType.String\",\n [SchemaType.BYTES18]: \"RecsType.String\",\n [SchemaType.BYTES19]: \"RecsType.String\",\n [SchemaType.BYTES20]: \"RecsType.String\",\n [SchemaType.BYTES21]: \"RecsType.String\",\n [SchemaType.BYTES22]: \"RecsType.String\",\n [SchemaType.BYTES23]: \"RecsType.String\",\n [SchemaType.BYTES24]: \"RecsType.String\",\n [SchemaType.BYTES25]: \"RecsType.String\",\n [SchemaType.BYTES26]: \"RecsType.String\",\n [SchemaType.BYTES27]: \"RecsType.String\",\n [SchemaType.BYTES28]: \"RecsType.String\",\n [SchemaType.BYTES29]: \"RecsType.String\",\n [SchemaType.BYTES30]: \"RecsType.String\",\n [SchemaType.BYTES31]: \"RecsType.String\",\n [SchemaType.BYTES32]: \"RecsType.String\",\n [SchemaType.BOOL]: \"RecsType.Boolean\",\n [SchemaType.ADDRESS]: \"RecsType.String\",\n [SchemaType.UINT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES1_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES2_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES3_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES4_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES5_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES6_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES7_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES8_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES9_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES10_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES11_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES12_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES13_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES14_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES15_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES16_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES17_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES18_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES19_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES20_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES21_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES22_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES23_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES24_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES25_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES26_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES27_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES28_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES29_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES30_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES31_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES32_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BOOL_ARRAY]: \"RecsType.T\", // no boolean array\n [SchemaType.ADDRESS_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES]: \"RecsType.String\",\n [SchemaType.STRING]: \"RecsType.String\",\n};\n","import { parse, visit } from \"@solidity-parser/parser\";\nimport type {\n ContractDefinition,\n SourceUnit,\n TypeName,\n VariableDeclaration,\n} from \"@solidity-parser/parser/dist/src/ast-types\";\nimport { MUDError } from \"../../errors\";\n\nexport interface ContractInterfaceFunction {\n name: string;\n parameters: string[];\n stateMutability: string;\n returnParameters: string[];\n}\n\nexport interface ContractInterfaceError {\n name: string;\n parameters: string[];\n}\n\ninterface SymbolImport {\n symbol: string;\n path: string;\n}\n\n/**\n * Parse the contract data to get the functions necessary to generate an interface,\n * and symbols to import from the original contract.\n * @param source contents of a file with the solidity contract\n * @param contractName name of the contract\n * @returns interface data\n */\nexport function contractToInterface(\n source: string,\n contractName: string,\n): {\n functions: ContractInterfaceFunction[];\n errors: ContractInterfaceError[];\n symbolImports: SymbolImport[];\n} {\n const ast = parse(source);\n const contractNode = findContractNode(ast, contractName);\n let symbolImports: SymbolImport[] = [];\n const functions: ContractInterfaceFunction[] = [];\n const errors: ContractInterfaceError[] = [];\n\n if (!contractNode) {\n throw new MUDError(`Contract not found: ${contractName}`);\n }\n\n visit(contractNode, {\n FunctionDefinition({\n name,\n visibility,\n parameters,\n stateMutability,\n returnParameters,\n isConstructor,\n isFallback,\n isReceiveEther,\n }) {\n try {\n // skip constructor and fallbacks\n if (isConstructor || isFallback || isReceiveEther) return;\n // forbid default visibility (this check might be unnecessary, modern solidity already disallows this)\n if (visibility === \"default\") throw new MUDError(`Visibility is not specified`);\n\n if (visibility === \"external\" || visibility === \"public\") {\n functions.push({\n name: name === null ? \"\" : name,\n parameters: parameters.map(parseParameter),\n stateMutability: stateMutability || \"\",\n returnParameters: returnParameters === null ? [] : returnParameters.map(parseParameter),\n });\n\n for (const { typeName } of parameters.concat(returnParameters ?? [])) {\n const symbols = typeNameToSymbols(typeName);\n symbolImports = symbolImports.concat(symbolsToImports(ast, symbols));\n }\n }\n } catch (error: unknown) {\n if (error instanceof MUDError) {\n error.message = `Function \"${name}\" in contract \"${contractName}\": ${error.message}`;\n }\n throw error;\n }\n },\n CustomErrorDefinition({ name, parameters }) {\n errors.push({\n name,\n parameters: parameters.map(parseParameter),\n });\n\n for (const parameter of parameters) {\n const symbols = typeNameToSymbols(parameter.typeName);\n symbolImports = symbolImports.concat(symbolsToImports(ast, symbols));\n }\n },\n });\n\n return {\n functions,\n errors,\n symbolImports,\n };\n}\n\nexport function findContractNode(ast: SourceUnit, contractName: string): ContractDefinition | undefined {\n let contract: ContractDefinition | undefined = undefined;\n\n visit(ast, {\n ContractDefinition(node) {\n if (node.name === contractName) {\n contract = node;\n }\n },\n });\n\n return contract;\n}\n\nfunction parseParameter({ name, typeName, storageLocation }: VariableDeclaration): string {\n let typedNameWithLocation = \"\";\n\n const { name: flattenedTypeName, stateMutability } = flattenTypeName(typeName);\n // type name (e.g. uint256)\n typedNameWithLocation += flattenedTypeName;\n // optional mutability (e.g. address payable)\n if (stateMutability !== null) {\n typedNameWithLocation += ` ${stateMutability}`;\n }\n // location, when relevant (e.g. string memory)\n if (storageLocation !== null) {\n typedNameWithLocation += ` ${storageLocation}`;\n }\n // optional variable name\n if (name !== null) {\n typedNameWithLocation += ` ${name}`;\n }\n\n return typedNameWithLocation;\n}\n\nfunction flattenTypeName(typeName: TypeName | null): { name: string; stateMutability: string | null } {\n if (typeName === null) {\n return {\n name: \"\",\n stateMutability: null,\n };\n }\n if (typeName.type === \"ElementaryTypeName\") {\n return {\n name: typeName.name,\n stateMutability: typeName.stateMutability,\n };\n } else if (typeName.type === \"UserDefinedTypeName\") {\n return {\n name: typeName.namePath,\n stateMutability: null,\n };\n } else if (typeName.type === \"ArrayTypeName\") {\n let length = \"\";\n if (typeName.length?.type === \"NumberLiteral\") {\n length = typeName.length.number;\n } else if (typeName.length?.type === \"Identifier\") {\n length = typeName.length.name;\n }\n\n const { name, stateMutability } = flattenTypeName(typeName.baseTypeName);\n return {\n name: `${name}[${length}]`,\n stateMutability,\n };\n } else {\n // TODO function types are unsupported but could be useful\n throw new MUDError(`Invalid typeName.type ${typeName.type}`);\n }\n}\n\n// Get symbols that need to be imported for given typeName\nfunction typeNameToSymbols(typeName: TypeName | null): string[] {\n if (typeName?.type === \"UserDefinedTypeName\") {\n // split is needed to get a library, if types are internal to it\n const symbol = typeName.namePath.split(\".\")[0];\n return [symbol];\n } else if (typeName?.type === \"ArrayTypeName\") {\n const symbols = typeNameToSymbols(typeName.baseTypeName);\n // array types can also use symbols (constants) for length\n if (typeName.length?.type === \"Identifier\") {\n const innerTypeName = typeName.length.name;\n symbols.push(innerTypeName.split(\".\")[0]);\n }\n return symbols;\n } else {\n return [];\n }\n}\n\n// Get imports for given symbols.\n// To avoid circular dependencies of interfaces on their implementations,\n// symbols used for args/returns must always be imported from an auxiliary file.\n// To avoid parsing the entire project to build dependencies,\n// symbols must be imported with an explicit `import { symbol } from ...`\nfunction symbolsToImports(ast: SourceUnit, symbols: string[]): SymbolImport[] {\n const imports: SymbolImport[] = [];\n\n for (const symbol of symbols) {\n let symbolImport: SymbolImport | undefined;\n\n visit(ast, {\n ImportDirective({ path, symbolAliases }) {\n if (symbolAliases) {\n for (const symbolAndAlias of symbolAliases) {\n // either check the alias, or the original symbol if there's no alias\n const symbolAlias = symbolAndAlias[1] || symbolAndAlias[0];\n if (symbol === symbolAlias) {\n symbolImport = {\n // always use the original symbol for interface imports\n symbol: symbolAndAlias[0],\n path,\n };\n return;\n }\n }\n }\n },\n });\n\n if (symbolImport) {\n imports.push(symbolImport);\n } else {\n throw new MUDError(`Symbol \"${symbol}\" has no explicit import`);\n }\n }\n\n return imports;\n}\n","import prettier from \"prettier\";\nimport prettierPluginSolidity from \"prettier-plugin-solidity\";\n\n/**\n * Formats solidity code using prettier\n * @param content solidity code\n * @param prettierConfigPath optional path to a prettier config\n * @returns formatted solidity code\n */\nexport async function formatSolidity(content: string, prettierConfigPath?: string): Promise<string> {\n let config;\n if (prettierConfigPath) {\n config = await prettier.resolveConfig(prettierConfigPath);\n }\n try {\n return prettier.format(content, {\n plugins: [prettierPluginSolidity],\n parser: \"solidity-parse\",\n\n printWidth: 120,\n semi: true,\n tabWidth: 2,\n useTabs: false,\n bracketSpacing: true,\n\n ...config,\n });\n } catch (error) {\n let message;\n if (error instanceof Error) {\n message = error.message;\n } else {\n message = error;\n }\n console.log(`Error during output formatting: ${message}`);\n return content;\n }\n}\n\n/**\n * Formats typescript code using prettier\n * @param content typescript code\n * @returns formatted typescript code\n */\nexport async function formatTypescript(content: string): Promise<string> {\n return prettier.format(content, {\n parser: \"typescript\",\n });\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { formatSolidity, formatTypescript } from \"./format\";\nimport { debug } from \"../debug\";\n\n/**\n * Formats solidity code using prettier and write it to a file\n * @param output solidity code\n * @param fullOutputPath full path to the output file\n * @param logPrefix prefix for debug logs\n */\nexport async function formatAndWriteSolidity(output: string, fullOutputPath: string, logPrefix: string): Promise<void> {\n const formattedOutput = await formatSolidity(output);\n\n await fs.mkdir(path.dirname(fullOutputPath), { recursive: true });\n\n await fs.writeFile(fullOutputPath, formattedOutput);\n debug(`${logPrefix}: ${fullOutputPath}`);\n}\n\n/**\n * Formats typescript code using prettier and write it to a file\n * @param output typescript code\n * @param fullOutputPath full path to the output file\n * @param logPrefix prefix for debug logs\n */\nexport async function formatAndWriteTypescript(\n output: string,\n fullOutputPath: string,\n logPrefix: string,\n): Promise<void> {\n const formattedOutput = await formatTypescript(output);\n\n await fs.mkdir(path.dirname(fullOutputPath), { recursive: true });\n\n await fs.writeFile(fullOutputPath, formattedOutput);\n debug(`${logPrefix}: ${fullOutputPath}`);\n}\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"codegen\");\nexport const error = parentDebug.extend(\"codegen\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n"],"mappings":"+HACA,OAAqC,iBAAAA,EAAe,sBAAAC,MAA0B,UCD9E,OAAOC,MAAU,YAIjB,SAASC,EAAWC,EAAyB,CAC3C,OAAOA,EAAQ,WAAWF,EAAK,MAAM,IAAKA,EAAK,MAAM,GAAG,CAC1D,CAEO,SAASG,EAAiBC,KAAqBC,EAAqC,CAEzF,IAAMC,EAAWN,EAAK,MACnB,KAAKC,EAAWG,CAAQ,EAAG,GAAGC,EAAS,IAAIJ,CAAU,CAAC,EAEtD,QAAQ,MAAO,EAAE,EAIpB,OAAIG,EAAS,WAAW,GAAG,GACJ,KAAOE,GACR,QAAQ,aAAc,GAAG,EAGxCA,CACT,CCfO,IAAMC,EAAyB;AAAA;AAAA;AAAA,iDAQ/B,SAASC,EAAcC,EAAWC,EAAwD,CAC/F,OAAOC,EAAmB,GAAIF,EAAMC,CAAU,CAChD,CAKO,SAASE,EAAgBC,EAAsC,CACpE,IAAMC,EAAeD,EAAK,OAAQE,GAAQA,IAAQ,QAAaA,IAAQ,EAAE,EACzE,OAAOJ,EAAmB,IAAKG,EAAeC,GAAQA,CAAG,CAC3D,CAiBO,SAASC,GAAiB,CAC/B,mBAAAC,EACA,SAAAC,CACF,EAGuB,CAErB,IAAMC,EAAgBF,EAAqB,GAAK,sBAC1CG,EAAgBR,E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AAgBE,CAAe,EAClDI,EAAM,GAAGL,MAAcD,GAAgB,CACzC,CAQA,eAAsBO,GACpBR,EACAC,EACAC,EACe,CACf,IAAMC,EAAkB,MAAMM,EAAiBT,CAAM,EAErD,MAAMK,EAAG,MAAMC,EAAK,QAAQL,CAAc,EAAG,CAAE,UAAW,EAAK,CAAC,EAEhE,MAAMI,EAAG,UAAUJ,EAAgBE,CAAe,EAClDI,EAAM,GAAGL,MAAcD,GAAgB,CACzC","names":["formatAbiItem","formatAbiParameter","path","winToPosix","segment","renderImportPath","basePath","segments","fullPath","renderedSolidityHeader","renderList","list","renderItem","internalRenderList","renderArguments","args","filteredArgs","arg","renderCommonData","staticResourceData","keyTuple","_typedTableId","_typedKeyArgs","name","typeWithLocation","_keyTupleDefinition","key","index","renderValueTypeToBytes32","renderImports","imports","aggregatedImports","symbol","path","renderedImports","symbols","renderedSymbols","renderImportPath","renderWithStore","storeArgument","callback","result","renderWithFieldSuffix","withSuffixlessFieldMethods","fieldName","methodNameSuffix","renderTableId","namespace","offchainOnly","tableId","resourceToHex","resource","hexToResource","typeUnwrap","internalTypeId","innerText","isLeftAligned","field","getLeftPaddingBits","lineTerminator","item","formatParam","param","formatAbiParameter","formatFunction","item","params","returns","formatSystemId","systemId","resource","hexToResource","abiToInterface","name","abi","imports","errors","functions","renderedSolidityHeader","formatAbiItem","renderEnums","enums","enumDefinitions","name","values","renderedSolidityHeader","renderTypeHelpers","options","fields","keyTuple","result","wrappingHelper","getWrappingHelpers","internalTypeId","array","wrappers","unwrappers","typeWrappingData","typeWrap","typeUnwrap","kind","elementType","staticLength","renderWrapperStaticArray","renderUnwrapperStaticArray","functionName","byteLength","SchemaType","schemaTypesToRecsTypeStrings","parse","visit","contractToInterface","source","contractName","ast","parse","contractNode","findContractNode","symbolImports","functions","errors","MUDError","visit","name","visibility","parameters","stateMutability","returnParameters","isConstructor","isFallback","isReceiveEther","parseParameter","typeName","symbols","typeNameToSymbols","symbolsToImports","error","parameter","contract","node","storageLocation","typedNameWithLocation","flattenedTypeName","flattenTypeName","length","innerTypeName","imports","symbol","symbolImport","path","symbolAliases","symbolAndAlias","symbolAlias","prettier","prettierPluginSolidity","formatSolidity","content","prettierConfigPath","config","error","message","formatTypescript","fs","path","debug","error","formatAndWriteSolidity","output","fullOutputPath","logPrefix","formattedOutput","formatSolidity","fs","path","debug","formatAndWriteTypescript","formatTypescript"]}
1
+ {"version":3,"sources":["../src/codegen/render-solidity/abiToInterface.ts","../src/codegen/render-solidity/renderImportPath.ts","../src/codegen/render-solidity/common.ts","../src/codegen/render-solidity/renderEnums.ts","../src/codegen/render-solidity/renderTypeHelpers.ts","../src/codegen/render-typescript/schemaTypesToRecsTypeStrings.ts","../src/codegen/utils/contractToInterface.ts","../src/codegen/utils/format.ts","../src/codegen/utils/formatAndWrite.ts","../src/codegen/debug.ts"],"sourcesContent":["import { AbiParameter, Hex } from \"viem\";\nimport { Abi, AbiError, AbiFunction, formatAbiItem, formatAbiParameter } from \"abitype\";\nimport { renderedSolidityHeader } from \"./common\";\nimport { hexToResource } from \"../../hexToResource\";\n\nfunction formatParam(param: AbiParameter): string {\n // return param.type === \"string\" || param.type === \"bytes\" || param.type === \"tuple\" || param.type.endsWith(\"]\")\n // ? `${formatAbiParameter(param)} memory`\n // : formatAbiParameter(param);\n return formatAbiParameter(param);\n}\n\nfunction formatFunction(item: AbiFunction): string {\n const params = item.inputs.map(formatParam).join(\", \");\n const returns = item.outputs.map(formatParam).join(\", \");\n return `function ${item.name}(${params}) external${returns.length ? ` returns (${returns})` : \"\"}`;\n}\n\nfunction formatSystemId(systemId: Hex): string {\n const resource = hexToResource(systemId);\n return `\n // equivalent to \\`WorldResourceIdLib.encode({ namespace: ${JSON.stringify(\n resource.namespace,\n )}, name: ${JSON.stringify(resource.name)}, typeId: RESOURCE_SYSTEM });\\`\n ResourceId constant systemId = ResourceId.wrap(${systemId});\n `;\n}\n\nexport type AbiToInterfaceOptions = {\n name: string;\n systemId?: Hex;\n abi: Abi;\n};\n\nexport function abiToInterface({ name, systemId, abi }: AbiToInterfaceOptions): string {\n const imports = systemId ? [`{ ResourceId } from \"@latticexyz/store/src/ResourceId.sol\"`] : [];\n const errors = abi.filter((item): item is AbiError => item.type === \"error\");\n const functions = abi.filter((item): item is AbiFunction => item.type === \"function\");\n\n return `\n ${renderedSolidityHeader}\n\n ${imports.map((item) => `import ${item};`).join(\"\\n\")}\n\n ${systemId ? formatSystemId(systemId) : \"\"}\n\n interface ${name} {\n ${errors.map((item) => `${formatAbiItem(item)};`).join(\"\\n\")}\n\n ${functions\n .map((item) => {\n if ([...item.inputs, ...item.outputs].some((param) => param.type.startsWith(\"tuple\"))) {\n return `// TODO: replace tuple with struct\\n// ${formatFunction(item)};`;\n }\n return `${formatFunction(item)};`;\n })\n .join(\"\\n\")}\n }\n `;\n}\n","import path from \"node:path\";\n\n// This will probably break for backslash-escaped POSIX paths,\n// but we'll worry about that later.\nfunction winToPosix(segment: string): string {\n return segment.replaceAll(path.win32.sep, path.posix.sep);\n}\n\nexport function renderImportPath(basePath: string, ...segments: readonly string[]): string {\n // Solidity compiler expects POSIX paths\n const fullPath = path.posix\n .join(winToPosix(basePath), ...segments.map(winToPosix))\n // remove trailing slash\n .replace(/\\/$/, \"\");\n\n // `path.join` strips the leading `./`\n // so if we started with a relative path, make it relative again\n if (basePath.startsWith(\".\")) {\n const relativePath = \"./\" + fullPath;\n return relativePath.replace(/^(\\.\\/)+\\./, \".\");\n }\n\n return fullPath;\n}\n","import { ImportDatum, StaticResourceData, RenderKeyTuple, RenderType } from \"./types\";\nimport { resourceToHex } from \"../../resourceToHex\";\nimport { hexToResource } from \"../../hexToResource\";\nimport { renderImportPath } from \"./renderImportPath\";\n\n/**\n * Common header for all codegenerated solidity files\n */\nexport const renderedSolidityHeader = `// SPDX-License-Identifier: MIT\npragma solidity >=0.8.24;\n\n/* Autogenerated file. Do not edit manually. */`;\n\n/**\n * Renders a list of lines\n */\nexport function renderList<T>(list: T[], renderItem: (item: T, index: number) => string): string {\n return internalRenderList(\"\", list, renderItem);\n}\n\n/**\n * Renders a comma-separated list of arguments for solidity functions, ignoring empty and undefined ones\n */\nexport function renderArguments(args: (string | undefined)[]): string {\n const filteredArgs = args.filter((arg) => arg !== undefined && arg !== \"\") as string[];\n return internalRenderList(\",\", filteredArgs, (arg) => arg);\n}\n\ninterface RenderedCommonData {\n /** `_tableId` variable prefixed with its type (empty string if absent) */\n _typedTableId: string;\n /** Comma-separated table key names prefixed with their types (empty string if 0 keys) */\n _typedKeyArgs: string;\n /** Definition and initialization of the dynamic `_keyTuple` bytes32 array */\n _keyTupleDefinition: string;\n}\n\n/**\n * Renders some solidity statements commonly used within table libraries\n * @param param0.staticResourceData static data about the table library\n * @param param0.keyTuple key tuple of the table library\n * @returns Rendered statement strings\n */\nexport function renderCommonData({\n staticResourceData,\n keyTuple,\n}: {\n staticResourceData?: StaticResourceData;\n keyTuple: RenderKeyTuple[];\n}): RenderedCommonData {\n // static resource means static tableId as well, and no tableId arguments\n const _typedTableId = staticResourceData ? \"\" : \"ResourceId _tableId\";\n const _typedKeyArgs = renderArguments(keyTuple.map(({ name, typeWithLocation }) => `${typeWithLocation} ${name}`));\n\n const _keyTupleDefinition = `\n bytes32[] memory _keyTuple = new bytes32[](${keyTuple.length});\n ${renderList(keyTuple, (key, index) => `_keyTuple[${index}] = ${renderValueTypeToBytes32(key.name, key)};`)}\n `;\n\n return {\n _typedTableId,\n _typedKeyArgs,\n _keyTupleDefinition,\n };\n}\n\n/**\n * Aggregates, deduplicates and renders imports for symbols per path.\n * Identical symbols from different paths are NOT handled, they should be checked before rendering.\n */\nexport function renderImports(imports: ImportDatum[]): string {\n // Aggregate symbols by import path, also deduplicating them\n const aggregatedImports = new Map<string, Set<string>>();\n for (const { symbol, path } of imports) {\n if (!aggregatedImports.has(path)) {\n aggregatedImports.set(path, new Set());\n }\n aggregatedImports.get(path)?.add(symbol);\n }\n // Render imports\n const renderedImports = [];\n for (const [path, symbols] of aggregatedImports) {\n const renderedSymbols = [...symbols].join(\", \");\n renderedImports.push(`import { ${renderedSymbols} } from \"${renderImportPath(path)}\";`);\n }\n return renderedImports.join(\"\\n\");\n}\n\ninterface RenderWithStoreCallbackData {\n /** `_store` variable prefixed with its type (undefined if library name) */\n _typedStore: string | undefined;\n /** `_store` variable (undefined if library name) */\n _store: string;\n /** Empty string if storeArgument is false, otherwise `\" (using the specified store)\"` */\n _commentSuffix: string;\n /** Prefix to differentiate different kinds of store usage within methods */\n _methodNamePrefix: string;\n /** Whether FieldLayout variable should be passed to store methods */\n _useExplicitFieldLayout?: boolean;\n}\n\n/**\n * Renders several versions of the callback's result, which access Store in different ways\n * @param storeArgument whether to render a version with `IStore _store` as an argument\n * @param callback renderer for a method which uses store\n * @returns Concatenated results of all callback calls\n */\nexport function renderWithStore(\n storeArgument: boolean,\n callback: (data: RenderWithStoreCallbackData) => string,\n): string {\n let result = \"\";\n result += callback({ _typedStore: undefined, _store: \"StoreSwitch\", _commentSuffix: \"\", _methodNamePrefix: \"\" });\n result += callback({\n _typedStore: undefined,\n _store: \"StoreCore\",\n _commentSuffix: \"\",\n _methodNamePrefix: \"_\",\n _useExplicitFieldLayout: true,\n });\n\n if (storeArgument) {\n result +=\n \"\\n\" +\n callback({\n _typedStore: \"IStore _store\",\n _store: \"_store\",\n _commentSuffix: \" (using the specified store)\",\n _methodNamePrefix: \"\",\n });\n }\n\n return result;\n}\n\n/**\n * Renders several versions of the callback's result, which have different method name suffixes\n * @param withSuffixlessFieldMethods whether to render methods with an empty suffix\n * @param fieldName name of the field which the methods access, used for a suffix\n * @param callback renderer for a method to be suffixed\n * @returns Concatenated results of all callback calls\n */\nexport function renderWithFieldSuffix(\n withSuffixlessFieldMethods: boolean,\n fieldName: string,\n callback: (_methodNameSuffix: string) => string,\n): string {\n const methodNameSuffix = `${fieldName[0].toUpperCase()}${fieldName.slice(1)}`;\n let result = \"\";\n result += callback(methodNameSuffix);\n\n if (withSuffixlessFieldMethods) {\n result += \"\\n\" + callback(\"\");\n }\n\n return result;\n}\n\n/**\n * Renders `_tableId` definition of the given table.\n * @param param0 static resource data needed to construct the table ID\n */\nexport function renderTableId({\n namespace,\n name,\n offchainOnly,\n}: Pick<StaticResourceData, \"namespace\" | \"name\" | \"offchainOnly\">): string {\n const tableId = resourceToHex({\n type: offchainOnly ? \"offchainTable\" : \"table\",\n namespace,\n name,\n });\n // turn table ID back into arguments that would be valid in `WorldResourceIdLib.encode` (like truncated names)\n const resource = hexToResource(tableId);\n return `\n // Hex below is the result of \\`WorldResourceIdLib.encode({ namespace: ${JSON.stringify(\n resource.namespace,\n )}, name: ${JSON.stringify(resource.name)}, typeId: ${offchainOnly ? \"RESOURCE_OFFCHAIN_TABLE\" : \"RESOURCE_TABLE\"} });\\`\n ResourceId constant _tableId = ResourceId.wrap(${tableId});\n `;\n}\n\n/**\n * Renders solidity typecasts to get from the given type to `bytes32`\n * @param name variable name to be typecasted\n * @param param1 type data\n */\nexport function renderValueTypeToBytes32(\n name: string,\n { typeUnwrap, internalTypeId }: Pick<RenderType, \"typeUnwrap\" | \"internalTypeId\">,\n): string {\n const innerText = typeUnwrap.length ? `${typeUnwrap}(${name})` : name;\n\n if (internalTypeId === \"bytes32\") {\n return innerText;\n } else if (/^bytes\\d{1,2}$/.test(internalTypeId)) {\n return `bytes32(${innerText})`;\n } else if (/^uint\\d{1,3}$/.test(internalTypeId)) {\n return `bytes32(uint256(${innerText}))`;\n } else if (/^int\\d{1,3}$/.test(internalTypeId)) {\n return `bytes32(uint256(int256(${innerText})))`;\n } else if (internalTypeId === \"address\") {\n return `bytes32(uint256(uint160(${innerText})))`;\n } else if (internalTypeId === \"bool\") {\n return `_boolToBytes32(${innerText})`;\n } else {\n throw new Error(`Unknown value type id ${internalTypeId}`);\n }\n}\n\n/**\n * Whether the storage representation of the given solidity type is left aligned\n */\nexport function isLeftAligned(field: Pick<RenderType, \"internalTypeId\">): boolean {\n return /^bytes\\d{1,2}$/.test(field.internalTypeId);\n}\n\n/**\n * The number of padding bits in the storage representation of a right-aligned solidity type\n */\nexport function getLeftPaddingBits(field: Pick<RenderType, \"internalTypeId\" | \"staticByteLength\">): number {\n if (isLeftAligned(field)) {\n return 0;\n } else {\n return 256 - field.staticByteLength * 8;\n }\n}\n\n/**\n * Internal helper to render `lineTerminator`-separated list of items mapped by `renderItem`\n */\nfunction internalRenderList<T>(\n lineTerminator: string,\n list: T[],\n renderItem: (item: T, index: number) => string,\n): string {\n return list\n .map((item, index) => renderItem(item, index) + (index === list.length - 1 ? \"\" : lineTerminator))\n .join(\"\\n\");\n}\n","import { renderedSolidityHeader } from \"./common\";\n\n// importing this from config or store would be a cyclic dependency :(\ntype Enums = {\n readonly [name: string]: readonly [string, ...string[]];\n};\n\n/**\n * Render a list of enum data as solidity enum definitions\n */\nexport function renderEnums(enums: Enums): string {\n const enumDefinitions = Object.entries(enums).map(\n ([name, values]) => `\n enum ${name} {\n ${values.join(\", \")}\n }\n `,\n );\n\n return `\n ${renderedSolidityHeader}\n ${enumDefinitions.join(\"\")}\n `;\n}\n","import { RenderField, RenderKeyTuple, RenderType } from \"./types\";\n\n/**\n * Renders the necessary helper functions to typecast to/from the types of given fields and keys\n */\nexport function renderTypeHelpers(options: { fields: RenderField[]; keyTuple: RenderKeyTuple[] }): string {\n const { fields, keyTuple } = options;\n\n let result = \"\";\n\n for (const wrappingHelper of getWrappingHelpers([...fields, ...keyTuple])) {\n result += wrappingHelper;\n }\n\n // bool is special - it's the only primitive value type that can't be typecasted to/from\n if (fields.some(({ internalTypeId }) => internalTypeId.match(\"bool\"))) {\n result += `\n /**\n * @notice Cast a value to a bool.\n * @dev Boolean values are encoded as uint8 (1 = true, 0 = false), but Solidity doesn't allow casting between uint8 and bool.\n * @param value The uint8 value to convert.\n * @return result The boolean value.\n */\n function _toBool(uint8 value) pure returns (bool result) {\n assembly {\n result := value\n }\n }\n `;\n }\n if (keyTuple.some(({ internalTypeId }) => internalTypeId.match(\"bool\"))) {\n result += `\n /**\n * @notice Cast a bool to a bytes32.\n * @dev The boolean value is casted to a bytes32 value with 0 or 1 at the least significant bit.\n */\n function _boolToBytes32(bool value) pure returns (bytes32 result) {\n assembly {\n result := value\n }\n }\n `;\n }\n\n return result;\n}\n\nfunction getWrappingHelpers(array: RenderType[]): string[] {\n const wrappers = new Map<string, string>();\n const unwrappers = new Map<string, string>();\n for (const { typeWrappingData, typeWrap, typeUnwrap, internalTypeId } of array) {\n if (!typeWrappingData) continue;\n const { kind } = typeWrappingData;\n\n if (kind === \"staticArray\") {\n const { elementType, staticLength } = typeWrappingData;\n wrappers.set(typeWrap, renderWrapperStaticArray(typeWrap, elementType, staticLength, internalTypeId));\n unwrappers.set(typeUnwrap, renderUnwrapperStaticArray(typeUnwrap, elementType, staticLength, internalTypeId));\n }\n }\n\n return [...wrappers.values(), ...unwrappers.values()];\n}\n\n/**\n * Renders a function to cast a dynamic array to a static array.\n * @param functionName name of the function to be rendered\n * @param elementType type of the array's element\n * @param staticLength length of the static array\n * @param internalTypeId solidity type name of the dynamic array\n * @returns\n */\nfunction renderWrapperStaticArray(\n functionName: string,\n elementType: string,\n staticLength: number,\n internalTypeId: string,\n): string {\n // WARNING: ensure this still works if changing major solidity versions!\n // (the memory layout for static arrays may change)\n return `\n /**\n * @notice Cast a dynamic array to a static array.\n * @dev In memory static arrays are just dynamic arrays without the 32 length bytes,\n * so this function moves the pointer to the first element of the dynamic array.\n * If the length of the dynamic array is smaller than the static length,\n * the function returns an uninitialized array to avoid memory corruption.\n * @param _value The dynamic array to cast.\n * @return _result The static array.\n */\n function ${functionName}(\n ${internalTypeId} memory _value\n ) pure returns (\n ${elementType}[${staticLength}] memory _result\n ) {\n if (_value.length < ${staticLength}) {\n // return an uninitialized array if the length is smaller than the fixed length to avoid memory corruption\n return _result;\n } else {\n // in memory static arrays are just dynamic arrays without the 32 length bytes\n // (without the length check this could lead to memory corruption)\n assembly {\n _result := add(_value, 0x20)\n }\n }\n }\n `;\n}\n\n/**\n * Renders a function to cast a static array to a dynamic array.\n * @param functionName name of the function to be rendered\n * @param elementType type of the array's element\n * @param staticLength length of the static array\n * @param internalTypeId solidity type name of the dynamic array\n * @returns\n */\nfunction renderUnwrapperStaticArray(\n functionName: string,\n elementType: string,\n staticLength: number,\n internalTypeId: string,\n): string {\n // byte length for memory copying (more efficient than a loop)\n const byteLength = staticLength * 32;\n // TODO to optimize memory usage consider generalizing TightEncoder to a render-time utility\n return `\n /**\n * @notice Copy a static array to a dynamic array.\n * @dev Static arrays don't have a length prefix, so this function copies the memory from the static array to a new dynamic array.\n * @param _value The static array to copy.\n * @return _result The dynamic array.\n */ \n function ${functionName}(\n ${elementType}[${staticLength}] memory _value\n ) pure returns (\n ${internalTypeId} memory _result\n ) {\n _result = new ${internalTypeId}(${staticLength});\n uint256 fromPointer;\n uint256 toPointer;\n assembly {\n fromPointer := _value\n toPointer := add(_result, 0x20)\n }\n Memory.copy(fromPointer, toPointer, ${byteLength});\n }\n `;\n}\n","import { SchemaType } from \"@latticexyz/schema-type/deprecated\";\n\nexport const schemaTypesToRecsTypeStrings: Record<SchemaType, string> = {\n [SchemaType.UINT8]: \"RecsType.Number\",\n [SchemaType.UINT16]: \"RecsType.Number\",\n [SchemaType.UINT24]: \"RecsType.Number\",\n [SchemaType.UINT32]: \"RecsType.Number\",\n [SchemaType.UINT40]: \"RecsType.Number\",\n [SchemaType.UINT48]: \"RecsType.Number\",\n [SchemaType.UINT56]: \"RecsType.BigInt\",\n [SchemaType.UINT64]: \"RecsType.BigInt\",\n [SchemaType.UINT72]: \"RecsType.BigInt\",\n [SchemaType.UINT80]: \"RecsType.BigInt\",\n [SchemaType.UINT88]: \"RecsType.BigInt\",\n [SchemaType.UINT96]: \"RecsType.BigInt\",\n [SchemaType.UINT104]: \"RecsType.BigInt\",\n [SchemaType.UINT112]: \"RecsType.BigInt\",\n [SchemaType.UINT120]: \"RecsType.BigInt\",\n [SchemaType.UINT128]: \"RecsType.BigInt\",\n [SchemaType.UINT136]: \"RecsType.BigInt\",\n [SchemaType.UINT144]: \"RecsType.BigInt\",\n [SchemaType.UINT152]: \"RecsType.BigInt\",\n [SchemaType.UINT160]: \"RecsType.BigInt\",\n [SchemaType.UINT168]: \"RecsType.BigInt\",\n [SchemaType.UINT176]: \"RecsType.BigInt\",\n [SchemaType.UINT184]: \"RecsType.BigInt\",\n [SchemaType.UINT192]: \"RecsType.BigInt\",\n [SchemaType.UINT200]: \"RecsType.BigInt\",\n [SchemaType.UINT208]: \"RecsType.BigInt\",\n [SchemaType.UINT216]: \"RecsType.BigInt\",\n [SchemaType.UINT224]: \"RecsType.BigInt\",\n [SchemaType.UINT232]: \"RecsType.BigInt\",\n [SchemaType.UINT240]: \"RecsType.BigInt\",\n [SchemaType.UINT248]: \"RecsType.BigInt\",\n [SchemaType.UINT256]: \"RecsType.BigInt\",\n [SchemaType.INT8]: \"RecsType.Number\",\n [SchemaType.INT16]: \"RecsType.Number\",\n [SchemaType.INT24]: \"RecsType.Number\",\n [SchemaType.INT32]: \"RecsType.Number\",\n [SchemaType.INT40]: \"RecsType.Number\",\n [SchemaType.INT48]: \"RecsType.Number\",\n [SchemaType.INT56]: \"RecsType.BigInt\",\n [SchemaType.INT64]: \"RecsType.BigInt\",\n [SchemaType.INT72]: \"RecsType.BigInt\",\n [SchemaType.INT80]: \"RecsType.BigInt\",\n [SchemaType.INT88]: \"RecsType.BigInt\",\n [SchemaType.INT96]: \"RecsType.BigInt\",\n [SchemaType.INT104]: \"RecsType.BigInt\",\n [SchemaType.INT112]: \"RecsType.BigInt\",\n [SchemaType.INT120]: \"RecsType.BigInt\",\n [SchemaType.INT128]: \"RecsType.BigInt\",\n [SchemaType.INT136]: \"RecsType.BigInt\",\n [SchemaType.INT144]: \"RecsType.BigInt\",\n [SchemaType.INT152]: \"RecsType.BigInt\",\n [SchemaType.INT160]: \"RecsType.BigInt\",\n [SchemaType.INT168]: \"RecsType.BigInt\",\n [SchemaType.INT176]: \"RecsType.BigInt\",\n [SchemaType.INT184]: \"RecsType.BigInt\",\n [SchemaType.INT192]: \"RecsType.BigInt\",\n [SchemaType.INT200]: \"RecsType.BigInt\",\n [SchemaType.INT208]: \"RecsType.BigInt\",\n [SchemaType.INT216]: \"RecsType.BigInt\",\n [SchemaType.INT224]: \"RecsType.BigInt\",\n [SchemaType.INT232]: \"RecsType.BigInt\",\n [SchemaType.INT240]: \"RecsType.BigInt\",\n [SchemaType.INT248]: \"RecsType.BigInt\",\n [SchemaType.INT256]: \"RecsType.BigInt\",\n [SchemaType.BYTES1]: \"RecsType.String\",\n [SchemaType.BYTES2]: \"RecsType.String\",\n [SchemaType.BYTES3]: \"RecsType.String\",\n [SchemaType.BYTES4]: \"RecsType.String\",\n [SchemaType.BYTES5]: \"RecsType.String\",\n [SchemaType.BYTES6]: \"RecsType.String\",\n [SchemaType.BYTES7]: \"RecsType.String\",\n [SchemaType.BYTES8]: \"RecsType.String\",\n [SchemaType.BYTES9]: \"RecsType.String\",\n [SchemaType.BYTES10]: \"RecsType.String\",\n [SchemaType.BYTES11]: \"RecsType.String\",\n [SchemaType.BYTES12]: \"RecsType.String\",\n [SchemaType.BYTES13]: \"RecsType.String\",\n [SchemaType.BYTES14]: \"RecsType.String\",\n [SchemaType.BYTES15]: \"RecsType.String\",\n [SchemaType.BYTES16]: \"RecsType.String\",\n [SchemaType.BYTES17]: \"RecsType.String\",\n [SchemaType.BYTES18]: \"RecsType.String\",\n [SchemaType.BYTES19]: \"RecsType.String\",\n [SchemaType.BYTES20]: \"RecsType.String\",\n [SchemaType.BYTES21]: \"RecsType.String\",\n [SchemaType.BYTES22]: \"RecsType.String\",\n [SchemaType.BYTES23]: \"RecsType.String\",\n [SchemaType.BYTES24]: \"RecsType.String\",\n [SchemaType.BYTES25]: \"RecsType.String\",\n [SchemaType.BYTES26]: \"RecsType.String\",\n [SchemaType.BYTES27]: \"RecsType.String\",\n [SchemaType.BYTES28]: \"RecsType.String\",\n [SchemaType.BYTES29]: \"RecsType.String\",\n [SchemaType.BYTES30]: \"RecsType.String\",\n [SchemaType.BYTES31]: \"RecsType.String\",\n [SchemaType.BYTES32]: \"RecsType.String\",\n [SchemaType.BOOL]: \"RecsType.Boolean\",\n [SchemaType.ADDRESS]: \"RecsType.String\",\n [SchemaType.UINT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.UINT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.UINT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT8_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT16_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT24_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT32_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT40_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT48_ARRAY]: \"RecsType.NumberArray\",\n [SchemaType.INT56_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT64_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT72_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT80_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT88_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT96_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT104_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT112_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT120_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT128_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT136_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT144_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT152_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT160_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT168_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT176_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT184_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT192_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT200_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT208_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT216_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT224_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT232_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT240_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT248_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.INT256_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES1_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES2_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES3_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES4_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES5_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES6_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES7_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES8_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES9_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES10_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES11_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES12_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES13_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES14_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES15_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES16_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES17_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES18_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES19_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES20_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES21_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES22_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES23_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES24_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES25_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES26_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES27_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES28_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES29_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES30_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES31_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BYTES32_ARRAY]: \"RecsType.BigIntArray\",\n [SchemaType.BOOL_ARRAY]: \"RecsType.T\", // no boolean array\n [SchemaType.ADDRESS_ARRAY]: \"RecsType.StringArray\",\n [SchemaType.BYTES]: \"RecsType.String\",\n [SchemaType.STRING]: \"RecsType.String\",\n};\n","import { parse, visit } from \"@solidity-parser/parser\";\nimport type {\n ContractDefinition,\n SourceUnit,\n TypeName,\n VariableDeclaration,\n} from \"@solidity-parser/parser/dist/src/ast-types\";\nimport { MUDError } from \"../../errors\";\n\nexport interface ContractInterfaceFunction {\n name: string;\n parameters: string[];\n stateMutability: string;\n returnParameters: string[];\n}\n\nexport interface ContractInterfaceError {\n name: string;\n parameters: string[];\n}\n\ninterface SymbolImport {\n symbol: string;\n path: string;\n}\n\n/**\n * Parse the contract data to get the functions necessary to generate an interface,\n * and symbols to import from the original contract.\n * @param source contents of a file with the solidity contract\n * @param contractName name of the contract\n * @returns interface data\n */\nexport function contractToInterface(\n source: string,\n contractName: string,\n): {\n functions: ContractInterfaceFunction[];\n errors: ContractInterfaceError[];\n symbolImports: SymbolImport[];\n} {\n const ast = parse(source);\n const contractNode = findContractNode(ast, contractName);\n let symbolImports: SymbolImport[] = [];\n const functions: ContractInterfaceFunction[] = [];\n const errors: ContractInterfaceError[] = [];\n\n if (!contractNode) {\n throw new MUDError(`Contract not found: ${contractName}`);\n }\n\n visit(contractNode, {\n FunctionDefinition({\n name,\n visibility,\n parameters,\n stateMutability,\n returnParameters,\n isConstructor,\n isFallback,\n isReceiveEther,\n }) {\n try {\n // skip constructor and fallbacks\n if (isConstructor || isFallback || isReceiveEther) return;\n // forbid default visibility (this check might be unnecessary, modern solidity already disallows this)\n if (visibility === \"default\") throw new MUDError(`Visibility is not specified`);\n\n if (visibility === \"external\" || visibility === \"public\") {\n functions.push({\n name: name === null ? \"\" : name,\n parameters: parameters.map(parseParameter),\n stateMutability: stateMutability || \"\",\n returnParameters: returnParameters === null ? [] : returnParameters.map(parseParameter),\n });\n\n for (const { typeName } of parameters.concat(returnParameters ?? [])) {\n const symbols = typeNameToSymbols(typeName);\n symbolImports = symbolImports.concat(symbolsToImports(ast, symbols));\n }\n }\n } catch (error: unknown) {\n if (error instanceof MUDError) {\n error.message = `Function \"${name}\" in contract \"${contractName}\": ${error.message}`;\n }\n throw error;\n }\n },\n CustomErrorDefinition({ name, parameters }) {\n errors.push({\n name,\n parameters: parameters.map(parseParameter),\n });\n\n for (const parameter of parameters) {\n const symbols = typeNameToSymbols(parameter.typeName);\n symbolImports = symbolImports.concat(symbolsToImports(ast, symbols));\n }\n },\n });\n\n return {\n functions,\n errors,\n symbolImports,\n };\n}\n\nexport function findContractNode(ast: SourceUnit, contractName: string): ContractDefinition | undefined {\n let contract: ContractDefinition | undefined = undefined;\n\n visit(ast, {\n ContractDefinition(node) {\n if (node.name === contractName) {\n contract = node;\n }\n },\n });\n\n return contract;\n}\n\nfunction parseParameter({ name, typeName, storageLocation }: VariableDeclaration): string {\n let typedNameWithLocation = \"\";\n\n const { name: flattenedTypeName, stateMutability } = flattenTypeName(typeName);\n // type name (e.g. uint256)\n typedNameWithLocation += flattenedTypeName;\n // optional mutability (e.g. address payable)\n if (stateMutability !== null) {\n typedNameWithLocation += ` ${stateMutability}`;\n }\n // location, when relevant (e.g. string memory)\n if (storageLocation !== null) {\n typedNameWithLocation += ` ${storageLocation}`;\n }\n // optional variable name\n if (name !== null) {\n typedNameWithLocation += ` ${name}`;\n }\n\n return typedNameWithLocation;\n}\n\nfunction flattenTypeName(typeName: TypeName | null): { name: string; stateMutability: string | null } {\n if (typeName === null) {\n return {\n name: \"\",\n stateMutability: null,\n };\n }\n if (typeName.type === \"ElementaryTypeName\") {\n return {\n name: typeName.name,\n stateMutability: typeName.stateMutability,\n };\n } else if (typeName.type === \"UserDefinedTypeName\") {\n return {\n name: typeName.namePath,\n stateMutability: null,\n };\n } else if (typeName.type === \"ArrayTypeName\") {\n let length = \"\";\n if (typeName.length?.type === \"NumberLiteral\") {\n length = typeName.length.number;\n } else if (typeName.length?.type === \"Identifier\") {\n length = typeName.length.name;\n }\n\n const { name, stateMutability } = flattenTypeName(typeName.baseTypeName);\n return {\n name: `${name}[${length}]`,\n stateMutability,\n };\n } else {\n // TODO function types are unsupported but could be useful\n throw new MUDError(`Invalid typeName.type ${typeName.type}`);\n }\n}\n\n// Get symbols that need to be imported for given typeName\nfunction typeNameToSymbols(typeName: TypeName | null): string[] {\n if (typeName?.type === \"UserDefinedTypeName\") {\n // split is needed to get a library, if types are internal to it\n const symbol = typeName.namePath.split(\".\")[0];\n return [symbol];\n } else if (typeName?.type === \"ArrayTypeName\") {\n const symbols = typeNameToSymbols(typeName.baseTypeName);\n // array types can also use symbols (constants) for length\n if (typeName.length?.type === \"Identifier\") {\n const innerTypeName = typeName.length.name;\n symbols.push(innerTypeName.split(\".\")[0]);\n }\n return symbols;\n } else {\n return [];\n }\n}\n\n// Get imports for given symbols.\n// To avoid circular dependencies of interfaces on their implementations,\n// symbols used for args/returns must always be imported from an auxiliary file.\n// To avoid parsing the entire project to build dependencies,\n// symbols must be imported with an explicit `import { symbol } from ...`\nfunction symbolsToImports(ast: SourceUnit, symbols: string[]): SymbolImport[] {\n const imports: SymbolImport[] = [];\n\n for (const symbol of symbols) {\n let symbolImport: SymbolImport | undefined;\n\n visit(ast, {\n ImportDirective({ path, symbolAliases }) {\n if (symbolAliases) {\n for (const symbolAndAlias of symbolAliases) {\n // either check the alias, or the original symbol if there's no alias\n const symbolAlias = symbolAndAlias[1] || symbolAndAlias[0];\n if (symbol === symbolAlias) {\n symbolImport = {\n // always use the original symbol for interface imports\n symbol: symbolAndAlias[0],\n path,\n };\n return;\n }\n }\n }\n },\n });\n\n if (symbolImport) {\n imports.push(symbolImport);\n } else {\n throw new MUDError(`Symbol \"${symbol}\" has no explicit import`);\n }\n }\n\n return imports;\n}\n","import prettier from \"prettier\";\nimport prettierPluginSolidity from \"prettier-plugin-solidity\";\n\n/**\n * Formats solidity code using prettier\n * @param content solidity code\n * @param prettierConfigPath optional path to a prettier config\n * @returns formatted solidity code\n */\nexport async function formatSolidity(content: string, prettierConfigPath?: string): Promise<string> {\n let config;\n if (prettierConfigPath) {\n config = await prettier.resolveConfig(prettierConfigPath);\n }\n try {\n return prettier.format(content, {\n plugins: [prettierPluginSolidity],\n parser: \"solidity-parse\",\n\n printWidth: 120,\n semi: true,\n tabWidth: 2,\n useTabs: false,\n bracketSpacing: true,\n\n ...config,\n });\n } catch (error) {\n let message;\n if (error instanceof Error) {\n message = error.message;\n } else {\n message = error;\n }\n console.log(`Error during output formatting: ${message}`);\n return content;\n }\n}\n\n/**\n * Formats typescript code using prettier\n * @param content typescript code\n * @returns formatted typescript code\n */\nexport async function formatTypescript(content: string): Promise<string> {\n return prettier.format(content, {\n parser: \"typescript\",\n });\n}\n","import fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { formatSolidity, formatTypescript } from \"./format\";\nimport { debug } from \"../debug\";\n\n/**\n * Formats solidity code using prettier and write it to a file\n * @param output solidity code\n * @param fullOutputPath full path to the output file\n * @param logPrefix prefix for debug logs\n */\nexport async function formatAndWriteSolidity(output: string, fullOutputPath: string, logPrefix: string): Promise<void> {\n const formattedOutput = await formatSolidity(output);\n\n await fs.mkdir(path.dirname(fullOutputPath), { recursive: true });\n\n await fs.writeFile(fullOutputPath, formattedOutput);\n debug(`${logPrefix}: ${fullOutputPath}`);\n}\n\n/**\n * Formats typescript code using prettier and write it to a file\n * @param output typescript code\n * @param fullOutputPath full path to the output file\n * @param logPrefix prefix for debug logs\n */\nexport async function formatAndWriteTypescript(\n output: string,\n fullOutputPath: string,\n logPrefix: string,\n): Promise<void> {\n const formattedOutput = await formatTypescript(output);\n\n await fs.mkdir(path.dirname(fullOutputPath), { recursive: true });\n\n await fs.writeFile(fullOutputPath, formattedOutput);\n debug(`${logPrefix}: ${fullOutputPath}`);\n}\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"codegen\");\nexport const error = parentDebug.extend(\"codegen\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n"],"mappings":"+HACA,OAAqC,iBAAAA,EAAe,sBAAAC,MAA0B,UCD9E,OAAOC,MAAU,YAIjB,SAASC,EAAWC,EAAyB,CAC3C,OAAOA,EAAQ,WAAWF,EAAK,MAAM,IAAKA,EAAK,MAAM,GAAG,CAC1D,CAEO,SAASG,EAAiBC,KAAqBC,EAAqC,CAEzF,IAAMC,EAAWN,EAAK,MACnB,KAAKC,EAAWG,CAAQ,EAAG,GAAGC,EAAS,IAAIJ,CAAU,CAAC,EAEtD,QAAQ,MAAO,EAAE,EAIpB,OAAIG,EAAS,WAAW,GAAG,GACJ,KAAOE,GACR,QAAQ,aAAc,GAAG,EAGxCA,CACT,CCfO,IAAMC,EAAyB;AAAA;AAAA;AAAA,iDAQ/B,SAASC,EAAcC,EAAWC,EAAwD,CAC/F,OAAOC,EAAmB,GAAIF,EAAMC,CAAU,CAChD,CAKO,SAASE,EAAgBC,EAAsC,CACpE,IAAMC,EAAeD,EAAK,OAAQE,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S,GACT,eAAgB,GAEhB,GAAGI,CACL,CAAC,CACH,OAASC,EAAO,CACd,IAAIC,EACJ,OAAID,aAAiB,MACnBC,EAAUD,EAAM,QAEhBC,EAAUD,EAEZ,QAAQ,IAAI,mCAAmCC,CAAO,EAAE,EACjDJ,CACT,CACF,CAOA,eAAsBK,EAAiBL,EAAkC,CACvE,OAAOH,EAAS,OAAOG,EAAS,CAC9B,OAAQ,YACV,CAAC,CACH,CChDA,OAAOM,MAAQ,mBACf,OAAOC,MAAU,YCCV,IAAMC,EAAQA,EAAY,OAAO,SAAS,EACpCC,EAAQD,EAAY,OAAO,SAAS,EAGjDA,EAAM,IAAM,QAAQ,MAAM,KAAK,OAAO,EAGtCC,EAAM,IAAM,QAAQ,MAAM,KAAK,OAAO,EDEtC,eAAsBC,GAAuBC,EAAgBC,EAAwBC,EAAkC,CACrH,IAAMC,EAAkB,MAAMC,EAAeJ,CAAM,EAEnD,MAAMK,EAAG,MAAMC,EAAK,QAAQL,CAAc,EAAG,CAAE,UAAW,EAAK,CAAC,EAEhE,MAAMI,EAAG,UAAUJ,EAAgBE,CAAe,EAClDI,EAAM,GAAGL,CAAS,KAAKD,CAAc,EAAE,CACzC,CAQA,eAAsBO,GACpBR,EACAC,EACAC,EACe,CACf,IAAMC,EAAkB,MAAMM,EAAiBT,CAAM,EAErD,MAAMK,EAAG,MAAMC,EAAK,QAAQL,CAAc,EAAG,CAAE,UAAW,EAAK,CAAC,EAEhE,MAAMI,EAAG,UAAUJ,EAAgBE,CAAe,EAClDI,EAAM,GAAGL,CAAS,KAAKD,CAAc,EAAE,CACzC","names":["formatAbiItem","formatAbiParameter","path","winToPosix","segment","renderImportPath","basePath","segments","fullPath","renderedSolidityHeader","renderList","list","renderItem","internalRenderList","renderArguments","args","filteredArgs","arg","renderCommonData","staticResourceData","keyTuple","_typedTableId","_typedKeyArgs","name","typeWithLocation","_keyTupleDefinition","key","index","renderValueTypeToBytes32","renderImports","imports","aggregatedImports","symbol","path","renderedImports","symbols","renderedSymbols","renderImportPath","renderWithStore","storeArgument","callback","result","renderWithFieldSuffix","withSuffixlessFieldMethods","fieldName","methodNameSuffix","renderTableId","namespace","offchainOnly","tableId","resourceToHex","resource","hexToResource","typeUnwrap","internalTypeId","innerText","isLeftAligned","field","getLeftPaddingBits","lineTerminator","item","formatParam","param","formatAbiParameter","formatFunction","item","params","returns","formatSystemId","systemId","resource","hexToResource","abiToInterface","name","abi","imports","errors","functions","renderedSolidityHeader","formatAbiItem","renderEnums","enums","enumDefinitions","name","values","renderedSolidityHeader","renderTypeHelpers","options","fields","keyTuple","result","wrappingHelper","getWrappingHelpers","internalTypeId","array","wrappers","unwrappers","typeWrappingData","typeWrap","typeUnwrap","kind","elementType","staticLength","renderWrapperStaticArray","renderUnwrapperStaticArray","functionName","byteLength","SchemaType","schemaTypesToRecsTypeStrings","parse","visit","contractToInterface","source","contractName","ast","parse","contractNode","findContractNode","symbolImports","functions","errors","MUDError","visit","name","visibility","parameters","stateMutability","returnParameters","isConstructor","isFallback","isReceiveEther","parseParameter","typeName","symbols","typeNameToSymbols","symbolsToImports","error","parameter","contract","node","storageLocation","typedNameWithLocation","flattenedTypeName","flattenTypeName","length","innerTypeName","imports","symbol","symbolImport","path","symbolAliases","symbolAndAlias","symbolAlias","prettier","prettierPluginSolidity","formatSolidity","content","prettierConfigPath","config","error","message","formatTypescript","fs","path","debug","error","formatAndWriteSolidity","output","fullOutputPath","logPrefix","formattedOutput","formatSolidity","fs","path","debug","formatAndWriteTypescript","formatTypescript"]}
package/dist/errors.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a}from"./chunk-UPQEB2HW.js";export{a as MUDError};
1
+ import{a}from"./chunk-QQCZY3XJ.js";export{a as MUDError};
2
2
  //# sourceMappingURL=errors.js.map
package/dist/foundry.d.ts CHANGED
@@ -66,4 +66,4 @@ declare function cast(args: string[], options?: {
66
66
  */
67
67
  declare function anvil(args: string[]): Promise<string>;
68
68
 
69
- export { ForgeConfig, anvil, cast, forge, getForgeConfig, getOutDirectory, getRpcUrl, getScriptDirectory, getSrcDirectory, getTestDirectory };
69
+ export { type ForgeConfig, anvil, cast, forge, getForgeConfig, getOutDirectory, getRpcUrl, getScriptDirectory, getSrcDirectory, getTestDirectory };
@@ -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 (await getForgeConfig(profile)).eth_rpc_url || \"http://127.0.0.1:8545\";\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: Options<string> = {\n env: { FOUNDRY_PROFILE: options?.profile, ...options?.env },\n stdout: \"inherit\",\n stderr: \"pipe\",\n cwd: options?.cwd,\n };\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<string>): Promise<string> {\n const commandString = `${command} ${args.join(\" \")}`;\n try {\n console.log(`running \"${commandString}\"`);\n const { stdout } = await execa(command, args, { stdout: \"pipe\", stderr: \"pipe\", ...options });\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,C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A,GAAO,SAAW,GACtD,MAAAC,GAAgB;AAAA,iBAAoBF,KAC9B,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 (await getForgeConfig(profile)).eth_rpc_url || \"http://127.0.0.1:8545\";\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: Options<string> = {\n env: { FOUNDRY_PROFILE: options?.profile, ...options?.env },\n stdout: \"inherit\",\n stderr: \"pipe\",\n cwd: options?.cwd,\n };\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<string>): Promise<string> {\n const commandString = `${command} ${args.join(\" \")}`;\n try {\n console.log(`running \"${commandString}\"`);\n const { stdout } = await execa(command, args, { stdout: \"pipe\", stderr: \"pipe\", ...options });\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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,EAC5F,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"]}
@@ -17,4 +17,4 @@ declare function getContract<TTransport extends Transport, TAddress extends Addr
17
17
  wallet: TWalletClient;
18
18
  }, TAddress>;
19
19
 
20
- export { ContractWrite as C, GetContractOptions as G, getContract as g };
20
+ export { type ContractWrite as C, type GetContractOptions as G, getContract as g };
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Hex, PrivateKeyAccount, Client, BlockTag, Chain, Transport, Account, SendTransactionRequest, SendTransactionParameters, SendTransactionReturnType, Abi, ContractFunctionName, ContractFunctionArgs, WriteContractParameters, WriteContractReturnType } from 'viem';
2
2
  import PQueue from 'p-queue';
3
- import { g as getContract } from './getContract-93922960.js';
4
- export { C as ContractWrite, G as GetContractOptions } from './getContract-93922960.js';
3
+ import { g as getContract } from './getContract-CA0EdVg6.js';
4
+ export { C as ContractWrite, G as GetContractOptions } from './getContract-CA0EdVg6.js';
5
5
 
6
6
  declare const resourceTypes: readonly ["table", "offchainTable", "namespace", "system"];
7
7
  type ResourceType = (typeof resourceTypes)[number];
@@ -155,4 +155,4 @@ declare const resourceIdToHex: typeof resourceToHex;
155
155
  /** @deprecated use `hexToResource` instead */
156
156
  declare const hexToResourceId: typeof hexToResource;
157
157
 
158
- export { CreateNonceManagerOptions, CreateNonceManagerResult, LruMap, Resource, ResourceLabel, ResourceType, Result, SendTransactionExtraOptions, WriteContractExtraOptions, createBenchmark, createBurnerAccount, createContract, createNonceManager, getBurnerPrivateKey, getContract, getNonceManager, getNonceManagerId, hexToResource, hexToResourceId, isError, isOk, logSort, readHex, resourceIdToHex, resourceToHex, resourceToLabel, resourceTypeIds, resourceTypes, sendTransaction, spliceHex, transportObserver, unwrap, writeContract };
158
+ export { type CreateNonceManagerOptions, type CreateNonceManagerResult, LruMap, type Resource, type ResourceLabel, type ResourceType, type Result, type SendTransactionExtraOptions, type WriteContractExtraOptions, createBenchmark, createBurnerAccount, createContract, createNonceManager, getBurnerPrivateKey, getContract, getNonceManager, getNonceManagerId, hexToResource, hexToResourceId, isError, isOk, logSort, readHex, resourceIdToHex, resourceToHex, resourceToLabel, resourceTypeIds, resourceTypes, sendTransaction, spliceHex, transportObserver, unwrap, writeContract };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as p}from"./chunk-WSHEKFYD.js";import{a as K,b as $,c as q,e as _}from"./chunk-RCAJ6T6T.js";import{a as B,b as D,c as x,d as L,e as m}from"./chunk-DDEUATTE.js";import{a as l}from"./chunk-TCWGPC6G.js";import h from"debug";var T=h("mud:benchmark");T.log=console.info.bind(console);function U(e){let r=T.extend(e),t=performance.now();return o=>{let n=(performance.now()-t)/1e3;r("%s: +%ds",o,n),t=performance.now()}}import{privateKeyToAccount as P}from"viem/accounts";function Q(e){return{...P(e)}}import{getContract as w}from"viem";function H(e){let r=e.length&&Array.isArray(e[0]),t=r?e[0]:[],o=(r?e[1]:e[0])??{};return{args:t,options:o}}function d({abi:e,address:r,client:{public:t,wallet:o},onWrite:n}){let i=w({abi:e,address:r,client:{public:t,wallet:o}});if(i.write){let s=0;i.write=new Proxy({},{get(F,C){return(...g)=>{let{args:A,options:k}=H(g),c={abi:e,address:r,functionName:C,args:A,...k,onWrite:n},u=p(o,c,{publicClient:t}),y=`${o.chain.id}:${o.account.address}:${s++}`;return n?.({id:y,request:c,result:u}),u}}})}return i}import{generatePrivateKey as v,privateKeyToAccount as f}from"viem/accounts";import{isHex as W}from"viem";function O(e,r){if(!W(e))throw console.error("Private key found in cache is not valid hex",{privateKey:e,cacheKey:r}),new Error(`Private key found in cache (${r}) is not valid hex`);f(e)}function Te(e="mud:burnerWallet"){let r=localStorage.getItem(e);if(r!=null)return O(r,e),r;let t=v();return console.log("New burner wallet created:",f(t)),localStorage.setItem(e,t),t}function fe(e,r){return e.blockNumber===r.blockNumber?e.logIndex===r.logIndex?0:e.logIndex==null?1:r.logIndex==null?-1:e.logIndex-r.logIndex:e.blockNumber==null?1:r.blockNumber==null?-1:e.blockNumber>r.blockNumber?1:e.blockNumber<r.blockNumber?-1:0}var b=class extends Map{maxSize;constructor(r){super(),this.maxSize=r}set(r,t){return super.set(r,t),this.maxSize&&this.size>this.maxSize&&this.delete(this.keys().next().value),this}};function a(e,r,t){return`0x${e.replace(/^0x/,"").slice(r*2,t!=null?t*2:void 0).padEnd(((t??r)-r)*2,"0")}`}function Ae(e){return"ok"in e}function I(e){return"error"in e}function ke(e){if(I(e))throw e.error;return e.ok}import{concatHex as N}from"viem";function He(e,r,t=0,o="0x"){return N([a(e,0,r),o,a(e,r+t)])}import{keccak256 as E}from"viem";var R=l.extend("transportObserver");function Ee(e){return r=>{let t=e(r);return{...t,request:async n=>{if(n.method==="eth_sendRawTransaction"&&n.params instanceof Array){let i=n.params.map(s=>E(s));R("saw txs",i)}return t.request(n)}}}}var S=d;var G=x;var z=m;export{b as LruMap,U as createBenchmark,Q as createBurnerAccount,S as createContract,$ as createNonceManager,Te as getBurnerPrivateKey,d as getContract,q as getNonceManager,K as getNonceManagerId,m as hexToResource,z as hexToResourceId,I as isError,Ae as isOk,fe as logSort,a as readHex,G as resourceIdToHex,x as resourceToHex,L as resourceToLabel,D as resourceTypeIds,B as resourceTypes,_ as sendTransaction,He as spliceHex,Ee as transportObserver,ke as unwrap,p as writeContract};
1
+ import{a as p}from"./chunk-Q7HNDKVJ.js";import{a as K,b as $,c as q,e as _}from"./chunk-GUEDVXKC.js";import{a as B,b as D,c as x,d as L,e as m}from"./chunk-ZIUX7JCQ.js";import{a as l}from"./chunk-TCWGPC6G.js";import h from"debug";var T=h("mud:benchmark");T.log=console.info.bind(console);function U(e){let r=T.extend(e),t=performance.now();return o=>{let n=(performance.now()-t)/1e3;r("%s: +%ds",o,n),t=performance.now()}}import{privateKeyToAccount as P}from"viem/accounts";function Q(e){return{...P(e)}}import{getContract as w}from"viem";function H(e){let r=e.length&&Array.isArray(e[0]),t=r?e[0]:[],o=(r?e[1]:e[0])??{};return{args:t,options:o}}function d({abi:e,address:r,client:{public:t,wallet:o},onWrite:n}){let i=w({abi:e,address:r,client:{public:t,wallet:o}});if(i.write){let s=0;i.write=new Proxy({},{get(F,C){return(...g)=>{let{args:A,options:k}=H(g),c={abi:e,address:r,functionName:C,args:A,...k,onWrite:n},u=p(o,c,{publicClient:t}),y=`${o.chain.id}:${o.account.address}:${s++}`;return n?.({id:y,request:c,result:u}),u}}})}return i}import{generatePrivateKey as v,privateKeyToAccount as f}from"viem/accounts";import{isHex as W}from"viem";function O(e,r){if(!W(e))throw console.error("Private key found in cache is not valid hex",{privateKey:e,cacheKey:r}),new Error(`Private key found in cache (${r}) is not valid hex`);f(e)}function Te(e="mud:burnerWallet"){let r=localStorage.getItem(e);if(r!=null)return O(r,e),r;let t=v();return console.log("New burner wallet created:",f(t)),localStorage.setItem(e,t),t}function fe(e,r){return e.blockNumber===r.blockNumber?e.logIndex===r.logIndex?0:e.logIndex==null?1:r.logIndex==null?-1:e.logIndex-r.logIndex:e.blockNumber==null?1:r.blockNumber==null?-1:e.blockNumber>r.blockNumber?1:e.blockNumber<r.blockNumber?-1:0}var b=class extends Map{constructor(r){super(),this.maxSize=r}set(r,t){return super.set(r,t),this.maxSize&&this.size>this.maxSize&&this.delete(this.keys().next().value),this}};function a(e,r,t){return`0x${e.replace(/^0x/,"").slice(r*2,t!=null?t*2:void 0).padEnd(((t??r)-r)*2,"0")}`}function Ae(e){return"ok"in e}function I(e){return"error"in e}function ke(e){if(I(e))throw e.error;return e.ok}import{concatHex as N}from"viem";function He(e,r,t=0,o="0x"){return N([a(e,0,r),o,a(e,r+t)])}import{keccak256 as E}from"viem";var R=l.extend("transportObserver");function Ee(e){return r=>{let t=e(r);return{...t,request:async n=>{if(n.method==="eth_sendRawTransaction"&&n.params instanceof Array){let i=n.params.map(s=>E(s));R("saw txs",i)}return t.request(n)}}}}var S=d;var G=x;var z=m;export{b as LruMap,U as createBenchmark,Q as createBurnerAccount,S as createContract,$ as createNonceManager,Te as getBurnerPrivateKey,d as getContract,q as getNonceManager,K as getNonceManagerId,m as hexToResource,z as hexToResourceId,I as isError,Ae as isOk,fe as logSort,a as readHex,G as resourceIdToHex,x as resourceToHex,L as resourceToLabel,D as resourceTypeIds,B as resourceTypes,_ as sendTransaction,He as spliceHex,Ee as transportObserver,ke as unwrap,p as writeContract};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/createBenchmark.ts","../src/createBurnerAccount.ts","../src/getContract.ts","../src/getBurnerPrivateKey.ts","../src/logSort.ts","../src/LruMap.ts","../src/readHex.ts","../src/result.ts","../src/spliceHex.ts","../src/transportObserver.ts","../src/deprecated/createContract.ts","../src/deprecated/resourceIdToHex.ts","../src/deprecated/hexToResourceId.ts"],"sourcesContent":["import createDebug from \"debug\";\n\nconst parentDebug = createDebug(\"mud:benchmark\");\n\n// Pipe debug output to stdout instead of stderr\nparentDebug.log = console.info.bind(console);\n\nexport function createBenchmark(namespace: string): (stepName: string) => void {\n const debug = parentDebug.extend(namespace);\n let lastStep = performance.now();\n\n return (stepName: string) => {\n const secondsSinceLastStep = (performance.now() - lastStep) / 1000;\n debug(\"%s: +%ds\", stepName, secondsSinceLastStep);\n lastStep = performance.now();\n };\n}\n","import { Hex, PrivateKeyAccount } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nexport function createBurnerAccount(privateKey: Hex): PrivateKeyAccount {\n const account = privateKeyToAccount(privateKey);\n // We may override account features here\n return {\n ...account,\n };\n}\n","import {\n Abi,\n Account,\n Address,\n Chain,\n GetContractParameters,\n GetContractReturnType,\n Hex,\n PublicClient,\n Transport,\n WalletClient,\n WriteContractParameters,\n type ContractFunctionName,\n type ContractFunctionArgs,\n getContract as viem_getContract,\n} from \"viem\";\nimport { UnionOmit } from \"./type-utils/common\";\nimport { writeContract } from \"./writeContract\";\n\n// copied from viem because this isn't exported\n// TODO: import from viem?\nfunction getFunctionParameters(values: [args?: readonly unknown[], options?: object]): {\n args: readonly unknown[];\n options: object;\n} {\n const hasArgs = values.length && Array.isArray(values[0]);\n const args = hasArgs ? values[0]! : [];\n const options = (hasArgs ? values[1] : values[0]) ?? {};\n return { args, options };\n}\n\nexport type ContractWrite = {\n id: string;\n request: WriteContractParameters;\n result: Promise<Hex>;\n};\n\nexport type GetContractOptions<\n TTransport extends Transport,\n TAddress extends Address,\n TAbi extends Abi,\n TChain extends Chain,\n TAccount extends Account,\n TPublicClient extends PublicClient<TTransport, TChain>,\n TWalletClient extends WalletClient<TTransport, TChain, TAccount>,\n> = GetContractParameters<\n TTransport,\n TChain,\n TAccount,\n TAbi,\n { public: TPublicClient; wallet: TWalletClient },\n TAddress\n> & {\n onWrite?: (write: ContractWrite) => void;\n};\n\n// TODO: migrate away from this approach once we can hook into viem: https://github.com/wagmi-dev/viem/discussions/1230\n\n/** @deprecated Use `walletClient.extend(transactionQueue()).extend(writeObserver({ onWrite }))` and viem's `getContract` instead. */\nexport function getContract<\n TTransport extends Transport,\n TAddress extends Address,\n TAbi extends Abi,\n TChain extends Chain,\n TAccount extends Account,\n TPublicClient extends PublicClient<TTransport, TChain>,\n TWalletClient extends WalletClient<TTransport, TChain, TAccount>,\n>({\n abi,\n address,\n client: { public: publicClient, wallet: walletClient },\n onWrite,\n}: GetContractOptions<\n TTransport,\n TAddress,\n TAbi,\n TChain,\n TAccount,\n TPublicClient,\n TWalletClient\n>): GetContractReturnType<TAbi, { public: TPublicClient; wallet: TWalletClient }, TAddress> {\n const contract: GetContractReturnType<TAbi, { public: TPublicClient; wallet: TWalletClient }, TAddress> & {\n write: unknown;\n } = viem_getContract({\n abi,\n address,\n client: {\n public: publicClient,\n wallet: walletClient,\n },\n }) as never;\n\n if (contract.write) {\n // Replace write calls with our own. Implemented ~the same as viem, but adds better handling of nonces (via queue + retries).\n let nextWriteId = 0;\n contract.write = new Proxy(\n {},\n {\n get(_, functionName: string) {\n return (\n ...parameters: [\n args?: readonly unknown[],\n options?: UnionOmit<WriteContractParameters, \"abi\" | \"address\" | \"functionName\" | \"args\">,\n ]\n ) => {\n const { args, options } = getFunctionParameters(parameters);\n const request: WriteContractParameters<\n TAbi,\n ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\">,\n TChain,\n TAccount\n > = {\n abi,\n address,\n functionName,\n args,\n ...options,\n onWrite,\n } as never;\n const result = writeContract(walletClient, request, { publicClient }) as never;\n\n const id = `${walletClient.chain.id}:${walletClient.account.address}:${nextWriteId++}`;\n onWrite?.({\n id,\n request: request as WriteContractParameters,\n result,\n });\n\n return result;\n };\n },\n },\n );\n }\n\n return contract;\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\";\nimport { isHex, Hex } from \"viem\";\n\nfunction assertPrivateKey(privateKey: string, cacheKey: string): asserts privateKey is Hex {\n if (!isHex(privateKey)) {\n console.error(\"Private key found in cache is not valid hex\", { privateKey, cacheKey });\n throw new Error(`Private key found in cache (${cacheKey}) is not valid hex`);\n }\n // ensure we can extract address from private key\n // this should throw on bad private keys\n privateKeyToAccount(privateKey);\n}\n\nexport function getBurnerPrivateKey(cacheKey = \"mud:burnerWallet\"): Hex {\n const cachedPrivateKey = localStorage.getItem(cacheKey);\n\n if (cachedPrivateKey != null) {\n assertPrivateKey(cachedPrivateKey, cacheKey);\n return cachedPrivateKey;\n }\n\n const privateKey = generatePrivateKey();\n console.log(\"New burner wallet created:\", privateKeyToAccount(privateKey));\n localStorage.setItem(cacheKey, privateKey);\n return privateKey;\n}\n","type PartialLog = { readonly blockNumber: bigint | null; readonly logIndex: number | null };\n\nexport function logSort(a: PartialLog, b: PartialLog): number {\n if (a.blockNumber === b.blockNumber) {\n if (a.logIndex === b.logIndex) return 0;\n if (a.logIndex == null) return 1;\n if (b.logIndex == null) return -1;\n return a.logIndex - b.logIndex;\n }\n\n if (a.blockNumber == null) return 1;\n if (b.blockNumber == null) return -1;\n if (a.blockNumber > b.blockNumber) return 1;\n if (a.blockNumber < b.blockNumber) return -1;\n return 0;\n}\n","/**\n * Map with a LRU (least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n * @link https://github.com/wevm/viem/blob/0fa08e113a890e6672fdc64fa7a2206a840611ab/src/utils/lru.ts\n */\nexport class LruMap<key, value> extends Map<key, value> {\n maxSize: number;\n\n constructor(size: number) {\n super();\n this.maxSize = size;\n }\n\n override set(key: key, value: value): this {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n this.delete(this.keys().next().value);\n }\n return this;\n }\n}\n","import { Hex } from \"viem\";\n\n/**\n * Get the hex value at start/end positions. This will always return a valid hex string.\n *\n * If `start` is out of range, this returns `\"0x\"`.\n *\n * If `end` is specified and out of range, the result is right zero-padded to the desired length (`end - start`).\n */\nexport function readHex(data: Hex, start: number, end?: number): Hex {\n return `0x${data\n .replace(/^0x/, \"\")\n .slice(start * 2, end != null ? end * 2 : undefined)\n .padEnd(((end ?? start) - start) * 2, \"0\")}`;\n}\n","// Inspired by https://doc.rust-lang.org/std/result/\nexport type Result<Ok, Err = unknown> = { ok: Ok } | { error: Err };\n\nexport function isOk<Ok, Err>(result: Result<Ok, Err>): result is { ok: Ok } {\n return \"ok\" in result;\n}\n\nexport function isError<Ok, Err>(result: Result<Ok, Err>): result is { error: Err } {\n return \"error\" in result;\n}\n\nexport function unwrap<Ok, Err>(result: Result<Ok, Err>): Ok {\n if (isError(result)) {\n throw result.error;\n }\n return result.ok;\n}\n","import { Hex, concatHex } from \"viem\";\nimport { readHex } from \"./readHex\";\n\nexport function spliceHex(data: Hex, start: number, deleteCount = 0, newData: Hex = \"0x\"): Hex {\n return concatHex([readHex(data, 0, start), newData, readHex(data, start + deleteCount)]);\n}\n","import { Hex, Transport, keccak256 } from \"viem\";\nimport { debug as parentDebug } from \"./debug\";\n\nconst debug = parentDebug.extend(\"transportObserver\");\n\nexport function transportObserver<TTransport extends Transport>(transport: TTransport): TTransport {\n return ((opts) => {\n const result = transport(opts);\n const request: typeof result.request = async (req) => {\n if (req.method === \"eth_sendRawTransaction\" && req.params instanceof Array) {\n const txs = req.params.map((data: Hex) => keccak256(data));\n debug(\"saw txs\", txs);\n // TODO: pass these tx hashes into dev tools\n }\n // TODO: add support for `eth_sendTransaction`\n return result.request(req);\n };\n return {\n ...result,\n request,\n };\n }) as TTransport;\n}\n","import { getContract } from \"../getContract\";\n\n/** @deprecated use `getContract` instead */\nexport const createContract = getContract;\n","import { resourceToHex } from \"../resourceToHex\";\n\n/** @deprecated use `resourceToHex` instead */\nexport const resourceIdToHex = resourceToHex;\n","import { hexToResource } from \"../hexToResource\";\n\n/** @deprecated use `hexToResource` instead */\nexport const hexToResourceId = hexToResource;\n"],"mappings":"iNAAA,OAAOA,MAAiB,QAExB,IAAMC,EAAcD,EAAY,eAAe,EAG/CC,EAAY,IAAM,QAAQ,KAAK,KAAK,OAAO,EAEpC,SAASC,EAAgBC,EAA+C,CAC7E,IAAMC,EAAQH,EAAY,OAAOE,CAAS,EACtCE,EAAW,YAAY,IAAI,EAE/B,OAAQC,GAAqB,CAC3B,IAAMC,GAAwB,YAAY,IAAI,EAAIF,GAAY,IAC9DD,EAAM,WAAYE,EAAUC,CAAoB,EAChDF,EAAW,YAAY,IAAI,CAC7B,CACF,CCfA,OAAS,uBAAAG,MAA2B,gBAE7B,SAASC,EAAoBC,EAAoC,CAGtE,MAAO,CACL,GAHcF,EAAoBE,CAAU,CAI9C,CACF,CCTA,OAcE,eAAeC,MACV,OAMP,SAASC,EAAsBC,EAG7B,CACA,IAAMC,EAAUD,EAAO,QAAU,MAAM,QAAQA,EAAO,CAAC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,SAASC,GAAUC,EAAWC,EAAeC,EAAc,EAAGC,EAAe,KAAW,CAC7F,OAAOC,EAAU,CAACC,EAAQL,EAAM,EAAGC,CAAK,EAAGE,EAASE,EAAQL,EAAMC,EAAQC,CAAW,CAAC,CAAC,CACzF,CCLA,OAAyB,aAAAI,MAAiB,OAG1C,IAAMC,EAAQA,EAAY,OAAO,mBAAmB,EAE7C,SAASC,GAAgDC,EAAmC,CACjG,OAASC,GAAS,CAChB,IAAMC,EAASF,EAAUC,CAAI,EAU7B,MAAO,CACL,GAAGC,EACH,QAXqC,MAAOC,GAAQ,CACpD,GAAIA,EAAI,SAAW,0BAA4BA,EAAI,kBAAkB,MAAO,CAC1E,IAAMC,EAAMD,EAAI,OAAO,IAAKE,GAAcC,EAAUD,CAAI,CAAC,EACzDP,EAAM,UAAWM,CAAG,EAItB,OAAOF,EAAO,QAAQC,CAAG,CAC3B,CAIA,CACF,CACF,CCnBO,IAAMI,EAAiBC,ECAvB,IAAMC,EAAkBC,ECAxB,IAAMC,EAAkBC","names":["createDebug","parentDebug","createBenchmark","namespace","debug","lastStep","stepName","secondsSinceLastStep","privateKeyToAccount","createBurnerAccount","privateKey","viem_getContract","getFunctionParameters","values","hasArgs","args","options","getContract","abi","address","publicClient","walletClient","onWrite","contract","viem_getContract","nextWriteId","_","functionName","parameters","request","result","writeContract","id","generatePrivateKey","privateKeyToAccount","isHex","assertPrivateKey","privateKey","cacheKey","getBurnerPrivateKey","cachedPrivateKey","logSort","a","b","LruMap","size","key","value","readHex","data","start","end","isOk","result","isError","unwrap","concatHex","spliceHex","data","start","deleteCount","newData","concatHex","readHex","keccak256","debug","transportObserver","transport","opts","result","req","txs","data","keccak256","createContract","getContract","resourceIdToHex","resourceToHex","hexToResourceId","hexToResource"]}
1
+ {"version":3,"sources":["../src/createBenchmark.ts","../src/createBurnerAccount.ts","../src/getContract.ts","../src/getBurnerPrivateKey.ts","../src/logSort.ts","../src/LruMap.ts","../src/readHex.ts","../src/result.ts","../src/spliceHex.ts","../src/transportObserver.ts","../src/deprecated/createContract.ts","../src/deprecated/resourceIdToHex.ts","../src/deprecated/hexToResourceId.ts"],"sourcesContent":["import createDebug from \"debug\";\n\nconst parentDebug = createDebug(\"mud:benchmark\");\n\n// Pipe debug output to stdout instead of stderr\nparentDebug.log = console.info.bind(console);\n\nexport function createBenchmark(namespace: string): (stepName: string) => void {\n const debug = parentDebug.extend(namespace);\n let lastStep = performance.now();\n\n return (stepName: string) => {\n const secondsSinceLastStep = (performance.now() - lastStep) / 1000;\n debug(\"%s: +%ds\", stepName, secondsSinceLastStep);\n lastStep = performance.now();\n };\n}\n","import { Hex, PrivateKeyAccount } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nexport function createBurnerAccount(privateKey: Hex): PrivateKeyAccount {\n const account = privateKeyToAccount(privateKey);\n // We may override account features here\n return {\n ...account,\n };\n}\n","import {\n Abi,\n Account,\n Address,\n Chain,\n GetContractParameters,\n GetContractReturnType,\n Hex,\n PublicClient,\n Transport,\n WalletClient,\n WriteContractParameters,\n type ContractFunctionName,\n type ContractFunctionArgs,\n getContract as viem_getContract,\n} from \"viem\";\nimport { UnionOmit } from \"./type-utils/common\";\nimport { writeContract } from \"./writeContract\";\n\n// copied from viem because this isn't exported\n// TODO: import from viem?\nfunction getFunctionParameters(values: [args?: readonly unknown[], options?: object]): {\n args: readonly unknown[];\n options: object;\n} {\n const hasArgs = values.length && Array.isArray(values[0]);\n const args = hasArgs ? values[0]! : [];\n const options = (hasArgs ? values[1] : values[0]) ?? {};\n return { args, options };\n}\n\nexport type ContractWrite = {\n id: string;\n request: WriteContractParameters;\n result: Promise<Hex>;\n};\n\nexport type GetContractOptions<\n TTransport extends Transport,\n TAddress extends Address,\n TAbi extends Abi,\n TChain extends Chain,\n TAccount extends Account,\n TPublicClient extends PublicClient<TTransport, TChain>,\n TWalletClient extends WalletClient<TTransport, TChain, TAccount>,\n> = GetContractParameters<\n TTransport,\n TChain,\n TAccount,\n TAbi,\n { public: TPublicClient; wallet: TWalletClient },\n TAddress\n> & {\n onWrite?: (write: ContractWrite) => void;\n};\n\n// TODO: migrate away from this approach once we can hook into viem: https://github.com/wagmi-dev/viem/discussions/1230\n\n/** @deprecated Use `walletClient.extend(transactionQueue()).extend(writeObserver({ onWrite }))` and viem's `getContract` instead. */\nexport function getContract<\n TTransport extends Transport,\n TAddress extends Address,\n TAbi extends Abi,\n TChain extends Chain,\n TAccount extends Account,\n TPublicClient extends PublicClient<TTransport, TChain>,\n TWalletClient extends WalletClient<TTransport, TChain, TAccount>,\n>({\n abi,\n address,\n client: { public: publicClient, wallet: walletClient },\n onWrite,\n}: GetContractOptions<\n TTransport,\n TAddress,\n TAbi,\n TChain,\n TAccount,\n TPublicClient,\n TWalletClient\n>): GetContractReturnType<TAbi, { public: TPublicClient; wallet: TWalletClient }, TAddress> {\n const contract: GetContractReturnType<TAbi, { public: TPublicClient; wallet: TWalletClient }, TAddress> & {\n write: unknown;\n } = viem_getContract({\n abi,\n address,\n client: {\n public: publicClient,\n wallet: walletClient,\n },\n }) as never;\n\n if (contract.write) {\n // Replace write calls with our own. Implemented ~the same as viem, but adds better handling of nonces (via queue + retries).\n let nextWriteId = 0;\n contract.write = new Proxy(\n {},\n {\n get(_, functionName: string) {\n return (\n ...parameters: [\n args?: readonly unknown[],\n options?: UnionOmit<WriteContractParameters, \"abi\" | \"address\" | \"functionName\" | \"args\">,\n ]\n ) => {\n const { args, options } = getFunctionParameters(parameters);\n const request: WriteContractParameters<\n TAbi,\n ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\">,\n TChain,\n TAccount\n > = {\n abi,\n address,\n functionName,\n args,\n ...options,\n onWrite,\n } as never;\n const result = writeContract(walletClient, request, { publicClient }) as never;\n\n const id = `${walletClient.chain.id}:${walletClient.account.address}:${nextWriteId++}`;\n onWrite?.({\n id,\n request: request as WriteContractParameters,\n result,\n });\n\n return result;\n };\n },\n },\n );\n }\n\n return contract;\n}\n","import { generatePrivateKey, privateKeyToAccount } from \"viem/accounts\";\nimport { isHex, Hex } from \"viem\";\n\nfunction assertPrivateKey(privateKey: string, cacheKey: string): asserts privateKey is Hex {\n if (!isHex(privateKey)) {\n console.error(\"Private key found in cache is not valid hex\", { privateKey, cacheKey });\n throw new Error(`Private key found in cache (${cacheKey}) is not valid hex`);\n }\n // ensure we can extract address from private key\n // this should throw on bad private keys\n privateKeyToAccount(privateKey);\n}\n\nexport function getBurnerPrivateKey(cacheKey = \"mud:burnerWallet\"): Hex {\n const cachedPrivateKey = localStorage.getItem(cacheKey);\n\n if (cachedPrivateKey != null) {\n assertPrivateKey(cachedPrivateKey, cacheKey);\n return cachedPrivateKey;\n }\n\n const privateKey = generatePrivateKey();\n console.log(\"New burner wallet created:\", privateKeyToAccount(privateKey));\n localStorage.setItem(cacheKey, privateKey);\n return privateKey;\n}\n","type PartialLog = { readonly blockNumber: bigint | null; readonly logIndex: number | null };\n\nexport function logSort(a: PartialLog, b: PartialLog): number {\n if (a.blockNumber === b.blockNumber) {\n if (a.logIndex === b.logIndex) return 0;\n if (a.logIndex == null) return 1;\n if (b.logIndex == null) return -1;\n return a.logIndex - b.logIndex;\n }\n\n if (a.blockNumber == null) return 1;\n if (b.blockNumber == null) return -1;\n if (a.blockNumber > b.blockNumber) return 1;\n if (a.blockNumber < b.blockNumber) return -1;\n return 0;\n}\n","/**\n * Map with a LRU (least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n * @link https://github.com/wevm/viem/blob/0fa08e113a890e6672fdc64fa7a2206a840611ab/src/utils/lru.ts\n */\nexport class LruMap<key, value> extends Map<key, value> {\n maxSize: number;\n\n constructor(size: number) {\n super();\n this.maxSize = size;\n }\n\n override set(key: key, value: value): this {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n this.delete(this.keys().next().value);\n }\n return this;\n }\n}\n","import { Hex } from \"viem\";\n\n/**\n * Get the hex value at start/end positions. This will always return a valid hex string.\n *\n * If `start` is out of range, this returns `\"0x\"`.\n *\n * If `end` is specified and out of range, the result is right zero-padded to the desired length (`end - start`).\n */\nexport function readHex(data: Hex, start: number, end?: number): Hex {\n return `0x${data\n .replace(/^0x/, \"\")\n .slice(start * 2, end != null ? end * 2 : undefined)\n .padEnd(((end ?? start) - start) * 2, \"0\")}`;\n}\n","// Inspired by https://doc.rust-lang.org/std/result/\nexport type Result<Ok, Err = unknown> = { ok: Ok } | { error: Err };\n\nexport function isOk<Ok, Err>(result: Result<Ok, Err>): result is { ok: Ok } {\n return \"ok\" in result;\n}\n\nexport function isError<Ok, Err>(result: Result<Ok, Err>): result is { error: Err } {\n return \"error\" in result;\n}\n\nexport function unwrap<Ok, Err>(result: Result<Ok, Err>): Ok {\n if (isError(result)) {\n throw result.error;\n }\n return result.ok;\n}\n","import { Hex, concatHex } from \"viem\";\nimport { readHex } from \"./readHex\";\n\nexport function spliceHex(data: Hex, start: number, deleteCount = 0, newData: Hex = \"0x\"): Hex {\n return concatHex([readHex(data, 0, start), newData, readHex(data, start + deleteCount)]);\n}\n","import { Hex, Transport, keccak256 } from \"viem\";\nimport { debug as parentDebug } from \"./debug\";\n\nconst debug = parentDebug.extend(\"transportObserver\");\n\nexport function transportObserver<TTransport extends Transport>(transport: TTransport): TTransport {\n return ((opts) => {\n const result = transport(opts);\n const request: typeof result.request = async (req) => {\n if (req.method === \"eth_sendRawTransaction\" && req.params instanceof Array) {\n const txs = req.params.map((data: Hex) => keccak256(data));\n debug(\"saw txs\", txs);\n // TODO: pass these tx hashes into dev tools\n }\n // TODO: add support for `eth_sendTransaction`\n return result.request(req);\n };\n return {\n ...result,\n request,\n };\n }) as TTransport;\n}\n","import { getContract } from \"../getContract\";\n\n/** @deprecated use `getContract` instead */\nexport const createContract = getContract;\n","import { resourceToHex } from \"../resourceToHex\";\n\n/** @deprecated use `resourceToHex` instead */\nexport const resourceIdToHex = resourceToHex;\n","import { hexToResource } from \"../hexToResource\";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AAMI,EAAiBC,ECAvB,IAAMC,EAAkBC,ECAxB,IAAMC,EAAkBC","names":["createDebug","parentDebug","createBenchmark","namespace","debug","lastStep","stepName","secondsSinceLastStep","privateKeyToAccount","createBurnerAccount","privateKey","viem_getContract","getFunctionParameters","values","hasArgs","args","options","getContract","abi","address","publicClient","walletClient","onWrite","contract","viem_getContract","nextWriteId","_","functionName","parameters","request","result","writeContract","id","generatePrivateKey","privateKeyToAccount","isHex","assertPrivateKey","privateKey","cacheKey","getBurnerPrivateKey","cachedPrivateKey","logSort","a","b","LruMap","size","key","value","readHex","data","start","end","isOk","result","isError","unwrap","concatHex","spliceHex","data","start","deleteCount","newData","concatHex","readHex","keccak256","debug","transportObserver","transport","opts","result","req","txs","data","keccak256","createContract","getContract","resourceIdToHex","resourceToHex","hexToResourceId","hexToResource"]}
@@ -33,4 +33,4 @@ declare function getContractAddress({ deployerAddress, bytecode, salt, }: {
33
33
 
34
34
  declare function getDeployer(client: Client<Transport, Chain | undefined>): Promise<Address | undefined>;
35
35
 
36
- export { Contract, ensureContract, ensureContractsDeployed, ensureDeployer, getContractAddress, getDeployer, waitForTransactions };
36
+ export { type Contract, ensureContract, ensureContractsDeployed, ensureDeployer, getContractAddress, getDeployer, waitForTransactions };
package/dist/internal.js CHANGED
@@ -1,4 +1,4 @@
1
- import{e as g}from"./chunk-RCAJ6T6T.js";import{a as c}from"./chunk-TCWGPC6G.js";import{a as x}from"./chunk-Y4MH6TRP.js";import{waitForTransactionReceipt as T}from"viem/actions";async function C({client:e,hashes:o,debugLabel:a="transactions"}){if(o.length){c(`waiting for ${a} to confirm`);for(let r of o)if((await T(e,{hash:r})).status==="reverted")throw new Error(`Transaction reverted: ${r}`)}}import{concatHex as H,getCreate2Address as R}from"viem";import{getCode as P}from"viem/actions";import{stringToHex as $}from"viem";var p=$("",{size:32}),l=parseInt("6000",16);var f=c.extend("deploy"),E=c.extend("deploy");f.log=console.debug.bind(console);E.log=console.error.bind(console);async function h({client:e,deployerAddress:o,bytecode:a,deployedBytecodeSize:r,debugLabel:t="contract",salt:s=p}){if(a.includes("__$"))throw new Error(`Found unlinked public library in ${t} bytecode`);let i=R({from:o,salt:s,bytecode:a});return await P(e,{address:i,blockTag:"pending"})?(f("found",t,"at",i),[]):(r!=null&&(r>l?console.warn(`
1
+ import{e as g}from"./chunk-GUEDVXKC.js";import{a as c}from"./chunk-TCWGPC6G.js";import{a as x}from"./chunk-ZV2KGJCD.js";import{waitForTransactionReceipt as T}from"viem/actions";async function C({client:e,hashes:o,debugLabel:a="transactions"}){if(o.length){c(`waiting for ${a} to confirm`);for(let r of o)if((await T(e,{hash:r})).status==="reverted")throw new Error(`Transaction reverted: ${r}`)}}import{concatHex as H,getCreate2Address as R}from"viem";import{getCode as P}from"viem/actions";import{stringToHex as $}from"viem";var p=$("",{size:32}),l=parseInt("6000",16);var f=c.extend("deploy"),E=c.extend("deploy");f.log=console.debug.bind(console);E.log=console.error.bind(console);async function h({client:e,deployerAddress:o,bytecode:a,deployedBytecodeSize:r,debugLabel:t="contract",salt:s=p}){if(a.includes("__$"))throw new Error(`Found unlinked public library in ${t} bytecode`);let i=R({from:o,salt:s,bytecode:a});return await P(e,{address:i,blockTag:"pending"})?(f("found",t,"at",i),[]):(r!=null&&(r>l?console.warn(`
2
2
  Bytecode for ${t} (${r} bytes) is over the contract size limit (${l} bytes). Run \`forge build --sizes\` for more info.
3
3
  `):r>l*.95&&console.warn(`
4
4
  Bytecode for ${t} (${r} bytes) is almost over the contract size limit (${l} bytes). Run \`forge build --sizes\` for more info.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/waitForTransactions.ts","../src/deploy/ensureContract.ts","../src/deploy/common.ts","../src/deploy/debug.ts","../src/deploy/ensureContractsDeployed.ts","../src/deploy/ensureDeployer.ts","../src/deploy/create2/deployment.json","../src/deploy/getDeployer.ts","../src/deploy/getContractAddress.ts"],"sourcesContent":["import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { debug } from \"./debug\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\n\nexport async function waitForTransactions({\n client,\n hashes,\n debugLabel = \"transactions\",\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly hashes: readonly Hex[];\n readonly debugLabel?: string;\n}): Promise<void> {\n if (!hashes.length) return;\n\n debug(`waiting for ${debugLabel} to confirm`);\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n for (const hash of hashes) {\n const receipt = await waitForTransactionReceipt(client, { hash });\n // TODO: handle user op failures?\n if (receipt.status === \"reverted\") {\n throw new Error(`Transaction reverted: ${hash}`);\n }\n }\n}\n","import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex } from \"viem\";\nimport { getCode } from \"viem/actions\";\nimport { contractSizeLimit, singletonSalt } from \"./common\";\nimport { debug } from \"./debug\";\nimport { sendTransaction } from \"../sendTransaction\";\n\nexport type Contract = {\n bytecode: Hex;\n deployedBytecodeSize?: number;\n debugLabel?: string;\n salt?: Hex;\n};\n\nexport async function ensureContract({\n client,\n deployerAddress,\n bytecode,\n deployedBytecodeSize,\n debugLabel = \"contract\",\n salt = singletonSalt,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n} & Contract): Promise<readonly Hex[]> {\n if (bytecode.includes(\"__$\")) {\n throw new Error(`Found unlinked public library in ${debugLabel} bytecode`);\n }\n\n const address = getCreate2Address({ from: deployerAddress, salt, bytecode });\n\n const contractCode = await getCode(client, { address, blockTag: \"pending\" });\n if (contractCode) {\n debug(\"found\", debugLabel, \"at\", address);\n return [];\n }\n\n if (deployedBytecodeSize != null) {\n if (deployedBytecodeSize > contractSizeLimit) {\n console.warn(\n `\\nBytecode for ${debugLabel} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n } else if (deployedBytecodeSize > contractSizeLimit * 0.95) {\n console.warn(\n // eslint-disable-next-line max-len\n `\\nBytecode for ${debugLabel} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n }\n }\n\n debug(\"deploying\", debugLabel, \"at\", address);\n return [\n await sendTransaction(client, {\n chain: client.chain ?? null,\n to: deployerAddress,\n data: concatHex([salt, bytecode]),\n }),\n ];\n}\n","import { stringToHex } from \"viem\";\n\n// salt for deterministic deploys of singleton contracts\nexport const singletonSalt = stringToHex(\"\", { size: 32 });\n\n// https://eips.ethereum.org/EIPS/eip-170\nexport const contractSizeLimit = parseInt(\"6000\", 16);\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"deploy\");\nexport const error = parentDebug.extend(\"deploy\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n","import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { Contract, ensureContract } from \"./ensureContract\";\nimport { waitForTransactions } from \"../waitForTransactions\";\nimport { uniqueBy } from \"../utils/uniqueBy\";\n\nexport async function ensureContractsDeployed({\n client,\n deployerAddress,\n contracts,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n readonly contracts: readonly Contract[];\n}): Promise<readonly Hex[]> {\n // Deployments assume a deterministic deployer, so we only need to deploy the unique bytecode\n const uniqueContracts = uniqueBy(contracts, (contract) => contract.bytecode);\n\n const txs = (\n await Promise.all(uniqueContracts.map((contract) => ensureContract({ client, deployerAddress, ...contract })))\n ).flat();\n\n await waitForTransactions({\n client,\n hashes: txs,\n debugLabel: \"contract deploys\",\n });\n\n return txs;\n}\n","import { Account, Address, Chain, Client, Transport } from \"viem\";\nimport { getBalance, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\nimport { getDeployer } from \"./getDeployer\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<Address> {\n const existingDeployer = await getDeployer(client);\n if (existingDeployer !== undefined) {\n return existingDeployer;\n }\n\n // There's not really a way to simulate a pre-EIP-155 (no chain ID) transaction,\n // so we have to attempt to create the deployer first and, if it fails, fall back\n // to a regular deploy.\n\n // Send gas to deployment signer\n const gasRequired = BigInt(deployment.gasLimit) * BigInt(deployment.gasPrice);\n const currentBalance = await getBalance(client, { address: `0x${deployment.signerAddress}` });\n const gasNeeded = gasRequired - currentBalance;\n if (gasNeeded > 0) {\n debug(\"sending gas for CREATE2 deployer to signer at\", deployment.signerAddress);\n const gasTx = await sendTransaction(client, {\n chain: client.chain ?? null,\n to: `0x${deployment.signerAddress}`,\n value: gasNeeded,\n });\n const gasReceipt = await waitForTransactionReceipt(client, { hash: gasTx });\n if (gasReceipt.status !== \"success\") {\n console.error(\"failed to send gas to deployer signer\", gasReceipt);\n throw new Error(\"failed to send gas to deployer signer\");\n }\n }\n\n // Deploy the deployer\n debug(\"deploying CREATE2 deployer at\", deployer);\n const deployTx = await sendRawTransaction(client, { serializedTransaction: `0x${deployment.transaction}` }).catch(\n (error) => {\n // Do a regular contract create if the presigned transaction doesn't work due to replay protection\n if (String(error).includes(\"only replay-protected (EIP-155) transactions allowed over RPC\")) {\n console.warn(\n // eslint-disable-next-line max-len\n `\\n ⚠️ Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.\\n\\n We recommend running your chain's node with \\`--rpc.allow-unprotected-txs\\` to enable determinstic deployments.\\n`,\n );\n debug(\"deploying CREATE2 deployer\");\n return sendTransaction(client, {\n chain: client.chain ?? null,\n data: `0x${deployment.creationCode}`,\n });\n }\n throw error;\n },\n );\n\n const deployReceipt = await waitForTransactionReceipt(client, { hash: deployTx });\n if (!deployReceipt.contractAddress) {\n throw new Error(\"Deploy receipt did not have contract address, was the deployer not deployed?\");\n }\n\n if (deployReceipt.contractAddress !== deployer) {\n console.warn(\n `\\n ⚠️ CREATE2 deployer created at ${deployReceipt.contractAddress} does not match the CREATE2 determinstic deployer we expected (${deployer})`,\n );\n }\n\n return deployReceipt.contractAddress;\n}\n","{\n \"gasPrice\": 100000000000,\n \"gasLimit\": 100000,\n \"signerAddress\": \"3fab184622dc19b6109349b94811493bf2a45362\",\n \"transaction\": \"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222\",\n \"address\": \"4e59b44847b379578588920ca78fbf26c0b4956c\",\n \"creationCode\": \"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3\"\n}\n","import { Address, Chain, Client, Transport, sliceHex } from \"viem\";\nimport { getCode } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function getDeployer(client: Client<Transport, Chain | undefined>): Promise<Address | undefined> {\n const bytecode = await getCode(client, { address: deployer });\n if (bytecode) {\n debug(\"found deployer bytecode at\", deployer);\n // check if deployed bytecode is the same as the expected bytecode (minus 14-bytes creation code prefix)\n if (bytecode !== sliceHex(`0x${deployment.creationCode}`, 14)) {\n console.warn(\n `\\n ⚠️ Bytecode for deployer at ${deployer} did not match the expected CREATE2 bytecode. You may have unexpected results.\\n`,\n );\n }\n return deployer;\n }\n}\n","import { Hex, getCreate2Address } from \"viem\";\nimport { singletonSalt } from \"./common\";\n\nexport function getContractAddress({\n deployerAddress,\n bytecode,\n salt = singletonSalt,\n}: {\n readonly deployerAddress: Hex;\n readonly bytecode: Hex;\n readonly salt?: Hex;\n}): Hex {\n return getCreate2Address({ from: deployerAddress, bytecode, salt });\n}\n"],"mappings":"wHAEA,OAAS,6BAAAA,MAAiC,eAE1C,eAAsBC,E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es","debugLabel","debug","hash","concatHex","getCreate2Address","getCode","stringToHex","singletonSalt","contractSizeLimit","debug","error","ensureContract","client","deployerAddress","bytecode","deployedBytecodeSize","debugLabel","salt","singletonSalt","address","getCreate2Address","getCode","debug","contractSizeLimit","sendTransaction","concatHex","ensureContractsDeployed","client","deployerAddress","contracts","uniqueContracts","uniqueBy","contract","txs","ensureContract","waitForTransactions","getBalance","sendRawTransaction","sendTransaction","waitForTransactionReceipt","deployment_default","sliceHex","getCode","deployer","deployment_default","getDeployer","client","bytecode","getCode","debug","sliceHex","deployer","deployment_default","ensureDeployer","client","existingDeployer","getDeployer","gasRequired","currentBalance","getBalance","gasNeeded","debug","gasTx","sendTransaction","gasReceipt","waitForTransactionReceipt","deployTx","sendRawTransaction","error","deployReceipt","getCreate2Address","getContractAddress","deployerAddress","bytecode","salt","singletonSalt","getCreate2Address"]}
1
+ {"version":3,"sources":["../src/waitForTransactions.ts","../src/deploy/ensureContract.ts","../src/deploy/common.ts","../src/deploy/debug.ts","../src/deploy/ensureContractsDeployed.ts","../src/deploy/ensureDeployer.ts","../src/deploy/create2/deployment.json","../src/deploy/getDeployer.ts","../src/deploy/getContractAddress.ts"],"sourcesContent":["import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { debug } from \"./debug\";\nimport { waitForTransactionReceipt } from \"viem/actions\";\n\nexport async function waitForTransactions({\n client,\n hashes,\n debugLabel = \"transactions\",\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly hashes: readonly Hex[];\n readonly debugLabel?: string;\n}): Promise<void> {\n if (!hashes.length) return;\n\n debug(`waiting for ${debugLabel} to confirm`);\n // wait for each tx separately/serially, because parallelizing results in RPC errors\n for (const hash of hashes) {\n const receipt = await waitForTransactionReceipt(client, { hash });\n // TODO: handle user op failures?\n if (receipt.status === \"reverted\") {\n throw new Error(`Transaction reverted: ${hash}`);\n }\n }\n}\n","import { Client, Transport, Chain, Account, concatHex, getCreate2Address, Hex } from \"viem\";\nimport { getCode } from \"viem/actions\";\nimport { contractSizeLimit, singletonSalt } from \"./common\";\nimport { debug } from \"./debug\";\nimport { sendTransaction } from \"../sendTransaction\";\n\nexport type Contract = {\n bytecode: Hex;\n deployedBytecodeSize?: number;\n debugLabel?: string;\n salt?: Hex;\n};\n\nexport async function ensureContract({\n client,\n deployerAddress,\n bytecode,\n deployedBytecodeSize,\n debugLabel = \"contract\",\n salt = singletonSalt,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n} & Contract): Promise<readonly Hex[]> {\n if (bytecode.includes(\"__$\")) {\n throw new Error(`Found unlinked public library in ${debugLabel} bytecode`);\n }\n\n const address = getCreate2Address({ from: deployerAddress, salt, bytecode });\n\n const contractCode = await getCode(client, { address, blockTag: \"pending\" });\n if (contractCode) {\n debug(\"found\", debugLabel, \"at\", address);\n return [];\n }\n\n if (deployedBytecodeSize != null) {\n if (deployedBytecodeSize > contractSizeLimit) {\n console.warn(\n `\\nBytecode for ${debugLabel} (${deployedBytecodeSize} bytes) is over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n } else if (deployedBytecodeSize > contractSizeLimit * 0.95) {\n console.warn(\n // eslint-disable-next-line max-len\n `\\nBytecode for ${debugLabel} (${deployedBytecodeSize} bytes) is almost over the contract size limit (${contractSizeLimit} bytes). Run \\`forge build --sizes\\` for more info.\\n`,\n );\n }\n }\n\n debug(\"deploying\", debugLabel, \"at\", address);\n return [\n await sendTransaction(client, {\n chain: client.chain ?? null,\n to: deployerAddress,\n data: concatHex([salt, bytecode]),\n }),\n ];\n}\n","import { stringToHex } from \"viem\";\n\n// salt for deterministic deploys of singleton contracts\nexport const singletonSalt = stringToHex(\"\", { size: 32 });\n\n// https://eips.ethereum.org/EIPS/eip-170\nexport const contractSizeLimit = parseInt(\"6000\", 16);\n","import { debug as parentDebug } from \"../debug\";\n\nexport const debug = parentDebug.extend(\"deploy\");\nexport const error = parentDebug.extend(\"deploy\");\n\n// Pipe debug output to stdout instead of stderr\ndebug.log = console.debug.bind(console);\n\n// Pipe error output to stderr\nerror.log = console.error.bind(console);\n","import { Client, Transport, Chain, Account, Hex } from \"viem\";\nimport { Contract, ensureContract } from \"./ensureContract\";\nimport { waitForTransactions } from \"../waitForTransactions\";\nimport { uniqueBy } from \"../utils/uniqueBy\";\n\nexport async function ensureContractsDeployed({\n client,\n deployerAddress,\n contracts,\n}: {\n readonly client: Client<Transport, Chain | undefined, Account>;\n readonly deployerAddress: Hex;\n readonly contracts: readonly Contract[];\n}): Promise<readonly Hex[]> {\n // Deployments assume a deterministic deployer, so we only need to deploy the unique bytecode\n const uniqueContracts = uniqueBy(contracts, (contract) => contract.bytecode);\n\n const txs = (\n await Promise.all(uniqueContracts.map((contract) => ensureContract({ client, deployerAddress, ...contract })))\n ).flat();\n\n await waitForTransactions({\n client,\n hashes: txs,\n debugLabel: \"contract deploys\",\n });\n\n return txs;\n}\n","import { Account, Address, Chain, Client, Transport } from \"viem\";\nimport { getBalance, sendRawTransaction, sendTransaction, waitForTransactionReceipt } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\nimport { getDeployer } from \"./getDeployer\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function ensureDeployer(client: Client<Transport, Chain | undefined, Account>): Promise<Address> {\n const existingDeployer = await getDeployer(client);\n if (existingDeployer !== undefined) {\n return existingDeployer;\n }\n\n // There's not really a way to simulate a pre-EIP-155 (no chain ID) transaction,\n // so we have to attempt to create the deployer first and, if it fails, fall back\n // to a regular deploy.\n\n // Send gas to deployment signer\n const gasRequired = BigInt(deployment.gasLimit) * BigInt(deployment.gasPrice);\n const currentBalance = await getBalance(client, { address: `0x${deployment.signerAddress}` });\n const gasNeeded = gasRequired - currentBalance;\n if (gasNeeded > 0) {\n debug(\"sending gas for CREATE2 deployer to signer at\", deployment.signerAddress);\n const gasTx = await sendTransaction(client, {\n chain: client.chain ?? null,\n to: `0x${deployment.signerAddress}`,\n value: gasNeeded,\n });\n const gasReceipt = await waitForTransactionReceipt(client, { hash: gasTx });\n if (gasReceipt.status !== \"success\") {\n console.error(\"failed to send gas to deployer signer\", gasReceipt);\n throw new Error(\"failed to send gas to deployer signer\");\n }\n }\n\n // Deploy the deployer\n debug(\"deploying CREATE2 deployer at\", deployer);\n const deployTx = await sendRawTransaction(client, { serializedTransaction: `0x${deployment.transaction}` }).catch(\n (error) => {\n // Do a regular contract create if the presigned transaction doesn't work due to replay protection\n if (String(error).includes(\"only replay-protected (EIP-155) transactions allowed over RPC\")) {\n console.warn(\n // eslint-disable-next-line max-len\n `\\n ⚠️ Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.\\n\\n We recommend running your chain's node with \\`--rpc.allow-unprotected-txs\\` to enable determinstic deployments.\\n`,\n );\n debug(\"deploying CREATE2 deployer\");\n return sendTransaction(client, {\n chain: client.chain ?? null,\n data: `0x${deployment.creationCode}`,\n });\n }\n throw error;\n },\n );\n\n const deployReceipt = await waitForTransactionReceipt(client, { hash: deployTx });\n if (!deployReceipt.contractAddress) {\n throw new Error(\"Deploy receipt did not have contract address, was the deployer not deployed?\");\n }\n\n if (deployReceipt.contractAddress !== deployer) {\n console.warn(\n `\\n ⚠️ CREATE2 deployer created at ${deployReceipt.contractAddress} does not match the CREATE2 determinstic deployer we expected (${deployer})`,\n );\n }\n\n return deployReceipt.contractAddress;\n}\n","{\n \"gasPrice\": 100000000000,\n \"gasLimit\": 100000,\n \"signerAddress\": \"3fab184622dc19b6109349b94811493bf2a45362\",\n \"transaction\": \"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222\",\n \"address\": \"4e59b44847b379578588920ca78fbf26c0b4956c\",\n \"creationCode\": \"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3\"\n}\n","import { Address, Chain, Client, Transport, sliceHex } from \"viem\";\nimport { getCode } from \"viem/actions\";\nimport deployment from \"./create2/deployment.json\";\nimport { debug } from \"./debug\";\n\nconst deployer = `0x${deployment.address}` as const;\n\nexport async function getDeployer(client: Client<Transport, Chain | undefined>): Promise<Address | undefined> {\n const bytecode = await getCode(client, { address: deployer });\n if (bytecode) {\n debug(\"found deployer bytecode at\", deployer);\n // check if deployed bytecode is the same as the expected bytecode (minus 14-bytes creation code prefix)\n if (bytecode !== sliceHex(`0x${deployment.creationCode}`, 14)) {\n console.warn(\n `\\n ⚠️ Bytecode for deployer at ${deployer} did not match the expected CREATE2 bytecode. You may have unexpected results.\\n`,\n );\n }\n return deployer;\n }\n}\n","import { Hex, getCreate2Address } from \"viem\";\nimport { singletonSalt } from \"./common\";\n\nexport function getContractAddress({\n deployerAddress,\n bytecode,\n salt = singletonSalt,\n}: {\n readonly deployerAddress: Hex;\n readonly bytecode: Hex;\n readonly salt?: Hex;\n}): Hex {\n return getCreate2Address({ from: deployerAddress, bytecode, salt });\n}\n"],"mappings":"wHAEA,OAAS,6BAAAA,MAAiC,eAE1C,eAAsBC,EAAoB,CACxC,OAAAC,EACA,OAAAC,EACA,WAAAC,EAAa,cACf,EAIkB,CAChB,GAAKD,EAAO,OAEZ,CAAAE,EAAM,eAAeD,CAAU,aAAa,EAE5C,QAAWE,KAAQH,EAGjB,IAFgB,MAAMH,EAA0BE,EAAQ,CAAE,KAAAI,CAAK,CAAC,GAEpD,SAAW,WACrB,MAAM,IAAI,MAAM,yBAAyBA,CAAI,EAAE,EAGrD,CCxBA,OAA4C,aAAAC,EAAW,qBAAAC,MAA8B,OACrF,OAAS,WAAAC,MAAe,eCDxB,OAAS,eAAAC,MAAmB,OAGrB,IAAMC,EAAgBD,EAAY,GAAI,CAAE,KAAM,EAAG,CAAC,EAG5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AAIE,EAAW,SAAW,UACxB,cAAQ,MAAM,wCAAyCA,CAAU,EAC3D,IAAI,MAAM,uCAAuC,CAE3D,CAGAH,EAAM,gCAAiCV,CAAQ,EAC/C,IAAMe,EAAW,MAAMC,EAAmBb,EAAQ,CAAE,sBAAuB,KAAKF,EAAW,WAAW,EAAG,CAAC,EAAE,MACzGgB,GAAU,CAET,GAAI,OAAOA,CAAK,EAAE,SAAS,+DAA+D,EACxF,eAAQ,KAEN;AAAA;AAAA;AAAA;AAAA,CACF,EACAP,EAAM,4BAA4B,EAC3BE,EAAgBT,EAAQ,CAC7B,MAAOA,EAAO,OAAS,KACvB,KAAM,KAAKF,EAAW,YAAY,EACpC,CAAC,EAEH,MAAMgB,CACR,CACF,EAEMC,EAAgB,MAAMJ,EAA0BX,EAAQ,CAAE,KAAMY,CAAS,CAAC,EAChF,GAAI,CAACG,EAAc,gBACjB,MAAM,IAAI,MAAM,8EAA8E,EAGhG,OAAIA,EAAc,kBAAoBlB,GACpC,QAAQ,KACN;AAAA,6CAAsCkB,EAAc,eAAe,kEAAkElB,CAAQ,GAC/I,EAGKkB,EAAc,eACvB,CGpEA,OAAc,qBAAAC,MAAyB,OAGhC,SAASC,GAAmB,CACjC,gBAAAC,EACA,SAAAC,EACA,KAAAC,EAAOC,CACT,EAIQ,CACN,OAAOC,EAAkB,CAAE,KAAMJ,EAAiB,SAAAC,EAAU,KAAAC,CAAK,CAAC,CACpE","names":["waitForTransactionReceipt","waitForTransactions","client","hashes","debugLabel","debug","hash","concatHex","getCreate2Address","getCode","stringToHex","singletonSalt","contractSizeLimit","debug","error","ensureContract","client","deployerAddress","bytecode","deployedBytecodeSize","debugLabel","salt","singletonSalt","address","getCreate2Address","getCode","debug","contractSizeLimit","sendTransaction","concatHex","ensureContractsDeployed","client","deployerAddress","contracts","uniqueContracts","uniqueBy","contract","txs","ensureContract","waitForTransactions","getBalance","sendRawTransaction","sendTransaction","waitForTransactionReceipt","deployment_default","sliceHex","getCode","deployer","deployment_default","getDeployer","client","bytecode","getCode","debug","sliceHex","deployer","deployment_default","ensureDeployer","client","existingDeployer","getDeployer","gasRequired","currentBalance","getBalance","gasNeeded","debug","gasTx","sendTransaction","gasReceipt","waitForTransactionReceipt","deployTx","sendRawTransaction","error","deployReceipt","getCreate2Address","getContractAddress","deployerAddress","bytecode","salt","singletonSalt","getCreate2Address"]}
package/dist/kms.d.ts CHANGED
@@ -15,4 +15,4 @@ type KmsAccount = LocalAccount<"aws-kms"> & {
15
15
  */
16
16
  declare function kmsKeyToAccount({ keyId, client, }: KmsKeyToAccountOptions): Promise<KmsAccount>;
17
17
 
18
- export { KmsAccount, KmsKeyToAccountOptions, kmsKeyToAccount };
18
+ export { type KmsAccount, type KmsKeyToAccountOptions, kmsKeyToAccount };
package/dist/kms.js CHANGED
@@ -1,2 +1,2 @@
1
- import{KMSClient as k}from"@aws-sdk/client-kms";import{hashMessage as M,hashTypedData as E,keccak256 as B,serializeTransaction as G,signatureToHex as d}from"viem";import{toAccount as v}from"viem/accounts";import{isAddressEqual as g,signatureToHex as l,toHex as m}from"viem";import{recoverAddress as S}from"viem/utils";import{SignCommand as p}from"@aws-sdk/client-kms";import{fromHex as K}from"viem";async function c({keyId:t,hash:s,client:n}){let o=Buffer.from(K(s,"bytes")),e=new p({KeyId:t,Message:o,SigningAlgorithm:"ECDSA_SHA_256",MessageType:"DIGEST"});return n.send(e)}import b from"asn1.js";var h=b.define("EcdsaSig",function(){this.seq().obj(this.key("r").int(),this.key("s").int())});async function x(t){let s=await c(t);if(s.Signature===void 0)throw new Error("Signature is undefined.");let n=h.decode(Buffer.from(s.Signature),"der"),o=BigInt(n.r),e=BigInt(n.s),r=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),i=r/2n;return e>i&&(e=r-e),{r:m(o),s:m(e)}}async function C(t,s,n,o){let e;for(e=0;e<=1;e++){let r=l({r:s,s:n,v:e?28n:27n,yParity:e}),i=await S({hash:t,signature:r});if(g(i,o))return e}throw new Error("Failed to calculate recovery param")}async function a({hash:t,address:s,keyId:n,client:o}){let{r:e,s:r}=await x({keyId:n,hash:t,client:o}),i=await C(t,e,r,s);return{r:e,s:r,v:i?28n:27n,yParity:i}}import{toHex as I}from"viem";import{publicKeyToAddress as P}from"viem/utils";import{GetPublicKeyCommand as A}from"@aws-sdk/client-kms";function u({keyId:t,client:s}){let n=new A({KeyId:t});return s.send(n)}import H from"asn1.js";var w=H.define("EcdsaPubKey",function(){this.seq().obj(this.key("algo").seq().obj(this.key("a").objid(),this.key("b").objid()),this.key("pubKey").bitstr())});function T(t){let n=w.decode(Buffer.from(t)).pubKey.data,o=I(n);return P(o)}async function f({keyId:t,client:s}){let n=await u({keyId:t,client:s});return T(n.PublicKey)}async function O({keyId:t,client:s=new k}){let n=await f({keyId:t,client:s});return{...v({address:n,async signMessage({message:e}){let r=await a({client:s,keyId:t,hash:M(e),address:n});return d(r)},async signTransaction(e,{serializer:r=G}={}){let i=(()=>e.type==="eip4844"?{...e,sidecars:!1}:e)(),y=await a({client:s,keyId:t,hash:B(r(i)),address:n});return r(e,y)},async signTypedData(e){let r=await a({client:s,keyId:t,hash:E(e),address:n});return d(r)}}),source:"aws-kms",getKeyId:()=>t}}export{O as kmsKeyToAccount};
1
+ import{KMSClient as k}from"@aws-sdk/client-kms";import{hashMessage as M,hashTypedData as E,keccak256 as B,serializeTransaction as G,signatureToHex as d}from"viem";import{toAccount as v}from"viem/accounts";import{isAddressEqual as g,signatureToHex as l,toHex as m}from"viem";import{recoverAddress as S}from"viem/utils";import{SignCommand as p}from"@aws-sdk/client-kms";import{fromHex as K}from"viem";async function c({keyId:t,hash:s,client:n}){let o=Buffer.from(K(s,"bytes")),e=new p({KeyId:t,Message:o,SigningAlgorithm:"ECDSA_SHA_256",MessageType:"DIGEST"});return n.send(e)}import b from"asn1.js";var h=b.define("EcdsaSig",function(){this.seq().obj(this.key("r").int(),this.key("s").int())});async function x(t){let s=await c(t);if(s.Signature===void 0)throw new Error("Signature is undefined.");let n=h.decode(Buffer.from(s.Signature),"der"),o=BigInt(n.r),e=BigInt(n.s),r=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),i=r/2n;return e>i&&(e=r-e),{r:m(o),s:m(e)}}async function C(t,s,n,o){let e;for(e=0;e<=1;e++){let r=l({r:s,s:n,v:e?28n:27n,yParity:e}),i=await S({hash:t,signature:r});if(g(i,o))return e}throw new Error("Failed to calculate recovery param")}async function a({hash:t,address:s,keyId:n,client:o}){let{r:e,s:r}=await x({keyId:n,hash:t,client:o}),i=await C(t,e,r,s);return{r:e,s:r,v:i?28n:27n,yParity:i}}import{toHex as I}from"viem";import{publicKeyToAddress as P}from"viem/utils";import{GetPublicKeyCommand as A}from"@aws-sdk/client-kms";function u({keyId:t,client:s}){let n=new A({KeyId:t});return s.send(n)}import H from"asn1.js";var w=H.define("EcdsaPubKey",function(){this.seq().obj(this.key("algo").seq().obj(this.key("a").objid(),this.key("b").objid()),this.key("pubKey").bitstr())});function T(t){let n=w.decode(Buffer.from(t)).pubKey.data,o=I(n);return P(o)}async function f({keyId:t,client:s}){let n=await u({keyId:t,client:s});return T(n.PublicKey)}async function O({keyId:t,client:s=new k}){let n=await f({keyId:t,client:s});return{...v({address:n,async signMessage({message:e}){let r=await a({client:s,keyId:t,hash:M(e),address:n});return d(r)},async signTransaction(e,{serializer:r=G}={}){let i=e.type==="eip4844"?{...e,sidecars:!1}:e,y=await a({client:s,keyId:t,hash:B(r(i)),address:n});return r(e,y)},async signTypedData(e){let r=await a({client:s,keyId:t,hash:E(e),address:n});return d(r)}}),source:"aws-kms",getKeyId:()=>t}}export{O as kmsKeyToAccount};
2
2
  //# sourceMappingURL=kms.js.map
package/dist/kms.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/account/kms/kmsKeyToAccount.ts","../src/account/kms/signWithKms.ts","../src/account/kms/sign.ts","../src/account/kms/getAddressFromKms.ts","../src/account/kms/getPublicKey.ts"],"sourcesContent":["import { KMSClient } from \"@aws-sdk/client-kms\";\nimport { LocalAccount, hashMessage, hashTypedData, keccak256, serializeTransaction, signatureToHex } from \"viem\";\nimport { toAccount } from \"viem/accounts\";\nimport { signWithKms } from \"./signWithKms\";\nimport { getAddressFromKms } from \"./getAddressFromKms\";\n\nexport type KmsKeyToAccountOptions = {\n keyId: string;\n client?: KMSClient;\n};\n\nexport type KmsAccount = LocalAccount<\"aws-kms\"> & {\n getKeyId(): string;\n};\n\n/**\n * @description Creates an Account from a KMS key.\n *\n * @returns A Local Account.\n */\nexport async function kmsKeyToAccount({\n keyId,\n client = new KMSClient(),\n}: KmsKeyToAccountOptions): Promise<KmsAccount> {\n const address = await getAddressFromKms({ keyId, client });\n\n const account = toAccount({\n address,\n async signMessage({ message }) {\n const signature = await signWithKms({\n client,\n keyId,\n hash: hashMessage(message),\n address,\n });\n\n return signatureToHex(signature);\n },\n // The logic of this function should be align with viem's signTransaction\n // https://github.com/wevm/viem/blob/main/src/accounts/utils/signTransaction.ts\n async signTransaction(transaction, { serializer = serializeTransaction } = {}) {\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === \"eip4844\")\n return {\n ...transaction,\n sidecars: false,\n };\n return transaction;\n })();\n\n const signature = await signWithKms({\n client,\n keyId,\n hash: keccak256(serializer(signableTransaction)),\n address,\n });\n\n return serializer(transaction, signature);\n },\n async signTypedData(typedData) {\n const signature = await signWithKms({\n client,\n keyId,\n hash: hashTypedData(typedData),\n address,\n });\n\n return signatureToHex(signature);\n },\n });\n\n return {\n ...account,\n source: \"aws-kms\",\n getKeyId: () => keyId,\n };\n}\n","import { Hex, Signature, isAddressEqual, signatureToHex, toHex } from \"viem\";\nimport { recoverAddress } from \"viem/utils\";\nimport { KMSClient, SignCommandInput } from \"@aws-sdk/client-kms\";\nimport { sign } from \"./sign\";\n// @ts-expect-error Could not find a declaration file for module 'asn1.js'.\nimport asn1 from \"asn1.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst EcdsaSigAsnParse = asn1.define(\"EcdsaSig\", function (this: any) {\n this.seq().obj(this.key(\"r\").int(), this.key(\"s\").int());\n});\n\nasync function getRS(signParams: {\n hash: Hex;\n keyId: SignCommandInput[\"KeyId\"];\n client: KMSClient;\n}): Promise<{ r: Hex; s: Hex }> {\n const signature = await sign(signParams);\n\n if (signature.Signature === undefined) {\n throw new Error(\"Signature is undefined.\");\n }\n\n const decoded = EcdsaSigAsnParse.decode(Buffer.from(signature.Signature), \"der\");\n\n const r = BigInt(decoded.r);\n let s = BigInt(decoded.s);\n\n const secp256k1N = BigInt(\"0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141\");\n const secp256k1halfN = secp256k1N / 2n;\n\n if (s > secp256k1halfN) {\n s = secp256k1N - s;\n }\n\n return {\n r: toHex(r),\n s: toHex(s),\n };\n}\n\nasync function getRecovery(hash: Hex, r: Hex, s: Hex, expectedAddress: Hex): Promise<number> {\n let recovery: number;\n for (recovery = 0; recovery <= 1; recovery++) {\n const signature = signatureToHex({\n r,\n s,\n v: recovery ? 28n : 27n,\n yParity: recovery,\n });\n\n const address = await recoverAddress({ hash, signature });\n\n if (isAddressEqual(address, expectedAddress)) {\n return recovery;\n }\n }\n throw new Error(\"Failed to calculate recovery param\");\n}\n\ntype SignParameters = {\n hash: Hex;\n keyId: SignCommandInput[\"KeyId\"];\n client: KMSClient;\n address: Hex;\n};\n\ntype SignReturnType = Signature;\n\n/**\n * @description Signs a hash with a given KMS key.\n *\n * @param hash The hash to sign.\n *\n * @returns The signature.\n */\nexport async function signWithKms({ hash, address, keyId, client }: SignParameters): Promise<SignReturnType> {\n const { r, s } = await getRS({ keyId, hash, client });\n const recovery = await getRecovery(hash, r, s, address);\n\n return {\n r,\n s,\n v: recovery ? 28n : 27n,\n yParity: recovery,\n };\n}\n","import { KMSClient, SignCommand, SignCommandInput, SignCommandOutput } from \"@aws-sdk/client-kms\";\nimport { Hex, fromHex } from \"viem\";\n\nexport async function sign({\n keyId,\n hash,\n client,\n}: {\n hash: Hex;\n keyId: SignCommandInput[\"KeyId\"];\n client: KMSClient;\n}): Promise<SignCommandOutput> {\n const formatted = Buffer.from(fromHex(hash, \"bytes\"));\n\n const command = new SignCommand({\n KeyId: keyId,\n Message: formatted,\n SigningAlgorithm: \"ECDSA_SHA_256\",\n MessageType: \"DIGEST\",\n });\n\n return client.send(command);\n}\n","import { Address, toHex } from \"viem\";\nimport { publicKeyToAddress } from \"viem/utils\";\nimport { GetPublicKeyCommandInput, KMSClient } from \"@aws-sdk/client-kms\";\nimport { getPublicKey } from \"./getPublicKey\";\n// @ts-expect-error Could not find a declaration file for module 'asn1.js'.\nimport asn1 from \"asn1.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst EcdsaPubKey = asn1.define(\"EcdsaPubKey\", function (this: any) {\n this.seq().obj(this.key(\"algo\").seq().obj(this.key(\"a\").objid(), this.key(\"b\").objid()), this.key(\"pubKey\").bitstr());\n});\n\nfunction publicKeyKmsToAddress(publicKey: Uint8Array): Address {\n const res = EcdsaPubKey.decode(Buffer.from(publicKey));\n\n const publicKeyBuffer: Buffer = res.pubKey.data;\n\n const publicKeyHex = toHex(publicKeyBuffer);\n const address = publicKeyToAddress(publicKeyHex);\n\n return address;\n}\n\nexport async function getAddressFromKms({\n keyId,\n client,\n}: {\n keyId: GetPublicKeyCommandInput[\"KeyId\"];\n client: KMSClient;\n}): Promise<Address> {\n const KMSKey = await getPublicKey({ keyId, client });\n\n return publicKeyKmsToAddress(KMSKey.PublicKey as Uint8Array);\n}\n","import {\n GetPublicKeyCommand,\n GetPublicKeyCommandInput,\n GetPublicKeyCommandOutput,\n KMSClient,\n} from \"@aws-sdk/client-kms\";\n\nexport function getPublicKey({\n keyId,\n client,\n}: {\n keyId: GetPublicKeyCommandInput[\"KeyId\"];\n client: KMSClient;\n}): Promise<GetPublicKeyCommandOutput> {\n const command = new GetPublicKeyCommand({ KeyId: keyId });\n\n return client.send(command);\n}\n"],"mappings":"AAAA,OAAS,aAAAA,MAAiB,sBAC1B,OAAuB,eAAAC,EAAa,iBAAAC,EAAe,aAAAC,EAAW,wBAAAC,EAAsB,kBAAAC,MAAsB,OAC1G,OAAS,aAAAC,MAAiB,gBCF1B,OAAyB,kBAAAC,EAAgB,kBAAAC,EAAgB,SAAAC,MAAa,OACtE,OAAS,kBAAAC,MAAsB,aCD/B,OAAoB,eAAAC,MAAwD,sBAC5E,OAAc,WAAAC,MAAe,OAE7B,eAAsBC,EAAK,CACzB,MAAAC,EACA,KAAAC,EACA,OAAAC,CACF,EAI+B,CAC7B,IAAMC,EAAY,OAAO,KAAKL,EAAQG,EAAM,OAAO,CAAC,EAE9CG,EAAU,IAAIP,EAAY,CAC9B,MAAOG,EACP,QAASG,EACT,iBAAkB,gBAClB,YAAa,QACf,CAAC,EAED,OAAOD,EAAO,KAAKE,CAAO,CAC5B,CDjBA,OAAOC,MAAU,UAGjB,IAAMC,EAAmBD,EAAK,OAAO,WAAY,UAAqB,CACpE,KAAK,IAAI,EAAE,IAAI,KAAK,IAAI,GAAG,EAAE,IAAI,EAAG,KAAK,IAAI,GAAG,EAAE,IAAI,CAAC,CACzD,CAAC,EAED,eAAeE,EAAMC,EAIW,CAC9B,IAAMC,EAAY,MAAMC,EAAKF,CAAU,EAEvC,GAAIC,EAAU,YAAc,OAC1B,MAAM,IAAI,MAAM,yBAAyB,EAG3C,IAAME,EAAUL,EAAiB,OAAO,OAAO,KAAKG,EAAU,SAAS,EAAG,KAAK,EAEzEG,EAAI,OAAOD,EAAQ,CAAC,EACtBE,EAAI,OAAOF,EAAQ,CAAC,EAElBG,EAAa,OAAO,oEAAoE,EACxFC,EAAiBD,EAAa,GAE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AC7B,QAAAb,CACF,CAAC,EAED,OAAOO,EAAeH,CAAS,CACjC,CACF,CAAC,EAIC,OAAQ,UACR,SAAU,IAAMP,CAClB,CACF","names":["KMSClient","hashMessage","hashTypedData","keccak256","serializeTransaction","signatureToHex","toAccount","isAddressEqual","signatureToHex","toHex","recoverAddress","SignCommand","fromHex","sign","keyId","hash","client","formatted","command","asn1","EcdsaSigAsnParse","getRS","signParams","signature","sign","decoded","r","s","secp256k1N","secp256k1halfN","toHex","getRecovery","hash","expectedAddress","recovery","signatureToHex","address","recoverAddress","isAddressEqual","signWithKms","keyId","client","toHex","publicKeyToAddress","GetPublicKeyCommand","getPublicKey","keyId","client","command","asn1","EcdsaPubKey","publicKeyKmsToAddress","publicKey","publicKeyBuffer","publicKeyHex","toHex","publicKeyToAddress","getAddressFromKms","keyId","client","KMSKey","getPublicKey","kmsKeyToAccount","keyId","client","KMSClient","address","getAddressFromKms","toAccount","message","signature","signWithKms","hashMessage","signatureToHex","transaction","serializer","serializeTransaction","signableTransaction","keccak256","typedData","hashTypedData"]}
1
+ {"version":3,"sources":["../src/account/kms/kmsKeyToAccount.ts","../src/account/kms/signWithKms.ts","../src/account/kms/sign.ts","../src/account/kms/getAddressFromKms.ts","../src/account/kms/getPublicKey.ts"],"sourcesContent":["import { KMSClient } from \"@aws-sdk/client-kms\";\nimport { LocalAccount, hashMessage, hashTypedData, keccak256, serializeTransaction, signatureToHex } from \"viem\";\nimport { toAccount } from \"viem/accounts\";\nimport { signWithKms } from \"./signWithKms\";\nimport { getAddressFromKms } from \"./getAddressFromKms\";\n\nexport type KmsKeyToAccountOptions = {\n keyId: string;\n client?: KMSClient;\n};\n\nexport type KmsAccount = LocalAccount<\"aws-kms\"> & {\n getKeyId(): string;\n};\n\n/**\n * @description Creates an Account from a KMS key.\n *\n * @returns A Local Account.\n */\nexport async function kmsKeyToAccount({\n keyId,\n client = new KMSClient(),\n}: KmsKeyToAccountOptions): Promise<KmsAccount> {\n const address = await getAddressFromKms({ keyId, client });\n\n const account = toAccount({\n address,\n async signMessage({ message }) {\n const signature = await signWithKms({\n client,\n keyId,\n hash: hashMessage(message),\n address,\n });\n\n return signatureToHex(signature);\n },\n // The logic of this function should be align with viem's signTransaction\n // https://github.com/wevm/viem/blob/main/src/accounts/utils/signTransaction.ts\n async signTransaction(transaction, { serializer = serializeTransaction } = {}) {\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n const signableTransaction = (() => {\n // For EIP-4844 Transactions, we want to sign the transaction payload body (tx_payload_body) without the sidecars (ie. without the network wrapper).\n // See: https://github.com/ethereum/EIPs/blob/e00f4daa66bd56e2dbd5f1d36d09fd613811a48b/EIPS/eip-4844.md#networking\n if (transaction.type === \"eip4844\")\n return {\n ...transaction,\n sidecars: false,\n };\n return transaction;\n })();\n\n const signature = await signWithKms({\n client,\n keyId,\n hash: keccak256(serializer(signableTransaction)),\n address,\n });\n\n return serializer(transaction, signature);\n },\n async signTypedData(typedData) {\n const signature = await signWithKms({\n client,\n keyId,\n hash: hashTypedData(typedData),\n address,\n });\n\n return signatureToHex(signature);\n },\n });\n\n return {\n ...account,\n source: \"aws-kms\",\n getKeyId: () => keyId,\n };\n}\n","import { Hex, Signature, isAddressEqual, signatureToHex, toHex } from \"viem\";\nimport { recoverAddress } from \"viem/utils\";\nimport { KMSClient, SignCommandInput } from \"@aws-sdk/client-kms\";\nimport { sign } from \"./sign\";\n// @ts-expect-error Could not find a declaration file for module 'asn1.js'.\nimport asn1 from \"asn1.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst EcdsaSigAsnParse = asn1.define(\"EcdsaSig\", function (this: any) {\n this.seq().obj(this.key(\"r\").int(), this.key(\"s\").int());\n});\n\nasync function getRS(signParams: {\n hash: Hex;\n keyId: SignCommandInput[\"KeyId\"];\n client: KMSClient;\n}): Promise<{ r: Hex; s: Hex }> {\n const signature = await sign(signParams);\n\n if (signature.Signature === undefined) {\n throw new Error(\"Signature is undefined.\");\n }\n\n const decoded = EcdsaSigAsnParse.decode(Buffer.from(signature.Signature), \"der\");\n\n const r = BigInt(decoded.r);\n let s = BigInt(decoded.s);\n\n const secp256k1N = BigInt(\"0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141\");\n const secp256k1halfN = secp256k1N / 2n;\n\n if (s > secp256k1halfN) {\n s = secp256k1N - s;\n }\n\n return {\n r: toHex(r),\n s: toHex(s),\n };\n}\n\nasync function getRecovery(hash: Hex, r: Hex, s: Hex, expectedAddress: Hex): Promise<number> {\n let recovery: number;\n for (recovery = 0; recovery <= 1; recovery++) {\n const signature = signatureToHex({\n r,\n s,\n v: recovery ? 28n : 27n,\n yParity: recovery,\n });\n\n const address = await recoverAddress({ hash, signature });\n\n if (isAddressEqual(address, expectedAddress)) {\n return recovery;\n }\n }\n throw new Error(\"Failed to calculate recovery param\");\n}\n\ntype SignParameters = {\n hash: Hex;\n keyId: SignCommandInput[\"KeyId\"];\n client: KMSClient;\n address: Hex;\n};\n\ntype SignReturnType = Signature;\n\n/**\n * @description Signs a hash with a given KMS key.\n *\n * @param hash The hash to sign.\n *\n * @returns The signature.\n */\nexport async function signWithKms({ hash, address, keyId, client }: SignParameters): Promise<SignReturnType> {\n const { r, s } = await getRS({ keyId, hash, client });\n const recovery = await getRecovery(hash, r, s, address);\n\n return {\n r,\n s,\n v: recovery ? 28n : 27n,\n yParity: recovery,\n };\n}\n","import { KMSClient, SignCommand, SignCommandInput, SignCommandOutput } from \"@aws-sdk/client-kms\";\nimport { Hex, fromHex } from \"viem\";\n\nexport async function sign({\n keyId,\n hash,\n client,\n}: {\n hash: Hex;\n keyId: SignCommandInput[\"KeyId\"];\n client: KMSClient;\n}): Promise<SignCommandOutput> {\n const formatted = Buffer.from(fromHex(hash, \"bytes\"));\n\n const command = new SignCommand({\n KeyId: keyId,\n Message: formatted,\n SigningAlgorithm: \"ECDSA_SHA_256\",\n MessageType: \"DIGEST\",\n });\n\n return client.send(command);\n}\n","import { Address, toHex } from \"viem\";\nimport { publicKeyToAddress } from \"viem/utils\";\nimport { GetPublicKeyCommandInput, KMSClient } from \"@aws-sdk/client-kms\";\nimport { getPublicKey } from \"./getPublicKey\";\n// @ts-expect-error Could not find a declaration file for module 'asn1.js'.\nimport asn1 from \"asn1.js\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst EcdsaPubKey = asn1.define(\"EcdsaPubKey\", function (this: any) {\n this.seq().obj(this.key(\"algo\").seq().obj(this.key(\"a\").objid(), this.key(\"b\").objid()), this.key(\"pubKey\").bitstr());\n});\n\nfunction publicKeyKmsToAddress(publicKey: Uint8Array): Address {\n const res = EcdsaPubKey.decode(Buffer.from(publicKey));\n\n const publicKeyBuffer: Buffer = res.pubKey.data;\n\n const publicKeyHex = toHex(publicKeyBuffer);\n const address = publicKeyToAddress(publicKeyHex);\n\n return address;\n}\n\nexport async function getAddressFromKms({\n keyId,\n client,\n}: {\n keyId: GetPublicKeyCommandInput[\"KeyId\"];\n client: KMSClient;\n}): Promise<Address> {\n const KMSKey = await getPublicKey({ keyId, client });\n\n return publicKeyKmsToAddress(KMSKey.PublicKey as Uint8Array);\n}\n","import {\n GetPublicKeyCommand,\n GetPublicKeyCommandInput,\n GetPublicKeyCommandOutput,\n KMSClient,\n} from \"@aws-sdk/client-kms\";\n\nexport function getPublicKey({\n keyId,\n client,\n}: {\n keyId: GetPublicKeyCommandInput[\"KeyId\"];\n client: KMSClient;\n}): Promise<GetPublicKeyCommandOutput> {\n const command = new GetPublicKeyCommand({ KeyId: keyId });\n\n return client.send(command);\n}\n"],"mappings":"AAAA,OAAS,aAAAA,MAAiB,sBAC1B,OAAuB,eAAAC,EAAa,iBAAAC,EAAe,aAAAC,EAAW,wBAAAC,EAAsB,kBAAAC,MAAsB,OAC1G,OAAS,aAAAC,MAAiB,gBCF1B,OAAyB,kBAAAC,EAAgB,kBAAAC,EAAgB,SAAAC,MAAa,OACtE,OAAS,kBAAAC,MAAsB,aCD/B,OAAoB,eAAAC,MAAwD,sBA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gB,CACpC,MAAAC,EACA,OAAAC,EAAS,IAAIC,CACf,EAAgD,CAC9C,IAAMC,EAAU,MAAMC,EAAkB,CAAE,MAAAJ,EAAO,OAAAC,CAAO,CAAC,EAkDzD,MAAO,CACL,GAjDcI,EAAU,CACxB,QAAAF,EACA,MAAM,YAAY,CAAE,QAAAG,CAAQ,EAAG,CAC7B,IAAMC,EAAY,MAAMC,EAAY,CAClC,OAAAP,EACA,MAAAD,EACA,KAAMS,EAAYH,CAAO,EACzB,QAAAH,CACF,CAAC,EAED,OAAOO,EAAeH,CAAS,CACjC,EAGA,MAAM,gBAAgBI,EAAa,CAAE,WAAAC,EAAaC,CAAqB,EAAI,CAAC,EAAG,CAE7E,IAAMC,EAGAH,EAAY,OAAS,UAChB,CACL,GAAGA,EACH,SAAU,EACZ,EACKA,EAGHJ,EAAY,MAAMC,EAAY,CAClC,OAAAP,EACA,MAAAD,EACA,KAAMe,EAAUH,EAAWE,CAAmB,CAAC,EAC/C,QAAAX,CACF,CAAC,EAED,OAAOS,EAAWD,EAAaJ,CAAS,CAC1C,EACA,MAAM,cAAcS,EAAW,CAC7B,IAAMT,EAAY,MAAMC,EAAY,CAClC,OAAAP,EACA,MAAAD,EACA,KAAMiB,EAAcD,CAAS,EAC7B,QAAAb,CACF,CAAC,EAED,OAAOO,EAAeH,CAAS,CACjC,CACF,CAAC,EAIC,OAAQ,UACR,SAAU,IAAMP,CAClB,CACF","names":["KMSClient","hashMessage","hashTypedData","keccak256","serializeTransaction","signatureToHex","toAccount","isAddressEqual","signatureToHex","toHex","recoverAddress","SignCommand","fromHex","sign","keyId","hash","client","formatted","command","asn1","EcdsaSigAsnParse","getRS","signParams","signature","sign","decoded","r","s","secp256k1N","secp256k1halfN","toHex","getRecovery","hash","expectedAddress","recovery","signatureToHex","address","recoverAddress","isAddressEqual","signWithKms","keyId","client","toHex","publicKeyToAddress","GetPublicKeyCommand","getPublicKey","keyId","client","command","asn1","EcdsaPubKey","publicKeyKmsToAddress","publicKey","publicKeyBuffer","publicKeyHex","toHex","publicKeyToAddress","getAddressFromKms","keyId","client","KMSKey","getPublicKey","kmsKeyToAccount","keyId","client","KMSClient","address","getAddressFromKms","toAccount","message","signature","signWithKms","hashMessage","signatureToHex","transaction","serializer","serializeTransaction","signableTransaction","keccak256","typedData","hashTypedData"]}
@@ -16,4 +16,4 @@ type ReverseMap<T extends Record<any, any>> = {
16
16
 
17
17
  type ExtractUserTypes<UnknownTypes extends StringForUnion> = Exclude<UnknownTypes, AbiType | StaticArray>;
18
18
 
19
- export { AsDependent, ExtractUserTypes, OrDefault, OrDefaults, RequireKeys, ReverseMap, StringForUnion, UnionKeys, UnionOmit, UnionPick };
19
+ export type { AsDependent, ExtractUserTypes, OrDefault, OrDefaults, RequireKeys, ReverseMap, StringForUnion, UnionKeys, UnionOmit, UnionPick };
package/dist/utils.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as i}from"./chunk-Y4MH6TRP.js";function u(e,r){throw new Error(r??`Unexpected value: ${e}`)}function f(...e){return e.reduce((r,t)=>t>r?t:r)}function p(...e){return e.reduce((r,t)=>t<r?t:r)}function s(e,r){return e<r?-1:e>r?1:0}function*x(e,r){for(let t=0;t<e.length;t+=r)yield e.slice(t,t+r)}function y(e,r){let t=new Map;for(let o of e){let n=r(o);t.has(n)||t.set(n,[]),t.get(n).push(o)}return t}function T(e){return e}function b(e,r){return e.includes(r)}function w(e,r=" "){return e.replaceAll(/(^|\n)/g,`$1${r}`)}function h(e){return e!==void 0}function P(e){return e!==null}async function M(e){let r=[];for await(let t of e)r.push(t);return r}function q(e,r){return Object.fromEntries(Object.entries(e).map(([t,o])=>[t,r(o,t)]))}function O(e){return Array.from(new Set(e))}function C(e){return new Promise(r=>setTimeout(()=>r(),e))}function B(){return new Promise(e=>{typeof requestIdleCallback<"u"?requestIdleCallback(()=>e()):setTimeout(()=>e(),1)})}export{u as assertExhaustive,f as bigIntMax,p as bigIntMin,s as bigIntSort,x as chunk,y as groupBy,T as identity,b as includes,w as indent,h as isDefined,P as isNotNull,M as iteratorToArray,q as mapObject,O as unique,i as uniqueBy,C as wait,B as waitForIdle};
1
+ import{a as i}from"./chunk-ZV2KGJCD.js";function u(e,r){throw new Error(r??`Unexpected value: ${e}`)}function f(...e){return e.reduce((r,t)=>t>r?t:r)}function p(...e){return e.reduce((r,t)=>t<r?t:r)}function s(e,r){return e<r?-1:e>r?1:0}function*x(e,r){for(let t=0;t<e.length;t+=r)yield e.slice(t,t+r)}function y(e,r){let t=new Map;for(let o of e){let n=r(o);t.has(n)||t.set(n,[]),t.get(n).push(o)}return t}function T(e){return e}function b(e,r){return e.includes(r)}function w(e,r=" "){return e.replaceAll(/(^|\n)/g,`$1${r}`)}function h(e){return e!==void 0}function P(e){return e!==null}async function M(e){let r=[];for await(let t of e)r.push(t);return r}function q(e,r){return Object.fromEntries(Object.entries(e).map(([t,o])=>[t,r(o,t)]))}function O(e){return Array.from(new Set(e))}function C(e){return new Promise(r=>setTimeout(()=>r(),e))}function B(){return new Promise(e=>{typeof requestIdleCallback<"u"?requestIdleCallback(()=>e()):setTimeout(()=>e(),1)})}export{u as assertExhaustive,f as bigIntMax,p as bigIntMin,s as bigIntSort,x as chunk,y as groupBy,T as identity,b as includes,w as indent,h as isDefined,P as isNotNull,M as iteratorToArray,q as mapObject,O as unique,i as uniqueBy,C as wait,B as waitForIdle};
2
2
  //# sourceMappingURL=utils.js.map
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/assertExhaustive.ts","../src/utils/bigIntMax.ts","../src/utils/bigIntMin.ts","../src/utils/bigIntSort.ts","../src/utils/chunk.ts","../src/utils/groupBy.ts","../src/utils/identity.ts","../src/utils/includes.ts","../src/utils/indent.ts","../src/utils/isDefined.ts","../src/utils/isNotNull.ts","../src/utils/iteratorToArray.ts","../src/utils/mapObject.ts","../src/utils/unique.ts","../src/utils/wait.ts","../src/utils/waitForIdle.ts"],"sourcesContent":["export function assertExhaustive(value: never, message?: string): never {\n throw new Error(message ?? `Unexpected value: ${value}`);\n}\n","export function bigIntMax(...args: bigint[]): bigint {\n return args.reduce((m, e) => (e > m ? e : m));\n}\n","export function bigIntMin(...args: bigint[]): bigint {\n return args.reduce((m, e) => (e < m ? e : m));\n}\n","export function bigIntSort(a: bigint, b: bigint): -1 | 0 | 1 {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","export function* chunk<T>(arr: readonly T[], n: number): Generator<readonly T[], void> {\n for (let i = 0; i < arr.length; i += n) {\n yield arr.slice(i, i + n);\n }\n}\n","export function groupBy<value, key>(\n values: readonly value[],\n getKey: (value: value) => key,\n): Map<key, readonly value[]> {\n const map = new Map<key, readonly value[]>();\n for (const value of values) {\n const key = getKey(value);\n if (!map.has(key)) map.set(key, []);\n (map.get(key) as value[]).push(value);\n }\n return map;\n}\n","export function identity<T>(value: T): T {\n return value;\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function includes<item>(items: item[], value: any): value is item {\n return items.includes(value);\n}\n","export function indent(message: string, indentation = \" \"): string {\n return message.replaceAll(/(^|\\n)/g, `$1${indentation}`);\n}\n","export function isDefined<T>(argument: T | undefined): argument is T {\n return argument !== undefined;\n}\n","export function isNotNull<T>(argument: T | null): argument is T {\n return argument !== null;\n}\n","export async function iteratorToArray<T>(iterator: AsyncIterable<T>): Promise<readonly T[]> {\n const items: T[] = [];\n for await (const item of iterator) {\n items.push(item);\n }\n return items;\n}\n","/**\n * Map each key of a source object via a given valueMap function\n */\nexport function mapObject<\n Source extends Record<string | number | symbol, unknown>,\n Target extends { [key in keyof Source]: unknown },\n>(source: Source, valueMap: (value: Source[typeof key], key: keyof Source) => Target[typeof key]): Target {\n return Object.fromEntries(\n Object.entries(source).map(([key, value]) => [key, valueMap(value as Source[keyof Source], key)]),\n ) as Target;\n}\n","export function unique<value>(values: readonly value[]): readonly value[] {\n return Array.from(new Set(values));\n}\n","export function wait(ms: number): Promise<void> {\n return new Promise<void>((resolve) => setTimeout(() => resolve(), ms));\n}\n","export function waitForIdle(): Promise<void> {\n return new Promise<void>((resolve) => {\n if (typeof requestIdleCallback !== \"undefined\") {\n requestIdleCallback(() => resolve());\n } else {\n setTimeout(() => resolve(), 1);\n }\n });\n}\n"],"mappings":"wCAAO,SAASA,EAAiBC,EAAcC,EAAyB,CACtE,MAAM,IAAI,MAAMA,GAAW,qBAAqBD,GAAO,CACzD,CCFO,SAASE,KAAaC,EAAwB,CACnD,OAAOA,EAAK,OAAO,CAACC,EAAGC,IAAOA,EAAID,EAAIC,EAAID,CAAE,CAC9C,CCFO,SAASE,KAAaC,EAAwB,CACnD,OAAOA,EAAK,OAAO,CAACC,EAAGC,IAAOA,EAAID,EAAIC,EAAID,CAAE,CAC9C,CCFO,SAASE,EAAWC,EAAWC,EAAuB,CAC3D,OAAOD,EAAIC,EAAI,GAAKD,EAAIC,EAAI,EAAI,CAClC,CCFO,SAAUC,EAASC,EAAmBC,EAA0C,CACrF,QAASC,EAAI,EAAGA,EAAIF,EAAI,OAAQE,GAAKD,EACnC,MAAMD,EAAI,MAAME,EAAGA,EAAID,CAAC,CAE5B,CCJO,SAASE,EACdC,EACAC,EAC4B,CAC5B,IAAMC,EAAM,IAAI,IAChB,QAAWC,KAASH,EAAQ,CAC1B,IAAMI,EAAMH,EAAOE,CAAK,EACnBD,EAAI,IAAIE,CAAG,GAAGF,EAAI,IAAIE,EAAK,CAAC,CAAC,EACjCF,EAAI,IAAIE,CAAG,EAAc,KAAKD,CAAK,EAEtC,OAAOD,CACT,CCXO,SAASG,EAAYC,EAAa,CACvC,OAAOA,CACT,CCDO,SAASC,EAAeC,EAAeC,EAA2B,CACvE,OAAOD,EAAM,SAASC,CAAK,CAC7B,CCHO,SAASC,EAAOC,EAAiBC,EAAc,KAAc,CAClE,OAAOD,EAAQ,WAAW,UAAW,KAAKC,GAAa,CACzD,CCFO,SAASC,EAAaC,EAAwC,CACnE,OAAOA,IAAa,MACtB,CCFO,SAASC,EAAaC,EAAmC,CAC9D,OAAOA,IAAa,IACtB,CCFA,eAAsBC,EAAmBC,EAAmD,CAC1F,IAAMC,EAAa,CAAC,EACpB,cAAiBC,KAAQF,EACvBC,EAAM,KAAKC,CAAI,EAEjB,OAAOD,CACT,CCHO,SAASE,EAGdC,EAAgBC,EAAwF,CACxG,OAAO,OAAO,YACZ,OAAO,QAAQD,CAAM,EAAE,IAAI,CAAC,CAACE,EAAKC,CAAK,IAAM,CAACD,EAAKD,EAASE,EAA+BD,CAAG,CAAC,CAAC,CAClG,CACF,CCVO,SAASE,EAAcC,EAA4C,CACxE,OAAO,MAAM,KAAK,IAAI,IAAIA,CAAM,CAAC,CACnC,CCFO,SAASC,EAAKC,EAA2B,CAC9C,OAAO,IAAI,QAAeC,GAAY,WAAW,IAAMA,EAAQ,EAAGD,CAAE,CAAC,CACvE,CCFO,SAASE,GAA6B,CAC3C,OAAO,IAAI,QAAeC,GAAY,CAChC,OAAO,oBAAwB,IACjC,oBAAoB,IAAMA,EAAQ,CAAC,EAEnC,WAAW,IAAMA,EAAQ,EAAG,CAAC,CAEjC,CAAC,CACH","names":["assertExhaustive","value","message","bigIntMax","args","m","e","bigIntMin","args","m","e","bigIntSort","a","b","chunk","arr","n","i","groupBy","values","getKey","map","value","key","identity","value","includes","items","value","indent","message","indentation","isDefined","argument","isNotNull","argument","iteratorToArray","iterator","items","item","mapObject","source","valueMap","key","value","unique","values","wait","ms","resolve","waitForIdle","resolve"]}
1
+ {"version":3,"sources":["../src/utils/assertExhaustive.ts","../src/utils/bigIntMax.ts","../src/utils/bigIntMin.ts","../src/utils/bigIntSort.ts","../src/utils/chunk.ts","../src/utils/groupBy.ts","../src/utils/identity.ts","../src/utils/includes.ts","../src/utils/indent.ts","../src/utils/isDefined.ts","../src/utils/isNotNull.ts","../src/utils/iteratorToArray.ts","../src/utils/mapObject.ts","../src/utils/unique.ts","../src/utils/wait.ts","../src/utils/waitForIdle.ts"],"sourcesContent":["export function assertExhaustive(value: never, message?: string): never {\n throw new Error(message ?? `Unexpected value: ${value}`);\n}\n","export function bigIntMax(...args: bigint[]): bigint {\n return args.reduce((m, e) => (e > m ? e : m));\n}\n","export function bigIntMin(...args: bigint[]): bigint {\n return args.reduce((m, e) => (e < m ? e : m));\n}\n","export function bigIntSort(a: bigint, b: bigint): -1 | 0 | 1 {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","export function* chunk<T>(arr: readonly T[], n: number): Generator<readonly T[], void> {\n for (let i = 0; i < arr.length; i += n) {\n yield arr.slice(i, i + n);\n }\n}\n","export function groupBy<value, key>(\n values: readonly value[],\n getKey: (value: value) => key,\n): Map<key, readonly value[]> {\n const map = new Map<key, readonly value[]>();\n for (const value of values) {\n const key = getKey(value);\n if (!map.has(key)) map.set(key, []);\n (map.get(key) as value[]).push(value);\n }\n return map;\n}\n","export function identity<T>(value: T): T {\n return value;\n}\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function includes<item>(items: item[], value: any): value is item {\n return items.includes(value);\n}\n","export function indent(message: string, indentation = \" \"): string {\n return message.replaceAll(/(^|\\n)/g, `$1${indentation}`);\n}\n","export function isDefined<T>(argument: T | undefined): argument is T {\n return argument !== undefined;\n}\n","export function isNotNull<T>(argument: T | null): argument is T {\n return argument !== null;\n}\n","export async function iteratorToArray<T>(iterator: AsyncIterable<T>): Promise<readonly T[]> {\n const items: T[] = [];\n for await (const item of iterator) {\n items.push(item);\n }\n return items;\n}\n","/**\n * Map each key of a source object via a given valueMap function\n */\nexport function mapObject<\n Source extends Record<string | number | symbol, unknown>,\n Target extends { [key in keyof Source]: unknown },\n>(source: Source, valueMap: (value: Source[typeof key], key: keyof Source) => Target[typeof key]): Target {\n return Object.fromEntries(\n Object.entries(source).map(([key, value]) => [key, valueMap(value as Source[keyof Source], key)]),\n ) as Target;\n}\n","export function unique<value>(values: readonly value[]): readonly value[] {\n return Array.from(new Set(values));\n}\n","export function wait(ms: number): Promise<void> {\n return new Promise<void>((resolve) => setTimeout(() => resolve(), ms));\n}\n","export function waitForIdle(): Promise<void> {\n return new Promise<void>((resolve) => {\n if (typeof requestIdleCallback !== \"undefined\") {\n requestIdleCallback(() => resolve());\n } else {\n setTimeout(() => resolve(), 1);\n }\n });\n}\n"],"mappings":"wCAAO,SAASA,EAAiBC,EAAcC,EAAyB,CACtE,MAAM,IAAI,MAAMA,GAAW,qBAAqBD,CAAK,EAAE,CACzD,CCFO,SAASE,KAAaC,EAAwB,CACnD,OAAOA,EAAK,OAAO,CAACC,EAAGC,IAAOA,EAAID,EAAIC,EAAID,CAAE,CAC9C,CCFO,SAASE,KAAaC,EAAwB,CACnD,OAAOA,EAAK,OAAO,CAACC,EAAGC,IAAOA,EAAID,EAAIC,EAAID,CAAE,CAC9C,CCFO,SAASE,EAAWC,EAAWC,EAAuB,CAC3D,OAAOD,EAAIC,EAAI,GAAKD,EAAIC,EAAI,EAAI,CAClC,CCFO,SAAUC,EAASC,EAAmBC,EAA0C,CACrF,QAASC,EAAI,EAAGA,EAAIF,EAAI,OAAQE,GAAKD,EACnC,MAAMD,EAAI,MAAME,EAAGA,EAAID,CAAC,CAE5B,CCJO,SAASE,EACdC,EACAC,EAC4B,CAC5B,IAAMC,EAAM,IAAI,IAChB,QAAWC,KAASH,EAAQ,CAC1B,IAAMI,EAAMH,EAAOE,CAAK,EACnBD,EAAI,IAAIE,CAAG,GAAGF,EAAI,IAAIE,EAAK,CAAC,CAAC,EACjCF,EAAI,IAAIE,CAAG,EAAc,KAAKD,CAAK,CACtC,CACA,OAAOD,CACT,CCXO,SAASG,EAAYC,EAAa,CACvC,OAAOA,CACT,CCDO,SAASC,EAAeC,EAAeC,EAA2B,CACvE,OAAOD,EAAM,SAASC,CAAK,CAC7B,CCHO,SAASC,EAAOC,EAAiBC,EAAc,KAAc,CAClE,OAAOD,EAAQ,WAAW,UAAW,KAAKC,CAAW,EAAE,CACzD,CCFO,SAASC,EAAaC,EAAwC,CACnE,OAAOA,IAAa,MACtB,CCFO,SAASC,EAAaC,EAAmC,CAC9D,OAAOA,IAAa,IACtB,CCFA,eAAsBC,EAAmBC,EAAmD,CAC1F,IAAMC,EAAa,CAAC,EACpB,cAAiBC,KAAQF,EACvBC,EAAM,KAAKC,CAAI,EAEjB,OAAOD,CACT,CCHO,SAASE,EAGdC,EAAgBC,EAAwF,CACxG,OAAO,OAAO,YACZ,OAAO,QAAQD,CAAM,EAAE,IAAI,CAAC,CAACE,EAAKC,CAAK,IAAM,CAACD,EAAKD,EAASE,EAA+BD,CAAG,CAAC,CAAC,CAClG,CACF,CCVO,SAASE,EAAcC,EAA4C,CACxE,OAAO,MAAM,KAAK,IAAI,IAAIA,CAAM,CAAC,CACnC,CCFO,SAASC,EAAKC,EAA2B,CAC9C,OAAO,IAAI,QAAeC,GAAY,WAAW,IAAMA,EAAQ,EAAGD,CAAE,CAAC,CACvE,CCFO,SAASE,GAA6B,CAC3C,OAAO,IAAI,QAAeC,GAAY,CAChC,OAAO,oBAAwB,IACjC,oBAAoB,IAAMA,EAAQ,CAAC,EAEnC,WAAW,IAAMA,EAAQ,EAAG,CAAC,CAEjC,CAAC,CACH","names":["assertExhaustive","value","message","bigIntMax","args","m","e","bigIntMin","args","m","e","bigIntSort","a","b","chunk","arr","n","i","groupBy","values","getKey","map","value","key","identity","value","includes","items","value","indent","message","indentation","isDefined","argument","isNotNull","argument","iteratorToArray","iterator","items","item","mapObject","source","valueMap","key","value","unique","values","wait","ms","resolve","waitForIdle","resolve"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@latticexyz/common",
3
- "version": "2.2.15",
3
+ "version": "2.2.16-59389b1e37bc84664972231989ce7fdc739cce42",
4
4
  "description": "Common low level logic shared between packages",
5
5
  "repository": {
6
6
  "type": "git",
@@ -69,13 +69,11 @@
69
69
  "p-retry": "^5.1.2",
70
70
  "prettier": "3.2.5",
71
71
  "prettier-plugin-solidity": "1.3.1",
72
- "@latticexyz/schema-type": "2.2.15"
72
+ "@latticexyz/schema-type": "2.2.16-59389b1e37bc84664972231989ce7fdc739cce42"
73
73
  },
74
74
  "devDependencies": {
75
75
  "@types/debug": "^4.1.7",
76
- "@types/node": "^18.15.11",
77
76
  "@viem/anvil": "^0.0.7",
78
- "tsup": "^6.7.0",
79
77
  "viem": "2.21.19",
80
78
  "vitest": "0.34.6"
81
79
  },
@@ -1,2 +0,0 @@
1
- var r=class extends Error{name="MUDError"};export{r as a};
2
- //# sourceMappingURL=chunk-UPQEB2HW.js.map