@latticexyz/common 2.0.0-next.16 → 2.0.0-next.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/actions.d.ts +11 -0
  2. package/dist/actions.js +2 -0
  3. package/dist/actions.js.map +1 -0
  4. package/dist/chains.d.ts +25 -8
  5. package/dist/chains.js +1 -1
  6. package/dist/chains.js.map +1 -1
  7. package/dist/chunk-6NUUDPWM.js +2 -0
  8. package/dist/chunk-6NUUDPWM.js.map +1 -0
  9. package/dist/chunk-PEY5BGLC.js +2 -0
  10. package/dist/chunk-PEY5BGLC.js.map +1 -0
  11. package/dist/codegen.d.ts +106 -16
  12. package/dist/codegen.js +22 -32
  13. package/dist/codegen.js.map +1 -1
  14. package/dist/foundry.js.map +1 -1
  15. package/dist/getContract-93922960.d.ts +20 -0
  16. package/dist/index.d.ts +15 -14
  17. package/dist/index.js +1 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/type-utils.d.ts +7 -1
  20. package/dist/utils.d.ts +1 -4
  21. package/dist/utils.js +1 -1
  22. package/dist/utils.js.map +1 -1
  23. package/package.json +10 -7
  24. package/src/actions/index.ts +2 -0
  25. package/src/actions/transactionQueue.ts +14 -0
  26. package/src/actions/writeObserver.ts +34 -0
  27. package/src/chains/latticeTestnet.ts +0 -1
  28. package/src/codegen/render-solidity/common.test.ts +79 -0
  29. package/src/codegen/render-solidity/common.ts +92 -41
  30. package/src/codegen/render-solidity/renderEnums.ts +4 -1
  31. package/src/codegen/render-solidity/renderTypeHelpers.ts +21 -2
  32. package/src/codegen/render-solidity/types.ts +5 -2
  33. package/src/codegen/utils/contractToInterface.ts +60 -42
  34. package/src/codegen/utils/extractUserTypes.ts +8 -1
  35. package/src/codegen/utils/format.ts +11 -0
  36. package/src/codegen/utils/formatAndWrite.ts +13 -1
  37. package/src/codegen/utils/loadUserTypesFile.ts +11 -4
  38. package/src/foundry/index.ts +1 -1
  39. package/src/getContract.ts +33 -14
  40. package/src/hexToResource.ts +3 -2
  41. package/src/index.ts +1 -0
  42. package/src/resourceToLabel.test.ts +16 -0
  43. package/src/resourceToLabel.ts +16 -0
  44. package/src/sendTransaction.ts +11 -11
  45. package/src/type-utils/common.ts +3 -0
  46. package/src/type-utils/evaluate.ts +2 -0
  47. package/src/type-utils/index.ts +2 -0
  48. package/src/type-utils/satisfy.ts +1 -0
  49. package/src/utils/groupBy.ts +1 -1
  50. package/src/utils/includes.ts +1 -0
  51. package/src/utils/index.ts +0 -1
  52. package/src/utils/mapObject.ts +2 -2
  53. package/src/utils/waitForIdle.ts +5 -1
  54. package/src/writeContract.ts +19 -15
  55. package/src/utils/curry.ts +0 -12
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/codegen/render-solidity/common.ts","../src/codegen/utils/contractToInterface.ts","../src/codegen/utils/extractUserTypes.ts","../src/codegen/utils/format.ts","../src/codegen/utils/formatAndWrite.ts","../src/codegen/debug.ts","../src/codegen/utils/loadUserTypesFile.ts","../src/codegen/utils/posixPath.ts","../src/codegen/render-solidity/renderEnums.ts","../src/codegen/render-solidity/renderTypeHelpers.ts","../src/codegen/render-typescript/schemaTypesToRecsTypeStrings.ts"],"sourcesContent":["import path from \"path\";\nimport {\n AbsoluteImportDatum,\n RelativeImportDatum,\n ImportDatum,\n StaticResourceData,\n RenderKeyTuple,\n RenderType,\n} from \"./types\";\nimport { posixPath } from \"../utils\";\n\nexport const renderedSolidityHeader = `// SPDX-License-Identifier: MIT\npragma solidity >=0.8.21;\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\nexport function renderCommonData({\n staticResourceData,\n keyTuple,\n}: {\n staticResourceData?: StaticResourceData;\n keyTuple: RenderKeyTuple[];\n}): {\n _typedTableId: string;\n _typedKeyArgs: string;\n _keyTupleDefinition: string;\n} {\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/** For 2 paths which are relative to a common root, create a relative import path from one to another */\nexport function solidityRelativeImportPath(fromPath: string, usedInPath: string): string {\n // 1st \"./\" must be added because path strips it,\n // but solidity expects it unless there's \"../\" (\"./../\" is fine).\n // 2nd and 3rd \"./\" forcefully avoid absolute paths (everything is relative to `src`).\n return posixPath(\"./\" + path.relative(\"./\" + usedInPath, \"./\" + fromPath));\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 return renderAbsoluteImports(\n imports.map((importDatum) => {\n if (\"path\" in importDatum) {\n return importDatum;\n } else {\n return {\n symbol: importDatum.symbol,\n path: solidityRelativeImportPath(importDatum.fromPath, importDatum.usedInPath),\n };\n }\n })\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 renderRelativeImports(imports: RelativeImportDatum[]): string {\n return renderAbsoluteImports(\n imports.map(({ symbol, fromPath, usedInPath }) => ({\n symbol,\n path: solidityRelativeImportPath(fromPath, usedInPath),\n }))\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 renderAbsoluteImports(imports: AbsoluteImportDatum[]): 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 \"${posixPath(path)}\";`);\n }\n return renderedImports.join(\"\\n\");\n}\n\nexport function renderWithStore(\n storeArgument: boolean,\n callback: (data: {\n _typedStore: string | undefined;\n _store: string;\n _commentSuffix: string;\n _methodNamePrefix: string;\n _useExplicitFieldLayout?: boolean;\n }) => 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\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\nexport function renderTableId({ namespace, name, offchainOnly, tableIdName }: StaticResourceData): {\n hardcodedTableId: string;\n tableIdDefinition: string;\n} {\n const hardcodedTableId = `\n ResourceId.wrap(\n bytes32(\n abi.encodePacked(\n ${offchainOnly ? \"RESOURCE_OFFCHAIN_TABLE\" : \"RESOURCE_TABLE\"},\n bytes14(\"${namespace}\"),\n bytes16(\"${name}\")\n )\n )\n )\n `;\n\n const tableIdDefinition = `\n ResourceId constant _tableId = ${hardcodedTableId};\n ResourceId constant ${tableIdName} = _tableId;\n `;\n return {\n hardcodedTableId,\n tableIdDefinition,\n };\n}\n\nexport function renderValueTypeToBytes32(name: string, { typeUnwrap, internalTypeId }: RenderType): 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\nexport function isLeftAligned(field: Pick<RenderType, \"internalTypeId\">): boolean {\n return /^bytes\\d{1,2}$/.test(field.internalTypeId);\n}\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\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 { parse, visit } from \"@solidity-parser/parser\";\nimport type { SourceUnit, TypeName, VariableDeclaration } 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 data contents of a file with the solidity contract\n * @param contractName name of the contract\n * @returns interface data\n */\nexport function contractToInterface(\n data: string,\n contractName: string\n): {\n functions: ContractInterfaceFunction[];\n errors: ContractInterfaceError[];\n symbolImports: SymbolImport[];\n} {\n const ast = parse(data);\n\n let withContract = false;\n let symbolImports: SymbolImport[] = [];\n const functions: ContractInterfaceFunction[] = [];\n const errors: ContractInterfaceError[] = [];\n\n visit(ast, {\n ContractDefinition({ name }) {\n if (name === contractName) {\n withContract = true;\n }\n },\n FunctionDefinition(\n { name, visibility, parameters, stateMutability, returnParameters, isConstructor, isFallback, isReceiveEther },\n parent\n ) {\n if (parent !== undefined && parent.type === \"ContractDefinition\" && parent.name === contractName) {\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 },\n CustomErrorDefinition({ name, parameters }) {\n errors.push({\n name: name === null ? \"\" : 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 if (!withContract) {\n throw new MUDError(`Contract not found: ${contractName}`);\n }\n\n return {\n functions,\n errors,\n symbolImports,\n };\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 { parse, visit } from \"@solidity-parser/parser\";\nimport { MUDError } from \"../../errors\";\n\nexport interface SolidityUserDefinedType {\n typeId: string;\n internalTypeId: string;\n importSymbol: string;\n fromPath: string;\n isRelativePath: boolean;\n}\n\n/**\n * Parse the solidity data to extract user-defined type information.\n * @param data contents of a solidity file with the user types declarations\n * @param userTypeNames names of the user types to extract\n */\nexport function extractUserTypes(\n data: string,\n userTypeNames: string[],\n fromPath: string\n): Record<string, SolidityUserDefinedType> {\n const ast = parse(data);\n\n const isRelativePath = fromPath.at(0) === \".\";\n const userDefinedTypes: Record<string, SolidityUserDefinedType> = {};\n\n visit(ast, {\n TypeDefinition({ name, definition }, parent) {\n if (definition.name.includes(\"fixed\")) throw new MUDError(`Fixed point numbers are not supported by MUD`);\n if (userTypeNames.includes(name)) {\n if (name in userDefinedTypes) {\n throw new MUDError(`File has multiple user types with the same name: ${name}`);\n }\n\n if (parent?.type === \"ContractDefinition\") {\n userDefinedTypes[name] = {\n typeId: `${parent.name}.${name}`,\n internalTypeId: definition.name,\n importSymbol: parent.name,\n fromPath,\n isRelativePath,\n };\n } else {\n userDefinedTypes[name] = {\n typeId: name,\n internalTypeId: definition.name,\n importSymbol: name,\n fromPath,\n isRelativePath,\n };\n }\n }\n },\n });\n\n return userDefinedTypes;\n}\n","import prettier from \"prettier\";\nimport prettierPluginSolidity from \"prettier-plugin-solidity\";\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\nexport async function formatTypescript(content: string): Promise<string> {\n return prettier.format(content, {\n parser: \"typescript\",\n });\n}\n","import { mkdir, writeFile } from \"fs/promises\";\nimport { dirname } from \"path\";\nimport { formatSolidity, formatTypescript } from \"./format\";\nimport { debug } from \"../debug\";\n\nexport async function formatAndWriteSolidity(output: string, fullOutputPath: string, logPrefix: string): Promise<void> {\n const formattedOutput = await formatSolidity(output);\n\n await mkdir(dirname(fullOutputPath), { recursive: true });\n\n await writeFile(fullOutputPath, formattedOutput);\n debug(`${logPrefix}: ${fullOutputPath}`);\n}\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 mkdir(dirname(fullOutputPath), { recursive: true });\n\n await 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","import { readFileSync } from \"fs\";\nimport path from \"path\";\nimport { SolidityUserDefinedType, extractUserTypes } from \"./extractUserTypes\";\nimport { MUDError } from \"../../errors\";\nimport { SchemaAbiType } from \"@latticexyz/schema-type\";\n\nexport type UserType = {\n filePath: string;\n internalType: SchemaAbiType;\n};\n\nexport function loadAndExtractUserTypes(\n userTypes: Record<string, UserType>,\n outputBaseDirectory: string,\n remappings: [string, string][]\n): Record<string, SolidityUserDefinedType> {\n const userTypesPerFile: Record<string, string[]> = {};\n for (const [userTypeName, { filePath: unresolvedFilePath }] of Object.entries(userTypes)) {\n if (!(unresolvedFilePath in userTypesPerFile)) {\n userTypesPerFile[unresolvedFilePath] = [];\n }\n userTypesPerFile[unresolvedFilePath].push(userTypeName);\n }\n let extractedUserTypes: Record<string, SolidityUserDefinedType> = {};\n for (const [unresolvedFilePath, userTypeNames] of Object.entries(userTypesPerFile)) {\n const { filePath, data } = loadUserTypesFile(outputBaseDirectory, unresolvedFilePath, remappings);\n const userTypesInFile = extractUserTypes(data, userTypeNames, filePath);\n\n // Verify the actual user type matches the internalType specified in the config\n for (const [userTypeName, userType] of Object.entries(userTypesInFile)) {\n if (userType.internalTypeId !== userTypes[userTypeName].internalType) {\n throw new MUDError(\n `User type \"${userTypeName}\" has internal type \"${userType.internalTypeId}\" but config specifies \"${userTypes[userTypeName].internalType}\"`\n );\n }\n }\n\n extractedUserTypes = { ...extractedUserTypes, ...userTypesInFile };\n }\n return extractedUserTypes;\n}\n\nfunction loadUserTypesFile(\n outputBaseDirectory: string,\n unresolvedFilePath: string,\n remappings: [string, string][]\n): {\n filePath: string;\n data: string;\n} {\n if (unresolvedFilePath.at(0) === \".\") {\n const relativePath = path.relative(outputBaseDirectory, unresolvedFilePath);\n return {\n filePath: \"./\" + relativePath, // solc doesn't like relative paths without \"./\"\n data: readFileSync(unresolvedFilePath, \"utf8\"),\n };\n } else {\n // apply remappings to read the file via node\n let remappedFilePath = unresolvedFilePath;\n for (const [from, to] of remappings) {\n if (remappedFilePath.includes(from)) {\n remappedFilePath = remappedFilePath.replace(from, to);\n break;\n }\n }\n\n return {\n filePath: unresolvedFilePath,\n data: readFileSync(remappedFilePath, \"utf8\"),\n };\n }\n}\n","/**\n * Explicitly normalize a given path to a posix path (using `/` as separator).\n * This should be used for generating Solidity files that will be consumed by solc,\n * because solc expects `/` as path separator, but path.join produces `\\` if the user is on windows.\n */\nexport function posixPath(path: string): string {\n return path.replace(/\\\\/g, \"/\");\n}\n","import { renderArguments, renderList, renderedSolidityHeader } from \"./common\";\nimport { RenderEnum } from \"./types\";\n\nexport function renderEnums(enums: RenderEnum[]): string {\n let result = renderedSolidityHeader;\n\n result += renderList(\n enums,\n ({ name, memberNames }) => `\n enum ${name} {\n ${renderArguments(memberNames)}\n }\n `\n );\n\n return result;\n}\n","import { RenderField, RenderKeyTuple, RenderType } from \"./types\";\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\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\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"],"mappings":"gFAAA,OAAOA,MAAU,OCAjB,OAAS,SAAAC,EAAO,SAAAC,MAAa,0BA4BtB,SAASC,GACdC,EACAC,EAKA,CACA,IAAMC,EAAMC,EAAMH,CAAI,EAElBI,EAAe,GACfC,EAAgC,CAAC,EAC/BC,EAAyC,CAAC,EAC1CC,EAAmC,CAAC,EAqD1C,GAnDAC,EAAMN,EAAK,CACT,mBAAmB,CAAE,KAAAO,CAAK,EAAG,CACvBA,IAASR,IACXG,EAAe,GAEnB,EACA,mBACE,CAAE,KAAAK,EAAM,WAAAC,EAAY,WAAAC,EAAY,gBAAAC,EAAiB,iBAAAC,EAAkB,cAAAC,EAAe,WAAAC,EAAY,eAAAC,CAAe,EAC7GC,EACA,CACA,GAAIA,IAAW,QAAaA,EAAO,OAAS,sBAAwBA,EAAO,OAAShB,EAClF,GAAI,CAEF,GAAIa,GAAiBC,GAAcC,EAAgB,OAEnD,GAAIN,IAAe,UAAW,MAAM,IAAIQ,EAAS,6BAA6B,EAE9E,GAAIR,IAAe,YAAcA,IAAe,SAAU,CACxDJ,EAAU,KAAK,CACb,KAAMG,IAAS,KAAO,GAAKA,EAC3B,WAAYE,EAAW,IAAIQ,CAAc,EACzC,gBAAiBP,GAAmB,GACpC,iBAAkBC,IAAqB,KAAO,CAAC,EAAIA,EAAi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,CAACA,EAAW,YAAY,EAAG,uBAC3B,CAACA,EAAW,YAAY,EAAG,uBAC3B,CAACA,EAAW,YAAY,EAAG,uBAC3B,CAACA,EAAW,YAAY,EAAG,uBAC3B,CAACA,EAAW,YAAY,EAAG,uBAC3B,CAACA,EAAW,YAAY,EAAG,uBAC3B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,UAAU,EAAG,aACzB,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,KAAK,EAAG,kBACpB,CAACA,EAAW,MAAM,EAAG,iBACvB","names":["path","parse","visit","contractToInterface","data","contractName","ast","parse","withContract","symbolImports","functions","errors","visit","name","visibility","parameters","stateMutability","returnParameters","isConstructor","isFallback","isReceiveEther","parent","MUDError","parseParameter","typeName","symbols","typeNameToSymbols","symbolsToImports","error","parameter","storageLocation","typedNameWithLocation","flattenedTypeName","flattenTypeName","length","innerTypeName","imports","symbol","symbolImport","path","symbolAliases","symbolAndAlias","symbolAlias","parse","visit","extractUserTypes","data","userTypeNames","fromPath","ast","parse","isRelativePath","userDefinedTypes","visit","name","definition","parent","MUDError","prettier","prettierPluginSolidity","formatSolidity","content","prettierConfigPath","config","error","message","formatTypescript","mkdir","writeFile","dirname","debug","error","formatAndWriteSolidity","output","fullOutputPath","logPrefix","formattedOutput","formatSolidity","mkdir","dirname","writeFile","debug","formatAndWriteTypescript","formatTypescript","readFileSync","path","loadAndExtractUserTypes","userTypes","outputBaseDirectory","remappings","userTypesPerFile","userTypeName","unresolvedFilePath","extractedUserTypes","userTypeNames","filePath","data","loadUserTypesFile","userTypesInFile","extractUserTypes","userType","MUDError","path","readFileSync","remappedFilePath","from","to","posixPath","path","renderedSolidityHeader","renderList","list","renderItem","internalRenderList","renderArguments","args","filteredArgs","arg","renderCommonData","staticResourceData","keyTuple","_typedTableId","_typedKeyArgs","name","typeWithLocation","_keyTupleDefinition","key","index","renderValueTypeToBytes32","solidityRelativeImportPath","fromPath","usedInPath","posixPath","path","renderImports","imports","renderAbsoluteImports","importDatum","renderRelativeImports","symbol","aggregatedImports","renderedImports","symbols","renderedSymbols","renderWithStore","storeArgument","callback","result","renderWithFieldSuffix","withSuffixlessFieldMethods","fieldName","methodNameSuffix","renderTableId","namespace","offchainOnly","tableIdName","hardcodedTableId","tableIdDefinition","typeUnwrap","internalTypeId","innerText","isLeftAligned","field","getLeftPaddingBits","lineTerminator","item","renderEnums","enums","result","renderedSolidityHeader","renderList","name","memberNames","renderArguments","renderTypeHelpers","options","fields","keyTuple","result","wrappingHelper","getWrappingHelpers","internalTypeId","array","wrappers","unwrappers","typeWrappingData","typeWrap","typeUnwrap","kind","elementType","staticLength","renderWrapperStaticArray","renderUnwrapperStaticArray","functionName","byteLength","SchemaType","schemaTypesToRecsTypeStrings"]}
1
+ {"version":3,"sources":["../src/codegen/render-solidity/common.ts","../src/codegen/utils/contractToInterface.ts","../src/codegen/utils/extractUserTypes.ts","../src/codegen/utils/format.ts","../src/codegen/utils/formatAndWrite.ts","../src/codegen/debug.ts","../src/codegen/utils/loadUserTypesFile.ts","../src/codegen/utils/posixPath.ts","../src/codegen/render-solidity/renderEnums.ts","../src/codegen/render-solidity/renderTypeHelpers.ts","../src/codegen/render-typescript/schemaTypesToRecsTypeStrings.ts"],"sourcesContent":["import path from \"path\";\nimport {\n AbsoluteImportDatum,\n RelativeImportDatum,\n ImportDatum,\n StaticResourceData,\n RenderKeyTuple,\n RenderType,\n} from \"./types\";\nimport { posixPath } from \"../utils\";\nimport { resourceToHex } from \"../../resourceToHex\";\nimport { hexToResource } from \"../../hexToResource\";\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/** For 2 paths which are relative to a common root, create a relative import path from one to another */\nexport function solidityRelativeImportPath(fromPath: string, usedInPath: string): string {\n // 1st \"./\" must be added because path strips it,\n // but solidity expects it unless there's \"../\" (\"./../\" is fine).\n // 2nd and 3rd \"./\" forcefully avoid absolute paths (everything is relative to `src`).\n return posixPath(\"./\" + path.relative(\"./\" + usedInPath, \"./\" + fromPath));\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 return renderAbsoluteImports(\n imports.map((importDatum) => {\n if (\"path\" in importDatum) {\n return importDatum;\n } else {\n return {\n symbol: importDatum.symbol,\n path: solidityRelativeImportPath(importDatum.fromPath, importDatum.usedInPath),\n };\n }\n }),\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 renderRelativeImports(imports: RelativeImportDatum[]): string {\n return renderAbsoluteImports(\n imports.map(({ symbol, fromPath, usedInPath }) => ({\n symbol,\n path: solidityRelativeImportPath(fromPath, usedInPath),\n })),\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 renderAbsoluteImports(imports: AbsoluteImportDatum[]): 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 \"${posixPath(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 { 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 data contents of a file with the solidity contract\n * @param contractName name of the contract\n * @returns interface data\n */\nexport function contractToInterface(\n data: string,\n contractName: string,\n): {\n functions: ContractInterfaceFunction[];\n errors: ContractInterfaceError[];\n symbolImports: SymbolImport[];\n} {\n const ast = parse(data);\n\n const contractNode = findContractNode(parse(data), 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\nfunction findContractNode(ast: SourceUnit, contractName: string): ContractDefinition | undefined {\n let contract = 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 { parse, visit } from \"@solidity-parser/parser\";\nimport { MUDError } from \"../../errors\";\n\nexport interface SolidityUserDefinedType {\n /** Fully-qualified name of the user-defined type (may include a library name as prefix) */\n typeId: string;\n /** Name of the wrapped primitive type */\n internalTypeId: string;\n /** Symbol which must be imported to use the type (either the type name, or the library name where the type is defined) */\n importSymbol: string;\n /** Path to the solidity file which contains the user type */\n fromPath: string;\n /** Whether `fromPath` is relative */\n isRelativePath: boolean;\n}\n\n/**\n * Parse the solidity data to extract user-defined type information.\n * @param data contents of a solidity file with the user types declarations\n * @param userTypeNames names of the user types to extract\n * @param fromPath path to the solidity file from which the user types are extracted\n * @returns record of type names mapped to the extracted type information\n */\nexport function extractUserTypes(\n data: string,\n userTypeNames: string[],\n fromPath: string,\n): Record<string, SolidityUserDefinedType> {\n const ast = parse(data);\n\n const isRelativePath = fromPath.at(0) === \".\";\n const userDefinedTypes: Record<string, SolidityUserDefinedType> = {};\n\n visit(ast, {\n TypeDefinition({ name, definition }, parent) {\n if (definition.name.includes(\"fixed\")) throw new MUDError(`Fixed point numbers are not supported by MUD`);\n if (userTypeNames.includes(name)) {\n if (name in userDefinedTypes) {\n throw new MUDError(`File has multiple user types with the same name: ${name}`);\n }\n\n if (parent?.type === \"ContractDefinition\") {\n userDefinedTypes[name] = {\n typeId: `${parent.name}.${name}`,\n internalTypeId: definition.name,\n importSymbol: parent.name,\n fromPath,\n isRelativePath,\n };\n } else {\n userDefinedTypes[name] = {\n typeId: name,\n internalTypeId: definition.name,\n importSymbol: name,\n fromPath,\n isRelativePath,\n };\n }\n }\n },\n });\n\n return userDefinedTypes;\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 { mkdir, writeFile } from \"fs/promises\";\nimport { dirname } from \"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 mkdir(dirname(fullOutputPath), { recursive: true });\n\n await 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 mkdir(dirname(fullOutputPath), { recursive: true });\n\n await 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","import { readFileSync } from \"fs\";\nimport path from \"path\";\nimport { SolidityUserDefinedType, extractUserTypes } from \"./extractUserTypes\";\nimport { MUDError } from \"../../errors\";\nimport { SchemaAbiType } from \"@latticexyz/schema-type/internal\";\n\nexport type UserType = {\n filePath: string;\n internalType: SchemaAbiType;\n};\n\n/**\n * Load the user type files and extract type information from them.\n * @param userTypes record of user type data mapped by type names\n * @param outputBaseDirectory base path to the output directory\n * @param remappings solc remappings\n * @returns record of the user type information mapped by type names\n */\nexport function loadAndExtractUserTypes(\n userTypes: Record<string, UserType>,\n outputBaseDirectory: string,\n remappings: [string, string][],\n): Record<string, SolidityUserDefinedType> {\n const userTypesPerFile: Record<string, string[]> = {};\n for (const [userTypeName, { filePath: unresolvedFilePath }] of Object.entries(userTypes)) {\n if (!(unresolvedFilePath in userTypesPerFile)) {\n userTypesPerFile[unresolvedFilePath] = [];\n }\n userTypesPerFile[unresolvedFilePath].push(userTypeName);\n }\n let extractedUserTypes: Record<string, SolidityUserDefinedType> = {};\n for (const [unresolvedFilePath, userTypeNames] of Object.entries(userTypesPerFile)) {\n const { filePath, data } = loadUserTypesFile(outputBaseDirectory, unresolvedFilePath, remappings);\n const userTypesInFile = extractUserTypes(data, userTypeNames, filePath);\n\n // Verify the actual user type matches the internalType specified in the config\n for (const [userTypeName, userType] of Object.entries(userTypesInFile)) {\n if (userType.internalTypeId !== userTypes[userTypeName].internalType) {\n throw new MUDError(\n `User type \"${userTypeName}\" has internal type \"${userType.internalTypeId}\" but config specifies \"${userTypes[userTypeName].internalType}\"`,\n );\n }\n }\n\n extractedUserTypes = { ...extractedUserTypes, ...userTypesInFile };\n }\n return extractedUserTypes;\n}\n\nfunction loadUserTypesFile(\n outputBaseDirectory: string,\n unresolvedFilePath: string,\n remappings: [string, string][],\n): {\n filePath: string;\n data: string;\n} {\n if (unresolvedFilePath.at(0) === \".\") {\n const relativePath = path.relative(outputBaseDirectory, unresolvedFilePath);\n return {\n filePath: \"./\" + relativePath, // solc doesn't like relative paths without \"./\"\n data: readFileSync(unresolvedFilePath, \"utf8\"),\n };\n } else {\n // apply remappings to read the file via node\n let remappedFilePath = unresolvedFilePath;\n for (const [from, to] of remappings) {\n if (remappedFilePath.includes(from)) {\n remappedFilePath = remappedFilePath.replace(from, to);\n break;\n }\n }\n\n return {\n filePath: unresolvedFilePath,\n data: readFileSync(remappedFilePath, \"utf8\"),\n };\n }\n}\n","/**\n * Explicitly normalize a given path to a posix path (using `/` as separator).\n * This should be used for generating Solidity files that will be consumed by solc,\n * because solc expects `/` as path separator, but path.join produces `\\` if the user is on windows.\n */\nexport function posixPath(path: string): string {\n return path.replace(/\\\\/g, \"/\");\n}\n","import { renderArguments, renderList, renderedSolidityHeader } from \"./common\";\nimport { RenderEnum } from \"./types\";\n\n/**\n * Render a list of enum data as solidity enum definitions\n */\nexport function renderEnums(enums: RenderEnum[]): string {\n let result = renderedSolidityHeader;\n\n result += renderList(\n enums,\n ({ name, memberNames }) => `\n enum ${name} {\n ${renderArguments(memberNames)}\n }\n `,\n );\n\n return result;\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"],"mappings":"+HAAA,OAAOA,MAAU,OCAjB,OAAS,SAAAC,EAAO,SAAAC,MAAa,0BAiCtB,SAASC,GACdC,EACAC,EAKA,CACA,IAAMC,EAAMC,EAAMH,CAAI,EAEhBI,EAAeC,EAAiBF,EAAMH,CAAI,EAAGC,CAAY,EAC3DK,EAAgC,CAAC,EAC/BC,EAAyC,CAAC,EAC1CC,EAAmC,CAAC,EAE1C,GAAI,CAACJ,EACH,MAAM,IAAIK,EAAS,uBAAuBR,GAAc,EAG1D,OAAAS,EAAMN,EAAc,CAClB,mBAAmB,CAC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AW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,UAAU,EAAG,aACzB,CAACA,EAAW,aAAa,EAAG,uBAC5B,CAACA,EAAW,KAAK,EAAG,kBACpB,CAACA,EAAW,MAAM,EAAG,iBACvB","names":["path","parse","visit","contractToInterface","data","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","parse","visit","extractUserTypes","data","userTypeNames","fromPath","ast","parse","isRelativePath","userDefinedTypes","visit","name","definition","parent","MUDError","prettier","prettierPluginSolidity","formatSolidity","content","prettierConfigPath","config","error","message","formatTypescript","mkdir","writeFile","dirname","debug","error","formatAndWriteSolidity","output","fullOutputPath","logPrefix","formattedOutput","formatSolidity","mkdir","dirname","writeFile","debug","formatAndWriteTypescript","formatTypescript","readFileSync","path","loadAndExtractUserTypes","userTypes","outputBaseDirectory","remappings","userTypesPerFile","userTypeName","unresolvedFilePath","extractedUserTypes","userTypeNames","filePath","data","loadUserTypesFile","userTypesInFile","extractUserTypes","userType","MUDError","path","readFileSync","remappedFilePath","from","to","posixPath","path","renderedSolidityHeader","renderList","list","renderItem","internalRenderList","renderArguments","args","filteredArgs","arg","renderCommonData","staticResourceData","keyTuple","_typedTableId","_typedKeyArgs","name","typeWithLocation","_keyTupleDefinition","key","index","renderValueTypeToBytes32","solidityRelativeImportPath","fromPath","usedInPath","posixPath","path","renderImports","imports","renderAbsoluteImports","importDatum","renderRelativeImports","symbol","aggregatedImports","renderedImports","symbols","renderedSymbols","renderWithStore","storeArgument","callback","result","renderWithFieldSuffix","withSuffixlessFieldMethods","fieldName","methodNameSuffix","renderTableId","namespace","offchainOnly","tableId","resourceToHex","resource","hexToResource","typeUnwrap","internalTypeId","innerText","isLeftAligned","field","getLeftPaddingBits","lineTerminator","item","renderEnums","enums","result","renderedSolidityHeader","renderList","name","memberNames","renderArguments","renderTypeHelpers","options","fields","keyTuple","result","wrappingHelper","getWrappingHelpers","internalTypeId","array","wrappers","unwrappers","typeWrappingData","typeWrap","typeUnwrap","kind","elementType","staticLength","renderWrapperStaticArray","renderUnwrapperStaticArray","functionName","byteLength","SchemaType","schemaTypesToRecsTypeStrings"]}
@@ -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 * Get the value of \"remappings\" from forge config\n * @param profile The foundry profile to use\n * @returns The array of remapping tuples `[from, to]`\n */\nexport async function getRemappings(profile?: string): Promise<[string, string][]> {\n return (await getForgeConfig(profile)).remappings.map((line) => line.trim().split(\"=\")) as [string, string][];\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 }\n): Promise<void> {\n const execOptions: Options<string> = {\n env: { FOUNDRY_PROFILE: options?.profile, ...options?.env },\n stdout: \"inherit\",\n stderr: \"pipe\",\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,CAAE,gBAAiBE,CAAQ,CAClC,CAAC,EAED,OAAO,KAAK,MAAMC,CAAM,CAC1B,CAMA,eAAsBC,EAAgBF,EAAmC,CACvE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,GACzC,CAMA,eAAsBG,EAAmBH,EAAmC,CAC1E,OAAQ,MAAMD,EAAeC,CAAO,GAAG,MACzC,CAMA,eAAsBI,EAAiBJ,EAAmC,CACxE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,IACzC,CAMA,eAAsBK,EAAgBL,EAAmC,CACvE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,GACzC,CAOA,eAAsBM,EAAUN,EAAmC,CACjE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,aAAe,uBACxD,CAOA,eAAsBO,EAAcP,EAA+C,CACjF,OAAQ,MAAMD,EAAeC,CAAO,GAAG,WAAW,IAAKQ,GAASA,EAAK,KAAK,EAAE,MAAM,GAAG,CAAC,CACxF,CAOA,eAAsBC,EACpBC,EACAC,EACe,CACf,IAAMC,EAA+B,CACnC,IAAK,CAAE,gBAAiBD,GAAS,QAAS,GAAGA,GAAS,GAAI,EAC1D,OAAQ,UACR,OAAQ,MACV,EAEA,MAAOA,GAAS,OAASb,EAAM,QAASY,EAAME,CAAW,EAAIC,EAAQ,QAASH,EAAME,CAAW,EACjG,CAOA,eAAsBE,EAAKJ,EAAgBC,EAAiD,CAC1F,OAAOE,EAAQ,OAAQH,EAAM,CAC3B,IAAK,CAAE,gBAAiBC,GAAS,OAAQ,CAC3C,CAAC,CACH,CAOA,eAAsBI,EAAML,EAAiC,CAC3D,OAAOG,EAAQ,QAASH,CAAI,CAC9B,CASA,eAAeG,EAAQG,EAAiBN,EAAgBC,EAA4C,CAClG,IAAMM,EAAgB,GAAGD,KAAWN,EAAK,KAAK,GAAG,IACjD,GAAI,CACF,QAAQ,IAAI,YAAYO,IAAgB,EACxC,GAAM,CAAE,OAAAhB,CAAO,EAAI,MAAMH,EAAMkB,EAASN,EAAM,CAAE,OAAQ,OAAQ,OAAQ,OAAQ,GAAGC,CAAQ,CAAC,EAC5F,OAAOV,CAET,OAASiB,EAAP,CACA,IAAIC,EAAeD,GAAO,QAAUA,GAAO,SAAW,GACtD,MAAAC,GAAgB;AAAA,iBAAoBF,KAC9B,IAAI,MAAME,CAAY,CAC9B,CACF","names":["execa","getForgeConfig","profile","stdout","getSrcDirectory","getScriptDirectory","getTestDirectory","getOutDirectory","getRpcUrl","getRemappings","line","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 * Get the value of \"remappings\" from forge config\n * @param profile The foundry profile to use\n * @returns The array of remapping tuples `[from, to]`\n */\nexport async function getRemappings(profile?: string): Promise<[string, string][]> {\n return (await getForgeConfig(profile)).remappings.map((line) => line.trim().split(\"=\")) as [string, string][];\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 },\n): Promise<void> {\n const execOptions: Options<string> = {\n env: { FOUNDRY_PROFILE: options?.profile, ...options?.env },\n stdout: \"inherit\",\n stderr: \"pipe\",\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,CAAE,gBAAiBE,CAAQ,CAClC,CAAC,EAED,OAAO,KAAK,MAAMC,CAAM,CAC1B,CAMA,eAAsBC,EAAgBF,EAAmC,CACvE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,GACzC,CAMA,eAAsBG,EAAmBH,EAAmC,CAC1E,OAAQ,MAAMD,EAAeC,CAAO,GAAG,MACzC,CAMA,eAAsBI,EAAiBJ,EAAmC,CACxE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,IACzC,CAMA,eAAsBK,EAAgBL,EAAmC,CACvE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,GACzC,CAOA,eAAsBM,EAAUN,EAAmC,CACjE,OAAQ,MAAMD,EAAeC,CAAO,GAAG,aAAe,uBACxD,CAOA,eAAsBO,EAAcP,EAA+C,CACjF,OAAQ,MAAMD,EAAeC,CAAO,GAAG,WAAW,IAAKQ,GAASA,EAAK,KAAK,EAAE,MAAM,GAAG,CAAC,CACxF,CAOA,eAAsBC,EACpBC,EACAC,EACe,CACf,IAAMC,EAA+B,CACnC,IAAK,CAAE,gBAAiBD,GAAS,QAAS,GAAGA,GAAS,GAAI,EAC1D,OAAQ,UACR,OAAQ,MACV,EAEA,MAAOA,GAAS,OAASb,EAAM,QAASY,EAAME,CAAW,EAAIC,EAAQ,QAASH,EAAME,CAAW,EACjG,CAOA,eAAsBE,EAAKJ,EAAgBC,EAAiD,CAC1F,OAAOE,EAAQ,OAAQH,EAAM,CAC3B,IAAK,CAAE,gBAAiBC,GAAS,OAAQ,CAC3C,CAAC,CACH,CAOA,eAAsBI,EAAML,EAAiC,CAC3D,OAAOG,EAAQ,QAASH,CAAI,CAC9B,CASA,eAAeG,EAAQG,EAAiBN,EAAgBC,EAA4C,CAClG,IAAMM,EAAgB,GAAGD,KAAWN,EAAK,KAAK,GAAG,IACjD,GAAI,CACF,QAAQ,IAAI,YAAYO,IAAgB,EACxC,GAAM,CAAE,OAAAhB,CAAO,EAAI,MAAMH,EAAMkB,EAASN,EAAM,CAAE,OAAQ,OAAQ,OAAQ,OAAQ,GAAGC,CAAQ,CAAC,EAC5F,OAAOV,CAET,OAASiB,EAAP,CACA,IAAIC,EAAeD,GAAO,QAAUA,GAAO,SAAW,GACtD,MAAAC,GAAgB;AAAA,iBAAoBF,KAC9B,IAAI,MAAME,CAAY,CAC9B,CACF","names":["execa","getForgeConfig","profile","stdout","getSrcDirectory","getScriptDirectory","getTestDirectory","getOutDirectory","getRpcUrl","getRemappings","line","forge","args","options","execOptions","execLog","cast","anvil","command","commandString","error","errorMessage"]}
@@ -0,0 +1,20 @@
1
+ import { WriteContractParameters, Hex, Transport, Address, Abi, Chain, Account, PublicClient, WalletClient, GetContractParameters, GetContractReturnType } from 'viem';
2
+
3
+ type ContractWrite = {
4
+ id: string;
5
+ request: WriteContractParameters;
6
+ result: Promise<Hex>;
7
+ };
8
+ type GetContractOptions<TTransport extends Transport, TAddress extends Address, TAbi extends Abi, TChain extends Chain, TAccount extends Account, TPublicClient extends PublicClient<TTransport, TChain>, TWalletClient extends WalletClient<TTransport, TChain, TAccount>> = GetContractParameters<TTransport, TChain, TAccount, TAbi, {
9
+ public: TPublicClient;
10
+ wallet: TWalletClient;
11
+ }, TAddress> & {
12
+ onWrite?: (write: ContractWrite) => void;
13
+ };
14
+ /** @deprecated Use `walletClient.extend(transactionQueue()).extend(writeObserver({ onWrite }))` and viem's `getContract` instead. */
15
+ declare function getContract<TTransport extends Transport, TAddress extends Address, TAbi extends Abi, TChain extends Chain, TAccount extends Account, TPublicClient extends PublicClient<TTransport, TChain>, TWalletClient extends WalletClient<TTransport, TChain, TAccount>>({ abi, address, client: { public: publicClient, wallet: walletClient }, onWrite, }: GetContractOptions<TTransport, TAddress, TAbi, TChain, TAccount, TPublicClient, TWalletClient>): GetContractReturnType<TAbi, {
16
+ public: TPublicClient;
17
+ wallet: TWalletClient;
18
+ }, TAddress>;
19
+
20
+ export { ContractWrite as C, GetContractOptions as G, getContract as g };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { Hex, Account, Client, BlockTag, WriteContractParameters, Transport, Address, Abi, Chain, PublicClient, WalletClient, GetContractParameters, GetContractReturnType, SendTransactionParameters, WriteContractReturnType } from 'viem';
1
+ import { Hex, Account, Client, BlockTag, Chain, Transport, 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
5
 
4
6
  declare const resourceTypes: readonly ["table", "offchainTable", "namespace", "module", "system"];
5
7
  type ResourceType = (typeof resourceTypes)[number];
@@ -31,16 +33,6 @@ type CreateNonceManagerResult = {
31
33
  declare function createNonceManager({ client, address, // TODO: rename to account?
32
34
  blockTag, broadcastChannelName, }: CreateNonceManagerOptions): CreateNonceManagerResult;
33
35
 
34
- type ContractWrite = {
35
- id: string;
36
- request: WriteContractParameters;
37
- result: Promise<Hex>;
38
- };
39
- type GetContractOptions<TTransport extends Transport, TAddress extends Address, TAbi extends Abi, TChain extends Chain, TAccount extends Account, TPublicClient extends PublicClient<TTransport, TChain>, TWalletClient extends WalletClient<TTransport, TChain, TAccount>> = Required<GetContractParameters<TTransport, TChain, TAccount, TAbi, TPublicClient, TWalletClient, TAddress>> & {
40
- onWrite?: (write: ContractWrite) => void;
41
- };
42
- declare function getContract<TTransport extends Transport, TAddress extends Address, TAbi extends Abi, TChain extends Chain, TAccount extends Account, TPublicClient extends PublicClient<TTransport, TChain>, TWalletClient extends WalletClient<TTransport, TChain, TAccount>>({ abi, address, publicClient, walletClient, onWrite, }: GetContractOptions<TTransport, TAddress, TAbi, TChain, TAccount, TPublicClient, TWalletClient>): GetContractReturnType<TAbi, TPublicClient, TWalletClient, TAddress>;
43
-
44
36
  declare function getBurnerPrivateKey(cacheKey?: string): Hex;
45
37
 
46
38
  declare function getNonceManager({ client, address, // TODO: rename to account?
@@ -63,6 +55,13 @@ declare function hexToResource(hex: Hex): Resource;
63
55
  */
64
56
  declare function readHex(data: Hex, start: number, end?: number): Hex;
65
57
 
58
+ declare const rootNamespace = "";
59
+ type ResourceLabel<namespace extends string = string, name extends string = string> = namespace extends typeof rootNamespace ? name : `${namespace}__${name}`;
60
+ declare function resourceToLabel<namespace extends string, name extends string>({ namespace, name, }: {
61
+ readonly namespace: namespace;
62
+ readonly name: name;
63
+ }): ResourceLabel<namespace, name>;
64
+
66
65
  /** @internal */
67
66
  declare const resourceTypeIds: {
68
67
  readonly table: "tb";
@@ -86,13 +85,15 @@ declare function isError<Ok, Err>(result: Result<Ok, Err>): result is {
86
85
  };
87
86
  declare function unwrap<Ok, Err>(result: Result<Ok, Err>): Ok;
88
87
 
89
- declare function sendTransaction<TChain extends Chain | undefined, TAccount extends Account | undefined, TChainOverride extends Chain | undefined>(client: Client<Transport, TChain, TAccount>, request: SendTransactionParameters<TChain, TAccount, TChainOverride>): Promise<WriteContractReturnType>;
88
+ /** @deprecated Use `walletClient.extend(transactionQueue())` instead. */
89
+ declare function sendTransaction<TChain extends Chain | undefined, TAccount extends Account | undefined, TChainOverride extends Chain | undefined>(client: Client<Transport, TChain, TAccount>, request: SendTransactionParameters<TChain, TAccount, TChainOverride>): Promise<SendTransactionReturnType>;
90
90
 
91
91
  declare function spliceHex(data: Hex, start: number, deleteCount?: number, newData?: Hex): Hex;
92
92
 
93
93
  declare function transportObserver<TTransport extends Transport>(transport: TTransport): TTransport;
94
94
 
95
- declare function writeContract<TChain extends Chain | undefined, TAccount extends Account | undefined, TAbi extends Abi | readonly unknown[], TFunctionName extends string, TChainOverride extends Chain | undefined>(client: Client<Transport, TChain, TAccount>, request: WriteContractParameters<TAbi, TFunctionName, TChain, TAccount, TChainOverride>): Promise<WriteContractReturnType>;
95
+ /** @deprecated Use `walletClient.extend(transactionQueue())` instead. */
96
+ declare function writeContract<chain extends Chain | undefined, account extends Account | undefined, abi extends Abi | readonly unknown[], functionName extends ContractFunctionName<abi, "nonpayable" | "payable">, args extends ContractFunctionArgs<abi, "nonpayable" | "payable", functionName>, chainOverride extends Chain | undefined>(client: Client<Transport, chain, account>, request: WriteContractParameters<abi, functionName, args, chain, account, chainOverride>): Promise<WriteContractReturnType>;
96
97
 
97
98
  /** @deprecated use `getContract` instead */
98
99
  declare const createContract: typeof getContract;
@@ -103,4 +104,4 @@ declare const resourceIdToHex: typeof resourceToHex;
103
104
  /** @deprecated use `hexToResource` instead */
104
105
  declare const hexToResourceId: typeof hexToResource;
105
106
 
106
- export { ContractWrite, CreateNonceManagerOptions, CreateNonceManagerResult, GetContractOptions, Resource, ResourceType, Result, createBenchmark, createBurnerAccount, createContract, createNonceManager, getBurnerPrivateKey, getContract, getNonceManager, getNonceManagerId, hexToResource, hexToResourceId, isError, isOk, readHex, resourceIdToHex, resourceToHex, resourceTypeIds, resourceTypes, sendTransaction, spliceHex, transportObserver, unwrap, writeContract };
107
+ export { CreateNonceManagerOptions, CreateNonceManagerResult, Resource, ResourceLabel, ResourceType, Result, createBenchmark, createBurnerAccount, createContract, createNonceManager, getBurnerPrivateKey, getContract, getNonceManager, getNonceManagerId, hexToResource, hexToResourceId, isError, isOk, readHex, resourceIdToHex, resourceToHex, resourceToLabel, resourceTypeIds, resourceTypes, sendTransaction, spliceHex, transportObserver, unwrap, writeContract };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import{a as u}from"./chunk-TCWGPC6G.js";import $ from"debug";var P=$("mud:benchmark");P.log=console.info.bind(console);function le(e){let r=P.extend(e),n=performance.now();return o=>{let t=(performance.now()-n)/1e3;r("%s: +%ds",o,t),n=performance.now()}}import{privateKeyToAccount as S}from"viem/accounts";function ge(e){return{...S(e)}}import{BaseError as G,NonceTooHighError as D,NonceTooLowError as Q}from"viem";import{getAddress as B}from"viem";import{getChainId as F}from"viem/actions";async function T({client:e,address:r,blockTag:n}){return`mud:createNonceManager:${e.chain?.id??await F(e)}:${B(r)}:${n}`}import{getTransactionCount as _}from"viem/actions";import j from"p-queue";var R=u.extend("createNonceManager");function k({client:e,address:r,blockTag:n="pending",broadcastChannelName:o}){let t={current:-1},a=null;typeof BroadcastChannel<"u"&&(o?Promise.resolve(o):T({client:e,address:r,blockTag:n})).then(p=>{a=new BroadcastChannel(p),a.addEventListener("message",m=>{let d=JSON.parse(m.data);R("got nonce from broadcast channel",d),t.current=d})});function s(){return t.current>=0}function c(){if(!s())throw new Error("call resetNonce before using nextNonce");let i=t.current++;return a?.postMessage(JSON.stringify(t.current)),i}async function g(){let i=await _(e,{address:r,blockTag:n});t.current=i,a?.postMessage(JSON.stringify(t.current)),R("reset nonce to",t.current)}function C(i){return i instanceof G&&i.walk(p=>p instanceof Q||p instanceof D)!=null}let h=new j({concurrency:1});return{hasNonce:s,nextNonce:c,resetNonce:g,shouldResetNonce:C,mempoolQueue:h}}import{getContract as U}from"viem";import{simulateContract as z,writeContract as J}from"viem/actions";import K from"p-retry";var O=new Map;async function l({client:e,address:r,blockTag:n="pending"}){let o=await T({client:e,address:r,blockTag:n}),t=O.get(o);if(t)return t;let a=k({client:e,address:r,blockTag:n});return O.set(o,a),a}import{parseAccount as L}from"viem/accounts";var f=u.extend("writeContract");async function H(e,r){let n=r.account??e.account;if(!n)throw new Error("No account provided");let o=L(n),t=await l({client:e,address:o.address,blockTag:"pending"});async function a(){return r.gas?(f("gas provided, skipping simulate",r.functionName,r.address),r):(f("simulating",r.functionName,"at",r.address),(await z(e,{...r,blockTag:"pending",account:o})).request)}let s=await a();return t.mempoolQueue.add(()=>K(async()=>{t.hasNonce()||await t.resetNonce();let c=t.nextNonce();return f("calling",s.functionName,"with nonce",c,"at",s.address),await J(e,{nonce:c,...s})},{retries:3,onFailedAttempt:async c=>{if(t.shouldResetNonce(c)){f("got nonce error, retrying",c.message),await t.resetNonce();return}throw c}}),{throwOnTimeout:!0})}function V(e){let r=e.length&&Array.isArray(e[0]),n=r?e[0]:[],o=(r?e[1]:e[0])??{};return{args:n,options:o}}function v({abi:e,address:r,publicClient:n,walletClient:o,onWrite:t}){let a=U({abi:e,address:r,publicClient:n,walletClient:o});if(a.write){let s=0;a.write=new Proxy({},{get(c,g){return(...C)=>{let{args:h,options:i}=V(C),p={abi:e,address:r,functionName:g,args:h,...i,onWrite:t},m=H(o,p),d=`${o.chain.id}:${o.account.address}:${s++}`;return t?.({id:d,request:p,result:m}),m}}})}return a}import{generatePrivateKey as X,privateKeyToAccount as W}from"viem/accounts";import{isHex as Y}from"viem";function Z(e,r){if(!Y(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`);W(e)}function ir(e="mud:burnerWallet"){let r=localStorage.getItem(e);if(r!=null)return Z(r,e),r;let n=X();return console.log("New burner wallet created:",W(n)),localStorage.setItem(e,n),n}import{hexToString as A,sliceHex as w}from"viem";var M=["table","offchainTable","namespace","module","system"];import{stringToHex as b,concatHex as q}from"viem";var y={table:"tb",offchainTable:"ot",namespace:"ns",module:"md",system:"sy"};function E(e){let r=y[e.type];return q([b(r,{size:2}),b(e.namespace.slice(0,14),{size:14}),b(e.name.slice(0,16),{size:16})])}var ee=Object.fromEntries(Object.entries(y).map(([e,r])=>[r,e]));function re(e){let r=ee[e];if(M.includes(r))return r}function I(e){let r=A(w(e,0,2)).replace(/\0+$/,""),n=re(r),o=A(w(e,2,16)).replace(/\0+$/,""),t=A(w(e,16,32)).replace(/\0+$/,"");if(!n)throw new Error(`Unknown type (${r}) for resource (${r}:${o}:${t})`);return{resourceId:e,type:n,namespace:o,name:t}}function N(e,r,n){return`0x${e.replace(/^0x/,"").slice(r*2,n!=null?n*2:void 0).padEnd(((n??r)-r)*2,"0")}`}function yr(e){return"ok"in e}function te(e){return"error"in e}function Ar(e){if(te(e))throw e.error;return e.ok}import{call as ne,sendTransaction as oe}from"viem/actions";import ae from"p-retry";import{parseAccount as ce}from"viem/accounts";var x=u.extend("sendTransaction");async function Hr(e,r){let n=r.account??e.account;if(!n)throw new Error("No account provided");let o=ce(n),t=await l({client:e,address:o.address,blockTag:"pending"});async function a(){return r.gas?(x("gas provided, skipping simulate",r.to),r):(x("simulating tx to",r.to),await ne(e,{...r,blockTag:"pending",account:o}),r)}let s=await a();return await t.mempoolQueue.add(()=>ae(async()=>{t.hasNonce()||await t.resetNonce();let c=t.nextNonce();return x("sending tx with nonce",c,"to",s.to),await oe(e,{nonce:c,...s})},{retries:3,onFailedAttempt:async c=>{if(t.shouldResetNonce(c)){x("got nonce error, retrying",c.message),await t.resetNonce();return}throw c}}),{throwOnTimeout:!0})}import{concatHex as se}from"viem";function Ir(e,r,n=0,o="0x"){return se([N(e,0,r),o,N(e,r+n)])}import{keccak256 as ie}from"viem";var ue=u.extend("transportObserver");function Dr(e){return r=>{let n=e(r);return{...n,request:async t=>{if(t.method==="eth_sendRawTransaction"&&t.params instanceof Array){let a=t.params.map(s=>ie(s));ue("saw txs",a)}return n.request(t)}}}}var pe=v;var me=E;var de=I;export{le as createBenchmark,ge as createBurnerAccount,pe as createContract,k as createNonceManager,ir as getBurnerPrivateKey,v as getContract,l as getNonceManager,T as getNonceManagerId,I as hexToResource,de as hexToResourceId,te as isError,yr as isOk,N as readHex,me as resourceIdToHex,E as resourceToHex,y as resourceTypeIds,M as resourceTypes,Hr as sendTransaction,Ir as spliceHex,Dr as transportObserver,Ar as unwrap,H as writeContract};
1
+ import{a as $,b as q,c as B,d as l,e as j}from"./chunk-PEY5BGLC.js";import{a as D,b as K,c as x,d as _,e as T}from"./chunk-6NUUDPWM.js";import{a as p}from"./chunk-TCWGPC6G.js";import w from"debug";var m=w("mud:benchmark");m.log=console.info.bind(console);function L(t){let r=m.extend(t),e=performance.now();return n=>{let o=(performance.now()-e)/1e3;r("%s: +%ds",n,o),e=performance.now()}}import{privateKeyToAccount as y}from"viem/accounts";function M(t){return{...y(t)}}import{getContract as h}from"viem";function P(t){let r=t.length&&Array.isArray(t[0]),e=r?t[0]:[],n=(r?t[1]:t[0])??{};return{args:e,options:n}}function d({abi:t,address:r,client:{public:e,wallet:n},onWrite:o}){let s=h({abi:t,address:r,client:{public:e,wallet:n}});if(s.write){let a=0;s.write=new Proxy({},{get(S,C){return(...b)=>{let{args:A,options:g}=P(b),c={abi:t,address:r,functionName:C,args:A,...g,onWrite:o},u=l(n,c),k=`${n.chain.id}:${n.account.address}:${a++}`;return o?.({id:k,request:c,result:u}),u}}})}return s}import{generatePrivateKey as H,privateKeyToAccount as f}from"viem/accounts";import{isHex as W}from"viem";function O(t,r){if(!W(t))throw console.error("Private key found in cache is not valid hex",{privateKey:t,cacheKey:r}),new Error(`Private key found in cache (${r}) is not valid hex`);f(t)}function Tt(t="mud:burnerWallet"){let r=localStorage.getItem(t);if(r!=null)return O(r,t),r;let e=H();return console.log("New burner wallet created:",f(e)),localStorage.setItem(t,e),e}function i(t,r,e){return`0x${t.replace(/^0x/,"").slice(r*2,e!=null?e*2:void 0).padEnd(((e??r)-r)*2,"0")}`}function ft(t){return"ok"in t}function E(t){return"error"in t}function Ct(t){if(E(t))throw t.error;return t.ok}import{concatHex as R}from"viem";function wt(t,r,e=0,n="0x"){return R([i(t,0,r),n,i(t,r+e)])}import{keccak256 as v}from"viem";var G=p.extend("transportObserver");function Ot(t){return r=>{let e=t(r);return{...e,request:async o=>{if(o.method==="eth_sendRawTransaction"&&o.params instanceof Array){let s=o.params.map(a=>v(a));G("saw txs",s)}return e.request(o)}}}}var I=d;var F=x;var N=T;export{L as createBenchmark,M as createBurnerAccount,I as createContract,q as createNonceManager,Tt as getBurnerPrivateKey,d as getContract,B as getNonceManager,$ as getNonceManagerId,T as hexToResource,N as hexToResourceId,E as isError,ft as isOk,i as readHex,F as resourceIdToHex,x as resourceToHex,_ as resourceToLabel,K as resourceTypeIds,D as resourceTypes,j as sendTransaction,wt as spliceHex,Ot as transportObserver,Ct as unwrap,l 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/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,MAAMF,EAAWE,CAAM,KAChBH,EAAWI,CAAO,KAAKC,GACrE,CDZA,OAAS,uBAAAC,MAA2B,eACpC,OAAOC,MAAY,UAEnB,IAAMC,EAAQA,EAAY,OAAO,oBAAoB,EAiB9C,SAASC,EAAmB,CACjC,OAAAC,EACA,QAAAC,EACA,SAAAC,EAAW,UACX,qBAAAC,CACF,EAAwD,CACtD,IAAMC,EAAW,CAAE,QAAS,EAAG,EAC3BC,EAAmC,KAEnC,OAAO,iBAAqB,MACVF,EAChB,QAAQ,QAAQA,CAAoB,EACpCG,EAAkB,CAAE,OAAAN,EAAQ,QAAAC,EAAS,SAAAC,CAAS,CAAC,GACvC,KAAMK,GAAS,CACzBF,EAAU,IAAI,iBAAiBE,CAAI,E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,EAEtC,OAAO,MAAMF,EAAa,aAAa,IACrC,IACEK,GACE,SAAY,CACLL,EAAa,SAAS,GACzB,MAAMA,EAAa,WAAW,EAGhC,IAAMM,EAAQN,EAAa,UAAU,EACrC,OAAAN,EAAM,wBAAyBY,EAAO,KAAMF,EAAgB,EAAE,EACvD,MAAMG,GAAqBX,EAAQ,CAAE,MAAAU,EAAO,GAAGF,CAAgB,CAAC,CACzE,EACA,CACE,QAAS,EACT,gBAAiB,MAAOI,GAAU,CAEhC,GAAIR,EAAa,iBAAiBQ,CAAK,EAAG,CACxCd,EAAM,4BAA6Bc,EAAM,OAAO,EAChD,MAAMR,EAAa,WAAW,EAC9B,OAGF,MAAMQ,CACR,CACF,CACF,EACF,CAAE,eAAgB,EAAK,CACzB,CACF,CCxFA,OAAc,aAAAC,OAAiB,OAGxB,SAASC,GAAUC,EAAWC,EAAeC,EAAc,EAAGC,EAAe,KAAW,CAC7F,OAAOC,GAAU,CAACC,EAAQL,EAAM,EAAGC,CAAK,EAAGE,EAASE,EAAQL,EAAMC,EAAQC,CAAW,CAAC,CAAC,CACzF,CCLA,OAAyB,aAAAI,OAAiB,OAG1C,IAAMC,GAAQA,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,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"]}
1
+ {"version":3,"sources":["../src/createBenchmark.ts","../src/createBurnerAccount.ts","../src/getContract.ts","../src/getBurnerPrivateKey.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 { 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 {\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 = viem_getContract({\n abi,\n address,\n client: {\n public: publicClient,\n wallet: walletClient,\n },\n }) as unknown as GetContractReturnType<TAbi, { public: TPublicClient; wallet: TWalletClient }, TAddress> & {\n write: unknown;\n };\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<\n TAbi,\n ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\">,\n TChain,\n TAccount\n >;\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, { public: TPublicClient; wallet: TWalletClient }, TAddress>;\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 } 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":"gLAAA,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,EAA0B,CAG5D,MAAO,CACL,GAHcF,EAAoBE,CAAU,CAI9C,CACF,CCTA,OAcE,eAAeC,MACV,OAMP,SAASC,EAAsBC,EAG7B,CACA,IAAMC,EAAUD,EAAO,QAAU,MAAM,QAAQA,EAAO,CAAC,CAAC,EAClDE,EAAOD,EAAUD,EAAO,CAAC,EAAK,CAAC,EAC/BG,GAAWF,EAAUD,EAAO,CAAC,EAAIA,EAAO,CAA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Step","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","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"]}
@@ -16,4 +16,10 @@ 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
+ type evaluate<t> = {
20
+ [k in keyof t]: t[k];
21
+ } & unknown;
22
+
23
+ type satisfy<base, t extends base> = t;
24
+
25
+ export { AsDependent, ExtractUserTypes, OrDefault, OrDefaults, RequireKeys, ReverseMap, StringForUnion, UnionKeys, UnionOmit, UnionPick, evaluate, satisfy };