@latticexyz/common 2.0.0-next.14 → 2.0.0-next.15
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/chains.d.ts +62 -0
- package/dist/chunk-TCWGPC6G.js +2 -0
- package/dist/chunk-TCWGPC6G.js.map +1 -0
- package/dist/codegen.d.ts +178 -0
- package/dist/codegen.js +14 -14
- package/dist/codegen.js.map +1 -1
- package/dist/errors.d.ts +5 -0
- package/dist/foundry.d.ts +74 -0
- package/dist/foundry.js.map +1 -1
- package/dist/index.d.ts +106 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/type-utils.d.ts +19 -0
- package/dist/utils.d.ts +41 -0
- package/dist/utils.js +1 -1
- package/dist/utils.js.map +1 -1
- package/package.json +2 -2
- package/src/codegen/debug.ts +7 -0
- package/src/codegen/modules.d.ts +1 -1
- package/src/createBenchmark.ts +17 -0
- package/src/debug.ts +7 -0
- package/src/foundry/index.ts +2 -0
- package/src/index.ts +2 -0
- package/src/result.ts +17 -0
- package/src/utils/chunk.ts +1 -1
- package/src/utils/groupBy.test.ts +32 -0
- package/src/utils/groupBy.ts +12 -0
- package/src/utils/includes.ts +3 -0
- package/src/utils/index.ts +3 -0
- package/src/utils/unique.test.ts +15 -0
- package/src/utils/unique.ts +3 -0
- package/dist/chunk-7WIPV3R3.js +0 -2
- package/dist/chunk-7WIPV3R3.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createBurnerAccount.ts","../src/createNonceManager.ts","../src/getNonceManagerId.ts","../src/getContract.ts","../src/writeContract.ts","../src/getNonceManager.ts","../src/getBurnerPrivateKey.ts","../src/hexToResource.ts","../src/resourceTypes.ts","../src/resourceToHex.ts","../src/readHex.ts","../src/sendTransaction.ts","../src/spliceHex.ts","../src/transportObserver.ts","../src/deprecated/createContract.ts","../src/deprecated/resourceIdToHex.ts","../src/deprecated/hexToResourceId.ts"],"sourcesContent":["import { Account, Hex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nexport function createBurnerAccount(privateKey: Hex): Account {\n const account = privateKeyToAccount(privateKey);\n // We may override account features here\n return {\n ...account,\n };\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\";\n\nconst debug = parentDebug.extend(\"createNonceManager\");\n\nexport type CreateNonceManagerOptions = {\n client: Client;\n address: Hex;\n blockTag?: BlockTag;\n broadcastChannelName?: string;\n};\n\nexport type CreateNonceManagerResult = {\n hasNonce: () => boolean;\n nextNonce: () => number;\n resetNonce: () => Promise<void>;\n shouldResetNonce: (error: unknown) => boolean;\n mempoolQueue: PQueue;\n};\n\nexport function createNonceManager({\n client,\n address, // TODO: rename to account?\n blockTag = \"pending\",\n broadcastChannelName,\n}: CreateNonceManagerOptions): CreateNonceManagerResult {\n const nonceRef = { current: -1 };\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 nonceRef.current = nonce;\n });\n });\n }\n\n function hasNonce(): boolean {\n return nonceRef.current >= 0;\n }\n\n function nextNonce(): number {\n if (!hasNonce()) throw new Error(\"call resetNonce before using nextNonce\");\n const nonce = nonceRef.current++;\n channel?.postMessage(JSON.stringify(nonceRef.current));\n return nonce;\n }\n\n async function resetNonce(): Promise<void> {\n const nonce = await getTransactionCount(client, { address, blockTag });\n nonceRef.current = nonce;\n channel?.postMessage(JSON.stringify(nonceRef.current));\n debug(\"reset nonce to\", nonceRef.current);\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: 1 });\n\n return {\n hasNonce,\n nextNonce,\n resetNonce,\n shouldResetNonce,\n mempoolQueue,\n };\n}\n","import { BlockTag, Client, Hex, getAddress } from \"viem\";\nimport { getChainId } from \"viem/actions\";\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 getChainId(client));\n return `mud:createNonceManager:${chainId}:${getAddress(address)}:${blockTag}`;\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 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> = Required<GetContractParameters<TTransport, TChain, TAccount, TAbi, TPublicClient, TWalletClient, TAddress>> & {\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\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 publicClient,\n walletClient,\n onWrite,\n}: GetContractOptions<\n TTransport,\n TAddress,\n TAbi,\n TChain,\n TAccount,\n TPublicClient,\n TWalletClient\n>): GetContractReturnType<TAbi, TPublicClient, TWalletClient, TAddress> {\n const contract = viem_getContract<TTransport, TAddress, TAbi, TChain, TAccount, TPublicClient, TWalletClient>({\n abi,\n address,\n publicClient,\n walletClient,\n }) as unknown as GetContractReturnType<Abi, PublicClient, WalletClient>;\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 = {\n abi,\n address,\n functionName,\n args,\n ...options,\n onWrite,\n } as unknown as WriteContractParameters<TAbi, typeof functionName, TChain, TAccount>;\n const result = writeContract(walletClient, request);\n\n const id = `${walletClient.chain.id}:${walletClient.account.address}:${nextWriteId++}`;\n onWrite?.({ id, request: request as WriteContractParameters, result });\n\n return result;\n };\n },\n }\n );\n }\n\n return contract as unknown as GetContractReturnType<TAbi, TPublicClient, TWalletClient, TAddress>;\n}\n","import {\n Abi,\n Account,\n Chain,\n Client,\n SimulateContractParameters,\n Transport,\n WriteContractParameters,\n WriteContractReturnType,\n} from \"viem\";\nimport { simulateContract, 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\";\n\nconst debug = parentDebug.extend(\"writeContract\");\n\n// TODO: migrate away from this approach once we can hook into viem's nonce management: https://github.com/wagmi-dev/viem/discussions/1230\n\nexport async function writeContract<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n TAbi extends Abi | readonly unknown[],\n TFunctionName extends string,\n TChainOverride extends Chain | undefined\n>(\n client: Client<Transport, TChain, TAccount>,\n request: WriteContractParameters<TAbi, TFunctionName, TChain, TAccount, TChainOverride>\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\n const nonceManager = await getNonceManager({\n client,\n address: account.address,\n blockTag: \"pending\",\n });\n\n async function prepareWrite(): Promise<\n WriteContractParameters<TAbi, TFunctionName, TChain, TAccount, TChainOverride>\n > {\n if (request.gas) {\n debug(\"gas provided, skipping simulate\", request.functionName, request.address);\n return request;\n }\n\n debug(\"simulating\", request.functionName, \"at\", request.address);\n const result = await simulateContract<TChain, TAbi, TFunctionName, TChainOverride>(client, {\n ...request,\n blockTag: \"pending\",\n account,\n } as unknown as SimulateContractParameters<TAbi, TFunctionName, TChain, TChainOverride>);\n\n return result.request as unknown as WriteContractParameters<TAbi, TFunctionName, TChain, TAccount, TChainOverride>;\n }\n\n const preparedWrite = await prepareWrite();\n\n return nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n if (!nonceManager.hasNonce()) {\n await nonceManager.resetNonce();\n }\n\n const nonce = nonceManager.nextNonce();\n debug(\"calling\", preparedWrite.functionName, \"with nonce\", nonce, \"at\", preparedWrite.address);\n return await viem_writeContract(client, { nonce, ...preparedWrite } as typeof preparedWrite);\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // On nonce errors, reset the nonce and retry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n await nonceManager.resetNonce();\n return;\n }\n // TODO: prepareWrite again if there are gas errors?\n throw error;\n },\n }\n ),\n { throwOnTimeout: true }\n );\n}\n","import { CreateNonceManagerOptions, CreateNonceManagerResult, createNonceManager } from \"./createNonceManager\";\nimport { getNonceManagerId } from \"./getNonceManagerId\";\n\nconst nonceManagers = new Map<string, CreateNonceManagerResult>();\n\nexport async function getNonceManager({\n client,\n address, // TODO: rename to account?\n blockTag = \"pending\",\n}: CreateNonceManagerOptions): Promise<CreateNonceManagerResult> {\n const id = await getNonceManagerId({ client, address, blockTag });\n\n const existingNonceManager = nonceManagers.get(id);\n if (existingNonceManager) {\n return existingNonceManager;\n }\n\n const nonceManager = createNonceManager({ client, address, blockTag });\n nonceManagers.set(id, nonceManager);\n return nonceManager;\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","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\";\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 (${resourceTypeId}:${namespace}:${name})`);\n }\n\n return { resourceId: hex, type, namespace, name };\n}\n","export const resourceTypes = [\"table\", \"offchainTable\", \"namespace\", \"module\", \"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 module: \"md\",\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 return concatHex([\n stringToHex(typeId, { size: 2 }),\n stringToHex(resource.namespace.slice(0, 14), { size: 14 }),\n stringToHex(resource.name.slice(0, 16), { size: 16 }),\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","import {\n Account,\n CallParameters,\n Chain,\n Client,\n SendTransactionParameters,\n Transport,\n WriteContractReturnType,\n} from \"viem\";\nimport { call, 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\";\n\nconst debug = parentDebug.extend(\"sendTransaction\");\n\n// TODO: migrate away from this approach once we can hook into viem's nonce management: https://github.com/wagmi-dev/viem/discussions/1230\n\nexport async function sendTransaction<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n TChainOverride extends Chain | undefined\n>(\n client: Client<Transport, TChain, TAccount>,\n request: SendTransactionParameters<TChain, TAccount, TChainOverride>\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\n const nonceManager = await getNonceManager({\n client,\n address: account.address,\n blockTag: \"pending\",\n });\n\n async function prepare(): Promise<SendTransactionParameters<TChain, TAccount, TChainOverride>> {\n if (request.gas) {\n debug(\"gas provided, skipping simulate\", request.to);\n return request;\n }\n\n debug(\"simulating tx to\", request.to);\n await call(client, {\n ...request,\n blockTag: \"pending\",\n account,\n } as CallParameters<TChain>);\n\n // TODO: estimate gas\n\n return request;\n }\n\n const preparedRequest = await prepare();\n\n return await nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n if (!nonceManager.hasNonce()) {\n await nonceManager.resetNonce();\n }\n\n const nonce = nonceManager.nextNonce();\n debug(\"sending tx with nonce\", nonce, \"to\", preparedRequest.to);\n return await viem_sendTransaction(client, { nonce, ...preparedRequest });\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // On nonce errors, reset the nonce and retry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n await nonceManager.resetNonce();\n return;\n }\n // TODO: prepare again if there are gas errors?\n throw error;\n },\n }\n ),\n { throwOnTimeout: true }\n );\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":"wCACA,OAAS,uBAAAA,MAA2B,gBAE7B,SAASC,GAAoBC,EAA0B,CAG5D,MAAO,CACL,GAHcF,EAAoBE,CAAU,CAI9C,CACF,CCTA,OAAS,aAAAC,EAAkC,qBAAAC,EAAmB,oBAAAC,MAAwB,OCAtF,OAAgC,cAAAC,MAAkB,OAClD,OAAS,cAAAC,MAAkB,eAE3B,eAAsBC,EAAkB,CACtC,OAAAC,EACA,QAAAC,EACA,SAAAC,CACF,EAIoB,CAGlB,MAAO,0BADSF,EAAO,O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I,OAAO,IAAKE,GAAcC,GAAUD,CAAI,CAAC,EACzDP,GAAM,UAAWM,CAAG,EAItB,OAAOF,EAAO,QAAQC,CAAG,CAC3B,CAIA,CACF,CACF,CCnBO,IAAMI,GAAiBC,ECAvB,IAAMC,GAAkBC,ECAxB,IAAMC,GAAkBC","names":["privateKeyToAccount","createBurnerAccount","privateKey","BaseError","NonceTooHighError","NonceTooLowError","getAddress","getChainId","getNonceManagerId","client","address","blockTag","getTransactionCount","PQueue","debug","createNonceManager","client","address","blockTag","broadcastChannelName","nonceRef","channel","getNonceManagerId","name","event","nonce","hasNonce","nextNonce","resetNonce","shouldResetNonce","error","BaseError","e","NonceTooLowError","NonceTooHighError","mempoolQueue","viem_getContract","simulateContract","viem_writeContract","pRetry","nonceManagers","getNonceManager","client","address","blockTag","id","getNonceManagerId","existingNonceManager","nonceManager","createNonceManager","parseAccount","debug","writeContract","client","request","rawAccount","account","nonceManager","getNonceManager","prepareWrite","simulateContract","preparedWrite","pRetry","nonce","viem_writeContract","error","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","hexToString","sliceHex","resourceTypes","stringToHex","concatHex","resourceTypeIds","resourceToHex","resource","typeId","resourceTypeIdToType","resourceTypeIds","key","value","getResourceType","resourceTypeId","type","resourceTypes","hexToResource","hex","hexToString","sliceHex","namespace","name","readHex","data","start","end","call","viem_sendTransaction","pRetry","parseAccount","debug","sendTransaction","client","request","rawAccount","account","nonceManager","getNonceManager","prepare","call","preparedRequest","pRetry","nonce","viem_sendTransaction","error","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/createNonceManager.ts","../src/getNonceManagerId.ts","../src/getContract.ts","../src/writeContract.ts","../src/getNonceManager.ts","../src/getBurnerPrivateKey.ts","../src/hexToResource.ts","../src/resourceTypes.ts","../src/resourceToHex.ts","../src/readHex.ts","../src/result.ts","../src/sendTransaction.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 { Account, Hex } from \"viem\";\nimport { privateKeyToAccount } from \"viem/accounts\";\n\nexport function createBurnerAccount(privateKey: Hex): Account {\n const account = privateKeyToAccount(privateKey);\n // We may override account features here\n return {\n ...account,\n };\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\";\n\nconst debug = parentDebug.extend(\"createNonceManager\");\n\nexport type CreateNonceManagerOptions = {\n client: Client;\n address: Hex;\n blockTag?: BlockTag;\n broadcastChannelName?: string;\n};\n\nexport type CreateNonceManagerResult = {\n hasNonce: () => boolean;\n nextNonce: () => number;\n resetNonce: () => Promise<void>;\n shouldResetNonce: (error: unknown) => boolean;\n mempoolQueue: PQueue;\n};\n\nexport function createNonceManager({\n client,\n address, // TODO: rename to account?\n blockTag = \"pending\",\n broadcastChannelName,\n}: CreateNonceManagerOptions): CreateNonceManagerResult {\n const nonceRef = { current: -1 };\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 nonceRef.current = nonce;\n });\n });\n }\n\n function hasNonce(): boolean {\n return nonceRef.current >= 0;\n }\n\n function nextNonce(): number {\n if (!hasNonce()) throw new Error(\"call resetNonce before using nextNonce\");\n const nonce = nonceRef.current++;\n channel?.postMessage(JSON.stringify(nonceRef.current));\n return nonce;\n }\n\n async function resetNonce(): Promise<void> {\n const nonce = await getTransactionCount(client, { address, blockTag });\n nonceRef.current = nonce;\n channel?.postMessage(JSON.stringify(nonceRef.current));\n debug(\"reset nonce to\", nonceRef.current);\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: 1 });\n\n return {\n hasNonce,\n nextNonce,\n resetNonce,\n shouldResetNonce,\n mempoolQueue,\n };\n}\n","import { BlockTag, Client, Hex, getAddress } from \"viem\";\nimport { getChainId } from \"viem/actions\";\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 getChainId(client));\n return `mud:createNonceManager:${chainId}:${getAddress(address)}:${blockTag}`;\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 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> = Required<GetContractParameters<TTransport, TChain, TAccount, TAbi, TPublicClient, TWalletClient, TAddress>> & {\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\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 publicClient,\n walletClient,\n onWrite,\n}: GetContractOptions<\n TTransport,\n TAddress,\n TAbi,\n TChain,\n TAccount,\n TPublicClient,\n TWalletClient\n>): GetContractReturnType<TAbi, TPublicClient, TWalletClient, TAddress> {\n const contract = viem_getContract<TTransport, TAddress, TAbi, TChain, TAccount, TPublicClient, TWalletClient>({\n abi,\n address,\n publicClient,\n walletClient,\n }) as unknown as GetContractReturnType<Abi, PublicClient, WalletClient>;\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 = {\n abi,\n address,\n functionName,\n args,\n ...options,\n onWrite,\n } as unknown as WriteContractParameters<TAbi, typeof functionName, TChain, TAccount>;\n const result = writeContract(walletClient, request);\n\n const id = `${walletClient.chain.id}:${walletClient.account.address}:${nextWriteId++}`;\n onWrite?.({ id, request: request as WriteContractParameters, result });\n\n return result;\n };\n },\n }\n );\n }\n\n return contract as unknown as GetContractReturnType<TAbi, TPublicClient, TWalletClient, TAddress>;\n}\n","import {\n Abi,\n Account,\n Chain,\n Client,\n SimulateContractParameters,\n Transport,\n WriteContractParameters,\n WriteContractReturnType,\n} from \"viem\";\nimport { simulateContract, 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\";\n\nconst debug = parentDebug.extend(\"writeContract\");\n\n// TODO: migrate away from this approach once we can hook into viem's nonce management: https://github.com/wagmi-dev/viem/discussions/1230\n\nexport async function writeContract<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n TAbi extends Abi | readonly unknown[],\n TFunctionName extends string,\n TChainOverride extends Chain | undefined\n>(\n client: Client<Transport, TChain, TAccount>,\n request: WriteContractParameters<TAbi, TFunctionName, TChain, TAccount, TChainOverride>\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\n const nonceManager = await getNonceManager({\n client,\n address: account.address,\n blockTag: \"pending\",\n });\n\n async function prepareWrite(): Promise<\n WriteContractParameters<TAbi, TFunctionName, TChain, TAccount, TChainOverride>\n > {\n if (request.gas) {\n debug(\"gas provided, skipping simulate\", request.functionName, request.address);\n return request;\n }\n\n debug(\"simulating\", request.functionName, \"at\", request.address);\n const result = await simulateContract<TChain, TAbi, TFunctionName, TChainOverride>(client, {\n ...request,\n blockTag: \"pending\",\n account,\n } as unknown as SimulateContractParameters<TAbi, TFunctionName, TChain, TChainOverride>);\n\n return result.request as unknown as WriteContractParameters<TAbi, TFunctionName, TChain, TAccount, TChainOverride>;\n }\n\n const preparedWrite = await prepareWrite();\n\n return nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n if (!nonceManager.hasNonce()) {\n await nonceManager.resetNonce();\n }\n\n const nonce = nonceManager.nextNonce();\n debug(\"calling\", preparedWrite.functionName, \"with nonce\", nonce, \"at\", preparedWrite.address);\n return await viem_writeContract(client, { nonce, ...preparedWrite } as typeof preparedWrite);\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // On nonce errors, reset the nonce and retry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n await nonceManager.resetNonce();\n return;\n }\n // TODO: prepareWrite again if there are gas errors?\n throw error;\n },\n }\n ),\n { throwOnTimeout: true }\n );\n}\n","import { CreateNonceManagerOptions, CreateNonceManagerResult, createNonceManager } from \"./createNonceManager\";\nimport { getNonceManagerId } from \"./getNonceManagerId\";\n\nconst nonceManagers = new Map<string, CreateNonceManagerResult>();\n\nexport async function getNonceManager({\n client,\n address, // TODO: rename to account?\n blockTag = \"pending\",\n}: CreateNonceManagerOptions): Promise<CreateNonceManagerResult> {\n const id = await getNonceManagerId({ client, address, blockTag });\n\n const existingNonceManager = nonceManagers.get(id);\n if (existingNonceManager) {\n return existingNonceManager;\n }\n\n const nonceManager = createNonceManager({ client, address, blockTag });\n nonceManagers.set(id, nonceManager);\n return nonceManager;\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","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\";\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 (${resourceTypeId}:${namespace}:${name})`);\n }\n\n return { resourceId: hex, type, namespace, name };\n}\n","export const resourceTypes = [\"table\", \"offchainTable\", \"namespace\", \"module\", \"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 module: \"md\",\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 return concatHex([\n stringToHex(typeId, { size: 2 }),\n stringToHex(resource.namespace.slice(0, 14), { size: 14 }),\n stringToHex(resource.name.slice(0, 16), { size: 16 }),\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 {\n Account,\n CallParameters,\n Chain,\n Client,\n SendTransactionParameters,\n Transport,\n WriteContractReturnType,\n} from \"viem\";\nimport { call, 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\";\n\nconst debug = parentDebug.extend(\"sendTransaction\");\n\n// TODO: migrate away from this approach once we can hook into viem's nonce management: https://github.com/wagmi-dev/viem/discussions/1230\n\nexport async function sendTransaction<\n TChain extends Chain | undefined,\n TAccount extends Account | undefined,\n TChainOverride extends Chain | undefined\n>(\n client: Client<Transport, TChain, TAccount>,\n request: SendTransactionParameters<TChain, TAccount, TChainOverride>\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\n const nonceManager = await getNonceManager({\n client,\n address: account.address,\n blockTag: \"pending\",\n });\n\n async function prepare(): Promise<SendTransactionParameters<TChain, TAccount, TChainOverride>> {\n if (request.gas) {\n debug(\"gas provided, skipping simulate\", request.to);\n return request;\n }\n\n debug(\"simulating tx to\", request.to);\n await call(client, {\n ...request,\n blockTag: \"pending\",\n account,\n } as CallParameters<TChain>);\n\n // TODO: estimate gas\n\n return request;\n }\n\n const preparedRequest = await prepare();\n\n return await nonceManager.mempoolQueue.add(\n () =>\n pRetry(\n async () => {\n if (!nonceManager.hasNonce()) {\n await nonceManager.resetNonce();\n }\n\n const nonce = nonceManager.nextNonce();\n debug(\"sending tx with nonce\", nonce, \"to\", preparedRequest.to);\n return await viem_sendTransaction(client, { nonce, ...preparedRequest });\n },\n {\n retries: 3,\n onFailedAttempt: async (error) => {\n // On nonce errors, reset the nonce and retry\n if (nonceManager.shouldResetNonce(error)) {\n debug(\"got nonce error, retrying\", error.message);\n await nonceManager.resetNonce();\n return;\n }\n // TODO: prepare again if there are gas errors?\n throw error;\n },\n }\n ),\n { throwOnTimeout: true }\n );\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":"wCAAA,OAAOA,MAAiB,QAExB,IAAMC,EAAcD,EAAY,eAAe,EAG/CC,EAAY,IAAM,QAAQ,KAAK,KAAK,OAAO,EAEpC,SAASC,GAAgBC,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,GAAoBC,EAA0B,CAG5D,MAAO,CACL,GAHcF,EAAoBE,CAAU,CAI9C,CACF,CCTA,OAAS,aAAAC,EAAkC,qBAAAC,EAAmB,oBAAAC,MAAwB,OCAtF,OAAgC,cAAAC,MAAkB,OAClD,OAAS,cAAAC,MAAkB,eAE3B,eAAsBC,EAAkB,CACtC,OAAAC,EACA,QAAAC,EACA,SAAAC,CACF,EAIoB,CAGlB,MAAO,0BADSF,EAAO,OAAO,IAAO,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gDC,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,GAAUD,CAAI,CAAC,EACzDP,GAAM,UAAWM,CAAG,EAItB,OAAOF,EAAO,QAAQC,CAAG,CAC3B,CAIA,CACF,CACF,CCnBO,IAAMI,GAAiBC,ECAvB,IAAMC,GAAkBC,ECAxB,IAAMC,GAAkBC","names":["createDebug","parentDebug","createBenchmark","namespace","debug","lastStep","stepName","secondsSinceLastStep","privateKeyToAccount","createBurnerAccount","privateKey","BaseError","NonceTooHighError","NonceTooLowError","getAddress","getChainId","getNonceManagerId","client","address","blockTag","getTransactionCount","PQueue","debug","createNonceManager","client","address","blockTag","broadcastChannelName","nonceRef","channel","getNonceManagerId","name","event","nonce","hasNonce","nextNonce","resetNonce","shouldResetNonce","error","BaseError","e","NonceTooLowError","NonceTooHighError","mempoolQueue","viem_getContract","simulateContract","viem_writeContract","pRetry","nonceManagers","getNonceManager","client","address","blockTag","id","getNonceManagerId","existingNonceManager","nonceManager","createNonceManager","parseAccount","debug","writeContract","client","request","rawAccount","account","nonceManager","getNonceManager","prepareWrite","simulateContract","preparedWrite","pRetry","nonce","viem_writeContract","error","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","hexToString","sliceHex","resourceTypes","stringToHex","concatHex","resourceTypeIds","resourceToHex","resource","typeId","resourceTypeIdToType","resourceTypeIds","key","value","getResourceType","resourceTypeId","type","resourceTypes","hexToResource","hex","hexToString","sliceHex","namespace","name","readHex","data","start","end","isOk","result","isError","unwrap","call","viem_sendTransaction","pRetry","parseAccount","debug","sendTransaction","client","request","rawAccount","account","nonceManager","getNonceManager","prepare","call","preparedRequest","pRetry","nonce","viem_sendTransaction","error","concatHex","spliceHex","data","start","deleteCount","newData","concatHex","readHex","keccak256","debug","transportObserver","transport","opts","result","req","txs","data","keccak256","createContract","getContract","resourceIdToHex","resourceToHex","hexToResourceId","hexToResource"]}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { AbiType, StaticArray } from '@latticexyz/schema-type/deprecated';
|
|
2
|
+
|
|
3
|
+
type RequireKeys<T extends Record<string, unknown>, P extends string> = T & Required<Pick<T, P>>;
|
|
4
|
+
type StringForUnion = string & Record<never, never>;
|
|
5
|
+
type AsDependent<T> = T extends infer P ? P : never;
|
|
6
|
+
type OrDefault<T, Default> = T extends undefined ? Default : T;
|
|
7
|
+
type OrDefaults<T extends object, Defaults> = {
|
|
8
|
+
[key in keyof Defaults]: key extends keyof T ? OrDefault<T[key], Defaults[key]> : Defaults[key];
|
|
9
|
+
};
|
|
10
|
+
type UnionOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
|
|
11
|
+
type UnionKeys<T> = T extends any ? keyof T : never;
|
|
12
|
+
type UnionPick<T, K extends UnionKeys<T>> = T extends any ? Pick<T, Extract<K, keyof T>> : never;
|
|
13
|
+
type ReverseMap<T extends Record<any, any>> = {
|
|
14
|
+
[K in keyof T as T[K]]: K;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
type ExtractUserTypes<UnknownTypes extends StringForUnion> = Exclude<UnknownTypes, AbiType | StaticArray>;
|
|
18
|
+
|
|
19
|
+
export { AsDependent, ExtractUserTypes, OrDefault, OrDefaults, RequireKeys, ReverseMap, StringForUnion, UnionKeys, UnionOmit, UnionPick };
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
declare function assertExhaustive(value: never, message?: string): never;
|
|
2
|
+
|
|
3
|
+
declare function bigIntMax(...args: bigint[]): bigint;
|
|
4
|
+
|
|
5
|
+
declare function bigIntMin(...args: bigint[]): bigint;
|
|
6
|
+
|
|
7
|
+
declare function bigIntSort(a: bigint, b: bigint): -1 | 0 | 1;
|
|
8
|
+
|
|
9
|
+
declare function chunk<T>(arr: readonly T[], n: number): Generator<readonly T[], void>;
|
|
10
|
+
|
|
11
|
+
declare function curry<F extends (...params: [...P, ...any[]]) => any, P extends any[]>(func: F, ...partialParams: P): CurryParams<F, P>;
|
|
12
|
+
type CurryParams<F extends (...params: [...PartialParams, ...any[]]) => any, PartialParams extends any[]> = F extends (...params: [...PartialParams, ...infer RemainingParams]) => infer Result ? (...params: RemainingParams) => Result : never;
|
|
13
|
+
|
|
14
|
+
declare function groupBy<value, key>(values: readonly value[], getKey: (value: value) => key): Map<key, readonly value[]>;
|
|
15
|
+
|
|
16
|
+
declare function identity<T>(value: T): T;
|
|
17
|
+
|
|
18
|
+
declare function includes<item>(items: item[], value: any): value is item;
|
|
19
|
+
|
|
20
|
+
declare function isDefined<T>(argument: T | undefined): argument is T;
|
|
21
|
+
|
|
22
|
+
declare function isNotNull<T>(argument: T | null): argument is T;
|
|
23
|
+
|
|
24
|
+
declare function iteratorToArray<T>(iterator: AsyncIterable<T>): Promise<T[]>;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Map each key of a source object via a given valueMap function
|
|
28
|
+
*/
|
|
29
|
+
declare function mapObject<Source extends Record<string | number | symbol, unknown>, Target extends {
|
|
30
|
+
[key in keyof Source]: unknown;
|
|
31
|
+
}>(source: Source, valueMap: (value: Source[typeof key], key: keyof Source) => Target[typeof key]): Target;
|
|
32
|
+
|
|
33
|
+
declare function unique<value>(values: readonly value[]): readonly value[];
|
|
34
|
+
|
|
35
|
+
declare function uniqueBy<value, key>(values: readonly value[], getKey: (value: value) => key): readonly value[];
|
|
36
|
+
|
|
37
|
+
declare function wait(ms: number): Promise<void>;
|
|
38
|
+
|
|
39
|
+
declare function waitForIdle(): Promise<void>;
|
|
40
|
+
|
|
41
|
+
export { assertExhaustive, bigIntMax, bigIntMin, bigIntSort, chunk, curry, groupBy, identity, includes, isDefined, isNotNull, iteratorToArray, mapObject, unique, uniqueBy, wait, waitForIdle };
|
package/dist/utils.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
function
|
|
1
|
+
function a(e,r){throw new Error(r??`Unexpected value: ${e}`)}function i(...e){return e.reduce((r,t)=>t>r?t:r)}function f(...e){return e.reduce((r,t)=>t<r?t:r)}function m(e,r){return e<r?-1:e>r?1:0}function*y(e,r){for(let t=0;t<e.length;t+=r)yield e.slice(t,t+r)}function x(e,...r){return(...t)=>e(...r,...t)}function v(e,r){let t=new Map;for(let n of e){let o=r(n);t.has(o)||t.set(o,[]),t.get(o).push(n)}return t}function T(e){return e}function k(e,r){return e.includes(r)}function w(e){return e!==void 0}function h(e){return e!==null}async function I(e){let r=[];for await(let t of e)r.push(t);return r}function R(e,r){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,r(n,t)]))}function C(e){return Array.from(new Set(e))}function q(e,r){let t=new Map;for(let n of e)t.set(r(n),n);return Array.from(t.values())}function O(e){return new Promise(r=>setTimeout(()=>r(),e))}function N(){return new Promise(e=>{requestIdleCallback(()=>e())})}export{a as assertExhaustive,i as bigIntMax,f as bigIntMin,m as bigIntSort,y as chunk,x as curry,v as groupBy,T as identity,k as includes,w as isDefined,h as isNotNull,I as iteratorToArray,R as mapObject,C as unique,q as uniqueBy,O as wait,N 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/curry.ts","../src/utils/identity.ts","../src/utils/isDefined.ts","../src/utils/isNotNull.ts","../src/utils/iteratorToArray.ts","../src/utils/mapObject.ts","../src/utils/uniqueBy.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: T[], n: number): Generator<T[], void> {\n for (let i = 0; i < arr.length; i += n) {\n yield arr.slice(i, i + n);\n }\n}\n","export function curry<F extends (...params: [...P, ...any[]]) => any, P extends any[]>(\n func: F,\n ...partialParams: P\n): CurryParams<F, P> {\n return ((...args: any[]) => func(...partialParams, ...args)) as CurryParams<F, P>;\n}\n\ntype CurryParams<F extends (...params: [...PartialParams, ...any[]]) => any, PartialParams extends any[]> = F extends (\n ...params: [...PartialParams, ...infer RemainingParams]\n) => infer Result\n ? (...params: RemainingParams) => Result\n : never;\n","export function identity<T>(value: T): T {\n return value;\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<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 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 map.set(getKey(value), value);\n }\n return Array.from(map.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 requestIdleCallback(() => resolve());\n });\n}\n"],"mappings":"AAAO,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,
|
|
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/curry.ts","../src/utils/groupBy.ts","../src/utils/identity.ts","../src/utils/includes.ts","../src/utils/isDefined.ts","../src/utils/isNotNull.ts","../src/utils/iteratorToArray.ts","../src/utils/mapObject.ts","../src/utils/unique.ts","../src/utils/uniqueBy.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 curry<F extends (...params: [...P, ...any[]]) => any, P extends any[]>(\n func: F,\n ...partialParams: P\n): CurryParams<F, P> {\n return ((...args: any[]) => func(...partialParams, ...args)) as CurryParams<F, P>;\n}\n\ntype CurryParams<F extends (...params: [...PartialParams, ...any[]]) => any, PartialParams extends any[]> = F extends (\n ...params: [...PartialParams, ...infer RemainingParams]\n) => infer Result\n ? (...params: RemainingParams) => Result\n : never;\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","export function includes<item>(items: item[], value: any): value is item {\n return items.includes(value);\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<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 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 map.set(getKey(value), value);\n }\n return Array.from(map.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 requestIdleCallback(() => resolve());\n });\n}\n"],"mappings":"AAAO,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,KACGC,EACgB,CACnB,MAAQ,IAAIC,IAAgBF,EAAK,GAAGC,EAAe,GAAGC,CAAI,CAC5D,CCLO,SAASC,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,CCFO,SAASC,EAAeC,EAAeC,EAA2B,CACvE,OAAOD,EAAM,SAASC,CAAK,CAC7B,CCFO,SAASC,EAAaC,EAAwC,CACnE,OAAOA,IAAa,MACtB,CCFO,SAASC,EAAaC,EAAmC,CAC9D,OAAOA,IAAa,IACtB,CCFA,eAAsBC,EAAmBC,EAA0C,CACjF,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,EAAqBC,EAA0BC,EAAiD,CAC9G,IAAMC,EAAM,IAAI,IAChB,QAAWC,KAASH,EAClBE,EAAI,IAAID,EAAOE,CAAK,EAAGA,CAAK,EAE9B,OAAO,MAAM,KAAKD,EAAI,OAAO,CAAC,CAChC,CCNO,SAASE,EAAKC,EAA2B,CAC9C,OAAO,IAAI,QAAeC,GAAY,WAAW,IAAMA,EAAQ,EAAGD,CAAE,CAAC,CACvE,CCFO,SAASE,GAA6B,CAC3C,OAAO,IAAI,QAAeC,GAAY,CACpC,oBAAoB,IAAMA,EAAQ,CAAC,CACrC,CAAC,CACH","names":["assertExhaustive","value","message","bigIntMax","args","m","e","bigIntMin","args","m","e","bigIntSort","a","b","chunk","arr","n","i","curry","func","partialParams","args","groupBy","values","getKey","map","value","key","identity","value","includes","items","value","isDefined","argument","isNotNull","argument","iteratorToArray","iterator","items","item","mapObject","source","valueMap","key","value","unique","values","uniqueBy","values","getKey","map","value","wait","ms","resolve","waitForIdle","resolve"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@latticexyz/common",
|
|
3
|
-
"version": "2.0.0-next.
|
|
3
|
+
"version": "2.0.0-next.15",
|
|
4
4
|
"description": "Common low level logic shared between packages",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"prettier": "^2.8.4",
|
|
53
53
|
"prettier-plugin-solidity": "1.1.3",
|
|
54
54
|
"viem": "1.14.0",
|
|
55
|
-
"@latticexyz/schema-type": "2.0.0-next.
|
|
55
|
+
"@latticexyz/schema-type": "2.0.0-next.15"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@types/debug": "^4.1.7",
|
package/src/codegen/debug.ts
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
1
|
import { debug as parentDebug } from "../debug";
|
|
2
2
|
|
|
3
3
|
export const debug = parentDebug.extend("codegen");
|
|
4
|
+
export const error = parentDebug.extend("codegen");
|
|
5
|
+
|
|
6
|
+
// Pipe debug output to stdout instead of stderr
|
|
7
|
+
debug.log = console.debug.bind(console);
|
|
8
|
+
|
|
9
|
+
// Pipe error output to stderr
|
|
10
|
+
error.log = console.error.bind(console);
|
package/src/codegen/modules.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
declare module "prettier-plugin-solidity"
|
|
1
|
+
declare module "prettier-plugin-solidity" {}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import createDebug from "debug";
|
|
2
|
+
|
|
3
|
+
const parentDebug = createDebug("mud:benchmark");
|
|
4
|
+
|
|
5
|
+
// Pipe debug output to stdout instead of stderr
|
|
6
|
+
parentDebug.log = console.info.bind(console);
|
|
7
|
+
|
|
8
|
+
export function createBenchmark(namespace: string): (stepName: string) => void {
|
|
9
|
+
const debug = parentDebug.extend(namespace);
|
|
10
|
+
let lastStep = performance.now();
|
|
11
|
+
|
|
12
|
+
return (stepName: string) => {
|
|
13
|
+
const secondsSinceLastStep = (performance.now() - lastStep) / 1000;
|
|
14
|
+
debug("%s: +%ds", stepName, secondsSinceLastStep);
|
|
15
|
+
lastStep = performance.now();
|
|
16
|
+
};
|
|
17
|
+
}
|
package/src/debug.ts
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
1
|
import createDebug from "debug";
|
|
2
2
|
|
|
3
3
|
export const debug = createDebug("mud:common");
|
|
4
|
+
export const error = createDebug("mud:common");
|
|
5
|
+
|
|
6
|
+
// Pipe debug output to stdout instead of stderr
|
|
7
|
+
debug.log = console.debug.bind(console);
|
|
8
|
+
|
|
9
|
+
// Pipe error output to stderr
|
|
10
|
+
error.log = console.error.bind(console);
|
package/src/foundry/index.ts
CHANGED
package/src/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export * from "./common";
|
|
2
|
+
export * from "./createBenchmark";
|
|
2
3
|
export * from "./createBurnerAccount";
|
|
3
4
|
export * from "./createNonceManager";
|
|
4
5
|
export * from "./getContract";
|
|
@@ -9,6 +10,7 @@ export * from "./hexToResource";
|
|
|
9
10
|
export * from "./readHex";
|
|
10
11
|
export * from "./resourceToHex";
|
|
11
12
|
export * from "./resourceTypes";
|
|
13
|
+
export * from "./result";
|
|
12
14
|
export * from "./sendTransaction";
|
|
13
15
|
export * from "./spliceHex";
|
|
14
16
|
export * from "./transportObserver";
|
package/src/result.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Inspired by https://doc.rust-lang.org/std/result/
|
|
2
|
+
export type Result<Ok, Err = unknown> = { ok: Ok } | { error: Err };
|
|
3
|
+
|
|
4
|
+
export function isOk<Ok, Err>(result: Result<Ok, Err>): result is { ok: Ok } {
|
|
5
|
+
return "ok" in result;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function isError<Ok, Err>(result: Result<Ok, Err>): result is { error: Err } {
|
|
9
|
+
return "error" in result;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function unwrap<Ok, Err>(result: Result<Ok, Err>): Ok {
|
|
13
|
+
if (isError(result)) {
|
|
14
|
+
throw result.error;
|
|
15
|
+
}
|
|
16
|
+
return result.ok;
|
|
17
|
+
}
|
package/src/utils/chunk.ts
CHANGED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { groupBy } from "./groupBy";
|
|
3
|
+
|
|
4
|
+
describe("groupBy", () => {
|
|
5
|
+
it("should group values by key", () => {
|
|
6
|
+
const records = [
|
|
7
|
+
{ type: "cat", name: "Bob" },
|
|
8
|
+
{ type: "cat", name: "Spot" },
|
|
9
|
+
{ type: "dog", name: "Rover" },
|
|
10
|
+
];
|
|
11
|
+
expect(groupBy(records, (record) => record.type)).toMatchInlineSnapshot(`
|
|
12
|
+
Map {
|
|
13
|
+
"cat" => [
|
|
14
|
+
{
|
|
15
|
+
"name": "Bob",
|
|
16
|
+
"type": "cat",
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
"name": "Spot",
|
|
20
|
+
"type": "cat",
|
|
21
|
+
},
|
|
22
|
+
],
|
|
23
|
+
"dog" => [
|
|
24
|
+
{
|
|
25
|
+
"name": "Rover",
|
|
26
|
+
"type": "dog",
|
|
27
|
+
},
|
|
28
|
+
],
|
|
29
|
+
}
|
|
30
|
+
`);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export function groupBy<value, key>(
|
|
2
|
+
values: readonly value[],
|
|
3
|
+
getKey: (value: value) => key
|
|
4
|
+
): Map<key, readonly value[]> {
|
|
5
|
+
const map = new Map<key, readonly value[]>();
|
|
6
|
+
for (const value of values) {
|
|
7
|
+
const key = getKey(value);
|
|
8
|
+
if (!map.has(key)) map.set(key, []);
|
|
9
|
+
(map.get(key) as value[]).push(value);
|
|
10
|
+
}
|
|
11
|
+
return map;
|
|
12
|
+
}
|
package/src/utils/index.ts
CHANGED
|
@@ -4,11 +4,14 @@ export * from "./bigIntMin";
|
|
|
4
4
|
export * from "./bigIntSort";
|
|
5
5
|
export * from "./chunk";
|
|
6
6
|
export * from "./curry";
|
|
7
|
+
export * from "./groupBy";
|
|
7
8
|
export * from "./identity";
|
|
9
|
+
export * from "./includes";
|
|
8
10
|
export * from "./isDefined";
|
|
9
11
|
export * from "./isNotNull";
|
|
10
12
|
export * from "./iteratorToArray";
|
|
11
13
|
export * from "./mapObject";
|
|
14
|
+
export * from "./unique";
|
|
12
15
|
export * from "./uniqueBy";
|
|
13
16
|
export * from "./wait";
|
|
14
17
|
export * from "./waitForIdle";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { unique } from "./unique";
|
|
3
|
+
|
|
4
|
+
describe("unique", () => {
|
|
5
|
+
it("should return unique values", () => {
|
|
6
|
+
expect(unique([1, 2, 1, 4, 3, 2])).toMatchInlineSnapshot(`
|
|
7
|
+
[
|
|
8
|
+
1,
|
|
9
|
+
2,
|
|
10
|
+
4,
|
|
11
|
+
3,
|
|
12
|
+
]
|
|
13
|
+
`);
|
|
14
|
+
});
|
|
15
|
+
});
|
package/dist/chunk-7WIPV3R3.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/debug.ts"],"sourcesContent":["import createDebug from \"debug\";\n\nexport const debug = createDebug(\"mud:common\");\n"],"mappings":"AAAA,OAAOA,MAAiB,QAEjB,IAAMC,EAAQD,EAAY,YAAY","names":["createDebug","debug"]}
|