diff --git a/package-lock.json b/package-lock.json index 75e37ab..345b4c8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1082,9 +1082,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1101,9 +1098,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1120,9 +1114,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1139,9 +1130,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1158,9 +1146,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1177,9 +1162,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1196,9 +1178,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1215,9 +1194,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -1234,9 +1210,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1259,9 +1232,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1284,9 +1254,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1309,9 +1276,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1334,9 +1298,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1359,9 +1320,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1384,9 +1342,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1409,9 +1364,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1644,9 +1596,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1663,9 +1612,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1682,9 +1628,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1701,9 +1644,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2488,9 +2428,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -2508,9 +2445,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -2528,9 +2462,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -2548,9 +2479,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -2568,9 +2496,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -2588,9 +2513,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -7391,9 +7313,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -7415,9 +7334,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -7439,9 +7355,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -7463,9 +7376,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ diff --git a/vendor/aa/index.js b/vendor/aa/index.js index 59a6b44..0c1089b 100644 --- a/vendor/aa/index.js +++ b/vendor/aa/index.js @@ -1,11 +1,15 @@ var __defProp = Object.defineProperty; +var __returnValue = (v) => v; +function __exportSetter(name, newValue) { + this[name] = __returnValue.bind(null, newValue); +} var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true, configurable: true, - set: (newValue) => all[name] = () => newValue + set: __exportSetter.bind(all, name) }); }; var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res); @@ -893,254 +897,805 @@ var init_exports = __esm(() => { init_parseAbiParameters(); }); -// ../viem/src/_esm/utils/abi/formatAbiItem.js -function formatAbiItem2(abiItem, { includeName = false } = {}) { - if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error") - throw new InvalidDefinitionTypeError(abiItem.type); - return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`; -} -function formatAbiParams(params, { includeName = false } = {}) { - if (!params) - return ""; - return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ","); -} -function formatAbiParam(param, { includeName }) { - if (param.type.startsWith("tuple")) { - return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`; - } - return param.type + (includeName && param.name ? ` ${param.name}` : ""); -} -var init_formatAbiItem2 = __esm(() => { - init_abi(); -}); - -// ../viem/src/_esm/utils/data/isHex.js -function isHex(value, { strict = true } = {}) { - if (!value) - return false; - if (typeof value !== "string") - return false; - return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x"); -} - -// ../viem/src/_esm/utils/data/size.js -function size(value) { - if (isHex(value, { strict: false })) - return Math.ceil((value.length - 2) / 2); - return value.length; +// ../viem/src/_esm/accounts/utils/parseAccount.js +function parseAccount(account) { + if (typeof account === "string") + return { address: account, type: "json-rpc" }; + return account; } -var init_size = () => {}; - -// ../viem/src/_esm/errors/version.js -var version2 = "2.55.15"; -// ../viem/src/_esm/errors/base.js -function walk(err, fn) { - if (fn?.(err)) - return err; - if (err && typeof err === "object" && "cause" in err && err.cause !== undefined) - return walk(err.cause, fn); - return fn ? null : err; -} -var errorConfig, BaseError2; -var init_base = __esm(() => { - errorConfig = { - getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : undefined, - version: `viem@${version2}` - }; - BaseError2 = class BaseError2 extends Error { - constructor(shortMessage, args = {}) { - const details = (() => { - if (args.cause instanceof BaseError2) - return args.cause.details; - if (args.cause?.message) - return args.cause.message; - return args.details; - })(); - const docsPath = (() => { - if (args.cause instanceof BaseError2) - return args.cause.docsPath || args.docsPath; - return args.docsPath; - })(); - const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath }); - const message = [ - shortMessage || "An error occurred.", - "", - ...args.metaMessages ? [...args.metaMessages, ""] : [], - ...docsUrl ? [`Docs: ${docsUrl}`] : [], - ...details ? [`Details: ${details}`] : [], - ...errorConfig.version ? [`Version: ${errorConfig.version}`] : [] - ].join(` -`); - super(message, args.cause ? { cause: args.cause } : undefined); - Object.defineProperty(this, "details", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "docsPath", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "metaMessages", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "shortMessage", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "version", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "BaseError" - }); - this.details = details; - this.docsPath = docsPath; - this.metaMessages = args.metaMessages; - this.name = args.name ?? this.name; - this.shortMessage = shortMessage; - this.version = version2; +// ../viem/src/_esm/constants/abis.js +var multicall3Abi, batchGatewayAbi, universalResolverErrors, universalResolverResolveAbi, universalResolverReverseAbi, textResolverAbi, addressResolverAbi, erc1271Abi, erc6492SignatureValidatorAbi, erc20Abi; +var init_abis = __esm(() => { + multicall3Abi = [ + { + inputs: [ + { + components: [ + { + name: "target", + type: "address" + }, + { + name: "allowFailure", + type: "bool" + }, + { + name: "callData", + type: "bytes" + } + ], + name: "calls", + type: "tuple[]" + } + ], + name: "aggregate3", + outputs: [ + { + components: [ + { + name: "success", + type: "bool" + }, + { + name: "returnData", + type: "bytes" + } + ], + name: "returnData", + type: "tuple[]" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + name: "addr", + type: "address" + } + ], + name: "getEthBalance", + outputs: [ + { + name: "balance", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "getCurrentBlockTimestamp", + outputs: [ + { + internalType: "uint256", + name: "timestamp", + type: "uint256" + } + ], + stateMutability: "view", + type: "function" } - walk(fn) { - return walk(this, fn); + ]; + batchGatewayAbi = [ + { + name: "query", + type: "function", + stateMutability: "view", + inputs: [ + { + type: "tuple[]", + name: "queries", + components: [ + { + type: "address", + name: "sender" + }, + { + type: "string[]", + name: "urls" + }, + { + type: "bytes", + name: "data" + } + ] + } + ], + outputs: [ + { + type: "bool[]", + name: "failures" + }, + { + type: "bytes[]", + name: "responses" + } + ] + }, + { + name: "HttpError", + type: "error", + inputs: [ + { + type: "uint16", + name: "status" + }, + { + type: "string", + name: "message" + } + ] } - }; -}); - -// ../viem/src/_esm/errors/abi.js -var AbiConstructorNotFoundError, AbiConstructorParamsNotFoundError, AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, AbiErrorInputsNotFoundError, AbiErrorNotFoundError, AbiErrorSignatureNotFoundError, AbiEventSignatureEmptyTopicsError, AbiEventSignatureNotFoundError, AbiEventNotFoundError, AbiFunctionNotFoundError, AbiFunctionOutputsNotFoundError, AbiFunctionSignatureNotFoundError, AbiItemAmbiguityError, BytesSizeMismatchError, DecodeLogDataMismatch, DecodeLogTopicsMismatch, InvalidAbiEncodingTypeError, InvalidAbiDecodingTypeError, InvalidArrayError, InvalidDefinitionTypeError; -var init_abi = __esm(() => { - init_formatAbiItem2(); - init_size(); - init_base(); - AbiConstructorNotFoundError = class AbiConstructorNotFoundError extends BaseError2 { - constructor({ docsPath }) { - super([ - "A constructor was not found on the ABI.", - "Make sure you are using the correct ABI and that the constructor exists on it." - ].join(` -`), { - docsPath, - name: "AbiConstructorNotFoundError" - }); + ]; + universalResolverErrors = [ + { + inputs: [ + { + name: "dns", + type: "bytes" + } + ], + name: "DNSDecodingFailed", + type: "error" + }, + { + inputs: [ + { + name: "ens", + type: "string" + } + ], + name: "DNSEncodingFailed", + type: "error" + }, + { + inputs: [], + name: "EmptyAddress", + type: "error" + }, + { + inputs: [ + { + name: "status", + type: "uint16" + }, + { + name: "message", + type: "string" + } + ], + name: "HttpError", + type: "error" + }, + { + inputs: [], + name: "InvalidBatchGatewayResponse", + type: "error" + }, + { + inputs: [ + { + name: "errorData", + type: "bytes" + } + ], + name: "ResolverError", + type: "error" + }, + { + inputs: [ + { + name: "name", + type: "bytes" + }, + { + name: "resolver", + type: "address" + } + ], + name: "ResolverNotContract", + type: "error" + }, + { + inputs: [ + { + name: "name", + type: "bytes" + } + ], + name: "ResolverNotFound", + type: "error" + }, + { + inputs: [ + { + name: "primary", + type: "string" + }, + { + name: "primaryAddress", + type: "bytes" + } + ], + name: "ReverseAddressMismatch", + type: "error" + }, + { + inputs: [ + { + internalType: "bytes4", + name: "selector", + type: "bytes4" + } + ], + name: "UnsupportedResolverProfile", + type: "error" } - }; - AbiConstructorParamsNotFoundError = class AbiConstructorParamsNotFoundError extends BaseError2 { - constructor({ docsPath }) { - super([ - "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.", - "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists." - ].join(` -`), { - docsPath, - name: "AbiConstructorParamsNotFoundError" - }); + ]; + universalResolverResolveAbi = [ + ...universalResolverErrors, + { + name: "resolveWithGateways", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes" }, + { name: "data", type: "bytes" }, + { name: "gateways", type: "string[]" } + ], + outputs: [ + { name: "", type: "bytes" }, + { name: "address", type: "address" } + ] } - }; - AbiDecodingDataSizeTooSmallError = class AbiDecodingDataSizeTooSmallError extends BaseError2 { - constructor({ data, params, size: size2 }) { - super([`Data size of ${size2} bytes is too small for given parameters.`].join(` -`), { - metaMessages: [ - `Params: (${formatAbiParams(params, { includeName: true })})`, - `Data: ${data} (${size2} bytes)` - ], - name: "AbiDecodingDataSizeTooSmallError" - }); - Object.defineProperty(this, "data", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "params", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "size", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.data = data; - this.params = params; - this.size = size2; + ]; + universalResolverReverseAbi = [ + ...universalResolverErrors, + { + name: "reverseWithGateways", + type: "function", + stateMutability: "view", + inputs: [ + { type: "bytes", name: "reverseName" }, + { type: "uint256", name: "coinType" }, + { type: "string[]", name: "gateways" } + ], + outputs: [ + { type: "string", name: "resolvedName" }, + { type: "address", name: "resolver" }, + { type: "address", name: "reverseResolver" } + ] } - }; - AbiDecodingZeroDataError = class AbiDecodingZeroDataError extends BaseError2 { - constructor({ cause } = {}) { - super('Cannot decode zero data ("0x") with ABI parameters.', { - name: "AbiDecodingZeroDataError", - cause - }); + ]; + textResolverAbi = [ + { + name: "text", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes32" }, + { name: "key", type: "string" } + ], + outputs: [{ name: "", type: "string" }] } - }; - AbiEncodingArrayLengthMismatchError = class AbiEncodingArrayLengthMismatchError extends BaseError2 { - constructor({ expectedLength, givenLength, type }) { - super([ - `ABI encoding array length mismatch for type ${type}.`, - `Expected length: ${expectedLength}`, - `Given length: ${givenLength}` - ].join(` -`), { name: "AbiEncodingArrayLengthMismatchError" }); + ]; + addressResolverAbi = [ + { + name: "addr", + type: "function", + stateMutability: "view", + inputs: [{ name: "name", type: "bytes32" }], + outputs: [{ name: "", type: "address" }] + }, + { + name: "addr", + type: "function", + stateMutability: "view", + inputs: [ + { name: "name", type: "bytes32" }, + { name: "coinType", type: "uint256" } + ], + outputs: [{ name: "", type: "bytes" }] } - }; - AbiEncodingBytesSizeMismatchError = class AbiEncodingBytesSizeMismatchError extends BaseError2 { - constructor({ expectedSize, value }) { - super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); + ]; + erc1271Abi = [ + { + name: "isValidSignature", + type: "function", + stateMutability: "view", + inputs: [ + { name: "hash", type: "bytes32" }, + { name: "signature", type: "bytes" } + ], + outputs: [{ name: "", type: "bytes4" }] } - }; - AbiEncodingLengthMismatchError = class AbiEncodingLengthMismatchError extends BaseError2 { - constructor({ expectedLength, givenLength }) { - super([ - "ABI encoding params/values length mismatch.", - `Expected length (params): ${expectedLength}`, - `Given length (values): ${givenLength}` - ].join(` -`), { name: "AbiEncodingLengthMismatchError" }); - } - }; - AbiErrorInputsNotFoundError = class AbiErrorInputsNotFoundError extends BaseError2 { - constructor(errorName, { docsPath }) { - super([ - `Arguments (\`args\`) were provided to "${errorName}", but "${errorName}" on the ABI does not contain any parameters (\`inputs\`).`, - "Cannot encode error result without knowing what the parameter types are.", - "Make sure you are using the correct ABI and that the inputs exist on it." - ].join(` -`), { - docsPath, - name: "AbiErrorInputsNotFoundError" - }); + ]; + erc6492SignatureValidatorAbi = [ + { + inputs: [ + { + name: "_signer", + type: "address" + }, + { + name: "_hash", + type: "bytes32" + }, + { + name: "_signature", + type: "bytes" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [ + { + name: "_signer", + type: "address" + }, + { + name: "_hash", + type: "bytes32" + }, + { + name: "_signature", + type: "bytes" + } + ], + outputs: [ + { + type: "bool" + } + ], + stateMutability: "nonpayable", + type: "function", + name: "isValidSig" } - }; - AbiErrorNotFoundError = class AbiErrorNotFoundError extends BaseError2 { - constructor(errorName, { docsPath } = {}) { - super([ - `Error ${errorName ? `"${errorName}" ` : ""}not found on ABI.`, - "Make sure you are using the correct ABI and that the error exists on it." - ].join(` -`), { - docsPath, - name: "AbiErrorNotFoundError" - }); + ]; + erc20Abi = [ + { + type: "event", + name: "Approval", + inputs: [ + { + indexed: true, + name: "owner", + type: "address" + }, + { + indexed: true, + name: "spender", + type: "address" + }, + { + indexed: false, + name: "value", + type: "uint256" + } + ] + }, + { + type: "event", + name: "Transfer", + inputs: [ + { + indexed: true, + name: "from", + type: "address" + }, + { + indexed: true, + name: "to", + type: "address" + }, + { + indexed: false, + name: "value", + type: "uint256" + } + ] + }, + { + type: "function", + name: "allowance", + stateMutability: "view", + inputs: [ + { + name: "owner", + type: "address" + }, + { + name: "spender", + type: "address" + } + ], + outputs: [ + { + type: "uint256" + } + ] + }, + { + type: "function", + name: "approve", + stateMutability: "nonpayable", + inputs: [ + { + name: "spender", + type: "address" + }, + { + name: "amount", + type: "uint256" + } + ], + outputs: [ + { + type: "bool" + } + ] + }, + { + type: "function", + name: "balanceOf", + stateMutability: "view", + inputs: [ + { + name: "account", + type: "address" + } + ], + outputs: [ + { + type: "uint256" + } + ] + }, + { + type: "function", + name: "decimals", + stateMutability: "view", + inputs: [], + outputs: [ + { + type: "uint8" + } + ] + }, + { + type: "function", + name: "name", + stateMutability: "view", + inputs: [], + outputs: [ + { + type: "string" + } + ] + }, + { + type: "function", + name: "symbol", + stateMutability: "view", + inputs: [], + outputs: [ + { + type: "string" + } + ] + }, + { + type: "function", + name: "totalSupply", + stateMutability: "view", + inputs: [], + outputs: [ + { + type: "uint256" + } + ] + }, + { + type: "function", + name: "transfer", + stateMutability: "nonpayable", + inputs: [ + { + name: "recipient", + type: "address" + }, + { + name: "amount", + type: "uint256" + } + ], + outputs: [ + { + type: "bool" + } + ] + }, + { + type: "function", + name: "transferFrom", + stateMutability: "nonpayable", + inputs: [ + { + name: "sender", + type: "address" + }, + { + name: "recipient", + type: "address" + }, + { + name: "amount", + type: "uint256" + } + ], + outputs: [ + { + type: "bool" + } + ] + } + ]; +}); + +// ../viem/src/_esm/utils/abi/formatAbiItem.js +function formatAbiItem2(abiItem, { includeName = false } = {}) { + if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error") + throw new InvalidDefinitionTypeError(abiItem.type); + return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`; +} +function formatAbiParams(params, { includeName = false } = {}) { + if (!params) + return ""; + return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ","); +} +function formatAbiParam(param, { includeName }) { + if (param.type.startsWith("tuple")) { + return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`; + } + return param.type + (includeName && param.name ? ` ${param.name}` : ""); +} +var init_formatAbiItem2 = __esm(() => { + init_abi(); +}); + +// ../viem/src/_esm/utils/data/isHex.js +function isHex(value, { strict = true } = {}) { + if (!value) + return false; + if (typeof value !== "string") + return false; + return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x"); +} + +// ../viem/src/_esm/utils/data/size.js +function size2(value) { + if (isHex(value, { strict: false })) + return Math.ceil((value.length - 2) / 2); + return value.length; +} +var init_size = () => {}; + +// ../viem/src/_esm/errors/version.js +var version2 = "2.55.15"; + +// ../viem/src/_esm/errors/base.js +function walk(err, fn) { + if (fn?.(err)) + return err; + if (err && typeof err === "object" && "cause" in err && err.cause !== undefined) + return walk(err.cause, fn); + return fn ? null : err; +} +var errorConfig, BaseError2; +var init_base = __esm(() => { + errorConfig = { + getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : undefined, + version: `viem@${version2}` + }; + BaseError2 = class BaseError2 extends Error { + constructor(shortMessage, args = {}) { + const details = (() => { + if (args.cause instanceof BaseError2) + return args.cause.details; + if (args.cause?.message) + return args.cause.message; + return args.details; + })(); + const docsPath = (() => { + if (args.cause instanceof BaseError2) + return args.cause.docsPath || args.docsPath; + return args.docsPath; + })(); + const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath }); + const message = [ + shortMessage || "An error occurred.", + "", + ...args.metaMessages ? [...args.metaMessages, ""] : [], + ...docsUrl ? [`Docs: ${docsUrl}`] : [], + ...details ? [`Details: ${details}`] : [], + ...errorConfig.version ? [`Version: ${errorConfig.version}`] : [] + ].join(` +`); + super(message, args.cause ? { cause: args.cause } : undefined); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "docsPath", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "metaMessages", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "version", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "BaseError" + }); + this.details = details; + this.docsPath = docsPath; + this.metaMessages = args.metaMessages; + this.name = args.name ?? this.name; + this.shortMessage = shortMessage; + this.version = version2; + } + walk(fn) { + return walk(this, fn); + } + }; +}); + +// ../viem/src/_esm/errors/abi.js +var AbiConstructorNotFoundError, AbiConstructorParamsNotFoundError, AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, AbiErrorInputsNotFoundError, AbiErrorNotFoundError, AbiErrorSignatureNotFoundError, AbiEventSignatureEmptyTopicsError, AbiEventSignatureNotFoundError, AbiEventNotFoundError, AbiFunctionNotFoundError, AbiFunctionOutputsNotFoundError, AbiFunctionSignatureNotFoundError, AbiItemAmbiguityError, BytesSizeMismatchError, DecodeLogDataMismatch, DecodeLogTopicsMismatch, InvalidAbiEncodingTypeError, InvalidAbiDecodingTypeError, InvalidArrayError, InvalidDefinitionTypeError; +var init_abi = __esm(() => { + init_formatAbiItem2(); + init_size(); + init_base(); + AbiConstructorNotFoundError = class AbiConstructorNotFoundError extends BaseError2 { + constructor({ docsPath }) { + super([ + "A constructor was not found on the ABI.", + "Make sure you are using the correct ABI and that the constructor exists on it." + ].join(` +`), { + docsPath, + name: "AbiConstructorNotFoundError" + }); + } + }; + AbiConstructorParamsNotFoundError = class AbiConstructorParamsNotFoundError extends BaseError2 { + constructor({ docsPath }) { + super([ + "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.", + "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists." + ].join(` +`), { + docsPath, + name: "AbiConstructorParamsNotFoundError" + }); + } + }; + AbiDecodingDataSizeTooSmallError = class AbiDecodingDataSizeTooSmallError extends BaseError2 { + constructor({ data, params, size: size3 }) { + super([`Data size of ${size3} bytes is too small for given parameters.`].join(` +`), { + metaMessages: [ + `Params: (${formatAbiParams(params, { includeName: true })})`, + `Data: ${data} (${size3} bytes)` + ], + name: "AbiDecodingDataSizeTooSmallError" + }); + Object.defineProperty(this, "data", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "params", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "size", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.data = data; + this.params = params; + this.size = size3; + } + }; + AbiDecodingZeroDataError = class AbiDecodingZeroDataError extends BaseError2 { + constructor({ cause } = {}) { + super('Cannot decode zero data ("0x") with ABI parameters.', { + name: "AbiDecodingZeroDataError", + cause + }); + } + }; + AbiEncodingArrayLengthMismatchError = class AbiEncodingArrayLengthMismatchError extends BaseError2 { + constructor({ expectedLength, givenLength, type }) { + super([ + `ABI encoding array length mismatch for type ${type}.`, + `Expected length: ${expectedLength}`, + `Given length: ${givenLength}` + ].join(` +`), { name: "AbiEncodingArrayLengthMismatchError" }); + } + }; + AbiEncodingBytesSizeMismatchError = class AbiEncodingBytesSizeMismatchError extends BaseError2 { + constructor({ expectedSize, value }) { + super(`Size of bytes "${value}" (bytes${size2(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); + } + }; + AbiEncodingLengthMismatchError = class AbiEncodingLengthMismatchError extends BaseError2 { + constructor({ expectedLength, givenLength }) { + super([ + "ABI encoding params/values length mismatch.", + `Expected length (params): ${expectedLength}`, + `Given length (values): ${givenLength}` + ].join(` +`), { name: "AbiEncodingLengthMismatchError" }); + } + }; + AbiErrorInputsNotFoundError = class AbiErrorInputsNotFoundError extends BaseError2 { + constructor(errorName, { docsPath }) { + super([ + `Arguments (\`args\`) were provided to "${errorName}", but "${errorName}" on the ABI does not contain any parameters (\`inputs\`).`, + "Cannot encode error result without knowing what the parameter types are.", + "Make sure you are using the correct ABI and that the inputs exist on it." + ].join(` +`), { + docsPath, + name: "AbiErrorInputsNotFoundError" + }); + } + }; + AbiErrorNotFoundError = class AbiErrorNotFoundError extends BaseError2 { + constructor(errorName, { docsPath } = {}) { + super([ + `Error ${errorName ? `"${errorName}" ` : ""}not found on ABI.`, + "Make sure you are using the correct ABI and that the error exists on it." + ].join(` +`), { + docsPath, + name: "AbiErrorNotFoundError" + }); } }; AbiErrorSignatureNotFoundError = class AbiErrorSignatureNotFoundError extends BaseError2 { @@ -1257,14 +1812,14 @@ var init_abi = __esm(() => { } }; DecodeLogDataMismatch = class DecodeLogDataMismatch extends BaseError2 { - constructor({ abiItem, data, params, size: size2 }) { + constructor({ abiItem, data, params, size: size3 }) { super([ - `Data size of ${size2} bytes is too small for non-indexed event parameters.` + `Data size of ${size3} bytes is too small for non-indexed event parameters.` ].join(` `), { metaMessages: [ `Params: (${formatAbiParams(params, { includeName: true })})`, - `Data: ${data} (${size2} bytes)` + `Data: ${data} (${size3} bytes)` ], name: "DecodeLogDataMismatch" }); @@ -1295,7 +1850,7 @@ var init_abi = __esm(() => { this.abiItem = abiItem; this.data = data; this.params = params; - this.size = size2; + this.size = size3; } }; DecodeLogTopicsMismatch = class DecodeLogTopicsMismatch extends BaseError2 { @@ -1350,58 +1905,75 @@ var init_abi = __esm(() => { }; }); -// ../viem/src/_esm/errors/data.js -var SliceOffsetOutOfBoundsError, SizeExceedsPaddingSizeError, InvalidBytesLengthError; -var init_data = __esm(() => { +// ../viem/src/_esm/errors/address.js +var InvalidAddressError; +var init_address = __esm(() => { init_base(); - SliceOffsetOutOfBoundsError = class SliceOffsetOutOfBoundsError extends BaseError2 { - constructor({ offset, position, size: size2 }) { - super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" }); - } - }; + InvalidAddressError = class InvalidAddressError extends BaseError2 { + constructor({ address }) { + super(`Address "${address}" is invalid.`, { + metaMessages: [ + "- Address must be a hex value of 20 bytes (40 hex characters).", + "- Address must match its checksum counterpart." + ], + name: "InvalidAddressError" + }); + } + }; +}); + +// ../viem/src/_esm/errors/data.js +var SliceOffsetOutOfBoundsError, SizeExceedsPaddingSizeError, InvalidBytesLengthError; +var init_data = __esm(() => { + init_base(); + SliceOffsetOutOfBoundsError = class SliceOffsetOutOfBoundsError extends BaseError2 { + constructor({ offset, position, size: size3 }) { + super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size3}).`, { name: "SliceOffsetOutOfBoundsError" }); + } + }; SizeExceedsPaddingSizeError = class SizeExceedsPaddingSizeError extends BaseError2 { - constructor({ size: size2, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); + constructor({ size: size3, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size3}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); } }; InvalidBytesLengthError = class InvalidBytesLengthError extends BaseError2 { - constructor({ size: size2, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size2} ${type} long.`, { name: "InvalidBytesLengthError" }); + constructor({ size: size3, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size3} ${type} long.`, { name: "InvalidBytesLengthError" }); } }; }); // ../viem/src/_esm/utils/data/pad.js -function pad(hexOrBytes, { dir, size: size2 = 32 } = {}) { +function pad(hexOrBytes, { dir, size: size3 = 32 } = {}) { if (typeof hexOrBytes === "string") - return padHex(hexOrBytes, { dir, size: size2 }); - return padBytes(hexOrBytes, { dir, size: size2 }); + return padHex(hexOrBytes, { dir, size: size3 }); + return padBytes(hexOrBytes, { dir, size: size3 }); } -function padHex(hex_, { dir, size: size2 = 32 } = {}) { - if (size2 === null) +function padHex(hex_, { dir, size: size3 = 32 } = {}) { + if (size3 === null) return hex_; const hex = hex_.replace("0x", ""); - if (hex.length > size2 * 2) + if (hex.length > size3 * 2) throw new SizeExceedsPaddingSizeError({ size: Math.ceil(hex.length / 2), - targetSize: size2, + targetSize: size3, type: "hex" }); - return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`; + return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size3 * 2, "0")}`; } -function padBytes(bytes, { dir, size: size2 = 32 } = {}) { - if (size2 === null) +function padBytes(bytes, { dir, size: size3 = 32 } = {}) { + if (size3 === null) return bytes; - if (bytes.length > size2) + if (bytes.length > size3) throw new SizeExceedsPaddingSizeError({ size: bytes.length, - targetSize: size2, + targetSize: size3, type: "bytes" }); - const paddedBytes = new Uint8Array(size2); - for (let i = 0;i < size2; i++) { + const paddedBytes = new Uint8Array(size3); + for (let i = 0;i < size3; i++) { const padEnd = dir === "right"; - paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; + paddedBytes[padEnd ? i : size3 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; } return paddedBytes; } @@ -1414,8 +1986,8 @@ var IntegerOutOfRangeError, InvalidBytesBooleanError, InvalidHexBooleanError, In var init_encoding = __esm(() => { init_base(); IntegerOutOfRangeError = class IntegerOutOfRangeError extends BaseError2 { - constructor({ max, min, signed, size: size2, value }) { - super(`Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" }); + constructor({ max, min, signed, size: size3, value }) { + super(`Number "${value}" is not in safe ${size3 ? `${size3 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" }); } }; InvalidBytesBooleanError = class InvalidBytesBooleanError extends BaseError2 { @@ -1479,11 +2051,11 @@ function trim(hexOrBytes, { dir = "left" } = {}) { } // ../viem/src/_esm/utils/encoding/fromHex.js -function assertSize(hexOrBytes, { size: size2 }) { - if (size(hexOrBytes) > size2) +function assertSize(hexOrBytes, { size: size3 }) { + if (size2(hexOrBytes) > size3) throw new SizeOverflowError({ - givenSize: size(hexOrBytes), - maxSize: size2 + givenSize: size2(hexOrBytes), + maxSize: size3 }); } function hexToBigInt(hex, opts = {}) { @@ -1493,11 +2065,11 @@ function hexToBigInt(hex, opts = {}) { const value = BigInt(hex); if (!signed) return value; - const size2 = (hex.length - 2) / 2; - const max = (1n << BigInt(size2) * 8n - 1n) - 1n; + const size3 = (hex.length - 2) / 2; + const max = (1n << BigInt(size3) * 8n - 1n) - 1n; if (value <= max) return value; - return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n; + return value - BigInt(`0x${"f".padStart(size3 * 2, "f")}`) - 1n; } function hexToBool(hex_, opts = {}) { let hex = hex_; @@ -1561,14 +2133,14 @@ function bytesToHex(value, opts = {}) { return hex; } function numberToHex(value_, opts = {}) { - const { signed, size: size2 } = opts; + const { signed, size: size3 } = opts; const value = BigInt(value_); let maxValue; - if (size2) { + if (size3) { if (signed) - maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n; + maxValue = (1n << BigInt(size3) * 8n - 1n) - 1n; else - maxValue = 2n ** (BigInt(size2) * 8n) - 1n; + maxValue = 2n ** (BigInt(size3) * 8n) - 1n; } else if (typeof value_ === "number") { maxValue = BigInt(Number.MAX_SAFE_INTEGER); } @@ -1579,13 +2151,13 @@ function numberToHex(value_, opts = {}) { max: maxValue ? `${maxValue}${suffix}` : undefined, min: `${minValue}${suffix}`, signed, - size: size2, + size: size3, value: `${value_}${suffix}` }); } - const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`; - if (size2) - return pad(hex, { size: size2 }); + const hex = `0x${(signed && value < 0 ? (1n << BigInt(size3 * 8)) + BigInt(value) : value).toString(16)}`; + if (size3) + return pad(hex, { size: size3 }); return hex; } function stringToHex(value_, opts = {}) { @@ -1640,13 +2212,13 @@ function hexToBytes(hex_, opts = {}) { hexString = `0${hexString}`; const length = hexString.length / 2; const bytes = new Uint8Array(length); - for (let index = 0, j = 0;index < length; index++) { + for (let index2 = 0, j = 0;index2 < length; index2++) { const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++)); const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++)); if (nibbleLeft === undefined || nibbleRight === undefined) { throw new BaseError2(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`); } - bytes[index] = nibbleLeft * 16 + nibbleRight; + bytes[index2] = nibbleLeft * 16 + nibbleRight; } return bytes; } @@ -2017,115 +2589,11 @@ var init_keccak256 = __esm(() => { init_toHex(); }); -// ../viem/src/_esm/utils/hash/hashSignature.js -function hashSignature(sig) { - return hash(sig); -} -var hash = (value) => keccak256(toBytes(value)); -var init_hashSignature = __esm(() => { - init_toBytes(); - init_keccak256(); -}); - -// ../viem/src/_esm/utils/hash/normalizeSignature.js -function normalizeSignature(signature) { - let active = true; - let current = ""; - let level = 0; - let result = ""; - let valid = false; - for (let i = 0;i < signature.length; i++) { - const char = signature[i]; - if (["(", ")", ","].includes(char)) - active = true; - if (char === "(") - level++; - if (char === ")") - level--; - if (!active) - continue; - if (level === 0) { - if (char === " " && ["event", "function", ""].includes(result)) - result = ""; - else { - result += char; - if (char === ")") { - valid = true; - break; - } - } - continue; - } - if (char === " ") { - if (signature[i - 1] !== "," && current !== "," && current !== ",(") { - current = ""; - active = false; - } - continue; - } - result += char; - current += char; - } - if (!valid) - throw new BaseError2("Unable to normalize signature."); - return result; -} -var init_normalizeSignature = __esm(() => { - init_base(); -}); - -// ../viem/src/_esm/utils/hash/toSignature.js -var toSignature = (def) => { - const def_ = (() => { - if (typeof def === "string") - return def; - return formatAbiItem(def); - })(); - return normalizeSignature(def_); -}; -var init_toSignature = __esm(() => { - init_exports(); - init_normalizeSignature(); -}); - -// ../viem/src/_esm/utils/hash/toSignatureHash.js -function toSignatureHash(fn) { - return hashSignature(toSignature(fn)); -} -var init_toSignatureHash = __esm(() => { - init_hashSignature(); - init_toSignature(); -}); - -// ../viem/src/_esm/utils/hash/toEventSelector.js -var toEventSelector; -var init_toEventSelector = __esm(() => { - init_toSignatureHash(); - toEventSelector = toSignatureHash; -}); - -// ../viem/src/_esm/errors/address.js -var InvalidAddressError; -var init_address = __esm(() => { - init_base(); - InvalidAddressError = class InvalidAddressError extends BaseError2 { - constructor({ address }) { - super(`Address "${address}" is invalid.`, { - metaMessages: [ - "- Address must be a hex value of 20 bytes (40 hex characters).", - "- Address must match its checksum counterpart." - ], - name: "InvalidAddressError" - }); - } - }; -}); - // ../viem/src/_esm/utils/lru.js var LruMap; var init_lru = __esm(() => { LruMap = class LruMap extends Map { - constructor(size2) { + constructor(size3) { super(); Object.defineProperty(this, "maxSize", { enumerable: true, @@ -2133,7 +2601,7 @@ var init_lru = __esm(() => { writable: true, value: undefined }); - this.maxSize = size2; + this.maxSize = size3; } get(key) { const value = super.get(key); @@ -2157,18 +2625,44 @@ var init_lru = __esm(() => { }; }); +// ../viem/src/_esm/utils/address/isAddress.js +function isAddress(address, options) { + const { strict = true } = options ?? {}; + const cacheKey = `${address}.${strict}`; + if (isAddressCache.has(cacheKey)) + return isAddressCache.get(cacheKey); + const result = (() => { + if (!addressRegex.test(address)) + return false; + if (address.toLowerCase() === address) + return true; + if (strict) + return checksumAddress(address) === address; + return true; + })(); + isAddressCache.set(cacheKey, result); + return result; +} +var addressRegex, isAddressCache; +var init_isAddress = __esm(() => { + init_lru(); + init_getAddress(); + addressRegex = /^0x[a-fA-F0-9]{40}$/; + isAddressCache = /* @__PURE__ */ new LruMap(8192); +}); + // ../viem/src/_esm/utils/address/getAddress.js function checksumAddress(address_, chainId) { if (checksumAddressCache.has(`${address_}.${chainId}`)) return checksumAddressCache.get(`${address_}.${chainId}`); const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase(); - const hash2 = keccak256(stringToBytes(hexAddress), "bytes"); + const hash = keccak256(stringToBytes(hexAddress), "bytes"); const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split(""); for (let i = 0;i < 40; i += 2) { - if (hash2[i >> 1] >> 4 >= 8 && address[i]) { + if (hash[i >> 1] >> 4 >= 8 && address[i]) { address[i] = address[i].toUpperCase(); } - if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) { + if ((hash[i >> 1] & 15) >= 8 && address[i + 1]) { address[i + 1] = address[i + 1].toUpperCase(); } } @@ -2191,84 +2685,231 @@ var init_getAddress = __esm(() => { checksumAddressCache = /* @__PURE__ */ new LruMap(8192); }); -// ../viem/src/_esm/utils/address/isAddress.js -function isAddress(address, options) { - const { strict = true } = options ?? {}; - const cacheKey = `${address}.${strict}`; - if (isAddressCache.has(cacheKey)) - return isAddressCache.get(cacheKey); - const result = (() => { - if (!addressRegex.test(address)) - return false; - if (address.toLowerCase() === address) - return true; - if (strict) - return checksumAddress(address) === address; - return true; - })(); - isAddressCache.set(cacheKey, result); - return result; -} -var addressRegex, isAddressCache; -var init_isAddress = __esm(() => { - init_lru(); - init_getAddress(); - addressRegex = /^0x[a-fA-F0-9]{40}$/; - isAddressCache = /* @__PURE__ */ new LruMap(8192); +// ../viem/src/_esm/errors/cursor.js +var NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError; +var init_cursor = __esm(() => { + init_base(); + NegativeOffsetError = class NegativeOffsetError extends BaseError2 { + constructor({ offset }) { + super(`Offset \`${offset}\` cannot be negative.`, { + name: "NegativeOffsetError" + }); + } + }; + PositionOutOfBoundsError = class PositionOutOfBoundsError extends BaseError2 { + constructor({ length, position }) { + super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); + } + }; + RecursiveReadLimitExceededError = class RecursiveReadLimitExceededError extends BaseError2 { + constructor({ count, limit }) { + super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" }); + } + }; }); -// ../viem/src/_esm/utils/data/concat.js -function concat(values) { - if (typeof values[0] === "string") - return concatHex(values); - return concatBytes2(values); -} -function concatBytes2(values) { - let length = 0; - for (const arr of values) { - length += arr.length; - } - const result = new Uint8Array(length); - let offset = 0; - for (const arr of values) { - result.set(arr, offset); - offset += arr.length; - } - return result; -} -function concatHex(values) { - return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`; -} - -// ../viem/src/_esm/utils/data/slice.js -function slice(value, start, end, { strict } = {}) { - if (isHex(value, { strict: false })) - return sliceHex(value, start, end, { - strict - }); - return sliceBytes(value, start, end, { - strict - }); -} -function assertStartOffset(value, start) { - if (typeof start === "number" && start > 0 && start > size(value) - 1) - throw new SliceOffsetOutOfBoundsError({ - offset: start, - position: "start", - size: size(value) - }); -} -function assertEndOffset(value, start, end) { - if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) { - throw new SliceOffsetOutOfBoundsError({ - offset: end, - position: "end", - size: size(value) - }); - } +// ../viem/src/_esm/utils/cursor.js +function createCursor(bytes, { recursiveReadLimit = 8192 } = {}) { + const cursor = Object.create(staticCursor); + cursor.bytes = bytes; + cursor.dataView = new DataView(bytes.buffer ?? bytes, bytes.byteOffset, bytes.byteLength); + cursor.positionReadCount = new Map; + cursor.recursiveReadLimit = recursiveReadLimit; + return cursor; } -function sliceBytes(value_, start, end, { strict } = {}) { - assertStartOffset(value_, start); +var staticCursor; +var init_cursor2 = __esm(() => { + init_cursor(); + staticCursor = { + bytes: new Uint8Array, + dataView: new DataView(new ArrayBuffer(0)), + position: 0, + positionReadCount: new Map, + recursiveReadCount: 0, + recursiveReadLimit: Number.POSITIVE_INFINITY, + assertReadLimit() { + if (this.recursiveReadCount >= this.recursiveReadLimit) + throw new RecursiveReadLimitExceededError({ + count: this.recursiveReadCount + 1, + limit: this.recursiveReadLimit + }); + }, + assertPosition(position) { + if (position < 0 || position > this.bytes.length - 1) + throw new PositionOutOfBoundsError({ + length: this.bytes.length, + position + }); + }, + decrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError({ offset }); + const position = this.position - offset; + this.assertPosition(position); + this.position = position; + }, + getReadCount(position) { + return this.positionReadCount.get(position || this.position) || 0; + }, + incrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError({ offset }); + const position = this.position + offset; + this.assertPosition(position); + this.position = position; + }, + inspectByte(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectBytes(length, position_) { + const position = position_ ?? this.position; + this.assertPosition(position + length - 1); + return this.bytes.subarray(position, position + length); + }, + inspectUint8(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectUint16(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 1); + return this.dataView.getUint16(position); + }, + inspectUint24(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 2); + return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); + }, + inspectUint32(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 3); + return this.dataView.getUint32(position); + }, + pushByte(byte) { + this.assertPosition(this.position); + this.bytes[this.position] = byte; + this.position++; + }, + pushBytes(bytes) { + this.assertPosition(this.position + bytes.length - 1); + this.bytes.set(bytes, this.position); + this.position += bytes.length; + }, + pushUint8(value) { + this.assertPosition(this.position); + this.bytes[this.position] = value; + this.position++; + }, + pushUint16(value) { + this.assertPosition(this.position + 1); + this.dataView.setUint16(this.position, value); + this.position += 2; + }, + pushUint24(value) { + this.assertPosition(this.position + 2); + this.dataView.setUint16(this.position, value >> 8); + this.dataView.setUint8(this.position + 2, value & ~4294967040); + this.position += 3; + }, + pushUint32(value) { + this.assertPosition(this.position + 3); + this.dataView.setUint32(this.position, value); + this.position += 4; + }, + readByte() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectByte(); + this.position++; + return value; + }, + readBytes(length, size3) { + this.assertReadLimit(); + this._touch(); + const value = this.inspectBytes(length); + this.position += size3 ?? length; + return value; + }, + readUint8() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint8(); + this.position += 1; + return value; + }, + readUint16() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint16(); + this.position += 2; + return value; + }, + readUint24() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint24(); + this.position += 3; + return value; + }, + readUint32() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint32(); + this.position += 4; + return value; + }, + get remaining() { + return this.bytes.length - this.position; + }, + setPosition(position) { + const oldPosition = this.position; + this.assertPosition(position); + this.position = position; + return () => this.position = oldPosition; + }, + _touch() { + if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) + return; + const count = this.getReadCount(); + this.positionReadCount.set(this.position, count + 1); + if (count > 0) + this.recursiveReadCount++; + } + }; +}); + +// ../viem/src/_esm/utils/data/slice.js +function slice(value, start, end, { strict } = {}) { + if (isHex(value, { strict: false })) + return sliceHex(value, start, end, { + strict + }); + return sliceBytes(value, start, end, { + strict + }); +} +function assertStartOffset(value, start) { + if (typeof start === "number" && start > 0 && start > size2(value) - 1) + throw new SliceOffsetOutOfBoundsError({ + offset: start, + position: "start", + size: size2(value) + }); +} +function assertEndOffset(value, start, end) { + if (typeof start === "number" && typeof end === "number" && size2(value) !== end - start) { + throw new SliceOffsetOutOfBoundsError({ + offset: end, + position: "end", + size: size2(value) + }); + } +} +function sliceBytes(value_, start, end, { strict } = {}) { + assertStartOffset(value_, start); const value = value_.slice(start, end); if (strict) assertEndOffset(value, start, end); @@ -2286,6 +2927,66 @@ var init_slice = __esm(() => { init_size(); }); +// ../viem/src/_esm/utils/encoding/fromBytes.js +function bytesToBigInt(bytes, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes, { size: opts.size }); + const hex = bytesToHex(bytes); + return hexToBigInt(hex, opts); +} +function bytesToBool(bytes_, opts = {}) { + let bytes = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes, { size: opts.size }); + bytes = trim(bytes); + } + if (bytes.length > 1 || bytes[0] > 1) + throw new InvalidBytesBooleanError(bytes); + return Boolean(bytes[0]); +} +function bytesToNumber(bytes, opts = {}) { + if (typeof opts.size !== "undefined") + assertSize(bytes, { size: opts.size }); + const hex = bytesToHex(bytes); + return hexToNumber(hex, opts); +} +function bytesToString(bytes_, opts = {}) { + let bytes = bytes_; + if (typeof opts.size !== "undefined") { + assertSize(bytes, { size: opts.size }); + bytes = trim(bytes, { dir: "right" }); + } + return new TextDecoder().decode(bytes); +} +var init_fromBytes = __esm(() => { + init_encoding(); + init_fromHex(); + init_toHex(); +}); + +// ../viem/src/_esm/utils/data/concat.js +function concat(values) { + if (typeof values[0] === "string") + return concatHex(values); + return concatBytes2(values); +} +function concatBytes2(values) { + let length = 0; + for (const arr of values) { + length += arr.length; + } + const result = new Uint8Array(length); + let offset = 0; + for (const arr of values) { + result.set(arr, offset); + offset += arr.length; + } + return result; +} +function concatHex(values) { + return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`; +} + // ../viem/src/_esm/utils/regex.js var bytesRegex2, integerRegex2; var init_regex2 = __esm(() => { @@ -2332,10 +3033,10 @@ function prepareParam({ param, value }) { } if (param.type.startsWith("uint") || param.type.startsWith("int")) { const signed = param.type.startsWith("int"); - const [, , size2 = "256"] = integerRegex2.exec(param.type) ?? []; + const [, , size3 = "256"] = integerRegex2.exec(param.type) ?? []; return encodeNumber(value, { signed, - size: Number(size2) + size: Number(size3) }); } if (param.type.startsWith("bytes")) { @@ -2355,7 +3056,7 @@ function encodeParams(preparedParams) { if (dynamic) staticSize += 32; else - staticSize += size(encoded); + staticSize += size2(encoded); } const staticParams = []; const dynamicParams = []; @@ -2365,7 +3066,7 @@ function encodeParams(preparedParams) { if (dynamic) { staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 })); dynamicParams.push(encoded); - dynamicSize += size(encoded); + dynamicSize += size2(encoded); } else { staticParams.push(encoded); } @@ -2414,7 +3115,7 @@ function encodeArray(value, { length, param }) { } function encodeBytes(value, { param }) { const [, paramSize] = param.type.split("bytes"); - const bytesSize = size(value); + const bytesSize = size2(value); if (!paramSize) { let value_ = value; if (bytesSize % 32 !== 0) @@ -2442,16 +3143,16 @@ function encodeBool(value) { throw new BaseError2(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); return { dynamic: false, encoded: padHex(boolToHex(value)) }; } -function encodeNumber(value, { signed, size: size2 = 256 }) { - if (typeof size2 === "number") { - const max = 2n ** (BigInt(size2) - (signed ? 1n : 0n)) - 1n; +function encodeNumber(value, { signed, size: size3 = 256 }) { + if (typeof size3 === "number") { + const max = 2n ** (BigInt(size3) - (signed ? 1n : 0n)) - 1n; const min = signed ? -max - 1n : 0n; if (value > max || value < min) throw new IntegerOutOfRangeError({ max: max.toString(), min: min.toString(), signed, - size: size2 / 8, + size: size3 / 8, value: value.toString() }); } @@ -2465,7 +3166,7 @@ function encodeNumber(value, { signed, size: size2 = 256 }) { } function encodeString(value) { const hexValue = stringToHex(value); - const partsLength = Math.ceil(size(hexValue) / 32); + const partsLength = Math.ceil(size2(hexValue) / 32); const parts = []; for (let i = 0;i < partsLength; i++) { parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), { @@ -2475,7 +3176,7 @@ function encodeString(value) { return { dynamic: true, encoded: concatHex([ - padHex(numberToHex(size(hexValue), { size: 32 })), + padHex(numberToHex(size2(hexValue), { size: 32 })), ...parts ]) }; @@ -2485,10 +3186,10 @@ function encodeTuple(value, { param }) { const preparedParams = []; for (let i = 0;i < param.components.length; i++) { const param_ = param.components[i]; - const index = Array.isArray(value) ? i : param_.name; + const index2 = Array.isArray(value) ? i : param_.name; const preparedParam = prepareParam({ param: param_, - value: value[index] + value: value[index2] }); preparedParams.push(preparedParam); if (preparedParam.dynamic) @@ -2531,694 +3232,647 @@ var init_encodeAbiParameters = __esm(() => { init_regex2(); }); -// ../viem/src/_esm/utils/hash/toFunctionSelector.js -var toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4); -var init_toFunctionSelector = __esm(() => { - init_slice(); - init_toSignatureHash(); -}); - -// ../viem/src/_esm/utils/abi/getAbiItem.js -function getAbiItem(parameters) { - const { abi, args = [], name } = parameters; - const isSelector = isHex(name, { strict: false }); - const abiItems = abi.filter((abiItem) => { - if (isSelector) { - if (abiItem.type === "function") - return toFunctionSelector(abiItem) === name; - if (abiItem.type === "event") - return toEventSelector(abiItem) === name; - return false; - } - return "name" in abiItem && abiItem.name === name; - }); - if (abiItems.length === 0) - return; - if (abiItems.length === 1) - return abiItems[0]; - let matchedAbiItem; - for (const abiItem of abiItems) { - if (!("inputs" in abiItem)) - continue; - if (!args || args.length === 0) { - if (!abiItem.inputs || abiItem.inputs.length === 0) - return abiItem; - continue; - } - if (!abiItem.inputs) - continue; - if (abiItem.inputs.length === 0) - continue; - if (abiItem.inputs.length !== args.length) - continue; - const matched = args.every((arg, index) => { - const abiParameter = "inputs" in abiItem && abiItem.inputs[index]; - if (!abiParameter) - return false; - return isArgOfType(arg, abiParameter); +// ../viem/src/_esm/utils/abi/decodeAbiParameters.js +function decodeAbiParameters(params, data) { + const bytes = typeof data === "string" ? hexToBytes(data) : data; + const cursor = createCursor(bytes); + if (size2(bytes) === 0 && params.length > 0) + throw new AbiDecodingZeroDataError; + if (size2(data) && size2(data) < 32) + throw new AbiDecodingDataSizeTooSmallError({ + data: typeof data === "string" ? data : bytesToHex(data), + params, + size: size2(data) }); - if (matched) { - if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { - const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args); - if (ambiguousTypes) - throw new AbiItemAmbiguityError({ - abiItem, - type: ambiguousTypes[0] - }, { - abiItem: matchedAbiItem, - type: ambiguousTypes[1] - }); - } - matchedAbiItem = abiItem; - } + let consumed = 0; + const values = []; + for (let i = 0;i < params.length; ++i) { + const param = params[i]; + if (consumed < bytes.length) + cursor.setPosition(consumed); + const [data2, consumed_] = decodeParameter(cursor, param, { + staticPosition: 0 + }); + consumed += consumed_; + values.push(data2); } - if (matchedAbiItem) - return matchedAbiItem; - return abiItems[0]; + return values; } -function isArgOfType(arg, abiParameter) { - const argType = typeof arg; - const abiParameterType = abiParameter.type; - switch (abiParameterType) { - case "address": - return isAddress(arg, { strict: false }); - case "bool": - return argType === "boolean"; - case "function": - return argType === "string"; - case "string": - return argType === "string"; - default: { - if (abiParameterType === "tuple" && "components" in abiParameter) - return Object.values(abiParameter.components).every((component, index) => { - return argType === "object" && isArgOfType(Object.values(arg)[index], component); - }); - if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) - return argType === "number" || argType === "bigint"; - if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) - return argType === "string" || arg instanceof Uint8Array; - if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { - return Array.isArray(arg) && arg.every((x) => isArgOfType(x, { - ...abiParameter, - type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") - })); +function decodeParameter(cursor, param, { staticPosition }) { + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return decodeArray(cursor, { ...param, type }, { length, staticPosition }); + } + if (param.type === "tuple") + return decodeTuple(cursor, param, { staticPosition }); + if (param.type === "address") + return decodeAddress(cursor); + if (param.type === "bool") + return decodeBool(cursor); + if (param.type.startsWith("bytes")) + return decodeBytes(cursor, param, { staticPosition }); + if (param.type.startsWith("uint") || param.type.startsWith("int")) + return decodeNumber(cursor, param); + if (param.type === "string") + return decodeString(cursor, { staticPosition }); + throw new InvalidAbiDecodingTypeError(param.type, { + docsPath: "/docs/contract/decodeAbiParameters" + }); +} +function decodeAddress(cursor) { + const value = cursor.readBytes(32); + return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]; +} +function decodeArray(cursor, param, { length, staticPosition }) { + if (length === null) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + const startOfData = start + sizeOfLength; + cursor.setPosition(start); + const length2 = bytesToNumber(cursor.readBytes(sizeOfLength)); + const dynamicChild = hasDynamicChild(param); + let consumed2 = 0; + const value2 = []; + for (let i = 0;i < length2; ++i) { + cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: startOfData + }); + consumed2 += consumed_; + value2.push(data); + if (consumed_ === 0) { + cursor.assertReadLimit(); + cursor._touch(); } - return false; } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; } -} -function getAmbiguousTypes(sourceParameters, targetParameters, args) { - for (const parameterIndex in sourceParameters) { - const sourceParameter = sourceParameters[parameterIndex]; - const targetParameter = targetParameters[parameterIndex]; - if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) - return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]); - const types = [sourceParameter.type, targetParameter.type]; - const ambiguous = (() => { - if (types.includes("address") && types.includes("bytes20")) - return true; - if (types.includes("address") && types.includes("string")) - return isAddress(args[parameterIndex], { strict: false }); - if (types.includes("address") && types.includes("bytes")) - return isAddress(args[parameterIndex], { strict: false }); - return false; - })(); - if (ambiguous) - return types; + if (hasDynamicChild(param)) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + const value2 = []; + for (let i = 0;i < length; ++i) { + cursor.setPosition(start + i * 32); + const [data] = decodeParameter(cursor, param, { + staticPosition: start + }); + value2.push(data); + } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; } - return; -} -var init_getAbiItem = __esm(() => { - init_abi(); - init_isAddress(); - init_toEventSelector(); - init_toFunctionSelector(); -}); - -// ../viem/src/_esm/accounts/utils/parseAccount.js -function parseAccount(account) { - if (typeof account === "string") - return { address: account, type: "json-rpc" }; - return account; -} - -// ../viem/src/_esm/utils/abi/prepareEncodeFunctionData.js -function prepareEncodeFunctionData(parameters) { - const { abi, args, functionName } = parameters; - let abiItem = abi[0]; - if (functionName) { - const item = getAbiItem({ - abi, - args, - name: functionName + let consumed = 0; + const value = []; + for (let i = 0;i < length; ++i) { + const [data, consumed_] = decodeParameter(cursor, param, { + staticPosition: staticPosition + consumed }); - if (!item) - throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath2 }); - abiItem = item; + consumed += consumed_; + value.push(data); + if (consumed_ === 0) { + cursor.assertReadLimit(); + cursor._touch(); + } } - if (abiItem.type !== "function") - throw new AbiFunctionNotFoundError(undefined, { docsPath: docsPath2 }); - return { - abi: [abiItem], - functionName: toFunctionSelector(formatAbiItem2(abiItem)) - }; + return [value, consumed]; } -var docsPath2 = "/docs/contract/encodeFunctionData"; -var init_prepareEncodeFunctionData = __esm(() => { - init_abi(); - init_toFunctionSelector(); - init_formatAbiItem2(); - init_getAbiItem(); -}); - -// ../viem/src/_esm/utils/abi/encodeFunctionData.js -function encodeFunctionData(parameters) { - const { args } = parameters; - const { abi, functionName } = (() => { - if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x")) - return parameters; - return prepareEncodeFunctionData(parameters); - })(); - const abiItem = abi[0]; - const signature = functionName; - const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : undefined; - return concatHex([signature, data ?? "0x"]); +function decodeBool(cursor) { + return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]; } -var init_encodeFunctionData = __esm(() => { - init_encodeAbiParameters(); - init_prepareEncodeFunctionData(); -}); - -// ../viem/src/_esm/constants/solidity.js -var panicReasons, solidityError, solidityPanic; -var init_solidity = __esm(() => { - panicReasons = { - 1: "An `assert` condition failed.", - 17: "Arithmetic operation resulted in underflow or overflow.", - 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).", - 33: "Attempted to convert to an invalid type.", - 34: "Attempted to access a storage byte array that is incorrectly encoded.", - 49: "Performed `.pop()` on an empty array", - 50: "Array index is out of bounds.", - 65: "Allocated too much memory or created an array which is too large.", - 81: "Attempted to call a zero-initialized variable of internal function type." - }; - solidityError = { - inputs: [ - { - name: "message", - type: "string" - } - ], - name: "Error", - type: "error" - }; - solidityPanic = { - inputs: [ - { - name: "reason", - type: "uint256" - } - ], - name: "Panic", - type: "error" - }; -}); - -// ../viem/src/_esm/errors/cursor.js -var NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError; -var init_cursor = __esm(() => { - init_base(); - NegativeOffsetError = class NegativeOffsetError extends BaseError2 { - constructor({ offset }) { - super(`Offset \`${offset}\` cannot be negative.`, { - name: "NegativeOffsetError" +function decodeBytes(cursor, param, { staticPosition }) { + const [_, size3] = param.type.split("bytes"); + if (!size3) { + const offset = bytesToNumber(cursor.readBytes(32)); + cursor.setPosition(staticPosition + offset); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["0x", 32]; + } + const data = cursor.readBytes(length); + cursor.setPosition(staticPosition + 32); + return [bytesToHex(data), 32]; + } + const value = bytesToHex(cursor.readBytes(Number.parseInt(size3, 10), 32)); + return [value, 32]; +} +function decodeNumber(cursor, param) { + const signed = param.type.startsWith("int"); + const size3 = Number.parseInt(param.type.split("int")[1] || "256", 10); + const value = cursor.readBytes(32); + return [ + size3 > 48 ? bytesToBigInt(value, { signed }) : bytesToNumber(value, { signed }), + 32 + ]; +} +function decodeTuple(cursor, param, { staticPosition }) { + const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name); + const value = hasUnnamedChild ? [] : {}; + let consumed = 0; + if (hasDynamicChild(param)) { + const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); + const start = staticPosition + offset; + for (let i = 0;i < param.components.length; ++i) { + const component = param.components[i]; + cursor.setPosition(start + consumed); + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition: start }); + consumed += consumed_; + value[hasUnnamedChild ? i : component?.name] = data; } - }; - PositionOutOfBoundsError = class PositionOutOfBoundsError extends BaseError2 { - constructor({ length, position }) { - super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); + cursor.setPosition(staticPosition + 32); + return [value, 32]; + } + for (let i = 0;i < param.components.length; ++i) { + const component = param.components[i]; + const [data, consumed_] = decodeParameter(cursor, component, { + staticPosition + }); + value[hasUnnamedChild ? i : component?.name] = data; + consumed += consumed_; + } + return [value, consumed]; +} +function decodeString(cursor, { staticPosition }) { + const offset = bytesToNumber(cursor.readBytes(32)); + const start = staticPosition + offset; + cursor.setPosition(start); + const length = bytesToNumber(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["", 32]; + } + const data = cursor.readBytes(length, 32); + const value = bytesToString(data); + cursor.setPosition(staticPosition + 32); + return [value, 32]; +} +function hasDynamicChild(param) { + const { type } = param; + if (type === "string") + return true; + if (type === "bytes") + return true; + if (type.endsWith("[]")) + return true; + if (type === "tuple") + return param.components?.some(hasDynamicChild); + const arrayComponents = getArrayComponents(param.type); + if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] })) + return true; + return false; +} +var sizeOfLength = 32, sizeOfOffset = 32; +var init_decodeAbiParameters = __esm(() => { + init_abi(); + init_getAddress(); + init_cursor2(); + init_size(); + init_slice(); + init_fromBytes(); + init_toBytes(); + init_toHex(); + init_encodeAbiParameters(); +}); + +// ../viem/src/_esm/utils/hash/hashSignature.js +function hashSignature(sig) { + return hash(sig); +} +var hash = (value) => keccak256(toBytes(value)); +var init_hashSignature = __esm(() => { + init_toBytes(); + init_keccak256(); +}); + +// ../viem/src/_esm/utils/hash/normalizeSignature.js +function normalizeSignature(signature) { + let active = true; + let current = ""; + let level = 0; + let result = ""; + let valid = false; + for (let i = 0;i < signature.length; i++) { + const char = signature[i]; + if (["(", ")", ","].includes(char)) + active = true; + if (char === "(") + level++; + if (char === ")") + level--; + if (!active) + continue; + if (level === 0) { + if (char === " " && ["event", "function", ""].includes(result)) + result = ""; + else { + result += char; + if (char === ")") { + valid = true; + break; + } + } + continue; } - }; - RecursiveReadLimitExceededError = class RecursiveReadLimitExceededError extends BaseError2 { - constructor({ count, limit }) { - super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" }); + if (char === " ") { + if (signature[i - 1] !== "," && current !== "," && current !== ",(") { + current = ""; + active = false; + } + continue; } - }; + result += char; + current += char; + } + if (!valid) + throw new BaseError2("Unable to normalize signature."); + return result; +} +var init_normalizeSignature = __esm(() => { + init_base(); }); -// ../viem/src/_esm/utils/cursor.js -function createCursor(bytes, { recursiveReadLimit = 8192 } = {}) { - const cursor = Object.create(staticCursor); - cursor.bytes = bytes; - cursor.dataView = new DataView(bytes.buffer ?? bytes, bytes.byteOffset, bytes.byteLength); - cursor.positionReadCount = new Map; - cursor.recursiveReadLimit = recursiveReadLimit; - return cursor; +// ../viem/src/_esm/utils/hash/toSignature.js +var toSignature = (def) => { + const def_ = (() => { + if (typeof def === "string") + return def; + return formatAbiItem(def); + })(); + return normalizeSignature(def_); +}; +var init_toSignature = __esm(() => { + init_exports(); + init_normalizeSignature(); +}); + +// ../viem/src/_esm/utils/hash/toSignatureHash.js +function toSignatureHash(fn) { + return hashSignature(toSignature(fn)); } -var staticCursor; -var init_cursor2 = __esm(() => { - init_cursor(); - staticCursor = { - bytes: new Uint8Array, - dataView: new DataView(new ArrayBuffer(0)), - position: 0, - positionReadCount: new Map, - recursiveReadCount: 0, - recursiveReadLimit: Number.POSITIVE_INFINITY, - assertReadLimit() { - if (this.recursiveReadCount >= this.recursiveReadLimit) - throw new RecursiveReadLimitExceededError({ - count: this.recursiveReadCount + 1, - limit: this.recursiveReadLimit - }); - }, - assertPosition(position) { - if (position < 0 || position > this.bytes.length - 1) - throw new PositionOutOfBoundsError({ - length: this.bytes.length, - position - }); - }, - decrementPosition(offset) { - if (offset < 0) - throw new NegativeOffsetError({ offset }); - const position = this.position - offset; - this.assertPosition(position); - this.position = position; - }, - getReadCount(position) { - return this.positionReadCount.get(position || this.position) || 0; - }, - incrementPosition(offset) { - if (offset < 0) - throw new NegativeOffsetError({ offset }); - const position = this.position + offset; - this.assertPosition(position); - this.position = position; - }, - inspectByte(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectBytes(length, position_) { - const position = position_ ?? this.position; - this.assertPosition(position + length - 1); - return this.bytes.subarray(position, position + length); - }, - inspectUint8(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectUint16(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 1); - return this.dataView.getUint16(position); - }, - inspectUint24(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 2); - return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); - }, - inspectUint32(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 3); - return this.dataView.getUint32(position); - }, - pushByte(byte) { - this.assertPosition(this.position); - this.bytes[this.position] = byte; - this.position++; - }, - pushBytes(bytes) { - this.assertPosition(this.position + bytes.length - 1); - this.bytes.set(bytes, this.position); - this.position += bytes.length; - }, - pushUint8(value) { - this.assertPosition(this.position); - this.bytes[this.position] = value; - this.position++; - }, - pushUint16(value) { - this.assertPosition(this.position + 1); - this.dataView.setUint16(this.position, value); - this.position += 2; - }, - pushUint24(value) { - this.assertPosition(this.position + 2); - this.dataView.setUint16(this.position, value >> 8); - this.dataView.setUint8(this.position + 2, value & ~4294967040); - this.position += 3; - }, - pushUint32(value) { - this.assertPosition(this.position + 3); - this.dataView.setUint32(this.position, value); - this.position += 4; - }, - readByte() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectByte(); - this.position++; - return value; - }, - readBytes(length, size2) { - this.assertReadLimit(); - this._touch(); - const value = this.inspectBytes(length); - this.position += size2 ?? length; - return value; - }, - readUint8() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint8(); - this.position += 1; - return value; - }, - readUint16() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint16(); - this.position += 2; - return value; - }, - readUint24() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint24(); - this.position += 3; - return value; - }, - readUint32() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint32(); - this.position += 4; - return value; - }, - get remaining() { - return this.bytes.length - this.position; - }, - setPosition(position) { - const oldPosition = this.position; - this.assertPosition(position); - this.position = position; - return () => this.position = oldPosition; - }, - _touch() { - if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) - return; - const count = this.getReadCount(); - this.positionReadCount.set(this.position, count + 1); - if (count > 0) - this.recursiveReadCount++; - } - }; +var init_toSignatureHash = __esm(() => { + init_hashSignature(); + init_toSignature(); }); -// ../viem/src/_esm/utils/encoding/fromBytes.js -function bytesToBigInt(bytes, opts = {}) { - if (typeof opts.size !== "undefined") - assertSize(bytes, { size: opts.size }); - const hex = bytesToHex(bytes); - return hexToBigInt(hex, opts); -} -function bytesToBool(bytes_, opts = {}) { - let bytes = bytes_; - if (typeof opts.size !== "undefined") { - assertSize(bytes, { size: opts.size }); - bytes = trim(bytes); - } - if (bytes.length > 1 || bytes[0] > 1) - throw new InvalidBytesBooleanError(bytes); - return Boolean(bytes[0]); -} -function bytesToNumber(bytes, opts = {}) { - if (typeof opts.size !== "undefined") - assertSize(bytes, { size: opts.size }); - const hex = bytesToHex(bytes); - return hexToNumber(hex, opts); -} -function bytesToString(bytes_, opts = {}) { - let bytes = bytes_; - if (typeof opts.size !== "undefined") { - assertSize(bytes, { size: opts.size }); - bytes = trim(bytes, { dir: "right" }); - } - return new TextDecoder().decode(bytes); -} -var init_fromBytes = __esm(() => { - init_encoding(); - init_fromHex(); - init_toHex(); +// ../viem/src/_esm/utils/hash/toEventSelector.js +var toEventSelector; +var init_toEventSelector = __esm(() => { + init_toSignatureHash(); + toEventSelector = toSignatureHash; }); -// ../viem/src/_esm/utils/abi/decodeAbiParameters.js -function decodeAbiParameters(params, data) { - const bytes = typeof data === "string" ? hexToBytes(data) : data; - const cursor = createCursor(bytes); - if (size(bytes) === 0 && params.length > 0) - throw new AbiDecodingZeroDataError; - if (size(data) && size(data) < 32) - throw new AbiDecodingDataSizeTooSmallError({ - data: typeof data === "string" ? data : bytesToHex(data), - params, - size: size(data) - }); - let consumed = 0; - const values = []; - for (let i = 0;i < params.length; ++i) { - const param = params[i]; - if (consumed < bytes.length) - cursor.setPosition(consumed); - const [data2, consumed_] = decodeParameter(cursor, param, { - staticPosition: 0 +// ../viem/src/_esm/utils/hash/toFunctionSelector.js +var toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4); +var init_toFunctionSelector = __esm(() => { + init_slice(); + init_toSignatureHash(); +}); + +// ../viem/src/_esm/utils/abi/getAbiItem.js +function getAbiItem(parameters) { + const { abi, args = [], name } = parameters; + const isSelector = isHex(name, { strict: false }); + const abiItems = abi.filter((abiItem) => { + if (isSelector) { + if (abiItem.type === "function") + return toFunctionSelector(abiItem) === name; + if (abiItem.type === "event") + return toEventSelector(abiItem) === name; + return false; + } + return "name" in abiItem && abiItem.name === name; + }); + if (abiItems.length === 0) + return; + if (abiItems.length === 1) + return abiItems[0]; + let matchedAbiItem; + for (const abiItem of abiItems) { + if (!("inputs" in abiItem)) + continue; + if (!args || args.length === 0) { + if (!abiItem.inputs || abiItem.inputs.length === 0) + return abiItem; + continue; + } + if (!abiItem.inputs) + continue; + if (abiItem.inputs.length === 0) + continue; + if (abiItem.inputs.length !== args.length) + continue; + const matched = args.every((arg, index2) => { + const abiParameter = "inputs" in abiItem && abiItem.inputs[index2]; + if (!abiParameter) + return false; + return isArgOfType(arg, abiParameter); }); - consumed += consumed_; - values.push(data2); + if (matched) { + if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { + const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args); + if (ambiguousTypes) + throw new AbiItemAmbiguityError({ + abiItem, + type: ambiguousTypes[0] + }, { + abiItem: matchedAbiItem, + type: ambiguousTypes[1] + }); + } + matchedAbiItem = abiItem; + } } - return values; + if (matchedAbiItem) + return matchedAbiItem; + return abiItems[0]; } -function decodeParameter(cursor, param, { staticPosition }) { - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return decodeArray(cursor, { ...param, type }, { length, staticPosition }); - } - if (param.type === "tuple") - return decodeTuple(cursor, param, { staticPosition }); - if (param.type === "address") - return decodeAddress(cursor); - if (param.type === "bool") - return decodeBool(cursor); - if (param.type.startsWith("bytes")) - return decodeBytes(cursor, param, { staticPosition }); - if (param.type.startsWith("uint") || param.type.startsWith("int")) - return decodeNumber(cursor, param); - if (param.type === "string") - return decodeString(cursor, { staticPosition }); - throw new InvalidAbiDecodingTypeError(param.type, { - docsPath: "/docs/contract/decodeAbiParameters" - }); -} -function decodeAddress(cursor) { - const value = cursor.readBytes(32); - return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32]; -} -function decodeArray(cursor, param, { length, staticPosition }) { - if (length === null) { - const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset; - const startOfData = start + sizeOfLength; - cursor.setPosition(start); - const length2 = bytesToNumber(cursor.readBytes(sizeOfLength)); - const dynamicChild = hasDynamicChild(param); - let consumed2 = 0; - const value2 = []; - for (let i = 0;i < length2; ++i) { - cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); - const [data, consumed_] = decodeParameter(cursor, param, { - staticPosition: startOfData - }); - consumed2 += consumed_; - value2.push(data); - if (consumed_ === 0) { - cursor.assertReadLimit(); - cursor._touch(); +function isArgOfType(arg, abiParameter) { + const argType = typeof arg; + const abiParameterType = abiParameter.type; + switch (abiParameterType) { + case "address": + return isAddress(arg, { strict: false }); + case "bool": + return argType === "boolean"; + case "function": + return argType === "string"; + case "string": + return argType === "string"; + default: { + if (abiParameterType === "tuple" && "components" in abiParameter) + return Object.values(abiParameter.components).every((component, index2) => { + return argType === "object" && isArgOfType(Object.values(arg)[index2], component); + }); + if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) + return argType === "number" || argType === "bigint"; + if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) + return argType === "string" || arg instanceof Uint8Array; + if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { + return Array.isArray(arg) && arg.every((x) => isArgOfType(x, { + ...abiParameter, + type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") + })); } + return false; } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; - } - if (hasDynamicChild(param)) { - const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset; - const value2 = []; - for (let i = 0;i < length; ++i) { - cursor.setPosition(start + i * 32); - const [data] = decodeParameter(cursor, param, { - staticPosition: start - }); - value2.push(data); - } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; - } - let consumed = 0; - const value = []; - for (let i = 0;i < length; ++i) { - const [data, consumed_] = decodeParameter(cursor, param, { - staticPosition: staticPosition + consumed - }); - consumed += consumed_; - value.push(data); - if (consumed_ === 0) { - cursor.assertReadLimit(); - cursor._touch(); - } - } - return [value, consumed]; -} -function decodeBool(cursor) { - return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32]; -} -function decodeBytes(cursor, param, { staticPosition }) { - const [_, size2] = param.type.split("bytes"); - if (!size2) { - const offset = bytesToNumber(cursor.readBytes(32)); - cursor.setPosition(staticPosition + offset); - const length = bytesToNumber(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["0x", 32]; - } - const data = cursor.readBytes(length); - cursor.setPosition(staticPosition + 32); - return [bytesToHex(data), 32]; - } - const value = bytesToHex(cursor.readBytes(Number.parseInt(size2, 10), 32)); - return [value, 32]; -} -function decodeNumber(cursor, param) { - const signed = param.type.startsWith("int"); - const size2 = Number.parseInt(param.type.split("int")[1] || "256", 10); - const value = cursor.readBytes(32); - return [ - size2 > 48 ? bytesToBigInt(value, { signed }) : bytesToNumber(value, { signed }), - 32 - ]; -} -function decodeTuple(cursor, param, { staticPosition }) { - const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name); - const value = hasUnnamedChild ? [] : {}; - let consumed = 0; - if (hasDynamicChild(param)) { - const offset = bytesToNumber(cursor.readBytes(sizeOfOffset)); - const start = staticPosition + offset; - for (let i = 0;i < param.components.length; ++i) { - const component = param.components[i]; - cursor.setPosition(start + consumed); - const [data, consumed_] = decodeParameter(cursor, component, { - staticPosition: start - }); - consumed += consumed_; - value[hasUnnamedChild ? i : component?.name] = data; - } - cursor.setPosition(staticPosition + 32); - return [value, 32]; - } - for (let i = 0;i < param.components.length; ++i) { - const component = param.components[i]; - const [data, consumed_] = decodeParameter(cursor, component, { - staticPosition - }); - value[hasUnnamedChild ? i : component?.name] = data; - consumed += consumed_; } - return [value, consumed]; } -function decodeString(cursor, { staticPosition }) { - const offset = bytesToNumber(cursor.readBytes(32)); - const start = staticPosition + offset; - cursor.setPosition(start); - const length = bytesToNumber(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["", 32]; +function getAmbiguousTypes(sourceParameters, targetParameters, args) { + for (const parameterIndex in sourceParameters) { + const sourceParameter = sourceParameters[parameterIndex]; + const targetParameter = targetParameters[parameterIndex]; + if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) + return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]); + const types = [sourceParameter.type, targetParameter.type]; + const ambiguous = (() => { + if (types.includes("address") && types.includes("bytes20")) + return true; + if (types.includes("address") && types.includes("string")) + return isAddress(args[parameterIndex], { strict: false }); + if (types.includes("address") && types.includes("bytes")) + return isAddress(args[parameterIndex], { strict: false }); + return false; + })(); + if (ambiguous) + return types; } - const data = cursor.readBytes(length, 32); - const value = bytesToString(data); - cursor.setPosition(staticPosition + 32); - return [value, 32]; -} -function hasDynamicChild(param) { - const { type } = param; - if (type === "string") - return true; - if (type === "bytes") - return true; - if (type.endsWith("[]")) - return true; - if (type === "tuple") - return param.components?.some(hasDynamicChild); - const arrayComponents = getArrayComponents(param.type); - if (arrayComponents && hasDynamicChild({ ...param, type: arrayComponents[1] })) - return true; - return false; + return; } -var sizeOfLength = 32, sizeOfOffset = 32; -var init_decodeAbiParameters = __esm(() => { +var init_getAbiItem = __esm(() => { init_abi(); - init_getAddress(); - init_cursor2(); - init_size(); - init_slice(); - init_fromBytes(); - init_toBytes(); - init_toHex(); - init_encodeAbiParameters(); + init_isAddress(); + init_toEventSelector(); + init_toFunctionSelector(); }); -// ../viem/src/_esm/utils/abi/decodeErrorResult.js -function decodeErrorResult(parameters) { - const { abi, data, cause } = parameters; - const signature = slice(data, 0, 4); - if (signature === "0x") - throw new AbiDecodingZeroDataError({ cause }); - const abi_ = [...abi || [], solidityError, solidityPanic]; - const abiItem = abi_.find((x) => x.type === "error" && signature === toFunctionSelector(formatAbiItem2(x))); - if (!abiItem) - throw new AbiErrorSignatureNotFoundError(signature, { - docsPath: "/docs/contract/decodeErrorResult", - cause - }); - return { - abiItem, - args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : undefined, - errorName: abiItem.name - }; +// ../viem/src/_esm/utils/abi/decodeFunctionResult.js +function decodeFunctionResult(parameters) { + const { abi, args, functionName, data } = parameters; + let abiItem = abi[0]; + if (functionName) { + const item = getAbiItem({ abi, args, name: functionName }); + if (!item) + throw new AbiFunctionNotFoundError(functionName, { docsPath }); + abiItem = item; + } + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(undefined, { docsPath }); + if (!abiItem.outputs) + throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath }); + const values = decodeAbiParameters(abiItem.outputs, data); + if (values && values.length > 1) + return values; + if (values && values.length === 1) + return values[0]; + return; } -var init_decodeErrorResult = __esm(() => { - init_solidity(); +var docsPath = "/docs/contract/decodeFunctionResult"; +var init_decodeFunctionResult = __esm(() => { init_abi(); - init_slice(); - init_toFunctionSelector(); init_decodeAbiParameters(); - init_formatAbiItem2(); + init_getAbiItem(); }); -// ../viem/src/_esm/utils/stringify.js -var stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => { - const value2 = typeof value_ === "bigint" ? value_.toString() : value_; - return typeof replacer === "function" ? replacer(key, value2) : value2; -}, space); - -// ../viem/src/_esm/utils/abi/formatAbiItemWithArgs.js +// ../viem/src/_esm/utils/abi/prepareEncodeFunctionData.js +function prepareEncodeFunctionData(parameters) { + const { abi, args, functionName } = parameters; + let abiItem = abi[0]; + if (functionName) { + const item = getAbiItem({ + abi, + args, + name: functionName + }); + if (!item) + throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath2 }); + abiItem = item; + } + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(undefined, { docsPath: docsPath2 }); + return { + abi: [abiItem], + functionName: toFunctionSelector(formatAbiItem2(abiItem)) + }; +} +var docsPath2 = "/docs/contract/encodeFunctionData"; +var init_prepareEncodeFunctionData = __esm(() => { + init_abi(); + init_toFunctionSelector(); + init_formatAbiItem2(); + init_getAbiItem(); +}); + +// ../viem/src/_esm/utils/abi/encodeFunctionData.js +function encodeFunctionData(parameters) { + const { args } = parameters; + const { abi, functionName } = (() => { + if (parameters.abi.length === 1 && parameters.functionName?.startsWith("0x")) + return parameters; + return prepareEncodeFunctionData(parameters); + })(); + const abiItem = abi[0]; + const signature = functionName; + const data = "inputs" in abiItem && abiItem.inputs ? encodeAbiParameters(abiItem.inputs, args ?? []) : undefined; + return concatHex([signature, data ?? "0x"]); +} +var init_encodeFunctionData = __esm(() => { + init_encodeAbiParameters(); + init_prepareEncodeFunctionData(); +}); + +// ../viem/src/_esm/errors/chain.js +var ChainDoesNotSupportContract, ChainMismatchError, ChainNotFoundError, ClientChainNotConfiguredError, InvalidChainIdError; +var init_chain = __esm(() => { + init_base(); + ChainDoesNotSupportContract = class ChainDoesNotSupportContract extends BaseError2 { + constructor({ blockNumber, chain, contract }) { + super(`Chain "${chain.name}" does not support contract "${contract.name}".`, { + metaMessages: [ + "This could be due to any of the following:", + ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [ + `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).` + ] : [ + `- The chain does not have the contract "${contract.name}" configured.` + ] + ], + name: "ChainDoesNotSupportContract" + }); + } + }; + ChainMismatchError = class ChainMismatchError extends BaseError2 { + constructor({ chain, currentChainId }) { + super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} – ${chain.name}).`, { + metaMessages: [ + `Current Chain ID: ${currentChainId}`, + `Expected Chain ID: ${chain.id} – ${chain.name}` + ], + name: "ChainMismatchError" + }); + } + }; + ChainNotFoundError = class ChainNotFoundError extends BaseError2 { + constructor() { + super([ + "No chain was provided to the request.", + "Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient." + ].join(` +`), { + name: "ChainNotFoundError" + }); + } + }; + ClientChainNotConfiguredError = class ClientChainNotConfiguredError extends BaseError2 { + constructor() { + super("No chain was provided to the Client.", { + name: "ClientChainNotConfiguredError" + }); + } + }; + InvalidChainIdError = class InvalidChainIdError extends BaseError2 { + constructor({ chainId }) { + super(typeof chainId === "number" ? `Chain ID "${chainId}" is invalid.` : "Chain ID is invalid.", { name: "InvalidChainIdError" }); + } + }; +}); + +// ../viem/src/_esm/utils/chain/getChainContractAddress.js +function getChainContractAddress({ blockNumber, chain, contract: name }) { + const contract = chain?.contracts?.[name]; + if (!contract) + throw new ChainDoesNotSupportContract({ + chain, + contract: { name } + }); + if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber) + throw new ChainDoesNotSupportContract({ + blockNumber, + chain, + contract: { + name, + blockCreated: contract.blockCreated + } + }); + return contract.address; +} +var init_getChainContractAddress = __esm(() => { + init_chain(); +}); + +// ../viem/src/_esm/constants/solidity.js +var panicReasons, solidityError, solidityPanic; +var init_solidity = __esm(() => { + panicReasons = { + 1: "An `assert` condition failed.", + 17: "Arithmetic operation resulted in underflow or overflow.", + 18: "Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).", + 33: "Attempted to convert to an invalid type.", + 34: "Attempted to access a storage byte array that is incorrectly encoded.", + 49: "Performed `.pop()` on an empty array", + 50: "Array index is out of bounds.", + 65: "Allocated too much memory or created an array which is too large.", + 81: "Attempted to call a zero-initialized variable of internal function type." + }; + solidityError = { + inputs: [ + { + name: "message", + type: "string" + } + ], + name: "Error", + type: "error" + }; + solidityPanic = { + inputs: [ + { + name: "reason", + type: "uint256" + } + ], + name: "Panic", + type: "error" + }; +}); + +// ../viem/src/_esm/utils/abi/decodeErrorResult.js +function decodeErrorResult(parameters) { + const { abi, data, cause } = parameters; + const signature = slice(data, 0, 4); + if (signature === "0x") + throw new AbiDecodingZeroDataError({ cause }); + const abi_ = [...abi || [], solidityError, solidityPanic]; + const abiItem = abi_.find((x) => x.type === "error" && signature === toFunctionSelector(formatAbiItem2(x))); + if (!abiItem) + throw new AbiErrorSignatureNotFoundError(signature, { + docsPath: "/docs/contract/decodeErrorResult", + cause + }); + return { + abiItem, + args: "inputs" in abiItem && abiItem.inputs && abiItem.inputs.length > 0 ? decodeAbiParameters(abiItem.inputs, slice(data, 4)) : undefined, + errorName: abiItem.name + }; +} +var init_decodeErrorResult = __esm(() => { + init_solidity(); + init_abi(); + init_slice(); + init_toFunctionSelector(); + init_decodeAbiParameters(); + init_formatAbiItem2(); +}); + +// ../viem/src/_esm/utils/stringify.js +var stringify = (value, replacer, space) => JSON.stringify(value, (key, value_) => { + const value2 = typeof value_ === "bigint" ? value_.toString() : value_; + return typeof replacer === "function" ? replacer(key, value2) : value2; +}, space); + +// ../viem/src/_esm/utils/abi/formatAbiItemWithArgs.js function formatAbiItemWithArgs({ abiItem, args, includeFunctionName = true, includeName = false }) { if (!("name" in abiItem)) return; @@ -3489,14 +4143,14 @@ var init_transaction = __esm(() => { } }; TransactionNotFoundError = class TransactionNotFoundError extends BaseError2 { - constructor({ blockHash, blockNumber, blockTag, hash: hash2, index }) { + constructor({ blockHash, blockNumber, blockTag, hash: hash2, index: index2 }) { let identifier = "Transaction"; - if (blockTag && index !== undefined) - identifier = `Transaction at block time "${blockTag}" at index "${index}"`; - if (blockHash && index !== undefined) - identifier = `Transaction at block hash "${blockHash}" at index "${index}"`; - if (blockNumber && index !== undefined) - identifier = `Transaction at block number "${blockNumber}" at index "${index}"`; + if (blockTag && index2 !== undefined) + identifier = `Transaction at block time "${blockTag}" at index "${index2}"`; + if (blockHash && index2 !== undefined) + identifier = `Transaction at block hash "${blockHash}" at index "${index2}"`; + if (blockNumber && index2 !== undefined) + identifier = `Transaction at block number "${blockNumber}" at index "${index2}"`; if (hash2) identifier = `Transaction with hash "${hash2}"`; super(`${identifier} could not be found.`, { @@ -3819,57 +4473,185 @@ ${prettyStateOverride(stateOverride)}`; }; }); -// ../viem/src/_esm/errors/request.js -var HttpRequestError, ResponseBodyTooLargeError, RpcRequestError, TimeoutError; -var init_request = __esm(() => { - init_base(); - HttpRequestError = class HttpRequestError extends BaseError2 { - constructor({ body, cause, details, headers, status, url }) { - super("HTTP request failed.", { - cause, - details, - metaMessages: [ - status && `Status: ${status}`, - `URL: ${getUrl(url)}`, - body && `Request body: ${stringify(body)}` - ].filter(Boolean), - name: "HttpRequestError" - }); - Object.defineProperty(this, "body", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "headers", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "url", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.body = body; - this.headers = headers; - this.status = status; - this.url = url; - } +// ../viem/src/_esm/utils/abi/decodeFunctionData.js +function decodeFunctionData(parameters) { + const { abi, data } = parameters; + const signature = slice(data, 0, 4); + const description = abi.find((x) => x.type === "function" && signature === toFunctionSelector(formatAbiItem2(x))); + if (!description) + throw new AbiFunctionSignatureNotFoundError(signature, { + docsPath: "/docs/contract/decodeFunctionData" + }); + return { + functionName: description.name, + args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbiParameters(description.inputs, slice(data, 4)) : undefined }; - ResponseBodyTooLargeError = class ResponseBodyTooLargeError extends BaseError2 { - constructor({ maxSize, size: size2 }) { - super("HTTP response body exceeded the size limit.", { - metaMessages: [`Max: ${maxSize} bytes`, `Received: ${size2} bytes`], - name: "ResponseBodyTooLargeError" +} +var init_decodeFunctionData = __esm(() => { + init_abi(); + init_slice(); + init_toFunctionSelector(); + init_decodeAbiParameters(); + init_formatAbiItem2(); +}); + +// ../viem/src/_esm/utils/abi/encodeErrorResult.js +function encodeErrorResult(parameters) { + const { abi, errorName, args } = parameters; + let abiItem = abi[0]; + if (errorName) { + const item = getAbiItem({ abi, args, name: errorName }); + if (!item) + throw new AbiErrorNotFoundError(errorName, { docsPath: docsPath3 }); + abiItem = item; + } + if (abiItem.type !== "error") + throw new AbiErrorNotFoundError(undefined, { docsPath: docsPath3 }); + const definition = formatAbiItem2(abiItem); + const signature = toFunctionSelector(definition); + let data = "0x"; + if (args && args.length > 0) { + if (!abiItem.inputs) + throw new AbiErrorInputsNotFoundError(abiItem.name, { docsPath: docsPath3 }); + data = encodeAbiParameters(abiItem.inputs, args); + } + return concatHex([signature, data]); +} +var docsPath3 = "/docs/contract/encodeErrorResult"; +var init_encodeErrorResult = __esm(() => { + init_abi(); + init_toFunctionSelector(); + init_encodeAbiParameters(); + init_formatAbiItem2(); + init_getAbiItem(); +}); + +// ../viem/src/_esm/utils/abi/encodeFunctionResult.js +function encodeFunctionResult(parameters) { + const { abi, functionName, result } = parameters; + let abiItem = abi[0]; + if (functionName) { + const item = getAbiItem({ abi, name: functionName }); + if (!item) + throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 }); + abiItem = item; + } + if (abiItem.type !== "function") + throw new AbiFunctionNotFoundError(undefined, { docsPath: docsPath4 }); + if (!abiItem.outputs) + throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath4 }); + const values = (() => { + if (abiItem.outputs.length === 0) + return []; + if (abiItem.outputs.length === 1) + return [result]; + if (Array.isArray(result)) + return result; + throw new InvalidArrayError(result); + })(); + return encodeAbiParameters(abiItem.outputs, values); +} +var docsPath4 = "/docs/contract/encodeFunctionResult"; +var init_encodeFunctionResult = __esm(() => { + init_abi(); + init_encodeAbiParameters(); + init_getAbiItem(); +}); + +// ../viem/src/_esm/utils/ens/localBatchGatewayRequest.js +async function localBatchGatewayRequest(parameters) { + const { data, ccipRequest } = parameters; + const { args: [queries] } = decodeFunctionData({ abi: batchGatewayAbi, data }); + const failures = []; + const responses = []; + await Promise.all(queries.map(async (query, i) => { + try { + responses[i] = query.urls.includes(localBatchGatewayUrl) ? await localBatchGatewayRequest({ data: query.data, ccipRequest }) : await ccipRequest(query); + failures[i] = false; + } catch (err) { + failures[i] = true; + responses[i] = encodeError(err); + } + })); + return encodeFunctionResult({ + abi: batchGatewayAbi, + functionName: "query", + result: [failures, responses] + }); +} +function encodeError(error) { + if (error.name === "HttpRequestError" && error.status) + return encodeErrorResult({ + abi: batchGatewayAbi, + errorName: "HttpError", + args: [error.status, error.shortMessage] + }); + return encodeErrorResult({ + abi: [solidityError], + errorName: "Error", + args: ["shortMessage" in error ? error.shortMessage : error.message] + }); +} +var localBatchGatewayUrl = "x-batch-gateway:true"; +var init_localBatchGatewayRequest = __esm(() => { + init_abis(); + init_solidity(); + init_decodeFunctionData(); + init_encodeErrorResult(); + init_encodeFunctionResult(); +}); + +// ../viem/src/_esm/errors/request.js +var HttpRequestError, ResponseBodyTooLargeError, RpcRequestError, TimeoutError; +var init_request = __esm(() => { + init_base(); + HttpRequestError = class HttpRequestError extends BaseError2 { + constructor({ body, cause, details, headers, status, url }) { + super("HTTP request failed.", { + cause, + details, + metaMessages: [ + status && `Status: ${status}`, + `URL: ${getUrl(url)}`, + body && `Request body: ${stringify(body)}` + ].filter(Boolean), + name: "HttpRequestError" + }); + Object.defineProperty(this, "body", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "headers", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "url", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.body = body; + this.headers = headers; + this.status = status; + this.url = url; + } + }; + ResponseBodyTooLargeError = class ResponseBodyTooLargeError extends BaseError2 { + constructor({ maxSize, size: size3 }) { + super("HTTP response body exceeded the size limit.", { + metaMessages: [`Max: ${maxSize} bytes`, `Received: ${size3} bytes`], + name: "ResponseBodyTooLargeError" }); Object.defineProperty(this, "maxSize", { enumerable: true, @@ -3884,7 +4666,7 @@ var init_request = __esm(() => { value: undefined }); this.maxSize = maxSize; - this.size = size2; + this.size = size3; } }; RpcRequestError = class RpcRequestError extends BaseError2 { @@ -3942,10 +4724,10 @@ var init_rpc = __esm(() => { init_base(); init_request(); RpcError = class RpcError extends BaseError2 { - constructor(cause, { code, docsPath: docsPath3, metaMessages, name, shortMessage }) { + constructor(cause, { code, docsPath: docsPath5, metaMessages, name, shortMessage }) { super(shortMessage, { cause, - docsPath: docsPath3, + docsPath: docsPath5, metaMessages: metaMessages || cause?.metaMessages, name: name || "RpcError" }); @@ -4385,6827 +5167,4703 @@ var init_rpc = __esm(() => { }; }); -// ../viem/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js -function setBigUint64(view, byteOffset, value, isLE2) { - if (typeof view.setBigUint64 === "function") - return view.setBigUint64(byteOffset, value, isLE2); - const _32n2 = BigInt(32); - const _u32_max = BigInt(4294967295); - const wh = Number(value >> _32n2 & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE2 ? 4 : 0; - const l = isLE2 ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE2); - view.setUint32(byteOffset + l, wl, isLE2); +// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/utils.js +function isBytes2(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } -function Chi(a, b, c) { - return a & b ^ ~a & c; +function abytes2(item) { + if (!isBytes2(item)) + throw new Error("Uint8Array expected"); } -function Maj(a, b, c) { - return a & b ^ a & c ^ b & c; +function abool(title, value) { + if (typeof value !== "boolean") + throw new Error(title + " boolean expected, got " + value); } -var HashMD, SHA256_IV, SHA384_IV, SHA512_IV; -var init__md = __esm(() => { - init_utils2(); - HashMD = class HashMD extends Hash { - constructor(blockLen, outputLen, padOffset, isLE2) { - super(); - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE2; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? "0" + hex : hex; +} +function hexToNumber2(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + return hex === "" ? _0n2 : BigInt("0x" + hex); +} +function bytesToHex2(bytes) { + abytes2(bytes); + if (hasHexBuiltin) + return bytes.toHex(); + let hex = ""; + for (let i = 0;i < bytes.length; i++) { + hex += hexes2[bytes[i]]; + } + return hex; +} +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); + return; +} +function hexToBytes2(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + if (hasHexBuiltin) + return Uint8Array.fromHex(hex); + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new Error("hex string expected, got unpadded hex of length " + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0;ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); } - update(data) { - aexists(this); - data = toBytes2(data); - abytes(data); - const { view, buffer, blockLen } = this; - const len = data.length; - for (let pos = 0;pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - if (take === blockLen) { - const dataView = createView(data); - for (;blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - aexists(this); - aoutput(out, this); - this.finished = true; - const { buffer, view, blockLen, isLE: isLE2 } = this; - let { pos } = this; - buffer[pos++] = 128; - clean(this.buffer.subarray(pos)); - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - for (let i = pos;i < blockLen; i++) - buffer[i] = 0; - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - if (len % 4) - throw new Error("_sha2: outputLen should be aligned to 32bit"); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error("_sha2: outputLen bigger than state"); - for (let i = 0;i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE2); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; + array[ai] = n1 * 16 + n2; + } + return array; +} +function bytesToNumberBE(bytes) { + return hexToNumber2(bytesToHex2(bytes)); +} +function bytesToNumberLE(bytes) { + abytes2(bytes); + return hexToNumber2(bytesToHex2(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes2(n.toString(16).padStart(len * 2, "0")); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === "string") { + try { + res = hexToBytes2(hex); + } catch (e) { + throw new Error(title + " must be hex string or Uint8Array, cause: " + e); } - _cloneInto(to) { - to || (to = new this.constructor); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.destroyed = destroyed; - to.finished = finished; - to.length = length; - to.pos = pos; - if (length % blockLen) - to.buffer.set(buffer); - return to; + } else if (isBytes2(hex)) { + res = Uint8Array.from(hex); + } else { + throw new Error(title + " must be hex string or Uint8Array"); + } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) + throw new Error(title + " of length " + expectedLength + " expected, got " + len); + return res; +} +function concatBytes3(...arrays) { + let sum = 0; + for (let i = 0;i < arrays.length; i++) { + const a = arrays[i]; + abytes2(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad2 = 0;i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad2); + pad2 += a.length; + } + return res; +} +function utf8ToBytes2(str) { + if (typeof str !== "string") + throw new Error("string expected"); + return new Uint8Array(new TextEncoder().encode(str)); +} +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +function aInRange(title, n, min, max) { + if (!inRange(n, min, max)) + throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); +} +function bitLen(n) { + let len; + for (len = 0;n > _0n2; n >>= _1n2, len += 1) + ; + return len; +} +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) + throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) + throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") + throw new Error("hmacFn must be a function"); + let v = u8n(hashLen); + let k = u8n(hashLen); + let i = 0; + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b) => hmacFn(k, v, ...b); + const reseed = (seed = u8n(0)) => { + k = h(u8fr([0]), seed); + v = h(); + if (seed.length === 0) + return; + k = h(u8fr([1]), seed); + v = h(); + }; + const gen2 = () => { + if (i++ >= 1000) + throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; } - clone() { - return this._cloneInto(); + return concatBytes3(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = undefined; + while (!(res = pred(gen2()))) + reseed(); + reset(); + return res; + }; + return genUntil; +} +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional) => { + const checkVal = validatorFns[type]; + if (typeof checkVal !== "function") + throw new Error("invalid validator function"); + const val = object[fieldName]; + if (isOptional && val === undefined) + return; + if (!checkVal(val, object)) { + throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val); } }; - SHA256_IV = /* @__PURE__ */ Uint32Array.from([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]); - SHA384_IV = /* @__PURE__ */ Uint32Array.from([ - 3418070365, - 3238371032, - 1654270250, - 914150663, - 2438529370, - 812702999, - 355462360, - 4144912697, - 1731405415, - 4290775857, - 2394180231, - 1750603025, - 3675008525, - 1694076839, - 1203062813, - 3204075428 - ]); - SHA512_IV = /* @__PURE__ */ Uint32Array.from([ - 1779033703, - 4089235720, - 3144134277, - 2227873595, - 1013904242, - 4271175723, - 2773480762, - 1595750129, - 1359893119, - 2917565137, - 2600822924, - 725511199, - 528734635, - 4215389547, - 1541459225, - 327033209 - ]); + for (const [fieldName, type] of Object.entries(validators)) + checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators)) + checkField(fieldName, type, true); + return object; +} +function memoized(fn) { + const map = new WeakMap; + return (arg, ...args) => { + const val = map.get(arg); + if (val !== undefined) + return val; + const computed = fn(arg, ...args); + map.set(arg, computed); + return computed; + }; +} +var _0n2, _1n2, hasHexBuiltin, hexes2, asciis, isPosBig = (n) => typeof n === "bigint" && _0n2 <= n, bitMask = (n) => (_1n2 << BigInt(n)) - _1n2, u8n = (len) => new Uint8Array(len), u8fr = (arr) => Uint8Array.from(arr), validatorFns; +var init_utils3 = __esm(() => { + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + _0n2 = /* @__PURE__ */ BigInt(0); + _1n2 = /* @__PURE__ */ BigInt(1); + hasHexBuiltin = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"; + hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); + asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; + validatorFns = { + bigint: (val) => typeof val === "bigint", + function: (val) => typeof val === "function", + boolean: (val) => typeof val === "boolean", + string: (val) => typeof val === "string", + stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val), + isSafeInteger: (val) => Number.isSafeInteger(val), + array: (val) => Array.isArray(val), + field: (val, object) => object.Fp.isValid(val), + hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) + }; }); -// ../viem/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js -var SHA256_K, SHA256_W, SHA256, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, SHA384, sha256, sha512, sha384; -var init_sha2 = __esm(() => { - init__md(); - init__u64(); - init_utils2(); - SHA256_K = /* @__PURE__ */ Uint32Array.from([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 - ]); - SHA256_W = /* @__PURE__ */ new Uint32Array(64); - SHA256 = class SHA256 extends HashMD { - constructor(outputLen = 32) { - super(64, outputLen, 8, false); - this.A = SHA256_IV[0] | 0; - this.B = SHA256_IV[1] | 0; - this.C = SHA256_IV[2] | 0; - this.D = SHA256_IV[3] | 0; - this.E = SHA256_IV[4] | 0; - this.F = SHA256_IV[5] | 0; - this.G = SHA256_IV[6] | 0; - this.H = SHA256_IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/version.js +var version3 = "0.1.1"; + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/errors.js +function getVersion() { + return version3; +} +var init_errors2 = () => {}; + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Errors.js +function walk2(err, fn) { + if (fn?.(err)) + return err; + if (err && typeof err === "object" && "cause" in err && err.cause) + return walk2(err.cause, fn); + return fn ? null : err; +} +var BaseError3; +var init_Errors = __esm(() => { + init_errors2(); + BaseError3 = class BaseError3 extends Error { + static setStaticOptions(options) { + BaseError3.prototype.docsOrigin = options.docsOrigin; + BaseError3.prototype.showVersion = options.showVersion; + BaseError3.prototype.version = options.version; } - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; + constructor(shortMessage, options = {}) { + const details = (() => { + if (options.cause instanceof BaseError3) { + if (options.cause.details) + return options.cause.details; + if (options.cause.shortMessage) + return options.cause.shortMessage; + } + if (options.cause && "details" in options.cause && typeof options.cause.details === "string") + return options.cause.details; + if (options.cause?.message) + return options.cause.message; + return options.details; + })(); + const docsPath5 = (() => { + if (options.cause instanceof BaseError3) + return options.cause.docsPath || options.docsPath; + return options.docsPath; + })(); + const docsBaseUrl = options.docsOrigin ?? BaseError3.prototype.docsOrigin; + const docs = `${docsBaseUrl}${docsPath5 ?? ""}`; + const showVersion = Boolean(options.version ?? BaseError3.prototype.showVersion); + const version4 = options.version ?? BaseError3.prototype.version; + const message = [ + shortMessage || "An error occurred.", + ...options.metaMessages ? ["", ...options.metaMessages] : [], + ...details || docsPath5 || showVersion ? [ + "", + details ? `Details: ${details}` : undefined, + docsPath5 ? `See: ${docs}` : undefined, + showVersion ? `Version: ${version4}` : undefined + ] : [] + ].filter((x) => typeof x === "string").join(` +`); + super(message, options.cause ? { cause: options.cause } : undefined); + Object.defineProperty(this, "details", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "docs", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "docsOrigin", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "docsPath", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "shortMessage", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "showVersion", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "version", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "BaseError" + }); + this.cause = options.cause; + this.details = details; + this.docs = docs; + this.docsOrigin = docsBaseUrl; + this.docsPath = docsPath5; + this.shortMessage = shortMessage; + this.showVersion = showVersion; + this.version = version4; } - process(view, offset) { - for (let i = 0;i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16;i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; - SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; - } - let { A, B, C, D, E, F, G, H } = this; - for (let i = 0;i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = sigma0 + Maj(A, B, C) | 0; - H = G; - G = F; - F = E; - E = D + T1 | 0; - D = C; - C = B; - B = A; - A = T1 + T2 | 0; - } - A = A + this.A | 0; - B = B + this.B | 0; - C = C + this.C | 0; - D = D + this.D | 0; - E = E + this.E | 0; - F = F + this.F | 0; - G = G + this.G | 0; - H = H + this.H | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - clean(SHA256_W); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - clean(this.buffer); - } - }; - K512 = /* @__PURE__ */ (() => split([ - "0x428a2f98d728ae22", - "0x7137449123ef65cd", - "0xb5c0fbcfec4d3b2f", - "0xe9b5dba58189dbbc", - "0x3956c25bf348b538", - "0x59f111f1b605d019", - "0x923f82a4af194f9b", - "0xab1c5ed5da6d8118", - "0xd807aa98a3030242", - "0x12835b0145706fbe", - "0x243185be4ee4b28c", - "0x550c7dc3d5ffb4e2", - "0x72be5d74f27b896f", - "0x80deb1fe3b1696b1", - "0x9bdc06a725c71235", - "0xc19bf174cf692694", - "0xe49b69c19ef14ad2", - "0xefbe4786384f25e3", - "0x0fc19dc68b8cd5b5", - "0x240ca1cc77ac9c65", - "0x2de92c6f592b0275", - "0x4a7484aa6ea6e483", - "0x5cb0a9dcbd41fbd4", - "0x76f988da831153b5", - "0x983e5152ee66dfab", - "0xa831c66d2db43210", - "0xb00327c898fb213f", - "0xbf597fc7beef0ee4", - "0xc6e00bf33da88fc2", - "0xd5a79147930aa725", - "0x06ca6351e003826f", - "0x142929670a0e6e70", - "0x27b70a8546d22ffc", - "0x2e1b21385c26c926", - "0x4d2c6dfc5ac42aed", - "0x53380d139d95b3df", - "0x650a73548baf63de", - "0x766a0abb3c77b2a8", - "0x81c2c92e47edaee6", - "0x92722c851482353b", - "0xa2bfe8a14cf10364", - "0xa81a664bbc423001", - "0xc24b8b70d0f89791", - "0xc76c51a30654be30", - "0xd192e819d6ef5218", - "0xd69906245565a910", - "0xf40e35855771202a", - "0x106aa07032bbd1b8", - "0x19a4c116b8d2d0c8", - "0x1e376c085141ab53", - "0x2748774cdf8eeb99", - "0x34b0bcb5e19b48a8", - "0x391c0cb3c5c95a63", - "0x4ed8aa4ae3418acb", - "0x5b9cca4f7763e373", - "0x682e6ff3d6b2b8a3", - "0x748f82ee5defb2fc", - "0x78a5636f43172f60", - "0x84c87814a1f0ab72", - "0x8cc702081a6439ec", - "0x90befffa23631e28", - "0xa4506cebde82bde9", - "0xbef9a3f7b2c67915", - "0xc67178f2e372532b", - "0xca273eceea26619c", - "0xd186b8c721c0c207", - "0xeada7dd6cde0eb1e", - "0xf57d4f7fee6ed178", - "0x06f067aa72176fba", - "0x0a637dc5a2c898a6", - "0x113f9804bef90dae", - "0x1b710b35131c471b", - "0x28db77f523047d84", - "0x32caab7b40c72493", - "0x3c9ebe0a15c9bebc", - "0x431d67c49c100d4c", - "0x4cc5d4becb3e42b6", - "0x597f299cfc657e2a", - "0x5fcb6fab3ad6faec", - "0x6c44198c4a475817" - ].map((n) => BigInt(n))))(); - SHA512_Kh = /* @__PURE__ */ (() => K512[0])(); - SHA512_Kl = /* @__PURE__ */ (() => K512[1])(); - SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); - SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); - SHA512 = class SHA512 extends HashMD { - constructor(outputLen = 64) { - super(128, outputLen, 16, false); - this.Ah = SHA512_IV[0] | 0; - this.Al = SHA512_IV[1] | 0; - this.Bh = SHA512_IV[2] | 0; - this.Bl = SHA512_IV[3] | 0; - this.Ch = SHA512_IV[4] | 0; - this.Cl = SHA512_IV[5] | 0; - this.Dh = SHA512_IV[6] | 0; - this.Dl = SHA512_IV[7] | 0; - this.Eh = SHA512_IV[8] | 0; - this.El = SHA512_IV[9] | 0; - this.Fh = SHA512_IV[10] | 0; - this.Fl = SHA512_IV[11] | 0; - this.Gh = SHA512_IV[12] | 0; - this.Gl = SHA512_IV[13] | 0; - this.Hh = SHA512_IV[14] | 0; - this.Hl = SHA512_IV[15] | 0; - } - get() { - const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; - } - set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { - this.Ah = Ah | 0; - this.Al = Al | 0; - this.Bh = Bh | 0; - this.Bl = Bl | 0; - this.Ch = Ch | 0; - this.Cl = Cl | 0; - this.Dh = Dh | 0; - this.Dl = Dl | 0; - this.Eh = Eh | 0; - this.El = El | 0; - this.Fh = Fh | 0; - this.Fl = Fl | 0; - this.Gh = Gh | 0; - this.Gl = Gl | 0; - this.Hh = Hh | 0; - this.Hl = Hl | 0; - } - process(view, offset) { - for (let i = 0;i < 16; i++, offset += 4) { - SHA512_W_H[i] = view.getUint32(offset); - SHA512_W_L[i] = view.getUint32(offset += 4); - } - for (let i = 16;i < 80; i++) { - const W15h = SHA512_W_H[i - 15] | 0; - const W15l = SHA512_W_L[i - 15] | 0; - const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7); - const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7); - const W2h = SHA512_W_H[i - 2] | 0; - const W2l = SHA512_W_L[i - 2] | 0; - const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6); - const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6); - const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); - const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); - SHA512_W_H[i] = SUMh | 0; - SHA512_W_L[i] = SUMl | 0; - } - let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - for (let i = 0;i < 80; i++) { - const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41); - const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41); - const CHIh = Eh & Fh ^ ~Eh & Gh; - const CHIl = El & Fl ^ ~El & Gl; - const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); - const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); - const T1l = T1ll | 0; - const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39); - const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39); - const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; - const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; - Hh = Gh | 0; - Hl = Gl | 0; - Gh = Fh | 0; - Gl = Fl | 0; - Fh = Eh | 0; - Fl = El | 0; - ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); - Dh = Ch | 0; - Dl = Cl | 0; - Ch = Bh | 0; - Cl = Bl | 0; - Bh = Ah | 0; - Bl = Al | 0; - const All = add3L(T1l, sigma0l, MAJl); - Ah = add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } - ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); - ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); - ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); - ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); - ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); - ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); - ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); - ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); - this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); - } - roundClean() { - clean(SHA512_W_H, SHA512_W_L); - } - destroy() { - clean(this.buffer); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + walk(fn) { + return walk2(this, fn); } }; - SHA384 = class SHA384 extends SHA512 { - constructor() { - super(48); - this.Ah = SHA384_IV[0] | 0; - this.Al = SHA384_IV[1] | 0; - this.Bh = SHA384_IV[2] | 0; - this.Bl = SHA384_IV[3] | 0; - this.Ch = SHA384_IV[4] | 0; - this.Cl = SHA384_IV[5] | 0; - this.Dh = SHA384_IV[6] | 0; - this.Dl = SHA384_IV[7] | 0; - this.Eh = SHA384_IV[8] | 0; - this.El = SHA384_IV[9] | 0; - this.Fh = SHA384_IV[10] | 0; - this.Fl = SHA384_IV[11] | 0; - this.Gh = SHA384_IV[12] | 0; - this.Gl = SHA384_IV[13] | 0; - this.Hh = SHA384_IV[14] | 0; - this.Hl = SHA384_IV[15] | 0; + Object.defineProperty(BaseError3, "defaultStaticOptions", { + enumerable: true, + configurable: true, + writable: true, + value: { + docsOrigin: "https://oxlib.sh", + showVersion: false, + version: `ox@${getVersion()}` } - }; - sha256 = /* @__PURE__ */ createHasher(() => new SHA256); - sha512 = /* @__PURE__ */ createHasher(() => new SHA512); - sha384 = /* @__PURE__ */ createHasher(() => new SHA384); + }); + (() => { + BaseError3.setStaticOptions(BaseError3.defaultStaticOptions); + })(); }); -// ../viem/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js -var HMAC, hmac = (hash2, key, message) => new HMAC(hash2, key).update(message).digest(); -var init_hmac = __esm(() => { - init_utils2(); - HMAC = class HMAC extends Hash { - constructor(hash2, _key) { - super(); - this.finished = false; - this.destroyed = false; - ahash(hash2); - const key = toBytes2(_key); - this.iHash = hash2.create(); - if (typeof this.iHash.update !== "function") - throw new Error("Expected instance of class which extends utils.Hash"); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad2 = new Uint8Array(blockLen); - pad2.set(key.length > blockLen ? hash2.create().update(key).digest() : key); - for (let i = 0;i < pad2.length; i++) - pad2[i] ^= 54; - this.iHash.update(pad2); - this.oHash = hash2.create(); - for (let i = 0;i < pad2.length; i++) - pad2[i] ^= 54 ^ 92; - this.oHash.update(pad2); - clean(pad2); - } - update(buf) { - aexists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - aexists(this); - abytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - clone() { - return this._cloneInto(); - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } - }; - hmac.create = (hash2, key) => new HMAC(hash2, key); -}); - -// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/utils.js -function isBytes2(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; -} -function abytes2(item) { - if (!isBytes2(item)) - throw new Error("Uint8Array expected"); -} -function abool(title, value) { - if (typeof value !== "boolean") - throw new Error(title + " boolean expected, got " + value); -} -function numberToHexUnpadded(num) { - const hex = num.toString(16); - return hex.length & 1 ? "0" + hex : hex; +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/bytes.js +function assertSize2(bytes, size_) { + if (size3(bytes) > size_) + throw new SizeOverflowError2({ + givenSize: size3(bytes), + maxSize: size_ + }); } -function hexToNumber2(hex) { - if (typeof hex !== "string") - throw new Error("hex string expected, got " + typeof hex); - return hex === "" ? _0n2 : BigInt("0x" + hex); +function assertStartOffset2(value, start) { + if (typeof start === "number" && start > 0 && start > size3(value) - 1) + throw new SliceOffsetOutOfBoundsError2({ + offset: start, + position: "start", + size: size3(value) + }); } -function bytesToHex2(bytes) { - abytes2(bytes); - if (hasHexBuiltin) - return bytes.toHex(); - let hex = ""; - for (let i = 0;i < bytes.length; i++) { - hex += hexes2[bytes[i]]; +function assertEndOffset2(value, start, end) { + if (typeof start === "number" && typeof end === "number" && size3(value) !== end - start) { + throw new SliceOffsetOutOfBoundsError2({ + offset: end, + position: "end", + size: size3(value) + }); } - return hex; } -function asciiToBase16(ch) { - if (ch >= asciis._0 && ch <= asciis._9) - return ch - asciis._0; - if (ch >= asciis.A && ch <= asciis.F) - return ch - (asciis.A - 10); - if (ch >= asciis.a && ch <= asciis.f) - return ch - (asciis.a - 10); +function charCodeToBase162(char) { + if (char >= charCodeMap2.zero && char <= charCodeMap2.nine) + return char - charCodeMap2.zero; + if (char >= charCodeMap2.A && char <= charCodeMap2.F) + return char - (charCodeMap2.A - 10); + if (char >= charCodeMap2.a && char <= charCodeMap2.f) + return char - (charCodeMap2.a - 10); return; } -function hexToBytes2(hex) { - if (typeof hex !== "string") - throw new Error("hex string expected, got " + typeof hex); - if (hasHexBuiltin) - return Uint8Array.fromHex(hex); - const hl = hex.length; - const al = hl / 2; - if (hl % 2) - throw new Error("hex string expected, got unpadded hex of length " + hl); - const array = new Uint8Array(al); - for (let ai = 0, hi = 0;ai < al; ai++, hi += 2) { - const n1 = asciiToBase16(hex.charCodeAt(hi)); - const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); - if (n1 === undefined || n2 === undefined) { - const char = hex.substring(hi, hi + 2); - throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); - } - array[ai] = n1 * 16 + n2; +function pad2(bytes, options = {}) { + const { dir, size: size4 = 32 } = options; + if (size4 === 0) + return bytes; + if (bytes.length > size4) + throw new SizeExceedsPaddingSizeError2({ + size: bytes.length, + targetSize: size4, + type: "Bytes" + }); + const paddedBytes = new Uint8Array(size4); + for (let i = 0;i < size4; i++) { + const padEnd = dir === "right"; + paddedBytes[padEnd ? i : size4 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; } - return array; -} -function bytesToNumberBE(bytes) { - return hexToNumber2(bytesToHex2(bytes)); + return paddedBytes; } -function bytesToNumberLE(bytes) { - abytes2(bytes); - return hexToNumber2(bytesToHex2(Uint8Array.from(bytes).reverse())); +function trim2(value, options = {}) { + const { dir = "left" } = options; + let data = value; + let sliceLength = 0; + for (let i = 0;i < data.length - 1; i++) { + if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") + sliceLength++; + else + break; + } + data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); + return data; } -function numberToBytesBE(n, len) { - return hexToBytes2(n.toString(16).padStart(len * 2, "0")); +var charCodeMap2; +var init_bytes = __esm(() => { + init_Bytes(); + charCodeMap2 = { + zero: 48, + nine: 57, + A: 65, + F: 70, + a: 97, + f: 102 + }; +}); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/hex.js +function assertSize3(hex, size_) { + if (size4(hex) > size_) + throw new SizeOverflowError3({ + givenSize: size4(hex), + maxSize: size_ + }); } -function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); +function assertStartOffset3(value, start) { + if (typeof start === "number" && start > 0 && start > size4(value) - 1) + throw new SliceOffsetOutOfBoundsError3({ + offset: start, + position: "start", + size: size4(value) + }); } -function ensureBytes(title, hex, expectedLength) { - let res; - if (typeof hex === "string") { - try { - res = hexToBytes2(hex); - } catch (e) { - throw new Error(title + " must be hex string or Uint8Array, cause: " + e); - } - } else if (isBytes2(hex)) { - res = Uint8Array.from(hex); - } else { - throw new Error(title + " must be hex string or Uint8Array"); +function assertEndOffset3(value, start, end) { + if (typeof start === "number" && typeof end === "number" && size4(value) !== end - start) { + throw new SliceOffsetOutOfBoundsError3({ + offset: end, + position: "end", + size: size4(value) + }); } - const len = res.length; - if (typeof expectedLength === "number" && len !== expectedLength) - throw new Error(title + " of length " + expectedLength + " expected, got " + len); - return res; } -function concatBytes3(...arrays) { - let sum = 0; - for (let i = 0;i < arrays.length; i++) { - const a = arrays[i]; - abytes2(a); - sum += a.length; - } - const res = new Uint8Array(sum); - for (let i = 0, pad2 = 0;i < arrays.length; i++) { - const a = arrays[i]; - res.set(a, pad2); - pad2 += a.length; - } - return res; +function pad3(hex_, options = {}) { + const { dir, size: size5 = 32 } = options; + if (size5 === 0) + return hex_; + const hex = hex_.replace("0x", ""); + if (hex.length > size5 * 2) + throw new SizeExceedsPaddingSizeError3({ + size: Math.ceil(hex.length / 2), + targetSize: size5, + type: "Hex" + }); + return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size5 * 2, "0")}`; } -function utf8ToBytes2(str) { - if (typeof str !== "string") - throw new Error("string expected"); - return new Uint8Array(new TextEncoder().encode(str)); +function trim3(value, options = {}) { + const { dir = "left" } = options; + let data = value.replace("0x", ""); + let sliceLength = 0; + for (let i = 0;i < data.length - 1; i++) { + if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") + sliceLength++; + else + break; + } + data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); + if (data === "0") + return "0x"; + if (dir === "right" && data.length % 2 === 1) + return `0x${data}0`; + return `0x${data}`; } -function inRange(n, min, max) { - return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +var init_hex = __esm(() => { + init_Hex(); +}); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Json.js +function stringify2(value, replacer, space) { + return JSON.stringify(value, (key, value2) => { + if (typeof replacer === "function") + return replacer(key, value2); + if (typeof value2 === "bigint") + return value2.toString() + bigIntSuffix; + return value2; + }, space); } -function aInRange(title, n, min, max) { - if (!inRange(n, min, max)) - throw new Error("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); +var bigIntSuffix = "#__bigint"; + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Bytes.js +function assert(value) { + if (value instanceof Uint8Array) + return; + if (!value) + throw new InvalidBytesTypeError(value); + if (typeof value !== "object") + throw new InvalidBytesTypeError(value); + if (!("BYTES_PER_ELEMENT" in value)) + throw new InvalidBytesTypeError(value); + if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== "Uint8Array") + throw new InvalidBytesTypeError(value); } -function bitLen(n) { - let len; - for (len = 0;n > _0n2; n >>= _1n2, len += 1) - ; - return len; +function from2(value) { + if (value instanceof Uint8Array) + return value; + if (typeof value === "string") + return fromHex(value); + return fromArray(value); } -function createHmacDrbg(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== "number" || hashLen < 2) - throw new Error("hashLen must be a number"); - if (typeof qByteLen !== "number" || qByteLen < 2) - throw new Error("qByteLen must be a number"); - if (typeof hmacFn !== "function") - throw new Error("hmacFn must be a function"); - let v = u8n(hashLen); - let k = u8n(hashLen); - let i = 0; - const reset = () => { - v.fill(1); - k.fill(0); - i = 0; - }; - const h = (...b) => hmacFn(k, v, ...b); - const reseed = (seed = u8n(0)) => { - k = h(u8fr([0]), seed); - v = h(); - if (seed.length === 0) - return; - k = h(u8fr([1]), seed); - v = h(); - }; - const gen2 = () => { - if (i++ >= 1000) - throw new Error("drbg: tried 1000 values"); - let len = 0; - const out = []; - while (len < qByteLen) { - v = h(); - const sl = v.slice(); - out.push(sl); - len += v.length; - } - return concatBytes3(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); - let res = undefined; - while (!(res = pred(gen2()))) - reseed(); - reset(); - return res; - }; - return genUntil; +function fromArray(value) { + return value instanceof Uint8Array ? value : new Uint8Array(value); } -function validateObject(object, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== "function") - throw new Error("invalid validator function"); - const val = object[fieldName]; - if (isOptional && val === undefined) - return; - if (!checkVal(val, object)) { - throw new Error("param " + String(fieldName) + " is invalid. Expected " + type + ", got " + val); +function fromHex(value, options = {}) { + const { size: size5 } = options; + let hex = value; + if (size5) { + assertSize3(value, size5); + hex = padRight(value, size5); + } + let hexString = hex.slice(2); + if (hexString.length % 2) + hexString = `0${hexString}`; + const length = hexString.length / 2; + const bytes = new Uint8Array(length); + for (let index2 = 0, j = 0;index2 < length; index2++) { + const nibbleLeft = charCodeToBase162(hexString.charCodeAt(j++)); + const nibbleRight = charCodeToBase162(hexString.charCodeAt(j++)); + if (nibbleLeft === undefined || nibbleRight === undefined) { + throw new BaseError3(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`); } - }; - for (const [fieldName, type] of Object.entries(validators)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object; + bytes[index2] = nibbleLeft << 4 | nibbleRight; + } + return bytes; } -function memoized(fn) { - const map = new WeakMap; - return (arg, ...args) => { - const val = map.get(arg); - if (val !== undefined) - return val; - const computed = fn(arg, ...args); - map.set(arg, computed); - return computed; - }; +function fromString(value, options = {}) { + const { size: size5 } = options; + const bytes = encoder3.encode(value); + if (typeof size5 === "number") { + assertSize2(bytes, size5); + return padRight2(bytes, size5); + } + return bytes; } -var _0n2, _1n2, hasHexBuiltin, hexes2, asciis, isPosBig = (n) => typeof n === "bigint" && _0n2 <= n, bitMask = (n) => (_1n2 << BigInt(n)) - _1n2, u8n = (len) => new Uint8Array(len), u8fr = (arr) => Uint8Array.from(arr), validatorFns; -var init_utils3 = __esm(() => { - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - _0n2 = /* @__PURE__ */ BigInt(0); - _1n2 = /* @__PURE__ */ BigInt(1); - hasHexBuiltin = typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function"; - hexes2 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); - asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; - validatorFns = { - bigint: (val) => typeof val === "bigint", - function: (val) => typeof val === "function", - boolean: (val) => typeof val === "boolean", - string: (val) => typeof val === "string", - stringOrUint8Array: (val) => typeof val === "string" || isBytes2(val), - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object) => object.Fp.isValid(val), - hash: (val) => typeof val === "function" && Number.isSafeInteger(val.outputLen) - }; -}); - -// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/modular.js -function mod(a, b) { - const result = a % b; - return result >= _0n3 ? result : b + result; +function padRight2(value, size5) { + return pad2(value, { dir: "right", size: size5 }); } -function pow2(x, power, modulo) { - let res = x; - while (power-- > _0n3) { - res *= res; - res %= modulo; +function size3(value) { + return value.length; +} +function slice2(value, start, end, options = {}) { + const { strict } = options; + assertStartOffset2(value, start); + const value_ = value.slice(start, end); + if (strict) + assertEndOffset2(value_, start, end); + return value_; +} +function toBigInt2(bytes, options = {}) { + const { size: size5 } = options; + if (typeof size5 !== "undefined") + assertSize2(bytes, size5); + const hex = fromBytes(bytes, options); + return toBigInt(hex, options); +} +function toBoolean(bytes, options = {}) { + const { size: size5 } = options; + let bytes_ = bytes; + if (typeof size5 !== "undefined") { + assertSize2(bytes_, size5); + bytes_ = trimLeft(bytes_); } - return res; + if (bytes_.length > 1 || bytes_[0] > 1) + throw new InvalidBytesBooleanError2(bytes_); + return Boolean(bytes_[0]); } -function invert(number, modulo) { - if (number === _0n3) - throw new Error("invert: expected non-zero number"); - if (modulo <= _0n3) - throw new Error("invert: expected positive modulus, got " + modulo); - let a = mod(number, modulo); - let b = modulo; - let x = _0n3, y = _1n3, u = _1n3, v = _0n3; - while (a !== _0n3) { - const q = b / a; - const r = b % a; - const m = x - u * q; - const n = y - v * q; - b = a, a = r, x = u, y = v, u = m, v = n; +function toNumber2(bytes, options = {}) { + const { size: size5 } = options; + if (typeof size5 !== "undefined") + assertSize2(bytes, size5); + const hex = fromBytes(bytes, options); + return toNumber(hex, options); +} +function toString(bytes, options = {}) { + const { size: size5 } = options; + let bytes_ = bytes; + if (typeof size5 !== "undefined") { + assertSize2(bytes_, size5); + bytes_ = trimRight(bytes_); } - const gcd = b; - if (gcd !== _1n3) - throw new Error("invert: does not exist"); - return mod(x, modulo); + return decoder.decode(bytes_); } -function sqrt3mod4(Fp, n) { - const p1div4 = (Fp.ORDER + _1n3) / _4n; - const root = Fp.pow(n, p1div4); - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; +function trimLeft(value) { + return trim2(value, { dir: "left" }); } -function sqrt5mod8(Fp, n) { - const p5div8 = (Fp.ORDER - _5n) / _8n; - const n2 = Fp.mul(n, _2n2); - const v = Fp.pow(n2, p5div8); - const nv = Fp.mul(n, v); - const i = Fp.mul(Fp.mul(nv, _2n2), v); - const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error("Cannot find square root"); - return root; +function trimRight(value) { + return trim2(value, { dir: "right" }); } -function tonelliShanks(P) { - if (P < BigInt(3)) - throw new Error("sqrt is not defined for small field"); - let Q = P - _1n3; - let S = 0; - while (Q % _2n2 === _0n3) { - Q /= _2n2; - S++; - } - let Z = _2n2; - const _Fp = Field(P); - while (FpLegendre(_Fp, Z) === 1) { - if (Z++ > 1000) - throw new Error("Cannot find square root: probably non-prime P"); +function validate(value) { + try { + assert(value); + return true; + } catch { + return false; } - if (S === 1) - return sqrt3mod4; - let cc = _Fp.pow(Z, Q); - const Q1div2 = (Q + _1n3) / _2n2; - return function tonelliSlow(Fp, n) { - if (Fp.is0(n)) - return n; - if (FpLegendre(Fp, n) !== 1) - throw new Error("Cannot find square root"); - let M = S; - let c = Fp.mul(Fp.ONE, cc); - let t = Fp.pow(n, Q); - let R = Fp.pow(n, Q1div2); - while (!Fp.eql(t, Fp.ONE)) { - if (Fp.is0(t)) - return Fp.ZERO; - let i = 1; - let t_tmp = Fp.sqr(t); - while (!Fp.eql(t_tmp, Fp.ONE)) { - i++; - t_tmp = Fp.sqr(t_tmp); - if (i === M) - throw new Error("Cannot find square root"); - } - const exponent = _1n3 << BigInt(M - i - 1); - const b = Fp.pow(c, exponent); - M = i; - c = Fp.sqr(b); - t = Fp.mul(t, c); - R = Fp.mul(R, b); +} +var decoder, encoder3, InvalidBytesBooleanError2, InvalidBytesTypeError, SizeOverflowError2, SliceOffsetOutOfBoundsError2, SizeExceedsPaddingSizeError2; +var init_Bytes = __esm(() => { + init_Errors(); + init_Hex(); + init_bytes(); + init_hex(); + decoder = /* @__PURE__ */ new TextDecoder; + encoder3 = /* @__PURE__ */ new TextEncoder; + InvalidBytesBooleanError2 = class InvalidBytesBooleanError2 extends BaseError3 { + constructor(bytes) { + super(`Bytes value \`${bytes}\` is not a valid boolean.`, { + metaMessages: [ + "The bytes array must contain a single byte of either a `0` or `1` value." + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Bytes.InvalidBytesBooleanError" + }); + } + }; + InvalidBytesTypeError = class InvalidBytesTypeError extends BaseError3 { + constructor(value) { + super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid Bytes value.`, { + metaMessages: ["Bytes values must be of type `Bytes`."] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Bytes.InvalidBytesTypeError" + }); + } + }; + SizeOverflowError2 = class SizeOverflowError2 extends BaseError3 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Bytes.SizeOverflowError" + }); + } + }; + SliceOffsetOutOfBoundsError2 = class SliceOffsetOutOfBoundsError2 extends BaseError3 { + constructor({ offset, position, size: size5 }) { + super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size5}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Bytes.SliceOffsetOutOfBoundsError" + }); + } + }; + SizeExceedsPaddingSizeError2 = class SizeExceedsPaddingSizeError2 extends BaseError3 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Bytes.SizeExceedsPaddingSizeError" + }); } - return R; }; +}); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Hex.js +function assert2(value, options = {}) { + const { strict = false } = options; + if (!value) + throw new InvalidHexTypeError(value); + if (typeof value !== "string") + throw new InvalidHexTypeError(value); + if (strict) { + if (!/^0x[0-9a-fA-F]*$/.test(value)) + throw new InvalidHexValueError2(value); + } + if (!value.startsWith("0x")) + throw new InvalidHexValueError2(value); } -function FpSqrt(P) { - if (P % _4n === _3n) - return sqrt3mod4; - if (P % _8n === _5n) - return sqrt5mod8; - return tonelliShanks(P); +function concat2(...values) { + return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`; } -function validateField(field) { - const initial = { - ORDER: "bigint", - MASK: "bigint", - BYTES: "isSafeInteger", - BITS: "isSafeInteger" - }; - const opts = FIELD_FIELDS.reduce((map, val) => { - map[val] = "function"; - return map; - }, initial); - return validateObject(field, opts); +function from3(value) { + if (value instanceof Uint8Array) + return fromBytes(value); + if (Array.isArray(value)) + return fromBytes(new Uint8Array(value)); + return value; } -function FpPow(Fp, num, power) { - if (power < _0n3) - throw new Error("invalid exponent, negatives unsupported"); - if (power === _0n3) - return Fp.ONE; - if (power === _1n3) - return num; - let p = Fp.ONE; - let d = num; - while (power > _0n3) { - if (power & _1n3) - p = Fp.mul(p, d); - d = Fp.sqr(d); - power >>= _1n3; +function fromBoolean(value, options = {}) { + const hex = `0x${Number(value)}`; + if (typeof options.size === "number") { + assertSize3(hex, options.size); + return padLeft(hex, options.size); } - return p; + return hex; } -function FpInvertBatch(Fp, nums, passZero = false) { - const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined); - const multipliedAcc = nums.reduce((acc, num, i) => { - if (Fp.is0(num)) - return acc; - inverted[i] = acc; - return Fp.mul(acc, num); - }, Fp.ONE); - const invertedAcc = Fp.inv(multipliedAcc); - nums.reduceRight((acc, num, i) => { - if (Fp.is0(num)) - return acc; - inverted[i] = Fp.mul(acc, inverted[i]); - return Fp.mul(acc, num); - }, invertedAcc); - return inverted; +function fromBytes(value, options = {}) { + let string = ""; + for (let i = 0;i < value.length; i++) + string += hexes3[value[i]]; + const hex = `0x${string}`; + if (typeof options.size === "number") { + assertSize3(hex, options.size); + return padRight(hex, options.size); + } + return hex; } -function FpLegendre(Fp, n) { - const p1mod2 = (Fp.ORDER - _1n3) / _2n2; - const powered = Fp.pow(n, p1mod2); - const yes = Fp.eql(powered, Fp.ONE); - const zero = Fp.eql(powered, Fp.ZERO); - const no = Fp.eql(powered, Fp.neg(Fp.ONE)); - if (!yes && !zero && !no) - throw new Error("invalid Legendre symbol result"); - return yes ? 1 : zero ? 0 : -1; +function fromNumber(value, options = {}) { + const { signed, size: size5 } = options; + const value_ = BigInt(value); + let maxValue; + if (size5) { + if (signed) + maxValue = (1n << BigInt(size5) * 8n - 1n) - 1n; + else + maxValue = 2n ** (BigInt(size5) * 8n) - 1n; + } else if (typeof value === "number") { + maxValue = BigInt(Number.MAX_SAFE_INTEGER); + } + const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0; + if (maxValue && value_ > maxValue || value_ < minValue) { + const suffix = typeof value === "bigint" ? "n" : ""; + throw new IntegerOutOfRangeError2({ + max: maxValue ? `${maxValue}${suffix}` : undefined, + min: `${minValue}${suffix}`, + signed, + size: size5, + value: `${value}${suffix}` + }); + } + const stringValue = (signed && value_ < 0 ? BigInt.asUintN(size5 * 8, BigInt(value_)) : value_).toString(16); + const hex = `0x${stringValue}`; + if (size5) + return padLeft(hex, size5); + return hex; } -function nLength(n, nBitLength) { - if (nBitLength !== undefined) - anumber(nBitLength); - const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; +function fromString2(value, options = {}) { + return fromBytes(encoder4.encode(value), options); } -function Field(ORDER, bitLen2, isLE2 = false, redef = {}) { - if (ORDER <= _0n3) - throw new Error("invalid field: expected ORDER > 0, got " + ORDER); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); - if (BYTES > 2048) - throw new Error("invalid field: expected ORDER of <= 2048 bytes"); - let sqrtP; - const f = Object.freeze({ - ORDER, - isLE: isLE2, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n3, - ONE: _1n3, - create: (num) => mod(num, ORDER), - isValid: (num) => { - if (typeof num !== "bigint") - throw new Error("invalid field element: expected bigint, got " + typeof num); - return _0n3 <= num && num < ORDER; - }, - is0: (num) => num === _0n3, - isOdd: (num) => (num & _1n3) === _1n3, - neg: (num) => mod(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod(num * num, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num, power) => FpPow(f, num, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert(num, ORDER), - sqrt: redef.sqrt || ((n) => { - if (!sqrtP) - sqrtP = FpSqrt(ORDER); - return sqrtP(f, n); - }), - toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), - fromBytes: (bytes) => { - if (bytes.length !== BYTES) - throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); - return isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); - }, - invertBatch: (lst) => FpInvertBatch(f, lst), - cmov: (a, b, c) => c ? b : a - }); - return Object.freeze(f); +function padLeft(value, size5) { + return pad3(value, { dir: "left", size: size5 }); } -function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== "bigint") - throw new Error("field order must be bigint"); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); +function padRight(value, size5) { + return pad3(value, { dir: "right", size: size5 }); } -function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); +function slice3(value, start, end, options = {}) { + const { strict } = options; + assertStartOffset3(value, start); + const value_ = `0x${value.replace("0x", "").slice((start ?? 0) * 2, (end ?? value.length) * 2)}`; + if (strict) + assertEndOffset3(value_, start, end); + return value_; } -function mapHashToField(key, fieldOrder, isLE2 = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - if (len < 16 || len < minLen || len > 1024) - throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); - const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key); - const reduced = mod(num, fieldOrder - _1n3) + _1n3; - return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +function size4(value) { + return Math.ceil((value.length - 2) / 2); } -var _0n3, _1n3, _2n2, _3n, _4n, _5n, _8n, FIELD_FIELDS; -var init_modular = __esm(() => { - init_utils2(); - init_utils3(); - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - _0n3 = BigInt(0); - _1n3 = BigInt(1); - _2n2 = /* @__PURE__ */ BigInt(2); - _3n = /* @__PURE__ */ BigInt(3); - _4n = /* @__PURE__ */ BigInt(4); - _5n = /* @__PURE__ */ BigInt(5); - _8n = /* @__PURE__ */ BigInt(8); - FIELD_FIELDS = [ - "create", - "isValid", - "is0", - "neg", - "inv", - "sqrt", - "sqr", - "eql", - "add", - "sub", - "mul", - "pow", - "div", - "addN", - "subN", - "mulN", - "sqrN" - ]; -}); - -// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/curve.js -function constTimeNegate(condition, item) { - const neg = item.negate(); - return condition ? neg : item; +function trimLeft2(value) { + return trim3(value, { dir: "left" }); } -function validateW(W, bits) { - if (!Number.isSafeInteger(W) || W <= 0 || W > bits) - throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); +function toBigInt(hex, options = {}) { + const { signed } = options; + if (options.size) + assertSize3(hex, options.size); + const value = BigInt(hex); + if (!signed) + return value; + const size5 = (hex.length - 2) / 2; + const max_unsigned = (1n << BigInt(size5) * 8n) - 1n; + const max_signed = max_unsigned >> 1n; + if (value <= max_signed) + return value; + return value - max_unsigned - 1n; } -function calcWOpts(W, scalarBits) { - validateW(W, scalarBits); - const windows = Math.ceil(scalarBits / W) + 1; - const windowSize = 2 ** (W - 1); - const maxNumber = 2 ** W; - const mask = bitMask(W); - const shiftBy = BigInt(W); - return { windows, windowSize, mask, maxNumber, shiftBy }; +function toNumber(hex, options = {}) { + const { signed, size: size5 } = options; + if (!signed && !size5) + return Number(hex); + return Number(toBigInt(hex, options)); } -function calcOffsets(n, window2, wOpts) { - const { windowSize, mask, maxNumber, shiftBy } = wOpts; - let wbits = Number(n & mask); - let nextN = n >> shiftBy; - if (wbits > windowSize) { - wbits -= maxNumber; - nextN += _1n4; +function validate2(value, options = {}) { + const { strict = false } = options; + try { + assert2(value, { strict }); + return true; + } catch { + return false; } - const offsetStart = window2 * windowSize; - const offset = offsetStart + Math.abs(wbits) - 1; - const isZero = wbits === 0; - const isNeg = wbits < 0; - const isNegF = window2 % 2 !== 0; - const offsetF = offsetStart; - return { nextN, offset, isZero, isNeg, isNegF, offsetF }; -} -function validateMSMPoints(points, c) { - if (!Array.isArray(points)) - throw new Error("array expected"); - points.forEach((p, i) => { - if (!(p instanceof c)) - throw new Error("invalid point at index " + i); - }); -} -function validateMSMScalars(scalars, field) { - if (!Array.isArray(scalars)) - throw new Error("array of scalars expected"); - scalars.forEach((s, i) => { - if (!field.isValid(s)) - throw new Error("invalid scalar at index " + i); - }); } -function getW(P) { - return pointWindowSizes.get(P) || 1; +var encoder4, hexes3, IntegerOutOfRangeError2, InvalidHexTypeError, InvalidHexValueError2, SizeOverflowError3, SliceOffsetOutOfBoundsError3, SizeExceedsPaddingSizeError3; +var init_Hex = __esm(() => { + init_Errors(); + init_hex(); + encoder4 = /* @__PURE__ */ new TextEncoder; + hexes3 = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); + IntegerOutOfRangeError2 = class IntegerOutOfRangeError2 extends BaseError3 { + constructor({ max, min, signed, size: size5, value }) { + super(`Number \`${value}\` is not in safe${size5 ? ` ${size5 * 8}-bit` : ""}${signed ? " signed" : " unsigned"} integer range ${max ? `(\`${min}\` to \`${max}\`)` : `(above \`${min}\`)`}`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.IntegerOutOfRangeError" + }); + } + }; + InvalidHexTypeError = class InvalidHexTypeError extends BaseError3 { + constructor(value) { + super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid hex type.`, { + metaMessages: ['Hex types must be represented as `"0x${string}"`.'] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.InvalidHexTypeError" + }); + } + }; + InvalidHexValueError2 = class InvalidHexValueError2 extends BaseError3 { + constructor(value) { + super(`Value \`${value}\` is an invalid hex value.`, { + metaMessages: [ + 'Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).' + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.InvalidHexValueError" + }); + } + }; + SizeOverflowError3 = class SizeOverflowError3 extends BaseError3 { + constructor({ givenSize, maxSize }) { + super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.SizeOverflowError" + }); + } + }; + SliceOffsetOutOfBoundsError3 = class SliceOffsetOutOfBoundsError3 extends BaseError3 { + constructor({ offset, position, size: size5 }) { + super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size5}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.SliceOffsetOutOfBoundsError" + }); + } + }; + SizeExceedsPaddingSizeError3 = class SizeExceedsPaddingSizeError3 extends BaseError3 { + constructor({ size: size5, targetSize, type }) { + super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size5}\`) exceeds padding size (\`${targetSize}\`).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Hex.SizeExceedsPaddingSizeError" + }); + } + }; +}); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Withdrawal.js +function toRpc(withdrawal) { + return { + address: withdrawal.address, + amount: fromNumber(withdrawal.amount), + index: fromNumber(withdrawal.index), + validatorIndex: fromNumber(withdrawal.validatorIndex) + }; } -function wNAF(c, bits) { +var init_Withdrawal = __esm(() => { + init_Hex(); +}); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/BlockOverrides.js +function toRpc2(blockOverrides) { return { - constTimeNegate, - hasPrecomputes(elm) { - return getW(elm) !== 1; + ...typeof blockOverrides.baseFeePerGas === "bigint" && { + baseFeePerGas: fromNumber(blockOverrides.baseFeePerGas) }, - unsafeLadder(elm, n, p = c.ZERO) { - let d = elm; - while (n > _0n4) { - if (n & _1n4) - p = p.add(d); - d = d.double(); - n >>= _1n4; - } - return p; + ...typeof blockOverrides.blobBaseFee === "bigint" && { + blobBaseFee: fromNumber(blockOverrides.blobBaseFee) }, - precomputeWindow(elm, W) { - const { windows, windowSize } = calcWOpts(W, bits); - const points = []; - let p = elm; - let base = p; - for (let window2 = 0;window2 < windows; window2++) { - base = p; - points.push(base); - for (let i = 1;i < windowSize; i++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; + ...typeof blockOverrides.feeRecipient === "string" && { + feeRecipient: blockOverrides.feeRecipient }, - wNAF(W, precomputes, n) { - let p = c.ZERO; - let f = c.BASE; - const wo = calcWOpts(W, bits); - for (let window2 = 0;window2 < wo.windows; window2++) { - const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo); - n = nextN; - if (isZero) { - f = f.add(constTimeNegate(isNegF, precomputes[offsetF])); - } else { - p = p.add(constTimeNegate(isNeg, precomputes[offset])); - } - } - return { p, f }; - }, - wNAFUnsafe(W, precomputes, n, acc = c.ZERO) { - const wo = calcWOpts(W, bits); - for (let window2 = 0;window2 < wo.windows; window2++) { - if (n === _0n4) - break; - const { nextN, offset, isZero, isNeg } = calcOffsets(n, window2, wo); - n = nextN; - if (isZero) { - continue; - } else { - const item = precomputes[offset]; - acc = acc.add(isNeg ? item.negate() : item); - } - } - return acc; + ...typeof blockOverrides.gasLimit === "bigint" && { + gasLimit: fromNumber(blockOverrides.gasLimit) }, - getPrecomputes(W, P, transform) { - let comp = pointPrecomputes.get(P); - if (!comp) { - comp = this.precomputeWindow(P, W); - if (W !== 1) - pointPrecomputes.set(P, transform(comp)); - } - return comp; + ...typeof blockOverrides.number === "bigint" && { + number: fromNumber(blockOverrides.number) }, - wNAFCached(P, n, transform) { - const W = getW(P); - return this.wNAF(W, this.getPrecomputes(W, P, transform), n); + ...typeof blockOverrides.prevRandao === "bigint" && { + prevRandao: fromNumber(blockOverrides.prevRandao) }, - wNAFCachedUnsafe(P, n, transform, prev) { - const W = getW(P); - if (W === 1) - return this.unsafeLadder(P, n, prev); - return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev); + ...typeof blockOverrides.time === "bigint" && { + time: fromNumber(blockOverrides.time) }, - setWindowSize(P, W) { - validateW(W, bits); - pointWindowSizes.set(P, W); - pointPrecomputes.delete(P); + ...blockOverrides.withdrawals && { + withdrawals: blockOverrides.withdrawals.map(toRpc) } }; } -function pippenger(c, fieldN, points, scalars) { - validateMSMPoints(points, c); - validateMSMScalars(scalars, fieldN); - const plength = points.length; - const slength = scalars.length; - if (plength !== slength) - throw new Error("arrays of points and scalars must have equal length"); - const zero = c.ZERO; - const wbits = bitLen(BigInt(plength)); - let windowSize = 1; - if (wbits > 12) - windowSize = wbits - 3; - else if (wbits > 4) - windowSize = wbits - 2; - else if (wbits > 0) - windowSize = 2; - const MASK = bitMask(windowSize); - const buckets = new Array(Number(MASK) + 1).fill(zero); - const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; - let sum = zero; - for (let i = lastBits;i >= 0; i -= windowSize) { - buckets.fill(zero); - for (let j = 0;j < slength; j++) { - const scalar = scalars[j]; - const wbits2 = Number(scalar >> BigInt(i) & MASK); - buckets[wbits2] = buckets[wbits2].add(points[j]); - } - let resI = zero; - for (let j = buckets.length - 1, sumI = zero;j > 0; j--) { - sumI = sumI.add(buckets[j]); - resI = resI.add(sumI); - } - sum = sum.add(resI); - if (i !== 0) - for (let j = 0;j < windowSize; j++) - sum = sum.double(); - } - return sum; +var init_BlockOverrides = __esm(() => { + init_Hex(); + init_Withdrawal(); +}); + +// ../viem/src/_esm/constants/contract.js +var aggregate3Signature = "0x82ad56cb"; + +// ../viem/src/_esm/constants/contracts.js +var deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe", deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe", erc6492SignatureValidatorByteCode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572", multicall3Bytecode = "0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033"; + +// ../viem/src/_esm/utils/abi/encodeDeployData.js +function encodeDeployData(parameters) { + const { abi, args, bytecode } = parameters; + if (!args || args.length === 0) + return bytecode; + const description = abi.find((x) => ("type" in x) && x.type === "constructor"); + if (!description) + throw new AbiConstructorNotFoundError({ docsPath: docsPath5 }); + if (!("inputs" in description)) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); + if (!description.inputs || description.inputs.length === 0) + throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); + const data = encodeAbiParameters(description.inputs, args); + return concatHex([bytecode, data]); } -function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: "bigint", - h: "bigint", - Gx: "field", - Gy: "field" - }, { - nBitLength: "isSafeInteger", - nByteLength: "isSafeInteger" - }); - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER } - }); +var docsPath5 = "/docs/contract/encodeDeployData"; +var init_encodeDeployData = __esm(() => { + init_abi(); + init_encodeAbiParameters(); +}); + +// ../viem/src/_esm/utils/address/isAddressEqual.js +function isAddressEqual(a, b) { + if (!isAddress(a, { strict: false })) + throw new InvalidAddressError({ address: a }); + if (!isAddress(b, { strict: false })) + throw new InvalidAddressError({ address: b }); + return a.toLowerCase() === b.toLowerCase(); } -var _0n4, _1n4, pointPrecomputes, pointWindowSizes; -var init_curve = __esm(() => { - init_modular(); - init_utils3(); - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - _0n4 = BigInt(0); - _1n4 = BigInt(1); - pointPrecomputes = new WeakMap; - pointWindowSizes = new WeakMap; +var init_isAddressEqual = __esm(() => { + init_address(); + init_isAddress(); }); -// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/weierstrass.js -function validateSigVerOpts(opts) { - if (opts.lowS !== undefined) - abool("lowS", opts.lowS); - if (opts.prehash !== undefined) - abool("prehash", opts.prehash); +// ../viem/src/_esm/utils/block/formatBlockParameter.js +function formatBlockParameter(parameters) { + const { blockHash, blockNumber, blockTag, requireCanonical } = parameters; + if (requireCanonical !== undefined && !blockHash) + throw new BaseError2("`requireCanonical` can only be provided when `blockHash` is set."); + if (blockHash) + return requireCanonical ? { blockHash, requireCanonical } : { blockHash }; + if (typeof blockNumber === "bigint") + return numberToHex(blockNumber); + return blockTag ?? "latest"; } -function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: "field", - b: "field" - }, { - allowInfinityPoint: "boolean", - allowedPrivateKeyLengths: "array", - clearCofactor: "function", - fromBytes: "function", - isTorsionFree: "function", - toBytes: "function", - wrapPrivateKey: "boolean" +var init_formatBlockParameter = __esm(() => { + init_base(); + init_toHex(); +}); + +// ../viem/src/_esm/errors/node.js +var ExecutionRevertedError, FeeCapTooHighError, FeeCapTooLowError, NonceTooHighError, NonceTooLowError, NonceMaxValueError, InsufficientFundsError, IntrinsicGasTooHighError, IntrinsicGasTooLowError, TransactionTypeNotSupportedError, TipAboveFeeCapError, UnknownNodeError; +var init_node = __esm(() => { + init_formatGwei(); + init_base(); + ExecutionRevertedError = class ExecutionRevertedError extends BaseError2 { + constructor({ cause, message } = {}) { + const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", ""); + super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { + cause, + name: "ExecutionRevertedError" + }); + } + }; + Object.defineProperty(ExecutionRevertedError, "code", { + enumerable: true, + configurable: true, + writable: true, + value: 3 }); - const { endo, Fp, a } = opts; - if (endo) { - if (!Fp.eql(a, Fp.ZERO)) { - throw new Error("invalid endo: CURVE.a must be 0"); + Object.defineProperty(ExecutionRevertedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /execution reverted|gas required exceeds allowance/ + }); + FeeCapTooHighError = class FeeCapTooHighError extends BaseError2 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei2(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, { + cause, + name: "FeeCapTooHighError" + }); } - if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { - throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function'); + }; + Object.defineProperty(FeeCapTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/ + }); + FeeCapTooLowError = class FeeCapTooLowError extends BaseError2 { + constructor({ cause, maxFeePerGas } = {}) { + super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei2(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, { + cause, + name: "FeeCapTooLowError" + }); } - } - return Object.freeze({ ...opts }); -} -function numToSizedHex(num, size2) { - return bytesToHex2(numberToBytesBE(num, size2)); -} -function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp } = CURVE; - const Fn = Field(CURVE.n, CURVE.nBitLength); - const toBytes3 = CURVE.toBytes || ((_c, point, _isCompressed) => { - const a = point.toAffine(); - return concatBytes3(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }; + Object.defineProperty(FeeCapTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/ }); - const fromBytes = CURVE.fromBytes || ((bytes) => { - const tail = bytes.subarray(1); - const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); - const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); - return { x, y }; - }); - function weierstrassEquation(x) { - const { a, b } = CURVE; - const x2 = Fp.sqr(x); - const x3 = Fp.mul(x2, x); - return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); - } - function isValidXY(x, y) { - const left = Fp.sqr(y); - const right = weierstrassEquation(x); - return Fp.eql(left, right); - } - if (!isValidXY(CURVE.Gx, CURVE.Gy)) - throw new Error("bad curve params: generator point"); - const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2); - const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27)); - if (Fp.is0(Fp.add(_4a3, _27b2))) - throw new Error("bad curve params: a or b"); - function isWithinCurveOrder(num) { - return inRange(num, _1n5, CURVE.n); - } - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; - if (lengths && typeof key !== "bigint") { - if (isBytes2(key)) - key = bytesToHex2(key); - if (typeof key !== "string" || !lengths.includes(key.length)) - throw new Error("invalid private key"); - key = key.padStart(nByteLength * 2, "0"); - } - let num; - try { - num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); - } catch (error) { - throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key); + NonceTooHighError = class NonceTooHighError extends BaseError2 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" }); } - if (wrapPrivateKey) - num = mod(num, N); - aInRange("private key", num, _1n5, N); - return num; - } - function aprjpoint(other) { - if (!(other instanceof Point)) - throw new Error("ProjectivePoint expected"); - } - const toAffineMemo = memoized((p, iz) => { - const { px: x, py: y, pz: z } = p; - if (Fp.eql(z, Fp.ONE)) - return { x, y }; - const is0 = p.is0(); - if (iz == null) - iz = is0 ? Fp.ONE : Fp.inv(z); - const ax = Fp.mul(x, iz); - const ay = Fp.mul(y, iz); - const zz = Fp.mul(z, iz); - if (is0) - return { x: Fp.ZERO, y: Fp.ZERO }; - if (!Fp.eql(zz, Fp.ONE)) - throw new Error("invZ was invalid"); - return { x: ax, y: ay }; + }; + Object.defineProperty(NonceTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too high/ }); - const assertValidMemo = memoized((p) => { - if (p.is0()) { - if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) - return; - throw new Error("bad point: ZERO"); + NonceTooLowError = class NonceTooLowError extends BaseError2 { + constructor({ cause, nonce } = {}) { + super([ + `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`, + "Try increasing the nonce or find the latest nonce with `getTransactionCount`." + ].join(` +`), { cause, name: "NonceTooLowError" }); } - const { x, y } = p.toAffine(); - if (!Fp.isValid(x) || !Fp.isValid(y)) - throw new Error("bad point: x or y not FE"); - if (!isValidXY(x, y)) - throw new Error("bad point: equation left != right"); - if (!p.isTorsionFree()) - throw new Error("bad point: not in prime-order subgroup"); - return true; + }; + Object.defineProperty(NonceTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce too low|transaction already imported|already known/ }); - - class Point { - constructor(px, py, pz) { - if (px == null || !Fp.isValid(px)) - throw new Error("x required"); - if (py == null || !Fp.isValid(py) || Fp.is0(py)) - throw new Error("y required"); - if (pz == null || !Fp.isValid(pz)) - throw new Error("z required"); - this.px = px; - this.py = py; - this.pz = pz; - Object.freeze(this); - } - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp.isValid(x) || !Fp.isValid(y)) - throw new Error("invalid affine point"); - if (p instanceof Point) - throw new Error("projective point not allowed"); - const is0 = (i) => Fp.eql(i, Fp.ZERO); - if (is0(x) && is0(y)) - return Point.ZERO; - return new Point(x, y, Fp.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - static normalizeZ(points) { - const toInv = FpInvertBatch(Fp, points.map((p) => p.pz)); - return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); - } - static fromHex(hex) { - const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex))); - P.assertValidity(); - return P; - } - static fromPrivateKey(privateKey) { - return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + NonceMaxValueError = class NonceMaxValueError extends BaseError2 { + constructor({ cause, nonce } = {}) { + super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" }); } - static msm(points, scalars) { - return pippenger(Point, Fn, points, scalars); + }; + Object.defineProperty(NonceMaxValueError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /nonce has max value/ + }); + InsufficientFundsError = class InsufficientFundsError extends BaseError2 { + constructor({ cause } = {}) { + super([ + "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account." + ].join(` +`), { + cause, + metaMessages: [ + "This error could arise when the account does not have enough funds to:", + " - pay for the total gas fee,", + " - pay for the value to send.", + " ", + "The cost of the transaction is calculated as `gas * gas fee + value`, where:", + " - `gas` is the amount of gas needed for transaction to execute,", + " - `gas fee` is the gas fee,", + " - `value` is the amount of ether to send to the recipient." + ], + name: "InsufficientFundsError" + }); } - _setWindowSize(windowSize) { - wnaf.setWindowSize(this, windowSize); + }; + Object.defineProperty(InsufficientFundsError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /insufficient funds|exceeds transaction sender account balance/ + }); + IntrinsicGasTooHighError = class IntrinsicGasTooHighError extends BaseError2 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, { + cause, + name: "IntrinsicGasTooHighError" + }); } - assertValidity() { - assertValidMemo(this); + }; + Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too high|gas limit reached/ + }); + IntrinsicGasTooLowError = class IntrinsicGasTooLowError extends BaseError2 { + constructor({ cause, gas } = {}) { + super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, { + cause, + name: "IntrinsicGasTooLowError" + }); } - hasEvenY() { - const { y } = this.toAffine(); - if (Fp.isOdd) - return !Fp.isOdd(y); - throw new Error("Field doesn't support isOdd"); + }; + Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /intrinsic gas too low/ + }); + TransactionTypeNotSupportedError = class TransactionTypeNotSupportedError extends BaseError2 { + constructor({ cause }) { + super("The transaction type is not supported for this chain.", { + cause, + name: "TransactionTypeNotSupportedError" + }); } - equals(other) { - aprjpoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); - const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); - return U1 && U2; + }; + Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /transaction type not valid/ + }); + TipAboveFeeCapError = class TipAboveFeeCapError extends BaseError2 { + constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) { + super([ + `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei2(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei2(maxFeePerGas)} gwei` : ""}).` + ].join(` +`), { + cause, + name: "TipAboveFeeCapError" + }); } - negate() { - return new Point(this.px, Fp.neg(this.py), this.pz); + }; + Object.defineProperty(TipAboveFeeCapError, "nodeMessage", { + enumerable: true, + configurable: true, + writable: true, + value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/ + }); + UnknownNodeError = class UnknownNodeError extends BaseError2 { + constructor({ cause }) { + super(`An error occurred while executing: ${cause?.shortMessage}`, { + cause, + name: "UnknownNodeError" + }); } - double() { - const { a, b } = CURVE; - const b3 = Fp.mul(b, _3n2); - const { px: X1, py: Y1, pz: Z1 } = this; - let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp; - let t0 = Fp.mul(X1, X1); - let t1 = Fp.mul(Y1, Y1); - let t2 = Fp.mul(Z1, Z1); - let t3 = Fp.mul(X1, Y1); - t3 = Fp.add(t3, t3); - Z3 = Fp.mul(X1, Z1); - Z3 = Fp.add(Z3, Z3); - X3 = Fp.mul(a, Z3); - Y3 = Fp.mul(b3, t2); - Y3 = Fp.add(X3, Y3); - X3 = Fp.sub(t1, Y3); - Y3 = Fp.add(t1, Y3); - Y3 = Fp.mul(X3, Y3); - X3 = Fp.mul(t3, X3); - Z3 = Fp.mul(b3, Z3); - t2 = Fp.mul(a, t2); - t3 = Fp.sub(t0, t2); - t3 = Fp.mul(a, t3); - t3 = Fp.add(t3, Z3); - Z3 = Fp.add(t0, t0); - t0 = Fp.add(Z3, t0); - t0 = Fp.add(t0, t2); - t0 = Fp.mul(t0, t3); - Y3 = Fp.add(Y3, t0); - t2 = Fp.mul(Y1, Z1); - t2 = Fp.add(t2, t2); - t0 = Fp.mul(t2, t3); - X3 = Fp.sub(X3, t0); - Z3 = Fp.mul(t2, t1); - Z3 = Fp.add(Z3, Z3); - Z3 = Fp.add(Z3, Z3); - return new Point(X3, Y3, Z3); - } - add(other) { - aprjpoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp; - const a = CURVE.a; - const b3 = Fp.mul(CURVE.b, _3n2); - let t0 = Fp.mul(X1, X2); - let t1 = Fp.mul(Y1, Y2); - let t2 = Fp.mul(Z1, Z2); - let t3 = Fp.add(X1, Y1); - let t4 = Fp.add(X2, Y2); - t3 = Fp.mul(t3, t4); - t4 = Fp.add(t0, t1); - t3 = Fp.sub(t3, t4); - t4 = Fp.add(X1, Z1); - let t5 = Fp.add(X2, Z2); - t4 = Fp.mul(t4, t5); - t5 = Fp.add(t0, t2); - t4 = Fp.sub(t4, t5); - t5 = Fp.add(Y1, Z1); - X3 = Fp.add(Y2, Z2); - t5 = Fp.mul(t5, X3); - X3 = Fp.add(t1, t2); - t5 = Fp.sub(t5, X3); - Z3 = Fp.mul(a, t4); - X3 = Fp.mul(b3, t2); - Z3 = Fp.add(X3, Z3); - X3 = Fp.sub(t1, Z3); - Z3 = Fp.add(t1, Z3); - Y3 = Fp.mul(X3, Z3); - t1 = Fp.add(t0, t0); - t1 = Fp.add(t1, t0); - t2 = Fp.mul(a, t2); - t4 = Fp.mul(b3, t4); - t1 = Fp.add(t1, t2); - t2 = Fp.sub(t0, t2); - t2 = Fp.mul(a, t2); - t4 = Fp.add(t4, t2); - t0 = Fp.mul(t1, t4); - Y3 = Fp.add(Y3, t0); - t0 = Fp.mul(t5, t4); - X3 = Fp.mul(t3, X3); - X3 = Fp.sub(X3, t0); - t0 = Fp.mul(t3, t1); - Z3 = Fp.mul(t5, Z3); - Z3 = Fp.add(Z3, t0); - return new Point(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point.ZERO); - } - wNAF(n) { - return wnaf.wNAFCached(this, n, Point.normalizeZ); - } - multiplyUnsafe(sc) { - const { endo: endo2, n: N } = CURVE; - aInRange("scalar", sc, _0n5, N); - const I = Point.ZERO; - if (sc === _0n5) - return I; - if (this.is0() || sc === _1n5) - return this; - if (!endo2 || wnaf.hasPrecomputes(this)) - return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ); - let { k1neg, k1, k2neg, k2 } = endo2.splitScalar(sc); - let k1p = I; - let k2p = I; - let d = this; - while (k1 > _0n5 || k2 > _0n5) { - if (k1 & _1n5) - k1p = k1p.add(d); - if (k2 & _1n5) - k2p = k2p.add(d); - d = d.double(); - k1 >>= _1n5; - k2 >>= _1n5; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - multiply(scalar) { - const { endo: endo2, n: N } = CURVE; - aInRange("scalar", scalar, _1n5, N); - let point, fake; - if (endo2) { - const { k1neg, k1, k2neg, k2 } = endo2.splitScalar(scalar); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } else { - const { p, f } = this.wNAF(scalar); - point = p; - fake = f; - } - return Point.normalizeZ([point, fake])[0]; - } - multiplyAndAddUnsafe(Q, a, b) { - const G = Point.BASE; - const mul = (P, a2) => a2 === _0n5 || a2 === _1n5 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); - const sum = mul(this, a).add(mul(Q, b)); - return sum.is0() ? undefined : sum; - } - toAffine(iz) { - return toAffineMemo(this, iz); - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n5) - return true; - if (isTorsionFree) - return isTorsionFree(Point, this); - throw new Error("isTorsionFree() has not been declared for the elliptic curve"); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n5) - return this; - if (clearCofactor) - return clearCofactor(Point, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - abool("isCompressed", isCompressed); - this.assertValidity(); - return toBytes3(Point, this, isCompressed); - } - toHex(isCompressed = true) { - abool("isCompressed", isCompressed); - return bytesToHex2(this.toRawBytes(isCompressed)); - } - } - Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); - Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); - const { endo, nBitLength } = CURVE; - const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength); - return { - CURVE, - ProjectivePoint: Point, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder }; -} -function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: "hash", - hmac: "function", - randomBytes: "function" - }, { - bits2int: "function", - bits2int_modN: "function", - lowS: "boolean" +}); + +// ../viem/src/_esm/utils/errors/getNodeError.js +function getNodeError(err, args) { + const message = (err.details || "").toLowerCase(); + const executionRevertedError = err instanceof BaseError2 ? err.walk((e) => e?.code === ExecutionRevertedError.code) : err; + if (executionRevertedError instanceof BaseError2) + return new ExecutionRevertedError({ + cause: err, + message: executionRevertedError.details + }); + if (ExecutionRevertedError.nodeMessage.test(message)) + return new ExecutionRevertedError({ + cause: err, + message: err.details + }); + if (FeeCapTooHighError.nodeMessage.test(message)) + return new FeeCapTooHighError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas + }); + if (FeeCapTooLowError.nodeMessage.test(message)) + return new FeeCapTooLowError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas + }); + if (NonceTooHighError.nodeMessage.test(message)) + return new NonceTooHighError({ cause: err, nonce: args?.nonce }); + if (NonceTooLowError.nodeMessage.test(message)) + return new NonceTooLowError({ cause: err, nonce: args?.nonce }); + if (NonceMaxValueError.nodeMessage.test(message)) + return new NonceMaxValueError({ cause: err, nonce: args?.nonce }); + if (InsufficientFundsError.nodeMessage.test(message)) + return new InsufficientFundsError({ cause: err }); + if (IntrinsicGasTooHighError.nodeMessage.test(message)) + return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas }); + if (IntrinsicGasTooLowError.nodeMessage.test(message)) + return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas }); + if (TransactionTypeNotSupportedError.nodeMessage.test(message)) + return new TransactionTypeNotSupportedError({ cause: err }); + if (TipAboveFeeCapError.nodeMessage.test(message)) + return new TipAboveFeeCapError({ + cause: err, + maxFeePerGas: args?.maxFeePerGas, + maxPriorityFeePerGas: args?.maxPriorityFeePerGas + }); + return new UnknownNodeError({ + cause: err }); - return Object.freeze({ lowS: true, ...opts }); } -function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE; - const compressedLen = Fp.BYTES + 1; - const uncompressedLen = 2 * Fp.BYTES + 1; - function modN(a) { - return mod(a, CURVE_ORDER); - } - function invN(a) { - return invert(a, CURVE_ORDER); - } - const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ - ...CURVE, - toBytes(_c, point, isCompressed) { - const a = point.toAffine(); - const x = Fp.toBytes(a.x); - const cat = concatBytes3; - abool("isCompressed", isCompressed); - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); - } else { - return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y)); - } - }, - fromBytes(bytes) { - const len = bytes.length; - const head = bytes[0]; - const tail = bytes.subarray(1); - if (len === compressedLen && (head === 2 || head === 3)) { - const x = bytesToNumberBE(tail); - if (!inRange(x, _1n5, Fp.ORDER)) - throw new Error("Point is not on curve"); - const y2 = weierstrassEquation(x); - let y; - try { - y = Fp.sqrt(y2); - } catch (sqrtError) { - const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; - throw new Error("Point is not on curve" + suffix); - } - const isYOdd = (y & _1n5) === _1n5; - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp.neg(y); - return { x, y }; - } else if (len === uncompressedLen && head === 4) { - const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); - const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); - return { x, y }; - } else { - const cl = compressedLen; - const ul = uncompressedLen; - throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len); - } - } +var init_getNodeError = __esm(() => { + init_base(); + init_node(); +}); + +// ../viem/src/_esm/utils/errors/getCallError.js +function getCallError(err, { docsPath: docsPath6, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new CallExecutionError(cause, { + docsPath: docsPath6, + ...args }); - function isBiggerThanHalfOrder(number) { - const HALF = CURVE_ORDER >> _1n5; - return number > HALF; - } - function normalizeS(s) { - return isBiggerThanHalfOrder(s) ? modN(-s) : s; - } - const slcNum = (b, from2, to) => bytesToNumberBE(b.slice(from2, to)); +} +var init_getCallError = __esm(() => { + init_contract(); + init_node(); + init_getNodeError(); +}); - class Signature { - constructor(r, s, recovery) { - aInRange("r", r, _1n5, CURVE_ORDER); - aInRange("s", s, _1n5, CURVE_ORDER); - this.r = r; - this.s = s; - if (recovery != null) - this.recovery = recovery; - Object.freeze(this); - } - static fromCompact(hex) { - const l = nByteLength; - hex = ensureBytes("compactSignature", hex, l * 2); - return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); - } - static fromDER(hex) { - const { r, s } = DER.toSig(ensureBytes("DER", hex)); - return new Signature(r, s); - } - assertValidity() {} - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r, s, recovery: rec } = this; - const h = bits2int_modN(ensureBytes("msgHash", msgHash)); - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error("recovery id invalid"); - const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; - if (radj >= Fp.ORDER) - throw new Error("recovery id 2 or 3 invalid"); - const prefix = (rec & 1) === 0 ? "02" : "03"; - const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES)); - const ir = invN(radj); - const u1 = modN(-h * ir); - const u2 = modN(s * ir); - const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); - if (!Q) - throw new Error("point at infinify"); - Q.assertValidity(); - return Q; - } - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; - } - toDERRawBytes() { - return hexToBytes2(this.toDERHex()); - } - toDERHex() { - return DER.hexFromSig(this); - } - toCompactRawBytes() { - return hexToBytes2(this.toCompactHex()); - } - toCompactHex() { - const l = nByteLength; - return numToSizedHex(this.r, l) + numToSizedHex(this.s, l); - } - } - const utils = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } catch (error) { - return false; - } - }, - normPrivateKeyToScalar, - randomPrivateKey: () => { - const length = getMinHashLength(CURVE.n); - return mapHashToField(CURVE.randomBytes(length), CURVE.n); - }, - precompute(windowSize = 8, point = Point.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); - return point; - } - }; - function getPublicKey(privateKey, isCompressed = true) { - return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - function isProbPub(item) { - if (typeof item === "bigint") - return false; - if (item instanceof Point) - return true; - const arr = ensureBytes("key", item); - const len = arr.length; - const fpl = Fp.BYTES; - const compLen = fpl + 1; - const uncompLen = 2 * fpl + 1; - if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) { - return; - } else { - return len === compLen || len === uncompLen; +// ../viem/src/_esm/utils/formatters/extract.js +function extract(value_, { format: format2 }) { + if (!format2) + return {}; + const value = {}; + function extract_(formatted2) { + const keys = Object.keys(formatted2); + for (const key of keys) { + if (key in value_) + value[key] = value_[key]; + if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key])) + extract_(formatted2[key]); } } - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA) === true) - throw new Error("first arg must be private key"); - if (isProbPub(publicB) === false) - throw new Error("second arg must be public key"); - const b = Point.fromHex(publicB); - return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); - } - const bits2int = CURVE.bits2int || function(bytes) { - if (bytes.length > 8192) - throw new Error("input is too large"); - const num = bytesToNumberBE(bytes); - const delta = bytes.length * 8 - nBitLength; - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE.bits2int_modN || function(bytes) { - return modN(bits2int(bytes)); + const formatted = format2(value_ || {}); + extract_(formatted); + return value; +} + +// ../viem/src/_esm/utils/formatters/formatter.js +function defineFormatter(type, format2) { + return ({ exclude, format: overrides }) => { + return { + exclude, + format: (args, action) => { + const formatted = format2(args, action); + if (exclude) { + for (const key of exclude) { + delete formatted[key]; + } + } + return { + ...formatted, + ...overrides(args, action) + }; + }, + type + }; }; - const ORDER_MASK = bitMask(nBitLength); - function int2octets(num) { - aInRange("num < 2^" + nBitLength, num, _0n5, ORDER_MASK); - return numberToBytesBE(num, nByteLength); +} + +// ../viem/src/_esm/utils/formatters/transactionRequest.js +function formatTransactionRequest(request, _) { + const rpcRequest = {}; + if (typeof request.authorizationList !== "undefined") + rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList); + if (typeof request.accessList !== "undefined") + rpcRequest.accessList = request.accessList; + if (typeof request.blobVersionedHashes !== "undefined") + rpcRequest.blobVersionedHashes = request.blobVersionedHashes; + if (typeof request.blobs !== "undefined") { + if (typeof request.blobs[0] !== "string") + rpcRequest.blobs = request.blobs.map((x) => bytesToHex(x)); + else + rpcRequest.blobs = request.blobs; } - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (["recovered", "canonical"].some((k) => (k in opts))) - throw new Error("sign() legacy options not supported"); - const { hash: hash2, randomBytes: randomBytes2 } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; - if (lowS == null) - lowS = true; - msgHash = ensureBytes("msgHash", msgHash); - validateSigVerOpts(opts); - if (prehash) - msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); - const h1int = bits2int_modN(msgHash); - const d = normPrivateKeyToScalar(privateKey); - const seedArgs = [int2octets(d), int2octets(h1int)]; - if (ent != null && ent !== false) { - const e = ent === true ? randomBytes2(Fp.BYTES) : ent; - seedArgs.push(ensureBytes("extraEntropy", e)); - } - const seed = concatBytes3(...seedArgs); - const m = h1int; - function k2sig(kBytes) { - const k = bits2int(kBytes); - if (!isWithinCurveOrder(k)) - return; - const ik = invN(k); - const q = Point.BASE.multiply(k).toAffine(); - const r = modN(q.x); - if (r === _0n5) - return; - const s = modN(ik * modN(m + r * d)); - if (s === _0n5) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n5); - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = normalizeS(s); - recovery ^= 1; + if (typeof request.data !== "undefined") + rpcRequest.data = request.data; + if (request.account) + rpcRequest.from = request.account.address; + if (typeof request.from !== "undefined") + rpcRequest.from = request.from; + if (typeof request.gas !== "undefined") + rpcRequest.gas = numberToHex(request.gas); + if (typeof request.gasPrice !== "undefined") + rpcRequest.gasPrice = numberToHex(request.gasPrice); + if (typeof request.maxFeePerBlobGas !== "undefined") + rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas); + if (typeof request.maxFeePerGas !== "undefined") + rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas); + if (typeof request.maxPriorityFeePerGas !== "undefined") + rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas); + if (typeof request.nonce !== "undefined") + rpcRequest.nonce = numberToHex(request.nonce); + if (typeof request.to !== "undefined") + rpcRequest.to = request.to; + if (typeof request.type !== "undefined") + rpcRequest.type = rpcTransactionType[request.type]; + if (typeof request.value !== "undefined") + rpcRequest.value = numberToHex(request.value); + return rpcRequest; +} +function formatAuthorizationList(authorizationList) { + return authorizationList.map((authorization) => ({ + address: authorization.address, + r: authorization.r ? numberToHex(BigInt(authorization.r)) : authorization.r, + s: authorization.s ? numberToHex(BigInt(authorization.s)) : authorization.s, + chainId: numberToHex(authorization.chainId), + nonce: numberToHex(authorization.nonce), + ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {}, + ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {} + })); +} +var rpcTransactionType; +var init_transactionRequest = __esm(() => { + init_toHex(); + rpcTransactionType = { + legacy: "0x0", + eip2930: "0x1", + eip1559: "0x2", + eip4844: "0x3", + eip7702: "0x4" + }; +}); + +// ../viem/src/_esm/utils/promise/withResolvers.js +function withResolvers() { + let resolve = () => { + return; + }; + let reject = () => { + return; + }; + const promise = new Promise((resolve_, reject_) => { + resolve = resolve_; + reject = reject_; + }); + return { promise, resolve, reject }; +} + +// ../viem/src/_esm/utils/promise/createBatchScheduler.js +function createBatchScheduler({ fn, id, shouldSplitBatch, wait = 0, sort }) { + const exec = async () => { + const scheduler = getScheduler(); + flush(); + const args = scheduler.map(({ args: args2 }) => args2); + if (args.length === 0) + return; + fn(args).then((data) => { + if (sort && Array.isArray(data)) + data.sort(sort); + for (let i = 0;i < scheduler.length; i++) { + const { resolve } = scheduler[i]; + resolve?.([data[i], data]); } - return new Signature(r, normS, recovery); - } - return { seed, k2sig }; - } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); - const C = CURVE; - const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); - return drbg(seed, k2sig); - } - Point.BASE._setWindowSize(8); - function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { - const sg = signature; - msgHash = ensureBytes("msgHash", msgHash); - publicKey = ensureBytes("publicKey", publicKey); - const { lowS, prehash, format: format2 } = opts; - validateSigVerOpts(opts); - if ("strict" in opts) - throw new Error("options.strict was renamed to lowS"); - if (format2 !== undefined && format2 !== "compact" && format2 !== "der") - throw new Error("format must be compact or der"); - const isHex2 = typeof sg === "string" || isBytes2(sg); - const isObj = !isHex2 && !format2 && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint"; - if (!isHex2 && !isObj) - throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); - let _sig = undefined; - let P; - try { - if (isObj) - _sig = new Signature(sg.r, sg.s); - if (isHex2) { - try { - if (format2 !== "compact") - _sig = Signature.fromDER(sg); - } catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; - } - if (!_sig && format2 !== "der") - _sig = Signature.fromCompact(sg); + }).catch((err) => { + for (let i = 0;i < scheduler.length; i++) { + const { reject } = scheduler[i]; + reject?.(err); } - P = Point.fromHex(publicKey); - } catch (error) { - return false; - } - if (!_sig) - return false; - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r, s } = _sig; - const h = bits2int_modN(msgHash); - const is = invN(s); - const u1 = modN(h * is); - const u2 = modN(r * is); - const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); - if (!R) - return false; - const v = modN(R.x); - return v === r; - } - return { - CURVE, - getPublicKey, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point, - Signature, - utils + }); }; -} -function SWUFpSqrtRatio(Fp, Z) { - const q = Fp.ORDER; - let l = _0n5; - for (let o = q - _1n5;o % _2n3 === _0n5; o /= _2n3) - l += _1n5; - const c1 = l; - const _2n_pow_c1_1 = _2n3 << c1 - _1n5 - _1n5; - const _2n_pow_c1 = _2n_pow_c1_1 * _2n3; - const c2 = (q - _1n5) / _2n_pow_c1; - const c3 = (c2 - _1n5) / _2n3; - const c4 = _2n_pow_c1 - _1n5; - const c5 = _2n_pow_c1_1; - const c6 = Fp.pow(Z, c2); - const c7 = Fp.pow(Z, (c2 + _1n5) / _2n3); - let sqrtRatio = (u, v) => { - let tv1 = c6; - let tv2 = Fp.pow(v, c4); - let tv3 = Fp.sqr(tv2); - tv3 = Fp.mul(tv3, v); - let tv5 = Fp.mul(u, tv3); - tv5 = Fp.pow(tv5, c3); - tv5 = Fp.mul(tv5, tv2); - tv2 = Fp.mul(tv5, v); - tv3 = Fp.mul(tv5, u); - let tv4 = Fp.mul(tv3, tv2); - tv5 = Fp.pow(tv4, c5); - let isQR = Fp.eql(tv5, Fp.ONE); - tv2 = Fp.mul(tv3, c7); - tv5 = Fp.mul(tv4, tv1); - tv3 = Fp.cmov(tv2, tv3, isQR); - tv4 = Fp.cmov(tv5, tv4, isQR); - for (let i = c1;i > _1n5; i--) { - let tv52 = i - _2n3; - tv52 = _2n3 << tv52 - _1n5; - let tvv5 = Fp.pow(tv4, tv52); - const e1 = Fp.eql(tvv5, Fp.ONE); - tv2 = Fp.mul(tv3, tv1); - tv1 = Fp.mul(tv1, tv1); - tvv5 = Fp.mul(tv4, tv1); - tv3 = Fp.cmov(tv2, tv3, e1); - tv4 = Fp.cmov(tvv5, tv4, e1); + const flush = () => schedulerCache.delete(id); + const getBatchedArgs = () => getScheduler().map(({ args }) => args); + const getScheduler = () => schedulerCache.get(id) || []; + const setScheduler = (item) => schedulerCache.set(id, [...getScheduler(), item]); + return { + flush, + async schedule(args) { + const { promise, resolve, reject } = withResolvers(); + const split2 = shouldSplitBatch?.([...getBatchedArgs(), args]); + if (split2) + exec(); + const hasActiveScheduler = getScheduler().length > 0; + if (hasActiveScheduler) { + setScheduler({ args, resolve, reject }); + return promise; + } + setScheduler({ args, resolve, reject }); + setTimeout(exec, wait); + return promise; } - return { isValid: isQR, value: tv3 }; }; - if (Fp.ORDER % _4n2 === _3n2) { - const c12 = (Fp.ORDER - _3n2) / _4n2; - const c22 = Fp.sqrt(Fp.neg(Z)); - sqrtRatio = (u, v) => { - let tv1 = Fp.sqr(v); - const tv2 = Fp.mul(u, v); - tv1 = Fp.mul(tv1, tv2); - let y1 = Fp.pow(tv1, c12); - y1 = Fp.mul(y1, tv2); - const y2 = Fp.mul(y1, c22); - const tv3 = Fp.mul(Fp.sqr(y1), v); - const isQR = Fp.eql(tv3, u); - let y = Fp.cmov(y2, y1, isQR); - return { isValid: isQR, value: y }; - }; - } - return sqrtRatio; } -function mapToCurveSimpleSWU(Fp, opts) { - validateField(Fp); - if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) - throw new Error("mapToCurveSimpleSWU: invalid opts"); - const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); - if (!Fp.isOdd) - throw new Error("Fp.isOdd is not implemented!"); - return (u) => { - let tv1, tv2, tv3, tv4, tv5, tv6, x, y; - tv1 = Fp.sqr(u); - tv1 = Fp.mul(tv1, opts.Z); - tv2 = Fp.sqr(tv1); - tv2 = Fp.add(tv2, tv1); - tv3 = Fp.add(tv2, Fp.ONE); - tv3 = Fp.mul(tv3, opts.B); - tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); - tv4 = Fp.mul(tv4, opts.A); - tv2 = Fp.sqr(tv3); - tv6 = Fp.sqr(tv4); - tv5 = Fp.mul(tv6, opts.A); - tv2 = Fp.add(tv2, tv5); - tv2 = Fp.mul(tv2, tv3); - tv6 = Fp.mul(tv6, tv4); - tv5 = Fp.mul(tv6, opts.B); - tv2 = Fp.add(tv2, tv5); - x = Fp.mul(tv1, tv3); - const { isValid, value } = sqrtRatio(tv2, tv6); - y = Fp.mul(tv1, u); - y = Fp.mul(y, value); - x = Fp.cmov(x, tv3, isValid); - y = Fp.cmov(y, value, isValid); - const e1 = Fp.isOdd(u) === Fp.isOdd(y); - y = Fp.cmov(Fp.neg(y), y, e1); - const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0]; - x = Fp.mul(x, tv4_inv); - return { x, y }; - }; -} -var DERErr, DER, _0n5, _1n5, _2n3, _3n2, _4n2; -var init_weierstrass = __esm(() => { - init_curve(); - init_modular(); - init_utils3(); - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - DERErr = class DERErr extends Error { - constructor(m = "") { - super(m); - } - }; - DER = { - Err: DERErr, - _tlv: { - encode: (tag, data) => { - const { Err: E } = DER; - if (tag < 0 || tag > 256) - throw new E("tlv.encode: wrong tag"); - if (data.length & 1) - throw new E("tlv.encode: unpadded data"); - const dataLen = data.length / 2; - const len = numberToHexUnpadded(dataLen); - if (len.length / 2 & 128) - throw new E("tlv.encode: long form length too big"); - const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; - const t = numberToHexUnpadded(tag); - return t + lenLen + len + data; - }, - decode(tag, data) { - const { Err: E } = DER; - let pos = 0; - if (tag < 0 || tag > 256) - throw new E("tlv.encode: wrong tag"); - if (data.length < 2 || data[pos++] !== tag) - throw new E("tlv.decode: wrong tlv"); - const first = data[pos++]; - const isLong = !!(first & 128); - let length = 0; - if (!isLong) - length = first; - else { - const lenLen = first & 127; - if (!lenLen) - throw new E("tlv.decode(long): indefinite length not supported"); - if (lenLen > 4) - throw new E("tlv.decode(long): byte length is too big"); - const lengthBytes = data.subarray(pos, pos + lenLen); - if (lengthBytes.length !== lenLen) - throw new E("tlv.decode: length bytes not complete"); - if (lengthBytes[0] === 0) - throw new E("tlv.decode(long): zero leftmost byte"); - for (const b of lengthBytes) - length = length << 8 | b; - pos += lenLen; - if (length < 128) - throw new E("tlv.decode(long): not minimal encoding"); - } - const v = data.subarray(pos, pos + length); - if (v.length !== length) - throw new E("tlv.decode: wrong value length"); - return { v, l: data.subarray(pos + length) }; - } - }, - _int: { - encode(num) { - const { Err: E } = DER; - if (num < _0n5) - throw new E("integer: negative integers are not allowed"); - let hex = numberToHexUnpadded(num); - if (Number.parseInt(hex[0], 16) & 8) - hex = "00" + hex; - if (hex.length & 1) - throw new E("unexpected DER parsing assertion: unpadded hex"); - return hex; - }, - decode(data) { - const { Err: E } = DER; - if (data[0] & 128) - throw new E("invalid signature integer: negative"); - if (data[0] === 0 && !(data[1] & 128)) - throw new E("invalid signature integer: unnecessary leading zero"); - return bytesToNumberBE(data); - } - }, - toSig(hex) { - const { Err: E, _int: int, _tlv: tlv } = DER; - const data = ensureBytes("signature", hex); - const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); - if (seqLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); - const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); - if (sLeftBytes.length) - throw new E("invalid signature: left bytes after parsing"); - return { r: int.decode(rBytes), s: int.decode(sBytes) }; - }, - hexFromSig(sig) { - const { _tlv: tlv, _int: int } = DER; - const rs = tlv.encode(2, int.encode(sig.r)); - const ss = tlv.encode(2, int.encode(sig.s)); - const seq = rs + ss; - return tlv.encode(48, seq); - } - }; - _0n5 = BigInt(0); - _1n5 = BigInt(1); - _2n3 = BigInt(2); - _3n2 = BigInt(3); - _4n2 = BigInt(4); -}); - -// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/_shortw_utils.js -function getHash(hash2) { - return { - hash: hash2, - hmac: (key, ...msgs) => hmac(hash2, key, concatBytes(...msgs)), - randomBytes - }; -} -function createCurve(curveDef, defHash) { - const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); - return { ...create(defHash), create }; -} -var init__shortw_utils = __esm(() => { - init_hmac(); - init_utils2(); - init_weierstrass(); - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +var schedulerCache; +var init_createBatchScheduler = __esm(() => { + schedulerCache = /* @__PURE__ */ new Map; }); -// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/hash-to-curve.js -function i2osp(value, length) { - anum(value); - anum(length); - if (value < 0 || value >= 1 << 8 * length) - throw new Error("invalid I2OSP input: " + value); - const res = Array.from({ length }).fill(0); - for (let i = length - 1;i >= 0; i--) { - res[i] = value & 255; - value >>>= 8; - } - return new Uint8Array(res); +// ../viem/src/_esm/utils/stateOverride.js +function serializeStateMapping(stateMapping) { + if (!stateMapping || stateMapping.length === 0) + return; + return stateMapping.reduce((acc, { slot, value }) => { + if (slot.length !== 66) + throw new InvalidBytesLengthError({ + size: slot.length, + targetSize: 66, + type: "hex" + }); + if (value.length !== 66) + throw new InvalidBytesLengthError({ + size: value.length, + targetSize: 66, + type: "hex" + }); + acc[slot] = value; + return acc; + }, {}); } -function strxor(a, b) { - const arr = new Uint8Array(a.length); - for (let i = 0;i < a.length; i++) { - arr[i] = a[i] ^ b[i]; +function serializeAccountStateOverride(parameters) { + const { balance, nonce, state, stateDiff, code } = parameters; + const rpcAccountStateOverride = {}; + if (code !== undefined) + rpcAccountStateOverride.code = code; + if (balance !== undefined) + rpcAccountStateOverride.balance = numberToHex(balance); + if (nonce !== undefined) + rpcAccountStateOverride.nonce = numberToHex(nonce); + if (state !== undefined) + rpcAccountStateOverride.state = serializeStateMapping(state); + if (stateDiff !== undefined) { + if (rpcAccountStateOverride.state) + throw new StateAssignmentConflictError; + rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff); } - return arr; -} -function anum(item) { - if (!Number.isSafeInteger(item)) - throw new Error("number expected"); + return rpcAccountStateOverride; } -function expand_message_xmd(msg, DST, lenInBytes, H) { - abytes2(msg); - abytes2(DST); - anum(lenInBytes); - if (DST.length > 255) - DST = H(concatBytes3(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST)); - const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; - const ell = Math.ceil(lenInBytes / b_in_bytes); - if (lenInBytes > 65535 || ell > 255) - throw new Error("expand_message_xmd: invalid lenInBytes"); - const DST_prime = concatBytes3(DST, i2osp(DST.length, 1)); - const Z_pad = i2osp(0, r_in_bytes); - const l_i_b_str = i2osp(lenInBytes, 2); - const b = new Array(ell); - const b_0 = H(concatBytes3(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); - b[0] = H(concatBytes3(b_0, i2osp(1, 1), DST_prime)); - for (let i = 1;i <= ell; i++) { - const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; - b[i] = H(concatBytes3(...args)); +function serializeStateOverride(parameters) { + if (!parameters) + return; + const rpcStateOverride = {}; + for (const { address, ...accountState } of parameters) { + if (!isAddress(address, { strict: false })) + throw new InvalidAddressError({ address }); + if (rpcStateOverride[address]) + throw new AccountStateConflictError({ address }); + rpcStateOverride[address] = serializeAccountStateOverride(accountState); } - const pseudo_random_bytes = concatBytes3(...b); - return pseudo_random_bytes.slice(0, lenInBytes); + return rpcStateOverride; } -function expand_message_xof(msg, DST, lenInBytes, k, H) { - abytes2(msg); - abytes2(DST); - anum(lenInBytes); - if (DST.length > 255) { - const dkLen = Math.ceil(2 * k / 8); - DST = H.create({ dkLen }).update(utf8ToBytes2("H2C-OVERSIZE-DST-")).update(DST).digest(); - } - if (lenInBytes > 65535 || DST.length > 255) - throw new Error("expand_message_xof: invalid lenInBytes"); - return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); +var init_stateOverride2 = __esm(() => { + init_address(); + init_data(); + init_stateOverride(); + init_isAddress(); + init_toHex(); +}); + +// ../viem/src/_esm/constants/number.js +var maxInt8, maxInt16, maxInt24, maxInt32, maxInt40, maxInt48, maxInt56, maxInt64, maxInt72, maxInt80, maxInt88, maxInt96, maxInt104, maxInt112, maxInt120, maxInt128, maxInt136, maxInt144, maxInt152, maxInt160, maxInt168, maxInt176, maxInt184, maxInt192, maxInt200, maxInt208, maxInt216, maxInt224, maxInt232, maxInt240, maxInt248, maxInt256, minInt8, minInt16, minInt24, minInt32, minInt40, minInt48, minInt56, minInt64, minInt72, minInt80, minInt88, minInt96, minInt104, minInt112, minInt120, minInt128, minInt136, minInt144, minInt152, minInt160, minInt168, minInt176, minInt184, minInt192, minInt200, minInt208, minInt216, minInt224, minInt232, minInt240, minInt248, minInt256, maxUint8, maxUint16, maxUint24, maxUint32, maxUint40, maxUint48, maxUint56, maxUint64, maxUint72, maxUint80, maxUint88, maxUint96, maxUint104, maxUint112, maxUint120, maxUint128, maxUint136, maxUint144, maxUint152, maxUint160, maxUint168, maxUint176, maxUint184, maxUint192, maxUint200, maxUint208, maxUint216, maxUint224, maxUint232, maxUint240, maxUint248, maxUint256; +var init_number = __esm(() => { + maxInt8 = 2n ** (8n - 1n) - 1n; + maxInt16 = 2n ** (16n - 1n) - 1n; + maxInt24 = 2n ** (24n - 1n) - 1n; + maxInt32 = 2n ** (32n - 1n) - 1n; + maxInt40 = 2n ** (40n - 1n) - 1n; + maxInt48 = 2n ** (48n - 1n) - 1n; + maxInt56 = 2n ** (56n - 1n) - 1n; + maxInt64 = 2n ** (64n - 1n) - 1n; + maxInt72 = 2n ** (72n - 1n) - 1n; + maxInt80 = 2n ** (80n - 1n) - 1n; + maxInt88 = 2n ** (88n - 1n) - 1n; + maxInt96 = 2n ** (96n - 1n) - 1n; + maxInt104 = 2n ** (104n - 1n) - 1n; + maxInt112 = 2n ** (112n - 1n) - 1n; + maxInt120 = 2n ** (120n - 1n) - 1n; + maxInt128 = 2n ** (128n - 1n) - 1n; + maxInt136 = 2n ** (136n - 1n) - 1n; + maxInt144 = 2n ** (144n - 1n) - 1n; + maxInt152 = 2n ** (152n - 1n) - 1n; + maxInt160 = 2n ** (160n - 1n) - 1n; + maxInt168 = 2n ** (168n - 1n) - 1n; + maxInt176 = 2n ** (176n - 1n) - 1n; + maxInt184 = 2n ** (184n - 1n) - 1n; + maxInt192 = 2n ** (192n - 1n) - 1n; + maxInt200 = 2n ** (200n - 1n) - 1n; + maxInt208 = 2n ** (208n - 1n) - 1n; + maxInt216 = 2n ** (216n - 1n) - 1n; + maxInt224 = 2n ** (224n - 1n) - 1n; + maxInt232 = 2n ** (232n - 1n) - 1n; + maxInt240 = 2n ** (240n - 1n) - 1n; + maxInt248 = 2n ** (248n - 1n) - 1n; + maxInt256 = 2n ** (256n - 1n) - 1n; + minInt8 = -(2n ** (8n - 1n)); + minInt16 = -(2n ** (16n - 1n)); + minInt24 = -(2n ** (24n - 1n)); + minInt32 = -(2n ** (32n - 1n)); + minInt40 = -(2n ** (40n - 1n)); + minInt48 = -(2n ** (48n - 1n)); + minInt56 = -(2n ** (56n - 1n)); + minInt64 = -(2n ** (64n - 1n)); + minInt72 = -(2n ** (72n - 1n)); + minInt80 = -(2n ** (80n - 1n)); + minInt88 = -(2n ** (88n - 1n)); + minInt96 = -(2n ** (96n - 1n)); + minInt104 = -(2n ** (104n - 1n)); + minInt112 = -(2n ** (112n - 1n)); + minInt120 = -(2n ** (120n - 1n)); + minInt128 = -(2n ** (128n - 1n)); + minInt136 = -(2n ** (136n - 1n)); + minInt144 = -(2n ** (144n - 1n)); + minInt152 = -(2n ** (152n - 1n)); + minInt160 = -(2n ** (160n - 1n)); + minInt168 = -(2n ** (168n - 1n)); + minInt176 = -(2n ** (176n - 1n)); + minInt184 = -(2n ** (184n - 1n)); + minInt192 = -(2n ** (192n - 1n)); + minInt200 = -(2n ** (200n - 1n)); + minInt208 = -(2n ** (208n - 1n)); + minInt216 = -(2n ** (216n - 1n)); + minInt224 = -(2n ** (224n - 1n)); + minInt232 = -(2n ** (232n - 1n)); + minInt240 = -(2n ** (240n - 1n)); + minInt248 = -(2n ** (248n - 1n)); + minInt256 = -(2n ** (256n - 1n)); + maxUint8 = 2n ** 8n - 1n; + maxUint16 = 2n ** 16n - 1n; + maxUint24 = 2n ** 24n - 1n; + maxUint32 = 2n ** 32n - 1n; + maxUint40 = 2n ** 40n - 1n; + maxUint48 = 2n ** 48n - 1n; + maxUint56 = 2n ** 56n - 1n; + maxUint64 = 2n ** 64n - 1n; + maxUint72 = 2n ** 72n - 1n; + maxUint80 = 2n ** 80n - 1n; + maxUint88 = 2n ** 88n - 1n; + maxUint96 = 2n ** 96n - 1n; + maxUint104 = 2n ** 104n - 1n; + maxUint112 = 2n ** 112n - 1n; + maxUint120 = 2n ** 120n - 1n; + maxUint128 = 2n ** 128n - 1n; + maxUint136 = 2n ** 136n - 1n; + maxUint144 = 2n ** 144n - 1n; + maxUint152 = 2n ** 152n - 1n; + maxUint160 = 2n ** 160n - 1n; + maxUint168 = 2n ** 168n - 1n; + maxUint176 = 2n ** 176n - 1n; + maxUint184 = 2n ** 184n - 1n; + maxUint192 = 2n ** 192n - 1n; + maxUint200 = 2n ** 200n - 1n; + maxUint208 = 2n ** 208n - 1n; + maxUint216 = 2n ** 216n - 1n; + maxUint224 = 2n ** 224n - 1n; + maxUint232 = 2n ** 232n - 1n; + maxUint240 = 2n ** 240n - 1n; + maxUint248 = 2n ** 248n - 1n; + maxUint256 = 2n ** 256n - 1n; +}); + +// ../viem/src/_esm/utils/transaction/assertRequest.js +function assertRequest(args) { + const { account: account_, maxFeePerGas, maxPriorityFeePerGas, to } = args; + const account = account_ ? parseAccount(account_) : undefined; + if (account && !isAddress(account.address)) + throw new InvalidAddressError({ address: account.address }); + if (to && !isAddress(to)) + throw new InvalidAddressError({ address: to }); + if (maxFeePerGas && maxFeePerGas > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas }); + if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) + throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); } -function hash_to_field(msg, count, options) { - validateObject(options, { - DST: "stringOrUint8Array", - p: "bigint", - m: "isSafeInteger", - k: "isSafeInteger", - hash: "hash" - }); - const { p, k, m, hash: hash2, expand, DST: _DST } = options; - abytes2(msg); - anum(count); - const DST = typeof _DST === "string" ? utf8ToBytes2(_DST) : _DST; - const log2p = p.toString(2).length; - const L = Math.ceil((log2p + k) / 8); - const len_in_bytes = count * m * L; - let prb; - if (expand === "xmd") { - prb = expand_message_xmd(msg, DST, len_in_bytes, hash2); - } else if (expand === "xof") { - prb = expand_message_xof(msg, DST, len_in_bytes, k, hash2); - } else if (expand === "_internal_pass") { - prb = msg; - } else { - throw new Error('expand must be "xmd" or "xof"'); - } - const u = new Array(count); - for (let i = 0;i < count; i++) { - const e = new Array(m); - for (let j = 0;j < m; j++) { - const elm_offset = L * (j + i * m); - const tv = prb.subarray(elm_offset, elm_offset + L); - e[j] = mod(os2ip(tv), p); +var init_assertRequest = __esm(() => { + init_number(); + init_address(); + init_node(); + init_isAddress(); +}); + +// ../viem/src/_esm/errors/ccip.js +var OffchainLookupError, OffchainLookupResponseMalformedError, OffchainLookupSenderMismatchError; +var init_ccip = __esm(() => { + init_base(); + OffchainLookupError = class OffchainLookupError extends BaseError2 { + constructor({ callbackSelector, cause, data, extraData, sender, urls }) { + super(cause.shortMessage || "An error occurred while fetching for an offchain result.", { + cause, + metaMessages: [ + ...cause.metaMessages || [], + cause.metaMessages?.length ? "" : [], + "Offchain Gateway Call:", + urls && [ + " Gateway URL(s):", + ...urls.map((url) => ` ${getUrl(url)}`) + ], + ` Sender: ${sender}`, + ` Data: ${data}`, + ` Callback selector: ${callbackSelector}`, + ` Extra data: ${extraData}` + ].flat(), + name: "OffchainLookupError" + }); } - u[i] = e; - } - return u; -} -function isogenyMap(field, map) { - const coeff = map.map((i) => Array.from(i).reverse()); - return (x, y) => { - const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); - const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true); - x = field.mul(xn, xd_inv); - y = field.mul(y, field.mul(yn, yd_inv)); - return { x, y }; }; -} -function createHasher2(Point, mapToCurve, defaults) { - if (typeof mapToCurve !== "function") - throw new Error("mapToCurve() must be defined"); - function map(num) { - return Point.fromAffine(mapToCurve(num)); - } - function clear(initial) { - const P = initial.clearCofactor(); - if (P.equals(Point.ZERO)) - return Point.ZERO; - P.assertValidity(); - return P; - } - return { - defaults, - hashToCurve(msg, options) { - const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options }); - const u0 = map(u[0]); - const u1 = map(u[1]); - return clear(u0.add(u1)); - }, - encodeToCurve(msg, options) { - const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options }); - return clear(map(u[0])); - }, - mapToCurve(scalars) { - if (!Array.isArray(scalars)) - throw new Error("expected array of bigints"); - for (const i of scalars) - if (typeof i !== "bigint") - throw new Error("expected array of bigints"); - return clear(map(scalars)); + OffchainLookupResponseMalformedError = class OffchainLookupResponseMalformedError extends BaseError2 { + constructor({ result, url }) { + super("Offchain gateway response is malformed. Response data must be a hex value.", { + metaMessages: [ + `Gateway URL: ${getUrl(url)}`, + `Response: ${stringify(result)}` + ], + name: "OffchainLookupResponseMalformedError" + }); + } + }; + OffchainLookupSenderMismatchError = class OffchainLookupSenderMismatchError extends BaseError2 { + constructor({ sender, to }) { + super("Reverted sender address does not match target contract address (`to`).", { + metaMessages: [ + `Contract address: ${to}`, + `OffchainLookup sender address: ${sender}` + ], + name: "OffchainLookupSenderMismatchError" + }); } }; -} -var os2ip; -var init_hash_to_curve = __esm(() => { - init_modular(); - init_utils3(); - os2ip = bytesToNumberBE; -}); - -// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/secp256k1.js -var exports_secp256k1 = {}; -__export(exports_secp256k1, { - secp256k1_hasher: () => secp256k1_hasher, - secp256k1: () => secp256k1, - schnorr: () => schnorr, - hashToCurve: () => hashToCurve, - encodeToCurve: () => encodeToCurve }); -function sqrtMod(y) { - const P = secp256k1P; - const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = y * y * y % P; - const b3 = b2 * b2 * y % P; - const b6 = pow2(b3, _3n3, P) * b3 % P; - const b9 = pow2(b6, _3n3, P) * b3 % P; - const b11 = pow2(b9, _2n4, P) * b2 % P; - const b22 = pow2(b11, _11n, P) * b11 % P; - const b44 = pow2(b22, _22n, P) * b22 % P; - const b88 = pow2(b44, _44n, P) * b44 % P; - const b176 = pow2(b88, _88n, P) * b88 % P; - const b220 = pow2(b176, _44n, P) * b44 % P; - const b223 = pow2(b220, _3n3, P) * b3 % P; - const t1 = pow2(b223, _23n, P) * b22 % P; - const t2 = pow2(t1, _6n, P) * b2 % P; - const root = pow2(t2, _2n4, P); - if (!Fpk1.eql(Fpk1.sqr(root), y)) - throw new Error("Cannot find square root"); - return root; -} -function taggedHash(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === undefined) { - const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); - tagP = concatBytes3(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } - return sha256(concatBytes3(tagP, ...messages)); -} -function schnorrGetExtPubKey(priv) { - let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); - let p = Point.fromPrivateKey(d_); - const scalar = p.hasEvenY() ? d_ : modN(-d_); - return { scalar, bytes: pointToBytes(p) }; -} -function lift_x(x) { - aInRange("x", x, _1n6, secp256k1P); - const xx = modP(x * x); - const c = modP(xx * x + BigInt(7)); - let y = sqrtMod(c); - if (y % _2n4 !== _0n6) - y = modP(-y); - const p = new Point(x, y, _1n6); - p.assertValidity(); - return p; -} -function challenge(...args) { - return modN(num(taggedHash("BIP0340/challenge", ...args))); -} -function schnorrGetPublicKey(privateKey) { - return schnorrGetExtPubKey(privateKey).bytes; -} -function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { - const m = ensureBytes("message", message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); - const a = ensureBytes("auxRand", auxRand, 32); - const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a))); - const rand = taggedHash("BIP0340/nonce", t, px, m); - const k_ = modN(num(rand)); - if (k_ === _0n6) - throw new Error("sign failed: k is zero"); - const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); - const e = challenge(rx, px, m); - const sig = new Uint8Array(64); - sig.set(rx, 0); - sig.set(numTo32b(modN(k + e * d)), 32); - if (!schnorrVerify(sig, m, px)) - throw new Error("sign: Invalid signature produced"); - return sig; -} -function schnorrVerify(signature, message, publicKey) { - const sig = ensureBytes("signature", signature, 64); - const m = ensureBytes("message", message); - const pub = ensureBytes("publicKey", publicKey, 32); + +// ../viem/src/_esm/utils/ccip.js +var exports_ccip = {}; +__export(exports_ccip, { + offchainLookupSignature: () => offchainLookupSignature, + offchainLookupAbiItem: () => offchainLookupAbiItem, + offchainLookup: () => offchainLookup, + ccipRequest: () => ccipRequest +}); +async function offchainLookup(client, { blockNumber, blockTag, data, requestOptions, to }) { + const { args } = decodeErrorResult({ + data, + abi: [offchainLookupAbiItem] + }); + const [sender, urls, callData, callbackSelector, extraData] = args; + const { ccipRead } = client; + const ccipRequest_ = ccipRead && typeof ccipRead?.request === "function" ? ccipRead.request : ccipRequest; try { - const P = lift_x(num(pub)); - const r = num(sig.subarray(0, 32)); - if (!inRange(r, _1n6, secp256k1P)) - return false; - const s = num(sig.subarray(32, 64)); - if (!inRange(s, _1n6, secp256k1N)) - return false; - const e = challenge(numTo32b(r), pointToBytes(P), m); - const R = GmulAdd(P, s, modN(-e)); - if (!R || !R.hasEvenY() || R.toAffine().x !== r) - return false; - return true; - } catch (error) { - return false; + if (!isAddressEqual(to, sender)) + throw new OffchainLookupSenderMismatchError({ sender, to }); + const result = urls.includes(localBatchGatewayUrl) ? await localBatchGatewayRequest({ + data: callData, + ccipRequest: (parameters) => ccipRequest_({ ...parameters, requestOptions }) + }) : await ccipRequest_({ data: callData, requestOptions, sender, urls }); + const { data: data_ } = await call(client, { + blockNumber, + blockTag, + data: concat([ + callbackSelector, + encodeAbiParameters([{ type: "bytes" }, { type: "bytes" }], [result, extraData]) + ]), + requestOptions, + to + }); + return data_; + } catch (err) { + if (requestOptions?.signal?.aborted) + throw getAbortError(requestOptions.signal); + if (isAbortError(err)) + throw err; + throw new OffchainLookupError({ + callbackSelector, + cause: err, + data, + extraData, + sender, + urls + }); } } -var secp256k1P, secp256k1N, _0n6, _1n6, _2n4, divNearest = (a, b) => (a + b / _2n4) / b, Fpk1, secp256k1, TAGGED_HASH_PREFIXES, pointToBytes = (point) => point.toRawBytes(true).slice(1), numTo32b = (n) => numberToBytesBE(n, 32), modP = (x) => mod(x, secp256k1P), modN = (x) => mod(x, secp256k1N), Point, GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b), num, schnorr, isoMap, mapSWU, secp256k1_hasher, hashToCurve, encodeToCurve; -var init_secp256k1 = __esm(() => { - init_sha2(); - init_utils2(); - init__shortw_utils(); - init_hash_to_curve(); - init_modular(); - init_utils3(); - init_weierstrass(); - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); - secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); - _0n6 = BigInt(0); - _1n6 = BigInt(1); - _2n4 = BigInt(2); - Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); - secp256k1 = createCurve({ - a: _0n6, - b: BigInt(7), - Fp: Fpk1, - n: secp256k1N, - Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), - Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), - h: BigInt(1), - lowS: true, - endo: { - beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), - splitScalar: (k) => { - const n = secp256k1N; - const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); - const b1 = -_1n6 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); - const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); - const b2 = a1; - const POW_2_128 = BigInt("0x100000000000000000000000000000000"); - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = mod(k - c1 * a1 - c2 * a2, n); - let k2 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k2 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k2 = n - k2; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error("splitScalar: Endomorphism failed, k=" + k); - } - return { k1neg, k1, k2neg, k2 }; +async function ccipRequest({ data, requestOptions, sender, urls }) { + let error = new Error("An unknown error occurred."); + for (let i = 0;i < urls.length; i++) { + if (requestOptions?.signal?.aborted) + throw getAbortError(requestOptions.signal); + const url = urls[i]; + const method = url.includes("{data}") ? "GET" : "POST"; + const body = method === "POST" ? { data, sender } : undefined; + const headers = method === "POST" ? { "Content-Type": "application/json" } : {}; + try { + const response = await fetch(url.replace("{sender}", sender.toLowerCase()).replace("{data}", data), { + body: JSON.stringify(body), + headers, + method, + ...requestOptions?.signal ? { signal: requestOptions.signal } : {} + }); + let result; + if (response.headers.get("Content-Type")?.startsWith("application/json")) { + result = (await response.json()).data; + } else { + result = await response.text(); + } + if (!response.ok) { + error = new HttpRequestError({ + body, + details: result?.error ? stringify(result.error) : response.statusText, + headers: response.headers, + status: response.status, + url + }); + continue; + } + if (!isHex(result)) { + error = new OffchainLookupResponseMalformedError({ + result, + url + }); + continue; } + return result; + } catch (err) { + if (requestOptions?.signal?.aborted) + throw getAbortError(requestOptions.signal); + if (isAbortError(err)) + throw err; + error = new HttpRequestError({ + body, + details: err.message, + url + }); } - }, sha256); - TAGGED_HASH_PREFIXES = {}; - Point = /* @__PURE__ */ (() => secp256k1.ProjectivePoint)(); - num = bytesToNumberBE; - schnorr = /* @__PURE__ */ (() => ({ - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - utils: { - randomPrivateKey: secp256k1.utils.randomPrivateKey, - lift_x, - pointToBytes, - numberToBytesBE, - bytesToNumberBE, - taggedHash, - mod - } - }))(); - isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [ - [ - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", - "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", - "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", - "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" - ], - [ - "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", - "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", - "0x0000000000000000000000000000000000000000000000000000000000000001" - ], - [ - "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", - "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", - "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", - "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" - ], - [ - "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", - "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", - "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", - "0x0000000000000000000000000000000000000000000000000000000000000001" + } + throw error; +} +var offchainLookupSignature = "0x556f1830", offchainLookupAbiItem; +var init_ccip2 = __esm(() => { + init_call(); + init_ccip(); + init_request(); + init_decodeErrorResult(); + init_encodeAbiParameters(); + init_isAddressEqual(); + init_localBatchGatewayRequest(); + offchainLookupAbiItem = { + name: "OffchainLookup", + type: "error", + inputs: [ + { + name: "sender", + type: "address" + }, + { + name: "urls", + type: "string[]" + }, + { + name: "callData", + type: "bytes" + }, + { + name: "callbackFunction", + type: "bytes4" + }, + { + name: "extraData", + type: "bytes" + } ] - ].map((i) => i.map((j) => BigInt(j)))))(); - mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, { - A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), - B: BigInt("1771"), - Z: Fpk1.create(BigInt("-11")) - }))(); - secp256k1_hasher = /* @__PURE__ */ (() => createHasher2(secp256k1.ProjectivePoint, (scalars) => { - const { x, y } = mapSWU(Fpk1.create(scalars[0])); - return isoMap(x, y); - }, { - DST: "secp256k1_XMD:SHA-256_SSWU_RO_", - encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", - p: Fpk1.ORDER, - m: 1, - k: 128, - expand: "xmd", - hash: sha256 - }))(); - hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)(); - encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)(); + }; }); -// ../viem/src/_esm/errors/node.js -var ExecutionRevertedError, FeeCapTooHighError, FeeCapTooLowError, NonceTooHighError, NonceTooLowError, NonceMaxValueError, InsufficientFundsError, IntrinsicGasTooHighError, IntrinsicGasTooLowError, TransactionTypeNotSupportedError, TipAboveFeeCapError, UnknownNodeError; -var init_node = __esm(() => { - init_formatGwei(); - init_base(); - ExecutionRevertedError = class ExecutionRevertedError extends BaseError2 { - constructor({ cause, message } = {}) { - const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", ""); - super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { - cause, - name: "ExecutionRevertedError" - }); - } - }; - Object.defineProperty(ExecutionRevertedError, "code", { - enumerable: true, - configurable: true, - writable: true, - value: 3 - }); - Object.defineProperty(ExecutionRevertedError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /execution reverted|gas required exceeds allowance/ - }); - FeeCapTooHighError = class FeeCapTooHighError extends BaseError2 { - constructor({ cause, maxFeePerGas } = {}) { - super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei2(maxFeePerGas)} gwei` : ""}) cannot be higher than the maximum allowed value (2^256-1).`, { - cause, - name: "FeeCapTooHighError" +// ../viem/src/_esm/actions/public/call.js +async function call(client, args) { + const { account: account_ = client.account, authorizationList, batch = Boolean(client.batch?.multicall), blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", requireCanonical, accessList, blobs, blockOverrides, code, data: data_, factory, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, requestOptions, to, value, stateOverride, ...rest } = args; + const account = account_ ? parseAccount(account_) : undefined; + if (code && (factory || factoryData)) + throw new BaseError2("Cannot provide both `code` & `factory`/`factoryData` as parameters."); + if (code && to) + throw new BaseError2("Cannot provide both `code` & `to` as parameters."); + const deploylessCallViaBytecode = code && data_; + const deploylessCallViaFactory = factory && factoryData && to && data_; + const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory; + const data = (() => { + if (deploylessCallViaBytecode) + return toDeploylessCallViaBytecodeData({ + code, + data: data_ }); - } - }; - Object.defineProperty(FeeCapTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/ - }); - FeeCapTooLowError = class FeeCapTooLowError extends BaseError2 { - constructor({ cause, maxFeePerGas } = {}) { - super(`The fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei2(maxFeePerGas)}` : ""} gwei) cannot be lower than the block base fee.`, { - cause, - name: "FeeCapTooLowError" + if (deploylessCallViaFactory) + return toDeploylessCallViaFactoryData({ + data: data_, + factory, + factoryData, + to }); + return data_; + })(); + try { + assertRequest(args); + const block = formatBlockParameter({ + blockHash, + blockNumber, + blockTag, + requireCanonical + }); + const rpcBlockOverrides = blockOverrides ? toRpc2(blockOverrides) : undefined; + const rpcStateOverride = serializeStateOverride(stateOverride); + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format2 = chainFormat || formatTransactionRequest; + const request = format2({ + ...extract(rest, { format: chainFormat }), + accessList, + account, + authorizationList, + blobs, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to: deploylessCall ? undefined : to, + value + }, "call"); + if (batch && shouldPerformMulticall({ request }) && !rpcBlockOverrides && blockHash === undefined) { + try { + const { deployless = false } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; + const multicallAddress = getMulticallAddress(client, { + blockNumber, + deployless + }); + if (!multicallAddress || !hasStateOverrideForAddress(rpcStateOverride, multicallAddress)) + return await scheduleMulticall(client, { + ...request, + blockHash, + blockNumber, + blockTag, + multicallAddress, + requestOptions, + requireCanonical, + rpcStateOverride + }); + } catch (err) { + if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract)) + throw err; + } } - }; - Object.defineProperty(FeeCapTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/ - }); - NonceTooHighError = class NonceTooHighError extends BaseError2 { - constructor({ cause, nonce } = {}) { - super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is higher than the next one expected.`, { cause, name: "NonceTooHighError" }); - } - }; - Object.defineProperty(NonceTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce too high/ - }); - NonceTooLowError = class NonceTooLowError extends BaseError2 { - constructor({ cause, nonce } = {}) { - super([ - `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}is lower than the current nonce of the account.`, - "Try increasing the nonce or find the latest nonce with `getTransactionCount`." - ].join(` -`), { cause, name: "NonceTooLowError" }); - } - }; - Object.defineProperty(NonceTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce too low|transaction already imported|already known/ - }); - NonceMaxValueError = class NonceMaxValueError extends BaseError2 { - constructor({ cause, nonce } = {}) { - super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ""}exceeds the maximum allowed nonce.`, { cause, name: "NonceMaxValueError" }); - } - }; - Object.defineProperty(NonceMaxValueError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /nonce has max value/ + const params = (() => { + const base = [ + request, + block + ]; + if (rpcStateOverride && rpcBlockOverrides) + return [...base, rpcStateOverride, rpcBlockOverrides]; + if (rpcStateOverride) + return [...base, rpcStateOverride]; + if (rpcBlockOverrides) + return [...base, {}, rpcBlockOverrides]; + return base; + })(); + const response = await client.request({ + method: "eth_call", + params + }, requestOptions); + if (response === "0x") + return { data: undefined }; + return { data: response }; + } catch (err) { + if (requestOptions?.signal?.aborted) + throw getAbortError(requestOptions.signal); + if (isAbortError(err)) + throw err; + const data2 = getRevertErrorData(err); + const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await Promise.resolve().then(() => (init_ccip2(), exports_ccip)); + if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to) + return { + data: await offchainLookup2(client, { data: data2, requestOptions, to }) + }; + if (deploylessCall && data2?.slice(0, 10) === "0x101bb98d") + throw new CounterfactualDeploymentFailedError({ factory }); + throw getCallError(err, { + ...args, + account, + chain: client.chain + }); + } +} +function shouldPerformMulticall({ request }) { + const { data, to, ...request_ } = request; + if (!data) + return false; + if (data.startsWith(aggregate3Signature)) + return false; + if (!to) + return false; + if (Object.values(request_).filter((x) => typeof x !== "undefined").length > 0) + return false; + return true; +} +function getRequestOptionsId(requestOptions) { + if (!requestOptions) + return "default"; + const id = requestOptionsIds.get(requestOptions); + if (id !== undefined) + return id; + const nextId = requestOptionsId++; + requestOptionsIds.set(requestOptions, nextId); + return nextId; +} +async function scheduleMulticall(client, args) { + const { batchSize = 1024, deployless = false, wait = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; + const { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", requireCanonical, data, multicallAddress: multicallAddress_, requestOptions, rpcStateOverride, to } = args; + const multicallAddress = multicallAddress_ !== undefined ? multicallAddress_ : getMulticallAddress(client, { + blockNumber, + deployless }); - InsufficientFundsError = class InsufficientFundsError extends BaseError2 { - constructor({ cause } = {}) { - super([ - "The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account." - ].join(` -`), { - cause, - metaMessages: [ - "This error could arise when the account does not have enough funds to:", - " - pay for the total gas fee,", - " - pay for the value to send.", - " ", - "The cost of the transaction is calculated as `gas * gas fee + value`, where:", - " - `gas` is the amount of gas needed for transaction to execute,", - " - `gas fee` is the gas fee,", - " - `value` is the amount of ether to send to the recipient." - ], - name: "InsufficientFundsError" - }); - } - }; - Object.defineProperty(InsufficientFundsError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /insufficient funds|exceeds transaction sender account balance/ + const block = formatBlockParameter({ + blockHash, + blockNumber, + blockTag, + requireCanonical }); - IntrinsicGasTooHighError = class IntrinsicGasTooHighError extends BaseError2 { - constructor({ cause, gas } = {}) { - super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction exceeds the limit allowed for the block.`, { - cause, - name: "IntrinsicGasTooHighError" + const blockId = typeof block === "string" ? block : JSON.stringify(block); + const stateOverrideKey = rpcStateOverride ? `.${JSON.stringify(rpcStateOverride)}` : ""; + const { schedule } = createBatchScheduler({ + id: `${client.uid}.${blockId}.${getRequestOptionsId(requestOptions)}${stateOverrideKey}`, + wait, + shouldSplitBatch(args2) { + const size5 = args2.reduce((size6, { data: data2 }) => size6 + (data2.length - 2), 0); + return size5 > batchSize * 2; + }, + fn: async (requests) => { + const calls = requests.map((request) => ({ + allowFailure: true, + callData: request.data, + target: request.to + })); + const calldata = encodeFunctionData({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3" }); - } - }; - Object.defineProperty(IntrinsicGasTooHighError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /intrinsic gas too high|gas limit reached/ - }); - IntrinsicGasTooLowError = class IntrinsicGasTooLowError extends BaseError2 { - constructor({ cause, gas } = {}) { - super(`The amount of gas ${gas ? `(${gas}) ` : ""}provided for the transaction is too low.`, { - cause, - name: "IntrinsicGasTooLowError" + const multicallRequest = { + ...multicallAddress === null ? { + data: toDeploylessCallViaBytecodeData({ + code: multicall3Bytecode, + data: calldata + }) + } : { to: multicallAddress, data: calldata } + }; + const data2 = await client.request({ + method: "eth_call", + params: rpcStateOverride ? [multicallRequest, block, rpcStateOverride] : [multicallRequest, block] + }, requestOptions); + return decodeFunctionResult({ + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3", + data: data2 || "0x" }); } - }; - Object.defineProperty(IntrinsicGasTooLowError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /intrinsic gas too low/ }); - TransactionTypeNotSupportedError = class TransactionTypeNotSupportedError extends BaseError2 { - constructor({ cause }) { - super("The transaction type is not supported for this chain.", { - cause, - name: "TransactionTypeNotSupportedError" - }); - } - }; - Object.defineProperty(TransactionTypeNotSupportedError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /transaction type not valid/ + const [{ returnData, success }] = await schedule({ data, to }); + if (!success) + throw new RawContractError({ data: returnData }); + if (returnData === "0x") + return { data: undefined }; + return { data: returnData }; +} +function getMulticallAddress(client, parameters) { + const { blockNumber, deployless } = parameters; + if (deployless) + return null; + if (client.chain) + return getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "multicall3" + }); + throw new ClientChainNotConfiguredError; +} +function hasStateOverrideForAddress(rpcStateOverride, address) { + if (!rpcStateOverride) + return false; + return Object.keys(rpcStateOverride).some((stateOverrideAddress) => isAddressEqual(stateOverrideAddress, address)); +} +function toDeploylessCallViaBytecodeData(parameters) { + const { code, data } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(bytes, bytes)"]), + bytecode: deploylessCallViaBytecodeBytecode, + args: [code, data] }); - TipAboveFeeCapError = class TipAboveFeeCapError extends BaseError2 { - constructor({ cause, maxPriorityFeePerGas, maxFeePerGas } = {}) { - super([ - `The provided tip (\`maxPriorityFeePerGas\`${maxPriorityFeePerGas ? ` = ${formatGwei2(maxPriorityFeePerGas)} gwei` : ""}) cannot be higher than the fee cap (\`maxFeePerGas\`${maxFeePerGas ? ` = ${formatGwei2(maxFeePerGas)} gwei` : ""}).` - ].join(` -`), { - cause, - name: "TipAboveFeeCapError" - }); - } - }; - Object.defineProperty(TipAboveFeeCapError, "nodeMessage", { - enumerable: true, - configurable: true, - writable: true, - value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/ - }); - UnknownNodeError = class UnknownNodeError extends BaseError2 { - constructor({ cause }) { - super(`An error occurred while executing: ${cause?.shortMessage}`, { - cause, - name: "UnknownNodeError" - }); - } - }; -}); - -// ../viem/src/_esm/utils/errors/getNodeError.js -function getNodeError(err, args) { - const message = (err.details || "").toLowerCase(); - const executionRevertedError = err instanceof BaseError2 ? err.walk((e) => e?.code === ExecutionRevertedError.code) : err; - if (executionRevertedError instanceof BaseError2) - return new ExecutionRevertedError({ - cause: err, - message: executionRevertedError.details - }); - if (ExecutionRevertedError.nodeMessage.test(message)) - return new ExecutionRevertedError({ - cause: err, - message: err.details - }); - if (FeeCapTooHighError.nodeMessage.test(message)) - return new FeeCapTooHighError({ - cause: err, - maxFeePerGas: args?.maxFeePerGas - }); - if (FeeCapTooLowError.nodeMessage.test(message)) - return new FeeCapTooLowError({ - cause: err, - maxFeePerGas: args?.maxFeePerGas - }); - if (NonceTooHighError.nodeMessage.test(message)) - return new NonceTooHighError({ cause: err, nonce: args?.nonce }); - if (NonceTooLowError.nodeMessage.test(message)) - return new NonceTooLowError({ cause: err, nonce: args?.nonce }); - if (NonceMaxValueError.nodeMessage.test(message)) - return new NonceMaxValueError({ cause: err, nonce: args?.nonce }); - if (InsufficientFundsError.nodeMessage.test(message)) - return new InsufficientFundsError({ cause: err }); - if (IntrinsicGasTooHighError.nodeMessage.test(message)) - return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas }); - if (IntrinsicGasTooLowError.nodeMessage.test(message)) - return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas }); - if (TransactionTypeNotSupportedError.nodeMessage.test(message)) - return new TransactionTypeNotSupportedError({ cause: err }); - if (TipAboveFeeCapError.nodeMessage.test(message)) - return new TipAboveFeeCapError({ - cause: err, - maxFeePerGas: args?.maxFeePerGas, - maxPriorityFeePerGas: args?.maxPriorityFeePerGas - }); - return new UnknownNodeError({ - cause: err +} +function toDeploylessCallViaFactoryData(parameters) { + const { data, factory, factoryData, to } = parameters; + return encodeDeployData({ + abi: parseAbi(["constructor(address, bytes, address, bytes)"]), + bytecode: deploylessCallViaFactoryBytecode, + args: [to, data, factory, factoryData] }); } -var init_getNodeError = __esm(() => { +function getRevertErrorData(err) { + if (!(err instanceof BaseError2)) + return; + const error = err.walk(); + return typeof error?.data === "object" ? error.data?.data : error.data; +} +var requestOptionsId = 0, requestOptionsIds; +var init_call = __esm(() => { + init_exports(); + init_BlockOverrides(); + init_abis(); init_base(); - init_node(); + init_chain(); + init_contract(); + init_decodeFunctionResult(); + init_encodeDeployData(); + init_encodeFunctionData(); + init_isAddressEqual(); + init_formatBlockParameter(); + init_getChainContractAddress(); + init_getCallError(); + init_transactionRequest(); + init_createBatchScheduler(); + init_stateOverride2(); + init_assertRequest(); + requestOptionsIds = new WeakMap; }); -// ../viem/src/_esm/utils/formatters/extract.js -function extract(value_, { format: format2 }) { - if (!format2) - return {}; - const value = {}; - function extract_(formatted2) { - const keys = Object.keys(formatted2); - for (const key of keys) { - if (key in value_) - value[key] = value_[key]; - if (formatted2[key] && typeof formatted2[key] === "object" && !Array.isArray(formatted2[key])) - extract_(formatted2[key]); - } - } - const formatted = format2(value_ || {}); - extract_(formatted); - return value; +// ../viem/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js +function setBigUint64(view, byteOffset, value, isLE2) { + if (typeof view.setBigUint64 === "function") + return view.setBigUint64(byteOffset, value, isLE2); + const _32n2 = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n2 & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE2 ? 4 : 0; + const l = isLE2 ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE2); + view.setUint32(byteOffset + l, wl, isLE2); } - -// ../viem/src/_esm/utils/formatters/transactionRequest.js -function formatTransactionRequest(request, _) { - const rpcRequest = {}; - if (typeof request.authorizationList !== "undefined") - rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList); - if (typeof request.accessList !== "undefined") - rpcRequest.accessList = request.accessList; - if (typeof request.blobVersionedHashes !== "undefined") - rpcRequest.blobVersionedHashes = request.blobVersionedHashes; - if (typeof request.blobs !== "undefined") { - if (typeof request.blobs[0] !== "string") - rpcRequest.blobs = request.blobs.map((x) => bytesToHex(x)); - else - rpcRequest.blobs = request.blobs; - } - if (typeof request.data !== "undefined") - rpcRequest.data = request.data; - if (request.account) - rpcRequest.from = request.account.address; - if (typeof request.from !== "undefined") - rpcRequest.from = request.from; - if (typeof request.gas !== "undefined") - rpcRequest.gas = numberToHex(request.gas); - if (typeof request.gasPrice !== "undefined") - rpcRequest.gasPrice = numberToHex(request.gasPrice); - if (typeof request.maxFeePerBlobGas !== "undefined") - rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas); - if (typeof request.maxFeePerGas !== "undefined") - rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas); - if (typeof request.maxPriorityFeePerGas !== "undefined") - rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas); - if (typeof request.nonce !== "undefined") - rpcRequest.nonce = numberToHex(request.nonce); - if (typeof request.to !== "undefined") - rpcRequest.to = request.to; - if (typeof request.type !== "undefined") - rpcRequest.type = rpcTransactionType[request.type]; - if (typeof request.value !== "undefined") - rpcRequest.value = numberToHex(request.value); - return rpcRequest; +function Chi(a, b, c) { + return a & b ^ ~a & c; } -function formatAuthorizationList(authorizationList) { - return authorizationList.map((authorization) => ({ - address: authorization.address, - r: authorization.r ? numberToHex(BigInt(authorization.r)) : authorization.r, - s: authorization.s ? numberToHex(BigInt(authorization.s)) : authorization.s, - chainId: numberToHex(authorization.chainId), - nonce: numberToHex(authorization.nonce), - ...typeof authorization.yParity !== "undefined" ? { yParity: numberToHex(authorization.yParity) } : {}, - ...typeof authorization.v !== "undefined" && typeof authorization.yParity === "undefined" ? { v: numberToHex(authorization.v) } : {} - })); +function Maj(a, b, c) { + return a & b ^ a & c ^ b & c; } -var rpcTransactionType; -var init_transactionRequest = __esm(() => { - init_toHex(); - rpcTransactionType = { - legacy: "0x0", - eip2930: "0x1", - eip1559: "0x2", - eip4844: "0x3", - eip7702: "0x4" +var HashMD, SHA256_IV, SHA384_IV, SHA512_IV; +var init__md = __esm(() => { + init_utils2(); + HashMD = class HashMD extends Hash { + constructor(blockLen, outputLen, padOffset, isLE2) { + super(); + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + data = toBytes2(data); + abytes(data); + const { view, buffer: buffer2, blockLen } = this; + const len = data.length; + for (let pos = 0;pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (;blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer2.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer: buffer2, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer2[pos++] = 128; + clean(this.buffer.subarray(pos)); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos;i < blockLen; i++) + buffer2[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0;i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer: buffer2, outputLen } = this; + this.digestInto(buffer2); + const res = buffer2.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor); + to.set(...this.get()); + const { blockLen, buffer: buffer2, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + if (length % blockLen) + to.buffer.set(buffer2); + return to; + } + clone() { + return this._cloneInto(); + } }; + SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 + ]); + SHA384_IV = /* @__PURE__ */ Uint32Array.from([ + 3418070365, + 3238371032, + 1654270250, + 914150663, + 2438529370, + 812702999, + 355462360, + 4144912697, + 1731405415, + 4290775857, + 2394180231, + 1750603025, + 3675008525, + 1694076839, + 1203062813, + 3204075428 + ]); + SHA512_IV = /* @__PURE__ */ Uint32Array.from([ + 1779033703, + 4089235720, + 3144134277, + 2227873595, + 1013904242, + 4271175723, + 2773480762, + 1595750129, + 1359893119, + 2917565137, + 2600822924, + 725511199, + 528734635, + 4215389547, + 1541459225, + 327033209 + ]); }); -// ../viem/src/_esm/utils/stateOverride.js -function serializeStateMapping(stateMapping) { - if (!stateMapping || stateMapping.length === 0) - return; - return stateMapping.reduce((acc, { slot, value }) => { - if (slot.length !== 66) - throw new InvalidBytesLengthError({ - size: slot.length, - targetSize: 66, - type: "hex" - }); - if (value.length !== 66) - throw new InvalidBytesLengthError({ - size: value.length, - targetSize: 66, - type: "hex" - }); - acc[slot] = value; - return acc; - }, {}); -} -function serializeAccountStateOverride(parameters) { - const { balance, nonce, state, stateDiff, code } = parameters; - const rpcAccountStateOverride = {}; - if (code !== undefined) - rpcAccountStateOverride.code = code; - if (balance !== undefined) - rpcAccountStateOverride.balance = numberToHex(balance); - if (nonce !== undefined) - rpcAccountStateOverride.nonce = numberToHex(nonce); - if (state !== undefined) - rpcAccountStateOverride.state = serializeStateMapping(state); - if (stateDiff !== undefined) { - if (rpcAccountStateOverride.state) - throw new StateAssignmentConflictError; - rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff); - } - return rpcAccountStateOverride; -} -function serializeStateOverride(parameters) { - if (!parameters) - return; - const rpcStateOverride = {}; - for (const { address, ...accountState } of parameters) { - if (!isAddress(address, { strict: false })) - throw new InvalidAddressError({ address }); - if (rpcStateOverride[address]) - throw new AccountStateConflictError({ address }); - rpcStateOverride[address] = serializeAccountStateOverride(accountState); - } - return rpcStateOverride; -} -var init_stateOverride2 = __esm(() => { - init_address(); - init_data(); - init_stateOverride(); - init_isAddress(); - init_toHex(); -}); - -// ../viem/src/_esm/constants/number.js -var maxInt8, maxInt16, maxInt24, maxInt32, maxInt40, maxInt48, maxInt56, maxInt64, maxInt72, maxInt80, maxInt88, maxInt96, maxInt104, maxInt112, maxInt120, maxInt128, maxInt136, maxInt144, maxInt152, maxInt160, maxInt168, maxInt176, maxInt184, maxInt192, maxInt200, maxInt208, maxInt216, maxInt224, maxInt232, maxInt240, maxInt248, maxInt256, minInt8, minInt16, minInt24, minInt32, minInt40, minInt48, minInt56, minInt64, minInt72, minInt80, minInt88, minInt96, minInt104, minInt112, minInt120, minInt128, minInt136, minInt144, minInt152, minInt160, minInt168, minInt176, minInt184, minInt192, minInt200, minInt208, minInt216, minInt224, minInt232, minInt240, minInt248, minInt256, maxUint8, maxUint16, maxUint24, maxUint32, maxUint40, maxUint48, maxUint56, maxUint64, maxUint72, maxUint80, maxUint88, maxUint96, maxUint104, maxUint112, maxUint120, maxUint128, maxUint136, maxUint144, maxUint152, maxUint160, maxUint168, maxUint176, maxUint184, maxUint192, maxUint200, maxUint208, maxUint216, maxUint224, maxUint232, maxUint240, maxUint248, maxUint256; -var init_number = __esm(() => { - maxInt8 = 2n ** (8n - 1n) - 1n; - maxInt16 = 2n ** (16n - 1n) - 1n; - maxInt24 = 2n ** (24n - 1n) - 1n; - maxInt32 = 2n ** (32n - 1n) - 1n; - maxInt40 = 2n ** (40n - 1n) - 1n; - maxInt48 = 2n ** (48n - 1n) - 1n; - maxInt56 = 2n ** (56n - 1n) - 1n; - maxInt64 = 2n ** (64n - 1n) - 1n; - maxInt72 = 2n ** (72n - 1n) - 1n; - maxInt80 = 2n ** (80n - 1n) - 1n; - maxInt88 = 2n ** (88n - 1n) - 1n; - maxInt96 = 2n ** (96n - 1n) - 1n; - maxInt104 = 2n ** (104n - 1n) - 1n; - maxInt112 = 2n ** (112n - 1n) - 1n; - maxInt120 = 2n ** (120n - 1n) - 1n; - maxInt128 = 2n ** (128n - 1n) - 1n; - maxInt136 = 2n ** (136n - 1n) - 1n; - maxInt144 = 2n ** (144n - 1n) - 1n; - maxInt152 = 2n ** (152n - 1n) - 1n; - maxInt160 = 2n ** (160n - 1n) - 1n; - maxInt168 = 2n ** (168n - 1n) - 1n; - maxInt176 = 2n ** (176n - 1n) - 1n; - maxInt184 = 2n ** (184n - 1n) - 1n; - maxInt192 = 2n ** (192n - 1n) - 1n; - maxInt200 = 2n ** (200n - 1n) - 1n; - maxInt208 = 2n ** (208n - 1n) - 1n; - maxInt216 = 2n ** (216n - 1n) - 1n; - maxInt224 = 2n ** (224n - 1n) - 1n; - maxInt232 = 2n ** (232n - 1n) - 1n; - maxInt240 = 2n ** (240n - 1n) - 1n; - maxInt248 = 2n ** (248n - 1n) - 1n; - maxInt256 = 2n ** (256n - 1n) - 1n; - minInt8 = -(2n ** (8n - 1n)); - minInt16 = -(2n ** (16n - 1n)); - minInt24 = -(2n ** (24n - 1n)); - minInt32 = -(2n ** (32n - 1n)); - minInt40 = -(2n ** (40n - 1n)); - minInt48 = -(2n ** (48n - 1n)); - minInt56 = -(2n ** (56n - 1n)); - minInt64 = -(2n ** (64n - 1n)); - minInt72 = -(2n ** (72n - 1n)); - minInt80 = -(2n ** (80n - 1n)); - minInt88 = -(2n ** (88n - 1n)); - minInt96 = -(2n ** (96n - 1n)); - minInt104 = -(2n ** (104n - 1n)); - minInt112 = -(2n ** (112n - 1n)); - minInt120 = -(2n ** (120n - 1n)); - minInt128 = -(2n ** (128n - 1n)); - minInt136 = -(2n ** (136n - 1n)); - minInt144 = -(2n ** (144n - 1n)); - minInt152 = -(2n ** (152n - 1n)); - minInt160 = -(2n ** (160n - 1n)); - minInt168 = -(2n ** (168n - 1n)); - minInt176 = -(2n ** (176n - 1n)); - minInt184 = -(2n ** (184n - 1n)); - minInt192 = -(2n ** (192n - 1n)); - minInt200 = -(2n ** (200n - 1n)); - minInt208 = -(2n ** (208n - 1n)); - minInt216 = -(2n ** (216n - 1n)); - minInt224 = -(2n ** (224n - 1n)); - minInt232 = -(2n ** (232n - 1n)); - minInt240 = -(2n ** (240n - 1n)); - minInt248 = -(2n ** (248n - 1n)); - minInt256 = -(2n ** (256n - 1n)); - maxUint8 = 2n ** 8n - 1n; - maxUint16 = 2n ** 16n - 1n; - maxUint24 = 2n ** 24n - 1n; - maxUint32 = 2n ** 32n - 1n; - maxUint40 = 2n ** 40n - 1n; - maxUint48 = 2n ** 48n - 1n; - maxUint56 = 2n ** 56n - 1n; - maxUint64 = 2n ** 64n - 1n; - maxUint72 = 2n ** 72n - 1n; - maxUint80 = 2n ** 80n - 1n; - maxUint88 = 2n ** 88n - 1n; - maxUint96 = 2n ** 96n - 1n; - maxUint104 = 2n ** 104n - 1n; - maxUint112 = 2n ** 112n - 1n; - maxUint120 = 2n ** 120n - 1n; - maxUint128 = 2n ** 128n - 1n; - maxUint136 = 2n ** 136n - 1n; - maxUint144 = 2n ** 144n - 1n; - maxUint152 = 2n ** 152n - 1n; - maxUint160 = 2n ** 160n - 1n; - maxUint168 = 2n ** 168n - 1n; - maxUint176 = 2n ** 176n - 1n; - maxUint184 = 2n ** 184n - 1n; - maxUint192 = 2n ** 192n - 1n; - maxUint200 = 2n ** 200n - 1n; - maxUint208 = 2n ** 208n - 1n; - maxUint216 = 2n ** 216n - 1n; - maxUint224 = 2n ** 224n - 1n; - maxUint232 = 2n ** 232n - 1n; - maxUint240 = 2n ** 240n - 1n; - maxUint248 = 2n ** 248n - 1n; - maxUint256 = 2n ** 256n - 1n; -}); - -// ../viem/src/_esm/utils/transaction/assertRequest.js -function assertRequest(args) { - const { account: account_, maxFeePerGas, maxPriorityFeePerGas, to } = args; - const account = account_ ? parseAccount(account_) : undefined; - if (account && !isAddress(account.address)) - throw new InvalidAddressError({ address: account.address }); - if (to && !isAddress(to)) - throw new InvalidAddressError({ address: to }); - if (maxFeePerGas && maxFeePerGas > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas }); - if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) - throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); -} -var init_assertRequest = __esm(() => { - init_number(); - init_address(); - init_node(); - init_isAddress(); -}); - -// ../viem/src/_esm/utils/block/formatBlockParameter.js -function formatBlockParameter(parameters) { - const { blockHash, blockNumber, blockTag, requireCanonical } = parameters; - if (requireCanonical !== undefined && !blockHash) - throw new BaseError2("`requireCanonical` can only be provided when `blockHash` is set."); - if (blockHash) - return requireCanonical ? { blockHash, requireCanonical } : { blockHash }; - if (typeof blockNumber === "bigint") - return numberToHex(blockNumber); - return blockTag ?? "latest"; -} -var init_formatBlockParameter = __esm(() => { - init_base(); - init_toHex(); -}); - -// ../viem/src/_esm/utils/address/isAddressEqual.js -function isAddressEqual(a, b) { - if (!isAddress(a, { strict: false })) - throw new InvalidAddressError({ address: a }); - if (!isAddress(b, { strict: false })) - throw new InvalidAddressError({ address: b }); - return a.toLowerCase() === b.toLowerCase(); -} -var init_isAddressEqual = __esm(() => { - init_address(); - init_isAddress(); -}); - -// ../viem/src/_esm/utils/abi/decodeFunctionResult.js -function decodeFunctionResult(parameters) { - const { abi, args, functionName, data } = parameters; - let abiItem = abi[0]; - if (functionName) { - const item = getAbiItem({ abi, args, name: functionName }); - if (!item) - throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath4 }); - abiItem = item; - } - if (abiItem.type !== "function") - throw new AbiFunctionNotFoundError(undefined, { docsPath: docsPath4 }); - if (!abiItem.outputs) - throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath4 }); - const values = decodeAbiParameters(abiItem.outputs, data); - if (values && values.length > 1) - return values; - if (values && values.length === 1) - return values[0]; - return; -} -var docsPath4 = "/docs/contract/decodeFunctionResult"; -var init_decodeFunctionResult = __esm(() => { - init_abi(); - init_decodeAbiParameters(); - init_getAbiItem(); -}); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/version.js -var version3 = "0.1.1"; - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/errors.js -function getVersion() { - return version3; -} -var init_errors2 = () => {}; - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Errors.js -function walk2(err, fn) { - if (fn?.(err)) - return err; - if (err && typeof err === "object" && "cause" in err && err.cause) - return walk2(err.cause, fn); - return fn ? null : err; -} -var BaseError3; -var init_Errors = __esm(() => { - init_errors2(); - BaseError3 = class BaseError3 extends Error { - static setStaticOptions(options) { - BaseError3.prototype.docsOrigin = options.docsOrigin; - BaseError3.prototype.showVersion = options.showVersion; - BaseError3.prototype.version = options.version; - } - constructor(shortMessage, options = {}) { - const details = (() => { - if (options.cause instanceof BaseError3) { - if (options.cause.details) - return options.cause.details; - if (options.cause.shortMessage) - return options.cause.shortMessage; - } - if (options.cause && "details" in options.cause && typeof options.cause.details === "string") - return options.cause.details; - if (options.cause?.message) - return options.cause.message; - return options.details; - })(); - const docsPath5 = (() => { - if (options.cause instanceof BaseError3) - return options.cause.docsPath || options.docsPath; - return options.docsPath; - })(); - const docsBaseUrl = options.docsOrigin ?? BaseError3.prototype.docsOrigin; - const docs = `${docsBaseUrl}${docsPath5 ?? ""}`; - const showVersion = Boolean(options.version ?? BaseError3.prototype.showVersion); - const version4 = options.version ?? BaseError3.prototype.version; - const message = [ - shortMessage || "An error occurred.", - ...options.metaMessages ? ["", ...options.metaMessages] : [], - ...details || docsPath5 || showVersion ? [ - "", - details ? `Details: ${details}` : undefined, - docsPath5 ? `See: ${docs}` : undefined, - showVersion ? `Version: ${version4}` : undefined - ] : [] - ].filter((x) => typeof x === "string").join(` -`); - super(message, options.cause ? { cause: options.cause } : undefined); - Object.defineProperty(this, "details", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "docs", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "docsOrigin", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "docsPath", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "shortMessage", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "showVersion", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "version", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "BaseError" - }); - this.cause = options.cause; - this.details = details; - this.docs = docs; - this.docsOrigin = docsBaseUrl; - this.docsPath = docsPath5; - this.shortMessage = shortMessage; - this.showVersion = showVersion; - this.version = version4; +// ../viem/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js +var SHA256_K, SHA256_W, SHA256, K512, SHA512_Kh, SHA512_Kl, SHA512_W_H, SHA512_W_L, SHA512, SHA384, sha256, sha512, sha384; +var init_sha2 = __esm(() => { + init__md(); + init__u64(); + init_utils2(); + SHA256_K = /* @__PURE__ */ Uint32Array.from([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + SHA256_W = /* @__PURE__ */ new Uint32Array(64); + SHA256 = class SHA256 extends HashMD { + constructor(outputLen = 32) { + super(64, outputLen, 8, false); + this.A = SHA256_IV[0] | 0; + this.B = SHA256_IV[1] | 0; + this.C = SHA256_IV[2] | 0; + this.D = SHA256_IV[3] | 0; + this.E = SHA256_IV[4] | 0; + this.F = SHA256_IV[5] | 0; + this.G = SHA256_IV[6] | 0; + this.H = SHA256_IV[7] | 0; } - walk(fn) { - return walk2(this, fn); + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; } - }; - Object.defineProperty(BaseError3, "defaultStaticOptions", { - enumerable: true, - configurable: true, - writable: true, - value: { - docsOrigin: "https://oxlib.sh", - showVersion: false, - version: `ox@${getVersion()}` + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; } - }); - (() => { - BaseError3.setStaticOptions(BaseError3.defaultStaticOptions); - })(); -}); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/bytes.js -function assertSize2(bytes, size_) { - if (size2(bytes) > size_) - throw new SizeOverflowError2({ - givenSize: size2(bytes), - maxSize: size_ - }); -} -function assertStartOffset2(value, start) { - if (typeof start === "number" && start > 0 && start > size2(value) - 1) - throw new SliceOffsetOutOfBoundsError2({ - offset: start, - position: "start", - size: size2(value) - }); -} -function assertEndOffset2(value, start, end) { - if (typeof start === "number" && typeof end === "number" && size2(value) !== end - start) { - throw new SliceOffsetOutOfBoundsError2({ - offset: end, - position: "end", - size: size2(value) - }); - } -} -function charCodeToBase162(char) { - if (char >= charCodeMap2.zero && char <= charCodeMap2.nine) - return char - charCodeMap2.zero; - if (char >= charCodeMap2.A && char <= charCodeMap2.F) - return char - (charCodeMap2.A - 10); - if (char >= charCodeMap2.a && char <= charCodeMap2.f) - return char - (charCodeMap2.a - 10); - return; -} -function pad2(bytes, options = {}) { - const { dir, size: size3 = 32 } = options; - if (size3 === 0) - return bytes; - if (bytes.length > size3) - throw new SizeExceedsPaddingSizeError2({ - size: bytes.length, - targetSize: size3, - type: "Bytes" - }); - const paddedBytes = new Uint8Array(size3); - for (let i = 0;i < size3; i++) { - const padEnd = dir === "right"; - paddedBytes[padEnd ? i : size3 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; - } - return paddedBytes; -} -function trim2(value, options = {}) { - const { dir = "left" } = options; - let data = value; - let sliceLength = 0; - for (let i = 0;i < data.length - 1; i++) { - if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") - sliceLength++; - else - break; - } - data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); - return data; -} -var charCodeMap2; -var init_bytes = __esm(() => { - init_Bytes(); - charCodeMap2 = { - zero: 48, - nine: 57, - A: 65, - F: 70, - a: 97, - f: 102 - }; -}); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/hex.js -function assertSize3(hex, size_) { - if (size3(hex) > size_) - throw new SizeOverflowError3({ - givenSize: size3(hex), - maxSize: size_ - }); -} -function assertStartOffset3(value, start) { - if (typeof start === "number" && start > 0 && start > size3(value) - 1) - throw new SliceOffsetOutOfBoundsError3({ - offset: start, - position: "start", - size: size3(value) - }); -} -function assertEndOffset3(value, start, end) { - if (typeof start === "number" && typeof end === "number" && size3(value) !== end - start) { - throw new SliceOffsetOutOfBoundsError3({ - offset: end, - position: "end", - size: size3(value) - }); - } -} -function pad3(hex_, options = {}) { - const { dir, size: size4 = 32 } = options; - if (size4 === 0) - return hex_; - const hex = hex_.replace("0x", ""); - if (hex.length > size4 * 2) - throw new SizeExceedsPaddingSizeError3({ - size: Math.ceil(hex.length / 2), - targetSize: size4, - type: "Hex" - }); - return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size4 * 2, "0")}`; -} -function trim3(value, options = {}) { - const { dir = "left" } = options; - let data = value.replace("0x", ""); - let sliceLength = 0; - for (let i = 0;i < data.length - 1; i++) { - if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") - sliceLength++; - else - break; - } - data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); - if (data === "0") - return "0x"; - if (dir === "right" && data.length % 2 === 1) - return `0x${data}0`; - return `0x${data}`; -} -var init_hex = __esm(() => { - init_Hex(); -}); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Json.js -function stringify2(value, replacer, space) { - return JSON.stringify(value, (key, value2) => { - if (typeof replacer === "function") - return replacer(key, value2); - if (typeof value2 === "bigint") - return value2.toString() + bigIntSuffix; - return value2; - }, space); -} -var bigIntSuffix = "#__bigint"; - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Bytes.js -function assert(value) { - if (value instanceof Uint8Array) - return; - if (!value) - throw new InvalidBytesTypeError(value); - if (typeof value !== "object") - throw new InvalidBytesTypeError(value); - if (!("BYTES_PER_ELEMENT" in value)) - throw new InvalidBytesTypeError(value); - if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== "Uint8Array") - throw new InvalidBytesTypeError(value); -} -function from2(value) { - if (value instanceof Uint8Array) - return value; - if (typeof value === "string") - return fromHex(value); - return fromArray(value); -} -function fromArray(value) { - return value instanceof Uint8Array ? value : new Uint8Array(value); -} -function fromHex(value, options = {}) { - const { size: size4 } = options; - let hex = value; - if (size4) { - assertSize3(value, size4); - hex = padRight(value, size4); - } - let hexString = hex.slice(2); - if (hexString.length % 2) - hexString = `0${hexString}`; - const length = hexString.length / 2; - const bytes = new Uint8Array(length); - for (let index = 0, j = 0;index < length; index++) { - const nibbleLeft = charCodeToBase162(hexString.charCodeAt(j++)); - const nibbleRight = charCodeToBase162(hexString.charCodeAt(j++)); - if (nibbleLeft === undefined || nibbleRight === undefined) { - throw new BaseError3(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`); + process(view, offset) { + for (let i = 0;i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16;i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0;i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = sigma0 + Maj(A, B, C) | 0; + H = G; + G = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G, H); } - bytes[index] = nibbleLeft << 4 | nibbleRight; - } - return bytes; -} -function fromString(value, options = {}) { - const { size: size4 } = options; - const bytes = encoder3.encode(value); - if (typeof size4 === "number") { - assertSize2(bytes, size4); - return padRight2(bytes, size4); - } - return bytes; -} -function padRight2(value, size4) { - return pad2(value, { dir: "right", size: size4 }); -} -function size2(value) { - return value.length; -} -function slice2(value, start, end, options = {}) { - const { strict } = options; - assertStartOffset2(value, start); - const value_ = value.slice(start, end); - if (strict) - assertEndOffset2(value_, start, end); - return value_; -} -function toBigInt2(bytes, options = {}) { - const { size: size4 } = options; - if (typeof size4 !== "undefined") - assertSize2(bytes, size4); - const hex = fromBytes(bytes, options); - return toBigInt(hex, options); -} -function toBoolean(bytes, options = {}) { - const { size: size4 } = options; - let bytes_ = bytes; - if (typeof size4 !== "undefined") { - assertSize2(bytes_, size4); - bytes_ = trimLeft(bytes_); - } - if (bytes_.length > 1 || bytes_[0] > 1) - throw new InvalidBytesBooleanError2(bytes_); - return Boolean(bytes_[0]); -} -function toNumber2(bytes, options = {}) { - const { size: size4 } = options; - if (typeof size4 !== "undefined") - assertSize2(bytes, size4); - const hex = fromBytes(bytes, options); - return toNumber(hex, options); -} -function toString(bytes, options = {}) { - const { size: size4 } = options; - let bytes_ = bytes; - if (typeof size4 !== "undefined") { - assertSize2(bytes_, size4); - bytes_ = trimRight(bytes_); - } - return decoder.decode(bytes_); -} -function trimLeft(value) { - return trim2(value, { dir: "left" }); -} -function trimRight(value) { - return trim2(value, { dir: "right" }); -} -function validate(value) { - try { - assert(value); - return true; - } catch { - return false; - } -} -var decoder, encoder3, InvalidBytesBooleanError2, InvalidBytesTypeError, SizeOverflowError2, SliceOffsetOutOfBoundsError2, SizeExceedsPaddingSizeError2; -var init_Bytes = __esm(() => { - init_Errors(); - init_Hex(); - init_bytes(); - init_hex(); - decoder = /* @__PURE__ */ new TextDecoder; - encoder3 = /* @__PURE__ */ new TextEncoder; - InvalidBytesBooleanError2 = class InvalidBytesBooleanError2 extends BaseError3 { - constructor(bytes) { - super(`Bytes value \`${bytes}\` is not a valid boolean.`, { - metaMessages: [ - "The bytes array must contain a single byte of either a `0` or `1` value." - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Bytes.InvalidBytesBooleanError" - }); + roundClean() { + clean(SHA256_W); } - }; - InvalidBytesTypeError = class InvalidBytesTypeError extends BaseError3 { - constructor(value) { - super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid Bytes value.`, { - metaMessages: ["Bytes values must be of type `Bytes`."] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Bytes.InvalidBytesTypeError" - }); + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); } }; - SizeOverflowError2 = class SizeOverflowError2 extends BaseError3 { - constructor({ givenSize, maxSize }) { - super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Bytes.SizeOverflowError" - }); + K512 = /* @__PURE__ */ (() => split([ + "0x428a2f98d728ae22", + "0x7137449123ef65cd", + "0xb5c0fbcfec4d3b2f", + "0xe9b5dba58189dbbc", + "0x3956c25bf348b538", + "0x59f111f1b605d019", + "0x923f82a4af194f9b", + "0xab1c5ed5da6d8118", + "0xd807aa98a3030242", + "0x12835b0145706fbe", + "0x243185be4ee4b28c", + "0x550c7dc3d5ffb4e2", + "0x72be5d74f27b896f", + "0x80deb1fe3b1696b1", + "0x9bdc06a725c71235", + "0xc19bf174cf692694", + "0xe49b69c19ef14ad2", + "0xefbe4786384f25e3", + "0x0fc19dc68b8cd5b5", + "0x240ca1cc77ac9c65", + "0x2de92c6f592b0275", + "0x4a7484aa6ea6e483", + "0x5cb0a9dcbd41fbd4", + "0x76f988da831153b5", + "0x983e5152ee66dfab", + "0xa831c66d2db43210", + "0xb00327c898fb213f", + "0xbf597fc7beef0ee4", + "0xc6e00bf33da88fc2", + "0xd5a79147930aa725", + "0x06ca6351e003826f", + "0x142929670a0e6e70", + "0x27b70a8546d22ffc", + "0x2e1b21385c26c926", + "0x4d2c6dfc5ac42aed", + "0x53380d139d95b3df", + "0x650a73548baf63de", + "0x766a0abb3c77b2a8", + "0x81c2c92e47edaee6", + "0x92722c851482353b", + "0xa2bfe8a14cf10364", + "0xa81a664bbc423001", + "0xc24b8b70d0f89791", + "0xc76c51a30654be30", + "0xd192e819d6ef5218", + "0xd69906245565a910", + "0xf40e35855771202a", + "0x106aa07032bbd1b8", + "0x19a4c116b8d2d0c8", + "0x1e376c085141ab53", + "0x2748774cdf8eeb99", + "0x34b0bcb5e19b48a8", + "0x391c0cb3c5c95a63", + "0x4ed8aa4ae3418acb", + "0x5b9cca4f7763e373", + "0x682e6ff3d6b2b8a3", + "0x748f82ee5defb2fc", + "0x78a5636f43172f60", + "0x84c87814a1f0ab72", + "0x8cc702081a6439ec", + "0x90befffa23631e28", + "0xa4506cebde82bde9", + "0xbef9a3f7b2c67915", + "0xc67178f2e372532b", + "0xca273eceea26619c", + "0xd186b8c721c0c207", + "0xeada7dd6cde0eb1e", + "0xf57d4f7fee6ed178", + "0x06f067aa72176fba", + "0x0a637dc5a2c898a6", + "0x113f9804bef90dae", + "0x1b710b35131c471b", + "0x28db77f523047d84", + "0x32caab7b40c72493", + "0x3c9ebe0a15c9bebc", + "0x431d67c49c100d4c", + "0x4cc5d4becb3e42b6", + "0x597f299cfc657e2a", + "0x5fcb6fab3ad6faec", + "0x6c44198c4a475817" + ].map((n) => BigInt(n))))(); + SHA512_Kh = /* @__PURE__ */ (() => K512[0])(); + SHA512_Kl = /* @__PURE__ */ (() => K512[1])(); + SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); + SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); + SHA512 = class SHA512 extends HashMD { + constructor(outputLen = 64) { + super(128, outputLen, 16, false); + this.Ah = SHA512_IV[0] | 0; + this.Al = SHA512_IV[1] | 0; + this.Bh = SHA512_IV[2] | 0; + this.Bl = SHA512_IV[3] | 0; + this.Ch = SHA512_IV[4] | 0; + this.Cl = SHA512_IV[5] | 0; + this.Dh = SHA512_IV[6] | 0; + this.Dl = SHA512_IV[7] | 0; + this.Eh = SHA512_IV[8] | 0; + this.El = SHA512_IV[9] | 0; + this.Fh = SHA512_IV[10] | 0; + this.Fl = SHA512_IV[11] | 0; + this.Gh = SHA512_IV[12] | 0; + this.Gl = SHA512_IV[13] | 0; + this.Hh = SHA512_IV[14] | 0; + this.Hl = SHA512_IV[15] | 0; } - }; - SliceOffsetOutOfBoundsError2 = class SliceOffsetOutOfBoundsError2 extends BaseError3 { - constructor({ offset, position, size: size4 }) { - super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size4}\`).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Bytes.SliceOffsetOutOfBoundsError" - }); + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; } - }; - SizeExceedsPaddingSizeError2 = class SizeExceedsPaddingSizeError2 extends BaseError3 { - constructor({ size: size4, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size4}\`) exceeds padding size (\`${targetSize}\`).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Bytes.SizeExceedsPaddingSizeError" - }); + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + for (let i = 0;i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32(offset += 4); + } + for (let i = 16;i < 80; i++) { + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7); + const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7); + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6); + const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6); + const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + for (let i = 0;i < 80; i++) { + const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41); + const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41); + const CHIh = Eh & Fh ^ ~Eh & Gh; + const CHIl = El & Fl ^ ~El & Gl; + const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39); + const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39); + const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; + const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = add3L(T1l, sigma0l, MAJl); + Ah = add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + clean(SHA512_W_H, SHA512_W_L); + } + destroy() { + clean(this.buffer); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } }; -}); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Hex.js -function assert2(value, options = {}) { - const { strict = false } = options; - if (!value) - throw new InvalidHexTypeError(value); - if (typeof value !== "string") - throw new InvalidHexTypeError(value); - if (strict) { - if (!/^0x[0-9a-fA-F]*$/.test(value)) - throw new InvalidHexValueError2(value); - } - if (!value.startsWith("0x")) - throw new InvalidHexValueError2(value); -} -function concat2(...values) { - return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`; -} -function from3(value) { - if (value instanceof Uint8Array) - return fromBytes(value); - if (Array.isArray(value)) - return fromBytes(new Uint8Array(value)); - return value; -} -function fromBoolean(value, options = {}) { - const hex = `0x${Number(value)}`; - if (typeof options.size === "number") { - assertSize3(hex, options.size); - return padLeft(hex, options.size); - } - return hex; -} -function fromBytes(value, options = {}) { - let string = ""; - for (let i = 0;i < value.length; i++) - string += hexes3[value[i]]; - const hex = `0x${string}`; - if (typeof options.size === "number") { - assertSize3(hex, options.size); - return padRight(hex, options.size); - } - return hex; -} -function fromNumber(value, options = {}) { - const { signed, size: size4 } = options; - const value_ = BigInt(value); - let maxValue; - if (size4) { - if (signed) - maxValue = (1n << BigInt(size4) * 8n - 1n) - 1n; - else - maxValue = 2n ** (BigInt(size4) * 8n) - 1n; - } else if (typeof value === "number") { - maxValue = BigInt(Number.MAX_SAFE_INTEGER); - } - const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0; - if (maxValue && value_ > maxValue || value_ < minValue) { - const suffix = typeof value === "bigint" ? "n" : ""; - throw new IntegerOutOfRangeError2({ - max: maxValue ? `${maxValue}${suffix}` : undefined, - min: `${minValue}${suffix}`, - signed, - size: size4, - value: `${value}${suffix}` - }); - } - const stringValue = (signed && value_ < 0 ? BigInt.asUintN(size4 * 8, BigInt(value_)) : value_).toString(16); - const hex = `0x${stringValue}`; - if (size4) - return padLeft(hex, size4); - return hex; -} -function fromString2(value, options = {}) { - return fromBytes(encoder4.encode(value), options); -} -function padLeft(value, size4) { - return pad3(value, { dir: "left", size: size4 }); -} -function padRight(value, size4) { - return pad3(value, { dir: "right", size: size4 }); -} -function slice3(value, start, end, options = {}) { - const { strict } = options; - assertStartOffset3(value, start); - const value_ = `0x${value.replace("0x", "").slice((start ?? 0) * 2, (end ?? value.length) * 2)}`; - if (strict) - assertEndOffset3(value_, start, end); - return value_; -} -function size3(value) { - return Math.ceil((value.length - 2) / 2); -} -function trimLeft2(value) { - return trim3(value, { dir: "left" }); -} -function toBigInt(hex, options = {}) { - const { signed } = options; - if (options.size) - assertSize3(hex, options.size); - const value = BigInt(hex); - if (!signed) - return value; - const size4 = (hex.length - 2) / 2; - const max_unsigned = (1n << BigInt(size4) * 8n) - 1n; - const max_signed = max_unsigned >> 1n; - if (value <= max_signed) - return value; - return value - max_unsigned - 1n; -} -function toNumber(hex, options = {}) { - const { signed, size: size4 } = options; - if (!signed && !size4) - return Number(hex); - return Number(toBigInt(hex, options)); -} -function validate2(value, options = {}) { - const { strict = false } = options; - try { - assert2(value, { strict }); - return true; - } catch { - return false; - } -} -var encoder4, hexes3, IntegerOutOfRangeError2, InvalidHexTypeError, InvalidHexValueError2, SizeOverflowError3, SliceOffsetOutOfBoundsError3, SizeExceedsPaddingSizeError3; -var init_Hex = __esm(() => { - init_Errors(); - init_hex(); - encoder4 = /* @__PURE__ */ new TextEncoder; - hexes3 = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); - IntegerOutOfRangeError2 = class IntegerOutOfRangeError2 extends BaseError3 { - constructor({ max, min, signed, size: size4, value }) { - super(`Number \`${value}\` is not in safe${size4 ? ` ${size4 * 8}-bit` : ""}${signed ? " signed" : " unsigned"} integer range ${max ? `(\`${min}\` to \`${max}\`)` : `(above \`${min}\`)`}`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.IntegerOutOfRangeError" - }); + SHA384 = class SHA384 extends SHA512 { + constructor() { + super(48); + this.Ah = SHA384_IV[0] | 0; + this.Al = SHA384_IV[1] | 0; + this.Bh = SHA384_IV[2] | 0; + this.Bl = SHA384_IV[3] | 0; + this.Ch = SHA384_IV[4] | 0; + this.Cl = SHA384_IV[5] | 0; + this.Dh = SHA384_IV[6] | 0; + this.Dl = SHA384_IV[7] | 0; + this.Eh = SHA384_IV[8] | 0; + this.El = SHA384_IV[9] | 0; + this.Fh = SHA384_IV[10] | 0; + this.Fl = SHA384_IV[11] | 0; + this.Gh = SHA384_IV[12] | 0; + this.Gl = SHA384_IV[13] | 0; + this.Hh = SHA384_IV[14] | 0; + this.Hl = SHA384_IV[15] | 0; } }; - InvalidHexTypeError = class InvalidHexTypeError extends BaseError3 { - constructor(value) { - super(`Value \`${typeof value === "object" ? stringify2(value) : value}\` of type \`${typeof value}\` is an invalid hex type.`, { - metaMessages: ['Hex types must be represented as `"0x${string}"`.'] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.InvalidHexTypeError" - }); + sha256 = /* @__PURE__ */ createHasher(() => new SHA256); + sha512 = /* @__PURE__ */ createHasher(() => new SHA512); + sha384 = /* @__PURE__ */ createHasher(() => new SHA384); +}); + +// ../viem/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/hmac.js +var HMAC, hmac = (hash2, key, message) => new HMAC(hash2, key).update(message).digest(); +var init_hmac = __esm(() => { + init_utils2(); + HMAC = class HMAC extends Hash { + constructor(hash2, _key) { + super(); + this.finished = false; + this.destroyed = false; + ahash(hash2); + const key = toBytes2(_key); + this.iHash = hash2.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad4 = new Uint8Array(blockLen); + pad4.set(key.length > blockLen ? hash2.create().update(key).digest() : key); + for (let i = 0;i < pad4.length; i++) + pad4[i] ^= 54; + this.iHash.update(pad4); + this.oHash = hash2.create(); + for (let i = 0;i < pad4.length; i++) + pad4[i] ^= 54 ^ 92; + this.oHash.update(pad4); + clean(pad4); } - }; - InvalidHexValueError2 = class InvalidHexValueError2 extends BaseError3 { - constructor(value) { - super(`Value \`${value}\` is an invalid hex value.`, { - metaMessages: [ - 'Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).' - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.InvalidHexValueError" - }); + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; } - }; - SizeOverflowError3 = class SizeOverflowError3 extends BaseError3 { - constructor({ givenSize, maxSize }) { - super(`Size cannot exceed \`${maxSize}\` bytes. Given size: \`${givenSize}\` bytes.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.SizeOverflowError" - }); + digestInto(out) { + aexists(this); + abytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); } - }; - SliceOffsetOutOfBoundsError3 = class SliceOffsetOutOfBoundsError3 extends BaseError3 { - constructor({ offset, position, size: size4 }) { - super(`Slice ${position === "start" ? "starting" : "ending"} at offset \`${offset}\` is out-of-bounds (size: \`${size4}\`).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.SliceOffsetOutOfBoundsError" - }); + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; } - }; - SizeExceedsPaddingSizeError3 = class SizeExceedsPaddingSizeError3 extends BaseError3 { - constructor({ size: size4, targetSize, type }) { - super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (\`${size4}\`) exceeds padding size (\`${targetSize}\`).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Hex.SizeExceedsPaddingSizeError" - }); + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + clone() { + return this._cloneInto(); + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); } }; + hmac.create = (hash2, key) => new HMAC(hash2, key); }); -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Withdrawal.js -function toRpc(withdrawal) { - return { - address: withdrawal.address, - amount: fromNumber(withdrawal.amount), - index: fromNumber(withdrawal.index), - validatorIndex: fromNumber(withdrawal.validatorIndex) - }; +// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/modular.js +function mod(a, b) { + const result = a % b; + return result >= _0n3 ? result : b + result; } -var init_Withdrawal = __esm(() => { - init_Hex(); -}); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/BlockOverrides.js -function toRpc2(blockOverrides) { - return { - ...typeof blockOverrides.baseFeePerGas === "bigint" && { - baseFeePerGas: fromNumber(blockOverrides.baseFeePerGas) - }, - ...typeof blockOverrides.blobBaseFee === "bigint" && { - blobBaseFee: fromNumber(blockOverrides.blobBaseFee) - }, - ...typeof blockOverrides.feeRecipient === "string" && { - feeRecipient: blockOverrides.feeRecipient - }, - ...typeof blockOverrides.gasLimit === "bigint" && { - gasLimit: fromNumber(blockOverrides.gasLimit) - }, - ...typeof blockOverrides.number === "bigint" && { - number: fromNumber(blockOverrides.number) - }, - ...typeof blockOverrides.prevRandao === "bigint" && { - prevRandao: fromNumber(blockOverrides.prevRandao) - }, - ...typeof blockOverrides.time === "bigint" && { - time: fromNumber(blockOverrides.time) - }, - ...blockOverrides.withdrawals && { - withdrawals: blockOverrides.withdrawals.map(toRpc) +function pow2(x, power, modulo) { + let res = x; + while (power-- > _0n3) { + res *= res; + res %= modulo; + } + return res; +} +function invert(number, modulo) { + if (number === _0n3) + throw new Error("invert: expected non-zero number"); + if (modulo <= _0n3) + throw new Error("invert: expected positive modulus, got " + modulo); + let a = mod(number, modulo); + let b = modulo; + let x = _0n3, y = _1n3, u = _1n3, v = _0n3; + while (a !== _0n3) { + const q = b / a; + const r = b % a; + const m = x - u * q; + const n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n3) + throw new Error("invert: does not exist"); + return mod(x, modulo); +} +function sqrt3mod4(Fp, n) { + const p1div4 = (Fp.ORDER + _1n3) / _4n; + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; +} +function sqrt5mod8(Fp, n) { + const p5div8 = (Fp.ORDER - _5n) / _8n; + const n2 = Fp.mul(n, _2n2); + const v = Fp.pow(n2, p5div8); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n2), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) + throw new Error("Cannot find square root"); + return root; +} +function tonelliShanks(P) { + if (P < BigInt(3)) + throw new Error("sqrt is not defined for small field"); + let Q = P - _1n3; + let S = 0; + while (Q % _2n2 === _0n3) { + Q /= _2n2; + S++; + } + let Z = _2n2; + const _Fp = Field(P); + while (FpLegendre(_Fp, Z) === 1) { + if (Z++ > 1000) + throw new Error("Cannot find square root: probably non-prime P"); + } + if (S === 1) + return sqrt3mod4; + let cc = _Fp.pow(Z, Q); + const Q1div2 = (Q + _1n3) / _2n2; + return function tonelliSlow(Fp, n) { + if (Fp.is0(n)) + return n; + if (FpLegendre(Fp, n) !== 1) + throw new Error("Cannot find square root"); + let M = S; + let c = Fp.mul(Fp.ONE, cc); + let t = Fp.pow(n, Q); + let R = Fp.pow(n, Q1div2); + while (!Fp.eql(t, Fp.ONE)) { + if (Fp.is0(t)) + return Fp.ZERO; + let i = 1; + let t_tmp = Fp.sqr(t); + while (!Fp.eql(t_tmp, Fp.ONE)) { + i++; + t_tmp = Fp.sqr(t_tmp); + if (i === M) + throw new Error("Cannot find square root"); + } + const exponent = _1n3 << BigInt(M - i - 1); + const b = Fp.pow(c, exponent); + M = i; + c = Fp.sqr(b); + t = Fp.mul(t, c); + R = Fp.mul(R, b); } + return R; }; } -var init_BlockOverrides = __esm(() => { - init_Hex(); - init_Withdrawal(); -}); - -// ../viem/src/_esm/constants/abis.js -var multicall3Abi, batchGatewayAbi, universalResolverErrors, universalResolverResolveAbi, universalResolverReverseAbi, textResolverAbi, addressResolverAbi, erc1271Abi, erc6492SignatureValidatorAbi, erc20Abi; -var init_abis = __esm(() => { - multicall3Abi = [ - { - inputs: [ - { - components: [ - { - name: "target", - type: "address" - }, - { - name: "allowFailure", - type: "bool" - }, - { - name: "callData", - type: "bytes" - } - ], - name: "calls", - type: "tuple[]" - } - ], - name: "aggregate3", - outputs: [ - { - components: [ - { - name: "success", - type: "bool" - }, - { - name: "returnData", - type: "bytes" - } - ], - name: "returnData", - type: "tuple[]" - } - ], - stateMutability: "view", - type: "function" +function FpSqrt(P) { + if (P % _4n === _3n) + return sqrt3mod4; + if (P % _8n === _5n) + return sqrt5mod8; + return tonelliShanks(P); +} +function validateField(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger" + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + return validateObject(field, opts); +} +function FpPow(Fp, num, power) { + if (power < _0n3) + throw new Error("invalid exponent, negatives unsupported"); + if (power === _0n3) + return Fp.ONE; + if (power === _1n3) + return num; + let p = Fp.ONE; + let d = num; + while (power > _0n3) { + if (power & _1n3) + p = Fp.mul(p, d); + d = Fp.sqr(d); + power >>= _1n3; + } + return p; +} +function FpInvertBatch(Fp, nums, passZero = false) { + const inverted = new Array(nums.length).fill(passZero ? Fp.ZERO : undefined); + const multipliedAcc = nums.reduce((acc, num, i) => { + if (Fp.is0(num)) + return acc; + inverted[i] = acc; + return Fp.mul(acc, num); + }, Fp.ONE); + const invertedAcc = Fp.inv(multipliedAcc); + nums.reduceRight((acc, num, i) => { + if (Fp.is0(num)) + return acc; + inverted[i] = Fp.mul(acc, inverted[i]); + return Fp.mul(acc, num); + }, invertedAcc); + return inverted; +} +function FpLegendre(Fp, n) { + const p1mod2 = (Fp.ORDER - _1n3) / _2n2; + const powered = Fp.pow(n, p1mod2); + const yes = Fp.eql(powered, Fp.ONE); + const zero = Fp.eql(powered, Fp.ZERO); + const no = Fp.eql(powered, Fp.neg(Fp.ONE)); + if (!yes && !zero && !no) + throw new Error("invalid Legendre symbol result"); + return yes ? 1 : zero ? 0 : -1; +} +function nLength(n, nBitLength) { + if (nBitLength !== undefined) + anumber(nBitLength); + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +function Field(ORDER, bitLen2, isLE2 = false, redef = {}) { + if (ORDER <= _0n3) + throw new Error("invalid field: expected ORDER > 0, got " + ORDER); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen2); + if (BYTES > 2048) + throw new Error("invalid field: expected ORDER of <= 2048 bytes"); + let sqrtP; + const f = Object.freeze({ + ORDER, + isLE: isLE2, + BITS, + BYTES, + MASK: bitMask(BITS), + ZERO: _0n3, + ONE: _1n3, + create: (num) => mod(num, ORDER), + isValid: (num) => { + if (typeof num !== "bigint") + throw new Error("invalid field element: expected bigint, got " + typeof num); + return _0n3 <= num && num < ORDER; }, - { - inputs: [ - { - name: "addr", - type: "address" - } - ], - name: "getEthBalance", - outputs: [ - { - name: "balance", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" + is0: (num) => num === _0n3, + isOdd: (num) => (num & _1n3) === _1n3, + neg: (num) => mod(-num, ORDER), + eql: (lhs, rhs) => lhs === rhs, + sqr: (num) => mod(num * num, ORDER), + add: (lhs, rhs) => mod(lhs + rhs, ORDER), + sub: (lhs, rhs) => mod(lhs - rhs, ORDER), + mul: (lhs, rhs) => mod(lhs * rhs, ORDER), + pow: (num, power) => FpPow(f, num, power), + div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), + sqrN: (num) => num * num, + addN: (lhs, rhs) => lhs + rhs, + subN: (lhs, rhs) => lhs - rhs, + mulN: (lhs, rhs) => lhs * rhs, + inv: (num) => invert(num, ORDER), + sqrt: redef.sqrt || ((n) => { + if (!sqrtP) + sqrtP = FpSqrt(ORDER); + return sqrtP(f, n); + }), + toBytes: (num) => isLE2 ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), + fromBytes: (bytes) => { + if (bytes.length !== BYTES) + throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); + return isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); }, - { - inputs: [], - name: "getCurrentBlockTimestamp", - outputs: [ - { - internalType: "uint256", - name: "timestamp", - type: "uint256" - } - ], - stateMutability: "view", - type: "function" - } + invertBatch: (lst) => FpInvertBatch(f, lst), + cmov: (a, b, c) => c ? b : a + }); + return Object.freeze(f); +} +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== "bigint") + throw new Error("field order must be bigint"); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +function mapHashToField(key, fieldOrder, isLE2 = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + if (len < 16 || len < minLen || len > 1024) + throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); + const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key); + const reduced = mod(num, fieldOrder - _1n3) + _1n3; + return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} +var _0n3, _1n3, _2n2, _3n, _4n, _5n, _8n, FIELD_FIELDS; +var init_modular = __esm(() => { + init_utils2(); + init_utils3(); + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + _0n3 = BigInt(0); + _1n3 = BigInt(1); + _2n2 = /* @__PURE__ */ BigInt(2); + _3n = /* @__PURE__ */ BigInt(3); + _4n = /* @__PURE__ */ BigInt(4); + _5n = /* @__PURE__ */ BigInt(5); + _8n = /* @__PURE__ */ BigInt(8); + FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" ]; - batchGatewayAbi = [ - { - name: "query", - type: "function", - stateMutability: "view", - inputs: [ - { - type: "tuple[]", - name: "queries", - components: [ - { - type: "address", - name: "sender" - }, - { - type: "string[]", - name: "urls" - }, - { - type: "bytes", - name: "data" - } - ] - } - ], - outputs: [ - { - type: "bool[]", - name: "failures" - }, - { - type: "bytes[]", - name: "responses" - } - ] +}); + +// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/curve.js +function constTimeNegate(condition, item) { + const neg = item.negate(); + return condition ? neg : item; +} +function validateW(W, bits) { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); +} +function calcWOpts(W, scalarBits) { + validateW(W, scalarBits); + const windows = Math.ceil(scalarBits / W) + 1; + const windowSize = 2 ** (W - 1); + const maxNumber = 2 ** W; + const mask = bitMask(W); + const shiftBy = BigInt(W); + return { windows, windowSize, mask, maxNumber, shiftBy }; +} +function calcOffsets(n, window2, wOpts) { + const { windowSize, mask, maxNumber, shiftBy } = wOpts; + let wbits = Number(n & mask); + let nextN = n >> shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + nextN += _1n4; + } + const offsetStart = window2 * windowSize; + const offset = offsetStart + Math.abs(wbits) - 1; + const isZero = wbits === 0; + const isNeg = wbits < 0; + const isNegF = window2 % 2 !== 0; + const offsetF = offsetStart; + return { nextN, offset, isZero, isNeg, isNegF, offsetF }; +} +function validateMSMPoints(points, c) { + if (!Array.isArray(points)) + throw new Error("array expected"); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error("invalid point at index " + i); + }); +} +function validateMSMScalars(scalars, field) { + if (!Array.isArray(scalars)) + throw new Error("array of scalars expected"); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error("invalid scalar at index " + i); + }); +} +function getW(P) { + return pointWindowSizes.get(P) || 1; +} +function wNAF(c, bits) { + return { + constTimeNegate, + hasPrecomputes(elm) { + return getW(elm) !== 1; }, - { - name: "HttpError", - type: "error", - inputs: [ - { - type: "uint16", - name: "status" - }, - { - type: "string", - name: "message" - } - ] - } - ]; - universalResolverErrors = [ - { - inputs: [ - { - name: "dns", - type: "bytes" - } - ], - name: "DNSDecodingFailed", - type: "error" + unsafeLadder(elm, n, p = c.ZERO) { + let d = elm; + while (n > _0n4) { + if (n & _1n4) + p = p.add(d); + d = d.double(); + n >>= _1n4; + } + return p; }, - { - inputs: [ - { - name: "ens", - type: "string" + precomputeWindow(elm, W) { + const { windows, windowSize } = calcWOpts(W, bits); + const points = []; + let p = elm; + let base = p; + for (let window2 = 0;window2 < windows; window2++) { + base = p; + points.push(base); + for (let i = 1;i < windowSize; i++) { + base = base.add(p); + points.push(base); } - ], - name: "DNSEncodingFailed", - type: "error" - }, - { - inputs: [], - name: "EmptyAddress", - type: "error" + p = base.double(); + } + return points; }, - { - inputs: [ - { - name: "status", - type: "uint16" - }, - { - name: "message", - type: "string" + wNAF(W, precomputes, n) { + let p = c.ZERO; + let f = c.BASE; + const wo = calcWOpts(W, bits); + for (let window2 = 0;window2 < wo.windows; window2++) { + const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window2, wo); + n = nextN; + if (isZero) { + f = f.add(constTimeNegate(isNegF, precomputes[offsetF])); + } else { + p = p.add(constTimeNegate(isNeg, precomputes[offset])); } - ], - name: "HttpError", - type: "error" - }, - { - inputs: [], - name: "InvalidBatchGatewayResponse", - type: "error" + } + return { p, f }; }, - { - inputs: [ - { - name: "errorData", - type: "bytes" + wNAFUnsafe(W, precomputes, n, acc = c.ZERO) { + const wo = calcWOpts(W, bits); + for (let window2 = 0;window2 < wo.windows; window2++) { + if (n === _0n4) + break; + const { nextN, offset, isZero, isNeg } = calcOffsets(n, window2, wo); + n = nextN; + if (isZero) { + continue; + } else { + const item = precomputes[offset]; + acc = acc.add(isNeg ? item.negate() : item); } - ], - name: "ResolverError", - type: "error" + } + return acc; }, - { - inputs: [ - { - name: "name", - type: "bytes" - }, - { - name: "resolver", - type: "address" - } - ], - name: "ResolverNotContract", - type: "error" + getPrecomputes(W, P, transform) { + let comp = pointPrecomputes.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) + pointPrecomputes.set(P, transform(comp)); + } + return comp; }, - { - inputs: [ - { - name: "name", - type: "bytes" - } - ], - name: "ResolverNotFound", - type: "error" + wNAFCached(P, n, transform) { + const W = getW(P); + return this.wNAF(W, this.getPrecomputes(W, P, transform), n); }, - { - inputs: [ - { - name: "primary", - type: "string" - }, - { - name: "primaryAddress", - type: "bytes" - } - ], - name: "ReverseAddressMismatch", - type: "error" + wNAFCachedUnsafe(P, n, transform, prev) { + const W = getW(P); + if (W === 1) + return this.unsafeLadder(P, n, prev); + return this.wNAFUnsafe(W, this.getPrecomputes(W, P, transform), n, prev); }, - { - inputs: [ - { - internalType: "bytes4", - name: "selector", - type: "bytes4" - } - ], - name: "UnsupportedResolverProfile", - type: "error" - } - ]; - universalResolverResolveAbi = [ - ...universalResolverErrors, - { - name: "resolveWithGateways", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes" }, - { name: "data", type: "bytes" }, - { name: "gateways", type: "string[]" } - ], - outputs: [ - { name: "", type: "bytes" }, - { name: "address", type: "address" } - ] - } - ]; - universalResolverReverseAbi = [ - ...universalResolverErrors, - { - name: "reverseWithGateways", - type: "function", - stateMutability: "view", - inputs: [ - { type: "bytes", name: "reverseName" }, - { type: "uint256", name: "coinType" }, - { type: "string[]", name: "gateways" } - ], - outputs: [ - { type: "string", name: "resolvedName" }, - { type: "address", name: "resolver" }, - { type: "address", name: "reverseResolver" } - ] - } - ]; - textResolverAbi = [ - { - name: "text", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes32" }, - { name: "key", type: "string" } - ], - outputs: [{ name: "", type: "string" }] + setWindowSize(P, W) { + validateW(W, bits); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); } - ]; - addressResolverAbi = [ - { - name: "addr", - type: "function", - stateMutability: "view", - inputs: [{ name: "name", type: "bytes32" }], - outputs: [{ name: "", type: "address" }] - }, - { - name: "addr", - type: "function", - stateMutability: "view", - inputs: [ - { name: "name", type: "bytes32" }, - { name: "coinType", type: "uint256" } - ], - outputs: [{ name: "", type: "bytes" }] + }; +} +function pippenger(c, fieldN, points, scalars) { + validateMSMPoints(points, c); + validateMSMScalars(scalars, fieldN); + const plength = points.length; + const slength = scalars.length; + if (plength !== slength) + throw new Error("arrays of points and scalars must have equal length"); + const zero = c.ZERO; + const wbits = bitLen(BigInt(plength)); + let windowSize = 1; + if (wbits > 12) + windowSize = wbits - 3; + else if (wbits > 4) + windowSize = wbits - 2; + else if (wbits > 0) + windowSize = 2; + const MASK = bitMask(windowSize); + const buckets = new Array(Number(MASK) + 1).fill(zero); + const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; + let sum = zero; + for (let i = lastBits;i >= 0; i -= windowSize) { + buckets.fill(zero); + for (let j = 0;j < slength; j++) { + const scalar = scalars[j]; + const wbits2 = Number(scalar >> BigInt(i) & MASK); + buckets[wbits2] = buckets[wbits2].add(points[j]); } - ]; - erc1271Abi = [ - { - name: "isValidSignature", - type: "function", - stateMutability: "view", - inputs: [ - { name: "hash", type: "bytes32" }, - { name: "signature", type: "bytes" } - ], - outputs: [{ name: "", type: "bytes4" }] + let resI = zero; + for (let j = buckets.length - 1, sumI = zero;j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); } - ]; - erc6492SignatureValidatorAbi = [ - { - inputs: [ - { - name: "_signer", - type: "address" - }, - { - name: "_hash", - type: "bytes32" - }, - { - name: "_signature", - type: "bytes" - } - ], - stateMutability: "nonpayable", - type: "constructor" - }, - { - inputs: [ - { - name: "_signer", - type: "address" - }, - { - name: "_hash", - type: "bytes32" - }, - { - name: "_signature", - type: "bytes" - } - ], - outputs: [ - { - type: "bool" - } - ], - stateMutability: "nonpayable", - type: "function", - name: "isValidSig" - } - ]; - erc20Abi = [ - { - type: "event", - name: "Approval", - inputs: [ - { - indexed: true, - name: "owner", - type: "address" - }, - { - indexed: true, - name: "spender", - type: "address" - }, - { - indexed: false, - name: "value", - type: "uint256" - } - ] - }, - { - type: "event", - name: "Transfer", - inputs: [ - { - indexed: true, - name: "from", - type: "address" - }, - { - indexed: true, - name: "to", - type: "address" - }, - { - indexed: false, - name: "value", - type: "uint256" - } - ] - }, - { - type: "function", - name: "allowance", - stateMutability: "view", - inputs: [ - { - name: "owner", - type: "address" - }, - { - name: "spender", - type: "address" - } - ], - outputs: [ - { - type: "uint256" - } - ] - }, - { - type: "function", - name: "approve", - stateMutability: "nonpayable", - inputs: [ - { - name: "spender", - type: "address" - }, - { - name: "amount", - type: "uint256" - } - ], - outputs: [ - { - type: "bool" - } - ] - }, - { - type: "function", - name: "balanceOf", - stateMutability: "view", - inputs: [ - { - name: "account", - type: "address" - } - ], - outputs: [ - { - type: "uint256" - } - ] - }, - { - type: "function", - name: "decimals", - stateMutability: "view", - inputs: [], - outputs: [ - { - type: "uint8" - } - ] - }, - { - type: "function", - name: "name", - stateMutability: "view", - inputs: [], - outputs: [ - { - type: "string" - } - ] - }, - { - type: "function", - name: "symbol", - stateMutability: "view", - inputs: [], - outputs: [ - { - type: "string" - } - ] - }, - { - type: "function", - name: "totalSupply", - stateMutability: "view", - inputs: [], - outputs: [ - { - type: "uint256" - } - ] - }, - { - type: "function", - name: "transfer", - stateMutability: "nonpayable", - inputs: [ - { - name: "recipient", - type: "address" - }, - { - name: "amount", - type: "uint256" - } - ], - outputs: [ - { - type: "bool" - } - ] - }, - { - type: "function", - name: "transferFrom", - stateMutability: "nonpayable", - inputs: [ - { - name: "sender", - type: "address" - }, - { - name: "recipient", - type: "address" - }, - { - name: "amount", - type: "uint256" - } - ], - outputs: [ - { - type: "bool" - } - ] - } - ]; + sum = sum.add(resI); + if (i !== 0) + for (let j = 0;j < windowSize; j++) + sum = sum.double(); + } + return sum; +} +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field" + }, { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger" + }); + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ p: curve.Fp.ORDER } + }); +} +var _0n4, _1n4, pointPrecomputes, pointWindowSizes; +var init_curve = __esm(() => { + init_modular(); + init_utils3(); + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + _0n4 = BigInt(0); + _1n4 = BigInt(1); + pointPrecomputes = new WeakMap; + pointWindowSizes = new WeakMap; }); -// ../viem/src/_esm/constants/contract.js -var aggregate3Signature = "0x82ad56cb"; - -// ../viem/src/_esm/constants/contracts.js -var deploylessCallViaBytecodeBytecode = "0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe", deploylessCallViaFactoryBytecode = "0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe", erc6492SignatureValidatorByteCode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572", multicall3Bytecode = "0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033"; - -// ../viem/src/_esm/errors/chain.js -var ChainDoesNotSupportContract, ChainMismatchError, ChainNotFoundError, ClientChainNotConfiguredError, InvalidChainIdError; -var init_chain = __esm(() => { - init_base(); - ChainDoesNotSupportContract = class ChainDoesNotSupportContract extends BaseError2 { - constructor({ blockNumber, chain, contract }) { - super(`Chain "${chain.name}" does not support contract "${contract.name}".`, { - metaMessages: [ - "This could be due to any of the following:", - ...blockNumber && contract.blockCreated && contract.blockCreated > blockNumber ? [ - `- The contract "${contract.name}" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).` - ] : [ - `- The chain does not have the contract "${contract.name}" configured.` - ] - ], - name: "ChainDoesNotSupportContract" - }); - } - }; - ChainMismatchError = class ChainMismatchError extends BaseError2 { - constructor({ chain, currentChainId }) { - super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} – ${chain.name}).`, { - metaMessages: [ - `Current Chain ID: ${currentChainId}`, - `Expected Chain ID: ${chain.id} – ${chain.name}` - ], - name: "ChainMismatchError" - }); - } - }; - ChainNotFoundError = class ChainNotFoundError extends BaseError2 { - constructor() { - super([ - "No chain was provided to the request.", - "Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient." - ].join(` -`), { - name: "ChainNotFoundError" - }); - } - }; - ClientChainNotConfiguredError = class ClientChainNotConfiguredError extends BaseError2 { - constructor() { - super("No chain was provided to the Client.", { - name: "ClientChainNotConfiguredError" - }); +// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/weierstrass.js +function validateSigVerOpts(opts) { + if (opts.lowS !== undefined) + abool("lowS", opts.lowS); + if (opts.prehash !== undefined) + abool("prehash", opts.prehash); +} +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: "field", + b: "field" + }, { + allowInfinityPoint: "boolean", + allowedPrivateKeyLengths: "array", + clearCofactor: "function", + fromBytes: "function", + isTorsionFree: "function", + toBytes: "function", + wrapPrivateKey: "boolean" + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error("invalid endo: CURVE.a must be 0"); } - }; - InvalidChainIdError = class InvalidChainIdError extends BaseError2 { - constructor({ chainId }) { - super(typeof chainId === "number" ? `Chain ID "${chainId}" is invalid.` : "Chain ID is invalid.", { name: "InvalidChainIdError" }); + if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { + throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function'); } - }; -}); - -// ../viem/src/_esm/utils/abi/encodeDeployData.js -function encodeDeployData(parameters) { - const { abi, args, bytecode } = parameters; - if (!args || args.length === 0) - return bytecode; - const description = abi.find((x) => ("type" in x) && x.type === "constructor"); - if (!description) - throw new AbiConstructorNotFoundError({ docsPath: docsPath5 }); - if (!("inputs" in description)) - throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); - if (!description.inputs || description.inputs.length === 0) - throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath5 }); - const data = encodeAbiParameters(description.inputs, args); - return concatHex([bytecode, data]); + } + return Object.freeze({ ...opts }); } -var docsPath5 = "/docs/contract/encodeDeployData"; -var init_encodeDeployData = __esm(() => { - init_abi(); - init_encodeAbiParameters(); -}); - -// ../viem/src/_esm/utils/chain/getChainContractAddress.js -function getChainContractAddress({ blockNumber, chain, contract: name }) { - const contract = chain?.contracts?.[name]; - if (!contract) - throw new ChainDoesNotSupportContract({ - chain, - contract: { name } - }); - if (blockNumber && contract.blockCreated && contract.blockCreated > blockNumber) - throw new ChainDoesNotSupportContract({ - blockNumber, - chain, - contract: { - name, - blockCreated: contract.blockCreated - } - }); - return contract.address; +function numToSizedHex(num, size5) { + return bytesToHex2(numberToBytesBE(num, size5)); } -var init_getChainContractAddress = __esm(() => { - init_chain(); -}); - -// ../viem/src/_esm/utils/errors/getCallError.js -function getCallError(err, { docsPath: docsPath6, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new CallExecutionError(cause, { - docsPath: docsPath6, - ...args +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; + const Fn = Field(CURVE.n, CURVE.nBitLength); + const toBytes3 = CURVE.toBytes || ((_c, point, _isCompressed) => { + const a = point.toAffine(); + return concatBytes3(Uint8Array.from([4]), Fp.toBytes(a.x), Fp.toBytes(a.y)); }); -} -var init_getCallError = __esm(() => { - init_contract(); - init_node(); - init_getNodeError(); -}); - -// ../viem/src/_esm/utils/promise/withResolvers.js -function withResolvers() { - let resolve = () => { - return; - }; - let reject = () => { - return; - }; - const promise = new Promise((resolve_, reject_) => { - resolve = resolve_; - reject = reject_; + const fromBytes2 = CURVE.fromBytes || ((bytes) => { + const tail = bytes.subarray(1); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; }); - return { promise, resolve, reject }; -} - -// ../viem/src/_esm/utils/promise/createBatchScheduler.js -function createBatchScheduler({ fn, id, shouldSplitBatch, wait = 0, sort }) { - const exec = async () => { - const scheduler = getScheduler(); - flush(); - const args = scheduler.map(({ args: args2 }) => args2); - if (args.length === 0) - return; - fn(args).then((data) => { - if (sort && Array.isArray(data)) - data.sort(sort); - for (let i = 0;i < scheduler.length; i++) { - const { resolve } = scheduler[i]; - resolve?.([data[i], data]); - } - }).catch((err) => { - for (let i = 0;i < scheduler.length; i++) { - const { reject } = scheduler[i]; - reject?.(err); - } - }); - }; - const flush = () => schedulerCache.delete(id); - const getBatchedArgs = () => getScheduler().map(({ args }) => args); - const getScheduler = () => schedulerCache.get(id) || []; - const setScheduler = (item) => schedulerCache.set(id, [...getScheduler(), item]); - return { - flush, - async schedule(args) { - const { promise, resolve, reject } = withResolvers(); - const split2 = shouldSplitBatch?.([...getBatchedArgs(), args]); - if (split2) - exec(); - const hasActiveScheduler = getScheduler().length > 0; - if (hasActiveScheduler) { - setScheduler({ args, resolve, reject }); - return promise; - } - setScheduler({ args, resolve, reject }); - setTimeout(exec, wait); - return promise; + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); + const x3 = Fp.mul(x2, x); + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); + } + function isValidXY(x, y) { + const left = Fp.sqr(y); + const right = weierstrassEquation(x); + return Fp.eql(left, right); + } + if (!isValidXY(CURVE.Gx, CURVE.Gy)) + throw new Error("bad curve params: generator point"); + const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2); + const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27)); + if (Fp.is0(Fp.add(_4a3, _27b2))) + throw new Error("bad curve params: a or b"); + function isWithinCurveOrder(num) { + return inRange(num, _1n5, CURVE.n); + } + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n: N } = CURVE; + if (lengths && typeof key !== "bigint") { + if (isBytes2(key)) + key = bytesToHex2(key); + if (typeof key !== "string" || !lengths.includes(key.length)) + throw new Error("invalid private key"); + key = key.padStart(nByteLength * 2, "0"); } - }; -} -var schedulerCache; -var init_createBatchScheduler = __esm(() => { - schedulerCache = /* @__PURE__ */ new Map; -}); - -// ../viem/src/_esm/errors/ccip.js -var OffchainLookupError, OffchainLookupResponseMalformedError, OffchainLookupSenderMismatchError; -var init_ccip = __esm(() => { - init_base(); - OffchainLookupError = class OffchainLookupError extends BaseError2 { - constructor({ callbackSelector, cause, data, extraData, sender, urls }) { - super(cause.shortMessage || "An error occurred while fetching for an offchain result.", { - cause, - metaMessages: [ - ...cause.metaMessages || [], - cause.metaMessages?.length ? "" : [], - "Offchain Gateway Call:", - urls && [ - " Gateway URL(s):", - ...urls.map((url) => ` ${getUrl(url)}`) - ], - ` Sender: ${sender}`, - ` Data: ${data}`, - ` Callback selector: ${callbackSelector}`, - ` Extra data: ${extraData}` - ].flat(), - name: "OffchainLookupError" - }); - } - }; - OffchainLookupResponseMalformedError = class OffchainLookupResponseMalformedError extends BaseError2 { - constructor({ result, url }) { - super("Offchain gateway response is malformed. Response data must be a hex value.", { - metaMessages: [ - `Gateway URL: ${getUrl(url)}`, - `Response: ${stringify(result)}` - ], - name: "OffchainLookupResponseMalformedError" - }); - } - }; - OffchainLookupSenderMismatchError = class OffchainLookupSenderMismatchError extends BaseError2 { - constructor({ sender, to }) { - super("Reverted sender address does not match target contract address (`to`).", { - metaMessages: [ - `Contract address: ${to}`, - `OffchainLookup sender address: ${sender}` - ], - name: "OffchainLookupSenderMismatchError" - }); + let num; + try { + num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + } catch (error) { + throw new Error("invalid private key, expected hex or " + nByteLength + " bytes, got " + typeof key); } - }; -}); - -// ../viem/src/_esm/utils/abi/decodeFunctionData.js -function decodeFunctionData(parameters) { - const { abi, data } = parameters; - const signature = slice(data, 0, 4); - const description = abi.find((x) => x.type === "function" && signature === toFunctionSelector(formatAbiItem2(x))); - if (!description) - throw new AbiFunctionSignatureNotFoundError(signature, { - docsPath: "/docs/contract/decodeFunctionData" - }); - return { - functionName: description.name, - args: "inputs" in description && description.inputs && description.inputs.length > 0 ? decodeAbiParameters(description.inputs, slice(data, 4)) : undefined - }; -} -var init_decodeFunctionData = __esm(() => { - init_abi(); - init_slice(); - init_toFunctionSelector(); - init_decodeAbiParameters(); - init_formatAbiItem2(); -}); - -// ../viem/src/_esm/utils/abi/encodeErrorResult.js -function encodeErrorResult(parameters) { - const { abi, errorName, args } = parameters; - let abiItem = abi[0]; - if (errorName) { - const item = getAbiItem({ abi, args, name: errorName }); - if (!item) - throw new AbiErrorNotFoundError(errorName, { docsPath: docsPath6 }); - abiItem = item; - } - if (abiItem.type !== "error") - throw new AbiErrorNotFoundError(undefined, { docsPath: docsPath6 }); - const definition = formatAbiItem2(abiItem); - const signature = toFunctionSelector(definition); - let data = "0x"; - if (args && args.length > 0) { - if (!abiItem.inputs) - throw new AbiErrorInputsNotFoundError(abiItem.name, { docsPath: docsPath6 }); - data = encodeAbiParameters(abiItem.inputs, args); + if (wrapPrivateKey) + num = mod(num, N); + aInRange("private key", num, _1n5, N); + return num; } - return concatHex([signature, data]); -} -var docsPath6 = "/docs/contract/encodeErrorResult"; -var init_encodeErrorResult = __esm(() => { - init_abi(); - init_toFunctionSelector(); - init_encodeAbiParameters(); - init_formatAbiItem2(); - init_getAbiItem(); -}); - -// ../viem/src/_esm/utils/abi/encodeFunctionResult.js -function encodeFunctionResult(parameters) { - const { abi, functionName, result } = parameters; - let abiItem = abi[0]; - if (functionName) { - const item = getAbiItem({ abi, name: functionName }); - if (!item) - throw new AbiFunctionNotFoundError(functionName, { docsPath: docsPath7 }); - abiItem = item; + function aprjpoint(other) { + if (!(other instanceof Point)) + throw new Error("ProjectivePoint expected"); } - if (abiItem.type !== "function") - throw new AbiFunctionNotFoundError(undefined, { docsPath: docsPath7 }); - if (!abiItem.outputs) - throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath: docsPath7 }); - const values = (() => { - if (abiItem.outputs.length === 0) - return []; - if (abiItem.outputs.length === 1) - return [result]; - if (Array.isArray(result)) - return result; - throw new InvalidArrayError(result); - })(); - return encodeAbiParameters(abiItem.outputs, values); -} -var docsPath7 = "/docs/contract/encodeFunctionResult"; -var init_encodeFunctionResult = __esm(() => { - init_abi(); - init_encodeAbiParameters(); - init_getAbiItem(); -}); - -// ../viem/src/_esm/utils/ens/localBatchGatewayRequest.js -async function localBatchGatewayRequest(parameters) { - const { data, ccipRequest } = parameters; - const { args: [queries] } = decodeFunctionData({ abi: batchGatewayAbi, data }); - const failures = []; - const responses = []; - await Promise.all(queries.map(async (query, i) => { - try { - responses[i] = query.urls.includes(localBatchGatewayUrl) ? await localBatchGatewayRequest({ data: query.data, ccipRequest }) : await ccipRequest(query); - failures[i] = false; - } catch (err) { - failures[i] = true; - responses[i] = encodeError(err); - } - })); - return encodeFunctionResult({ - abi: batchGatewayAbi, - functionName: "query", - result: [failures, responses] + const toAffineMemo = memoized((p, iz) => { + const { px: x, py: y, pz: z } = p; + if (Fp.eql(z, Fp.ONE)) + return { x, y }; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error("invZ was invalid"); + return { x: ax, y: ay }; }); -} -function encodeError(error) { - if (error.name === "HttpRequestError" && error.status) - return encodeErrorResult({ - abi: batchGatewayAbi, - errorName: "HttpError", - args: [error.status, error.shortMessage] - }); - return encodeErrorResult({ - abi: [solidityError], - errorName: "Error", - args: ["shortMessage" in error ? error.shortMessage : error.message] + const assertValidMemo = memoized((p) => { + if (p.is0()) { + if (CURVE.allowInfinityPoint && !Fp.is0(p.py)) + return; + throw new Error("bad point: ZERO"); + } + const { x, y } = p.toAffine(); + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error("bad point: x or y not FE"); + if (!isValidXY(x, y)) + throw new Error("bad point: equation left != right"); + if (!p.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); + return true; }); -} -var localBatchGatewayUrl = "x-batch-gateway:true"; -var init_localBatchGatewayRequest = __esm(() => { - init_abis(); - init_solidity(); - init_decodeFunctionData(); - init_encodeErrorResult(); - init_encodeFunctionResult(); -}); -// ../viem/src/_esm/utils/ccip.js -var exports_ccip = {}; -__export(exports_ccip, { - offchainLookupSignature: () => offchainLookupSignature, - offchainLookupAbiItem: () => offchainLookupAbiItem, - offchainLookup: () => offchainLookup, - ccipRequest: () => ccipRequest -}); -async function offchainLookup(client, { blockNumber, blockTag, data, requestOptions, to }) { - const { args } = decodeErrorResult({ - data, - abi: [offchainLookupAbiItem] - }); - const [sender, urls, callData, callbackSelector, extraData] = args; - const { ccipRead } = client; - const ccipRequest_ = ccipRead && typeof ccipRead?.request === "function" ? ccipRead.request : ccipRequest; - try { - if (!isAddressEqual(to, sender)) - throw new OffchainLookupSenderMismatchError({ sender, to }); - const result = urls.includes(localBatchGatewayUrl) ? await localBatchGatewayRequest({ - data: callData, - ccipRequest: (parameters) => ccipRequest_({ ...parameters, requestOptions }) - }) : await ccipRequest_({ data: callData, requestOptions, sender, urls }); - const { data: data_ } = await call(client, { - blockNumber, - blockTag, - data: concat([ - callbackSelector, - encodeAbiParameters([{ type: "bytes" }, { type: "bytes" }], [result, extraData]) - ]), - requestOptions, - to - }); - return data_; - } catch (err) { - if (requestOptions?.signal?.aborted) - throw getAbortError(requestOptions.signal); - if (isAbortError(err)) - throw err; - throw new OffchainLookupError({ - callbackSelector, - cause: err, - data, - extraData, - sender, - urls - }); - } -} -async function ccipRequest({ data, requestOptions, sender, urls }) { - let error = new Error("An unknown error occurred."); - for (let i = 0;i < urls.length; i++) { - if (requestOptions?.signal?.aborted) - throw getAbortError(requestOptions.signal); - const url = urls[i]; - const method = url.includes("{data}") ? "GET" : "POST"; - const body = method === "POST" ? { data, sender } : undefined; - const headers = method === "POST" ? { "Content-Type": "application/json" } : {}; - try { - const response = await fetch(url.replace("{sender}", sender.toLowerCase()).replace("{data}", data), { - body: JSON.stringify(body), - headers, - method, - ...requestOptions?.signal ? { signal: requestOptions.signal } : {} - }); - let result; - if (response.headers.get("Content-Type")?.startsWith("application/json")) { - result = (await response.json()).data; - } else { - result = await response.text(); - } - if (!response.ok) { - error = new HttpRequestError({ - body, - details: result?.error ? stringify(result.error) : response.statusText, - headers: response.headers, - status: response.status, - url - }); - continue; + class Point { + constructor(px, py, pz) { + if (px == null || !Fp.isValid(px)) + throw new Error("x required"); + if (py == null || !Fp.isValid(py) || Fp.is0(py)) + throw new Error("y required"); + if (pz == null || !Fp.isValid(pz)) + throw new Error("z required"); + this.px = px; + this.py = py; + this.pz = pz; + Object.freeze(this); + } + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error("invalid affine point"); + if (p instanceof Point) + throw new Error("projective point not allowed"); + const is0 = (i) => Fp.eql(i, Fp.ZERO); + if (is0(x) && is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + static normalizeZ(points) { + const toInv = FpInvertBatch(Fp, points.map((p) => p.pz)); + return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); + } + static fromHex(hex) { + const P = Point.fromAffine(fromBytes2(ensureBytes("pointHex", hex))); + P.assertValidity(); + return P; + } + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + static msm(points, scalars) { + return pippenger(Point, Fn, points, scalars); + } + _setWindowSize(windowSize) { + wnaf.setWindowSize(this, windowSize); + } + assertValidity() { + assertValidMemo(this); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) + return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + equals(other) { + aprjpoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n2); + const { px: X1, py: Y1, pz: Z1 } = this; + let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp; + let t0 = Fp.mul(X1, X1); + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + add(other) { + aprjpoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let { ZERO: X3, ZERO: Y3, ZERO: Z3 } = Fp; + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n2); + let t0 = Fp.mul(X1, X2); + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, n, Point.normalizeZ); + } + multiplyUnsafe(sc) { + const { endo: endo2, n: N } = CURVE; + aInRange("scalar", sc, _0n5, N); + const I = Point.ZERO; + if (sc === _0n5) + return I; + if (this.is0() || sc === _1n5) + return this; + if (!endo2 || wnaf.hasPrecomputes(this)) + return wnaf.wNAFCachedUnsafe(this, sc, Point.normalizeZ); + let { k1neg, k1, k2neg, k2 } = endo2.splitScalar(sc); + let k1p = I; + let k2p = I; + let d = this; + while (k1 > _0n5 || k2 > _0n5) { + if (k1 & _1n5) + k1p = k1p.add(d); + if (k2 & _1n5) + k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n5; + k2 >>= _1n5; } - if (!isHex(result)) { - error = new OffchainLookupResponseMalformedError({ - result, - url - }); - continue; + if (k1neg) + k1p = k1p.negate(); + if (k2neg) + k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + multiply(scalar) { + const { endo: endo2, n: N } = CURVE; + aInRange("scalar", scalar, _1n5, N); + let point, fake; + if (endo2) { + const { k1neg, k1, k2neg, k2 } = endo2.splitScalar(scalar); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo2.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(scalar); + point = p; + fake = f; } - return result; - } catch (err) { - if (requestOptions?.signal?.aborted) - throw getAbortError(requestOptions.signal); - if (isAbortError(err)) - throw err; - error = new HttpRequestError({ - body, - details: err.message, - url - }); + return Point.normalizeZ([point, fake])[0]; } - } - throw error; -} -var offchainLookupSignature = "0x556f1830", offchainLookupAbiItem; -var init_ccip2 = __esm(() => { - init_call(); - init_ccip(); - init_request(); - init_decodeErrorResult(); - init_encodeAbiParameters(); - init_isAddressEqual(); - init_localBatchGatewayRequest(); - offchainLookupAbiItem = { - name: "OffchainLookup", - type: "error", - inputs: [ - { - name: "sender", - type: "address" - }, - { - name: "urls", - type: "string[]" - }, - { - name: "callData", - type: "bytes" - }, - { - name: "callbackFunction", - type: "bytes4" - }, - { - name: "extraData", - type: "bytes" - } - ] - }; -}); - -// ../viem/src/_esm/actions/public/call.js -async function call(client, args) { - const { account: account_ = client.account, authorizationList, batch = Boolean(client.batch?.multicall), blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", requireCanonical, accessList, blobs, blockOverrides, code, data: data_, factory, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, requestOptions, to, value, stateOverride, ...rest } = args; - const account = account_ ? parseAccount(account_) : undefined; - if (code && (factory || factoryData)) - throw new BaseError2("Cannot provide both `code` & `factory`/`factoryData` as parameters."); - if (code && to) - throw new BaseError2("Cannot provide both `code` & `to` as parameters."); - const deploylessCallViaBytecode = code && data_; - const deploylessCallViaFactory = factory && factoryData && to && data_; - const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory; - const data = (() => { - if (deploylessCallViaBytecode) - return toDeploylessCallViaBytecodeData({ - code, - data: data_ - }); - if (deploylessCallViaFactory) - return toDeploylessCallViaFactoryData({ - data: data_, - factory, - factoryData, - to - }); - return data_; - })(); - try { - assertRequest(args); - const block = formatBlockParameter({ - blockHash, - blockNumber, - blockTag, - requireCanonical - }); - const rpcBlockOverrides = blockOverrides ? toRpc2(blockOverrides) : undefined; - const rpcStateOverride = serializeStateOverride(stateOverride); - const chainFormat = client.chain?.formatters?.transactionRequest?.format; - const format2 = chainFormat || formatTransactionRequest; - const request = format2({ - ...extract(rest, { format: chainFormat }), - accessList, - account, - authorizationList, - blobs, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to: deploylessCall ? undefined : to, - value - }, "call"); - if (batch && shouldPerformMulticall({ request }) && !rpcBlockOverrides && blockHash === undefined) { - try { - const { deployless = false } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; - const multicallAddress = getMulticallAddress(client, { - blockNumber, - deployless - }); - if (!multicallAddress || !hasStateOverrideForAddress(rpcStateOverride, multicallAddress)) - return await scheduleMulticall(client, { - ...request, - blockHash, - blockNumber, - blockTag, - multicallAddress, - requestOptions, - requireCanonical, - rpcStateOverride - }); - } catch (err) { - if (!(err instanceof ClientChainNotConfiguredError) && !(err instanceof ChainDoesNotSupportContract)) - throw err; - } + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; + const mul = (P, a2) => a2 === _0n5 || a2 === _1n5 || !P.equals(G) ? P.multiplyUnsafe(a2) : P.multiply(a2); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + toAffine(iz) { + return toAffineMemo(this, iz); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n5) + return true; + if (isTorsionFree) + return isTorsionFree(Point, this); + throw new Error("isTorsionFree() has not been declared for the elliptic curve"); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n5) + return this; + if (clearCofactor) + return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + abool("isCompressed", isCompressed); + this.assertValidity(); + return toBytes3(Point, this, isCompressed); + } + toHex(isCompressed = true) { + abool("isCompressed", isCompressed); + return bytesToHex2(this.toRawBytes(isCompressed)); } - const params = (() => { - const base = [ - request, - block - ]; - if (rpcStateOverride && rpcBlockOverrides) - return [...base, rpcStateOverride, rpcBlockOverrides]; - if (rpcStateOverride) - return [...base, rpcStateOverride]; - if (rpcBlockOverrides) - return [...base, {}, rpcBlockOverrides]; - return base; - })(); - const response = await client.request({ - method: "eth_call", - params - }, requestOptions); - if (response === "0x") - return { data: undefined }; - return { data: response }; - } catch (err) { - if (requestOptions?.signal?.aborted) - throw getAbortError(requestOptions.signal); - if (isAbortError(err)) - throw err; - const data2 = getRevertErrorData(err); - const { offchainLookup: offchainLookup2, offchainLookupSignature: offchainLookupSignature2 } = await Promise.resolve().then(() => (init_ccip2(), exports_ccip)); - if (client.ccipRead !== false && data2?.slice(0, 10) === offchainLookupSignature2 && to) - return { - data: await offchainLookup2(client, { data: data2, requestOptions, to }) - }; - if (deploylessCall && data2?.slice(0, 10) === "0x101bb98d") - throw new CounterfactualDeploymentFailedError({ factory }); - throw getCallError(err, { - ...args, - account, - chain: client.chain - }); } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const { endo, nBitLength } = CURVE; + const wnaf = wNAF(Point, endo ? Math.ceil(nBitLength / 2) : nBitLength); + return { + CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar, + weierstrassEquation, + isWithinCurveOrder + }; } -function shouldPerformMulticall({ request }) { - const { data, to, ...request_ } = request; - if (!data) - return false; - if (data.startsWith(aggregate3Signature)) - return false; - if (!to) - return false; - if (Object.values(request_).filter((x) => typeof x !== "undefined").length > 0) - return false; - return true; -} -function getRequestOptionsId(requestOptions) { - if (!requestOptions) - return "default"; - const id = requestOptionsIds.get(requestOptions); - if (id !== undefined) - return id; - const nextId = requestOptionsId++; - requestOptionsIds.set(requestOptions, nextId); - return nextId; -} -async function scheduleMulticall(client, args) { - const { batchSize = 1024, deployless = false, wait = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; - const { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", requireCanonical, data, multicallAddress: multicallAddress_, requestOptions, rpcStateOverride, to } = args; - const multicallAddress = multicallAddress_ !== undefined ? multicallAddress_ : getMulticallAddress(client, { - blockNumber, - deployless - }); - const block = formatBlockParameter({ - blockHash, - blockNumber, - blockTag, - requireCanonical +function validateOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: "hash", + hmac: "function", + randomBytes: "function" + }, { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean" }); - const blockId = typeof block === "string" ? block : JSON.stringify(block); - const stateOverrideKey = rpcStateOverride ? `.${JSON.stringify(rpcStateOverride)}` : ""; - const { schedule } = createBatchScheduler({ - id: `${client.uid}.${blockId}.${getRequestOptionsId(requestOptions)}${stateOverrideKey}`, - wait, - shouldSplitBatch(args2) { - const size4 = args2.reduce((size5, { data: data2 }) => size5 + (data2.length - 2), 0); - return size4 > batchSize * 2; + return Object.freeze({ lowS: true, ...opts }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER, nByteLength, nBitLength } = CURVE; + const compressedLen = Fp.BYTES + 1; + const uncompressedLen = 2 * Fp.BYTES + 1; + function modN(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ + ...CURVE, + toBytes(_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = concatBytes3; + abool("isCompressed", isCompressed); + if (isCompressed) { + return cat(Uint8Array.from([point.hasEvenY() ? 2 : 3]), x); + } else { + return cat(Uint8Array.from([4]), x, Fp.toBytes(a.y)); + } }, - fn: async (requests) => { - const calls = requests.map((request) => ({ - allowFailure: true, - callData: request.data, - target: request.to - })); - const calldata = encodeFunctionData({ - abi: multicall3Abi, - args: [calls], - functionName: "aggregate3" - }); - const multicallRequest = { - ...multicallAddress === null ? { - data: toDeploylessCallViaBytecodeData({ - code: multicall3Bytecode, - data: calldata - }) - } : { to: multicallAddress, data: calldata } - }; - const data2 = await client.request({ - method: "eth_call", - params: rpcStateOverride ? [multicallRequest, block, rpcStateOverride] : [multicallRequest, block] - }, requestOptions); - return decodeFunctionResult({ - abi: multicall3Abi, - args: [calls], - functionName: "aggregate3", - data: data2 || "0x" - }); + fromBytes(bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x = bytesToNumberBE(tail); + if (!inRange(x, _1n5, Fp.ORDER)) + throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x); + let y; + try { + y = Fp.sqrt(y2); + } catch (sqrtError) { + const suffix = sqrtError instanceof Error ? ": " + sqrtError.message : ""; + throw new Error("Point is not on curve" + suffix); + } + const isYOdd = (y & _1n5) === _1n5; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) + y = Fp.neg(y); + return { x, y }; + } else if (len === uncompressedLen && head === 4) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { x, y }; + } else { + const cl = compressedLen; + const ul = uncompressedLen; + throw new Error("invalid Point, expected length of " + cl + ", or uncompressed " + ul + ", got " + len); + } } }); - const [{ returnData, success }] = await schedule({ data, to }); - if (!success) - throw new RawContractError({ data: returnData }); - if (returnData === "0x") - return { data: undefined }; - return { data: returnData }; -} -function getMulticallAddress(client, parameters) { - const { blockNumber, deployless } = parameters; - if (deployless) - return null; - if (client.chain) - return getChainContractAddress({ - blockNumber, - chain: client.chain, - contract: "multicall3" - }); - throw new ClientChainNotConfiguredError; -} -function hasStateOverrideForAddress(rpcStateOverride, address) { - if (!rpcStateOverride) - return false; - return Object.keys(rpcStateOverride).some((stateOverrideAddress) => isAddressEqual(stateOverrideAddress, address)); -} -function toDeploylessCallViaBytecodeData(parameters) { - const { code, data } = parameters; - return encodeDeployData({ - abi: parseAbi(["constructor(bytes, bytes)"]), - bytecode: deploylessCallViaBytecodeBytecode, - args: [code, data] - }); -} -function toDeploylessCallViaFactoryData(parameters) { - const { data, factory, factoryData, to } = parameters; - return encodeDeployData({ - abi: parseAbi(["constructor(address, bytes, address, bytes)"]), - bytecode: deploylessCallViaFactoryBytecode, - args: [to, data, factory, factoryData] - }); -} -function getRevertErrorData(err) { - if (!(err instanceof BaseError2)) - return; - const error = err.walk(); - return typeof error?.data === "object" ? error.data?.data : error.data; -} -var requestOptionsId = 0, requestOptionsIds; -var init_call = __esm(() => { - init_exports(); - init_BlockOverrides(); - init_abis(); - init_base(); - init_chain(); - init_contract(); - init_decodeFunctionResult(); - init_encodeDeployData(); - init_encodeFunctionData(); - init_isAddressEqual(); - init_formatBlockParameter(); - init_getChainContractAddress(); - init_getCallError(); - init_transactionRequest(); - init_createBatchScheduler(); - init_stateOverride2(); - init_assertRequest(); - requestOptionsIds = new WeakMap; -}); - -// ../viem/src/_esm/index.js -init_exports(); - -// ../viem/src/_esm/utils/getAction.js -function getAction(client, actionFn, name) { - const action_implicit = client[actionFn.name]; - if (typeof action_implicit === "function") - return action_implicit; - const action_explicit = client[name]; - if (typeof action_explicit === "function") - return action_explicit; - return (params) => actionFn(client, params); -} - -// ../viem/src/_esm/utils/abi/encodeEventTopics.js -init_abi(); - -// ../viem/src/_esm/errors/log.js -init_base(); - -class FilterTypeNotSupportedError extends BaseError2 { - constructor(type) { - super(`Filter type "${type}" is not supported.`, { - name: "FilterTypeNotSupportedError" - }); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n5; + return number > HALF; } -} - -// ../viem/src/_esm/utils/abi/encodeEventTopics.js -init_toBytes(); -init_keccak256(); -init_toEventSelector(); -init_encodeAbiParameters(); -init_formatAbiItem2(); -init_getAbiItem(); -var docsPath = "/docs/contract/encodeEventTopics"; -function encodeEventTopics(parameters) { - const { abi, eventName, args } = parameters; - let abiItem = abi[0]; - if (eventName) { - const item = getAbiItem({ abi, name: eventName }); - if (!item) - throw new AbiEventNotFoundError(eventName, { docsPath }); - abiItem = item; + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; } - if (abiItem.type !== "event") - throw new AbiEventNotFoundError(undefined, { docsPath }); - let topics = []; - if (args && "inputs" in abiItem) { - const indexedInputs = abiItem.inputs?.filter((param) => ("indexed" in param) && param.indexed); - const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? indexedInputs?.map((x) => args[x.name]) ?? [] : []; - if (args_.length > 0) { - topics = indexedInputs?.map((param, i) => { - if (Array.isArray(args_[i])) - return args_[i].map((_, j) => encodeArg({ param, value: args_[i][j] })); - return typeof args_[i] !== "undefined" && args_[i] !== null ? encodeArg({ param, value: args_[i] }) : null; - }) ?? []; + const slcNum = (b, from4, to) => bytesToNumberBE(b.slice(from4, to)); + + class Signature { + constructor(r, s, recovery) { + aInRange("r", r, _1n5, CURVE_ORDER); + aInRange("s", s, _1n5, CURVE_ORDER); + this.r = r; + this.s = s; + if (recovery != null) + this.recovery = recovery; + Object.freeze(this); + } + static fromCompact(hex) { + const l = nByteLength; + hex = ensureBytes("compactSignature", hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes("DER", hex)); + return new Signature(r, s); + } + assertValidity() {} + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes("msgHash", msgHash)); + if (rec == null || ![0, 1, 2, 3].includes(rec)) + throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) + throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R = Point.fromHex(prefix + numToSizedHex(radj, Fp.BYTES)); + const ir = invN(radj); + const u1 = modN(-h * ir); + const u2 = modN(s * ir); + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) + throw new Error("point at infinify"); + Q.assertValidity(); + return Q; + } + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + toDERRawBytes() { + return hexToBytes2(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig(this); + } + toCompactRawBytes() { + return hexToBytes2(this.toCompactHex()); + } + toCompactHex() { + const l = nByteLength; + return numToSizedHex(this.r, l) + numToSizedHex(this.s, l); } } - if (abiItem.anonymous) - return topics; - const definition = formatAbiItem2(abiItem); - const signature = toEventSelector(definition); - return [signature, ...topics]; -} -function encodeArg({ param, value }) { - if (param.type === "string" || param.type === "bytes") - return keccak256(toBytes(value)); - if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) - throw new FilterTypeNotSupportedError(param.type); - return encodeAbiParameters([param], [value]); -} - -// ../viem/src/_esm/actions/public/createContractEventFilter.js -init_toHex(); - -// ../viem/src/_esm/utils/filters/createFilterRequestScope.js -function createFilterRequestScope(client, { method }) { - const requestMap = {}; - if (client.transport.type === "fallback") - client.transport.onResponse?.(({ method: method_, response: id, status, transport }) => { - if (status === "success" && method === method_) - requestMap[id] = transport.request; - }); - return (id) => requestMap[id] || client.request; -} - -// ../viem/src/_esm/actions/public/createContractEventFilter.js -async function createContractEventFilter(client, parameters) { - const { address, abi, args, eventName, fromBlock, strict, toBlock } = parameters; - const getRequest = createFilterRequestScope(client, { - method: "eth_newFilter" - }); - const topics = eventName ? encodeEventTopics({ - abi, - args, - eventName - }) : undefined; - const id = await client.request({ - method: "eth_newFilter", - params: [ - { - address, - fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, - toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, - topics - } - ] - }); - return { - abi, - args, - eventName, - id, - request: getRequest(id), - strict: Boolean(strict), - type: "event" - }; -} - -// ../viem/src/_esm/actions/public/estimateContractGas.js -init_encodeFunctionData(); - -// ../viem/src/_esm/utils/errors/getContractError.js -init_abi(); -init_base(); -init_contract(); -init_request(); -init_rpc(); -var EXECUTION_REVERTED_ERROR_CODE = 3; -function getContractError(err, { abi, address, args, docsPath: docsPath3, functionName, sender }) { - const error = err instanceof RawContractError ? err : err instanceof BaseError2 ? err.walk((err2) => ("data" in err2)) || err.walk() : {}; - const { code, data, details, message, shortMessage } = error; - const cause = (() => { - if (err instanceof AbiDecodingZeroDataError) - return new ContractFunctionZeroDataError({ functionName, cause: err }); - if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || details || message || shortMessage) || code === InvalidInputRpcError.code && details === "execution reverted" && data) { - return new ContractFunctionRevertedError({ - abi, - data: typeof data === "object" ? data.data : data, - functionName, - message: error instanceof RpcRequestError ? details : shortMessage ?? message, - cause: err - }); - } - return err; - })(); - return new ContractFunctionExecutionError(cause, { - abi, - args, - contractAddress: address, - docsPath: docsPath3, - functionName, - sender - }); -} - -// ../viem/src/_esm/actions/public/estimateGas.js -init_base(); - -// ../viem/src/_esm/accounts/utils/publicKeyToAddress.js -init_getAddress(); -init_keccak256(); -function publicKeyToAddress(publicKey) { - const address = keccak256(`0x${publicKey.substring(4)}`).substring(26); - return checksumAddress(`0x${address}`); -} - -// ../viem/src/_esm/utils/signature/recoverPublicKey.js -init_size(); -init_fromHex(); -init_toHex(); -async function recoverPublicKey({ hash: hash2, signature }) { - const hashHex = isHex(hash2) ? hash2 : toHex(hash2); - const { secp256k1: secp256k12 } = await Promise.resolve().then(() => (init_secp256k1(), exports_secp256k1)); - const signature_ = (() => { - if (typeof signature === "object" && "r" in signature && "s" in signature) { - const { r, s, v, yParity } = signature; - const yParityOrV2 = Number(yParity ?? v); - const recoveryBit2 = toRecoveryBit(yParityOrV2); - return new secp256k12.Signature(hexToBigInt(r), hexToBigInt(s)).addRecoveryBit(recoveryBit2); - } - const signatureHex = isHex(signature) ? signature : toHex(signature); - if (size(signatureHex) !== 65) - throw new Error("invalid signature length"); - const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`); - const recoveryBit = toRecoveryBit(yParityOrV); - return secp256k12.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit); - })(); - const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false); - return `0x${publicKey}`; -} -function toRecoveryBit(yParityOrV) { - if (yParityOrV === 0 || yParityOrV === 1) - return yParityOrV; - if (yParityOrV === 27) - return 0; - if (yParityOrV === 28) - return 1; - throw new Error("Invalid yParityOrV value"); -} - -// ../viem/src/_esm/utils/signature/recoverAddress.js -async function recoverAddress({ hash: hash2, signature }) { - return publicKeyToAddress(await recoverPublicKey({ hash: hash2, signature })); -} - -// ../viem/src/_esm/utils/authorization/hashAuthorization.js -init_toBytes(); -init_toHex(); - -// ../viem/src/_esm/utils/encoding/toRlp.js -init_base(); -init_cursor2(); -init_toBytes(); -init_toHex(); -function toRlp(bytes, to = "hex") { - const encodable = getEncodable(bytes); - const cursor = createCursor(new Uint8Array(encodable.length)); - encodable.encode(cursor); - if (to === "hex") - return bytesToHex(cursor.bytes); - return cursor.bytes; -} -function getEncodable(bytes) { - if (Array.isArray(bytes)) - return getEncodableList(bytes.map((x) => getEncodable(x))); - return getEncodableBytes(bytes); -} -function getEncodableList(list) { - const bodyLength = list.reduce((acc, x) => acc + x.length, 0); - const sizeOfBodyLength = getSizeOfLength(bodyLength); - const length = (() => { - if (bodyLength <= 55) - return 1 + bodyLength; - return 1 + sizeOfBodyLength + bodyLength; - })(); - return { - length, - encode(cursor) { - if (bodyLength <= 55) { - cursor.pushByte(192 + bodyLength); - } else { - cursor.pushByte(192 + 55 + sizeOfBodyLength); - if (sizeOfBodyLength === 1) - cursor.pushUint8(bodyLength); - else if (sizeOfBodyLength === 2) - cursor.pushUint16(bodyLength); - else if (sizeOfBodyLength === 3) - cursor.pushUint24(bodyLength); - else - cursor.pushUint32(bodyLength); - } - for (const { encode } of list) { - encode(cursor); + const utils = { + isValidPrivateKey(privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; } + }, + normPrivateKeyToScalar, + randomPrivateKey: () => { + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + precompute(windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; } }; -} -function getEncodableBytes(bytesOrHex) { - const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex; - const sizeOfBytesLength = getSizeOfLength(bytes.length); - const length = (() => { - if (bytes.length === 1 && bytes[0] < 128) - return 1; - if (bytes.length <= 55) - return 1 + bytes.length; - return 1 + sizeOfBytesLength + bytes.length; - })(); - return { - length, - encode(cursor) { - if (bytes.length === 1 && bytes[0] < 128) { - cursor.pushBytes(bytes); - } else if (bytes.length <= 55) { - cursor.pushByte(128 + bytes.length); - cursor.pushBytes(bytes); - } else { - cursor.pushByte(128 + 55 + sizeOfBytesLength); - if (sizeOfBytesLength === 1) - cursor.pushUint8(bytes.length); - else if (sizeOfBytesLength === 2) - cursor.pushUint16(bytes.length); - else if (sizeOfBytesLength === 3) - cursor.pushUint24(bytes.length); - else - cursor.pushUint32(bytes.length); - cursor.pushBytes(bytes); - } + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + function isProbPub(item) { + if (typeof item === "bigint") + return false; + if (item instanceof Point) + return true; + const arr = ensureBytes("key", item); + const len = arr.length; + const fpl = Fp.BYTES; + const compLen = fpl + 1; + const uncompLen = 2 * fpl + 1; + if (CURVE.allowedPrivateKeyLengths || nByteLength === compLen) { + return; + } else { + return len === compLen || len === uncompLen; } - }; -} -function getSizeOfLength(length) { - if (length < 2 ** 8) - return 1; - if (length < 2 ** 16) - return 2; - if (length < 2 ** 24) - return 3; - if (length < 2 ** 32) - return 4; - throw new BaseError2("Length is too large."); -} - -// ../viem/src/_esm/utils/authorization/hashAuthorization.js -init_keccak256(); -function hashAuthorization(parameters) { - const { chainId, nonce, to } = parameters; - const address = parameters.contractAddress ?? parameters.address; - const hash2 = keccak256(concatHex([ - "0x05", - toRlp([ - chainId ? numberToHex(chainId) : "0x", - address, - nonce ? numberToHex(nonce) : "0x" - ]) - ])); - if (to === "bytes") - return hexToBytes(hash2); - return hash2; -} - -// ../viem/src/_esm/utils/authorization/recoverAuthorizationAddress.js -async function recoverAuthorizationAddress(parameters) { - const { authorization, signature } = parameters; - return recoverAddress({ - hash: hashAuthorization(authorization), - signature: signature ?? authorization - }); -} - -// ../viem/src/_esm/actions/public/estimateGas.js -init_toHex(); - -// ../viem/src/_esm/errors/estimateGas.js -init_formatEther(); -init_formatGwei(); -init_base(); -init_transaction(); - -class EstimateGasExecutionError extends BaseError2 { - constructor(cause, { account, docsPath: docsPath3, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) { - const prettyArgs = prettyPrint({ - from: account?.address, - to, - value: typeof value !== "undefined" && `${formatEther2(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, - data, - gas, - gasPrice: typeof gasPrice !== "undefined" && `${formatGwei2(gasPrice)} gwei`, - maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei2(maxFeePerGas)} gwei`, - maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei2(maxPriorityFeePerGas)} gwei`, - nonce - }); - super(cause.shortMessage, { - cause, - docsPath: docsPath3, - metaMessages: [ - ...cause.metaMessages ? [...cause.metaMessages, " "] : [], - "Estimate Gas Arguments:", - prettyArgs - ].filter(Boolean), - name: "EstimateGasExecutionError" - }); - Object.defineProperty(this, "cause", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.cause = cause; } -} - -// ../viem/src/_esm/utils/errors/getEstimateGasError.js -init_node(); -init_getNodeError(); -function getEstimateGasError(err, { docsPath: docsPath3, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new EstimateGasExecutionError(cause, { - docsPath: docsPath3, - ...args - }); -} - -// ../viem/src/_esm/actions/public/estimateGas.js -init_transactionRequest(); -init_stateOverride2(); -init_assertRequest(); -// ../viem/src/_esm/errors/fee.js -init_formatGwei(); -init_base(); - -class BaseFeeScalarError extends BaseError2 { - constructor() { - super("`baseFeeMultiplier` must be greater than 1.", { - name: "BaseFeeScalarError" - }); - } -} - -class Eip1559FeesNotSupportedError extends BaseError2 { - constructor() { - super("Chain does not support EIP-1559 fees.", { - name: "Eip1559FeesNotSupportedError" - }); - } -} - -class MaxFeePerGasTooLowError extends BaseError2 { - constructor({ maxPriorityFeePerGas }) { - super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei2(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" }); - } -} - -// ../viem/src/_esm/actions/public/estimateMaxPriorityFeePerGas.js -init_fromHex(); - -// ../viem/src/_esm/errors/block.js -init_base(); - -class BlockNotFoundError extends BaseError2 { - constructor({ blockHash, blockNumber }) { - let identifier = "Block"; - if (blockHash) - identifier = `Block at hash "${blockHash}"`; - if (blockNumber) - identifier = `Block at number "${blockNumber}"`; - super(`${identifier} could not be found.`, { name: "BlockNotFoundError" }); + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA) === true) + throw new Error("first arg must be private key"); + if (isProbPub(publicB) === false) + throw new Error("second arg must be public key"); + const b = Point.fromHex(publicB); + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); } -} - -// ../viem/src/_esm/actions/public/getBlock.js -init_toHex(); - -// ../viem/src/_esm/utils/formatters/transaction.js -init_fromHex(); -var transactionType = { - "0x0": "legacy", - "0x1": "eip2930", - "0x2": "eip1559", - "0x3": "eip4844", - "0x4": "eip7702", - "0x79": "eip8130" -}; -function formatTransaction(transaction, _) { - const transaction_ = { - ...transaction, - blockHash: transaction.blockHash ? transaction.blockHash : null, - blockNumber: transaction.blockNumber ? BigInt(transaction.blockNumber) : null, - ...transaction.blockTimestamp != null && { - blockTimestamp: BigInt(transaction.blockTimestamp) - }, - chainId: transaction.chainId ? hexToNumber(transaction.chainId) : undefined, - gas: transaction.gas ? BigInt(transaction.gas) : undefined, - gasPrice: transaction.gasPrice ? BigInt(transaction.gasPrice) : undefined, - maxFeePerBlobGas: transaction.maxFeePerBlobGas ? BigInt(transaction.maxFeePerBlobGas) : undefined, - maxFeePerGas: transaction.maxFeePerGas ? BigInt(transaction.maxFeePerGas) : undefined, - maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? BigInt(transaction.maxPriorityFeePerGas) : undefined, - nonce: transaction.nonce ? hexToNumber(transaction.nonce) : undefined, - to: transaction.to ? transaction.to : null, - transactionIndex: transaction.transactionIndex ? Number(transaction.transactionIndex) : null, - type: transaction.type ? transactionType[transaction.type] : undefined, - typeHex: transaction.type ? transaction.type : undefined, - value: transaction.value ? BigInt(transaction.value) : undefined, - v: transaction.v ? BigInt(transaction.v) : undefined + const bits2int = CURVE.bits2int || function(bytes) { + if (bytes.length > 8192) + throw new Error("input is too large"); + const num = bytesToNumberBE(bytes); + const delta = bytes.length * 8 - nBitLength; + return delta > 0 ? num >> BigInt(delta) : num; }; - if (transaction.authorizationList) - transaction_.authorizationList = formatAuthorizationList2(transaction.authorizationList); - transaction_.yParity = (() => { - if (transaction.yParity) - return Number(transaction.yParity); - if (typeof transaction_.v === "bigint") { - if (transaction_.v === 0n || transaction_.v === 27n) - return 0; - if (transaction_.v === 1n || transaction_.v === 28n) - return 1; - if (transaction_.v >= 35n) - return transaction_.v % 2n === 0n ? 1 : 0; + const bits2int_modN = CURVE.bits2int_modN || function(bytes) { + return modN(bits2int(bytes)); + }; + const ORDER_MASK = bitMask(nBitLength); + function int2octets(num) { + aInRange("num < 2^" + nBitLength, num, _0n5, ORDER_MASK); + return numberToBytesBE(num, nByteLength); + } + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if (["recovered", "canonical"].some((k) => (k in opts))) + throw new Error("sign() legacy options not supported"); + const { hash: hash2, randomBytes: randomBytes2 } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) + lowS = true; + msgHash = ensureBytes("msgHash", msgHash); + validateSigVerOpts(opts); + if (prehash) + msgHash = ensureBytes("prehashed msgHash", hash2(msgHash)); + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); + const seedArgs = [int2octets(d), int2octets(h1int)]; + if (ent != null && ent !== false) { + const e = ent === true ? randomBytes2(Fp.BYTES) : ent; + seedArgs.push(ensureBytes("extraEntropy", e)); } - return; - })(); - if (transaction_.type === "legacy") { - delete transaction_.accessList; - delete transaction_.maxFeePerBlobGas; - delete transaction_.maxFeePerGas; - delete transaction_.maxPriorityFeePerGas; - delete transaction_.yParity; + const seed = concatBytes3(...seedArgs); + const m = h1int; + function k2sig(kBytes) { + const k = bits2int(kBytes); + if (!isWithinCurveOrder(k)) + return; + const ik = invN(k); + const q = Point.BASE.multiply(k).toAffine(); + const r = modN(q.x); + if (r === _0n5) + return; + const s = modN(ik * modN(m + r * d)); + if (s === _0n5) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n5); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); + recovery ^= 1; + } + return new Signature(r, normS, recovery); + } + return { seed, k2sig }; } - if (transaction_.type === "eip2930") { - delete transaction_.maxFeePerBlobGas; - delete transaction_.maxFeePerGas; - delete transaction_.maxPriorityFeePerGas; + const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; + const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); + } + Point.BASE._setWindowSize(8); + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes("msgHash", msgHash); + publicKey = ensureBytes("publicKey", publicKey); + const { lowS, prehash, format: format2 } = opts; + validateSigVerOpts(opts); + if ("strict" in opts) + throw new Error("options.strict was renamed to lowS"); + if (format2 !== undefined && format2 !== "compact" && format2 !== "der") + throw new Error("format must be compact or der"); + const isHex2 = typeof sg === "string" || isBytes2(sg); + const isObj = !isHex2 && !format2 && typeof sg === "object" && sg !== null && typeof sg.r === "bigint" && typeof sg.s === "bigint"; + if (!isHex2 && !isObj) + throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance"); + let _sig = undefined; + let P; + try { + if (isObj) + _sig = new Signature(sg.r, sg.s); + if (isHex2) { + try { + if (format2 !== "compact") + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) + throw derError; + } + if (!_sig && format2 !== "der") + _sig = Signature.fromCompact(sg); + } + P = Point.fromHex(publicKey); + } catch (error) { + return false; + } + if (!_sig) + return false; + if (lowS && _sig.hasHighS()) + return false; + if (prehash) + msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); + const is = invN(s); + const u1 = modN(h * is); + const u2 = modN(r * is); + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); + if (!R) + return false; + const v = modN(R.x); + return v === r; } - if (transaction_.type === "eip1559") - delete transaction_.maxFeePerBlobGas; - return transaction_; -} -function formatAuthorizationList2(authorizationList) { - return authorizationList.map((authorization) => ({ - address: authorization.address, - chainId: Number(authorization.chainId), - nonce: Number(authorization.nonce), - r: authorization.r, - s: authorization.s, - yParity: Number(authorization.yParity) - })); -} - -// ../viem/src/_esm/utils/formatters/block.js -function formatBlock(block, _) { - const transactions = (block.transactions ?? []).map((transaction) => { - if (typeof transaction === "string") - return transaction; - return formatTransaction(transaction); - }); return { - ...block, - baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null, - blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined, - difficulty: block.difficulty ? BigInt(block.difficulty) : undefined, - excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : undefined, - gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined, - gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined, - hash: block.hash ? block.hash : null, - logsBloom: block.logsBloom ? block.logsBloom : null, - nonce: block.nonce ? block.nonce : null, - number: block.number ? BigInt(block.number) : null, - size: block.size ? BigInt(block.size) : undefined, - timestamp: block.timestamp ? BigInt(block.timestamp) : undefined, - transactions, - totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null + CURVE, + getPublicKey, + getSharedSecret, + sign, + verify, + ProjectivePoint: Point, + Signature, + utils }; } - -// ../viem/src/_esm/actions/public/getBlock.js -async function getBlock(client, { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", includeTransactions: includeTransactions_ } = {}) { - const includeTransactions = includeTransactions_ ?? false; - const blockNumberHex = blockNumber !== undefined ? numberToHex(blockNumber) : undefined; - let block = null; - if (blockHash) { - block = await client.request({ - method: "eth_getBlockByHash", - params: [blockHash, includeTransactions] - }, { dedupe: true }); - } else { - block = await client.request({ - method: "eth_getBlockByNumber", - params: [blockNumberHex || blockTag, includeTransactions] - }, { dedupe: Boolean(blockNumberHex) }); +function SWUFpSqrtRatio(Fp, Z) { + const q = Fp.ORDER; + let l = _0n5; + for (let o = q - _1n5;o % _2n3 === _0n5; o /= _2n3) + l += _1n5; + const c1 = l; + const _2n_pow_c1_1 = _2n3 << c1 - _1n5 - _1n5; + const _2n_pow_c1 = _2n_pow_c1_1 * _2n3; + const c2 = (q - _1n5) / _2n_pow_c1; + const c3 = (c2 - _1n5) / _2n3; + const c4 = _2n_pow_c1 - _1n5; + const c5 = _2n_pow_c1_1; + const c6 = Fp.pow(Z, c2); + const c7 = Fp.pow(Z, (c2 + _1n5) / _2n3); + let sqrtRatio = (u, v) => { + let tv1 = c6; + let tv2 = Fp.pow(v, c4); + let tv3 = Fp.sqr(tv2); + tv3 = Fp.mul(tv3, v); + let tv5 = Fp.mul(u, tv3); + tv5 = Fp.pow(tv5, c3); + tv5 = Fp.mul(tv5, tv2); + tv2 = Fp.mul(tv5, v); + tv3 = Fp.mul(tv5, u); + let tv4 = Fp.mul(tv3, tv2); + tv5 = Fp.pow(tv4, c5); + let isQR = Fp.eql(tv5, Fp.ONE); + tv2 = Fp.mul(tv3, c7); + tv5 = Fp.mul(tv4, tv1); + tv3 = Fp.cmov(tv2, tv3, isQR); + tv4 = Fp.cmov(tv5, tv4, isQR); + for (let i = c1;i > _1n5; i--) { + let tv52 = i - _2n3; + tv52 = _2n3 << tv52 - _1n5; + let tvv5 = Fp.pow(tv4, tv52); + const e1 = Fp.eql(tvv5, Fp.ONE); + tv2 = Fp.mul(tv3, tv1); + tv1 = Fp.mul(tv1, tv1); + tvv5 = Fp.mul(tv4, tv1); + tv3 = Fp.cmov(tv2, tv3, e1); + tv4 = Fp.cmov(tvv5, tv4, e1); + } + return { isValid: isQR, value: tv3 }; + }; + if (Fp.ORDER % _4n2 === _3n2) { + const c12 = (Fp.ORDER - _3n2) / _4n2; + const c22 = Fp.sqrt(Fp.neg(Z)); + sqrtRatio = (u, v) => { + let tv1 = Fp.sqr(v); + const tv2 = Fp.mul(u, v); + tv1 = Fp.mul(tv1, tv2); + let y1 = Fp.pow(tv1, c12); + y1 = Fp.mul(y1, tv2); + const y2 = Fp.mul(y1, c22); + const tv3 = Fp.mul(Fp.sqr(y1), v); + const isQR = Fp.eql(tv3, u); + let y = Fp.cmov(y2, y1, isQR); + return { isValid: isQR, value: y }; + }; } - if (!block) - throw new BlockNotFoundError({ blockHash, blockNumber }); - const format2 = client.chain?.formatters?.block?.format || formatBlock; - return format2(block, "getBlock"); -} - -// ../viem/src/_esm/actions/public/getGasPrice.js -async function getGasPrice(client) { - const gasPrice = await client.request({ - method: "eth_gasPrice" - }); - return BigInt(gasPrice); + return sqrtRatio; } - -// ../viem/src/_esm/actions/public/estimateMaxPriorityFeePerGas.js -async function estimateMaxPriorityFeePerGas(client, args) { - return internal_estimateMaxPriorityFeePerGas(client, args); +function mapToCurveSimpleSWU(Fp, opts) { + validateField(Fp); + if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z)) + throw new Error("mapToCurveSimpleSWU: invalid opts"); + const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z); + if (!Fp.isOdd) + throw new Error("Fp.isOdd is not implemented!"); + return (u) => { + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = Fp.sqr(u); + tv1 = Fp.mul(tv1, opts.Z); + tv2 = Fp.sqr(tv1); + tv2 = Fp.add(tv2, tv1); + tv3 = Fp.add(tv2, Fp.ONE); + tv3 = Fp.mul(tv3, opts.B); + tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); + tv4 = Fp.mul(tv4, opts.A); + tv2 = Fp.sqr(tv3); + tv6 = Fp.sqr(tv4); + tv5 = Fp.mul(tv6, opts.A); + tv2 = Fp.add(tv2, tv5); + tv2 = Fp.mul(tv2, tv3); + tv6 = Fp.mul(tv6, tv4); + tv5 = Fp.mul(tv6, opts.B); + tv2 = Fp.add(tv2, tv5); + x = Fp.mul(tv1, tv3); + const { isValid, value } = sqrtRatio(tv2, tv6); + y = Fp.mul(tv1, u); + y = Fp.mul(y, value); + x = Fp.cmov(x, tv3, isValid); + y = Fp.cmov(y, value, isValid); + const e1 = Fp.isOdd(u) === Fp.isOdd(y); + y = Fp.cmov(Fp.neg(y), y, e1); + const tv4_inv = FpInvertBatch(Fp, [tv4], true)[0]; + x = Fp.mul(x, tv4_inv); + return { x, y }; + }; } -async function internal_estimateMaxPriorityFeePerGas(client, args) { - const { block: block_, chain = client.chain, request } = args || {}; - try { - const maxPriorityFeePerGas = chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee; - if (typeof maxPriorityFeePerGas === "function") { - const block = block_ || await getAction(client, getBlock, "getBlock")({}); - const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({ - block, - client, - request - }); - if (maxPriorityFeePerGas_ === null) - throw new Error; - return maxPriorityFeePerGas_; +var DERErr, DER, _0n5, _1n5, _2n3, _3n2, _4n2; +var init_weierstrass = __esm(() => { + init_curve(); + init_modular(); + init_utils3(); + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + DERErr = class DERErr extends Error { + constructor(m = "") { + super(m); } - if (typeof maxPriorityFeePerGas !== "undefined") - return maxPriorityFeePerGas; - const maxPriorityFeePerGasHex = await client.request({ - method: "eth_maxPriorityFeePerGas" - }); - return hexToBigInt(maxPriorityFeePerGasHex); - } catch { - const [block, gasPrice] = await Promise.all([ - block_ ? Promise.resolve(block_) : getAction(client, getBlock, "getBlock")({}), - getAction(client, getGasPrice, "getGasPrice")({}) - ]); - if (typeof block.baseFeePerGas !== "bigint") - throw new Eip1559FeesNotSupportedError; - const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas; - if (maxPriorityFeePerGas < 0n) - return 0n; - return maxPriorityFeePerGas; - } -} + }; + DER = { + Err: DERErr, + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length & 1) + throw new E("tlv.encode: unpadded data"); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if (len.length / 2 & 128) + throw new E("tlv.encode: long form length too big"); + const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; + const t = numberToHexUnpadded(tag); + return t + lenLen + len + data; + }, + decode(tag, data) { + const { Err: E } = DER; + let pos = 0; + if (tag < 0 || tag > 256) + throw new E("tlv.encode: wrong tag"); + if (data.length < 2 || data[pos++] !== tag) + throw new E("tlv.decode: wrong tlv"); + const first = data[pos++]; + const isLong = !!(first & 128); + let length = 0; + if (!isLong) + length = first; + else { + const lenLen = first & 127; + if (!lenLen) + throw new E("tlv.decode(long): indefinite length not supported"); + if (lenLen > 4) + throw new E("tlv.decode(long): byte length is too big"); + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E("tlv.decode: length bytes not complete"); + if (lengthBytes[0] === 0) + throw new E("tlv.decode(long): zero leftmost byte"); + for (const b of lengthBytes) + length = length << 8 | b; + pos += lenLen; + if (length < 128) + throw new E("tlv.decode(long): not minimal encoding"); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E("tlv.decode: wrong value length"); + return { v, l: data.subarray(pos + length) }; + } + }, + _int: { + encode(num) { + const { Err: E } = DER; + if (num < _0n5) + throw new E("integer: negative integers are not allowed"); + let hex = numberToHexUnpadded(num); + if (Number.parseInt(hex[0], 16) & 8) + hex = "00" + hex; + if (hex.length & 1) + throw new E("unexpected DER parsing assertion: unpadded hex"); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data[0] & 128) + throw new E("invalid signature integer: negative"); + if (data[0] === 0 && !(data[1] & 128)) + throw new E("invalid signature integer: unnecessary leading zero"); + return bytesToNumberBE(data); + } + }, + toSig(hex) { + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = ensureBytes("signature", hex); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); + if (seqLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); + if (sLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const rs = tlv.encode(2, int.encode(sig.r)); + const ss = tlv.encode(2, int.encode(sig.s)); + const seq = rs + ss; + return tlv.encode(48, seq); + } + }; + _0n5 = BigInt(0); + _1n5 = BigInt(1); + _2n3 = BigInt(2); + _3n2 = BigInt(3); + _4n2 = BigInt(4); +}); -// ../viem/src/_esm/actions/public/estimateFeesPerGas.js -async function estimateFeesPerGas(client, args) { - return internal_estimateFeesPerGas(client, args); -} -async function internal_estimateFeesPerGas(client, args) { - const { block: block_, chain = client.chain, request, type = "eip1559" } = args || {}; - const baseFeeMultiplier = await (async () => { - if (typeof chain?.fees?.baseFeeMultiplier === "function") - return chain.fees.baseFeeMultiplier({ - block: block_, - client, - request - }); - return chain?.fees?.baseFeeMultiplier ?? 1.2; - })(); - if (baseFeeMultiplier < 1) - throw new BaseFeeScalarError; - const decimals = baseFeeMultiplier.toString().split(".")[1]?.length ?? 0; - const denominator = 10 ** decimals; - const multiply = (base) => base * BigInt(Math.round(baseFeeMultiplier * denominator)) / BigInt(denominator); - const block = block_ ? block_ : await getAction(client, getBlock, "getBlock")({}); - if (typeof chain?.fees?.estimateFeesPerGas === "function") { - const fees = await chain.fees.estimateFeesPerGas({ - block: block_, - client, - multiply, - request, - type - }); - if (fees !== null) - return fees; - } - if (type === "eip1559") { - if (typeof block.baseFeePerGas !== "bigint") - throw new Eip1559FeesNotSupportedError; - const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, { - block, - chain, - request - }); - const baseFeePerGas = multiply(block.baseFeePerGas); - const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas; - return { - maxFeePerGas, - maxPriorityFeePerGas - }; - } - const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({})); +// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/_shortw_utils.js +function getHash(hash2) { return { - gasPrice + hash: hash2, + hmac: (key, ...msgs) => hmac(hash2, key, concatBytes(...msgs)), + randomBytes }; } - -// ../viem/src/_esm/actions/public/getTransactionCount.js -init_formatBlockParameter(); -init_fromHex(); -async function getTransactionCount(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical }) { - const block = formatBlockParameter({ - blockHash, - blockNumber, - blockTag, - requireCanonical - }); - const count = await client.request({ - method: "eth_getTransactionCount", - params: [address, block] - }, { - dedupe: typeof blockNumber === "bigint" || blockHash !== undefined - }); - return hexToNumber(count); +function createCurve(curveDef, defHash) { + const create = (hash2) => weierstrass({ ...curveDef, ...getHash(hash2) }); + return { ...create(defHash), create }; } +var init__shortw_utils = __esm(() => { + init_hmac(); + init_utils2(); + init_weierstrass(); + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +}); -// ../viem/src/_esm/utils/blob/blobsToCommitments.js -init_toBytes(); -init_toHex(); -function blobsToCommitments(parameters) { - const { kzg } = parameters; - const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); - const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs; - const commitments = []; - for (const blob of blobs) - commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob))); - return to === "bytes" ? commitments : commitments.map((x) => bytesToHex(x)); +// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/abstract/hash-to-curve.js +function i2osp(value, length) { + anum(value); + anum(length); + if (value < 0 || value >= 1 << 8 * length) + throw new Error("invalid I2OSP input: " + value); + const res = Array.from({ length }).fill(0); + for (let i = length - 1;i >= 0; i--) { + res[i] = value & 255; + value >>>= 8; + } + return new Uint8Array(res); } - -// ../viem/src/_esm/utils/blob/blobsToProofs.js -init_toBytes(); -init_toHex(); -function blobsToProofs(parameters) { - const { kzg } = parameters; - const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); - const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs; - const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes(x)) : parameters.commitments; - const proofs = []; - for (let i = 0;i < blobs.length; i++) { - const blob = blobs[i]; - const commitment = commitments[i]; - proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))); +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0;i < a.length; i++) { + arr[i] = a[i] ^ b[i]; } - return to === "bytes" ? proofs : proofs.map((x) => bytesToHex(x)); + return arr; } - -// ../viem/src/_esm/utils/blob/commitmentToVersionedHash.js -init_toHex(); - -// ../viem/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js -init_sha2(); -var sha2562 = sha256; - -// ../viem/src/_esm/utils/hash/sha256.js -init_toBytes(); -init_toHex(); -function sha2563(value, to_) { - const to = to_ || "hex"; - const bytes = sha2562(isHex(value, { strict: false }) ? toBytes(value) : value); - if (to === "bytes") - return bytes; - return toHex(bytes); +function anum(item) { + if (!Number.isSafeInteger(item)) + throw new Error("number expected"); } - -// ../viem/src/_esm/utils/blob/commitmentToVersionedHash.js -function commitmentToVersionedHash(parameters) { - const { commitment, version: version3 = 1 } = parameters; - const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes"); - const versionedHash = sha2563(commitment, "bytes"); - versionedHash.set([version3], 0); - return to === "bytes" ? versionedHash : bytesToHex(versionedHash); -} - -// ../viem/src/_esm/utils/blob/commitmentsToVersionedHashes.js -function commitmentsToVersionedHashes(parameters) { - const { commitments, version: version3 } = parameters; - const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes"); - const hashes = []; - for (const commitment of commitments) { - hashes.push(commitmentToVersionedHash({ - commitment, - to, - version: version3 - })); - } - return hashes; -} - -// ../viem/src/_esm/constants/blob.js -var blobsPerTransaction = 6; -var bytesPerFieldElement = 32; -var fieldElementsPerBlob = 4096; -var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob; -var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - 1 - 1 * fieldElementsPerBlob * blobsPerTransaction; - -// ../viem/src/_esm/constants/kzg.js -var versionedHashVersionKzg = 1; - -// ../viem/src/_esm/errors/blob.js -init_base(); - -class BlobSizeTooLargeError extends BaseError2 { - constructor({ maxSize, size: size2 }) { - super("Blob size is too large.", { - metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size2} bytes`], - name: "BlobSizeTooLargeError" - }); - } -} - -class EmptyBlobError extends BaseError2 { - constructor() { - super("Blob data must not be empty.", { name: "EmptyBlobError" }); +function expand_message_xmd(msg, DST, lenInBytes, H) { + abytes2(msg); + abytes2(DST); + anum(lenInBytes); + if (DST.length > 255) + DST = H(concatBytes3(utf8ToBytes2("H2C-OVERSIZE-DST-"), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (lenInBytes > 65535 || ell > 255) + throw new Error("expand_message_xmd: invalid lenInBytes"); + const DST_prime = concatBytes3(DST, i2osp(DST.length, 1)); + const Z_pad = i2osp(0, r_in_bytes); + const l_i_b_str = i2osp(lenInBytes, 2); + const b = new Array(ell); + const b_0 = H(concatBytes3(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes3(b_0, i2osp(1, 1), DST_prime)); + for (let i = 1;i <= ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes3(...args)); } + const pseudo_random_bytes = concatBytes3(...b); + return pseudo_random_bytes.slice(0, lenInBytes); } - -class InvalidVersionedHashSizeError extends BaseError2 { - constructor({ hash: hash2, size: size2 }) { - super(`Versioned hash "${hash2}" size is invalid.`, { - metaMessages: ["Expected: 32", `Received: ${size2}`], - name: "InvalidVersionedHashSizeError" - }); +function expand_message_xof(msg, DST, lenInBytes, k, H) { + abytes2(msg); + abytes2(DST); + anum(lenInBytes); + if (DST.length > 255) { + const dkLen = Math.ceil(2 * k / 8); + DST = H.create({ dkLen }).update(utf8ToBytes2("H2C-OVERSIZE-DST-")).update(DST).digest(); } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error("expand_message_xof: invalid lenInBytes"); + return H.create({ dkLen: lenInBytes }).update(msg).update(i2osp(lenInBytes, 2)).update(DST).update(i2osp(DST.length, 1)).digest(); } - -class InvalidVersionedHashVersionError extends BaseError2 { - constructor({ hash: hash2, version: version3 }) { - super(`Versioned hash "${hash2}" version is invalid.`, { - metaMessages: [ - `Expected: ${versionedHashVersionKzg}`, - `Received: ${version3}` - ], - name: "InvalidVersionedHashVersionError" - }); +function hash_to_field(msg, count, options) { + validateObject(options, { + DST: "stringOrUint8Array", + p: "bigint", + m: "isSafeInteger", + k: "isSafeInteger", + hash: "hash" + }); + const { p, k, m, hash: hash2, expand, DST: _DST } = options; + abytes2(msg); + anum(count); + const DST = typeof _DST === "string" ? utf8ToBytes2(_DST) : _DST; + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); + const len_in_bytes = count * m * L; + let prb; + if (expand === "xmd") { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash2); + } else if (expand === "xof") { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash2); + } else if (expand === "_internal_pass") { + prb = msg; + } else { + throw new Error('expand must be "xmd" or "xof"'); } -} - -// ../viem/src/_esm/utils/blob/toBlobs.js -init_cursor2(); -init_size(); -init_toBytes(); -init_toHex(); -function toBlobs(parameters) { - const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes"); - const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data; - const size_ = size(data); - if (!size_) - throw new EmptyBlobError; - if (size_ > maxBytesPerTransaction) - throw new BlobSizeTooLargeError({ - maxSize: maxBytesPerTransaction, - size: size_ - }); - const blobs = []; - let active = true; - let position = 0; - while (active) { - const blob = createCursor(new Uint8Array(bytesPerBlob)); - let size2 = 0; - while (size2 < fieldElementsPerBlob) { - const bytes = data.slice(position, position + (bytesPerFieldElement - 1)); - blob.pushByte(0); - blob.pushBytes(bytes); - if (bytes.length < 31) { - blob.pushByte(128); - active = false; - break; - } - size2++; - position += 31; + const u = new Array(count); + for (let i = 0;i < count; i++) { + const e = new Array(m); + for (let j = 0;j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); } - blobs.push(blob); + u[i] = e; } - return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex(x.bytes)); + return u; } - -// ../viem/src/_esm/utils/blob/toBlobSidecars.js -function toBlobSidecars(parameters) { - const { data, kzg, to } = parameters; - const blobs = parameters.blobs ?? toBlobs({ data, to }); - const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to }); - const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to }); - const sidecars = []; - for (let i = 0;i < blobs.length; i++) - sidecars.push({ - blob: blobs[i], - commitment: commitments[i], - proof: proofs[i] - }); - return sidecars; +function isogenyMap(field, map) { + const coeff = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true); + x = field.mul(xn, xd_inv); + y = field.mul(y, field.mul(yn, yd_inv)); + return { x, y }; + }; } - -// ../viem/src/_esm/actions/wallet/prepareTransactionRequest.js -init_lru(); -init_assertRequest(); - -// ../viem/src/_esm/utils/transaction/getTransactionType.js -init_transaction(); -function getTransactionType(transaction) { - if (transaction.type) - return transaction.type; - if (typeof transaction.authorizationList !== "undefined") - return "eip7702"; - if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined") - return "eip4844"; - if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") { - return "eip1559"; +function createHasher2(Point, mapToCurve, defaults) { + if (typeof mapToCurve !== "function") + throw new Error("mapToCurve() must be defined"); + function map(num) { + return Point.fromAffine(mapToCurve(num)); } - if (typeof transaction.gasPrice !== "undefined") { - if (typeof transaction.accessList !== "undefined") - return "eip2930"; - return "legacy"; + function clear(initial) { + const P = initial.clearCofactor(); + if (P.equals(Point.ZERO)) + return Point.ZERO; + P.assertValidity(); + return P; } - throw new InvalidSerializableTransactionError({ transaction }); -} -// ../viem/src/_esm/utils/errors/getTransactionError.js -init_node(); -init_transaction(); -init_getNodeError(); -function getTransactionError(err, { docsPath: docsPath3, ...args }) { - const cause = (() => { - const cause2 = getNodeError(err, args); - if (cause2 instanceof UnknownNodeError) - return err; - return cause2; - })(); - return new TransactionExecutionError(cause, { - docsPath: docsPath3, - ...args - }); + return { + defaults, + hashToCurve(msg, options) { + const u = hash_to_field(msg, 2, { ...defaults, DST: defaults.DST, ...options }); + const u0 = map(u[0]); + const u1 = map(u[1]); + return clear(u0.add(u1)); + }, + encodeToCurve(msg, options) { + const u = hash_to_field(msg, 1, { ...defaults, DST: defaults.encodeDST, ...options }); + return clear(map(u[0])); + }, + mapToCurve(scalars) { + if (!Array.isArray(scalars)) + throw new Error("expected array of bigints"); + for (const i of scalars) + if (typeof i !== "bigint") + throw new Error("expected array of bigints"); + return clear(map(scalars)); + } + }; } -// ../viem/src/_esm/actions/public/fillTransaction.js -init_transactionRequest(); -init_assertRequest(); +var os2ip; +var init_hash_to_curve = __esm(() => { + init_modular(); + init_utils3(); + os2ip = bytesToNumberBE; +}); -// ../viem/src/_esm/actions/public/getChainId.js -init_fromHex(); -async function getChainId(client) { - const chainIdHex = await client.request({ - method: "eth_chainId" - }, { dedupe: true }); - return hexToNumber(chainIdHex); +// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/secp256k1.js +var exports_secp256k1 = {}; +__export(exports_secp256k1, { + secp256k1_hasher: () => secp256k1_hasher, + secp256k1: () => secp256k1, + schnorr: () => schnorr, + hashToCurve: () => hashToCurve, + encodeToCurve: () => encodeToCurve +}); +function sqrtMod(y) { + const P = secp256k1P; + const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = y * y * y % P; + const b3 = b2 * b2 * y % P; + const b6 = pow2(b3, _3n3, P) * b3 % P; + const b9 = pow2(b6, _3n3, P) * b3 % P; + const b11 = pow2(b9, _2n4, P) * b2 % P; + const b22 = pow2(b11, _11n, P) * b11 % P; + const b44 = pow2(b22, _22n, P) * b22 % P; + const b88 = pow2(b44, _44n, P) * b44 % P; + const b176 = pow2(b88, _88n, P) * b88 % P; + const b220 = pow2(b176, _44n, P) * b44 % P; + const b223 = pow2(b220, _3n3, P) * b3 % P; + const t1 = pow2(b223, _23n, P) * b22 % P; + const t2 = pow2(t1, _6n, P) * b2 % P; + const root = pow2(t2, _2n4, P); + if (!Fpk1.eql(Fpk1.sqr(root), y)) + throw new Error("Cannot find square root"); + return root; } - -// ../viem/src/_esm/actions/public/fillTransaction.js -async function fillTransaction(client, parameters) { - const { account = client.account, accessList, authorizationList, chain = client.chain, blobVersionedHashes, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce: nonce_, nonceManager, to, type, value, ...rest } = parameters; - const nonce = await (async () => { - if (!account) - return nonce_; - if (!nonceManager) - return nonce_; - if (typeof nonce_ !== "undefined") - return nonce_; - const account_ = parseAccount(account); - const chainId = chain ? chain.id : await getAction(client, getChainId, "getChainId")({}); - return await nonceManager.consume({ - address: account_.address, - chainId, - client - }); - })(); - assertRequest(parameters); - const chainFormat = chain?.formatters?.transactionRequest?.format; - const format2 = chainFormat || formatTransactionRequest; - const request = format2({ - ...extract(rest, { format: chainFormat }), - account: account ? parseAccount(account) : undefined, - accessList, - authorizationList, - blobs, - blobVersionedHashes, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to, - type, - value - }, "fillTransaction"); - try { - const response = await client.request({ - method: "eth_fillTransaction", - params: [request] - }); - const format3 = chain?.formatters?.transaction?.format || formatTransaction; - const transaction = format3(response.tx); - delete transaction.blockHash; - delete transaction.blockNumber; - delete transaction.r; - delete transaction.s; - delete transaction.transactionIndex; - delete transaction.v; - delete transaction.yParity; - transaction.data = transaction.input; - if (transaction.gas) - transaction.gas = parameters.gas ?? transaction.gas; - if (transaction.gasPrice) - transaction.gasPrice = parameters.gasPrice ?? transaction.gasPrice; - if (transaction.maxFeePerBlobGas) - transaction.maxFeePerBlobGas = parameters.maxFeePerBlobGas ?? transaction.maxFeePerBlobGas; - if (transaction.maxFeePerGas) - transaction.maxFeePerGas = parameters.maxFeePerGas ?? transaction.maxFeePerGas; - if (transaction.maxPriorityFeePerGas) - transaction.maxPriorityFeePerGas = parameters.maxPriorityFeePerGas ?? transaction.maxPriorityFeePerGas; - if (typeof transaction.nonce !== "undefined") - transaction.nonce = parameters.nonce ?? transaction.nonce; - const feeMultiplier = await (async () => { - if (typeof chain?.fees?.baseFeeMultiplier === "function") { - const block = await getAction(client, getBlock, "getBlock")({}); - return chain.fees.baseFeeMultiplier({ - block, - client, - request: parameters - }); - } - return chain?.fees?.baseFeeMultiplier ?? 1.2; - })(); - if (feeMultiplier < 1) - throw new BaseFeeScalarError; - const decimals = feeMultiplier.toString().split(".")[1]?.length ?? 0; - const denominator = 10 ** decimals; - const multiplyFee = (base) => base * BigInt(Math.round(feeMultiplier * denominator)) / BigInt(denominator); - if (!transaction.feePayerSignature) { - if (transaction.maxFeePerGas && !parameters.maxFeePerGas) - transaction.maxFeePerGas = multiplyFee(transaction.maxFeePerGas); - if (transaction.gasPrice && !parameters.gasPrice) - transaction.gasPrice = multiplyFee(transaction.gasPrice); - } - return { - raw: response.raw, - transaction: { - from: request.from, - ...transaction - }, - ...response.capabilities ? { capabilities: response.capabilities } : {} - }; - } catch (err) { - throw getTransactionError(err, { - ...parameters, - chain: client.chain - }); +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0))); + tagP = concatBytes3(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; } + return sha256(concatBytes3(tagP, ...messages)); } - -// ../viem/src/_esm/actions/wallet/prepareTransactionRequest.js -var defaultParameters = [ - "blobVersionedHashes", - "chainId", - "fees", - "gas", - "nonce", - "type" -]; -var eip1559NetworkCache = /* @__PURE__ */ new Map; -var supportsFillTransaction = /* @__PURE__ */ new LruMap(128); -async function prepareTransactionRequest(client, args) { - let request = args; - request.account ??= client.account; - request.parameters ??= defaultParameters; - const { account: account_, chain = client.chain, nonceManager, parameters } = request; - const prepareTransactionRequest2 = (() => { - if (typeof chain?.prepareTransactionRequest === "function") - return { - fn: chain.prepareTransactionRequest, - runAt: ["beforeFillTransaction"] - }; - if (Array.isArray(chain?.prepareTransactionRequest)) - return { - fn: chain.prepareTransactionRequest[0], - runAt: chain.prepareTransactionRequest[1].runAt - }; - return; - })(); - let chainId; - async function getChainId2() { - if (chainId) - return chainId; - if (typeof request.chainId !== "undefined") - return request.chainId; - if (chain) - return chain.id; - const chainId_ = await getAction(client, getChainId, "getChainId")({}); - chainId = chainId_; - return chainId; - } - let account = account_ ? parseAccount(account_) : account_; - let nonce = request.nonce; - if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillTransaction")) { - request = await prepareTransactionRequest2.fn({ ...request, chain }, { - client, - phase: "beforeFillTransaction" - }); - nonce ??= request.nonce; - const sender = request.account ?? request.from; - account = sender ? parseAccount(sender) : undefined; - } - if (parameters.includes("nonce") && typeof nonce === "undefined" && account && nonceManager) { - const chainId2 = await getChainId2(); - nonce = await nonceManager.consume({ - address: account.address, - chainId: chainId2, - client - }); - } - const attemptFill = (() => { - if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && request.kzg && request.blobs) - return false; - if (parameters.length > 0 && "feePayer" in request && request.feePayer && !(("feePayerSignature" in request) && request.feePayerSignature)) - return true; - if (supportsFillTransaction.get(client.uid) === false) +function schnorrGetExtPubKey(priv) { + let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); + let p = Point.fromPrivateKey(d_); + const scalar = p.hasEvenY() ? d_ : modN(-d_); + return { scalar, bytes: pointToBytes(p) }; +} +function lift_x(x) { + aInRange("x", x, _1n6, secp256k1P); + const xx = modP(x * x); + const c = modP(xx * x + BigInt(7)); + let y = sqrtMod(c); + if (y % _2n4 !== _0n6) + y = modP(-y); + const p = new Point(x, y, _1n6); + p.assertValidity(); + return p; +} +function challenge(...args) { + return modN(num(taggedHash("BIP0340/challenge", ...args))); +} +function schnorrGetPublicKey(privateKey) { + return schnorrGetExtPubKey(privateKey).bytes; +} +function schnorrSign(message, privateKey, auxRand = randomBytes(32)) { + const m = ensureBytes("message", message); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); + const a = ensureBytes("auxRand", auxRand, 32); + const t = numTo32b(d ^ num(taggedHash("BIP0340/aux", a))); + const rand = taggedHash("BIP0340/nonce", t, px, m); + const k_ = modN(num(rand)); + if (k_ === _0n6) + throw new Error("sign failed: k is zero"); + const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); + const e = challenge(rx, px, m); + const sig = new Uint8Array(64); + sig.set(rx, 0); + sig.set(numTo32b(modN(k + e * d)), 32); + if (!schnorrVerify(sig, m, px)) + throw new Error("sign: Invalid signature produced"); + return sig; +} +function schnorrVerify(signature, message, publicKey) { + const sig = ensureBytes("signature", signature, 64); + const m = ensureBytes("message", message); + const pub = ensureBytes("publicKey", publicKey, 32); + try { + const P = lift_x(num(pub)); + const r = num(sig.subarray(0, 32)); + if (!inRange(r, _1n6, secp256k1P)) return false; - const shouldAttempt = ["fees", "gas"].some((parameter) => parameters.includes(parameter)); - if (!shouldAttempt) + const s = num(sig.subarray(32, 64)); + if (!inRange(s, _1n6, secp256k1N)) return false; - if (parameters.includes("chainId") && typeof request.chainId !== "number") - return true; - if (parameters.includes("nonce") && typeof nonce !== "number") - return true; - if (parameters.includes("fees") && typeof request.gasPrice !== "bigint" && (typeof request.maxFeePerGas !== "bigint" || typeof request.maxPriorityFeePerGas !== "bigint")) - return true; - if (parameters.includes("gas") && typeof request.gas !== "bigint") - return true; + const e = challenge(numTo32b(r), pointToBytes(P), m); + const R = GmulAdd(P, s, modN(-e)); + if (!R || !R.hasEvenY() || R.toAffine().x !== r) + return false; + return true; + } catch (error) { return false; - })(); - const fillResult = attemptFill ? await getAction(client, fillTransaction, "fillTransaction")({ ...request, nonce }).then((result) => { - const { chainId: chainId2, from: from2, gas: gas2, gasPrice, nonce: nonce2, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, type: type2, ...rest } = result.transaction; - const feeToken = "feeToken" in rest ? rest.feeToken : undefined; - const hasFilledFeePayerSignature = "feePayerSignature" in rest && rest.feePayerSignature !== null && typeof rest.feePayerSignature !== "undefined"; - const shouldUseFilledFeeToken = typeof feeToken !== "undefined" && feeToken !== null && (!("feeToken" in request) || hasFilledFeePayerSignature); - supportsFillTransaction.set(client.uid, true); - return { - ...request, - ...from2 ? { from: from2 } : {}, - ...type2 && !request.type ? { type: type2 } : {}, - ...typeof chainId2 !== "undefined" ? { chainId: chainId2 } : {}, - ...typeof gas2 !== "undefined" ? { gas: gas2 } : {}, - ...typeof gasPrice !== "undefined" ? { gasPrice } : {}, - ...typeof nonce2 !== "undefined" ? { nonce: nonce2 } : {}, - ...typeof maxFeePerBlobGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerBlobGas } : {}, - ...typeof maxFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerGas } : {}, - ...typeof maxPriorityFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxPriorityFeePerGas } : {}, - ..."nonceKey" in rest && typeof rest.nonceKey !== "undefined" ? { nonceKey: rest.nonceKey } : {}, - ..."keyAuthorization" in rest && typeof rest.keyAuthorization !== "undefined" && rest.keyAuthorization !== null && !("keyAuthorization" in request) ? { keyAuthorization: rest.keyAuthorization } : {}, - ..."feePayerSignature" in rest && typeof rest.feePayerSignature !== "undefined" && rest.feePayerSignature !== null ? { feePayerSignature: rest.feePayerSignature } : {}, - ...shouldUseFilledFeeToken ? { feeToken } : {}, - ...result.capabilities ? { _capabilities: result.capabilities } : {} - }; - }).catch((e) => { - const error = e; - if (error.name !== "TransactionExecutionError") - return request; - const executionReverted = error.walk?.((e2) => { - const error2 = e2; - return error2.name === "ExecutionRevertedError"; - }); - if (executionReverted) - throw e; - const unsupported = error.walk?.((e2) => { - const error2 = e2; - return error2.name === "MethodNotFoundRpcError" || error2.name === "MethodNotSupportedRpcError" || error2.message?.includes("eth_fillTransaction is not available"); - }); - if (unsupported) - supportsFillTransaction.set(client.uid, false); - return request; - }) : request; - nonce ??= fillResult.nonce; - request = { - ...fillResult, - ...account ? { from: account?.address } : {}, - ...typeof nonce !== "undefined" ? { nonce } : {} - }; - const { blobs, gas, kzg, type } = request; - if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillParameters")) { - request = await prepareTransactionRequest2.fn({ ...request, chain }, { - client, - phase: "beforeFillParameters" - }); - } - let block; - async function getBlock2() { - if (block) - return block; - block = await getAction(client, getBlock, "getBlock")({ blockTag: "latest" }); - return block; } - if (parameters.includes("nonce") && typeof nonce === "undefined" && account && !nonceManager) - request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ - address: account.address, - blockTag: "pending" - }); - if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) { - const commitments = blobsToCommitments({ blobs, kzg }); - if (parameters.includes("blobVersionedHashes")) { - const versionedHashes = commitmentsToVersionedHashes({ - commitments, - to: "hex" - }); - request.blobVersionedHashes = versionedHashes; +} +var secp256k1P, secp256k1N, _0n6, _1n6, _2n4, divNearest = (a, b) => (a + b / _2n4) / b, Fpk1, secp256k1, TAGGED_HASH_PREFIXES, pointToBytes = (point) => point.toRawBytes(true).slice(1), numTo32b = (n) => numberToBytesBE(n, 32), modP = (x) => mod(x, secp256k1P), modN = (x) => mod(x, secp256k1N), Point, GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b), num, schnorr, isoMap, mapSWU, secp256k1_hasher, hashToCurve, encodeToCurve; +var init_secp256k1 = __esm(() => { + init_sha2(); + init_utils2(); + init__shortw_utils(); + init_hash_to_curve(); + init_modular(); + init_utils3(); + init_weierstrass(); + /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); + secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); + _0n6 = BigInt(0); + _1n6 = BigInt(1); + _2n4 = BigInt(2); + Fpk1 = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); + secp256k1 = createCurve({ + a: _0n6, + b: BigInt(7), + Fp: Fpk1, + n: secp256k1N, + Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), + Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), + h: BigInt(1), + lowS: true, + endo: { + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + splitScalar: (k) => { + const n = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n6 * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) + k1 = n - k1; + if (k2neg) + k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k); + } + return { k1neg, k1, k2neg, k2 }; + } } - if (parameters.includes("sidecars")) { - const proofs = blobsToProofs({ blobs, commitments, kzg }); - const sidecars = toBlobSidecars({ - blobs, - commitments, - proofs, - to: "hex" - }); - request.sidecars = sidecars; + }, sha256); + TAGGED_HASH_PREFIXES = {}; + Point = /* @__PURE__ */ (() => secp256k1.ProjectivePoint)(); + num = bytesToNumberBE; + schnorr = /* @__PURE__ */ (() => ({ + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + utils: { + randomPrivateKey: secp256k1.utils.randomPrivateKey, + lift_x, + pointToBytes, + numberToBytesBE, + bytesToNumberBE, + taggedHash, + mod } - } - if (parameters.includes("chainId")) - request.chainId = await getChainId2(); - if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") { - try { - request.type = getTransactionType(request); - } catch { - let isEip1559Network = eip1559NetworkCache.get(client.uid); - if (typeof isEip1559Network === "undefined") { - const block2 = await getBlock2(); - isEip1559Network = typeof block2?.baseFeePerGas === "bigint"; - eip1559NetworkCache.set(client.uid, isEip1559Network); - } - request.type = isEip1559Network ? "eip1559" : "legacy"; + }))(); + isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [ + [ + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7", + "0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581", + "0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262", + "0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c" + ], + [ + "0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b", + "0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14", + "0x0000000000000000000000000000000000000000000000000000000000000001" + ], + [ + "0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c", + "0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3", + "0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931", + "0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84" + ], + [ + "0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b", + "0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573", + "0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f", + "0x0000000000000000000000000000000000000000000000000000000000000001" + ] + ].map((i) => i.map((j) => BigInt(j)))))(); + mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fpk1, { + A: BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"), + B: BigInt("1771"), + Z: Fpk1.create(BigInt("-11")) + }))(); + secp256k1_hasher = /* @__PURE__ */ (() => createHasher2(secp256k1.ProjectivePoint, (scalars) => { + const { x, y } = mapSWU(Fpk1.create(scalars[0])); + return isoMap(x, y); + }, { + DST: "secp256k1_XMD:SHA-256_SSWU_RO_", + encodeDST: "secp256k1_XMD:SHA-256_SSWU_NU_", + p: Fpk1.ORDER, + m: 1, + k: 128, + expand: "xmd", + hash: sha256 + }))(); + hashToCurve = /* @__PURE__ */ (() => secp256k1_hasher.hashToCurve)(); + encodeToCurve = /* @__PURE__ */ (() => secp256k1_hasher.encodeToCurve)(); +}); + +// ../viem/src/_esm/index.js +init_exports(); +// ../viem/src/_esm/utils/uid.js +var size = 256; +var index = size; +var buffer; +function uid(length = 11) { + if (!buffer || index + length > size * 2) { + buffer = ""; + index = 0; + for (let i = 0;i < size; i++) { + buffer += (256 + Math.random() * 256 | 0).toString(16).substring(1); } } - if (parameters.includes("fees")) { - if (request.type !== "legacy" && request.type !== "eip2930") { - if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") { - const block2 = await getBlock2(); - const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, { - block: block2, - chain, - request - }); - if (typeof request.maxPriorityFeePerGas === "undefined" && request.maxFeePerGas && request.maxFeePerGas < maxPriorityFeePerGas) - throw new MaxFeePerGasTooLowError({ - maxPriorityFeePerGas - }); - request.maxPriorityFeePerGas = maxPriorityFeePerGas; - request.maxFeePerGas = maxFeePerGas; - } - } else { - if (typeof request.maxFeePerGas !== "undefined" || typeof request.maxPriorityFeePerGas !== "undefined") - throw new Eip1559FeesNotSupportedError; - if (typeof request.gasPrice === "undefined") { - const block2 = await getBlock2(); - const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, { - block: block2, - chain, - request, - type: "legacy" - }); - request.gasPrice = gasPrice_; - } - } - } - if (parameters.includes("gas") && typeof gas === "undefined") - request.gas = await getAction(client, estimateGas, "estimateGas")({ - ...request, - account, - prepare: account?.type === "local" ? [] : ["blobVersionedHashes"] - }); - if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("afterFillParameters")) - request = await prepareTransactionRequest2.fn({ ...request, chain }, { - client, - phase: "afterFillParameters" - }); - assertRequest(request); - delete request.parameters; - return request; -} - -// ../viem/src/_esm/actions/public/estimateGas.js -async function estimateGas(client, args) { - const { account: account_ = client.account, prepare = true } = args; - const account = account_ ? parseAccount(account_) : undefined; - const parameters = (() => { - if (Array.isArray(prepare)) - return prepare; - if (account?.type !== "local") - return ["blobVersionedHashes"]; - return; - })(); - try { - const to = await (async () => { - if (args.to) - return args.to; - if (args.authorizationList && args.authorizationList.length > 0) - return await recoverAuthorizationAddress({ - authorization: args.authorizationList[0] - }).catch(() => { - throw new BaseError2("`to` is required. Could not infer from `authorizationList`"); - }); - return; - })(); - const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = prepare ? await prepareTransactionRequest(client, { - ...args, - parameters, - to - }) : args; - if (gas && args.gas !== gas) - return gas; - const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : undefined; - const block = blockNumberHex || blockTag; - const rpcStateOverride = serializeStateOverride(stateOverride); - assertRequest(args); - const chainFormat = client.chain?.formatters?.transactionRequest?.format; - const format2 = chainFormat || formatTransactionRequest; - const request = format2({ - ...extract(rest, { format: chainFormat }), - account, - accessList, - authorizationList, - blobs, - blobVersionedHashes, - data, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to, - value - }, "estimateGas"); - return BigInt(await client.request({ - method: "eth_estimateGas", - params: rpcStateOverride ? [ - request, - block ?? client.experimental_blockTag ?? "latest", - rpcStateOverride - ] : block ? [request, block] : [request] - })); - } catch (err) { - throw getEstimateGasError(err, { - ...args, - account, - chain: client.chain - }); - } + return buffer.substring(index, index++ + length); } -// ../viem/src/_esm/actions/public/estimateContractGas.js -async function estimateContractGas(client, parameters) { - const { abi, address, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...request } = parameters; - const data = encodeFunctionData({ - abi, - args, - functionName +// ../viem/src/_esm/clients/createClient.js +function createClient(parameters) { + const { batch, chain, ccipRead, dataSuffix, key = "base", name = "Base Client", tokens, type = "base" } = parameters; + const experimental_blockTag = parameters.experimental_blockTag ?? (typeof chain?.experimental_preconfirmationTime === "number" ? "pending" : undefined); + const blockTime = chain?.blockTime ?? 12000; + const defaultPollingInterval = Math.min(Math.max(Math.floor(blockTime / 2), 500), 4000); + const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval; + const cacheTime = parameters.cacheTime ?? pollingInterval; + const account = parameters.account ? parseAccount(parameters.account) : undefined; + const { config, request, value } = parameters.transport({ + account, + chain, + pollingInterval }); - try { - const gas = await getAction(client, estimateGas, "estimateGas")({ - data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, - to: address, - ...request - }); - return gas; - } catch (error) { - const account = request.account ? parseAccount(request.account) : undefined; - throw getContractError(error, { - abi, - address, - args, - docsPath: "/docs/contract/estimateContractGas", - functionName, - sender: account?.address - }); + const transport = { ...config, ...value }; + const client = { + account, + batch, + cacheTime, + ccipRead, + chain, + dataSuffix, + key, + name, + pollingInterval, + request, + tokens, + transport, + type, + uid: uid(), + ...experimental_blockTag ? { experimental_blockTag } : {} + }; + function extend(base) { + return (extendFn) => { + const extended = extendFn(base); + for (const key2 in client) + delete extended[key2]; + const combined = { ...base, ...extended }; + for (const key2 in extended) { + const a = base[key2]; + const b = extended[key2]; + if (isPlainObject(a) && isPlainObject(b)) + combined[key2] = { ...a, ...b }; + } + return Object.assign(combined, { extend: extend(combined) }); + }; } + return Object.assign(client, { extend: extend(client) }); +} +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} +function bindActionDecorators(client, action) { + const wrapped = (parameters = {}) => action(client, parameters); + for (const key of [ + "call", + "calls", + "callWithPeriod", + "estimateGas", + "prepare", + "prepareRecipient", + "predict", + "simulate" + ]) + if (Object.hasOwn(action, key)) { + const helper = action[key]; + wrapped[key] = (args = {}) => { + if (helper.length === 1) + return helper(args); + return helper(client, args); + }; + } + for (const key of ["extractEvent", "extractEvents"]) + if (Object.hasOwn(action, key)) + wrapped[key] = action[key]; + return wrapped; } -// ../viem/src/_esm/actions/public/getContractEvents.js -init_getAbiItem(); - -// ../viem/src/_esm/utils/abi/parseEventLogs.js -init_isAddressEqual(); -init_toBytes(); +// ../viem/src/_esm/actions/ens/getEnsAddress.js +init_abis(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_getAddress(); +init_getChainContractAddress(); +init_size(); +init_toHex(); -// ../viem/src/_esm/utils/formatters/log.js -function formatLog(log, { args, eventName } = {}) { - return { - ...log, - blockHash: log.blockHash ? log.blockHash : null, - blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null, - blockTimestamp: log.blockTimestamp ? BigInt(log.blockTimestamp) : log.blockTimestamp === null ? null : undefined, - logIndex: log.logIndex ? Number(log.logIndex) : null, - transactionHash: log.transactionHash ? log.transactionHash : null, - transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null, - ...eventName ? { args, eventName } : {} - }; +// ../viem/src/_esm/utils/ens/errors.js +init_base(); +init_contract(); +function isNullUniversalResolverError(err) { + if (!(err instanceof BaseError2)) + return false; + const cause = err.walk((e) => e instanceof ContractFunctionRevertedError); + if (!(cause instanceof ContractFunctionRevertedError)) + return false; + if (cause.data?.errorName === "HttpError") + return true; + if (cause.data?.errorName === "ResolverError") + return true; + if (cause.data?.errorName === "ResolverNotContract") + return true; + if (cause.data?.errorName === "ResolverNotFound") + return true; + if (cause.data?.errorName === "ReverseAddressMismatch") + return true; + if (cause.data?.errorName === "UnsupportedResolverProfile") + return true; + return false; } -// ../viem/src/_esm/utils/abi/parseEventLogs.js +// ../viem/src/_esm/actions/ens/getEnsAddress.js +init_localBatchGatewayRequest(); + +// ../viem/src/_esm/utils/ens/namehash.js +init_toBytes(); +init_toHex(); init_keccak256(); -init_toEventSelector(); -// ../viem/src/_esm/utils/abi/decodeEventLog.js -init_abi(); -init_cursor(); -init_size(); -init_toEventSelector(); -init_decodeAbiParameters(); -init_formatAbiItem2(); -var docsPath3 = "/docs/contract/decodeEventLog"; -function decodeEventLog(parameters) { - const { abi, data, strict: strict_, topics } = parameters; - const strict = strict_ ?? true; - const [signature, ...argTopics] = topics; - if (!signature) - throw new AbiEventSignatureEmptyTopicsError({ docsPath: docsPath3 }); - const abiItem = abi.find((x) => x.type === "event" && signature === toEventSelector(formatAbiItem2(x))); - if (!(abiItem && ("name" in abiItem)) || abiItem.type !== "event") - throw new AbiEventSignatureNotFoundError(signature, { docsPath: docsPath3 }); - const { name, inputs } = abiItem; - const isUnnamed = inputs?.some((x) => !(("name" in x) && x.name)); - const args = isUnnamed ? [] : {}; - const indexedInputs = inputs.map((x, i) => [x, i]).filter(([x]) => ("indexed" in x) && x.indexed); - const missingIndexedInputs = []; - for (let i = 0;i < indexedInputs.length; i++) { - const [param, argIndex] = indexedInputs[i]; - const topic = argTopics[i]; - if (!topic) { - if (strict) - throw new DecodeLogTopicsMismatch({ - abiItem, - param - }); - missingIndexedInputs.push([param, argIndex]); - continue; - } - args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({ - param, - value: topic - }); - } - const nonIndexedInputs = inputs.filter((x) => !(("indexed" in x) && x.indexed)); - const inputsToDecode = strict ? nonIndexedInputs : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs]; - if (inputsToDecode.length > 0) { - if (data && data !== "0x") { - try { - const decodedData = decodeAbiParameters(inputsToDecode, data); - if (decodedData) { - let dataIndex = 0; - if (!strict) { - for (const [param, argIndex] of missingIndexedInputs) { - args[isUnnamed ? argIndex : param.name || argIndex] = decodedData[dataIndex++]; - } - } - if (isUnnamed) { - for (let i = 0;i < inputs.length; i++) - if (args[i] === undefined && dataIndex < decodedData.length) - args[i] = decodedData[dataIndex++]; - } else - for (let i = 0;i < nonIndexedInputs.length; i++) - args[nonIndexedInputs[i].name] = decodedData[dataIndex++]; - } - } catch (err) { - if (strict) { - if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError) - throw new DecodeLogDataMismatch({ - abiItem, - data, - params: inputsToDecode, - size: size(data) - }); - throw err; - } - } - } else if (strict) { - throw new DecodeLogDataMismatch({ - abiItem, - data: "0x", - params: inputsToDecode, - size: 0 - }); - } +// ../viem/src/_esm/utils/ens/encodedLabelToLabelhash.js +function encodedLabelToLabelhash(label) { + if (label.length !== 66) + return null; + if (label.indexOf("[") !== 0) + return null; + if (label.indexOf("]") !== 65) + return null; + const hash2 = `0x${label.slice(1, 65)}`; + if (!isHex(hash2)) + return null; + return hash2; +} + +// ../viem/src/_esm/utils/ens/namehash.js +function namehash(name) { + let result = new Uint8Array(32).fill(0); + if (!name) + return bytesToHex(result); + const labels = name.split("."); + for (let i = labels.length - 1;i >= 0; i -= 1) { + const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]); + const hashed = hashFromEncodedLabel ? toBytes(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes"); + result = keccak256(concat([result, hashed]), "bytes"); } - return { - eventName: name, - args: Object.values(args).length > 0 ? args : undefined - }; + return bytesToHex(result); } -function decodeTopic({ param, value }) { - if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) - return value; - const decodedArg = decodeAbiParameters([param], value) || []; - return decodedArg[0]; + +// ../viem/src/_esm/utils/ens/packetToBytes.js +init_toBytes(); + +// ../viem/src/_esm/utils/ens/encodeLabelhash.js +function encodeLabelhash(hash2) { + return `[${hash2.slice(2)}]`; } -// ../viem/src/_esm/utils/abi/parseEventLogs.js -function parseEventLogs(parameters) { - const { abi, args, logs, strict = true } = parameters; - const eventName = (() => { - if (!parameters.eventName) - return; - if (Array.isArray(parameters.eventName)) - return parameters.eventName; - return [parameters.eventName]; - })(); - const abiTopics = abi.filter((abiItem) => abiItem.type === "event").map((abiItem) => ({ - abi: abiItem, - selector: toEventSelector(abiItem) - })); - return logs.map((log) => { - const formattedLog = typeof log.blockNumber === "string" ? formatLog(log) : log; - const abiItems = abiTopics.filter((abiTopic) => formattedLog.topics[0] === abiTopic.selector); - if (abiItems.length === 0) - return null; - let event; - let abiItem; - for (const item of abiItems) { - try { - event = decodeEventLog({ - ...formattedLog, - abi: [item.abi], - strict: true - }); - abiItem = item; - break; - } catch {} - } - if (!event && !strict) { - abiItem = abiItems[0]; - try { - event = decodeEventLog({ - data: formattedLog.data, - topics: formattedLog.topics, - abi: [abiItem.abi], - strict: false - }); - } catch { - const isUnnamed = abiItem.abi.inputs?.some((x) => !(("name" in x) && x.name)); - return { - ...formattedLog, - args: isUnnamed ? [] : {}, - eventName: abiItem.abi.name - }; - } - } - if (!event || !abiItem) - return null; - if (eventName && !eventName.includes(event.eventName)) - return null; - if (!includesArgs({ - args: event.args, - inputs: abiItem.abi.inputs, - matchArgs: args - })) - return null; - return { ...event, ...formattedLog }; - }).filter(Boolean); +// ../viem/src/_esm/utils/ens/labelhash.js +init_toBytes(); +init_toHex(); +init_keccak256(); +function labelhash(label) { + const result = new Uint8Array(32).fill(0); + if (!label) + return bytesToHex(result); + return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label)); } -function includesArgs(parameters) { - const { args, inputs, matchArgs } = parameters; - if (!matchArgs) - return true; - if (!args) - return false; - function isEqual(input, value, arg) { - try { - if (input.type === "address") - return isAddressEqual(value, arg); - if (input.type === "string" || input.type === "bytes") - return keccak256(toBytes(value)) === arg; - return value === arg; - } catch { - return false; - } - } - if (Array.isArray(args) && Array.isArray(matchArgs)) { - return matchArgs.every((value, index) => { - if (value === null || value === undefined) - return true; - const input = inputs[index]; - if (!input) - return false; - const value_ = Array.isArray(value) ? value : [value]; - return value_.some((value2) => isEqual(input, value2, args[index])); - }); + +// ../viem/src/_esm/utils/ens/packetToBytes.js +function packetToBytes(packet) { + const value = packet.replace(/^\.|\.$/gm, ""); + if (value.length === 0) + return new Uint8Array(1); + const bytes = new Uint8Array(stringToBytes(value).byteLength + 2); + let offset = 0; + const list = value.split("."); + for (let i = 0;i < list.length; i++) { + let encoded = stringToBytes(list[i]); + if (encoded.byteLength > 255) + encoded = stringToBytes(encodeLabelhash(labelhash(list[i]))); + bytes[offset] = encoded.length; + bytes.set(encoded, offset + 1); + offset += encoded.length + 1; } - if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs)) - return Object.entries(matchArgs).every(([key, value]) => { - if (value === null || value === undefined) - return true; - const input = inputs.find((input2) => input2.name === key); - if (!input) - return false; - const value_ = Array.isArray(value) ? value : [value]; - return value_.some((value2) => isEqual(input, value2, args[key])); - }); - return false; + if (bytes.byteLength !== offset + 1) + return bytes.slice(0, offset + 1); + return bytes; } -// ../viem/src/_esm/actions/public/getLogs.js -init_toHex(); -async function getLogs(client, { address, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) { - const strict = strict_ ?? false; - const events = events_ ?? (event ? [event] : undefined); - let topics = []; - if (events) { - const encoded = events.flatMap((event2) => encodeEventTopics({ - abi: [event2], - eventName: event2.name, - args: events_ ? undefined : args - })); - topics = [encoded]; - if (event) - topics = topics[0]; - } - let logs; - if (blockHash) { - logs = await client.request({ - method: "eth_getLogs", - params: [{ address, topics, blockHash }] - }); - } else { - logs = await client.request({ - method: "eth_getLogs", - params: [ - { - address, - topics, - fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, - toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock - } - ] - }); - } - const formattedLogs = logs.map((log) => formatLog(log)); - if (!events) - return formattedLogs; - return parseEventLogs({ - abi: events, - args, - logs: formattedLogs, - strict - }); +// ../viem/src/_esm/utils/getAction.js +function getAction(client, actionFn, name) { + const action_implicit = client[actionFn.name]; + if (typeof action_implicit === "function") + return action_implicit; + const action_explicit = client[name]; + if (typeof action_explicit === "function") + return action_explicit; + return (params) => actionFn(client, params); } -// ../viem/src/_esm/actions/public/getContractEvents.js -async function getContractEvents(client, parameters) { - const { abi, address, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters; - const event = eventName ? getAbiItem({ abi, name: eventName }) : undefined; - const events = !event ? abi.filter((x) => x.type === "event") : undefined; - return getAction(client, getLogs, "getLogs")({ - address, +// ../viem/src/_esm/actions/public/readContract.js +init_decodeFunctionResult(); +init_encodeFunctionData(); + +// ../viem/src/_esm/utils/errors/getContractError.js +init_abi(); +init_base(); +init_contract(); +init_request(); +init_rpc(); +var EXECUTION_REVERTED_ERROR_CODE = 3; +function getContractError(err, { abi, address, args, docsPath: docsPath5, functionName, sender }) { + const error = err instanceof RawContractError ? err : err instanceof BaseError2 ? err.walk((err2) => ("data" in err2)) || err.walk() : {}; + const { code, data, details, message, shortMessage } = error; + const cause = (() => { + if (err instanceof AbiDecodingZeroDataError) + return new ContractFunctionZeroDataError({ functionName, cause: err }); + if ([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) && (data || details || message || shortMessage) || code === InvalidInputRpcError.code && details === "execution reverted" && data) { + return new ContractFunctionRevertedError({ + abi, + data: typeof data === "object" ? data.data : data, + functionName, + message: error instanceof RpcRequestError ? details : shortMessage ?? message, + cause: err + }); + } + return err; + })(); + return new ContractFunctionExecutionError(cause, { + abi, args, - blockHash, - event, - events, - fromBlock, - toBlock, - strict + contractAddress: address, + docsPath: docsPath5, + functionName, + sender }); } // ../viem/src/_esm/actions/public/readContract.js -init_decodeFunctionResult(); -init_encodeFunctionData(); init_call(); async function readContract(client, parameters) { const { abi, address, args, functionName, ...rest } = parameters; @@ -11237,3380 +9895,3116 @@ async function readContract(client, parameters) { } } -// ../viem/src/_esm/actions/public/simulateContract.js -init_decodeFunctionResult(); -init_encodeFunctionData(); -init_call(); -async function simulateContract(client, parameters) { - const { abi, address, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...callRequest } = parameters; - const account = callRequest.account ? parseAccount(callRequest.account) : client.account; - const calldata = encodeFunctionData({ abi, args, functionName }); - try { - const { data } = await getAction(client, call, "call")({ - batch: false, - data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, - to: address, - ...callRequest, - account +// ../viem/src/_esm/actions/ens/getEnsAddress.js +async function getEnsAddress(client, parameters) { + const { blockNumber, blockTag, coinType, name, gatewayUrls, strict } = parameters; + const { chain } = client; + const universalResolverAddress = (() => { + if (parameters.universalResolverAddress) + return parameters.universalResolverAddress; + if (!chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + return getChainContractAddress({ + blockNumber, + chain, + contract: "ensUniversalResolver" }); - const result = decodeFunctionResult({ - abi, - args, - functionName, - data: data || "0x" + })(); + const tlds = chain?.ensTlds; + if (tlds && !tlds.some((tld) => name.endsWith(tld))) + return null; + const args = (() => { + if (coinType != null) + return [namehash(name), BigInt(coinType)]; + return [namehash(name)]; + })(); + try { + const functionData = encodeFunctionData({ + abi: addressResolverAbi, + functionName: "addr", + args }); - const minimizedAbi = abi.filter((abiItem) => ("name" in abiItem) && abiItem.name === parameters.functionName); - return { - result, - request: { - abi: minimizedAbi, - address, - args, - dataSuffix, - functionName, - ...callRequest, - account - } + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverResolveAbi, + functionName: "resolveWithGateways", + args: [ + toHex(packetToBytes(name)), + functionData, + gatewayUrls ?? [localBatchGatewayUrl] + ], + blockNumber, + blockTag }; - } catch (error) { - throw getContractError(error, { - abi, - address, + const readContractAction = getAction(client, readContract, "readContract"); + const res = await readContractAction(readContractParameters); + if (res[0] === "0x") + return null; + const address = decodeAddress2({ coinType, data: res[0], args }); + if (address === "0x") + return null; + if (trim(address) === "0x00") + return null; + return address; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err)) + return null; + throw err; + } +} +function decodeAddress2({ coinType, data, args }) { + try { + return decodeFunctionResult({ + abi: addressResolverAbi, args, - docsPath: "/docs/contract/simulateContract", - functionName, - sender: account?.address + functionName: "addr", + data }); + } catch (err) { + if (coinType == null) + throw err; + const address = trim(data); + if (size2(address) === 20) + return getAddress(address); + throw err; } } -// ../viem/src/_esm/actions/public/watchContractEvent.js -init_abi(); -init_rpc(); +// ../viem/src/_esm/errors/ens.js +init_base(); -// ../viem/src/_esm/utils/observe.js -var listenersCache = /* @__PURE__ */ new Map; -var cleanupCache = /* @__PURE__ */ new Map; -var callbackCount = 0; -function observe(observerId, callbacks, fn) { - const callbackId = ++callbackCount; - const getListeners = () => listenersCache.get(observerId) || []; - const unsubscribe = () => { - const listeners2 = getListeners(); - const nextListeners = listeners2.filter((cb) => cb.id !== callbackId); - if (nextListeners.length === 0) { - listenersCache.delete(observerId); - cleanupCache.delete(observerId); - return; - } - listenersCache.set(observerId, nextListeners); - }; - const unwatch = () => { - const listeners2 = getListeners(); - if (!listeners2.some((cb) => cb.id === callbackId)) - return; - const cleanup2 = cleanupCache.get(observerId); - if (listeners2.length === 1 && cleanup2) { - const p = cleanup2(); - if (p instanceof Promise) - p.catch(() => {}); - } - unsubscribe(); - }; - const listeners = getListeners(); - listenersCache.set(observerId, [ - ...listeners, - { id: callbackId, fns: callbacks } - ]); - if (listeners && listeners.length > 0) - return unwatch; - const emit = {}; - for (const key in callbacks) { - emit[key] = (...args) => { - const listeners2 = getListeners(); - if (listeners2.length === 0) - return; - for (const listener of listeners2) - listener.fns[key]?.(...args); - }; +class EnsAvatarInvalidMetadataError extends BaseError2 { + constructor({ data }) { + super("Unable to extract image from metadata. The metadata may be malformed or invalid.", { + metaMessages: [ + "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.", + "", + `Provided data: ${JSON.stringify(data)}` + ], + name: "EnsAvatarInvalidMetadataError" + }); } - const cleanup = fn(emit); - if (typeof cleanup === "function") - cleanupCache.set(observerId, cleanup); - return unwatch; } -// ../viem/src/_esm/utils/wait.js -async function wait(time, { signal } = {}) { - return new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(getAbortError(signal)); - return; - } - const cleanup = () => signal?.removeEventListener("abort", onAbort); - const timeout = setTimeout(() => { - cleanup(); - resolve(); - }, time); - const onAbort = () => { - clearTimeout(timeout); - cleanup(); - reject(getAbortError(signal)); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} - -// ../viem/src/_esm/utils/poll.js -function poll(fn, { emitOnBegin, initialWaitTime, interval }) { - let active = true; - const unwatch = () => active = false; - const watch = async () => { - let data; - if (emitOnBegin) - data = await fn({ unpoll: unwatch }); - const initialWait = await initialWaitTime?.(data) ?? interval; - await wait(initialWait); - const poll2 = async () => { - if (!active) - return; - await fn({ unpoll: unwatch }); - await wait(interval); - poll2(); - }; - poll2(); - }; - watch(); - return unwatch; -} -// ../viem/src/_esm/utils/promise/withCache.js -var promiseCache = /* @__PURE__ */ new Map; -var responseCache = /* @__PURE__ */ new Map; -function getCache(cacheKey) { - const buildCache = (cacheKey2, cache) => ({ - clear: () => cache.delete(cacheKey2), - get: () => cache.get(cacheKey2), - set: (data) => cache.set(cacheKey2, data) - }); - const promise = buildCache(cacheKey, promiseCache); - const response = buildCache(cacheKey, responseCache); - return { - clear: () => { - promise.clear(); - response.clear(); - }, - promise, - response - }; -} -async function withCache(fn, { cacheKey, cacheTime = Number.POSITIVE_INFINITY }) { - const cache = getCache(cacheKey); - const response = cache.response.get(); - if (response && cacheTime > 0) { - const age = Date.now() - response.created.getTime(); - if (age < cacheTime) - return response.data; - } - let promise = cache.promise.get(); - if (!promise) { - promise = fn(); - cache.promise.set(promise); - } - try { - const data = await promise; - cache.response.set({ created: new Date, data }); - return data; - } finally { - cache.promise.clear(); +class EnsAvatarInvalidNftUriError extends BaseError2 { + constructor({ reason }) { + super(`ENS NFT avatar URI is invalid. ${reason}`, { + name: "EnsAvatarInvalidNftUriError" + }); } } -// ../viem/src/_esm/actions/public/getBlockNumber.js -var cacheKey = (id) => `blockNumber.${id}`; -async function getBlockNumber(client, { cacheTime = client.cacheTime } = {}) { - const blockNumberHex = await withCache(() => client.request({ - method: "eth_blockNumber" - }), { cacheKey: cacheKey(client.uid), cacheTime }); - return BigInt(blockNumberHex); -} - -// ../viem/src/_esm/actions/public/getFilterChanges.js -async function getFilterChanges(_client, { filter }) { - const strict = "strict" in filter && filter.strict; - const logs = await filter.request({ - method: "eth_getFilterChanges", - params: [filter.id] - }); - if (typeof logs[0] === "string") - return logs; - const formattedLogs = logs.map((log) => formatLog(log)); - if (!("abi" in filter) || !filter.abi) - return formattedLogs; - return parseEventLogs({ - abi: filter.abi, - logs: formattedLogs, - strict - }); +class EnsAvatarUriResolutionError extends BaseError2 { + constructor({ uri }) { + super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" }); + } } -// ../viem/src/_esm/actions/public/uninstallFilter.js -async function uninstallFilter(_client, { filter }) { - return filter.request({ - method: "eth_uninstallFilter", - params: [filter.id] - }); +class EnsAvatarUnsupportedNamespaceError extends BaseError2 { + constructor({ namespace }) { + super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" }); + } } -// ../viem/src/_esm/actions/public/watchContractEvent.js -function watchContractEvent(client, parameters) { - const { abi, address, args, batch = true, eventName, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ } = parameters; - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (typeof fromBlock === "bigint") - return true; - if (client.transport.type === "webSocket" || client.transport.type === "ipc") +// ../viem/src/_esm/utils/ens/avatar/utils.js +var networkRegex = /(?https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/; +var ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/; +var base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/; +var dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/; +async function isImageUri(uri) { + try { + const res = await fetch(uri, { method: "HEAD" }); + if (res.status === 200) { + const contentType = res.headers.get("content-type"); + return contentType?.startsWith("image/"); + } + return false; + } catch (error) { + if (typeof error === "object" && typeof error.response !== "undefined") { return false; - if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc")) + } + if (!Object.hasOwn(globalThis, "Image")) return false; - return true; - })(); - const pollContractEvent = () => { - const strict = strict_ ?? false; - const observerId = stringify([ - "watchContractEvent", - address, - args, - batch, - client.uid, - eventName, - pollingInterval, - strict, - fromBlock - ]); - return observe(observerId, { onLogs, onError }, (emit) => { - let previousBlockNumber; - if (fromBlock !== undefined) - previousBlockNumber = fromBlock - 1n; - let filter; - let initialized = false; - const unwatch = poll(async () => { - if (!initialized) { - try { - filter = await getAction(client, createContractEventFilter, "createContractEventFilter")({ - abi, - address, - args, - eventName, - strict, - fromBlock - }); - } catch {} - initialized = true; - return; - } - try { - let logs; - if (filter) { - logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter }); - } else { - const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); - if (previousBlockNumber && previousBlockNumber < blockNumber) { - logs = await getAction(client, getContractEvents, "getContractEvents")({ - abi, - address, - args, - eventName, - fromBlock: previousBlockNumber + 1n, - toBlock: blockNumber, - strict - }); - } else { - logs = []; - } - previousBlockNumber = blockNumber; - } - if (logs.length === 0) - return; - if (batch) - emit.onLogs(logs); - else - for (const log of logs) - emit.onLogs([log]); - } catch (err) { - if (filter && err instanceof InvalidInputRpcError) - initialized = false; - emit.onError?.(err); - } - }, { - emitOnBegin: true, - interval: pollingInterval - }); - return async () => { - if (filter) - await getAction(client, uninstallFilter, "uninstallFilter")({ filter }); - unwatch(); + return new Promise((resolve) => { + const img = new Image; + img.onload = () => { + resolve(true); + }; + img.onerror = () => { + resolve(false); }; + img.src = uri; }); - }; - const subscribeContractEvent = () => { - const strict = strict_ ?? false; - const observerId = stringify([ - "watchContractEvent", - address, - args, - batch, - client.uid, - eventName, - pollingInterval, - strict - ]); - let active = true; - let unsubscribe = () => active = false; - return observe(observerId, { onLogs, onError }, (emit) => { - (async () => { - try { - const transport = (() => { - if (client.transport.type === "fallback") { - const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); - if (!transport2) - return client.transport; - return transport2.value; - } - return client.transport; - })(); - const topics = eventName ? encodeEventTopics({ - abi, - eventName, - args - }) : []; - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["logs", { address, topics }], - onData(data) { - if (!active) - return; - const log = data.result; - try { - const { eventName: eventName2, args: args2 } = decodeEventLog({ - abi, - data: log.data, - topics: log.topics, - strict: strict_ - }); - const formatted = formatLog(log, { - args: args2, - eventName: eventName2 - }); - emit.onLogs([formatted]); - } catch (err) { - let eventName2; - let isUnnamed; - if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { - if (strict_) - return; - eventName2 = err.abiItem.name; - isUnnamed = err.abiItem.inputs?.some((x) => !(("name" in x) && x.name)); - } - const formatted = formatLog(log, { - args: isUnnamed ? [] : {}, - eventName: eventName2 - }); - emit.onLogs([formatted]); - } - }, - onError(error) { - emit.onError?.(error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError?.(err); - } - })(); - return () => unsubscribe(); + } +} +function getGateway(custom, defaultGateway) { + if (!custom) + return defaultGateway; + if (custom.endsWith("/")) + return custom.slice(0, -1); + return custom; +} +function resolveAvatarUri({ uri, gatewayUrls }) { + const isEncoded = base64Regex.test(uri); + if (isEncoded) + return { uri, isOnChain: true, isEncoded }; + const ipfsGateway = getGateway(gatewayUrls?.ipfs, "https://ipfs.io"); + const arweaveGateway = getGateway(gatewayUrls?.arweave, "https://arweave.net"); + const networkRegexMatch = uri.match(networkRegex); + const { protocol, subpath, target, subtarget = "" } = networkRegexMatch?.groups || {}; + const isIPNS = protocol === "ipns:/" || subpath === "ipns/"; + const isIPFS = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri); + if (uri.startsWith("http") && !isIPNS && !isIPFS) { + let replacedUri = uri; + if (gatewayUrls?.arweave) + replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls?.arweave); + return { uri: replacedUri, isOnChain: false, isEncoded: false }; + } + if ((isIPNS || isIPFS) && target) { + return { + uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`, + isOnChain: false, + isEncoded: false + }; + } + if (protocol === "ar:/" && target) { + return { + uri: `${arweaveGateway}/${target}${subtarget || ""}`, + isOnChain: false, + isEncoded: false + }; + } + let parsedUri = uri.replace(dataURIRegex, ""); + if (parsedUri.startsWith(" res2.json()); + const image = await parseAvatarUri({ + gatewayUrls, + uri: getJsonImage(res) + }); + return image; + } catch { + throw new EnsAvatarUriResolutionError({ uri }); + } +} +async function parseAvatarUri({ gatewayUrls, uri }) { + const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls }); + if (isOnChain) + return resolvedURI; + const isImage = await isImageUri(resolvedURI); + if (isImage) + return resolvedURI; + throw new EnsAvatarUriResolutionError({ uri }); +} +function parseNftUri(uri_) { + let uri = uri_; + if (uri.startsWith("did:nft:")) { + uri = uri.replace("did:nft:", "").replace(/_/g, "/"); + } + const [reference, asset_namespace, tokenID] = uri.split("/"); + const [eip_namespace, chainID] = reference.split(":"); + const [erc_namespace, contractAddress] = asset_namespace.split(":"); + if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155") + throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" }); + if (!chainID) + throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" }); + if (!contractAddress) + throw new EnsAvatarInvalidNftUriError({ + reason: "Contract address not found" }); + if (!tokenID) + throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" }); + if (!erc_namespace) + throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" }); + return { + chainID: Number.parseInt(chainID, 10), + namespace: erc_namespace.toLowerCase(), + contractAddress, + tokenID }; - return enablePolling ? pollContractEvent() : subscribeContractEvent(); } -// ../viem/src/_esm/errors/account.js -init_base(); - -class AccountNotFoundError extends BaseError2 { - constructor({ docsPath: docsPath8 } = {}) { - super([ - "Could not find an Account to execute with this Action.", - "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client." - ].join(` -`), { - docsPath: docsPath8, - docsSlug: "account", - name: "AccountNotFoundError" +async function getNftTokenUri(client, { nft }) { + if (nft.namespace === "erc721") { + return readContract(client, { + address: nft.contractAddress, + abi: [ + { + name: "tokenURI", + type: "function", + stateMutability: "view", + inputs: [{ name: "tokenId", type: "uint256" }], + outputs: [{ name: "", type: "string" }] + } + ], + functionName: "tokenURI", + args: [BigInt(nft.tokenID)] }); } -} - -class AccountTypeNotSupportedError extends BaseError2 { - constructor({ docsPath: docsPath8, metaMessages, type }) { - super(`Account type "${type}" is not supported.`, { - docsPath: docsPath8, - metaMessages, - name: "AccountTypeNotSupportedError" + if (nft.namespace === "erc1155") { + return readContract(client, { + address: nft.contractAddress, + abi: [ + { + name: "uri", + type: "function", + stateMutability: "view", + inputs: [{ name: "_id", type: "uint256" }], + outputs: [{ name: "", type: "string" }] + } + ], + functionName: "uri", + args: [BigInt(nft.tokenID)] }); } + throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace }); } -// ../viem/src/_esm/actions/wallet/writeContract.js -init_encodeFunctionData(); -// ../viem/src/_esm/actions/wallet/sendTransaction.js -init_base(); - -// ../viem/src/_esm/utils/chain/assertCurrentChain.js -init_chain(); -function assertCurrentChain({ chain, currentChainId }) { - if (!chain) - throw new ChainNotFoundError; - if (currentChainId !== chain.id) - throw new ChainMismatchError({ chain, currentChainId }); +// ../viem/src/_esm/utils/ens/avatar/parseAvatarRecord.js +async function parseAvatarRecord(client, { gatewayUrls, record }) { + if (/eip155:/i.test(record)) + return parseNftAvatarUri(client, { gatewayUrls, record }); + return parseAvatarUri({ uri: record, gatewayUrls }); } -// ../viem/src/_esm/actions/wallet/sendTransaction.js -init_transactionRequest(); -init_lru(); -init_assertRequest(); - -// ../viem/src/_esm/actions/wallet/sendRawTransaction.js -async function sendRawTransaction(client, { serializedTransaction }) { - return client.request({ - method: "eth_sendRawTransaction", - params: [serializedTransaction] - }, { retryCount: 0 }); +async function parseNftAvatarUri(client, { gatewayUrls, record }) { + const nft = parseNftUri(record); + const nftUri = await getNftTokenUri(client, { nft }); + const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls }); + if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) { + const encodedJson = isEncoded ? atob(resolvedNftUri.replace("data:application/json;base64,", "")) : resolvedNftUri; + const decoded = JSON.parse(encodedJson); + return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls }); + } + let uriTokenId = nft.tokenID; + if (nft.namespace === "erc1155") + uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0"); + return getMetadataAvatarUri({ + gatewayUrls, + uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId) + }); } -// ../viem/src/_esm/actions/wallet/sendTransaction.js -var supportsWalletNamespace = new LruMap(128); -async function sendTransaction(client, parameters) { - const { account: account_ = client.account, assertChainId = true, chain = client.chain, accessList, authorizationList, blobs, data, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, type, value, ...rest } = parameters; - if (typeof account_ === "undefined") - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/sendTransaction" - }); - const account = account_ ? parseAccount(account_) : null; - let nonceManagerParameters; - try { - assertRequest(parameters); - const to = await (async () => { - if (parameters.to) - return parameters.to; - if (parameters.to === null) - return; - if (authorizationList && authorizationList.length > 0) - return await recoverAuthorizationAddress({ - authorization: authorizationList[0] - }).catch(() => { - throw new BaseError2("`to` is required. Could not infer from `authorizationList`."); - }); - return; - })(); - if (account?.type === "json-rpc" || account === null) { - let chainId; - if (chain !== null) { - chainId = await getAction(client, getChainId, "getChainId")({}); - if (assertChainId) - assertCurrentChain({ - currentChainId: chainId, - chain - }); - } - const chainFormat = client.chain?.formatters?.transactionRequest?.format; - const format2 = chainFormat || formatTransactionRequest; - const request = format2({ - ...extract(rest, { format: chainFormat }), - accessList, - account, - authorizationList, - blobs, - chainId, - data: dataSuffix ? concat([data ?? "0x", dataSuffix]) : data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to, - type, - value - }, "sendTransaction"); - const isWalletNamespaceSupported = supportsWalletNamespace.get(client.uid); - const method = isWalletNamespaceSupported ? "wallet_sendTransaction" : "eth_sendTransaction"; - try { - return await client.request({ - method, - params: [request] - }, { retryCount: 0 }); - } catch (e) { - if (isWalletNamespaceSupported === false) - throw e; - const error = e; - if (error.name === "InvalidInputRpcError" || error.name === "InvalidParamsRpcError" || error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError") { - return await client.request({ - method: "wallet_sendTransaction", - params: [request] - }, { retryCount: 0 }).then((hash2) => { - supportsWalletNamespace.set(client.uid, true); - return hash2; - }).catch((e2) => { - const walletNamespaceError = e2; - if (walletNamespaceError.name === "MethodNotFoundRpcError" || walletNamespaceError.name === "MethodNotSupportedRpcError") { - supportsWalletNamespace.set(client.uid, false); - throw error; - } - throw walletNamespaceError; - }); - } - throw error; - } - } - if (account?.type === "local") { - const nonceManager = (() => { - if (!account.nonceManager || typeof nonce !== "undefined") - return account.nonceManager; - const nonceManager2 = account.nonceManager; - return { - consume(parameters2) { - nonceManagerParameters = { - address: parameters2.address, - chainId: parameters2.chainId - }; - return nonceManager2.consume(parameters2); - }, - get(parameters2) { - return nonceManager2.get(parameters2); - }, - increment(parameters2) { - return nonceManager2.increment(parameters2); - }, - reset(parameters2) { - return nonceManager2.reset(parameters2); - } - }; - })(); - const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({ - account, - accessList, - authorizationList, - blobs, - chain, - data: dataSuffix ? concat([data ?? "0x", dataSuffix]) : data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - nonceManager, - parameters: [...defaultParameters, "sidecars"], - type, - value, - ...rest, - to - }); - const serializer = chain?.serializers?.transaction; - const serializedTransaction = await account.signTransaction(request, { - serializer - }); - return await getAction(client, sendRawTransaction, "sendRawTransaction")({ - serializedTransaction - }); - } - if (account?.type === "smart") - throw new AccountTypeNotSupportedError({ - metaMessages: [ - "Consider using the `sendUserOperation` Action instead." - ], - docsPath: "/docs/actions/bundler/sendUserOperation", - type: "smart" - }); - throw new AccountTypeNotSupportedError({ - docsPath: "/docs/actions/wallet/sendTransaction", - type: account?.type +// ../viem/src/_esm/actions/ens/getEnsText.js +init_abis(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_getChainContractAddress(); +init_toHex(); +init_localBatchGatewayRequest(); +async function getEnsText(client, parameters) { + const { blockNumber, blockTag, key, name, gatewayUrls, strict } = parameters; + const { chain } = client; + const universalResolverAddress = (() => { + if (parameters.universalResolverAddress) + return parameters.universalResolverAddress; + if (!chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + return getChainContractAddress({ + blockNumber, + chain, + contract: "ensUniversalResolver" + }); + })(); + const tlds = chain?.ensTlds; + if (tlds && !tlds.some((tld) => name.endsWith(tld))) + return null; + try { + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverResolveAbi, + args: [ + toHex(packetToBytes(name)), + encodeFunctionData({ + abi: textResolverAbi, + functionName: "text", + args: [namehash(name), key] + }), + gatewayUrls ?? [localBatchGatewayUrl] + ], + functionName: "resolveWithGateways", + blockNumber, + blockTag + }; + const readContractAction = getAction(client, readContract, "readContract"); + const res = await readContractAction(readContractParameters); + if (res[0] === "0x") + return null; + const record = decodeFunctionResult({ + abi: textResolverAbi, + functionName: "text", + data: res[0] }); + return record === "" ? null : record; } catch (err) { - if (err instanceof AccountTypeNotSupportedError) + if (strict) throw err; - if (nonceManagerParameters) - account?.nonceManager?.reset(nonceManagerParameters); - throw getTransactionError(err, { - ...parameters, - account, - chain: parameters.chain || undefined - }); + if (isNullUniversalResolverError(err)) + return null; + throw err; } } -// ../viem/src/_esm/actions/wallet/writeContract.js -async function writeContract(client, parameters) { - return writeContract.internal(client, sendTransaction, "sendTransaction", parameters); -} -(function(writeContract2) { - async function internal(client, actionFn, name, parameters) { - const { abi, account: account_ = client.account, address, args, functionName, ...request } = parameters; - if (typeof account_ === "undefined") - throw new AccountNotFoundError({ - docsPath: "/docs/contract/writeContract" - }); - const account = account_ ? parseAccount(account_) : null; - const data = encodeFunctionData({ - abi, - args, - functionName +// ../viem/src/_esm/actions/ens/getEnsAvatar.js +async function getEnsAvatar(client, { blockNumber, blockTag, assetGatewayUrls, name, gatewayUrls, strict, universalResolverAddress }) { + const record = await getAction(client, getEnsText, "getEnsText")({ + blockNumber, + blockTag, + key: "avatar", + name, + universalResolverAddress, + gatewayUrls, + strict + }); + if (!record) + return null; + try { + return await parseAvatarRecord(client, { + record, + gatewayUrls: assetGatewayUrls }); - try { - return await getAction(client, actionFn, name)({ - data, - to: address, - account, - ...request - }); - } catch (error) { - throw getContractError(error, { - abi, - address, - args, - docsPath: "/docs/contract/writeContract", - functionName, - sender: account?.address - }); - } + } catch { + return null; } - writeContract2.internal = internal; -})(writeContract || (writeContract = {})); - -// ../viem/src/_esm/actions/wallet/waitForCallsStatus.js -init_base(); - -// ../viem/src/_esm/errors/calls.js -init_base(); +} -class BundleFailedError extends BaseError2 { - constructor(result) { - super(`Call bundle failed with status: ${result.statusCode}`, { - name: "BundleFailedError" - }); - Object.defineProperty(this, "result", { - enumerable: true, - configurable: true, - writable: true, - value: undefined +// ../viem/src/_esm/actions/ens/getEnsName.js +init_abis(); +init_getChainContractAddress(); +init_localBatchGatewayRequest(); +async function getEnsName(client, parameters) { + const { address, blockNumber, blockTag, coinType = 60n, gatewayUrls, strict } = parameters; + const { chain } = client; + const universalResolverAddress = (() => { + if (parameters.universalResolverAddress) + return parameters.universalResolverAddress; + if (!chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + return getChainContractAddress({ + blockNumber, + chain, + contract: "ensUniversalResolver" }); - this.result = result; + })(); + try { + const readContractParameters = { + address: universalResolverAddress, + abi: universalResolverReverseAbi, + args: [address, coinType, gatewayUrls ?? [localBatchGatewayUrl]], + functionName: "reverseWithGateways", + blockNumber, + blockTag + }; + const readContractAction = getAction(client, readContract, "readContract"); + const [name] = await readContractAction(readContractParameters); + return name || null; + } catch (err) { + if (strict) + throw err; + if (isNullUniversalResolverError(err)) + return null; + throw err; } } -// ../viem/src/_esm/utils/promise/withRetry.js -function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry = () => true, signal } = {}) { - return new Promise((resolve, reject) => { - const attemptRetry = async ({ count = 0 } = {}) => { - if (signal?.aborted) { - reject(getAbortError(signal)); - return; - } - const retry = async ({ error }) => { - const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_; - if (delay) { - try { - await wait(delay, { signal }); - } catch (err) { - reject(err); - return; - } - } - return attemptRetry({ count: count + 1 }); - }; - try { - const data = await fn(); - resolve(data); - } catch (err) { - if (signal?.aborted) { - reject(getAbortError(signal)); - return; - } - if (isAbortError(err)) { - reject(err); - return; - } - if (count < retryCount && await shouldRetry({ count, error: err })) - return retry({ error: err }); - reject(err); + +// ../viem/src/_esm/actions/ens/getEnsResolver.js +init_getChainContractAddress(); +init_toHex(); +async function getEnsResolver(client, parameters) { + const { blockNumber, blockTag, name } = parameters; + const { chain } = client; + const universalResolverAddress = (() => { + if (parameters.universalResolverAddress) + return parameters.universalResolverAddress; + if (!chain) + throw new Error("client chain not configured. universalResolverAddress is required."); + return getChainContractAddress({ + blockNumber, + chain, + contract: "ensUniversalResolver" + }); + })(); + const tlds = chain?.ensTlds; + if (tlds && !tlds.some((tld) => name.endsWith(tld))) + throw new Error(`${name} is not a valid ENS TLD (${tlds?.join(", ")}) for chain "${chain.name}" (id: ${chain.id}).`); + const [resolverAddress] = await getAction(client, readContract, "readContract")({ + address: universalResolverAddress, + abi: [ + { + inputs: [{ type: "bytes" }], + name: "findResolver", + outputs: [ + { type: "address" }, + { type: "bytes32" }, + { type: "uint256" } + ], + stateMutability: "view", + type: "function" } - }; - attemptRetry().catch(reject); + ], + functionName: "findResolver", + args: [toHex(packetToBytes(name))], + blockNumber, + blockTag }); + return resolverAddress; } -// ../viem/src/_esm/actions/wallet/getCallsStatus.js -init_slice(); -init_fromHex(); -// ../viem/src/_esm/utils/formatters/transactionReceipt.js -init_fromHex(); -var receiptStatuses = { - "0x0": "reverted", - "0x1": "success" -}; -function formatTransactionReceipt(transactionReceipt, _) { - const receipt = { - ...transactionReceipt, - blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null, - contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null, - cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null, - effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null, - gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null, - logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null, - to: transactionReceipt.to ? transactionReceipt.to : null, - transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null, - status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null, - type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null - }; - if (transactionReceipt.blobGasPrice) - receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice); - if (transactionReceipt.blobGasUsed) - receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed); - return receipt; -} +// ../viem/src/_esm/clients/decorators/public.js +init_call(); -// ../viem/src/_esm/actions/wallet/sendCalls.js +// ../viem/src/_esm/actions/public/createAccessList.js init_base(); -init_rpc(); -init_encodeFunctionData(); -init_fromHex(); init_toHex(); -var fallbackMagicIdentifier = "0x5792579257925792579257925792579257925792579257925792579257925792"; -var fallbackTransactionErrorMagicIdentifier = numberToHex(0, { - size: 32 -}); -async function sendCalls(client, parameters) { - const { account: account_ = client.account, chain = client.chain, experimental_fallback, experimental_fallbackDelay = 32, forceAtomic = false, id, version: version4 = "2.0.0" } = parameters; - const account = account_ ? parseAccount(account_) : null; - let capabilities = parameters.capabilities; - if (client.dataSuffix && !parameters.capabilities?.dataSuffix) { - if (typeof client.dataSuffix === "string") - capabilities = { - ...parameters.capabilities, - dataSuffix: { value: client.dataSuffix, optional: true } - }; - else - capabilities = { - ...parameters.capabilities, - dataSuffix: { - value: client.dataSuffix.value, - ...client.dataSuffix.required ? {} : { optional: true } - } - }; - } - const calls = parameters.calls.map((call_) => { - const call2 = call_; - const data = call2.abi ? encodeFunctionData({ - abi: call2.abi, - functionName: call2.functionName, - args: call2.args - }) : call2.data; - return { - data: call2.dataSuffix && data ? concat([data, call2.dataSuffix]) : data, - to: call2.to, - value: call2.value ? numberToHex(call2.value) : undefined - }; - }); +init_getCallError(); +init_transactionRequest(); +init_assertRequest(); +async function createAccessList(client, args) { + const { account: account_ = client.account, blockNumber, blockTag = "latest", blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, to, value, ...rest } = args; + const account = account_ ? parseAccount(account_) : undefined; try { + assertRequest(args); + const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : undefined; + const block = blockNumberHex || blockTag; + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format2 = chainFormat || formatTransactionRequest; + const request = format2({ + ...extract(rest, { format: chainFormat }), + account, + blobs, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + to, + value + }, "createAccessList"); const response = await client.request({ - method: "wallet_sendCalls", - params: [ - { - atomicRequired: forceAtomic, - calls, - capabilities, - chainId: numberToHex(chain.id), - from: account?.address, - id, - version: version4 - } - ] - }, { retryCount: 0 }); - if (typeof response === "string") - return { id: response }; - return response; + method: "eth_createAccessList", + params: [request, block] + }); + if (response.error) + throw new BaseError2(response.error, { details: response.error }); + return { + accessList: response.accessList, + gasUsed: BigInt(response.gasUsed) + }; } catch (err) { - const error = err; - if (experimental_fallback && (error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError" || error.name === "UnknownRpcError" || error.details.toLowerCase().includes("does not exist / is not available") || error.details.toLowerCase().includes("missing or invalid. request()") || error.details.toLowerCase().includes("did not match any variant of untagged enum") || error.details.toLowerCase().includes("account upgraded to unsupported contract") || error.details.toLowerCase().includes("eip-7702 not supported") || error.details.toLowerCase().includes("unsupported wc_ method") || error.details.toLowerCase().includes("feature toggled misconfigured") || error.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))) { - if (capabilities) { - const hasNonOptionalCapability = Object.values(capabilities).some((capability) => !capability.optional); - if (hasNonOptionalCapability) { - const message = "non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`."; - throw new UnsupportedNonOptionalCapabilityError(new BaseError2(message, { - details: message - })); - } - } - if (forceAtomic && calls.length > 1) { - const message = "`forceAtomic` is not supported on fallback to `eth_sendTransaction`."; - throw new AtomicityNotSupportedError(new BaseError2(message, { - details: message - })); - } - const results = []; - for (const call2 of calls) { - try { - const value = await sendTransaction(client, { - account, - chain, - data: call2.data, - to: call2.to, - value: call2.value ? hexToBigInt(call2.value) : undefined - }); - results.push({ status: "fulfilled", value }); - } catch (reason) { - results.push({ reason, status: "rejected" }); - } - if (experimental_fallbackDelay > 0) - await new Promise((resolve) => setTimeout(resolve, experimental_fallbackDelay)); - } - if (results.every((r) => r.status === "rejected")) - throw results[0].reason; - const hashes = results.map((result) => { - if (result.status === "fulfilled") - return result.value; - return fallbackTransactionErrorMagicIdentifier; - }); - return { - id: concat([ - ...hashes, - numberToHex(chain.id, { size: 32 }), - fallbackMagicIdentifier - ]) - }; - } - throw getTransactionError(err, { - ...parameters, + throw getCallError(err, { + ...args, account, - chain: parameters.chain + chain: client.chain }); } } -// ../viem/src/_esm/actions/wallet/getCallsStatus.js -async function getCallsStatus(client, parameters) { - async function getStatus(id) { - const isTransactions = id.endsWith(fallbackMagicIdentifier.slice(2)); - if (isTransactions) { - const chainId2 = trim(sliceHex(id, -64, -32)); - const hashes = sliceHex(id, 0, -64).slice(2).match(/.{1,64}/g); - const receipts2 = await Promise.all(hashes.map((hash2) => fallbackTransactionErrorMagicIdentifier.slice(2) !== hash2 ? client.request({ - method: "eth_getTransactionReceipt", - params: [`0x${hash2}`] - }, { dedupe: true }) : undefined)); - const status2 = (() => { - if (receipts2.some((r) => r === null)) - return 100; - if (receipts2.every((r) => r?.status === "0x1")) - return 200; - if (receipts2.every((r) => r?.status === "0x0")) - return 500; - return 600; - })(); - return { - atomic: false, - chainId: hexToNumber(chainId2), - receipts: receipts2.filter(Boolean), - status: status2, - version: "2.0.0" - }; - } - return client.request({ - method: "wallet_getCallsStatus", - params: [id] +// ../viem/src/_esm/utils/filters/createFilterRequestScope.js +function createFilterRequestScope(client, { method }) { + const requestMap = {}; + if (client.transport.type === "fallback") + client.transport.onResponse?.(({ method: method_, response: id, status, transport }) => { + if (status === "success" && method === method_) + requestMap[id] = transport.request; }); - } - const { atomic = false, chainId, receipts, version: version4 = "2.0.0", ...response } = await getStatus(parameters.id); - const [status, statusCode] = (() => { - const statusCode2 = response.status; - if (statusCode2 >= 100 && statusCode2 < 200) - return ["pending", statusCode2]; - if (statusCode2 >= 200 && statusCode2 < 300) - return ["success", statusCode2]; - if (statusCode2 >= 300 && statusCode2 < 700) - return ["failure", statusCode2]; - if (statusCode2 === "CONFIRMED") - return ["success", 200]; - if (statusCode2 === "PENDING") - return ["pending", 100]; - return [undefined, statusCode2]; - })(); - return { - ...response, - atomic, - chainId: chainId ? hexToNumber(chainId) : undefined, - receipts: receipts?.map((receipt) => ({ - ...receipt, - blockNumber: hexToBigInt(receipt.blockNumber), - gasUsed: hexToBigInt(receipt.gasUsed), - status: receiptStatuses[receipt.status] - })) ?? [], - statusCode, - status, - version: version4 - }; + return (id) => requestMap[id] || client.request; } -// ../viem/src/_esm/actions/wallet/waitForCallsStatus.js -async function waitForCallsStatus(client, parameters) { - const { - id, - pollingInterval = client.pollingInterval, - status = ({ statusCode }) => statusCode === 200 || statusCode >= 300, - retryCount = 4, - retryDelay = ({ count }) => ~~(1 << count) * 200, - timeout = 60000, - throwOnFailure = false - } = parameters; - const observerId = stringify(["waitForCallsStatus", client.uid, id]); - const { promise, resolve, reject } = withResolvers(); - let timer; - const unobserve = observe(observerId, { resolve, reject }, (emit) => { - const unpoll = poll(async () => { - const done = (fn) => { - clearTimeout(timer); - unpoll(); - fn(); - unobserve(); - }; - try { - const result = await withRetry(async () => { - const result2 = await getAction(client, getCallsStatus, "getCallsStatus")({ id }); - if (throwOnFailure && result2.status === "failure") - throw new BundleFailedError(result2); - return result2; - }, { - retryCount, - delay: retryDelay - }); - if (!status(result)) - return; - done(() => emit.resolve(result)); - } catch (error) { - done(() => emit.reject(error)); - } - }, { - interval: pollingInterval, - emitOnBegin: true - }); - return unpoll; +// ../viem/src/_esm/actions/public/createBlockFilter.js +async function createBlockFilter(client) { + const getRequest = createFilterRequestScope(client, { + method: "eth_newBlockFilter" }); - timer = timeout ? setTimeout(() => { - unobserve(); - clearTimeout(timer); - reject(new WaitForCallsStatusTimeoutError({ id })); - }, timeout) : undefined; - return await promise; + const id = await client.request({ + method: "eth_newBlockFilter" + }); + return { id, request: getRequest(id), type: "block" }; } -class WaitForCallsStatusTimeoutError extends BaseError2 { - constructor({ id }) { - super(`Timed out while waiting for call bundle with id "${id}" to be confirmed.`, { name: "WaitForCallsStatusTimeoutError" }); +// ../viem/src/_esm/utils/abi/encodeEventTopics.js +init_abi(); + +// ../viem/src/_esm/errors/log.js +init_base(); + +class FilterTypeNotSupportedError extends BaseError2 { + constructor(type) { + super(`Filter type "${type}" is not supported.`, { + name: "FilterTypeNotSupportedError" + }); } } -// ../viem/src/_esm/utils/uid.js -var size4 = 256; -var index = size4; -var buffer; -function uid(length = 11) { - if (!buffer || index + length > size4 * 2) { - buffer = ""; - index = 0; - const bytes4 = new Uint8Array(size4); - globalThis.crypto.getRandomValues(bytes4); - for (let i = 0;i < size4; i++) { - buffer += (256 + bytes4[i]).toString(16).substring(1); + +// ../viem/src/_esm/utils/abi/encodeEventTopics.js +init_toBytes(); +init_keccak256(); +init_toEventSelector(); +init_encodeAbiParameters(); +init_formatAbiItem2(); +init_getAbiItem(); +var docsPath6 = "/docs/contract/encodeEventTopics"; +function encodeEventTopics(parameters) { + const { abi, eventName, args } = parameters; + let abiItem = abi[0]; + if (eventName) { + const item = getAbiItem({ abi, name: eventName }); + if (!item) + throw new AbiEventNotFoundError(eventName, { docsPath: docsPath6 }); + abiItem = item; + } + if (abiItem.type !== "event") + throw new AbiEventNotFoundError(undefined, { docsPath: docsPath6 }); + let topics = []; + if (args && "inputs" in abiItem) { + const indexedInputs = abiItem.inputs?.filter((param) => ("indexed" in param) && param.indexed); + const args_ = Array.isArray(args) ? args : Object.values(args).length > 0 ? indexedInputs?.map((x) => args[x.name]) ?? [] : []; + if (args_.length > 0) { + topics = indexedInputs?.map((param, i) => { + if (Array.isArray(args_[i])) + return args_[i].map((_, j) => encodeArg({ param, value: args_[i][j] })); + return typeof args_[i] !== "undefined" && args_[i] !== null ? encodeArg({ param, value: args_[i] }) : null; + }) ?? []; } } - return buffer.substring(index, index++ + length); + if (abiItem.anonymous) + return topics; + const definition = formatAbiItem2(abiItem); + const signature = toEventSelector(definition); + return [signature, ...topics]; +} +function encodeArg({ param, value }) { + if (param.type === "string" || param.type === "bytes") + return keccak256(toBytes(value)); + if (param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) + throw new FilterTypeNotSupportedError(param.type); + return encodeAbiParameters([param], [value]); } -// ../viem/src/_esm/clients/createClient.js -function createClient(parameters) { - const { batch, chain, ccipRead, dataSuffix, key = "base", name = "Base Client", tokens, type = "base" } = parameters; - const experimental_blockTag = parameters.experimental_blockTag ?? (typeof chain?.experimental_preconfirmationTime === "number" ? "pending" : undefined); - const blockTime = chain?.blockTime ?? 12000; - const defaultPollingInterval = Math.min(Math.max(Math.floor(blockTime / 2), 500), 4000); - const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval; - const cacheTime = parameters.cacheTime ?? pollingInterval; - const account = parameters.account ? parseAccount(parameters.account) : undefined; - const { config, request, value } = parameters.transport({ - account, - chain, - pollingInterval +// ../viem/src/_esm/actions/public/createContractEventFilter.js +init_toHex(); +async function createContractEventFilter(client, parameters) { + const { address, abi, args, eventName, fromBlock, strict, toBlock } = parameters; + const getRequest = createFilterRequestScope(client, { + method: "eth_newFilter" }); - const transport = { ...config, ...value }; - const client = { - account, - batch, - cacheTime, - ccipRead, - chain, - dataSuffix, - key, - name, - pollingInterval, - request, - tokens, - transport, - type, - uid: uid(), - ...experimental_blockTag ? { experimental_blockTag } : {} - }; - function extend(base) { - return (extendFn) => { - const extended = extendFn(base); - for (const key2 in client) - delete extended[key2]; - const combined = { ...base, ...extended }; - for (const key2 in extended) { - const a = base[key2]; - const b = extended[key2]; - if (isPlainObject(a) && isPlainObject(b)) - combined[key2] = { ...a, ...b }; + const topics = eventName ? encodeEventTopics({ + abi, + args, + eventName + }) : undefined; + const id = await client.request({ + method: "eth_newFilter", + params: [ + { + address, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, + topics } - return Object.assign(combined, { extend: extend(combined) }); - }; - } - return Object.assign(client, { extend: extend(client) }); + ] + }); + return { + abi, + args, + eventName, + id, + request: getRequest(id), + strict: Boolean(strict), + type: "event" + }; } -function isPlainObject(value) { - if (typeof value !== "object" || value === null) - return false; - const prototype = Object.getPrototypeOf(value); - return prototype === Object.prototype || prototype === null; + +// ../viem/src/_esm/actions/public/createEventFilter.js +init_toHex(); +async function createEventFilter(client, { address, args, event, events: events_, fromBlock, strict, toBlock } = {}) { + const events = events_ ?? (event ? [event] : undefined); + const getRequest = createFilterRequestScope(client, { + method: "eth_newFilter" + }); + let topics = []; + if (events) { + const encoded = events.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + const id = await client.request({ + method: "eth_newFilter", + params: [ + { + address, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, + ...topics.length ? { topics } : {} + } + ] + }); + return { + abi: events, + args, + eventName: event ? event.name : undefined, + fromBlock, + id, + request: getRequest(id), + strict: Boolean(strict), + toBlock, + type: "event" + }; } -function bindActionDecorators(client, action) { - const wrapped = (parameters = {}) => action(client, parameters); - for (const key of [ - "call", - "calls", - "callWithPeriod", - "estimateGas", - "prepare", - "prepareRecipient", - "predict", - "simulate" - ]) - if (Object.hasOwn(action, key)) { - const helper = action[key]; - wrapped[key] = (args = {}) => { - if (helper.length === 1) - return helper(args); - return helper(client, args); - }; - } - for (const key of ["extractEvent", "extractEvents"]) - if (Object.hasOwn(action, key)) - wrapped[key] = action[key]; - return wrapped; + +// ../viem/src/_esm/actions/public/createPendingTransactionFilter.js +async function createPendingTransactionFilter(client) { + const getRequest = createFilterRequestScope(client, { + method: "eth_newPendingTransactionFilter" + }); + const id = await client.request({ + method: "eth_newPendingTransactionFilter" + }); + return { id, request: getRequest(id), type: "transaction" }; } -// ../viem/src/_esm/actions/ens/getEnsAddress.js -init_abis(); -init_decodeFunctionResult(); +// ../viem/src/_esm/actions/public/estimateContractGas.js init_encodeFunctionData(); -init_getAddress(); -init_getChainContractAddress(); -init_size(); -init_toHex(); -// ../viem/src/_esm/utils/ens/errors.js +// ../viem/src/_esm/actions/public/estimateGas.js init_base(); -init_contract(); -function isNullUniversalResolverError(err) { - if (!(err instanceof BaseError2)) - return false; - const cause = err.walk((e) => e instanceof ContractFunctionRevertedError); - if (!(cause instanceof ContractFunctionRevertedError)) - return false; - if (cause.data?.errorName === "HttpError") - return true; - if (cause.data?.errorName === "ResolverError") - return true; - if (cause.data?.errorName === "ResolverNotContract") - return true; - if (cause.data?.errorName === "ResolverNotFound") - return true; - if (cause.data?.errorName === "ReverseAddressMismatch") - return true; - if (cause.data?.errorName === "UnsupportedResolverProfile") - return true; - return false; -} - -// ../viem/src/_esm/actions/ens/getEnsAddress.js -init_localBatchGatewayRequest(); -// ../viem/src/_esm/utils/ens/namehash.js -init_toBytes(); -init_toHex(); +// ../viem/src/_esm/accounts/utils/publicKeyToAddress.js +init_getAddress(); init_keccak256(); +function publicKeyToAddress(publicKey) { + const address = keccak256(`0x${publicKey.substring(4)}`).substring(26); + return checksumAddress(`0x${address}`); +} -// ../viem/src/_esm/utils/ens/encodedLabelToLabelhash.js -function encodedLabelToLabelhash(label) { - if (label.length !== 66) - return null; - if (label.indexOf("[") !== 0) - return null; - if (label.indexOf("]") !== 65) - return null; - const hash2 = `0x${label.slice(1, 65)}`; - if (!isHex(hash2)) - return null; - return hash2; +// ../viem/src/_esm/utils/signature/recoverPublicKey.js +init_size(); +init_fromHex(); +init_toHex(); +async function recoverPublicKey({ hash: hash2, signature }) { + const hashHex = isHex(hash2) ? hash2 : toHex(hash2); + const { secp256k1: secp256k12 } = await Promise.resolve().then(() => (init_secp256k1(), exports_secp256k1)); + const signature_ = (() => { + if (typeof signature === "object" && "r" in signature && "s" in signature) { + const { r, s, v, yParity } = signature; + const yParityOrV2 = Number(yParity ?? v); + const recoveryBit2 = toRecoveryBit(yParityOrV2); + return new secp256k12.Signature(hexToBigInt(r), hexToBigInt(s)).addRecoveryBit(recoveryBit2); + } + const signatureHex = isHex(signature) ? signature : toHex(signature); + if (size2(signatureHex) !== 65) + throw new Error("invalid signature length"); + const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`); + const recoveryBit = toRecoveryBit(yParityOrV); + return secp256k12.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit); + })(); + const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false); + return `0x${publicKey}`; +} +function toRecoveryBit(yParityOrV) { + if (yParityOrV === 0 || yParityOrV === 1) + return yParityOrV; + if (yParityOrV === 27) + return 0; + if (yParityOrV === 28) + return 1; + throw new Error("Invalid yParityOrV value"); } -// ../viem/src/_esm/utils/ens/namehash.js -function namehash(name) { - let result = new Uint8Array(32).fill(0); - if (!name) - return bytesToHex(result); - const labels = name.split("."); - for (let i = labels.length - 1;i >= 0; i -= 1) { - const hashFromEncodedLabel = encodedLabelToLabelhash(labels[i]); - const hashed = hashFromEncodedLabel ? toBytes(hashFromEncodedLabel) : keccak256(stringToBytes(labels[i]), "bytes"); - result = keccak256(concat([result, hashed]), "bytes"); - } - return bytesToHex(result); +// ../viem/src/_esm/utils/signature/recoverAddress.js +async function recoverAddress({ hash: hash2, signature }) { + return publicKeyToAddress(await recoverPublicKey({ hash: hash2, signature })); } -// ../viem/src/_esm/utils/ens/packetToBytes.js +// ../viem/src/_esm/utils/authorization/hashAuthorization.js init_toBytes(); +init_toHex(); -// ../viem/src/_esm/utils/ens/encodeLabelhash.js -function encodeLabelhash(hash2) { - return `[${hash2.slice(2)}]`; -} - -// ../viem/src/_esm/utils/ens/labelhash.js +// ../viem/src/_esm/utils/encoding/toRlp.js +init_base(); +init_cursor2(); init_toBytes(); init_toHex(); -init_keccak256(); -function labelhash(label) { - const result = new Uint8Array(32).fill(0); - if (!label) - return bytesToHex(result); - return encodedLabelToLabelhash(label) || keccak256(stringToBytes(label)); +function toRlp(bytes, to = "hex") { + const encodable = getEncodable(bytes); + const cursor = createCursor(new Uint8Array(encodable.length)); + encodable.encode(cursor); + if (to === "hex") + return bytesToHex(cursor.bytes); + return cursor.bytes; } - -// ../viem/src/_esm/utils/ens/packetToBytes.js -function packetToBytes(packet) { - const value = packet.replace(/^\.|\.$/gm, ""); - if (value.length === 0) - return new Uint8Array(1); - const bytes = new Uint8Array(stringToBytes(value).byteLength + 2); - let offset = 0; - const list = value.split("."); - for (let i = 0;i < list.length; i++) { - let encoded = stringToBytes(list[i]); - if (encoded.byteLength > 255) - encoded = stringToBytes(encodeLabelhash(labelhash(list[i]))); - bytes[offset] = encoded.length; - bytes.set(encoded, offset + 1); - offset += encoded.length + 1; - } - if (bytes.byteLength !== offset + 1) - return bytes.slice(0, offset + 1); - return bytes; +function getEncodable(bytes) { + if (Array.isArray(bytes)) + return getEncodableList(bytes.map((x) => getEncodable(x))); + return getEncodableBytes(bytes); } - -// ../viem/src/_esm/actions/ens/getEnsAddress.js -async function getEnsAddress(client, parameters) { - const { blockNumber, blockTag, coinType, name, gatewayUrls, strict } = parameters; - const { chain } = client; - const universalResolverAddress = (() => { - if (parameters.universalResolverAddress) - return parameters.universalResolverAddress; - if (!chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - return getChainContractAddress({ - blockNumber, - chain, - contract: "ensUniversalResolver" - }); +function getEncodableList(list) { + const bodyLength = list.reduce((acc, x) => acc + x.length, 0); + const sizeOfBodyLength = getSizeOfLength(bodyLength); + const length = (() => { + if (bodyLength <= 55) + return 1 + bodyLength; + return 1 + sizeOfBodyLength + bodyLength; })(); - const tlds = chain?.ensTlds; - if (tlds && !tlds.some((tld) => name.endsWith(tld))) - return null; - const args = (() => { - if (coinType != null) - return [namehash(name), BigInt(coinType)]; - return [namehash(name)]; + return { + length, + encode(cursor) { + if (bodyLength <= 55) { + cursor.pushByte(192 + bodyLength); + } else { + cursor.pushByte(192 + 55 + sizeOfBodyLength); + if (sizeOfBodyLength === 1) + cursor.pushUint8(bodyLength); + else if (sizeOfBodyLength === 2) + cursor.pushUint16(bodyLength); + else if (sizeOfBodyLength === 3) + cursor.pushUint24(bodyLength); + else + cursor.pushUint32(bodyLength); + } + for (const { encode } of list) { + encode(cursor); + } + } + }; +} +function getEncodableBytes(bytesOrHex) { + const bytes = typeof bytesOrHex === "string" ? hexToBytes(bytesOrHex) : bytesOrHex; + const sizeOfBytesLength = getSizeOfLength(bytes.length); + const length = (() => { + if (bytes.length === 1 && bytes[0] < 128) + return 1; + if (bytes.length <= 55) + return 1 + bytes.length; + return 1 + sizeOfBytesLength + bytes.length; })(); - try { - const functionData = encodeFunctionData({ - abi: addressResolverAbi, - functionName: "addr", - args - }); - const readContractParameters = { - address: universalResolverAddress, - abi: universalResolverResolveAbi, - functionName: "resolveWithGateways", - args: [ - toHex(packetToBytes(name)), - functionData, - gatewayUrls ?? [localBatchGatewayUrl] - ], - blockNumber, - blockTag - }; - const readContractAction = getAction(client, readContract, "readContract"); - const res = await readContractAction(readContractParameters); - if (res[0] === "0x") - return null; - const address = decodeAddress2({ coinType, data: res[0], args }); - if (address === "0x") - return null; - if (trim(address) === "0x00") - return null; - return address; - } catch (err) { - if (strict) - throw err; - if (isNullUniversalResolverError(err)) - return null; - throw err; - } + return { + length, + encode(cursor) { + if (bytes.length === 1 && bytes[0] < 128) { + cursor.pushBytes(bytes); + } else if (bytes.length <= 55) { + cursor.pushByte(128 + bytes.length); + cursor.pushBytes(bytes); + } else { + cursor.pushByte(128 + 55 + sizeOfBytesLength); + if (sizeOfBytesLength === 1) + cursor.pushUint8(bytes.length); + else if (sizeOfBytesLength === 2) + cursor.pushUint16(bytes.length); + else if (sizeOfBytesLength === 3) + cursor.pushUint24(bytes.length); + else + cursor.pushUint32(bytes.length); + cursor.pushBytes(bytes); + } + } + }; } -function decodeAddress2({ coinType, data, args }) { - try { - return decodeFunctionResult({ - abi: addressResolverAbi, - args, - functionName: "addr", - data - }); - } catch (err) { - if (coinType == null) - throw err; - const address = trim(data); - if (size(address) === 20) - return getAddress(address); - throw err; - } +function getSizeOfLength(length) { + if (length < 2 ** 8) + return 1; + if (length < 2 ** 16) + return 2; + if (length < 2 ** 24) + return 3; + if (length < 2 ** 32) + return 4; + throw new BaseError2("Length is too large."); } -// ../viem/src/_esm/errors/ens.js +// ../viem/src/_esm/utils/authorization/hashAuthorization.js +init_keccak256(); +function hashAuthorization(parameters) { + const { chainId, nonce, to } = parameters; + const address = parameters.contractAddress ?? parameters.address; + const hash2 = keccak256(concatHex([ + "0x05", + toRlp([ + chainId ? numberToHex(chainId) : "0x", + address, + nonce ? numberToHex(nonce) : "0x" + ]) + ])); + if (to === "bytes") + return hexToBytes(hash2); + return hash2; +} + +// ../viem/src/_esm/utils/authorization/recoverAuthorizationAddress.js +async function recoverAuthorizationAddress(parameters) { + const { authorization, signature } = parameters; + return recoverAddress({ + hash: hashAuthorization(authorization), + signature: signature ?? authorization + }); +} + +// ../viem/src/_esm/actions/public/estimateGas.js +init_toHex(); + +// ../viem/src/_esm/errors/estimateGas.js +init_formatEther(); +init_formatGwei(); init_base(); +init_transaction(); -class EnsAvatarInvalidMetadataError extends BaseError2 { - constructor({ data }) { - super("Unable to extract image from metadata. The metadata may be malformed or invalid.", { +class EstimateGasExecutionError extends BaseError2 { + constructor(cause, { account, docsPath: docsPath7, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value }) { + const prettyArgs = prettyPrint({ + from: account?.address, + to, + value: typeof value !== "undefined" && `${formatEther2(value)} ${chain?.nativeCurrency?.symbol || "ETH"}`, + data, + gas, + gasPrice: typeof gasPrice !== "undefined" && `${formatGwei2(gasPrice)} gwei`, + maxFeePerGas: typeof maxFeePerGas !== "undefined" && `${formatGwei2(maxFeePerGas)} gwei`, + maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== "undefined" && `${formatGwei2(maxPriorityFeePerGas)} gwei`, + nonce + }); + super(cause.shortMessage, { + cause, + docsPath: docsPath7, metaMessages: [ - "- Metadata must be a JSON object with at least an `image`, `image_url` or `image_data` property.", - "", - `Provided data: ${JSON.stringify(data)}` - ], - name: "EnsAvatarInvalidMetadataError" + ...cause.metaMessages ? [...cause.metaMessages, " "] : [], + "Estimate Gas Arguments:", + prettyArgs + ].filter(Boolean), + name: "EstimateGasExecutionError" + }); + Object.defineProperty(this, "cause", { + enumerable: true, + configurable: true, + writable: true, + value: undefined }); + this.cause = cause; } } -class EnsAvatarInvalidNftUriError extends BaseError2 { - constructor({ reason }) { - super(`ENS NFT avatar URI is invalid. ${reason}`, { - name: "EnsAvatarInvalidNftUriError" +// ../viem/src/_esm/utils/errors/getEstimateGasError.js +init_node(); +init_getNodeError(); +function getEstimateGasError(err, { docsPath: docsPath7, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new EstimateGasExecutionError(cause, { + docsPath: docsPath7, + ...args + }); +} + +// ../viem/src/_esm/actions/public/estimateGas.js +init_transactionRequest(); +init_stateOverride2(); +init_assertRequest(); +// ../viem/src/_esm/errors/fee.js +init_formatGwei(); +init_base(); + +class BaseFeeScalarError extends BaseError2 { + constructor() { + super("`baseFeeMultiplier` must be greater than 1.", { + name: "BaseFeeScalarError" }); } } -class EnsAvatarUriResolutionError extends BaseError2 { - constructor({ uri }) { - super(`Unable to resolve ENS avatar URI "${uri}". The URI may be malformed, invalid, or does not respond with a valid image.`, { name: "EnsAvatarUriResolutionError" }); +class Eip1559FeesNotSupportedError extends BaseError2 { + constructor() { + super("Chain does not support EIP-1559 fees.", { + name: "Eip1559FeesNotSupportedError" + }); } } -class EnsAvatarUnsupportedNamespaceError extends BaseError2 { - constructor({ namespace }) { - super(`ENS NFT avatar namespace "${namespace}" is not supported. Must be "erc721" or "erc1155".`, { name: "EnsAvatarUnsupportedNamespaceError" }); +class MaxFeePerGasTooLowError extends BaseError2 { + constructor({ maxPriorityFeePerGas }) { + super(`\`maxFeePerGas\` cannot be less than the \`maxPriorityFeePerGas\` (${formatGwei2(maxPriorityFeePerGas)} gwei).`, { name: "MaxFeePerGasTooLowError" }); } } -// ../viem/src/_esm/utils/ens/avatar/utils.js -var networkRegex = /(?https?:\/\/[^/]*|ipfs:\/|ipns:\/|ar:\/)?(?\/)?(?ipfs\/|ipns\/)?(?[\w\-.]+)(?\/.*)?/; -var ipfsHashRegex = /^(Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,})(\/(?[\w\-.]+))?(?\/.*)?$/; -var base64Regex = /^data:([a-zA-Z\-/+]*);base64,([^"].*)/; -var dataURIRegex = /^data:([a-zA-Z\-/+]*)?(;[a-zA-Z0-9].*?)?(,)/; -async function isImageUri(uri) { - try { - const res = await fetch(uri, { method: "HEAD" }); - if (res.status === 200) { - const contentType = res.headers.get("content-type"); - return contentType?.startsWith("image/"); - } - return false; - } catch (error) { - if (typeof error === "object" && typeof error.response !== "undefined") { - return false; - } - if (!Object.hasOwn(globalThis, "Image")) - return false; - return new Promise((resolve) => { - const img = new Image; - img.onload = () => { - resolve(true); - }; - img.onerror = () => { - resolve(false); - }; - img.src = uri; - }); - } -} -function getGateway(custom, defaultGateway) { - if (!custom) - return defaultGateway; - if (custom.endsWith("/")) - return custom.slice(0, -1); - return custom; -} -function resolveAvatarUri({ uri, gatewayUrls }) { - const isEncoded = base64Regex.test(uri); - if (isEncoded) - return { uri, isOnChain: true, isEncoded }; - const ipfsGateway = getGateway(gatewayUrls?.ipfs, "https://ipfs.io"); - const arweaveGateway = getGateway(gatewayUrls?.arweave, "https://arweave.net"); - const networkRegexMatch = uri.match(networkRegex); - const { protocol, subpath, target, subtarget = "" } = networkRegexMatch?.groups || {}; - const isIPNS = protocol === "ipns:/" || subpath === "ipns/"; - const isIPFS = protocol === "ipfs:/" || subpath === "ipfs/" || ipfsHashRegex.test(uri); - if (uri.startsWith("http") && !isIPNS && !isIPFS) { - let replacedUri = uri; - if (gatewayUrls?.arweave) - replacedUri = uri.replace(/https:\/\/arweave.net/g, gatewayUrls?.arweave); - return { uri: replacedUri, isOnChain: false, isEncoded: false }; - } - if ((isIPNS || isIPFS) && target) { - return { - uri: `${ipfsGateway}/${isIPNS ? "ipns" : "ipfs"}/${target}${subtarget}`, - isOnChain: false, - isEncoded: false - }; - } - if (protocol === "ar:/" && target) { - return { - uri: `${arweaveGateway}/${target}${subtarget || ""}`, - isOnChain: false, - isEncoded: false - }; - } - let parsedUri = uri.replace(dataURIRegex, ""); - if (parsedUri.startsWith(" { + if (transaction.yParity) + return Number(transaction.yParity); + if (typeof transaction_.v === "bigint") { + if (transaction_.v === 0n || transaction_.v === 27n) + return 0; + if (transaction_.v === 1n || transaction_.v === 28n) + return 1; + if (transaction_.v >= 35n) + return transaction_.v % 2n === 0n ? 1 : 0; + } + return; + })(); + if (transaction_.type === "legacy") { + delete transaction_.accessList; + delete transaction_.maxFeePerBlobGas; + delete transaction_.maxFeePerGas; + delete transaction_.maxPriorityFeePerGas; + delete transaction_.yParity; } - return data.image || data.image_url || data.image_data; -} -async function getMetadataAvatarUri({ gatewayUrls, uri }) { - try { - const res = await fetch(uri).then((res2) => res2.json()); - const image = await parseAvatarUri({ - gatewayUrls, - uri: getJsonImage(res) - }); - return image; - } catch { - throw new EnsAvatarUriResolutionError({ uri }); + if (transaction_.type === "eip2930") { + delete transaction_.maxFeePerBlobGas; + delete transaction_.maxFeePerGas; + delete transaction_.maxPriorityFeePerGas; } + if (transaction_.type === "eip1559") + delete transaction_.maxFeePerBlobGas; + return transaction_; } -async function parseAvatarUri({ gatewayUrls, uri }) { - const { uri: resolvedURI, isOnChain } = resolveAvatarUri({ uri, gatewayUrls }); - if (isOnChain) - return resolvedURI; - const isImage = await isImageUri(resolvedURI); - if (isImage) - return resolvedURI; - throw new EnsAvatarUriResolutionError({ uri }); +function formatAuthorizationList2(authorizationList) { + return authorizationList.map((authorization) => ({ + address: authorization.address, + chainId: Number(authorization.chainId), + nonce: Number(authorization.nonce), + r: authorization.r, + s: authorization.s, + yParity: Number(authorization.yParity) + })); } -function parseNftUri(uri_) { - let uri = uri_; - if (uri.startsWith("did:nft:")) { - uri = uri.replace("did:nft:", "").replace(/_/g, "/"); - } - const [reference, asset_namespace, tokenID] = uri.split("/"); - const [eip_namespace, chainID] = reference.split(":"); - const [erc_namespace, contractAddress] = asset_namespace.split(":"); - if (!eip_namespace || eip_namespace.toLowerCase() !== "eip155") - throw new EnsAvatarInvalidNftUriError({ reason: "Only EIP-155 supported" }); - if (!chainID) - throw new EnsAvatarInvalidNftUriError({ reason: "Chain ID not found" }); - if (!contractAddress) - throw new EnsAvatarInvalidNftUriError({ - reason: "Contract address not found" - }); - if (!tokenID) - throw new EnsAvatarInvalidNftUriError({ reason: "Token ID not found" }); - if (!erc_namespace) - throw new EnsAvatarInvalidNftUriError({ reason: "ERC namespace not found" }); + +// ../viem/src/_esm/utils/formatters/block.js +function formatBlock(block, _) { + const transactions = (block.transactions ?? []).map((transaction) => { + if (typeof transaction === "string") + return transaction; + return formatTransaction(transaction); + }); return { - chainID: Number.parseInt(chainID, 10), - namespace: erc_namespace.toLowerCase(), - contractAddress, - tokenID + ...block, + baseFeePerGas: block.baseFeePerGas ? BigInt(block.baseFeePerGas) : null, + blobGasUsed: block.blobGasUsed ? BigInt(block.blobGasUsed) : undefined, + difficulty: block.difficulty ? BigInt(block.difficulty) : undefined, + excessBlobGas: block.excessBlobGas ? BigInt(block.excessBlobGas) : undefined, + gasLimit: block.gasLimit ? BigInt(block.gasLimit) : undefined, + gasUsed: block.gasUsed ? BigInt(block.gasUsed) : undefined, + hash: block.hash ? block.hash : null, + logsBloom: block.logsBloom ? block.logsBloom : null, + nonce: block.nonce ? block.nonce : null, + number: block.number ? BigInt(block.number) : null, + size: block.size ? BigInt(block.size) : undefined, + timestamp: block.timestamp ? BigInt(block.timestamp) : undefined, + transactions, + totalDifficulty: block.totalDifficulty ? BigInt(block.totalDifficulty) : null }; } -async function getNftTokenUri(client, { nft }) { - if (nft.namespace === "erc721") { - return readContract(client, { - address: nft.contractAddress, - abi: [ - { - name: "tokenURI", - type: "function", - stateMutability: "view", - inputs: [{ name: "tokenId", type: "uint256" }], - outputs: [{ name: "", type: "string" }] - } - ], - functionName: "tokenURI", - args: [BigInt(nft.tokenID)] - }); - } - if (nft.namespace === "erc1155") { - return readContract(client, { - address: nft.contractAddress, - abi: [ - { - name: "uri", - type: "function", - stateMutability: "view", - inputs: [{ name: "_id", type: "uint256" }], - outputs: [{ name: "", type: "string" }] - } - ], - functionName: "uri", - args: [BigInt(nft.tokenID)] - }); + +// ../viem/src/_esm/actions/public/getBlock.js +async function getBlock(client, { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", includeTransactions: includeTransactions_ } = {}) { + const includeTransactions = includeTransactions_ ?? false; + const blockNumberHex = blockNumber !== undefined ? numberToHex(blockNumber) : undefined; + let block = null; + if (blockHash) { + block = await client.request({ + method: "eth_getBlockByHash", + params: [blockHash, includeTransactions] + }, { dedupe: true }); + } else { + block = await client.request({ + method: "eth_getBlockByNumber", + params: [blockNumberHex || blockTag, includeTransactions] + }, { dedupe: Boolean(blockNumberHex) }); } - throw new EnsAvatarUnsupportedNamespaceError({ namespace: nft.namespace }); + if (!block) + throw new BlockNotFoundError({ blockHash, blockNumber }); + const format2 = client.chain?.formatters?.block?.format || formatBlock; + return format2(block, "getBlock"); } -// ../viem/src/_esm/utils/ens/avatar/parseAvatarRecord.js -async function parseAvatarRecord(client, { gatewayUrls, record }) { - if (/eip155:/i.test(record)) - return parseNftAvatarUri(client, { gatewayUrls, record }); - return parseAvatarUri({ uri: record, gatewayUrls }); +// ../viem/src/_esm/actions/public/getGasPrice.js +async function getGasPrice(client) { + const gasPrice = await client.request({ + method: "eth_gasPrice" + }); + return BigInt(gasPrice); } -async function parseNftAvatarUri(client, { gatewayUrls, record }) { - const nft = parseNftUri(record); - const nftUri = await getNftTokenUri(client, { nft }); - const { uri: resolvedNftUri, isOnChain, isEncoded } = resolveAvatarUri({ uri: nftUri, gatewayUrls }); - if (isOnChain && (resolvedNftUri.includes("data:application/json;base64,") || resolvedNftUri.startsWith("{"))) { - const encodedJson = isEncoded ? atob(resolvedNftUri.replace("data:application/json;base64,", "")) : resolvedNftUri; - const decoded = JSON.parse(encodedJson); - return parseAvatarUri({ uri: getJsonImage(decoded), gatewayUrls }); + +// ../viem/src/_esm/actions/public/estimateMaxPriorityFeePerGas.js +async function estimateMaxPriorityFeePerGas(client, args) { + return internal_estimateMaxPriorityFeePerGas(client, args); +} +async function internal_estimateMaxPriorityFeePerGas(client, args) { + const { block: block_, chain = client.chain, request } = args || {}; + try { + const maxPriorityFeePerGas = chain?.fees?.maxPriorityFeePerGas ?? chain?.fees?.defaultPriorityFee; + if (typeof maxPriorityFeePerGas === "function") { + const block = block_ || await getAction(client, getBlock, "getBlock")({}); + const maxPriorityFeePerGas_ = await maxPriorityFeePerGas({ + block, + client, + request + }); + if (maxPriorityFeePerGas_ === null) + throw new Error; + return maxPriorityFeePerGas_; + } + if (typeof maxPriorityFeePerGas !== "undefined") + return maxPriorityFeePerGas; + const maxPriorityFeePerGasHex = await client.request({ + method: "eth_maxPriorityFeePerGas" + }); + return hexToBigInt(maxPriorityFeePerGasHex); + } catch { + const [block, gasPrice] = await Promise.all([ + block_ ? Promise.resolve(block_) : getAction(client, getBlock, "getBlock")({}), + getAction(client, getGasPrice, "getGasPrice")({}) + ]); + if (typeof block.baseFeePerGas !== "bigint") + throw new Eip1559FeesNotSupportedError; + const maxPriorityFeePerGas = gasPrice - block.baseFeePerGas; + if (maxPriorityFeePerGas < 0n) + return 0n; + return maxPriorityFeePerGas; } - let uriTokenId = nft.tokenID; - if (nft.namespace === "erc1155") - uriTokenId = uriTokenId.replace("0x", "").padStart(64, "0"); - return getMetadataAvatarUri({ - gatewayUrls, - uri: resolvedNftUri.replace(/(?:0x)?{id}/, uriTokenId) - }); } -// ../viem/src/_esm/actions/ens/getEnsText.js -init_abis(); -init_decodeFunctionResult(); -init_encodeFunctionData(); -init_getChainContractAddress(); -init_toHex(); -init_localBatchGatewayRequest(); -async function getEnsText(client, parameters) { - const { blockNumber, blockTag, key, name, gatewayUrls, strict } = parameters; - const { chain } = client; - const universalResolverAddress = (() => { - if (parameters.universalResolverAddress) - return parameters.universalResolverAddress; - if (!chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - return getChainContractAddress({ - blockNumber, +// ../viem/src/_esm/actions/public/estimateFeesPerGas.js +async function estimateFeesPerGas(client, args) { + return internal_estimateFeesPerGas(client, args); +} +async function internal_estimateFeesPerGas(client, args) { + const { block: block_, chain = client.chain, request, type = "eip1559" } = args || {}; + const baseFeeMultiplier = await (async () => { + if (typeof chain?.fees?.baseFeeMultiplier === "function") + return chain.fees.baseFeeMultiplier({ + block: block_, + client, + request + }); + return chain?.fees?.baseFeeMultiplier ?? 1.2; + })(); + if (baseFeeMultiplier < 1) + throw new BaseFeeScalarError; + const decimals = baseFeeMultiplier.toString().split(".")[1]?.length ?? 0; + const denominator = 10 ** decimals; + const multiply = (base) => base * BigInt(Math.round(baseFeeMultiplier * denominator)) / BigInt(denominator); + const block = block_ ? block_ : await getAction(client, getBlock, "getBlock")({}); + if (typeof chain?.fees?.estimateFeesPerGas === "function") { + const fees = await chain.fees.estimateFeesPerGas({ + block: block_, + client, + multiply, + request, + type + }); + if (fees !== null) + return fees; + } + if (type === "eip1559") { + if (typeof block.baseFeePerGas !== "bigint") + throw new Eip1559FeesNotSupportedError; + const maxPriorityFeePerGas = typeof request?.maxPriorityFeePerGas === "bigint" ? request.maxPriorityFeePerGas : await internal_estimateMaxPriorityFeePerGas(client, { + block, chain, - contract: "ensUniversalResolver" + request }); - })(); - const tlds = chain?.ensTlds; - if (tlds && !tlds.some((tld) => name.endsWith(tld))) - return null; - try { - const readContractParameters = { - address: universalResolverAddress, - abi: universalResolverResolveAbi, - args: [ - toHex(packetToBytes(name)), - encodeFunctionData({ - abi: textResolverAbi, - functionName: "text", - args: [namehash(name), key] - }), - gatewayUrls ?? [localBatchGatewayUrl] - ], - functionName: "resolveWithGateways", - blockNumber, - blockTag + const baseFeePerGas = multiply(block.baseFeePerGas); + const maxFeePerGas = request?.maxFeePerGas ?? baseFeePerGas + maxPriorityFeePerGas; + return { + maxFeePerGas, + maxPriorityFeePerGas }; - const readContractAction = getAction(client, readContract, "readContract"); - const res = await readContractAction(readContractParameters); - if (res[0] === "0x") - return null; - const record = decodeFunctionResult({ - abi: textResolverAbi, - functionName: "text", - data: res[0] - }); - return record === "" ? null : record; - } catch (err) { - if (strict) - throw err; - if (isNullUniversalResolverError(err)) - return null; - throw err; } + const gasPrice = request?.gasPrice ?? multiply(await getAction(client, getGasPrice, "getGasPrice")({})); + return { + gasPrice + }; } -// ../viem/src/_esm/actions/ens/getEnsAvatar.js -async function getEnsAvatar(client, { blockNumber, blockTag, assetGatewayUrls, name, gatewayUrls, strict, universalResolverAddress }) { - const record = await getAction(client, getEnsText, "getEnsText")({ +// ../viem/src/_esm/actions/public/getTransactionCount.js +init_formatBlockParameter(); +init_fromHex(); +async function getTransactionCount(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical }) { + const block = formatBlockParameter({ + blockHash, blockNumber, blockTag, - key: "avatar", - name, - universalResolverAddress, - gatewayUrls, - strict + requireCanonical }); - if (!record) - return null; - try { - return await parseAvatarRecord(client, { - record, - gatewayUrls: assetGatewayUrls - }); - } catch { - return null; - } + const count = await client.request({ + method: "eth_getTransactionCount", + params: [address, block] + }, { + dedupe: typeof blockNumber === "bigint" || blockHash !== undefined + }); + return hexToNumber(count); } -// ../viem/src/_esm/actions/ens/getEnsName.js -init_abis(); -init_getChainContractAddress(); -init_localBatchGatewayRequest(); -async function getEnsName(client, parameters) { - const { address, blockNumber, blockTag, coinType = 60n, gatewayUrls, strict } = parameters; - const { chain } = client; - const universalResolverAddress = (() => { - if (parameters.universalResolverAddress) - return parameters.universalResolverAddress; - if (!chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - return getChainContractAddress({ - blockNumber, - chain, - contract: "ensUniversalResolver" - }); - })(); - try { - const readContractParameters = { - address: universalResolverAddress, - abi: universalResolverReverseAbi, - args: [address, coinType, gatewayUrls ?? [localBatchGatewayUrl]], - functionName: "reverseWithGateways", - blockNumber, - blockTag - }; - const readContractAction = getAction(client, readContract, "readContract"); - const [name] = await readContractAction(readContractParameters); - return name || null; - } catch (err) { - if (strict) - throw err; - if (isNullUniversalResolverError(err)) - return null; - throw err; - } +// ../viem/src/_esm/utils/blob/blobsToCommitments.js +init_toBytes(); +init_toHex(); +function blobsToCommitments(parameters) { + const { kzg } = parameters; + const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs; + const commitments = []; + for (const blob of blobs) + commitments.push(Uint8Array.from(kzg.blobToKzgCommitment(blob))); + return to === "bytes" ? commitments : commitments.map((x) => bytesToHex(x)); } -// ../viem/src/_esm/actions/ens/getEnsResolver.js -init_getChainContractAddress(); +// ../viem/src/_esm/utils/blob/blobsToProofs.js +init_toBytes(); init_toHex(); -async function getEnsResolver(client, parameters) { - const { blockNumber, blockTag, name } = parameters; - const { chain } = client; - const universalResolverAddress = (() => { - if (parameters.universalResolverAddress) - return parameters.universalResolverAddress; - if (!chain) - throw new Error("client chain not configured. universalResolverAddress is required."); - return getChainContractAddress({ - blockNumber, - chain, - contract: "ensUniversalResolver" - }); - })(); - const tlds = chain?.ensTlds; - if (tlds && !tlds.some((tld) => name.endsWith(tld))) - throw new Error(`${name} is not a valid ENS TLD (${tlds?.join(", ")}) for chain "${chain.name}" (id: ${chain.id}).`); - const [resolverAddress] = await getAction(client, readContract, "readContract")({ - address: universalResolverAddress, - abi: [ - { - inputs: [{ type: "bytes" }], - name: "findResolver", - outputs: [ - { type: "address" }, - { type: "bytes32" }, - { type: "uint256" } - ], - stateMutability: "view", - type: "function" - } - ], - functionName: "findResolver", - args: [toHex(packetToBytes(name))], - blockNumber, - blockTag - }); - return resolverAddress; +function blobsToProofs(parameters) { + const { kzg } = parameters; + const to = parameters.to ?? (typeof parameters.blobs[0] === "string" ? "hex" : "bytes"); + const blobs = typeof parameters.blobs[0] === "string" ? parameters.blobs.map((x) => hexToBytes(x)) : parameters.blobs; + const commitments = typeof parameters.commitments[0] === "string" ? parameters.commitments.map((x) => hexToBytes(x)) : parameters.commitments; + const proofs = []; + for (let i = 0;i < blobs.length; i++) { + const blob = blobs[i]; + const commitment = commitments[i]; + proofs.push(Uint8Array.from(kzg.computeBlobKzgProof(blob, commitment))); + } + return to === "bytes" ? proofs : proofs.map((x) => bytesToHex(x)); } -// ../viem/src/_esm/clients/decorators/public.js -init_call(); +// ../viem/src/_esm/utils/blob/commitmentToVersionedHash.js +init_toHex(); -// ../viem/src/_esm/actions/public/createAccessList.js -init_base(); +// ../viem/node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha256.js +init_sha2(); +var sha2562 = sha256; + +// ../viem/src/_esm/utils/hash/sha256.js +init_toBytes(); init_toHex(); -init_getCallError(); -init_transactionRequest(); -init_assertRequest(); -async function createAccessList(client, args) { - const { account: account_ = client.account, blockNumber, blockTag = "latest", blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, to, value, ...rest } = args; - const account = account_ ? parseAccount(account_) : undefined; - try { - assertRequest(args); - const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : undefined; - const block = blockNumberHex || blockTag; - const chainFormat = client.chain?.formatters?.transactionRequest?.format; - const format2 = chainFormat || formatTransactionRequest; - const request = format2({ - ...extract(rest, { format: chainFormat }), - account, - blobs, - data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, +function sha2563(value, to_) { + const to = to_ || "hex"; + const bytes = sha2562(isHex(value, { strict: false }) ? toBytes(value) : value); + if (to === "bytes") + return bytes; + return toHex(bytes); +} + +// ../viem/src/_esm/utils/blob/commitmentToVersionedHash.js +function commitmentToVersionedHash(parameters) { + const { commitment, version: version4 = 1 } = parameters; + const to = parameters.to ?? (typeof commitment === "string" ? "hex" : "bytes"); + const versionedHash = sha2563(commitment, "bytes"); + versionedHash.set([version4], 0); + return to === "bytes" ? versionedHash : bytesToHex(versionedHash); +} + +// ../viem/src/_esm/utils/blob/commitmentsToVersionedHashes.js +function commitmentsToVersionedHashes(parameters) { + const { commitments, version: version4 } = parameters; + const to = parameters.to ?? (typeof commitments[0] === "string" ? "hex" : "bytes"); + const hashes = []; + for (const commitment of commitments) { + hashes.push(commitmentToVersionedHash({ + commitment, to, - value - }, "createAccessList"); - const response = await client.request({ - method: "eth_createAccessList", - params: [request, block] - }); - if (response.error) - throw new BaseError2(response.error, { details: response.error }); - return { - accessList: response.accessList, - gasUsed: BigInt(response.gasUsed) - }; - } catch (err) { - throw getCallError(err, { - ...args, - account, - chain: client.chain + version: version4 + })); + } + return hashes; +} + +// ../viem/src/_esm/constants/blob.js +var blobsPerTransaction = 6; +var bytesPerFieldElement = 32; +var fieldElementsPerBlob = 4096; +var bytesPerBlob = bytesPerFieldElement * fieldElementsPerBlob; +var maxBytesPerTransaction = bytesPerBlob * blobsPerTransaction - 1 - 1 * fieldElementsPerBlob * blobsPerTransaction; + +// ../viem/src/_esm/constants/kzg.js +var versionedHashVersionKzg = 1; + +// ../viem/src/_esm/errors/blob.js +init_base(); + +class BlobSizeTooLargeError extends BaseError2 { + constructor({ maxSize, size: size5 }) { + super("Blob size is too large.", { + metaMessages: [`Max: ${maxSize} bytes`, `Given: ${size5} bytes`], + name: "BlobSizeTooLargeError" }); } } -// ../viem/src/_esm/actions/public/createBlockFilter.js -async function createBlockFilter(client) { - const getRequest = createFilterRequestScope(client, { - method: "eth_newBlockFilter" - }); - const id = await client.request({ - method: "eth_newBlockFilter" - }); - return { id, request: getRequest(id), type: "block" }; +class EmptyBlobError extends BaseError2 { + constructor() { + super("Blob data must not be empty.", { name: "EmptyBlobError" }); + } } -// ../viem/src/_esm/actions/public/createEventFilter.js -init_toHex(); -async function createEventFilter(client, { address, args, event, events: events_, fromBlock, strict, toBlock } = {}) { - const events = events_ ?? (event ? [event] : undefined); - const getRequest = createFilterRequestScope(client, { - method: "eth_newFilter" - }); - let topics = []; - if (events) { - const encoded = events.flatMap((event2) => encodeEventTopics({ - abi: [event2], - eventName: event2.name, - args - })); - topics = [encoded]; - if (event) - topics = topics[0]; +class InvalidVersionedHashSizeError extends BaseError2 { + constructor({ hash: hash2, size: size5 }) { + super(`Versioned hash "${hash2}" size is invalid.`, { + metaMessages: ["Expected: 32", `Received: ${size5}`], + name: "InvalidVersionedHashSizeError" + }); } - const id = await client.request({ - method: "eth_newFilter", - params: [ - { - address, - fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, - toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock, - ...topics.length ? { topics } : {} - } - ] - }); - return { - abi: events, - args, - eventName: event ? event.name : undefined, - fromBlock, - id, - request: getRequest(id), - strict: Boolean(strict), - toBlock, - type: "event" - }; } -// ../viem/src/_esm/actions/public/createPendingTransactionFilter.js -async function createPendingTransactionFilter(client) { - const getRequest = createFilterRequestScope(client, { - method: "eth_newPendingTransactionFilter" - }); - const id = await client.request({ - method: "eth_newPendingTransactionFilter" - }); - return { id, request: getRequest(id), type: "transaction" }; +class InvalidVersionedHashVersionError extends BaseError2 { + constructor({ hash: hash2, version: version4 }) { + super(`Versioned hash "${hash2}" version is invalid.`, { + metaMessages: [ + `Expected: ${versionedHashVersionKzg}`, + `Received: ${version4}` + ], + name: "InvalidVersionedHashVersionError" + }); + } } -// ../viem/src/_esm/actions/public/getBalance.js -init_abis(); -init_decodeFunctionResult(); -init_encodeFunctionData(); -init_formatBlockParameter(); -init_call(); -async function getBalance(client, { address, blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", requireCanonical }) { - const block = formatBlockParameter({ - blockHash, - blockNumber, - blockTag, - requireCanonical - }); - if (client.batch?.multicall && client.chain?.contracts?.multicall3) { - const multicall3Address = client.chain.contracts.multicall3.address; - const calldata = encodeFunctionData({ - abi: multicall3Abi, - functionName: "getEthBalance", - args: [address] - }); - const { data } = await getAction(client, call, "call")({ - to: multicall3Address, - data: calldata, - blockHash, - blockNumber, - blockTag, - requireCanonical - }); - return decodeFunctionResult({ - abi: multicall3Abi, - functionName: "getEthBalance", - args: [address], - data: data || "0x" +// ../viem/src/_esm/utils/blob/toBlobs.js +init_cursor2(); +init_size(); +init_toBytes(); +init_toHex(); +function toBlobs(parameters) { + const to = parameters.to ?? (typeof parameters.data === "string" ? "hex" : "bytes"); + const data = typeof parameters.data === "string" ? hexToBytes(parameters.data) : parameters.data; + const size_ = size2(data); + if (!size_) + throw new EmptyBlobError; + if (size_ > maxBytesPerTransaction) + throw new BlobSizeTooLargeError({ + maxSize: maxBytesPerTransaction, + size: size_ }); + const blobs = []; + let active = true; + let position = 0; + while (active) { + const blob = createCursor(new Uint8Array(bytesPerBlob)); + let size5 = 0; + while (size5 < fieldElementsPerBlob) { + const bytes = data.slice(position, position + (bytesPerFieldElement - 1)); + blob.pushByte(0); + blob.pushBytes(bytes); + if (bytes.length < 31) { + blob.pushByte(128); + active = false; + break; + } + size5++; + position += 31; + } + blobs.push(blob); } - const balance = await client.request({ - method: "eth_getBalance", - params: [address, block] - }); - return BigInt(balance); + return to === "bytes" ? blobs.map((x) => x.bytes) : blobs.map((x) => bytesToHex(x.bytes)); } -// ../viem/src/_esm/actions/public/getBlobBaseFee.js -async function getBlobBaseFee(client) { - const baseFee = await client.request({ - method: "eth_blobBaseFee" - }); - return BigInt(baseFee); +// ../viem/src/_esm/utils/blob/toBlobSidecars.js +function toBlobSidecars(parameters) { + const { data, kzg, to } = parameters; + const blobs = parameters.blobs ?? toBlobs({ data, to }); + const commitments = parameters.commitments ?? blobsToCommitments({ blobs, kzg, to }); + const proofs = parameters.proofs ?? blobsToProofs({ blobs, commitments, kzg, to }); + const sidecars = []; + for (let i = 0;i < blobs.length; i++) + sidecars.push({ + blob: blobs[i], + commitment: commitments[i], + proof: proofs[i] + }); + return sidecars; } -// ../viem/src/_esm/actions/public/getBlockReceipts.js -init_toHex(); -async function getBlockReceipts(client, { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest" } = {}) { - const blockNumberHex = blockNumber !== undefined ? numberToHex(blockNumber) : undefined; - const receipts = await client.request({ - method: "eth_getBlockReceipts", - params: [blockHash || blockNumberHex || blockTag] - }, { dedupe: Boolean(blockHash || blockNumberHex) }); - if (!receipts) - throw new BlockNotFoundError({ blockHash, blockNumber }); - const format2 = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt; - return receipts.map((receipt) => format2(receipt, "getBlockReceipts")); -} +// ../viem/src/_esm/actions/wallet/prepareTransactionRequest.js +init_lru(); +init_assertRequest(); -// ../viem/src/_esm/actions/public/getBlockTransactionCount.js -init_fromHex(); -init_toHex(); -async function getBlockTransactionCount(client, { blockHash, blockNumber, blockTag = "latest" } = {}) { - const blockNumberHex = blockNumber !== undefined ? numberToHex(blockNumber) : undefined; - let count; - if (blockHash) { - count = await client.request({ - method: "eth_getBlockTransactionCountByHash", - params: [blockHash] - }, { dedupe: true }); - } else { - count = await client.request({ - method: "eth_getBlockTransactionCountByNumber", - params: [blockNumberHex || blockTag] - }, { dedupe: Boolean(blockNumberHex) }); +// ../viem/src/_esm/utils/transaction/getTransactionType.js +init_transaction(); +function getTransactionType(transaction) { + if (transaction.type) + return transaction.type; + if (typeof transaction.authorizationList !== "undefined") + return "eip7702"; + if (typeof transaction.blobs !== "undefined" || typeof transaction.blobVersionedHashes !== "undefined" || typeof transaction.maxFeePerBlobGas !== "undefined" || typeof transaction.sidecars !== "undefined") + return "eip4844"; + if (typeof transaction.maxFeePerGas !== "undefined" || typeof transaction.maxPriorityFeePerGas !== "undefined") { + return "eip1559"; } - return hexToNumber(count); + if (typeof transaction.gasPrice !== "undefined") { + if (typeof transaction.accessList !== "undefined") + return "eip2930"; + return "legacy"; + } + throw new InvalidSerializableTransactionError({ transaction }); } - -// ../viem/src/_esm/actions/public/getCode.js -init_formatBlockParameter(); -async function getCode(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical }) { - const block = formatBlockParameter({ - blockHash, - blockNumber, - blockTag, - requireCanonical - }); - const hex = await client.request({ - method: "eth_getCode", - params: [address, block] - }, { - dedupe: typeof blockNumber === "bigint" || blockHash !== undefined +// ../viem/src/_esm/utils/errors/getTransactionError.js +init_node(); +init_transaction(); +init_getNodeError(); +function getTransactionError(err, { docsPath: docsPath7, ...args }) { + const cause = (() => { + const cause2 = getNodeError(err, args); + if (cause2 instanceof UnknownNodeError) + return err; + return cause2; + })(); + return new TransactionExecutionError(cause, { + docsPath: docsPath7, + ...args }); - if (hex === "0x") - return; - return hex; } +// ../viem/src/_esm/actions/public/fillTransaction.js +init_transactionRequest(); +init_assertRequest(); -// ../viem/src/_esm/actions/public/getDelegation.js -init_getAddress(); -init_size(); -init_slice(); -async function getDelegation(client, { address, blockNumber, blockTag = "latest" }) { - const code = await getCode(client, { - address, - ...blockNumber !== undefined ? { blockNumber } : { blockTag } - }); - if (!code) - return; - if (size(code) !== 23) - return; - if (!code.startsWith("0xef0100")) - return; - return getAddress(slice(code, 3, 23)); +// ../viem/src/_esm/actions/public/getChainId.js +init_fromHex(); +async function getChainId(client) { + const chainIdHex = await client.request({ + method: "eth_chainId" + }, { dedupe: true }); + return hexToNumber(chainIdHex); } -// ../viem/src/_esm/errors/eip712.js -init_base(); - -class Eip712DomainNotFoundError extends BaseError2 { - constructor({ address }) { - super(`No EIP-712 domain found on contract "${address}".`, { - metaMessages: [ - "Ensure that:", - `- The contract is deployed at the address "${address}".`, - "- `eip712Domain()` function exists on the contract.", - "- `eip712Domain()` function matches signature to ERC-5267 specification." - ], - name: "Eip712DomainNotFoundError" +// ../viem/src/_esm/actions/public/fillTransaction.js +async function fillTransaction(client, parameters) { + const { account = client.account, accessList, authorizationList, chain = client.chain, blobVersionedHashes, blobs, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce: nonce_, nonceManager, to, type, value, ...rest } = parameters; + const nonce = await (async () => { + if (!account) + return nonce_; + if (!nonceManager) + return nonce_; + if (typeof nonce_ !== "undefined") + return nonce_; + const account_ = parseAccount(account); + const chainId = chain ? chain.id : await getAction(client, getChainId, "getChainId")({}); + return await nonceManager.consume({ + address: account_.address, + chainId, + client }); - } -} - -// ../viem/src/_esm/actions/public/getEip712Domain.js -async function getEip712Domain(client, parameters) { - const { address, factory, factoryData } = parameters; + })(); + assertRequest(parameters); + const chainFormat = chain?.formatters?.transactionRequest?.format; + const format2 = chainFormat || formatTransactionRequest; + const request = format2({ + ...extract(rest, { format: chainFormat }), + account: account ? parseAccount(account) : undefined, + accessList, + authorizationList, + blobs, + blobVersionedHashes, + data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to, + type, + value + }, "fillTransaction"); try { - const [fields, name, version4, chainId, verifyingContract, salt, extensions] = await getAction(client, readContract, "readContract")({ - abi, - address, - functionName: "eip712Domain", - factory, - factoryData - }); + const response = await client.request({ + method: "eth_fillTransaction", + params: [request] + }); + const format3 = chain?.formatters?.transaction?.format || formatTransaction; + const transaction = format3(response.tx); + delete transaction.blockHash; + delete transaction.blockNumber; + delete transaction.r; + delete transaction.s; + delete transaction.transactionIndex; + delete transaction.v; + delete transaction.yParity; + transaction.data = transaction.input; + if (transaction.gas) + transaction.gas = parameters.gas ?? transaction.gas; + if (transaction.gasPrice) + transaction.gasPrice = parameters.gasPrice ?? transaction.gasPrice; + if (transaction.maxFeePerBlobGas) + transaction.maxFeePerBlobGas = parameters.maxFeePerBlobGas ?? transaction.maxFeePerBlobGas; + if (transaction.maxFeePerGas) + transaction.maxFeePerGas = parameters.maxFeePerGas ?? transaction.maxFeePerGas; + if (transaction.maxPriorityFeePerGas) + transaction.maxPriorityFeePerGas = parameters.maxPriorityFeePerGas ?? transaction.maxPriorityFeePerGas; + if (typeof transaction.nonce !== "undefined") + transaction.nonce = parameters.nonce ?? transaction.nonce; + const feeMultiplier = await (async () => { + if (typeof chain?.fees?.baseFeeMultiplier === "function") { + const block = await getAction(client, getBlock, "getBlock")({}); + return chain.fees.baseFeeMultiplier({ + block, + client, + request: parameters + }); + } + return chain?.fees?.baseFeeMultiplier ?? 1.2; + })(); + if (feeMultiplier < 1) + throw new BaseFeeScalarError; + const decimals = feeMultiplier.toString().split(".")[1]?.length ?? 0; + const denominator = 10 ** decimals; + const multiplyFee = (base) => base * BigInt(Math.round(feeMultiplier * denominator)) / BigInt(denominator); + if (!transaction.feePayerSignature) { + if (transaction.maxFeePerGas && !parameters.maxFeePerGas) + transaction.maxFeePerGas = multiplyFee(transaction.maxFeePerGas); + if (transaction.gasPrice && !parameters.gasPrice) + transaction.gasPrice = multiplyFee(transaction.gasPrice); + } return { - domain: { - name, - version: version4, - chainId: Number(chainId), - verifyingContract, - salt + raw: response.raw, + transaction: { + from: request.from, + ...transaction }, - extensions, - fields + ...response.capabilities ? { capabilities: response.capabilities } : {} }; - } catch (e) { - const error = e; - if (error.name === "ContractFunctionExecutionError" && error.cause.name === "ContractFunctionZeroDataError") { - throw new Eip712DomainNotFoundError({ address }); - } - throw error; - } -} -var abi = [ - { - inputs: [], - name: "eip712Domain", - outputs: [ - { name: "fields", type: "bytes1" }, - { name: "name", type: "string" }, - { name: "version", type: "string" }, - { name: "chainId", type: "uint256" }, - { name: "verifyingContract", type: "address" }, - { name: "salt", type: "bytes32" }, - { name: "extensions", type: "uint256[]" } - ], - stateMutability: "view", - type: "function" + } catch (err) { + throw getTransactionError(err, { + ...parameters, + chain: client.chain + }); } -]; - -// ../viem/src/_esm/actions/public/getFeeHistory.js -init_toHex(); - -// ../viem/src/_esm/utils/formatters/feeHistory.js -function formatFeeHistory(feeHistory) { - return { - baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)), - gasUsedRatio: feeHistory.gasUsedRatio, - oldestBlock: BigInt(feeHistory.oldestBlock), - reward: feeHistory.reward?.map((reward) => reward.map((value) => BigInt(value))) - }; -} - -// ../viem/src/_esm/actions/public/getFeeHistory.js -async function getFeeHistory(client, { blockCount, blockNumber, blockTag = "latest", rewardPercentiles }) { - const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : undefined; - const feeHistory = await client.request({ - method: "eth_feeHistory", - params: [ - numberToHex(blockCount), - blockNumberHex || blockTag, - rewardPercentiles - ] - }, { dedupe: Boolean(blockNumberHex) }); - return formatFeeHistory(feeHistory); -} - -// ../viem/src/_esm/actions/public/getFilterLogs.js -async function getFilterLogs(_client, { filter }) { - const strict = filter.strict ?? false; - const logs = await filter.request({ - method: "eth_getFilterLogs", - params: [filter.id] - }); - const formattedLogs = logs.map((log) => formatLog(log)); - if (!filter.abi) - return formattedLogs; - return parseEventLogs({ - abi: filter.abi, - logs: formattedLogs, - strict - }); -} - -// ../viem/src/_esm/actions/public/getProof.js -init_formatBlockParameter(); - -// ../viem/src/_esm/utils/index.js -init_encodeFunctionData(); -// ../viem/src/_esm/utils/data/isBytes.js -function isBytes3(value) { - if (!value) - return false; - if (typeof value !== "object") - return false; - if (!("BYTES_PER_ELEMENT" in value)) - return false; - return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array"; } -// ../viem/src/_esm/utils/address/getContractAddress.js -init_pad(); -init_slice(); -init_toBytes(); -init_keccak256(); -init_getAddress(); -function getCreate2Address(opts) { - const from4 = toBytes(getAddress(opts.from)); - const salt = pad(isBytes3(opts.salt) ? opts.salt : toBytes(opts.salt), { - size: 32 - }); - const bytecodeHash = (() => { - if ("bytecodeHash" in opts) { - if (isBytes3(opts.bytecodeHash)) - return opts.bytecodeHash; - return toBytes(opts.bytecodeHash); - } - return keccak256(opts.bytecode, "bytes"); +// ../viem/src/_esm/actions/wallet/prepareTransactionRequest.js +var defaultParameters = [ + "blobVersionedHashes", + "chainId", + "fees", + "gas", + "nonce", + "type" +]; +var eip1559NetworkCache = /* @__PURE__ */ new Map; +var supportsFillTransaction = /* @__PURE__ */ new LruMap(128); +async function prepareTransactionRequest(client, args) { + let request = args; + request.account ??= client.account; + request.parameters ??= defaultParameters; + const { account: account_, chain = client.chain, nonceManager, parameters } = request; + const prepareTransactionRequest2 = (() => { + if (typeof chain?.prepareTransactionRequest === "function") + return { + fn: chain.prepareTransactionRequest, + runAt: ["beforeFillTransaction"] + }; + if (Array.isArray(chain?.prepareTransactionRequest)) + return { + fn: chain.prepareTransactionRequest[0], + runAt: chain.prepareTransactionRequest[1].runAt + }; + return; })(); - return getAddress(slice(keccak256(concat([toBytes("0xff"), from4, salt, bytecodeHash])), 12)); -} - -// ../viem/src/_esm/utils/authorization/serializeAuthorizationList.js -init_toHex(); - -// ../viem/src/_esm/utils/transaction/serializeTransaction.js -init_transaction(); -init_toHex(); - -// ../viem/src/_esm/utils/transaction/assertTransaction.js -init_number(); -init_address(); -init_base(); -init_chain(); -init_node(); -init_isAddress(); -init_size(); -init_slice(); -init_fromHex(); -function assertTransactionEIP7702(transaction) { - const { authorizationList } = transaction; - if (authorizationList) { - for (const authorization of authorizationList) { - const { chainId } = authorization; - const address = authorization.address; - if (!isAddress(address)) - throw new InvalidAddressError({ address }); - if (chainId < 0) - throw new InvalidChainIdError({ chainId }); - } + let chainId; + async function getChainId2() { + if (chainId) + return chainId; + if (typeof request.chainId !== "undefined") + return request.chainId; + if (chain) + return chain.id; + const chainId_ = await getAction(client, getChainId, "getChainId")({}); + chainId = chainId_; + return chainId; } - assertTransactionEIP1559(transaction); -} -function assertTransactionEIP4844(transaction) { - const { blobVersionedHashes } = transaction; - if (blobVersionedHashes) { - if (blobVersionedHashes.length === 0) - throw new EmptyBlobError; - for (const hash2 of blobVersionedHashes) { - const size_ = size(hash2); - const version4 = hexToNumber(slice(hash2, 0, 1)); - if (size_ !== 32) - throw new InvalidVersionedHashSizeError({ hash: hash2, size: size_ }); - if (version4 !== versionedHashVersionKzg) - throw new InvalidVersionedHashVersionError({ - hash: hash2, - version: version4 - }); - } + let account = account_ ? parseAccount(account_) : account_; + let nonce = request.nonce; + if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillTransaction")) { + request = await prepareTransactionRequest2.fn({ ...request, chain }, { + client, + phase: "beforeFillTransaction" + }); + nonce ??= request.nonce; + const sender = request.account ?? request.from; + account = sender ? parseAccount(sender) : undefined; } - assertTransactionEIP1559(transaction); -} -function assertTransactionEIP1559(transaction) { - const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction; - if (chainId <= 0) - throw new InvalidChainIdError({ chainId }); - if (to && !isAddress(to)) - throw new InvalidAddressError({ address: to }); - if (maxFeePerGas && maxFeePerGas > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas }); - if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) - throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); -} -function assertTransactionEIP2930(transaction) { - const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction; - if (chainId <= 0) - throw new InvalidChainIdError({ chainId }); - if (to && !isAddress(to)) - throw new InvalidAddressError({ address: to }); - if (maxPriorityFeePerGas || maxFeePerGas) - throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute."); - if (gasPrice && gasPrice > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); -} -function assertTransactionLegacy(transaction) { - const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction; - if (to && !isAddress(to)) - throw new InvalidAddressError({ address: to }); - if (typeof chainId !== "undefined" && chainId <= 0) - throw new InvalidChainIdError({ chainId }); - if (maxPriorityFeePerGas || maxFeePerGas) - throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute."); - if (gasPrice && gasPrice > maxUint256) - throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); -} - -// ../viem/src/_esm/utils/transaction/serializeAccessList.js -init_address(); -init_transaction(); -init_isAddress(); -function serializeAccessList(accessList) { - if (!accessList || accessList.length === 0) - return []; - const serializedAccessList = []; - for (let i = 0;i < accessList.length; i++) { - const { address, storageKeys } = accessList[i]; - for (let j = 0;j < storageKeys.length; j++) { - if (storageKeys[j].length - 2 !== 64) { - throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] }); - } - } - if (!isAddress(address, { strict: false })) { - throw new InvalidAddressError({ address }); - } - serializedAccessList.push([address, storageKeys]); + if (parameters.includes("nonce") && typeof nonce === "undefined" && account && nonceManager) { + const chainId2 = await getChainId2(); + nonce = await nonceManager.consume({ + address: account.address, + chainId: chainId2, + client + }); } - return serializedAccessList; -} - -// ../viem/src/_esm/utils/transaction/serializeTransaction.js -function serializeTransaction(transaction, signature) { - const type = getTransactionType(transaction); - if (type === "eip1559") - return serializeTransactionEIP1559(transaction, signature); - if (type === "eip2930") - return serializeTransactionEIP2930(transaction, signature); - if (type === "eip4844") - return serializeTransactionEIP4844(transaction, signature); - if (type === "eip7702") - return serializeTransactionEIP7702(transaction, signature); - return serializeTransactionLegacy(transaction, signature); -} -function serializeTransactionEIP7702(transaction, signature) { - const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; - assertTransactionEIP7702(transaction); - const serializedAccessList = serializeAccessList(accessList); - const serializedAuthorizationList = serializeAuthorizationList(authorizationList); - return concatHex([ - "0x04", - toRlp([ - numberToHex(chainId), - nonce ? numberToHex(nonce) : "0x", - maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x", - maxFeePerGas ? numberToHex(maxFeePerGas) : "0x", - gas ? numberToHex(gas) : "0x", - to ?? "0x", - value ? numberToHex(value) : "0x", - data ?? "0x", - serializedAccessList, - serializedAuthorizationList, - ...toYParitySignatureArray(transaction, signature) - ]) - ]); -} -function serializeTransactionEIP4844(transaction, signature) { - const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; - assertTransactionEIP4844(transaction); - let blobVersionedHashes = transaction.blobVersionedHashes; - let sidecars = transaction.sidecars; - if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) { - const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex(x)); - const kzg = transaction.kzg; - const commitments2 = blobsToCommitments({ - blobs: blobs2, - kzg + const attemptFill = (() => { + if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && request.kzg && request.blobs) + return false; + if (parameters.length > 0 && "feePayer" in request && request.feePayer && !(("feePayerSignature" in request) && request.feePayerSignature)) + return true; + if (supportsFillTransaction.get(client.uid) === false) + return false; + const shouldAttempt = ["fees", "gas"].some((parameter) => parameters.includes(parameter)); + if (!shouldAttempt) + return false; + if (parameters.includes("chainId") && typeof request.chainId !== "number") + return true; + if (parameters.includes("nonce") && typeof nonce !== "number") + return true; + if (parameters.includes("fees") && typeof request.gasPrice !== "bigint" && (typeof request.maxFeePerGas !== "bigint" || typeof request.maxPriorityFeePerGas !== "bigint")) + return true; + if (parameters.includes("gas") && typeof request.gas !== "bigint") + return true; + return false; + })(); + const fillResult = attemptFill ? await getAction(client, fillTransaction, "fillTransaction")({ ...request, nonce }).then((result) => { + const { chainId: chainId2, from: from4, gas: gas2, gasPrice, nonce: nonce2, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, type: type2, ...rest } = result.transaction; + const feeToken = "feeToken" in rest ? rest.feeToken : undefined; + const hasFilledFeePayerSignature = "feePayerSignature" in rest && rest.feePayerSignature !== null && typeof rest.feePayerSignature !== "undefined"; + const shouldUseFilledFeeToken = typeof feeToken !== "undefined" && feeToken !== null && (!("feeToken" in request) || hasFilledFeePayerSignature); + supportsFillTransaction.set(client.uid, true); + return { + ...request, + ...from4 ? { from: from4 } : {}, + ...type2 && !request.type ? { type: type2 } : {}, + ...typeof chainId2 !== "undefined" ? { chainId: chainId2 } : {}, + ...typeof gas2 !== "undefined" ? { gas: gas2 } : {}, + ...typeof gasPrice !== "undefined" ? { gasPrice } : {}, + ...typeof nonce2 !== "undefined" ? { nonce: nonce2 } : {}, + ...typeof maxFeePerBlobGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerBlobGas } : {}, + ...typeof maxFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxFeePerGas } : {}, + ...typeof maxPriorityFeePerGas !== "undefined" && request.type !== "legacy" && request.type !== "eip2930" ? { maxPriorityFeePerGas } : {}, + ..."nonceKey" in rest && typeof rest.nonceKey !== "undefined" ? { nonceKey: rest.nonceKey } : {}, + ..."keyAuthorization" in rest && typeof rest.keyAuthorization !== "undefined" && rest.keyAuthorization !== null && !("keyAuthorization" in request) ? { keyAuthorization: rest.keyAuthorization } : {}, + ..."feePayerSignature" in rest && typeof rest.feePayerSignature !== "undefined" && rest.feePayerSignature !== null ? { feePayerSignature: rest.feePayerSignature } : {}, + ...shouldUseFilledFeeToken ? { feeToken } : {}, + ...result.capabilities ? { _capabilities: result.capabilities } : {} + }; + }).catch((e) => { + const error = e; + if (error.name !== "TransactionExecutionError") + return request; + const executionReverted = error.walk?.((e2) => { + const error2 = e2; + return error2.name === "ExecutionRevertedError"; }); - if (typeof blobVersionedHashes === "undefined") - blobVersionedHashes = commitmentsToVersionedHashes({ - commitments: commitments2 + if (executionReverted) + throw e; + const unsupported = error.walk?.((e2) => { + const error2 = e2; + return error2.name === "MethodNotFoundRpcError" || error2.name === "MethodNotSupportedRpcError" || error2.message?.includes("eth_fillTransaction is not available"); + }); + if (unsupported) + supportsFillTransaction.set(client.uid, false); + return request; + }) : request; + nonce ??= fillResult.nonce; + request = { + ...fillResult, + ...account ? { from: account?.address } : {}, + ...typeof nonce !== "undefined" ? { nonce } : {} + }; + const { blobs, gas, kzg, type } = request; + if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("beforeFillParameters")) { + request = await prepareTransactionRequest2.fn({ ...request, chain }, { + client, + phase: "beforeFillParameters" + }); + } + let block; + async function getBlock2() { + if (block) + return block; + block = await getAction(client, getBlock, "getBlock")({ blockTag: "latest" }); + return block; + } + if (parameters.includes("nonce") && typeof nonce === "undefined" && account && !nonceManager) + request.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ + address: account.address, + blockTag: "pending" + }); + if ((parameters.includes("blobVersionedHashes") || parameters.includes("sidecars")) && blobs && kzg) { + const commitments = blobsToCommitments({ blobs, kzg }); + if (parameters.includes("blobVersionedHashes")) { + const versionedHashes = commitmentsToVersionedHashes({ + commitments, + to: "hex" }); - if (typeof sidecars === "undefined") { - const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg }); - sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 }); + request.blobVersionedHashes = versionedHashes; + } + if (parameters.includes("sidecars")) { + const proofs = blobsToProofs({ blobs, commitments, kzg }); + const sidecars = toBlobSidecars({ + blobs, + commitments, + proofs, + to: "hex" + }); + request.sidecars = sidecars; } } - const serializedAccessList = serializeAccessList(accessList); - const serializedTransaction = [ - numberToHex(chainId), - nonce ? numberToHex(nonce) : "0x", - maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x", - maxFeePerGas ? numberToHex(maxFeePerGas) : "0x", - gas ? numberToHex(gas) : "0x", - to ?? "0x", - value ? numberToHex(value) : "0x", - data ?? "0x", - serializedAccessList, - maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : "0x", - blobVersionedHashes ?? [], - ...toYParitySignatureArray(transaction, signature) - ]; - const blobs = []; - const commitments = []; - const proofs = []; - if (sidecars) - for (let i = 0;i < sidecars.length; i++) { - const { blob, commitment, proof } = sidecars[i]; - blobs.push(blob); - commitments.push(commitment); - proofs.push(proof); + if (parameters.includes("chainId")) + request.chainId = await getChainId2(); + if ((parameters.includes("fees") || parameters.includes("type")) && typeof type === "undefined") { + try { + request.type = getTransactionType(request); + } catch { + let isEip1559Network = eip1559NetworkCache.get(client.uid); + if (typeof isEip1559Network === "undefined") { + const block2 = await getBlock2(); + isEip1559Network = typeof block2?.baseFeePerGas === "bigint"; + eip1559NetworkCache.set(client.uid, isEip1559Network); + } + request.type = isEip1559Network ? "eip1559" : "legacy"; } - return concatHex([ - "0x03", - sidecars ? toRlp([serializedTransaction, blobs, commitments, proofs]) : toRlp(serializedTransaction) - ]); -} -function serializeTransactionEIP1559(transaction, signature) { - const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; - assertTransactionEIP1559(transaction); - const serializedAccessList = serializeAccessList(accessList); - const serializedTransaction = [ - numberToHex(chainId), - nonce ? numberToHex(nonce) : "0x", - maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x", - maxFeePerGas ? numberToHex(maxFeePerGas) : "0x", - gas ? numberToHex(gas) : "0x", - to ?? "0x", - value ? numberToHex(value) : "0x", - data ?? "0x", - serializedAccessList, - ...toYParitySignatureArray(transaction, signature) - ]; - return concatHex([ - "0x02", - toRlp(serializedTransaction) - ]); -} -function serializeTransactionEIP2930(transaction, signature) { - const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction; - assertTransactionEIP2930(transaction); - const serializedAccessList = serializeAccessList(accessList); - const serializedTransaction = [ - numberToHex(chainId), - nonce ? numberToHex(nonce) : "0x", - gasPrice ? numberToHex(gasPrice) : "0x", - gas ? numberToHex(gas) : "0x", - to ?? "0x", - value ? numberToHex(value) : "0x", - data ?? "0x", - serializedAccessList, - ...toYParitySignatureArray(transaction, signature) - ]; - return concatHex([ - "0x01", - toRlp(serializedTransaction) - ]); -} -function serializeTransactionLegacy(transaction, signature) { - const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction; - assertTransactionLegacy(transaction); - let serializedTransaction = [ - nonce ? numberToHex(nonce) : "0x", - gasPrice ? numberToHex(gasPrice) : "0x", - gas ? numberToHex(gas) : "0x", - to ?? "0x", - value ? numberToHex(value) : "0x", - data ?? "0x" - ]; - if (signature) { - const v = (() => { - if (signature.v >= 35n) { - const inferredChainId = (signature.v - 35n) / 2n; - if (inferredChainId > 0) - return signature.v; - return 27n + (signature.v === 35n ? 0n : 1n); + } + if (parameters.includes("fees")) { + if (request.type !== "legacy" && request.type !== "eip2930") { + if (typeof request.maxFeePerGas === "undefined" || typeof request.maxPriorityFeePerGas === "undefined") { + const block2 = await getBlock2(); + const { maxFeePerGas, maxPriorityFeePerGas } = await internal_estimateFeesPerGas(client, { + block: block2, + chain, + request + }); + if (typeof request.maxPriorityFeePerGas === "undefined" && request.maxFeePerGas && request.maxFeePerGas < maxPriorityFeePerGas) + throw new MaxFeePerGasTooLowError({ + maxPriorityFeePerGas + }); + request.maxPriorityFeePerGas = maxPriorityFeePerGas; + request.maxFeePerGas = maxFeePerGas; } - if (chainId > 0) - return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n); - const v2 = 27n + (signature.v === 27n ? 0n : 1n); - if (signature.v !== v2) - throw new InvalidLegacyVError({ v: signature.v }); - return v2; - })(); - const r = trim(signature.r); - const s = trim(signature.s); - serializedTransaction = [ - ...serializedTransaction, - numberToHex(v), - r === "0x00" ? "0x" : r, - s === "0x00" ? "0x" : s - ]; - } else if (chainId > 0) { - serializedTransaction = [ - ...serializedTransaction, - numberToHex(chainId), - "0x", - "0x" - ]; + } else { + if (typeof request.maxFeePerGas !== "undefined" || typeof request.maxPriorityFeePerGas !== "undefined") + throw new Eip1559FeesNotSupportedError; + if (typeof request.gasPrice === "undefined") { + const block2 = await getBlock2(); + const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(client, { + block: block2, + chain, + request, + type: "legacy" + }); + request.gasPrice = gasPrice_; + } + } } - return toRlp(serializedTransaction); -} -function toYParitySignatureArray(transaction, signature_) { - const signature = signature_ ?? transaction; - const { v, yParity } = signature; - if (typeof signature.r === "undefined") - return []; - if (typeof signature.s === "undefined") - return []; - if (typeof v === "undefined" && typeof yParity === "undefined") - return []; - const r = trim(signature.r); - const s = trim(signature.s); - const yParity_ = (() => { - if (typeof yParity === "number") - return yParity ? numberToHex(1) : "0x"; - if (v === 0n) - return "0x"; - if (v === 1n) - return numberToHex(1); - return v === 27n ? "0x" : numberToHex(1); - })(); - return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s]; + if (parameters.includes("gas") && typeof gas === "undefined") + request.gas = await getAction(client, estimateGas, "estimateGas")({ + ...request, + account, + prepare: account?.type === "local" ? [] : ["blobVersionedHashes"] + }); + if (prepareTransactionRequest2?.fn && prepareTransactionRequest2.runAt?.includes("afterFillParameters")) + request = await prepareTransactionRequest2.fn({ ...request, chain }, { + client, + phase: "afterFillParameters" + }); + assertRequest(request); + delete request.parameters; + return request; } -// ../viem/src/_esm/utils/authorization/serializeAuthorizationList.js -function serializeAuthorizationList(authorizationList) { - if (!authorizationList || authorizationList.length === 0) - return []; - const serializedAuthorizationList = []; - for (const authorization of authorizationList) { - const { chainId, nonce, ...signature } = authorization; - const contractAddress = authorization.address; - serializedAuthorizationList.push([ - chainId ? toHex(chainId) : "0x", - contractAddress, - nonce ? toHex(nonce) : "0x", - ...toYParitySignatureArray({}, signature) - ]); +// ../viem/src/_esm/actions/public/estimateGas.js +async function estimateGas(client, args) { + const { account: account_ = client.account, prepare = true } = args; + const account = account_ ? parseAccount(account_) : undefined; + const parameters = (() => { + if (Array.isArray(prepare)) + return prepare; + if (account?.type !== "local") + return ["blobVersionedHashes"]; + return; + })(); + try { + const to = await (async () => { + if (args.to) + return args.to; + if (args.authorizationList && args.authorizationList.length > 0) + return await recoverAuthorizationAddress({ + authorization: args.authorizationList[0] + }).catch(() => { + throw new BaseError2("`to` is required. Could not infer from `authorizationList`"); + }); + return; + })(); + const { accessList, authorizationList, blobs, blobVersionedHashes, blockNumber, blockTag, data, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, value, stateOverride, ...rest } = prepare ? await prepareTransactionRequest(client, { + ...args, + parameters, + to + }) : args; + if (gas && args.gas !== gas) + return gas; + const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : undefined; + const block = blockNumberHex || blockTag; + const rpcStateOverride = serializeStateOverride(stateOverride); + assertRequest(args); + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format2 = chainFormat || formatTransactionRequest; + const request = format2({ + ...extract(rest, { format: chainFormat }), + account, + accessList, + authorizationList, + blobs, + blobVersionedHashes, + data, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to, + value + }, "estimateGas"); + return BigInt(await client.request({ + method: "eth_estimateGas", + params: rpcStateOverride ? [ + request, + block ?? client.experimental_blockTag ?? "latest", + rpcStateOverride + ] : block ? [request, block] : [request] + })); + } catch (err) { + throw getEstimateGasError(err, { + ...args, + account, + chain: client.chain + }); } - return serializedAuthorizationList; } -// ../viem/src/_esm/utils/authorization/verifyAuthorization.js -init_getAddress(); -init_isAddressEqual(); -async function verifyAuthorization({ address, authorization, signature }) { - return isAddressEqual(getAddress(address), await recoverAuthorizationAddress({ - authorization, - signature - })); +// ../viem/src/_esm/actions/public/estimateContractGas.js +async function estimateContractGas(client, parameters) { + const { abi, address, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...request } = parameters; + const data = encodeFunctionData({ + abi, + args, + functionName + }); + try { + const gas = await getAction(client, estimateGas, "estimateGas")({ + data: `${data}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + ...request + }); + return gas; + } catch (error) { + const account = request.account ? parseAccount(request.account) : undefined; + throw getContractError(error, { + abi, + address, + args, + docsPath: "/docs/contract/estimateContractGas", + functionName, + sender: account?.address + }); + } } -// ../viem/src/_esm/utils/buildRequest.js -init_base(); -init_request(); -init_rpc(); - -// ../viem/src/_esm/utils/promise/withDedupe.js -init_lru(); -var promiseCache2 = /* @__PURE__ */ new LruMap(8192); -function withDedupe(fn, { enabled = true, id }) { - if (!enabled || !id) - return fn(); - if (promiseCache2.get(id)) - return promiseCache2.get(id); - const promise = fn().finally(() => promiseCache2.delete(id)); - promiseCache2.set(id, promise); - return promise; +// ../viem/src/_esm/actions/public/getBalance.js +init_abis(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_formatBlockParameter(); +init_call(); +async function getBalance(client, { address, blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest", requireCanonical }) { + const block = formatBlockParameter({ + blockHash, + blockNumber, + blockTag, + requireCanonical + }); + if (client.batch?.multicall && client.chain?.contracts?.multicall3) { + const multicall3Address = client.chain.contracts.multicall3.address; + const calldata = encodeFunctionData({ + abi: multicall3Abi, + functionName: "getEthBalance", + args: [address] + }); + const { data } = await getAction(client, call, "call")({ + to: multicall3Address, + data: calldata, + blockHash, + blockNumber, + blockTag, + requireCanonical + }); + return decodeFunctionResult({ + abi: multicall3Abi, + functionName: "getEthBalance", + args: [address], + data: data || "0x" + }); + } + const balance = await client.request({ + method: "eth_getBalance", + params: [address, block] + }); + return BigInt(balance); } -// ../viem/src/_esm/utils/buildRequest.js -function buildRequest(request, options = {}) { - return async (args, overrideOptions = {}) => { - const { dedupe = false, methods, retryDelay = 150, retryCount = 3, signal, uid: uid2 } = { - ...options, - ...overrideOptions - }; - const { method } = args; - if (methods?.exclude?.includes(method)) - throw new MethodNotSupportedRpcError(new Error("method not supported"), { - method - }); - if (methods?.include && !methods.include.includes(method)) - throw new MethodNotSupportedRpcError(new Error("method not supported"), { - method - }); - if (signal?.aborted) - throw getAbortError(signal); - const requestId = dedupe ? hashString(`${uid2}.${stringify(args)}`) : undefined; - return withDedupe(() => withRetry(async () => { - try { - return await request(args, signal ? { signal } : undefined); - } catch (err_) { - if (signal?.aborted) - throw getAbortError(signal); - if (isAbortError(err_)) - throw err_; - const err = err_; - switch (err.code) { - case ParseRpcError.code: - throw new ParseRpcError(err); - case InvalidRequestRpcError.code: - throw new InvalidRequestRpcError(err); - case MethodNotFoundRpcError.code: - throw new MethodNotFoundRpcError(err, { method: args.method }); - case InvalidParamsRpcError.code: - throw new InvalidParamsRpcError(err); - case InternalRpcError.code: - throw new InternalRpcError(err); - case InvalidInputRpcError.code: - throw new InvalidInputRpcError(err); - case ResourceNotFoundRpcError.code: - throw new ResourceNotFoundRpcError(err); - case ResourceUnavailableRpcError.code: - throw new ResourceUnavailableRpcError(err); - case TransactionRejectedRpcError.code: - throw new TransactionRejectedRpcError(err); - case MethodNotSupportedRpcError.code: - throw new MethodNotSupportedRpcError(err, { - method: args.method - }); - case LimitExceededRpcError.code: - throw new LimitExceededRpcError(err); - case JsonRpcVersionUnsupportedError.code: - throw new JsonRpcVersionUnsupportedError(err); - case UserRejectedRequestError.code: - throw new UserRejectedRequestError(err); - case UnauthorizedProviderError.code: - throw new UnauthorizedProviderError(err); - case UnsupportedProviderMethodError.code: - throw new UnsupportedProviderMethodError(err); - case ProviderDisconnectedError.code: - throw new ProviderDisconnectedError(err); - case ChainDisconnectedError.code: - throw new ChainDisconnectedError(err); - case SwitchChainError.code: - throw new SwitchChainError(err); - case UnsupportedNonOptionalCapabilityError.code: - throw new UnsupportedNonOptionalCapabilityError(err); - case UnsupportedChainIdError.code: - throw new UnsupportedChainIdError(err); - case DuplicateIdError.code: - throw new DuplicateIdError(err); - case UnknownBundleIdError.code: - throw new UnknownBundleIdError(err); - case BundleTooLargeError.code: - throw new BundleTooLargeError(err); - case AtomicReadyWalletRejectedUpgradeError.code: - throw new AtomicReadyWalletRejectedUpgradeError(err); - case AtomicityNotSupportedError.code: - throw new AtomicityNotSupportedError(err); - case 5000: - throw new UserRejectedRequestError(err); - case WalletConnectSessionSettlementError.code: - throw new WalletConnectSessionSettlementError(err); - default: - if (err_ instanceof BaseError2) - throw err_; - throw new UnknownRpcError(err); - } - } - }, { - delay: ({ count, error }) => { - if (error && error instanceof HttpRequestError) { - const retryAfter = error?.headers?.get("Retry-After"); - if (retryAfter?.match(/\d/)) - return Number.parseInt(retryAfter, 10) * 1000; - } - return ~~(1 << count) * retryDelay; - }, - retryCount, - signal, - shouldRetry: ({ error }) => shouldRetry(error) - }), { enabled: dedupe, id: requestId }); +// ../viem/src/_esm/actions/public/getBlobBaseFee.js +async function getBlobBaseFee(client) { + const baseFee = await client.request({ + method: "eth_blobBaseFee" + }); + return BigInt(baseFee); +} + +// ../viem/src/_esm/utils/promise/withCache.js +var promiseCache = /* @__PURE__ */ new Map; +var responseCache = /* @__PURE__ */ new Map; +function getCache(cacheKey) { + const buildCache = (cacheKey2, cache) => ({ + clear: () => cache.delete(cacheKey2), + get: () => cache.get(cacheKey2), + set: (data) => cache.set(cacheKey2, data) + }); + const promise = buildCache(cacheKey, promiseCache); + const response = buildCache(cacheKey, responseCache); + return { + clear: () => { + promise.clear(); + response.clear(); + }, + promise, + response }; } -function shouldRetry(error) { - if (isAbortError(error)) - return false; - if ("code" in error && typeof error.code === "number") { - if (error.code === -1) - return true; - if (error.code === LimitExceededRpcError.code) - return true; - if (error.code === InternalRpcError.code) - return true; - if (error.code === 429) - return true; - return false; +async function withCache(fn, { cacheKey, cacheTime = Number.POSITIVE_INFINITY }) { + const cache = getCache(cacheKey); + const response = cache.response.get(); + if (response && cacheTime > 0) { + const age = Date.now() - response.created.getTime(); + if (age < cacheTime) + return response.data; } - if (error instanceof HttpRequestError && error.status) { - if (error.status === 403) - return true; - if (error.status === 408) - return true; - if (error.status === 413) - return true; - if (error.status === 429) - return true; - if (error.status === 500) - return true; - if (error.status === 502) - return true; - if (error.status === 503) - return true; - if (error.status === 504) - return true; - return false; + let promise = cache.promise.get(); + if (!promise) { + promise = fn(); + cache.promise.set(promise); } - return true; -} -function hashString(str, seed = 0) { - let h1 = 3735928559 ^ seed; - let h2 = 1103547991 ^ seed; - for (let i = 0;i < str.length; i++) { - const ch = str.charCodeAt(i); - h1 = Math.imul(h1 ^ ch, 2654435761); - h2 = Math.imul(h2 ^ ch, 1597334677); + try { + const data = await promise; + cache.response.set({ created: new Date, data }); + return data; + } finally { + cache.promise.clear(); } - h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507); - h1 ^= Math.imul(h2 ^ h2 >>> 16, 3266489909); - h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507); - h2 ^= Math.imul(h1 ^ h1 >>> 16, 3266489909); - return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36); } -// ../viem/src/_esm/utils/index.js -init_pad(); -init_fromHex(); +// ../viem/src/_esm/actions/public/getBlockNumber.js +var cacheKey = (id) => `blockNumber.${id}`; +async function getBlockNumber(client, { cacheTime = client.cacheTime } = {}) { + const blockNumberHex = await withCache(() => client.request({ + method: "eth_blockNumber" + }), { cacheKey: cacheKey(client.uid), cacheTime }); + return BigInt(blockNumberHex); +} -// ../viem/src/_esm/utils/encoding/fromRlp.js -init_base(); -init_encoding(); -init_cursor2(); -init_toBytes(); +// ../viem/src/_esm/actions/public/getBlockReceipts.js init_toHex(); -var rlpDepthLimit = 1024; -function fromRlp(value, to = "hex") { - const bytes = (() => { - if (typeof value === "string") { - if (value.length > 3 && value.length % 2 !== 0) - throw new InvalidHexValueError(value); - return hexToBytes(value); - } - return value; - })(); - const cursor = createCursor(bytes, { - recursiveReadLimit: Number.POSITIVE_INFINITY - }); - const result = fromRlpCursor(cursor, to); - if (cursor.position < cursor.bytes.length) - throw new RlpTrailingBytesError({ - count: cursor.bytes.length - cursor.position - }); - return result; -} -function fromRlpCursor(cursor, to = "hex", recursiveDepth = 0) { - if (recursiveDepth >= rlpDepthLimit) - throw new RlpDepthLimitExceededError({ limit: rlpDepthLimit }); - if (cursor.bytes.length === 0) - return to === "hex" ? bytesToHex(cursor.bytes) : cursor.bytes; - const prefix = cursor.readByte(); - if (prefix < 128) - cursor.decrementPosition(1); - if (prefix < 192) { - const length2 = readLength(cursor, prefix, 128); - const bytes = cursor.readBytes(length2); - return to === "hex" ? bytesToHex(bytes) : bytes; - } - const length = readLength(cursor, prefix, 192); - return readList(cursor, length, to, recursiveDepth + 1); -} -function readLength(cursor, prefix, offset) { - if (offset === 128 && prefix < 128) - return 1; - if (prefix <= offset + 55) - return prefix - offset; - if (prefix === offset + 55 + 1) - return cursor.readUint8(); - if (prefix === offset + 55 + 2) - return cursor.readUint16(); - if (prefix === offset + 55 + 3) - return cursor.readUint24(); - if (prefix === offset + 55 + 4) - return cursor.readUint32(); - throw new BaseError2("Invalid RLP prefix"); -} -function readList(cursor, length, to, recursiveDepth) { - const position = cursor.position; - const value = []; - while (cursor.position - position < length) - value.push(fromRlpCursor(cursor, to, recursiveDepth)); - if (cursor.position - position !== length) - throw new RlpListBoundaryExceededError({ - consumed: cursor.position - position, - declared: length - }); - return value; -} -// ../viem/src/_esm/utils/index.js -init_toHex(); +// ../viem/src/_esm/utils/formatters/transactionReceipt.js +init_fromHex(); -// ../viem/src/_esm/utils/nonceManager.js -init_lru(); -function createNonceManager(parameters) { - const { source } = parameters; - const deltaMap = new Map; - const nonceMap = new LruMap(8192); - const promiseMap = new Map; - const getKey = ({ address, chainId }) => `${address}.${chainId}`; - const resetCache = (key) => { - deltaMap.delete(key); - promiseMap.delete(key); - }; +// ../viem/src/_esm/utils/formatters/log.js +function formatLog(log, { args, eventName } = {}) { return { - async consume({ address, chainId, client }) { - const key = getKey({ address, chainId }); - const promise = this.get({ address, chainId, client }); - this.increment({ address, chainId }); - const nonce = await promise; - await source.set({ address, chainId }, nonce); - nonceMap.set(key, nonce); - return nonce; - }, - async increment({ address, chainId }) { - const key = getKey({ address, chainId }); - const delta = deltaMap.get(key) ?? 0; - deltaMap.set(key, delta + 1); - }, - async get({ address, chainId, client }) { - const key = getKey({ address, chainId }); - let promise = promiseMap.get(key); - if (!promise) { - promise = (async () => { - try { - const nonce = await source.get({ address, chainId, client }); - const previousNonce = nonceMap.get(key) ?? 0; - if (previousNonce > 0 && nonce <= previousNonce) - return previousNonce + 1; - nonceMap.delete(key); - return nonce; - } finally { - resetCache(key); - } - })(); - promiseMap.set(key, promise); - } - const delta = deltaMap.get(key) ?? 0; - return delta + await promise; - }, - reset({ address, chainId }) { - const key = getKey({ address, chainId }); - nonceMap.delete(key); - resetCache(key); - } + ...log, + blockHash: log.blockHash ? log.blockHash : null, + blockNumber: log.blockNumber ? BigInt(log.blockNumber) : null, + blockTimestamp: log.blockTimestamp ? BigInt(log.blockTimestamp) : log.blockTimestamp === null ? null : undefined, + logIndex: log.logIndex ? Number(log.logIndex) : null, + transactionHash: log.transactionHash ? log.transactionHash : null, + transactionIndex: log.transactionIndex ? Number(log.transactionIndex) : null, + ...eventName ? { args, eventName } : {} }; } -function jsonRpc() { - return { - async get(parameters) { - const { address, client } = parameters; - return getTransactionCount(client, { - address, - blockTag: "pending" - }); - }, - set() {} + +// ../viem/src/_esm/utils/formatters/transactionReceipt.js +var receiptStatuses = { + "0x0": "reverted", + "0x1": "success" +}; +function formatTransactionReceipt(transactionReceipt, _) { + const receipt = { + ...transactionReceipt, + blockNumber: transactionReceipt.blockNumber ? BigInt(transactionReceipt.blockNumber) : null, + contractAddress: transactionReceipt.contractAddress ? transactionReceipt.contractAddress : null, + cumulativeGasUsed: transactionReceipt.cumulativeGasUsed ? BigInt(transactionReceipt.cumulativeGasUsed) : null, + effectiveGasPrice: transactionReceipt.effectiveGasPrice ? BigInt(transactionReceipt.effectiveGasPrice) : null, + gasUsed: transactionReceipt.gasUsed ? BigInt(transactionReceipt.gasUsed) : null, + logs: transactionReceipt.logs ? transactionReceipt.logs.map((log) => formatLog(log)) : null, + to: transactionReceipt.to ? transactionReceipt.to : null, + transactionIndex: transactionReceipt.transactionIndex ? hexToNumber(transactionReceipt.transactionIndex) : null, + status: transactionReceipt.status ? receiptStatuses[transactionReceipt.status] : null, + type: transactionReceipt.type ? transactionType[transactionReceipt.type] || transactionReceipt.type : null }; + if (transactionReceipt.blobGasPrice) + receipt.blobGasPrice = BigInt(transactionReceipt.blobGasPrice); + if (transactionReceipt.blobGasUsed) + receipt.blobGasUsed = BigInt(transactionReceipt.blobGasUsed); + return receipt; } -var nonceManager = /* @__PURE__ */ createNonceManager({ - source: jsonRpc() -}); +var defineTransactionReceipt = /* @__PURE__ */ defineFormatter("transactionReceipt", formatTransactionReceipt); -// ../viem/src/_esm/utils/rpc/http.js -init_request(); +// ../viem/src/_esm/actions/public/getBlockReceipts.js +async function getBlockReceipts(client, { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? "latest" } = {}) { + const blockNumberHex = blockNumber !== undefined ? numberToHex(blockNumber) : undefined; + const receipts = await client.request({ + method: "eth_getBlockReceipts", + params: [blockHash || blockNumberHex || blockTag] + }, { dedupe: Boolean(blockHash || blockNumberHex) }); + if (!receipts) + throw new BlockNotFoundError({ blockHash, blockNumber }); + const format2 = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt; + return receipts.map((receipt) => format2(receipt, "getBlockReceipts")); +} -// ../viem/src/_esm/utils/promise/withTimeout.js -function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, signal }) { - return new Promise((resolve, reject) => { - (async () => { - let timeoutId; - const controller = new AbortController; - try { - if (timeout > 0) { - timeoutId = setTimeout(() => { - if (signal) { - controller.abort(); - } else { - reject(errorInstance); - } - }, timeout); - } - resolve(await fn({ signal: controller?.signal || null })); - } catch (err) { - if (controller?.signal.aborted && isAbortError(err)) { - reject(errorInstance); - return; - } - reject(err); - } finally { - clearTimeout(timeoutId); - } - })(); - }); +// ../viem/src/_esm/actions/public/getBlockTransactionCount.js +init_fromHex(); +init_toHex(); +async function getBlockTransactionCount(client, { blockHash, blockNumber, blockTag = "latest" } = {}) { + const blockNumberHex = blockNumber !== undefined ? numberToHex(blockNumber) : undefined; + let count; + if (blockHash) { + count = await client.request({ + method: "eth_getBlockTransactionCountByHash", + params: [blockHash] + }, { dedupe: true }); + } else { + count = await client.request({ + method: "eth_getBlockTransactionCountByNumber", + params: [blockNumberHex || blockTag] + }, { dedupe: Boolean(blockNumberHex) }); + } + return hexToNumber(count); } -// ../viem/src/_esm/utils/rpc/id.js -function createIdStore() { - return { - current: 0, - take() { - return this.current++; - }, - reset() { - this.current = 0; - } - }; + +// ../viem/src/_esm/actions/public/getCode.js +init_formatBlockParameter(); +async function getCode(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical }) { + const block = formatBlockParameter({ + blockHash, + blockNumber, + blockTag, + requireCanonical + }); + const hex = await client.request({ + method: "eth_getCode", + params: [address, block] + }, { + dedupe: typeof blockNumber === "bigint" || blockHash !== undefined + }); + if (hex === "0x") + return; + return hex; } -var idCache = /* @__PURE__ */ createIdStore(); -// ../viem/src/_esm/utils/rpc/http.js -var defaultMaxResponseBodySize = 10485760; -function getHttpRpcClient(url_, options = {}) { - const { url, headers: headers_url } = parseUrl(url_); - return { - async request(params) { - const { body, fetchFn = options.fetchFn ?? fetch, maxResponseBodySize = options.maxResponseBodySize ?? defaultMaxResponseBodySize, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params; - const fetchOptions = { - ...options.fetchOptions ?? {}, - ...params.fetchOptions ?? {} - }; - const { headers, method, signal: signal_ } = fetchOptions; - try { - const response = await withTimeout(async ({ signal }) => { - const init = { - ...fetchOptions, - body: Array.isArray(body) ? stringify(body.map((body2) => ({ - jsonrpc: "2.0", - id: body2.id ?? idCache.take(), - ...body2 - }))) : stringify({ - jsonrpc: "2.0", - id: body.id ?? idCache.take(), - ...body - }), - headers: { - ...headers_url, - "Content-Type": "application/json", - ...headers - }, - method: method || "POST", - signal: signal_ || (timeout > 0 ? signal : null) - }; - const request = new Request(url, init); - const args = await onRequest?.(request, init) ?? { ...init, url }; - const response2 = await fetchFn(args.url ?? url, args); - return response2; - }, { - errorInstance: new TimeoutError({ body, url }), - timeout, - signal: true - }); - if (onResponse) - await onResponse(response); - let data; - const responseBody = await readResponseBody(response, { - maxResponseBodySize +// ../viem/src/_esm/actions/public/getContractEvents.js +init_getAbiItem(); + +// ../viem/src/_esm/utils/abi/parseEventLogs.js +init_isAddressEqual(); +init_toBytes(); +init_keccak256(); +init_toEventSelector(); + +// ../viem/src/_esm/utils/abi/decodeEventLog.js +init_abi(); +init_cursor(); +init_size(); +init_toEventSelector(); +init_decodeAbiParameters(); +init_formatAbiItem2(); +var docsPath7 = "/docs/contract/decodeEventLog"; +function decodeEventLog(parameters) { + const { abi, data, strict: strict_, topics } = parameters; + const strict = strict_ ?? true; + const [signature, ...argTopics] = topics; + if (!signature) + throw new AbiEventSignatureEmptyTopicsError({ docsPath: docsPath7 }); + const abiItem = abi.find((x) => x.type === "event" && signature === toEventSelector(formatAbiItem2(x))); + if (!(abiItem && ("name" in abiItem)) || abiItem.type !== "event") + throw new AbiEventSignatureNotFoundError(signature, { docsPath: docsPath7 }); + const { name, inputs } = abiItem; + const isUnnamed = inputs?.some((x) => !(("name" in x) && x.name)); + const args = isUnnamed ? [] : {}; + const indexedInputs = inputs.map((x, i) => [x, i]).filter(([x]) => ("indexed" in x) && x.indexed); + const missingIndexedInputs = []; + for (let i = 0;i < indexedInputs.length; i++) { + const [param, argIndex] = indexedInputs[i]; + const topic = argTopics[i]; + if (!topic) { + if (strict) + throw new DecodeLogTopicsMismatch({ + abiItem, + param }); - if (response.headers.get("Content-Type")?.startsWith("application/json")) - data = JSON.parse(responseBody); - else { - data = responseBody; - try { - data = JSON.parse(data || "{}"); - } catch (err) { - if (response.ok) - throw err; - data = { error: data }; + missingIndexedInputs.push([param, argIndex]); + continue; + } + args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({ + param, + value: topic + }); + } + const nonIndexedInputs = inputs.filter((x) => !(("indexed" in x) && x.indexed)); + const inputsToDecode = strict ? nonIndexedInputs : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs]; + if (inputsToDecode.length > 0) { + if (data && data !== "0x") { + try { + const decodedData = decodeAbiParameters(inputsToDecode, data); + if (decodedData) { + let dataIndex = 0; + if (!strict) { + for (const [param, argIndex] of missingIndexedInputs) { + args[isUnnamed ? argIndex : param.name || argIndex] = decodedData[dataIndex++]; + } } + if (isUnnamed) { + for (let i = 0;i < inputs.length; i++) + if (args[i] === undefined && dataIndex < decodedData.length) + args[i] = decodedData[dataIndex++]; + } else + for (let i = 0;i < nonIndexedInputs.length; i++) + args[nonIndexedInputs[i].name] = decodedData[dataIndex++]; } - if (!response.ok) { - if (typeof data.error?.code === "number" && typeof data.error?.message === "string") - return data; - throw new HttpRequestError({ - body, - details: stringify(data.error) || response.statusText, - headers: response.headers, - status: response.status, - url - }); - } - return data; } catch (err) { - if (signal_?.aborted) - throw getAbortError(signal_); - if (isAbortError(err)) - throw err; - if (err instanceof HttpRequestError) - throw err; - if (err instanceof ResponseBodyTooLargeError) - throw err; - if (err instanceof TimeoutError) + if (strict) { + if (err instanceof AbiDecodingDataSizeTooSmallError || err instanceof PositionOutOfBoundsError) + throw new DecodeLogDataMismatch({ + abiItem, + data, + params: inputsToDecode, + size: size2(data) + }); throw err; - throw new HttpRequestError({ - body, - cause: err, - url - }); + } } + } else if (strict) { + throw new DecodeLogDataMismatch({ + abiItem, + data: "0x", + params: inputsToDecode, + size: 0 + }); } + } + return { + eventName: name, + args: Object.values(args).length > 0 ? args : undefined }; } -async function readResponseBody(response, { maxResponseBodySize }) { - if (maxResponseBodySize === false) - return response.text(); - const contentLength = response.headers.get("Content-Length"); - if (contentLength) { - const size6 = Number(contentLength); - if (size6 > maxResponseBodySize) - throw new ResponseBodyTooLargeError({ - maxSize: maxResponseBodySize, - size: size6 - }); - } - if (!response.body) { - const body2 = await response.text(); - const size6 = new TextEncoder().encode(body2).length; - if (size6 > maxResponseBodySize) - throw new ResponseBodyTooLargeError({ - maxSize: maxResponseBodySize, - size: size6 - }); - return body2; - } - const reader = response.body.getReader(); - const decoder2 = new TextDecoder; - let body = ""; - let size5 = 0; - try { - while (true) { - const { done, value } = await reader.read(); - if (done) - break; - size5 += value.byteLength; - if (size5 > maxResponseBodySize) { - await reader.cancel(); - throw new ResponseBodyTooLargeError({ - maxSize: maxResponseBodySize, - size: size5 +function decodeTopic({ param, value }) { + if (param.type === "string" || param.type === "bytes" || param.type === "tuple" || param.type.match(/^(.*)\[(\d+)?\]$/)) + return value; + const decodedArg = decodeAbiParameters([param], value) || []; + return decodedArg[0]; +} + +// ../viem/src/_esm/utils/abi/parseEventLogs.js +function parseEventLogs(parameters) { + const { abi, args, logs, strict = true } = parameters; + const eventName = (() => { + if (!parameters.eventName) + return; + if (Array.isArray(parameters.eventName)) + return parameters.eventName; + return [parameters.eventName]; + })(); + const abiTopics = abi.filter((abiItem) => abiItem.type === "event").map((abiItem) => ({ + abi: abiItem, + selector: toEventSelector(abiItem) + })); + return logs.map((log) => { + const formattedLog = typeof log.blockNumber === "string" ? formatLog(log) : log; + const abiItems = abiTopics.filter((abiTopic) => formattedLog.topics[0] === abiTopic.selector); + if (abiItems.length === 0) + return null; + let event; + let abiItem; + for (const item of abiItems) { + try { + event = decodeEventLog({ + ...formattedLog, + abi: [item.abi], + strict: true }); - } - body += decoder2.decode(value, { stream: true }); + abiItem = item; + break; + } catch {} } - body += decoder2.decode(); - return body; - } finally { - reader.releaseLock(); - } -} -function parseUrl(url_) { - try { - const url = new URL(url_); - const result = (() => { - if (url.username) { - const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`; - url.username = ""; - url.password = ""; + if (!event && !strict) { + abiItem = abiItems[0]; + try { + event = decodeEventLog({ + data: formattedLog.data, + topics: formattedLog.topics, + abi: [abiItem.abi], + strict: false + }); + } catch { + const isUnnamed = abiItem.abi.inputs?.some((x) => !(("name" in x) && x.name)); return { - url: url.toString(), - headers: { Authorization: `Basic ${btoa(credentials)}` } + ...formattedLog, + args: isUnnamed ? [] : {}, + eventName: abiItem.abi.name }; } - return; - })(); - return { url: url.toString(), ...result }; - } catch { - return { url: url_ }; - } -} - -// ../viem/src/_esm/utils/signature/hashMessage.js -init_keccak256(); - -// ../viem/src/_esm/constants/strings.js -var presignMessagePrefix = `\x19Ethereum Signed Message: -`; - -// ../viem/src/_esm/utils/signature/toPrefixedMessage.js -init_size(); -init_toHex(); -function toPrefixedMessage(message_) { - const message = (() => { - if (typeof message_ === "string") - return stringToHex(message_); - if (typeof message_.raw === "string") - return message_.raw; - return bytesToHex(message_.raw); - })(); - const prefix = stringToHex(`${presignMessagePrefix}${size(message)}`); - return concat([prefix, message]); + } + if (!event || !abiItem) + return null; + if (eventName && !eventName.includes(event.eventName)) + return null; + if (!includesArgs({ + args: event.args, + inputs: abiItem.abi.inputs, + matchArgs: args + })) + return null; + return { ...event, ...formattedLog }; + }).filter(Boolean); } - -// ../viem/src/_esm/utils/signature/hashMessage.js -function hashMessage(message, to_) { - return keccak256(toPrefixedMessage(message), to_); +function includesArgs(parameters) { + const { args, inputs, matchArgs } = parameters; + if (!matchArgs) + return true; + if (!args) + return false; + function isEqual(input, value, arg) { + try { + if (input.type === "address") + return isAddressEqual(value, arg); + if (input.type === "string" || input.type === "bytes") + return keccak256(toBytes(value)) === arg; + return value === arg; + } catch { + return false; + } + } + if (Array.isArray(args) && Array.isArray(matchArgs)) { + return matchArgs.every((value, index2) => { + if (value === null || value === undefined) + return true; + const input = inputs[index2]; + if (!input) + return false; + const value_ = Array.isArray(value) ? value : [value]; + return value_.some((value2) => isEqual(input, value2, args[index2])); + }); + } + if (typeof args === "object" && !Array.isArray(args) && typeof matchArgs === "object" && !Array.isArray(matchArgs)) + return Object.entries(matchArgs).every(([key, value]) => { + if (value === null || value === undefined) + return true; + const input = inputs.find((input2) => input2.name === key); + if (!input) + return false; + const value_ = Array.isArray(value) ? value : [value]; + return value_.some((value2) => isEqual(input, value2, args[key])); + }); + return false; } -// ../viem/src/_esm/utils/signature/hashTypedData.js -init_encodeAbiParameters(); +// ../viem/src/_esm/actions/public/getLogs.js init_toHex(); -init_keccak256(); - -// ../viem/src/_esm/utils/typedData.js -init_abi(); -init_address(); - -// ../viem/src/_esm/errors/typedData.js -init_base(); - -class InvalidDomainError extends BaseError2 { - constructor({ domain }) { - super(`Invalid domain "${stringify(domain)}".`, { - metaMessages: ["Must be a valid EIP-712 domain."] +async function getLogs(client, { address, blockHash, fromBlock, toBlock, event, events: events_, args, strict: strict_ } = {}) { + const strict = strict_ ?? false; + const events = events_ ?? (event ? [event] : undefined); + let topics = []; + if (events) { + const encoded = events.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args: events_ ? undefined : args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + let logs; + if (blockHash) { + logs = await client.request({ + method: "eth_getLogs", + params: [{ address, topics, blockHash }] + }); + } else { + logs = await client.request({ + method: "eth_getLogs", + params: [ + { + address, + topics, + fromBlock: typeof fromBlock === "bigint" ? numberToHex(fromBlock) : fromBlock, + toBlock: typeof toBlock === "bigint" ? numberToHex(toBlock) : toBlock + } + ] }); } + const formattedLogs = logs.map((log) => formatLog(log)); + if (!events) + return formattedLogs; + return parseEventLogs({ + abi: events, + args, + logs: formattedLogs, + strict + }); } -class InvalidPrimaryTypeError extends BaseError2 { - constructor({ primaryType, types }) { - super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, { - docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror", - metaMessages: ["Check that the primary type is a key in `types`."] - }); - } +// ../viem/src/_esm/actions/public/getContractEvents.js +async function getContractEvents(client, parameters) { + const { abi, address, args, blockHash, eventName, fromBlock, toBlock, strict } = parameters; + const event = eventName ? getAbiItem({ abi, name: eventName }) : undefined; + const events = !event ? abi.filter((x) => x.type === "event") : undefined; + return getAction(client, getLogs, "getLogs")({ + address, + args, + blockHash, + event, + events, + fromBlock, + toBlock, + strict + }); } -class InvalidStructTypeError extends BaseError2 { - constructor({ type }) { - super(`Struct type "${type}" is invalid.`, { - metaMessages: ["Struct type must not be a Solidity type."], - name: "InvalidStructTypeError" +// ../viem/src/_esm/actions/public/getDelegation.js +init_getAddress(); +init_size(); +init_slice(); +async function getDelegation(client, { address, blockNumber, blockTag = "latest" }) { + const code = await getCode(client, { + address, + ...blockNumber !== undefined ? { blockNumber } : { blockTag } + }); + if (!code) + return; + if (size2(code) !== 23) + return; + if (!code.startsWith("0xef0100")) + return; + return getAddress(slice(code, 3, 23)); +} + +// ../viem/src/_esm/errors/eip712.js +init_base(); + +class Eip712DomainNotFoundError extends BaseError2 { + constructor({ address }) { + super(`No EIP-712 domain found on contract "${address}".`, { + metaMessages: [ + "Ensure that:", + `- The contract is deployed at the address "${address}".`, + "- `eip712Domain()` function exists on the contract.", + "- `eip712Domain()` function matches signature to ERC-5267 specification." + ], + name: "Eip712DomainNotFoundError" }); } } -class InvalidTypedDataTypeError extends BaseError2 { - constructor({ type }) { - const canonicalType = type.replace(/^(u?int)/, "$&256"); - super(`Type "${type}" is not a valid EIP-712 type.`, { - metaMessages: [`Use "${canonicalType}" instead.`], - name: "InvalidTypedDataTypeError" +// ../viem/src/_esm/actions/public/getEip712Domain.js +async function getEip712Domain(client, parameters) { + const { address, factory, factoryData } = parameters; + try { + const [fields, name, version4, chainId, verifyingContract, salt, extensions] = await getAction(client, readContract, "readContract")({ + abi, + address, + functionName: "eip712Domain", + factory, + factoryData }); + return { + domain: { + name, + version: version4, + chainId: Number(chainId), + verifyingContract, + salt + }, + extensions, + fields + }; + } catch (e) { + const error = e; + if (error.name === "ContractFunctionExecutionError" && error.cause.name === "ContractFunctionZeroDataError") { + throw new Eip712DomainNotFoundError({ address }); + } + throw error; } } +var abi = [ + { + inputs: [], + name: "eip712Domain", + outputs: [ + { name: "fields", type: "bytes1" }, + { name: "name", type: "string" }, + { name: "version", type: "string" }, + { name: "chainId", type: "uint256" }, + { name: "verifyingContract", type: "address" }, + { name: "salt", type: "bytes32" }, + { name: "extensions", type: "uint256[]" } + ], + stateMutability: "view", + type: "function" + } +]; -// ../viem/src/_esm/utils/typedData.js -init_isAddress(); -init_size(); +// ../viem/src/_esm/actions/public/getFeeHistory.js init_toHex(); -init_regex2(); -function serializeTypedData(parameters) { - const { domain: domain_, message: message_, primaryType, types } = parameters; - const normalizeData = (struct, data_) => { - const data = { ...data_ }; - for (const param of struct) { - const { name, type } = param; - if (type === "address") - data[name] = data[name].toLowerCase(); - } - return data; + +// ../viem/src/_esm/utils/formatters/feeHistory.js +function formatFeeHistory(feeHistory) { + return { + baseFeePerGas: feeHistory.baseFeePerGas.map((value) => BigInt(value)), + gasUsedRatio: feeHistory.gasUsedRatio, + oldestBlock: BigInt(feeHistory.oldestBlock), + reward: feeHistory.reward?.map((reward) => reward.map((value) => BigInt(value))) }; - const domain = (() => { - if (!types.EIP712Domain) - return {}; - if (!domain_) - return {}; - return normalizeData(types.EIP712Domain, domain_); - })(); - const message = (() => { - if (primaryType === "EIP712Domain") - return; - return normalizeData(types[primaryType], message_); - })(); - return stringify({ domain, message, primaryType, types }); -} -function validateTypedData(parameters) { - const { domain, message, primaryType, types } = parameters; - const validateData = (struct, data) => { - for (const param of struct) { - const { name, type } = param; - const value = data[name]; - const baseType = type.replace(/(\[[0-9]*\])+$/, ""); - if (baseType === "int" || baseType === "uint") - throw new InvalidTypedDataTypeError({ type }); - const integerMatch = type.match(integerRegex2); - if (integerMatch && (typeof value === "number" || typeof value === "bigint")) { - const [_type, base, size_] = integerMatch; - numberToHex(value, { - signed: base === "int", - size: Number.parseInt(size_, 10) / 8 - }); - } - if (type === "address" && typeof value === "string" && !isAddress(value)) - throw new InvalidAddressError({ address: value }); - const bytesMatch = type.match(bytesRegex2); - if (bytesMatch) { - const [_type, size_] = bytesMatch; - if (size_ && size(value) !== Number.parseInt(size_, 10)) - throw new BytesSizeMismatchError({ - expectedSize: Number.parseInt(size_, 10), - givenSize: size(value) - }); - } - const struct2 = types[type]; - if (struct2) { - validateReference(type); - validateData(struct2, value); - } - } - }; - if (types.EIP712Domain && domain) { - if (typeof domain !== "object") - throw new InvalidDomainError({ domain }); - validateData(types.EIP712Domain, domain); - } - if (primaryType !== "EIP712Domain") { - if (types[primaryType]) - validateData(types[primaryType], message); - else - throw new InvalidPrimaryTypeError({ primaryType, types }); - } } -function getTypesForEIP712Domain({ domain }) { - return [ - typeof domain?.name === "string" && { name: "name", type: "string" }, - domain?.version && { name: "version", type: "string" }, - (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && { - name: "chainId", - type: "uint256" - }, - domain?.verifyingContract && { - name: "verifyingContract", - type: "address" - }, - domain?.salt && { name: "salt", type: "bytes32" } - ].filter(Boolean); -} -function validateReference(type) { - if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) - throw new InvalidStructTypeError({ type }); + +// ../viem/src/_esm/actions/public/getFeeHistory.js +async function getFeeHistory(client, { blockCount, blockNumber, blockTag = "latest", rewardPercentiles }) { + const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : undefined; + const feeHistory = await client.request({ + method: "eth_feeHistory", + params: [ + numberToHex(blockCount), + blockNumberHex || blockTag, + rewardPercentiles + ] + }, { dedupe: Boolean(blockNumberHex) }); + return formatFeeHistory(feeHistory); } -// ../viem/src/_esm/utils/signature/hashTypedData.js -function hashTypedData(parameters) { - const { domain = {}, message, primaryType } = parameters; - const types = { - EIP712Domain: getTypesForEIP712Domain({ domain }), - ...parameters.types - }; - validateTypedData({ - domain, - message, - primaryType, - types +// ../viem/src/_esm/actions/public/getFilterChanges.js +async function getFilterChanges(_client, { filter }) { + const strict = "strict" in filter && filter.strict; + const logs = await filter.request({ + method: "eth_getFilterChanges", + params: [filter.id] }); - const parts = ["0x1901"]; - if (domain) - parts.push(hashDomain({ - domain, - types - })); - if (primaryType !== "EIP712Domain") - parts.push(hashStruct({ - data: message, - primaryType, - types - })); - return keccak256(concat(parts)); -} -function hashDomain({ domain, types }) { - return hashStruct({ - data: domain, - primaryType: "EIP712Domain", - types + if (typeof logs[0] === "string") + return logs; + const formattedLogs = logs.map((log) => formatLog(log)); + if (!("abi" in filter) || !filter.abi) + return formattedLogs; + return parseEventLogs({ + abi: filter.abi, + logs: formattedLogs, + strict }); } -function hashStruct({ data, primaryType, types }) { - const encoded = encodeData({ - data, - primaryType, - types + +// ../viem/src/_esm/actions/public/getFilterLogs.js +async function getFilterLogs(_client, { filter }) { + const strict = filter.strict ?? false; + const logs = await filter.request({ + method: "eth_getFilterLogs", + params: [filter.id] + }); + const formattedLogs = logs.map((log) => formatLog(log)); + if (!filter.abi) + return formattedLogs; + return parseEventLogs({ + abi: filter.abi, + logs: formattedLogs, + strict }); - return keccak256(encoded); -} -function encodeData({ data, primaryType, types }) { - const encodedTypes = [{ type: "bytes32" }]; - const encodedValues = [hashType({ primaryType, types })]; - for (const field of types[primaryType]) { - const [type, value] = encodeField({ - types, - name: field.name, - type: field.type, - value: data[field.name] - }); - encodedTypes.push(type); - encodedValues.push(value); - } - return encodeAbiParameters(encodedTypes, encodedValues); -} -function hashType({ primaryType, types }) { - const encodedHashType = toHex(encodeType({ primaryType, types })); - return keccak256(encodedHashType); } -function encodeType({ primaryType, types }) { - let result = ""; - const unsortedDeps = findTypeDependencies({ primaryType, types }); - unsortedDeps.delete(primaryType); - const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; - for (const type of deps) { - result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`; - } - return result; + +// ../viem/src/_esm/actions/public/getProof.js +init_formatBlockParameter(); + +// ../viem/src/_esm/utils/index.js +init_encodeFunctionData(); +init_pad(); +init_fromHex(); +init_toHex(); +init_formatGwei(); + +// ../viem/src/_esm/utils/formatters/proof.js +function formatStorageProof(storageProof) { + return storageProof.map((proof) => ({ + ...proof, + value: BigInt(proof.value) + })); } -function findTypeDependencies({ primaryType: primaryType_, types }, results = new Set) { - const match = primaryType_.match(/^\w*/u); - const primaryType = match?.[0]; - if (results.has(primaryType) || types[primaryType] === undefined) { - return results; - } - results.add(primaryType); - for (const field of types[primaryType]) { - findTypeDependencies({ primaryType: field.type, types }, results); - } - return results; +function formatProof(proof) { + return { + ...proof, + balance: proof.balance ? BigInt(proof.balance) : undefined, + nonce: proof.nonce ? hexToNumber(proof.nonce) : undefined, + storageProof: proof.storageProof ? formatStorageProof(proof.storageProof) : undefined + }; } -function encodeField({ types, name, type, value }) { - if (types[type] !== undefined) { - return [ - { type: "bytes32" }, - keccak256(encodeData({ data: value, primaryType: type, types })) - ]; - } - if (type === "bytes") - return [{ type: "bytes32" }, keccak256(value)]; - if (type === "string") - return [{ type: "bytes32" }, keccak256(toHex(value))]; - if (type.lastIndexOf("]") === type.length - 1) { - const parsedType = type.slice(0, type.lastIndexOf("[")); - const typeValuePairs = value.map((item) => encodeField({ - name, - type: parsedType, - types, - value: item - })); - return [ - { type: "bytes32" }, - keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v))) - ]; - } - return [{ type }, value]; + +// ../viem/src/_esm/actions/public/getProof.js +async function getProof(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical, storageKeys }) { + const block = formatBlockParameter({ + blockHash, + blockNumber, + blockTag, + requireCanonical + }); + const proof = await client.request({ + method: "eth_getProof", + params: [address, storageKeys, block] + }); + return formatProof(proof); } -// ../viem/src/_esm/constants/bytes.js -var erc6492MagicBytes = "0x6492649264926492649264926492649264926492649264926492649264926492"; +// ../viem/src/_esm/actions/public/getRawTransaction.js +init_transaction(); +async function getRawTransaction(client, { hash: hash2 }) { + const rawTransaction = await client.request({ + method: "eth_getRawTransactionByHash", + params: [hash2] + }, { dedupe: true }); + if (!rawTransaction) + throw new TransactionNotFoundError({ hash: hash2 }); + return rawTransaction; +} -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/erc8010/SignatureErc8010.js -var exports_SignatureErc8010 = {}; -__export(exports_SignatureErc8010, { - wrap: () => wrap, - validate: () => validate4, - unwrap: () => unwrap, - suffixParameters: () => suffixParameters, - magicBytes: () => magicBytes, - from: () => from10, - assert: () => assert6, - InvalidWrappedSignatureError: () => InvalidWrappedSignatureError -}); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiParameters.js -init_exports(); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Address.js -init_Bytes(); +// ../viem/src/_esm/actions/public/getStorageAt.js +init_formatBlockParameter(); +async function getStorageAt(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical, slot }) { + const block = formatBlockParameter({ + blockHash, + blockNumber, + blockTag, + requireCanonical + }); + const data = await client.request({ + method: "eth_getStorageAt", + params: [address, slot, block] + }); + return data; +} -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/lru.js -class LruMap2 extends Map { - constructor(size5) { - super(); - Object.defineProperty(this, "maxSize", { - enumerable: true, - configurable: true, - writable: true, - value: undefined - }); - this.maxSize = size5; - } - get(key) { - const value = super.get(key); - if (super.has(key) && value !== undefined) { - this.delete(key); - super.set(key, value); - } - return value; +// ../viem/src/_esm/actions/public/getTransaction.js +init_transaction(); +init_toHex(); +async function getTransaction(client, { blockHash, blockNumber, blockTag: blockTag_, hash: hash2, index: index2, sender, nonce }) { + const blockTag = blockTag_ || "latest"; + const blockNumberHex = blockNumber !== undefined ? numberToHex(blockNumber) : undefined; + let transaction = null; + if (hash2) { + transaction = await client.request({ + method: "eth_getTransactionByHash", + params: [hash2] + }, { dedupe: true }); + } else if (blockHash) { + transaction = await client.request({ + method: "eth_getTransactionByBlockHashAndIndex", + params: [blockHash, numberToHex(index2)] + }, { dedupe: true }); + } else if ((blockNumberHex || blockTag) && typeof index2 === "number") { + transaction = await client.request({ + method: "eth_getTransactionByBlockNumberAndIndex", + params: [blockNumberHex || blockTag, numberToHex(index2)] + }, { dedupe: Boolean(blockNumberHex) }); + } else if (sender && typeof nonce === "number") { + transaction = await client.request({ + method: "eth_getTransactionBySenderAndNonce", + params: [sender, numberToHex(nonce)] + }, { dedupe: true }); } - set(key, value) { - super.set(key, value); - if (this.maxSize && this.size > this.maxSize) { - const firstKey = this.keys().next().value; - if (firstKey) - this.delete(firstKey); - } - return this; + if (!transaction) + throw new TransactionNotFoundError({ + blockHash, + blockNumber, + blockTag, + hash: hash2, + index: index2 + }); + if (transaction.type === "0x79") { + const raw = transaction; + const body = raw.tx ?? {}; + transaction = { + hash: hash2 ?? undefined, + type: "0x79", + blockHash: raw.blockHash, + blockNumber: raw.blockNumber, + blockTimestamp: raw.blockTimestamp, + transactionIndex: raw.transactionIndex, + gasPrice: raw.gasPrice, + from: raw.from ?? body.sender, + chainId: body.chainId != null ? numberToHex(body.chainId) : undefined, + gas: body.gasLimit != null ? numberToHex(body.gasLimit) : undefined, + maxFeePerGas: body.maxFeePerGas, + maxPriorityFeePerGas: body.maxPriorityFeePerGas, + nonce: body.nonceSequence != null ? numberToHex(body.nonceSequence) : undefined, + to: null, + value: "0x0", + input: "0x", + nonceKey: body.nonceKey, + expiry: body.expiry, + calls: body.calls, + accountChanges: body.accountChanges, + metadata: body.metadata, + payer: body.payer ?? null, + senderAuth: raw.senderAuth, + payerAuth: raw.payerAuth + }; } + const format2 = client.chain?.formatters?.transaction?.format || formatTransaction; + return format2(transaction, "getTransaction"); } -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Caches.js -var caches = { - checksum: /* @__PURE__ */ new LruMap2(8192) -}; -var checksum = caches.checksum; - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Address.js -init_Errors(); +// ../viem/src/_esm/actions/public/getTransactionConfirmations.js +async function getTransactionConfirmations(client, { hash: hash2, transactionReceipt }) { + const [blockNumber, transaction] = await Promise.all([ + getAction(client, getBlockNumber, "getBlockNumber")({}), + hash2 ? getAction(client, getTransaction, "getTransaction")({ hash: hash2 }) : undefined + ]); + const transactionBlockNumber = transactionReceipt?.blockNumber || transaction?.blockNumber; + if (!transactionBlockNumber) + return 0n; + return blockNumber - transactionBlockNumber + 1n; +} -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Hash.js -init_sha3(); -init_Bytes(); -init_Hex(); -function keccak2562(value, options = {}) { - const { as = typeof value === "string" ? "Hex" : "Bytes" } = options; - const bytes = keccak_256(from2(value)); - if (as === "Bytes") - return bytes; - return fromBytes(bytes); +// ../viem/src/_esm/actions/public/getTransactionReceipt.js +init_transaction(); +async function getTransactionReceipt(client, { hash: hash2 }) { + const receipt = await client.request({ + method: "eth_getTransactionReceipt", + params: [hash2] + }, { dedupe: true }); + if (!receipt) + throw new TransactionReceiptNotFoundError({ hash: hash2 }); + const format2 = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt; + return format2(receipt, "getTransactionReceipt"); } -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/PublicKey.js -init_Bytes(); -init_Errors(); -init_Hex(); -function assert3(publicKey, options = {}) { - const { compressed } = options; - const { prefix, x, y } = publicKey; - if (compressed === false || typeof x === "bigint" && typeof y === "bigint") { - if (prefix !== 4) - throw new InvalidPrefixError({ - prefix, - cause: new InvalidUncompressedPrefixError +// ../viem/src/_esm/actions/public/multicall.js +init_abis(); +init_abi(); +init_base(); +init_contract(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_getChainContractAddress(); +init_createBatchScheduler(); +async function multicall(client, parameters) { + const { account, authorizationList, allowFailure = true, blockHash, blockNumber, blockOverrides, blockTag, requireCanonical, stateOverride } = parameters; + const contracts = parameters.contracts; + const batch = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; + const batchSize = parameters.batchSize ?? batch.batchSize ?? 1024; + const deployless = parameters.deployless ?? batch.deployless ?? false; + const multicallAddress = (() => { + if (parameters.multicallAddress) + return parameters.multicallAddress; + if (deployless) + return null; + if (client.chain) { + return getChainContractAddress({ + blockNumber, + chain: client.chain, + contract: "multicall3" }); - return; - } - if (compressed === true || typeof x === "bigint" && typeof y === "undefined") { - if (prefix !== 3 && prefix !== 2) - throw new InvalidPrefixError({ - prefix, - cause: new InvalidCompressedPrefixError + } + throw new Error("client chain not configured. multicallAddress is required."); + })(); + const chunkedCalls = [[]]; + let currentChunk = 0; + let currentChunkSize = 0; + for (let i = 0;i < contracts.length; i++) { + const { abi: abi2, address, args, functionName } = contracts[i]; + try { + const callData = encodeFunctionData({ abi: abi2, args, functionName }); + currentChunkSize += (callData.length - 2) / 2; + if (batchSize > 0 && currentChunkSize > batchSize && chunkedCalls[currentChunk].length > 0) { + currentChunk++; + currentChunkSize = (callData.length - 2) / 2; + chunkedCalls[currentChunk] = []; + } + chunkedCalls[currentChunk] = [ + ...chunkedCalls[currentChunk], + { + allowFailure: true, + callData, + target: address + } + ]; + } catch (err) { + const error = getContractError(err, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/multicall", + functionName, + sender: account }); - return; + if (!allowFailure) + throw error; + chunkedCalls[currentChunk] = [ + ...chunkedCalls[currentChunk], + { + allowFailure: true, + callData: "0x", + target: address + } + ]; + } } - throw new InvalidError({ publicKey }); -} -function from4(value) { - const publicKey = (() => { - if (validate2(value)) - return fromHex2(value); - if (validate(value)) - return fromBytes2(value); - const { prefix, x, y } = value; - if (typeof x === "bigint" && typeof y === "bigint") - return { prefix: prefix ?? 4, x, y }; - return { prefix, x }; - })(); - assert3(publicKey); - return publicKey; -} -function fromBytes2(publicKey) { - return fromHex2(fromBytes(publicKey)); -} -function fromHex2(publicKey) { - if (publicKey.length !== 132 && publicKey.length !== 130 && publicKey.length !== 68) - throw new InvalidSerializedSizeError({ publicKey }); - if (publicKey.length === 130) { - const x2 = BigInt(slice3(publicKey, 0, 32)); - const y = BigInt(slice3(publicKey, 32, 64)); - return { - prefix: 4, - x: x2, - y - }; - } - if (publicKey.length === 132) { - const prefix2 = Number(slice3(publicKey, 0, 1)); - const x2 = BigInt(slice3(publicKey, 1, 33)); - const y = BigInt(slice3(publicKey, 33, 65)); - return { - prefix: prefix2, - x: x2, - y - }; - } - const prefix = Number(slice3(publicKey, 0, 1)); - const x = BigInt(slice3(publicKey, 1, 33)); - return { - prefix, - x - }; -} -function toHex2(publicKey, options = {}) { - assert3(publicKey); - const { prefix, x, y } = publicKey; - const { includePrefix = true } = options; - const publicKey_ = concat2(includePrefix ? fromNumber(prefix, { size: 1 }) : "0x", fromNumber(x, { size: 32 }), typeof y === "bigint" ? fromNumber(y, { size: 32 }) : "0x"); - return publicKey_; -} -class InvalidError extends BaseError3 { - constructor({ publicKey }) { - super(`Value \`${stringify2(publicKey)}\` is not a valid public key.`, { - metaMessages: [ - "Public key must contain:", - "- an `x` and `prefix` value (compressed)", - "- an `x`, `y`, and `prefix` value (uncompressed)" - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "PublicKey.InvalidError" + const batching = Boolean(client.batch?.multicall); + const batches = batching ? chunkedCalls.flatMap((calls) => calls.map((call2) => [call2])) : chunkedCalls; + const aggregate3Results = await Promise.allSettled(batches.map((calls) => { + if (batching) + return scheduleMulticall2(client, { + account, + authorizationList, + batchSize, + blockHash, + blockNumber, + blockOverrides, + blockTag, + call: calls[0], + multicallAddress, + requireCanonical, + stateOverride + }).then((result) => [result]); + return getAction(client, readContract, "readContract")({ + ...multicallAddress === null ? { code: multicall3Bytecode } : { address: multicallAddress }, + abi: multicall3Abi, + account, + args: [calls], + authorizationList, + blockHash, + blockNumber, + blockOverrides, + blockTag, + functionName: "aggregate3", + requireCanonical, + stateOverride }); + })); + const results = []; + for (let i = 0;i < aggregate3Results.length; i++) { + const result = aggregate3Results[i]; + if (result.status === "rejected") { + if (!allowFailure) + throw result.reason; + for (let j = 0;j < batches[i].length; j++) { + results.push({ + status: "failure", + error: result.reason, + result: undefined + }); + } + continue; + } + const aggregate3Result = result.value; + for (let j = 0;j < aggregate3Result.length; j++) { + const { returnData, success } = aggregate3Result[j]; + const { callData } = batches[i][j]; + const { abi: abi2, address, functionName, args } = contracts[results.length]; + try { + if (callData === "0x") + throw new AbiDecodingZeroDataError; + if (!success) + throw new RawContractError({ data: returnData }); + const result2 = decodeFunctionResult({ + abi: abi2, + args, + data: returnData, + functionName + }); + results.push(allowFailure ? { result: result2, status: "success" } : result2); + } catch (err) { + const error = getContractError(err, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/multicall", + functionName + }); + if (!allowFailure) + throw error; + results.push({ error, result: undefined, status: "failure" }); + } + } } + if (results.length !== contracts.length) + throw new BaseError2("multicall results mismatch"); + return results; } - -class InvalidPrefixError extends BaseError3 { - constructor({ prefix, cause }) { - super(`Prefix "${prefix}" is invalid.`, { - cause - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "PublicKey.InvalidPrefixError" - }); - } +async function scheduleMulticall2(client, parameters) { + const { batchSize, call: call2, multicallAddress, ...rest } = parameters; + const { wait = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; + const { schedule } = createBatchScheduler({ + id: stringify(["multicall", client.uid, batchSize, multicallAddress, rest]), + wait, + shouldSplitBatch(calls) { + if (batchSize === 0) + return false; + const size6 = calls.reduce((size7, { callData }) => size7 + (callData.length - 2) / 2, 0); + return size6 > batchSize; + }, + fn: (calls) => getAction(client, readContract, "readContract")({ + ...multicallAddress === null ? { code: multicall3Bytecode } : { address: multicallAddress }, + ...rest, + abi: multicall3Abi, + args: [calls], + functionName: "aggregate3" + }) + }); + const [result] = await schedule(call2); + return result; } -class InvalidCompressedPrefixError extends BaseError3 { - constructor() { - super("Prefix must be 2 or 3 for compressed public keys."); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "PublicKey.InvalidCompressedPrefixError" +// ../viem/src/_esm/actions/public/simulateBlocks.js +init_BlockOverrides(); +init_abi(); +init_contract(); +init_node(); +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_toHex(); +init_getNodeError(); +init_transactionRequest(); +init_stateOverride2(); +init_assertRequest(); +async function simulateBlocks(client, parameters) { + const { blockNumber, blockTag = client.experimental_blockTag ?? "latest", blocks, returnFullTransactions, traceTransfers, validation } = parameters; + try { + const blockStateCalls = []; + for (const block2 of blocks) { + const blockOverrides = block2.blockOverrides ? toRpc2(block2.blockOverrides) : undefined; + const calls = block2.calls.map((call_) => { + const call2 = call_; + const account = call2.account ? parseAccount(call2.account) : undefined; + const data = call2.abi ? encodeFunctionData(call2) : call2.data; + const request = { + ...call2, + account, + data: call2.dataSuffix ? concat([data || "0x", call2.dataSuffix]) : data, + from: call2.from ?? account?.address + }; + assertRequest(request); + return formatTransactionRequest(request); + }); + const stateOverrides = block2.stateOverrides ? serializeStateOverride(block2.stateOverrides) : undefined; + blockStateCalls.push({ + blockOverrides, + calls, + stateOverrides + }); + } + const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : undefined; + const block = blockNumberHex || blockTag; + const result = await client.request({ + method: "eth_simulateV1", + params: [ + { blockStateCalls, returnFullTransactions, traceTransfers, validation }, + block + ] + }); + return result.map((block2, i) => ({ + ...formatBlock(block2), + calls: block2.calls.map((call2, j) => { + const { abi: abi2, args, functionName, to } = blocks[i].calls[j]; + const data = call2.error?.data ?? call2.returnData; + const gasUsed = BigInt(call2.gasUsed); + const logs = call2.logs?.map((log) => formatLog(log)); + const status = call2.status === "0x1" ? "success" : "failure"; + const result2 = abi2 && status === "success" && data !== "0x" ? decodeFunctionResult({ + abi: abi2, + data, + functionName + }) : null; + const error = (() => { + if (status === "success") + return; + let error2; + if (data === "0x") + error2 = new AbiDecodingZeroDataError; + else if (data) + error2 = new RawContractError({ data }); + if (!error2) + return; + return getContractError(error2, { + abi: abi2 ?? [], + address: to ?? "0x", + args, + functionName: functionName ?? "" + }); + })(); + return { + data, + gasUsed, + logs, + status, + ...status === "success" ? { + result: result2 + } : { + error + } + }; + }) + })); + } catch (e) { + const cause = e; + const error = getNodeError(cause, {}); + if (error instanceof UnknownNodeError) + throw cause; + throw error; + } +} + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiItem.js +init_exports(); +init_Errors(); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Hash.js +init_sha3(); +init_Bytes(); +init_Hex(); +function keccak2563(value, options = {}) { + const { as = typeof value === "string" ? "Hex" : "Bytes" } = options; + const bytes = keccak_256(from2(value)); + if (as === "Bytes") + return bytes; + return fromBytes(bytes); +} + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiItem.js +init_Hex(); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Address.js +init_Bytes(); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/lru.js +class LruMap2 extends Map { + constructor(size6) { + super(); + Object.defineProperty(this, "maxSize", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.maxSize = size6; + } + get(key) { + const value = super.get(key); + if (super.has(key) && value !== undefined) { + this.delete(key); + super.set(key, value); + } + return value; + } + set(key, value) { + super.set(key, value); + if (this.maxSize && this.size > this.maxSize) { + const firstKey = this.keys().next().value; + if (firstKey) + this.delete(firstKey); + } + return this; + } +} + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Caches.js +var caches = { + checksum: /* @__PURE__ */ new LruMap2(8192) +}; +var checksum = caches.checksum; + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Address.js +init_Errors(); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/PublicKey.js +init_Bytes(); +init_Errors(); +init_Hex(); +function assert3(publicKey, options = {}) { + const { compressed } = options; + const { prefix, x, y } = publicKey; + if (compressed === false || typeof x === "bigint" && typeof y === "bigint") { + if (prefix !== 4) + throw new InvalidPrefixError({ + prefix, + cause: new InvalidUncompressedPrefixError + }); + return; + } + if (compressed === true || typeof x === "bigint" && typeof y === "undefined") { + if (prefix !== 3 && prefix !== 2) + throw new InvalidPrefixError({ + prefix, + cause: new InvalidCompressedPrefixError + }); + return; + } + throw new InvalidError({ publicKey }); +} +function from4(value) { + const publicKey = (() => { + if (validate2(value)) + return fromHex3(value); + if (validate(value)) + return fromBytes3(value); + const { prefix, x, y } = value; + if (typeof x === "bigint" && typeof y === "bigint") + return { prefix: prefix ?? 4, x, y }; + return { prefix, x }; + })(); + assert3(publicKey); + return publicKey; +} +function fromBytes3(publicKey) { + return fromHex3(fromBytes(publicKey)); +} +function fromHex3(publicKey) { + if (publicKey.length !== 132 && publicKey.length !== 130 && publicKey.length !== 68) + throw new InvalidSerializedSizeError({ publicKey }); + if (publicKey.length === 130) { + const x2 = BigInt(slice3(publicKey, 0, 32)); + const y = BigInt(slice3(publicKey, 32, 64)); + return { + prefix: 4, + x: x2, + y + }; + } + if (publicKey.length === 132) { + const prefix2 = Number(slice3(publicKey, 0, 1)); + const x2 = BigInt(slice3(publicKey, 1, 33)); + const y = BigInt(slice3(publicKey, 33, 65)); + return { + prefix: prefix2, + x: x2, + y + }; + } + const prefix = Number(slice3(publicKey, 0, 1)); + const x = BigInt(slice3(publicKey, 1, 33)); + return { + prefix, + x + }; +} +function toHex2(publicKey, options = {}) { + assert3(publicKey); + const { prefix, x, y } = publicKey; + const { includePrefix = true } = options; + const publicKey_ = concat2(includePrefix ? fromNumber(prefix, { size: 1 }) : "0x", fromNumber(x, { size: 32 }), typeof y === "bigint" ? fromNumber(y, { size: 32 }) : "0x"); + return publicKey_; +} +class InvalidError extends BaseError3 { + constructor({ publicKey }) { + super(`Value \`${stringify2(publicKey)}\` is not a valid public key.`, { + metaMessages: [ + "Public key must contain:", + "- an `x` and `prefix` value (compressed)", + "- an `x`, `y`, and `prefix` value (uncompressed)" + ] + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "PublicKey.InvalidError" + }); + } +} + +class InvalidPrefixError extends BaseError3 { + constructor({ prefix, cause }) { + super(`Prefix "${prefix}" is invalid.`, { + cause + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "PublicKey.InvalidPrefixError" + }); + } +} + +class InvalidCompressedPrefixError extends BaseError3 { + constructor() { + super("Prefix must be 2 or 3 for compressed public keys."); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "PublicKey.InvalidCompressedPrefixError" }); } } @@ -14632,7 +13026,7 @@ class InvalidSerializedSizeError extends BaseError3 { super(`Value \`${publicKey}\` is an invalid public key size.`, { metaMessages: [ "Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).", - `Received ${size3(from3(publicKey))} bytes.` + `Received ${size4(from3(publicKey))} bytes.` ] }); Object.defineProperty(this, "name", { @@ -14668,7 +13062,7 @@ function checksum2(address) { return checksum.get(address); assert4(address, { strict: false }); const hexAddress = address.substring(2).toLowerCase(); - const hash2 = keccak2562(fromString(hexAddress), { as: "Bytes" }); + const hash2 = keccak2563(fromString(hexAddress), { as: "Bytes" }); const characters = hexAddress.split(""); for (let i = 0;i < 40; i += 2) { if (hash2[i >> 1] >> 4 >= 8 && characters[i]) { @@ -14690,7 +13084,7 @@ function from5(address, options = {}) { return address; } function fromPublicKey(publicKey, options = {}) { - const address = keccak2562(`0x${toHex2(publicKey).slice(4)}`).substring(26); + const address = keccak2563(`0x${toHex2(publicKey).slice(4)}`).substring(26); return from5(`0x${address}`, options); } function validate3(address, options = {}) { @@ -14741,2439 +13135,2038 @@ class InvalidChecksumError extends BaseError3 { } } -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiParameters.js -init_Bytes(); -init_Errors(); -init_Hex(); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/abiParameters.js -init_Bytes(); +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/abiItem.js init_Errors(); -init_Hex(); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Solidity.js -var arrayRegex = /^(.*)\[([0-9]*)\]$/; -var bytesRegex3 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; -var integerRegex3 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; -var maxInt82 = 2n ** (8n - 1n) - 1n; -var maxInt162 = 2n ** (16n - 1n) - 1n; -var maxInt242 = 2n ** (24n - 1n) - 1n; -var maxInt322 = 2n ** (32n - 1n) - 1n; -var maxInt402 = 2n ** (40n - 1n) - 1n; -var maxInt482 = 2n ** (48n - 1n) - 1n; -var maxInt562 = 2n ** (56n - 1n) - 1n; -var maxInt642 = 2n ** (64n - 1n) - 1n; -var maxInt722 = 2n ** (72n - 1n) - 1n; -var maxInt802 = 2n ** (80n - 1n) - 1n; -var maxInt882 = 2n ** (88n - 1n) - 1n; -var maxInt962 = 2n ** (96n - 1n) - 1n; -var maxInt1042 = 2n ** (104n - 1n) - 1n; -var maxInt1122 = 2n ** (112n - 1n) - 1n; -var maxInt1202 = 2n ** (120n - 1n) - 1n; -var maxInt1282 = 2n ** (128n - 1n) - 1n; -var maxInt1362 = 2n ** (136n - 1n) - 1n; -var maxInt1442 = 2n ** (144n - 1n) - 1n; -var maxInt1522 = 2n ** (152n - 1n) - 1n; -var maxInt1602 = 2n ** (160n - 1n) - 1n; -var maxInt1682 = 2n ** (168n - 1n) - 1n; -var maxInt1762 = 2n ** (176n - 1n) - 1n; -var maxInt1842 = 2n ** (184n - 1n) - 1n; -var maxInt1922 = 2n ** (192n - 1n) - 1n; -var maxInt2002 = 2n ** (200n - 1n) - 1n; -var maxInt2082 = 2n ** (208n - 1n) - 1n; -var maxInt2162 = 2n ** (216n - 1n) - 1n; -var maxInt2242 = 2n ** (224n - 1n) - 1n; -var maxInt2322 = 2n ** (232n - 1n) - 1n; -var maxInt2402 = 2n ** (240n - 1n) - 1n; -var maxInt2482 = 2n ** (248n - 1n) - 1n; -var maxInt2562 = 2n ** (256n - 1n) - 1n; -var minInt82 = -(2n ** (8n - 1n)); -var minInt162 = -(2n ** (16n - 1n)); -var minInt242 = -(2n ** (24n - 1n)); -var minInt322 = -(2n ** (32n - 1n)); -var minInt402 = -(2n ** (40n - 1n)); -var minInt482 = -(2n ** (48n - 1n)); -var minInt562 = -(2n ** (56n - 1n)); -var minInt642 = -(2n ** (64n - 1n)); -var minInt722 = -(2n ** (72n - 1n)); -var minInt802 = -(2n ** (80n - 1n)); -var minInt882 = -(2n ** (88n - 1n)); -var minInt962 = -(2n ** (96n - 1n)); -var minInt1042 = -(2n ** (104n - 1n)); -var minInt1122 = -(2n ** (112n - 1n)); -var minInt1202 = -(2n ** (120n - 1n)); -var minInt1282 = -(2n ** (128n - 1n)); -var minInt1362 = -(2n ** (136n - 1n)); -var minInt1442 = -(2n ** (144n - 1n)); -var minInt1522 = -(2n ** (152n - 1n)); -var minInt1602 = -(2n ** (160n - 1n)); -var minInt1682 = -(2n ** (168n - 1n)); -var minInt1762 = -(2n ** (176n - 1n)); -var minInt1842 = -(2n ** (184n - 1n)); -var minInt1922 = -(2n ** (192n - 1n)); -var minInt2002 = -(2n ** (200n - 1n)); -var minInt2082 = -(2n ** (208n - 1n)); -var minInt2162 = -(2n ** (216n - 1n)); -var minInt2242 = -(2n ** (224n - 1n)); -var minInt2322 = -(2n ** (232n - 1n)); -var minInt2402 = -(2n ** (240n - 1n)); -var minInt2482 = -(2n ** (248n - 1n)); -var minInt2562 = -(2n ** (256n - 1n)); -var maxUint82 = 2n ** 8n - 1n; -var maxUint162 = 2n ** 16n - 1n; -var maxUint242 = 2n ** 24n - 1n; -var maxUint322 = 2n ** 32n - 1n; -var maxUint402 = 2n ** 40n - 1n; -var maxUint482 = 2n ** 48n - 1n; -var maxUint562 = 2n ** 56n - 1n; -var maxUint642 = 2n ** 64n - 1n; -var maxUint722 = 2n ** 72n - 1n; -var maxUint802 = 2n ** 80n - 1n; -var maxUint882 = 2n ** 88n - 1n; -var maxUint962 = 2n ** 96n - 1n; -var maxUint1042 = 2n ** 104n - 1n; -var maxUint1122 = 2n ** 112n - 1n; -var maxUint1202 = 2n ** 120n - 1n; -var maxUint1282 = 2n ** 128n - 1n; -var maxUint1362 = 2n ** 136n - 1n; -var maxUint1442 = 2n ** 144n - 1n; -var maxUint1522 = 2n ** 152n - 1n; -var maxUint1602 = 2n ** 160n - 1n; -var maxUint1682 = 2n ** 168n - 1n; -var maxUint1762 = 2n ** 176n - 1n; -var maxUint1842 = 2n ** 184n - 1n; -var maxUint1922 = 2n ** 192n - 1n; -var maxUint2002 = 2n ** 200n - 1n; -var maxUint2082 = 2n ** 208n - 1n; -var maxUint2162 = 2n ** 216n - 1n; -var maxUint2242 = 2n ** 224n - 1n; -var maxUint2322 = 2n ** 232n - 1n; -var maxUint2402 = 2n ** 240n - 1n; -var maxUint2482 = 2n ** 248n - 1n; -var maxUint2562 = 2n ** 256n - 1n; - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/abiParameters.js -function decodeParameter2(cursor, param, options) { - const { checksumAddress: checksumAddress2, staticPosition } = options; - const arrayComponents = getArrayComponents2(param.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return decodeArray2(cursor, { ...param, type }, { checksumAddress: checksumAddress2, length, staticPosition }); - } - if (param.type === "tuple") - return decodeTuple2(cursor, param, { - checksumAddress: checksumAddress2, - staticPosition - }); - if (param.type === "address") - return decodeAddress3(cursor, { checksum: checksumAddress2 }); - if (param.type === "bool") - return decodeBool2(cursor); - if (param.type.startsWith("bytes")) - return decodeBytes2(cursor, param, { staticPosition }); - if (param.type.startsWith("uint") || param.type.startsWith("int")) - return decodeNumber2(cursor, param); - if (param.type === "string") - return decodeString2(cursor, { staticPosition }); - throw new InvalidTypeError(param.type); -} -var sizeOfLength2 = 32; -var sizeOfOffset2 = 32; -function decodeAddress3(cursor, options = {}) { - const { checksum: checksum3 = false } = options; - const value = cursor.readBytes(32); - const wrap = (address) => checksum3 ? checksum2(address) : address; - return [wrap(fromBytes(slice2(value, -20))), 32]; -} -function decodeArray2(cursor, param, options) { - const { checksumAddress: checksumAddress2, length, staticPosition } = options; - if (length === null) { - const offset = toNumber2(cursor.readBytes(sizeOfOffset2)); - const start = staticPosition + offset; - const startOfData = start + sizeOfLength2; - cursor.setPosition(start); - const length2 = toNumber2(cursor.readBytes(sizeOfLength2)); - const dynamicChild = hasDynamicChild2(param); - let consumed2 = 0; - const value2 = []; - for (let i = 0;i < length2; ++i) { - cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); - const [data, consumed_] = decodeParameter2(cursor, param, { - checksumAddress: checksumAddress2, - staticPosition: startOfData - }); - consumed2 += consumed_; - value2.push(data); - if (consumed_ === 0) { - cursor.assertReadLimit(); - cursor._touch(); +function normalizeSignature2(signature) { + let active = true; + let current = ""; + let level = 0; + let result = ""; + let valid = false; + for (let i = 0;i < signature.length; i++) { + const char = signature[i]; + if (["(", ")", ","].includes(char)) + active = true; + if (char === "(") + level++; + if (char === ")") + level--; + if (!active) + continue; + if (level === 0) { + if (char === " " && ["event", "function", "error", ""].includes(result)) + result = ""; + else { + result += char; + if (char === ")") { + valid = true; + break; + } } + continue; } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; - } - if (hasDynamicChild2(param)) { - const offset = toNumber2(cursor.readBytes(sizeOfOffset2)); - const start = staticPosition + offset; - const value2 = []; - for (let i = 0;i < length; ++i) { - cursor.setPosition(start + i * 32); - const [data] = decodeParameter2(cursor, param, { - checksumAddress: checksumAddress2, - staticPosition: start - }); - value2.push(data); - } - cursor.setPosition(staticPosition + 32); - return [value2, 32]; - } - let consumed = 0; - const value = []; - for (let i = 0;i < length; ++i) { - const [data, consumed_] = decodeParameter2(cursor, param, { - checksumAddress: checksumAddress2, - staticPosition: staticPosition + consumed - }); - consumed += consumed_; - value.push(data); - if (consumed_ === 0) { - cursor.assertReadLimit(); - cursor._touch(); + if (char === " ") { + if (signature[i - 1] !== "," && current !== "," && current !== ",(") { + current = ""; + active = false; + } + continue; } + result += char; + current += char; } - return [value, consumed]; -} -function decodeBool2(cursor) { - return [toBoolean(cursor.readBytes(32), { size: 32 }), 32]; + if (!valid) + throw new BaseError3("Unable to normalize signature."); + return result; } -function decodeBytes2(cursor, param, { staticPosition }) { - const [_, size5] = param.type.split("bytes"); - if (!size5) { - const offset = toNumber2(cursor.readBytes(32)); - cursor.setPosition(staticPosition + offset); - const length = toNumber2(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["0x", 32]; +function isArgOfType2(arg, abiParameter) { + const argType = typeof arg; + const abiParameterType = abiParameter.type; + switch (abiParameterType) { + case "address": + return validate3(arg, { strict: false }); + case "bool": + return argType === "boolean"; + case "function": + return argType === "string"; + case "string": + return argType === "string"; + default: { + if (abiParameterType === "tuple" && "components" in abiParameter) + return Object.values(abiParameter.components).every((component, index2) => { + return isArgOfType2(Object.values(arg)[index2], component); + }); + if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) + return argType === "number" || argType === "bigint"; + if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) + return argType === "string" || arg instanceof Uint8Array; + if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { + return Array.isArray(arg) && arg.every((x) => isArgOfType2(x, { + ...abiParameter, + type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") + })); + } + return false; } - const data = cursor.readBytes(length); - cursor.setPosition(staticPosition + 32); - return [fromBytes(data), 32]; } - const value = fromBytes(cursor.readBytes(Number.parseInt(size5, 10), 32)); - return [value, 32]; -} -function decodeNumber2(cursor, param) { - const signed = param.type.startsWith("int"); - const size5 = Number.parseInt(param.type.split("int")[1] || "256", 10); - const value = cursor.readBytes(32); - return [ - size5 > 48 ? toBigInt2(value, { signed }) : toNumber2(value, { signed }), - 32 - ]; } -function decodeTuple2(cursor, param, options) { - const { checksumAddress: checksumAddress2, staticPosition } = options; - const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name); - const value = hasUnnamedChild ? [] : {}; - let consumed = 0; - if (hasDynamicChild2(param)) { - const offset = toNumber2(cursor.readBytes(sizeOfOffset2)); - const start = staticPosition + offset; - for (let i = 0;i < param.components.length; ++i) { - const component = param.components[i]; - cursor.setPosition(start + consumed); - const [data, consumed_] = decodeParameter2(cursor, component, { - checksumAddress: checksumAddress2, - staticPosition: start - }); - consumed += consumed_; - value[hasUnnamedChild ? i : component?.name] = data; - } - cursor.setPosition(staticPosition + 32); - return [value, 32]; - } - for (let i = 0;i < param.components.length; ++i) { - const component = param.components[i]; - const [data, consumed_] = decodeParameter2(cursor, component, { - checksumAddress: checksumAddress2, - staticPosition - }); - value[hasUnnamedChild ? i : component?.name] = data; - consumed += consumed_; +function getAmbiguousTypes2(sourceParameters, targetParameters, args) { + for (const parameterIndex in sourceParameters) { + const sourceParameter = sourceParameters[parameterIndex]; + const targetParameter = targetParameters[parameterIndex]; + if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) + return getAmbiguousTypes2(sourceParameter.components, targetParameter.components, args[parameterIndex]); + const types = [sourceParameter.type, targetParameter.type]; + const ambiguous = (() => { + if (types.includes("address") && types.includes("bytes20")) + return true; + if (types.includes("address") && types.includes("string")) + return validate3(args[parameterIndex], { + strict: false + }); + if (types.includes("address") && types.includes("bytes")) + return validate3(args[parameterIndex], { + strict: false + }); + return false; + })(); + if (ambiguous) + return types; } - return [value, consumed]; + return; } -function decodeString2(cursor, { staticPosition }) { - const offset = toNumber2(cursor.readBytes(32)); - const start = staticPosition + offset; - cursor.setPosition(start); - const length = toNumber2(cursor.readBytes(32)); - if (length === 0) { - cursor.setPosition(staticPosition + 32); - return ["", 32]; - } - const data = cursor.readBytes(length, 32); - const value = toString(trimLeft(data)); - cursor.setPosition(staticPosition + 32); - return [value, 32]; -} -function prepareParameters({ checksumAddress: checksumAddress2, parameters, values }) { - const preparedParameters = []; - for (let i = 0;i < parameters.length; i++) { - preparedParameters.push(prepareParameter({ - checksumAddress: checksumAddress2, - parameter: parameters[i], - value: values[i] - })); - } - return preparedParameters; -} -function prepareParameter({ checksumAddress: checksumAddress2 = false, parameter: parameter_, value }) { - const parameter = parameter_; - const arrayComponents = getArrayComponents2(parameter.type); - if (arrayComponents) { - const [length, type] = arrayComponents; - return encodeArray2(value, { - checksumAddress: checksumAddress2, - length, - parameter: { - ...parameter, - type - } - }); - } - if (parameter.type === "tuple") { - return encodeTuple2(value, { - checksumAddress: checksumAddress2, - parameter - }); - } - if (parameter.type === "address") { - return encodeAddress2(value, { - checksum: checksumAddress2 - }); - } - if (parameter.type === "bool") { - return encodeBoolean(value); - } - if (parameter.type.startsWith("uint") || parameter.type.startsWith("int")) { - const signed = parameter.type.startsWith("int"); - const [, , size5 = "256"] = integerRegex3.exec(parameter.type) ?? []; - return encodeNumber2(value, { - signed, - size: Number(size5) - }); - } - if (parameter.type.startsWith("bytes")) { - return encodeBytes2(value, { type: parameter.type }); - } - if (parameter.type === "string") { - return encodeString2(value); - } - throw new InvalidTypeError(parameter.type); -} -function encode(preparedParameters) { - let staticSize = 0; - for (let i = 0;i < preparedParameters.length; i++) { - const { dynamic, encoded } = preparedParameters[i]; - if (dynamic) - staticSize += 32; - else - staticSize += size3(encoded); - } - const staticParameters = []; - const dynamicParameters = []; - let dynamicSize = 0; - for (let i = 0;i < preparedParameters.length; i++) { - const { dynamic, encoded } = preparedParameters[i]; - if (dynamic) { - staticParameters.push(fromNumber(staticSize + dynamicSize, { size: 32 })); - dynamicParameters.push(encoded); - dynamicSize += size3(encoded); - } else { - staticParameters.push(encoded); - } - } - return concat2(...staticParameters, ...dynamicParameters); -} -function encodeAddress2(value, options) { - const { checksum: checksum3 = false } = options; - assert4(value, { strict: checksum3 }); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiItem.js +function from6(abiItem, options = {}) { + const { prepare = true } = options; + const item = (() => { + if (Array.isArray(abiItem)) + return parseAbiItem(abiItem); + if (typeof abiItem === "string") + return parseAbiItem(abiItem); + return abiItem; + })(); return { - dynamic: false, - encoded: padLeft(value.toLowerCase()) + ...item, + ...prepare ? { hash: getSignatureHash(item) } : {} }; } -function encodeArray2(value, options) { - const { checksumAddress: checksumAddress2, length, parameter } = options; - const dynamic = length === null; - if (!Array.isArray(value)) - throw new InvalidArrayError2(value); - if (!dynamic && value.length !== length) - throw new ArrayLengthMismatchError({ - expectedLength: length, - givenLength: value.length, - type: `${parameter.type}[${length}]` - }); - let dynamicChild = value.length === 0 && hasDynamicChild2(parameter); - const preparedParameters = []; - for (let i = 0;i < value.length; i++) { - const preparedParam = prepareParameter({ - checksumAddress: checksumAddress2, - parameter, - value: value[i] - }); - if (preparedParam.dynamic) - dynamicChild = true; - preparedParameters.push(preparedParam); - } - if (dynamic || dynamicChild) { - const data = encode(preparedParameters); - if (dynamic) { - const length2 = fromNumber(preparedParameters.length, { size: 32 }); - return { - dynamic: true, - encoded: preparedParameters.length > 0 ? concat2(length2, data) : length2 - }; +function fromAbi(abi2, name, options) { + const { args = [], prepare = true } = options ?? {}; + const isSelector = validate2(name, { strict: false }); + const abiItems = abi2.filter((abiItem2) => { + if (isSelector) { + if (abiItem2.type === "function" || abiItem2.type === "error") + return getSelector(abiItem2) === slice3(name, 0, 4); + if (abiItem2.type === "event") + return getSignatureHash(abiItem2) === name; + return false; } - if (dynamicChild) - return { dynamic: true, encoded: data }; - } - return { - dynamic: false, - encoded: concat2(...preparedParameters.map(({ encoded }) => encoded)) - }; -} -function encodeBytes2(value, { type }) { - const [, parametersize] = type.split("bytes"); - const bytesSize = size3(value); - if (!parametersize) { - let value_ = value; - if (bytesSize % 32 !== 0) - value_ = padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32); + return "name" in abiItem2 && abiItem2.name === name; + }); + if (abiItems.length === 0) + throw new NotFoundError({ name }); + if (abiItems.length === 1) return { - dynamic: true, - encoded: concat2(padLeft(fromNumber(bytesSize, { size: 32 })), value_) + ...abiItems[0], + ...prepare ? { hash: getSignatureHash(abiItems[0]) } : {} }; - } - if (bytesSize !== Number.parseInt(parametersize, 10)) - throw new BytesSizeMismatchError2({ - expectedSize: Number.parseInt(parametersize, 10), - value + let matchedAbiItem; + for (const abiItem2 of abiItems) { + if (!("inputs" in abiItem2)) + continue; + if (!args || args.length === 0) { + if (!abiItem2.inputs || abiItem2.inputs.length === 0) + return { + ...abiItem2, + ...prepare ? { hash: getSignatureHash(abiItem2) } : {} + }; + continue; + } + if (!abiItem2.inputs) + continue; + if (abiItem2.inputs.length === 0) + continue; + if (abiItem2.inputs.length !== args.length) + continue; + const matched = args.every((arg, index2) => { + const abiParameter = "inputs" in abiItem2 && abiItem2.inputs[index2]; + if (!abiParameter) + return false; + return isArgOfType2(arg, abiParameter); }); - return { dynamic: false, encoded: padRight(value) }; -} -function encodeBoolean(value) { - if (typeof value !== "boolean") - throw new BaseError3(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); - return { dynamic: false, encoded: padLeft(fromBoolean(value)) }; -} -function encodeNumber2(value, { signed, size: size5 }) { - if (typeof size5 === "number") { - const max = 2n ** (BigInt(size5) - (signed ? 1n : 0n)) - 1n; - const min = signed ? -max - 1n : 0n; - if (value > max || value < min) - throw new IntegerOutOfRangeError2({ - max: max.toString(), - min: min.toString(), - signed, - size: size5 / 8, - value: value.toString() - }); - } - return { - dynamic: false, - encoded: fromNumber(value, { - size: 32, - signed - }) - }; -} -function encodeString2(value) { - const hexValue = fromString2(value); - const partsLength = Math.ceil(size3(hexValue) / 32); - const parts = []; - for (let i = 0;i < partsLength; i++) { - parts.push(padRight(slice3(hexValue, i * 32, (i + 1) * 32))); + if (matched) { + if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { + const ambiguousTypes = getAmbiguousTypes2(abiItem2.inputs, matchedAbiItem.inputs, args); + if (ambiguousTypes) + throw new AmbiguityError({ + abiItem: abiItem2, + type: ambiguousTypes[0] + }, { + abiItem: matchedAbiItem, + type: ambiguousTypes[1] + }); + } + matchedAbiItem = abiItem2; + } } + const abiItem = (() => { + if (matchedAbiItem) + return matchedAbiItem; + const [abiItem2, ...overloads] = abiItems; + return { ...abiItem2, overloads }; + })(); + if (!abiItem) + throw new NotFoundError({ name }); return { - dynamic: true, - encoded: concat2(padRight(fromNumber(size3(hexValue), { size: 32 })), ...parts) + ...abiItem, + ...prepare ? { hash: getSignatureHash(abiItem) } : {} }; } -function encodeTuple2(value, options) { - const { checksumAddress: checksumAddress2, parameter } = options; - let dynamic = false; - const preparedParameters = []; - for (let i = 0;i < parameter.components.length; i++) { - const param_ = parameter.components[i]; - const index2 = Array.isArray(value) ? i : param_.name; - const preparedParam = prepareParameter({ - checksumAddress: checksumAddress2, - parameter: param_, - value: value[index2] - }); - preparedParameters.push(preparedParam); - if (preparedParam.dynamic) - dynamic = true; - } - return { - dynamic, - encoded: dynamic ? encode(preparedParameters) : concat2(...preparedParameters.map(({ encoded }) => encoded)) - }; -} -function getArrayComponents2(type) { - const matches = type.match(/^(.*)\[(\d+)?\]$/); - return matches ? [matches[2] ? Number(matches[2]) : null, matches[1]] : undefined; +function getSelector(...parameters) { + const abiItem = (() => { + if (Array.isArray(parameters[0])) { + const [abi2, name] = parameters; + return fromAbi(abi2, name); + } + return parameters[0]; + })(); + return slice3(getSignatureHash(abiItem), 0, 4); } -function hasDynamicChild2(param) { - const { type } = param; - if (type === "string") - return true; - if (type === "bytes") - return true; - if (type.endsWith("[]")) - return true; - if (type === "tuple") - return param.components?.some(hasDynamicChild2); - const arrayComponents = getArrayComponents2(param.type); - if (arrayComponents && hasDynamicChild2({ - ...param, - type: arrayComponents[1] - })) - return true; - return false; +function getSignature(...parameters) { + const abiItem = (() => { + if (Array.isArray(parameters[0])) { + const [abi2, name] = parameters; + return fromAbi(abi2, name); + } + return parameters[0]; + })(); + const signature = (() => { + if (typeof abiItem === "string") + return abiItem; + return formatAbiItem(abiItem); + })(); + return normalizeSignature2(signature); } - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/cursor.js -init_Errors(); -var staticCursor2 = { - bytes: new Uint8Array, - dataView: new DataView(new ArrayBuffer(0)), - position: 0, - positionReadCount: new Map, - recursiveReadCount: 0, - recursiveReadLimit: Number.POSITIVE_INFINITY, - assertReadLimit() { - if (this.recursiveReadCount >= this.recursiveReadLimit) - throw new RecursiveReadLimitExceededError2({ - count: this.recursiveReadCount + 1, - limit: this.recursiveReadLimit - }); - }, - assertPosition(position) { - if (position < 0 || position > this.bytes.length - 1) - throw new PositionOutOfBoundsError2({ - length: this.bytes.length, - position - }); - }, - decrementPosition(offset) { - if (offset < 0) - throw new NegativeOffsetError2({ offset }); - const position = this.position - offset; - this.assertPosition(position); - this.position = position; - }, - getReadCount(position) { - return this.positionReadCount.get(position || this.position) || 0; - }, - incrementPosition(offset) { - if (offset < 0) - throw new NegativeOffsetError2({ offset }); - const position = this.position + offset; - this.assertPosition(position); - this.position = position; - }, - inspectByte(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectBytes(length, position_) { - const position = position_ ?? this.position; - this.assertPosition(position + length - 1); - return this.bytes.subarray(position, position + length); - }, - inspectUint8(position_) { - const position = position_ ?? this.position; - this.assertPosition(position); - return this.bytes[position]; - }, - inspectUint16(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 1); - return this.dataView.getUint16(position); - }, - inspectUint24(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 2); - return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); - }, - inspectUint32(position_) { - const position = position_ ?? this.position; - this.assertPosition(position + 3); - return this.dataView.getUint32(position); - }, - pushByte(byte) { - this.assertPosition(this.position); - this.bytes[this.position] = byte; - this.position++; - }, - pushBytes(bytes) { - this.assertPosition(this.position + bytes.length - 1); - this.bytes.set(bytes, this.position); - this.position += bytes.length; - }, - pushUint8(value) { - this.assertPosition(this.position); - this.bytes[this.position] = value; - this.position++; - }, - pushUint16(value) { - this.assertPosition(this.position + 1); - this.dataView.setUint16(this.position, value); - this.position += 2; - }, - pushUint24(value) { - this.assertPosition(this.position + 2); - this.dataView.setUint16(this.position, value >> 8); - this.dataView.setUint8(this.position + 2, value & ~4294967040); - this.position += 3; - }, - pushUint32(value) { - this.assertPosition(this.position + 3); - this.dataView.setUint32(this.position, value); - this.position += 4; - }, - readByte() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectByte(); - this.position++; - return value; - }, - readBytes(length, size5) { - this.assertReadLimit(); - this._touch(); - const value = this.inspectBytes(length); - this.position += size5 ?? length; - return value; - }, - readUint8() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint8(); - this.position += 1; - return value; - }, - readUint16() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint16(); - this.position += 2; - return value; - }, - readUint24() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint24(); - this.position += 3; - return value; - }, - readUint32() { - this.assertReadLimit(); - this._touch(); - const value = this.inspectUint32(); - this.position += 4; - return value; - }, - get remaining() { - return this.bytes.length - this.position; - }, - setPosition(position) { - const oldPosition = this.position; - this.assertPosition(position); - this.position = position; - return () => this.position = oldPosition; - }, - _touch() { - if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) - return; - const count = this.getReadCount(); - this.positionReadCount.set(this.position, count + 1); - if (count > 0) - this.recursiveReadCount++; - } -}; -function create(bytes, { recursiveReadLimit = 8192 } = {}) { - const cursor = Object.create(staticCursor2); - cursor.bytes = bytes; - cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - cursor.positionReadCount = new Map; - cursor.recursiveReadLimit = recursiveReadLimit; - return cursor; +function getSignatureHash(...parameters) { + const abiItem = (() => { + if (Array.isArray(parameters[0])) { + const [abi2, name] = parameters; + return fromAbi(abi2, name); + } + return parameters[0]; + })(); + if (typeof abiItem !== "string" && "hash" in abiItem && abiItem.hash) + return abiItem.hash; + return keccak2563(fromString2(getSignature(abiItem))); } -class NegativeOffsetError2 extends BaseError3 { - constructor({ offset }) { - super(`Offset \`${offset}\` cannot be negative.`); +class AmbiguityError extends BaseError3 { + constructor(x, y) { + super("Found ambiguous types in overloaded ABI Items.", { + metaMessages: [ + `\`${x.type}\` in \`${normalizeSignature2(formatAbiItem(x.abiItem))}\`, and`, + `\`${y.type}\` in \`${normalizeSignature2(formatAbiItem(y.abiItem))}\``, + "", + "These types encode differently and cannot be distinguished at runtime.", + "Remove one of the ambiguous items in the ABI." + ] + }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: "Cursor.NegativeOffsetError" + value: "AbiItem.AmbiguityError" }); } } -class PositionOutOfBoundsError2 extends BaseError3 { - constructor({ length, position }) { - super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Cursor.PositionOutOfBoundsError" - }); - } -} - -class RecursiveReadLimitExceededError2 extends BaseError3 { - constructor({ count, limit }) { - super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`); +class NotFoundError extends BaseError3 { + constructor({ name, data, type = "item" }) { + const selector = (() => { + if (name) + return ` with name "${name}"`; + if (data) + return ` with data "${data}"`; + return ""; + })(); + super(`ABI ${type}${selector} not found.`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: "Cursor.RecursiveReadLimitExceededError" + value: "AbiItem.NotFoundError" }); } } // ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiParameters.js -function decode(parameters, data, options = {}) { - const { as = "Array", checksumAddress: checksumAddress2 = false } = options; - const bytes = typeof data === "string" ? fromHex(data) : data; - const cursor = create(bytes); - if (size2(bytes) === 0 && parameters.length > 0) - throw new ZeroDataError; - if (size2(bytes) && size2(bytes) < 32) - throw new DataSizeTooSmallError({ - data: typeof data === "string" ? data : fromBytes(data), - parameters, - size: size2(bytes) +init_exports(); +init_Bytes(); +init_Errors(); +init_Hex(); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/abiParameters.js +init_Bytes(); +init_Errors(); +init_Hex(); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Solidity.js +var arrayRegex2 = /^(.*)\[([0-9]*)\]$/; +var bytesRegex4 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; +var integerRegex4 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; +var maxInt82 = 2n ** (8n - 1n) - 1n; +var maxInt162 = 2n ** (16n - 1n) - 1n; +var maxInt242 = 2n ** (24n - 1n) - 1n; +var maxInt322 = 2n ** (32n - 1n) - 1n; +var maxInt402 = 2n ** (40n - 1n) - 1n; +var maxInt482 = 2n ** (48n - 1n) - 1n; +var maxInt562 = 2n ** (56n - 1n) - 1n; +var maxInt642 = 2n ** (64n - 1n) - 1n; +var maxInt722 = 2n ** (72n - 1n) - 1n; +var maxInt802 = 2n ** (80n - 1n) - 1n; +var maxInt882 = 2n ** (88n - 1n) - 1n; +var maxInt962 = 2n ** (96n - 1n) - 1n; +var maxInt1042 = 2n ** (104n - 1n) - 1n; +var maxInt1122 = 2n ** (112n - 1n) - 1n; +var maxInt1202 = 2n ** (120n - 1n) - 1n; +var maxInt1282 = 2n ** (128n - 1n) - 1n; +var maxInt1362 = 2n ** (136n - 1n) - 1n; +var maxInt1442 = 2n ** (144n - 1n) - 1n; +var maxInt1522 = 2n ** (152n - 1n) - 1n; +var maxInt1602 = 2n ** (160n - 1n) - 1n; +var maxInt1682 = 2n ** (168n - 1n) - 1n; +var maxInt1762 = 2n ** (176n - 1n) - 1n; +var maxInt1842 = 2n ** (184n - 1n) - 1n; +var maxInt1922 = 2n ** (192n - 1n) - 1n; +var maxInt2002 = 2n ** (200n - 1n) - 1n; +var maxInt2082 = 2n ** (208n - 1n) - 1n; +var maxInt2162 = 2n ** (216n - 1n) - 1n; +var maxInt2242 = 2n ** (224n - 1n) - 1n; +var maxInt2322 = 2n ** (232n - 1n) - 1n; +var maxInt2402 = 2n ** (240n - 1n) - 1n; +var maxInt2482 = 2n ** (248n - 1n) - 1n; +var maxInt2562 = 2n ** (256n - 1n) - 1n; +var minInt82 = -(2n ** (8n - 1n)); +var minInt162 = -(2n ** (16n - 1n)); +var minInt242 = -(2n ** (24n - 1n)); +var minInt322 = -(2n ** (32n - 1n)); +var minInt402 = -(2n ** (40n - 1n)); +var minInt482 = -(2n ** (48n - 1n)); +var minInt562 = -(2n ** (56n - 1n)); +var minInt642 = -(2n ** (64n - 1n)); +var minInt722 = -(2n ** (72n - 1n)); +var minInt802 = -(2n ** (80n - 1n)); +var minInt882 = -(2n ** (88n - 1n)); +var minInt962 = -(2n ** (96n - 1n)); +var minInt1042 = -(2n ** (104n - 1n)); +var minInt1122 = -(2n ** (112n - 1n)); +var minInt1202 = -(2n ** (120n - 1n)); +var minInt1282 = -(2n ** (128n - 1n)); +var minInt1362 = -(2n ** (136n - 1n)); +var minInt1442 = -(2n ** (144n - 1n)); +var minInt1522 = -(2n ** (152n - 1n)); +var minInt1602 = -(2n ** (160n - 1n)); +var minInt1682 = -(2n ** (168n - 1n)); +var minInt1762 = -(2n ** (176n - 1n)); +var minInt1842 = -(2n ** (184n - 1n)); +var minInt1922 = -(2n ** (192n - 1n)); +var minInt2002 = -(2n ** (200n - 1n)); +var minInt2082 = -(2n ** (208n - 1n)); +var minInt2162 = -(2n ** (216n - 1n)); +var minInt2242 = -(2n ** (224n - 1n)); +var minInt2322 = -(2n ** (232n - 1n)); +var minInt2402 = -(2n ** (240n - 1n)); +var minInt2482 = -(2n ** (248n - 1n)); +var minInt2562 = -(2n ** (256n - 1n)); +var maxUint82 = 2n ** 8n - 1n; +var maxUint162 = 2n ** 16n - 1n; +var maxUint242 = 2n ** 24n - 1n; +var maxUint322 = 2n ** 32n - 1n; +var maxUint402 = 2n ** 40n - 1n; +var maxUint482 = 2n ** 48n - 1n; +var maxUint562 = 2n ** 56n - 1n; +var maxUint642 = 2n ** 64n - 1n; +var maxUint722 = 2n ** 72n - 1n; +var maxUint802 = 2n ** 80n - 1n; +var maxUint882 = 2n ** 88n - 1n; +var maxUint962 = 2n ** 96n - 1n; +var maxUint1042 = 2n ** 104n - 1n; +var maxUint1122 = 2n ** 112n - 1n; +var maxUint1202 = 2n ** 120n - 1n; +var maxUint1282 = 2n ** 128n - 1n; +var maxUint1362 = 2n ** 136n - 1n; +var maxUint1442 = 2n ** 144n - 1n; +var maxUint1522 = 2n ** 152n - 1n; +var maxUint1602 = 2n ** 160n - 1n; +var maxUint1682 = 2n ** 168n - 1n; +var maxUint1762 = 2n ** 176n - 1n; +var maxUint1842 = 2n ** 184n - 1n; +var maxUint1922 = 2n ** 192n - 1n; +var maxUint2002 = 2n ** 200n - 1n; +var maxUint2082 = 2n ** 208n - 1n; +var maxUint2162 = 2n ** 216n - 1n; +var maxUint2242 = 2n ** 224n - 1n; +var maxUint2322 = 2n ** 232n - 1n; +var maxUint2402 = 2n ** 240n - 1n; +var maxUint2482 = 2n ** 248n - 1n; +var maxUint2562 = 2n ** 256n - 1n; + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/abiParameters.js +function decodeParameter2(cursor, param, options) { + const { checksumAddress: checksumAddress2, staticPosition } = options; + const arrayComponents = getArrayComponents2(param.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return decodeArray2(cursor, { ...param, type }, { checksumAddress: checksumAddress2, length, staticPosition }); + } + if (param.type === "tuple") + return decodeTuple2(cursor, param, { + checksumAddress: checksumAddress2, + staticPosition }); + if (param.type === "address") + return decodeAddress3(cursor, { checksum: checksumAddress2 }); + if (param.type === "bool") + return decodeBool2(cursor); + if (param.type.startsWith("bytes")) + return decodeBytes2(cursor, param, { staticPosition }); + if (param.type.startsWith("uint") || param.type.startsWith("int")) + return decodeNumber2(cursor, param); + if (param.type === "string") + return decodeString2(cursor, { staticPosition }); + throw new InvalidTypeError(param.type); +} +var sizeOfLength2 = 32; +var sizeOfOffset2 = 32; +function decodeAddress3(cursor, options = {}) { + const { checksum: checksum3 = false } = options; + const value = cursor.readBytes(32); + const wrap = (address) => checksum3 ? checksum2(address) : address; + return [wrap(fromBytes(slice2(value, -20))), 32]; +} +function decodeArray2(cursor, param, options) { + const { checksumAddress: checksumAddress2, length, staticPosition } = options; + if (length === null) { + const offset = toNumber2(cursor.readBytes(sizeOfOffset2)); + const start = staticPosition + offset; + const startOfData = start + sizeOfLength2; + cursor.setPosition(start); + const length2 = toNumber2(cursor.readBytes(sizeOfLength2)); + const dynamicChild = hasDynamicChild2(param); + let consumed2 = 0; + const value2 = []; + for (let i = 0;i < length2; ++i) { + cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed2)); + const [data, consumed_] = decodeParameter2(cursor, param, { + checksumAddress: checksumAddress2, + staticPosition: startOfData + }); + consumed2 += consumed_; + value2.push(data); + if (consumed_ === 0) { + cursor.assertReadLimit(); + cursor._touch(); + } + } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; + } + if (hasDynamicChild2(param)) { + const offset = toNumber2(cursor.readBytes(sizeOfOffset2)); + const start = staticPosition + offset; + const value2 = []; + for (let i = 0;i < length; ++i) { + cursor.setPosition(start + i * 32); + const [data] = decodeParameter2(cursor, param, { + checksumAddress: checksumAddress2, + staticPosition: start + }); + value2.push(data); + } + cursor.setPosition(staticPosition + 32); + return [value2, 32]; + } let consumed = 0; - const values = as === "Array" ? [] : {}; - for (let i = 0;i < parameters.length; ++i) { - const param = parameters[i]; - if (consumed < bytes.length) - cursor.setPosition(consumed); - const [data2, consumed_] = decodeParameter2(cursor, param, { + const value = []; + for (let i = 0;i < length; ++i) { + const [data, consumed_] = decodeParameter2(cursor, param, { checksumAddress: checksumAddress2, - staticPosition: 0 + staticPosition: staticPosition + consumed }); consumed += consumed_; - if (as === "Array") - values.push(data2); - else - values[param.name ?? i] = data2; + value.push(data); + if (consumed_ === 0) { + cursor.assertReadLimit(); + cursor._touch(); + } } - return values; + return [value, consumed]; } -function encode2(parameters, values, options) { - const { checksumAddress: checksumAddress2 = false } = options ?? {}; - if (parameters.length !== values.length) - throw new LengthMismatchError({ - expectedLength: parameters.length, - givenLength: values.length - }); - const preparedParameters = prepareParameters({ - checksumAddress: checksumAddress2, - parameters, - values - }); - const data = encode(preparedParameters); - if (data.length === 0) - return "0x"; - return data; +function decodeBool2(cursor) { + return [toBoolean(cursor.readBytes(32), { size: 32 }), 32]; } -function encodePacked(types, values) { - if (types.length !== values.length) - throw new LengthMismatchError({ - expectedLength: types.length, - givenLength: values.length - }); - const data = []; - for (let i = 0;i < types.length; i++) { - const type = types[i]; - const value = values[i]; - data.push(encodePacked.encode(type, value)); +function decodeBytes2(cursor, param, { staticPosition }) { + const [_, size6] = param.type.split("bytes"); + if (!size6) { + const offset = toNumber2(cursor.readBytes(32)); + cursor.setPosition(staticPosition + offset); + const length = toNumber2(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["0x", 32]; + } + const data = cursor.readBytes(length); + cursor.setPosition(staticPosition + 32); + return [fromBytes(data), 32]; } - return concat2(...data); + const value = fromBytes(cursor.readBytes(Number.parseInt(size6, 10), 32)); + return [value, 32]; } -(function(encodePacked2) { - function encode3(type, value, isArray = false) { - if (type === "address") { - const address = value; - assert4(address); - return padLeft(address.toLowerCase(), isArray ? 32 : 0); - } - if (type === "string") - return fromString2(value); - if (type === "bytes") - return value; - if (type === "bool") - return padLeft(fromBoolean(value), isArray ? 32 : 1); - const intMatch = type.match(integerRegex3); - if (intMatch) { - const [_type, baseType, bits = "256"] = intMatch; - const size5 = Number.parseInt(bits, 10) / 8; - return fromNumber(value, { - size: isArray ? 32 : size5, - signed: baseType === "int" +function decodeNumber2(cursor, param) { + const signed = param.type.startsWith("int"); + const size6 = Number.parseInt(param.type.split("int")[1] || "256", 10); + const value = cursor.readBytes(32); + return [ + size6 > 48 ? toBigInt2(value, { signed }) : toNumber2(value, { signed }), + 32 + ]; +} +function decodeTuple2(cursor, param, options) { + const { checksumAddress: checksumAddress2, staticPosition } = options; + const hasUnnamedChild = param.components.length === 0 || param.components.some(({ name }) => !name); + const value = hasUnnamedChild ? [] : {}; + let consumed = 0; + if (hasDynamicChild2(param)) { + const offset = toNumber2(cursor.readBytes(sizeOfOffset2)); + const start = staticPosition + offset; + for (let i = 0;i < param.components.length; ++i) { + const component = param.components[i]; + cursor.setPosition(start + consumed); + const [data, consumed_] = decodeParameter2(cursor, component, { + checksumAddress: checksumAddress2, + staticPosition: start }); + consumed += consumed_; + value[hasUnnamedChild ? i : component?.name] = data; } - const bytesMatch = type.match(bytesRegex3); - if (bytesMatch) { - const [_type, size5] = bytesMatch; - if (Number.parseInt(size5, 10) !== (value.length - 2) / 2) - throw new BytesSizeMismatchError2({ - expectedSize: Number.parseInt(size5, 10), - value - }); - return padRight(value, isArray ? 32 : 0); - } - const arrayMatch = type.match(arrayRegex); - if (arrayMatch && Array.isArray(value)) { - const [_type, childType] = arrayMatch; - const data = []; - for (let i = 0;i < value.length; i++) { - data.push(encode3(childType, value[i], true)); - } - if (data.length === 0) - return "0x"; - return concat2(...data); - } - throw new InvalidTypeError(type); + cursor.setPosition(staticPosition + 32); + return [value, 32]; } - encodePacked2.encode = encode3; -})(encodePacked || (encodePacked = {})); -function from6(parameters) { - if (Array.isArray(parameters) && typeof parameters[0] === "string") - return parseAbiParameters(parameters); - if (typeof parameters === "string") - return parseAbiParameters(parameters); - return parameters; -} - -class DataSizeTooSmallError extends BaseError3 { - constructor({ data, parameters, size: size5 }) { - super(`Data size of ${size5} bytes is too small for given parameters.`, { - metaMessages: [ - `Params: (${formatAbiParameters(parameters)})`, - `Data: ${data} (${size5} bytes)` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.DataSizeTooSmallError" + for (let i = 0;i < param.components.length; ++i) { + const component = param.components[i]; + const [data, consumed_] = decodeParameter2(cursor, component, { + checksumAddress: checksumAddress2, + staticPosition }); + value[hasUnnamedChild ? i : component?.name] = data; + consumed += consumed_; } + return [value, consumed]; } - -class ZeroDataError extends BaseError3 { - constructor() { - super('Cannot decode zero data ("0x") with ABI parameters.'); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.ZeroDataError" - }); +function decodeString2(cursor, { staticPosition }) { + const offset = toNumber2(cursor.readBytes(32)); + const start = staticPosition + offset; + cursor.setPosition(start); + const length = toNumber2(cursor.readBytes(32)); + if (length === 0) { + cursor.setPosition(staticPosition + 32); + return ["", 32]; } + const data = cursor.readBytes(length, 32); + const value = toString(trimLeft(data)); + cursor.setPosition(staticPosition + 32); + return [value, 32]; } - -class ArrayLengthMismatchError extends BaseError3 { - constructor({ expectedLength, givenLength, type }) { - super(`Array length mismatch for type \`${type}\`. Expected: \`${expectedLength}\`. Given: \`${givenLength}\`.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.ArrayLengthMismatchError" - }); +function prepareParameters({ checksumAddress: checksumAddress2, parameters, values }) { + const preparedParameters = []; + for (let i = 0;i < parameters.length; i++) { + preparedParameters.push(prepareParameter({ + checksumAddress: checksumAddress2, + parameter: parameters[i], + value: values[i] + })); } + return preparedParameters; } - -class BytesSizeMismatchError2 extends BaseError3 { - constructor({ expectedSize, value }) { - super(`Size of bytes "${value}" (bytes${size3(value)}) does not match expected size (bytes${expectedSize}).`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.BytesSizeMismatchError" +function prepareParameter({ checksumAddress: checksumAddress2 = false, parameter: parameter_, value }) { + const parameter = parameter_; + const arrayComponents = getArrayComponents2(parameter.type); + if (arrayComponents) { + const [length, type] = arrayComponents; + return encodeArray2(value, { + checksumAddress: checksumAddress2, + length, + parameter: { + ...parameter, + type + } }); } -} - -class LengthMismatchError extends BaseError3 { - constructor({ expectedLength, givenLength }) { - super([ - "ABI encoding parameters/values length mismatch.", - `Expected length (parameters): ${expectedLength}`, - `Given length (values): ${givenLength}` - ].join(` -`)); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.LengthMismatchError" + if (parameter.type === "tuple") { + return encodeTuple2(value, { + checksumAddress: checksumAddress2, + parameter }); } -} - -class InvalidArrayError2 extends BaseError3 { - constructor(value) { - super(`Value \`${value}\` is not a valid array.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.InvalidArrayError" + if (parameter.type === "address") { + return encodeAddress2(value, { + checksum: checksumAddress2 }); } -} - -class InvalidTypeError extends BaseError3 { - constructor(type) { - super(`Type \`${type}\` is not a valid ABI Type.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "AbiParameters.InvalidTypeError" + if (parameter.type === "bool") { + return encodeBoolean(value); + } + if (parameter.type.startsWith("uint") || parameter.type.startsWith("int")) { + const signed = parameter.type.startsWith("int"); + const [, , size6 = "256"] = integerRegex4.exec(parameter.type) ?? []; + return encodeNumber2(value, { + signed, + size: Number(size6) }); } + if (parameter.type.startsWith("bytes")) { + return encodeBytes2(value, { type: parameter.type }); + } + if (parameter.type === "string") { + return encodeString2(value); + } + throw new InvalidTypeError(parameter.type); } - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Authorization.js -init_Hex(); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Rlp.js -init_Bytes(); -init_Errors(); -init_Hex(); -function from7(value, options) { - const { as } = options; - const encodable = getEncodable2(value); - const cursor = create(new Uint8Array(encodable.length)); - encodable.encode(cursor); - if (as === "Hex") - return fromBytes(cursor.bytes); - return cursor.bytes; -} -function fromHex3(hex, options = {}) { - const { as = "Hex" } = options; - return from7(hex, { as }); +function encode(preparedParameters) { + let staticSize = 0; + for (let i = 0;i < preparedParameters.length; i++) { + const { dynamic, encoded } = preparedParameters[i]; + if (dynamic) + staticSize += 32; + else + staticSize += size4(encoded); + } + const staticParameters = []; + const dynamicParameters = []; + let dynamicSize = 0; + for (let i = 0;i < preparedParameters.length; i++) { + const { dynamic, encoded } = preparedParameters[i]; + if (dynamic) { + staticParameters.push(fromNumber(staticSize + dynamicSize, { size: 32 })); + dynamicParameters.push(encoded); + dynamicSize += size4(encoded); + } else { + staticParameters.push(encoded); + } + } + return concat2(...staticParameters, ...dynamicParameters); } -function getEncodable2(bytes) { - if (Array.isArray(bytes)) - return getEncodableList2(bytes.map((x) => getEncodable2(x))); - return getEncodableBytes2(bytes); -} -function getEncodableList2(list) { - const bodyLength = list.reduce((acc, x) => acc + x.length, 0); - const sizeOfBodyLength = getSizeOfLength2(bodyLength); - const length = (() => { - if (bodyLength <= 55) - return 1 + bodyLength; - return 1 + sizeOfBodyLength + bodyLength; - })(); - return { - length, - encode(cursor) { - if (bodyLength <= 55) { - cursor.pushByte(192 + bodyLength); - } else { - cursor.pushByte(192 + 55 + sizeOfBodyLength); - if (sizeOfBodyLength === 1) - cursor.pushUint8(bodyLength); - else if (sizeOfBodyLength === 2) - cursor.pushUint16(bodyLength); - else if (sizeOfBodyLength === 3) - cursor.pushUint24(bodyLength); - else - cursor.pushUint32(bodyLength); - } - for (const { encode: encode3 } of list) { - encode3(cursor); - } - } - }; -} -function getEncodableBytes2(bytesOrHex) { - const bytes = typeof bytesOrHex === "string" ? fromHex(bytesOrHex) : bytesOrHex; - const sizeOfBytesLength = getSizeOfLength2(bytes.length); - const length = (() => { - if (bytes.length === 1 && bytes[0] < 128) - return 1; - if (bytes.length <= 55) - return 1 + bytes.length; - return 1 + sizeOfBytesLength + bytes.length; - })(); +function encodeAddress2(value, options) { + const { checksum: checksum3 = false } = options; + assert4(value, { strict: checksum3 }); return { - length, - encode(cursor) { - if (bytes.length === 1 && bytes[0] < 128) { - cursor.pushBytes(bytes); - } else if (bytes.length <= 55) { - cursor.pushByte(128 + bytes.length); - cursor.pushBytes(bytes); - } else { - cursor.pushByte(128 + 55 + sizeOfBytesLength); - if (sizeOfBytesLength === 1) - cursor.pushUint8(bytes.length); - else if (sizeOfBytesLength === 2) - cursor.pushUint16(bytes.length); - else if (sizeOfBytesLength === 3) - cursor.pushUint24(bytes.length); - else - cursor.pushUint32(bytes.length); - cursor.pushBytes(bytes); - } - } + dynamic: false, + encoded: padLeft(value.toLowerCase()) }; } -function getSizeOfLength2(length) { - if (length <= 255) - return 1; - if (length <= 65535) - return 2; - if (length <= 16777215) - return 3; - if (length <= 4294967295) - return 4; - throw new BaseError3("Length is too large."); -} - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Signature.js -init_Errors(); -init_Hex(); -function assert5(signature, options = {}) { - const { recovered } = options; - if (typeof signature.r === "undefined") - throw new MissingPropertiesError({ signature }); - if (typeof signature.s === "undefined") - throw new MissingPropertiesError({ signature }); - if (recovered && typeof signature.yParity === "undefined") - throw new MissingPropertiesError({ signature }); - if (signature.r < 0n || signature.r > maxUint2562) - throw new InvalidRError({ value: signature.r }); - if (signature.s < 0n || signature.s > maxUint2562) - throw new InvalidSError({ value: signature.s }); - if (typeof signature.yParity === "number" && signature.yParity !== 0 && signature.yParity !== 1) - throw new InvalidYParityError({ value: signature.yParity }); -} -function fromBytes3(signature) { - return fromHex4(fromBytes(signature)); -} -function fromHex4(signature) { - if (signature.length !== 130 && signature.length !== 132) - throw new InvalidSerializedSizeError2({ signature }); - const r = BigInt(slice3(signature, 0, 32)); - const s = BigInt(slice3(signature, 32, 64)); - const yParity = (() => { - const yParity2 = Number(`0x${signature.slice(130)}`); - if (Number.isNaN(yParity2)) - return; - try { - return vToYParity(yParity2); - } catch { - throw new InvalidYParityError({ value: yParity2 }); +function encodeArray2(value, options) { + const { checksumAddress: checksumAddress2, length, parameter } = options; + const dynamic = length === null; + if (!Array.isArray(value)) + throw new InvalidArrayError2(value); + if (!dynamic && value.length !== length) + throw new ArrayLengthMismatchError({ + expectedLength: length, + givenLength: value.length, + type: `${parameter.type}[${length}]` + }); + let dynamicChild = value.length === 0 && hasDynamicChild2(parameter); + const preparedParameters = []; + for (let i = 0;i < value.length; i++) { + const preparedParam = prepareParameter({ + checksumAddress: checksumAddress2, + parameter, + value: value[i] + }); + if (preparedParam.dynamic) + dynamicChild = true; + preparedParameters.push(preparedParam); + } + if (dynamic || dynamicChild) { + const data = encode(preparedParameters); + if (dynamic) { + const length2 = fromNumber(preparedParameters.length, { size: 32 }); + return { + dynamic: true, + encoded: preparedParameters.length > 0 ? concat2(length2, data) : length2 + }; } - })(); - if (typeof yParity === "undefined") - return { - r, - s - }; + if (dynamicChild) + return { dynamic: true, encoded: data }; + } return { - r, - s, - yParity + dynamic: false, + encoded: concat2(...preparedParameters.map(({ encoded }) => encoded)) }; } -function extract2(value) { - if (typeof value.r === "undefined") - return; - if (typeof value.s === "undefined") - return; - return from8(value); -} -function from8(signature) { - const signature_ = (() => { - if (typeof signature === "string") - return fromHex4(signature); - if (signature instanceof Uint8Array) - return fromBytes3(signature); - if (typeof signature.r === "string") - return fromRpc2(signature); - if (signature.v) - return fromLegacy(signature); +function encodeBytes2(value, { type }) { + const [, parametersize] = type.split("bytes"); + const bytesSize = size4(value); + if (!parametersize) { + let value_ = value; + if (bytesSize % 32 !== 0) + value_ = padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32); return { - r: signature.r, - s: signature.s, - ...typeof signature.yParity !== "undefined" ? { yParity: signature.yParity } : {} + dynamic: true, + encoded: concat2(padLeft(fromNumber(bytesSize, { size: 32 })), value_) }; - })(); - assert5(signature_); - return signature_; + } + if (bytesSize !== Number.parseInt(parametersize, 10)) + throw new BytesSizeMismatchError2({ + expectedSize: Number.parseInt(parametersize, 10), + value + }); + return { dynamic: false, encoded: padRight(value) }; } -function fromLegacy(signature) { +function encodeBoolean(value) { + if (typeof value !== "boolean") + throw new BaseError3(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); + return { dynamic: false, encoded: padLeft(fromBoolean(value)) }; +} +function encodeNumber2(value, { signed, size: size6 }) { + if (typeof size6 === "number") { + const max = 2n ** (BigInt(size6) - (signed ? 1n : 0n)) - 1n; + const min = signed ? -max - 1n : 0n; + if (value > max || value < min) + throw new IntegerOutOfRangeError2({ + max: max.toString(), + min: min.toString(), + signed, + size: size6 / 8, + value: value.toString() + }); + } return { - r: signature.r, - s: signature.s, - yParity: vToYParity(signature.v) + dynamic: false, + encoded: fromNumber(value, { + size: 32, + signed + }) }; } -function fromRpc2(signature) { - const yParity = (() => { - const v = signature.v ? Number(signature.v) : undefined; - let yParity2 = signature.yParity ? Number(signature.yParity) : undefined; - if (typeof v === "number" && typeof yParity2 !== "number") - yParity2 = vToYParity(v); - if (typeof yParity2 !== "number") - throw new InvalidYParityError({ value: signature.yParity }); - return yParity2; - })(); +function encodeString2(value) { + const hexValue = fromString2(value); + const partsLength = Math.ceil(size4(hexValue) / 32); + const parts = []; + for (let i = 0;i < partsLength; i++) { + parts.push(padRight(slice3(hexValue, i * 32, (i + 1) * 32))); + } return { - r: BigInt(signature.r), - s: BigInt(signature.s), - yParity + dynamic: true, + encoded: concat2(padRight(fromNumber(size4(hexValue), { size: 32 })), ...parts) }; } -function toHex3(signature) { - assert5(signature); - const r = signature.r; - const s = signature.s; - const signature_ = concat2(fromNumber(r, { size: 32 }), fromNumber(s, { size: 32 }), typeof signature.yParity === "number" ? fromNumber(yParityToV(signature.yParity), { size: 1 }) : "0x"); - return signature_; +function encodeTuple2(value, options) { + const { checksumAddress: checksumAddress2, parameter } = options; + let dynamic = false; + const preparedParameters = []; + for (let i = 0;i < parameter.components.length; i++) { + const param_ = parameter.components[i]; + const index2 = Array.isArray(value) ? i : param_.name; + const preparedParam = prepareParameter({ + checksumAddress: checksumAddress2, + parameter: param_, + value: value[index2] + }); + preparedParameters.push(preparedParam); + if (preparedParam.dynamic) + dynamic = true; + } + return { + dynamic, + encoded: dynamic ? encode(preparedParameters) : concat2(...preparedParameters.map(({ encoded }) => encoded)) + }; } -function toTuple(signature) { - const { r, s, yParity } = signature; - return [ - yParity ? "0x01" : "0x", - r === 0n ? "0x" : trimLeft2(fromNumber(r)), - s === 0n ? "0x" : trimLeft2(fromNumber(s)) - ]; -} -function vToYParity(v) { - if (v === 0 || v === 27) - return 0; - if (v === 1 || v === 28) - return 1; - if (v >= 35) - return v % 2 === 0 ? 1 : 0; - throw new InvalidVError({ value: v }); -} -function yParityToV(yParity) { - if (yParity === 0) - return 27; - if (yParity === 1) - return 28; - throw new InvalidYParityError({ value: yParity }); +function getArrayComponents2(type) { + const matches = type.match(/^(.*)\[(\d+)?\]$/); + return matches ? [matches[2] ? Number(matches[2]) : null, matches[1]] : undefined; } - -class InvalidSerializedSizeError2 extends BaseError3 { - constructor({ signature }) { - super(`Value \`${signature}\` is an invalid signature size.`, { - metaMessages: [ - "Expected: 64 bytes or 65 bytes.", - `Received ${size3(from3(signature))} bytes.` - ] - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Signature.InvalidSerializedSizeError" - }); - } +function hasDynamicChild2(param) { + const { type } = param; + if (type === "string") + return true; + if (type === "bytes") + return true; + if (type.endsWith("[]")) + return true; + if (type === "tuple") + return param.components?.some(hasDynamicChild2); + const arrayComponents = getArrayComponents2(param.type); + if (arrayComponents && hasDynamicChild2({ + ...param, + type: arrayComponents[1] + })) + return true; + return false; } -class MissingPropertiesError extends BaseError3 { - constructor({ signature }) { - super(`Signature \`${stringify2(signature)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Signature.MissingPropertiesError" - }); +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/cursor.js +init_Errors(); +var staticCursor2 = { + bytes: new Uint8Array, + dataView: new DataView(new ArrayBuffer(0)), + position: 0, + positionReadCount: new Map, + recursiveReadCount: 0, + recursiveReadLimit: Number.POSITIVE_INFINITY, + assertReadLimit() { + if (this.recursiveReadCount >= this.recursiveReadLimit) + throw new RecursiveReadLimitExceededError2({ + count: this.recursiveReadCount + 1, + limit: this.recursiveReadLimit + }); + }, + assertPosition(position) { + if (position < 0 || position > this.bytes.length - 1) + throw new PositionOutOfBoundsError2({ + length: this.bytes.length, + position + }); + }, + decrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError2({ offset }); + const position = this.position - offset; + this.assertPosition(position); + this.position = position; + }, + getReadCount(position) { + return this.positionReadCount.get(position || this.position) || 0; + }, + incrementPosition(offset) { + if (offset < 0) + throw new NegativeOffsetError2({ offset }); + const position = this.position + offset; + this.assertPosition(position); + this.position = position; + }, + inspectByte(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectBytes(length, position_) { + const position = position_ ?? this.position; + this.assertPosition(position + length - 1); + return this.bytes.subarray(position, position + length); + }, + inspectUint8(position_) { + const position = position_ ?? this.position; + this.assertPosition(position); + return this.bytes[position]; + }, + inspectUint16(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 1); + return this.dataView.getUint16(position); + }, + inspectUint24(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 2); + return (this.dataView.getUint16(position) << 8) + this.dataView.getUint8(position + 2); + }, + inspectUint32(position_) { + const position = position_ ?? this.position; + this.assertPosition(position + 3); + return this.dataView.getUint32(position); + }, + pushByte(byte) { + this.assertPosition(this.position); + this.bytes[this.position] = byte; + this.position++; + }, + pushBytes(bytes) { + this.assertPosition(this.position + bytes.length - 1); + this.bytes.set(bytes, this.position); + this.position += bytes.length; + }, + pushUint8(value) { + this.assertPosition(this.position); + this.bytes[this.position] = value; + this.position++; + }, + pushUint16(value) { + this.assertPosition(this.position + 1); + this.dataView.setUint16(this.position, value); + this.position += 2; + }, + pushUint24(value) { + this.assertPosition(this.position + 2); + this.dataView.setUint16(this.position, value >> 8); + this.dataView.setUint8(this.position + 2, value & ~4294967040); + this.position += 3; + }, + pushUint32(value) { + this.assertPosition(this.position + 3); + this.dataView.setUint32(this.position, value); + this.position += 4; + }, + readByte() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectByte(); + this.position++; + return value; + }, + readBytes(length, size6) { + this.assertReadLimit(); + this._touch(); + const value = this.inspectBytes(length); + this.position += size6 ?? length; + return value; + }, + readUint8() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint8(); + this.position += 1; + return value; + }, + readUint16() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint16(); + this.position += 2; + return value; + }, + readUint24() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint24(); + this.position += 3; + return value; + }, + readUint32() { + this.assertReadLimit(); + this._touch(); + const value = this.inspectUint32(); + this.position += 4; + return value; + }, + get remaining() { + return this.bytes.length - this.position; + }, + setPosition(position) { + const oldPosition = this.position; + this.assertPosition(position); + this.position = position; + return () => this.position = oldPosition; + }, + _touch() { + if (this.recursiveReadLimit === Number.POSITIVE_INFINITY) + return; + const count = this.getReadCount(); + this.positionReadCount.set(this.position, count + 1); + if (count > 0) + this.recursiveReadCount++; } +}; +function create(bytes, { recursiveReadLimit = 8192 } = {}) { + const cursor = Object.create(staticCursor2); + cursor.bytes = bytes; + cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + cursor.positionReadCount = new Map; + cursor.recursiveReadLimit = recursiveReadLimit; + return cursor; } -class InvalidRError extends BaseError3 { - constructor({ value }) { - super(`Value \`${value}\` is an invalid r value. r must be a positive integer less than 2^256.`); +class NegativeOffsetError2 extends BaseError3 { + constructor({ offset }) { + super(`Offset \`${offset}\` cannot be negative.`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: "Signature.InvalidRError" + value: "Cursor.NegativeOffsetError" }); } } -class InvalidSError extends BaseError3 { - constructor({ value }) { - super(`Value \`${value}\` is an invalid s value. s must be a positive integer less than 2^256.`); +class PositionOutOfBoundsError2 extends BaseError3 { + constructor({ length, position }) { + super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: "Signature.InvalidSError" + value: "Cursor.PositionOutOfBoundsError" }); } } -class InvalidYParityError extends BaseError3 { - constructor({ value }) { - super(`Value \`${value}\` is an invalid y-parity value. Y-parity must be 0 or 1.`); +class RecursiveReadLimitExceededError2 extends BaseError3 { + constructor({ count, limit }) { + super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: "Signature.InvalidYParityError" + value: "Cursor.RecursiveReadLimitExceededError" }); } } -class InvalidVError extends BaseError3 { - constructor({ value }) { - super(`Value \`${value}\` is an invalid v value. v must be 27, 28 or >=35.`); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Signature.InvalidVError" +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiParameters.js +function decode(parameters, data, options = {}) { + const { as = "Array", checksumAddress: checksumAddress2 = false } = options; + const bytes = typeof data === "string" ? fromHex(data) : data; + const cursor = create(bytes); + if (size3(bytes) === 0 && parameters.length > 0) + throw new ZeroDataError; + if (size3(bytes) && size3(bytes) < 32) + throw new DataSizeTooSmallError({ + data: typeof data === "string" ? data : fromBytes(data), + parameters, + size: size3(bytes) }); + let consumed = 0; + const values = as === "Array" ? [] : {}; + for (let i = 0;i < parameters.length; ++i) { + const param = parameters[i]; + if (consumed < bytes.length) + cursor.setPosition(consumed); + const [data2, consumed_] = decodeParameter2(cursor, param, { + checksumAddress: checksumAddress2, + staticPosition: 0 + }); + consumed += consumed_; + if (as === "Array") + values.push(data2); + else + values[param.name ?? i] = data2; } + return values; } - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Authorization.js -function from9(authorization, options = {}) { - if (typeof authorization.chainId === "string") - return fromRpc3(authorization); - return { ...authorization, ...options.signature }; -} -function fromRpc3(authorization) { - const { address, chainId, nonce } = authorization; - const signature = extract2(authorization); - return { - address, - chainId: Number(chainId), - nonce: BigInt(nonce), - ...signature - }; -} -function getSignPayload(authorization) { - return hash2(authorization, { presign: true }); -} -function hash2(authorization, options = {}) { - const { presign } = options; - return keccak2562(concat2("0x05", fromHex3(toTuple2(presign ? { - address: authorization.address, - chainId: authorization.chainId, - nonce: authorization.nonce - } : authorization)))); -} -function toTuple2(authorization) { - const { address, chainId, nonce } = authorization; - const signature = extract2(authorization); - return [ - chainId ? fromNumber(chainId) : "0x", - address, - nonce ? fromNumber(nonce) : "0x", - ...signature ? toTuple(signature) : [] - ]; -} - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/erc8010/SignatureErc8010.js -init_Errors(); -init_Hex(); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Secp256k1.js -init_secp256k1(); -init_Hex(); - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/entropy.js -var extraEntropy = false; - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Secp256k1.js -function recoverAddress2(options) { - return fromPublicKey(recoverPublicKey2(options)); -} -function recoverPublicKey2(options) { - const { payload, signature } = options; - const { r, s, yParity } = signature; - const signature_ = new secp256k1.Signature(BigInt(r), BigInt(s)).addRecoveryBit(yParity); - const point = signature_.recoverPublicKey(from3(payload).substring(2)); - return from4(point); -} - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/erc8010/SignatureErc8010.js -var magicBytes = "0x8010801080108010801080108010801080108010801080108010801080108010"; -var suffixParameters = from6("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data"); -function assert6(value) { - if (typeof value === "string") { - if (slice3(value, -32) !== magicBytes) - throw new InvalidWrappedSignatureError(value); - } else - assert5(value.authorization); -} -function from10(value) { - if (typeof value === "string") - return unwrap(value); - return value; -} -function unwrap(wrapped) { - assert6(wrapped); - const suffixLength = toNumber(slice3(wrapped, -64, -32)); - const suffix = slice3(wrapped, -suffixLength - 64, -64); - const signature = slice3(wrapped, 0, -suffixLength - 64); - const [auth, to, data] = decode(suffixParameters, suffix); - const authorization = from9({ - address: auth.delegation, - chainId: Number(auth.chainId), - nonce: auth.nonce, - yParity: auth.yParity, - r: auth.r, - s: auth.s +function encode2(parameters, values, options) { + const { checksumAddress: checksumAddress2 = false } = options ?? {}; + if (parameters.length !== values.length) + throw new LengthMismatchError({ + expectedLength: parameters.length, + givenLength: values.length + }); + const preparedParameters = prepareParameters({ + checksumAddress: checksumAddress2, + parameters, + values }); - return { - authorization, - signature, - ...data && data !== "0x" ? { data, to } : {} - }; + const data = encode(preparedParameters); + if (data.length === 0) + return "0x"; + return data; } -function wrap(value) { - const { data, signature } = value; - assert6(value); - const self = recoverAddress2({ - payload: getSignPayload(value.authorization), - signature: from8(value.authorization) - }); - const suffix = encode2(suffixParameters, [ - { - ...value.authorization, - delegation: value.authorization.address, - chainId: BigInt(value.authorization.chainId) - }, - value.to ?? self, - data ?? "0x" - ]); - const suffixLength = fromNumber(size3(suffix), { size: 32 }); - return concat2(signature, suffix, suffixLength, magicBytes); +function encodePacked2(types, values) { + if (types.length !== values.length) + throw new LengthMismatchError({ + expectedLength: types.length, + givenLength: values.length + }); + const data = []; + for (let i = 0;i < types.length; i++) { + const type = types[i]; + const value = values[i]; + data.push(encodePacked2.encode(type, value)); + } + return concat2(...data); } -function validate4(value) { - try { - assert6(value); - return true; - } catch { - return false; +(function(encodePacked3) { + function encode3(type, value, isArray = false) { + if (type === "address") { + const address = value; + assert4(address); + return padLeft(address.toLowerCase(), isArray ? 32 : 0); + } + if (type === "string") + return fromString2(value); + if (type === "bytes") + return value; + if (type === "bool") + return padLeft(fromBoolean(value), isArray ? 32 : 1); + const intMatch = type.match(integerRegex4); + if (intMatch) { + const [_type, baseType, bits = "256"] = intMatch; + const size6 = Number.parseInt(bits, 10) / 8; + return fromNumber(value, { + size: isArray ? 32 : size6, + signed: baseType === "int" + }); + } + const bytesMatch = type.match(bytesRegex4); + if (bytesMatch) { + const [_type, size6] = bytesMatch; + if (Number.parseInt(size6, 10) !== (value.length - 2) / 2) + throw new BytesSizeMismatchError2({ + expectedSize: Number.parseInt(size6, 10), + value + }); + return padRight(value, isArray ? 32 : 0); + } + const arrayMatch = type.match(arrayRegex2); + if (arrayMatch && Array.isArray(value)) { + const [_type, childType] = arrayMatch; + const data = []; + for (let i = 0;i < value.length; i++) { + data.push(encode3(childType, value[i], true)); + } + if (data.length === 0) + return "0x"; + return concat2(...data); + } + throw new InvalidTypeError(type); } + encodePacked3.encode = encode3; +})(encodePacked2 || (encodePacked2 = {})); +function from7(parameters) { + if (Array.isArray(parameters) && typeof parameters[0] === "string") + return parseAbiParameters(parameters); + if (typeof parameters === "string") + return parseAbiParameters(parameters); + return parameters; } -class InvalidWrappedSignatureError extends BaseError3 { - constructor(wrapped) { - super(`Value \`${wrapped}\` is an invalid ERC-8010 wrapped signature.`); +class DataSizeTooSmallError extends BaseError3 { + constructor({ data, parameters, size: size6 }) { + super(`Data size of ${size6} bytes is too small for given parameters.`, { + metaMessages: [ + `Params: (${formatAbiParameters(parameters)})`, + `Data: ${data} (${size6} bytes)` + ] + }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: "SignatureErc8010.InvalidWrappedSignatureError" + value: "AbiParameters.DataSizeTooSmallError" }); } } -// ../viem/src/_esm/utils/signature/serializeErc6492Signature.js -init_encodeAbiParameters(); -init_toBytes(); -function serializeErc6492Signature(parameters) { - const { address, data, signature, to = "hex" } = parameters; - const signature_ = concatHex([ - encodeAbiParameters([{ type: "address" }, { type: "bytes" }, { type: "bytes" }], [address, data, signature]), - erc6492MagicBytes - ]); - if (to === "hex") - return signature_; - return hexToBytes(signature_); -} - -// ../viem/src/_esm/utils/index.js -init_formatGwei(); -// ../viem/src/_esm/utils/unit/formatUnits.js -init_Value(); -function formatUnits(value, decimals) { - return format(value, decimals); +class ZeroDataError extends BaseError3 { + constructor() { + super('Cannot decode zero data ("0x") with ABI parameters.'); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.ZeroDataError" + }); + } } -// ../viem/src/_esm/utils/unit/parseEther.js -init_Value(); -function parseEther(ether, unit = "wei") { - return fromEther(ether, unit); +class ArrayLengthMismatchError extends BaseError3 { + constructor({ expectedLength, givenLength, type }) { + super(`Array length mismatch for type \`${type}\`. Expected: \`${expectedLength}\`. Given: \`${givenLength}\`.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.ArrayLengthMismatchError" + }); + } } -// ../viem/src/_esm/utils/unit/parseUnits.js -init_Value(); -function parseUnits(value, decimals) { - return from(value, decimals); +class BytesSizeMismatchError2 extends BaseError3 { + constructor({ expectedSize, value }) { + super(`Size of bytes "${value}" (bytes${size4(value)}) does not match expected size (bytes${expectedSize}).`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.BytesSizeMismatchError" + }); + } } -// ../viem/src/_esm/utils/formatters/proof.js -function formatStorageProof(storageProof) { - return storageProof.map((proof) => ({ - ...proof, - value: BigInt(proof.value) - })); -} -function formatProof(proof) { - return { - ...proof, - balance: proof.balance ? BigInt(proof.balance) : undefined, - nonce: proof.nonce ? hexToNumber(proof.nonce) : undefined, - storageProof: proof.storageProof ? formatStorageProof(proof.storageProof) : undefined - }; -} - -// ../viem/src/_esm/actions/public/getProof.js -async function getProof(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical, storageKeys }) { - const block = formatBlockParameter({ - blockHash, - blockNumber, - blockTag, - requireCanonical - }); - const proof = await client.request({ - method: "eth_getProof", - params: [address, storageKeys, block] - }); - return formatProof(proof); -} - -// ../viem/src/_esm/actions/public/getRawTransaction.js -init_transaction(); -async function getRawTransaction(client, { hash: hash3 }) { - const rawTransaction = await client.request({ - method: "eth_getRawTransactionByHash", - params: [hash3] - }, { dedupe: true }); - if (!rawTransaction) - throw new TransactionNotFoundError({ hash: hash3 }); - return rawTransaction; +class LengthMismatchError extends BaseError3 { + constructor({ expectedLength, givenLength }) { + super([ + "ABI encoding parameters/values length mismatch.", + `Expected length (parameters): ${expectedLength}`, + `Given length (values): ${givenLength}` + ].join(` +`)); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.LengthMismatchError" + }); + } } -// ../viem/src/_esm/actions/public/getStorageAt.js -init_formatBlockParameter(); -async function getStorageAt(client, { address, blockHash, blockNumber, blockTag = "latest", requireCanonical, slot }) { - const block = formatBlockParameter({ - blockHash, - blockNumber, - blockTag, - requireCanonical - }); - const data = await client.request({ - method: "eth_getStorageAt", - params: [address, slot, block] - }); - return data; +class InvalidArrayError2 extends BaseError3 { + constructor(value) { + super(`Value \`${value}\` is not a valid array.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.InvalidArrayError" + }); + } } -// ../viem/src/_esm/actions/public/getTransaction.js -init_transaction(); -init_toHex(); -async function getTransaction(client, { blockHash, blockNumber, blockTag: blockTag_, hash: hash3, index: index2, sender, nonce }) { - const blockTag = blockTag_ || "latest"; - const blockNumberHex = blockNumber !== undefined ? numberToHex(blockNumber) : undefined; - let transaction = null; - if (hash3) { - transaction = await client.request({ - method: "eth_getTransactionByHash", - params: [hash3] - }, { dedupe: true }); - } else if (blockHash) { - transaction = await client.request({ - method: "eth_getTransactionByBlockHashAndIndex", - params: [blockHash, numberToHex(index2)] - }, { dedupe: true }); - } else if ((blockNumberHex || blockTag) && typeof index2 === "number") { - transaction = await client.request({ - method: "eth_getTransactionByBlockNumberAndIndex", - params: [blockNumberHex || blockTag, numberToHex(index2)] - }, { dedupe: Boolean(blockNumberHex) }); - } else if (sender && typeof nonce === "number") { - transaction = await client.request({ - method: "eth_getTransactionBySenderAndNonce", - params: [sender, numberToHex(nonce)] - }, { dedupe: true }); - } - if (!transaction) - throw new TransactionNotFoundError({ - blockHash, - blockNumber, - blockTag, - hash: hash3, - index: index2 +class InvalidTypeError extends BaseError3 { + constructor(type) { + super(`Type \`${type}\` is not a valid ABI Type.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "AbiParameters.InvalidTypeError" }); - if (transaction.type === "0x79") { - const raw = transaction; - const body = raw.tx ?? {}; - transaction = { - hash: hash3 ?? undefined, - type: "0x79", - blockHash: raw.blockHash, - blockNumber: raw.blockNumber, - blockTimestamp: raw.blockTimestamp, - transactionIndex: raw.transactionIndex, - gasPrice: raw.gasPrice, - from: raw.from ?? body.sender, - chainId: body.chainId != null ? numberToHex(body.chainId) : undefined, - gas: body.gasLimit != null ? numberToHex(body.gasLimit) : undefined, - maxFeePerGas: body.maxFeePerGas, - maxPriorityFeePerGas: body.maxPriorityFeePerGas, - nonce: body.nonceSequence != null ? numberToHex(body.nonceSequence) : undefined, - to: null, - value: "0x0", - input: "0x", - nonceKey: body.nonceKey, - expiry: body.expiry, - calls: body.calls, - accountChanges: body.accountChanges, - metadata: body.metadata, - payer: body.payer ?? null, - senderAuth: raw.senderAuth, - payerAuth: raw.payerAuth - }; } - const format2 = client.chain?.formatters?.transaction?.format || formatTransaction; - return format2(transaction, "getTransaction"); } -// ../viem/src/_esm/actions/public/getTransactionConfirmations.js -async function getTransactionConfirmations(client, { hash: hash3, transactionReceipt }) { - const [blockNumber, transaction] = await Promise.all([ - getAction(client, getBlockNumber, "getBlockNumber")({}), - hash3 ? getAction(client, getTransaction, "getTransaction")({ hash: hash3 }) : undefined - ]); - const transactionBlockNumber = transactionReceipt?.blockNumber || transaction?.blockNumber; - if (!transactionBlockNumber) - return 0n; - return blockNumber - transactionBlockNumber + 1n; +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiConstructor.js +init_Hex(); +function encode3(...parameters) { + const [abiConstructor, options] = (() => { + if (Array.isArray(parameters[0])) { + const [abi2, options2] = parameters; + return [fromAbi2(abi2), options2]; + } + return parameters; + })(); + const { bytecode, args } = options; + return concat2(bytecode, abiConstructor.inputs?.length && args?.length ? encode2(abiConstructor.inputs, args) : "0x"); +} +function from8(abiConstructor) { + return from6(abiConstructor); +} +function fromAbi2(abi2) { + const item = abi2.find((item2) => item2.type === "constructor"); + if (!item) + throw new NotFoundError({ name: "constructor" }); + return item; } -// ../viem/src/_esm/actions/public/getTransactionReceipt.js -init_transaction(); -async function getTransactionReceipt(client, { hash: hash3 }) { - const receipt = await client.request({ - method: "eth_getTransactionReceipt", - params: [hash3] - }, { dedupe: true }); - if (!receipt) - throw new TransactionReceiptNotFoundError({ hash: hash3 }); - const format2 = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt; - return format2(receipt, "getTransactionReceipt"); +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiFunction.js +init_Hex(); +function encodeData(...parameters) { + const [abiFunction, args = []] = (() => { + if (Array.isArray(parameters[0])) { + const [abi2, name, args3] = parameters; + return [fromAbi3(abi2, name, { args: args3 }), args3]; + } + const [abiFunction2, args2] = parameters; + return [abiFunction2, args2]; + })(); + const { overloads } = abiFunction; + const item = overloads ? fromAbi3([abiFunction, ...overloads], abiFunction.name, { + args + }) : abiFunction; + const selector = getSelector2(item); + const data = args.length > 0 ? encode2(item.inputs, args) : undefined; + return data ? concat2(selector, data) : selector; +} +function from9(abiFunction, options = {}) { + return from6(abiFunction, options); +} +function fromAbi3(abi2, name, options) { + const item = fromAbi(abi2, name, options); + if (item.type !== "function") + throw new NotFoundError({ name, type: "function" }); + return item; +} +function getSelector2(abiItem) { + return getSelector(abiItem); } +// ../viem/src/_esm/constants/address.js +var ethAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; +var zeroAddress = "0x0000000000000000000000000000000000000000"; -// ../viem/src/_esm/actions/public/multicall.js -init_abis(); -init_abi(); +// ../viem/src/_esm/actions/public/simulateCalls.js init_base(); -init_contract(); -init_decodeFunctionResult(); init_encodeFunctionData(); -init_getChainContractAddress(); -init_createBatchScheduler(); -async function multicall(client, parameters) { - const { account, authorizationList, allowFailure = true, blockHash, blockNumber, blockOverrides, blockTag, requireCanonical, stateOverride } = parameters; - const contracts = parameters.contracts; - const batch = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; - const batchSize = parameters.batchSize ?? batch.batchSize ?? 1024; - const deployless = parameters.deployless ?? batch.deployless ?? false; - const multicallAddress = (() => { - if (parameters.multicallAddress) - return parameters.multicallAddress; - if (deployless) - return null; - if (client.chain) { - return getChainContractAddress({ - blockNumber, - chain: client.chain, - contract: "multicall3" - }); - } - throw new Error("client chain not configured. multicallAddress is required."); - })(); - const chunkedCalls = [[]]; - let currentChunk = 0; - let currentChunkSize = 0; - for (let i = 0;i < contracts.length; i++) { - const { abi: abi2, address, args, functionName } = contracts[i]; - try { - const callData = encodeFunctionData({ abi: abi2, args, functionName }); - currentChunkSize += (callData.length - 2) / 2; - if (batchSize > 0 && currentChunkSize > batchSize && chunkedCalls[currentChunk].length > 0) { - currentChunk++; - currentChunkSize = (callData.length - 2) / 2; - chunkedCalls[currentChunk] = []; - } - chunkedCalls[currentChunk] = [ - ...chunkedCalls[currentChunk], +var getBalanceCode = "0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033"; +async function simulateCalls(client, parameters) { + const { blockNumber, blockTag, calls, stateOverrides, traceAssetChanges, traceTransfers, validation } = parameters; + const account = parameters.account ? parseAccount(parameters.account) : undefined; + if (traceAssetChanges && !account) + throw new BaseError2("`account` is required when `traceAssetChanges` is true"); + const getBalanceData = account ? encode3(from8("constructor(bytes, bytes)"), { + bytecode: deploylessCallViaBytecodeBytecode, + args: [ + getBalanceCode, + encodeData(from9("function getBalance(address)"), [account.address]) + ] + }) : undefined; + const assetAddresses = traceAssetChanges ? await Promise.all(parameters.calls.map(async (call2) => { + if (!call2.data && !call2.abi) + return; + const { accessList } = await createAccessList(client, { + account: account.address, + ...call2, + data: call2.abi ? encodeFunctionData(call2) : call2.data + }); + return accessList.map(({ address, storageKeys }) => storageKeys.length > 0 ? address : null); + })).then((x) => x.flat().filter(Boolean)) : []; + const blocks = await simulateBlocks(client, { + blockNumber, + blockTag, + blocks: [ + ...traceAssetChanges ? [ { - allowFailure: true, - callData, - target: address + calls: [{ data: getBalanceData }], + stateOverrides + }, + { + calls: assetAddresses.map((address, i) => ({ + abi: [ + from9("function balanceOf(address) returns (uint256)") + ], + functionName: "balanceOf", + args: [account.address], + to: address, + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] } - ]; - } catch (err) { - const error = getContractError(err, { - abi: abi2, - address, - args, - docsPath: "/docs/contract/multicall", - functionName, - sender: account - }); - if (!allowFailure) - throw error; - chunkedCalls[currentChunk] = [ - ...chunkedCalls[currentChunk], + ] : [], + { + calls: [...calls, { to: zeroAddress }].map((call2) => ({ + ...call2, + from: account?.address + })), + stateOverrides + }, + ...traceAssetChanges ? [ { - allowFailure: true, - callData: "0x", - target: address + calls: [{ data: getBalanceData }] + }, + { + calls: assetAddresses.map((address, i) => ({ + abi: [ + from9("function balanceOf(address) returns (uint256)") + ], + functionName: "balanceOf", + args: [account.address], + to: address, + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + }, + { + calls: assetAddresses.map((address, i) => ({ + to: address, + abi: [ + from9("function decimals() returns (uint256)") + ], + functionName: "decimals", + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + }, + { + calls: assetAddresses.map((address, i) => ({ + to: address, + abi: [ + from9("function tokenURI(uint256) returns (string)") + ], + functionName: "tokenURI", + args: [0n], + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] + }, + { + calls: assetAddresses.map((address, i) => ({ + to: address, + abi: [from9("function symbol() returns (string)")], + functionName: "symbol", + from: zeroAddress, + nonce: i + })), + stateOverrides: [ + { + address: zeroAddress, + nonce: 0 + } + ] } - ]; - } + ] : [] + ], + traceTransfers, + validation + }); + const block_results = traceAssetChanges ? blocks[2] : blocks[0]; + const [block_ethPre, block_assetsPre, , block_ethPost, block_assetsPost, block_decimals, block_tokenURI, block_symbols] = traceAssetChanges ? blocks : []; + const { calls: block_calls, ...block } = block_results; + const results = block_calls.slice(0, -1) ?? []; + const ethPre = block_ethPre?.calls ?? []; + const assetsPre = block_assetsPre?.calls ?? []; + const balancesPre = [...ethPre, ...assetsPre].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); + const ethPost = block_ethPost?.calls ?? []; + const assetsPost = block_assetsPost?.calls ?? []; + const balancesPost = [...ethPost, ...assetsPost].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); + const decimals = (block_decimals?.calls ?? []).map((x) => x.status === "success" ? x.result : null); + const symbols = (block_symbols?.calls ?? []).map((x) => x.status === "success" ? x.result : null); + const tokenURI = (block_tokenURI?.calls ?? []).map((x) => x.status === "success" ? x.result : null); + const changes = []; + for (const [i, balancePost] of balancesPost.entries()) { + const balancePre = balancesPre[i]; + if (typeof balancePost !== "bigint") + continue; + if (typeof balancePre !== "bigint") + continue; + const decimals_ = decimals[i - 1]; + const symbol_ = symbols[i - 1]; + const tokenURI_ = tokenURI[i - 1]; + const token = (() => { + if (i === 0) + return { + address: ethAddress, + decimals: 18, + symbol: "ETH" + }; + return { + address: assetAddresses[i - 1], + decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : undefined, + symbol: symbol_ ?? undefined + }; + })(); + if (changes.some((change) => change.token.address === token.address)) + continue; + changes.push({ + token, + value: { + pre: balancePre, + post: balancePost, + diff: balancePost - balancePre + } + }); } - const batching = Boolean(client.batch?.multicall); - const batches = batching ? chunkedCalls.flatMap((calls) => calls.map((call2) => [call2])) : chunkedCalls; - const aggregate3Results = await Promise.allSettled(batches.map((calls) => { - if (batching) - return scheduleMulticall2(client, { - account, - authorizationList, - batchSize, - blockHash, - blockNumber, - blockOverrides, - blockTag, - call: calls[0], - multicallAddress, - requireCanonical, - stateOverride - }).then((result) => [result]); - return getAction(client, readContract, "readContract")({ - ...multicallAddress === null ? { code: multicall3Bytecode } : { address: multicallAddress }, - abi: multicall3Abi, - account, - args: [calls], - authorizationList, - blockHash, - blockNumber, - blockOverrides, - blockTag, - functionName: "aggregate3", - requireCanonical, - stateOverride + return { + assetChanges: changes, + block, + results + }; +} + +// ../viem/src/_esm/actions/public/simulateContract.js +init_decodeFunctionResult(); +init_encodeFunctionData(); +init_call(); +async function simulateContract(client, parameters) { + const { abi: abi2, address, args, functionName, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, ...callRequest } = parameters; + const account = callRequest.account ? parseAccount(callRequest.account) : client.account; + const calldata = encodeFunctionData({ abi: abi2, args, functionName }); + try { + const { data } = await getAction(client, call, "call")({ + batch: false, + data: `${calldata}${dataSuffix ? dataSuffix.replace("0x", "") : ""}`, + to: address, + ...callRequest, + account }); - })); - const results = []; - for (let i = 0;i < aggregate3Results.length; i++) { - const result = aggregate3Results[i]; - if (result.status === "rejected") { - if (!allowFailure) - throw result.reason; - for (let j = 0;j < batches[i].length; j++) { - results.push({ - status: "failure", - error: result.reason, - result: undefined - }); - } - continue; - } - const aggregate3Result = result.value; - for (let j = 0;j < aggregate3Result.length; j++) { - const { returnData, success } = aggregate3Result[j]; - const { callData } = batches[i][j]; - const { abi: abi2, address, functionName, args } = contracts[results.length]; - try { - if (callData === "0x") - throw new AbiDecodingZeroDataError; - if (!success) - throw new RawContractError({ data: returnData }); - const result2 = decodeFunctionResult({ - abi: abi2, - args, - data: returnData, - functionName - }); - results.push(allowFailure ? { result: result2, status: "success" } : result2); - } catch (err) { - const error = getContractError(err, { - abi: abi2, - address, - args, - docsPath: "/docs/contract/multicall", - functionName - }); - if (!allowFailure) - throw error; - results.push({ error, result: undefined, status: "failure" }); + const result = decodeFunctionResult({ + abi: abi2, + args, + functionName, + data: data || "0x" + }); + const minimizedAbi = abi2.filter((abiItem) => ("name" in abiItem) && abiItem.name === parameters.functionName); + return { + result, + request: { + abi: minimizedAbi, + address, + args, + dataSuffix, + functionName, + ...callRequest, + account } - } + }; + } catch (error) { + throw getContractError(error, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/simulateContract", + functionName, + sender: account?.address + }); } - if (results.length !== contracts.length) - throw new BaseError2("multicall results mismatch"); - return results; } -async function scheduleMulticall2(client, parameters) { - const { batchSize, call: call2, multicallAddress, ...rest } = parameters; - const { wait: wait2 = 0 } = typeof client.batch?.multicall === "object" ? client.batch.multicall : {}; - const { schedule } = createBatchScheduler({ - id: stringify(["multicall", client.uid, batchSize, multicallAddress, rest]), - wait: wait2, - shouldSplitBatch(calls) { - if (batchSize === 0) - return false; - const size5 = calls.reduce((size6, { callData }) => size6 + (callData.length - 2) / 2, 0); - return size5 > batchSize; - }, - fn: (calls) => getAction(client, readContract, "readContract")({ - ...multicallAddress === null ? { code: multicall3Bytecode } : { address: multicallAddress }, - ...rest, - abi: multicall3Abi, - args: [calls], - functionName: "aggregate3" - }) + +// ../viem/src/_esm/actions/public/uninstallFilter.js +async function uninstallFilter(_client, { filter }) { + return filter.request({ + method: "eth_uninstallFilter", + params: [filter.id] }); - const [result] = await schedule(call2); - return result; } -// ../viem/src/_esm/actions/public/simulateBlocks.js -init_BlockOverrides(); -init_abi(); -init_contract(); -init_node(); -init_decodeFunctionResult(); -init_encodeFunctionData(); -init_toHex(); -init_getNodeError(); -init_transactionRequest(); -init_stateOverride2(); -init_assertRequest(); -async function simulateBlocks(client, parameters) { - const { blockNumber, blockTag = client.experimental_blockTag ?? "latest", blocks, returnFullTransactions, traceTransfers, validation } = parameters; +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/erc6492/SignatureErc6492.js +var exports_SignatureErc6492 = {}; +__export(exports_SignatureErc6492, { + wrap: () => wrap, + validate: () => validate4, + unwrap: () => unwrap, + universalSignatureValidatorBytecode: () => universalSignatureValidatorBytecode, + universalSignatureValidatorAbi: () => universalSignatureValidatorAbi, + magicBytes: () => magicBytes, + from: () => from10, + assert: () => assert5, + InvalidWrappedSignatureError: () => InvalidWrappedSignatureError +}); +init_Errors(); +init_Hex(); +var magicBytes = "0x6492649264926492649264926492649264926492649264926492649264926492"; +var universalSignatureValidatorBytecode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572"; +var universalSignatureValidatorAbi = [ + { + inputs: [ + { + name: "_signer", + type: "address" + }, + { + name: "_hash", + type: "bytes32" + }, + { + name: "_signature", + type: "bytes" + } + ], + stateMutability: "nonpayable", + type: "constructor" + }, + { + inputs: [ + { + name: "_signer", + type: "address" + }, + { + name: "_hash", + type: "bytes32" + }, + { + name: "_signature", + type: "bytes" + } + ], + outputs: [ + { + type: "bool" + } + ], + stateMutability: "nonpayable", + type: "function", + name: "isValidSig" + } +]; +function assert5(wrapped) { + if (slice3(wrapped, -32) !== magicBytes) + throw new InvalidWrappedSignatureError(wrapped); +} +function from10(wrapped) { + if (typeof wrapped === "string") + return unwrap(wrapped); + return wrapped; +} +function unwrap(wrapped) { + assert5(wrapped); + const [to, data, signature] = decode(from7("address, bytes, bytes"), wrapped); + return { data, signature, to }; +} +function wrap(value) { + const { data, signature, to } = value; + return concat2(encode2(from7("address, bytes, bytes"), [ + to, + data, + signature + ]), magicBytes); +} +function validate4(wrapped) { try { - const blockStateCalls = []; - for (const block2 of blocks) { - const blockOverrides = block2.blockOverrides ? toRpc2(block2.blockOverrides) : undefined; - const calls = block2.calls.map((call_) => { - const call2 = call_; - const account = call2.account ? parseAccount(call2.account) : undefined; - const data = call2.abi ? encodeFunctionData(call2) : call2.data; - const request = { - ...call2, - account, - data: call2.dataSuffix ? concat([data || "0x", call2.dataSuffix]) : data, - from: call2.from ?? account?.address - }; - assertRequest(request); - return formatTransactionRequest(request); - }); - const stateOverrides = block2.stateOverrides ? serializeStateOverride(block2.stateOverrides) : undefined; - blockStateCalls.push({ - blockOverrides, - calls, - stateOverrides - }); - } - const blockNumberHex = typeof blockNumber === "bigint" ? numberToHex(blockNumber) : undefined; - const block = blockNumberHex || blockTag; - const result = await client.request({ - method: "eth_simulateV1", - params: [ - { blockStateCalls, returnFullTransactions, traceTransfers, validation }, - block - ] - }); - return result.map((block2, i) => ({ - ...formatBlock(block2), - calls: block2.calls.map((call2, j) => { - const { abi: abi2, args, functionName, to } = blocks[i].calls[j]; - const data = call2.error?.data ?? call2.returnData; - const gasUsed = BigInt(call2.gasUsed); - const logs = call2.logs?.map((log) => formatLog(log)); - const status = call2.status === "0x1" ? "success" : "failure"; - const result2 = abi2 && status === "success" && data !== "0x" ? decodeFunctionResult({ - abi: abi2, - data, - functionName - }) : null; - const error = (() => { - if (status === "success") - return; - let error2; - if (data === "0x") - error2 = new AbiDecodingZeroDataError; - else if (data) - error2 = new RawContractError({ data }); - if (!error2) - return; - return getContractError(error2, { - abi: abi2 ?? [], - address: to ?? "0x", - args, - functionName: functionName ?? "" - }); - })(); - return { - data, - gasUsed, - logs, - status, - ...status === "success" ? { - result: result2 - } : { - error - } - }; - }) - })); - } catch (e) { - const cause = e; - const error = getNodeError(cause, {}); - if (error instanceof UnknownNodeError) - throw cause; - throw error; + assert5(wrapped); + return true; + } catch { + return false; } } -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiItem.js -init_exports(); -init_Errors(); +class InvalidWrappedSignatureError extends BaseError3 { + constructor(wrapped) { + super(`Value \`${wrapped}\` is an invalid ERC-6492 wrapped signature.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "SignatureErc6492.InvalidWrappedSignatureError" + }); + } +} +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/erc8010/SignatureErc8010.js +var exports_SignatureErc8010 = {}; +__export(exports_SignatureErc8010, { + wrap: () => wrap2, + validate: () => validate5, + unwrap: () => unwrap2, + suffixParameters: () => suffixParameters, + magicBytes: () => magicBytes2, + from: () => from14, + assert: () => assert7, + InvalidWrappedSignatureError: () => InvalidWrappedSignatureError2 +}); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Authorization.js init_Hex(); -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/abiItem.js +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Rlp.js +init_Bytes(); init_Errors(); -function normalizeSignature2(signature) { - let active = true; - let current = ""; - let level = 0; - let result = ""; - let valid = false; - for (let i = 0;i < signature.length; i++) { - const char = signature[i]; - if (["(", ")", ","].includes(char)) - active = true; - if (char === "(") - level++; - if (char === ")") - level--; - if (!active) - continue; - if (level === 0) { - if (char === " " && ["event", "function", "error", ""].includes(result)) - result = ""; - else { - result += char; - if (char === ")") { - valid = true; - break; - } +init_Hex(); +function from11(value, options) { + const { as } = options; + const encodable = getEncodable2(value); + const cursor = create(new Uint8Array(encodable.length)); + encodable.encode(cursor); + if (as === "Hex") + return fromBytes(cursor.bytes); + return cursor.bytes; +} +function fromHex4(hex, options = {}) { + const { as = "Hex" } = options; + return from11(hex, { as }); +} +function getEncodable2(bytes) { + if (Array.isArray(bytes)) + return getEncodableList2(bytes.map((x) => getEncodable2(x))); + return getEncodableBytes2(bytes); +} +function getEncodableList2(list) { + const bodyLength = list.reduce((acc, x) => acc + x.length, 0); + const sizeOfBodyLength = getSizeOfLength2(bodyLength); + const length = (() => { + if (bodyLength <= 55) + return 1 + bodyLength; + return 1 + sizeOfBodyLength + bodyLength; + })(); + return { + length, + encode(cursor) { + if (bodyLength <= 55) { + cursor.pushByte(192 + bodyLength); + } else { + cursor.pushByte(192 + 55 + sizeOfBodyLength); + if (sizeOfBodyLength === 1) + cursor.pushUint8(bodyLength); + else if (sizeOfBodyLength === 2) + cursor.pushUint16(bodyLength); + else if (sizeOfBodyLength === 3) + cursor.pushUint24(bodyLength); + else + cursor.pushUint32(bodyLength); } - continue; - } - if (char === " ") { - if (signature[i - 1] !== "," && current !== "," && current !== ",(") { - current = ""; - active = false; + for (const { encode: encode4 } of list) { + encode4(cursor); } - continue; } - result += char; - current += char; - } - if (!valid) - throw new BaseError3("Unable to normalize signature."); - return result; + }; } -function isArgOfType2(arg, abiParameter) { - const argType = typeof arg; - const abiParameterType = abiParameter.type; - switch (abiParameterType) { - case "address": - return validate3(arg, { strict: false }); - case "bool": - return argType === "boolean"; - case "function": - return argType === "string"; - case "string": - return argType === "string"; - default: { - if (abiParameterType === "tuple" && "components" in abiParameter) - return Object.values(abiParameter.components).every((component, index2) => { - return isArgOfType2(Object.values(arg)[index2], component); - }); - if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType)) - return argType === "number" || argType === "bigint"; - if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType)) - return argType === "string" || arg instanceof Uint8Array; - if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) { - return Array.isArray(arg) && arg.every((x) => isArgOfType2(x, { - ...abiParameter, - type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "") - })); +function getEncodableBytes2(bytesOrHex) { + const bytes = typeof bytesOrHex === "string" ? fromHex(bytesOrHex) : bytesOrHex; + const sizeOfBytesLength = getSizeOfLength2(bytes.length); + const length = (() => { + if (bytes.length === 1 && bytes[0] < 128) + return 1; + if (bytes.length <= 55) + return 1 + bytes.length; + return 1 + sizeOfBytesLength + bytes.length; + })(); + return { + length, + encode(cursor) { + if (bytes.length === 1 && bytes[0] < 128) { + cursor.pushBytes(bytes); + } else if (bytes.length <= 55) { + cursor.pushByte(128 + bytes.length); + cursor.pushBytes(bytes); + } else { + cursor.pushByte(128 + 55 + sizeOfBytesLength); + if (sizeOfBytesLength === 1) + cursor.pushUint8(bytes.length); + else if (sizeOfBytesLength === 2) + cursor.pushUint16(bytes.length); + else if (sizeOfBytesLength === 3) + cursor.pushUint24(bytes.length); + else + cursor.pushUint32(bytes.length); + cursor.pushBytes(bytes); } - return false; } - } + }; } -function getAmbiguousTypes2(sourceParameters, targetParameters, args) { - for (const parameterIndex in sourceParameters) { - const sourceParameter = sourceParameters[parameterIndex]; - const targetParameter = targetParameters[parameterIndex]; - if (sourceParameter.type === "tuple" && targetParameter.type === "tuple" && "components" in sourceParameter && "components" in targetParameter) - return getAmbiguousTypes2(sourceParameter.components, targetParameter.components, args[parameterIndex]); - const types = [sourceParameter.type, targetParameter.type]; - const ambiguous = (() => { - if (types.includes("address") && types.includes("bytes20")) - return true; - if (types.includes("address") && types.includes("string")) - return validate3(args[parameterIndex], { - strict: false - }); - if (types.includes("address") && types.includes("bytes")) - return validate3(args[parameterIndex], { - strict: false - }); - return false; - })(); - if (ambiguous) - return types; - } - return; +function getSizeOfLength2(length) { + if (length <= 255) + return 1; + if (length <= 65535) + return 2; + if (length <= 16777215) + return 3; + if (length <= 4294967295) + return 4; + throw new BaseError3("Length is too large."); } -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiItem.js -function from11(abiItem, options = {}) { - const { prepare = true } = options; - const item = (() => { - if (Array.isArray(abiItem)) - return parseAbiItem(abiItem); - if (typeof abiItem === "string") - return parseAbiItem(abiItem); - return abiItem; +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Signature.js +init_Errors(); +init_Hex(); +function assert6(signature, options = {}) { + const { recovered } = options; + if (typeof signature.r === "undefined") + throw new MissingPropertiesError({ signature }); + if (typeof signature.s === "undefined") + throw new MissingPropertiesError({ signature }); + if (recovered && typeof signature.yParity === "undefined") + throw new MissingPropertiesError({ signature }); + if (signature.r < 0n || signature.r > maxUint2562) + throw new InvalidRError({ value: signature.r }); + if (signature.s < 0n || signature.s > maxUint2562) + throw new InvalidSError({ value: signature.s }); + if (typeof signature.yParity === "number" && signature.yParity !== 0 && signature.yParity !== 1) + throw new InvalidYParityError({ value: signature.yParity }); +} +function fromBytes4(signature) { + return fromHex5(fromBytes(signature)); +} +function fromHex5(signature) { + if (signature.length !== 130 && signature.length !== 132) + throw new InvalidSerializedSizeError2({ signature }); + const r = BigInt(slice3(signature, 0, 32)); + const s = BigInt(slice3(signature, 32, 64)); + const yParity = (() => { + const yParity2 = Number(`0x${signature.slice(130)}`); + if (Number.isNaN(yParity2)) + return; + try { + return vToYParity(yParity2); + } catch { + throw new InvalidYParityError({ value: yParity2 }); + } })(); + if (typeof yParity === "undefined") + return { + r, + s + }; return { - ...item, - ...prepare ? { hash: getSignatureHash(item) } : {} + r, + s, + yParity }; } -function fromAbi(abi2, name, options) { - const { args = [], prepare = true } = options ?? {}; - const isSelector = validate2(name, { strict: false }); - const abiItems = abi2.filter((abiItem2) => { - if (isSelector) { - if (abiItem2.type === "function" || abiItem2.type === "error") - return getSelector(abiItem2) === slice3(name, 0, 4); - if (abiItem2.type === "event") - return getSignatureHash(abiItem2) === name; - return false; - } - return "name" in abiItem2 && abiItem2.name === name; - }); - if (abiItems.length === 0) - throw new NotFoundError({ name }); - if (abiItems.length === 1) +function extract3(value) { + if (typeof value.r === "undefined") + return; + if (typeof value.s === "undefined") + return; + return from12(value); +} +function from12(signature) { + const signature_ = (() => { + if (typeof signature === "string") + return fromHex5(signature); + if (signature instanceof Uint8Array) + return fromBytes4(signature); + if (typeof signature.r === "string") + return fromRpc2(signature); + if (signature.v) + return fromLegacy(signature); return { - ...abiItems[0], - ...prepare ? { hash: getSignatureHash(abiItems[0]) } : {} + r: signature.r, + s: signature.s, + ...typeof signature.yParity !== "undefined" ? { yParity: signature.yParity } : {} }; - let matchedAbiItem; - for (const abiItem2 of abiItems) { - if (!("inputs" in abiItem2)) - continue; - if (!args || args.length === 0) { - if (!abiItem2.inputs || abiItem2.inputs.length === 0) - return { - ...abiItem2, - ...prepare ? { hash: getSignatureHash(abiItem2) } : {} - }; - continue; - } - if (!abiItem2.inputs) - continue; - if (abiItem2.inputs.length === 0) - continue; - if (abiItem2.inputs.length !== args.length) - continue; - const matched = args.every((arg, index2) => { - const abiParameter = "inputs" in abiItem2 && abiItem2.inputs[index2]; - if (!abiParameter) - return false; - return isArgOfType2(arg, abiParameter); - }); - if (matched) { - if (matchedAbiItem && "inputs" in matchedAbiItem && matchedAbiItem.inputs) { - const ambiguousTypes = getAmbiguousTypes2(abiItem2.inputs, matchedAbiItem.inputs, args); - if (ambiguousTypes) - throw new AmbiguityError({ - abiItem: abiItem2, - type: ambiguousTypes[0] - }, { - abiItem: matchedAbiItem, - type: ambiguousTypes[1] - }); - } - matchedAbiItem = abiItem2; - } - } - const abiItem = (() => { - if (matchedAbiItem) - return matchedAbiItem; - const [abiItem2, ...overloads] = abiItems; - return { ...abiItem2, overloads }; })(); - if (!abiItem) - throw new NotFoundError({ name }); + assert6(signature_); + return signature_; +} +function fromLegacy(signature) { return { - ...abiItem, - ...prepare ? { hash: getSignatureHash(abiItem) } : {} + r: signature.r, + s: signature.s, + yParity: vToYParity(signature.v) }; } -function getSelector(...parameters) { - const abiItem = (() => { - if (Array.isArray(parameters[0])) { - const [abi2, name] = parameters; - return fromAbi(abi2, name); - } - return parameters[0]; +function fromRpc2(signature) { + const yParity = (() => { + const v = signature.v ? Number(signature.v) : undefined; + let yParity2 = signature.yParity ? Number(signature.yParity) : undefined; + if (typeof v === "number" && typeof yParity2 !== "number") + yParity2 = vToYParity(v); + if (typeof yParity2 !== "number") + throw new InvalidYParityError({ value: signature.yParity }); + return yParity2; })(); - return slice3(getSignatureHash(abiItem), 0, 4); + return { + r: BigInt(signature.r), + s: BigInt(signature.s), + yParity + }; } -function getSignature(...parameters) { - const abiItem = (() => { - if (Array.isArray(parameters[0])) { - const [abi2, name] = parameters; - return fromAbi(abi2, name); - } - return parameters[0]; - })(); - const signature = (() => { - if (typeof abiItem === "string") - return abiItem; - return formatAbiItem(abiItem); - })(); - return normalizeSignature2(signature); +function toHex3(signature) { + assert6(signature); + const r = signature.r; + const s = signature.s; + const signature_ = concat2(fromNumber(r, { size: 32 }), fromNumber(s, { size: 32 }), typeof signature.yParity === "number" ? fromNumber(yParityToV(signature.yParity), { size: 1 }) : "0x"); + return signature_; } -function getSignatureHash(...parameters) { - const abiItem = (() => { - if (Array.isArray(parameters[0])) { - const [abi2, name] = parameters; - return fromAbi(abi2, name); - } - return parameters[0]; - })(); - if (typeof abiItem !== "string" && "hash" in abiItem && abiItem.hash) - return abiItem.hash; - return keccak2562(fromString2(getSignature(abiItem))); +function toTuple(signature) { + const { r, s, yParity } = signature; + return [ + yParity ? "0x01" : "0x", + r === 0n ? "0x" : trimLeft2(fromNumber(r)), + s === 0n ? "0x" : trimLeft2(fromNumber(s)) + ]; +} +function vToYParity(v) { + if (v === 0 || v === 27) + return 0; + if (v === 1 || v === 28) + return 1; + if (v >= 35) + return v % 2 === 0 ? 1 : 0; + throw new InvalidVError({ value: v }); +} +function yParityToV(yParity) { + if (yParity === 0) + return 27; + if (yParity === 1) + return 28; + throw new InvalidYParityError({ value: yParity }); } -class AmbiguityError extends BaseError3 { - constructor(x, y) { - super("Found ambiguous types in overloaded ABI Items.", { +class InvalidSerializedSizeError2 extends BaseError3 { + constructor({ signature }) { + super(`Value \`${signature}\` is an invalid signature size.`, { metaMessages: [ - `\`${x.type}\` in \`${normalizeSignature2(formatAbiItem(x.abiItem))}\`, and`, - `\`${y.type}\` in \`${normalizeSignature2(formatAbiItem(y.abiItem))}\``, - "", - "These types encode differently and cannot be distinguished at runtime.", - "Remove one of the ambiguous items in the ABI." + "Expected: 64 bytes or 65 bytes.", + `Received ${size4(from3(signature))} bytes.` ] }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: "AbiItem.AmbiguityError" + value: "Signature.InvalidSerializedSizeError" }); } } -class NotFoundError extends BaseError3 { - constructor({ name, data, type = "item" }) { - const selector = (() => { - if (name) - return ` with name "${name}"`; - if (data) - return ` with data "${data}"`; - return ""; - })(); - super(`ABI ${type}${selector} not found.`); +class MissingPropertiesError extends BaseError3 { + constructor({ signature }) { + super(`Signature \`${stringify2(signature)}\` is missing either an \`r\`, \`s\`, or \`yParity\` property.`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: "AbiItem.NotFoundError" + value: "Signature.MissingPropertiesError" }); } } -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiConstructor.js -init_Hex(); -function encode3(...parameters) { - const [abiConstructor, options] = (() => { - if (Array.isArray(parameters[0])) { - const [abi2, options2] = parameters; - return [fromAbi2(abi2), options2]; - } - return parameters; - })(); - const { bytecode, args } = options; - return concat2(bytecode, abiConstructor.inputs?.length && args?.length ? encode2(abiConstructor.inputs, args) : "0x"); -} -function from12(abiConstructor) { - return from11(abiConstructor); -} -function fromAbi2(abi2) { - const item = abi2.find((item2) => item2.type === "constructor"); - if (!item) - throw new NotFoundError({ name: "constructor" }); - return item; +class InvalidRError extends BaseError3 { + constructor({ value }) { + super(`Value \`${value}\` is an invalid r value. r must be a positive integer less than 2^256.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Signature.InvalidRError" + }); + } } -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/AbiFunction.js -init_Hex(); -function encodeData2(...parameters) { - const [abiFunction, args = []] = (() => { - if (Array.isArray(parameters[0])) { - const [abi2, name, args3] = parameters; - return [fromAbi3(abi2, name, { args: args3 }), args3]; - } - const [abiFunction2, args2] = parameters; - return [abiFunction2, args2]; - })(); - const { overloads } = abiFunction; - const item = overloads ? fromAbi3([abiFunction, ...overloads], abiFunction.name, { - args - }) : abiFunction; - const selector = getSelector2(item); - const data = args.length > 0 ? encode2(item.inputs, args) : undefined; - return data ? concat2(selector, data) : selector; -} -function from13(abiFunction, options = {}) { - return from11(abiFunction, options); -} -function fromAbi3(abi2, name, options) { - const item = fromAbi(abi2, name, options); - if (item.type !== "function") - throw new NotFoundError({ name, type: "function" }); - return item; -} -function getSelector2(abiItem) { - return getSelector(abiItem); +class InvalidSError extends BaseError3 { + constructor({ value }) { + super(`Value \`${value}\` is an invalid s value. s must be a positive integer less than 2^256.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Signature.InvalidSError" + }); + } } -// ../viem/src/_esm/constants/address.js -var ethAddress = "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"; -var zeroAddress = "0x0000000000000000000000000000000000000000"; -// ../viem/src/_esm/actions/public/simulateCalls.js -init_base(); -init_encodeFunctionData(); -var getBalanceCode = "0x6080604052348015600e575f80fd5b5061016d8061001c5f395ff3fe608060405234801561000f575f80fd5b5060043610610029575f3560e01c8063f8b2cb4f1461002d575b5f80fd5b610047600480360381019061004291906100db565b61005d565b604051610054919061011e565b60405180910390f35b5f8173ffffffffffffffffffffffffffffffffffffffff16319050919050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6100aa82610081565b9050919050565b6100ba816100a0565b81146100c4575f80fd5b50565b5f813590506100d5816100b1565b92915050565b5f602082840312156100f0576100ef61007d565b5b5f6100fd848285016100c7565b91505092915050565b5f819050919050565b61011881610106565b82525050565b5f6020820190506101315f83018461010f565b9291505056fea26469706673582212203b9fe929fe995c7cf9887f0bdba8a36dd78e8b73f149b17d2d9ad7cd09d2dc6264736f6c634300081a0033"; -async function simulateCalls(client, parameters) { - const { blockNumber, blockTag, calls, stateOverrides, traceAssetChanges, traceTransfers, validation } = parameters; - const account = parameters.account ? parseAccount(parameters.account) : undefined; - if (traceAssetChanges && !account) - throw new BaseError2("`account` is required when `traceAssetChanges` is true"); - const getBalanceData = account ? encode3(from12("constructor(bytes, bytes)"), { - bytecode: deploylessCallViaBytecodeBytecode, - args: [ - getBalanceCode, - encodeData2(from13("function getBalance(address)"), [account.address]) - ] - }) : undefined; - const assetAddresses = traceAssetChanges ? await Promise.all(parameters.calls.map(async (call2) => { - if (!call2.data && !call2.abi) - return; - const { accessList } = await createAccessList(client, { - account: account.address, - ...call2, - data: call2.abi ? encodeFunctionData(call2) : call2.data +class InvalidYParityError extends BaseError3 { + constructor({ value }) { + super(`Value \`${value}\` is an invalid y-parity value. Y-parity must be 0 or 1.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Signature.InvalidYParityError" }); - return accessList.map(({ address, storageKeys }) => storageKeys.length > 0 ? address : null); - })).then((x) => x.flat().filter(Boolean)) : []; - const blocks = await simulateBlocks(client, { - blockNumber, - blockTag, - blocks: [ - ...traceAssetChanges ? [ - { - calls: [{ data: getBalanceData }], - stateOverrides - }, - { - calls: assetAddresses.map((address, i) => ({ - abi: [ - from13("function balanceOf(address) returns (uint256)") - ], - functionName: "balanceOf", - args: [account.address], - to: address, - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - } - ] : [], - { - calls: [...calls, { to: zeroAddress }].map((call2) => ({ - ...call2, - from: account?.address - })), - stateOverrides - }, - ...traceAssetChanges ? [ - { - calls: [{ data: getBalanceData }] - }, - { - calls: assetAddresses.map((address, i) => ({ - abi: [ - from13("function balanceOf(address) returns (uint256)") - ], - functionName: "balanceOf", - args: [account.address], - to: address, - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - }, - { - calls: assetAddresses.map((address, i) => ({ - to: address, - abi: [ - from13("function decimals() returns (uint256)") - ], - functionName: "decimals", - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - }, - { - calls: assetAddresses.map((address, i) => ({ - to: address, - abi: [ - from13("function tokenURI(uint256) returns (string)") - ], - functionName: "tokenURI", - args: [0n], - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - }, - { - calls: assetAddresses.map((address, i) => ({ - to: address, - abi: [from13("function symbol() returns (string)")], - functionName: "symbol", - from: zeroAddress, - nonce: i - })), - stateOverrides: [ - { - address: zeroAddress, - nonce: 0 - } - ] - } - ] : [] - ], - traceTransfers, - validation - }); - const block_results = traceAssetChanges ? blocks[2] : blocks[0]; - const [block_ethPre, block_assetsPre, , block_ethPost, block_assetsPost, block_decimals, block_tokenURI, block_symbols] = traceAssetChanges ? blocks : []; - const { calls: block_calls, ...block } = block_results; - const results = block_calls.slice(0, -1) ?? []; - const ethPre = block_ethPre?.calls ?? []; - const assetsPre = block_assetsPre?.calls ?? []; - const balancesPre = [...ethPre, ...assetsPre].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); - const ethPost = block_ethPost?.calls ?? []; - const assetsPost = block_assetsPost?.calls ?? []; - const balancesPost = [...ethPost, ...assetsPost].map((call2) => call2.status === "success" ? hexToBigInt(call2.data) : null); - const decimals = (block_decimals?.calls ?? []).map((x) => x.status === "success" ? x.result : null); - const symbols = (block_symbols?.calls ?? []).map((x) => x.status === "success" ? x.result : null); - const tokenURI = (block_tokenURI?.calls ?? []).map((x) => x.status === "success" ? x.result : null); - const changes = []; - for (const [i, balancePost] of balancesPost.entries()) { - const balancePre = balancesPre[i]; - if (typeof balancePost !== "bigint") - continue; - if (typeof balancePre !== "bigint") - continue; - const decimals_ = decimals[i - 1]; - const symbol_ = symbols[i - 1]; - const tokenURI_ = tokenURI[i - 1]; - const token = (() => { - if (i === 0) - return { - address: ethAddress, - decimals: 18, - symbol: "ETH" - }; - return { - address: assetAddresses[i - 1], - decimals: tokenURI_ || decimals_ ? Number(decimals_ ?? 1) : undefined, - symbol: symbol_ ?? undefined - }; - })(); - if (changes.some((change) => change.token.address === token.address)) - continue; - changes.push({ - token, - value: { - pre: balancePre, - post: balancePost, - diff: balancePost - balancePre - } + } +} + +class InvalidVError extends BaseError3 { + constructor({ value }) { + super(`Value \`${value}\` is an invalid v value. v must be 27, 28 or >=35.`); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Signature.InvalidVError" }); } +} + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Authorization.js +function from13(authorization, options = {}) { + if (typeof authorization.chainId === "string") + return fromRpc3(authorization); + return { ...authorization, ...options.signature }; +} +function fromRpc3(authorization) { + const { address, chainId, nonce } = authorization; + const signature = extract3(authorization); return { - assetChanges: changes, - block, - results + address, + chainId: Number(chainId), + nonce: BigInt(nonce), + ...signature }; } +function getSignPayload(authorization) { + return hash2(authorization, { presign: true }); +} +function hash2(authorization, options = {}) { + const { presign } = options; + return keccak2563(concat2("0x05", fromHex4(toTuple2(presign ? { + address: authorization.address, + chainId: authorization.chainId, + nonce: authorization.nonce + } : authorization)))); +} +function toTuple2(authorization) { + const { address, chainId, nonce } = authorization; + const signature = extract3(authorization); + return [ + chainId ? fromNumber(chainId) : "0x", + address, + nonce ? fromNumber(nonce) : "0x", + ...signature ? toTuple(signature) : [] + ]; +} -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/erc6492/SignatureErc6492.js -var exports_SignatureErc6492 = {}; -__export(exports_SignatureErc6492, { - wrap: () => wrap2, - validate: () => validate5, - unwrap: () => unwrap2, - universalSignatureValidatorBytecode: () => universalSignatureValidatorBytecode, - universalSignatureValidatorAbi: () => universalSignatureValidatorAbi, - magicBytes: () => magicBytes2, - from: () => from14, - assert: () => assert7, - InvalidWrappedSignatureError: () => InvalidWrappedSignatureError2 -}); +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/erc8010/SignatureErc8010.js init_Errors(); init_Hex(); -var magicBytes2 = "0x6492649264926492649264926492649264926492649264926492649264926492"; -var universalSignatureValidatorBytecode = "0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572"; -var universalSignatureValidatorAbi = [ - { - inputs: [ - { - name: "_signer", - type: "address" - }, - { - name: "_hash", - type: "bytes32" - }, - { - name: "_signature", - type: "bytes" - } - ], - stateMutability: "nonpayable", - type: "constructor" - }, - { - inputs: [ - { - name: "_signer", - type: "address" - }, - { - name: "_hash", - type: "bytes32" - }, - { - name: "_signature", - type: "bytes" - } - ], - outputs: [ - { - type: "bool" - } - ], - stateMutability: "nonpayable", - type: "function", - name: "isValidSig" - } -]; -function assert7(wrapped) { - if (slice3(wrapped, -32) !== magicBytes2) - throw new InvalidWrappedSignatureError2(wrapped); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Secp256k1.js +init_secp256k1(); +init_Hex(); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/entropy.js +var extraEntropy = false; + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Secp256k1.js +function recoverAddress3(options) { + return fromPublicKey(recoverPublicKey3(options)); } -function from14(wrapped) { - if (typeof wrapped === "string") - return unwrap2(wrapped); - return wrapped; +function recoverPublicKey3(options) { + const { payload, signature } = options; + const { r, s, yParity } = signature; + const signature_ = new secp256k1.Signature(BigInt(r), BigInt(s)).addRecoveryBit(yParity); + const point = signature_.recoverPublicKey(from3(payload).substring(2)); + return from4(point); +} + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/erc8010/SignatureErc8010.js +var magicBytes2 = "0x8010801080108010801080108010801080108010801080108010801080108010"; +var suffixParameters = from7("(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data"); +function assert7(value) { + if (typeof value === "string") { + if (slice3(value, -32) !== magicBytes2) + throw new InvalidWrappedSignatureError2(value); + } else + assert6(value.authorization); +} +function from14(value) { + if (typeof value === "string") + return unwrap2(value); + return value; } function unwrap2(wrapped) { assert7(wrapped); - const [to, data, signature] = decode(from6("address, bytes, bytes"), wrapped); - return { data, signature, to }; + const suffixLength = toNumber(slice3(wrapped, -64, -32)); + const suffix = slice3(wrapped, -suffixLength - 64, -64); + const signature = slice3(wrapped, 0, -suffixLength - 64); + const [auth, to, data] = decode(suffixParameters, suffix); + const authorization = from13({ + address: auth.delegation, + chainId: Number(auth.chainId), + nonce: auth.nonce, + yParity: auth.yParity, + r: auth.r, + s: auth.s + }); + return { + authorization, + signature, + ...data && data !== "0x" ? { data, to } : {} + }; } function wrap2(value) { - const { data, signature, to } = value; - return concat2(encode2(from6("address, bytes, bytes"), [ - to, - data, - signature - ]), magicBytes2); + const { data, signature } = value; + assert7(value); + const self = recoverAddress3({ + payload: getSignPayload(value.authorization), + signature: from12(value.authorization) + }); + const suffix = encode2(suffixParameters, [ + { + ...value.authorization, + delegation: value.authorization.address, + chainId: BigInt(value.authorization.chainId) + }, + value.to ?? self, + data ?? "0x" + ]); + const suffixLength = fromNumber(size4(suffix), { size: 32 }); + return concat2(signature, suffix, suffixLength, magicBytes2); } -function validate5(wrapped) { +function validate5(value) { try { - assert7(wrapped); + assert7(value); return true; } catch { return false; @@ -17182,12 +15175,12 @@ function validate5(wrapped) { class InvalidWrappedSignatureError2 extends BaseError3 { constructor(wrapped) { - super(`Value \`${wrapped}\` is an invalid ERC-6492 wrapped signature.`); + super(`Value \`${wrapped}\` is an invalid ERC-8010 wrapped signature.`); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, - value: "SignatureErc6492.InvalidWrappedSignatureError" + value: "SignatureErc8010.InvalidWrappedSignatureError" }); } } @@ -17198,6 +15191,18 @@ init_encodeDeployData(); init_encodeFunctionData(); init_getAddress(); init_isAddressEqual(); + +// ../viem/src/_esm/utils/authorization/verifyAuthorization.js +init_getAddress(); +init_isAddressEqual(); +async function verifyAuthorization2({ address, authorization, signature }) { + return isAddressEqual(getAddress(address), await recoverAuthorizationAddress({ + authorization, + signature + })); +} + +// ../viem/src/_esm/actions/public/verifyHash.js init_fromHex(); init_toHex(); @@ -17221,7 +15226,7 @@ function serializeSignature({ r, s, to = "hex", v, yParity }) { // ../viem/src/_esm/actions/public/verifyHash.js init_call(); -async function verifyHash(client, parameters) { +async function verifyHash2(client, parameters) { const { address, chain = client.chain, hash: hash3, erc6492VerifierAddress: verifierAddress = parameters.universalSignatureVerifierAddress ?? chain?.contracts?.erc6492Verifier?.address, multicallAddress = parameters.multicallAddress ?? chain?.contracts?.multicall3?.address, mode = "auto" } = parameters; if (chain?.verifyHash) return await chain.verifyHash(client, parameters); @@ -17289,7 +15294,7 @@ async function verifyErc8010(client, parameters) { s: numberToHex(authorization_ox.s, { size: 32 }), yParity: authorization_ox.yParity }; - const valid = await verifyAuthorization({ + const valid = await verifyAuthorization2({ address, authorization }); @@ -17392,10 +15397,37 @@ async function verifyErc1271(client, parameters) { class VerificationError extends Error { } +// ../viem/src/_esm/utils/signature/hashMessage.js +init_keccak256(); + +// ../viem/src/_esm/constants/strings.js +var presignMessagePrefix = `\x19Ethereum Signed Message: +`; + +// ../viem/src/_esm/utils/signature/toPrefixedMessage.js +init_size(); +init_toHex(); +function toPrefixedMessage(message_) { + const message = (() => { + if (typeof message_ === "string") + return stringToHex(message_); + if (typeof message_.raw === "string") + return message_.raw; + return bytesToHex(message_.raw); + })(); + const prefix = stringToHex(`${presignMessagePrefix}${size2(message)}`); + return concat([prefix, message]); +} + +// ../viem/src/_esm/utils/signature/hashMessage.js +function hashMessage2(message, to_) { + return keccak256(toPrefixedMessage(message), to_); +} + // ../viem/src/_esm/actions/public/verifyMessage.js -async function verifyMessage(client, { address, message, factory, factoryData, signature, ...callRequest }) { - const hash3 = hashMessage(message); - return getAction(client, verifyHash, "verifyHash")({ +async function verifyMessage2(client, { address, message, factory, factoryData, signature, ...callRequest }) { + const hash3 = hashMessage2(message); + return getAction(client, verifyHash2, "verifyHash")({ address, factory, factoryData, @@ -17405,3179 +15437,4129 @@ async function verifyMessage(client, { address, message, factory, factoryData, s }); } -// ../viem/src/_esm/actions/public/verifyTypedData.js -async function verifyTypedData(client, parameters) { - const { address, factory, factoryData, signature, message, primaryType, types, domain, ...callRequest } = parameters; - const hash3 = hashTypedData({ message, primaryType, types, domain }); - return getAction(client, verifyHash, "verifyHash")({ - address, - factory, - factoryData, - hash: hash3, - signature, - ...callRequest - }); +// ../viem/src/_esm/utils/signature/hashTypedData.js +init_encodeAbiParameters(); +init_toHex(); +init_keccak256(); + +// ../viem/src/_esm/utils/typedData.js +init_abi(); +init_address(); + +// ../viem/src/_esm/errors/typedData.js +init_base(); + +class InvalidDomainError extends BaseError2 { + constructor({ domain }) { + super(`Invalid domain "${stringify(domain)}".`, { + metaMessages: ["Must be a valid EIP-712 domain."] + }); + } } -// ../viem/src/_esm/actions/public/waitForTransactionReceipt.js -init_transaction(); -// ../viem/src/_esm/actions/public/watchBlockNumber.js -init_fromHex(); -function watchBlockNumber(client, { emitOnBegin = false, emitMissed = false, onBlockNumber, onError, poll: poll_, pollingInterval = client.pollingInterval }) { - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (client.transport.type === "webSocket" || client.transport.type === "ipc") - return false; - if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc")) - return false; - return true; - })(); - let prevBlockNumber; - const pollBlockNumber = () => { - const observerId = stringify([ - "watchBlockNumber", - client.uid, - emitOnBegin, - emitMissed, - pollingInterval - ]); - return observe(observerId, { onBlockNumber, onError }, (emit) => poll(async () => { - try { - const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({ cacheTime: 0 }); - if (prevBlockNumber !== undefined) { - if (blockNumber === prevBlockNumber) - return; - if (blockNumber - prevBlockNumber > 1 && emitMissed) { - for (let i = prevBlockNumber + 1n;i < blockNumber; i++) { - emit.onBlockNumber(i, prevBlockNumber); - prevBlockNumber = i; - } - } - } - if (prevBlockNumber === undefined || blockNumber > prevBlockNumber) { - emit.onBlockNumber(blockNumber, prevBlockNumber); - prevBlockNumber = blockNumber; - } - } catch (err) { - emit.onError?.(err); - } - }, { - emitOnBegin, - interval: pollingInterval - })); - }; - const subscribeBlockNumber = () => { - const observerId = stringify([ - "watchBlockNumber", - client.uid, - emitOnBegin, - emitMissed - ]); - return observe(observerId, { onBlockNumber, onError }, (emit) => { - let active = true; - let unsubscribe = () => active = false; - (async () => { - try { - const transport = (() => { - if (client.transport.type === "fallback") { - const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); - if (!transport2) - return client.transport; - return transport2.value; - } - return client.transport; - })(); - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["newHeads"], - onData(data) { - if (!active) - return; - const blockNumber = hexToBigInt(data.result?.number); - emit.onBlockNumber(blockNumber, prevBlockNumber); - prevBlockNumber = blockNumber; - }, - onError(error) { - emit.onError?.(error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError?.(err); - } - })(); - return () => unsubscribe(); +class InvalidPrimaryTypeError extends BaseError2 { + constructor({ primaryType, types }) { + super(`Invalid primary type \`${primaryType}\` must be one of \`${JSON.stringify(Object.keys(types))}\`.`, { + docsPath: "/api/glossary/Errors#typeddatainvalidprimarytypeerror", + metaMessages: ["Check that the primary type is a key in `types`."] }); - }; - return enablePolling ? pollBlockNumber() : subscribeBlockNumber(); + } } -// ../viem/src/_esm/actions/public/waitForTransactionReceipt.js -async function waitForTransactionReceipt(client, parameters) { - const { - checkReplacement = client.chain?.supportsTransactionReplacementDetection ?? true, - confirmations = 1, - hash: hash3, - onReplaced, - retryCount = 6, - retryDelay = ({ count }) => ~~(1 << count) * 200, - timeout = 180000 - } = parameters; - const observerId = stringify(["waitForTransactionReceipt", client.uid, hash3]); - const pollingInterval = (() => { - if (parameters.pollingInterval) - return parameters.pollingInterval; - if (client.chain?.experimental_preconfirmationTime) - return client.chain.experimental_preconfirmationTime; - return client.pollingInterval; - })(); - let transaction; - let replacedTransaction; - let receipt; - let retrying = false; - let _unobserve; - let _unwatch; - const { promise, resolve, reject } = withResolvers(); - const timer = timeout ? setTimeout(() => { - _unwatch?.(); - _unobserve?.(); - reject(new WaitForTransactionReceiptTimeoutError({ hash: hash3 })); - }, timeout) : undefined; - _unobserve = observe(observerId, { onReplaced, resolve, reject }, async (emit) => { - receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash3 }).catch(() => { - return; +class InvalidStructTypeError extends BaseError2 { + constructor({ type }) { + super(`Struct type "${type}" is invalid.`, { + metaMessages: ["Struct type must not be a Solidity type."], + name: "InvalidStructTypeError" }); - if (receipt && confirmations <= 1) { - clearTimeout(timer); - emit.resolve(receipt); - _unobserve?.(); - return; - } - _unwatch = getAction(client, watchBlockNumber, "watchBlockNumber")({ - emitMissed: true, - emitOnBegin: true, - poll: true, - pollingInterval, - async onBlockNumber(blockNumber_) { - const done = (fn) => { - clearTimeout(timer); - _unwatch?.(); - fn(); - _unobserve?.(); - }; - let blockNumber = blockNumber_; - if (retrying) - return; - try { - if (receipt) { - if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) - return; - done(() => emit.resolve(receipt)); - return; - } - if (checkReplacement && !transaction) { - retrying = true; - await withRetry(async () => { - transaction = await getAction(client, getTransaction, "getTransaction")({ hash: hash3 }); - if (transaction.blockNumber) - blockNumber = transaction.blockNumber; - }, { - delay: retryDelay, - retryCount - }); - retrying = false; - } - receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash3 }); - if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) - return; - done(() => emit.resolve(receipt)); - } catch (err) { - if (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError) { - if (!transaction) { - retrying = false; - return; - } - try { - replacedTransaction = transaction; - retrying = true; - const block = await withRetry(() => getAction(client, getBlock, "getBlock")({ - blockNumber, - includeTransactions: true - }), { - delay: retryDelay, - retryCount, - shouldRetry: ({ error }) => error instanceof BlockNotFoundError - }); - retrying = false; - const replacementTransaction = block.transactions.find(({ from: from15, nonce }) => from15 === replacedTransaction.from && nonce === replacedTransaction.nonce); - if (!replacementTransaction || !replacementTransaction.hash) - return; - receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ - hash: replacementTransaction.hash - }); - if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) - return; - let reason = "replaced"; - if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value && replacementTransaction.input === replacedTransaction.input) { - reason = "repriced"; - } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) { - reason = "cancelled"; - } - done(() => { - emit.onReplaced?.({ - reason, - replacedTransaction, - transaction: replacementTransaction, - transactionReceipt: receipt - }); - emit.resolve(receipt); - }); - } catch (err_) { - done(() => emit.reject(err_)); - } - } else { - done(() => emit.reject(err)); - } - } - } + } +} + +class InvalidTypedDataTypeError extends BaseError2 { + constructor({ type }) { + const canonicalType = type.replace(/^(u?int)/, "$&256"); + super(`Type "${type}" is not a valid EIP-712 type.`, { + metaMessages: [`Use "${canonicalType}" instead.`], + name: "InvalidTypedDataTypeError" }); - }); - return promise; + } } -// ../viem/src/_esm/actions/public/watchBlockHeaders.js -var blockFields = [ - "size", - "totalDifficulty", - "transactions", - "uncles", - "withdrawals" -]; -function watchBlockHeaders(client, { onBlockHeader, onError }) { - let prevBlockHeader; - const observerId = stringify(["watchBlockHeaders", client.uid]); - return observe(observerId, { onBlockHeader, onError }, (emit) => { - let active = true; - let subscribed = false; - let unsubscribe = () => active = false; - (async () => { - try { - const transport = (() => { - if (client.transport.type === "fallback") { - const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); - if (!transport2) - return client.transport; - return transport2.value; - } - return client.transport; - })(); - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["newHeads"], - onData(data) { - if (!active) - return; - const blockHeader = (client.chain?.formatters?.block?.format || formatBlock)(data.result, "watchBlockHeaders"); - for (const field of blockFields) - delete blockHeader[field]; - emit.onBlockHeader(blockHeader, prevBlockHeader); - prevBlockHeader = blockHeader; - }, - onError(error) { - if (subscribed) - emit.onError?.(error); - } +// ../viem/src/_esm/utils/typedData.js +init_isAddress(); +init_size(); +init_toHex(); +init_regex2(); +function serializeTypedData2(parameters) { + const { domain: domain_, message: message_, primaryType, types } = parameters; + const normalizeData = (struct, data_) => { + const data = { ...data_ }; + for (const param of struct) { + const { name, type } = param; + if (type === "address") + data[name] = data[name].toLowerCase(); + } + return data; + }; + const domain = (() => { + if (!types.EIP712Domain) + return {}; + if (!domain_) + return {}; + return normalizeData(types.EIP712Domain, domain_); + })(); + const message = (() => { + if (primaryType === "EIP712Domain") + return; + return normalizeData(types[primaryType], message_); + })(); + return stringify({ domain, message, primaryType, types }); +} +function validateTypedData2(parameters) { + const { domain, message, primaryType, types } = parameters; + const validateData = (struct, data) => { + for (const param of struct) { + const { name, type } = param; + const value = data[name]; + const baseType = type.replace(/(\[[0-9]*\])+$/, ""); + if (baseType === "int" || baseType === "uint") + throw new InvalidTypedDataTypeError({ type }); + const integerMatch = type.match(integerRegex2); + if (integerMatch && (typeof value === "number" || typeof value === "bigint")) { + const [_type, base, size_] = integerMatch; + numberToHex(value, { + signed: base === "int", + size: Number.parseInt(size_, 10) / 8 }); - subscribed = true; - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - emit.onError?.(err); } - })(); - return () => unsubscribe(); - }); + if (type === "address" && typeof value === "string" && !isAddress(value)) + throw new InvalidAddressError({ address: value }); + const bytesMatch = type.match(bytesRegex2); + if (bytesMatch) { + const [_type, size_] = bytesMatch; + if (size_ && size2(value) !== Number.parseInt(size_, 10)) + throw new BytesSizeMismatchError({ + expectedSize: Number.parseInt(size_, 10), + givenSize: size2(value) + }); + } + const struct2 = types[type]; + if (struct2) { + validateReference(type); + validateData(struct2, value); + } + } + }; + if (types.EIP712Domain && domain) { + if (typeof domain !== "object") + throw new InvalidDomainError({ domain }); + validateData(types.EIP712Domain, domain); + } + if (primaryType !== "EIP712Domain") { + if (types[primaryType]) + validateData(types[primaryType], message); + else + throw new InvalidPrimaryTypeError({ primaryType, types }); + } } -// ../viem/src/_esm/actions/public/watchBlocks.js -function watchBlocks(client, { blockTag = client.experimental_blockTag ?? "latest", emitMissed = false, emitOnBegin = false, onBlock, onError, includeTransactions: includeTransactions_, poll: poll_, pollingInterval = client.pollingInterval }) { - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (client.transport.type === "webSocket" || client.transport.type === "ipc") - return false; - if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc")) - return false; - return true; - })(); - const includeTransactions = includeTransactions_ ?? false; - let prevBlock; - const pollBlocks = () => { - const observerId = stringify([ - "watchBlocks", - client.uid, - blockTag, - emitMissed, - emitOnBegin, - includeTransactions, - pollingInterval - ]); - return observe(observerId, { onBlock, onError }, (emit) => poll(async () => { - try { - const block = await getAction(client, getBlock, "getBlock")({ - blockTag, - includeTransactions - }); - if (block.number !== null && prevBlock?.number != null) { - if (block.number === prevBlock.number) - return; - if (block.number - prevBlock.number > 1 && emitMissed) { - for (let i = prevBlock?.number + 1n;i < block.number; i++) { - const block2 = await getAction(client, getBlock, "getBlock")({ - blockNumber: i, - includeTransactions - }); - emit.onBlock(block2, prevBlock); - prevBlock = block2; - } - } - } - if (prevBlock?.number == null || blockTag === "pending" && block?.number == null || block.number !== null && block.number > prevBlock.number) { - emit.onBlock(block, prevBlock); - prevBlock = block; - } - } catch (err) { - emit.onError?.(err); - } - }, { - emitOnBegin, - interval: pollingInterval - })); - }; - const subscribeBlocks = () => { - let active = true; - let emitFetched = true; - let unsubscribe = () => active = false; - (async () => { - try { - if (emitOnBegin) { - getAction(client, getBlock, "getBlock")({ - blockTag, - includeTransactions - }).then((block) => { - if (!active) - return; - if (!emitFetched) - return; - onBlock(block, undefined); - emitFetched = false; - }).catch(onError); - } - const transport = (() => { - if (client.transport.type === "fallback") { - const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); - if (!transport2) - return client.transport; - return transport2.value; - } - return client.transport; - })(); - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["newHeads"], - async onData(data) { - if (!active) - return; - const block = await getAction(client, getBlock, "getBlock")({ - blockNumber: data.result?.number, - includeTransactions - }).catch(() => {}); - if (!active) - return; - onBlock(block, prevBlock); - emitFetched = false; - prevBlock = block; - }, - onError(error) { - onError?.(error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError?.(err); - } - })(); - return () => unsubscribe(); - }; - return enablePolling ? pollBlocks() : subscribeBlocks(); +function getTypesForEIP712Domain({ domain }) { + return [ + typeof domain?.name === "string" && { name: "name", type: "string" }, + domain?.version && { name: "version", type: "string" }, + (typeof domain?.chainId === "number" || typeof domain?.chainId === "bigint") && { + name: "chainId", + type: "uint256" + }, + domain?.verifyingContract && { + name: "verifyingContract", + type: "address" + }, + domain?.salt && { name: "salt", type: "bytes32" } + ].filter(Boolean); +} +function validateReference(type) { + if (type === "address" || type === "bool" || type === "string" || type.startsWith("bytes") || type.startsWith("uint") || type.startsWith("int")) + throw new InvalidStructTypeError({ type }); } -// ../viem/src/_esm/actions/public/watchEvent.js -init_abi(); -init_rpc(); -function watchEvent(client, { address, args, batch = true, event, events, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ }) { - const enablePolling = (() => { - if (typeof poll_ !== "undefined") - return poll_; - if (typeof fromBlock === "bigint") - return true; - if (client.transport.type === "webSocket" || client.transport.type === "ipc") - return false; - if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc")) - return false; - return true; - })(); - const strict = strict_ ?? false; - const pollEvent = () => { - const observerId = stringify([ - "watchEvent", - address, - args, - batch, - client.uid, - event, - pollingInterval, - fromBlock - ]); - return observe(observerId, { onLogs, onError }, (emit) => { - let previousBlockNumber; - if (fromBlock !== undefined) - previousBlockNumber = fromBlock - 1n; - let filter; - let initialized = false; - const unwatch = poll(async () => { - if (!initialized) { - try { - filter = await getAction(client, createEventFilter, "createEventFilter")({ - address, - args, - event, - events, - strict, - fromBlock - }); - } catch {} - initialized = true; - return; - } - try { - let logs; - if (filter) { - logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter }); - } else { - const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); - if (previousBlockNumber && previousBlockNumber !== blockNumber) { - logs = await getAction(client, getLogs, "getLogs")({ - address, - args, - event, - events, - fromBlock: previousBlockNumber + 1n, - toBlock: blockNumber - }); - } else { - logs = []; - } - previousBlockNumber = blockNumber; - } - if (logs.length === 0) - return; - if (batch) - emit.onLogs(logs); - else - for (const log of logs) - emit.onLogs([log]); - } catch (err) { - if (filter && err instanceof InvalidInputRpcError) - initialized = false; - emit.onError?.(err); - } - }, { - emitOnBegin: true, - interval: pollingInterval - }); - return async () => { - if (filter) - await getAction(client, uninstallFilter, "uninstallFilter")({ filter }); - unwatch(); - }; - }); +// ../viem/src/_esm/utils/signature/hashTypedData.js +function hashTypedData2(parameters) { + const { domain = {}, message, primaryType } = parameters; + const types = { + EIP712Domain: getTypesForEIP712Domain({ domain }), + ...parameters.types }; - const subscribeEvent = () => { - let active = true; - let unsubscribe = () => active = false; - (async () => { - try { - const transport = (() => { - if (client.transport.type === "fallback") { - const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); - if (!transport2) - return client.transport; - return transport2.value; - } - return client.transport; - })(); - const events_ = events ?? (event ? [event] : undefined); - let topics = []; - if (events_) { - const encoded = events_.flatMap((event2) => encodeEventTopics({ - abi: [event2], - eventName: event2.name, - args - })); - topics = [encoded]; - if (event) - topics = topics[0]; - } - const { unsubscribe: unsubscribe_ } = await transport.subscribe({ - params: ["logs", { address, topics }], - onData(data) { - if (!active) - return; - const log = data.result; - try { - const { eventName, args: args2 } = decodeEventLog({ - abi: events_ ?? [], - data: log.data, - topics: log.topics, - strict - }); - const formatted = formatLog(log, { args: args2, eventName }); - onLogs([formatted]); - } catch (err) { - let eventName; - let isUnnamed; - if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { - if (strict_) - return; - eventName = err.abiItem.name; - isUnnamed = err.abiItem.inputs?.some((x) => !(("name" in x) && x.name)); - } - const formatted = formatLog(log, { - args: isUnnamed ? [] : {}, - eventName - }); - onLogs([formatted]); - } - }, - onError(error) { - onError?.(error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError?.(err); - } - })(); - return () => unsubscribe(); - }; - return enablePolling ? pollEvent() : subscribeEvent(); -} -// ../viem/src/_esm/actions/public/watchPendingTransactions.js -function watchPendingTransactions(client, { batch = true, onError, onTransactions, poll: poll_, pollingInterval = client.pollingInterval }) { - const enablePolling = typeof poll_ !== "undefined" ? poll_ : client.transport.type !== "webSocket" && client.transport.type !== "ipc"; - const pollPendingTransactions = () => { - const observerId = stringify([ - "watchPendingTransactions", - client.uid, - batch, - pollingInterval - ]); - return observe(observerId, { onTransactions, onError }, (emit) => { - let filter; - const unwatch = poll(async () => { - try { - if (!filter) { - try { - filter = await getAction(client, createPendingTransactionFilter, "createPendingTransactionFilter")({}); - return; - } catch (err) { - unwatch(); - throw err; - } - } - const hashes = await getAction(client, getFilterChanges, "getFilterChanges")({ filter }); - if (hashes.length === 0) - return; - if (batch) - emit.onTransactions(hashes); - else - for (const hash3 of hashes) - emit.onTransactions([hash3]); - } catch (err) { - emit.onError?.(err); - } - }, { - emitOnBegin: true, - interval: pollingInterval - }); - return async () => { - if (filter) - await getAction(client, uninstallFilter, "uninstallFilter")({ filter }); - unwatch(); - }; - }); - }; - const subscribePendingTransactions = () => { - let active = true; - let unsubscribe = () => active = false; - (async () => { - try { - const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({ - params: ["newPendingTransactions"], - onData(data) { - if (!active) - return; - const transaction = data.result; - onTransactions([transaction]); - }, - onError(error) { - onError?.(error); - } - }); - unsubscribe = unsubscribe_; - if (!active) - unsubscribe(); - } catch (err) { - onError?.(err); - } - })(); - return () => unsubscribe(); - }; - return enablePolling ? pollPendingTransactions() : subscribePendingTransactions(); -} - -// ../viem/src/_esm/utils/siwe/parseSiweMessage.js -function parseSiweMessage(message) { - const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {}; - const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {}; - const resources = message.split("Resources:")[1]?.split(` -- `).slice(1); - return { - ...prefix, - ...suffix, - ...chainId ? { chainId: Number(chainId) } : {}, - ...expirationTime ? { expirationTime: new Date(expirationTime) } : {}, - ...issuedAt ? { issuedAt: new Date(issuedAt) } : {}, - ...notBefore ? { notBefore: new Date(notBefore) } : {}, - ...requestId ? { requestId } : {}, - ...resources ? { resources } : {}, - ...scheme ? { scheme } : {}, - ...statement ? { statement } : {} - }; -} -var prefixRegex = /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/; -var suffixRegex = /(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/; - -// ../viem/src/_esm/utils/siwe/validateSiweMessage.js -init_isAddress(); -init_isAddressEqual(); -function validateSiweMessage(parameters) { - const { address, domain, message, nonce, scheme, time = new Date } = parameters; - if (domain && message.domain !== domain) - return false; - if (nonce && message.nonce !== nonce) - return false; - if (scheme && message.scheme !== scheme) - return false; - if (message.expirationTime && time >= message.expirationTime) - return false; - if (message.notBefore && time < message.notBefore) - return false; - try { - if (!message.address) - return false; - if (!isAddress(message.address, { strict: false })) - return false; - if (address && !isAddressEqual(message.address, address)) - return false; - } catch { - return false; - } - return true; -} - -// ../viem/src/_esm/actions/siwe/verifySiweMessage.js -async function verifySiweMessage(client, parameters) { - const { address, domain, message, nonce, scheme, signature, time = new Date, ...callRequest } = parameters; - const parsed = parseSiweMessage(message); - if (!parsed.address) - return false; - const isValid = validateSiweMessage({ - address, + validateTypedData2({ domain, - message: parsed, - nonce, - scheme, - time + message, + primaryType, + types }); - if (!isValid) - return false; - const hash3 = hashMessage(message); - return verifyHash(client, { - address: parsed.address, - hash: hash3, - signature, - ...callRequest + const parts = ["0x1901"]; + if (domain) + parts.push(hashDomain({ + domain, + types + })); + if (primaryType !== "EIP712Domain") + parts.push(hashStruct2({ + data: message, + primaryType, + types + })); + return keccak256(concat(parts)); +} +function hashDomain({ domain, types }) { + return hashStruct2({ + data: domain, + primaryType: "EIP712Domain", + types }); } - -// ../viem/src/_esm/actions/token/approve.js -init_abis(); - -// ../viem/src/_esm/actions/token/internal.js -init_abis(); -init_isAddress(); -init_isAddressEqual(); -function toAmount(amount, decimals) { - return { amount, decimals, formatted: formatUnits(amount, decimals) }; +function hashStruct2({ data, primaryType, types }) { + const encoded = encodeData2({ + data, + primaryType, + types + }); + return keccak256(encoded); } -function toBaseUnits(amount, decimals) { - if (typeof amount === "bigint") - return amount; - const resolved = amount.decimals ?? decimals; - return parseUnits(amount.formatted, requireTokenDecimals(resolved)); +function encodeData2({ data, primaryType, types }) { + const encodedTypes = [{ type: "bytes32" }]; + const encodedValues = [hashType({ primaryType, types })]; + for (const field of types[primaryType]) { + const [type, value] = encodeField({ + types, + name: field.name, + type: field.type, + value: data[field.name] + }); + encodedTypes.push(type); + encodedValues.push(value); + } + return encodeAbiParameters(encodedTypes, encodedValues); } -function requireTokenDecimals(decimals) { - if (decimals === undefined) - throw new Error("Token decimals are required. Pass `amount.decimals` or select a declared token."); - return decimals; +function hashType({ primaryType, types }) { + const encodedHashType = toHex(encodeType({ primaryType, types })); + return keccak256(encodedHashType); } -function resolveAmountDecimals(amount, decimals) { - if (typeof amount === "bigint") - return decimals; - return amount.decimals ?? decimals; +function encodeType({ primaryType, types }) { + let result = ""; + const unsortedDeps = findTypeDependencies({ primaryType, types }); + unsortedDeps.delete(primaryType); + const deps = [primaryType, ...Array.from(unsortedDeps).sort()]; + for (const type of deps) { + result += `${type}(${types[type].map(({ name, type: t }) => `${t} ${name}`).join(",")})`; + } + return result; } -function resolveToken(client, parameters) { - const { decimals, token } = parameters; - const declared = findDeclaredToken(client, token); - if (declared) - return { - address: declared.address, - decimals: decimals ?? declared.decimals - }; - if (isAddress(token, { strict: false })) - return { - address: token, - decimals: decimals ?? inferDecimals(client, token) - }; - throw new Error(`Token "${token}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`); +function findTypeDependencies({ primaryType: primaryType_, types }, results = new Set) { + const match = primaryType_.match(/^\w*/u); + const primaryType = match?.[0]; + if (results.has(primaryType) || types[primaryType] === undefined) { + return results; + } + results.add(primaryType); + for (const field of types[primaryType]) { + findTypeDependencies({ primaryType: field.type, types }, results); + } + return results; } -function findDeclaredToken(client, token) { - const tokens = client.tokens; - const chainId = client.chain?.id; - if (!tokens || chainId === undefined) - return; - const bySymbol = findTokenBySymbol(tokens, token); - if (bySymbol) - return resolveTokenForChain(bySymbol, chainId); - if (isAddress(token, { strict: false })) - for (const token_ of tokens) { - const resolved = resolveTokenForChain(token_, chainId); - if (resolved && isAddressEqual(resolved.address, token)) - return resolved; - } - return; +function encodeField({ types, name, type, value }) { + if (types[type] !== undefined) { + return [ + { type: "bytes32" }, + keccak256(encodeData2({ data: value, primaryType: type, types })) + ]; + } + if (type === "bytes") + return [{ type: "bytes32" }, keccak256(value)]; + if (type === "string") + return [{ type: "bytes32" }, keccak256(toHex(value))]; + if (type.lastIndexOf("]") === type.length - 1) { + const parsedType = type.slice(0, type.lastIndexOf("[")); + const typeValuePairs = value.map((item) => encodeField({ + name, + type: parsedType, + types, + value: item + })); + return [ + { type: "bytes32" }, + keccak256(encodeAbiParameters(typeValuePairs.map(([t]) => t), typeValuePairs.map(([, v]) => v))) + ]; + } + return [{ type }, value]; } -function resolveTokenForChain(token, chainId) { - const address = token.addresses[chainId]; - if (!address) - return; - return { + +// ../viem/src/_esm/actions/public/verifyTypedData.js +async function verifyTypedData2(client, parameters) { + const { address, factory, factoryData, signature, message, primaryType, types, domain, ...callRequest } = parameters; + const hash3 = hashTypedData2({ message, primaryType, types, domain }); + return getAction(client, verifyHash2, "verifyHash")({ address, - currency: token.currency, - decimals: token.decimals, - name: token.name, - popular: token.popular, - symbol: token.symbol - }; + factory, + factoryData, + hash: hash3, + signature, + ...callRequest + }); } -function findTokenBySymbol(tokens, symbol) { - const lowerSymbol = symbol.toLowerCase(); - for (const token of tokens) { - if (token.symbol?.toLowerCase() === lowerSymbol) - return token; + +// ../viem/src/_esm/actions/public/waitForTransactionReceipt.js +init_transaction(); + +// ../viem/src/_esm/utils/observe.js +var listenersCache = /* @__PURE__ */ new Map; +var cleanupCache = /* @__PURE__ */ new Map; +var callbackCount = 0; +function observe(observerId, callbacks, fn) { + const callbackId = ++callbackCount; + const getListeners = () => listenersCache.get(observerId) || []; + const unsubscribe = () => { + const listeners2 = getListeners(); + const nextListeners = listeners2.filter((cb) => cb.id !== callbackId); + if (nextListeners.length === 0) { + listenersCache.delete(observerId); + cleanupCache.delete(observerId); + return; + } + listenersCache.set(observerId, nextListeners); + }; + const unwatch = () => { + const listeners2 = getListeners(); + if (!listeners2.some((cb) => cb.id === callbackId)) + return; + const cleanup2 = cleanupCache.get(observerId); + if (listeners2.length === 1 && cleanup2) { + const p = cleanup2(); + if (p instanceof Promise) + p.catch(() => {}); + } + unsubscribe(); + }; + const listeners = getListeners(); + listenersCache.set(observerId, [ + ...listeners, + { id: callbackId, fns: callbacks } + ]); + if (listeners && listeners.length > 0) + return unwatch; + const emit = {}; + for (const key in callbacks) { + emit[key] = (...args) => { + const listeners2 = getListeners(); + if (listeners2.length === 0) + return; + for (const listener of listeners2) + listener.fns[key]?.(...args); + }; } - return; + const cleanup = fn(emit); + if (typeof cleanup === "function") + cleanupCache.set(observerId, cleanup); + return unwatch; } -function inferDecimals(client, address) { - const tokens = client.tokens; - const chainId = client.chain?.id; - if (tokens && chainId !== undefined) - for (const token of tokens) { - const resolved = resolveTokenForChain(token, chainId); - if (resolved && isAddressEqual(resolved.address, address)) - return resolved.decimals; +// ../viem/src/_esm/utils/wait.js +async function wait(time, { signal } = {}) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(getAbortError(signal)); + return; } - return; -} -async function resolveTokenWithDecimals(client, parameters) { - const { address, decimals } = resolveToken(client, parameters); - if (decimals !== undefined) - return { address, decimals }; - return { - address, - decimals: await readContract(client, { - abi: erc20Abi, - address, - functionName: "decimals" - }) - }; + const cleanup = () => signal?.removeEventListener("abort", onAbort); + const timeout = setTimeout(() => { + cleanup(); + resolve(); + }, time); + const onAbort = () => { + clearTimeout(timeout); + cleanup(); + reject(getAbortError(signal)); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); } -function pickWriteParameters(parameters) { - const { account, chain, gas, maxFeePerGas, maxPriorityFeePerGas, nonce } = parameters; - return { account, chain, gas, maxFeePerGas, maxPriorityFeePerGas, nonce }; + +// ../viem/src/_esm/utils/promise/withRetry.js +function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry = () => true, signal } = {}) { + return new Promise((resolve, reject) => { + const attemptRetry = async ({ count = 0 } = {}) => { + if (signal?.aborted) { + reject(getAbortError(signal)); + return; + } + const retry = async ({ error }) => { + const delay = typeof delay_ === "function" ? delay_({ count, error }) : delay_; + if (delay) { + try { + await wait(delay, { signal }); + } catch (err) { + reject(err); + return; + } + } + return attemptRetry({ count: count + 1 }); + }; + try { + const data = await fn(); + resolve(data); + } catch (err) { + if (signal?.aborted) { + reject(getAbortError(signal)); + return; + } + if (isAbortError(err)) { + reject(err); + return; + } + if (count < retryCount && await shouldRetry({ count, error: err })) + return retry({ error: err }); + reject(err); + } + }; + attemptRetry().catch(reject); + }); } -function defineCall(call2) { - return { - ...call2, - data: encodeFunctionData(call2), - to: call2.address +// ../viem/src/_esm/actions/public/watchBlockNumber.js +init_fromHex(); + +// ../viem/src/_esm/utils/poll.js +function poll(fn, { emitOnBegin, initialWaitTime, interval }) { + let active = true; + const unwatch = () => active = false; + const watch = async () => { + let data; + if (emitOnBegin) + data = await fn({ unpoll: unwatch }); + const initialWait = await initialWaitTime?.(data) ?? interval; + await wait(initialWait); + const poll2 = async () => { + if (!active) + return; + await fn({ unpoll: unwatch }); + await wait(interval); + poll2(); + }; + poll2(); }; + watch(); + return unwatch; } - -// ../viem/src/_esm/actions/token/approve.js -async function approve(client, parameters) { - return approve.inner(writeContract, client, parameters); -} -(function(approve2) { - async function inner(action, client, parameters) { - return await action(client, { - ...parameters, - ...approve2.call(client, parameters) - }); - } - approve2.inner = inner; - function call2(client, parameters) { - return defineCall(getCall(client, parameters)); - } - approve2.call = call2; - async function estimateGas2(client, parameters) { - return estimateContractGas(client, { - ...pickWriteParameters(parameters), - ...approve2.call(client, parameters) - }); - } - approve2.estimateGas = estimateGas2; - async function simulate(client, parameters) { - return simulateContract(client, { - ...pickWriteParameters(parameters), - ...approve2.call(client, parameters) - }); - } - approve2.simulate = simulate; - function extractEvent(logs) { - const [log] = parseEventLogs({ - abi: erc20Abi, - logs, - eventName: "Approval", - strict: true +// ../viem/src/_esm/actions/public/watchBlockNumber.js +function watchBlockNumber(client, { emitOnBegin = false, emitMissed = false, onBlockNumber, onError, poll: poll_, pollingInterval = client.pollingInterval }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (client.transport.type === "webSocket" || client.transport.type === "ipc") + return false; + if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc")) + return false; + return true; + })(); + let prevBlockNumber; + const pollBlockNumber = () => { + const observerId = stringify([ + "watchBlockNumber", + client.uid, + emitOnBegin, + emitMissed, + pollingInterval + ]); + return observe(observerId, { onBlockNumber, onError }, (emit) => poll(async () => { + try { + const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({ cacheTime: 0 }); + if (prevBlockNumber !== undefined) { + if (blockNumber === prevBlockNumber) + return; + if (blockNumber - prevBlockNumber > 1 && emitMissed) { + for (let i = prevBlockNumber + 1n;i < blockNumber; i++) { + emit.onBlockNumber(i, prevBlockNumber); + prevBlockNumber = i; + } + } + } + if (prevBlockNumber === undefined || blockNumber > prevBlockNumber) { + emit.onBlockNumber(blockNumber, prevBlockNumber); + prevBlockNumber = blockNumber; + } + } catch (err) { + emit.onError?.(err); + } + }, { + emitOnBegin, + interval: pollingInterval + })); + }; + const subscribeBlockNumber = () => { + const observerId = stringify([ + "watchBlockNumber", + client.uid, + emitOnBegin, + emitMissed + ]); + return observe(observerId, { onBlockNumber, onError }, (emit) => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["newHeads"], + onData(data) { + if (!active) + return; + const blockNumber = hexToBigInt(data.result?.number); + emit.onBlockNumber(blockNumber, prevBlockNumber); + prevBlockNumber = blockNumber; + }, + onError(error) { + emit.onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); }); - if (!log) - throw new Error("`Approval` event not found."); - return log; - } - approve2.extractEvent = extractEvent; -})(approve || (approve = {})); -function getCall(client, parameters) { - const { amount, spender, token } = parameters; - const { address, decimals } = resolveToken(client, { token }); - return { - abi: erc20Abi, - address, - args: [spender, toBaseUnits(amount, decimals)], - functionName: "approve" }; -} -// ../viem/src/_esm/actions/wallet/sendTransactionSync.js -init_base(); -init_transaction(); -init_transactionRequest(); -init_lru(); -init_assertRequest(); - -// ../viem/src/_esm/actions/wallet/sendRawTransactionSync.js -init_transaction(); -async function sendRawTransactionSync(client, { serializedTransaction, throwOnReceiptRevert, timeout }) { - const receipt = await client.request({ - method: "eth_sendRawTransactionSync", - params: timeout ? [serializedTransaction, timeout] : [serializedTransaction] - }, { retryCount: 0 }); - const format2 = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt; - const formatted = format2(receipt); - if (formatted.status === "reverted" && throwOnReceiptRevert) - throw new TransactionReceiptRevertedError({ receipt: formatted }); - return formatted; + return enablePolling ? pollBlockNumber() : subscribeBlockNumber(); } -// ../viem/src/_esm/actions/wallet/sendTransactionSync.js -var supportsWalletNamespace2 = new LruMap(128); -async function sendTransactionSync(client, parameters) { - const { account: account_ = client.account, assertChainId = true, chain = client.chain, accessList, authorizationList, blobs, data, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, pollingInterval, throwOnReceiptRevert, type, value, ...rest } = parameters; - const timeout = parameters.timeout ?? Math.max((chain?.blockTime ?? 0) * 3, 5000); - if (typeof account_ === "undefined") - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/sendTransactionSync" +// ../viem/src/_esm/actions/public/waitForTransactionReceipt.js +async function waitForTransactionReceipt(client, parameters) { + const { + checkReplacement = client.chain?.supportsTransactionReplacementDetection ?? true, + confirmations = 1, + hash: hash3, + onReplaced, + retryCount = 6, + retryDelay = ({ count }) => ~~(1 << count) * 200, + timeout = 180000 + } = parameters; + const observerId = stringify(["waitForTransactionReceipt", client.uid, hash3]); + const pollingInterval = (() => { + if (parameters.pollingInterval) + return parameters.pollingInterval; + if (client.chain?.experimental_preconfirmationTime) + return client.chain.experimental_preconfirmationTime; + return client.pollingInterval; + })(); + let transaction; + let replacedTransaction; + let receipt; + let retrying = false; + let _unobserve; + let _unwatch; + const { promise, resolve, reject } = withResolvers(); + const timer = timeout ? setTimeout(() => { + _unwatch?.(); + _unobserve?.(); + reject(new WaitForTransactionReceiptTimeoutError({ hash: hash3 })); + }, timeout) : undefined; + _unobserve = observe(observerId, { onReplaced, resolve, reject }, async (emit) => { + receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash3 }).catch(() => { + return; }); - const account = account_ ? parseAccount(account_) : null; - let nonceManagerParameters; - try { - assertRequest(parameters); - const to = await (async () => { - if (parameters.to) - return parameters.to; - if (parameters.to === null) - return; - if (authorizationList && authorizationList.length > 0) - return await recoverAuthorizationAddress({ - authorization: authorizationList[0] - }).catch(() => { - throw new BaseError2("`to` is required. Could not infer from `authorizationList`."); - }); + if (receipt && confirmations <= 1) { + clearTimeout(timer); + emit.resolve(receipt); + _unobserve?.(); return; - })(); - if (account?.type === "json-rpc" || account === null) { - let chainId; - if (chain !== null) { - chainId = await getAction(client, getChainId, "getChainId")({}); - if (assertChainId) - assertCurrentChain({ - currentChainId: chainId, - chain - }); - } - const chainFormat = client.chain?.formatters?.transactionRequest?.format; - const format2 = chainFormat || formatTransactionRequest; - const request = format2({ - ...extract(rest, { format: chainFormat }), - accessList, - account, - authorizationList, - blobs, - chainId, - data: dataSuffix ? concat([data ?? "0x", dataSuffix]) : data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - to, - type, - value - }, "sendTransaction"); - const isWalletNamespaceSupported = supportsWalletNamespace2.get(client.uid); - const method = isWalletNamespaceSupported ? "wallet_sendTransaction" : "eth_sendTransaction"; - const hash3 = await (async () => { - try { - return await client.request({ - method, - params: [request] - }, { retryCount: 0 }); - } catch (e) { - if (isWalletNamespaceSupported === false) - throw e; - const error = e; - if (error.name === "InvalidInputRpcError" || error.name === "InvalidParamsRpcError" || error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError") { - return await client.request({ - method: "wallet_sendTransaction", - params: [request] - }, { retryCount: 0 }).then((hash4) => { - supportsWalletNamespace2.set(client.uid, true); - return hash4; - }).catch((e2) => { - const walletNamespaceError = e2; - if (walletNamespaceError.name === "MethodNotFoundRpcError" || walletNamespaceError.name === "MethodNotSupportedRpcError") { - supportsWalletNamespace2.set(client.uid, false); - throw error; - } - throw walletNamespaceError; + } + _unwatch = getAction(client, watchBlockNumber, "watchBlockNumber")({ + emitMissed: true, + emitOnBegin: true, + poll: true, + pollingInterval, + async onBlockNumber(blockNumber_) { + const done = (fn) => { + clearTimeout(timer); + _unwatch?.(); + fn(); + _unobserve?.(); + }; + let blockNumber = blockNumber_; + if (retrying) + return; + try { + if (receipt) { + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + done(() => emit.resolve(receipt)); + return; + } + if (checkReplacement && !transaction) { + retrying = true; + await withRetry(async () => { + transaction = await getAction(client, getTransaction, "getTransaction")({ hash: hash3 }); + if (transaction.blockNumber) + blockNumber = transaction.blockNumber; + }, { + delay: retryDelay, + retryCount }); + retrying = false; } - throw error; - } - })(); - const receipt = await getAction(client, waitForTransactionReceipt, "waitForTransactionReceipt")({ - checkReplacement: false, - hash: hash3, - pollingInterval, - timeout - }); - if (throwOnReceiptRevert && receipt.status === "reverted") - throw new TransactionReceiptRevertedError({ receipt }); - return receipt; - } - if (account?.type === "local") { - const nonceManager2 = (() => { - if (!account.nonceManager || typeof nonce !== "undefined") - return account.nonceManager; - const nonceManager3 = account.nonceManager; - return { - consume(parameters2) { - nonceManagerParameters = { - address: parameters2.address, - chainId: parameters2.chainId - }; - return nonceManager3.consume(parameters2); - }, - get(parameters2) { - return nonceManager3.get(parameters2); - }, - increment(parameters2) { - return nonceManager3.increment(parameters2); - }, - reset(parameters2) { - return nonceManager3.reset(parameters2); + receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ hash: hash3 }); + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + done(() => emit.resolve(receipt)); + } catch (err) { + if (err instanceof TransactionNotFoundError || err instanceof TransactionReceiptNotFoundError) { + if (!transaction) { + retrying = false; + return; + } + try { + replacedTransaction = transaction; + retrying = true; + const block = await withRetry(() => getAction(client, getBlock, "getBlock")({ + blockNumber, + includeTransactions: true + }), { + delay: retryDelay, + retryCount, + shouldRetry: ({ error }) => error instanceof BlockNotFoundError + }); + retrying = false; + const replacementTransaction = block.transactions.find(({ from: from15, nonce }) => from15 === replacedTransaction.from && nonce === replacedTransaction.nonce); + if (!replacementTransaction || !replacementTransaction.hash) + return; + receipt = await getAction(client, getTransactionReceipt, "getTransactionReceipt")({ + hash: replacementTransaction.hash + }); + if (confirmations > 1 && (!receipt.blockNumber || blockNumber - receipt.blockNumber + 1n < confirmations)) + return; + let reason = "replaced"; + if (replacementTransaction.to === replacedTransaction.to && replacementTransaction.value === replacedTransaction.value && replacementTransaction.input === replacedTransaction.input) { + reason = "repriced"; + } else if (replacementTransaction.from === replacementTransaction.to && replacementTransaction.value === 0n) { + reason = "cancelled"; + } + done(() => { + emit.onReplaced?.({ + reason, + replacedTransaction, + transaction: replacementTransaction, + transactionReceipt: receipt + }); + emit.resolve(receipt); + }); + } catch (err_) { + done(() => emit.reject(err_)); + } + } else { + done(() => emit.reject(err)); } - }; - })(); - const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({ - account, - accessList, - authorizationList, - blobs, - chain, - data: dataSuffix ? concat([data ?? "0x", dataSuffix]) : data, - gas, - gasPrice, - maxFeePerBlobGas, - maxFeePerGas, - maxPriorityFeePerGas, - nonce, - nonceManager: nonceManager2, - parameters: [...defaultParameters, "sidecars"], - type, - value, - ...rest, - to - }); - const serializer = chain?.serializers?.transaction; - const serializedTransaction = await account.signTransaction(request, { - serializer - }); - return await getAction(client, sendRawTransactionSync, "sendRawTransactionSync")({ - serializedTransaction, - throwOnReceiptRevert, - timeout: parameters.timeout - }); - } - if (account?.type === "smart") - throw new AccountTypeNotSupportedError({ - metaMessages: [ - "Consider using the `sendUserOperation` Action instead." - ], - docsPath: "/docs/actions/bundler/sendUserOperation", - type: "smart" - }); - throw new AccountTypeNotSupportedError({ - docsPath: "/docs/actions/wallet/sendTransactionSync", - type: account?.type - }); - } catch (err) { - if (err instanceof AccountTypeNotSupportedError) - throw err; - if (nonceManagerParameters && !(err instanceof TransactionReceiptRevertedError)) - account?.nonceManager?.reset(nonceManagerParameters); - throw getTransactionError(err, { - ...parameters, - account, - chain: parameters.chain || undefined + } + } }); - } -} - -// ../viem/src/_esm/actions/wallet/writeContractSync.js -async function writeContractSync(client, parameters) { - return writeContract.internal(client, sendTransactionSync, "sendTransactionSync", parameters); + }); + return promise; } -// ../viem/src/_esm/actions/token/approveSync.js -async function approveSync(client, parameters) { - const { amount, token, throwOnReceiptRevert = true } = parameters; - const { decimals } = resolveToken(client, { token }); - const resolved = resolveAmountDecimals(amount, decimals); - const receipt = await approve.inner(writeContractSync, client, { - ...parameters, - throwOnReceiptRevert +// ../viem/src/_esm/actions/public/watchBlockHeaders.js +var blockFields = [ + "size", + "totalDifficulty", + "transactions", + "uncles", + "withdrawals" +]; +function watchBlockHeaders(client, { onBlockHeader, onError }) { + let prevBlockHeader; + const observerId = stringify(["watchBlockHeaders", client.uid]); + return observe(observerId, { onBlockHeader, onError }, (emit) => { + let active = true; + let subscribed = false; + let unsubscribe = () => active = false; + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["newHeads"], + onData(data) { + if (!active) + return; + const blockHeader = (client.chain?.formatters?.block?.format || formatBlock)(data.result, "watchBlockHeaders"); + for (const field of blockFields) + delete blockHeader[field]; + emit.onBlockHeader(blockHeader, prevBlockHeader); + prevBlockHeader = blockHeader; + }, + onError(error) { + if (subscribed) + emit.onError?.(error); + } + }); + subscribed = true; + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + emit.onError?.(err); + } + })(); + return () => unsubscribe(); }); - const { args } = approve.extractEvent(receipt.logs); - return { - ...args, - ...resolved === undefined ? {} : { decimals: resolved, formatted: formatUnits(args.value, resolved) }, - receipt - }; -} -// ../viem/src/_esm/actions/token/getAllowance.js -init_abis(); -async function getAllowance(client, parameters) { - const { account, decimals, spender, token, ...rest } = parameters; - const [amount, { decimals: resolved }] = await Promise.all([ - readContract(client, { - ...rest, - ...getAllowance.call(client, { account, spender, token }) - }), - resolveTokenWithDecimals(client, { - decimals, - token - }) - ]); - return toAmount(amount, resolved); -} -(function(getAllowance2) { - function call2(client, args) { - return defineCall({ - address: resolveToken(client, args).address, - abi: erc20Abi, - functionName: "allowance", - args: [args.account, args.spender] - }); - } - getAllowance2.call = call2; -})(getAllowance || (getAllowance = {})); -// ../viem/src/_esm/actions/token/getBalance.js -init_abis(); -async function getBalance2(client, parameters) { - const { account: account_ = client.account, decimals, token, ...rest } = parameters; - if (!account_) - throw new AccountNotFoundError; - const account = parseAccount(account_).address; - const [amount, { decimals: resolved }] = await Promise.all([ - readContract(client, { - ...rest, - ...getBalance2.call(client, { account, token }) - }), - resolveTokenWithDecimals(client, { - decimals, - token - }) - ]); - return toAmount(amount, resolved); } -(function(getBalance3) { - function call2(client, args) { - const account_ = args.account ?? client.account; - if (!account_) - throw new AccountNotFoundError; - const account = parseAccount(account_).address; - return defineCall({ - address: resolveToken(client, args).address, - abi: erc20Abi, - functionName: "balanceOf", - args: [account] - }); - } - getBalance3.call = call2; -})(getBalance2 || (getBalance2 = {})); -// ../viem/src/_esm/actions/token/getMetadata.js -init_abis(); -async function getMetadata(client, parameters) { - const { token, ...rest } = parameters; - const { address } = resolveToken(client, { token }); - const declared = findDeclaredToken(client, token); - const [decimals_, name, symbol] = await Promise.all([ - declared?.decimals ?? readContract(client, { - ...rest, - abi: erc20Abi, - address, - functionName: "decimals" - }), - declared?.name ?? readContract(client, { - ...rest, - abi: erc20Abi, - address, - functionName: "name" - }), - declared?.symbol ?? readContract(client, { - ...rest, - abi: erc20Abi, - address, - functionName: "symbol" - }) - ]); - return { - decimals: decimals_, - name, - symbol +// ../viem/src/_esm/actions/public/watchBlocks.js +function watchBlocks(client, { blockTag = client.experimental_blockTag ?? "latest", emitMissed = false, emitOnBegin = false, onBlock, onError, includeTransactions: includeTransactions_, poll: poll_, pollingInterval = client.pollingInterval }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (client.transport.type === "webSocket" || client.transport.type === "ipc") + return false; + if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc")) + return false; + return true; + })(); + const includeTransactions = includeTransactions_ ?? false; + let prevBlock; + const pollBlocks = () => { + const observerId = stringify([ + "watchBlocks", + client.uid, + blockTag, + emitMissed, + emitOnBegin, + includeTransactions, + pollingInterval + ]); + return observe(observerId, { onBlock, onError }, (emit) => poll(async () => { + try { + const block = await getAction(client, getBlock, "getBlock")({ + blockTag, + includeTransactions + }); + if (block.number !== null && prevBlock?.number != null) { + if (block.number === prevBlock.number) + return; + if (block.number - prevBlock.number > 1 && emitMissed) { + for (let i = prevBlock?.number + 1n;i < block.number; i++) { + const block2 = await getAction(client, getBlock, "getBlock")({ + blockNumber: i, + includeTransactions + }); + emit.onBlock(block2, prevBlock); + prevBlock = block2; + } + } + } + if (prevBlock?.number == null || blockTag === "pending" && block?.number == null || block.number !== null && block.number > prevBlock.number) { + emit.onBlock(block, prevBlock); + prevBlock = block; + } + } catch (err) { + emit.onError?.(err); + } + }, { + emitOnBegin, + interval: pollingInterval + })); }; + const subscribeBlocks = () => { + let active = true; + let emitFetched = true; + let unsubscribe = () => active = false; + (async () => { + try { + if (emitOnBegin) { + getAction(client, getBlock, "getBlock")({ + blockTag, + includeTransactions + }).then((block) => { + if (!active) + return; + if (!emitFetched) + return; + onBlock(block, undefined); + emitFetched = false; + }).catch(onError); + } + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["newHeads"], + async onData(data) { + if (!active) + return; + const block = await getAction(client, getBlock, "getBlock")({ + blockNumber: data.result?.number, + includeTransactions + }).catch(() => {}); + if (!active) + return; + onBlock(block, prevBlock); + emitFetched = false; + prevBlock = block; + }, + onError(error) { + onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollBlocks() : subscribeBlocks(); } -// ../viem/src/_esm/actions/token/getTotalSupply.js -init_abis(); -async function getTotalSupply(client, parameters) { - const { decimals, token, ...rest } = parameters; - const [amount, { decimals: resolved }] = await Promise.all([ - readContract(client, { - ...rest, - ...getTotalSupply.call(client, { token }) - }), - resolveTokenWithDecimals(client, { - decimals, - token - }) - ]); - return toAmount(amount, resolved); -} -(function(getTotalSupply2) { - function call2(client, args) { - return defineCall({ - address: resolveToken(client, args).address, - abi: erc20Abi, - args: [], - functionName: "totalSupply" - }); - } - getTotalSupply2.call = call2; -})(getTotalSupply || (getTotalSupply = {})); -// ../viem/src/_esm/actions/token/transfer.js -init_abis(); -async function transfer(client, parameters) { - return transfer.inner(writeContract, client, parameters); -} -(function(transfer2) { - async function inner(action, client, parameters) { - return await action(client, { - ...parameters, - ...transfer2.call(client, parameters) - }); - } - transfer2.inner = inner; - function call2(client, parameters) { - return defineCall(getCall2(client, parameters)); - } - transfer2.call = call2; - async function estimateGas2(client, parameters) { - return estimateContractGas(client, { - ...pickWriteParameters(parameters), - ...transfer2.call(client, parameters) - }); - } - transfer2.estimateGas = estimateGas2; - async function simulate(client, parameters) { - return simulateContract(client, { - ...pickWriteParameters(parameters), - ...transfer2.call(client, parameters) - }); - } - transfer2.simulate = simulate; - function extractEvent(logs) { - const [log] = parseEventLogs({ - abi: erc20Abi, - logs, - eventName: "Transfer", - strict: true - }); - if (!log) - throw new Error("`Transfer` event not found."); - return log; - } - transfer2.extractEvent = extractEvent; -})(transfer || (transfer = {})); -function getCall2(client, parameters) { - const { amount, from: from15, to, token } = parameters; - const { address, decimals } = resolveToken(client, { token }); - const value = toBaseUnits(amount, decimals); - if (from15) - return { - abi: erc20Abi, + +// ../viem/src/_esm/actions/public/watchContractEvent.js +init_abi(); +init_rpc(); +function watchContractEvent(client, parameters) { + const { abi: abi2, address, args, batch = true, eventName, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ } = parameters; + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (typeof fromBlock === "bigint") + return true; + if (client.transport.type === "webSocket" || client.transport.type === "ipc") + return false; + if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc")) + return false; + return true; + })(); + const pollContractEvent = () => { + const strict = strict_ ?? false; + const observerId = stringify([ + "watchContractEvent", address, - args: [from15, to, value], - functionName: "transferFrom" - }; - return { - abi: erc20Abi, - address, - args: [to, value], - functionName: "transfer" + args, + batch, + client.uid, + eventName, + pollingInterval, + strict, + fromBlock + ]); + return observe(observerId, { onLogs, onError }, (emit) => { + let previousBlockNumber; + if (fromBlock !== undefined) + previousBlockNumber = fromBlock - 1n; + let filter; + let initialized = false; + const unwatch = poll(async () => { + if (!initialized) { + try { + filter = await getAction(client, createContractEventFilter, "createContractEventFilter")({ + abi: abi2, + address, + args, + eventName, + strict, + fromBlock + }); + } catch {} + initialized = true; + return; + } + try { + let logs; + if (filter) { + logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter }); + } else { + const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); + if (previousBlockNumber && previousBlockNumber < blockNumber) { + logs = await getAction(client, getContractEvents, "getContractEvents")({ + abi: abi2, + address, + args, + eventName, + fromBlock: previousBlockNumber + 1n, + toBlock: blockNumber, + strict + }); + } else { + logs = []; + } + previousBlockNumber = blockNumber; + } + if (logs.length === 0) + return; + if (batch) + emit.onLogs(logs); + else + for (const log of logs) + emit.onLogs([log]); + } catch (err) { + if (filter && err instanceof InvalidInputRpcError) + initialized = false; + emit.onError?.(err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter) + await getAction(client, uninstallFilter, "uninstallFilter")({ filter }); + unwatch(); + }; + }); }; -} -// ../viem/src/_esm/actions/token/transferSync.js -async function transferSync(client, parameters) { - const { amount, token, throwOnReceiptRevert = true } = parameters; - const { decimals } = resolveToken(client, { token }); - const resolved = resolveAmountDecimals(amount, decimals); - const receipt = await transfer.inner(writeContractSync, client, { - ...parameters, - throwOnReceiptRevert - }); - const { args } = transfer.extractEvent(receipt.logs); - return { - ...args, - ...resolved === undefined ? {} : { decimals: resolved, formatted: formatUnits(args.value, resolved) }, - receipt + const subscribeContractEvent = () => { + const strict = strict_ ?? false; + const observerId = stringify([ + "watchContractEvent", + address, + args, + batch, + client.uid, + eventName, + pollingInterval, + strict + ]); + let active = true; + let unsubscribe = () => active = false; + return observe(observerId, { onLogs, onError }, (emit) => { + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const topics = eventName ? encodeEventTopics({ + abi: abi2, + eventName, + args + }) : []; + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["logs", { address, topics }], + onData(data) { + if (!active) + return; + const log = data.result; + try { + const { eventName: eventName2, args: args2 } = decodeEventLog({ + abi: abi2, + data: log.data, + topics: log.topics, + strict: strict_ + }); + const formatted = formatLog(log, { + args: args2, + eventName: eventName2 + }); + emit.onLogs([formatted]); + } catch (err) { + let eventName2; + let isUnnamed; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict_) + return; + eventName2 = err.abiItem.name; + isUnnamed = err.abiItem.inputs?.some((x) => !(("name" in x) && x.name)); + } + const formatted = formatLog(log, { + args: isUnnamed ? [] : {}, + eventName: eventName2 + }); + emit.onLogs([formatted]); + } + }, + onError(error) { + emit.onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }); }; -} -// ../viem/src/_esm/clients/decorators/public.js -function publicActions(client) { - return { - call: (args) => call(client, args), - createAccessList: (args) => createAccessList(client, args), - createBlockFilter: () => createBlockFilter(client), - createContractEventFilter: (args) => createContractEventFilter(client, args), - createEventFilter: (args) => createEventFilter(client, args), - createPendingTransactionFilter: () => createPendingTransactionFilter(client), - estimateContractGas: (args) => estimateContractGas(client, args), - estimateGas: (args) => estimateGas(client, args), - getBalance: (args) => getBalance(client, args), - getBlobBaseFee: () => getBlobBaseFee(client), - getBlock: (args) => getBlock(client, args), - getBlockNumber: (args) => getBlockNumber(client, args), - getBlockReceipts: (args) => getBlockReceipts(client, args), - getBlockTransactionCount: (args) => getBlockTransactionCount(client, args), - getBytecode: (args) => getCode(client, args), - getChainId: () => getChainId(client), - getCode: (args) => getCode(client, args), - getContractEvents: (args) => getContractEvents(client, args), - getDelegation: (args) => getDelegation(client, args), - getEip712Domain: (args) => getEip712Domain(client, args), - getEnsAddress: (args) => getEnsAddress(client, args), - getEnsAvatar: (args) => getEnsAvatar(client, args), - getEnsName: (args) => getEnsName(client, args), - getEnsResolver: (args) => getEnsResolver(client, args), - getEnsText: (args) => getEnsText(client, args), - getFeeHistory: (args) => getFeeHistory(client, args), - estimateFeesPerGas: (args) => estimateFeesPerGas(client, args), - getFilterChanges: (args) => getFilterChanges(client, args), - getFilterLogs: (args) => getFilterLogs(client, args), - getGasPrice: () => getGasPrice(client), - getLogs: (args) => getLogs(client, args), - getProof: (args) => getProof(client, args), - estimateMaxPriorityFeePerGas: (args) => estimateMaxPriorityFeePerGas(client, args), - fillTransaction: (args) => fillTransaction(client, args), - getRawTransaction: (args) => getRawTransaction(client, args), - getStorageAt: (args) => getStorageAt(client, args), - getTransaction: (args) => getTransaction(client, args), - getTransactionConfirmations: (args) => getTransactionConfirmations(client, args), - getTransactionCount: (args) => getTransactionCount(client, args), - getTransactionReceipt: (args) => getTransactionReceipt(client, args), - multicall: (args) => multicall(client, args), - prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), - readContract: (args) => readContract(client, args), - sendRawTransaction: (args) => sendRawTransaction(client, args), - sendRawTransactionSync: (args) => sendRawTransactionSync(client, args), - simulate: (args) => simulateBlocks(client, args), - simulateBlocks: (args) => simulateBlocks(client, args), - simulateCalls: (args) => simulateCalls(client, args), - simulateContract: (args) => simulateContract(client, args), - verifyHash: (args) => verifyHash(client, args), - verifyMessage: (args) => verifyMessage(client, args), - verifySiweMessage: (args) => verifySiweMessage(client, args), - verifyTypedData: (args) => verifyTypedData(client, args), - uninstallFilter: (args) => uninstallFilter(client, args), - waitForTransactionReceipt: (args) => waitForTransactionReceipt(client, args), - watchBlockHeaders: (args) => watchBlockHeaders(client, args), - watchBlocks: (args) => watchBlocks(client, args), - watchBlockNumber: (args) => watchBlockNumber(client, args), - watchContractEvent: (args) => watchContractEvent(client, args), - watchEvent: (args) => watchEvent(client, args), - watchPendingTransactions: (args) => watchPendingTransactions(client, args), - token: bindPublicToken(client) - }; -} -function bindPublicToken(client) { - return { - getAllowance: bindActionDecorators(client, getAllowance), - getBalance: bindActionDecorators(client, getBalance2), - getMetadata: bindActionDecorators(client, getMetadata), - getTotalSupply: bindActionDecorators(client, getTotalSupply) - }; -} - -// ../viem/src/_esm/clients/createPublicClient.js -function createPublicClient(parameters) { - const { key = "public", name = "Public Client" } = parameters; - const client = createClient({ - ...parameters, - key, - name, - type: "publicClient" - }); - return client.extend(publicActions); -} -// ../viem/src/_esm/actions/wallet/addChain.js -init_toHex(); -async function addChain(client, { chain }) { - const { id, name, nativeCurrency, rpcUrls, blockExplorers } = chain; - await client.request({ - method: "wallet_addEthereumChain", - params: [ - { - chainId: numberToHex(id), - chainName: name, - nativeCurrency, - rpcUrls: rpcUrls.default.http, - blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url }) => url) : undefined - } - ] - }, { dedupe: true, retryCount: 0 }); -} - -// ../viem/src/_esm/actions/wallet/deployContract.js -init_encodeDeployData(); -function deployContract(walletClient, parameters) { - const { abi: abi2, args, bytecode, ...request } = parameters; - const calldata = encodeDeployData({ abi: abi2, args, bytecode }); - return sendTransaction(walletClient, { - ...request, - ...request.authorizationList ? { to: null } : {}, - data: calldata - }); -} - -// ../viem/src/_esm/actions/wallet/getAddresses.js -init_getAddress(); -async function getAddresses(client) { - if (client.account?.type === "local") - return [client.account.address]; - const addresses = await client.request({ method: "eth_accounts" }, { dedupe: true }); - return addresses.map((address) => checksumAddress(address)); -} - -// ../viem/src/_esm/actions/wallet/getCapabilities.js -init_toHex(); -async function getCapabilities(client, parameters = {}) { - const { account = client.account, chainId } = parameters; - const account_ = account ? parseAccount(account) : undefined; - const params = chainId ? [account_?.address, [numberToHex(chainId)]] : [account_?.address]; - const capabilities_raw = await client.request({ - method: "wallet_getCapabilities", - params - }); - const capabilities = {}; - for (const [chainId2, capabilities_] of Object.entries(capabilities_raw)) { - capabilities[Number(chainId2)] = {}; - for (let [key, value] of Object.entries(capabilities_)) { - if (key === "addSubAccount") - key = "unstable_addSubAccount"; - capabilities[Number(chainId2)][key] = value; - } - } - return typeof chainId === "number" ? capabilities[chainId] : capabilities; + return enablePolling ? pollContractEvent() : subscribeContractEvent(); } -// ../viem/src/_esm/actions/wallet/getPermissions.js -async function getPermissions(client) { - const permissions = await client.request({ method: "wallet_getPermissions" }, { dedupe: true }); - return permissions; -} -// ../viem/src/_esm/actions/wallet/prepareAuthorization.js -init_isAddressEqual(); -async function prepareAuthorization(client, parameters) { - const { account: account_ = client.account, chainId, nonce } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/eip7702/prepareAuthorization" - }); - const account = parseAccount(account_); - const executor = (() => { - if (!parameters.executor) - return; - if (parameters.executor === "self") - return parameters.executor; - return parseAccount(parameters.executor); +// ../viem/src/_esm/actions/public/watchEvent.js +init_abi(); +init_rpc(); +function watchEvent(client, { address, args, batch = true, event, events, fromBlock, onError, onLogs, poll: poll_, pollingInterval = client.pollingInterval, strict: strict_ }) { + const enablePolling = (() => { + if (typeof poll_ !== "undefined") + return poll_; + if (typeof fromBlock === "bigint") + return true; + if (client.transport.type === "webSocket" || client.transport.type === "ipc") + return false; + if (client.transport.type === "fallback" && (client.transport.transports[0].config.type === "webSocket" || client.transport.transports[0].config.type === "ipc")) + return false; + return true; })(); - const authorization = { - address: parameters.contractAddress ?? parameters.address, - chainId, - nonce - }; - if (typeof authorization.chainId === "undefined") - authorization.chainId = client.chain?.id ?? await getAction(client, getChainId, "getChainId")({}); - if (typeof authorization.nonce === "undefined") { - authorization.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ - address: account.address, - blockTag: "pending" + const strict = strict_ ?? false; + const pollEvent = () => { + const observerId = stringify([ + "watchEvent", + address, + args, + batch, + client.uid, + event, + pollingInterval, + fromBlock + ]); + return observe(observerId, { onLogs, onError }, (emit) => { + let previousBlockNumber; + if (fromBlock !== undefined) + previousBlockNumber = fromBlock - 1n; + let filter; + let initialized = false; + const unwatch = poll(async () => { + if (!initialized) { + try { + filter = await getAction(client, createEventFilter, "createEventFilter")({ + address, + args, + event, + events, + strict, + fromBlock + }); + } catch {} + initialized = true; + return; + } + try { + let logs; + if (filter) { + logs = await getAction(client, getFilterChanges, "getFilterChanges")({ filter }); + } else { + const blockNumber = await getAction(client, getBlockNumber, "getBlockNumber")({}); + if (previousBlockNumber && previousBlockNumber !== blockNumber) { + logs = await getAction(client, getLogs, "getLogs")({ + address, + args, + event, + events, + fromBlock: previousBlockNumber + 1n, + toBlock: blockNumber + }); + } else { + logs = []; + } + previousBlockNumber = blockNumber; + } + if (logs.length === 0) + return; + if (batch) + emit.onLogs(logs); + else + for (const log of logs) + emit.onLogs([log]); + } catch (err) { + if (filter && err instanceof InvalidInputRpcError) + initialized = false; + emit.onError?.(err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter) + await getAction(client, uninstallFilter, "uninstallFilter")({ filter }); + unwatch(); + }; }); - if (executor === "self" || executor?.address && isAddressEqual(executor.address, account.address)) - authorization.nonce += 1; - } - return authorization; -} - -// ../viem/src/_esm/actions/wallet/requestAddresses.js -init_getAddress(); -async function requestAddresses(client) { - const addresses = await client.request({ method: "eth_requestAccounts" }, { dedupe: true, retryCount: 0 }); - return addresses.map((address) => getAddress(address)); -} - -// ../viem/src/_esm/actions/wallet/requestPermissions.js -async function requestPermissions(client, permissions) { - return client.request({ - method: "wallet_requestPermissions", - params: [permissions] - }, { retryCount: 0 }); -} - -// ../viem/src/_esm/actions/wallet/sendCallsSync.js -async function sendCallsSync(client, parameters) { - const { chain = client.chain } = parameters; - const timeout = parameters.timeout ?? Math.max((chain?.blockTime ?? 0) * 3, 5000); - const result = await getAction(client, sendCalls, "sendCalls")(parameters); - const status = await getAction(client, waitForCallsStatus, "waitForCallsStatus")({ - ...parameters, - id: result.id, - timeout - }); - return status; -} - -// ../viem/src/_esm/actions/wallet/showCallsStatus.js -async function showCallsStatus(client, parameters) { - const { id } = parameters; - await client.request({ - method: "wallet_showCallsStatus", - params: [id] - }); - return; -} -// ../viem/src/_esm/actions/wallet/signAuthorization.js -async function signAuthorization(client, parameters) { - const { account: account_ = client.account } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/eip7702/signAuthorization" - }); - const account = parseAccount(account_); - if (!account.signAuthorization) - throw new AccountTypeNotSupportedError({ - docsPath: "/docs/eip7702/signAuthorization", - metaMessages: [ - "The `signAuthorization` Action does not support JSON-RPC Accounts." - ], - type: account.type - }); - const authorization = await prepareAuthorization(client, parameters); - return account.signAuthorization(authorization); -} -// ../viem/src/_esm/actions/wallet/signMessage.js -init_toHex(); -async function signMessage(client, { account: account_ = client.account, message }) { - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/signMessage" - }); - const account = parseAccount(account_); - if (account.signMessage) - return account.signMessage({ message }); - const message_ = (() => { - if (typeof message === "string") - return stringToHex(message); - if (message.raw instanceof Uint8Array) - return toHex(message.raw); - return message.raw; - })(); - return client.request({ - method: "personal_sign", - params: [message_, account.address] - }, { retryCount: 0 }); -} -// ../viem/src/_esm/actions/wallet/signTransaction.js -init_toHex(); -init_transactionRequest(); -init_assertRequest(); -async function signTransaction(client, parameters) { - const { account: account_ = client.account, chain = client.chain, ...transaction } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/signTransaction" - }); - const account = parseAccount(account_); - assertRequest({ - account, - ...parameters - }); - const chainId = await getAction(client, getChainId, "getChainId")({}); - if (chain !== null) - assertCurrentChain({ - currentChainId: chainId, - chain - }); - const formatters = chain?.formatters || client.chain?.formatters; - const format2 = formatters?.transactionRequest?.format || formatTransactionRequest; - if (account.signTransaction) - return account.signTransaction({ - ...transaction, - account, - chainId - }, { serializer: client.chain?.serializers?.transaction }); - return await client.request({ - method: "eth_signTransaction", - params: [ - { - ...format2({ - ...transaction, - account - }, "signTransaction"), - chainId: numberToHex(chainId), - from: account.address + }; + const subscribeEvent = () => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const transport = (() => { + if (client.transport.type === "fallback") { + const transport2 = client.transport.transports.find((transport3) => transport3.config.type === "webSocket" || transport3.config.type === "ipc"); + if (!transport2) + return client.transport; + return transport2.value; + } + return client.transport; + })(); + const events_ = events ?? (event ? [event] : undefined); + let topics = []; + if (events_) { + const encoded = events_.flatMap((event2) => encodeEventTopics({ + abi: [event2], + eventName: event2.name, + args + })); + topics = [encoded]; + if (event) + topics = topics[0]; + } + const { unsubscribe: unsubscribe_ } = await transport.subscribe({ + params: ["logs", { address, topics }], + onData(data) { + if (!active) + return; + const log = data.result; + try { + const { eventName, args: args2 } = decodeEventLog({ + abi: events_ ?? [], + data: log.data, + topics: log.topics, + strict + }); + const formatted = formatLog(log, { args: args2, eventName }); + onLogs([formatted]); + } catch (err) { + let eventName; + let isUnnamed; + if (err instanceof DecodeLogDataMismatch || err instanceof DecodeLogTopicsMismatch) { + if (strict_) + return; + eventName = err.abiItem.name; + isUnnamed = err.abiItem.inputs?.some((x) => !(("name" in x) && x.name)); + } + const formatted = formatLog(log, { + args: isUnnamed ? [] : {}, + eventName + }); + onLogs([formatted]); + } + }, + onError(error) { + onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); } - ] - }, { retryCount: 0 }); + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollEvent() : subscribeEvent(); } -// ../viem/src/_esm/actions/wallet/signTypedData.js -async function signTypedData(client, parameters) { - const { account: account_ = client.account, domain, message, primaryType } = parameters; - if (!account_) - throw new AccountNotFoundError({ - docsPath: "/docs/actions/wallet/signTypedData" +// ../viem/src/_esm/actions/public/watchPendingTransactions.js +function watchPendingTransactions(client, { batch = true, onError, onTransactions, poll: poll_, pollingInterval = client.pollingInterval }) { + const enablePolling = typeof poll_ !== "undefined" ? poll_ : client.transport.type !== "webSocket" && client.transport.type !== "ipc"; + const pollPendingTransactions = () => { + const observerId = stringify([ + "watchPendingTransactions", + client.uid, + batch, + pollingInterval + ]); + return observe(observerId, { onTransactions, onError }, (emit) => { + let filter; + const unwatch = poll(async () => { + try { + if (!filter) { + try { + filter = await getAction(client, createPendingTransactionFilter, "createPendingTransactionFilter")({}); + return; + } catch (err) { + unwatch(); + throw err; + } + } + const hashes = await getAction(client, getFilterChanges, "getFilterChanges")({ filter }); + if (hashes.length === 0) + return; + if (batch) + emit.onTransactions(hashes); + else + for (const hash3 of hashes) + emit.onTransactions([hash3]); + } catch (err) { + emit.onError?.(err); + } + }, { + emitOnBegin: true, + interval: pollingInterval + }); + return async () => { + if (filter) + await getAction(client, uninstallFilter, "uninstallFilter")({ filter }); + unwatch(); + }; }); - const account = parseAccount(account_); - const types = { - EIP712Domain: getTypesForEIP712Domain({ domain }), - ...parameters.types }; - validateTypedData({ domain, message, primaryType, types }); - if (account.signTypedData) - return account.signTypedData({ domain, message, primaryType, types }); - const typedData = serializeTypedData({ domain, message, primaryType, types }); - return client.request({ - method: "eth_signTypedData_v4", - params: [account.address, typedData] - }, { retryCount: 0 }); + const subscribePendingTransactions = () => { + let active = true; + let unsubscribe = () => active = false; + (async () => { + try { + const { unsubscribe: unsubscribe_ } = await client.transport.subscribe({ + params: ["newPendingTransactions"], + onData(data) { + if (!active) + return; + const transaction = data.result; + onTransactions([transaction]); + }, + onError(error) { + onError?.(error); + } + }); + unsubscribe = unsubscribe_; + if (!active) + unsubscribe(); + } catch (err) { + onError?.(err); + } + })(); + return () => unsubscribe(); + }; + return enablePolling ? pollPendingTransactions() : subscribePendingTransactions(); } -// ../viem/src/_esm/actions/wallet/switchChain.js -init_toHex(); -async function switchChain(client, { id }) { - await client.request({ - method: "wallet_switchEthereumChain", - params: [ - { - chainId: numberToHex(id) - } - ] - }, { retryCount: 0 }); -} - -// ../viem/src/_esm/actions/wallet/watchAsset.js -async function watchAsset(client, params) { - const added = await client.request({ - method: "wallet_watchAsset", - params - }, { retryCount: 0 }); - return added; -} - -// ../viem/src/_esm/clients/decorators/wallet.js -function walletActions(client) { +// ../viem/src/_esm/utils/siwe/parseSiweMessage.js +function parseSiweMessage(message) { + const { scheme, statement, ...prefix } = message.match(prefixRegex)?.groups ?? {}; + const { chainId, expirationTime, issuedAt, notBefore, requestId, ...suffix } = message.match(suffixRegex)?.groups ?? {}; + const resources = message.split("Resources:")[1]?.split(` +- `).slice(1); return { - addChain: (args) => addChain(client, args), - deployContract: (args) => deployContract(client, args), - fillTransaction: (args) => fillTransaction(client, args), - getAddresses: () => getAddresses(client), - getCallsStatus: (args) => getCallsStatus(client, args), - getCapabilities: (args) => getCapabilities(client, args), - getChainId: () => getChainId(client), - getPermissions: () => getPermissions(client), - prepareAuthorization: (args) => prepareAuthorization(client, args), - prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), - requestAddresses: () => requestAddresses(client), - requestPermissions: (args) => requestPermissions(client, args), - sendCalls: (args) => sendCalls(client, args), - sendCallsSync: (args) => sendCallsSync(client, args), - sendRawTransaction: (args) => sendRawTransaction(client, args), - sendRawTransactionSync: (args) => sendRawTransactionSync(client, args), - sendTransaction: (args) => sendTransaction(client, args), - sendTransactionSync: (args) => sendTransactionSync(client, args), - showCallsStatus: (args) => showCallsStatus(client, args), - signAuthorization: (args) => signAuthorization(client, args), - signMessage: (args) => signMessage(client, args), - signTransaction: (args) => signTransaction(client, args), - signTypedData: (args) => signTypedData(client, args), - switchChain: (args) => switchChain(client, args), - waitForCallsStatus: (args) => waitForCallsStatus(client, args), - watchAsset: (args) => watchAsset(client, args), - writeContract: (args) => writeContract(client, args), - writeContractSync: (args) => writeContractSync(client, args), - token: { - approve: bindActionDecorators(client, approve), - approveSync: bindActionDecorators(client, approveSync), - transfer: bindActionDecorators(client, transfer), - transferSync: bindActionDecorators(client, transferSync) - } + ...prefix, + ...suffix, + ...chainId ? { chainId: Number(chainId) } : {}, + ...expirationTime ? { expirationTime: new Date(expirationTime) } : {}, + ...issuedAt ? { issuedAt: new Date(issuedAt) } : {}, + ...notBefore ? { notBefore: new Date(notBefore) } : {}, + ...requestId ? { requestId } : {}, + ...resources ? { resources } : {}, + ...scheme ? { scheme } : {}, + ...statement ? { statement } : {} }; } +var prefixRegex = /^(?:(?[a-zA-Z][a-zA-Z0-9+-.]*):\/\/)?(?[a-zA-Z0-9+-.]*(?::[0-9]{1,5})?) (?:wants you to sign in with your Ethereum account:\n)(?
0x[a-fA-F0-9]{40})\n\n(?:(?.*)\n\n)?/; +var suffixRegex = /(?:URI: (?.+))\n(?:Version: (?.+))\n(?:Chain ID: (?\d+))\n(?:Nonce: (?[a-zA-Z0-9]+))\n(?:Issued At: (?.+))(?:\nExpiration Time: (?.+))?(?:\nNot Before: (?.+))?(?:\nRequest ID: (?.+))?/; -// ../viem/src/_esm/clients/createWalletClient.js -function createWalletClient(parameters) { - const { key = "wallet", name = "Wallet Client", transport } = parameters; - const client = createClient({ - ...parameters, - key, - name, - transport, - type: "walletClient" - }); - return client.extend(walletActions); -} -// ../viem/src/_esm/clients/transports/createTransport.js -function createTransport({ key, methods, name, request, retryCount = 3, retryDelay = 150, timeout, type }, value) { - const uid2 = uid(); - return { - config: { - key, - methods, - name, - request, - retryCount, - retryDelay, - timeout, - type - }, - request: buildRequest(request, { methods, retryCount, retryDelay, uid: uid2 }), - value - }; +// ../viem/src/_esm/utils/siwe/validateSiweMessage.js +init_isAddress(); +init_isAddressEqual(); +function validateSiweMessage(parameters) { + const { address, domain, message, nonce, scheme, time = new Date } = parameters; + if (domain && message.domain !== domain) + return false; + if (nonce && message.nonce !== nonce) + return false; + if (scheme && message.scheme !== scheme) + return false; + if (message.expirationTime && time >= message.expirationTime) + return false; + if (message.notBefore && time < message.notBefore) + return false; + try { + if (!message.address) + return false; + if (!isAddress(message.address, { strict: false })) + return false; + if (address && !isAddressEqual(message.address, address)) + return false; + } catch { + return false; + } + return true; } -// ../viem/src/_esm/clients/transports/custom.js -function custom(provider, config = {}) { - const { key = "custom", methods, name = "Custom Provider", retryDelay } = config; - return ({ retryCount: defaultRetryCount }) => createTransport({ - key, - methods, - name, - request: provider.request.bind(provider), - retryCount: config.retryCount ?? defaultRetryCount, - retryDelay, - type: "custom" +// ../viem/src/_esm/actions/siwe/verifySiweMessage.js +async function verifySiweMessage(client, parameters) { + const { address, domain, message, nonce, scheme, signature, time = new Date, ...callRequest } = parameters; + const parsed = parseSiweMessage(message); + if (!parsed.address) + return false; + const isValid = validateSiweMessage({ + address, + domain, + message: parsed, + nonce, + scheme, + time + }); + if (!isValid) + return false; + const hash3 = hashMessage2(message); + return verifyHash2(client, { + address: parsed.address, + hash: hash3, + signature, + ...callRequest }); } -// ../viem/src/_esm/clients/transports/http.js -init_request(); -// ../viem/src/_esm/errors/transport.js +// ../viem/src/_esm/actions/token/approve.js +init_abis(); +// ../viem/src/_esm/errors/account.js init_base(); -class UrlRequiredError extends BaseError2 { - constructor() { - super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", { - docsPath: "/docs/clients/intro", - name: "UrlRequiredError" +class AccountNotFoundError extends BaseError2 { + constructor({ docsPath: docsPath8 } = {}) { + super([ + "Could not find an Account to execute with this Action.", + "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client." + ].join(` +`), { + docsPath: docsPath8, + docsSlug: "account", + name: "AccountNotFoundError" }); } } -// ../viem/src/_esm/clients/transports/http.js -init_createBatchScheduler(); -var signalId = 0; -var signalIds = new WeakMap; -function getSignalId(signal) { - if (!signal) - return "default"; - const id = signalIds.get(signal); - if (id !== undefined) - return id; - const nextId = signalId++; - signalIds.set(signal, nextId); - return nextId; -} -function http(url, config = {}) { - const { batch, fetchFn, fetchOptions, key = "http", maxResponseBodySize, methods, name = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay, raw } = config; - return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => { - const { batchSize = 1000, wait: wait2 = 0 } = typeof batch === "object" ? batch : {}; - const retryCount = config.retryCount ?? retryCount_; - const timeout = timeout_ ?? config.timeout ?? 1e4; - const url_ = url || chain?.rpcUrls.default.http[0]; - if (!url_) - throw new UrlRequiredError; - const rpcClient = getHttpRpcClient(url_, { - fetchFn, - fetchOptions, - maxResponseBodySize, - onRequest: onFetchRequest, - onResponse: onFetchResponse, - timeout - }); - return createTransport({ - key, - methods, - name, - async request({ method, params }, options) { - const body = { method, params }; - const fetchOptions2 = options?.signal ? { signal: options.signal } : undefined; - const { schedule } = createBatchScheduler({ - id: `${url_}.${getSignalId(options?.signal)}`, - wait: wait2, - shouldSplitBatch(requests) { - return requests.length > batchSize; - }, - fn: (body2) => rpcClient.request({ - body: body2, - fetchOptions: fetchOptions2 - }), - sort: (a, b) => a.id - b.id - }); - const fn = async (body2) => batch ? schedule(body2) : [ - await rpcClient.request({ - body: body2, - fetchOptions: fetchOptions2 - }) - ]; - const [{ error, result }] = await fn(body); - if (raw) - return { error, result }; - if (error) - throw new RpcRequestError({ - body, - error, - url: url_ - }); - return result; - }, - retryCount, - retryDelay, - timeout, - type: "http" - }, { - fetchOptions, - url: url_ +class AccountTypeNotSupportedError extends BaseError2 { + constructor({ docsPath: docsPath8, metaMessages, type }) { + super(`Account type "${type}" is not supported.`, { + docsPath: docsPath8, + metaMessages, + name: "AccountTypeNotSupportedError" }); - }; -} -// ../viem/src/_esm/index.js -init_decodeAbiParameters(); -init_encodeAbiParameters(); -init_encodeFunctionData(); -init_slice(); -init_fromHex(); -init_toHex(); -init_keccak256(); -init_formatEther(); -// ../viem/src/_esm/accounts/generatePrivateKey.js -init_secp256k1(); -init_toHex(); -function generatePrivateKey() { - return toHex(secp256k1.utils.randomPrivateKey()); -} -// ../viem/src/_esm/accounts/privateKeyToAccount.js -init_secp256k1(); -init_toHex(); - -// ../viem/src/_esm/accounts/toAccount.js -init_address(); -init_isAddress(); -function toAccount(source) { - if (typeof source === "string") { - if (!isAddress(source, { strict: false })) - throw new InvalidAddressError({ address: source }); - return { - address: source, - type: "json-rpc" - }; - } - if (!isAddress(source.address, { strict: false })) - throw new InvalidAddressError({ address: source.address }); - return { - address: source.address, - nonceManager: source.nonceManager, - sign: source.sign, - signAuthorization: source.signAuthorization, - signMessage: source.signMessage, - signTransaction: source.signTransaction, - signTypedData: source.signTypedData, - source: "custom", - type: "local" - }; -} - -// ../viem/src/_esm/accounts/utils/sign.js -init_secp256k1(); -init_toBytes(); -init_toHex(); -var extraEntropy2 = false; -async function sign({ hash: hash3, privateKey, to = "object" }) { - const { r, s, recovery } = secp256k1.sign(hash3.slice(2), privateKey.slice(2), { - lowS: true, - extraEntropy: isHex(extraEntropy2, { strict: false }) ? hexToBytes(extraEntropy2) : extraEntropy2 - }); - const signature = { - r: numberToHex(r, { size: 32 }), - s: numberToHex(s, { size: 32 }), - v: recovery ? 28n : 27n, - yParity: recovery - }; - return (() => { - if (to === "bytes" || to === "hex") - return serializeSignature({ ...signature, to }); - return signature; - })(); -} - -// ../viem/src/_esm/accounts/utils/signAuthorization.js -async function signAuthorization2(parameters) { - const { chainId, nonce, privateKey, to = "object" } = parameters; - const address = parameters.contractAddress ?? parameters.address; - const signature = await sign({ - hash: hashAuthorization({ address, chainId, nonce }), - privateKey, - to - }); - if (to === "object") - return { - address, - chainId, - nonce, - ...signature - }; - return signature; + } } -// ../viem/src/_esm/accounts/utils/signMessage.js -async function signMessage2({ message, privateKey }) { - return await sign({ hash: hashMessage(message), privateKey, to: "hex" }); -} +// ../viem/src/_esm/actions/wallet/writeContract.js +init_encodeFunctionData(); +// ../viem/src/_esm/actions/wallet/sendTransaction.js +init_base(); -// ../viem/src/_esm/accounts/utils/signTransaction.js -init_keccak256(); -async function signTransaction2(parameters) { - const { privateKey, transaction, serializer = serializeTransaction } = parameters; - const signableTransaction = (() => { - if (transaction.type === "eip4844") - return { - ...transaction, - sidecars: false - }; - return transaction; - })(); - const signature = await sign({ - hash: keccak256(await serializer(signableTransaction)), - privateKey - }); - return await serializer(transaction, signature); +// ../viem/src/_esm/utils/chain/assertCurrentChain.js +init_chain(); +function assertCurrentChain2({ chain, currentChainId }) { + if (!chain) + throw new ChainNotFoundError; + if (currentChainId !== chain.id) + throw new ChainMismatchError({ chain, currentChainId }); } +// ../viem/src/_esm/actions/wallet/sendTransaction.js +init_transactionRequest(); +init_lru(); +init_assertRequest(); -// ../viem/src/_esm/accounts/utils/signTypedData.js -async function signTypedData2(parameters) { - const { privateKey, ...typedData } = parameters; - return await sign({ - hash: hashTypedData(typedData), - privateKey, - to: "hex" - }); +// ../viem/src/_esm/actions/wallet/sendRawTransaction.js +async function sendRawTransaction(client, { serializedTransaction }) { + return client.request({ + method: "eth_sendRawTransaction", + params: [serializedTransaction] + }, { retryCount: 0 }); } -// ../viem/src/_esm/accounts/privateKeyToAccount.js -function privateKeyToAccount(privateKey, options = {}) { - const { nonceManager: nonceManager2 } = options; - const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false)); - const address = publicKeyToAddress(publicKey); - const account = toAccount({ - address, - nonceManager: nonceManager2, - async sign({ hash: hash3 }) { - return sign({ hash: hash3, privateKey, to: "hex" }); - }, - async signAuthorization(authorization) { - return signAuthorization2({ ...authorization, privateKey }); - }, - async signMessage({ message }) { - return signMessage2({ message, privateKey }); - }, - async signTransaction(transaction, { serializer } = {}) { - return signTransaction2({ privateKey, transaction, serializer }); - }, - async signTypedData(typedData) { - return signTypedData2({ ...typedData, privateKey }); +// ../viem/src/_esm/actions/wallet/sendTransaction.js +var supportsWalletNamespace = new LruMap(128); +async function sendTransaction(client, parameters) { + const { account: account_ = client.account, assertChainId = true, chain = client.chain, accessList, authorizationList, blobs, data, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, type, value, ...rest } = parameters; + if (typeof account_ === "undefined") + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/sendTransaction" + }); + const account = account_ ? parseAccount(account_) : null; + let nonceManagerParameters; + try { + assertRequest(parameters); + const to = await (async () => { + if (parameters.to) + return parameters.to; + if (parameters.to === null) + return; + if (authorizationList && authorizationList.length > 0) + return await recoverAuthorizationAddress({ + authorization: authorizationList[0] + }).catch(() => { + throw new BaseError2("`to` is required. Could not infer from `authorizationList`."); + }); + return; + })(); + if (account?.type === "json-rpc" || account === null) { + let chainId; + if (chain !== null) { + chainId = await getAction(client, getChainId, "getChainId")({}); + if (assertChainId) + assertCurrentChain2({ + currentChainId: chainId, + chain + }); + } + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format2 = chainFormat || formatTransactionRequest; + const request = format2({ + ...extract(rest, { format: chainFormat }), + accessList, + account, + authorizationList, + blobs, + chainId, + data: dataSuffix ? concat([data ?? "0x", dataSuffix]) : data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to, + type, + value + }, "sendTransaction"); + const isWalletNamespaceSupported = supportsWalletNamespace.get(client.uid); + const method = isWalletNamespaceSupported ? "wallet_sendTransaction" : "eth_sendTransaction"; + try { + return await client.request({ + method, + params: [request] + }, { retryCount: 0 }); + } catch (e) { + if (isWalletNamespaceSupported === false) + throw e; + const error = e; + if (error.name === "InvalidInputRpcError" || error.name === "InvalidParamsRpcError" || error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError") { + return await client.request({ + method: "wallet_sendTransaction", + params: [request] + }, { retryCount: 0 }).then((hash3) => { + supportsWalletNamespace.set(client.uid, true); + return hash3; + }).catch((e2) => { + const walletNamespaceError = e2; + if (walletNamespaceError.name === "MethodNotFoundRpcError" || walletNamespaceError.name === "MethodNotSupportedRpcError") { + supportsWalletNamespace.set(client.uid, false); + throw error; + } + throw walletNamespaceError; + }); + } + throw error; + } } - }); - return { - ...account, - publicKey, - source: "privateKey" - }; -} -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Base64.js -var encoder5 = /* @__PURE__ */ new TextEncoder; -var integerToCharacter = /* @__PURE__ */ Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((a, i) => [i, a.charCodeAt(0)])); -var characterToInteger = { - ...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((a, i) => [a.charCodeAt(0), i])), - [61]: 0, - [45]: 62, - [95]: 63 -}; -function toBytes4(value) { - const base64 = value.replace(/=+$/, ""); - const size5 = base64.length; - const decoded = new Uint8Array(size5 + 3); - encoder5.encodeInto(base64 + "===", decoded); - for (let i = 0, j = 0;i < base64.length; i += 4, j += 3) { - const x = (characterToInteger[decoded[i]] << 18) + (characterToInteger[decoded[i + 1]] << 12) + (characterToInteger[decoded[i + 2]] << 6) + characterToInteger[decoded[i + 3]]; - decoded[j] = x >> 16; - decoded[j + 1] = x >> 8 & 255; - decoded[j + 2] = x & 255; + if (account?.type === "local") { + const nonceManager2 = (() => { + if (!account.nonceManager || typeof nonce !== "undefined") + return account.nonceManager; + const nonceManager3 = account.nonceManager; + return { + consume(parameters2) { + nonceManagerParameters = { + address: parameters2.address, + chainId: parameters2.chainId + }; + return nonceManager3.consume(parameters2); + }, + get(parameters2) { + return nonceManager3.get(parameters2); + }, + increment(parameters2) { + return nonceManager3.increment(parameters2); + }, + reset(parameters2) { + return nonceManager3.reset(parameters2); + } + }; + })(); + const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({ + account, + accessList, + authorizationList, + blobs, + chain, + data: dataSuffix ? concat([data ?? "0x", dataSuffix]) : data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + nonceManager: nonceManager2, + parameters: [...defaultParameters, "sidecars"], + type, + value, + ...rest, + to + }); + const serializer = chain?.serializers?.transaction; + const serializedTransaction = await account.signTransaction(request, { + serializer + }); + return await getAction(client, sendRawTransaction, "sendRawTransaction")({ + serializedTransaction + }); + } + if (account?.type === "smart") + throw new AccountTypeNotSupportedError({ + metaMessages: [ + "Consider using the `sendUserOperation` Action instead." + ], + docsPath: "/docs/actions/bundler/sendUserOperation", + type: "smart" + }); + throw new AccountTypeNotSupportedError({ + docsPath: "/docs/actions/wallet/sendTransaction", + type: account?.type + }); + } catch (err) { + if (err instanceof AccountTypeNotSupportedError) + throw err; + if (nonceManagerParameters) + account?.nonceManager?.reset(nonceManagerParameters); + throw getTransactionError(err, { + ...parameters, + account, + chain: parameters.chain || undefined + }); } - const decodedSize = (size5 >> 2) * 3 + (size5 % 4 && size5 % 4 - 1); - return new Uint8Array(decoded.buffer, 0, decodedSize); } -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/webauthn/Authentication.js -init_Bytes(); -init_Errors(); -init_Hex(); +// ../viem/src/_esm/actions/wallet/writeContract.js +async function writeContract(client, parameters) { + return writeContract.internal(client, sendTransaction, "sendTransaction", parameters); +} +(function(writeContract2) { + async function internal(client, actionFn, name, parameters) { + const { abi: abi2, account: account_ = client.account, address, args, functionName, ...request } = parameters; + if (typeof account_ === "undefined") + throw new AccountNotFoundError({ + docsPath: "/docs/contract/writeContract" + }); + const account = account_ ? parseAccount(account_) : null; + const data = encodeFunctionData({ + abi: abi2, + args, + functionName + }); + try { + return await getAction(client, actionFn, name)({ + data, + to: address, + account, + ...request + }); + } catch (error) { + throw getContractError(error, { + abi: abi2, + address, + args, + docsPath: "/docs/contract/writeContract", + functionName, + sender: account?.address + }); + } + } + writeContract2.internal = internal; +})(writeContract || (writeContract = {})); -// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/nist.js -init_sha2(); -init__shortw_utils(); -init_modular(); -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -var Fp256 = Field(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")); -var p256_a = Fp256.create(BigInt("-3")); -var p256_b = BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"); -var p256 = createCurve({ - a: p256_a, - b: p256_b, - Fp: Fp256, - n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"), - Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), - Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), - h: BigInt(1), - lowS: false -}, sha256); -var Fp384 = Field(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")); -var p384_a = Fp384.create(BigInt("-3")); -var p384_b = BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"); -var p384 = createCurve({ - a: p384_a, - b: p384_b, - Fp: Fp384, - n: BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"), - Gx: BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"), - Gy: BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"), - h: BigInt(1), - lowS: false -}, sha384); -var Fp521 = Field(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); -var p521_a = Fp521.create(BigInt("-3")); -var p521_b = BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"); -var p521 = createCurve({ - a: p521_a, - b: p521_b, - Fp: Fp521, - n: BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"), - Gx: BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"), - Gy: BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"), - h: BigInt(1), - lowS: false, - allowedPrivateKeyLengths: [130, 131, 132] -}, sha512); +// ../viem/src/_esm/actions/token/internal.js +init_abis(); +init_isAddress(); +init_isAddressEqual(); -// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/p256.js -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -var p2562 = p256; -var secp256r1 = p256; +// ../viem/src/_esm/utils/unit/formatUnits.js +init_Value(); +function formatUnits2(value, decimals) { + return format(value, decimals); +} -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/webauthn/Registration.js -init_Bytes(); -init_Errors(); +// ../viem/src/_esm/utils/unit/parseUnits.js +init_Value(); +function parseUnits2(value, decimals) { + return from(value, decimals); +} -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/P256.js -init_Bytes(); -init_Hex(); -function getPublicKey(options) { - const { privateKey } = options; - const point = secp256r1.ProjectivePoint.fromPrivateKey(typeof privateKey === "string" ? privateKey.slice(2) : fromBytes(privateKey).slice(2)); - return from4(point); +// ../viem/src/_esm/actions/token/internal.js +function toAmount(amount, decimals) { + return { amount, decimals, formatted: formatUnits2(amount, decimals) }; } -function sign2(options) { - const { extraEntropy: extraEntropy3 = extraEntropy, hash: hash3, payload, privateKey } = options; - const { r, s, recovery } = secp256r1.sign(payload instanceof Uint8Array ? payload : fromHex(payload), privateKey instanceof Uint8Array ? privateKey : fromHex(privateKey), { - extraEntropy: typeof extraEntropy3 === "boolean" ? extraEntropy3 : from3(extraEntropy3).slice(2), - lowS: true, - ...hash3 ? { prehash: true } : {} - }); +function toBaseUnits(amount, decimals) { + if (typeof amount === "bigint") + return amount; + const resolved = amount.decimals ?? decimals; + return parseUnits2(amount.formatted, requireTokenDecimals(resolved)); +} +function requireTokenDecimals(decimals) { + if (decimals === undefined) + throw new Error("Token decimals are required. Pass `amount.decimals` or select a declared token."); + return decimals; +} +function resolveAmountDecimals(amount, decimals) { + if (typeof amount === "bigint") + return decimals; + return amount.decimals ?? decimals; +} +function resolveToken(client, parameters) { + const { decimals, token } = parameters; + const declared = findDeclaredToken(client, token); + if (declared) + return { + address: declared.address, + decimals: decimals ?? declared.decimals + }; + if (isAddress(token, { strict: false })) + return { + address: token, + decimals: decimals ?? inferDecimals(client, token) + }; + throw new Error(`Token "${token}" is not a declared ERC-20 token on the client's \`tokens\` array (with an address for the client's chain), and is not a valid address.`); +} +function findDeclaredToken(client, token) { + const tokens = client.tokens; + const chainId = client.chain?.id; + if (!tokens || chainId === undefined) + return; + const bySymbol = findTokenBySymbol(tokens, token); + if (bySymbol) + return resolveTokenForChain(bySymbol, chainId); + if (isAddress(token, { strict: false })) + for (const token_ of tokens) { + const resolved = resolveTokenForChain(token_, chainId); + if (resolved && isAddressEqual(resolved.address, token)) + return resolved; + } + return; +} +function resolveTokenForChain(token, chainId) { + const address = token.addresses[chainId]; + if (!address) + return; return { - r, - s, - yParity: recovery + address, + currency: token.currency, + decimals: token.decimals, + name: token.name, + popular: token.popular, + symbol: token.symbol }; } - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/webauthn/Registration.js -var createChallenge = Uint8Array.from([ - 105, - 171, - 180, - 181, - 160, - 222, - 75, - 198, - 42, - 42, - 32, - 31, - 141, - 37, - 186, - 233 -]); -async function create2(options) { - const { createFn = (opts) => window.navigator.credentials.create(opts), ...rest } = options; - const creationOptions = "publicKey" in rest ? rest : getOptions(rest); - try { - const credential = await createFn(creationOptions); - if (!credential) - throw new CreateFailedError; - const response = credential.response; - const attestationObject = response.attestationObject; - const clientDataJSON = response.clientDataJSON; - const id = credential.id; - const publicKey = await parseCredentialPublicKey(response, attestationObject); - return { - attestationObject, - clientDataJSON, - id, - publicKey, - raw: credential - }; - } catch (error) { - throw new CreateFailedError({ - cause: error - }); +function findTokenBySymbol(tokens, symbol) { + const lowerSymbol = symbol.toLowerCase(); + for (const token of tokens) { + if (token.symbol?.toLowerCase() === lowerSymbol) + return token; } + return; } -function getOptions(options) { - const { attestation = "none", authenticatorSelection = { - residentKey: "preferred", - requireResidentKey: false, - userVerification: "required" - }, challenge: challenge2 = createChallenge, excludeCredentialIds, extensions, name: name_, rp = { - id: window.location.hostname, - name: window.document.title - }, user } = options; - const name = user?.name ?? name_; - return { - publicKey: { - attestation, - authenticatorSelection, - challenge: typeof challenge2 === "string" ? fromHex(challenge2) : challenge2, - ...excludeCredentialIds ? { - excludeCredentials: excludeCredentialIds?.map((id) => ({ - id: toBytes4(id), - type: "public-key" - })) - } : {}, - pubKeyCredParams: [ - { - type: "public-key", - alg: -7 - } - ], - rp, - user: { - id: user?.id ?? keccak2562(fromString(name), { as: "Bytes" }), - name, - displayName: user?.displayName ?? name - }, - ...extensions && { extensions } +function inferDecimals(client, address) { + const tokens = client.tokens; + const chainId = client.chain?.id; + if (tokens && chainId !== undefined) + for (const token of tokens) { + const resolved = resolveTokenForChain(token, chainId); + if (resolved && isAddressEqual(resolved.address, address)) + return resolved.decimals; } - }; -} -class CreateFailedError extends BaseError3 { - constructor({ cause } = {}) { - super("Failed to create credential.", { - cause - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Registration.CreateFailedError" - }); - } + return; } - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/webauthn.js -function parseAsn1Signature(bytes) { - const sig = p2562.Signature.fromDER(bytes).normalizeS(); - return { r: sig.r, s: sig.s }; +async function resolveTokenWithDecimals(client, parameters) { + const { address, decimals } = resolveToken(client, parameters); + if (decimals !== undefined) + return { address, decimals }; + return { + address, + decimals: await readContract(client, { + abi: erc20Abi, + address, + functionName: "decimals" + }) + }; } -async function parseCredentialPublicKey(response, attestationObject) { - try { - const publicKeyBuffer = response.getPublicKey(); - if (!publicKeyBuffer) - throw new CreateFailedError; - const publicKeyBytes = new Uint8Array(publicKeyBuffer); - const cryptoKey = await crypto.subtle.importKey("spki", new Uint8Array(publicKeyBytes), { - name: "ECDSA", - namedCurve: "P-256", - hash: "SHA-256" - }, true, ["verify"]); - const publicKey = new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKey)); - return from4(publicKey); - } catch (error) { - if (error.message !== "Permission denied to access object") - throw error; - const data = new Uint8Array(attestationObject ?? response.attestationObject); - const coordinateLength = 32; - const cborPrefix = 88; - const findStart = (key) => { - const coordinate = new Uint8Array([key, cborPrefix, coordinateLength]); - for (let i = 0;i < data.length - coordinate.length; i++) - if (coordinate.every((byte, j) => data[i + j] === byte)) - return i + coordinate.length; - throw new CreateFailedError; - }; - const xStart = findStart(33); - const yStart = findStart(34); - return from4(new Uint8Array([ - 4, - ...data.slice(xStart, xStart + coordinateLength), - ...data.slice(yStart, yStart + coordinateLength) - ])); - } +function pickWriteParameters(parameters) { + const { account, chain, gas, maxFeePerGas, maxPriorityFeePerGas, nonce } = parameters; + return { account, chain, gas, maxFeePerGas, maxPriorityFeePerGas, nonce }; } - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/webauthn/Authentication.js -function getOptions2(options) { - const { credentialId, challenge: challenge2, extensions, rpId = window.location.hostname, userVerification = "required" } = options; +function defineCall(call2) { return { - publicKey: { - ...credentialId ? { - allowCredentials: Array.isArray(credentialId) ? credentialId.map((id) => ({ - id: toBytes4(id), - type: "public-key" - })) : [ - { - id: toBytes4(credentialId), - type: "public-key" - } - ] - } : {}, - challenge: fromHex(challenge2), - ...extensions && { extensions }, - rpId, - userVerification - } + ...call2, + data: encodeFunctionData(call2), + to: call2.address }; } -async function sign3(options) { - const { getFn = (opts) => window.navigator.credentials.get(opts), ...rest } = options; - const requestOptions = "publicKey" in rest ? rest : getOptions2(rest); - try { - const credential = await getFn(requestOptions); - if (!credential) - throw new SignFailedError; - const response = credential.response; - const clientDataJSONBytes = new Uint8Array(response.clientDataJSON); - const authenticatorDataBytes = new Uint8Array(response.authenticatorData); - const signatureBytes = new Uint8Array(response.signature); - const id = credential.id; - const clientDataJSON = String.fromCharCode(...clientDataJSONBytes); - const challengeIndex = clientDataJSON.indexOf('"challenge"'); - const typeIndex = clientDataJSON.indexOf('"type"'); - const signature = parseAsn1Signature(signatureBytes); - return { - id, - metadata: { - authenticatorData: fromBytes(authenticatorDataBytes), - clientDataJSON, - challengeIndex, - typeIndex, - userVerificationRequired: requestOptions.publicKey.userVerification === "required" - }, - signature, - raw: credential - }; - } catch (error) { - throw new SignFailedError({ - cause: error + +// ../viem/src/_esm/actions/token/approve.js +async function approve(client, parameters) { + return approve.inner(writeContract, client, parameters); +} +(function(approve2) { + async function inner(action, client, parameters) { + return await action(client, { + ...parameters, + ...approve2.call(client, parameters) }); } -} - -class SignFailedError extends BaseError3 { - constructor({ cause } = {}) { - super("Failed to request credential.", { - cause + approve2.inner = inner; + function call2(client, parameters) { + return defineCall(getCall(client, parameters)); + } + approve2.call = call2; + async function estimateGas2(client, parameters) { + return estimateContractGas(client, { + ...pickWriteParameters(parameters), + ...approve2.call(client, parameters) }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: "Authentication.SignFailedError" + } + approve2.estimateGas = estimateGas2; + async function simulate(client, parameters) { + return simulateContract(client, { + ...pickWriteParameters(parameters), + ...approve2.call(client, parameters) }); } -} - -// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/WebAuthnP256.js -async function createCredential(options) { - return create2(options); -} -async function sign4(options) { - return sign3(options); -} - -// ../viem/src/_esm/account-abstraction/accounts/createWebAuthnCredential.js -async function createWebAuthnCredential(parameters) { - const credential = await createCredential(parameters); + approve2.simulate = simulate; + function extractEvent(logs) { + const [log] = parseEventLogs({ + abi: erc20Abi, + logs, + eventName: "Approval", + strict: true + }); + if (!log) + throw new Error("`Approval` event not found."); + return log; + } + approve2.extractEvent = extractEvent; +})(approve || (approve = {})); +function getCall(client, parameters) { + const { amount, spender, token } = parameters; + const { address, decimals } = resolveToken(client, { token }); return { - id: credential.id, - publicKey: toHex2(credential.publicKey, { includePrefix: false }), - raw: credential.raw + abi: erc20Abi, + address, + args: [spender, toBaseUnits(amount, decimals)], + functionName: "approve" }; } -// ../viem/src/_esm/account-abstraction/constants/abis.js -var entryPoint07Abi = [ - { - inputs: [ - { name: "success", type: "bool" }, - { name: "ret", type: "bytes" } - ], - name: "DelegateAndRevert", - type: "error" - }, - { - inputs: [ - { name: "opIndex", type: "uint256" }, - { name: "reason", type: "string" } - ], - name: "FailedOp", - type: "error" - }, - { - inputs: [ - { name: "opIndex", type: "uint256" }, - { name: "reason", type: "string" }, - { name: "inner", type: "bytes" } - ], - name: "FailedOpWithRevert", - type: "error" - }, - { - inputs: [{ name: "returnData", type: "bytes" }], - name: "PostOpReverted", - type: "error" - }, - { inputs: [], name: "ReentrancyGuardReentrantCall", type: "error" }, - { - inputs: [{ name: "sender", type: "address" }], - name: "SenderAddressResult", - type: "error" - }, - { - inputs: [{ name: "aggregator", type: "address" }], - name: "SignatureValidationFailed", - type: "error" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "userOpHash", - type: "bytes32" - }, - { - indexed: true, - name: "sender", - type: "address" - }, - { - indexed: false, - name: "factory", - type: "address" - }, - { - indexed: false, - name: "paymaster", - type: "address" - } - ], - name: "AccountDeployed", - type: "event" - }, - { anonymous: false, inputs: [], name: "BeforeExecution", type: "event" }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "account", - type: "address" - }, - { - indexed: false, - name: "totalDeposit", - type: "uint256" - } - ], - name: "Deposited", - type: "event" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "userOpHash", - type: "bytes32" - }, - { - indexed: true, - name: "sender", - type: "address" - }, - { - indexed: false, - name: "nonce", - type: "uint256" - }, - { - indexed: false, - name: "revertReason", - type: "bytes" - } - ], - name: "PostOpRevertReason", - type: "event" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "aggregator", - type: "address" - } - ], - name: "SignatureAggregatorChanged", - type: "event" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "account", - type: "address" - }, - { - indexed: false, - name: "totalStaked", - type: "uint256" - }, - { - indexed: false, - name: "unstakeDelaySec", - type: "uint256" - } - ], - name: "StakeLocked", - type: "event" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "account", - type: "address" - }, - { - indexed: false, - name: "withdrawTime", - type: "uint256" +// ../viem/src/_esm/actions/wallet/sendTransactionSync.js +init_base(); +init_transaction(); +init_transactionRequest(); +init_lru(); +init_assertRequest(); + +// ../viem/src/_esm/actions/wallet/sendRawTransactionSync.js +init_transaction(); +async function sendRawTransactionSync(client, { serializedTransaction, throwOnReceiptRevert, timeout }) { + const receipt = await client.request({ + method: "eth_sendRawTransactionSync", + params: timeout ? [serializedTransaction, timeout] : [serializedTransaction] + }, { retryCount: 0 }); + const format2 = client.chain?.formatters?.transactionReceipt?.format || formatTransactionReceipt; + const formatted = format2(receipt); + if (formatted.status === "reverted" && throwOnReceiptRevert) + throw new TransactionReceiptRevertedError({ receipt: formatted }); + return formatted; +} + +// ../viem/src/_esm/actions/wallet/sendTransactionSync.js +var supportsWalletNamespace2 = new LruMap(128); +async function sendTransactionSync(client, parameters) { + const { account: account_ = client.account, assertChainId = true, chain = client.chain, accessList, authorizationList, blobs, data, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, pollingInterval, throwOnReceiptRevert, type, value, ...rest } = parameters; + const timeout = parameters.timeout ?? Math.max((chain?.blockTime ?? 0) * 3, 5000); + if (typeof account_ === "undefined") + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/sendTransactionSync" + }); + const account = account_ ? parseAccount(account_) : null; + let nonceManagerParameters; + try { + assertRequest(parameters); + const to = await (async () => { + if (parameters.to) + return parameters.to; + if (parameters.to === null) + return; + if (authorizationList && authorizationList.length > 0) + return await recoverAuthorizationAddress({ + authorization: authorizationList[0] + }).catch(() => { + throw new BaseError2("`to` is required. Could not infer from `authorizationList`."); + }); + return; + })(); + if (account?.type === "json-rpc" || account === null) { + let chainId; + if (chain !== null) { + chainId = await getAction(client, getChainId, "getChainId")({}); + if (assertChainId) + assertCurrentChain2({ + currentChainId: chainId, + chain + }); } - ], - name: "StakeUnlocked", - type: "event" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "account", - type: "address" - }, - { - indexed: false, - name: "withdrawAddress", - type: "address" - }, + const chainFormat = client.chain?.formatters?.transactionRequest?.format; + const format2 = chainFormat || formatTransactionRequest; + const request = format2({ + ...extract(rest, { format: chainFormat }), + accessList, + account, + authorizationList, + blobs, + chainId, + data: dataSuffix ? concat([data ?? "0x", dataSuffix]) : data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + to, + type, + value + }, "sendTransaction"); + const isWalletNamespaceSupported = supportsWalletNamespace2.get(client.uid); + const method = isWalletNamespaceSupported ? "wallet_sendTransaction" : "eth_sendTransaction"; + const hash3 = await (async () => { + try { + return await client.request({ + method, + params: [request] + }, { retryCount: 0 }); + } catch (e) { + if (isWalletNamespaceSupported === false) + throw e; + const error = e; + if (error.name === "InvalidInputRpcError" || error.name === "InvalidParamsRpcError" || error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError") { + return await client.request({ + method: "wallet_sendTransaction", + params: [request] + }, { retryCount: 0 }).then((hash4) => { + supportsWalletNamespace2.set(client.uid, true); + return hash4; + }).catch((e2) => { + const walletNamespaceError = e2; + if (walletNamespaceError.name === "MethodNotFoundRpcError" || walletNamespaceError.name === "MethodNotSupportedRpcError") { + supportsWalletNamespace2.set(client.uid, false); + throw error; + } + throw walletNamespaceError; + }); + } + throw error; + } + })(); + const receipt = await getAction(client, waitForTransactionReceipt, "waitForTransactionReceipt")({ + checkReplacement: false, + hash: hash3, + pollingInterval, + timeout + }); + if (throwOnReceiptRevert && receipt.status === "reverted") + throw new TransactionReceiptRevertedError({ receipt }); + return receipt; + } + if (account?.type === "local") { + const nonceManager2 = (() => { + if (!account.nonceManager || typeof nonce !== "undefined") + return account.nonceManager; + const nonceManager3 = account.nonceManager; + return { + consume(parameters2) { + nonceManagerParameters = { + address: parameters2.address, + chainId: parameters2.chainId + }; + return nonceManager3.consume(parameters2); + }, + get(parameters2) { + return nonceManager3.get(parameters2); + }, + increment(parameters2) { + return nonceManager3.increment(parameters2); + }, + reset(parameters2) { + return nonceManager3.reset(parameters2); + } + }; + })(); + const request = await getAction(client, prepareTransactionRequest, "prepareTransactionRequest")({ + account, + accessList, + authorizationList, + blobs, + chain, + data: dataSuffix ? concat([data ?? "0x", dataSuffix]) : data, + gas, + gasPrice, + maxFeePerBlobGas, + maxFeePerGas, + maxPriorityFeePerGas, + nonce, + nonceManager: nonceManager2, + parameters: [...defaultParameters, "sidecars"], + type, + value, + ...rest, + to + }); + const serializer = chain?.serializers?.transaction; + const serializedTransaction = await account.signTransaction(request, { + serializer + }); + return await getAction(client, sendRawTransactionSync, "sendRawTransactionSync")({ + serializedTransaction, + throwOnReceiptRevert, + timeout: parameters.timeout + }); + } + if (account?.type === "smart") + throw new AccountTypeNotSupportedError({ + metaMessages: [ + "Consider using the `sendUserOperation` Action instead." + ], + docsPath: "/docs/actions/bundler/sendUserOperation", + type: "smart" + }); + throw new AccountTypeNotSupportedError({ + docsPath: "/docs/actions/wallet/sendTransactionSync", + type: account?.type + }); + } catch (err) { + if (err instanceof AccountTypeNotSupportedError) + throw err; + if (nonceManagerParameters && !(err instanceof TransactionReceiptRevertedError)) + account?.nonceManager?.reset(nonceManagerParameters); + throw getTransactionError(err, { + ...parameters, + account, + chain: parameters.chain || undefined + }); + } +} + +// ../viem/src/_esm/actions/wallet/writeContractSync.js +async function writeContractSync(client, parameters) { + return writeContract.internal(client, sendTransactionSync, "sendTransactionSync", parameters); +} + +// ../viem/src/_esm/actions/token/approveSync.js +async function approveSync(client, parameters) { + const { amount, token, throwOnReceiptRevert = true } = parameters; + const { decimals } = resolveToken(client, { token }); + const resolved = resolveAmountDecimals(amount, decimals); + const receipt = await approve.inner(writeContractSync, client, { + ...parameters, + throwOnReceiptRevert + }); + const { args } = approve.extractEvent(receipt.logs); + return { + ...args, + ...resolved === undefined ? {} : { decimals: resolved, formatted: formatUnits2(args.value, resolved) }, + receipt + }; +} +// ../viem/src/_esm/actions/token/getAllowance.js +init_abis(); +async function getAllowance(client, parameters) { + const { account, decimals, spender, token, ...rest } = parameters; + const [amount, { decimals: resolved }] = await Promise.all([ + readContract(client, { + ...rest, + ...getAllowance.call(client, { account, spender, token }) + }), + resolveTokenWithDecimals(client, { + decimals, + token + }) + ]); + return toAmount(amount, resolved); +} +(function(getAllowance2) { + function call2(client, args) { + return defineCall({ + address: resolveToken(client, args).address, + abi: erc20Abi, + functionName: "allowance", + args: [args.account, args.spender] + }); + } + getAllowance2.call = call2; +})(getAllowance || (getAllowance = {})); +// ../viem/src/_esm/actions/token/getBalance.js +init_abis(); +async function getBalance2(client, parameters) { + const { account: account_ = client.account, decimals, token, ...rest } = parameters; + if (!account_) + throw new AccountNotFoundError; + const account = parseAccount(account_).address; + const [amount, { decimals: resolved }] = await Promise.all([ + readContract(client, { + ...rest, + ...getBalance2.call(client, { account, token }) + }), + resolveTokenWithDecimals(client, { + decimals, + token + }) + ]); + return toAmount(amount, resolved); +} +(function(getBalance3) { + function call2(client, args) { + const account_ = args.account ?? client.account; + if (!account_) + throw new AccountNotFoundError; + const account = parseAccount(account_).address; + return defineCall({ + address: resolveToken(client, args).address, + abi: erc20Abi, + functionName: "balanceOf", + args: [account] + }); + } + getBalance3.call = call2; +})(getBalance2 || (getBalance2 = {})); +// ../viem/src/_esm/actions/token/getMetadata.js +init_abis(); +async function getMetadata(client, parameters) { + const { token, ...rest } = parameters; + const { address } = resolveToken(client, { token }); + const declared = findDeclaredToken(client, token); + const [decimals_, name, symbol] = await Promise.all([ + declared?.decimals ?? readContract(client, { + ...rest, + abi: erc20Abi, + address, + functionName: "decimals" + }), + declared?.name ?? readContract(client, { + ...rest, + abi: erc20Abi, + address, + functionName: "name" + }), + declared?.symbol ?? readContract(client, { + ...rest, + abi: erc20Abi, + address, + functionName: "symbol" + }) + ]); + return { + decimals: decimals_, + name, + symbol + }; +} +// ../viem/src/_esm/actions/token/getTotalSupply.js +init_abis(); +async function getTotalSupply(client, parameters) { + const { decimals, token, ...rest } = parameters; + const [amount, { decimals: resolved }] = await Promise.all([ + readContract(client, { + ...rest, + ...getTotalSupply.call(client, { token }) + }), + resolveTokenWithDecimals(client, { + decimals, + token + }) + ]); + return toAmount(amount, resolved); +} +(function(getTotalSupply2) { + function call2(client, args) { + return defineCall({ + address: resolveToken(client, args).address, + abi: erc20Abi, + args: [], + functionName: "totalSupply" + }); + } + getTotalSupply2.call = call2; +})(getTotalSupply || (getTotalSupply = {})); +// ../viem/src/_esm/actions/token/transfer.js +init_abis(); +async function transfer(client, parameters) { + return transfer.inner(writeContract, client, parameters); +} +(function(transfer2) { + async function inner(action, client, parameters) { + return await action(client, { + ...parameters, + ...transfer2.call(client, parameters) + }); + } + transfer2.inner = inner; + function call2(client, parameters) { + return defineCall(getCall2(client, parameters)); + } + transfer2.call = call2; + async function estimateGas2(client, parameters) { + return estimateContractGas(client, { + ...pickWriteParameters(parameters), + ...transfer2.call(client, parameters) + }); + } + transfer2.estimateGas = estimateGas2; + async function simulate(client, parameters) { + return simulateContract(client, { + ...pickWriteParameters(parameters), + ...transfer2.call(client, parameters) + }); + } + transfer2.simulate = simulate; + function extractEvent(logs) { + const [log] = parseEventLogs({ + abi: erc20Abi, + logs, + eventName: "Transfer", + strict: true + }); + if (!log) + throw new Error("`Transfer` event not found."); + return log; + } + transfer2.extractEvent = extractEvent; +})(transfer || (transfer = {})); +function getCall2(client, parameters) { + const { amount, from: from15, to, token } = parameters; + const { address, decimals } = resolveToken(client, { token }); + const value = toBaseUnits(amount, decimals); + if (from15) + return { + abi: erc20Abi, + address, + args: [from15, to, value], + functionName: "transferFrom" + }; + return { + abi: erc20Abi, + address, + args: [to, value], + functionName: "transfer" + }; +} +// ../viem/src/_esm/actions/token/transferSync.js +async function transferSync(client, parameters) { + const { amount, token, throwOnReceiptRevert = true } = parameters; + const { decimals } = resolveToken(client, { token }); + const resolved = resolveAmountDecimals(amount, decimals); + const receipt = await transfer.inner(writeContractSync, client, { + ...parameters, + throwOnReceiptRevert + }); + const { args } = transfer.extractEvent(receipt.logs); + return { + ...args, + ...resolved === undefined ? {} : { decimals: resolved, formatted: formatUnits2(args.value, resolved) }, + receipt + }; +} +// ../viem/src/_esm/clients/decorators/public.js +function publicActions(client) { + return { + call: (args) => call(client, args), + createAccessList: (args) => createAccessList(client, args), + createBlockFilter: () => createBlockFilter(client), + createContractEventFilter: (args) => createContractEventFilter(client, args), + createEventFilter: (args) => createEventFilter(client, args), + createPendingTransactionFilter: () => createPendingTransactionFilter(client), + estimateContractGas: (args) => estimateContractGas(client, args), + estimateGas: (args) => estimateGas(client, args), + getBalance: (args) => getBalance(client, args), + getBlobBaseFee: () => getBlobBaseFee(client), + getBlock: (args) => getBlock(client, args), + getBlockNumber: (args) => getBlockNumber(client, args), + getBlockReceipts: (args) => getBlockReceipts(client, args), + getBlockTransactionCount: (args) => getBlockTransactionCount(client, args), + getBytecode: (args) => getCode(client, args), + getChainId: () => getChainId(client), + getCode: (args) => getCode(client, args), + getContractEvents: (args) => getContractEvents(client, args), + getDelegation: (args) => getDelegation(client, args), + getEip712Domain: (args) => getEip712Domain(client, args), + getEnsAddress: (args) => getEnsAddress(client, args), + getEnsAvatar: (args) => getEnsAvatar(client, args), + getEnsName: (args) => getEnsName(client, args), + getEnsResolver: (args) => getEnsResolver(client, args), + getEnsText: (args) => getEnsText(client, args), + getFeeHistory: (args) => getFeeHistory(client, args), + estimateFeesPerGas: (args) => estimateFeesPerGas(client, args), + getFilterChanges: (args) => getFilterChanges(client, args), + getFilterLogs: (args) => getFilterLogs(client, args), + getGasPrice: () => getGasPrice(client), + getLogs: (args) => getLogs(client, args), + getProof: (args) => getProof(client, args), + estimateMaxPriorityFeePerGas: (args) => estimateMaxPriorityFeePerGas(client, args), + fillTransaction: (args) => fillTransaction(client, args), + getRawTransaction: (args) => getRawTransaction(client, args), + getStorageAt: (args) => getStorageAt(client, args), + getTransaction: (args) => getTransaction(client, args), + getTransactionConfirmations: (args) => getTransactionConfirmations(client, args), + getTransactionCount: (args) => getTransactionCount(client, args), + getTransactionReceipt: (args) => getTransactionReceipt(client, args), + multicall: (args) => multicall(client, args), + prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), + readContract: (args) => readContract(client, args), + sendRawTransaction: (args) => sendRawTransaction(client, args), + sendRawTransactionSync: (args) => sendRawTransactionSync(client, args), + simulate: (args) => simulateBlocks(client, args), + simulateBlocks: (args) => simulateBlocks(client, args), + simulateCalls: (args) => simulateCalls(client, args), + simulateContract: (args) => simulateContract(client, args), + verifyHash: (args) => verifyHash2(client, args), + verifyMessage: (args) => verifyMessage2(client, args), + verifySiweMessage: (args) => verifySiweMessage(client, args), + verifyTypedData: (args) => verifyTypedData2(client, args), + uninstallFilter: (args) => uninstallFilter(client, args), + waitForTransactionReceipt: (args) => waitForTransactionReceipt(client, args), + watchBlockHeaders: (args) => watchBlockHeaders(client, args), + watchBlocks: (args) => watchBlocks(client, args), + watchBlockNumber: (args) => watchBlockNumber(client, args), + watchContractEvent: (args) => watchContractEvent(client, args), + watchEvent: (args) => watchEvent(client, args), + watchPendingTransactions: (args) => watchPendingTransactions(client, args), + token: bindPublicToken(client) + }; +} +function bindPublicToken(client) { + return { + getAllowance: bindActionDecorators(client, getAllowance), + getBalance: bindActionDecorators(client, getBalance2), + getMetadata: bindActionDecorators(client, getMetadata), + getTotalSupply: bindActionDecorators(client, getTotalSupply) + }; +} + +// ../viem/src/_esm/clients/createPublicClient.js +function createPublicClient(parameters) { + const { key = "public", name = "Public Client" } = parameters; + const client = createClient({ + ...parameters, + key, + name, + type: "publicClient" + }); + return client.extend(publicActions); +} +// ../viem/src/_esm/actions/wallet/addChain.js +init_toHex(); +async function addChain(client, { chain }) { + const { id, name, nativeCurrency, rpcUrls, blockExplorers } = chain; + await client.request({ + method: "wallet_addEthereumChain", + params: [ { - indexed: false, - name: "amount", - type: "uint256" + chainId: numberToHex(id), + chainName: name, + nativeCurrency, + rpcUrls: rpcUrls.default.http, + blockExplorerUrls: blockExplorers ? Object.values(blockExplorers).map(({ url }) => url) : undefined + } + ] + }, { dedupe: true, retryCount: 0 }); +} + +// ../viem/src/_esm/actions/wallet/deployContract.js +init_encodeDeployData(); +function deployContract(walletClient, parameters) { + const { abi: abi2, args, bytecode, ...request } = parameters; + const calldata = encodeDeployData({ abi: abi2, args, bytecode }); + return sendTransaction(walletClient, { + ...request, + ...request.authorizationList ? { to: null } : {}, + data: calldata + }); +} + +// ../viem/src/_esm/actions/wallet/getAddresses.js +init_getAddress(); +async function getAddresses(client) { + if (client.account?.type === "local") + return [client.account.address]; + const addresses = await client.request({ method: "eth_accounts" }, { dedupe: true }); + return addresses.map((address) => checksumAddress(address)); +} + +// ../viem/src/_esm/actions/wallet/getCallsStatus.js +init_slice(); +init_fromHex(); + +// ../viem/src/_esm/actions/wallet/sendCalls.js +init_base(); +init_rpc(); +init_encodeFunctionData(); +init_fromHex(); +init_toHex(); +var fallbackMagicIdentifier = "0x5792579257925792579257925792579257925792579257925792579257925792"; +var fallbackTransactionErrorMagicIdentifier = numberToHex(0, { + size: 32 +}); +async function sendCalls(client, parameters) { + const { account: account_ = client.account, chain = client.chain, experimental_fallback, experimental_fallbackDelay = 32, forceAtomic = false, id, version: version4 = "2.0.0" } = parameters; + const account = account_ ? parseAccount(account_) : null; + let capabilities = parameters.capabilities; + if (client.dataSuffix && !parameters.capabilities?.dataSuffix) { + if (typeof client.dataSuffix === "string") + capabilities = { + ...parameters.capabilities, + dataSuffix: { value: client.dataSuffix, optional: true } + }; + else + capabilities = { + ...parameters.capabilities, + dataSuffix: { + value: client.dataSuffix.value, + ...client.dataSuffix.required ? {} : { optional: true } + } + }; + } + const calls = parameters.calls.map((call_) => { + const call2 = call_; + const data = call2.abi ? encodeFunctionData({ + abi: call2.abi, + functionName: call2.functionName, + args: call2.args + }) : call2.data; + return { + data: call2.dataSuffix && data ? concat([data, call2.dataSuffix]) : data, + to: call2.to, + value: call2.value ? numberToHex(call2.value) : undefined + }; + }); + try { + const response = await client.request({ + method: "wallet_sendCalls", + params: [ + { + atomicRequired: forceAtomic, + calls, + capabilities, + chainId: numberToHex(chain.id), + from: account?.address, + id, + version: version4 + } + ] + }, { retryCount: 0 }); + if (typeof response === "string") + return { id: response }; + return response; + } catch (err) { + const error = err; + if (experimental_fallback && (error.name === "MethodNotFoundRpcError" || error.name === "MethodNotSupportedRpcError" || error.name === "UnknownRpcError" || error.details.toLowerCase().includes("does not exist / is not available") || error.details.toLowerCase().includes("missing or invalid. request()") || error.details.toLowerCase().includes("did not match any variant of untagged enum") || error.details.toLowerCase().includes("account upgraded to unsupported contract") || error.details.toLowerCase().includes("eip-7702 not supported") || error.details.toLowerCase().includes("unsupported wc_ method") || error.details.toLowerCase().includes("feature toggled misconfigured") || error.details.toLowerCase().includes("jsonrpcengine: response has no error or result for request"))) { + if (capabilities) { + const hasNonOptionalCapability = Object.values(capabilities).some((capability) => !capability.optional); + if (hasNonOptionalCapability) { + const message = "non-optional `capabilities` are not supported on fallback to `eth_sendTransaction`."; + throw new UnsupportedNonOptionalCapabilityError(new BaseError2(message, { + details: message + })); + } + } + if (forceAtomic && calls.length > 1) { + const message = "`forceAtomic` is not supported on fallback to `eth_sendTransaction`."; + throw new AtomicityNotSupportedError(new BaseError2(message, { + details: message + })); + } + const results = []; + for (const call2 of calls) { + try { + const value = await sendTransaction(client, { + account, + chain, + data: call2.data, + to: call2.to, + value: call2.value ? hexToBigInt(call2.value) : undefined + }); + results.push({ status: "fulfilled", value }); + } catch (reason) { + results.push({ reason, status: "rejected" }); + } + if (experimental_fallbackDelay > 0) + await new Promise((resolve) => setTimeout(resolve, experimental_fallbackDelay)); + } + if (results.every((r) => r.status === "rejected")) + throw results[0].reason; + const hashes = results.map((result) => { + if (result.status === "fulfilled") + return result.value; + return fallbackTransactionErrorMagicIdentifier; + }); + return { + id: concat([ + ...hashes, + numberToHex(chain.id, { size: 32 }), + fallbackMagicIdentifier + ]) + }; + } + throw getTransactionError(err, { + ...parameters, + account, + chain: parameters.chain + }); + } +} + +// ../viem/src/_esm/actions/wallet/getCallsStatus.js +async function getCallsStatus(client, parameters) { + async function getStatus(id) { + const isTransactions = id.endsWith(fallbackMagicIdentifier.slice(2)); + if (isTransactions) { + const chainId2 = trim(sliceHex(id, -64, -32)); + const hashes = sliceHex(id, 0, -64).slice(2).match(/.{1,64}/g); + const receipts2 = await Promise.all(hashes.map((hash3) => fallbackTransactionErrorMagicIdentifier.slice(2) !== hash3 ? client.request({ + method: "eth_getTransactionReceipt", + params: [`0x${hash3}`] + }, { dedupe: true }) : undefined)); + const status2 = (() => { + if (receipts2.some((r) => r === null)) + return 100; + if (receipts2.every((r) => r?.status === "0x1")) + return 200; + if (receipts2.every((r) => r?.status === "0x0")) + return 500; + return 600; + })(); + return { + atomic: false, + chainId: hexToNumber(chainId2), + receipts: receipts2.filter(Boolean), + status: status2, + version: "2.0.0" + }; + } + return client.request({ + method: "wallet_getCallsStatus", + params: [id] + }); + } + const { atomic = false, chainId, receipts, version: version4 = "2.0.0", ...response } = await getStatus(parameters.id); + const [status, statusCode] = (() => { + const statusCode2 = response.status; + if (statusCode2 >= 100 && statusCode2 < 200) + return ["pending", statusCode2]; + if (statusCode2 >= 200 && statusCode2 < 300) + return ["success", statusCode2]; + if (statusCode2 >= 300 && statusCode2 < 700) + return ["failure", statusCode2]; + if (statusCode2 === "CONFIRMED") + return ["success", 200]; + if (statusCode2 === "PENDING") + return ["pending", 100]; + return [undefined, statusCode2]; + })(); + return { + ...response, + atomic, + chainId: chainId ? hexToNumber(chainId) : undefined, + receipts: receipts?.map((receipt) => ({ + ...receipt, + blockNumber: hexToBigInt(receipt.blockNumber), + gasUsed: hexToBigInt(receipt.gasUsed), + status: receiptStatuses[receipt.status] + })) ?? [], + statusCode, + status, + version: version4 + }; +} + +// ../viem/src/_esm/actions/wallet/getCapabilities.js +init_toHex(); +async function getCapabilities(client, parameters = {}) { + const { account = client.account, chainId } = parameters; + const account_ = account ? parseAccount(account) : undefined; + const params = chainId ? [account_?.address, [numberToHex(chainId)]] : [account_?.address]; + const capabilities_raw = await client.request({ + method: "wallet_getCapabilities", + params + }); + const capabilities = {}; + for (const [chainId2, capabilities_] of Object.entries(capabilities_raw)) { + capabilities[Number(chainId2)] = {}; + for (let [key, value] of Object.entries(capabilities_)) { + if (key === "addSubAccount") + key = "unstable_addSubAccount"; + capabilities[Number(chainId2)][key] = value; + } + } + return typeof chainId === "number" ? capabilities[chainId] : capabilities; +} + +// ../viem/src/_esm/actions/wallet/getPermissions.js +async function getPermissions(client) { + const permissions = await client.request({ method: "wallet_getPermissions" }, { dedupe: true }); + return permissions; +} +// ../viem/src/_esm/actions/wallet/prepareAuthorization.js +init_isAddressEqual(); +async function prepareAuthorization(client, parameters) { + const { account: account_ = client.account, chainId, nonce } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/eip7702/prepareAuthorization" + }); + const account = parseAccount(account_); + const executor = (() => { + if (!parameters.executor) + return; + if (parameters.executor === "self") + return parameters.executor; + return parseAccount(parameters.executor); + })(); + const authorization = { + address: parameters.contractAddress ?? parameters.address, + chainId, + nonce + }; + if (typeof authorization.chainId === "undefined") + authorization.chainId = client.chain?.id ?? await getAction(client, getChainId, "getChainId")({}); + if (typeof authorization.nonce === "undefined") { + authorization.nonce = await getAction(client, getTransactionCount, "getTransactionCount")({ + address: account.address, + blockTag: "pending" + }); + if (executor === "self" || executor?.address && isAddressEqual(executor.address, account.address)) + authorization.nonce += 1; + } + return authorization; +} + +// ../viem/src/_esm/actions/wallet/requestAddresses.js +init_getAddress(); +async function requestAddresses(client) { + const addresses = await client.request({ method: "eth_requestAccounts" }, { dedupe: true, retryCount: 0 }); + return addresses.map((address) => getAddress(address)); +} + +// ../viem/src/_esm/actions/wallet/requestPermissions.js +async function requestPermissions(client, permissions) { + return client.request({ + method: "wallet_requestPermissions", + params: [permissions] + }, { retryCount: 0 }); +} + +// ../viem/src/_esm/actions/wallet/waitForCallsStatus.js +init_base(); + +// ../viem/src/_esm/errors/calls.js +init_base(); + +class BundleFailedError extends BaseError2 { + constructor(result) { + super(`Call bundle failed with status: ${result.statusCode}`, { + name: "BundleFailedError" + }); + Object.defineProperty(this, "result", { + enumerable: true, + configurable: true, + writable: true, + value: undefined + }); + this.result = result; + } +} +// ../viem/src/_esm/actions/wallet/waitForCallsStatus.js +async function waitForCallsStatus(client, parameters) { + const { + id, + pollingInterval = client.pollingInterval, + status = ({ statusCode }) => statusCode === 200 || statusCode >= 300, + retryCount = 4, + retryDelay = ({ count }) => ~~(1 << count) * 200, + timeout = 60000, + throwOnFailure = false + } = parameters; + const observerId = stringify(["waitForCallsStatus", client.uid, id]); + const { promise, resolve, reject } = withResolvers(); + let timer; + const unobserve = observe(observerId, { resolve, reject }, (emit) => { + const unpoll = poll(async () => { + const done = (fn) => { + clearTimeout(timer); + unpoll(); + fn(); + unobserve(); + }; + try { + const result = await withRetry(async () => { + const result2 = await getAction(client, getCallsStatus, "getCallsStatus")({ id }); + if (throwOnFailure && result2.status === "failure") + throw new BundleFailedError(result2); + return result2; + }, { + retryCount, + delay: retryDelay + }); + if (!status(result)) + return; + done(() => emit.resolve(result)); + } catch (error) { + done(() => emit.reject(error)); } - ], - name: "StakeWithdrawn", - type: "event" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "userOpHash", - type: "bytes32" - }, - { - indexed: true, - name: "sender", - type: "address" - }, - { - indexed: true, - name: "paymaster", - type: "address" - }, - { - indexed: false, - name: "nonce", - type: "uint256" - }, - { indexed: false, name: "success", type: "bool" }, - { - indexed: false, - name: "actualGasCost", - type: "uint256" - }, + }, { + interval: pollingInterval, + emitOnBegin: true + }); + return unpoll; + }); + timer = timeout ? setTimeout(() => { + unobserve(); + clearTimeout(timer); + reject(new WaitForCallsStatusTimeoutError({ id })); + }, timeout) : undefined; + return await promise; +} + +class WaitForCallsStatusTimeoutError extends BaseError2 { + constructor({ id }) { + super(`Timed out while waiting for call bundle with id "${id}" to be confirmed.`, { name: "WaitForCallsStatusTimeoutError" }); + } +} + +// ../viem/src/_esm/actions/wallet/sendCallsSync.js +async function sendCallsSync(client, parameters) { + const { chain = client.chain } = parameters; + const timeout = parameters.timeout ?? Math.max((chain?.blockTime ?? 0) * 3, 5000); + const result = await getAction(client, sendCalls, "sendCalls")(parameters); + const status = await getAction(client, waitForCallsStatus, "waitForCallsStatus")({ + ...parameters, + id: result.id, + timeout + }); + return status; +} + +// ../viem/src/_esm/actions/wallet/showCallsStatus.js +async function showCallsStatus(client, parameters) { + const { id } = parameters; + await client.request({ + method: "wallet_showCallsStatus", + params: [id] + }); + return; +} +// ../viem/src/_esm/actions/wallet/signAuthorization.js +async function signAuthorization(client, parameters) { + const { account: account_ = client.account } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/eip7702/signAuthorization" + }); + const account = parseAccount(account_); + if (!account.signAuthorization) + throw new AccountTypeNotSupportedError({ + docsPath: "/docs/eip7702/signAuthorization", + metaMessages: [ + "The `signAuthorization` Action does not support JSON-RPC Accounts." + ], + type: account.type + }); + const authorization = await prepareAuthorization(client, parameters); + return account.signAuthorization(authorization); +} +// ../viem/src/_esm/actions/wallet/signMessage.js +init_toHex(); +async function signMessage(client, { account: account_ = client.account, message }) { + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signMessage" + }); + const account = parseAccount(account_); + if (account.signMessage) + return account.signMessage({ message }); + const message_ = (() => { + if (typeof message === "string") + return stringToHex(message); + if (message.raw instanceof Uint8Array) + return toHex(message.raw); + return message.raw; + })(); + return client.request({ + method: "personal_sign", + params: [message_, account.address] + }, { retryCount: 0 }); +} +// ../viem/src/_esm/actions/wallet/signTransaction.js +init_toHex(); +init_transactionRequest(); +init_assertRequest(); +async function signTransaction(client, parameters) { + const { account: account_ = client.account, chain = client.chain, ...transaction } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signTransaction" + }); + const account = parseAccount(account_); + assertRequest({ + account, + ...parameters + }); + const chainId = await getAction(client, getChainId, "getChainId")({}); + if (chain !== null) + assertCurrentChain2({ + currentChainId: chainId, + chain + }); + const formatters = chain?.formatters || client.chain?.formatters; + const format2 = formatters?.transactionRequest?.format || formatTransactionRequest; + if (account.signTransaction) + return account.signTransaction({ + ...transaction, + account, + chainId + }, { serializer: client.chain?.serializers?.transaction }); + return await client.request({ + method: "eth_signTransaction", + params: [ { - indexed: false, - name: "actualGasUsed", - type: "uint256" + ...format2({ + ...transaction, + account + }, "signTransaction"), + chainId: numberToHex(chainId), + from: account.address } - ], - name: "UserOperationEvent", - type: "event" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "userOpHash", - type: "bytes32" - }, - { - indexed: true, - name: "sender", - type: "address" - }, + ] + }, { retryCount: 0 }); +} +// ../viem/src/_esm/actions/wallet/signTypedData.js +async function signTypedData(client, parameters) { + const { account: account_ = client.account, domain, message, primaryType } = parameters; + if (!account_) + throw new AccountNotFoundError({ + docsPath: "/docs/actions/wallet/signTypedData" + }); + const account = parseAccount(account_); + const types = { + EIP712Domain: getTypesForEIP712Domain({ domain }), + ...parameters.types + }; + validateTypedData2({ domain, message, primaryType, types }); + if (account.signTypedData) + return account.signTypedData({ domain, message, primaryType, types }); + const typedData = serializeTypedData2({ domain, message, primaryType, types }); + return client.request({ + method: "eth_signTypedData_v4", + params: [account.address, typedData] + }, { retryCount: 0 }); +} + +// ../viem/src/_esm/actions/wallet/switchChain.js +init_toHex(); +async function switchChain(client, { id }) { + await client.request({ + method: "wallet_switchEthereumChain", + params: [ { - indexed: false, - name: "nonce", - type: "uint256" + chainId: numberToHex(id) } - ], - name: "UserOperationPrefundTooLow", - type: "event" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "userOpHash", - type: "bytes32" - }, - { - indexed: true, - name: "sender", - type: "address" - }, - { - indexed: false, - name: "nonce", - type: "uint256" - }, - { - indexed: false, - name: "revertReason", - type: "bytes" + ] + }, { retryCount: 0 }); +} + +// ../viem/src/_esm/actions/wallet/watchAsset.js +async function watchAsset(client, params) { + const added = await client.request({ + method: "wallet_watchAsset", + params + }, { retryCount: 0 }); + return added; +} + +// ../viem/src/_esm/clients/decorators/wallet.js +function walletActions(client) { + return { + addChain: (args) => addChain(client, args), + deployContract: (args) => deployContract(client, args), + fillTransaction: (args) => fillTransaction(client, args), + getAddresses: () => getAddresses(client), + getCallsStatus: (args) => getCallsStatus(client, args), + getCapabilities: (args) => getCapabilities(client, args), + getChainId: () => getChainId(client), + getPermissions: () => getPermissions(client), + prepareAuthorization: (args) => prepareAuthorization(client, args), + prepareTransactionRequest: (args) => prepareTransactionRequest(client, args), + requestAddresses: () => requestAddresses(client), + requestPermissions: (args) => requestPermissions(client, args), + sendCalls: (args) => sendCalls(client, args), + sendCallsSync: (args) => sendCallsSync(client, args), + sendRawTransaction: (args) => sendRawTransaction(client, args), + sendRawTransactionSync: (args) => sendRawTransactionSync(client, args), + sendTransaction: (args) => sendTransaction(client, args), + sendTransactionSync: (args) => sendTransactionSync(client, args), + showCallsStatus: (args) => showCallsStatus(client, args), + signAuthorization: (args) => signAuthorization(client, args), + signMessage: (args) => signMessage(client, args), + signTransaction: (args) => signTransaction(client, args), + signTypedData: (args) => signTypedData(client, args), + switchChain: (args) => switchChain(client, args), + waitForCallsStatus: (args) => waitForCallsStatus(client, args), + watchAsset: (args) => watchAsset(client, args), + writeContract: (args) => writeContract(client, args), + writeContractSync: (args) => writeContractSync(client, args), + token: { + approve: bindActionDecorators(client, approve), + approveSync: bindActionDecorators(client, approveSync), + transfer: bindActionDecorators(client, transfer), + transferSync: bindActionDecorators(client, transferSync) + } + }; +} + +// ../viem/src/_esm/clients/createWalletClient.js +function createWalletClient(parameters) { + const { key = "wallet", name = "Wallet Client", transport } = parameters; + const client = createClient({ + ...parameters, + key, + name, + transport, + type: "walletClient" + }); + return client.extend(walletActions); +} +// ../viem/src/_esm/utils/buildRequest.js +init_base(); +init_request(); +init_rpc(); + +// ../viem/src/_esm/utils/promise/withDedupe.js +init_lru(); +var promiseCache2 = /* @__PURE__ */ new LruMap(8192); +function withDedupe(fn, { enabled = true, id }) { + if (!enabled || !id) + return fn(); + if (promiseCache2.get(id)) + return promiseCache2.get(id); + const promise = fn().finally(() => promiseCache2.delete(id)); + promiseCache2.set(id, promise); + return promise; +} + +// ../viem/src/_esm/utils/buildRequest.js +function buildRequest2(request, options = {}) { + return async (args, overrideOptions = {}) => { + const { dedupe = false, methods, retryDelay = 150, retryCount = 3, signal, uid: uid2 } = { + ...options, + ...overrideOptions + }; + const { method } = args; + if (methods?.exclude?.includes(method)) + throw new MethodNotSupportedRpcError(new Error("method not supported"), { + method + }); + if (methods?.include && !methods.include.includes(method)) + throw new MethodNotSupportedRpcError(new Error("method not supported"), { + method + }); + if (signal?.aborted) + throw getAbortError(signal); + const requestId = dedupe ? hashString(`${uid2}.${stringify(args)}`) : undefined; + return withDedupe(() => withRetry(async () => { + try { + return await request(args, signal ? { signal } : undefined); + } catch (err_) { + if (signal?.aborted) + throw getAbortError(signal); + if (isAbortError(err_)) + throw err_; + const err = err_; + switch (err.code) { + case ParseRpcError.code: + throw new ParseRpcError(err); + case InvalidRequestRpcError.code: + throw new InvalidRequestRpcError(err); + case MethodNotFoundRpcError.code: + throw new MethodNotFoundRpcError(err, { method: args.method }); + case InvalidParamsRpcError.code: + throw new InvalidParamsRpcError(err); + case InternalRpcError.code: + throw new InternalRpcError(err); + case InvalidInputRpcError.code: + throw new InvalidInputRpcError(err); + case ResourceNotFoundRpcError.code: + throw new ResourceNotFoundRpcError(err); + case ResourceUnavailableRpcError.code: + throw new ResourceUnavailableRpcError(err); + case TransactionRejectedRpcError.code: + throw new TransactionRejectedRpcError(err); + case MethodNotSupportedRpcError.code: + throw new MethodNotSupportedRpcError(err, { + method: args.method + }); + case LimitExceededRpcError.code: + throw new LimitExceededRpcError(err); + case JsonRpcVersionUnsupportedError.code: + throw new JsonRpcVersionUnsupportedError(err); + case UserRejectedRequestError.code: + throw new UserRejectedRequestError(err); + case UnauthorizedProviderError.code: + throw new UnauthorizedProviderError(err); + case UnsupportedProviderMethodError.code: + throw new UnsupportedProviderMethodError(err); + case ProviderDisconnectedError.code: + throw new ProviderDisconnectedError(err); + case ChainDisconnectedError.code: + throw new ChainDisconnectedError(err); + case SwitchChainError.code: + throw new SwitchChainError(err); + case UnsupportedNonOptionalCapabilityError.code: + throw new UnsupportedNonOptionalCapabilityError(err); + case UnsupportedChainIdError.code: + throw new UnsupportedChainIdError(err); + case DuplicateIdError.code: + throw new DuplicateIdError(err); + case UnknownBundleIdError.code: + throw new UnknownBundleIdError(err); + case BundleTooLargeError.code: + throw new BundleTooLargeError(err); + case AtomicReadyWalletRejectedUpgradeError.code: + throw new AtomicReadyWalletRejectedUpgradeError(err); + case AtomicityNotSupportedError.code: + throw new AtomicityNotSupportedError(err); + case 5000: + throw new UserRejectedRequestError(err); + case WalletConnectSessionSettlementError.code: + throw new WalletConnectSessionSettlementError(err); + default: + if (err_ instanceof BaseError2) + throw err_; + throw new UnknownRpcError(err); + } } - ], - name: "UserOperationRevertReason", - type: "event" - }, - { - anonymous: false, - inputs: [ - { - indexed: true, - name: "account", - type: "address" - }, - { - indexed: false, - name: "withdrawAddress", - type: "address" + }, { + delay: ({ count, error }) => { + if (error && error instanceof HttpRequestError) { + const retryAfter = error?.headers?.get("Retry-After"); + if (retryAfter?.match(/\d/)) + return Number.parseInt(retryAfter, 10) * 1000; + } + return ~~(1 << count) * retryDelay; }, - { - indexed: false, - name: "amount", - type: "uint256" - } - ], - name: "Withdrawn", - type: "event" - }, - { - inputs: [{ name: "unstakeDelaySec", type: "uint32" }], - name: "addStake", - outputs: [], - stateMutability: "payable", - type: "function" - }, - { - inputs: [{ name: "account", type: "address" }], - name: "balanceOf", - outputs: [{ name: "", type: "uint256" }], - stateMutability: "view", - type: "function" - }, - { - inputs: [ - { name: "target", type: "address" }, - { name: "data", type: "bytes" } - ], - name: "delegateAndRevert", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [{ name: "account", type: "address" }], - name: "depositTo", - outputs: [], - stateMutability: "payable", - type: "function" - }, - { - inputs: [{ name: "", type: "address" }], - name: "deposits", - outputs: [ - { name: "deposit", type: "uint256" }, - { name: "staked", type: "bool" }, - { name: "stake", type: "uint112" }, - { name: "unstakeDelaySec", type: "uint32" }, - { name: "withdrawTime", type: "uint48" } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [{ name: "account", type: "address" }], - name: "getDepositInfo", - outputs: [ - { - components: [ - { name: "deposit", type: "uint256" }, - { name: "staked", type: "bool" }, - { name: "stake", type: "uint112" }, - { name: "unstakeDelaySec", type: "uint32" }, - { name: "withdrawTime", type: "uint48" } - ], - name: "info", - type: "tuple" - } - ], - stateMutability: "view", - type: "function" - }, - { - inputs: [ - { name: "sender", type: "address" }, - { name: "key", type: "uint192" } - ], - name: "getNonce", - outputs: [{ name: "nonce", type: "uint256" }], - stateMutability: "view", - type: "function" - }, - { - inputs: [{ name: "initCode", type: "bytes" }], - name: "getSenderAddress", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - components: [ - { name: "sender", type: "address" }, - { name: "nonce", type: "uint256" }, - { name: "initCode", type: "bytes" }, - { name: "callData", type: "bytes" }, - { - name: "accountGasLimits", - type: "bytes32" - }, - { - name: "preVerificationGas", - type: "uint256" - }, - { name: "gasFees", type: "bytes32" }, - { name: "paymasterAndData", type: "bytes" }, - { name: "signature", type: "bytes" } - ], - name: "userOp", - type: "tuple" + retryCount, + signal, + shouldRetry: ({ error }) => shouldRetry(error) + }), { enabled: dedupe, id: requestId }); + }; +} +function shouldRetry(error) { + if (isAbortError(error)) + return false; + if ("code" in error && typeof error.code === "number") { + if (error.code === -1) + return true; + if (error.code === LimitExceededRpcError.code) + return true; + if (error.code === InternalRpcError.code) + return true; + if (error.code === 429) + return true; + return false; + } + if (error instanceof HttpRequestError && error.status) { + if (error.status === 403) + return true; + if (error.status === 408) + return true; + if (error.status === 413) + return true; + if (error.status === 429) + return true; + if (error.status === 500) + return true; + if (error.status === 502) + return true; + if (error.status === 503) + return true; + if (error.status === 504) + return true; + return false; + } + return true; +} +function hashString(str, seed = 0) { + let h1 = 3735928559 ^ seed; + let h2 = 1103547991 ^ seed; + for (let i = 0;i < str.length; i++) { + const ch = str.charCodeAt(i); + h1 = Math.imul(h1 ^ ch, 2654435761); + h2 = Math.imul(h2 ^ ch, 1597334677); + } + h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507); + h1 ^= Math.imul(h2 ^ h2 >>> 16, 3266489909); + h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507); + h2 ^= Math.imul(h1 ^ h1 >>> 16, 3266489909); + return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36); +} + +// ../viem/src/_esm/clients/transports/createTransport.js +function createTransport({ key, methods, name, request, retryCount = 3, retryDelay = 150, timeout, type }, value) { + const uid2 = uid(); + return { + config: { + key, + methods, + name, + request, + retryCount, + retryDelay, + timeout, + type + }, + request: buildRequest2(request, { methods, retryCount, retryDelay, uid: uid2 }), + value + }; +} + +// ../viem/src/_esm/clients/transports/custom.js +function custom(provider, config = {}) { + const { key = "custom", methods, name = "Custom Provider", retryDelay } = config; + return ({ retryCount: defaultRetryCount }) => createTransport({ + key, + methods, + name, + request: provider.request.bind(provider), + retryCount: config.retryCount ?? defaultRetryCount, + retryDelay, + type: "custom" + }); +} +// ../viem/src/_esm/clients/transports/http.js +init_request(); + +// ../viem/src/_esm/errors/transport.js +init_base(); + +class UrlRequiredError extends BaseError2 { + constructor() { + super("No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.", { + docsPath: "/docs/clients/intro", + name: "UrlRequiredError" + }); + } +} + +// ../viem/src/_esm/clients/transports/http.js +init_createBatchScheduler(); + +// ../viem/src/_esm/utils/rpc/http.js +init_request(); + +// ../viem/src/_esm/utils/promise/withTimeout.js +function withTimeout(fn, { errorInstance = new Error("timed out"), timeout, signal }) { + return new Promise((resolve, reject) => { + (async () => { + let timeoutId; + const controller = new AbortController; + try { + if (timeout > 0) { + timeoutId = setTimeout(() => { + if (signal) { + controller.abort(); + } else { + reject(errorInstance); + } + }, timeout); + } + resolve(await fn({ signal: controller?.signal || null })); + } catch (err) { + if (controller?.signal.aborted && isAbortError(err)) { + reject(errorInstance); + return; + } + reject(err); + } finally { + clearTimeout(timeoutId); } - ], - name: "getUserOpHash", - outputs: [{ name: "", type: "bytes32" }], - stateMutability: "view", - type: "function" - }, - { - inputs: [ - { - components: [ - { - components: [ - { name: "sender", type: "address" }, - { name: "nonce", type: "uint256" }, - { name: "initCode", type: "bytes" }, - { name: "callData", type: "bytes" }, - { - name: "accountGasLimits", - type: "bytes32" - }, - { - name: "preVerificationGas", - type: "uint256" - }, - { name: "gasFees", type: "bytes32" }, - { - name: "paymasterAndData", - type: "bytes" - }, - { name: "signature", type: "bytes" } - ], - name: "userOps", - type: "tuple[]" - }, - { - name: "aggregator", - type: "address" - }, - { name: "signature", type: "bytes" } - ], - name: "opsPerAggregator", - type: "tuple[]" - }, - { name: "beneficiary", type: "address" } - ], - name: "handleAggregatedOps", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - components: [ - { name: "sender", type: "address" }, - { name: "nonce", type: "uint256" }, - { name: "initCode", type: "bytes" }, - { name: "callData", type: "bytes" }, - { - name: "accountGasLimits", - type: "bytes32" - }, - { - name: "preVerificationGas", - type: "uint256" - }, - { name: "gasFees", type: "bytes32" }, - { name: "paymasterAndData", type: "bytes" }, - { name: "signature", type: "bytes" } - ], - name: "ops", - type: "tuple[]" - }, - { name: "beneficiary", type: "address" } - ], - name: "handleOps", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [{ name: "key", type: "uint192" }], - name: "incrementNonce", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { name: "callData", type: "bytes" }, - { - components: [ - { - components: [ - { name: "sender", type: "address" }, - { name: "nonce", type: "uint256" }, - { - name: "verificationGasLimit", - type: "uint256" - }, - { - name: "callGasLimit", - type: "uint256" - }, - { - name: "paymasterVerificationGasLimit", - type: "uint256" - }, - { - name: "paymasterPostOpGasLimit", - type: "uint256" - }, - { - name: "preVerificationGas", - type: "uint256" - }, - { name: "paymaster", type: "address" }, - { - name: "maxFeePerGas", - type: "uint256" - }, - { - name: "maxPriorityFeePerGas", - type: "uint256" - } - ], - name: "mUserOp", - type: "tuple" + })(); + }); +} +// ../viem/src/_esm/utils/rpc/id.js +function createIdStore() { + return { + current: 0, + take() { + return this.current++; + }, + reset() { + this.current = 0; + } + }; +} +var idCache = /* @__PURE__ */ createIdStore(); + +// ../viem/src/_esm/utils/rpc/http.js +var defaultMaxResponseBodySize = 10485760; +function getHttpRpcClient2(url_, options = {}) { + const { url, headers: headers_url } = parseUrl(url_); + return { + async request(params) { + const { body, fetchFn = options.fetchFn ?? fetch, maxResponseBodySize = options.maxResponseBodySize ?? defaultMaxResponseBodySize, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 1e4 } = params; + const fetchOptions = { + ...options.fetchOptions ?? {}, + ...params.fetchOptions ?? {} + }; + const { headers, method, signal: signal_ } = fetchOptions; + try { + const response = await withTimeout(async ({ signal }) => { + const init = { + ...fetchOptions, + body: Array.isArray(body) ? stringify(body.map((body2) => ({ + jsonrpc: "2.0", + id: body2.id ?? idCache.take(), + ...body2 + }))) : stringify({ + jsonrpc: "2.0", + id: body.id ?? idCache.take(), + ...body + }), + headers: { + ...headers_url, + "Content-Type": "application/json", + ...headers + }, + method: method || "POST", + signal: signal_ || (timeout > 0 ? signal : null) + }; + const request = new Request(url, init); + const args = await onRequest?.(request, init) ?? { ...init, url }; + const response2 = await fetchFn(args.url ?? url, args); + return response2; + }, { + errorInstance: new TimeoutError({ body, url }), + timeout, + signal: true + }); + if (onResponse) + await onResponse(response); + let data; + const responseBody = await readResponseBody(response, { + maxResponseBodySize + }); + if (response.headers.get("Content-Type")?.startsWith("application/json")) + data = JSON.parse(responseBody); + else { + data = responseBody; + try { + data = JSON.parse(data || "{}"); + } catch (err) { + if (response.ok) + throw err; + data = { error: data }; + } + } + if (!response.ok) { + if (typeof data.error?.code === "number" && typeof data.error?.message === "string") + return data; + throw new HttpRequestError({ + body, + details: stringify(data.error) || response.statusText, + headers: response.headers, + status: response.status, + url + }); + } + return data; + } catch (err) { + if (signal_?.aborted) + throw getAbortError(signal_); + if (isAbortError(err)) + throw err; + if (err instanceof HttpRequestError) + throw err; + if (err instanceof ResponseBodyTooLargeError) + throw err; + if (err instanceof TimeoutError) + throw err; + throw new HttpRequestError({ + body, + cause: err, + url + }); + } + } + }; +} +async function readResponseBody(response, { maxResponseBodySize }) { + if (maxResponseBodySize === false) + return response.text(); + const contentLength = response.headers.get("Content-Length"); + if (contentLength) { + const size7 = Number(contentLength); + if (size7 > maxResponseBodySize) + throw new ResponseBodyTooLargeError({ + maxSize: maxResponseBodySize, + size: size7 + }); + } + if (!response.body) { + const body2 = await response.text(); + const size7 = new TextEncoder().encode(body2).length; + if (size7 > maxResponseBodySize) + throw new ResponseBodyTooLargeError({ + maxSize: maxResponseBodySize, + size: size7 + }); + return body2; + } + const reader = response.body.getReader(); + const decoder2 = new TextDecoder; + let body = ""; + let size6 = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) + break; + size6 += value.byteLength; + if (size6 > maxResponseBodySize) { + await reader.cancel(); + throw new ResponseBodyTooLargeError({ + maxSize: maxResponseBodySize, + size: size6 + }); + } + body += decoder2.decode(value, { stream: true }); + } + body += decoder2.decode(); + return body; + } finally { + reader.releaseLock(); + } +} +function parseUrl(url_) { + try { + const url = new URL(url_); + const result = (() => { + if (url.username) { + const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`; + url.username = ""; + url.password = ""; + return { + url: url.toString(), + headers: { Authorization: `Basic ${btoa(credentials)}` } + }; + } + return; + })(); + return { url: url.toString(), ...result }; + } catch { + return { url: url_ }; + } +} + +// ../viem/src/_esm/clients/transports/http.js +var signalId = 0; +var signalIds = new WeakMap; +function getSignalId(signal) { + if (!signal) + return "default"; + const id = signalIds.get(signal); + if (id !== undefined) + return id; + const nextId = signalId++; + signalIds.set(signal, nextId); + return nextId; +} +function http(url, config = {}) { + const { batch, fetchFn, fetchOptions, key = "http", maxResponseBodySize, methods, name = "HTTP JSON-RPC", onFetchRequest, onFetchResponse, retryDelay, raw } = config; + return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => { + const { batchSize = 1000, wait: wait2 = 0 } = typeof batch === "object" ? batch : {}; + const retryCount = config.retryCount ?? retryCount_; + const timeout = timeout_ ?? config.timeout ?? 1e4; + const url_ = url || chain?.rpcUrls.default.http[0]; + if (!url_) + throw new UrlRequiredError; + const rpcClient = getHttpRpcClient2(url_, { + fetchFn, + fetchOptions, + maxResponseBodySize, + onRequest: onFetchRequest, + onResponse: onFetchResponse, + timeout + }); + return createTransport({ + key, + methods, + name, + async request({ method, params }, options) { + const body = { method, params }; + const fetchOptions2 = options?.signal ? { signal: options.signal } : undefined; + const { schedule } = createBatchScheduler({ + id: `${url_}.${getSignalId(options?.signal)}`, + wait: wait2, + shouldSplitBatch(requests) { + return requests.length > batchSize; }, - { name: "userOpHash", type: "bytes32" }, - { name: "prefund", type: "uint256" }, - { name: "contextOffset", type: "uint256" }, - { name: "preOpGas", type: "uint256" } - ], - name: "opInfo", - type: "tuple" + fn: (body2) => rpcClient.request({ + body: body2, + fetchOptions: fetchOptions2 + }), + sort: (a, b) => a.id - b.id + }); + const fn = async (body2) => batch ? schedule(body2) : [ + await rpcClient.request({ + body: body2, + fetchOptions: fetchOptions2 + }) + ]; + const [{ error, result }] = await fn(body); + if (raw) + return { error, result }; + if (error) + throw new RpcRequestError({ + body, + error, + url: url_ + }); + return result; }, - { name: "context", type: "bytes" } - ], - name: "innerHandleOp", - outputs: [{ name: "actualGasCost", type: "uint256" }], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { name: "", type: "address" }, - { name: "", type: "uint192" } - ], - name: "nonceSequenceNumber", - outputs: [{ name: "", type: "uint256" }], - stateMutability: "view", - type: "function" - }, - { - inputs: [{ name: "interfaceId", type: "bytes4" }], - name: "supportsInterface", - outputs: [{ name: "", type: "bool" }], - stateMutability: "view", - type: "function" - }, - { - inputs: [], - name: "unlockStake", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - name: "withdrawAddress", - type: "address" + retryCount, + retryDelay, + timeout, + type: "http" + }, { + fetchOptions, + url: url_ + }); + }; +} + +// ../viem/src/_esm/index.js +init_decodeAbiParameters(); +init_encodeAbiParameters(); +init_encodeFunctionData(); +init_slice(); +init_fromHex(); +init_toHex(); +init_keccak256(); +init_formatEther(); + +// ../viem/src/_esm/utils/unit/parseEther.js +init_Value(); +function parseEther2(ether, unit = "wei") { + return fromEther(ether, unit); +} +// ../viem/src/_esm/accounts/generatePrivateKey.js +init_secp256k1(); +init_toHex(); +function generatePrivateKey() { + return toHex(secp256k1.utils.randomPrivateKey()); +} +// ../viem/src/_esm/accounts/privateKeyToAccount.js +init_secp256k1(); +init_toHex(); + +// ../viem/src/_esm/accounts/toAccount.js +init_address(); +init_isAddress(); +function toAccount(source) { + if (typeof source === "string") { + if (!isAddress(source, { strict: false })) + throw new InvalidAddressError({ address: source }); + return { + address: source, + type: "json-rpc" + }; + } + if (!isAddress(source.address, { strict: false })) + throw new InvalidAddressError({ address: source.address }); + return { + address: source.address, + nonceManager: source.nonceManager, + sign: source.sign, + signAuthorization: source.signAuthorization, + signMessage: source.signMessage, + signTransaction: source.signTransaction, + signTypedData: source.signTypedData, + source: "custom", + type: "local" + }; +} + +// ../viem/src/_esm/accounts/utils/sign.js +init_secp256k1(); +init_toBytes(); +init_toHex(); +var extraEntropy2 = false; +async function sign({ hash: hash3, privateKey, to = "object" }) { + const { r, s, recovery } = secp256k1.sign(hash3.slice(2), privateKey.slice(2), { + lowS: true, + extraEntropy: isHex(extraEntropy2, { strict: false }) ? hexToBytes(extraEntropy2) : extraEntropy2 + }); + const signature = { + r: numberToHex(r, { size: 32 }), + s: numberToHex(s, { size: 32 }), + v: recovery ? 28n : 27n, + yParity: recovery + }; + return (() => { + if (to === "bytes" || to === "hex") + return serializeSignature({ ...signature, to }); + return signature; + })(); +} + +// ../viem/src/_esm/accounts/utils/signAuthorization.js +async function signAuthorization2(parameters) { + const { chainId, nonce, privateKey, to = "object" } = parameters; + const address = parameters.contractAddress ?? parameters.address; + const signature = await sign({ + hash: hashAuthorization({ address, chainId, nonce }), + privateKey, + to + }); + if (to === "object") + return { + address, + chainId, + nonce, + ...signature + }; + return signature; +} + +// ../viem/src/_esm/accounts/utils/signMessage.js +async function signMessage2({ message, privateKey }) { + return await sign({ hash: hashMessage2(message), privateKey, to: "hex" }); +} + +// ../viem/src/_esm/accounts/utils/signTransaction.js +init_keccak256(); + +// ../viem/src/_esm/utils/transaction/serializeTransaction.js +init_transaction(); + +// ../viem/src/_esm/utils/authorization/serializeAuthorizationList.js +init_toHex(); +function serializeAuthorizationList2(authorizationList) { + if (!authorizationList || authorizationList.length === 0) + return []; + const serializedAuthorizationList = []; + for (const authorization of authorizationList) { + const { chainId, nonce, ...signature } = authorization; + const contractAddress = authorization.address; + serializedAuthorizationList.push([ + chainId ? toHex(chainId) : "0x", + contractAddress, + nonce ? toHex(nonce) : "0x", + ...toYParitySignatureArray({}, signature) + ]); + } + return serializedAuthorizationList; +} + +// ../viem/src/_esm/utils/transaction/serializeTransaction.js +init_toHex(); + +// ../viem/src/_esm/utils/transaction/assertTransaction.js +init_number(); +init_address(); +init_base(); +init_chain(); +init_node(); +init_isAddress(); +init_size(); +init_slice(); +init_fromHex(); +function assertTransactionEIP7702(transaction) { + const { authorizationList } = transaction; + if (authorizationList) { + for (const authorization of authorizationList) { + const { chainId } = authorization; + const address = authorization.address; + if (!isAddress(address)) + throw new InvalidAddressError({ address }); + if (chainId < 0) + throw new InvalidChainIdError({ chainId }); + } + } + assertTransactionEIP15593(transaction); +} +function assertTransactionEIP4844(transaction) { + const { blobVersionedHashes } = transaction; + if (blobVersionedHashes) { + if (blobVersionedHashes.length === 0) + throw new EmptyBlobError; + for (const hash3 of blobVersionedHashes) { + const size_ = size2(hash3); + const version4 = hexToNumber(slice(hash3, 0, 1)); + if (size_ !== 32) + throw new InvalidVersionedHashSizeError({ hash: hash3, size: size_ }); + if (version4 !== versionedHashVersionKzg) + throw new InvalidVersionedHashVersionError({ + hash: hash3, + version: version4 + }); + } + } + assertTransactionEIP15593(transaction); +} +function assertTransactionEIP15593(transaction) { + const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = transaction; + if (chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (to && !isAddress(to)) + throw new InvalidAddressError({ address: to }); + if (maxFeePerGas && maxFeePerGas > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas }); + if (maxPriorityFeePerGas && maxFeePerGas && maxPriorityFeePerGas > maxFeePerGas) + throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas }); +} +function assertTransactionEIP29303(transaction) { + const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction; + if (chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (to && !isAddress(to)) + throw new InvalidAddressError({ address: to }); + if (maxPriorityFeePerGas || maxFeePerGas) + throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute."); + if (gasPrice && gasPrice > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); +} +function assertTransactionLegacy3(transaction) { + const { chainId, maxPriorityFeePerGas, gasPrice, maxFeePerGas, to } = transaction; + if (to && !isAddress(to)) + throw new InvalidAddressError({ address: to }); + if (typeof chainId !== "undefined" && chainId <= 0) + throw new InvalidChainIdError({ chainId }); + if (maxPriorityFeePerGas || maxFeePerGas) + throw new BaseError2("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute."); + if (gasPrice && gasPrice > maxUint256) + throw new FeeCapTooHighError({ maxFeePerGas: gasPrice }); +} + +// ../viem/src/_esm/utils/transaction/serializeAccessList.js +init_address(); +init_transaction(); +init_isAddress(); +function serializeAccessList3(accessList) { + if (!accessList || accessList.length === 0) + return []; + const serializedAccessList = []; + for (let i = 0;i < accessList.length; i++) { + const { address, storageKeys } = accessList[i]; + for (let j = 0;j < storageKeys.length; j++) { + if (storageKeys[j].length - 2 !== 64) { + throw new InvalidStorageKeySizeError({ storageKey: storageKeys[j] }); + } + } + if (!isAddress(address, { strict: false })) { + throw new InvalidAddressError({ address }); + } + serializedAccessList.push([address, storageKeys]); + } + return serializedAccessList; +} + +// ../viem/src/_esm/utils/transaction/serializeTransaction.js +function serializeTransaction3(transaction, signature) { + const type = getTransactionType(transaction); + if (type === "eip1559") + return serializeTransactionEIP1559(transaction, signature); + if (type === "eip2930") + return serializeTransactionEIP2930(transaction, signature); + if (type === "eip4844") + return serializeTransactionEIP4844(transaction, signature); + if (type === "eip7702") + return serializeTransactionEIP7702(transaction, signature); + return serializeTransactionLegacy(transaction, signature); +} +function serializeTransactionEIP7702(transaction, signature) { + const { authorizationList, chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP7702(transaction); + const serializedAccessList = serializeAccessList3(accessList); + const serializedAuthorizationList = serializeAuthorizationList2(authorizationList); + return concatHex([ + "0x04", + toRlp([ + numberToHex(chainId), + nonce ? numberToHex(nonce) : "0x", + maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? numberToHex(maxFeePerGas) : "0x", + gas ? numberToHex(gas) : "0x", + to ?? "0x", + value ? numberToHex(value) : "0x", + data ?? "0x", + serializedAccessList, + serializedAuthorizationList, + ...toYParitySignatureArray(transaction, signature) + ]) + ]); +} +function serializeTransactionEIP4844(transaction, signature) { + const { chainId, gas, nonce, to, value, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP4844(transaction); + let blobVersionedHashes = transaction.blobVersionedHashes; + let sidecars = transaction.sidecars; + if (transaction.blobs && (typeof blobVersionedHashes === "undefined" || typeof sidecars === "undefined")) { + const blobs2 = typeof transaction.blobs[0] === "string" ? transaction.blobs : transaction.blobs.map((x) => bytesToHex(x)); + const kzg = transaction.kzg; + const commitments2 = blobsToCommitments({ + blobs: blobs2, + kzg + }); + if (typeof blobVersionedHashes === "undefined") + blobVersionedHashes = commitmentsToVersionedHashes({ + commitments: commitments2 + }); + if (typeof sidecars === "undefined") { + const proofs2 = blobsToProofs({ blobs: blobs2, commitments: commitments2, kzg }); + sidecars = toBlobSidecars({ blobs: blobs2, commitments: commitments2, proofs: proofs2 }); + } + } + const serializedAccessList = serializeAccessList3(accessList); + const serializedTransaction = [ + numberToHex(chainId), + nonce ? numberToHex(nonce) : "0x", + maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? numberToHex(maxFeePerGas) : "0x", + gas ? numberToHex(gas) : "0x", + to ?? "0x", + value ? numberToHex(value) : "0x", + data ?? "0x", + serializedAccessList, + maxFeePerBlobGas ? numberToHex(maxFeePerBlobGas) : "0x", + blobVersionedHashes ?? [], + ...toYParitySignatureArray(transaction, signature) + ]; + const blobs = []; + const commitments = []; + const proofs = []; + if (sidecars) + for (let i = 0;i < sidecars.length; i++) { + const { blob, commitment, proof } = sidecars[i]; + blobs.push(blob); + commitments.push(commitment); + proofs.push(proof); + } + return concatHex([ + "0x03", + sidecars ? toRlp([serializedTransaction, blobs, commitments, proofs]) : toRlp(serializedTransaction) + ]); +} +function serializeTransactionEIP1559(transaction, signature) { + const { chainId, gas, nonce, to, value, maxFeePerGas, maxPriorityFeePerGas, accessList, data } = transaction; + assertTransactionEIP15593(transaction); + const serializedAccessList = serializeAccessList3(accessList); + const serializedTransaction = [ + numberToHex(chainId), + nonce ? numberToHex(nonce) : "0x", + maxPriorityFeePerGas ? numberToHex(maxPriorityFeePerGas) : "0x", + maxFeePerGas ? numberToHex(maxFeePerGas) : "0x", + gas ? numberToHex(gas) : "0x", + to ?? "0x", + value ? numberToHex(value) : "0x", + data ?? "0x", + serializedAccessList, + ...toYParitySignatureArray(transaction, signature) + ]; + return concatHex([ + "0x02", + toRlp(serializedTransaction) + ]); +} +function serializeTransactionEIP2930(transaction, signature) { + const { chainId, gas, data, nonce, to, value, accessList, gasPrice } = transaction; + assertTransactionEIP29303(transaction); + const serializedAccessList = serializeAccessList3(accessList); + const serializedTransaction = [ + numberToHex(chainId), + nonce ? numberToHex(nonce) : "0x", + gasPrice ? numberToHex(gasPrice) : "0x", + gas ? numberToHex(gas) : "0x", + to ?? "0x", + value ? numberToHex(value) : "0x", + data ?? "0x", + serializedAccessList, + ...toYParitySignatureArray(transaction, signature) + ]; + return concatHex([ + "0x01", + toRlp(serializedTransaction) + ]); +} +function serializeTransactionLegacy(transaction, signature) { + const { chainId = 0, gas, data, nonce, to, value, gasPrice } = transaction; + assertTransactionLegacy3(transaction); + let serializedTransaction = [ + nonce ? numberToHex(nonce) : "0x", + gasPrice ? numberToHex(gasPrice) : "0x", + gas ? numberToHex(gas) : "0x", + to ?? "0x", + value ? numberToHex(value) : "0x", + data ?? "0x" + ]; + if (signature) { + const v = (() => { + if (signature.v >= 35n) { + const inferredChainId = (signature.v - 35n) / 2n; + if (inferredChainId > 0) + return signature.v; + return 27n + (signature.v === 35n ? 0n : 1n); } - ], - name: "withdrawStake", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { - inputs: [ - { - name: "withdrawAddress", - type: "address" - }, - { name: "withdrawAmount", type: "uint256" } - ], - name: "withdrawTo", - outputs: [], - stateMutability: "nonpayable", - type: "function" - }, - { stateMutability: "payable", type: "receive" } -]; + if (chainId > 0) + return BigInt(chainId * 2) + BigInt(35n + signature.v - 27n); + const v2 = 27n + (signature.v === 27n ? 0n : 1n); + if (signature.v !== v2) + throw new InvalidLegacyVError({ v: signature.v }); + return v2; + })(); + const r = trim(signature.r); + const s = trim(signature.s); + serializedTransaction = [ + ...serializedTransaction, + numberToHex(v), + r === "0x00" ? "0x" : r, + s === "0x00" ? "0x" : s + ]; + } else if (chainId > 0) { + serializedTransaction = [ + ...serializedTransaction, + numberToHex(chainId), + "0x", + "0x" + ]; + } + return toRlp(serializedTransaction); +} +function toYParitySignatureArray(transaction, signature_) { + const signature = signature_ ?? transaction; + const { v, yParity } = signature; + if (typeof signature.r === "undefined") + return []; + if (typeof signature.s === "undefined") + return []; + if (typeof v === "undefined" && typeof yParity === "undefined") + return []; + const r = trim(signature.r); + const s = trim(signature.s); + const yParity_ = (() => { + if (typeof yParity === "number") + return yParity ? numberToHex(1) : "0x"; + if (v === 0n) + return "0x"; + if (v === 1n) + return numberToHex(1); + return v === 27n ? "0x" : numberToHex(1); + })(); + return [yParity_, r === "0x00" ? "0x" : r, s === "0x00" ? "0x" : s]; +} -// ../viem/src/_esm/account-abstraction/constants/address.js -var entryPoint07Address = "0x0000000071727De22E5E9d8BAf0edAc6f37da032"; +// ../viem/src/_esm/accounts/utils/signTransaction.js +async function signTransaction2(parameters) { + const { privateKey, transaction, serializer = serializeTransaction3 } = parameters; + const signableTransaction = (() => { + if (transaction.type === "eip4844") + return { + ...transaction, + sidecars: false + }; + return transaction; + })(); + const signature = await sign({ + hash: keccak256(await serializer(signableTransaction)), + privateKey + }); + return await serializer(transaction, signature); +} -// ../viem/src/_esm/account-abstraction/utils/userOperation/getUserOperationHash.js -init_encodeAbiParameters(); -init_keccak256(); +// ../viem/src/_esm/accounts/utils/signTypedData.js +async function signTypedData2(parameters) { + const { privateKey, ...typedData } = parameters; + return await sign({ + hash: hashTypedData2(typedData), + privateKey, + to: "hex" + }); +} + +// ../viem/src/_esm/accounts/privateKeyToAccount.js +function privateKeyToAccount(privateKey, options = {}) { + const { nonceManager: nonceManager3 } = options; + const publicKey = toHex(secp256k1.getPublicKey(privateKey.slice(2), false)); + const address = publicKeyToAddress(publicKey); + const account = toAccount({ + address, + nonceManager: nonceManager3, + async sign({ hash: hash3 }) { + return sign({ hash: hash3, privateKey, to: "hex" }); + }, + async signAuthorization(authorization) { + return signAuthorization2({ ...authorization, privateKey }); + }, + async signMessage({ message }) { + return signMessage2({ message, privateKey }); + }, + async signTransaction(transaction, { serializer } = {}) { + return signTransaction2({ privateKey, transaction, serializer }); + }, + async signTypedData(typedData) { + return signTypedData2({ ...typedData, privateKey }); + } + }); + return { + ...account, + publicKey, + source: "privateKey" + }; +} +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/Base64.js +var encoder5 = /* @__PURE__ */ new TextEncoder; +var integerToCharacter = /* @__PURE__ */ Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((a, i) => [i, a.charCodeAt(0)])); +var characterToInteger = { + ...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((a, i) => [a.charCodeAt(0), i])), + [61]: 0, + [45]: 62, + [95]: 63 +}; +function toBytes6(value) { + const base64 = value.replace(/=+$/, ""); + const size7 = base64.length; + const decoded = new Uint8Array(size7 + 3); + encoder5.encodeInto(base64 + "===", decoded); + for (let i = 0, j = 0;i < base64.length; i += 4, j += 3) { + const x = (characterToInteger[decoded[i]] << 18) + (characterToInteger[decoded[i + 1]] << 12) + (characterToInteger[decoded[i + 2]] << 6) + characterToInteger[decoded[i + 3]]; + decoded[j] = x >> 16; + decoded[j + 1] = x >> 8 & 255; + decoded[j + 2] = x & 255; + } + const decodedSize = (size7 >> 2) * 3 + (size7 % 4 && size7 % 4 - 1); + return new Uint8Array(decoded.buffer, 0, decodedSize); +} + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/webauthn/Authentication.js +init_Bytes(); +init_Errors(); +init_Hex(); + +// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/nist.js +init_sha2(); +init__shortw_utils(); +init_modular(); +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +var Fp256 = Field(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")); +var p256_a = Fp256.create(BigInt("-3")); +var p256_b = BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"); +var p256 = createCurve({ + a: p256_a, + b: p256_b, + Fp: Fp256, + n: BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"), + Gx: BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"), + Gy: BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"), + h: BigInt(1), + lowS: false +}, sha256); +var Fp384 = Field(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")); +var p384_a = Fp384.create(BigInt("-3")); +var p384_b = BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"); +var p384 = createCurve({ + a: p384_a, + b: p384_b, + Fp: Fp384, + n: BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"), + Gx: BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"), + Gy: BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"), + h: BigInt(1), + lowS: false +}, sha384); +var Fp521 = Field(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")); +var p521_a = Fp521.create(BigInt("-3")); +var p521_b = BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"); +var p521 = createCurve({ + a: p521_a, + b: p521_b, + Fp: Fp521, + n: BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"), + Gx: BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"), + Gy: BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"), + h: BigInt(1), + lowS: false, + allowedPrivateKeyLengths: [130, 131, 132] +}, sha512); + +// ../viem/node_modules/.pnpm/@noble+curves@1.9.1/node_modules/@noble/curves/esm/p256.js +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +var p2562 = p256; +var secp256r1 = p256; + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/webauthn/Registration.js +init_Bytes(); +init_Errors(); + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/P256.js +init_Bytes(); +init_Hex(); +function getPublicKey(options) { + const { privateKey } = options; + const point = secp256r1.ProjectivePoint.fromPrivateKey(typeof privateKey === "string" ? privateKey.slice(2) : fromBytes(privateKey).slice(2)); + return from4(point); +} +function sign3(options) { + const { extraEntropy: extraEntropy3 = extraEntropy, hash: hash3, payload, privateKey } = options; + const { r, s, recovery } = secp256r1.sign(payload instanceof Uint8Array ? payload : fromHex(payload), privateKey instanceof Uint8Array ? privateKey : fromHex(privateKey), { + extraEntropy: typeof extraEntropy3 === "boolean" ? extraEntropy3 : from3(extraEntropy3).slice(2), + lowS: true, + ...hash3 ? { prehash: true } : {} + }); + return { + r, + s, + yParity: recovery + }; +} -// ../viem/src/_esm/account-abstraction/utils/userOperation/getInitCode.js -function getInitCode(userOperation, options = {}) { - const { forHash } = options; - const { authorization, factory, factoryData } = userOperation; - if (forHash && (factory === "0x7702" || factory === "0x7702000000000000000000000000000000000000")) { - if (!authorization) - return "0x7702000000000000000000000000000000000000"; - return concat([authorization.address, factoryData ?? "0x"]); +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/webauthn/Registration.js +var createChallenge = Uint8Array.from([ + 105, + 171, + 180, + 181, + 160, + 222, + 75, + 198, + 42, + 42, + 32, + 31, + 141, + 37, + 186, + 233 +]); +async function create2(options) { + const { createFn = (opts) => window.navigator.credentials.create(opts), ...rest } = options; + const creationOptions = "publicKey" in rest ? rest : getOptions(rest); + try { + const credential = await createFn(creationOptions); + if (!credential) + throw new CreateFailedError; + const response = credential.response; + const attestationObject = response.attestationObject; + const clientDataJSON = response.clientDataJSON; + const id = credential.id; + const publicKey = await parseCredentialPublicKey(response, attestationObject); + return { + attestationObject, + clientDataJSON, + id, + publicKey, + raw: credential + }; + } catch (error) { + throw new CreateFailedError({ + cause: error + }); } - if (!factory) - return "0x"; - return concat([factory, factoryData ?? "0x"]); } - -// ../viem/src/_esm/account-abstraction/utils/userOperation/toPackedUserOperation.js -init_pad(); -init_size(); -var paymasterSignatureMagic = "0x22e325a297439656"; -function toPackedUserOperation(userOperation, options = {}) { - const { callGasLimit, callData, maxPriorityFeePerGas, maxFeePerGas, paymaster, paymasterData, paymasterPostOpGasLimit, paymasterSignature, paymasterVerificationGasLimit, sender, signature = "0x", verificationGasLimit } = userOperation; - const accountGasLimits = concat([ - pad(numberToHex(verificationGasLimit || 0n), { size: 16 }), - pad(numberToHex(callGasLimit || 0n), { size: 16 }) - ]); - const initCode = getInitCode(userOperation, options); - const gasFees = concat([ - pad(numberToHex(maxPriorityFeePerGas || 0n), { size: 16 }), - pad(numberToHex(maxFeePerGas || 0n), { size: 16 }) - ]); - const nonce = userOperation.nonce ?? 0n; - const paymasterAndData = paymaster ? concat([ - paymaster, - pad(numberToHex(paymasterVerificationGasLimit || 0n), { - size: 16 - }), - pad(numberToHex(paymasterPostOpGasLimit || 0n), { - size: 16 - }), - paymasterData || "0x", - ...paymasterSignature ? options.forHash ? [paymasterSignatureMagic] : [ - paymasterSignature, - pad(numberToHex(size(paymasterSignature)), { size: 2 }), - paymasterSignatureMagic - ] : [] - ]) : "0x"; - const preVerificationGas = userOperation.preVerificationGas ?? 0n; +function getOptions(options) { + const { attestation = "none", authenticatorSelection = { + residentKey: "preferred", + requireResidentKey: false, + userVerification: "required" + }, challenge: challenge2 = createChallenge, excludeCredentialIds, extensions, name: name_, rp = { + id: window.location.hostname, + name: window.document.title + }, user } = options; + const name = user?.name ?? name_; return { - accountGasLimits, - callData, - initCode, - gasFees, - nonce, - paymasterAndData, - preVerificationGas, - sender, - signature + publicKey: { + attestation, + authenticatorSelection, + challenge: typeof challenge2 === "string" ? fromHex(challenge2) : challenge2, + ...excludeCredentialIds ? { + excludeCredentials: excludeCredentialIds?.map((id) => ({ + id: toBytes6(id), + type: "public-key" + })) + } : {}, + pubKeyCredParams: [ + { + type: "public-key", + alg: -7 + } + ], + rp, + user: { + id: user?.id ?? keccak2563(fromString(name), { as: "Bytes" }), + name, + displayName: user?.displayName ?? name + }, + ...extensions && { extensions } + } }; } +class CreateFailedError extends BaseError3 { + constructor({ cause } = {}) { + super("Failed to create credential.", { + cause + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Registration.CreateFailedError" + }); + } +} -// ../viem/src/_esm/account-abstraction/utils/userOperation/getUserOperationTypedData.js -var types = { - PackedUserOperation: [ - { type: "address", name: "sender" }, - { type: "uint256", name: "nonce" }, - { type: "bytes", name: "initCode" }, - { type: "bytes", name: "callData" }, - { type: "bytes32", name: "accountGasLimits" }, - { type: "uint256", name: "preVerificationGas" }, - { type: "bytes32", name: "gasFees" }, - { type: "bytes", name: "paymasterAndData" } - ] -}; -function getUserOperationTypedData(parameters) { - const { chainId, entryPointAddress, userOperation } = parameters; - const packedUserOp = toPackedUserOperation(userOperation, { forHash: true }); +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/internal/webauthn.js +function parseAsn1Signature(bytes) { + const sig = p2562.Signature.fromDER(bytes).normalizeS(); + return { r: sig.r, s: sig.s }; +} +async function parseCredentialPublicKey(response, attestationObject) { + try { + const publicKeyBuffer = response.getPublicKey(); + if (!publicKeyBuffer) + throw new CreateFailedError; + const publicKeyBytes = new Uint8Array(publicKeyBuffer); + const cryptoKey = await crypto.subtle.importKey("spki", new Uint8Array(publicKeyBytes), { + name: "ECDSA", + namedCurve: "P-256", + hash: "SHA-256" + }, true, ["verify"]); + const publicKey = new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKey)); + return from4(publicKey); + } catch (error) { + if (error.message !== "Permission denied to access object") + throw error; + const data = new Uint8Array(attestationObject ?? response.attestationObject); + const coordinateLength = 32; + const cborPrefix = 88; + const findStart = (key) => { + const coordinate = new Uint8Array([key, cborPrefix, coordinateLength]); + for (let i = 0;i < data.length - coordinate.length; i++) + if (coordinate.every((byte, j) => data[i + j] === byte)) + return i + coordinate.length; + throw new CreateFailedError; + }; + const xStart = findStart(33); + const yStart = findStart(34); + return from4(new Uint8Array([ + 4, + ...data.slice(xStart, xStart + coordinateLength), + ...data.slice(yStart, yStart + coordinateLength) + ])); + } +} + +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/webauthn/Authentication.js +function getOptions2(options) { + const { credentialId, challenge: challenge2, extensions, rpId = window.location.hostname, userVerification = "required" } = options; return { - types, - primaryType: "PackedUserOperation", - domain: { - name: "ERC4337", - version: "1", - chainId, - verifyingContract: entryPointAddress - }, - message: packedUserOp + publicKey: { + ...credentialId ? { + allowCredentials: Array.isArray(credentialId) ? credentialId.map((id) => ({ + id: toBytes6(id), + type: "public-key" + })) : [ + { + id: toBytes6(credentialId), + type: "public-key" + } + ] + } : {}, + challenge: fromHex(challenge2), + ...extensions && { extensions }, + rpId, + userVerification + } }; } +async function sign4(options) { + const { getFn = (opts) => window.navigator.credentials.get(opts), ...rest } = options; + const requestOptions = "publicKey" in rest ? rest : getOptions2(rest); + try { + const credential = await getFn(requestOptions); + if (!credential) + throw new SignFailedError; + const response = credential.response; + const clientDataJSONBytes = new Uint8Array(response.clientDataJSON); + const authenticatorDataBytes = new Uint8Array(response.authenticatorData); + const signatureBytes = new Uint8Array(response.signature); + const id = credential.id; + const clientDataJSON = String.fromCharCode(...clientDataJSONBytes); + const challengeIndex = clientDataJSON.indexOf('"challenge"'); + const typeIndex = clientDataJSON.indexOf('"type"'); + const signature = parseAsn1Signature(signatureBytes); + return { + id, + metadata: { + authenticatorData: fromBytes(authenticatorDataBytes), + clientDataJSON, + challengeIndex, + typeIndex, + userVerificationRequired: requestOptions.publicKey.userVerification === "required" + }, + signature, + raw: credential + }; + } catch (error) { + throw new SignFailedError({ + cause: error + }); + } +} + +class SignFailedError extends BaseError3 { + constructor({ cause } = {}) { + super("Failed to request credential.", { + cause + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: "Authentication.SignFailedError" + }); + } +} -// ../viem/src/_esm/account-abstraction/utils/userOperation/getUserOperationHash.js -function getUserOperationHash(parameters) { - const { chainId, entryPointAddress, entryPointVersion } = parameters; - const userOperation = parameters.userOperation; - const { authorization, callData = "0x", callGasLimit, maxFeePerGas, maxPriorityFeePerGas, nonce, paymasterAndData = "0x", preVerificationGas, sender, verificationGasLimit } = userOperation; - if (entryPointVersion === "0.8" || entryPointVersion === "0.9") - return hashTypedData(getUserOperationTypedData({ - chainId, - entryPointAddress, - userOperation - })); - const packedUserOp = (() => { - if (entryPointVersion === "0.6") { - const factory = userOperation.initCode?.slice(0, 42); - const factoryData = userOperation.initCode?.slice(42); - const initCode = getInitCode({ - authorization, - factory, - factoryData - }, { forHash: true }); - return encodeAbiParameters([ - { type: "address" }, - { type: "uint256" }, - { type: "bytes32" }, - { type: "bytes32" }, - { type: "uint256" }, - { type: "uint256" }, - { type: "uint256" }, - { type: "uint256" }, - { type: "uint256" }, - { type: "bytes32" } - ], [ - sender, - nonce, - keccak256(initCode), - keccak256(callData), - callGasLimit, - verificationGasLimit, - preVerificationGas, - maxFeePerGas, - maxPriorityFeePerGas, - keccak256(paymasterAndData) - ]); - } - if (entryPointVersion === "0.7") { - const packedUserOp2 = toPackedUserOperation(userOperation, { - forHash: true - }); - return encodeAbiParameters([ - { type: "address" }, - { type: "uint256" }, - { type: "bytes32" }, - { type: "bytes32" }, - { type: "bytes32" }, - { type: "uint256" }, - { type: "bytes32" }, - { type: "bytes32" } - ], [ - packedUserOp2.sender, - packedUserOp2.nonce, - keccak256(packedUserOp2.initCode), - keccak256(packedUserOp2.callData), - packedUserOp2.accountGasLimits, - packedUserOp2.preVerificationGas, - packedUserOp2.gasFees, - keccak256(packedUserOp2.paymasterAndData) - ]); - } - throw new Error(`entryPointVersion "${entryPointVersion}" not supported.`); - })(); - return keccak256(encodeAbiParameters([{ type: "bytes32" }, { type: "address" }, { type: "uint256" }], [keccak256(packedUserOp), entryPointAddress, BigInt(chainId)])); +// ../viem/node_modules/.pnpm/ox@0.14.33_typescript@5.9.3_zod@4.4.3/node_modules/ox/_esm/core/WebAuthnP256.js +async function createCredential(options) { + return create2(options); +} +async function sign5(options) { + return sign4(options); } -// ../viem/src/_esm/account-abstraction/accounts/toSmartAccount.js -init_exports(); -async function toSmartAccount(implementation) { - const { extend, nonceKeyManager = createNonceManager({ - source: { - get() { - return Date.now(); - }, - set() {} - } - }), ...rest } = implementation; - let deployed = false; - const address = await implementation.getAddress(); +// ../viem/src/_esm/account-abstraction/accounts/createWebAuthnCredential.js +async function createWebAuthnCredential(parameters) { + const credential = await createCredential(parameters); return { - ...extend, - ...rest, - address, - async getFactoryArgs() { - if ("isDeployed" in this && await this.isDeployed()) - return { factory: undefined, factoryData: undefined }; - return implementation.getFactoryArgs(); - }, - async getNonce(parameters) { - const key = parameters?.key ?? BigInt(await nonceKeyManager.consume({ - address, - chainId: implementation.client.chain.id, - client: implementation.client - })); - if (implementation.getNonce) - return await implementation.getNonce({ ...parameters, key }); - const nonce = await readContract(implementation.client, { - abi: parseAbi([ - "function getNonce(address, uint192) pure returns (uint256)" - ]), - address: implementation.entryPoint.address, - functionName: "getNonce", - args: [address, key] - }); - return nonce; - }, - async isDeployed() { - if (deployed) - return true; - const code = await getAction(implementation.client, getCode, "getCode")({ - address - }); - deployed = Boolean(code); - return deployed; - }, - ...implementation.sign ? { - async sign(parameters) { - const [{ factory, factoryData }, signature] = await Promise.all([ - this.getFactoryArgs(), - implementation.sign(parameters) - ]); - if (factory && factoryData) - return serializeErc6492Signature({ - address: factory, - data: factoryData, - signature - }); - return signature; - } - } : {}, - async signMessage(parameters) { - const [{ factory, factoryData }, signature] = await Promise.all([ - this.getFactoryArgs(), - implementation.signMessage(parameters) - ]); - if (factory && factoryData && factory !== "0x7702") - return serializeErc6492Signature({ - address: factory, - data: factoryData, - signature - }); - return signature; - }, - async signTypedData(parameters) { - const [{ factory, factoryData }, signature] = await Promise.all([ - this.getFactoryArgs(), - implementation.signTypedData(parameters) - ]); - if (factory && factoryData && factory !== "0x7702") - return serializeErc6492Signature({ - address: factory, - data: factoryData, - signature - }); - return signature; - }, - type: "smart" + id: credential.id, + publicKey: toHex2(credential.publicKey, { includePrefix: false }), + raw: credential.raw }; } - // ../viem/src/_esm/account-abstraction/accounts/toWebAuthnAccount.js function toWebAuthnAccount(parameters) { const { getFn, rpId } = parameters; @@ -20586,7 +19568,7 @@ function toWebAuthnAccount(parameters) { id, publicKey, async sign({ hash: hash3 }) { - const { metadata, raw, signature } = await sign4({ + const { metadata, raw, signature } = await sign5({ credentialId: id, getFn, challenge: hash3, @@ -20599,10 +19581,10 @@ function toWebAuthnAccount(parameters) { }; }, async signMessage({ message }) { - return this.sign({ hash: hashMessage(message) }); + return this.sign({ hash: hashMessage2(message) }); }, async signTypedData(parameters2) { - return this.sign({ hash: hashTypedData(parameters2) }); + return this.sign({ hash: hashTypedData2(parameters2) }); }, type: "webAuthn" }; @@ -20638,7 +19620,7 @@ Object.defineProperty(AccountNotDeployedError, "message", { value: /aa20/ }); -class ExecutionRevertedError2 extends BaseError2 { +class ExecutionRevertedError3 extends BaseError2 { constructor({ cause, data, message } = {}) { const reason = message?.replace("execution reverted: ", "")?.replace("execution reverted", ""); super(`Execution reverted ${reason ? `with reason: ${reason}` : "for an unknown reason"}.`, { @@ -20654,13 +19636,13 @@ class ExecutionRevertedError2 extends BaseError2 { this.data = data; } } -Object.defineProperty(ExecutionRevertedError2, "code", { +Object.defineProperty(ExecutionRevertedError3, "code", { enumerable: true, configurable: true, writable: true, value: -32521 }); -Object.defineProperty(ExecutionRevertedError2, "message", { +Object.defineProperty(ExecutionRevertedError3, "message", { enumerable: true, configurable: true, writable: true, @@ -21320,7 +20302,7 @@ class WaitForUserOperationReceiptTimeoutError extends BaseError2 { // ../viem/src/_esm/account-abstraction/utils/errors/getBundlerError.js var bundlerErrors = [ - ExecutionRevertedError2, + ExecutionRevertedError3, InvalidFieldsError, PaymasterDepositTooLowError, PaymasterRateLimitError, @@ -21450,8 +20432,8 @@ function getBundlerError(err, args) { }); const error = err.walk((e) => bundlerErrors.some((error2) => error2.code === e.code)); if (error) { - if (error.code === ExecutionRevertedError2.code) - return new ExecutionRevertedError2({ + if (error.code === ExecutionRevertedError3.code) + return new ExecutionRevertedError3({ cause: err, data: error.data, message: error.details @@ -21506,11 +20488,11 @@ function getBundlerError(err, args) { function getUserOperationError(err, { calls, docsPath: docsPath8, ...args }) { const cause = (() => { const cause2 = getBundlerError(err, args); - if (calls && cause2 instanceof ExecutionRevertedError2) { + if (calls && cause2 instanceof ExecutionRevertedError3) { const revertData = getRevertData(cause2); const contractCalls = calls?.filter((call2) => call2.abi); if (revertData && contractCalls.length > 0) - return getContractError2({ calls: contractCalls, revertData }); + return getContractError4({ calls: contractCalls, revertData }); } return cause2; })(); @@ -21534,7 +20516,7 @@ function getRevertData(error) { }); return revertData; } -function getContractError2(parameters) { +function getContractError4(parameters) { const { calls, revertData } = parameters; const { abi: abi2, functionName, args, to } = (() => { const contractCalls = calls?.filter((call2) => Boolean(call2.abi)); @@ -21712,7 +20694,7 @@ async function getPaymasterStubData(client, parameters) { } // ../viem/src/_esm/account-abstraction/actions/bundler/prepareUserOperation.js -var defaultParameters2 = [ +var defaultParameters3 = [ "factory", "fees", "gas", @@ -21723,7 +20705,7 @@ var defaultParameters2 = [ ]; async function prepareUserOperation(client, parameters_) { const parameters = parameters_; - const { account: account_ = client.account, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, parameters: properties = defaultParameters2, stateOverride } = parameters; + const { account: account_ = client.account, dataSuffix = typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value, parameters: properties = defaultParameters3, stateOverride } = parameters; if (!account_) throw new AccountNotFoundError; const account = parseAccount(account_); @@ -21758,14 +20740,14 @@ async function prepareUserOperation(client, parameters_) { (async () => { if (parameters.calls) return account.encodeCalls(parameters.calls.map((call_) => { - const call2 = call_; - if (call2.abi) + const call3 = call_; + if (call3.abi) return { - data: encodeFunctionData(call2), - to: call2.to, - value: call2.value + data: encodeFunctionData(call3), + to: call3.to, + value: call3.value }; - return call2; + return call3; })); return parameters.callData; })(), @@ -21863,7 +20845,7 @@ async function prepareUserOperation(client, parameters_) { if (account.entryPoint.version === "0.6" && !request.initCode) request.initCode = "0x"; let chainId; - async function getChainId2() { + async function getChainId3() { if (chainId) return chainId; if (client.chain) @@ -21875,7 +20857,7 @@ async function prepareUserOperation(client, parameters_) { let isPaymasterPopulated = false; if (properties.includes("paymaster") && getPaymasterStubData2 && !paymasterAddress && !parameters.paymasterAndData) { const { isFinal = false, sponsor: _, ...paymasterArgs } = await getPaymasterStubData2({ - chainId: await getChainId2(), + chainId: await getChainId3(), entryPointAddress: account.entryPoint.address, context: paymasterContext, ...request @@ -21921,7 +20903,7 @@ async function prepareUserOperation(client, parameters_) { } if (properties.includes("paymaster") && getPaymasterData2 && !paymasterAddress && !parameters.paymasterAndData && !isPaymasterPopulated) { const paymaster2 = await getPaymasterData2({ - chainId: await getChainId2(), + chainId: await getChainId3(), entryPointAddress: account.entryPoint.address, context: paymasterContext, ...request @@ -22150,9 +21132,606 @@ function createBundlerClient(parameters) { }); return client.extend(bundlerActions); } +// ../viem/src/_esm/account-abstraction/constants/abis.js +var entryPoint07Abi = [ + { + inputs: [ + { name: "success", type: "bool" }, + { name: "ret", type: "bytes" } + ], + name: "DelegateAndRevert", + type: "error" + }, + { + inputs: [ + { name: "opIndex", type: "uint256" }, + { name: "reason", type: "string" } + ], + name: "FailedOp", + type: "error" + }, + { + inputs: [ + { name: "opIndex", type: "uint256" }, + { name: "reason", type: "string" }, + { name: "inner", type: "bytes" } + ], + name: "FailedOpWithRevert", + type: "error" + }, + { + inputs: [{ name: "returnData", type: "bytes" }], + name: "PostOpReverted", + type: "error" + }, + { inputs: [], name: "ReentrancyGuardReentrantCall", type: "error" }, + { + inputs: [{ name: "sender", type: "address" }], + name: "SenderAddressResult", + type: "error" + }, + { + inputs: [{ name: "aggregator", type: "address" }], + name: "SignatureValidationFailed", + type: "error" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "userOpHash", + type: "bytes32" + }, + { + indexed: true, + name: "sender", + type: "address" + }, + { + indexed: false, + name: "factory", + type: "address" + }, + { + indexed: false, + name: "paymaster", + type: "address" + } + ], + name: "AccountDeployed", + type: "event" + }, + { anonymous: false, inputs: [], name: "BeforeExecution", type: "event" }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "account", + type: "address" + }, + { + indexed: false, + name: "totalDeposit", + type: "uint256" + } + ], + name: "Deposited", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "userOpHash", + type: "bytes32" + }, + { + indexed: true, + name: "sender", + type: "address" + }, + { + indexed: false, + name: "nonce", + type: "uint256" + }, + { + indexed: false, + name: "revertReason", + type: "bytes" + } + ], + name: "PostOpRevertReason", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "aggregator", + type: "address" + } + ], + name: "SignatureAggregatorChanged", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "account", + type: "address" + }, + { + indexed: false, + name: "totalStaked", + type: "uint256" + }, + { + indexed: false, + name: "unstakeDelaySec", + type: "uint256" + } + ], + name: "StakeLocked", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "account", + type: "address" + }, + { + indexed: false, + name: "withdrawTime", + type: "uint256" + } + ], + name: "StakeUnlocked", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "account", + type: "address" + }, + { + indexed: false, + name: "withdrawAddress", + type: "address" + }, + { + indexed: false, + name: "amount", + type: "uint256" + } + ], + name: "StakeWithdrawn", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "userOpHash", + type: "bytes32" + }, + { + indexed: true, + name: "sender", + type: "address" + }, + { + indexed: true, + name: "paymaster", + type: "address" + }, + { + indexed: false, + name: "nonce", + type: "uint256" + }, + { indexed: false, name: "success", type: "bool" }, + { + indexed: false, + name: "actualGasCost", + type: "uint256" + }, + { + indexed: false, + name: "actualGasUsed", + type: "uint256" + } + ], + name: "UserOperationEvent", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "userOpHash", + type: "bytes32" + }, + { + indexed: true, + name: "sender", + type: "address" + }, + { + indexed: false, + name: "nonce", + type: "uint256" + } + ], + name: "UserOperationPrefundTooLow", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "userOpHash", + type: "bytes32" + }, + { + indexed: true, + name: "sender", + type: "address" + }, + { + indexed: false, + name: "nonce", + type: "uint256" + }, + { + indexed: false, + name: "revertReason", + type: "bytes" + } + ], + name: "UserOperationRevertReason", + type: "event" + }, + { + anonymous: false, + inputs: [ + { + indexed: true, + name: "account", + type: "address" + }, + { + indexed: false, + name: "withdrawAddress", + type: "address" + }, + { + indexed: false, + name: "amount", + type: "uint256" + } + ], + name: "Withdrawn", + type: "event" + }, + { + inputs: [{ name: "unstakeDelaySec", type: "uint32" }], + name: "addStake", + outputs: [], + stateMutability: "payable", + type: "function" + }, + { + inputs: [{ name: "account", type: "address" }], + name: "balanceOf", + outputs: [{ name: "", type: "uint256" }], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { name: "target", type: "address" }, + { name: "data", type: "bytes" } + ], + name: "delegateAndRevert", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [{ name: "account", type: "address" }], + name: "depositTo", + outputs: [], + stateMutability: "payable", + type: "function" + }, + { + inputs: [{ name: "", type: "address" }], + name: "deposits", + outputs: [ + { name: "deposit", type: "uint256" }, + { name: "staked", type: "bool" }, + { name: "stake", type: "uint112" }, + { name: "unstakeDelaySec", type: "uint32" }, + { name: "withdrawTime", type: "uint48" } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [{ name: "account", type: "address" }], + name: "getDepositInfo", + outputs: [ + { + components: [ + { name: "deposit", type: "uint256" }, + { name: "staked", type: "bool" }, + { name: "stake", type: "uint112" }, + { name: "unstakeDelaySec", type: "uint32" }, + { name: "withdrawTime", type: "uint48" } + ], + name: "info", + type: "tuple" + } + ], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { name: "sender", type: "address" }, + { name: "key", type: "uint192" } + ], + name: "getNonce", + outputs: [{ name: "nonce", type: "uint256" }], + stateMutability: "view", + type: "function" + }, + { + inputs: [{ name: "initCode", type: "bytes" }], + name: "getSenderAddress", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + components: [ + { name: "sender", type: "address" }, + { name: "nonce", type: "uint256" }, + { name: "initCode", type: "bytes" }, + { name: "callData", type: "bytes" }, + { + name: "accountGasLimits", + type: "bytes32" + }, + { + name: "preVerificationGas", + type: "uint256" + }, + { name: "gasFees", type: "bytes32" }, + { name: "paymasterAndData", type: "bytes" }, + { name: "signature", type: "bytes" } + ], + name: "userOp", + type: "tuple" + } + ], + name: "getUserOpHash", + outputs: [{ name: "", type: "bytes32" }], + stateMutability: "view", + type: "function" + }, + { + inputs: [ + { + components: [ + { + components: [ + { name: "sender", type: "address" }, + { name: "nonce", type: "uint256" }, + { name: "initCode", type: "bytes" }, + { name: "callData", type: "bytes" }, + { + name: "accountGasLimits", + type: "bytes32" + }, + { + name: "preVerificationGas", + type: "uint256" + }, + { name: "gasFees", type: "bytes32" }, + { + name: "paymasterAndData", + type: "bytes" + }, + { name: "signature", type: "bytes" } + ], + name: "userOps", + type: "tuple[]" + }, + { + name: "aggregator", + type: "address" + }, + { name: "signature", type: "bytes" } + ], + name: "opsPerAggregator", + type: "tuple[]" + }, + { name: "beneficiary", type: "address" } + ], + name: "handleAggregatedOps", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + components: [ + { name: "sender", type: "address" }, + { name: "nonce", type: "uint256" }, + { name: "initCode", type: "bytes" }, + { name: "callData", type: "bytes" }, + { + name: "accountGasLimits", + type: "bytes32" + }, + { + name: "preVerificationGas", + type: "uint256" + }, + { name: "gasFees", type: "bytes32" }, + { name: "paymasterAndData", type: "bytes" }, + { name: "signature", type: "bytes" } + ], + name: "ops", + type: "tuple[]" + }, + { name: "beneficiary", type: "address" } + ], + name: "handleOps", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [{ name: "key", type: "uint192" }], + name: "incrementNonce", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { name: "callData", type: "bytes" }, + { + components: [ + { + components: [ + { name: "sender", type: "address" }, + { name: "nonce", type: "uint256" }, + { + name: "verificationGasLimit", + type: "uint256" + }, + { + name: "callGasLimit", + type: "uint256" + }, + { + name: "paymasterVerificationGasLimit", + type: "uint256" + }, + { + name: "paymasterPostOpGasLimit", + type: "uint256" + }, + { + name: "preVerificationGas", + type: "uint256" + }, + { name: "paymaster", type: "address" }, + { + name: "maxFeePerGas", + type: "uint256" + }, + { + name: "maxPriorityFeePerGas", + type: "uint256" + } + ], + name: "mUserOp", + type: "tuple" + }, + { name: "userOpHash", type: "bytes32" }, + { name: "prefund", type: "uint256" }, + { name: "contextOffset", type: "uint256" }, + { name: "preOpGas", type: "uint256" } + ], + name: "opInfo", + type: "tuple" + }, + { name: "context", type: "bytes" } + ], + name: "innerHandleOp", + outputs: [{ name: "actualGasCost", type: "uint256" }], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { name: "", type: "address" }, + { name: "", type: "uint192" } + ], + name: "nonceSequenceNumber", + outputs: [{ name: "", type: "uint256" }], + stateMutability: "view", + type: "function" + }, + { + inputs: [{ name: "interfaceId", type: "bytes4" }], + name: "supportsInterface", + outputs: [{ name: "", type: "bool" }], + stateMutability: "view", + type: "function" + }, + { + inputs: [], + name: "unlockStake", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + name: "withdrawAddress", + type: "address" + } + ], + name: "withdrawStake", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { + inputs: [ + { + name: "withdrawAddress", + type: "address" + }, + { name: "withdrawAmount", type: "uint256" } + ], + name: "withdrawTo", + outputs: [], + stateMutability: "nonpayable", + type: "function" + }, + { stateMutability: "payable", type: "receive" } +]; +// ../viem/src/_esm/account-abstraction/constants/address.js +var entryPoint07Address = "0x0000000071727De22E5E9d8BAf0edAc6f37da032"; // ../viem/src/_esm/eip8130/abis.js init_exports(); -var accountConfigurationAbi = parseAbi([ +var keystoreAbi = parseAbi([ "struct InitialActor { bytes32 actorId; address authenticator; uint16 scope; bytes policyData; }", "struct ActorConfig { address authenticator; uint48 expiry; uint16 scope; }", "struct Actor { bytes32 actorId; ActorConfig config; bytes policyData; }", @@ -22255,7 +21834,7 @@ var canonicalAuthenticators = { k1: "0x0000000000000000000000000000000000000001", p256: "0x8130C89F65750431b564A4730397552a11CeA256", passkey: "0x813007b6b1b48E75D91dEc5927ab515d12a0F1d0", - delegate: "0x8130b7D430D041ED4050935814D493299980aDE1" + delegate: "0x8130015119757e0b1F9985F723091a851598Ade1" }; var canonicalAuthDataLength = { [canonicalAuthenticators.k1.toLowerCase()]: 65, @@ -22264,8 +21843,8 @@ var canonicalAuthDataLength = { }; var nonceManagerAddress = "0x813000000000000000000000000000000000aa01"; var txContextAddress = "0x813000000000000000000000000000000000aa02"; -var keystoreAddress = "0x81305d4f4976220D2af17E5Dc246848E235600AC"; -var defaultAccountAddress = "0x813078f98b3eb214046C8Dc93A771ac9de5AaDEf"; +var keystoreAddress = "0x813011b7a5f25f8433Ac1E0993DE06CB2d1500Ac"; +var defaultAccountAddress = "0x813035E3fc4a102CE2b4a73D78a25D1Ea5AFadEf"; var deploymentHeaderSize = 14; var maxCodeSize = 24576; @@ -22273,19 +21852,19 @@ var maxCodeSize = 24576; var canonicalEip8130Deployment = { accounts: { upgradeable: undefined, - default: "0x813078f98b3eb214046C8Dc93A771ac9de5AaDEf", - defaultHighRate: "0x8130931874c894aC4963e128D6273AE520dAFa57" + default: "0x813035E3fc4a102CE2b4a73D78a25D1Ea5AFadEf", + defaultHighRate: "0x8130D6819734515f958965eFd2d212541d44FA57" }, authenticators: { k1: "0x0000000000000000000000000000000000000001", p256: "0x8130C89F65750431b564A4730397552a11CeA256", webAuthn: "0x813007b6b1b48E75D91dEc5927ab515d12a0F1d0", - delegate: "0x8130b7D430D041ED4050935814D493299980aDE1", + delegate: "0x8130015119757e0b1F9985F723091a851598Ade1", alwaysValid: "0xA550545Da91720c23483c5B3493412A02D1cF9F9" }, policies: { - manager: "0x813077055d1110F92191ccE13018f51820B40ac1", - sessionPolicy: "0x813070914C530d030f4Efd8Fa99C18e836435e55" + manager: "0x8130fAA29D2675D05d01D387C576c6525F280ac1", + sessionPolicy: "0x81306283dfD94FcDe1a3aD4b7beDF1c5cD0f5e55" } }; var baseSepoliaDeployment = { @@ -22317,12 +21896,12 @@ function actorIdFromAddress(address) { } function actorIdFromPublicKey(publicKey) { if (typeof publicKey === "string") { - if (size(publicKey) !== 64) - throw new BaseError2(`Public key must be 64 bytes (x || y); got ${size(publicKey)} bytes.`); + if (size2(publicKey) !== 64) + throw new BaseError2(`Public key must be 64 bytes (x || y); got ${size2(publicKey)} bytes.`); return keccak256(publicKey); } const { x, y } = publicKey; - if (size(x) !== 32 || size(y) !== 32) + if (size2(x) !== 32 || size2(y) !== 32) throw new BaseError2("Public key coordinates `x` and `y` must be 32 bytes."); return keccak256(concatHex([x, y])); } @@ -22385,7 +21964,7 @@ function isNoncelessOnly(scope) { function encodePolicyData(policy) { if (policy.type === 0) throw new BaseError2("`policy.type` must be non-zero (0 = no policy)."); - if (size(policy.commitment) !== 32) + if (size2(policy.commitment) !== 32) throw new BaseError2("`policy.commitment` must be 32 bytes."); return concatHex([pad(policy.manager, { size: 20 }), policy.commitment]); } @@ -22418,6 +21997,40 @@ function incrementLocalEpoch() { // ../viem/src/_esm/eip8130/utils/computeAddress.js init_base(); +// ../viem/src/_esm/utils/data/isBytes.js +function isBytes5(value) { + if (!value) + return false; + if (typeof value !== "object") + return false; + if (!("BYTES_PER_ELEMENT" in value)) + return false; + return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array"; +} + +// ../viem/src/_esm/utils/address/getContractAddress.js +init_pad(); +init_slice(); +init_toBytes(); +init_keccak256(); +init_getAddress(); +function getCreate2Address3(opts) { + const from15 = toBytes(getAddress(opts.from)); + const salt = pad(isBytes5(opts.salt) ? opts.salt : toBytes(opts.salt), { + size: 32 + }); + const bytecodeHash = (() => { + if ("bytecodeHash" in opts) { + if (isBytes5(opts.bytecodeHash)) + return opts.bytecodeHash; + return toBytes(opts.bytecodeHash); + } + return keccak256(opts.bytecode, "bytes"); + })(); + return getAddress(slice(keccak256(concat([toBytes("0xff"), from15, salt, bytecodeHash])), 12)); +} + +// ../viem/src/_esm/eip8130/utils/computeAddress.js init_size(); init_fromHex(); init_toHex(); @@ -22444,7 +22057,7 @@ function deploymentHeader(codeSize) { } function computeAddress(parameters) { const { userSalt, code, initialActors } = parameters; - const codeSize = size(code); + const codeSize = size2(code); if (codeSize === 0) throw new BaseError2("`code` must not be empty."); if (codeSize > maxCodeSize) @@ -22463,7 +22076,7 @@ function computeAddress(parameters) { ]))))); const effectiveSalt = keccak256(concatHex([userSalt, actorsCommitment])); const deploymentCode = concatHex([deploymentHeader(codeSize), code]); - return getCreate2Address({ + return getCreate2Address3({ from: keystoreAddress, salt: effectiveSalt, bytecode: deploymentCode @@ -22611,9 +22224,9 @@ function assertTransaction(transaction) { throw new InvalidChainIdError({ chainId }); if (calls) { for (const phase of calls) - for (const call2 of phase) - if (call2.value && call2.value !== 0n) - throw new BaseError2("EIP-8130 calls cannot carry `value` on the wire. Route value-bearing calls through the account wallet (e.g. `encodeWalletCalls` / `sendCalls`)."); + for (const call3 of phase) + if (call3.value && call3.value !== 0n) + throw new BaseError2("EIP-8130 calls cannot carry `value` on the wire. Route value-bearing calls through the account wallet (e.g. `encodeWalletCalls` / `sendTransaction`)."); } if (typeof nonceKey === "bigint" && nonceKey === nonceKeyMax) { if (nonceSequence !== undefined && nonceSequence !== 0n) @@ -22627,7 +22240,7 @@ function assertTransaction(transaction) { // ../viem/src/_esm/eip8130/utils/serializeTransaction.js function toCallsList(calls) { - return (calls ?? []).map((phase) => phase.map((call2) => [call2.to, call2.data ?? "0x"])); + return (calls ?? []).map((phase) => phase.map((call3) => [call3.to, call3.data ?? "0x"])); } function toChange(change) { return [ @@ -22677,7 +22290,7 @@ function toTransactionBody(transaction) { metadata ?? "0x" ]; } -function serializeTransaction2(transaction) { +function serializeTransaction4(transaction) { assertTransaction(transaction); const { payer, senderAuth, payerAuth } = transaction; return concatHex([ @@ -22713,192 +22326,551 @@ function getPayerSignatureHash(parameters) { return hash3; } -// ../viem/src/_esm/eip8130/utils/signTransaction.js -async function signTransaction3(parameters) { - const { account, payer } = parameters; - const transaction = { ...parameters.transaction }; - if (!transaction.senderAuth) { - if (!account?.sign) - throw new BaseError2("A sender `account` with raw signing support, or a preset `transaction.senderAuth`, is required."); - const authenticator = parameters.authenticator ?? account.authenticator ?? ecrecoverAuthenticator; - const senderHash = getSenderSignatureHash(transaction); - const signature = await account.sign({ hash: senderHash }); - transaction.senderAuth = transaction.from ? concatHex([authenticator, signature]) : signature; - } - if (payer && !transaction.payer) - transaction.payer = payer.address ?? payer.account.address; - if (transaction.payer && !transaction.payerAuth) { - if (!payer?.account.sign) - throw new BaseError2("A `payer` signer with raw signing support, or a preset `transaction.payerAuth`, is required for sponsored transactions."); - const authenticator = payer.authenticator ?? payer.account.authenticator ?? ecrecoverAuthenticator; - const from15 = transaction.from ?? account?.address; - const payerHash = getPayerSignatureHash({ ...transaction, from: from15 }); - const signature = await payer.account.sign({ hash: payerHash }); - transaction.payerAuth = concatHex([authenticator, signature]); - } - return serializeTransaction2(transaction); +// ../viem/src/_esm/eip8130/utils/signTransaction.js +async function signTransaction5(parameters) { + const { account, payer } = parameters; + const transaction = { ...parameters.transaction }; + if (!transaction.senderAuth) { + if (!account?.sign) + throw new BaseError2("A sender `account` with raw signing support, or a preset `transaction.senderAuth`, is required."); + const authenticator = parameters.authenticator ?? account.authenticator ?? ecrecoverAuthenticator; + const senderHash = getSenderSignatureHash(transaction); + const signature = await account.sign({ hash: senderHash }); + transaction.senderAuth = transaction.from ? concatHex([authenticator, signature]) : signature; + } + if (payer && !transaction.payer) + transaction.payer = payer.address ?? payer.account.address; + if (transaction.payer && !transaction.payerAuth) { + if (!payer?.account.sign) + throw new BaseError2("A `payer` signer with raw signing support, or a preset `transaction.payerAuth`, is required for sponsored transactions."); + const authenticator = payer.authenticator ?? payer.account.authenticator ?? ecrecoverAuthenticator; + const from15 = transaction.from ?? account?.address; + const payerHash = getPayerSignatureHash({ ...transaction, from: from15 }); + const signature = await payer.account.sign({ hash: payerHash }); + transaction.payerAuth = concatHex([authenticator, signature]); + } + return serializeTransaction4(transaction); +} + +// ../viem/src/_esm/eip8130/accounts/toAccount.js +function toAccount3(parameters) { + const { signer, authenticator = ecrecoverAuthenticator, scope } = parameters; + const isAddressOnly = parameters.userSalt === undefined; + const address = (() => { + if (parameters.address) + return parameters.address; + if (isAddressOnly) + throw new BaseError2("Provide `address` or `userSalt + code + initialActors` to derive the account address."); + return computeAddress({ + userSalt: parameters.userSalt, + code: parameters.code, + initialActors: parameters.initialActors + }); + })(); + const initialActors = parameters.initialActors ?? []; + const isK1Authenticator = authenticator === ecrecoverAuthenticator || authenticator === canonicalAuthenticators.k1; + const actorId = parameters.actorId ?? (isK1Authenticator ? key.k1(signer.address).actorId : undefined); + const signerPublicKey = signer.publicKey; + const publicKey = typeof signerPublicKey === "string" ? signerPublicKey : "0x"; + return { + address, + signer, + initialActors, + scope, + actorId, + type: "local", + source: "eip8130", + publicKey, + signMessage() { + throw new BaseError2("`signMessage` is not supported for EIP-8130 accounts."); + }, + signTypedData() { + throw new BaseError2("`signTypedData` is not supported for EIP-8130 accounts."); + }, + create() { + if (isAddressOnly) + throw new BaseError2("`create()` is not available for address-only (delegated EOA) accounts. " + "Include `account.delegate(impl)` in `accountChanges` instead."); + return { + type: "create", + userSalt: parameters.userSalt, + code: parameters.code, + initialActors: parameters.initialActors + }; + }, + async change(changes, options = {}) { + return signAccountChanges({ + signer, + account: address, + channel: options.channel ?? "local", + chainId: options.chainId ?? 0, + sequence: options.sequence ?? 0n, + changes, + authenticator + }); + }, + delegate(target) { + return { type: "delegation", target }; + }, + async signTransaction(transaction, options = {}) { + if (!signer.sign) + throw new BaseError2("`signer` does not support raw signing."); + return signTransaction5({ + transaction: { ...transaction, from: transaction.from ?? address }, + account: signer, + authenticator, + payer: options.payer + }); + } + }; +} +function newSmartAccount(parameters) { + const { signer, implementation, proxy = "upgradeable", admins = [], extraActors = [] } = parameters; + const primaryActor = "publicKey" in signer && signer.publicKey && typeof signer.publicKey !== "string" ? signer.authenticator === canonicalAuthenticators.passkey ? key.webAuthn(signer.publicKey) : key.p256(signer.publicKey) : key.k1(signer.address); + const adminActors = admins.map((a) => ({ + actorId: a.actorId, + authenticator: a.authenticator + })); + const allActors = [ + primaryActor, + ...adminActors, + ...extraActors + ].sort((a, b) => { + const ai = hexToBigInt(a.actorId); + const bi = hexToBigInt(b.actorId); + return ai < bi ? -1 : ai > bi ? 1 : 0; + }); + for (let i = 1;i < allActors.length; i++) + if (allActors[i].actorId === allActors[i - 1].actorId) + throw new BaseError2(`Duplicate initial actor id \`${allActors[i].actorId}\` (signer, admins, and extraActors must be distinct).`); + const salt = parameters.salt ?? randomBytes32(); + const code = parameters.code ?? (() => { + if (proxy === "erc1167") + return erc1167Bytecode(implementation ?? canonicalEip8130Deployment.accounts.default); + const impl = implementation ?? canonicalEip8130Deployment.accounts.upgradeable; + if (!impl) + throw new BaseError2("No canonical `UpgradeableAccount` is enshrined yet (pending final " + 'implementation), so `proxy: "upgradeable"` requires an explicit ' + "`implementation` — a UUPS UpgradeableAccount you deployed (see " + "https://github.com/base/eip-8130-examples). Alternatively pass " + '`proxy: "erc1167"` for an immutable DefaultAccount-backed account.'); + return upgradeableProxyBytecode(impl); + })(); + const inner = toAccount3({ + signer, + userSalt: salt, + code, + initialActors: allActors, + authenticator: signer.authenticator, + scope: primaryActor.scope ?? scopeUnrestricted + }); + return { ...inner, createChange: inner.create() }; +} +function toEoaAccount(signer, parameters = {}) { + if (!signer.address) + throw new BaseError2("`signer.address` is required. Use `privateKeyToAccount(pk)` or equivalent."); + const address = signer.address; + const scope = parameters.scope ?? scopeUnrestricted; + return { + address, + signer, + scope, + delegate(target) { + return { type: "delegation", target }; + }, + async change(changes, options = {}) { + return signAccountChanges({ + signer, + account: address, + channel: options.channel ?? "local", + chainId: options.chainId ?? 0, + sequence: options.sequence ?? 0n, + changes, + authenticator: ecrecoverAuthenticator + }); + }, + async signTransaction(transaction, options = {}) { + if (!signer.sign) + throw new BaseError2("`signer` does not support raw signing."); + return signTransaction5({ + transaction, + account: signer, + authenticator: ecrecoverAuthenticator, + payer: options.payer + }); + } + }; +} +function toDelegateSigner(parameters) { + const { delegateAccount, nestedSigner, nestedAuthenticator = ecrecoverAuthenticator, authenticator = canonicalAuthenticators.delegate } = parameters; + if (!nestedSigner.sign) + throw new BaseError2("`nestedSigner` must support raw signing."); + return { + address: nestedSigner.address, + authenticator, + async sign({ hash: hash3 }) { + const nestedSignature = await nestedSigner.sign({ hash: hash3 }); + return concatHex([delegateAccount, nestedAuthenticator, nestedSignature]); + } + }; +} +function delegateAuthSize(nestedDataLength = 65) { + return 20 + 20 + 20 + nestedDataLength; +} +function randomBytes32() { + const buf = new Uint8Array(32); + globalThis.crypto.getRandomValues(buf); + return bytesToHex(buf); +} +// ../viem/src/_esm/account-abstraction/accounts/toSmartAccount.js +init_exports(); + +// ../viem/src/_esm/utils/nonceManager.js +init_lru(); +function createNonceManager4(parameters) { + const { source } = parameters; + const deltaMap = new Map; + const nonceMap = new LruMap(8192); + const promiseMap = new Map; + const getKey = ({ address, chainId }) => `${address}.${chainId}`; + const resetCache = (key2) => { + deltaMap.delete(key2); + promiseMap.delete(key2); + }; + return { + async consume({ address, chainId, client }) { + const key2 = getKey({ address, chainId }); + const promise = this.get({ address, chainId, client }); + this.increment({ address, chainId }); + const nonce = await promise; + await source.set({ address, chainId }, nonce); + nonceMap.set(key2, nonce); + return nonce; + }, + async increment({ address, chainId }) { + const key2 = getKey({ address, chainId }); + const delta = deltaMap.get(key2) ?? 0; + deltaMap.set(key2, delta + 1); + }, + async get({ address, chainId, client }) { + const key2 = getKey({ address, chainId }); + let promise = promiseMap.get(key2); + if (!promise) { + promise = (async () => { + try { + const nonce = await source.get({ address, chainId, client }); + const previousNonce = nonceMap.get(key2) ?? 0; + if (previousNonce > 0 && nonce <= previousNonce) + return previousNonce + 1; + nonceMap.delete(key2); + return nonce; + } finally { + resetCache(key2); + } + })(); + promiseMap.set(key2, promise); + } + const delta = deltaMap.get(key2) ?? 0; + return delta + await promise; + }, + reset({ address, chainId }) { + const key2 = getKey({ address, chainId }); + nonceMap.delete(key2); + resetCache(key2); + } + }; +} +function jsonRpc() { + return { + async get(parameters) { + const { address, client } = parameters; + return getTransactionCount(client, { + address, + blockTag: "pending" + }); + }, + set() {} + }; +} +var nonceManager4 = /* @__PURE__ */ createNonceManager4({ + source: jsonRpc() +}); + +// ../viem/src/_esm/constants/bytes.js +var erc6492MagicBytes = "0x6492649264926492649264926492649264926492649264926492649264926492"; + +// ../viem/src/_esm/utils/signature/serializeErc6492Signature.js +init_encodeAbiParameters(); +init_toBytes(); +function serializeErc6492Signature3(parameters) { + const { address, data, signature, to = "hex" } = parameters; + const signature_ = concatHex([ + encodeAbiParameters([{ type: "address" }, { type: "bytes" }, { type: "bytes" }], [address, data, signature]), + erc6492MagicBytes + ]); + if (to === "hex") + return signature_; + return hexToBytes(signature_); } -// ../viem/src/_esm/eip8130/accounts/toAccount.js -function toAccount2(parameters) { - const { signer, authenticator = ecrecoverAuthenticator, scope } = parameters; - const isAddressOnly = parameters.userSalt === undefined; - const address = (() => { - if (parameters.address) - return parameters.address; - if (isAddressOnly) - throw new BaseError2("Provide `address` or `userSalt + code + initialActors` to derive the account address."); - return computeAddress({ - userSalt: parameters.userSalt, - code: parameters.code, - initialActors: parameters.initialActors - }); - })(); - const initialActors = parameters.initialActors ?? []; - const isK1Authenticator = authenticator === ecrecoverAuthenticator || authenticator === canonicalAuthenticators.k1; - const actorId = parameters.actorId ?? (isK1Authenticator ? key.k1(signer.address).actorId : undefined); +// ../viem/src/_esm/account-abstraction/accounts/toSmartAccount.js +async function toSmartAccount2(implementation) { + const { extend, nonceKeyManager = createNonceManager4({ + source: { + get() { + return Date.now(); + }, + set() {} + } + }), ...rest } = implementation; + let deployed = false; + const address = await implementation.getAddress(); return { + ...extend, + ...rest, address, - signer, - initialActors, - scope, - actorId, - create() { - if (isAddressOnly) - throw new BaseError2("`create()` is not available for address-only (delegated EOA) accounts. " + "Include `account.delegate(impl)` in `accountChanges` instead."); - return { - type: "create", - userSalt: parameters.userSalt, - code: parameters.code, - initialActors: parameters.initialActors - }; + async getFactoryArgs() { + if ("isDeployed" in this && await this.isDeployed()) + return { factory: undefined, factoryData: undefined }; + return implementation.getFactoryArgs(); }, - async change(changes, options = {}) { - return signAccountChanges({ - signer, - account: address, - channel: options.channel ?? "local", - chainId: options.chainId ?? 0, - sequence: options.sequence ?? 0n, - changes, - authenticator + async getNonce(parameters) { + const key2 = parameters?.key ?? BigInt(await nonceKeyManager.consume({ + address, + chainId: implementation.client.chain.id, + client: implementation.client + })); + if (implementation.getNonce) + return await implementation.getNonce({ ...parameters, key: key2 }); + const nonce = await readContract(implementation.client, { + abi: parseAbi([ + "function getNonce(address, uint192) pure returns (uint256)" + ]), + address: implementation.entryPoint.address, + functionName: "getNonce", + args: [address, key2] }); + return nonce; }, - delegate(target) { - return { type: "delegation", target }; - }, - async signTransaction(transaction, options = {}) { - if (!signer.sign) - throw new BaseError2("`signer` does not support raw signing."); - return signTransaction3({ - transaction: { ...transaction, from: transaction.from ?? address }, - account: signer, - authenticator, - payer: options.payer + async isDeployed() { + if (deployed) + return true; + const code = await getAction(implementation.client, getCode, "getCode")({ + address }); - } + deployed = Boolean(code); + return deployed; + }, + ...implementation.sign ? { + async sign(parameters) { + const [{ factory, factoryData }, signature] = await Promise.all([ + this.getFactoryArgs(), + implementation.sign(parameters) + ]); + if (factory && factoryData) + return serializeErc6492Signature3({ + address: factory, + data: factoryData, + signature + }); + return signature; + } + } : {}, + async signMessage(parameters) { + const [{ factory, factoryData }, signature] = await Promise.all([ + this.getFactoryArgs(), + implementation.signMessage(parameters) + ]); + if (factory && factoryData && factory !== "0x7702") + return serializeErc6492Signature3({ + address: factory, + data: factoryData, + signature + }); + return signature; + }, + async signTypedData(parameters) { + const [{ factory, factoryData }, signature] = await Promise.all([ + this.getFactoryArgs(), + implementation.signTypedData(parameters) + ]); + if (factory && factoryData && factory !== "0x7702") + return serializeErc6492Signature3({ + address: factory, + data: factoryData, + signature + }); + return signature; + }, + type: "smart" }; } -function newSmartAccount(parameters) { - const { signer, implementation, proxy = "upgradeable", admins = [], extraActors = [] } = parameters; - const primaryActor = "publicKey" in signer && signer.publicKey && typeof signer.publicKey !== "string" ? signer.authenticator === canonicalAuthenticators.passkey ? key.webAuthn(signer.publicKey) : key.p256(signer.publicKey) : key.k1(signer.address); - const adminActors = admins.map((a) => ({ - actorId: a.actorId, - authenticator: a.authenticator - })); - const allActors = [ - primaryActor, - ...adminActors, - ...extraActors - ].sort((a, b) => { - const ai = hexToBigInt(a.actorId); - const bi = hexToBigInt(b.actorId); - return ai < bi ? -1 : ai > bi ? 1 : 0; - }); - for (let i = 1;i < allActors.length; i++) - if (allActors[i].actorId === allActors[i - 1].actorId) - throw new BaseError2(`Duplicate initial actor id \`${allActors[i].actorId}\` (signer, admins, and extraActors must be distinct).`); - const salt = parameters.salt ?? randomBytes32(); - const code = parameters.code ?? (() => { - if (proxy === "erc1167") - return erc1167Bytecode(implementation ?? canonicalEip8130Deployment.accounts.default); - const impl = implementation ?? canonicalEip8130Deployment.accounts.upgradeable; - if (!impl) - throw new BaseError2("No canonical `UpgradeableAccount` is enshrined yet (pending final " + 'implementation), so `proxy: "upgradeable"` requires an explicit ' + "`implementation` — a UUPS UpgradeableAccount you deployed (see " + "https://github.com/base/eip-8130-examples). Alternatively pass " + '`proxy: "erc1167"` for an immutable DefaultAccount-backed account.'); - return upgradeableProxyBytecode(impl); - })(); - const inner = toAccount2({ - signer, - userSalt: salt, - code, - initialActors: allActors, - authenticator: signer.authenticator, - scope: primaryActor.scope ?? scopeUnrestricted - }); - return { ...inner, createChange: inner.create() }; + +// ../viem/src/_esm/account-abstraction/utils/userOperation/getUserOperationHash.js +init_encodeAbiParameters(); +init_keccak256(); + +// ../viem/src/_esm/account-abstraction/utils/userOperation/getInitCode.js +function getInitCode2(userOperation, options = {}) { + const { forHash } = options; + const { authorization, factory, factoryData } = userOperation; + if (forHash && (factory === "0x7702" || factory === "0x7702000000000000000000000000000000000000")) { + if (!authorization) + return "0x7702000000000000000000000000000000000000"; + return concat([authorization.address, factoryData ?? "0x"]); + } + if (!factory) + return "0x"; + return concat([factory, factoryData ?? "0x"]); +} + +// ../viem/src/_esm/account-abstraction/utils/userOperation/toPackedUserOperation.js +init_pad(); +init_size(); +var paymasterSignatureMagic = "0x22e325a297439656"; +function toPackedUserOperation2(userOperation, options = {}) { + const { callGasLimit, callData, maxPriorityFeePerGas, maxFeePerGas, paymaster, paymasterData, paymasterPostOpGasLimit, paymasterSignature, paymasterVerificationGasLimit, sender, signature = "0x", verificationGasLimit } = userOperation; + const accountGasLimits = concat([ + pad(numberToHex(verificationGasLimit || 0n), { size: 16 }), + pad(numberToHex(callGasLimit || 0n), { size: 16 }) + ]); + const initCode = getInitCode2(userOperation, options); + const gasFees = concat([ + pad(numberToHex(maxPriorityFeePerGas || 0n), { size: 16 }), + pad(numberToHex(maxFeePerGas || 0n), { size: 16 }) + ]); + const nonce = userOperation.nonce ?? 0n; + const paymasterAndData = paymaster ? concat([ + paymaster, + pad(numberToHex(paymasterVerificationGasLimit || 0n), { + size: 16 + }), + pad(numberToHex(paymasterPostOpGasLimit || 0n), { + size: 16 + }), + paymasterData || "0x", + ...paymasterSignature ? options.forHash ? [paymasterSignatureMagic] : [ + paymasterSignature, + pad(numberToHex(size2(paymasterSignature)), { size: 2 }), + paymasterSignatureMagic + ] : [] + ]) : "0x"; + const preVerificationGas = userOperation.preVerificationGas ?? 0n; + return { + accountGasLimits, + callData, + initCode, + gasFees, + nonce, + paymasterAndData, + preVerificationGas, + sender, + signature + }; } -function toEoaAccount(signer, parameters = {}) { - if (!signer.address) - throw new BaseError2("`signer.address` is required. Use `privateKeyToAccount(pk)` or equivalent."); - const address = signer.address; - const scope = parameters.scope ?? scopeUnrestricted; + +// ../viem/src/_esm/account-abstraction/utils/userOperation/getUserOperationTypedData.js +var types = { + PackedUserOperation: [ + { type: "address", name: "sender" }, + { type: "uint256", name: "nonce" }, + { type: "bytes", name: "initCode" }, + { type: "bytes", name: "callData" }, + { type: "bytes32", name: "accountGasLimits" }, + { type: "uint256", name: "preVerificationGas" }, + { type: "bytes32", name: "gasFees" }, + { type: "bytes", name: "paymasterAndData" } + ] +}; +function getUserOperationTypedData2(parameters) { + const { chainId, entryPointAddress, userOperation } = parameters; + const packedUserOp = toPackedUserOperation2(userOperation, { forHash: true }); return { - address, - signer, - scope, - delegate(target) { - return { type: "delegation", target }; - }, - async change(changes, options = {}) { - return signAccountChanges({ - signer, - account: address, - channel: options.channel ?? "local", - chainId: options.chainId ?? 0, - sequence: options.sequence ?? 0n, - changes, - authenticator: ecrecoverAuthenticator - }); + types, + primaryType: "PackedUserOperation", + domain: { + name: "ERC4337", + version: "1", + chainId, + verifyingContract: entryPointAddress }, - async signTransaction(transaction, options = {}) { - if (!signer.sign) - throw new BaseError2("`signer` does not support raw signing."); - return signTransaction3({ - transaction, - account: signer, - authenticator: ecrecoverAuthenticator, - payer: options.payer - }); - } + message: packedUserOp }; } -function toDelegateSigner(parameters) { - const { delegateAccount, nestedSigner, nestedAuthenticator = ecrecoverAuthenticator, authenticator = canonicalAuthenticators.delegate } = parameters; - if (!nestedSigner.sign) - throw new BaseError2("`nestedSigner` must support raw signing."); - return { - address: nestedSigner.address, - authenticator, - async sign({ hash: hash3 }) { - const nestedSignature = await nestedSigner.sign({ hash: hash3 }); - return concatHex([delegateAccount, nestedAuthenticator, nestedSignature]); + +// ../viem/src/_esm/account-abstraction/utils/userOperation/getUserOperationHash.js +function getUserOperationHash2(parameters) { + const { chainId, entryPointAddress, entryPointVersion } = parameters; + const userOperation = parameters.userOperation; + const { authorization, callData = "0x", callGasLimit, maxFeePerGas, maxPriorityFeePerGas, nonce, paymasterAndData = "0x", preVerificationGas, sender, verificationGasLimit } = userOperation; + if (entryPointVersion === "0.8" || entryPointVersion === "0.9") + return hashTypedData2(getUserOperationTypedData2({ + chainId, + entryPointAddress, + userOperation + })); + const packedUserOp = (() => { + if (entryPointVersion === "0.6") { + const factory = userOperation.initCode?.slice(0, 42); + const factoryData = userOperation.initCode?.slice(42); + const initCode = getInitCode2({ + authorization, + factory, + factoryData + }, { forHash: true }); + return encodeAbiParameters([ + { type: "address" }, + { type: "uint256" }, + { type: "bytes32" }, + { type: "bytes32" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "uint256" }, + { type: "bytes32" } + ], [ + sender, + nonce, + keccak256(initCode), + keccak256(callData), + callGasLimit, + verificationGasLimit, + preVerificationGas, + maxFeePerGas, + maxPriorityFeePerGas, + keccak256(paymasterAndData) + ]); } - }; -} -function delegateAuthSize(nestedDataLength = 65) { - return 20 + 20 + 20 + nestedDataLength; -} -function randomBytes32() { - const buf = new Uint8Array(32); - globalThis.crypto.getRandomValues(buf); - return bytesToHex(buf); + if (entryPointVersion === "0.7") { + const packedUserOp2 = toPackedUserOperation2(userOperation, { + forHash: true + }); + return encodeAbiParameters([ + { type: "address" }, + { type: "uint256" }, + { type: "bytes32" }, + { type: "bytes32" }, + { type: "bytes32" }, + { type: "uint256" }, + { type: "bytes32" }, + { type: "bytes32" } + ], [ + packedUserOp2.sender, + packedUserOp2.nonce, + keccak256(packedUserOp2.initCode), + keccak256(packedUserOp2.callData), + packedUserOp2.accountGasLimits, + packedUserOp2.preVerificationGas, + packedUserOp2.gasFees, + keccak256(packedUserOp2.paymasterAndData) + ]); + } + throw new Error(`entryPointVersion "${entryPointVersion}" not supported.`); + })(); + return keccak256(encodeAbiParameters([{ type: "bytes32" }, { type: "address" }, { type: "uint256" }], [keccak256(packedUserOp), entryPointAddress, BigInt(chainId)])); } // ../viem/src/_esm/eip8130/accounts/toSmartAccount.js init_base(); init_decodeFunctionData(); init_encodeFunctionData(); -// ../viem/src/_esm/eip8130/utils/accountConfigCalls.js +// ../viem/src/_esm/eip8130/utils/keystoreCalls.js init_encodeFunctionData(); function toInitialActors(actors) { return actors.map((actor) => ({ @@ -22917,7 +22889,7 @@ function toAbiChanges(changes) { function encodeCreateAccountData(parameters) { const { userSalt, code, initialActors } = parameters; return encodeFunctionData({ - abi: accountConfigurationAbi, + abi: keystoreAbi, functionName: "createAccount", args: [userSalt, code, toInitialActors(initialActors)] }); @@ -22931,7 +22903,7 @@ function toFactoryArgs(parameters) { function encodeApplySignedAccountChangesData(parameters) { const { account, channel, sequence, changes, signature } = parameters; return encodeFunctionData({ - abi: accountConfigurationAbi, + abi: keystoreAbi, functionName: "applySignedAccountChanges", args: [ account, @@ -22946,7 +22918,7 @@ function encodeApplySignedAccountChangesData(parameters) { } // ../viem/src/_esm/eip8130/accounts/toSmartAccount.js -async function toSmartAccount2(parameters) { +async function toSmartAccount3(parameters) { const { client, entryPoint: entryPoint_ = { abi: entryPoint07Abi, address: entryPoint07Address, @@ -22959,7 +22931,7 @@ async function toSmartAccount2(parameters) { }; const owner = parseAccount(parameters.owner); const stubData = parameters.stubData ?? "0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c"; - const sign5 = parameters.sign ?? (async (hash3) => { + const sign6 = parameters.sign ?? (async (hash3) => { if (!owner.sign) throw new BaseError2("`owner` must be a local account exposing `sign`, or pass a custom `sign` function. EIP-8130 validates the raw `userOpHash` (no EIP-191 prefix)."); return owner.sign({ hash: hash3 }); @@ -22976,7 +22948,7 @@ async function toSmartAccount2(parameters) { initialActors: parameters.initialActors }; } - return toSmartAccount({ + return toSmartAccount2({ client, entryPoint, getNonce, @@ -22984,10 +22956,10 @@ async function toSmartAccount2(parameters) { async decodeCalls(data) { const result = decodeFunctionData({ abi: erc4337AccountAbi, data }); if (result.functionName === "executeBatch") - return result.args[0].map((call2) => ({ - to: call2.target, - value: call2.value, - data: call2.data + return result.args[0].map((call3) => ({ + to: call3.target, + value: call3.value, + data: call3.data })); throw new BaseError2(`unable to decode calls for "${result.functionName}"`); }, @@ -22996,10 +22968,10 @@ async function toSmartAccount2(parameters) { abi: erc4337AccountAbi, functionName: "executeBatch", args: [ - calls.map((call2) => ({ - target: call2.to, - value: call2.value ?? 0n, - data: call2.data ?? "0x" + calls.map((call3) => ({ + target: call3.to, + value: call3.value ?? 0n, + data: call3.data ?? "0x" })) ] }); @@ -23026,7 +22998,7 @@ async function toSmartAccount2(parameters) { async signUserOperation(parameters_) { const { chainId = client.chain.id, ...userOperation } = parameters_; const address = await this.getAddress(); - const userOpHash = getUserOperationHash({ + const userOpHash = getUserOperationHash2({ chainId, entryPointAddress: entryPoint.address, entryPointVersion: entryPoint.version, @@ -23035,7 +23007,7 @@ async function toSmartAccount2(parameters) { sender: address } }); - return concatHex([authenticator, await sign5(userOpHash)]); + return concatHex([authenticator, await sign6(userOpHash)]); } }); } @@ -23043,8 +23015,19 @@ async function toSmartAccount2(parameters) { init_base(); init_fromHex(); init_toHex(); + +// ../viem/src/_esm/eip8130/utils/toPhases.js +function toPhases(calls) { + if (!calls || calls.length === 0) + return []; + if (Array.isArray(calls[0])) + return calls; + return [calls]; +} + +// ../viem/src/_esm/eip8130/actions/estimateGas.js var maxAuthSize = 8192; -async function estimateGas2(client, parameters) { +async function estimateGas3(client, parameters) { const { from: from15, sender, to, data, value, senderAuth: senderAuthExplicit, senderAuthAuthenticator, senderAuthSize, senderActorId, accountChanges, calls, nonceKey = 0n, nonceSequence = 0, payer, payerAuth: payerAuthExplicit, payerAuthAuthenticator, payerAuthSize, dataSuffix: dataSuffixParam, blockNumber, blockTag = "pending" } = parameters; const dataSuffix = dataSuffixParam ?? (typeof client.dataSuffix === "string" ? client.dataSuffix : client.dataSuffix?.value); const account_ = sender ?? from15; @@ -23052,9 +23035,9 @@ async function estimateGas2(client, parameters) { throw new BaseError2("`sender` (or `from`) is required for an EIP-8130 gas estimate: the sender drives actor/policy resolution."); if (sender && from15 && sender !== from15) throw new BaseError2(`\`sender\` (${sender}) and \`from\` (${from15}) must agree when both are set.`); - for (const size5 of [senderAuthSize, payerAuthSize]) - if (size5 !== undefined && (size5 < 0 || size5 > maxAuthSize)) - throw new BaseError2(`auth size ${size5} out of range (0..=${maxAuthSize}).`); + for (const size7 of [senderAuthSize, payerAuthSize]) + if (size7 !== undefined && (size7 < 0 || size7 > maxAuthSize)) + throw new BaseError2(`auth size ${size7} out of range (0..=${maxAuthSize}).`); const senderAuth = buildAuthBlob(senderAuthExplicit, senderAuthAuthenticator, senderAuthSize); const payerAuth = buildAuthBlob(payerAuthExplicit, payerAuthAuthenticator, payerAuthSize); const useFullBody = accountChanges !== undefined || calls !== undefined; @@ -23071,7 +23054,7 @@ async function estimateGas2(client, parameters) { maxPriorityFeePerGas: numberToHex(1000000n), gasLimit: 30000000, accountChanges: (accountChanges ?? []).map(serializeAccountChange), - calls: (calls ?? [[{ to: account_, value: 0n, data: "0x" }]]).map((phase) => phase.map((c) => ({ + calls: (calls !== undefined ? toPhases(calls) : [[{ to: account_, value: 0n, data: "0x" }]]).map((phase) => phase.map((c) => ({ to: c.to, value: numberToHex(c.value ?? 0n), data: c.data ?? "0x" @@ -23109,15 +23092,15 @@ async function estimateGas2(client, parameters) { const gas = await client.request({ method: "eth_estimateGas", params: [request, block] }); return hexToBigInt(gas); } -function buildAuthBlob(explicit, authenticator, size5) { +function buildAuthBlob(explicit, authenticator, size7) { if (explicit !== undefined) return explicit; if (authenticator === undefined) { - if (size5 === undefined) + if (size7 === undefined) return; - return filler(size5); + return filler(size7); } - const dataLength = size5 ?? canonicalAuthDataLength[authenticator.toLowerCase()]; + const dataLength = size7 ?? canonicalAuthDataLength[authenticator.toLowerCase()]; if (dataLength === undefined) throw new BaseError2(`No default auth-payload length is known for authenticator ${authenticator}. Pass an explicit auth size.`); return concatHex([authenticator, filler(dataLength)]); @@ -23165,7 +23148,7 @@ async function getActorConfig(client, parameters) { const { account, actorId } = parameters; const config = await readContract(client, { address: keystoreAddress, - abi: accountConfigurationAbi, + abi: keystoreAbi, functionName: "getActorConfig", args: [account, actorId] }); @@ -23181,7 +23164,7 @@ async function getConfigSequence(client, parameters) { const { account } = parameters; const result = await readContract(client, { address: keystoreAddress, - abi: accountConfigurationAbi, + abi: keystoreAbi, functionName: "getChangeSequences", args: [account] }); @@ -23201,7 +23184,7 @@ async function getLockStatus(client, parameters) { const { account } = parameters; const [locked, hasInitiatedUnlock, unlocksAt, unlockDelay] = await readContract(client, { address: keystoreAddress, - abi: accountConfigurationAbi, + abi: keystoreAbi, functionName: "getLockStatus", args: [account] }); @@ -23212,7 +23195,7 @@ async function getPolicy(client, parameters) { const { account, actorId } = parameters; const [, policyManager, policyCommitment] = await readContract(client, { address: keystoreAddress, - abi: accountConfigurationAbi, + abi: keystoreAbi, functionName: "getActor", args: [account, actorId] }); @@ -23420,7 +23403,7 @@ async function getSessionSpend(client, parameters) { }; } // ../viem/src/_esm/eip8130/actions/getTransaction.js -async function getTransaction2(client, parameters) { +async function getTransaction3(client, parameters) { const { hash: hash3 } = parameters; const raw = await client.request({ method: "eth_getTransactionByHash", params: [hash3] }); if (!raw || raw.type !== aaTransactionType) @@ -23453,7 +23436,7 @@ async function getTransaction2(client, parameters) { // ../viem/src/_esm/eip8130/actions/getTransactionCount.js init_fromHex(); init_toHex(); -async function getTransactionCount2(client, parameters) { +async function getTransactionCount3(client, parameters) { const { address, nonceKey = 0n, blockNumber, blockTag = "pending" } = parameters; if (nonceKey === nonceKeyMax) throw new Error("nonceKey NONCE_KEY_MAX selects the expiring-nonce channel, which has no per-channel counter. Use an `expiry` instead of reading a sequence number."); @@ -23478,7 +23461,7 @@ function allPhasesSucceeded(fields) { return true; return phases.every((s) => s === "0x1" || s === "0x01"); } -async function getTransactionReceipt2(client, parameters) { +async function getTransactionReceipt3(client, parameters) { const { hash: hash3 } = parameters; const receipt = await client.request({ method: "eth_getTransactionReceipt", params: [hash3] }); if (!receipt) @@ -23499,12 +23482,12 @@ async function isLocked(client, parameters) { const { account } = parameters; return readContract(client, { address: keystoreAddress, - abi: accountConfigurationAbi, + abi: keystoreAbi, functionName: "isLocked", args: [account] }); } -// ../viem/src/_esm/eip8130/actions/sendCalls.js +// ../viem/src/_esm/eip8130/actions/sendTransaction.js init_base(); // ../viem/src/_esm/eip8130/errors.js @@ -23586,10 +23569,10 @@ var defaultEncodeExecute = ({ account, calls }) => ({ abi: erc4337AccountAbi, functionName: "executeBatch", args: [ - calls.map((call2) => ({ - target: call2.to, - value: call2.value, - data: call2.data + calls.map((call3) => ({ + target: call3.to, + value: call3.value, + data: call3.data })) ] }) @@ -23597,19 +23580,19 @@ var defaultEncodeExecute = ({ account, calls }) => ({ function encodeWalletCalls(parameters) { const { account, calls, encodeExecute = defaultEncodeExecute } = parameters; return calls.map((phase) => { - const hasValue = phase.some((call2) => call2.value && call2.value !== 0n); + const hasValue = phase.some((call3) => call3.value && call3.value !== 0n); if (!hasValue) - return phase.map((call2) => ({ to: call2.to, data: call2.data ?? "0x" })); - const normalized = phase.map((call2) => ({ - to: call2.to, - value: call2.value ?? 0n, - data: call2.data ?? "0x" + return phase.map((call3) => ({ to: call3.to, data: call3.data ?? "0x" })); + const normalized = phase.map((call3) => ({ + to: call3.to, + value: call3.value ?? 0n, + data: call3.data ?? "0x" })); return [encodeExecute({ account, calls: normalized })]; }); } -// ../viem/src/_esm/eip8130/actions/sendCalls.js +// ../viem/src/_esm/eip8130/actions/sendTransaction.js async function resolveSigningScope(client, account) { const { actorId, scope: declared } = account; if (!actorId) @@ -23628,7 +23611,7 @@ async function resolveSigningScope(client, account) { throw new ScopeMismatchError({ declared, onChain }); return onChain; } -async function prepareTransaction(client, parameters) { +async function prepareTransactionRequest3(client, parameters) { const { account, calls, accountChanges, payer, gas } = parameters; const chainId = client.chain?.id; if (!chainId) @@ -23654,10 +23637,10 @@ async function prepareTransaction(client, parameters) { let nonceSequence = parameters.nonceSequence; if (nonceKey === nonceKeyMax) { if (!validBefore || validBefore === 0n) - validBefore = BigInt(Date.now()) + nonceFreeMaxExpiryWindow; + validBefore = (parameters.now ?? BigInt(Date.now())) + (parameters.expiryWindow ?? nonceFreeMaxExpiryWindow); nonceSequence ??= 0n; } else if (nonceSequence === undefined) { - nonceSequence = await getAction(client, getTransactionCount2, "getTransactionCount")({ address: account.address, nonceKey }); + nonceSequence = await getAction(client, getTransactionCount3, "getTransactionCount")({ address: account.address, nonceKey }); } return { chainId, @@ -23675,16 +23658,9 @@ async function prepareTransaction(client, parameters) { payer: payer?.address ?? payer?.account.address }; } -function toPhases(calls) { - if (calls.length === 0) - return []; - if (Array.isArray(calls[0])) - return calls; - return [calls]; -} -async function sendCalls2(client, parameters) { +async function prepareAndSign(client, parameters) { const { account, calls, payer, encodeExecute, onTransaction, ...rest } = parameters; - const transaction = await prepareTransaction(client, { + const transaction = await prepareTransactionRequest3(client, { ...rest, account, calls: encodeWalletCalls({ @@ -23695,24 +23671,31 @@ async function sendCalls2(client, parameters) { payer }); onTransaction?.(transaction); - const serializedTransaction = await account.signTransaction(transaction, { - payer - }); + return account.signTransaction(transaction, { payer }); +} +async function sendTransaction3(client, parameters) { + const serializedTransaction = await prepareAndSign(client, parameters); return getAction(client, sendRawTransaction, "sendRawTransaction")({ serializedTransaction }); } +async function sendTransactionSync3(client, parameters) { + const { throwOnReceiptRevert, timeout, ...rest } = parameters; + const serializedTransaction = await prepareAndSign(client, rest); + const receipt = await getAction(client, sendRawTransactionSync, "sendRawTransactionSync")({ serializedTransaction, throwOnReceiptRevert, timeout }); + return { ...receipt, eip8130: parseReceiptFields(receipt) }; +} // ../viem/src/_esm/eip8130/actions/waitForTransactionReceipt.js -async function waitForTransactionReceipt2(client, parameters) { +async function waitForTransactionReceipt3(client, parameters) { const { hash: hash3, pollingInterval = 500, timeout = 60000 } = parameters; const deadline = Date.now() + timeout; const suppliedValidBefore = parameters.validBefore !== undefined && BigInt(parameters.validBefore) > 0n; let validBefore = suppliedValidBefore ? BigInt(parameters.validBefore) : undefined; while (Date.now() < deadline) { - const receipt = await getTransactionReceipt2(client, { hash: hash3 }); + const receipt = await getTransactionReceipt3(client, { hash: hash3 }); if (receipt !== null) return receipt; if (validBefore === undefined) { try { - const tx = await getTransaction2(client, { hash: hash3 }); + const tx = await getTransaction3(client, { hash: hash3 }); if (tx.validBefore > 0) validBefore = BigInt(tx.validBefore); } catch {} @@ -23779,6 +23762,63 @@ function eip8130CapabilitiesByChain(chainIds, parameters = {}) { } return record; } +// ../viem/src/_esm/eip8130/chainConfig.js +init_base(); +var eip8130ChainConfig = { + formatters: { + transactionReceipt: defineTransactionReceipt({ + format(receipt) { + return { + ...formatTransactionReceipt(receipt), + eip8130: parseReceiptFields(receipt) + }; + } + }) + }, + prepareTransactionRequest: [ + async (request, { client }) => { + const req = request; + if (req.account?.source !== "eip8130" || !req.calls) + return request; + if (req.payer) + throw new BaseError2("Sponsored EIP-8130 transactions are not supported through core `sendTransaction`. " + "Use `client.eip8130.sendTransaction` (local payer signer) or " + "`client.eip8168.sendTransaction` (ERC-8168 payer service)."); + const account = req.account; + const calls = encodeWalletCalls({ + account: account.address, + calls: toPhases(req.calls), + encodeExecute: req.encodeExecute + }); + const gas = req.gas ?? await estimateGas3(client, { + sender: account.address, + accountChanges: req.accountChanges, + calls, + nonceKey: req.nonceKey, + senderActorId: req.senderActorId ?? account.actorId, + senderAuthAuthenticator: req.senderAuthAuthenticator, + dataSuffix: req.metadata + }); + const body = await prepareTransactionRequest3(client, { + account, + calls, + accountChanges: req.accountChanges, + gas, + nonceKey: req.nonceKey, + nonceSequence: req.nonceSequence, + validAfter: req.validAfter, + validBefore: req.validBefore, + maxFeePerGas: req.maxFeePerGas, + maxPriorityFeePerGas: req.maxPriorityFeePerGas, + dataSuffix: req.metadata + }); + return { + ...request, + ...body, + nonce: Number(body.nonceSequence) + }; + }, + { runAt: ["beforeFillTransaction"] } + ] +}; // ../viem/src/_esm/eip8130/chains.js var eip8130ChainIds = new Set; function register8130Chains(...chainIds) { @@ -23794,6 +23834,27 @@ function is8130Enabled(chain, parameters = {}) { const set = parameters.chainIds ? parameters.chainIds instanceof Set ? parameters.chainIds : new Set(parameters.chainIds) : eip8130ChainIds; return set.has(id); } +// ../viem/src/_esm/eip8130/decorators/eip8130Actions.js +function eip8130Actions() { + return (client) => ({ + eip8130: { + sendTransaction: (parameters) => sendTransaction3(client, parameters), + sendTransactionSync: (parameters) => sendTransactionSync3(client, parameters), + prepareTransactionRequest: (parameters) => prepareTransactionRequest3(client, parameters), + estimateGas: (parameters) => estimateGas3(client, parameters), + waitForTransactionReceipt: (parameters) => waitForTransactionReceipt3(client, parameters), + getTransaction: (parameters) => getTransaction3(client, parameters), + getTransactionCount: (parameters) => getTransactionCount3(client, parameters), + getConfigSequence: (parameters) => getConfigSequence(client, parameters), + getActorConfig: (parameters) => getActorConfig(client, parameters), + getPolicy: (parameters) => getPolicy(client, parameters), + isActor: (parameters) => isActor(client, parameters), + isLocked: (parameters) => isLocked(client, parameters), + getLockStatus: (parameters) => getLockStatus(client, parameters), + getSessionSpend: (parameters) => getSessionSpend(client, parameters) + } + }); +} // ../viem/src/_esm/eip8130/lock.js init_base(); var maxUnlockDelay = 65535; @@ -23899,13 +23960,13 @@ function toSessionPolicyConfig(permissions) { break; } case "erc20-token-transfer": { - const token = permission.data.address; + const token2 = permission.data.address; const { limit, period } = spendFromPolicies(permission.policies); if (limit === undefined) throw new BaseError2("An `erc20-token-transfer` permission must include a `token-allowance` policy (an unbounded spend cannot be granted)."); - tokenLimits.push({ token, limit, period }); + tokenLimits.push({ token: token2, limit, period }); callScopes.push({ - target: token, + target: token2, selectorRules: erc20TransferSelectors.map((selector) => ({ selector })) @@ -23915,8 +23976,8 @@ function toSessionPolicyConfig(permissions) { case "contract-call": { callScopes.push({ target: permission.data.address, - selectorRules: permission.data.calls.map((call2) => ({ - selector: toSelector(call2) + selectorRules: permission.data.calls.map((call3) => ({ + selector: toSelector(call3) })) }); break; @@ -24077,7 +24138,7 @@ function fulfillAddSubAccount(parameters) { throw new BaseError2("No canonical `UpgradeableAccount` is enshrined yet (pending final " + 'implementation), so `proxy: "upgradeable"` requires an explicit ' + '`implementation`. Pass `proxy: "erc1167"` for an immutable ' + "DefaultAccount-backed sub-account."); return upgradeableProxyBytecode(impl); })(); - const inner = toAccount2({ + const inner = toAccount3({ signer, userSalt: salt, code, @@ -24098,6 +24159,78 @@ init_base(); init_decodeAbiParameters(); init_slice(); init_fromHex(); + +// ../viem/src/_esm/utils/encoding/fromRlp.js +init_base(); +init_encoding(); +init_cursor2(); +init_toBytes(); +init_toHex(); +var rlpDepthLimit = 1024; +function fromRlp3(value, to = "hex") { + const bytes = (() => { + if (typeof value === "string") { + if (value.length > 3 && value.length % 2 !== 0) + throw new InvalidHexValueError(value); + return hexToBytes(value); + } + return value; + })(); + const cursor = createCursor(bytes, { + recursiveReadLimit: Number.POSITIVE_INFINITY + }); + const result = fromRlpCursor(cursor, to); + if (cursor.position < cursor.bytes.length) + throw new RlpTrailingBytesError({ + count: cursor.bytes.length - cursor.position + }); + return result; +} +function fromRlpCursor(cursor, to = "hex", recursiveDepth = 0) { + if (recursiveDepth >= rlpDepthLimit) + throw new RlpDepthLimitExceededError({ limit: rlpDepthLimit }); + if (cursor.bytes.length === 0) + return to === "hex" ? bytesToHex(cursor.bytes) : cursor.bytes; + const prefix = cursor.readByte(); + if (prefix < 128) + cursor.decrementPosition(1); + if (prefix < 192) { + const length2 = readLength(cursor, prefix, 128); + const bytes = cursor.readBytes(length2); + return to === "hex" ? bytesToHex(bytes) : bytes; + } + const length = readLength(cursor, prefix, 192); + return readList(cursor, length, to, recursiveDepth + 1); +} +function readLength(cursor, prefix, offset) { + if (offset === 128 && prefix < 128) + return 1; + if (prefix <= offset + 55) + return prefix - offset; + if (prefix === offset + 55 + 1) + return cursor.readUint8(); + if (prefix === offset + 55 + 2) + return cursor.readUint16(); + if (prefix === offset + 55 + 3) + return cursor.readUint24(); + if (prefix === offset + 55 + 4) + return cursor.readUint32(); + throw new BaseError2("Invalid RLP prefix"); +} +function readList(cursor, length, to, recursiveDepth) { + const position = cursor.position; + const value = []; + while (cursor.position - position < length) + value.push(fromRlpCursor(cursor, to, recursiveDepth)); + if (cursor.position - position !== length) + throw new RlpListBoundaryExceededError({ + consumed: cursor.position - position, + declared: length + }); + return value; +} + +// ../viem/src/_esm/eip8130/utils/parseTransaction.js function toOptionalAddress(value) { return value === "0x" ? undefined : value; } @@ -24106,8 +24239,8 @@ function toOptionalBigInt(value) { } function parseCalls(value) { const phases = value; - return phases.map((phase) => phase.map((call2) => { - const [to, data] = call2; + return phases.map((phase) => phase.map((call3) => { + const [to, data] = call3; return { to, data: data === "0x" ? undefined : data }; })); } @@ -24186,11 +24319,11 @@ function parseAccountChanges(value) { } return result; } -function parseTransaction(serialized) { +function parseTransaction3(serialized) { const type = sliceHex(serialized, 0, 1); if (type !== aaTransactionType) throw new BaseError2(`Serialized transaction type "${type}" is not an EIP-8130 transaction.`); - const fields = fromRlp(sliceHex(serialized, 1), "hex"); + const fields = fromRlp3(sliceHex(serialized, 1), "hex"); const [chainId, from15, nonceKey, nonceSequence, validAfter, validBefore, maxPriorityFeePerGas, maxFeePerGas, gas, accountChanges, calls, metadata, payer, senderAuth, payerAuth] = fields; const transaction = { chainId: hexToNumber(chainId) @@ -24288,8 +24421,8 @@ init_toHex(); function publicKeyToXY(publicKey) { if (typeof publicKey !== "string") return publicKey; - const body = size(publicKey) === 65 ? sliceHex(publicKey, 1) : publicKey; - if (size(body) !== 64) + const body = size2(publicKey) === 65 ? sliceHex(publicKey, 1) : publicKey; + if (size2(body) !== 64) throw new Error("`publicKey` must be a 64-byte `x || y` hex (optionally 0x04-prefixed) or `{ x, y }`."); return { x: sliceHex(body, 0, 32), y: sliceHex(body, 32, 64) }; } @@ -24304,7 +24437,7 @@ function toP256Signer(parameters) { authenticator, publicKey: { x, y }, async sign({ hash: hash3 }) { - const { r, s } = sign2({ payload: hash3, privateKey }); + const { r, s } = sign3({ payload: hash3, privateKey }); return concatHex([ numberToHex(r, { size: 32 }), numberToHex(s, { size: 32 }), @@ -24389,15 +24522,15 @@ function isSelectableOffer(option) { return isSponsoredOffer(option) || isTokenOffer(option); } function selectPaymentOption(terms, parameters = {}) { - const { token } = parameters; + const { token: token2 } = parameters; const options = terms.options ?? []; const matchChoice = (offer) => { const choices = offer.tokens ?? []; - if (token) - return choices.find((c) => c.token.toLowerCase() === token.toLowerCase()); + if (token2) + return choices.find((c) => c.token.toLowerCase() === token2.toLowerCase()); return choices[0]; }; - if (token) { + if (token2) { for (const option of options) { if (!isTokenOffer(option)) continue; @@ -24405,7 +24538,7 @@ function selectPaymentOption(terms, parameters = {}) { if (tokenChoice) return { option, tokenChoice }; } - throw new BaseError2(`No token offer matches the requested token "${token}".`); + throw new BaseError2(`No token offer matches the requested token "${token2}".`); } const sponsored = options.find(isSponsoredOffer); if (sponsored) @@ -24420,8 +24553,8 @@ function selectPaymentOption(terms, parameters = {}) { throw new BaseError2("Terms carry no selectable offer (only `sponsored_declined` entries, or an empty `options` array)."); } function buildSponsoredCalls(parameters) { - const { terms, calls, token } = parameters; - const { option, tokenChoice } = selectPaymentOption(terms, { token }); + const { terms, calls, token: token2 } = parameters; + const { option, tokenChoice } = selectPaymentOption(terms, { token: token2 }); if (option.kind === "sponsored") return { payer: option.payer, calls: [calls], option }; if (!tokenChoice) @@ -24489,18 +24622,18 @@ function parsePayerError(error) { // ../viem/src/_esm/eip8168/actions/sendSponsoredCalls.js async function sendSponsoredCalls(client, parameters) { - const { account, payerClient, calls, accountChanges, mode = "send", token, context, retries = 2, confirmRetry, onTransaction } = parameters; + const { account, payerClient, calls, accountChanges, mode = "send", token: token2, context, retries = 2, confirmRetry, onTransaction } = parameters; const chainId = client.chain?.id; if (!chainId) throw new BaseError2("`client` must be configured with a `chain`."); const terms = parameters.terms ?? await payerClient.getTerms({ chainId: numberToHex(chainId), from: account.address, - calls: calls.map((call2) => ({ to: call2.to, data: call2.data ?? "0x" })), - ...token ? { preferredTokens: [token] } : {}, + calls: calls.map((call3) => ({ to: call3.to, data: call3.data ?? "0x" })), + ...token2 ? { preferredTokens: [token2] } : {}, ...context ? { context } : {} }); - const built = buildSponsoredCalls({ terms, calls, token }); + const built = buildSponsoredCalls({ terms, calls, token: token2 }); const { option } = built; if (mode === "sign" && !option.methods?.includes("payer_signTransaction")) throw new BaseError2('Selected offer does not advertise `payer_signTransaction`; use `mode: "send"` or pick an offer whose `methods` includes it.'); @@ -24520,7 +24653,7 @@ async function sendSponsoredCalls(client, parameters) { const maxExpiry = option.conditions?.maxExpiry; return maxExpiry !== undefined ? BigInt(Date.now()) + BigInt(maxExpiry) * 1000n : 0n; }; - const transaction = await prepareTransaction(client, { + const transaction = await prepareTransactionRequest3(client, { account, calls: built.calls, accountChanges, @@ -24626,7 +24759,7 @@ function createPayerClient(parameters) { } export { zeroAddress, - waitForTransactionReceipt2 as waitForTransactionReceipt, + waitForTransactionReceipt3 as waitForTransactionReceipt, vibenetDevnetDeployment, upgradeableProxyBytecode, unsequencedLocalSequence, @@ -24639,7 +24772,7 @@ export { toWebAuthnSigner, toWebAuthnAccount, toTransactionBody, - toSmartAccount2 as toSmartAccount, + toSmartAccount3 as toSmartAccount, toSessionPolicyConfig, toSessionPolicy, toScope, @@ -24651,7 +24784,7 @@ export { toDelegateSigner, toCallsList, toAccountChangesList, - toAccount2 as toAccount, + toAccount3 as toAccount, supportedSubAccountKeyTypes, supportedSignerTypes, supportedPolicyTypes, @@ -24660,13 +24793,14 @@ export { slice, signedActorChangesMagic, signedAccountChangesTypehash, - signTransaction3 as signTransaction, + signTransaction5 as signTransaction, signAccountChanges, sessionPolicyAddress, sessionPolicyAbi, - serializeTransaction2 as serializeTransaction, + serializeTransaction4 as serializeTransaction, + sendTransactionSync3 as sendTransactionSync, + sendTransaction3 as sendTransaction, sendSponsoredCalls, - sendCalls2 as sendCalls, selectPaymentOption, scopeUnrestricted, routePermissionedCalls, @@ -24677,17 +24811,17 @@ export { register8130Chains, recoverSenderAddress, privateKeyToAccount, - prepareTransaction, + prepareTransactionRequest3 as prepareTransactionRequest, policyManagerAbi, policyDataLength, payerRejectedCode, payerErrorCode, - parseUnits, - parseTransaction, + parseUnits2 as parseUnits, + parseTransaction3 as parseTransaction, parseReceiptFields, parsePermissionsContext, parsePayerError, - parseEther, + parseEther2 as parseEther, parseAbi, nonceManagerAddress, nonceManagerAbi, @@ -24703,6 +24837,7 @@ export { maxCodeSize, lockChange, keystoreAddress, + keystoreAbi, key, keccak256, isTokenOffer, @@ -24717,9 +24852,9 @@ export { http, hexToBigInt, hashAccountChanges, - getTransactionReceipt2 as getTransactionReceipt, - getTransactionCount2 as getTransactionCount, - getTransaction2 as getTransaction, + getTransactionReceipt3 as getTransactionReceipt, + getTransactionCount3 as getTransactionCount, + getTransaction3 as getTransaction, getSessionSpend, getSenderSignatureHash, getPolicy, @@ -24733,7 +24868,7 @@ export { fulfillAddSubAccount, formatEther2 as formatEther, externalPolicyAuthenticator, - estimateGas2 as estimateGas, + estimateGas3 as estimateGas, erc4337AccountAbi, erc1167Bytecode, entryPoint07Address, @@ -24751,8 +24886,10 @@ export { encodeAbiParameters, eip8130Deployments, eip8130ChainIds, + eip8130ChainConfig, eip8130CapabilitiesByChain, eip8130Capabilities, + eip8130Actions, ecrecoverAuthenticator, deploymentHeaderSize, deploymentHeader, @@ -24786,7 +24923,6 @@ export { actorIdFromPublicKey, actorIdFromAddress, accountStateFlags, - accountConfigurationAbi, accountChangeTypehash, accountChangeType, aaTransactionType,