gun-eth 1.4.23 → 1.4.24

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gun-eth.bundle.min.js","sources":["../node_modules/ethers/lib.esm/_version.js","../node_modules/ethers/lib.esm/utils/properties.js","../node_modules/ethers/lib.esm/utils/errors.js","../node_modules/ethers/lib.esm/utils/data.js","../node_modules/ethers/lib.esm/utils/maths.js","../node_modules/ethers/lib.esm/utils/base58.js","../node_modules/ethers/lib.esm/utils/events.js","../node_modules/ethers/lib.esm/utils/utf8.js","../node_modules/ethers/lib.esm/utils/fetch.js","../node_modules/ethers/lib.esm/utils/rlp-decode.js","../node_modules/ethers/lib.esm/utils/rlp-encode.js","../node_modules/ethers/lib.esm/utils/uuid.js","../node_modules/ethers/lib.esm/abi/coders/abstract-coder.js","../node_modules/ethers/lib.esm/crypto/hmac.js","../node_modules/ethers/lib.esm/crypto/keccak.js","../node_modules/ethers/lib.esm/crypto/ripemd160.js","../node_modules/ethers/lib.esm/crypto/pbkdf2.js","../node_modules/ethers/lib.esm/crypto/random.js","../node_modules/ethers/lib.esm/crypto/scrypt.js","../node_modules/ethers/lib.esm/crypto/sha2.js","../node_modules/ethers/lib.esm/constants/addresses.js","../node_modules/ethers/lib.esm/constants/hashes.js","../node_modules/ethers/lib.esm/crypto/signature.js","../node_modules/ethers/lib.esm/crypto/signing-key.js","../node_modules/ethers/lib.esm/address/address.js","../node_modules/ethers/lib.esm/address/checks.js","../node_modules/ethers/lib.esm/abi/typed.js","../node_modules/ethers/lib.esm/abi/coders/address.js","../node_modules/ethers/lib.esm/abi/coders/anonymous.js","../node_modules/ethers/lib.esm/abi/coders/array.js","../node_modules/ethers/lib.esm/abi/coders/boolean.js","../node_modules/ethers/lib.esm/abi/coders/bytes.js","../node_modules/ethers/lib.esm/abi/coders/fixed-bytes.js","../node_modules/ethers/lib.esm/abi/coders/null.js","../node_modules/ethers/lib.esm/abi/coders/number.js","../node_modules/ethers/lib.esm/abi/coders/string.js","../node_modules/ethers/lib.esm/abi/coders/tuple.js","../node_modules/ethers/lib.esm/hash/id.js","../node_modules/ethers/lib.esm/hash/namehash.js","../node_modules/ethers/lib.esm/transaction/accesslist.js","../node_modules/ethers/lib.esm/transaction/address.js","../node_modules/ethers/lib.esm/transaction/transaction.js","../node_modules/ethers/lib.esm/hash/message.js","../node_modules/ethers/lib.esm/constants/strings.js","../node_modules/ethers/lib.esm/hash/typed-data.js","../node_modules/ethers/lib.esm/abi/fragments.js","../node_modules/ethers/lib.esm/abi/abi-coder.js","../node_modules/ethers/lib.esm/abi/interface.js","../node_modules/ethers/lib.esm/providers/provider.js","../node_modules/ethers/lib.esm/contract/wrappers.js","../node_modules/ethers/lib.esm/contract/contract.js","../node_modules/ethers/lib.esm/providers/ens-resolver.js","../node_modules/ethers/lib.esm/providers/format.js","../node_modules/ethers/lib.esm/address/contract-address.js","../node_modules/ethers/lib.esm/providers/plugins-network.js","../node_modules/ethers/lib.esm/providers/network.js","../node_modules/ethers/lib.esm/providers/subscriber-polling.js","../node_modules/ethers/lib.esm/providers/abstract-provider.js","../node_modules/ethers/lib.esm/providers/abstract-signer.js","../node_modules/ethers/lib.esm/providers/subscriber-filterid.js","../node_modules/ethers/lib.esm/providers/provider-jsonrpc.js","../node_modules/ethers/lib.esm/providers/provider-browser.js","../node_modules/ethers/lib.esm/wallet/base-wallet.js","../node_modules/ethers/lib.esm/wordlists/decode-owl.js","../node_modules/ethers/lib.esm/wordlists/wordlist.js","../node_modules/ethers/lib.esm/wordlists/wordlist-owl.js","../node_modules/ethers/lib.esm/wordlists/lang-en.js","../node_modules/ethers/lib.esm/wallet/mnemonic.js","../node_modules/ethers/lib.esm/wallet/utils.js","../node_modules/ethers/lib.esm/wallet/json-keystore.js","../node_modules/ethers/lib.esm/wallet/hdwallet.js","../node_modules/ethers/lib.esm/wallet/json-crowdsale.js","../node_modules/ethers/lib.esm/wallet/wallet.js","../src/config/local.js","../src/abis/abis.js","../src/index.js"],"sourcesContent":["/* Do NOT modify this file; see /src.ts/_admin/update-version.ts */\n/**\n * The current version of Ethers.\n */\nexport const version = \"6.13.4\";\n//# sourceMappingURL=_version.js.map","/**\n * Property helper functions.\n *\n * @_subsection api/utils:Properties [about-properties]\n */\nfunction checkType(value, type, name) {\n const types = type.split(\"|\").map(t => t.trim());\n for (let i = 0; i < types.length; i++) {\n switch (type) {\n case \"any\":\n return;\n case \"bigint\":\n case \"boolean\":\n case \"number\":\n case \"string\":\n if (typeof (value) === type) {\n return;\n }\n }\n }\n const error = new Error(`invalid value for type ${type}`);\n error.code = \"INVALID_ARGUMENT\";\n error.argument = `value.${name}`;\n error.value = value;\n throw error;\n}\n/**\n * Resolves to a new object that is a copy of %%value%%, but with all\n * values resolved.\n */\nexport async function resolveProperties(value) {\n const keys = Object.keys(value);\n const results = await Promise.all(keys.map((k) => Promise.resolve(value[k])));\n return results.reduce((accum, v, index) => {\n accum[keys[index]] = v;\n return accum;\n }, {});\n}\n/**\n * Assigns the %%values%% to %%target%% as read-only values.\n *\n * It %%types%% is specified, the values are checked.\n */\nexport function defineProperties(target, values, types) {\n for (let key in values) {\n let value = values[key];\n const type = (types ? types[key] : null);\n if (type) {\n checkType(value, type, key);\n }\n Object.defineProperty(target, key, { enumerable: true, value, writable: false });\n }\n}\n//# sourceMappingURL=properties.js.map","/**\n * All errors in ethers include properties to ensure they are both\n * human-readable (i.e. ``.message``) and machine-readable (i.e. ``.code``).\n *\n * The [[isError]] function can be used to check the error ``code`` and\n * provide a type guard for the properties present on that error interface.\n *\n * @_section: api/utils/errors:Errors [about-errors]\n */\nimport { version } from \"../_version.js\";\nimport { defineProperties } from \"./properties.js\";\nfunction stringify(value) {\n if (value == null) {\n return \"null\";\n }\n if (Array.isArray(value)) {\n return \"[ \" + (value.map(stringify)).join(\", \") + \" ]\";\n }\n if (value instanceof Uint8Array) {\n const HEX = \"0123456789abcdef\";\n let result = \"0x\";\n for (let i = 0; i < value.length; i++) {\n result += HEX[value[i] >> 4];\n result += HEX[value[i] & 0xf];\n }\n return result;\n }\n if (typeof (value) === \"object\" && typeof (value.toJSON) === \"function\") {\n return stringify(value.toJSON());\n }\n switch (typeof (value)) {\n case \"boolean\":\n case \"symbol\":\n return value.toString();\n case \"bigint\":\n return BigInt(value).toString();\n case \"number\":\n return (value).toString();\n case \"string\":\n return JSON.stringify(value);\n case \"object\": {\n const keys = Object.keys(value);\n keys.sort();\n return \"{ \" + keys.map((k) => `${stringify(k)}: ${stringify(value[k])}`).join(\", \") + \" }\";\n }\n }\n return `[ COULD NOT SERIALIZE ]`;\n}\n/**\n * Returns true if the %%error%% matches an error thrown by ethers\n * that matches the error %%code%%.\n *\n * In TypeScript environments, this can be used to check that %%error%%\n * matches an EthersError type, which means the expected properties will\n * be set.\n *\n * @See [ErrorCodes](api:ErrorCode)\n * @example\n * try {\n * // code....\n * } catch (e) {\n * if (isError(e, \"CALL_EXCEPTION\")) {\n * // The Type Guard has validated this object\n * console.log(e.data);\n * }\n * }\n */\nexport function isError(error, code) {\n return (error && error.code === code);\n}\n/**\n * Returns true if %%error%% is a [[CallExceptionError].\n */\nexport function isCallException(error) {\n return isError(error, \"CALL_EXCEPTION\");\n}\n/**\n * Returns a new Error configured to the format ethers emits errors, with\n * the %%message%%, [[api:ErrorCode]] %%code%% and additional properties\n * for the corresponding EthersError.\n *\n * Each error in ethers includes the version of ethers, a\n * machine-readable [[ErrorCode]], and depending on %%code%%, additional\n * required properties. The error message will also include the %%message%%,\n * ethers version, %%code%% and all additional properties, serialized.\n */\nexport function makeError(message, code, info) {\n let shortMessage = message;\n {\n const details = [];\n if (info) {\n if (\"message\" in info || \"code\" in info || \"name\" in info) {\n throw new Error(`value will overwrite populated values: ${stringify(info)}`);\n }\n for (const key in info) {\n if (key === \"shortMessage\") {\n continue;\n }\n const value = (info[key]);\n // try {\n details.push(key + \"=\" + stringify(value));\n // } catch (error: any) {\n // console.log(\"MMM\", error.message);\n // details.push(key + \"=[could not serialize object]\");\n // }\n }\n }\n details.push(`code=${code}`);\n details.push(`version=${version}`);\n if (details.length) {\n message += \" (\" + details.join(\", \") + \")\";\n }\n }\n let error;\n switch (code) {\n case \"INVALID_ARGUMENT\":\n error = new TypeError(message);\n break;\n case \"NUMERIC_FAULT\":\n case \"BUFFER_OVERRUN\":\n error = new RangeError(message);\n break;\n default:\n error = new Error(message);\n }\n defineProperties(error, { code });\n if (info) {\n Object.assign(error, info);\n }\n if (error.shortMessage == null) {\n defineProperties(error, { shortMessage });\n }\n return error;\n}\n/**\n * Throws an EthersError with %%message%%, %%code%% and additional error\n * %%info%% when %%check%% is falsish..\n *\n * @see [[api:makeError]]\n */\nexport function assert(check, message, code, info) {\n if (!check) {\n throw makeError(message, code, info);\n }\n}\n/**\n * A simple helper to simply ensuring provided arguments match expected\n * constraints, throwing if not.\n *\n * In TypeScript environments, the %%check%% has been asserted true, so\n * any further code does not need additional compile-time checks.\n */\nexport function assertArgument(check, message, name, value) {\n assert(check, message, \"INVALID_ARGUMENT\", { argument: name, value: value });\n}\nexport function assertArgumentCount(count, expectedCount, message) {\n if (message == null) {\n message = \"\";\n }\n if (message) {\n message = \": \" + message;\n }\n assert(count >= expectedCount, \"missing arguemnt\" + message, \"MISSING_ARGUMENT\", {\n count: count,\n expectedCount: expectedCount\n });\n assert(count <= expectedCount, \"too many arguments\" + message, \"UNEXPECTED_ARGUMENT\", {\n count: count,\n expectedCount: expectedCount\n });\n}\nconst _normalizeForms = [\"NFD\", \"NFC\", \"NFKD\", \"NFKC\"].reduce((accum, form) => {\n try {\n // General test for normalize\n /* c8 ignore start */\n if (\"test\".normalize(form) !== \"test\") {\n throw new Error(\"bad\");\n }\n ;\n /* c8 ignore stop */\n if (form === \"NFD\") {\n const check = String.fromCharCode(0xe9).normalize(\"NFD\");\n const expected = String.fromCharCode(0x65, 0x0301);\n /* c8 ignore start */\n if (check !== expected) {\n throw new Error(\"broken\");\n }\n /* c8 ignore stop */\n }\n accum.push(form);\n }\n catch (error) { }\n return accum;\n}, []);\n/**\n * Throws if the normalization %%form%% is not supported.\n */\nexport function assertNormalize(form) {\n assert(_normalizeForms.indexOf(form) >= 0, \"platform missing String.prototype.normalize\", \"UNSUPPORTED_OPERATION\", {\n operation: \"String.prototype.normalize\", info: { form }\n });\n}\n/**\n * Many classes use file-scoped values to guard the constructor,\n * making it effectively private. This facilitates that pattern\n * by ensuring the %%givenGaurd%% matches the file-scoped %%guard%%,\n * throwing if not, indicating the %%className%% if provided.\n */\nexport function assertPrivate(givenGuard, guard, className) {\n if (className == null) {\n className = \"\";\n }\n if (givenGuard !== guard) {\n let method = className, operation = \"new\";\n if (className) {\n method += \".\";\n operation += \" \" + className;\n }\n assert(false, `private constructor; use ${method}from* methods`, \"UNSUPPORTED_OPERATION\", {\n operation\n });\n }\n}\n//# sourceMappingURL=errors.js.map","/**\n * Some data helpers.\n *\n *\n * @_subsection api/utils:Data Helpers [about-data]\n */\nimport { assert, assertArgument } from \"./errors.js\";\nfunction _getBytes(value, name, copy) {\n if (value instanceof Uint8Array) {\n if (copy) {\n return new Uint8Array(value);\n }\n return value;\n }\n if (typeof (value) === \"string\" && value.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)) {\n const result = new Uint8Array((value.length - 2) / 2);\n let offset = 2;\n for (let i = 0; i < result.length; i++) {\n result[i] = parseInt(value.substring(offset, offset + 2), 16);\n offset += 2;\n }\n return result;\n }\n assertArgument(false, \"invalid BytesLike value\", name || \"value\", value);\n}\n/**\n * Get a typed Uint8Array for %%value%%. If already a Uint8Array\n * the original %%value%% is returned; if a copy is required use\n * [[getBytesCopy]].\n *\n * @see: getBytesCopy\n */\nexport function getBytes(value, name) {\n return _getBytes(value, name, false);\n}\n/**\n * Get a typed Uint8Array for %%value%%, creating a copy if necessary\n * to prevent any modifications of the returned value from being\n * reflected elsewhere.\n *\n * @see: getBytes\n */\nexport function getBytesCopy(value, name) {\n return _getBytes(value, name, true);\n}\n/**\n * Returns true if %%value%% is a valid [[HexString]].\n *\n * If %%length%% is ``true`` or a //number//, it also checks that\n * %%value%% is a valid [[DataHexString]] of %%length%% (if a //number//)\n * bytes of data (e.g. ``0x1234`` is 2 bytes).\n */\nexport function isHexString(value, length) {\n if (typeof (value) !== \"string\" || !value.match(/^0x[0-9A-Fa-f]*$/)) {\n return false;\n }\n if (typeof (length) === \"number\" && value.length !== 2 + 2 * length) {\n return false;\n }\n if (length === true && (value.length % 2) !== 0) {\n return false;\n }\n return true;\n}\n/**\n * Returns true if %%value%% is a valid representation of arbitrary\n * data (i.e. a valid [[DataHexString]] or a Uint8Array).\n */\nexport function isBytesLike(value) {\n return (isHexString(value, true) || (value instanceof Uint8Array));\n}\nconst HexCharacters = \"0123456789abcdef\";\n/**\n * Returns a [[DataHexString]] representation of %%data%%.\n */\nexport function hexlify(data) {\n const bytes = getBytes(data);\n let result = \"0x\";\n for (let i = 0; i < bytes.length; i++) {\n const v = bytes[i];\n result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f];\n }\n return result;\n}\n/**\n * Returns a [[DataHexString]] by concatenating all values\n * within %%data%%.\n */\nexport function concat(datas) {\n return \"0x\" + datas.map((d) => hexlify(d).substring(2)).join(\"\");\n}\n/**\n * Returns the length of %%data%%, in bytes.\n */\nexport function dataLength(data) {\n if (isHexString(data, true)) {\n return (data.length - 2) / 2;\n }\n return getBytes(data).length;\n}\n/**\n * Returns a [[DataHexString]] by slicing %%data%% from the %%start%%\n * offset to the %%end%% offset.\n *\n * By default %%start%% is 0 and %%end%% is the length of %%data%%.\n */\nexport function dataSlice(data, start, end) {\n const bytes = getBytes(data);\n if (end != null && end > bytes.length) {\n assert(false, \"cannot slice beyond data bounds\", \"BUFFER_OVERRUN\", {\n buffer: bytes, length: bytes.length, offset: end\n });\n }\n return hexlify(bytes.slice((start == null) ? 0 : start, (end == null) ? bytes.length : end));\n}\n/**\n * Return the [[DataHexString]] result by stripping all **leading**\n ** zero bytes from %%data%%.\n */\nexport function stripZerosLeft(data) {\n let bytes = hexlify(data).substring(2);\n while (bytes.startsWith(\"00\")) {\n bytes = bytes.substring(2);\n }\n return \"0x\" + bytes;\n}\nfunction zeroPad(data, length, left) {\n const bytes = getBytes(data);\n assert(length >= bytes.length, \"padding exceeds data length\", \"BUFFER_OVERRUN\", {\n buffer: new Uint8Array(bytes),\n length: length,\n offset: length + 1\n });\n const result = new Uint8Array(length);\n result.fill(0);\n if (left) {\n result.set(bytes, length - bytes.length);\n }\n else {\n result.set(bytes, 0);\n }\n return hexlify(result);\n}\n/**\n * Return the [[DataHexString]] of %%data%% padded on the **left**\n * to %%length%% bytes.\n *\n * If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is\n * thrown.\n *\n * This pads data the same as **values** are in Solidity\n * (e.g. ``uint128``).\n */\nexport function zeroPadValue(data, length) {\n return zeroPad(data, length, true);\n}\n/**\n * Return the [[DataHexString]] of %%data%% padded on the **right**\n * to %%length%% bytes.\n *\n * If %%data%% already exceeds %%length%%, a [[BufferOverrunError]] is\n * thrown.\n *\n * This pads data the same as **bytes** are in Solidity\n * (e.g. ``bytes16``).\n */\nexport function zeroPadBytes(data, length) {\n return zeroPad(data, length, false);\n}\n//# sourceMappingURL=data.js.map","/**\n * Some mathematic operations.\n *\n * @_subsection: api/utils:Math Helpers [about-maths]\n */\nimport { hexlify, isBytesLike } from \"./data.js\";\nimport { assert, assertArgument } from \"./errors.js\";\nconst BN_0 = BigInt(0);\nconst BN_1 = BigInt(1);\n//const BN_Max256 = (BN_1 << BigInt(256)) - BN_1;\n// IEEE 754 support 53-bits of mantissa\nconst maxValue = 0x1fffffffffffff;\n/**\n * Convert %%value%% from a twos-compliment representation of %%width%%\n * bits to its value.\n *\n * If the highest bit is ``1``, the result will be negative.\n */\nexport function fromTwos(_value, _width) {\n const value = getUint(_value, \"value\");\n const width = BigInt(getNumber(_width, \"width\"));\n assert((value >> width) === BN_0, \"overflow\", \"NUMERIC_FAULT\", {\n operation: \"fromTwos\", fault: \"overflow\", value: _value\n });\n // Top bit set; treat as a negative value\n if (value >> (width - BN_1)) {\n const mask = (BN_1 << width) - BN_1;\n return -(((~value) & mask) + BN_1);\n }\n return value;\n}\n/**\n * Convert %%value%% to a twos-compliment representation of\n * %%width%% bits.\n *\n * The result will always be positive.\n */\nexport function toTwos(_value, _width) {\n let value = getBigInt(_value, \"value\");\n const width = BigInt(getNumber(_width, \"width\"));\n const limit = (BN_1 << (width - BN_1));\n if (value < BN_0) {\n value = -value;\n assert(value <= limit, \"too low\", \"NUMERIC_FAULT\", {\n operation: \"toTwos\", fault: \"overflow\", value: _value\n });\n const mask = (BN_1 << width) - BN_1;\n return ((~value) & mask) + BN_1;\n }\n else {\n assert(value < limit, \"too high\", \"NUMERIC_FAULT\", {\n operation: \"toTwos\", fault: \"overflow\", value: _value\n });\n }\n return value;\n}\n/**\n * Mask %%value%% with a bitmask of %%bits%% ones.\n */\nexport function mask(_value, _bits) {\n const value = getUint(_value, \"value\");\n const bits = BigInt(getNumber(_bits, \"bits\"));\n return value & ((BN_1 << bits) - BN_1);\n}\n/**\n * Gets a BigInt from %%value%%. If it is an invalid value for\n * a BigInt, then an ArgumentError will be thrown for %%name%%.\n */\nexport function getBigInt(value, name) {\n switch (typeof (value)) {\n case \"bigint\": return value;\n case \"number\":\n assertArgument(Number.isInteger(value), \"underflow\", name || \"value\", value);\n assertArgument(value >= -maxValue && value <= maxValue, \"overflow\", name || \"value\", value);\n return BigInt(value);\n case \"string\":\n try {\n if (value === \"\") {\n throw new Error(\"empty string\");\n }\n if (value[0] === \"-\" && value[1] !== \"-\") {\n return -BigInt(value.substring(1));\n }\n return BigInt(value);\n }\n catch (e) {\n assertArgument(false, `invalid BigNumberish string: ${e.message}`, name || \"value\", value);\n }\n }\n assertArgument(false, \"invalid BigNumberish value\", name || \"value\", value);\n}\n/**\n * Returns %%value%% as a bigint, validating it is valid as a bigint\n * value and that it is positive.\n */\nexport function getUint(value, name) {\n const result = getBigInt(value, name);\n assert(result >= BN_0, \"unsigned value cannot be negative\", \"NUMERIC_FAULT\", {\n fault: \"overflow\", operation: \"getUint\", value\n });\n return result;\n}\nconst Nibbles = \"0123456789abcdef\";\n/*\n * Converts %%value%% to a BigInt. If %%value%% is a Uint8Array, it\n * is treated as Big Endian data.\n */\nexport function toBigInt(value) {\n if (value instanceof Uint8Array) {\n let result = \"0x0\";\n for (const v of value) {\n result += Nibbles[v >> 4];\n result += Nibbles[v & 0x0f];\n }\n return BigInt(result);\n }\n return getBigInt(value);\n}\n/**\n * Gets a //number// from %%value%%. If it is an invalid value for\n * a //number//, then an ArgumentError will be thrown for %%name%%.\n */\nexport function getNumber(value, name) {\n switch (typeof (value)) {\n case \"bigint\":\n assertArgument(value >= -maxValue && value <= maxValue, \"overflow\", name || \"value\", value);\n return Number(value);\n case \"number\":\n assertArgument(Number.isInteger(value), \"underflow\", name || \"value\", value);\n assertArgument(value >= -maxValue && value <= maxValue, \"overflow\", name || \"value\", value);\n return value;\n case \"string\":\n try {\n if (value === \"\") {\n throw new Error(\"empty string\");\n }\n return getNumber(BigInt(value), name);\n }\n catch (e) {\n assertArgument(false, `invalid numeric string: ${e.message}`, name || \"value\", value);\n }\n }\n assertArgument(false, \"invalid numeric value\", name || \"value\", value);\n}\n/**\n * Converts %%value%% to a number. If %%value%% is a Uint8Array, it\n * is treated as Big Endian data. Throws if the value is not safe.\n */\nexport function toNumber(value) {\n return getNumber(toBigInt(value));\n}\n/**\n * Converts %%value%% to a Big Endian hexstring, optionally padded to\n * %%width%% bytes.\n */\nexport function toBeHex(_value, _width) {\n const value = getUint(_value, \"value\");\n let result = value.toString(16);\n if (_width == null) {\n // Ensure the value is of even length\n if (result.length % 2) {\n result = \"0\" + result;\n }\n }\n else {\n const width = getNumber(_width, \"width\");\n assert(width * 2 >= result.length, `value exceeds width (${width} bytes)`, \"NUMERIC_FAULT\", {\n operation: \"toBeHex\",\n fault: \"overflow\",\n value: _value\n });\n // Pad the value to the required width\n while (result.length < (width * 2)) {\n result = \"0\" + result;\n }\n }\n return \"0x\" + result;\n}\n/**\n * Converts %%value%% to a Big Endian Uint8Array.\n */\nexport function toBeArray(_value) {\n const value = getUint(_value, \"value\");\n if (value === BN_0) {\n return new Uint8Array([]);\n }\n let hex = value.toString(16);\n if (hex.length % 2) {\n hex = \"0\" + hex;\n }\n const result = new Uint8Array(hex.length / 2);\n for (let i = 0; i < result.length; i++) {\n const offset = i * 2;\n result[i] = parseInt(hex.substring(offset, offset + 2), 16);\n }\n return result;\n}\n/**\n * Returns a [[HexString]] for %%value%% safe to use as a //Quantity//.\n *\n * A //Quantity// does not have and leading 0 values unless the value is\n * the literal value `0x0`. This is most commonly used for JSSON-RPC\n * numeric values.\n */\nexport function toQuantity(value) {\n let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2);\n while (result.startsWith(\"0\")) {\n result = result.substring(1);\n }\n if (result === \"\") {\n result = \"0\";\n }\n return \"0x\" + result;\n}\n//# sourceMappingURL=maths.js.map","/**\n * The [Base58 Encoding](link-base58) scheme allows a **numeric** value\n * to be encoded as a compact string using a radix of 58 using only\n * alpha-numeric characters. Confusingly similar characters are omitted\n * (i.e. ``\"l0O\"``).\n *\n * Note that Base58 encodes a **numeric** value, not arbitrary bytes,\n * since any zero-bytes on the left would get removed. To mitigate this\n * issue most schemes that use Base58 choose specific high-order values\n * to ensure non-zero prefixes.\n *\n * @_subsection: api/utils:Base58 Encoding [about-base58]\n */\nimport { getBytes } from \"./data.js\";\nimport { assertArgument } from \"./errors.js\";\nimport { toBigInt } from \"./maths.js\";\nconst Alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\";\nlet Lookup = null;\nfunction getAlpha(letter) {\n if (Lookup == null) {\n Lookup = {};\n for (let i = 0; i < Alphabet.length; i++) {\n Lookup[Alphabet[i]] = BigInt(i);\n }\n }\n const result = Lookup[letter];\n assertArgument(result != null, `invalid base58 value`, \"letter\", letter);\n return result;\n}\nconst BN_0 = BigInt(0);\nconst BN_58 = BigInt(58);\n/**\n * Encode %%value%% as a Base58-encoded string.\n */\nexport function encodeBase58(_value) {\n const bytes = getBytes(_value);\n let value = toBigInt(bytes);\n let result = \"\";\n while (value) {\n result = Alphabet[Number(value % BN_58)] + result;\n value /= BN_58;\n }\n // Account for leading padding zeros\n for (let i = 0; i < bytes.length; i++) {\n if (bytes[i]) {\n break;\n }\n result = Alphabet[0] + result;\n }\n return result;\n}\n/**\n * Decode the Base58-encoded %%value%%.\n */\nexport function decodeBase58(value) {\n let result = BN_0;\n for (let i = 0; i < value.length; i++) {\n result *= BN_58;\n result += getAlpha(value[i]);\n }\n return result;\n}\n//# sourceMappingURL=base58.js.map","/**\n * Events allow for applications to use the observer pattern, which\n * allows subscribing and publishing events, outside the normal\n * execution paths.\n *\n * @_section api/utils/events:Events [about-events]\n */\nimport { defineProperties } from \"./properties.js\";\n/**\n * When an [[EventEmitterable]] triggers a [[Listener]], the\n * callback always ahas one additional argument passed, which is\n * an **EventPayload**.\n */\nexport class EventPayload {\n /**\n * The event filter.\n */\n filter;\n /**\n * The **EventEmitterable**.\n */\n emitter;\n #listener;\n /**\n * Create a new **EventPayload** for %%emitter%% with\n * the %%listener%% and for %%filter%%.\n */\n constructor(emitter, listener, filter) {\n this.#listener = listener;\n defineProperties(this, { emitter, filter });\n }\n /**\n * Unregister the triggered listener for future events.\n */\n async removeListener() {\n if (this.#listener == null) {\n return;\n }\n await this.emitter.off(this.filter, this.#listener);\n }\n}\n//# sourceMappingURL=events.js.map","/**\n * Using strings in Ethereum (or any security-basd system) requires\n * additional care. These utilities attempt to mitigate some of the\n * safety issues as well as provide the ability to recover and analyse\n * strings.\n *\n * @_subsection api/utils:Strings and UTF-8 [about-strings]\n */\nimport { getBytes } from \"./data.js\";\nimport { assertArgument, assertNormalize } from \"./errors.js\";\nfunction errorFunc(reason, offset, bytes, output, badCodepoint) {\n assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, \"bytes\", bytes);\n}\nfunction ignoreFunc(reason, offset, bytes, output, badCodepoint) {\n // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes\n if (reason === \"BAD_PREFIX\" || reason === \"UNEXPECTED_CONTINUE\") {\n let i = 0;\n for (let o = offset + 1; o < bytes.length; o++) {\n if (bytes[o] >> 6 !== 0x02) {\n break;\n }\n i++;\n }\n return i;\n }\n // This byte runs us past the end of the string, so just jump to the end\n // (but the first byte was read already read and therefore skipped)\n if (reason === \"OVERRUN\") {\n return bytes.length - offset - 1;\n }\n // Nothing to skip\n return 0;\n}\nfunction replaceFunc(reason, offset, bytes, output, badCodepoint) {\n // Overlong representations are otherwise \"valid\" code points; just non-deistingtished\n if (reason === \"OVERLONG\") {\n assertArgument(typeof (badCodepoint) === \"number\", \"invalid bad code point for replacement\", \"badCodepoint\", badCodepoint);\n output.push(badCodepoint);\n return 0;\n }\n // Put the replacement character into the output\n output.push(0xfffd);\n // Otherwise, process as if ignoring errors\n return ignoreFunc(reason, offset, bytes, output, badCodepoint);\n}\n/**\n * A handful of popular, built-in UTF-8 error handling strategies.\n *\n * **``\"error\"``** - throws on ANY illegal UTF-8 sequence or\n * non-canonical (overlong) codepoints (this is the default)\n *\n * **``\"ignore\"``** - silently drops any illegal UTF-8 sequence\n * and accepts non-canonical (overlong) codepoints\n *\n * **``\"replace\"``** - replace any illegal UTF-8 sequence with the\n * UTF-8 replacement character (i.e. ``\"\\\\ufffd\"``) and accepts\n * non-canonical (overlong) codepoints\n *\n * @returns: Record<\"error\" | \"ignore\" | \"replace\", Utf8ErrorFunc>\n */\nexport const Utf8ErrorFuncs = Object.freeze({\n error: errorFunc,\n ignore: ignoreFunc,\n replace: replaceFunc\n});\n// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499\nfunction getUtf8CodePoints(_bytes, onError) {\n if (onError == null) {\n onError = Utf8ErrorFuncs.error;\n }\n const bytes = getBytes(_bytes, \"bytes\");\n const result = [];\n let i = 0;\n // Invalid bytes are ignored\n while (i < bytes.length) {\n const c = bytes[i++];\n // 0xxx xxxx\n if (c >> 7 === 0) {\n result.push(c);\n continue;\n }\n // Multibyte; how many bytes left for this character?\n let extraLength = null;\n let overlongMask = null;\n // 110x xxxx 10xx xxxx\n if ((c & 0xe0) === 0xc0) {\n extraLength = 1;\n overlongMask = 0x7f;\n // 1110 xxxx 10xx xxxx 10xx xxxx\n }\n else if ((c & 0xf0) === 0xe0) {\n extraLength = 2;\n overlongMask = 0x7ff;\n // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx\n }\n else if ((c & 0xf8) === 0xf0) {\n extraLength = 3;\n overlongMask = 0xffff;\n }\n else {\n if ((c & 0xc0) === 0x80) {\n i += onError(\"UNEXPECTED_CONTINUE\", i - 1, bytes, result);\n }\n else {\n i += onError(\"BAD_PREFIX\", i - 1, bytes, result);\n }\n continue;\n }\n // Do we have enough bytes in our data?\n if (i - 1 + extraLength >= bytes.length) {\n i += onError(\"OVERRUN\", i - 1, bytes, result);\n continue;\n }\n // Remove the length prefix from the char\n let res = c & ((1 << (8 - extraLength - 1)) - 1);\n for (let j = 0; j < extraLength; j++) {\n let nextChar = bytes[i];\n // Invalid continuation byte\n if ((nextChar & 0xc0) != 0x80) {\n i += onError(\"MISSING_CONTINUE\", i, bytes, result);\n res = null;\n break;\n }\n ;\n res = (res << 6) | (nextChar & 0x3f);\n i++;\n }\n // See above loop for invalid continuation byte\n if (res === null) {\n continue;\n }\n // Maximum code point\n if (res > 0x10ffff) {\n i += onError(\"OUT_OF_RANGE\", i - 1 - extraLength, bytes, result, res);\n continue;\n }\n // Reserved for UTF-16 surrogate halves\n if (res >= 0xd800 && res <= 0xdfff) {\n i += onError(\"UTF16_SURROGATE\", i - 1 - extraLength, bytes, result, res);\n continue;\n }\n // Check for overlong sequences (more bytes than needed)\n if (res <= overlongMask) {\n i += onError(\"OVERLONG\", i - 1 - extraLength, bytes, result, res);\n continue;\n }\n result.push(res);\n }\n return result;\n}\n// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array\n/**\n * Returns the UTF-8 byte representation of %%str%%.\n *\n * If %%form%% is specified, the string is normalized.\n */\nexport function toUtf8Bytes(str, form) {\n assertArgument(typeof (str) === \"string\", \"invalid string value\", \"str\", str);\n if (form != null) {\n assertNormalize(form);\n str = str.normalize(form);\n }\n let result = [];\n for (let i = 0; i < str.length; i++) {\n const c = str.charCodeAt(i);\n if (c < 0x80) {\n result.push(c);\n }\n else if (c < 0x800) {\n result.push((c >> 6) | 0xc0);\n result.push((c & 0x3f) | 0x80);\n }\n else if ((c & 0xfc00) == 0xd800) {\n i++;\n const c2 = str.charCodeAt(i);\n assertArgument(i < str.length && ((c2 & 0xfc00) === 0xdc00), \"invalid surrogate pair\", \"str\", str);\n // Surrogate Pair\n const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);\n result.push((pair >> 18) | 0xf0);\n result.push(((pair >> 12) & 0x3f) | 0x80);\n result.push(((pair >> 6) & 0x3f) | 0x80);\n result.push((pair & 0x3f) | 0x80);\n }\n else {\n result.push((c >> 12) | 0xe0);\n result.push(((c >> 6) & 0x3f) | 0x80);\n result.push((c & 0x3f) | 0x80);\n }\n }\n return new Uint8Array(result);\n}\n;\n//export \nfunction _toUtf8String(codePoints) {\n return codePoints.map((codePoint) => {\n if (codePoint <= 0xffff) {\n return String.fromCharCode(codePoint);\n }\n codePoint -= 0x10000;\n return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00));\n }).join(\"\");\n}\n/**\n * Returns the string represented by the UTF-8 data %%bytes%%.\n *\n * When %%onError%% function is specified, it is called on UTF-8\n * errors allowing recovery using the [[Utf8ErrorFunc]] API.\n * (default: [error](Utf8ErrorFuncs))\n */\nexport function toUtf8String(bytes, onError) {\n return _toUtf8String(getUtf8CodePoints(bytes, onError));\n}\n/**\n * Returns the UTF-8 code-points for %%str%%.\n *\n * If %%form%% is specified, the string is normalized.\n */\nexport function toUtf8CodePoints(str, form) {\n return getUtf8CodePoints(toUtf8Bytes(str, form));\n}\n//# sourceMappingURL=utf8.js.map","/**\n * Fetching content from the web is environment-specific, so Ethers\n * provides an abstraction that each environment can implement to provide\n * this service.\n *\n * On [Node.js](link-node), the ``http`` and ``https`` libs are used to\n * create a request object, register event listeners and process data\n * and populate the [[FetchResponse]].\n *\n * In a browser, the [DOM fetch](link-js-fetch) is used, and the resulting\n * ``Promise`` is waited on to retrieve the payload.\n *\n * The [[FetchRequest]] is responsible for handling many common situations,\n * such as redirects, server throttling, authentication, etc.\n *\n * It also handles common gateways, such as IPFS and data URIs.\n *\n * @_section api/utils/fetching:Fetching Web Content [about-fetch]\n */\nimport { decodeBase64, encodeBase64 } from \"./base64.js\";\nimport { hexlify } from \"./data.js\";\nimport { assert, assertArgument } from \"./errors.js\";\nimport { defineProperties } from \"./properties.js\";\nimport { toUtf8Bytes, toUtf8String } from \"./utf8.js\";\nimport { createGetUrl } from \"./geturl.js\";\nconst MAX_ATTEMPTS = 12;\nconst SLOT_INTERVAL = 250;\n// The global FetchGetUrlFunc implementation.\nlet defaultGetUrlFunc = createGetUrl();\nconst reData = new RegExp(\"^data:([^;:]*)?(;base64)?,(.*)$\", \"i\");\nconst reIpfs = new RegExp(\"^ipfs:/\\/(ipfs/)?(.*)$\", \"i\");\n// If locked, new Gateways cannot be added\nlet locked = false;\n// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs\nasync function dataGatewayFunc(url, signal) {\n try {\n const match = url.match(reData);\n if (!match) {\n throw new Error(\"invalid data\");\n }\n return new FetchResponse(200, \"OK\", {\n \"content-type\": (match[1] || \"text/plain\"),\n }, (match[2] ? decodeBase64(match[3]) : unpercent(match[3])));\n }\n catch (error) {\n return new FetchResponse(599, \"BAD REQUEST (invalid data: URI)\", {}, null, new FetchRequest(url));\n }\n}\n/**\n * Returns a [[FetchGatewayFunc]] for fetching content from a standard\n * IPFS gateway hosted at %%baseUrl%%.\n */\nfunction getIpfsGatewayFunc(baseUrl) {\n async function gatewayIpfs(url, signal) {\n try {\n const match = url.match(reIpfs);\n if (!match) {\n throw new Error(\"invalid link\");\n }\n return new FetchRequest(`${baseUrl}${match[2]}`);\n }\n catch (error) {\n return new FetchResponse(599, \"BAD REQUEST (invalid IPFS URI)\", {}, null, new FetchRequest(url));\n }\n }\n return gatewayIpfs;\n}\nconst Gateways = {\n \"data\": dataGatewayFunc,\n \"ipfs\": getIpfsGatewayFunc(\"https:/\\/gateway.ipfs.io/ipfs/\")\n};\nconst fetchSignals = new WeakMap();\n/**\n * @_ignore\n */\nexport class FetchCancelSignal {\n #listeners;\n #cancelled;\n constructor(request) {\n this.#listeners = [];\n this.#cancelled = false;\n fetchSignals.set(request, () => {\n if (this.#cancelled) {\n return;\n }\n this.#cancelled = true;\n for (const listener of this.#listeners) {\n setTimeout(() => { listener(); }, 0);\n }\n this.#listeners = [];\n });\n }\n addListener(listener) {\n assert(!this.#cancelled, \"singal already cancelled\", \"UNSUPPORTED_OPERATION\", {\n operation: \"fetchCancelSignal.addCancelListener\"\n });\n this.#listeners.push(listener);\n }\n get cancelled() { return this.#cancelled; }\n checkSignal() {\n assert(!this.cancelled, \"cancelled\", \"CANCELLED\", {});\n }\n}\n// Check the signal, throwing if it is cancelled\nfunction checkSignal(signal) {\n if (signal == null) {\n throw new Error(\"missing signal; should not happen\");\n }\n signal.checkSignal();\n return signal;\n}\n/**\n * Represents a request for a resource using a URI.\n *\n * By default, the supported schemes are ``HTTP``, ``HTTPS``, ``data:``,\n * and ``IPFS:``.\n *\n * Additional schemes can be added globally using [[registerGateway]].\n *\n * @example:\n * req = new FetchRequest(\"https://www.ricmoo.com\")\n * resp = await req.send()\n * resp.body.length\n * //_result:\n */\nexport class FetchRequest {\n #allowInsecure;\n #gzip;\n #headers;\n #method;\n #timeout;\n #url;\n #body;\n #bodyType;\n #creds;\n // Hooks\n #preflight;\n #process;\n #retry;\n #signal;\n #throttle;\n #getUrlFunc;\n /**\n * The fetch URL to request.\n */\n get url() { return this.#url; }\n set url(url) {\n this.#url = String(url);\n }\n /**\n * The fetch body, if any, to send as the request body. //(default: null)//\n *\n * When setting a body, the intrinsic ``Content-Type`` is automatically\n * set and will be used if **not overridden** by setting a custom\n * header.\n *\n * If %%body%% is null, the body is cleared (along with the\n * intrinsic ``Content-Type``).\n *\n * If %%body%% is a string, the intrinsic ``Content-Type`` is set to\n * ``text/plain``.\n *\n * If %%body%% is a Uint8Array, the intrinsic ``Content-Type`` is set to\n * ``application/octet-stream``.\n *\n * If %%body%% is any other object, the intrinsic ``Content-Type`` is\n * set to ``application/json``.\n */\n get body() {\n if (this.#body == null) {\n return null;\n }\n return new Uint8Array(this.#body);\n }\n set body(body) {\n if (body == null) {\n this.#body = undefined;\n this.#bodyType = undefined;\n }\n else if (typeof (body) === \"string\") {\n this.#body = toUtf8Bytes(body);\n this.#bodyType = \"text/plain\";\n }\n else if (body instanceof Uint8Array) {\n this.#body = body;\n this.#bodyType = \"application/octet-stream\";\n }\n else if (typeof (body) === \"object\") {\n this.#body = toUtf8Bytes(JSON.stringify(body));\n this.#bodyType = \"application/json\";\n }\n else {\n throw new Error(\"invalid body\");\n }\n }\n /**\n * Returns true if the request has a body.\n */\n hasBody() {\n return (this.#body != null);\n }\n /**\n * The HTTP method to use when requesting the URI. If no method\n * has been explicitly set, then ``GET`` is used if the body is\n * null and ``POST`` otherwise.\n */\n get method() {\n if (this.#method) {\n return this.#method;\n }\n if (this.hasBody()) {\n return \"POST\";\n }\n return \"GET\";\n }\n set method(method) {\n if (method == null) {\n method = \"\";\n }\n this.#method = String(method).toUpperCase();\n }\n /**\n * The headers that will be used when requesting the URI. All\n * keys are lower-case.\n *\n * This object is a copy, so any changes will **NOT** be reflected\n * in the ``FetchRequest``.\n *\n * To set a header entry, use the ``setHeader`` method.\n */\n get headers() {\n const headers = Object.assign({}, this.#headers);\n if (this.#creds) {\n headers[\"authorization\"] = `Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`;\n }\n ;\n if (this.allowGzip) {\n headers[\"accept-encoding\"] = \"gzip\";\n }\n if (headers[\"content-type\"] == null && this.#bodyType) {\n headers[\"content-type\"] = this.#bodyType;\n }\n if (this.body) {\n headers[\"content-length\"] = String(this.body.length);\n }\n return headers;\n }\n /**\n * Get the header for %%key%%, ignoring case.\n */\n getHeader(key) {\n return this.headers[key.toLowerCase()];\n }\n /**\n * Set the header for %%key%% to %%value%%. All values are coerced\n * to a string.\n */\n setHeader(key, value) {\n this.#headers[String(key).toLowerCase()] = String(value);\n }\n /**\n * Clear all headers, resetting all intrinsic headers.\n */\n clearHeaders() {\n this.#headers = {};\n }\n [Symbol.iterator]() {\n const headers = this.headers;\n const keys = Object.keys(headers);\n let index = 0;\n return {\n next: () => {\n if (index < keys.length) {\n const key = keys[index++];\n return {\n value: [key, headers[key]], done: false\n };\n }\n return { value: undefined, done: true };\n }\n };\n }\n /**\n * The value that will be sent for the ``Authorization`` header.\n *\n * To set the credentials, use the ``setCredentials`` method.\n */\n get credentials() {\n return this.#creds || null;\n }\n /**\n * Sets an ``Authorization`` for %%username%% with %%password%%.\n */\n setCredentials(username, password) {\n assertArgument(!username.match(/:/), \"invalid basic authentication username\", \"username\", \"[REDACTED]\");\n this.#creds = `${username}:${password}`;\n }\n /**\n * Enable and request gzip-encoded responses. The response will\n * automatically be decompressed. //(default: true)//\n */\n get allowGzip() {\n return this.#gzip;\n }\n set allowGzip(value) {\n this.#gzip = !!value;\n }\n /**\n * Allow ``Authentication`` credentials to be sent over insecure\n * channels. //(default: false)//\n */\n get allowInsecureAuthentication() {\n return !!this.#allowInsecure;\n }\n set allowInsecureAuthentication(value) {\n this.#allowInsecure = !!value;\n }\n /**\n * The timeout (in milliseconds) to wait for a complete response.\n * //(default: 5 minutes)//\n */\n get timeout() { return this.#timeout; }\n set timeout(timeout) {\n assertArgument(timeout >= 0, \"timeout must be non-zero\", \"timeout\", timeout);\n this.#timeout = timeout;\n }\n /**\n * This function is called prior to each request, for example\n * during a redirection or retry in case of server throttling.\n *\n * This offers an opportunity to populate headers or update\n * content before sending a request.\n */\n get preflightFunc() {\n return this.#preflight || null;\n }\n set preflightFunc(preflight) {\n this.#preflight = preflight;\n }\n /**\n * This function is called after each response, offering an\n * opportunity to provide client-level throttling or updating\n * response data.\n *\n * Any error thrown in this causes the ``send()`` to throw.\n *\n * To schedule a retry attempt (assuming the maximum retry limit\n * has not been reached), use [[response.throwThrottleError]].\n */\n get processFunc() {\n return this.#process || null;\n }\n set processFunc(process) {\n this.#process = process;\n }\n /**\n * This function is called on each retry attempt.\n */\n get retryFunc() {\n return this.#retry || null;\n }\n set retryFunc(retry) {\n this.#retry = retry;\n }\n /**\n * This function is called to fetch content from HTTP and\n * HTTPS URLs and is platform specific (e.g. nodejs vs\n * browsers).\n *\n * This is by default the currently registered global getUrl\n * function, which can be changed using [[registerGetUrl]].\n * If this has been set, setting is to ``null`` will cause\n * this FetchRequest (and any future clones) to revert back to\n * using the currently registered global getUrl function.\n *\n * Setting this is generally not necessary, but may be useful\n * for developers that wish to intercept requests or to\n * configurege a proxy or other agent.\n */\n get getUrlFunc() {\n return this.#getUrlFunc || defaultGetUrlFunc;\n }\n set getUrlFunc(value) {\n this.#getUrlFunc = value;\n }\n /**\n * Create a new FetchRequest instance with default values.\n *\n * Once created, each property may be set before issuing a\n * ``.send()`` to make the request.\n */\n constructor(url) {\n this.#url = String(url);\n this.#allowInsecure = false;\n this.#gzip = true;\n this.#headers = {};\n this.#method = \"\";\n this.#timeout = 300000;\n this.#throttle = {\n slotInterval: SLOT_INTERVAL,\n maxAttempts: MAX_ATTEMPTS\n };\n this.#getUrlFunc = null;\n }\n toString() {\n return `<FetchRequest method=${JSON.stringify(this.method)} url=${JSON.stringify(this.url)} headers=${JSON.stringify(this.headers)} body=${this.#body ? hexlify(this.#body) : \"null\"}>`;\n }\n /**\n * Update the throttle parameters used to determine maximum\n * attempts and exponential-backoff properties.\n */\n setThrottleParams(params) {\n if (params.slotInterval != null) {\n this.#throttle.slotInterval = params.slotInterval;\n }\n if (params.maxAttempts != null) {\n this.#throttle.maxAttempts = params.maxAttempts;\n }\n }\n async #send(attempt, expires, delay, _request, _response) {\n if (attempt >= this.#throttle.maxAttempts) {\n return _response.makeServerError(\"exceeded maximum retry limit\");\n }\n assert(getTime() <= expires, \"timeout\", \"TIMEOUT\", {\n operation: \"request.send\", reason: \"timeout\", request: _request\n });\n if (delay > 0) {\n await wait(delay);\n }\n let req = this.clone();\n const scheme = (req.url.split(\":\")[0] || \"\").toLowerCase();\n // Process any Gateways\n if (scheme in Gateways) {\n const result = await Gateways[scheme](req.url, checkSignal(_request.#signal));\n if (result instanceof FetchResponse) {\n let response = result;\n if (this.processFunc) {\n checkSignal(_request.#signal);\n try {\n response = await this.processFunc(req, response);\n }\n catch (error) {\n // Something went wrong during processing; throw a 5xx server error\n if (error.throttle == null || typeof (error.stall) !== \"number\") {\n response.makeServerError(\"error in post-processing function\", error).assertOk();\n }\n // Ignore throttling\n }\n }\n return response;\n }\n req = result;\n }\n // We have a preflight function; update the request\n if (this.preflightFunc) {\n req = await this.preflightFunc(req);\n }\n const resp = await this.getUrlFunc(req, checkSignal(_request.#signal));\n let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request);\n if (response.statusCode === 301 || response.statusCode === 302) {\n // Redirect\n try {\n const location = response.headers.location || \"\";\n return req.redirect(location).#send(attempt + 1, expires, 0, _request, response);\n }\n catch (error) { }\n // Things won't get any better on another attempt; abort\n return response;\n }\n else if (response.statusCode === 429) {\n // Throttle\n if (this.retryFunc == null || (await this.retryFunc(req, response, attempt))) {\n const retryAfter = response.headers[\"retry-after\"];\n let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));\n if (typeof (retryAfter) === \"string\" && retryAfter.match(/^[1-9][0-9]*$/)) {\n delay = parseInt(retryAfter);\n }\n return req.clone().#send(attempt + 1, expires, delay, _request, response);\n }\n }\n if (this.processFunc) {\n checkSignal(_request.#signal);\n try {\n response = await this.processFunc(req, response);\n }\n catch (error) {\n // Something went wrong during processing; throw a 5xx server error\n if (error.throttle == null || typeof (error.stall) !== \"number\") {\n response.makeServerError(\"error in post-processing function\", error).assertOk();\n }\n // Throttle\n let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt));\n ;\n if (error.stall >= 0) {\n delay = error.stall;\n }\n return req.clone().#send(attempt + 1, expires, delay, _request, response);\n }\n }\n return response;\n }\n /**\n * Resolves to the response by sending the request.\n */\n send() {\n assert(this.#signal == null, \"request already sent\", \"UNSUPPORTED_OPERATION\", { operation: \"fetchRequest.send\" });\n this.#signal = new FetchCancelSignal(this);\n return this.#send(0, getTime() + this.timeout, 0, this, new FetchResponse(0, \"\", {}, null, this));\n }\n /**\n * Cancels the inflight response, causing a ``CANCELLED``\n * error to be rejected from the [[send]].\n */\n cancel() {\n assert(this.#signal != null, \"request has not been sent\", \"UNSUPPORTED_OPERATION\", { operation: \"fetchRequest.cancel\" });\n const signal = fetchSignals.get(this);\n if (!signal) {\n throw new Error(\"missing signal; should not happen\");\n }\n signal();\n }\n /**\n * Returns a new [[FetchRequest]] that represents the redirection\n * to %%location%%.\n */\n redirect(location) {\n // Redirection; for now we only support absolute locations\n const current = this.url.split(\":\")[0].toLowerCase();\n const target = location.split(\":\")[0].toLowerCase();\n // Don't allow redirecting:\n // - non-GET requests\n // - downgrading the security (e.g. https => http)\n // - to non-HTTP (or non-HTTPS) protocols [this could be relaxed?]\n assert(this.method === \"GET\" && (current !== \"https\" || target !== \"http\") && location.match(/^https?:/), `unsupported redirect`, \"UNSUPPORTED_OPERATION\", {\n operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`\n });\n // Create a copy of this request, with a new URL\n const req = new FetchRequest(location);\n req.method = \"GET\";\n req.allowGzip = this.allowGzip;\n req.timeout = this.timeout;\n req.#headers = Object.assign({}, this.#headers);\n if (this.#body) {\n req.#body = new Uint8Array(this.#body);\n }\n req.#bodyType = this.#bodyType;\n // Do not forward credentials unless on the same domain; only absolute\n //req.allowInsecure = false;\n // paths are currently supported; may want a way to specify to forward?\n //setStore(req.#props, \"creds\", getStore(this.#pros, \"creds\"));\n return req;\n }\n /**\n * Create a new copy of this request.\n */\n clone() {\n const clone = new FetchRequest(this.url);\n // Preserve \"default method\" (i.e. null)\n clone.#method = this.#method;\n // Preserve \"default body\" with type, copying the Uint8Array is present\n if (this.#body) {\n clone.#body = this.#body;\n }\n clone.#bodyType = this.#bodyType;\n // Preserve \"default headers\"\n clone.#headers = Object.assign({}, this.#headers);\n // Credentials is readonly, so we copy internally\n clone.#creds = this.#creds;\n if (this.allowGzip) {\n clone.allowGzip = true;\n }\n clone.timeout = this.timeout;\n if (this.allowInsecureAuthentication) {\n clone.allowInsecureAuthentication = true;\n }\n clone.#preflight = this.#preflight;\n clone.#process = this.#process;\n clone.#retry = this.#retry;\n clone.#throttle = Object.assign({}, this.#throttle);\n clone.#getUrlFunc = this.#getUrlFunc;\n return clone;\n }\n /**\n * Locks all static configuration for gateways and FetchGetUrlFunc\n * registration.\n */\n static lockConfig() {\n locked = true;\n }\n /**\n * Get the current Gateway function for %%scheme%%.\n */\n static getGateway(scheme) {\n return Gateways[scheme.toLowerCase()] || null;\n }\n /**\n * Use the %%func%% when fetching URIs using %%scheme%%.\n *\n * This method affects all requests globally.\n *\n * If [[lockConfig]] has been called, no change is made and this\n * throws.\n */\n static registerGateway(scheme, func) {\n scheme = scheme.toLowerCase();\n if (scheme === \"http\" || scheme === \"https\") {\n throw new Error(`cannot intercept ${scheme}; use registerGetUrl`);\n }\n if (locked) {\n throw new Error(\"gateways locked\");\n }\n Gateways[scheme] = func;\n }\n /**\n * Use %%getUrl%% when fetching URIs over HTTP and HTTPS requests.\n *\n * This method affects all requests globally.\n *\n * If [[lockConfig]] has been called, no change is made and this\n * throws.\n */\n static registerGetUrl(getUrl) {\n if (locked) {\n throw new Error(\"gateways locked\");\n }\n defaultGetUrlFunc = getUrl;\n }\n /**\n * Creates a getUrl function that fetches content from HTTP and\n * HTTPS URLs.\n *\n * The available %%options%% are dependent on the platform\n * implementation of the default getUrl function.\n *\n * This is not generally something that is needed, but is useful\n * when trying to customize simple behaviour when fetching HTTP\n * content.\n */\n static createGetUrlFunc(options) {\n return createGetUrl(options);\n }\n /**\n * Creates a function that can \"fetch\" data URIs.\n *\n * Note that this is automatically done internally to support\n * data URIs, so it is not necessary to register it.\n *\n * This is not generally something that is needed, but may\n * be useful in a wrapper to perfom custom data URI functionality.\n */\n static createDataGateway() {\n return dataGatewayFunc;\n }\n /**\n * Creates a function that will fetch IPFS (unvalidated) from\n * a custom gateway baseUrl.\n *\n * The default IPFS gateway used internally is\n * ``\"https:/\\/gateway.ipfs.io/ipfs/\"``.\n */\n static createIpfsGatewayFunc(baseUrl) {\n return getIpfsGatewayFunc(baseUrl);\n }\n}\n;\n/**\n * The response for a FetchRequest.\n */\nexport class FetchResponse {\n #statusCode;\n #statusMessage;\n #headers;\n #body;\n #request;\n #error;\n toString() {\n return `<FetchResponse status=${this.statusCode} body=${this.#body ? hexlify(this.#body) : \"null\"}>`;\n }\n /**\n * The response status code.\n */\n get statusCode() { return this.#statusCode; }\n /**\n * The response status message.\n */\n get statusMessage() { return this.#statusMessage; }\n /**\n * The response headers. All keys are lower-case.\n */\n get headers() { return Object.assign({}, this.#headers); }\n /**\n * The response body, or ``null`` if there was no body.\n */\n get body() {\n return (this.#body == null) ? null : new Uint8Array(this.#body);\n }\n /**\n * The response body as a UTF-8 encoded string, or the empty\n * string (i.e. ``\"\"``) if there was no body.\n *\n * An error is thrown if the body is invalid UTF-8 data.\n */\n get bodyText() {\n try {\n return (this.#body == null) ? \"\" : toUtf8String(this.#body);\n }\n catch (error) {\n assert(false, \"response body is not valid UTF-8 data\", \"UNSUPPORTED_OPERATION\", {\n operation: \"bodyText\", info: { response: this }\n });\n }\n }\n /**\n * The response body, decoded as JSON.\n *\n * An error is thrown if the body is invalid JSON-encoded data\n * or if there was no body.\n */\n get bodyJson() {\n try {\n return JSON.parse(this.bodyText);\n }\n catch (error) {\n assert(false, \"response body is not valid JSON\", \"UNSUPPORTED_OPERATION\", {\n operation: \"bodyJson\", info: { response: this }\n });\n }\n }\n [Symbol.iterator]() {\n const headers = this.headers;\n const keys = Object.keys(headers);\n let index = 0;\n return {\n next: () => {\n if (index < keys.length) {\n const key = keys[index++];\n return {\n value: [key, headers[key]], done: false\n };\n }\n return { value: undefined, done: true };\n }\n };\n }\n constructor(statusCode, statusMessage, headers, body, request) {\n this.#statusCode = statusCode;\n this.#statusMessage = statusMessage;\n this.#headers = Object.keys(headers).reduce((accum, k) => {\n accum[k.toLowerCase()] = String(headers[k]);\n return accum;\n }, {});\n this.#body = ((body == null) ? null : new Uint8Array(body));\n this.#request = (request || null);\n this.#error = { message: \"\" };\n }\n /**\n * Return a Response with matching headers and body, but with\n * an error status code (i.e. 599) and %%message%% with an\n * optional %%error%%.\n */\n makeServerError(message, error) {\n let statusMessage;\n if (!message) {\n message = `${this.statusCode} ${this.statusMessage}`;\n statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`;\n }\n else {\n statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`;\n }\n const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined);\n response.#error = { message, error };\n return response;\n }\n /**\n * If called within a [request.processFunc](FetchRequest-processFunc)\n * call, causes the request to retry as if throttled for %%stall%%\n * milliseconds.\n */\n throwThrottleError(message, stall) {\n if (stall == null) {\n stall = -1;\n }\n else {\n assertArgument(Number.isInteger(stall) && stall >= 0, \"invalid stall timeout\", \"stall\", stall);\n }\n const error = new Error(message || \"throttling requests\");\n defineProperties(error, { stall, throttle: true });\n throw error;\n }\n /**\n * Get the header value for %%key%%, ignoring case.\n */\n getHeader(key) {\n return this.headers[key.toLowerCase()];\n }\n /**\n * Returns true if the response has a body.\n */\n hasBody() {\n return (this.#body != null);\n }\n /**\n * The request made for this response.\n */\n get request() { return this.#request; }\n /**\n * Returns true if this response was a success statusCode.\n */\n ok() {\n return (this.#error.message === \"\" && this.statusCode >= 200 && this.statusCode < 300);\n }\n /**\n * Throws a ``SERVER_ERROR`` if this response is not ok.\n */\n assertOk() {\n if (this.ok()) {\n return;\n }\n let { message, error } = this.#error;\n if (message === \"\") {\n message = `server response ${this.statusCode} ${this.statusMessage}`;\n }\n let requestUrl = null;\n if (this.request) {\n requestUrl = this.request.url;\n }\n let responseBody = null;\n try {\n if (this.#body) {\n responseBody = toUtf8String(this.#body);\n }\n }\n catch (e) { }\n assert(false, message, \"SERVER_ERROR\", {\n request: (this.request || \"unknown request\"), response: this, error,\n info: {\n requestUrl, responseBody,\n responseStatus: `${this.statusCode} ${this.statusMessage}`\n }\n });\n }\n}\nfunction getTime() { return (new Date()).getTime(); }\nfunction unpercent(value) {\n return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => {\n return String.fromCharCode(parseInt(code, 16));\n }));\n}\nfunction wait(delay) {\n return new Promise((resolve) => setTimeout(resolve, delay));\n}\n//# sourceMappingURL=fetch.js.map","//See: https://github.com/ethereum/wiki/wiki/RLP\nimport { hexlify } from \"./data.js\";\nimport { assert, assertArgument } from \"./errors.js\";\nimport { getBytes } from \"./data.js\";\nfunction hexlifyByte(value) {\n let result = value.toString(16);\n while (result.length < 2) {\n result = \"0\" + result;\n }\n return \"0x\" + result;\n}\nfunction unarrayifyInteger(data, offset, length) {\n let result = 0;\n for (let i = 0; i < length; i++) {\n result = (result * 256) + data[offset + i];\n }\n return result;\n}\nfunction _decodeChildren(data, offset, childOffset, length) {\n const result = [];\n while (childOffset < offset + 1 + length) {\n const decoded = _decode(data, childOffset);\n result.push(decoded.result);\n childOffset += decoded.consumed;\n assert(childOffset <= offset + 1 + length, \"child data too short\", \"BUFFER_OVERRUN\", {\n buffer: data, length, offset\n });\n }\n return { consumed: (1 + length), result: result };\n}\n// returns { consumed: number, result: Object }\nfunction _decode(data, offset) {\n assert(data.length !== 0, \"data too short\", \"BUFFER_OVERRUN\", {\n buffer: data, length: 0, offset: 1\n });\n const checkOffset = (offset) => {\n assert(offset <= data.length, \"data short segment too short\", \"BUFFER_OVERRUN\", {\n buffer: data, length: data.length, offset\n });\n };\n // Array with extra length prefix\n if (data[offset] >= 0xf8) {\n const lengthLength = data[offset] - 0xf7;\n checkOffset(offset + 1 + lengthLength);\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n checkOffset(offset + 1 + lengthLength + length);\n return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);\n }\n else if (data[offset] >= 0xc0) {\n const length = data[offset] - 0xc0;\n checkOffset(offset + 1 + length);\n return _decodeChildren(data, offset, offset + 1, length);\n }\n else if (data[offset] >= 0xb8) {\n const lengthLength = data[offset] - 0xb7;\n checkOffset(offset + 1 + lengthLength);\n const length = unarrayifyInteger(data, offset + 1, lengthLength);\n checkOffset(offset + 1 + lengthLength + length);\n const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));\n return { consumed: (1 + lengthLength + length), result: result };\n }\n else if (data[offset] >= 0x80) {\n const length = data[offset] - 0x80;\n checkOffset(offset + 1 + length);\n const result = hexlify(data.slice(offset + 1, offset + 1 + length));\n return { consumed: (1 + length), result: result };\n }\n return { consumed: 1, result: hexlifyByte(data[offset]) };\n}\n/**\n * Decodes %%data%% into the structured data it represents.\n */\nexport function decodeRlp(_data) {\n const data = getBytes(_data, \"data\");\n const decoded = _decode(data, 0);\n assertArgument(decoded.consumed === data.length, \"unexpected junk after rlp payload\", \"data\", _data);\n return decoded.result;\n}\n//# sourceMappingURL=rlp-decode.js.map","//See: https://github.com/ethereum/wiki/wiki/RLP\nimport { getBytes } from \"./data.js\";\nfunction arrayifyInteger(value) {\n const result = [];\n while (value) {\n result.unshift(value & 0xff);\n value >>= 8;\n }\n return result;\n}\nfunction _encode(object) {\n if (Array.isArray(object)) {\n let payload = [];\n object.forEach(function (child) {\n payload = payload.concat(_encode(child));\n });\n if (payload.length <= 55) {\n payload.unshift(0xc0 + payload.length);\n return payload;\n }\n const length = arrayifyInteger(payload.length);\n length.unshift(0xf7 + length.length);\n return length.concat(payload);\n }\n const data = Array.prototype.slice.call(getBytes(object, \"object\"));\n if (data.length === 1 && data[0] <= 0x7f) {\n return data;\n }\n else if (data.length <= 55) {\n data.unshift(0x80 + data.length);\n return data;\n }\n const length = arrayifyInteger(data.length);\n length.unshift(0xb7 + length.length);\n return length.concat(data);\n}\nconst nibbles = \"0123456789abcdef\";\n/**\n * Encodes %%object%% as an RLP-encoded [[DataHexString]].\n */\nexport function encodeRlp(object) {\n let result = \"0x\";\n for (const v of _encode(object)) {\n result += nibbles[v >> 4];\n result += nibbles[v & 0xf];\n }\n return result;\n}\n//# sourceMappingURL=rlp-encode.js.map","/**\n * Explain UUID and link to RFC here.\n *\n * @_subsection: api/utils:UUID [about-uuid]\n */\nimport { getBytes, hexlify } from \"./data.js\";\n/**\n * Returns the version 4 [[link-uuid]] for the %%randomBytes%%.\n *\n * @see: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)\n */\nexport function uuidV4(randomBytes) {\n const bytes = getBytes(randomBytes, \"randomBytes\");\n // Section: 4.1.3:\n // - time_hi_and_version[12:16] = 0b0100\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n // Section 4.4\n // - clock_seq_hi_and_reserved[6] = 0b0\n // - clock_seq_hi_and_reserved[7] = 0b1\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const value = hexlify(bytes);\n return [\n value.substring(2, 10),\n value.substring(10, 14),\n value.substring(14, 18),\n value.substring(18, 22),\n value.substring(22, 34),\n ].join(\"-\");\n}\n//# sourceMappingURL=uuid.js.map","import { defineProperties, concat, getBytesCopy, getNumber, hexlify, toBeArray, toBigInt, toNumber, assert, assertArgument\n/*, isError*/\n } from \"../../utils/index.js\";\n/**\n * @_ignore:\n */\nexport const WordSize = 32;\nconst Padding = new Uint8Array(WordSize);\n// Properties used to immediate pass through to the underlying object\n// - `then` is used to detect if an object is a Promise for await\nconst passProperties = [\"then\"];\nconst _guard = {};\nconst resultNames = new WeakMap();\nfunction getNames(result) {\n return resultNames.get(result);\n}\nfunction setNames(result, names) {\n resultNames.set(result, names);\n}\nfunction throwError(name, error) {\n const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`);\n wrapped.error = error;\n throw wrapped;\n}\nfunction toObject(names, items, deep) {\n if (names.indexOf(null) >= 0) {\n return items.map((item, index) => {\n if (item instanceof Result) {\n return toObject(getNames(item), item, deep);\n }\n return item;\n });\n }\n return names.reduce((accum, name, index) => {\n let item = items.getValue(name);\n if (!(name in accum)) {\n if (deep && item instanceof Result) {\n item = toObject(getNames(item), item, deep);\n }\n accum[name] = item;\n }\n return accum;\n }, {});\n}\n/**\n * A [[Result]] is a sub-class of Array, which allows accessing any\n * of its values either positionally by its index or, if keys are\n * provided by its name.\n *\n * @_docloc: api/abi\n */\nexport class Result extends Array {\n // No longer used; but cannot be removed as it will remove the\n // #private field from the .d.ts which may break backwards\n // compatibility\n #names;\n /**\n * @private\n */\n constructor(...args) {\n // To properly sub-class Array so the other built-in\n // functions work, the constructor has to behave fairly\n // well. So, in the event we are created via fromItems()\n // we build the read-only Result object we want, but on\n // any other input, we use the default constructor\n // constructor(guard: any, items: Array<any>, keys?: Array<null | string>);\n const guard = args[0];\n let items = args[1];\n let names = (args[2] || []).slice();\n let wrap = true;\n if (guard !== _guard) {\n items = args;\n names = [];\n wrap = false;\n }\n // Can't just pass in ...items since an array of length 1\n // is a special case in the super.\n super(items.length);\n items.forEach((item, index) => { this[index] = item; });\n // Find all unique keys\n const nameCounts = names.reduce((accum, name) => {\n if (typeof (name) === \"string\") {\n accum.set(name, (accum.get(name) || 0) + 1);\n }\n return accum;\n }, (new Map()));\n // Remove any key thats not unique\n setNames(this, Object.freeze(items.map((item, index) => {\n const name = names[index];\n if (name != null && nameCounts.get(name) === 1) {\n return name;\n }\n return null;\n })));\n // Dummy operations to prevent TypeScript from complaining\n this.#names = [];\n if (this.#names == null) {\n void (this.#names);\n }\n if (!wrap) {\n return;\n }\n // A wrapped Result is immutable\n Object.freeze(this);\n // Proxy indices and names so we can trap deferred errors\n const proxy = new Proxy(this, {\n get: (target, prop, receiver) => {\n if (typeof (prop) === \"string\") {\n // Index accessor\n if (prop.match(/^[0-9]+$/)) {\n const index = getNumber(prop, \"%index\");\n if (index < 0 || index >= this.length) {\n throw new RangeError(\"out of result range\");\n }\n const item = target[index];\n if (item instanceof Error) {\n throwError(`index ${index}`, item);\n }\n return item;\n }\n // Pass important checks (like `then` for Promise) through\n if (passProperties.indexOf(prop) >= 0) {\n return Reflect.get(target, prop, receiver);\n }\n const value = target[prop];\n if (value instanceof Function) {\n // Make sure functions work with private variables\n // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#no_private_property_forwarding\n return function (...args) {\n return value.apply((this === receiver) ? target : this, args);\n };\n }\n else if (!(prop in target)) {\n // Possible name accessor\n return target.getValue.apply((this === receiver) ? target : this, [prop]);\n }\n }\n return Reflect.get(target, prop, receiver);\n }\n });\n setNames(proxy, getNames(this));\n return proxy;\n }\n /**\n * Returns the Result as a normal Array. If %%deep%%, any children\n * which are Result objects are also converted to a normal Array.\n *\n * This will throw if there are any outstanding deferred\n * errors.\n */\n toArray(deep) {\n const result = [];\n this.forEach((item, index) => {\n if (item instanceof Error) {\n throwError(`index ${index}`, item);\n }\n if (deep && item instanceof Result) {\n item = item.toArray(deep);\n }\n result.push(item);\n });\n return result;\n }\n /**\n * Returns the Result as an Object with each name-value pair. If\n * %%deep%%, any children which are Result objects are also\n * converted to an Object.\n *\n * This will throw if any value is unnamed, or if there are\n * any outstanding deferred errors.\n */\n toObject(deep) {\n const names = getNames(this);\n return names.reduce((accum, name, index) => {\n assert(name != null, `value at index ${index} unnamed`, \"UNSUPPORTED_OPERATION\", {\n operation: \"toObject()\"\n });\n return toObject(names, this, deep);\n }, {});\n }\n /**\n * @_ignore\n */\n slice(start, end) {\n if (start == null) {\n start = 0;\n }\n if (start < 0) {\n start += this.length;\n if (start < 0) {\n start = 0;\n }\n }\n if (end == null) {\n end = this.length;\n }\n if (end < 0) {\n end += this.length;\n if (end < 0) {\n end = 0;\n }\n }\n if (end > this.length) {\n end = this.length;\n }\n const _names = getNames(this);\n const result = [], names = [];\n for (let i = start; i < end; i++) {\n result.push(this[i]);\n names.push(_names[i]);\n }\n return new Result(_guard, result, names);\n }\n /**\n * @_ignore\n */\n filter(callback, thisArg) {\n const _names = getNames(this);\n const result = [], names = [];\n for (let i = 0; i < this.length; i++) {\n const item = this[i];\n if (item instanceof Error) {\n throwError(`index ${i}`, item);\n }\n if (callback.call(thisArg, item, i, this)) {\n result.push(item);\n names.push(_names[i]);\n }\n }\n return new Result(_guard, result, names);\n }\n /**\n * @_ignore\n */\n map(callback, thisArg) {\n const result = [];\n for (let i = 0; i < this.length; i++) {\n const item = this[i];\n if (item instanceof Error) {\n throwError(`index ${i}`, item);\n }\n result.push(callback.call(thisArg, item, i, this));\n }\n return result;\n }\n /**\n * Returns the value for %%name%%.\n *\n * Since it is possible to have a key whose name conflicts with\n * a method on a [[Result]] or its superclass Array, or any\n * JavaScript keyword, this ensures all named values are still\n * accessible by name.\n */\n getValue(name) {\n const index = getNames(this).indexOf(name);\n if (index === -1) {\n return undefined;\n }\n const value = this[index];\n if (value instanceof Error) {\n throwError(`property ${JSON.stringify(name)}`, value.error);\n }\n return value;\n }\n /**\n * Creates a new [[Result]] for %%items%% with each entry\n * also accessible by its corresponding name in %%keys%%.\n */\n static fromItems(items, keys) {\n return new Result(_guard, items, keys);\n }\n}\n/**\n * Returns all errors found in a [[Result]].\n *\n * Since certain errors encountered when creating a [[Result]] do\n * not impact the ability to continue parsing data, they are\n * deferred until they are actually accessed. Hence a faulty string\n * in an Event that is never used does not impact the program flow.\n *\n * However, sometimes it may be useful to access, identify or\n * validate correctness of a [[Result]].\n *\n * @_docloc api/abi\n */\nexport function checkResultErrors(result) {\n // Find the first error (if any)\n const errors = [];\n const checkErrors = function (path, object) {\n if (!Array.isArray(object)) {\n return;\n }\n for (let key in object) {\n const childPath = path.slice();\n childPath.push(key);\n try {\n checkErrors(childPath, object[key]);\n }\n catch (error) {\n errors.push({ path: childPath, error: error });\n }\n }\n };\n checkErrors([], result);\n return errors;\n}\nfunction getValue(value) {\n let bytes = toBeArray(value);\n assert(bytes.length <= WordSize, \"value out-of-bounds\", \"BUFFER_OVERRUN\", { buffer: bytes, length: WordSize, offset: bytes.length });\n if (bytes.length !== WordSize) {\n bytes = getBytesCopy(concat([Padding.slice(bytes.length % WordSize), bytes]));\n }\n return bytes;\n}\n/**\n * @_ignore\n */\nexport class Coder {\n // The coder name:\n // - address, uint256, tuple, array, etc.\n name;\n // The fully expanded type, including composite types:\n // - address, uint256, tuple(address,bytes), uint256[3][4][], etc.\n type;\n // The localName bound in the signature, in this example it is \"baz\":\n // - tuple(address foo, uint bar) baz\n localName;\n // Whether this type is dynamic:\n // - Dynamic: bytes, string, address[], tuple(boolean[]), etc.\n // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8)\n dynamic;\n constructor(name, type, localName, dynamic) {\n defineProperties(this, { name, type, localName, dynamic }, {\n name: \"string\", type: \"string\", localName: \"string\", dynamic: \"boolean\"\n });\n }\n _throwError(message, value) {\n assertArgument(false, message, this.localName, value);\n }\n}\n/**\n * @_ignore\n */\nexport class Writer {\n // An array of WordSize lengthed objects to concatenation\n #data;\n #dataLength;\n constructor() {\n this.#data = [];\n this.#dataLength = 0;\n }\n get data() {\n return concat(this.#data);\n }\n get length() { return this.#dataLength; }\n #writeData(data) {\n this.#data.push(data);\n this.#dataLength += data.length;\n return data.length;\n }\n appendWriter(writer) {\n return this.#writeData(getBytesCopy(writer.data));\n }\n // Arrayish item; pad on the right to *nearest* WordSize\n writeBytes(value) {\n let bytes = getBytesCopy(value);\n const paddingOffset = bytes.length % WordSize;\n if (paddingOffset) {\n bytes = getBytesCopy(concat([bytes, Padding.slice(paddingOffset)]));\n }\n return this.#writeData(bytes);\n }\n // Numeric item; pad on the left *to* WordSize\n writeValue(value) {\n return this.#writeData(getValue(value));\n }\n // Inserts a numeric place-holder, returning a callback that can\n // be used to asjust the value later\n writeUpdatableValue() {\n const offset = this.#data.length;\n this.#data.push(Padding);\n this.#dataLength += WordSize;\n return (value) => {\n this.#data[offset] = getValue(value);\n };\n }\n}\n/**\n * @_ignore\n */\nexport class Reader {\n // Allows incomplete unpadded data to be read; otherwise an error\n // is raised if attempting to overrun the buffer. This is required\n // to deal with an old Solidity bug, in which event data for\n // external (not public thoguh) was tightly packed.\n allowLoose;\n #data;\n #offset;\n #bytesRead;\n #parent;\n #maxInflation;\n constructor(data, allowLoose, maxInflation) {\n defineProperties(this, { allowLoose: !!allowLoose });\n this.#data = getBytesCopy(data);\n this.#bytesRead = 0;\n this.#parent = null;\n this.#maxInflation = (maxInflation != null) ? maxInflation : 1024;\n this.#offset = 0;\n }\n get data() { return hexlify(this.#data); }\n get dataLength() { return this.#data.length; }\n get consumed() { return this.#offset; }\n get bytes() { return new Uint8Array(this.#data); }\n #incrementBytesRead(count) {\n if (this.#parent) {\n return this.#parent.#incrementBytesRead(count);\n }\n this.#bytesRead += count;\n // Check for excessive inflation (see: #4537)\n assert(this.#maxInflation < 1 || this.#bytesRead <= this.#maxInflation * this.dataLength, `compressed ABI data exceeds inflation ratio of ${this.#maxInflation} ( see: https:/\\/github.com/ethers-io/ethers.js/issues/4537 )`, \"BUFFER_OVERRUN\", {\n buffer: getBytesCopy(this.#data), offset: this.#offset,\n length: count, info: {\n bytesRead: this.#bytesRead,\n dataLength: this.dataLength\n }\n });\n }\n #peekBytes(offset, length, loose) {\n let alignedLength = Math.ceil(length / WordSize) * WordSize;\n if (this.#offset + alignedLength > this.#data.length) {\n if (this.allowLoose && loose && this.#offset + length <= this.#data.length) {\n alignedLength = length;\n }\n else {\n assert(false, \"data out-of-bounds\", \"BUFFER_OVERRUN\", {\n buffer: getBytesCopy(this.#data),\n length: this.#data.length,\n offset: this.#offset + alignedLength\n });\n }\n }\n return this.#data.slice(this.#offset, this.#offset + alignedLength);\n }\n // Create a sub-reader with the same underlying data, but offset\n subReader(offset) {\n const reader = new Reader(this.#data.slice(this.#offset + offset), this.allowLoose, this.#maxInflation);\n reader.#parent = this;\n return reader;\n }\n // Read bytes\n readBytes(length, loose) {\n let bytes = this.#peekBytes(0, length, !!loose);\n this.#incrementBytesRead(length);\n this.#offset += bytes.length;\n // @TODO: Make sure the length..end bytes are all 0?\n return bytes.slice(0, length);\n }\n // Read a numeric values\n readValue() {\n return toBigInt(this.readBytes(WordSize));\n }\n readIndex() {\n return toNumber(this.readBytes(WordSize));\n }\n}\n//# sourceMappingURL=abstract-coder.js.map","/**\n * An **HMAC** enables verification that a given key was used\n * to authenticate a payload.\n *\n * See: [[link-wiki-hmac]]\n *\n * @_subsection: api/crypto:HMAC [about-hmac]\n */\nimport { createHmac } from \"./crypto.js\";\nimport { getBytes, hexlify } from \"../utils/index.js\";\nlet locked = false;\nconst _computeHmac = function (algorithm, key, data) {\n return createHmac(algorithm, key).update(data).digest();\n};\nlet __computeHmac = _computeHmac;\n/**\n * Return the HMAC for %%data%% using the %%key%% key with the underlying\n * %%algo%% used for compression.\n *\n * @example:\n * key = id(\"some-secret\")\n *\n * // Compute the HMAC\n * computeHmac(\"sha256\", key, \"0x1337\")\n * //_result:\n *\n * // To compute the HMAC of UTF-8 data, the data must be\n * // converted to UTF-8 bytes\n * computeHmac(\"sha256\", key, toUtf8Bytes(\"Hello World\"))\n * //_result:\n *\n */\nexport function computeHmac(algorithm, _key, _data) {\n const key = getBytes(_key, \"key\");\n const data = getBytes(_data, \"data\");\n return hexlify(__computeHmac(algorithm, key, data));\n}\ncomputeHmac._ = _computeHmac;\ncomputeHmac.lock = function () { locked = true; };\ncomputeHmac.register = function (func) {\n if (locked) {\n throw new Error(\"computeHmac is locked\");\n }\n __computeHmac = func;\n};\nObject.freeze(computeHmac);\n//# sourceMappingURL=hmac.js.map","/**\n * Cryptographic hashing functions\n *\n * @_subsection: api/crypto:Hash Functions [about-crypto-hashing]\n */\nimport { keccak_256 } from \"@noble/hashes/sha3\";\nimport { getBytes, hexlify } from \"../utils/index.js\";\nlet locked = false;\nconst _keccak256 = function (data) {\n return keccak_256(data);\n};\nlet __keccak256 = _keccak256;\n/**\n * Compute the cryptographic KECCAK256 hash of %%data%%.\n *\n * The %%data%% **must** be a data representation, to compute the\n * hash of UTF-8 data use the [[id]] function.\n *\n * @returns DataHexstring\n * @example:\n * keccak256(\"0x\")\n * //_result:\n *\n * keccak256(\"0x1337\")\n * //_result:\n *\n * keccak256(new Uint8Array([ 0x13, 0x37 ]))\n * //_result:\n *\n * // Strings are assumed to be DataHexString, otherwise it will\n * // throw. To hash UTF-8 data, see the note above.\n * keccak256(\"Hello World\")\n * //_error:\n */\nexport function keccak256(_data) {\n const data = getBytes(_data, \"data\");\n return hexlify(__keccak256(data));\n}\nkeccak256._ = _keccak256;\nkeccak256.lock = function () { locked = true; };\nkeccak256.register = function (func) {\n if (locked) {\n throw new TypeError(\"keccak256 is locked\");\n }\n __keccak256 = func;\n};\nObject.freeze(keccak256);\n//# sourceMappingURL=keccak.js.map","import { ripemd160 as noble_ripemd160 } from \"@noble/hashes/ripemd160\";\nimport { getBytes, hexlify } from \"../utils/index.js\";\nlet locked = false;\nconst _ripemd160 = function (data) {\n return noble_ripemd160(data);\n};\nlet __ripemd160 = _ripemd160;\n/**\n * Compute the cryptographic RIPEMD-160 hash of %%data%%.\n *\n * @_docloc: api/crypto:Hash Functions\n * @returns DataHexstring\n *\n * @example:\n * ripemd160(\"0x\")\n * //_result:\n *\n * ripemd160(\"0x1337\")\n * //_result:\n *\n * ripemd160(new Uint8Array([ 0x13, 0x37 ]))\n * //_result:\n *\n */\nexport function ripemd160(_data) {\n const data = getBytes(_data, \"data\");\n return hexlify(__ripemd160(data));\n}\nripemd160._ = _ripemd160;\nripemd160.lock = function () { locked = true; };\nripemd160.register = function (func) {\n if (locked) {\n throw new TypeError(\"ripemd160 is locked\");\n }\n __ripemd160 = func;\n};\nObject.freeze(ripemd160);\n//# sourceMappingURL=ripemd160.js.map","/**\n * A **Password-Based Key-Derivation Function** is designed to create\n * a sequence of bytes suitible as a **key** from a human-rememberable\n * password.\n *\n * @_subsection: api/crypto:Passwords [about-pbkdf]\n */\nimport { pbkdf2Sync } from \"./crypto.js\";\nimport { getBytes, hexlify } from \"../utils/index.js\";\nlet locked = false;\nconst _pbkdf2 = function (password, salt, iterations, keylen, algo) {\n return pbkdf2Sync(password, salt, iterations, keylen, algo);\n};\nlet __pbkdf2 = _pbkdf2;\n/**\n * Return the [[link-pbkdf2]] for %%keylen%% bytes for %%password%% using\n * the %%salt%% and using %%iterations%% of %%algo%%.\n *\n * This PBKDF is outdated and should not be used in new projects, but is\n * required to decrypt older files.\n *\n * @example:\n * // The password must be converted to bytes, and it is generally\n * // best practices to ensure the string has been normalized. Many\n * // formats explicitly indicate the normalization form to use.\n * password = \"hello\"\n * passwordBytes = toUtf8Bytes(password, \"NFKC\")\n *\n * salt = id(\"some-salt\")\n *\n * // Compute the PBKDF2\n * pbkdf2(passwordBytes, salt, 1024, 16, \"sha256\")\n * //_result:\n */\nexport function pbkdf2(_password, _salt, iterations, keylen, algo) {\n const password = getBytes(_password, \"password\");\n const salt = getBytes(_salt, \"salt\");\n return hexlify(__pbkdf2(password, salt, iterations, keylen, algo));\n}\npbkdf2._ = _pbkdf2;\npbkdf2.lock = function () { locked = true; };\npbkdf2.register = function (func) {\n if (locked) {\n throw new Error(\"pbkdf2 is locked\");\n }\n __pbkdf2 = func;\n};\nObject.freeze(pbkdf2);\n//# sourceMappingURL=pbkdf2.js.map","/**\n * A **Cryptographically Secure Random Value** is one that has been\n * generated with additional care take to prevent side-channels\n * from allowing others to detect it and prevent others from through\n * coincidence generate the same values.\n *\n * @_subsection: api/crypto:Random Values [about-crypto-random]\n */\nimport { randomBytes as crypto_random } from \"./crypto.js\";\nlet locked = false;\nconst _randomBytes = function (length) {\n return new Uint8Array(crypto_random(length));\n};\nlet __randomBytes = _randomBytes;\n/**\n * Return %%length%% bytes of cryptographically secure random data.\n *\n * @example:\n * randomBytes(8)\n * //_result:\n */\nexport function randomBytes(length) {\n return __randomBytes(length);\n}\nrandomBytes._ = _randomBytes;\nrandomBytes.lock = function () { locked = true; };\nrandomBytes.register = function (func) {\n if (locked) {\n throw new Error(\"randomBytes is locked\");\n }\n __randomBytes = func;\n};\nObject.freeze(randomBytes);\n//# sourceMappingURL=random.js.map","import { scrypt as _nobleSync, scryptAsync as _nobleAsync } from \"@noble/hashes/scrypt\";\nimport { getBytes, hexlify as H } from \"../utils/index.js\";\nlet lockedSync = false, lockedAsync = false;\nconst _scryptAsync = async function (passwd, salt, N, r, p, dkLen, onProgress) {\n return await _nobleAsync(passwd, salt, { N, r, p, dkLen, onProgress });\n};\nconst _scryptSync = function (passwd, salt, N, r, p, dkLen) {\n return _nobleSync(passwd, salt, { N, r, p, dkLen });\n};\nlet __scryptAsync = _scryptAsync;\nlet __scryptSync = _scryptSync;\n/**\n * The [[link-wiki-scrypt]] uses a memory and cpu hard method of\n * derivation to increase the resource cost to brute-force a password\n * for a given key.\n *\n * This means this algorithm is intentionally slow, and can be tuned to\n * become slower. As computation and memory speed improve over time,\n * increasing the difficulty maintains the cost of an attacker.\n *\n * For example, if a target time of 5 seconds is used, a legitimate user\n * which knows their password requires only 5 seconds to unlock their\n * account. A 6 character password has 68 billion possibilities, which\n * would require an attacker to invest over 10,000 years of CPU time. This\n * is of course a crude example (as password generally aren't random),\n * but demonstrates to value of imposing large costs to decryption.\n *\n * For this reason, if building a UI which involved decrypting or\n * encrypting datsa using scrypt, it is recommended to use a\n * [[ProgressCallback]] (as event short periods can seem lik an eternity\n * if the UI freezes). Including the phrase //\"decrypting\"// in the UI\n * can also help, assuring the user their waiting is for a good reason.\n *\n * @_docloc: api/crypto:Passwords\n *\n * @example:\n * // The password must be converted to bytes, and it is generally\n * // best practices to ensure the string has been normalized. Many\n * // formats explicitly indicate the normalization form to use.\n * password = \"hello\"\n * passwordBytes = toUtf8Bytes(password, \"NFKC\")\n *\n * salt = id(\"some-salt\")\n *\n * // Compute the scrypt\n * scrypt(passwordBytes, salt, 1024, 8, 1, 16)\n * //_result:\n */\nexport async function scrypt(_passwd, _salt, N, r, p, dkLen, progress) {\n const passwd = getBytes(_passwd, \"passwd\");\n const salt = getBytes(_salt, \"salt\");\n return H(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress));\n}\nscrypt._ = _scryptAsync;\nscrypt.lock = function () { lockedAsync = true; };\nscrypt.register = function (func) {\n if (lockedAsync) {\n throw new Error(\"scrypt is locked\");\n }\n __scryptAsync = func;\n};\nObject.freeze(scrypt);\n/**\n * Provides a synchronous variant of [[scrypt]].\n *\n * This will completely lock up and freeze the UI in a browser and will\n * prevent any event loop from progressing. For this reason, it is\n * preferred to use the [async variant](scrypt).\n *\n * @_docloc: api/crypto:Passwords\n *\n * @example:\n * // The password must be converted to bytes, and it is generally\n * // best practices to ensure the string has been normalized. Many\n * // formats explicitly indicate the normalization form to use.\n * password = \"hello\"\n * passwordBytes = toUtf8Bytes(password, \"NFKC\")\n *\n * salt = id(\"some-salt\")\n *\n * // Compute the scrypt\n * scryptSync(passwordBytes, salt, 1024, 8, 1, 16)\n * //_result:\n */\nexport function scryptSync(_passwd, _salt, N, r, p, dkLen) {\n const passwd = getBytes(_passwd, \"passwd\");\n const salt = getBytes(_salt, \"salt\");\n return H(__scryptSync(passwd, salt, N, r, p, dkLen));\n}\nscryptSync._ = _scryptSync;\nscryptSync.lock = function () { lockedSync = true; };\nscryptSync.register = function (func) {\n if (lockedSync) {\n throw new Error(\"scryptSync is locked\");\n }\n __scryptSync = func;\n};\nObject.freeze(scryptSync);\n//# sourceMappingURL=scrypt.js.map","import { createHash } from \"./crypto.js\";\nimport { getBytes, hexlify } from \"../utils/index.js\";\nconst _sha256 = function (data) {\n return createHash(\"sha256\").update(data).digest();\n};\nconst _sha512 = function (data) {\n return createHash(\"sha512\").update(data).digest();\n};\nlet __sha256 = _sha256;\nlet __sha512 = _sha512;\nlet locked256 = false, locked512 = false;\n/**\n * Compute the cryptographic SHA2-256 hash of %%data%%.\n *\n * @_docloc: api/crypto:Hash Functions\n * @returns DataHexstring\n *\n * @example:\n * sha256(\"0x\")\n * //_result:\n *\n * sha256(\"0x1337\")\n * //_result:\n *\n * sha256(new Uint8Array([ 0x13, 0x37 ]))\n * //_result:\n *\n */\nexport function sha256(_data) {\n const data = getBytes(_data, \"data\");\n return hexlify(__sha256(data));\n}\nsha256._ = _sha256;\nsha256.lock = function () { locked256 = true; };\nsha256.register = function (func) {\n if (locked256) {\n throw new Error(\"sha256 is locked\");\n }\n __sha256 = func;\n};\nObject.freeze(sha256);\n/**\n * Compute the cryptographic SHA2-512 hash of %%data%%.\n *\n * @_docloc: api/crypto:Hash Functions\n * @returns DataHexstring\n *\n * @example:\n * sha512(\"0x\")\n * //_result:\n *\n * sha512(\"0x1337\")\n * //_result:\n *\n * sha512(new Uint8Array([ 0x13, 0x37 ]))\n * //_result:\n */\nexport function sha512(_data) {\n const data = getBytes(_data, \"data\");\n return hexlify(__sha512(data));\n}\nsha512._ = _sha512;\nsha512.lock = function () { locked512 = true; };\nsha512.register = function (func) {\n if (locked512) {\n throw new Error(\"sha512 is locked\");\n }\n __sha512 = func;\n};\nObject.freeze(sha256);\n//# sourceMappingURL=sha2.js.map","/**\n * A constant for the zero address.\n *\n * (**i.e.** ``\"0x0000000000000000000000000000000000000000\"``)\n */\nexport const ZeroAddress = \"0x0000000000000000000000000000000000000000\";\n//# sourceMappingURL=addresses.js.map","/**\n * A constant for the zero hash.\n *\n * (**i.e.** ``\"0x0000000000000000000000000000000000000000000000000000000000000000\"``)\n */\nexport const ZeroHash = \"0x0000000000000000000000000000000000000000000000000000000000000000\";\n//# sourceMappingURL=hashes.js.map","import { ZeroHash } from \"../constants/index.js\";\nimport { concat, dataLength, getBigInt, getBytes, getNumber, hexlify, toBeArray, isHexString, zeroPadValue, assertArgument, assertPrivate } from \"../utils/index.js\";\n// Constants\nconst BN_0 = BigInt(0);\nconst BN_1 = BigInt(1);\nconst BN_2 = BigInt(2);\nconst BN_27 = BigInt(27);\nconst BN_28 = BigInt(28);\nconst BN_35 = BigInt(35);\nconst _guard = {};\nfunction toUint256(value) {\n return zeroPadValue(toBeArray(value), 32);\n}\n/**\n * A Signature @TODO\n *\n *\n * @_docloc: api/crypto:Signing\n */\nexport class Signature {\n #r;\n #s;\n #v;\n #networkV;\n /**\n * The ``r`` value for a signautre.\n *\n * This represents the ``x`` coordinate of a \"reference\" or\n * challenge point, from which the ``y`` can be computed.\n */\n get r() { return this.#r; }\n set r(value) {\n assertArgument(dataLength(value) === 32, \"invalid r\", \"value\", value);\n this.#r = hexlify(value);\n }\n /**\n * The ``s`` value for a signature.\n */\n get s() { return this.#s; }\n set s(_value) {\n assertArgument(dataLength(_value) === 32, \"invalid s\", \"value\", _value);\n const value = hexlify(_value);\n assertArgument(parseInt(value.substring(0, 3)) < 8, \"non-canonical s\", \"value\", value);\n this.#s = value;\n }\n /**\n * The ``v`` value for a signature.\n *\n * Since a given ``x`` value for ``r`` has two possible values for\n * its correspondin ``y``, the ``v`` indicates which of the two ``y``\n * values to use.\n *\n * It is normalized to the values ``27`` or ``28`` for legacy\n * purposes.\n */\n get v() { return this.#v; }\n set v(value) {\n const v = getNumber(value, \"value\");\n assertArgument(v === 27 || v === 28, \"invalid v\", \"v\", value);\n this.#v = v;\n }\n /**\n * The EIP-155 ``v`` for legacy transactions. For non-legacy\n * transactions, this value is ``null``.\n */\n get networkV() { return this.#networkV; }\n /**\n * The chain ID for EIP-155 legacy transactions. For non-legacy\n * transactions, this value is ``null``.\n */\n get legacyChainId() {\n const v = this.networkV;\n if (v == null) {\n return null;\n }\n return Signature.getChainId(v);\n }\n /**\n * The ``yParity`` for the signature.\n *\n * See ``v`` for more details on how this value is used.\n */\n get yParity() {\n return (this.v === 27) ? 0 : 1;\n }\n /**\n * The [[link-eip-2098]] compact representation of the ``yParity``\n * and ``s`` compacted into a single ``bytes32``.\n */\n get yParityAndS() {\n // The EIP-2098 compact representation\n const yParityAndS = getBytes(this.s);\n if (this.yParity) {\n yParityAndS[0] |= 0x80;\n }\n return hexlify(yParityAndS);\n }\n /**\n * The [[link-eip-2098]] compact representation.\n */\n get compactSerialized() {\n return concat([this.r, this.yParityAndS]);\n }\n /**\n * The serialized representation.\n */\n get serialized() {\n return concat([this.r, this.s, (this.yParity ? \"0x1c\" : \"0x1b\")]);\n }\n /**\n * @private\n */\n constructor(guard, r, s, v) {\n assertPrivate(guard, _guard, \"Signature\");\n this.#r = r;\n this.#s = s;\n this.#v = v;\n this.#networkV = null;\n }\n [Symbol.for('nodejs.util.inspect.custom')]() {\n return `Signature { r: \"${this.r}\", s: \"${this.s}\", yParity: ${this.yParity}, networkV: ${this.networkV} }`;\n }\n /**\n * Returns a new identical [[Signature]].\n */\n clone() {\n const clone = new Signature(_guard, this.r, this.s, this.v);\n if (this.networkV) {\n clone.#networkV = this.networkV;\n }\n return clone;\n }\n /**\n * Returns a representation that is compatible with ``JSON.stringify``.\n */\n toJSON() {\n const networkV = this.networkV;\n return {\n _type: \"signature\",\n networkV: ((networkV != null) ? networkV.toString() : null),\n r: this.r, s: this.s, v: this.v,\n };\n }\n /**\n * Compute the chain ID from the ``v`` in a legacy EIP-155 transactions.\n *\n * @example:\n * Signature.getChainId(45)\n * //_result:\n *\n * Signature.getChainId(46)\n * //_result:\n */\n static getChainId(v) {\n const bv = getBigInt(v, \"v\");\n // The v is not an EIP-155 v, so it is the unspecified chain ID\n if ((bv == BN_27) || (bv == BN_28)) {\n return BN_0;\n }\n // Bad value for an EIP-155 v\n assertArgument(bv >= BN_35, \"invalid EIP-155 v\", \"v\", v);\n return (bv - BN_35) / BN_2;\n }\n /**\n * Compute the ``v`` for a chain ID for a legacy EIP-155 transactions.\n *\n * Legacy transactions which use [[link-eip-155]] hijack the ``v``\n * property to include the chain ID.\n *\n * @example:\n * Signature.getChainIdV(5, 27)\n * //_result:\n *\n * Signature.getChainIdV(5, 28)\n * //_result:\n *\n */\n static getChainIdV(chainId, v) {\n return (getBigInt(chainId) * BN_2) + BigInt(35 + v - 27);\n }\n /**\n * Compute the normalized legacy transaction ``v`` from a ``yParirty``,\n * a legacy transaction ``v`` or a legacy [[link-eip-155]] transaction.\n *\n * @example:\n * // The values 0 and 1 imply v is actually yParity\n * Signature.getNormalizedV(0)\n * //_result:\n *\n * // Legacy non-EIP-1559 transaction (i.e. 27 or 28)\n * Signature.getNormalizedV(27)\n * //_result:\n *\n * // Legacy EIP-155 transaction (i.e. >= 35)\n * Signature.getNormalizedV(46)\n * //_result:\n *\n * // Invalid values throw\n * Signature.getNormalizedV(5)\n * //_error:\n */\n static getNormalizedV(v) {\n const bv = getBigInt(v);\n if (bv === BN_0 || bv === BN_27) {\n return 27;\n }\n if (bv === BN_1 || bv === BN_28) {\n return 28;\n }\n assertArgument(bv >= BN_35, \"invalid v\", \"v\", v);\n // Otherwise, EIP-155 v means odd is 27 and even is 28\n return (bv & BN_1) ? 27 : 28;\n }\n /**\n * Creates a new [[Signature]].\n *\n * If no %%sig%% is provided, a new [[Signature]] is created\n * with default values.\n *\n * If %%sig%% is a string, it is parsed.\n */\n static from(sig) {\n function assertError(check, message) {\n assertArgument(check, message, \"signature\", sig);\n }\n ;\n if (sig == null) {\n return new Signature(_guard, ZeroHash, ZeroHash, 27);\n }\n if (typeof (sig) === \"string\") {\n const bytes = getBytes(sig, \"signature\");\n if (bytes.length === 64) {\n const r = hexlify(bytes.slice(0, 32));\n const s = bytes.slice(32, 64);\n const v = (s[0] & 0x80) ? 28 : 27;\n s[0] &= 0x7f;\n return new Signature(_guard, r, hexlify(s), v);\n }\n if (bytes.length === 65) {\n const r = hexlify(bytes.slice(0, 32));\n const s = bytes.slice(32, 64);\n assertError((s[0] & 0x80) === 0, \"non-canonical s\");\n const v = Signature.getNormalizedV(bytes[64]);\n return new Signature(_guard, r, hexlify(s), v);\n }\n assertError(false, \"invalid raw signature length\");\n }\n if (sig instanceof Signature) {\n return sig.clone();\n }\n // Get r\n const _r = sig.r;\n assertError(_r != null, \"missing r\");\n const r = toUint256(_r);\n // Get s; by any means necessary (we check consistency below)\n const s = (function (s, yParityAndS) {\n if (s != null) {\n return toUint256(s);\n }\n if (yParityAndS != null) {\n assertError(isHexString(yParityAndS, 32), \"invalid yParityAndS\");\n const bytes = getBytes(yParityAndS);\n bytes[0] &= 0x7f;\n return hexlify(bytes);\n }\n assertError(false, \"missing s\");\n })(sig.s, sig.yParityAndS);\n assertError((getBytes(s)[0] & 0x80) == 0, \"non-canonical s\");\n // Get v; by any means necessary (we check consistency below)\n const { networkV, v } = (function (_v, yParityAndS, yParity) {\n if (_v != null) {\n const v = getBigInt(_v);\n return {\n networkV: ((v >= BN_35) ? v : undefined),\n v: Signature.getNormalizedV(v)\n };\n }\n if (yParityAndS != null) {\n assertError(isHexString(yParityAndS, 32), \"invalid yParityAndS\");\n return { v: ((getBytes(yParityAndS)[0] & 0x80) ? 28 : 27) };\n }\n if (yParity != null) {\n switch (getNumber(yParity, \"sig.yParity\")) {\n case 0: return { v: 27 };\n case 1: return { v: 28 };\n }\n assertError(false, \"invalid yParity\");\n }\n assertError(false, \"missing v\");\n })(sig.v, sig.yParityAndS, sig.yParity);\n const result = new Signature(_guard, r, s, v);\n if (networkV) {\n result.#networkV = networkV;\n }\n // If multiple of v, yParity, yParityAndS we given, check they match\n assertError(sig.yParity == null || getNumber(sig.yParity, \"sig.yParity\") === result.yParity, \"yParity mismatch\");\n assertError(sig.yParityAndS == null || sig.yParityAndS === result.yParityAndS, \"yParityAndS mismatch\");\n return result;\n }\n}\n//# sourceMappingURL=signature.js.map","/**\n * Add details about signing here.\n *\n * @_subsection: api/crypto:Signing [about-signing]\n */\nimport { secp256k1 } from \"@noble/curves/secp256k1\";\nimport { concat, dataLength, getBytes, getBytesCopy, hexlify, toBeHex, assertArgument } from \"../utils/index.js\";\nimport { Signature } from \"./signature.js\";\n/**\n * A **SigningKey** provides high-level access to the elliptic curve\n * cryptography (ECC) operations and key management.\n */\nexport class SigningKey {\n #privateKey;\n /**\n * Creates a new **SigningKey** for %%privateKey%%.\n */\n constructor(privateKey) {\n assertArgument(dataLength(privateKey) === 32, \"invalid private key\", \"privateKey\", \"[REDACTED]\");\n this.#privateKey = hexlify(privateKey);\n }\n /**\n * The private key.\n */\n get privateKey() { return this.#privateKey; }\n /**\n * The uncompressed public key.\n *\n * This will always begin with the prefix ``0x04`` and be 132\n * characters long (the ``0x`` prefix and 130 hexadecimal nibbles).\n */\n get publicKey() { return SigningKey.computePublicKey(this.#privateKey); }\n /**\n * The compressed public key.\n *\n * This will always begin with either the prefix ``0x02`` or ``0x03``\n * and be 68 characters long (the ``0x`` prefix and 33 hexadecimal\n * nibbles)\n */\n get compressedPublicKey() { return SigningKey.computePublicKey(this.#privateKey, true); }\n /**\n * Return the signature of the signed %%digest%%.\n */\n sign(digest) {\n assertArgument(dataLength(digest) === 32, \"invalid digest length\", \"digest\", digest);\n const sig = secp256k1.sign(getBytesCopy(digest), getBytesCopy(this.#privateKey), {\n lowS: true\n });\n return Signature.from({\n r: toBeHex(sig.r, 32),\n s: toBeHex(sig.s, 32),\n v: (sig.recovery ? 0x1c : 0x1b)\n });\n }\n /**\n * Returns the [[link-wiki-ecdh]] shared secret between this\n * private key and the %%other%% key.\n *\n * The %%other%% key may be any type of key, a raw public key,\n * a compressed/uncompressed pubic key or aprivate key.\n *\n * Best practice is usually to use a cryptographic hash on the\n * returned value before using it as a symetric secret.\n *\n * @example:\n * sign1 = new SigningKey(id(\"some-secret-1\"))\n * sign2 = new SigningKey(id(\"some-secret-2\"))\n *\n * // Notice that privA.computeSharedSecret(pubB)...\n * sign1.computeSharedSecret(sign2.publicKey)\n * //_result:\n *\n * // ...is equal to privB.computeSharedSecret(pubA).\n * sign2.computeSharedSecret(sign1.publicKey)\n * //_result:\n */\n computeSharedSecret(other) {\n const pubKey = SigningKey.computePublicKey(other);\n return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey), getBytes(pubKey), false));\n }\n /**\n * Compute the public key for %%key%%, optionally %%compressed%%.\n *\n * The %%key%% may be any type of key, a raw public key, a\n * compressed/uncompressed public key or private key.\n *\n * @example:\n * sign = new SigningKey(id(\"some-secret\"));\n *\n * // Compute the uncompressed public key for a private key\n * SigningKey.computePublicKey(sign.privateKey)\n * //_result:\n *\n * // Compute the compressed public key for a private key\n * SigningKey.computePublicKey(sign.privateKey, true)\n * //_result:\n *\n * // Compute the uncompressed public key\n * SigningKey.computePublicKey(sign.publicKey, false);\n * //_result:\n *\n * // Compute the Compressed a public key\n * SigningKey.computePublicKey(sign.publicKey, true);\n * //_result:\n */\n static computePublicKey(key, compressed) {\n let bytes = getBytes(key, \"key\");\n // private key\n if (bytes.length === 32) {\n const pubKey = secp256k1.getPublicKey(bytes, !!compressed);\n return hexlify(pubKey);\n }\n // raw public key; use uncompressed key with 0x04 prefix\n if (bytes.length === 64) {\n const pub = new Uint8Array(65);\n pub[0] = 0x04;\n pub.set(bytes, 1);\n bytes = pub;\n }\n const point = secp256k1.ProjectivePoint.fromHex(bytes);\n return hexlify(point.toRawBytes(compressed));\n }\n /**\n * Returns the public key for the private key which produced the\n * %%signature%% for the given %%digest%%.\n *\n * @example:\n * key = new SigningKey(id(\"some-secret\"))\n * digest = id(\"hello world\")\n * sig = key.sign(digest)\n *\n * // Notice the signer public key...\n * key.publicKey\n * //_result:\n *\n * // ...is equal to the recovered public key\n * SigningKey.recoverPublicKey(digest, sig)\n * //_result:\n *\n */\n static recoverPublicKey(digest, signature) {\n assertArgument(dataLength(digest) === 32, \"invalid digest length\", \"digest\", digest);\n const sig = Signature.from(signature);\n let secpSig = secp256k1.Signature.fromCompact(getBytesCopy(concat([sig.r, sig.s])));\n secpSig = secpSig.addRecoveryBit(sig.yParity);\n const pubKey = secpSig.recoverPublicKey(getBytesCopy(digest));\n assertArgument(pubKey != null, \"invalid signautre for digest\", \"signature\", signature);\n return \"0x\" + pubKey.toHex(false);\n }\n /**\n * Returns the point resulting from adding the ellipic curve points\n * %%p0%% and %%p1%%.\n *\n * This is not a common function most developers should require, but\n * can be useful for certain privacy-specific techniques.\n *\n * For example, it is used by [[HDNodeWallet]] to compute child\n * addresses from parent public keys and chain codes.\n */\n static addPoints(p0, p1, compressed) {\n const pub0 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p0).substring(2));\n const pub1 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p1).substring(2));\n return \"0x\" + pub0.add(pub1).toHex(!!compressed);\n }\n}\n//# sourceMappingURL=signing-key.js.map","import { keccak256 } from \"../crypto/index.js\";\nimport { getBytes, assertArgument } from \"../utils/index.js\";\nconst BN_0 = BigInt(0);\nconst BN_36 = BigInt(36);\nfunction getChecksumAddress(address) {\n // if (!isHexString(address, 20)) {\n // logger.throwArgumentError(\"invalid address\", \"address\", address);\n // }\n address = address.toLowerCase();\n const chars = address.substring(2).split(\"\");\n const expanded = new Uint8Array(40);\n for (let i = 0; i < 40; i++) {\n expanded[i] = chars[i].charCodeAt(0);\n }\n const hashed = getBytes(keccak256(expanded));\n for (let i = 0; i < 40; i += 2) {\n if ((hashed[i >> 1] >> 4) >= 8) {\n chars[i] = chars[i].toUpperCase();\n }\n if ((hashed[i >> 1] & 0x0f) >= 8) {\n chars[i + 1] = chars[i + 1].toUpperCase();\n }\n }\n return \"0x\" + chars.join(\"\");\n}\n// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number\n// Create lookup table\nconst ibanLookup = {};\nfor (let i = 0; i < 10; i++) {\n ibanLookup[String(i)] = String(i);\n}\nfor (let i = 0; i < 26; i++) {\n ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);\n}\n// How many decimal digits can we process? (for 64-bit float, this is 15)\n// i.e. Math.floor(Math.log10(Number.MAX_SAFE_INTEGER));\nconst safeDigits = 15;\nfunction ibanChecksum(address) {\n address = address.toUpperCase();\n address = address.substring(4) + address.substring(0, 2) + \"00\";\n let expanded = address.split(\"\").map((c) => { return ibanLookup[c]; }).join(\"\");\n // Javascript can handle integers safely up to 15 (decimal) digits\n while (expanded.length >= safeDigits) {\n let block = expanded.substring(0, safeDigits);\n expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);\n }\n let checksum = String(98 - (parseInt(expanded, 10) % 97));\n while (checksum.length < 2) {\n checksum = \"0\" + checksum;\n }\n return checksum;\n}\n;\nconst Base36 = (function () {\n ;\n const result = {};\n for (let i = 0; i < 36; i++) {\n const key = \"0123456789abcdefghijklmnopqrstuvwxyz\"[i];\n result[key] = BigInt(i);\n }\n return result;\n})();\nfunction fromBase36(value) {\n value = value.toLowerCase();\n let result = BN_0;\n for (let i = 0; i < value.length; i++) {\n result = result * BN_36 + Base36[value[i]];\n }\n return result;\n}\n/**\n * Returns a normalized and checksumed address for %%address%%.\n * This accepts non-checksum addresses, checksum addresses and\n * [[getIcapAddress]] formats.\n *\n * The checksum in Ethereum uses the capitalization (upper-case\n * vs lower-case) of the characters within an address to encode\n * its checksum, which offers, on average, a checksum of 15-bits.\n *\n * If %%address%% contains both upper-case and lower-case, it is\n * assumed to already be a checksum address and its checksum is\n * validated, and if the address fails its expected checksum an\n * error is thrown.\n *\n * If you wish the checksum of %%address%% to be ignore, it should\n * be converted to lower-case (i.e. ``.toLowercase()``) before\n * being passed in. This should be a very rare situation though,\n * that you wish to bypass the safegaurds in place to protect\n * against an address that has been incorrectly copied from another\n * source.\n *\n * @example:\n * // Adds the checksum (via upper-casing specific letters)\n * getAddress(\"0x8ba1f109551bd432803012645ac136ddd64dba72\")\n * //_result:\n *\n * // Converts ICAP address and adds checksum\n * getAddress(\"XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36\");\n * //_result:\n *\n * // Throws an error if an address contains mixed case,\n * // but the checksum fails\n * getAddress(\"0x8Ba1f109551bD432803012645Ac136ddd64DBA72\")\n * //_error:\n */\nexport function getAddress(address) {\n assertArgument(typeof (address) === \"string\", \"invalid address\", \"address\", address);\n if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {\n // Missing the 0x prefix\n if (!address.startsWith(\"0x\")) {\n address = \"0x\" + address;\n }\n const result = getChecksumAddress(address);\n // It is a checksummed address with a bad checksum\n assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, \"bad address checksum\", \"address\", address);\n return result;\n }\n // Maybe ICAP? (we only support direct mode)\n if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {\n // It is an ICAP address with a bad checksum\n assertArgument(address.substring(2, 4) === ibanChecksum(address), \"bad icap checksum\", \"address\", address);\n let result = fromBase36(address.substring(4)).toString(16);\n while (result.length < 40) {\n result = \"0\" + result;\n }\n return getChecksumAddress(\"0x\" + result);\n }\n assertArgument(false, \"invalid address\", \"address\", address);\n}\n/**\n * The [ICAP Address format](link-icap) format is an early checksum\n * format which attempts to be compatible with the banking\n * industry [IBAN format](link-wiki-iban) for bank accounts.\n *\n * It is no longer common or a recommended format.\n *\n * @example:\n * getIcapAddress(\"0x8ba1f109551bd432803012645ac136ddd64dba72\");\n * //_result:\n *\n * getIcapAddress(\"XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36\");\n * //_result:\n *\n * // Throws an error if the ICAP checksum is wrong\n * getIcapAddress(\"XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK37\");\n * //_error:\n */\nexport function getIcapAddress(address) {\n //let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase();\n let base36 = BigInt(getAddress(address)).toString(36).toUpperCase();\n while (base36.length < 30) {\n base36 = \"0\" + base36;\n }\n return \"XE\" + ibanChecksum(\"XE00\" + base36) + base36;\n}\n//# sourceMappingURL=address.js.map","import { assert, assertArgument } from \"../utils/index.js\";\nimport { getAddress } from \"./address.js\";\n/**\n * Returns true if %%value%% is an object which implements the\n * [[Addressable]] interface.\n *\n * @example:\n * // Wallets and AbstractSigner sub-classes\n * isAddressable(Wallet.createRandom())\n * //_result:\n *\n * // Contracts\n * contract = new Contract(\"dai.tokens.ethers.eth\", [ ], provider)\n * isAddressable(contract)\n * //_result:\n */\nexport function isAddressable(value) {\n return (value && typeof (value.getAddress) === \"function\");\n}\n/**\n * Returns true if %%value%% is a valid address.\n *\n * @example:\n * // Valid address\n * isAddress(\"0x8ba1f109551bD432803012645Ac136ddd64DBA72\")\n * //_result:\n *\n * // Valid ICAP address\n * isAddress(\"XE65GB6LDNXYOFTX0NSV3FUWKOWIXAMJK36\")\n * //_result:\n *\n * // Invalid checksum\n * isAddress(\"0x8Ba1f109551bD432803012645Ac136ddd64DBa72\")\n * //_result:\n *\n * // Invalid ICAP checksum\n * isAddress(\"0x8Ba1f109551bD432803012645Ac136ddd64DBA72\")\n * //_result:\n *\n * // Not an address (an ENS name requires a provided and an\n * // asynchronous API to access)\n * isAddress(\"ricmoo.eth\")\n * //_result:\n */\nexport function isAddress(value) {\n try {\n getAddress(value);\n return true;\n }\n catch (error) { }\n return false;\n}\nasync function checkAddress(target, promise) {\n const result = await promise;\n if (result == null || result === \"0x0000000000000000000000000000000000000000\") {\n assert(typeof (target) !== \"string\", \"unconfigured name\", \"UNCONFIGURED_NAME\", { value: target });\n assertArgument(false, \"invalid AddressLike value; did not resolve to a value address\", \"target\", target);\n }\n return getAddress(result);\n}\n/**\n * Resolves to an address for the %%target%%, which may be any\n * supported address type, an [[Addressable]] or a Promise which\n * resolves to an address.\n *\n * If an ENS name is provided, but that name has not been correctly\n * configured a [[UnconfiguredNameError]] is thrown.\n *\n * @example:\n * addr = \"0x6B175474E89094C44Da98b954EedeAC495271d0F\"\n *\n * // Addresses are return synchronously\n * resolveAddress(addr, provider)\n * //_result:\n *\n * // Address promises are resolved asynchronously\n * resolveAddress(Promise.resolve(addr))\n * //_result:\n *\n * // ENS names are resolved asynchronously\n * resolveAddress(\"dai.tokens.ethers.eth\", provider)\n * //_result:\n *\n * // Addressable objects are resolved asynchronously\n * contract = new Contract(addr, [ ])\n * resolveAddress(contract, provider)\n * //_result:\n *\n * // Unconfigured ENS names reject\n * resolveAddress(\"nothing-here.ricmoo.eth\", provider)\n * //_error:\n *\n * // ENS names require a NameResolver object passed in\n * // (notice the provider was omitted)\n * resolveAddress(\"nothing-here.ricmoo.eth\")\n * //_error:\n */\nexport function resolveAddress(target, resolver) {\n if (typeof (target) === \"string\") {\n if (target.match(/^0x[0-9a-f]{40}$/i)) {\n return getAddress(target);\n }\n assert(resolver != null, \"ENS resolution requires a provider\", \"UNSUPPORTED_OPERATION\", { operation: \"resolveName\" });\n return checkAddress(target, resolver.resolveName(target));\n }\n else if (isAddressable(target)) {\n return checkAddress(target, target.getAddress());\n }\n else if (target && typeof (target.then) === \"function\") {\n return checkAddress(target, target);\n }\n assertArgument(false, \"unsupported addressable value\", \"target\", target);\n}\n//# sourceMappingURL=checks.js.map","/**\n * A Typed object allows a value to have its type explicitly\n * specified.\n *\n * For example, in Solidity, the value ``45`` could represent a\n * ``uint8`` or a ``uint256``. The value ``0x1234`` could represent\n * a ``bytes2`` or ``bytes``.\n *\n * Since JavaScript has no meaningful way to explicitly inform any\n * APIs which what the type is, this allows transparent interoperation\n * with Soldity.\n *\n * @_subsection: api/abi:Typed Values\n */\nimport { assertPrivate, defineProperties } from \"../utils/index.js\";\nconst _gaurd = {};\nfunction n(value, width) {\n let signed = false;\n if (width < 0) {\n signed = true;\n width *= -1;\n }\n // @TODO: Check range is valid for value\n return new Typed(_gaurd, `${signed ? \"\" : \"u\"}int${width}`, value, { signed, width });\n}\nfunction b(value, size) {\n // @TODO: Check range is valid for value\n return new Typed(_gaurd, `bytes${(size) ? size : \"\"}`, value, { size });\n}\nconst _typedSymbol = Symbol.for(\"_ethers_typed\");\n/**\n * The **Typed** class to wrap values providing explicit type information.\n */\nexport class Typed {\n /**\n * The type, as a Solidity-compatible type.\n */\n type;\n /**\n * The actual value.\n */\n value;\n #options;\n /**\n * @_ignore:\n */\n _typedSymbol;\n /**\n * @_ignore:\n */\n constructor(gaurd, type, value, options) {\n if (options == null) {\n options = null;\n }\n assertPrivate(_gaurd, gaurd, \"Typed\");\n defineProperties(this, { _typedSymbol, type, value });\n this.#options = options;\n // Check the value is valid\n this.format();\n }\n /**\n * Format the type as a Human-Readable type.\n */\n format() {\n if (this.type === \"array\") {\n throw new Error(\"\");\n }\n else if (this.type === \"dynamicArray\") {\n throw new Error(\"\");\n }\n else if (this.type === \"tuple\") {\n return `tuple(${this.value.map((v) => v.format()).join(\",\")})`;\n }\n return this.type;\n }\n /**\n * The default value returned by this type.\n */\n defaultValue() {\n return 0;\n }\n /**\n * The minimum value for numeric types.\n */\n minValue() {\n return 0;\n }\n /**\n * The maximum value for numeric types.\n */\n maxValue() {\n return 0;\n }\n /**\n * Returns ``true`` and provides a type guard is this is a [[TypedBigInt]].\n */\n isBigInt() {\n return !!(this.type.match(/^u?int[0-9]+$/));\n }\n /**\n * Returns ``true`` and provides a type guard is this is a [[TypedData]].\n */\n isData() {\n return this.type.startsWith(\"bytes\");\n }\n /**\n * Returns ``true`` and provides a type guard is this is a [[TypedString]].\n */\n isString() {\n return (this.type === \"string\");\n }\n /**\n * Returns the tuple name, if this is a tuple. Throws otherwise.\n */\n get tupleName() {\n if (this.type !== \"tuple\") {\n throw TypeError(\"not a tuple\");\n }\n return this.#options;\n }\n // Returns the length of this type as an array\n // - `null` indicates the length is unforced, it could be dynamic\n // - `-1` indicates the length is dynamic\n // - any other value indicates it is a static array and is its length\n /**\n * Returns the length of the array type or ``-1`` if it is dynamic.\n *\n * Throws if the type is not an array.\n */\n get arrayLength() {\n if (this.type !== \"array\") {\n throw TypeError(\"not an array\");\n }\n if (this.#options === true) {\n return -1;\n }\n if (this.#options === false) {\n return (this.value).length;\n }\n return null;\n }\n /**\n * Returns a new **Typed** of %%type%% with the %%value%%.\n */\n static from(type, value) {\n return new Typed(_gaurd, type, value);\n }\n /**\n * Return a new ``uint8`` type for %%v%%.\n */\n static uint8(v) { return n(v, 8); }\n /**\n * Return a new ``uint16`` type for %%v%%.\n */\n static uint16(v) { return n(v, 16); }\n /**\n * Return a new ``uint24`` type for %%v%%.\n */\n static uint24(v) { return n(v, 24); }\n /**\n * Return a new ``uint32`` type for %%v%%.\n */\n static uint32(v) { return n(v, 32); }\n /**\n * Return a new ``uint40`` type for %%v%%.\n */\n static uint40(v) { return n(v, 40); }\n /**\n * Return a new ``uint48`` type for %%v%%.\n */\n static uint48(v) { return n(v, 48); }\n /**\n * Return a new ``uint56`` type for %%v%%.\n */\n static uint56(v) { return n(v, 56); }\n /**\n * Return a new ``uint64`` type for %%v%%.\n */\n static uint64(v) { return n(v, 64); }\n /**\n * Return a new ``uint72`` type for %%v%%.\n */\n static uint72(v) { return n(v, 72); }\n /**\n * Return a new ``uint80`` type for %%v%%.\n */\n static uint80(v) { return n(v, 80); }\n /**\n * Return a new ``uint88`` type for %%v%%.\n */\n static uint88(v) { return n(v, 88); }\n /**\n * Return a new ``uint96`` type for %%v%%.\n */\n static uint96(v) { return n(v, 96); }\n /**\n * Return a new ``uint104`` type for %%v%%.\n */\n static uint104(v) { return n(v, 104); }\n /**\n * Return a new ``uint112`` type for %%v%%.\n */\n static uint112(v) { return n(v, 112); }\n /**\n * Return a new ``uint120`` type for %%v%%.\n */\n static uint120(v) { return n(v, 120); }\n /**\n * Return a new ``uint128`` type for %%v%%.\n */\n static uint128(v) { return n(v, 128); }\n /**\n * Return a new ``uint136`` type for %%v%%.\n */\n static uint136(v) { return n(v, 136); }\n /**\n * Return a new ``uint144`` type for %%v%%.\n */\n static uint144(v) { return n(v, 144); }\n /**\n * Return a new ``uint152`` type for %%v%%.\n */\n static uint152(v) { return n(v, 152); }\n /**\n * Return a new ``uint160`` type for %%v%%.\n */\n static uint160(v) { return n(v, 160); }\n /**\n * Return a new ``uint168`` type for %%v%%.\n */\n static uint168(v) { return n(v, 168); }\n /**\n * Return a new ``uint176`` type for %%v%%.\n */\n static uint176(v) { return n(v, 176); }\n /**\n * Return a new ``uint184`` type for %%v%%.\n */\n static uint184(v) { return n(v, 184); }\n /**\n * Return a new ``uint192`` type for %%v%%.\n */\n static uint192(v) { return n(v, 192); }\n /**\n * Return a new ``uint200`` type for %%v%%.\n */\n static uint200(v) { return n(v, 200); }\n /**\n * Return a new ``uint208`` type for %%v%%.\n */\n static uint208(v) { return n(v, 208); }\n /**\n * Return a new ``uint216`` type for %%v%%.\n */\n static uint216(v) { return n(v, 216); }\n /**\n * Return a new ``uint224`` type for %%v%%.\n */\n static uint224(v) { return n(v, 224); }\n /**\n * Return a new ``uint232`` type for %%v%%.\n */\n static uint232(v) { return n(v, 232); }\n /**\n * Return a new ``uint240`` type for %%v%%.\n */\n static uint240(v) { return n(v, 240); }\n /**\n * Return a new ``uint248`` type for %%v%%.\n */\n static uint248(v) { return n(v, 248); }\n /**\n * Return a new ``uint256`` type for %%v%%.\n */\n static uint256(v) { return n(v, 256); }\n /**\n * Return a new ``uint256`` type for %%v%%.\n */\n static uint(v) { return n(v, 256); }\n /**\n * Return a new ``int8`` type for %%v%%.\n */\n static int8(v) { return n(v, -8); }\n /**\n * Return a new ``int16`` type for %%v%%.\n */\n static int16(v) { return n(v, -16); }\n /**\n * Return a new ``int24`` type for %%v%%.\n */\n static int24(v) { return n(v, -24); }\n /**\n * Return a new ``int32`` type for %%v%%.\n */\n static int32(v) { return n(v, -32); }\n /**\n * Return a new ``int40`` type for %%v%%.\n */\n static int40(v) { return n(v, -40); }\n /**\n * Return a new ``int48`` type for %%v%%.\n */\n static int48(v) { return n(v, -48); }\n /**\n * Return a new ``int56`` type for %%v%%.\n */\n static int56(v) { return n(v, -56); }\n /**\n * Return a new ``int64`` type for %%v%%.\n */\n static int64(v) { return n(v, -64); }\n /**\n * Return a new ``int72`` type for %%v%%.\n */\n static int72(v) { return n(v, -72); }\n /**\n * Return a new ``int80`` type for %%v%%.\n */\n static int80(v) { return n(v, -80); }\n /**\n * Return a new ``int88`` type for %%v%%.\n */\n static int88(v) { return n(v, -88); }\n /**\n * Return a new ``int96`` type for %%v%%.\n */\n static int96(v) { return n(v, -96); }\n /**\n * Return a new ``int104`` type for %%v%%.\n */\n static int104(v) { return n(v, -104); }\n /**\n * Return a new ``int112`` type for %%v%%.\n */\n static int112(v) { return n(v, -112); }\n /**\n * Return a new ``int120`` type for %%v%%.\n */\n static int120(v) { return n(v, -120); }\n /**\n * Return a new ``int128`` type for %%v%%.\n */\n static int128(v) { return n(v, -128); }\n /**\n * Return a new ``int136`` type for %%v%%.\n */\n static int136(v) { return n(v, -136); }\n /**\n * Return a new ``int144`` type for %%v%%.\n */\n static int144(v) { return n(v, -144); }\n /**\n * Return a new ``int52`` type for %%v%%.\n */\n static int152(v) { return n(v, -152); }\n /**\n * Return a new ``int160`` type for %%v%%.\n */\n static int160(v) { return n(v, -160); }\n /**\n * Return a new ``int168`` type for %%v%%.\n */\n static int168(v) { return n(v, -168); }\n /**\n * Return a new ``int176`` type for %%v%%.\n */\n static int176(v) { return n(v, -176); }\n /**\n * Return a new ``int184`` type for %%v%%.\n */\n static int184(v) { return n(v, -184); }\n /**\n * Return a new ``int92`` type for %%v%%.\n */\n static int192(v) { return n(v, -192); }\n /**\n * Return a new ``int200`` type for %%v%%.\n */\n static int200(v) { return n(v, -200); }\n /**\n * Return a new ``int208`` type for %%v%%.\n */\n static int208(v) { return n(v, -208); }\n /**\n * Return a new ``int216`` type for %%v%%.\n */\n static int216(v) { return n(v, -216); }\n /**\n * Return a new ``int224`` type for %%v%%.\n */\n static int224(v) { return n(v, -224); }\n /**\n * Return a new ``int232`` type for %%v%%.\n */\n static int232(v) { return n(v, -232); }\n /**\n * Return a new ``int240`` type for %%v%%.\n */\n static int240(v) { return n(v, -240); }\n /**\n * Return a new ``int248`` type for %%v%%.\n */\n static int248(v) { return n(v, -248); }\n /**\n * Return a new ``int256`` type for %%v%%.\n */\n static int256(v) { return n(v, -256); }\n /**\n * Return a new ``int256`` type for %%v%%.\n */\n static int(v) { return n(v, -256); }\n /**\n * Return a new ``bytes1`` type for %%v%%.\n */\n static bytes1(v) { return b(v, 1); }\n /**\n * Return a new ``bytes2`` type for %%v%%.\n */\n static bytes2(v) { return b(v, 2); }\n /**\n * Return a new ``bytes3`` type for %%v%%.\n */\n static bytes3(v) { return b(v, 3); }\n /**\n * Return a new ``bytes4`` type for %%v%%.\n */\n static bytes4(v) { return b(v, 4); }\n /**\n * Return a new ``bytes5`` type for %%v%%.\n */\n static bytes5(v) { return b(v, 5); }\n /**\n * Return a new ``bytes6`` type for %%v%%.\n */\n static bytes6(v) { return b(v, 6); }\n /**\n * Return a new ``bytes7`` type for %%v%%.\n */\n static bytes7(v) { return b(v, 7); }\n /**\n * Return a new ``bytes8`` type for %%v%%.\n */\n static bytes8(v) { return b(v, 8); }\n /**\n * Return a new ``bytes9`` type for %%v%%.\n */\n static bytes9(v) { return b(v, 9); }\n /**\n * Return a new ``bytes10`` type for %%v%%.\n */\n static bytes10(v) { return b(v, 10); }\n /**\n * Return a new ``bytes11`` type for %%v%%.\n */\n static bytes11(v) { return b(v, 11); }\n /**\n * Return a new ``bytes12`` type for %%v%%.\n */\n static bytes12(v) { return b(v, 12); }\n /**\n * Return a new ``bytes13`` type for %%v%%.\n */\n static bytes13(v) { return b(v, 13); }\n /**\n * Return a new ``bytes14`` type for %%v%%.\n */\n static bytes14(v) { return b(v, 14); }\n /**\n * Return a new ``bytes15`` type for %%v%%.\n */\n static bytes15(v) { return b(v, 15); }\n /**\n * Return a new ``bytes16`` type for %%v%%.\n */\n static bytes16(v) { return b(v, 16); }\n /**\n * Return a new ``bytes17`` type for %%v%%.\n */\n static bytes17(v) { return b(v, 17); }\n /**\n * Return a new ``bytes18`` type for %%v%%.\n */\n static bytes18(v) { return b(v, 18); }\n /**\n * Return a new ``bytes19`` type for %%v%%.\n */\n static bytes19(v) { return b(v, 19); }\n /**\n * Return a new ``bytes20`` type for %%v%%.\n */\n static bytes20(v) { return b(v, 20); }\n /**\n * Return a new ``bytes21`` type for %%v%%.\n */\n static bytes21(v) { return b(v, 21); }\n /**\n * Return a new ``bytes22`` type for %%v%%.\n */\n static bytes22(v) { return b(v, 22); }\n /**\n * Return a new ``bytes23`` type for %%v%%.\n */\n static bytes23(v) { return b(v, 23); }\n /**\n * Return a new ``bytes24`` type for %%v%%.\n */\n static bytes24(v) { return b(v, 24); }\n /**\n * Return a new ``bytes25`` type for %%v%%.\n */\n static bytes25(v) { return b(v, 25); }\n /**\n * Return a new ``bytes26`` type for %%v%%.\n */\n static bytes26(v) { return b(v, 26); }\n /**\n * Return a new ``bytes27`` type for %%v%%.\n */\n static bytes27(v) { return b(v, 27); }\n /**\n * Return a new ``bytes28`` type for %%v%%.\n */\n static bytes28(v) { return b(v, 28); }\n /**\n * Return a new ``bytes29`` type for %%v%%.\n */\n static bytes29(v) { return b(v, 29); }\n /**\n * Return a new ``bytes30`` type for %%v%%.\n */\n static bytes30(v) { return b(v, 30); }\n /**\n * Return a new ``bytes31`` type for %%v%%.\n */\n static bytes31(v) { return b(v, 31); }\n /**\n * Return a new ``bytes32`` type for %%v%%.\n */\n static bytes32(v) { return b(v, 32); }\n /**\n * Return a new ``address`` type for %%v%%.\n */\n static address(v) { return new Typed(_gaurd, \"address\", v); }\n /**\n * Return a new ``bool`` type for %%v%%.\n */\n static bool(v) { return new Typed(_gaurd, \"bool\", !!v); }\n /**\n * Return a new ``bytes`` type for %%v%%.\n */\n static bytes(v) { return new Typed(_gaurd, \"bytes\", v); }\n /**\n * Return a new ``string`` type for %%v%%.\n */\n static string(v) { return new Typed(_gaurd, \"string\", v); }\n /**\n * Return a new ``array`` type for %%v%%, allowing %%dynamic%% length.\n */\n static array(v, dynamic) {\n throw new Error(\"not implemented yet\");\n return new Typed(_gaurd, \"array\", v, dynamic);\n }\n /**\n * Return a new ``tuple`` type for %%v%%, with the optional %%name%%.\n */\n static tuple(v, name) {\n throw new Error(\"not implemented yet\");\n return new Typed(_gaurd, \"tuple\", v, name);\n }\n /**\n * Return a new ``uint8`` type for %%v%%.\n */\n static overrides(v) {\n return new Typed(_gaurd, \"overrides\", Object.assign({}, v));\n }\n /**\n * Returns true only if %%value%% is a [[Typed]] instance.\n */\n static isTyped(value) {\n return (value\n && typeof (value) === \"object\"\n && \"_typedSymbol\" in value\n && value._typedSymbol === _typedSymbol);\n }\n /**\n * If the value is a [[Typed]] instance, validates the underlying value\n * and returns it, otherwise returns value directly.\n *\n * This is useful for functions that with to accept either a [[Typed]]\n * object or values.\n */\n static dereference(value, type) {\n if (Typed.isTyped(value)) {\n if (value.type !== type) {\n throw new Error(`invalid type: expecetd ${type}, got ${value.type}`);\n }\n return value.value;\n }\n return value;\n }\n}\n//# sourceMappingURL=typed.js.map","import { getAddress } from \"../../address/index.js\";\nimport { toBeHex } from \"../../utils/maths.js\";\nimport { Typed } from \"../typed.js\";\nimport { Coder } from \"./abstract-coder.js\";\n/**\n * @_ignore\n */\nexport class AddressCoder extends Coder {\n constructor(localName) {\n super(\"address\", \"address\", localName, false);\n }\n defaultValue() {\n return \"0x0000000000000000000000000000000000000000\";\n }\n encode(writer, _value) {\n let value = Typed.dereference(_value, \"string\");\n try {\n value = getAddress(value);\n }\n catch (error) {\n return this._throwError(error.message, _value);\n }\n return writer.writeValue(value);\n }\n decode(reader) {\n return getAddress(toBeHex(reader.readValue(), 20));\n }\n}\n//# sourceMappingURL=address.js.map","import { Coder } from \"./abstract-coder.js\";\n/**\n * Clones the functionality of an existing Coder, but without a localName\n *\n * @_ignore\n */\nexport class AnonymousCoder extends Coder {\n coder;\n constructor(coder) {\n super(coder.name, coder.type, \"_\", coder.dynamic);\n this.coder = coder;\n }\n defaultValue() {\n return this.coder.defaultValue();\n }\n encode(writer, value) {\n return this.coder.encode(writer, value);\n }\n decode(reader) {\n return this.coder.decode(reader);\n }\n}\n//# sourceMappingURL=anonymous.js.map","import { defineProperties, isError, assert, assertArgument, assertArgumentCount } from \"../../utils/index.js\";\nimport { Typed } from \"../typed.js\";\nimport { Coder, Result, WordSize, Writer } from \"./abstract-coder.js\";\nimport { AnonymousCoder } from \"./anonymous.js\";\n/**\n * @_ignore\n */\nexport function pack(writer, coders, values) {\n let arrayValues = [];\n if (Array.isArray(values)) {\n arrayValues = values;\n }\n else if (values && typeof (values) === \"object\") {\n let unique = {};\n arrayValues = coders.map((coder) => {\n const name = coder.localName;\n assert(name, \"cannot encode object for signature with missing names\", \"INVALID_ARGUMENT\", { argument: \"values\", info: { coder }, value: values });\n assert(!unique[name], \"cannot encode object for signature with duplicate names\", \"INVALID_ARGUMENT\", { argument: \"values\", info: { coder }, value: values });\n unique[name] = true;\n return values[name];\n });\n }\n else {\n assertArgument(false, \"invalid tuple value\", \"tuple\", values);\n }\n assertArgument(coders.length === arrayValues.length, \"types/value length mismatch\", \"tuple\", values);\n let staticWriter = new Writer();\n let dynamicWriter = new Writer();\n let updateFuncs = [];\n coders.forEach((coder, index) => {\n let value = arrayValues[index];\n if (coder.dynamic) {\n // Get current dynamic offset (for the future pointer)\n let dynamicOffset = dynamicWriter.length;\n // Encode the dynamic value into the dynamicWriter\n coder.encode(dynamicWriter, value);\n // Prepare to populate the correct offset once we are done\n let updateFunc = staticWriter.writeUpdatableValue();\n updateFuncs.push((baseOffset) => {\n updateFunc(baseOffset + dynamicOffset);\n });\n }\n else {\n coder.encode(staticWriter, value);\n }\n });\n // Backfill all the dynamic offsets, now that we know the static length\n updateFuncs.forEach((func) => { func(staticWriter.length); });\n let length = writer.appendWriter(staticWriter);\n length += writer.appendWriter(dynamicWriter);\n return length;\n}\n/**\n * @_ignore\n */\nexport function unpack(reader, coders) {\n let values = [];\n let keys = [];\n // A reader anchored to this base\n let baseReader = reader.subReader(0);\n coders.forEach((coder) => {\n let value = null;\n if (coder.dynamic) {\n let offset = reader.readIndex();\n let offsetReader = baseReader.subReader(offset);\n try {\n value = coder.decode(offsetReader);\n }\n catch (error) {\n // Cannot recover from this\n if (isError(error, \"BUFFER_OVERRUN\")) {\n throw error;\n }\n value = error;\n value.baseType = coder.name;\n value.name = coder.localName;\n value.type = coder.type;\n }\n }\n else {\n try {\n value = coder.decode(reader);\n }\n catch (error) {\n // Cannot recover from this\n if (isError(error, \"BUFFER_OVERRUN\")) {\n throw error;\n }\n value = error;\n value.baseType = coder.name;\n value.name = coder.localName;\n value.type = coder.type;\n }\n }\n if (value == undefined) {\n throw new Error(\"investigate\");\n }\n values.push(value);\n keys.push(coder.localName || null);\n });\n return Result.fromItems(values, keys);\n}\n/**\n * @_ignore\n */\nexport class ArrayCoder extends Coder {\n coder;\n length;\n constructor(coder, length, localName) {\n const type = (coder.type + \"[\" + (length >= 0 ? length : \"\") + \"]\");\n const dynamic = (length === -1 || coder.dynamic);\n super(\"array\", type, localName, dynamic);\n defineProperties(this, { coder, length });\n }\n defaultValue() {\n // Verifies the child coder is valid (even if the array is dynamic or 0-length)\n const defaultChild = this.coder.defaultValue();\n const result = [];\n for (let i = 0; i < this.length; i++) {\n result.push(defaultChild);\n }\n return result;\n }\n encode(writer, _value) {\n const value = Typed.dereference(_value, \"array\");\n if (!Array.isArray(value)) {\n this._throwError(\"expected array value\", value);\n }\n let count = this.length;\n if (count === -1) {\n count = value.length;\n writer.writeValue(value.length);\n }\n assertArgumentCount(value.length, count, \"coder array\" + (this.localName ? (\" \" + this.localName) : \"\"));\n let coders = [];\n for (let i = 0; i < value.length; i++) {\n coders.push(this.coder);\n }\n return pack(writer, coders, value);\n }\n decode(reader) {\n let count = this.length;\n if (count === -1) {\n count = reader.readIndex();\n // Check that there is *roughly* enough data to ensure\n // stray random data is not being read as a length. Each\n // slot requires at least 32 bytes for their value (or 32\n // bytes as a link to the data). This could use a much\n // tighter bound, but we are erroring on the side of safety.\n assert(count * WordSize <= reader.dataLength, \"insufficient data length\", \"BUFFER_OVERRUN\", { buffer: reader.bytes, offset: count * WordSize, length: reader.dataLength });\n }\n let coders = [];\n for (let i = 0; i < count; i++) {\n coders.push(new AnonymousCoder(this.coder));\n }\n return unpack(reader, coders);\n }\n}\n//# sourceMappingURL=array.js.map","import { Typed } from \"../typed.js\";\nimport { Coder } from \"./abstract-coder.js\";\n/**\n * @_ignore\n */\nexport class BooleanCoder extends Coder {\n constructor(localName) {\n super(\"bool\", \"bool\", localName, false);\n }\n defaultValue() {\n return false;\n }\n encode(writer, _value) {\n const value = Typed.dereference(_value, \"bool\");\n return writer.writeValue(value ? 1 : 0);\n }\n decode(reader) {\n return !!reader.readValue();\n }\n}\n//# sourceMappingURL=boolean.js.map","import { getBytesCopy, hexlify } from \"../../utils/index.js\";\nimport { Coder } from \"./abstract-coder.js\";\n/**\n * @_ignore\n */\nexport class DynamicBytesCoder extends Coder {\n constructor(type, localName) {\n super(type, type, localName, true);\n }\n defaultValue() {\n return \"0x\";\n }\n encode(writer, value) {\n value = getBytesCopy(value);\n let length = writer.writeValue(value.length);\n length += writer.writeBytes(value);\n return length;\n }\n decode(reader) {\n return reader.readBytes(reader.readIndex(), true);\n }\n}\n/**\n * @_ignore\n */\nexport class BytesCoder extends DynamicBytesCoder {\n constructor(localName) {\n super(\"bytes\", localName);\n }\n decode(reader) {\n return hexlify(super.decode(reader));\n }\n}\n//# sourceMappingURL=bytes.js.map","import { defineProperties, getBytesCopy, hexlify } from \"../../utils/index.js\";\nimport { Typed } from \"../typed.js\";\nimport { Coder } from \"./abstract-coder.js\";\n/**\n * @_ignore\n */\nexport class FixedBytesCoder extends Coder {\n size;\n constructor(size, localName) {\n let name = \"bytes\" + String(size);\n super(name, name, localName, false);\n defineProperties(this, { size }, { size: \"number\" });\n }\n defaultValue() {\n return (\"0x0000000000000000000000000000000000000000000000000000000000000000\").substring(0, 2 + this.size * 2);\n }\n encode(writer, _value) {\n let data = getBytesCopy(Typed.dereference(_value, this.type));\n if (data.length !== this.size) {\n this._throwError(\"incorrect data length\", _value);\n }\n return writer.writeBytes(data);\n }\n decode(reader) {\n return hexlify(reader.readBytes(this.size));\n }\n}\n//# sourceMappingURL=fixed-bytes.js.map","import { Coder } from \"./abstract-coder.js\";\nconst Empty = new Uint8Array([]);\n/**\n * @_ignore\n */\nexport class NullCoder extends Coder {\n constructor(localName) {\n super(\"null\", \"\", localName, false);\n }\n defaultValue() {\n return null;\n }\n encode(writer, value) {\n if (value != null) {\n this._throwError(\"not null\", value);\n }\n return writer.writeBytes(Empty);\n }\n decode(reader) {\n reader.readBytes(0);\n return null;\n }\n}\n//# sourceMappingURL=null.js.map","import { defineProperties, fromTwos, getBigInt, mask, toTwos } from \"../../utils/index.js\";\nimport { Typed } from \"../typed.js\";\nimport { Coder, WordSize } from \"./abstract-coder.js\";\nconst BN_0 = BigInt(0);\nconst BN_1 = BigInt(1);\nconst BN_MAX_UINT256 = BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n/**\n * @_ignore\n */\nexport class NumberCoder extends Coder {\n size;\n signed;\n constructor(size, signed, localName) {\n const name = ((signed ? \"int\" : \"uint\") + (size * 8));\n super(name, name, localName, false);\n defineProperties(this, { size, signed }, { size: \"number\", signed: \"boolean\" });\n }\n defaultValue() {\n return 0;\n }\n encode(writer, _value) {\n let value = getBigInt(Typed.dereference(_value, this.type));\n // Check bounds are safe for encoding\n let maxUintValue = mask(BN_MAX_UINT256, WordSize * 8);\n if (this.signed) {\n let bounds = mask(maxUintValue, (this.size * 8) - 1);\n if (value > bounds || value < -(bounds + BN_1)) {\n this._throwError(\"value out-of-bounds\", _value);\n }\n value = toTwos(value, 8 * WordSize);\n }\n else if (value < BN_0 || value > mask(maxUintValue, this.size * 8)) {\n this._throwError(\"value out-of-bounds\", _value);\n }\n return writer.writeValue(value);\n }\n decode(reader) {\n let value = mask(reader.readValue(), this.size * 8);\n if (this.signed) {\n value = fromTwos(value, this.size * 8);\n }\n return value;\n }\n}\n//# sourceMappingURL=number.js.map","import { toUtf8Bytes, toUtf8String } from \"../../utils/utf8.js\";\nimport { Typed } from \"../typed.js\";\nimport { DynamicBytesCoder } from \"./bytes.js\";\n/**\n * @_ignore\n */\nexport class StringCoder extends DynamicBytesCoder {\n constructor(localName) {\n super(\"string\", localName);\n }\n defaultValue() {\n return \"\";\n }\n encode(writer, _value) {\n return super.encode(writer, toUtf8Bytes(Typed.dereference(_value, \"string\")));\n }\n decode(reader) {\n return toUtf8String(super.decode(reader));\n }\n}\n//# sourceMappingURL=string.js.map","import { defineProperties } from \"../../utils/properties.js\";\nimport { Typed } from \"../typed.js\";\nimport { Coder } from \"./abstract-coder.js\";\nimport { pack, unpack } from \"./array.js\";\n/**\n * @_ignore\n */\nexport class TupleCoder extends Coder {\n coders;\n constructor(coders, localName) {\n let dynamic = false;\n const types = [];\n coders.forEach((coder) => {\n if (coder.dynamic) {\n dynamic = true;\n }\n types.push(coder.type);\n });\n const type = (\"tuple(\" + types.join(\",\") + \")\");\n super(\"tuple\", type, localName, dynamic);\n defineProperties(this, { coders: Object.freeze(coders.slice()) });\n }\n defaultValue() {\n const values = [];\n this.coders.forEach((coder) => {\n values.push(coder.defaultValue());\n });\n // We only output named properties for uniquely named coders\n const uniqueNames = this.coders.reduce((accum, coder) => {\n const name = coder.localName;\n if (name) {\n if (!accum[name]) {\n accum[name] = 0;\n }\n accum[name]++;\n }\n return accum;\n }, {});\n // Add named values\n this.coders.forEach((coder, index) => {\n let name = coder.localName;\n if (!name || uniqueNames[name] !== 1) {\n return;\n }\n if (name === \"length\") {\n name = \"_length\";\n }\n if (values[name] != null) {\n return;\n }\n values[name] = values[index];\n });\n return Object.freeze(values);\n }\n encode(writer, _value) {\n const value = Typed.dereference(_value, \"tuple\");\n return pack(writer, this.coders, value);\n }\n decode(reader) {\n return unpack(reader, this.coders);\n }\n}\n//# sourceMappingURL=tuple.js.map","import { keccak256 } from \"../crypto/index.js\";\nimport { toUtf8Bytes } from \"../utils/index.js\";\n/**\n * A simple hashing function which operates on UTF-8 strings to\n * compute an 32-byte identifier.\n *\n * This simply computes the [UTF-8 bytes](toUtf8Bytes) and computes\n * the [[keccak256]].\n *\n * @example:\n * id(\"hello world\")\n * //_result:\n */\nexport function id(value) {\n return keccak256(toUtf8Bytes(value));\n}\n//# sourceMappingURL=id.js.map","import { keccak256 } from \"../crypto/index.js\";\nimport { concat, hexlify, assertArgument, toUtf8Bytes } from \"../utils/index.js\";\nimport { ens_normalize } from \"@adraffy/ens-normalize\";\nconst Zeros = new Uint8Array(32);\nZeros.fill(0);\nfunction checkComponent(comp) {\n assertArgument(comp.length !== 0, \"invalid ENS name; empty component\", \"comp\", comp);\n return comp;\n}\nfunction ensNameSplit(name) {\n const bytes = toUtf8Bytes(ensNormalize(name));\n const comps = [];\n if (name.length === 0) {\n return comps;\n }\n let last = 0;\n for (let i = 0; i < bytes.length; i++) {\n const d = bytes[i];\n // A separator (i.e. \".\"); copy this component\n if (d === 0x2e) {\n comps.push(checkComponent(bytes.slice(last, i)));\n last = i + 1;\n }\n }\n // There was a stray separator at the end of the name\n assertArgument(last < bytes.length, \"invalid ENS name; empty component\", \"name\", name);\n comps.push(checkComponent(bytes.slice(last)));\n return comps;\n}\n/**\n * Returns the ENS %%name%% normalized.\n */\nexport function ensNormalize(name) {\n try {\n if (name.length === 0) {\n throw new Error(\"empty label\");\n }\n return ens_normalize(name);\n }\n catch (error) {\n assertArgument(false, `invalid ENS name (${error.message})`, \"name\", name);\n }\n}\n/**\n * Returns ``true`` if %%name%% is a valid ENS name.\n */\nexport function isValidName(name) {\n try {\n return (ensNameSplit(name).length !== 0);\n }\n catch (error) { }\n return false;\n}\n/**\n * Returns the [[link-namehash]] for %%name%%.\n */\nexport function namehash(name) {\n assertArgument(typeof (name) === \"string\", \"invalid ENS name; not a string\", \"name\", name);\n assertArgument(name.length, `invalid ENS name (empty label)`, \"name\", name);\n let result = Zeros;\n const comps = ensNameSplit(name);\n while (comps.length) {\n result = keccak256(concat([result, keccak256((comps.pop()))]));\n }\n return hexlify(result);\n}\n/**\n * Returns the DNS encoded %%name%%.\n *\n * This is used for various parts of ENS name resolution, such\n * as the wildcard resolution.\n */\nexport function dnsEncode(name, _maxLength) {\n const length = (_maxLength != null) ? _maxLength : 63;\n assertArgument(length <= 255, \"DNS encoded label cannot exceed 255\", \"length\", length);\n return hexlify(concat(ensNameSplit(name).map((comp) => {\n assertArgument(comp.length <= length, `label ${JSON.stringify(name)} exceeds ${length} bytes`, \"name\", name);\n const bytes = new Uint8Array(comp.length + 1);\n bytes.set(comp, 1);\n bytes[0] = bytes.length - 1;\n return bytes;\n }))) + \"00\";\n}\n//# sourceMappingURL=namehash.js.map","import { getAddress } from \"../address/index.js\";\nimport { assertArgument, isHexString } from \"../utils/index.js\";\nfunction accessSetify(addr, storageKeys) {\n return {\n address: getAddress(addr),\n storageKeys: storageKeys.map((storageKey, index) => {\n assertArgument(isHexString(storageKey, 32), \"invalid slot\", `storageKeys[${index}]`, storageKey);\n return storageKey.toLowerCase();\n })\n };\n}\n/**\n * Returns a [[AccessList]] from any ethers-supported access-list structure.\n */\nexport function accessListify(value) {\n if (Array.isArray(value)) {\n return value.map((set, index) => {\n if (Array.isArray(set)) {\n assertArgument(set.length === 2, \"invalid slot set\", `value[${index}]`, set);\n return accessSetify(set[0], set[1]);\n }\n assertArgument(set != null && typeof (set) === \"object\", \"invalid address-slot set\", \"value\", value);\n return accessSetify(set.address, set.storageKeys);\n });\n }\n assertArgument(value != null && typeof (value) === \"object\", \"invalid access list\", \"value\", value);\n const result = Object.keys(value).map((addr) => {\n const storageKeys = value[addr].reduce((accum, storageKey) => {\n accum[storageKey] = true;\n return accum;\n }, {});\n return accessSetify(addr, Object.keys(storageKeys).sort());\n });\n result.sort((a, b) => (a.address.localeCompare(b.address)));\n return result;\n}\n//# sourceMappingURL=accesslist.js.map","import { getAddress } from \"../address/index.js\";\nimport { keccak256, SigningKey } from \"../crypto/index.js\";\n/**\n * Returns the address for the %%key%%.\n *\n * The key may be any standard form of public key or a private key.\n */\nexport function computeAddress(key) {\n let pubkey;\n if (typeof (key) === \"string\") {\n pubkey = SigningKey.computePublicKey(key, false);\n }\n else {\n pubkey = key.publicKey;\n }\n return getAddress(keccak256(\"0x\" + pubkey.substring(4)).substring(26));\n}\n/**\n * Returns the recovered address for the private key that was\n * used to sign %%digest%% that resulted in %%signature%%.\n */\nexport function recoverAddress(digest, signature) {\n return computeAddress(SigningKey.recoverPublicKey(digest, signature));\n}\n//# sourceMappingURL=address.js.map","import { getAddress } from \"../address/index.js\";\nimport { ZeroAddress } from \"../constants/addresses.js\";\nimport { keccak256, sha256, Signature, SigningKey } from \"../crypto/index.js\";\nimport { concat, decodeRlp, encodeRlp, getBytes, getBigInt, getNumber, hexlify, assert, assertArgument, isBytesLike, isHexString, toBeArray, zeroPadValue } from \"../utils/index.js\";\nimport { accessListify } from \"./accesslist.js\";\nimport { recoverAddress } from \"./address.js\";\nconst BN_0 = BigInt(0);\nconst BN_2 = BigInt(2);\nconst BN_27 = BigInt(27);\nconst BN_28 = BigInt(28);\nconst BN_35 = BigInt(35);\nconst BN_MAX_UINT = BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\nconst BLOB_SIZE = 4096 * 32;\nfunction getVersionedHash(version, hash) {\n let versioned = version.toString(16);\n while (versioned.length < 2) {\n versioned = \"0\" + versioned;\n }\n versioned += sha256(hash).substring(4);\n return \"0x\" + versioned;\n}\nfunction handleAddress(value) {\n if (value === \"0x\") {\n return null;\n }\n return getAddress(value);\n}\nfunction handleAccessList(value, param) {\n try {\n return accessListify(value);\n }\n catch (error) {\n assertArgument(false, error.message, param, value);\n }\n}\nfunction handleNumber(_value, param) {\n if (_value === \"0x\") {\n return 0;\n }\n return getNumber(_value, param);\n}\nfunction handleUint(_value, param) {\n if (_value === \"0x\") {\n return BN_0;\n }\n const value = getBigInt(_value, param);\n assertArgument(value <= BN_MAX_UINT, \"value exceeds uint size\", param, value);\n return value;\n}\nfunction formatNumber(_value, name) {\n const value = getBigInt(_value, \"value\");\n const result = toBeArray(value);\n assertArgument(result.length <= 32, `value too large`, `tx.${name}`, value);\n return result;\n}\nfunction formatAccessList(value) {\n return accessListify(value).map((set) => [set.address, set.storageKeys]);\n}\nfunction formatHashes(value, param) {\n assertArgument(Array.isArray(value), `invalid ${param}`, \"value\", value);\n for (let i = 0; i < value.length; i++) {\n assertArgument(isHexString(value[i], 32), \"invalid ${ param } hash\", `value[${i}]`, value[i]);\n }\n return value;\n}\nfunction _parseLegacy(data) {\n const fields = decodeRlp(data);\n assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 6), \"invalid field count for legacy transaction\", \"data\", data);\n const tx = {\n type: 0,\n nonce: handleNumber(fields[0], \"nonce\"),\n gasPrice: handleUint(fields[1], \"gasPrice\"),\n gasLimit: handleUint(fields[2], \"gasLimit\"),\n to: handleAddress(fields[3]),\n value: handleUint(fields[4], \"value\"),\n data: hexlify(fields[5]),\n chainId: BN_0\n };\n // Legacy unsigned transaction\n if (fields.length === 6) {\n return tx;\n }\n const v = handleUint(fields[6], \"v\");\n const r = handleUint(fields[7], \"r\");\n const s = handleUint(fields[8], \"s\");\n if (r === BN_0 && s === BN_0) {\n // EIP-155 unsigned transaction\n tx.chainId = v;\n }\n else {\n // Compute the EIP-155 chain ID (or 0 for legacy)\n let chainId = (v - BN_35) / BN_2;\n if (chainId < BN_0) {\n chainId = BN_0;\n }\n tx.chainId = chainId;\n // Signed Legacy Transaction\n assertArgument(chainId !== BN_0 || (v === BN_27 || v === BN_28), \"non-canonical legacy v\", \"v\", fields[6]);\n tx.signature = Signature.from({\n r: zeroPadValue(fields[7], 32),\n s: zeroPadValue(fields[8], 32),\n v\n });\n //tx.hash = keccak256(data);\n }\n return tx;\n}\nfunction _serializeLegacy(tx, sig) {\n const fields = [\n formatNumber(tx.nonce, \"nonce\"),\n formatNumber(tx.gasPrice || 0, \"gasPrice\"),\n formatNumber(tx.gasLimit, \"gasLimit\"),\n (tx.to || \"0x\"),\n formatNumber(tx.value, \"value\"),\n tx.data,\n ];\n let chainId = BN_0;\n if (tx.chainId != BN_0) {\n // A chainId was provided; if non-zero we'll use EIP-155\n chainId = getBigInt(tx.chainId, \"tx.chainId\");\n // We have a chainId in the tx and an EIP-155 v in the signature,\n // make sure they agree with each other\n assertArgument(!sig || sig.networkV == null || sig.legacyChainId === chainId, \"tx.chainId/sig.v mismatch\", \"sig\", sig);\n }\n else if (tx.signature) {\n // No explicit chainId, but EIP-155 have a derived implicit chainId\n const legacy = tx.signature.legacyChainId;\n if (legacy != null) {\n chainId = legacy;\n }\n }\n // Requesting an unsigned transaction\n if (!sig) {\n // We have an EIP-155 transaction (chainId was specified and non-zero)\n if (chainId !== BN_0) {\n fields.push(toBeArray(chainId));\n fields.push(\"0x\");\n fields.push(\"0x\");\n }\n return encodeRlp(fields);\n }\n // @TODO: We should probably check that tx.signature, chainId, and sig\n // match but that logic could break existing code, so schedule\n // this for the next major bump.\n // Compute the EIP-155 v\n let v = BigInt(27 + sig.yParity);\n if (chainId !== BN_0) {\n v = Signature.getChainIdV(chainId, sig.v);\n }\n else if (BigInt(sig.v) !== v) {\n assertArgument(false, \"tx.chainId/sig.v mismatch\", \"sig\", sig);\n }\n // Add the signature\n fields.push(toBeArray(v));\n fields.push(toBeArray(sig.r));\n fields.push(toBeArray(sig.s));\n return encodeRlp(fields);\n}\nfunction _parseEipSignature(tx, fields) {\n let yParity;\n try {\n yParity = handleNumber(fields[0], \"yParity\");\n if (yParity !== 0 && yParity !== 1) {\n throw new Error(\"bad yParity\");\n }\n }\n catch (error) {\n assertArgument(false, \"invalid yParity\", \"yParity\", fields[0]);\n }\n const r = zeroPadValue(fields[1], 32);\n const s = zeroPadValue(fields[2], 32);\n const signature = Signature.from({ r, s, yParity });\n tx.signature = signature;\n}\nfunction _parseEip1559(data) {\n const fields = decodeRlp(getBytes(data).slice(1));\n assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 12), \"invalid field count for transaction type: 2\", \"data\", hexlify(data));\n const tx = {\n type: 2,\n chainId: handleUint(fields[0], \"chainId\"),\n nonce: handleNumber(fields[1], \"nonce\"),\n maxPriorityFeePerGas: handleUint(fields[2], \"maxPriorityFeePerGas\"),\n maxFeePerGas: handleUint(fields[3], \"maxFeePerGas\"),\n gasPrice: null,\n gasLimit: handleUint(fields[4], \"gasLimit\"),\n to: handleAddress(fields[5]),\n value: handleUint(fields[6], \"value\"),\n data: hexlify(fields[7]),\n accessList: handleAccessList(fields[8], \"accessList\"),\n };\n // Unsigned EIP-1559 Transaction\n if (fields.length === 9) {\n return tx;\n }\n //tx.hash = keccak256(data);\n _parseEipSignature(tx, fields.slice(9));\n return tx;\n}\nfunction _serializeEip1559(tx, sig) {\n const fields = [\n formatNumber(tx.chainId, \"chainId\"),\n formatNumber(tx.nonce, \"nonce\"),\n formatNumber(tx.maxPriorityFeePerGas || 0, \"maxPriorityFeePerGas\"),\n formatNumber(tx.maxFeePerGas || 0, \"maxFeePerGas\"),\n formatNumber(tx.gasLimit, \"gasLimit\"),\n (tx.to || \"0x\"),\n formatNumber(tx.value, \"value\"),\n tx.data,\n formatAccessList(tx.accessList || [])\n ];\n if (sig) {\n fields.push(formatNumber(sig.yParity, \"yParity\"));\n fields.push(toBeArray(sig.r));\n fields.push(toBeArray(sig.s));\n }\n return concat([\"0x02\", encodeRlp(fields)]);\n}\nfunction _parseEip2930(data) {\n const fields = decodeRlp(getBytes(data).slice(1));\n assertArgument(Array.isArray(fields) && (fields.length === 8 || fields.length === 11), \"invalid field count for transaction type: 1\", \"data\", hexlify(data));\n const tx = {\n type: 1,\n chainId: handleUint(fields[0], \"chainId\"),\n nonce: handleNumber(fields[1], \"nonce\"),\n gasPrice: handleUint(fields[2], \"gasPrice\"),\n gasLimit: handleUint(fields[3], \"gasLimit\"),\n to: handleAddress(fields[4]),\n value: handleUint(fields[5], \"value\"),\n data: hexlify(fields[6]),\n accessList: handleAccessList(fields[7], \"accessList\")\n };\n // Unsigned EIP-2930 Transaction\n if (fields.length === 8) {\n return tx;\n }\n //tx.hash = keccak256(data);\n _parseEipSignature(tx, fields.slice(8));\n return tx;\n}\nfunction _serializeEip2930(tx, sig) {\n const fields = [\n formatNumber(tx.chainId, \"chainId\"),\n formatNumber(tx.nonce, \"nonce\"),\n formatNumber(tx.gasPrice || 0, \"gasPrice\"),\n formatNumber(tx.gasLimit, \"gasLimit\"),\n (tx.to || \"0x\"),\n formatNumber(tx.value, \"value\"),\n tx.data,\n formatAccessList(tx.accessList || [])\n ];\n if (sig) {\n fields.push(formatNumber(sig.yParity, \"recoveryParam\"));\n fields.push(toBeArray(sig.r));\n fields.push(toBeArray(sig.s));\n }\n return concat([\"0x01\", encodeRlp(fields)]);\n}\nfunction _parseEip4844(data) {\n let fields = decodeRlp(getBytes(data).slice(1));\n let typeName = \"3\";\n let blobs = null;\n // Parse the network format\n if (fields.length === 4 && Array.isArray(fields[0])) {\n typeName = \"3 (network format)\";\n const fBlobs = fields[1], fCommits = fields[2], fProofs = fields[3];\n assertArgument(Array.isArray(fBlobs), \"invalid network format: blobs not an array\", \"fields[1]\", fBlobs);\n assertArgument(Array.isArray(fCommits), \"invalid network format: commitments not an array\", \"fields[2]\", fCommits);\n assertArgument(Array.isArray(fProofs), \"invalid network format: proofs not an array\", \"fields[3]\", fProofs);\n assertArgument(fBlobs.length === fCommits.length, \"invalid network format: blobs/commitments length mismatch\", \"fields\", fields);\n assertArgument(fBlobs.length === fProofs.length, \"invalid network format: blobs/proofs length mismatch\", \"fields\", fields);\n blobs = [];\n for (let i = 0; i < fields[1].length; i++) {\n blobs.push({\n data: fBlobs[i],\n commitment: fCommits[i],\n proof: fProofs[i],\n });\n }\n fields = fields[0];\n }\n assertArgument(Array.isArray(fields) && (fields.length === 11 || fields.length === 14), `invalid field count for transaction type: ${typeName}`, \"data\", hexlify(data));\n const tx = {\n type: 3,\n chainId: handleUint(fields[0], \"chainId\"),\n nonce: handleNumber(fields[1], \"nonce\"),\n maxPriorityFeePerGas: handleUint(fields[2], \"maxPriorityFeePerGas\"),\n maxFeePerGas: handleUint(fields[3], \"maxFeePerGas\"),\n gasPrice: null,\n gasLimit: handleUint(fields[4], \"gasLimit\"),\n to: handleAddress(fields[5]),\n value: handleUint(fields[6], \"value\"),\n data: hexlify(fields[7]),\n accessList: handleAccessList(fields[8], \"accessList\"),\n maxFeePerBlobGas: handleUint(fields[9], \"maxFeePerBlobGas\"),\n blobVersionedHashes: fields[10]\n };\n if (blobs) {\n tx.blobs = blobs;\n }\n assertArgument(tx.to != null, `invalid address for transaction type: ${typeName}`, \"data\", data);\n assertArgument(Array.isArray(tx.blobVersionedHashes), \"invalid blobVersionedHashes: must be an array\", \"data\", data);\n for (let i = 0; i < tx.blobVersionedHashes.length; i++) {\n assertArgument(isHexString(tx.blobVersionedHashes[i], 32), `invalid blobVersionedHash at index ${i}: must be length 32`, \"data\", data);\n }\n // Unsigned EIP-4844 Transaction\n if (fields.length === 11) {\n return tx;\n }\n // @TODO: Do we need to do this? This is only called internally\n // and used to verify hashes; it might save time to not do this\n //tx.hash = keccak256(concat([ \"0x03\", encodeRlp(fields) ]));\n _parseEipSignature(tx, fields.slice(11));\n return tx;\n}\nfunction _serializeEip4844(tx, sig, blobs) {\n const fields = [\n formatNumber(tx.chainId, \"chainId\"),\n formatNumber(tx.nonce, \"nonce\"),\n formatNumber(tx.maxPriorityFeePerGas || 0, \"maxPriorityFeePerGas\"),\n formatNumber(tx.maxFeePerGas || 0, \"maxFeePerGas\"),\n formatNumber(tx.gasLimit, \"gasLimit\"),\n (tx.to || ZeroAddress),\n formatNumber(tx.value, \"value\"),\n tx.data,\n formatAccessList(tx.accessList || []),\n formatNumber(tx.maxFeePerBlobGas || 0, \"maxFeePerBlobGas\"),\n formatHashes(tx.blobVersionedHashes || [], \"blobVersionedHashes\")\n ];\n if (sig) {\n fields.push(formatNumber(sig.yParity, \"yParity\"));\n fields.push(toBeArray(sig.r));\n fields.push(toBeArray(sig.s));\n // We have blobs; return the network wrapped format\n if (blobs) {\n return concat([\n \"0x03\",\n encodeRlp([\n fields,\n blobs.map((b) => b.data),\n blobs.map((b) => b.commitment),\n blobs.map((b) => b.proof),\n ])\n ]);\n }\n }\n return concat([\"0x03\", encodeRlp(fields)]);\n}\n/**\n * A **Transaction** describes an operation to be executed on\n * Ethereum by an Externally Owned Account (EOA). It includes\n * who (the [[to]] address), what (the [[data]]) and how much (the\n * [[value]] in ether) the operation should entail.\n *\n * @example:\n * tx = new Transaction()\n * //_result:\n *\n * tx.data = \"0x1234\";\n * //_result:\n */\nexport class Transaction {\n #type;\n #to;\n #data;\n #nonce;\n #gasLimit;\n #gasPrice;\n #maxPriorityFeePerGas;\n #maxFeePerGas;\n #value;\n #chainId;\n #sig;\n #accessList;\n #maxFeePerBlobGas;\n #blobVersionedHashes;\n #kzg;\n #blobs;\n /**\n * The transaction type.\n *\n * If null, the type will be automatically inferred based on\n * explicit properties.\n */\n get type() { return this.#type; }\n set type(value) {\n switch (value) {\n case null:\n this.#type = null;\n break;\n case 0:\n case \"legacy\":\n this.#type = 0;\n break;\n case 1:\n case \"berlin\":\n case \"eip-2930\":\n this.#type = 1;\n break;\n case 2:\n case \"london\":\n case \"eip-1559\":\n this.#type = 2;\n break;\n case 3:\n case \"cancun\":\n case \"eip-4844\":\n this.#type = 3;\n break;\n default:\n assertArgument(false, \"unsupported transaction type\", \"type\", value);\n }\n }\n /**\n * The name of the transaction type.\n */\n get typeName() {\n switch (this.type) {\n case 0: return \"legacy\";\n case 1: return \"eip-2930\";\n case 2: return \"eip-1559\";\n case 3: return \"eip-4844\";\n }\n return null;\n }\n /**\n * The ``to`` address for the transaction or ``null`` if the\n * transaction is an ``init`` transaction.\n */\n get to() {\n const value = this.#to;\n if (value == null && this.type === 3) {\n return ZeroAddress;\n }\n return value;\n }\n set to(value) {\n this.#to = (value == null) ? null : getAddress(value);\n }\n /**\n * The transaction nonce.\n */\n get nonce() { return this.#nonce; }\n set nonce(value) { this.#nonce = getNumber(value, \"value\"); }\n /**\n * The gas limit.\n */\n get gasLimit() { return this.#gasLimit; }\n set gasLimit(value) { this.#gasLimit = getBigInt(value); }\n /**\n * The gas price.\n *\n * On legacy networks this defines the fee that will be paid. On\n * EIP-1559 networks, this should be ``null``.\n */\n get gasPrice() {\n const value = this.#gasPrice;\n if (value == null && (this.type === 0 || this.type === 1)) {\n return BN_0;\n }\n return value;\n }\n set gasPrice(value) {\n this.#gasPrice = (value == null) ? null : getBigInt(value, \"gasPrice\");\n }\n /**\n * The maximum priority fee per unit of gas to pay. On legacy\n * networks this should be ``null``.\n */\n get maxPriorityFeePerGas() {\n const value = this.#maxPriorityFeePerGas;\n if (value == null) {\n if (this.type === 2 || this.type === 3) {\n return BN_0;\n }\n return null;\n }\n return value;\n }\n set maxPriorityFeePerGas(value) {\n this.#maxPriorityFeePerGas = (value == null) ? null : getBigInt(value, \"maxPriorityFeePerGas\");\n }\n /**\n * The maximum total fee per unit of gas to pay. On legacy\n * networks this should be ``null``.\n */\n get maxFeePerGas() {\n const value = this.#maxFeePerGas;\n if (value == null) {\n if (this.type === 2 || this.type === 3) {\n return BN_0;\n }\n return null;\n }\n return value;\n }\n set maxFeePerGas(value) {\n this.#maxFeePerGas = (value == null) ? null : getBigInt(value, \"maxFeePerGas\");\n }\n /**\n * The transaction data. For ``init`` transactions this is the\n * deployment code.\n */\n get data() { return this.#data; }\n set data(value) { this.#data = hexlify(value); }\n /**\n * The amount of ether (in wei) to send in this transactions.\n */\n get value() { return this.#value; }\n set value(value) {\n this.#value = getBigInt(value, \"value\");\n }\n /**\n * The chain ID this transaction is valid on.\n */\n get chainId() { return this.#chainId; }\n set chainId(value) { this.#chainId = getBigInt(value); }\n /**\n * If signed, the signature for this transaction.\n */\n get signature() { return this.#sig || null; }\n set signature(value) {\n this.#sig = (value == null) ? null : Signature.from(value);\n }\n /**\n * The access list.\n *\n * An access list permits discounted (but pre-paid) access to\n * bytecode and state variable access within contract execution.\n */\n get accessList() {\n const value = this.#accessList || null;\n if (value == null) {\n if (this.type === 1 || this.type === 2 || this.type === 3) {\n // @TODO: in v7, this should assign the value or become\n // a live object itself, otherwise mutation is inconsistent\n return [];\n }\n return null;\n }\n return value;\n }\n set accessList(value) {\n this.#accessList = (value == null) ? null : accessListify(value);\n }\n /**\n * The max fee per blob gas for Cancun transactions.\n */\n get maxFeePerBlobGas() {\n const value = this.#maxFeePerBlobGas;\n if (value == null && this.type === 3) {\n return BN_0;\n }\n return value;\n }\n set maxFeePerBlobGas(value) {\n this.#maxFeePerBlobGas = (value == null) ? null : getBigInt(value, \"maxFeePerBlobGas\");\n }\n /**\n * The BLOb versioned hashes for Cancun transactions.\n */\n get blobVersionedHashes() {\n // @TODO: Mutation is inconsistent; if unset, the returned value\n // cannot mutate the object, if set it can\n let value = this.#blobVersionedHashes;\n if (value == null && this.type === 3) {\n return [];\n }\n return value;\n }\n set blobVersionedHashes(value) {\n if (value != null) {\n assertArgument(Array.isArray(value), \"blobVersionedHashes must be an Array\", \"value\", value);\n value = value.slice();\n for (let i = 0; i < value.length; i++) {\n assertArgument(isHexString(value[i], 32), \"invalid blobVersionedHash\", `value[${i}]`, value[i]);\n }\n }\n this.#blobVersionedHashes = value;\n }\n /**\n * The BLObs for the Transaction, if any.\n *\n * If ``blobs`` is non-``null``, then the [[seriailized]]\n * will return the network formatted sidecar, otherwise it\n * will return the standard [[link-eip-2718]] payload. The\n * [[unsignedSerialized]] is unaffected regardless.\n *\n * When setting ``blobs``, either fully valid [[Blob]] objects\n * may be specified (i.e. correctly padded, with correct\n * committments and proofs) or a raw [[BytesLike]] may\n * be provided.\n *\n * If raw [[BytesLike]] are provided, the [[kzg]] property **must**\n * be already set. The blob will be correctly padded and the\n * [[KzgLibrary]] will be used to compute the committment and\n * proof for the blob.\n *\n * A BLOb is a sequence of field elements, each of which must\n * be within the BLS field modulo, so some additional processing\n * may be required to encode arbitrary data to ensure each 32 byte\n * field is within the valid range.\n *\n * Setting this automatically populates [[blobVersionedHashes]],\n * overwriting any existing values. Setting this to ``null``\n * does **not** remove the [[blobVersionedHashes]], leaving them\n * present.\n */\n get blobs() {\n if (this.#blobs == null) {\n return null;\n }\n return this.#blobs.map((b) => Object.assign({}, b));\n }\n set blobs(_blobs) {\n if (_blobs == null) {\n this.#blobs = null;\n return;\n }\n const blobs = [];\n const versionedHashes = [];\n for (let i = 0; i < _blobs.length; i++) {\n const blob = _blobs[i];\n if (isBytesLike(blob)) {\n assert(this.#kzg, \"adding a raw blob requires a KZG library\", \"UNSUPPORTED_OPERATION\", {\n operation: \"set blobs()\"\n });\n let data = getBytes(blob);\n assertArgument(data.length <= BLOB_SIZE, \"blob is too large\", `blobs[${i}]`, blob);\n // Pad blob if necessary\n if (data.length !== BLOB_SIZE) {\n const padded = new Uint8Array(BLOB_SIZE);\n padded.set(data);\n data = padded;\n }\n const commit = this.#kzg.blobToKzgCommitment(data);\n const proof = hexlify(this.#kzg.computeBlobKzgProof(data, commit));\n blobs.push({\n data: hexlify(data),\n commitment: hexlify(commit),\n proof\n });\n versionedHashes.push(getVersionedHash(1, commit));\n }\n else {\n const commit = hexlify(blob.commitment);\n blobs.push({\n data: hexlify(blob.data),\n commitment: commit,\n proof: hexlify(blob.proof)\n });\n versionedHashes.push(getVersionedHash(1, commit));\n }\n }\n this.#blobs = blobs;\n this.#blobVersionedHashes = versionedHashes;\n }\n get kzg() { return this.#kzg; }\n set kzg(kzg) {\n this.#kzg = kzg;\n }\n /**\n * Creates a new Transaction with default values.\n */\n constructor() {\n this.#type = null;\n this.#to = null;\n this.#nonce = 0;\n this.#gasLimit = BN_0;\n this.#gasPrice = null;\n this.#maxPriorityFeePerGas = null;\n this.#maxFeePerGas = null;\n this.#data = \"0x\";\n this.#value = BN_0;\n this.#chainId = BN_0;\n this.#sig = null;\n this.#accessList = null;\n this.#maxFeePerBlobGas = null;\n this.#blobVersionedHashes = null;\n this.#blobs = null;\n this.#kzg = null;\n }\n /**\n * The transaction hash, if signed. Otherwise, ``null``.\n */\n get hash() {\n if (this.signature == null) {\n return null;\n }\n return keccak256(this.#getSerialized(true, false));\n }\n /**\n * The pre-image hash of this transaction.\n *\n * This is the digest that a [[Signer]] must sign to authorize\n * this transaction.\n */\n get unsignedHash() {\n return keccak256(this.unsignedSerialized);\n }\n /**\n * The sending address, if signed. Otherwise, ``null``.\n */\n get from() {\n if (this.signature == null) {\n return null;\n }\n return recoverAddress(this.unsignedHash, this.signature);\n }\n /**\n * The public key of the sender, if signed. Otherwise, ``null``.\n */\n get fromPublicKey() {\n if (this.signature == null) {\n return null;\n }\n return SigningKey.recoverPublicKey(this.unsignedHash, this.signature);\n }\n /**\n * Returns true if signed.\n *\n * This provides a Type Guard that properties requiring a signed\n * transaction are non-null.\n */\n isSigned() {\n return this.signature != null;\n }\n #getSerialized(signed, sidecar) {\n assert(!signed || this.signature != null, \"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized\", \"UNSUPPORTED_OPERATION\", { operation: \".serialized\" });\n const sig = signed ? this.signature : null;\n switch (this.inferType()) {\n case 0:\n return _serializeLegacy(this, sig);\n case 1:\n return _serializeEip2930(this, sig);\n case 2:\n return _serializeEip1559(this, sig);\n case 3:\n return _serializeEip4844(this, sig, sidecar ? this.blobs : null);\n }\n assert(false, \"unsupported transaction type\", \"UNSUPPORTED_OPERATION\", { operation: \".serialized\" });\n }\n /**\n * The serialized transaction.\n *\n * This throws if the transaction is unsigned. For the pre-image,\n * use [[unsignedSerialized]].\n */\n get serialized() {\n return this.#getSerialized(true, true);\n }\n /**\n * The transaction pre-image.\n *\n * The hash of this is the digest which needs to be signed to\n * authorize this transaction.\n */\n get unsignedSerialized() {\n return this.#getSerialized(false, false);\n }\n /**\n * Return the most \"likely\" type; currently the highest\n * supported transaction type.\n */\n inferType() {\n const types = this.inferTypes();\n // Prefer London (EIP-1559) over Cancun (BLOb)\n if (types.indexOf(2) >= 0) {\n return 2;\n }\n // Return the highest inferred type\n return (types.pop());\n }\n /**\n * Validates the explicit properties and returns a list of compatible\n * transaction types.\n */\n inferTypes() {\n // Checks that there are no conflicting properties set\n const hasGasPrice = this.gasPrice != null;\n const hasFee = (this.maxFeePerGas != null || this.maxPriorityFeePerGas != null);\n const hasAccessList = (this.accessList != null);\n const hasBlob = (this.#maxFeePerBlobGas != null || this.#blobVersionedHashes);\n //if (hasGasPrice && hasFee) {\n // throw new Error(\"transaction cannot have gasPrice and maxFeePerGas\");\n //}\n if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) {\n assert(this.maxFeePerGas >= this.maxPriorityFeePerGas, \"priorityFee cannot be more than maxFee\", \"BAD_DATA\", { value: this });\n }\n //if (this.type === 2 && hasGasPrice) {\n // throw new Error(\"eip-1559 transaction cannot have gasPrice\");\n //}\n assert(!hasFee || (this.type !== 0 && this.type !== 1), \"transaction type cannot have maxFeePerGas or maxPriorityFeePerGas\", \"BAD_DATA\", { value: this });\n assert(this.type !== 0 || !hasAccessList, \"legacy transaction cannot have accessList\", \"BAD_DATA\", { value: this });\n const types = [];\n // Explicit type\n if (this.type != null) {\n types.push(this.type);\n }\n else {\n if (hasFee) {\n types.push(2);\n }\n else if (hasGasPrice) {\n types.push(1);\n if (!hasAccessList) {\n types.push(0);\n }\n }\n else if (hasAccessList) {\n types.push(1);\n types.push(2);\n }\n else if (hasBlob && this.to) {\n types.push(3);\n }\n else {\n types.push(0);\n types.push(1);\n types.push(2);\n types.push(3);\n }\n }\n types.sort();\n return types;\n }\n /**\n * Returns true if this transaction is a legacy transaction (i.e.\n * ``type === 0``).\n *\n * This provides a Type Guard that the related properties are\n * non-null.\n */\n isLegacy() {\n return (this.type === 0);\n }\n /**\n * Returns true if this transaction is berlin hardform transaction (i.e.\n * ``type === 1``).\n *\n * This provides a Type Guard that the related properties are\n * non-null.\n */\n isBerlin() {\n return (this.type === 1);\n }\n /**\n * Returns true if this transaction is london hardform transaction (i.e.\n * ``type === 2``).\n *\n * This provides a Type Guard that the related properties are\n * non-null.\n */\n isLondon() {\n return (this.type === 2);\n }\n /**\n * Returns true if this transaction is an [[link-eip-4844]] BLOB\n * transaction.\n *\n * This provides a Type Guard that the related properties are\n * non-null.\n */\n isCancun() {\n return (this.type === 3);\n }\n /**\n * Create a copy of this transaciton.\n */\n clone() {\n return Transaction.from(this);\n }\n /**\n * Return a JSON-friendly object.\n */\n toJSON() {\n const s = (v) => {\n if (v == null) {\n return null;\n }\n return v.toString();\n };\n return {\n type: this.type,\n to: this.to,\n // from: this.from,\n data: this.data,\n nonce: this.nonce,\n gasLimit: s(this.gasLimit),\n gasPrice: s(this.gasPrice),\n maxPriorityFeePerGas: s(this.maxPriorityFeePerGas),\n maxFeePerGas: s(this.maxFeePerGas),\n value: s(this.value),\n chainId: s(this.chainId),\n sig: this.signature ? this.signature.toJSON() : null,\n accessList: this.accessList\n };\n }\n /**\n * Create a **Transaction** from a serialized transaction or a\n * Transaction-like object.\n */\n static from(tx) {\n if (tx == null) {\n return new Transaction();\n }\n if (typeof (tx) === \"string\") {\n const payload = getBytes(tx);\n if (payload[0] >= 0x7f) { // @TODO: > vs >= ??\n return Transaction.from(_parseLegacy(payload));\n }\n switch (payload[0]) {\n case 1: return Transaction.from(_parseEip2930(payload));\n case 2: return Transaction.from(_parseEip1559(payload));\n case 3: return Transaction.from(_parseEip4844(payload));\n }\n assert(false, \"unsupported transaction type\", \"UNSUPPORTED_OPERATION\", { operation: \"from\" });\n }\n const result = new Transaction();\n if (tx.type != null) {\n result.type = tx.type;\n }\n if (tx.to != null) {\n result.to = tx.to;\n }\n if (tx.nonce != null) {\n result.nonce = tx.nonce;\n }\n if (tx.gasLimit != null) {\n result.gasLimit = tx.gasLimit;\n }\n if (tx.gasPrice != null) {\n result.gasPrice = tx.gasPrice;\n }\n if (tx.maxPriorityFeePerGas != null) {\n result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas;\n }\n if (tx.maxFeePerGas != null) {\n result.maxFeePerGas = tx.maxFeePerGas;\n }\n if (tx.maxFeePerBlobGas != null) {\n result.maxFeePerBlobGas = tx.maxFeePerBlobGas;\n }\n if (tx.data != null) {\n result.data = tx.data;\n }\n if (tx.value != null) {\n result.value = tx.value;\n }\n if (tx.chainId != null) {\n result.chainId = tx.chainId;\n }\n if (tx.signature != null) {\n result.signature = Signature.from(tx.signature);\n }\n if (tx.accessList != null) {\n result.accessList = tx.accessList;\n }\n // This will get overwritten by blobs, if present\n if (tx.blobVersionedHashes != null) {\n result.blobVersionedHashes = tx.blobVersionedHashes;\n }\n // Make sure we assign the kzg before assigning blobs, which\n // require the library in the event raw blob data is provided.\n if (tx.kzg != null) {\n result.kzg = tx.kzg;\n }\n if (tx.blobs != null) {\n result.blobs = tx.blobs;\n }\n if (tx.hash != null) {\n assertArgument(result.isSigned(), \"unsigned transaction cannot define '.hash'\", \"tx\", tx);\n assertArgument(result.hash === tx.hash, \"hash mismatch\", \"tx\", tx);\n }\n if (tx.from != null) {\n assertArgument(result.isSigned(), \"unsigned transaction cannot define '.from'\", \"tx\", tx);\n assertArgument(result.from.toLowerCase() === (tx.from || \"\").toLowerCase(), \"from mismatch\", \"tx\", tx);\n }\n return result;\n }\n}\n//# sourceMappingURL=transaction.js.map","import { keccak256 } from \"../crypto/index.js\";\nimport { MessagePrefix } from \"../constants/index.js\";\nimport { recoverAddress } from \"../transaction/index.js\";\nimport { concat, toUtf8Bytes } from \"../utils/index.js\";\n/**\n * Computes the [[link-eip-191]] personal-sign message digest to sign.\n *\n * This prefixes the message with [[MessagePrefix]] and the decimal length\n * of %%message%% and computes the [[keccak256]] digest.\n *\n * If %%message%% is a string, it is converted to its UTF-8 bytes\n * first. To compute the digest of a [[DataHexString]], it must be converted\n * to [bytes](getBytes).\n *\n * @example:\n * hashMessage(\"Hello World\")\n * //_result:\n *\n * // Hashes the SIX (6) string characters, i.e.\n * // [ \"0\", \"x\", \"4\", \"2\", \"4\", \"3\" ]\n * hashMessage(\"0x4243\")\n * //_result:\n *\n * // Hashes the TWO (2) bytes [ 0x42, 0x43 ]...\n * hashMessage(getBytes(\"0x4243\"))\n * //_result:\n *\n * // ...which is equal to using data\n * hashMessage(new Uint8Array([ 0x42, 0x43 ]))\n * //_result:\n *\n */\nexport function hashMessage(message) {\n if (typeof (message) === \"string\") {\n message = toUtf8Bytes(message);\n }\n return keccak256(concat([\n toUtf8Bytes(MessagePrefix),\n toUtf8Bytes(String(message.length)),\n message\n ]));\n}\n/**\n * Return the address of the private key that produced\n * the signature %%sig%% during signing for %%message%%.\n */\nexport function verifyMessage(message, sig) {\n const digest = hashMessage(message);\n return recoverAddress(digest, sig);\n}\n//# sourceMappingURL=message.js.map","// NFKC (composed) // (decomposed)\n/**\n * A constant for the ether symbol (normalized using NFKC).\n *\n * (**i.e.** ``\"\\\\u039e\"``)\n */\nexport const EtherSymbol = \"\\u039e\"; // \"\\uD835\\uDF63\";\n/**\n * A constant for the [[link-eip-191]] personal message prefix.\n *\n * (**i.e.** ``\"\\\\x19Ethereum Signed Message:\\\\n\"``)\n */\nexport const MessagePrefix = \"\\x19Ethereum Signed Message:\\n\";\n//# sourceMappingURL=strings.js.map","//import { TypedDataDomain, TypedDataField } from \"@ethersproject/providerabstract-signer\";\nimport { getAddress } from \"../address/index.js\";\nimport { keccak256 } from \"../crypto/index.js\";\nimport { recoverAddress } from \"../transaction/index.js\";\nimport { concat, defineProperties, getBigInt, getBytes, hexlify, isHexString, mask, toBeHex, toQuantity, toTwos, zeroPadValue, assertArgument } from \"../utils/index.js\";\nimport { id } from \"./id.js\";\nconst padding = new Uint8Array(32);\npadding.fill(0);\nconst BN__1 = BigInt(-1);\nconst BN_0 = BigInt(0);\nconst BN_1 = BigInt(1);\nconst BN_MAX_UINT256 = BigInt(\"0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff\");\n;\n;\nfunction hexPadRight(value) {\n const bytes = getBytes(value);\n const padOffset = bytes.length % 32;\n if (padOffset) {\n return concat([bytes, padding.slice(padOffset)]);\n }\n return hexlify(bytes);\n}\nconst hexTrue = toBeHex(BN_1, 32);\nconst hexFalse = toBeHex(BN_0, 32);\nconst domainFieldTypes = {\n name: \"string\",\n version: \"string\",\n chainId: \"uint256\",\n verifyingContract: \"address\",\n salt: \"bytes32\"\n};\nconst domainFieldNames = [\n \"name\", \"version\", \"chainId\", \"verifyingContract\", \"salt\"\n];\nfunction checkString(key) {\n return function (value) {\n assertArgument(typeof (value) === \"string\", `invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value);\n return value;\n };\n}\nconst domainChecks = {\n name: checkString(\"name\"),\n version: checkString(\"version\"),\n chainId: function (_value) {\n const value = getBigInt(_value, \"domain.chainId\");\n assertArgument(value >= 0, \"invalid chain ID\", \"domain.chainId\", _value);\n if (Number.isSafeInteger(value)) {\n return Number(value);\n }\n return toQuantity(value);\n },\n verifyingContract: function (value) {\n try {\n return getAddress(value).toLowerCase();\n }\n catch (error) { }\n assertArgument(false, `invalid domain value \"verifyingContract\"`, \"domain.verifyingContract\", value);\n },\n salt: function (value) {\n const bytes = getBytes(value, \"domain.salt\");\n assertArgument(bytes.length === 32, `invalid domain value \"salt\"`, \"domain.salt\", value);\n return hexlify(bytes);\n }\n};\nfunction getBaseEncoder(type) {\n // intXX and uintXX\n {\n const match = type.match(/^(u?)int(\\d+)$/);\n if (match) {\n const signed = (match[1] === \"\");\n const width = parseInt(match[2]);\n assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && match[2] === String(width), \"invalid numeric width\", \"type\", type);\n const boundsUpper = mask(BN_MAX_UINT256, signed ? (width - 1) : width);\n const boundsLower = signed ? ((boundsUpper + BN_1) * BN__1) : BN_0;\n return function (_value) {\n const value = getBigInt(_value, \"value\");\n assertArgument(value >= boundsLower && value <= boundsUpper, `value out-of-bounds for ${type}`, \"value\", value);\n return toBeHex(signed ? toTwos(value, 256) : value, 32);\n };\n }\n }\n // bytesXX\n {\n const match = type.match(/^bytes(\\d+)$/);\n if (match) {\n const width = parseInt(match[1]);\n assertArgument(width !== 0 && width <= 32 && match[1] === String(width), \"invalid bytes width\", \"type\", type);\n return function (value) {\n const bytes = getBytes(value);\n assertArgument(bytes.length === width, `invalid length for ${type}`, \"value\", value);\n return hexPadRight(value);\n };\n }\n }\n switch (type) {\n case \"address\": return function (value) {\n return zeroPadValue(getAddress(value), 32);\n };\n case \"bool\": return function (value) {\n return ((!value) ? hexFalse : hexTrue);\n };\n case \"bytes\": return function (value) {\n return keccak256(value);\n };\n case \"string\": return function (value) {\n return id(value);\n };\n }\n return null;\n}\nfunction encodeType(name, fields) {\n return `${name}(${fields.map(({ name, type }) => (type + \" \" + name)).join(\",\")})`;\n}\n// foo[][3] => { base: \"foo\", index: \"[][3]\", array: {\n// base: \"foo\", prefix: \"foo[]\", count: 3 } }\nfunction splitArray(type) {\n const match = type.match(/^([^\\x5b]*)((\\x5b\\d*\\x5d)*)(\\x5b(\\d*)\\x5d)$/);\n if (match) {\n return {\n base: match[1],\n index: (match[2] + match[4]),\n array: {\n base: match[1],\n prefix: (match[1] + match[2]),\n count: (match[5] ? parseInt(match[5]) : -1),\n }\n };\n }\n return { base: type };\n}\n/**\n * A **TypedDataEncode** prepares and encodes [[link-eip-712]] payloads\n * for signed typed data.\n *\n * This is useful for those that wish to compute various components of a\n * typed data hash, primary types, or sub-components, but generally the\n * higher level [[Signer-signTypedData]] is more useful.\n */\nexport class TypedDataEncoder {\n /**\n * The primary type for the structured [[types]].\n *\n * This is derived automatically from the [[types]], since no\n * recursion is possible, once the DAG for the types is consturcted\n * internally, the primary type must be the only remaining type with\n * no parent nodes.\n */\n primaryType;\n #types;\n /**\n * The types.\n */\n get types() {\n return JSON.parse(this.#types);\n }\n #fullTypes;\n #encoderCache;\n /**\n * Create a new **TypedDataEncoder** for %%types%%.\n *\n * This performs all necessary checking that types are valid and\n * do not violate the [[link-eip-712]] structural constraints as\n * well as computes the [[primaryType]].\n */\n constructor(_types) {\n this.#fullTypes = new Map();\n this.#encoderCache = new Map();\n // Link struct types to their direct child structs\n const links = new Map();\n // Link structs to structs which contain them as a child\n const parents = new Map();\n // Link all subtypes within a given struct\n const subtypes = new Map();\n const types = {};\n Object.keys(_types).forEach((type) => {\n types[type] = _types[type].map(({ name, type }) => {\n // Normalize the base type (unless name conflict)\n let { base, index } = splitArray(type);\n if (base === \"int\" && !_types[\"int\"]) {\n base = \"int256\";\n }\n if (base === \"uint\" && !_types[\"uint\"]) {\n base = \"uint256\";\n }\n return { name, type: (base + (index || \"\")) };\n });\n links.set(type, new Set());\n parents.set(type, []);\n subtypes.set(type, new Set());\n });\n this.#types = JSON.stringify(types);\n for (const name in types) {\n const uniqueNames = new Set();\n for (const field of types[name]) {\n // Check each field has a unique name\n assertArgument(!uniqueNames.has(field.name), `duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, \"types\", _types);\n uniqueNames.add(field.name);\n // Get the base type (drop any array specifiers)\n const baseType = splitArray(field.type).base;\n assertArgument(baseType !== name, `circular type reference to ${JSON.stringify(baseType)}`, \"types\", _types);\n // Is this a base encoding type?\n const encoder = getBaseEncoder(baseType);\n if (encoder) {\n continue;\n }\n assertArgument(parents.has(baseType), `unknown type ${JSON.stringify(baseType)}`, \"types\", _types);\n // Add linkage\n parents.get(baseType).push(name);\n links.get(name).add(baseType);\n }\n }\n // Deduce the primary type\n const primaryTypes = Array.from(parents.keys()).filter((n) => (parents.get(n).length === 0));\n assertArgument(primaryTypes.length !== 0, \"missing primary type\", \"types\", _types);\n assertArgument(primaryTypes.length === 1, `ambiguous primary types or unused types: ${primaryTypes.map((t) => (JSON.stringify(t))).join(\", \")}`, \"types\", _types);\n defineProperties(this, { primaryType: primaryTypes[0] });\n // Check for circular type references\n function checkCircular(type, found) {\n assertArgument(!found.has(type), `circular type reference to ${JSON.stringify(type)}`, \"types\", _types);\n found.add(type);\n for (const child of links.get(type)) {\n if (!parents.has(child)) {\n continue;\n }\n // Recursively check children\n checkCircular(child, found);\n // Mark all ancestors as having this decendant\n for (const subtype of found) {\n subtypes.get(subtype).add(child);\n }\n }\n found.delete(type);\n }\n checkCircular(this.primaryType, new Set());\n // Compute each fully describe type\n for (const [name, set] of subtypes) {\n const st = Array.from(set);\n st.sort();\n this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join(\"\"));\n }\n }\n /**\n * Returnthe encoder for the specific %%type%%.\n */\n getEncoder(type) {\n let encoder = this.#encoderCache.get(type);\n if (!encoder) {\n encoder = this.#getEncoder(type);\n this.#encoderCache.set(type, encoder);\n }\n return encoder;\n }\n #getEncoder(type) {\n // Basic encoder type (address, bool, uint256, etc)\n {\n const encoder = getBaseEncoder(type);\n if (encoder) {\n return encoder;\n }\n }\n // Array\n const array = splitArray(type).array;\n if (array) {\n const subtype = array.prefix;\n const subEncoder = this.getEncoder(subtype);\n return (value) => {\n assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, \"value\", value);\n let result = value.map(subEncoder);\n if (this.#fullTypes.has(subtype)) {\n result = result.map(keccak256);\n }\n return keccak256(concat(result));\n };\n }\n // Struct\n const fields = this.types[type];\n if (fields) {\n const encodedType = id(this.#fullTypes.get(type));\n return (value) => {\n const values = fields.map(({ name, type }) => {\n const result = this.getEncoder(type)(value[name]);\n if (this.#fullTypes.has(type)) {\n return keccak256(result);\n }\n return result;\n });\n values.unshift(encodedType);\n return concat(values);\n };\n }\n assertArgument(false, `unknown type: ${type}`, \"type\", type);\n }\n /**\n * Return the full type for %%name%%.\n */\n encodeType(name) {\n const result = this.#fullTypes.get(name);\n assertArgument(result, `unknown type: ${JSON.stringify(name)}`, \"name\", name);\n return result;\n }\n /**\n * Return the encoded %%value%% for the %%type%%.\n */\n encodeData(type, value) {\n return this.getEncoder(type)(value);\n }\n /**\n * Returns the hash of %%value%% for the type of %%name%%.\n */\n hashStruct(name, value) {\n return keccak256(this.encodeData(name, value));\n }\n /**\n * Return the fulled encoded %%value%% for the [[types]].\n */\n encode(value) {\n return this.encodeData(this.primaryType, value);\n }\n /**\n * Return the hash of the fully encoded %%value%% for the [[types]].\n */\n hash(value) {\n return this.hashStruct(this.primaryType, value);\n }\n /**\n * @_ignore:\n */\n _visit(type, value, callback) {\n // Basic encoder type (address, bool, uint256, etc)\n {\n const encoder = getBaseEncoder(type);\n if (encoder) {\n return callback(type, value);\n }\n }\n // Array\n const array = splitArray(type).array;\n if (array) {\n assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, \"value\", value);\n return value.map((v) => this._visit(array.prefix, v, callback));\n }\n // Struct\n const fields = this.types[type];\n if (fields) {\n return fields.reduce((accum, { name, type }) => {\n accum[name] = this._visit(type, value[name], callback);\n return accum;\n }, {});\n }\n assertArgument(false, `unknown type: ${type}`, \"type\", type);\n }\n /**\n * Call %%calback%% for each value in %%value%%, passing the type and\n * component within %%value%%.\n *\n * This is useful for replacing addresses or other transformation that\n * may be desired on each component, based on its type.\n */\n visit(value, callback) {\n return this._visit(this.primaryType, value, callback);\n }\n /**\n * Create a new **TypedDataEncoder** for %%types%%.\n */\n static from(types) {\n return new TypedDataEncoder(types);\n }\n /**\n * Return the primary type for %%types%%.\n */\n static getPrimaryType(types) {\n return TypedDataEncoder.from(types).primaryType;\n }\n /**\n * Return the hashed struct for %%value%% using %%types%% and %%name%%.\n */\n static hashStruct(name, types, value) {\n return TypedDataEncoder.from(types).hashStruct(name, value);\n }\n /**\n * Return the domain hash for %%domain%%.\n */\n static hashDomain(domain) {\n const domainFields = [];\n for (const name in domain) {\n if (domain[name] == null) {\n continue;\n }\n const type = domainFieldTypes[name];\n assertArgument(type, `invalid typed-data domain key: ${JSON.stringify(name)}`, \"domain\", domain);\n domainFields.push({ name, type });\n }\n domainFields.sort((a, b) => {\n return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name);\n });\n return TypedDataEncoder.hashStruct(\"EIP712Domain\", { EIP712Domain: domainFields }, domain);\n }\n /**\n * Return the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.\n */\n static encode(domain, types, value) {\n return concat([\n \"0x1901\",\n TypedDataEncoder.hashDomain(domain),\n TypedDataEncoder.from(types).hash(value)\n ]);\n }\n /**\n * Return the hash of the fully encoded [[link-eip-712]] %%value%% for %%types%% with %%domain%%.\n */\n static hash(domain, types, value) {\n return keccak256(TypedDataEncoder.encode(domain, types, value));\n }\n // Replaces all address types with ENS names with their looked up address\n /**\n * Resolves to the value from resolving all addresses in %%value%% for\n * %%types%% and the %%domain%%.\n */\n static async resolveNames(domain, types, value, resolveName) {\n // Make a copy to isolate it from the object passed in\n domain = Object.assign({}, domain);\n // Allow passing null to ignore value\n for (const key in domain) {\n if (domain[key] == null) {\n delete domain[key];\n }\n }\n // Look up all ENS names\n const ensCache = {};\n // Do we need to look up the domain's verifyingContract?\n if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) {\n ensCache[domain.verifyingContract] = \"0x\";\n }\n // We are going to use the encoder to visit all the base values\n const encoder = TypedDataEncoder.from(types);\n // Get a list of all the addresses\n encoder.visit(value, (type, value) => {\n if (type === \"address\" && !isHexString(value, 20)) {\n ensCache[value] = \"0x\";\n }\n return value;\n });\n // Lookup each name\n for (const name in ensCache) {\n ensCache[name] = await resolveName(name);\n }\n // Replace the domain verifyingContract if needed\n if (domain.verifyingContract && ensCache[domain.verifyingContract]) {\n domain.verifyingContract = ensCache[domain.verifyingContract];\n }\n // Replace all ENS names with their address\n value = encoder.visit(value, (type, value) => {\n if (type === \"address\" && ensCache[value]) {\n return ensCache[value];\n }\n return value;\n });\n return { domain, value };\n }\n /**\n * Returns the JSON-encoded payload expected by nodes which implement\n * the JSON-RPC [[link-eip-712]] method.\n */\n static getPayload(domain, types, value) {\n // Validate the domain fields\n TypedDataEncoder.hashDomain(domain);\n // Derive the EIP712Domain Struct reference type\n const domainValues = {};\n const domainTypes = [];\n domainFieldNames.forEach((name) => {\n const value = domain[name];\n if (value == null) {\n return;\n }\n domainValues[name] = domainChecks[name](value);\n domainTypes.push({ name, type: domainFieldTypes[name] });\n });\n const encoder = TypedDataEncoder.from(types);\n // Get the normalized types\n types = encoder.types;\n const typesWithDomain = Object.assign({}, types);\n assertArgument(typesWithDomain.EIP712Domain == null, \"types must not contain EIP712Domain type\", \"types.EIP712Domain\", types);\n typesWithDomain.EIP712Domain = domainTypes;\n // Validate the data structures and types\n encoder.encode(value);\n return {\n types: typesWithDomain,\n domain: domainValues,\n primaryType: encoder.primaryType,\n message: encoder.visit(value, (type, value) => {\n // bytes\n if (type.match(/^bytes(\\d*)/)) {\n return hexlify(getBytes(value));\n }\n // uint or int\n if (type.match(/^u?int/)) {\n return getBigInt(value).toString();\n }\n switch (type) {\n case \"address\":\n return value.toLowerCase();\n case \"bool\":\n return !!value;\n case \"string\":\n assertArgument(typeof (value) === \"string\", \"invalid string\", \"value\", value);\n return value;\n }\n assertArgument(false, \"unsupported type\", \"type\", type);\n })\n };\n }\n}\n/**\n * Compute the address used to sign the typed data for the %%signature%%.\n */\nexport function verifyTypedData(domain, types, value, signature) {\n return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature);\n}\n//# sourceMappingURL=typed-data.js.map","/**\n * A fragment is a single item from an ABI, which may represent any of:\n *\n * - [Functions](FunctionFragment)\n * - [Events](EventFragment)\n * - [Constructors](ConstructorFragment)\n * - Custom [Errors](ErrorFragment)\n * - [Fallback or Receive](FallbackFragment) functions\n *\n * @_subsection api/abi/abi-coder:Fragments [about-fragments]\n */\nimport { defineProperties, getBigInt, getNumber, assert, assertPrivate, assertArgument } from \"../utils/index.js\";\nimport { id } from \"../hash/index.js\";\n;\n// [ \"a\", \"b\" ] => { \"a\": 1, \"b\": 1 }\nfunction setify(items) {\n const result = new Set();\n items.forEach((k) => result.add(k));\n return Object.freeze(result);\n}\nconst _kwVisibDeploy = \"external public payable override\";\nconst KwVisibDeploy = setify(_kwVisibDeploy.split(\" \"));\n// Visibility Keywords\nconst _kwVisib = \"constant external internal payable private public pure view override\";\nconst KwVisib = setify(_kwVisib.split(\" \"));\nconst _kwTypes = \"constructor error event fallback function receive struct\";\nconst KwTypes = setify(_kwTypes.split(\" \"));\nconst _kwModifiers = \"calldata memory storage payable indexed\";\nconst KwModifiers = setify(_kwModifiers.split(\" \"));\nconst _kwOther = \"tuple returns\";\n// All Keywords\nconst _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(\" \");\nconst Keywords = setify(_keywords.split(\" \"));\n// Single character tokens\nconst SimpleTokens = {\n \"(\": \"OPEN_PAREN\", \")\": \"CLOSE_PAREN\",\n \"[\": \"OPEN_BRACKET\", \"]\": \"CLOSE_BRACKET\",\n \",\": \"COMMA\", \"@\": \"AT\"\n};\n// Parser regexes to consume the next token\nconst regexWhitespacePrefix = new RegExp(\"^(\\\\s*)\");\nconst regexNumberPrefix = new RegExp(\"^([0-9]+)\");\nconst regexIdPrefix = new RegExp(\"^([a-zA-Z$_][a-zA-Z0-9$_]*)\");\n// Parser regexs to check validity\nconst regexId = new RegExp(\"^([a-zA-Z$_][a-zA-Z0-9$_]*)$\");\nconst regexType = new RegExp(\"^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$\");\nclass TokenString {\n #offset;\n #tokens;\n get offset() { return this.#offset; }\n get length() { return this.#tokens.length - this.#offset; }\n constructor(tokens) {\n this.#offset = 0;\n this.#tokens = tokens.slice();\n }\n clone() { return new TokenString(this.#tokens); }\n reset() { this.#offset = 0; }\n #subTokenString(from = 0, to = 0) {\n return new TokenString(this.#tokens.slice(from, to).map((t) => {\n return Object.freeze(Object.assign({}, t, {\n match: (t.match - from),\n linkBack: (t.linkBack - from),\n linkNext: (t.linkNext - from),\n }));\n }));\n }\n // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens\n popKeyword(allowed) {\n const top = this.peek();\n if (top.type !== \"KEYWORD\" || !allowed.has(top.text)) {\n throw new Error(`expected keyword ${top.text}`);\n }\n return this.pop().text;\n }\n // Pops and returns the value of the next token if it is `type`; throws if out of tokens\n popType(type) {\n if (this.peek().type !== type) {\n const top = this.peek();\n throw new Error(`expected ${type}; got ${top.type} ${JSON.stringify(top.text)}`);\n }\n return this.pop().text;\n }\n // Pops and returns a \"(\" TOKENS \")\"\n popParen() {\n const top = this.peek();\n if (top.type !== \"OPEN_PAREN\") {\n throw new Error(\"bad start\");\n }\n const result = this.#subTokenString(this.#offset + 1, top.match + 1);\n this.#offset = top.match + 1;\n return result;\n }\n // Pops and returns the items within \"(\" ITEM1 \",\" ITEM2 \",\" ... \")\"\n popParams() {\n const top = this.peek();\n if (top.type !== \"OPEN_PAREN\") {\n throw new Error(\"bad start\");\n }\n const result = [];\n while (this.#offset < top.match - 1) {\n const link = this.peek().linkNext;\n result.push(this.#subTokenString(this.#offset + 1, link));\n this.#offset = link;\n }\n this.#offset = top.match + 1;\n return result;\n }\n // Returns the top Token, throwing if out of tokens\n peek() {\n if (this.#offset >= this.#tokens.length) {\n throw new Error(\"out-of-bounds\");\n }\n return this.#tokens[this.#offset];\n }\n // Returns the next value, if it is a keyword in `allowed`\n peekKeyword(allowed) {\n const top = this.peekType(\"KEYWORD\");\n return (top != null && allowed.has(top)) ? top : null;\n }\n // Returns the value of the next token if it is `type`\n peekType(type) {\n if (this.length === 0) {\n return null;\n }\n const top = this.peek();\n return (top.type === type) ? top.text : null;\n }\n // Returns the next token; throws if out of tokens\n pop() {\n const result = this.peek();\n this.#offset++;\n return result;\n }\n toString() {\n const tokens = [];\n for (let i = this.#offset; i < this.#tokens.length; i++) {\n const token = this.#tokens[i];\n tokens.push(`${token.type}:${token.text}`);\n }\n return `<TokenString ${tokens.join(\" \")}>`;\n }\n}\nfunction lex(text) {\n const tokens = [];\n const throwError = (message) => {\n const token = (offset < text.length) ? JSON.stringify(text[offset]) : \"$EOI\";\n throw new Error(`invalid token ${token} at ${offset}: ${message}`);\n };\n let brackets = [];\n let commas = [];\n let offset = 0;\n while (offset < text.length) {\n // Strip off any leading whitespace\n let cur = text.substring(offset);\n let match = cur.match(regexWhitespacePrefix);\n if (match) {\n offset += match[1].length;\n cur = text.substring(offset);\n }\n const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: \"\", text: \"\", offset, value: -1 };\n tokens.push(token);\n let type = (SimpleTokens[cur[0]] || \"\");\n if (type) {\n token.type = type;\n token.text = cur[0];\n offset++;\n if (type === \"OPEN_PAREN\") {\n brackets.push(tokens.length - 1);\n commas.push(tokens.length - 1);\n }\n else if (type == \"CLOSE_PAREN\") {\n if (brackets.length === 0) {\n throwError(\"no matching open bracket\");\n }\n token.match = brackets.pop();\n (tokens[token.match]).match = tokens.length - 1;\n token.depth--;\n token.linkBack = commas.pop();\n (tokens[token.linkBack]).linkNext = tokens.length - 1;\n }\n else if (type === \"COMMA\") {\n token.linkBack = commas.pop();\n (tokens[token.linkBack]).linkNext = tokens.length - 1;\n commas.push(tokens.length - 1);\n }\n else if (type === \"OPEN_BRACKET\") {\n token.type = \"BRACKET\";\n }\n else if (type === \"CLOSE_BRACKET\") {\n // Remove the CLOSE_BRACKET\n let suffix = tokens.pop().text;\n if (tokens.length > 0 && tokens[tokens.length - 1].type === \"NUMBER\") {\n const value = tokens.pop().text;\n suffix = value + suffix;\n (tokens[tokens.length - 1]).value = getNumber(value);\n }\n if (tokens.length === 0 || tokens[tokens.length - 1].type !== \"BRACKET\") {\n throw new Error(\"missing opening bracket\");\n }\n (tokens[tokens.length - 1]).text += suffix;\n }\n continue;\n }\n match = cur.match(regexIdPrefix);\n if (match) {\n token.text = match[1];\n offset += token.text.length;\n if (Keywords.has(token.text)) {\n token.type = \"KEYWORD\";\n continue;\n }\n if (token.text.match(regexType)) {\n token.type = \"TYPE\";\n continue;\n }\n token.type = \"ID\";\n continue;\n }\n match = cur.match(regexNumberPrefix);\n if (match) {\n token.text = match[1];\n token.type = \"NUMBER\";\n offset += token.text.length;\n continue;\n }\n throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`);\n }\n return new TokenString(tokens.map((t) => Object.freeze(t)));\n}\n// Check only one of `allowed` is in `set`\nfunction allowSingle(set, allowed) {\n let included = [];\n for (const key in allowed.keys()) {\n if (set.has(key)) {\n included.push(key);\n }\n }\n if (included.length > 1) {\n throw new Error(`conflicting types: ${included.join(\", \")}`);\n }\n}\n// Functions to process a Solidity Signature TokenString from left-to-right for...\n// ...the name with an optional type, returning the name\nfunction consumeName(type, tokens) {\n if (tokens.peekKeyword(KwTypes)) {\n const keyword = tokens.pop().text;\n if (keyword !== type) {\n throw new Error(`expected ${type}, got ${keyword}`);\n }\n }\n return tokens.popType(\"ID\");\n}\n// ...all keywords matching allowed, returning the keywords\nfunction consumeKeywords(tokens, allowed) {\n const keywords = new Set();\n while (true) {\n const keyword = tokens.peekType(\"KEYWORD\");\n if (keyword == null || (allowed && !allowed.has(keyword))) {\n break;\n }\n tokens.pop();\n if (keywords.has(keyword)) {\n throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`);\n }\n keywords.add(keyword);\n }\n return Object.freeze(keywords);\n}\n// ...all visibility keywords, returning the coalesced mutability\nfunction consumeMutability(tokens) {\n let modifiers = consumeKeywords(tokens, KwVisib);\n // Detect conflicting modifiers\n allowSingle(modifiers, setify(\"constant payable nonpayable\".split(\" \")));\n allowSingle(modifiers, setify(\"pure view payable nonpayable\".split(\" \")));\n // Process mutability states\n if (modifiers.has(\"view\")) {\n return \"view\";\n }\n if (modifiers.has(\"pure\")) {\n return \"pure\";\n }\n if (modifiers.has(\"payable\")) {\n return \"payable\";\n }\n if (modifiers.has(\"nonpayable\")) {\n return \"nonpayable\";\n }\n // Process legacy `constant` last\n if (modifiers.has(\"constant\")) {\n return \"view\";\n }\n return \"nonpayable\";\n}\n// ...a parameter list, returning the ParamType list\nfunction consumeParams(tokens, allowIndexed) {\n return tokens.popParams().map((t) => ParamType.from(t, allowIndexed));\n}\n// ...a gas limit, returning a BigNumber or null if none\nfunction consumeGas(tokens) {\n if (tokens.peekType(\"AT\")) {\n tokens.pop();\n if (tokens.peekType(\"NUMBER\")) {\n return getBigInt(tokens.pop().text);\n }\n throw new Error(\"invalid gas\");\n }\n return null;\n}\nfunction consumeEoi(tokens) {\n if (tokens.length) {\n throw new Error(`unexpected tokens at offset ${tokens.offset}: ${tokens.toString()}`);\n }\n}\nconst regexArrayType = new RegExp(/^(.*)\\[([0-9]*)\\]$/);\nfunction verifyBasicType(type) {\n const match = type.match(regexType);\n assertArgument(match, \"invalid type\", \"type\", type);\n if (type === \"uint\") {\n return \"uint256\";\n }\n if (type === \"int\") {\n return \"int256\";\n }\n if (match[2]) {\n // bytesXX\n const length = parseInt(match[2]);\n assertArgument(length !== 0 && length <= 32, \"invalid bytes length\", \"type\", type);\n }\n else if (match[3]) {\n // intXX or uintXX\n const size = parseInt(match[3]);\n assertArgument(size !== 0 && size <= 256 && (size % 8) === 0, \"invalid numeric width\", \"type\", type);\n }\n return type;\n}\n// Make the Fragment constructors effectively private\nconst _guard = {};\nconst internal = Symbol.for(\"_ethers_internal\");\nconst ParamTypeInternal = \"_ParamTypeInternal\";\nconst ErrorFragmentInternal = \"_ErrorInternal\";\nconst EventFragmentInternal = \"_EventInternal\";\nconst ConstructorFragmentInternal = \"_ConstructorInternal\";\nconst FallbackFragmentInternal = \"_FallbackInternal\";\nconst FunctionFragmentInternal = \"_FunctionInternal\";\nconst StructFragmentInternal = \"_StructInternal\";\n/**\n * Each input and output of a [[Fragment]] is an Array of **ParamType**.\n */\nexport class ParamType {\n /**\n * The local name of the parameter (or ``\"\"`` if unbound)\n */\n name;\n /**\n * The fully qualified type (e.g. ``\"address\"``, ``\"tuple(address)\"``,\n * ``\"uint256[3][]\"``)\n */\n type;\n /**\n * The base type (e.g. ``\"address\"``, ``\"tuple\"``, ``\"array\"``)\n */\n baseType;\n /**\n * True if the parameters is indexed.\n *\n * For non-indexable types this is ``null``.\n */\n indexed;\n /**\n * The components for the tuple.\n *\n * For non-tuple types this is ``null``.\n */\n components;\n /**\n * The array length, or ``-1`` for dynamic-lengthed arrays.\n *\n * For non-array types this is ``null``.\n */\n arrayLength;\n /**\n * The type of each child in the array.\n *\n * For non-array types this is ``null``.\n */\n arrayChildren;\n /**\n * @private\n */\n constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren) {\n assertPrivate(guard, _guard, \"ParamType\");\n Object.defineProperty(this, internal, { value: ParamTypeInternal });\n if (components) {\n components = Object.freeze(components.slice());\n }\n if (baseType === \"array\") {\n if (arrayLength == null || arrayChildren == null) {\n throw new Error(\"\");\n }\n }\n else if (arrayLength != null || arrayChildren != null) {\n throw new Error(\"\");\n }\n if (baseType === \"tuple\") {\n if (components == null) {\n throw new Error(\"\");\n }\n }\n else if (components != null) {\n throw new Error(\"\");\n }\n defineProperties(this, {\n name, type, baseType, indexed, components, arrayLength, arrayChildren\n });\n }\n /**\n * Return a string representation of this type.\n *\n * For example,\n *\n * ``sighash\" => \"(uint256,address)\"``\n *\n * ``\"minimal\" => \"tuple(uint256,address) indexed\"``\n *\n * ``\"full\" => \"tuple(uint256 foo, address bar) indexed baz\"``\n */\n format(format) {\n if (format == null) {\n format = \"sighash\";\n }\n if (format === \"json\") {\n const name = this.name || \"\";\n if (this.isArray()) {\n const result = JSON.parse(this.arrayChildren.format(\"json\"));\n result.name = name;\n result.type += `[${(this.arrayLength < 0 ? \"\" : String(this.arrayLength))}]`;\n return JSON.stringify(result);\n }\n const result = {\n type: ((this.baseType === \"tuple\") ? \"tuple\" : this.type),\n name\n };\n if (typeof (this.indexed) === \"boolean\") {\n result.indexed = this.indexed;\n }\n if (this.isTuple()) {\n result.components = this.components.map((c) => JSON.parse(c.format(format)));\n }\n return JSON.stringify(result);\n }\n let result = \"\";\n // Array\n if (this.isArray()) {\n result += this.arrayChildren.format(format);\n result += `[${(this.arrayLength < 0 ? \"\" : String(this.arrayLength))}]`;\n }\n else {\n if (this.isTuple()) {\n result += \"(\" + this.components.map((comp) => comp.format(format)).join((format === \"full\") ? \", \" : \",\") + \")\";\n }\n else {\n result += this.type;\n }\n }\n if (format !== \"sighash\") {\n if (this.indexed === true) {\n result += \" indexed\";\n }\n if (format === \"full\" && this.name) {\n result += \" \" + this.name;\n }\n }\n return result;\n }\n /**\n * Returns true if %%this%% is an Array type.\n *\n * This provides a type gaurd ensuring that [[arrayChildren]]\n * and [[arrayLength]] are non-null.\n */\n isArray() {\n return (this.baseType === \"array\");\n }\n /**\n * Returns true if %%this%% is a Tuple type.\n *\n * This provides a type gaurd ensuring that [[components]]\n * is non-null.\n */\n isTuple() {\n return (this.baseType === \"tuple\");\n }\n /**\n * Returns true if %%this%% is an Indexable type.\n *\n * This provides a type gaurd ensuring that [[indexed]]\n * is non-null.\n */\n isIndexable() {\n return (this.indexed != null);\n }\n /**\n * Walks the **ParamType** with %%value%%, calling %%process%%\n * on each type, destructing the %%value%% recursively.\n */\n walk(value, process) {\n if (this.isArray()) {\n if (!Array.isArray(value)) {\n throw new Error(\"invalid array value\");\n }\n if (this.arrayLength !== -1 && value.length !== this.arrayLength) {\n throw new Error(\"array is wrong length\");\n }\n const _this = this;\n return value.map((v) => (_this.arrayChildren.walk(v, process)));\n }\n if (this.isTuple()) {\n if (!Array.isArray(value)) {\n throw new Error(\"invalid tuple value\");\n }\n if (value.length !== this.components.length) {\n throw new Error(\"array is wrong length\");\n }\n const _this = this;\n return value.map((v, i) => (_this.components[i].walk(v, process)));\n }\n return process(this.type, value);\n }\n #walkAsync(promises, value, process, setValue) {\n if (this.isArray()) {\n if (!Array.isArray(value)) {\n throw new Error(\"invalid array value\");\n }\n if (this.arrayLength !== -1 && value.length !== this.arrayLength) {\n throw new Error(\"array is wrong length\");\n }\n const childType = this.arrayChildren;\n const result = value.slice();\n result.forEach((value, index) => {\n childType.#walkAsync(promises, value, process, (value) => {\n result[index] = value;\n });\n });\n setValue(result);\n return;\n }\n if (this.isTuple()) {\n const components = this.components;\n // Convert the object into an array\n let result;\n if (Array.isArray(value)) {\n result = value.slice();\n }\n else {\n if (value == null || typeof (value) !== \"object\") {\n throw new Error(\"invalid tuple value\");\n }\n result = components.map((param) => {\n if (!param.name) {\n throw new Error(\"cannot use object value with unnamed components\");\n }\n if (!(param.name in value)) {\n throw new Error(`missing value for component ${param.name}`);\n }\n return value[param.name];\n });\n }\n if (result.length !== this.components.length) {\n throw new Error(\"array is wrong length\");\n }\n result.forEach((value, index) => {\n components[index].#walkAsync(promises, value, process, (value) => {\n result[index] = value;\n });\n });\n setValue(result);\n return;\n }\n const result = process(this.type, value);\n if (result.then) {\n promises.push((async function () { setValue(await result); })());\n }\n else {\n setValue(result);\n }\n }\n /**\n * Walks the **ParamType** with %%value%%, asynchronously calling\n * %%process%% on each type, destructing the %%value%% recursively.\n *\n * This can be used to resolve ENS names by walking and resolving each\n * ``\"address\"`` type.\n */\n async walkAsync(value, process) {\n const promises = [];\n const result = [value];\n this.#walkAsync(promises, value, process, (value) => {\n result[0] = value;\n });\n if (promises.length) {\n await Promise.all(promises);\n }\n return result[0];\n }\n /**\n * Creates a new **ParamType** for %%obj%%.\n *\n * If %%allowIndexed%% then the ``indexed`` keyword is permitted,\n * otherwise the ``indexed`` keyword will throw an error.\n */\n static from(obj, allowIndexed) {\n if (ParamType.isParamType(obj)) {\n return obj;\n }\n if (typeof (obj) === \"string\") {\n try {\n return ParamType.from(lex(obj), allowIndexed);\n }\n catch (error) {\n assertArgument(false, \"invalid param type\", \"obj\", obj);\n }\n }\n else if (obj instanceof TokenString) {\n let type = \"\", baseType = \"\";\n let comps = null;\n if (consumeKeywords(obj, setify([\"tuple\"])).has(\"tuple\") || obj.peekType(\"OPEN_PAREN\")) {\n // Tuple\n baseType = \"tuple\";\n comps = obj.popParams().map((t) => ParamType.from(t));\n type = `tuple(${comps.map((c) => c.format()).join(\",\")})`;\n }\n else {\n // Normal\n type = verifyBasicType(obj.popType(\"TYPE\"));\n baseType = type;\n }\n // Check for Array\n let arrayChildren = null;\n let arrayLength = null;\n while (obj.length && obj.peekType(\"BRACKET\")) {\n const bracket = obj.pop(); //arrays[i];\n arrayChildren = new ParamType(_guard, \"\", type, baseType, null, comps, arrayLength, arrayChildren);\n arrayLength = bracket.value;\n type += bracket.text;\n baseType = \"array\";\n comps = null;\n }\n let indexed = null;\n const keywords = consumeKeywords(obj, KwModifiers);\n if (keywords.has(\"indexed\")) {\n if (!allowIndexed) {\n throw new Error(\"\");\n }\n indexed = true;\n }\n const name = (obj.peekType(\"ID\") ? obj.pop().text : \"\");\n if (obj.length) {\n throw new Error(\"leftover tokens\");\n }\n return new ParamType(_guard, name, type, baseType, indexed, comps, arrayLength, arrayChildren);\n }\n const name = obj.name;\n assertArgument(!name || (typeof (name) === \"string\" && name.match(regexId)), \"invalid name\", \"obj.name\", name);\n let indexed = obj.indexed;\n if (indexed != null) {\n assertArgument(allowIndexed, \"parameter cannot be indexed\", \"obj.indexed\", obj.indexed);\n indexed = !!indexed;\n }\n let type = obj.type;\n let arrayMatch = type.match(regexArrayType);\n if (arrayMatch) {\n const arrayLength = parseInt(arrayMatch[2] || \"-1\");\n const arrayChildren = ParamType.from({\n type: arrayMatch[1],\n components: obj.components\n });\n return new ParamType(_guard, name || \"\", type, \"array\", indexed, null, arrayLength, arrayChildren);\n }\n if (type === \"tuple\" || type.startsWith(\"tuple(\" /* fix: ) */) || type.startsWith(\"(\" /* fix: ) */)) {\n const comps = (obj.components != null) ? obj.components.map((c) => ParamType.from(c)) : null;\n const tuple = new ParamType(_guard, name || \"\", type, \"tuple\", indexed, comps, null, null);\n // @TODO: use lexer to validate and normalize type\n return tuple;\n }\n type = verifyBasicType(obj.type);\n return new ParamType(_guard, name || \"\", type, type, indexed, null, null, null);\n }\n /**\n * Returns true if %%value%% is a **ParamType**.\n */\n static isParamType(value) {\n return (value && value[internal] === ParamTypeInternal);\n }\n}\n/**\n * An abstract class to represent An individual fragment from a parse ABI.\n */\nexport class Fragment {\n /**\n * The type of the fragment.\n */\n type;\n /**\n * The inputs for the fragment.\n */\n inputs;\n /**\n * @private\n */\n constructor(guard, type, inputs) {\n assertPrivate(guard, _guard, \"Fragment\");\n inputs = Object.freeze(inputs.slice());\n defineProperties(this, { type, inputs });\n }\n /**\n * Creates a new **Fragment** for %%obj%%, wich can be any supported\n * ABI frgament type.\n */\n static from(obj) {\n if (typeof (obj) === \"string\") {\n // Try parsing JSON...\n try {\n Fragment.from(JSON.parse(obj));\n }\n catch (e) { }\n // ...otherwise, use the human-readable lexer\n return Fragment.from(lex(obj));\n }\n if (obj instanceof TokenString) {\n // Human-readable ABI (already lexed)\n const type = obj.peekKeyword(KwTypes);\n switch (type) {\n case \"constructor\": return ConstructorFragment.from(obj);\n case \"error\": return ErrorFragment.from(obj);\n case \"event\": return EventFragment.from(obj);\n case \"fallback\":\n case \"receive\":\n return FallbackFragment.from(obj);\n case \"function\": return FunctionFragment.from(obj);\n case \"struct\": return StructFragment.from(obj);\n }\n }\n else if (typeof (obj) === \"object\") {\n // JSON ABI\n switch (obj.type) {\n case \"constructor\": return ConstructorFragment.from(obj);\n case \"error\": return ErrorFragment.from(obj);\n case \"event\": return EventFragment.from(obj);\n case \"fallback\":\n case \"receive\":\n return FallbackFragment.from(obj);\n case \"function\": return FunctionFragment.from(obj);\n case \"struct\": return StructFragment.from(obj);\n }\n assert(false, `unsupported type: ${obj.type}`, \"UNSUPPORTED_OPERATION\", {\n operation: \"Fragment.from\"\n });\n }\n assertArgument(false, \"unsupported frgament object\", \"obj\", obj);\n }\n /**\n * Returns true if %%value%% is a [[ConstructorFragment]].\n */\n static isConstructor(value) {\n return ConstructorFragment.isFragment(value);\n }\n /**\n * Returns true if %%value%% is an [[ErrorFragment]].\n */\n static isError(value) {\n return ErrorFragment.isFragment(value);\n }\n /**\n * Returns true if %%value%% is an [[EventFragment]].\n */\n static isEvent(value) {\n return EventFragment.isFragment(value);\n }\n /**\n * Returns true if %%value%% is a [[FunctionFragment]].\n */\n static isFunction(value) {\n return FunctionFragment.isFragment(value);\n }\n /**\n * Returns true if %%value%% is a [[StructFragment]].\n */\n static isStruct(value) {\n return StructFragment.isFragment(value);\n }\n}\n/**\n * An abstract class to represent An individual fragment\n * which has a name from a parse ABI.\n */\nexport class NamedFragment extends Fragment {\n /**\n * The name of the fragment.\n */\n name;\n /**\n * @private\n */\n constructor(guard, type, name, inputs) {\n super(guard, type, inputs);\n assertArgument(typeof (name) === \"string\" && name.match(regexId), \"invalid identifier\", \"name\", name);\n inputs = Object.freeze(inputs.slice());\n defineProperties(this, { name });\n }\n}\nfunction joinParams(format, params) {\n return \"(\" + params.map((p) => p.format(format)).join((format === \"full\") ? \", \" : \",\") + \")\";\n}\n/**\n * A Fragment which represents a //Custom Error//.\n */\nexport class ErrorFragment extends NamedFragment {\n /**\n * @private\n */\n constructor(guard, name, inputs) {\n super(guard, \"error\", name, inputs);\n Object.defineProperty(this, internal, { value: ErrorFragmentInternal });\n }\n /**\n * The Custom Error selector.\n */\n get selector() {\n return id(this.format(\"sighash\")).substring(0, 10);\n }\n /**\n * Returns a string representation of this fragment as %%format%%.\n */\n format(format) {\n if (format == null) {\n format = \"sighash\";\n }\n if (format === \"json\") {\n return JSON.stringify({\n type: \"error\",\n name: this.name,\n inputs: this.inputs.map((input) => JSON.parse(input.format(format))),\n });\n }\n const result = [];\n if (format !== \"sighash\") {\n result.push(\"error\");\n }\n result.push(this.name + joinParams(format, this.inputs));\n return result.join(\" \");\n }\n /**\n * Returns a new **ErrorFragment** for %%obj%%.\n */\n static from(obj) {\n if (ErrorFragment.isFragment(obj)) {\n return obj;\n }\n if (typeof (obj) === \"string\") {\n return ErrorFragment.from(lex(obj));\n }\n else if (obj instanceof TokenString) {\n const name = consumeName(\"error\", obj);\n const inputs = consumeParams(obj);\n consumeEoi(obj);\n return new ErrorFragment(_guard, name, inputs);\n }\n return new ErrorFragment(_guard, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []);\n }\n /**\n * Returns ``true`` and provides a type guard if %%value%% is an\n * **ErrorFragment**.\n */\n static isFragment(value) {\n return (value && value[internal] === ErrorFragmentInternal);\n }\n}\n/**\n * A Fragment which represents an Event.\n */\nexport class EventFragment extends NamedFragment {\n /**\n * Whether this event is anonymous.\n */\n anonymous;\n /**\n * @private\n */\n constructor(guard, name, inputs, anonymous) {\n super(guard, \"event\", name, inputs);\n Object.defineProperty(this, internal, { value: EventFragmentInternal });\n defineProperties(this, { anonymous });\n }\n /**\n * The Event topic hash.\n */\n get topicHash() {\n return id(this.format(\"sighash\"));\n }\n /**\n * Returns a string representation of this event as %%format%%.\n */\n format(format) {\n if (format == null) {\n format = \"sighash\";\n }\n if (format === \"json\") {\n return JSON.stringify({\n type: \"event\",\n anonymous: this.anonymous,\n name: this.name,\n inputs: this.inputs.map((i) => JSON.parse(i.format(format)))\n });\n }\n const result = [];\n if (format !== \"sighash\") {\n result.push(\"event\");\n }\n result.push(this.name + joinParams(format, this.inputs));\n if (format !== \"sighash\" && this.anonymous) {\n result.push(\"anonymous\");\n }\n return result.join(\" \");\n }\n /**\n * Return the topic hash for an event with %%name%% and %%params%%.\n */\n static getTopicHash(name, params) {\n params = (params || []).map((p) => ParamType.from(p));\n const fragment = new EventFragment(_guard, name, params, false);\n return fragment.topicHash;\n }\n /**\n * Returns a new **EventFragment** for %%obj%%.\n */\n static from(obj) {\n if (EventFragment.isFragment(obj)) {\n return obj;\n }\n if (typeof (obj) === \"string\") {\n try {\n return EventFragment.from(lex(obj));\n }\n catch (error) {\n assertArgument(false, \"invalid event fragment\", \"obj\", obj);\n }\n }\n else if (obj instanceof TokenString) {\n const name = consumeName(\"event\", obj);\n const inputs = consumeParams(obj, true);\n const anonymous = !!consumeKeywords(obj, setify([\"anonymous\"])).has(\"anonymous\");\n consumeEoi(obj);\n return new EventFragment(_guard, name, inputs, anonymous);\n }\n return new EventFragment(_guard, obj.name, obj.inputs ? obj.inputs.map((p) => ParamType.from(p, true)) : [], !!obj.anonymous);\n }\n /**\n * Returns ``true`` and provides a type guard if %%value%% is an\n * **EventFragment**.\n */\n static isFragment(value) {\n return (value && value[internal] === EventFragmentInternal);\n }\n}\n/**\n * A Fragment which represents a constructor.\n */\nexport class ConstructorFragment extends Fragment {\n /**\n * Whether the constructor can receive an endowment.\n */\n payable;\n /**\n * The recommended gas limit for deployment or ``null``.\n */\n gas;\n /**\n * @private\n */\n constructor(guard, type, inputs, payable, gas) {\n super(guard, type, inputs);\n Object.defineProperty(this, internal, { value: ConstructorFragmentInternal });\n defineProperties(this, { payable, gas });\n }\n /**\n * Returns a string representation of this constructor as %%format%%.\n */\n format(format) {\n assert(format != null && format !== \"sighash\", \"cannot format a constructor for sighash\", \"UNSUPPORTED_OPERATION\", { operation: \"format(sighash)\" });\n if (format === \"json\") {\n return JSON.stringify({\n type: \"constructor\",\n stateMutability: (this.payable ? \"payable\" : \"undefined\"),\n payable: this.payable,\n gas: ((this.gas != null) ? this.gas : undefined),\n inputs: this.inputs.map((i) => JSON.parse(i.format(format)))\n });\n }\n const result = [`constructor${joinParams(format, this.inputs)}`];\n if (this.payable) {\n result.push(\"payable\");\n }\n if (this.gas != null) {\n result.push(`@${this.gas.toString()}`);\n }\n return result.join(\" \");\n }\n /**\n * Returns a new **ConstructorFragment** for %%obj%%.\n */\n static from(obj) {\n if (ConstructorFragment.isFragment(obj)) {\n return obj;\n }\n if (typeof (obj) === \"string\") {\n try {\n return ConstructorFragment.from(lex(obj));\n }\n catch (error) {\n assertArgument(false, \"invalid constuctor fragment\", \"obj\", obj);\n }\n }\n else if (obj instanceof TokenString) {\n consumeKeywords(obj, setify([\"constructor\"]));\n const inputs = consumeParams(obj);\n const payable = !!consumeKeywords(obj, KwVisibDeploy).has(\"payable\");\n const gas = consumeGas(obj);\n consumeEoi(obj);\n return new ConstructorFragment(_guard, \"constructor\", inputs, payable, gas);\n }\n return new ConstructorFragment(_guard, \"constructor\", obj.inputs ? obj.inputs.map(ParamType.from) : [], !!obj.payable, (obj.gas != null) ? obj.gas : null);\n }\n /**\n * Returns ``true`` and provides a type guard if %%value%% is a\n * **ConstructorFragment**.\n */\n static isFragment(value) {\n return (value && value[internal] === ConstructorFragmentInternal);\n }\n}\n/**\n * A Fragment which represents a method.\n */\nexport class FallbackFragment extends Fragment {\n /**\n * If the function can be sent value during invocation.\n */\n payable;\n constructor(guard, inputs, payable) {\n super(guard, \"fallback\", inputs);\n Object.defineProperty(this, internal, { value: FallbackFragmentInternal });\n defineProperties(this, { payable });\n }\n /**\n * Returns a string representation of this fallback as %%format%%.\n */\n format(format) {\n const type = ((this.inputs.length === 0) ? \"receive\" : \"fallback\");\n if (format === \"json\") {\n const stateMutability = (this.payable ? \"payable\" : \"nonpayable\");\n return JSON.stringify({ type, stateMutability });\n }\n return `${type}()${this.payable ? \" payable\" : \"\"}`;\n }\n /**\n * Returns a new **FallbackFragment** for %%obj%%.\n */\n static from(obj) {\n if (FallbackFragment.isFragment(obj)) {\n return obj;\n }\n if (typeof (obj) === \"string\") {\n try {\n return FallbackFragment.from(lex(obj));\n }\n catch (error) {\n assertArgument(false, \"invalid fallback fragment\", \"obj\", obj);\n }\n }\n else if (obj instanceof TokenString) {\n const errorObj = obj.toString();\n const topIsValid = obj.peekKeyword(setify([\"fallback\", \"receive\"]));\n assertArgument(topIsValid, \"type must be fallback or receive\", \"obj\", errorObj);\n const type = obj.popKeyword(setify([\"fallback\", \"receive\"]));\n // receive()\n if (type === \"receive\") {\n const inputs = consumeParams(obj);\n assertArgument(inputs.length === 0, `receive cannot have arguments`, \"obj.inputs\", inputs);\n consumeKeywords(obj, setify([\"payable\"]));\n consumeEoi(obj);\n return new FallbackFragment(_guard, [], true);\n }\n // fallback() [payable]\n // fallback(bytes) [payable] returns (bytes)\n let inputs = consumeParams(obj);\n if (inputs.length) {\n assertArgument(inputs.length === 1 && inputs[0].type === \"bytes\", \"invalid fallback inputs\", \"obj.inputs\", inputs.map((i) => i.format(\"minimal\")).join(\", \"));\n }\n else {\n inputs = [ParamType.from(\"bytes\")];\n }\n const mutability = consumeMutability(obj);\n assertArgument(mutability === \"nonpayable\" || mutability === \"payable\", \"fallback cannot be constants\", \"obj.stateMutability\", mutability);\n if (consumeKeywords(obj, setify([\"returns\"])).has(\"returns\")) {\n const outputs = consumeParams(obj);\n assertArgument(outputs.length === 1 && outputs[0].type === \"bytes\", \"invalid fallback outputs\", \"obj.outputs\", outputs.map((i) => i.format(\"minimal\")).join(\", \"));\n }\n consumeEoi(obj);\n return new FallbackFragment(_guard, inputs, mutability === \"payable\");\n }\n if (obj.type === \"receive\") {\n return new FallbackFragment(_guard, [], true);\n }\n if (obj.type === \"fallback\") {\n const inputs = [ParamType.from(\"bytes\")];\n const payable = (obj.stateMutability === \"payable\");\n return new FallbackFragment(_guard, inputs, payable);\n }\n assertArgument(false, \"invalid fallback description\", \"obj\", obj);\n }\n /**\n * Returns ``true`` and provides a type guard if %%value%% is a\n * **FallbackFragment**.\n */\n static isFragment(value) {\n return (value && value[internal] === FallbackFragmentInternal);\n }\n}\n/**\n * A Fragment which represents a method.\n */\nexport class FunctionFragment extends NamedFragment {\n /**\n * If the function is constant (e.g. ``pure`` or ``view`` functions).\n */\n constant;\n /**\n * The returned types for the result of calling this function.\n */\n outputs;\n /**\n * The state mutability (e.g. ``payable``, ``nonpayable``, ``view``\n * or ``pure``)\n */\n stateMutability;\n /**\n * If the function can be sent value during invocation.\n */\n payable;\n /**\n * The recommended gas limit to send when calling this function.\n */\n gas;\n /**\n * @private\n */\n constructor(guard, name, stateMutability, inputs, outputs, gas) {\n super(guard, \"function\", name, inputs);\n Object.defineProperty(this, internal, { value: FunctionFragmentInternal });\n outputs = Object.freeze(outputs.slice());\n const constant = (stateMutability === \"view\" || stateMutability === \"pure\");\n const payable = (stateMutability === \"payable\");\n defineProperties(this, { constant, gas, outputs, payable, stateMutability });\n }\n /**\n * The Function selector.\n */\n get selector() {\n return id(this.format(\"sighash\")).substring(0, 10);\n }\n /**\n * Returns a string representation of this function as %%format%%.\n */\n format(format) {\n if (format == null) {\n format = \"sighash\";\n }\n if (format === \"json\") {\n return JSON.stringify({\n type: \"function\",\n name: this.name,\n constant: this.constant,\n stateMutability: ((this.stateMutability !== \"nonpayable\") ? this.stateMutability : undefined),\n payable: this.payable,\n gas: ((this.gas != null) ? this.gas : undefined),\n inputs: this.inputs.map((i) => JSON.parse(i.format(format))),\n outputs: this.outputs.map((o) => JSON.parse(o.format(format))),\n });\n }\n const result = [];\n if (format !== \"sighash\") {\n result.push(\"function\");\n }\n result.push(this.name + joinParams(format, this.inputs));\n if (format !== \"sighash\") {\n if (this.stateMutability !== \"nonpayable\") {\n result.push(this.stateMutability);\n }\n if (this.outputs && this.outputs.length) {\n result.push(\"returns\");\n result.push(joinParams(format, this.outputs));\n }\n if (this.gas != null) {\n result.push(`@${this.gas.toString()}`);\n }\n }\n return result.join(\" \");\n }\n /**\n * Return the selector for a function with %%name%% and %%params%%.\n */\n static getSelector(name, params) {\n params = (params || []).map((p) => ParamType.from(p));\n const fragment = new FunctionFragment(_guard, name, \"view\", params, [], null);\n return fragment.selector;\n }\n /**\n * Returns a new **FunctionFragment** for %%obj%%.\n */\n static from(obj) {\n if (FunctionFragment.isFragment(obj)) {\n return obj;\n }\n if (typeof (obj) === \"string\") {\n try {\n return FunctionFragment.from(lex(obj));\n }\n catch (error) {\n assertArgument(false, \"invalid function fragment\", \"obj\", obj);\n }\n }\n else if (obj instanceof TokenString) {\n const name = consumeName(\"function\", obj);\n const inputs = consumeParams(obj);\n const mutability = consumeMutability(obj);\n let outputs = [];\n if (consumeKeywords(obj, setify([\"returns\"])).has(\"returns\")) {\n outputs = consumeParams(obj);\n }\n const gas = consumeGas(obj);\n consumeEoi(obj);\n return new FunctionFragment(_guard, name, mutability, inputs, outputs, gas);\n }\n let stateMutability = obj.stateMutability;\n // Use legacy Solidity ABI logic if stateMutability is missing\n if (stateMutability == null) {\n stateMutability = \"payable\";\n if (typeof (obj.constant) === \"boolean\") {\n stateMutability = \"view\";\n if (!obj.constant) {\n stateMutability = \"payable\";\n if (typeof (obj.payable) === \"boolean\" && !obj.payable) {\n stateMutability = \"nonpayable\";\n }\n }\n }\n else if (typeof (obj.payable) === \"boolean\" && !obj.payable) {\n stateMutability = \"nonpayable\";\n }\n }\n // @TODO: verifyState for stateMutability (e.g. throw if\n // payable: false but stateMutability is \"nonpayable\")\n return new FunctionFragment(_guard, obj.name, stateMutability, obj.inputs ? obj.inputs.map(ParamType.from) : [], obj.outputs ? obj.outputs.map(ParamType.from) : [], (obj.gas != null) ? obj.gas : null);\n }\n /**\n * Returns ``true`` and provides a type guard if %%value%% is a\n * **FunctionFragment**.\n */\n static isFragment(value) {\n return (value && value[internal] === FunctionFragmentInternal);\n }\n}\n/**\n * A Fragment which represents a structure.\n */\nexport class StructFragment extends NamedFragment {\n /**\n * @private\n */\n constructor(guard, name, inputs) {\n super(guard, \"struct\", name, inputs);\n Object.defineProperty(this, internal, { value: StructFragmentInternal });\n }\n /**\n * Returns a string representation of this struct as %%format%%.\n */\n format() {\n throw new Error(\"@TODO\");\n }\n /**\n * Returns a new **StructFragment** for %%obj%%.\n */\n static from(obj) {\n if (typeof (obj) === \"string\") {\n try {\n return StructFragment.from(lex(obj));\n }\n catch (error) {\n assertArgument(false, \"invalid struct fragment\", \"obj\", obj);\n }\n }\n else if (obj instanceof TokenString) {\n const name = consumeName(\"struct\", obj);\n const inputs = consumeParams(obj);\n consumeEoi(obj);\n return new StructFragment(_guard, name, inputs);\n }\n return new StructFragment(_guard, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []);\n }\n // @TODO: fix this return type\n /**\n * Returns ``true`` and provides a type guard if %%value%% is a\n * **StructFragment**.\n */\n static isFragment(value) {\n return (value && value[internal] === StructFragmentInternal);\n }\n}\n//# sourceMappingURL=fragments.js.map","/**\n * When sending values to or receiving values from a [[Contract]], the\n * data is generally encoded using the [ABI standard](link-solc-abi).\n *\n * The AbiCoder provides a utility to encode values to ABI data and\n * decode values from ABI data.\n *\n * Most of the time, developers should favour the [[Contract]] class,\n * which further abstracts a lot of the finer details of ABI data.\n *\n * @_section api/abi/abi-coder:ABI Encoding\n */\n// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI\nimport { assertArgumentCount, assertArgument } from \"../utils/index.js\";\nimport { Reader, Writer } from \"./coders/abstract-coder.js\";\nimport { AddressCoder } from \"./coders/address.js\";\nimport { ArrayCoder } from \"./coders/array.js\";\nimport { BooleanCoder } from \"./coders/boolean.js\";\nimport { BytesCoder } from \"./coders/bytes.js\";\nimport { FixedBytesCoder } from \"./coders/fixed-bytes.js\";\nimport { NullCoder } from \"./coders/null.js\";\nimport { NumberCoder } from \"./coders/number.js\";\nimport { StringCoder } from \"./coders/string.js\";\nimport { TupleCoder } from \"./coders/tuple.js\";\nimport { ParamType } from \"./fragments.js\";\nimport { getAddress } from \"../address/index.js\";\nimport { getBytes, hexlify, makeError } from \"../utils/index.js\";\n// https://docs.soliditylang.org/en/v0.8.17/control-structures.html\nconst PanicReasons = new Map();\nPanicReasons.set(0x00, \"GENERIC_PANIC\");\nPanicReasons.set(0x01, \"ASSERT_FALSE\");\nPanicReasons.set(0x11, \"OVERFLOW\");\nPanicReasons.set(0x12, \"DIVIDE_BY_ZERO\");\nPanicReasons.set(0x21, \"ENUM_RANGE_ERROR\");\nPanicReasons.set(0x22, \"BAD_STORAGE_DATA\");\nPanicReasons.set(0x31, \"STACK_UNDERFLOW\");\nPanicReasons.set(0x32, \"ARRAY_RANGE_ERROR\");\nPanicReasons.set(0x41, \"OUT_OF_MEMORY\");\nPanicReasons.set(0x51, \"UNINITIALIZED_FUNCTION_CALL\");\nconst paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);\nconst paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);\nlet defaultCoder = null;\nlet defaultMaxInflation = 1024;\nfunction getBuiltinCallException(action, tx, data, abiCoder) {\n let message = \"missing revert data\";\n let reason = null;\n const invocation = null;\n let revert = null;\n if (data) {\n message = \"execution reverted\";\n const bytes = getBytes(data);\n data = hexlify(data);\n if (bytes.length === 0) {\n message += \" (no data present; likely require(false) occurred\";\n reason = \"require(false)\";\n }\n else if (bytes.length % 32 !== 4) {\n message += \" (could not decode reason; invalid data length)\";\n }\n else if (hexlify(bytes.slice(0, 4)) === \"0x08c379a0\") {\n // Error(string)\n try {\n reason = abiCoder.decode([\"string\"], bytes.slice(4))[0];\n revert = {\n signature: \"Error(string)\",\n name: \"Error\",\n args: [reason]\n };\n message += `: ${JSON.stringify(reason)}`;\n }\n catch (error) {\n message += \" (could not decode reason; invalid string data)\";\n }\n }\n else if (hexlify(bytes.slice(0, 4)) === \"0x4e487b71\") {\n // Panic(uint256)\n try {\n const code = Number(abiCoder.decode([\"uint256\"], bytes.slice(4))[0]);\n revert = {\n signature: \"Panic(uint256)\",\n name: \"Panic\",\n args: [code]\n };\n reason = `Panic due to ${PanicReasons.get(code) || \"UNKNOWN\"}(${code})`;\n message += `: ${reason}`;\n }\n catch (error) {\n message += \" (could not decode panic code)\";\n }\n }\n else {\n message += \" (unknown custom error)\";\n }\n }\n const transaction = {\n to: (tx.to ? getAddress(tx.to) : null),\n data: (tx.data || \"0x\")\n };\n if (tx.from) {\n transaction.from = getAddress(tx.from);\n }\n return makeError(message, \"CALL_EXCEPTION\", {\n action, data, reason, transaction, invocation, revert\n });\n}\n/**\n * The **AbiCoder** is a low-level class responsible for encoding JavaScript\n * values into binary data and decoding binary data into JavaScript values.\n */\nexport class AbiCoder {\n #getCoder(param) {\n if (param.isArray()) {\n return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name);\n }\n if (param.isTuple()) {\n return new TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name);\n }\n switch (param.baseType) {\n case \"address\":\n return new AddressCoder(param.name);\n case \"bool\":\n return new BooleanCoder(param.name);\n case \"string\":\n return new StringCoder(param.name);\n case \"bytes\":\n return new BytesCoder(param.name);\n case \"\":\n return new NullCoder(param.name);\n }\n // u?int[0-9]*\n let match = param.type.match(paramTypeNumber);\n if (match) {\n let size = parseInt(match[2] || \"256\");\n assertArgument(size !== 0 && size <= 256 && (size % 8) === 0, \"invalid \" + match[1] + \" bit length\", \"param\", param);\n return new NumberCoder(size / 8, (match[1] === \"int\"), param.name);\n }\n // bytes[0-9]+\n match = param.type.match(paramTypeBytes);\n if (match) {\n let size = parseInt(match[1]);\n assertArgument(size !== 0 && size <= 32, \"invalid bytes length\", \"param\", param);\n return new FixedBytesCoder(size, param.name);\n }\n assertArgument(false, \"invalid type\", \"type\", param.type);\n }\n /**\n * Get the default values for the given %%types%%.\n *\n * For example, a ``uint`` is by default ``0`` and ``bool``\n * is by default ``false``.\n */\n getDefaultValue(types) {\n const coders = types.map((type) => this.#getCoder(ParamType.from(type)));\n const coder = new TupleCoder(coders, \"_\");\n return coder.defaultValue();\n }\n /**\n * Encode the %%values%% as the %%types%% into ABI data.\n *\n * @returns DataHexstring\n */\n encode(types, values) {\n assertArgumentCount(values.length, types.length, \"types/values length mismatch\");\n const coders = types.map((type) => this.#getCoder(ParamType.from(type)));\n const coder = (new TupleCoder(coders, \"_\"));\n const writer = new Writer();\n coder.encode(writer, values);\n return writer.data;\n }\n /**\n * Decode the ABI %%data%% as the %%types%% into values.\n *\n * If %%loose%% decoding is enabled, then strict padding is\n * not enforced. Some older versions of Solidity incorrectly\n * padded event data emitted from ``external`` functions.\n */\n decode(types, data, loose) {\n const coders = types.map((type) => this.#getCoder(ParamType.from(type)));\n const coder = new TupleCoder(coders, \"_\");\n return coder.decode(new Reader(data, loose, defaultMaxInflation));\n }\n static _setDefaultMaxInflation(value) {\n assertArgument(typeof (value) === \"number\" && Number.isInteger(value), \"invalid defaultMaxInflation factor\", \"value\", value);\n defaultMaxInflation = value;\n }\n /**\n * Returns the shared singleton instance of a default [[AbiCoder]].\n *\n * On the first call, the instance is created internally.\n */\n static defaultAbiCoder() {\n if (defaultCoder == null) {\n defaultCoder = new AbiCoder();\n }\n return defaultCoder;\n }\n /**\n * Returns an ethers-compatible [[CallExceptionError]] Error for the given\n * result %%data%% for the [[CallExceptionAction]] %%action%% against\n * the Transaction %%tx%%.\n */\n static getBuiltinCallException(action, tx, data) {\n return getBuiltinCallException(action, tx, data, AbiCoder.defaultAbiCoder());\n }\n}\n//# sourceMappingURL=abi-coder.js.map","/**\n * The Interface class is a low-level class that accepts an\n * ABI and provides all the necessary functionality to encode\n * and decode paramaters to and results from methods, events\n * and errors.\n *\n * It also provides several convenience methods to automatically\n * search and find matching transactions and events to parse them.\n *\n * @_subsection api/abi:Interfaces [interfaces]\n */\nimport { keccak256 } from \"../crypto/index.js\";\nimport { id } from \"../hash/index.js\";\nimport { concat, dataSlice, getBigInt, getBytes, getBytesCopy, hexlify, zeroPadBytes, zeroPadValue, isHexString, defineProperties, assertArgument, toBeHex, assert } from \"../utils/index.js\";\nimport { AbiCoder } from \"./abi-coder.js\";\nimport { checkResultErrors, Result } from \"./coders/abstract-coder.js\";\nimport { ConstructorFragment, ErrorFragment, EventFragment, Fragment, FunctionFragment, ParamType } from \"./fragments.js\";\nimport { Typed } from \"./typed.js\";\nexport { checkResultErrors, Result };\n/**\n * When using the [[Interface-parseLog]] to automatically match a Log to its event\n * for parsing, a **LogDescription** is returned.\n */\nexport class LogDescription {\n /**\n * The matching fragment for the ``topic0``.\n */\n fragment;\n /**\n * The name of the Event.\n */\n name;\n /**\n * The full Event signature.\n */\n signature;\n /**\n * The topic hash for the Event.\n */\n topic;\n /**\n * The arguments passed into the Event with ``emit``.\n */\n args;\n /**\n * @_ignore:\n */\n constructor(fragment, topic, args) {\n const name = fragment.name, signature = fragment.format();\n defineProperties(this, {\n fragment, name, signature, topic, args\n });\n }\n}\n/**\n * When using the [[Interface-parseTransaction]] to automatically match\n * a transaction data to its function for parsing,\n * a **TransactionDescription** is returned.\n */\nexport class TransactionDescription {\n /**\n * The matching fragment from the transaction ``data``.\n */\n fragment;\n /**\n * The name of the Function from the transaction ``data``.\n */\n name;\n /**\n * The arguments passed to the Function from the transaction ``data``.\n */\n args;\n /**\n * The full Function signature from the transaction ``data``.\n */\n signature;\n /**\n * The selector for the Function from the transaction ``data``.\n */\n selector;\n /**\n * The ``value`` (in wei) from the transaction.\n */\n value;\n /**\n * @_ignore:\n */\n constructor(fragment, selector, args, value) {\n const name = fragment.name, signature = fragment.format();\n defineProperties(this, {\n fragment, name, args, signature, selector, value\n });\n }\n}\n/**\n * When using the [[Interface-parseError]] to automatically match an\n * error for a call result for parsing, an **ErrorDescription** is returned.\n */\nexport class ErrorDescription {\n /**\n * The matching fragment.\n */\n fragment;\n /**\n * The name of the Error.\n */\n name;\n /**\n * The arguments passed to the Error with ``revert``.\n */\n args;\n /**\n * The full Error signature.\n */\n signature;\n /**\n * The selector for the Error.\n */\n selector;\n /**\n * @_ignore:\n */\n constructor(fragment, selector, args) {\n const name = fragment.name, signature = fragment.format();\n defineProperties(this, {\n fragment, name, args, signature, selector\n });\n }\n}\n/**\n * An **Indexed** is used as a value when a value that does not\n * fit within a topic (i.e. not a fixed-length, 32-byte type). It\n * is the ``keccak256`` of the value, and used for types such as\n * arrays, tuples, bytes and strings.\n */\nexport class Indexed {\n /**\n * The ``keccak256`` of the value logged.\n */\n hash;\n /**\n * @_ignore:\n */\n _isIndexed;\n /**\n * Returns ``true`` if %%value%% is an **Indexed**.\n *\n * This provides a Type Guard for property access.\n */\n static isIndexed(value) {\n return !!(value && value._isIndexed);\n }\n /**\n * @_ignore:\n */\n constructor(hash) {\n defineProperties(this, { hash, _isIndexed: true });\n }\n}\n// https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require\nconst PanicReasons = {\n \"0\": \"generic panic\",\n \"1\": \"assert(false)\",\n \"17\": \"arithmetic overflow\",\n \"18\": \"division or modulo by zero\",\n \"33\": \"enum overflow\",\n \"34\": \"invalid encoded storage byte array accessed\",\n \"49\": \"out-of-bounds array access; popping on an empty array\",\n \"50\": \"out-of-bounds access of an array or bytesN\",\n \"65\": \"out of memory\",\n \"81\": \"uninitialized function\",\n};\nconst BuiltinErrors = {\n \"0x08c379a0\": {\n signature: \"Error(string)\",\n name: \"Error\",\n inputs: [\"string\"],\n reason: (message) => {\n return `reverted with reason string ${JSON.stringify(message)}`;\n }\n },\n \"0x4e487b71\": {\n signature: \"Panic(uint256)\",\n name: \"Panic\",\n inputs: [\"uint256\"],\n reason: (code) => {\n let reason = \"unknown panic code\";\n if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) {\n reason = PanicReasons[code.toString()];\n }\n return `reverted with panic code 0x${code.toString(16)} (${reason})`;\n }\n }\n};\n/**\n * An Interface abstracts many of the low-level details for\n * encoding and decoding the data on the blockchain.\n *\n * An ABI provides information on how to encode data to send to\n * a Contract, how to decode the results and events and how to\n * interpret revert errors.\n *\n * The ABI can be specified by [any supported format](InterfaceAbi).\n */\nexport class Interface {\n /**\n * All the Contract ABI members (i.e. methods, events, errors, etc).\n */\n fragments;\n /**\n * The Contract constructor.\n */\n deploy;\n /**\n * The Fallback method, if any.\n */\n fallback;\n /**\n * If receiving ether is supported.\n */\n receive;\n #errors;\n #events;\n #functions;\n // #structs: Map<string, StructFragment>;\n #abiCoder;\n /**\n * Create a new Interface for the %%fragments%%.\n */\n constructor(fragments) {\n let abi = [];\n if (typeof (fragments) === \"string\") {\n abi = JSON.parse(fragments);\n }\n else {\n abi = fragments;\n }\n this.#functions = new Map();\n this.#errors = new Map();\n this.#events = new Map();\n // this.#structs = new Map();\n const frags = [];\n for (const a of abi) {\n try {\n frags.push(Fragment.from(a));\n }\n catch (error) {\n console.log(`[Warning] Invalid Fragment ${JSON.stringify(a)}:`, error.message);\n }\n }\n defineProperties(this, {\n fragments: Object.freeze(frags)\n });\n let fallback = null;\n let receive = false;\n this.#abiCoder = this.getAbiCoder();\n // Add all fragments by their signature\n this.fragments.forEach((fragment, index) => {\n let bucket;\n switch (fragment.type) {\n case \"constructor\":\n if (this.deploy) {\n console.log(\"duplicate definition - constructor\");\n return;\n }\n //checkNames(fragment, \"input\", fragment.inputs);\n defineProperties(this, { deploy: fragment });\n return;\n case \"fallback\":\n if (fragment.inputs.length === 0) {\n receive = true;\n }\n else {\n assertArgument(!fallback || fragment.payable !== fallback.payable, \"conflicting fallback fragments\", `fragments[${index}]`, fragment);\n fallback = fragment;\n receive = fallback.payable;\n }\n return;\n case \"function\":\n //checkNames(fragment, \"input\", fragment.inputs);\n //checkNames(fragment, \"output\", (<FunctionFragment>fragment).outputs);\n bucket = this.#functions;\n break;\n case \"event\":\n //checkNames(fragment, \"input\", fragment.inputs);\n bucket = this.#events;\n break;\n case \"error\":\n bucket = this.#errors;\n break;\n default:\n return;\n }\n // Two identical entries; ignore it\n const signature = fragment.format();\n if (bucket.has(signature)) {\n return;\n }\n bucket.set(signature, fragment);\n });\n // If we do not have a constructor add a default\n if (!this.deploy) {\n defineProperties(this, {\n deploy: ConstructorFragment.from(\"constructor()\")\n });\n }\n defineProperties(this, { fallback, receive });\n }\n /**\n * Returns the entire Human-Readable ABI, as an array of\n * signatures, optionally as %%minimal%% strings, which\n * removes parameter names and unneceesary spaces.\n */\n format(minimal) {\n const format = (minimal ? \"minimal\" : \"full\");\n const abi = this.fragments.map((f) => f.format(format));\n return abi;\n }\n /**\n * Return the JSON-encoded ABI. This is the format Solidiy\n * returns.\n */\n formatJson() {\n const abi = this.fragments.map((f) => f.format(\"json\"));\n // We need to re-bundle the JSON fragments a bit\n return JSON.stringify(abi.map((j) => JSON.parse(j)));\n }\n /**\n * The ABI coder that will be used to encode and decode binary\n * data.\n */\n getAbiCoder() {\n return AbiCoder.defaultAbiCoder();\n }\n // Find a function definition by any means necessary (unless it is ambiguous)\n #getFunction(key, values, forceUnique) {\n // Selector\n if (isHexString(key)) {\n const selector = key.toLowerCase();\n for (const fragment of this.#functions.values()) {\n if (selector === fragment.selector) {\n return fragment;\n }\n }\n return null;\n }\n // It is a bare name, look up the function (will return null if ambiguous)\n if (key.indexOf(\"(\") === -1) {\n const matching = [];\n for (const [name, fragment] of this.#functions) {\n if (name.split(\"(\" /* fix:) */)[0] === key) {\n matching.push(fragment);\n }\n }\n if (values) {\n const lastValue = (values.length > 0) ? values[values.length - 1] : null;\n let valueLength = values.length;\n let allowOptions = true;\n if (Typed.isTyped(lastValue) && lastValue.type === \"overrides\") {\n allowOptions = false;\n valueLength--;\n }\n // Remove all matches that don't have a compatible length. The args\n // may contain an overrides, so the match may have n or n - 1 parameters\n for (let i = matching.length - 1; i >= 0; i--) {\n const inputs = matching[i].inputs.length;\n if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) {\n matching.splice(i, 1);\n }\n }\n // Remove all matches that don't match the Typed signature\n for (let i = matching.length - 1; i >= 0; i--) {\n const inputs = matching[i].inputs;\n for (let j = 0; j < values.length; j++) {\n // Not a typed value\n if (!Typed.isTyped(values[j])) {\n continue;\n }\n // We are past the inputs\n if (j >= inputs.length) {\n if (values[j].type === \"overrides\") {\n continue;\n }\n matching.splice(i, 1);\n break;\n }\n // Make sure the value type matches the input type\n if (values[j].type !== inputs[j].baseType) {\n matching.splice(i, 1);\n break;\n }\n }\n }\n }\n // We found a single matching signature with an overrides, but the\n // last value is something that cannot possibly be an options\n if (matching.length === 1 && values && values.length !== matching[0].inputs.length) {\n const lastArg = values[values.length - 1];\n if (lastArg == null || Array.isArray(lastArg) || typeof (lastArg) !== \"object\") {\n matching.splice(0, 1);\n }\n }\n if (matching.length === 0) {\n return null;\n }\n if (matching.length > 1 && forceUnique) {\n const matchStr = matching.map((m) => JSON.stringify(m.format())).join(\", \");\n assertArgument(false, `ambiguous function description (i.e. matches ${matchStr})`, \"key\", key);\n }\n return matching[0];\n }\n // Normalize the signature and lookup the function\n const result = this.#functions.get(FunctionFragment.from(key).format());\n if (result) {\n return result;\n }\n return null;\n }\n /**\n * Get the function name for %%key%%, which may be a function selector,\n * function name or function signature that belongs to the ABI.\n */\n getFunctionName(key) {\n const fragment = this.#getFunction(key, null, false);\n assertArgument(fragment, \"no matching function\", \"key\", key);\n return fragment.name;\n }\n /**\n * Returns true if %%key%% (a function selector, function name or\n * function signature) is present in the ABI.\n *\n * In the case of a function name, the name may be ambiguous, so\n * accessing the [[FunctionFragment]] may require refinement.\n */\n hasFunction(key) {\n return !!this.#getFunction(key, null, false);\n }\n /**\n * Get the [[FunctionFragment]] for %%key%%, which may be a function\n * selector, function name or function signature that belongs to the ABI.\n *\n * If %%values%% is provided, it will use the Typed API to handle\n * ambiguous cases where multiple functions match by name.\n *\n * If the %%key%% and %%values%% do not refine to a single function in\n * the ABI, this will throw.\n */\n getFunction(key, values) {\n return this.#getFunction(key, values || null, true);\n }\n /**\n * Iterate over all functions, calling %%callback%%, sorted by their name.\n */\n forEachFunction(callback) {\n const names = Array.from(this.#functions.keys());\n names.sort((a, b) => a.localeCompare(b));\n for (let i = 0; i < names.length; i++) {\n const name = names[i];\n callback((this.#functions.get(name)), i);\n }\n }\n // Find an event definition by any means necessary (unless it is ambiguous)\n #getEvent(key, values, forceUnique) {\n // EventTopic\n if (isHexString(key)) {\n const eventTopic = key.toLowerCase();\n for (const fragment of this.#events.values()) {\n if (eventTopic === fragment.topicHash) {\n return fragment;\n }\n }\n return null;\n }\n // It is a bare name, look up the function (will return null if ambiguous)\n if (key.indexOf(\"(\") === -1) {\n const matching = [];\n for (const [name, fragment] of this.#events) {\n if (name.split(\"(\" /* fix:) */)[0] === key) {\n matching.push(fragment);\n }\n }\n if (values) {\n // Remove all matches that don't have a compatible length.\n for (let i = matching.length - 1; i >= 0; i--) {\n if (matching[i].inputs.length < values.length) {\n matching.splice(i, 1);\n }\n }\n // Remove all matches that don't match the Typed signature\n for (let i = matching.length - 1; i >= 0; i--) {\n const inputs = matching[i].inputs;\n for (let j = 0; j < values.length; j++) {\n // Not a typed value\n if (!Typed.isTyped(values[j])) {\n continue;\n }\n // Make sure the value type matches the input type\n if (values[j].type !== inputs[j].baseType) {\n matching.splice(i, 1);\n break;\n }\n }\n }\n }\n if (matching.length === 0) {\n return null;\n }\n if (matching.length > 1 && forceUnique) {\n const matchStr = matching.map((m) => JSON.stringify(m.format())).join(\", \");\n assertArgument(false, `ambiguous event description (i.e. matches ${matchStr})`, \"key\", key);\n }\n return matching[0];\n }\n // Normalize the signature and lookup the function\n const result = this.#events.get(EventFragment.from(key).format());\n if (result) {\n return result;\n }\n return null;\n }\n /**\n * Get the event name for %%key%%, which may be a topic hash,\n * event name or event signature that belongs to the ABI.\n */\n getEventName(key) {\n const fragment = this.#getEvent(key, null, false);\n assertArgument(fragment, \"no matching event\", \"key\", key);\n return fragment.name;\n }\n /**\n * Returns true if %%key%% (an event topic hash, event name or\n * event signature) is present in the ABI.\n *\n * In the case of an event name, the name may be ambiguous, so\n * accessing the [[EventFragment]] may require refinement.\n */\n hasEvent(key) {\n return !!this.#getEvent(key, null, false);\n }\n /**\n * Get the [[EventFragment]] for %%key%%, which may be a topic hash,\n * event name or event signature that belongs to the ABI.\n *\n * If %%values%% is provided, it will use the Typed API to handle\n * ambiguous cases where multiple events match by name.\n *\n * If the %%key%% and %%values%% do not refine to a single event in\n * the ABI, this will throw.\n */\n getEvent(key, values) {\n return this.#getEvent(key, values || null, true);\n }\n /**\n * Iterate over all events, calling %%callback%%, sorted by their name.\n */\n forEachEvent(callback) {\n const names = Array.from(this.#events.keys());\n names.sort((a, b) => a.localeCompare(b));\n for (let i = 0; i < names.length; i++) {\n const name = names[i];\n callback((this.#events.get(name)), i);\n }\n }\n /**\n * Get the [[ErrorFragment]] for %%key%%, which may be an error\n * selector, error name or error signature that belongs to the ABI.\n *\n * If %%values%% is provided, it will use the Typed API to handle\n * ambiguous cases where multiple errors match by name.\n *\n * If the %%key%% and %%values%% do not refine to a single error in\n * the ABI, this will throw.\n */\n getError(key, values) {\n if (isHexString(key)) {\n const selector = key.toLowerCase();\n if (BuiltinErrors[selector]) {\n return ErrorFragment.from(BuiltinErrors[selector].signature);\n }\n for (const fragment of this.#errors.values()) {\n if (selector === fragment.selector) {\n return fragment;\n }\n }\n return null;\n }\n // It is a bare name, look up the function (will return null if ambiguous)\n if (key.indexOf(\"(\") === -1) {\n const matching = [];\n for (const [name, fragment] of this.#errors) {\n if (name.split(\"(\" /* fix:) */)[0] === key) {\n matching.push(fragment);\n }\n }\n if (matching.length === 0) {\n if (key === \"Error\") {\n return ErrorFragment.from(\"error Error(string)\");\n }\n if (key === \"Panic\") {\n return ErrorFragment.from(\"error Panic(uint256)\");\n }\n return null;\n }\n else if (matching.length > 1) {\n const matchStr = matching.map((m) => JSON.stringify(m.format())).join(\", \");\n assertArgument(false, `ambiguous error description (i.e. ${matchStr})`, \"name\", key);\n }\n return matching[0];\n }\n // Normalize the signature and lookup the function\n key = ErrorFragment.from(key).format();\n if (key === \"Error(string)\") {\n return ErrorFragment.from(\"error Error(string)\");\n }\n if (key === \"Panic(uint256)\") {\n return ErrorFragment.from(\"error Panic(uint256)\");\n }\n const result = this.#errors.get(key);\n if (result) {\n return result;\n }\n return null;\n }\n /**\n * Iterate over all errors, calling %%callback%%, sorted by their name.\n */\n forEachError(callback) {\n const names = Array.from(this.#errors.keys());\n names.sort((a, b) => a.localeCompare(b));\n for (let i = 0; i < names.length; i++) {\n const name = names[i];\n callback((this.#errors.get(name)), i);\n }\n }\n // Get the 4-byte selector used by Solidity to identify a function\n /*\ngetSelector(fragment: ErrorFragment | FunctionFragment): string {\n if (typeof(fragment) === \"string\") {\n const matches: Array<Fragment> = [ ];\n\n try { matches.push(this.getFunction(fragment)); } catch (error) { }\n try { matches.push(this.getError(<string>fragment)); } catch (_) { }\n\n if (matches.length === 0) {\n logger.throwArgumentError(\"unknown fragment\", \"key\", fragment);\n } else if (matches.length > 1) {\n logger.throwArgumentError(\"ambiguous fragment matches function and error\", \"key\", fragment);\n }\n\n fragment = matches[0];\n }\n\n return dataSlice(id(fragment.format()), 0, 4);\n}\n */\n // Get the 32-byte topic hash used by Solidity to identify an event\n /*\n getEventTopic(fragment: EventFragment): string {\n //if (typeof(fragment) === \"string\") { fragment = this.getEvent(eventFragment); }\n return id(fragment.format());\n }\n */\n _decodeParams(params, data) {\n return this.#abiCoder.decode(params, data);\n }\n _encodeParams(params, values) {\n return this.#abiCoder.encode(params, values);\n }\n /**\n * Encodes a ``tx.data`` object for deploying the Contract with\n * the %%values%% as the constructor arguments.\n */\n encodeDeploy(values) {\n return this._encodeParams(this.deploy.inputs, values || []);\n }\n /**\n * Decodes the result %%data%% (e.g. from an ``eth_call``) for the\n * specified error (see [[getError]] for valid values for\n * %%key%%).\n *\n * Most developers should prefer the [[parseCallResult]] method instead,\n * which will automatically detect a ``CALL_EXCEPTION`` and throw the\n * corresponding error.\n */\n decodeErrorResult(fragment, data) {\n if (typeof (fragment) === \"string\") {\n const f = this.getError(fragment);\n assertArgument(f, \"unknown error\", \"fragment\", fragment);\n fragment = f;\n }\n assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match error ${fragment.name}.`, \"data\", data);\n return this._decodeParams(fragment.inputs, dataSlice(data, 4));\n }\n /**\n * Encodes the transaction revert data for a call result that\n * reverted from the the Contract with the sepcified %%error%%\n * (see [[getError]] for valid values for %%fragment%%) with the %%values%%.\n *\n * This is generally not used by most developers, unless trying to mock\n * a result from a Contract.\n */\n encodeErrorResult(fragment, values) {\n if (typeof (fragment) === \"string\") {\n const f = this.getError(fragment);\n assertArgument(f, \"unknown error\", \"fragment\", fragment);\n fragment = f;\n }\n return concat([\n fragment.selector,\n this._encodeParams(fragment.inputs, values || [])\n ]);\n }\n /**\n * Decodes the %%data%% from a transaction ``tx.data`` for\n * the function specified (see [[getFunction]] for valid values\n * for %%fragment%%).\n *\n * Most developers should prefer the [[parseTransaction]] method\n * instead, which will automatically detect the fragment.\n */\n decodeFunctionData(fragment, data) {\n if (typeof (fragment) === \"string\") {\n const f = this.getFunction(fragment);\n assertArgument(f, \"unknown function\", \"fragment\", fragment);\n fragment = f;\n }\n assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match function ${fragment.name}.`, \"data\", data);\n return this._decodeParams(fragment.inputs, dataSlice(data, 4));\n }\n /**\n * Encodes the ``tx.data`` for a transaction that calls the function\n * specified (see [[getFunction]] for valid values for %%fragment%%) with\n * the %%values%%.\n */\n encodeFunctionData(fragment, values) {\n if (typeof (fragment) === \"string\") {\n const f = this.getFunction(fragment);\n assertArgument(f, \"unknown function\", \"fragment\", fragment);\n fragment = f;\n }\n return concat([\n fragment.selector,\n this._encodeParams(fragment.inputs, values || [])\n ]);\n }\n /**\n * Decodes the result %%data%% (e.g. from an ``eth_call``) for the\n * specified function (see [[getFunction]] for valid values for\n * %%key%%).\n *\n * Most developers should prefer the [[parseCallResult]] method instead,\n * which will automatically detect a ``CALL_EXCEPTION`` and throw the\n * corresponding error.\n */\n decodeFunctionResult(fragment, data) {\n if (typeof (fragment) === \"string\") {\n const f = this.getFunction(fragment);\n assertArgument(f, \"unknown function\", \"fragment\", fragment);\n fragment = f;\n }\n let message = \"invalid length for result data\";\n const bytes = getBytesCopy(data);\n if ((bytes.length % 32) === 0) {\n try {\n return this.#abiCoder.decode(fragment.outputs, bytes);\n }\n catch (error) {\n message = \"could not decode result data\";\n }\n }\n // Call returned data with no error, but the data is junk\n assert(false, message, \"BAD_DATA\", {\n value: hexlify(bytes),\n info: { method: fragment.name, signature: fragment.format() }\n });\n }\n makeError(_data, tx) {\n const data = getBytes(_data, \"data\");\n const error = AbiCoder.getBuiltinCallException(\"call\", tx, data);\n // Not a built-in error; try finding a custom error\n const customPrefix = \"execution reverted (unknown custom error)\";\n if (error.message.startsWith(customPrefix)) {\n const selector = hexlify(data.slice(0, 4));\n const ef = this.getError(selector);\n if (ef) {\n try {\n const args = this.#abiCoder.decode(ef.inputs, data.slice(4));\n error.revert = {\n name: ef.name, signature: ef.format(), args\n };\n error.reason = error.revert.signature;\n error.message = `execution reverted: ${error.reason}`;\n }\n catch (e) {\n error.message = `execution reverted (coult not decode custom error)`;\n }\n }\n }\n // Add the invocation, if available\n const parsed = this.parseTransaction(tx);\n if (parsed) {\n error.invocation = {\n method: parsed.name,\n signature: parsed.signature,\n args: parsed.args\n };\n }\n return error;\n }\n /**\n * Encodes the result data (e.g. from an ``eth_call``) for the\n * specified function (see [[getFunction]] for valid values\n * for %%fragment%%) with %%values%%.\n *\n * This is generally not used by most developers, unless trying to mock\n * a result from a Contract.\n */\n encodeFunctionResult(fragment, values) {\n if (typeof (fragment) === \"string\") {\n const f = this.getFunction(fragment);\n assertArgument(f, \"unknown function\", \"fragment\", fragment);\n fragment = f;\n }\n return hexlify(this.#abiCoder.encode(fragment.outputs, values || []));\n }\n /*\n spelunk(inputs: Array<ParamType>, values: ReadonlyArray<any>, processfunc: (type: string, value: any) => Promise<any>): Promise<Array<any>> {\n const promises: Array<Promise<>> = [ ];\n const process = function(type: ParamType, value: any): any {\n if (type.baseType === \"array\") {\n return descend(type.child\n }\n if (type. === \"address\") {\n }\n };\n \n const descend = function (inputs: Array<ParamType>, values: ReadonlyArray<any>) {\n if (inputs.length !== values.length) { throw new Error(\"length mismatch\"); }\n \n };\n \n const result: Array<any> = [ ];\n values.forEach((value, index) => {\n if (value == null) {\n topics.push(null);\n } else if (param.baseType === \"array\" || param.baseType === \"tuple\") {\n logger.throwArgumentError(\"filtering with tuples or arrays not supported\", (\"contract.\" + param.name), value);\n } else if (Array.isArray(value)) {\n topics.push(value.map((value) => encodeTopic(param, value)));\n } else {\n topics.push(encodeTopic(param, value));\n }\n });\n }\n */\n // Create the filter for the event with search criteria (e.g. for eth_filterLog)\n encodeFilterTopics(fragment, values) {\n if (typeof (fragment) === \"string\") {\n const f = this.getEvent(fragment);\n assertArgument(f, \"unknown event\", \"eventFragment\", fragment);\n fragment = f;\n }\n assert(values.length <= fragment.inputs.length, `too many arguments for ${fragment.format()}`, \"UNEXPECTED_ARGUMENT\", { count: values.length, expectedCount: fragment.inputs.length });\n const topics = [];\n if (!fragment.anonymous) {\n topics.push(fragment.topicHash);\n }\n // @TODO: Use the coders for this; to properly support tuples, etc.\n const encodeTopic = (param, value) => {\n if (param.type === \"string\") {\n return id(value);\n }\n else if (param.type === \"bytes\") {\n return keccak256(hexlify(value));\n }\n if (param.type === \"bool\" && typeof (value) === \"boolean\") {\n value = (value ? \"0x01\" : \"0x00\");\n }\n else if (param.type.match(/^u?int/)) {\n value = toBeHex(value); // @TODO: Should this toTwos??\n }\n else if (param.type.match(/^bytes/)) {\n value = zeroPadBytes(value, 32);\n }\n else if (param.type === \"address\") {\n // Check addresses are valid\n this.#abiCoder.encode([\"address\"], [value]);\n }\n return zeroPadValue(hexlify(value), 32);\n };\n values.forEach((value, index) => {\n const param = fragment.inputs[index];\n if (!param.indexed) {\n assertArgument(value == null, \"cannot filter non-indexed parameters; must be null\", (\"contract.\" + param.name), value);\n return;\n }\n if (value == null) {\n topics.push(null);\n }\n else if (param.baseType === \"array\" || param.baseType === \"tuple\") {\n assertArgument(false, \"filtering with tuples or arrays not supported\", (\"contract.\" + param.name), value);\n }\n else if (Array.isArray(value)) {\n topics.push(value.map((value) => encodeTopic(param, value)));\n }\n else {\n topics.push(encodeTopic(param, value));\n }\n });\n // Trim off trailing nulls\n while (topics.length && topics[topics.length - 1] === null) {\n topics.pop();\n }\n return topics;\n }\n encodeEventLog(fragment, values) {\n if (typeof (fragment) === \"string\") {\n const f = this.getEvent(fragment);\n assertArgument(f, \"unknown event\", \"eventFragment\", fragment);\n fragment = f;\n }\n const topics = [];\n const dataTypes = [];\n const dataValues = [];\n if (!fragment.anonymous) {\n topics.push(fragment.topicHash);\n }\n assertArgument(values.length === fragment.inputs.length, \"event arguments/values mismatch\", \"values\", values);\n fragment.inputs.forEach((param, index) => {\n const value = values[index];\n if (param.indexed) {\n if (param.type === \"string\") {\n topics.push(id(value));\n }\n else if (param.type === \"bytes\") {\n topics.push(keccak256(value));\n }\n else if (param.baseType === \"tuple\" || param.baseType === \"array\") {\n // @TODO\n throw new Error(\"not implemented\");\n }\n else {\n topics.push(this.#abiCoder.encode([param.type], [value]));\n }\n }\n else {\n dataTypes.push(param);\n dataValues.push(value);\n }\n });\n return {\n data: this.#abiCoder.encode(dataTypes, dataValues),\n topics: topics\n };\n }\n // Decode a filter for the event and the search criteria\n decodeEventLog(fragment, data, topics) {\n if (typeof (fragment) === \"string\") {\n const f = this.getEvent(fragment);\n assertArgument(f, \"unknown event\", \"eventFragment\", fragment);\n fragment = f;\n }\n if (topics != null && !fragment.anonymous) {\n const eventTopic = fragment.topicHash;\n assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic, \"fragment/topic mismatch\", \"topics[0]\", topics[0]);\n topics = topics.slice(1);\n }\n const indexed = [];\n const nonIndexed = [];\n const dynamic = [];\n fragment.inputs.forEach((param, index) => {\n if (param.indexed) {\n if (param.type === \"string\" || param.type === \"bytes\" || param.baseType === \"tuple\" || param.baseType === \"array\") {\n indexed.push(ParamType.from({ type: \"bytes32\", name: param.name }));\n dynamic.push(true);\n }\n else {\n indexed.push(param);\n dynamic.push(false);\n }\n }\n else {\n nonIndexed.push(param);\n dynamic.push(false);\n }\n });\n const resultIndexed = (topics != null) ? this.#abiCoder.decode(indexed, concat(topics)) : null;\n const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true);\n //const result: (Array<any> & { [ key: string ]: any }) = [ ];\n const values = [];\n const keys = [];\n let nonIndexedIndex = 0, indexedIndex = 0;\n fragment.inputs.forEach((param, index) => {\n let value = null;\n if (param.indexed) {\n if (resultIndexed == null) {\n value = new Indexed(null);\n }\n else if (dynamic[index]) {\n value = new Indexed(resultIndexed[indexedIndex++]);\n }\n else {\n try {\n value = resultIndexed[indexedIndex++];\n }\n catch (error) {\n value = error;\n }\n }\n }\n else {\n try {\n value = resultNonIndexed[nonIndexedIndex++];\n }\n catch (error) {\n value = error;\n }\n }\n values.push(value);\n keys.push(param.name || null);\n });\n return Result.fromItems(values, keys);\n }\n /**\n * Parses a transaction, finding the matching function and extracts\n * the parameter values along with other useful function details.\n *\n * If the matching function cannot be found, return null.\n */\n parseTransaction(tx) {\n const data = getBytes(tx.data, \"tx.data\");\n const value = getBigInt((tx.value != null) ? tx.value : 0, \"tx.value\");\n const fragment = this.getFunction(hexlify(data.slice(0, 4)));\n if (!fragment) {\n return null;\n }\n const args = this.#abiCoder.decode(fragment.inputs, data.slice(4));\n return new TransactionDescription(fragment, fragment.selector, args, value);\n }\n parseCallResult(data) {\n throw new Error(\"@TODO\");\n }\n /**\n * Parses a receipt log, finding the matching event and extracts\n * the parameter values along with other useful event details.\n *\n * If the matching event cannot be found, returns null.\n */\n parseLog(log) {\n const fragment = this.getEvent(log.topics[0]);\n if (!fragment || fragment.anonymous) {\n return null;\n }\n // @TODO: If anonymous, and the only method, and the input count matches, should we parse?\n // Probably not, because just because it is the only event in the ABI does\n // not mean we have the full ABI; maybe just a fragment?\n return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics));\n }\n /**\n * Parses a revert data, finding the matching error and extracts\n * the parameter values along with other useful error details.\n *\n * If the matching error cannot be found, returns null.\n */\n parseError(data) {\n const hexData = hexlify(data);\n const fragment = this.getError(dataSlice(hexData, 0, 4));\n if (!fragment) {\n return null;\n }\n const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4));\n return new ErrorDescription(fragment, fragment.selector, args);\n }\n /**\n * Creates a new [[Interface]] from the ABI %%value%%.\n *\n * The %%value%% may be provided as an existing [[Interface]] object,\n * a JSON-encoded ABI or any Human-Readable ABI format.\n */\n static from(value) {\n // Already an Interface, which is immutable\n if (value instanceof Interface) {\n return value;\n }\n // JSON\n if (typeof (value) === \"string\") {\n return new Interface(JSON.parse(value));\n }\n // An Interface; possibly from another v6 instance\n if (typeof (value.formatJson) === \"function\") {\n return new Interface(value.formatJson());\n }\n // A legacy Interface; from an older version\n if (typeof (value.format) === \"function\") {\n return new Interface(value.format(\"json\"));\n }\n // Array of fragments\n return new Interface(value);\n }\n}\n//# sourceMappingURL=interface.js.map","//import { resolveAddress } from \"@ethersproject/address\";\nimport { defineProperties, getBigInt, getNumber, hexlify, isBytesLike, resolveProperties, assert, assertArgument, isError, makeError } from \"../utils/index.js\";\nimport { accessListify } from \"../transaction/index.js\";\nconst BN_0 = BigInt(0);\n// -----------------------\nfunction getValue(value) {\n if (value == null) {\n return null;\n }\n return value;\n}\nfunction toJson(value) {\n if (value == null) {\n return null;\n }\n return value.toString();\n}\n// @TODO? <T extends FeeData = { }> implements Required<T>\n/**\n * A **FeeData** wraps all the fee-related values associated with\n * the network.\n */\nexport class FeeData {\n /**\n * The gas price for legacy networks.\n */\n gasPrice;\n /**\n * The maximum fee to pay per gas.\n *\n * The base fee per gas is defined by the network and based on\n * congestion, increasing the cost during times of heavy load\n * and lowering when less busy.\n *\n * The actual fee per gas will be the base fee for the block\n * and the priority fee, up to the max fee per gas.\n *\n * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))\n */\n maxFeePerGas;\n /**\n * The additional amout to pay per gas to encourage a validator\n * to include the transaction.\n *\n * The purpose of this is to compensate the validator for the\n * adjusted risk for including a given transaction.\n *\n * This will be ``null`` on legacy networks (i.e. [pre-EIP-1559](link-eip-1559))\n */\n maxPriorityFeePerGas;\n /**\n * Creates a new FeeData for %%gasPrice%%, %%maxFeePerGas%% and\n * %%maxPriorityFeePerGas%%.\n */\n constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) {\n defineProperties(this, {\n gasPrice: getValue(gasPrice),\n maxFeePerGas: getValue(maxFeePerGas),\n maxPriorityFeePerGas: getValue(maxPriorityFeePerGas)\n });\n }\n /**\n * Returns a JSON-friendly value.\n */\n toJSON() {\n const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this;\n return {\n _type: \"FeeData\",\n gasPrice: toJson(gasPrice),\n maxFeePerGas: toJson(maxFeePerGas),\n maxPriorityFeePerGas: toJson(maxPriorityFeePerGas),\n };\n }\n}\n;\n/**\n * Returns a copy of %%req%% with all properties coerced to their strict\n * types.\n */\nexport function copyRequest(req) {\n const result = {};\n // These could be addresses, ENS names or Addressables\n if (req.to) {\n result.to = req.to;\n }\n if (req.from) {\n result.from = req.from;\n }\n if (req.data) {\n result.data = hexlify(req.data);\n }\n const bigIntKeys = \"chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value\".split(/,/);\n for (const key of bigIntKeys) {\n if (!(key in req) || req[key] == null) {\n continue;\n }\n result[key] = getBigInt(req[key], `request.${key}`);\n }\n const numberKeys = \"type,nonce\".split(/,/);\n for (const key of numberKeys) {\n if (!(key in req) || req[key] == null) {\n continue;\n }\n result[key] = getNumber(req[key], `request.${key}`);\n }\n if (req.accessList) {\n result.accessList = accessListify(req.accessList);\n }\n if (\"blockTag\" in req) {\n result.blockTag = req.blockTag;\n }\n if (\"enableCcipRead\" in req) {\n result.enableCcipRead = !!req.enableCcipRead;\n }\n if (\"customData\" in req) {\n result.customData = req.customData;\n }\n if (\"blobVersionedHashes\" in req && req.blobVersionedHashes) {\n result.blobVersionedHashes = req.blobVersionedHashes.slice();\n }\n if (\"kzg\" in req) {\n result.kzg = req.kzg;\n }\n if (\"blobs\" in req && req.blobs) {\n result.blobs = req.blobs.map((b) => {\n if (isBytesLike(b)) {\n return hexlify(b);\n }\n return Object.assign({}, b);\n });\n }\n return result;\n}\n/**\n * A **Block** represents the data associated with a full block on\n * Ethereum.\n */\nexport class Block {\n /**\n * The provider connected to the block used to fetch additional details\n * if necessary.\n */\n provider;\n /**\n * The block number, sometimes called the block height. This is a\n * sequential number that is one higher than the parent block.\n */\n number;\n /**\n * The block hash.\n *\n * This hash includes all properties, so can be safely used to identify\n * an exact set of block properties.\n */\n hash;\n /**\n * The timestamp for this block, which is the number of seconds since\n * epoch that this block was included.\n */\n timestamp;\n /**\n * The block hash of the parent block.\n */\n parentHash;\n /**\n * The hash tree root of the parent beacon block for the given\n * execution block. See [[link-eip-4788]].\n */\n parentBeaconBlockRoot;\n /**\n * The nonce.\n *\n * On legacy networks, this is the random number inserted which\n * permitted the difficulty target to be reached.\n */\n nonce;\n /**\n * The difficulty target.\n *\n * On legacy networks, this is the proof-of-work target required\n * for a block to meet the protocol rules to be included.\n *\n * On modern networks, this is a random number arrived at using\n * randao. @TODO: Find links?\n */\n difficulty;\n /**\n * The total gas limit for this block.\n */\n gasLimit;\n /**\n * The total gas used in this block.\n */\n gasUsed;\n /**\n * The root hash for the global state after applying changes\n * in this block.\n */\n stateRoot;\n /**\n * The hash of the transaction receipts trie.\n */\n receiptsRoot;\n /**\n * The total amount of blob gas consumed by the transactions\n * within the block. See [[link-eip-4844]].\n */\n blobGasUsed;\n /**\n * The running total of blob gas consumed in excess of the\n * target, prior to the block. See [[link-eip-4844]].\n */\n excessBlobGas;\n /**\n * The miner coinbase address, wihch receives any subsidies for\n * including this block.\n */\n miner;\n /**\n * The latest RANDAO mix of the post beacon state of\n * the previous block.\n */\n prevRandao;\n /**\n * Any extra data the validator wished to include.\n */\n extraData;\n /**\n * The base fee per gas that all transactions in this block were\n * charged.\n *\n * This adjusts after each block, depending on how congested the network\n * is.\n */\n baseFeePerGas;\n #transactions;\n /**\n * Create a new **Block** object.\n *\n * This should generally not be necessary as the unless implementing a\n * low-level library.\n */\n constructor(block, provider) {\n this.#transactions = block.transactions.map((tx) => {\n if (typeof (tx) !== \"string\") {\n return new TransactionResponse(tx, provider);\n }\n return tx;\n });\n defineProperties(this, {\n provider,\n hash: getValue(block.hash),\n number: block.number,\n timestamp: block.timestamp,\n parentHash: block.parentHash,\n parentBeaconBlockRoot: block.parentBeaconBlockRoot,\n nonce: block.nonce,\n difficulty: block.difficulty,\n gasLimit: block.gasLimit,\n gasUsed: block.gasUsed,\n blobGasUsed: block.blobGasUsed,\n excessBlobGas: block.excessBlobGas,\n miner: block.miner,\n prevRandao: getValue(block.prevRandao),\n extraData: block.extraData,\n baseFeePerGas: getValue(block.baseFeePerGas),\n stateRoot: block.stateRoot,\n receiptsRoot: block.receiptsRoot,\n });\n }\n /**\n * Returns the list of transaction hashes, in the order\n * they were executed within the block.\n */\n get transactions() {\n return this.#transactions.map((tx) => {\n if (typeof (tx) === \"string\") {\n return tx;\n }\n return tx.hash;\n });\n }\n /**\n * Returns the complete transactions, in the order they\n * were executed within the block.\n *\n * This is only available for blocks which prefetched\n * transactions, by passing ``true`` to %%prefetchTxs%%\n * into [[Provider-getBlock]].\n */\n get prefetchedTransactions() {\n const txs = this.#transactions.slice();\n // Doesn't matter...\n if (txs.length === 0) {\n return [];\n }\n // Make sure we prefetched the transactions\n assert(typeof (txs[0]) === \"object\", \"transactions were not prefetched with block request\", \"UNSUPPORTED_OPERATION\", {\n operation: \"transactionResponses()\"\n });\n return txs;\n }\n /**\n * Returns a JSON-friendly value.\n */\n toJSON() {\n const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, prevRandao, nonce, number, parentHash, parentBeaconBlockRoot, stateRoot, receiptsRoot, timestamp, transactions } = this;\n return {\n _type: \"Block\",\n baseFeePerGas: toJson(baseFeePerGas),\n difficulty: toJson(difficulty),\n extraData,\n gasLimit: toJson(gasLimit),\n gasUsed: toJson(gasUsed),\n blobGasUsed: toJson(this.blobGasUsed),\n excessBlobGas: toJson(this.excessBlobGas),\n hash, miner, prevRandao, nonce, number, parentHash, timestamp,\n parentBeaconBlockRoot, stateRoot, receiptsRoot,\n transactions,\n };\n }\n [Symbol.iterator]() {\n let index = 0;\n const txs = this.transactions;\n return {\n next: () => {\n if (index < this.length) {\n return {\n value: txs[index++], done: false\n };\n }\n return { value: undefined, done: true };\n }\n };\n }\n /**\n * The number of transactions in this block.\n */\n get length() { return this.#transactions.length; }\n /**\n * The [[link-js-date]] this block was included at.\n */\n get date() {\n if (this.timestamp == null) {\n return null;\n }\n return new Date(this.timestamp * 1000);\n }\n /**\n * Get the transaction at %%indexe%% within this block.\n */\n async getTransaction(indexOrHash) {\n // Find the internal value by its index or hash\n let tx = undefined;\n if (typeof (indexOrHash) === \"number\") {\n tx = this.#transactions[indexOrHash];\n }\n else {\n const hash = indexOrHash.toLowerCase();\n for (const v of this.#transactions) {\n if (typeof (v) === \"string\") {\n if (v !== hash) {\n continue;\n }\n tx = v;\n break;\n }\n else {\n if (v.hash === hash) {\n continue;\n }\n tx = v;\n break;\n }\n }\n }\n if (tx == null) {\n throw new Error(\"no such tx\");\n }\n if (typeof (tx) === \"string\") {\n return (await this.provider.getTransaction(tx));\n }\n else {\n return tx;\n }\n }\n /**\n * If a **Block** was fetched with a request to include the transactions\n * this will allow synchronous access to those transactions.\n *\n * If the transactions were not prefetched, this will throw.\n */\n getPrefetchedTransaction(indexOrHash) {\n const txs = this.prefetchedTransactions;\n if (typeof (indexOrHash) === \"number\") {\n return txs[indexOrHash];\n }\n indexOrHash = indexOrHash.toLowerCase();\n for (const tx of txs) {\n if (tx.hash === indexOrHash) {\n return tx;\n }\n }\n assertArgument(false, \"no matching transaction\", \"indexOrHash\", indexOrHash);\n }\n /**\n * Returns true if this block been mined. This provides a type guard\n * for all properties on a [[MinedBlock]].\n */\n isMined() { return !!this.hash; }\n /**\n * Returns true if this block is an [[link-eip-2930]] block.\n */\n isLondon() {\n return !!this.baseFeePerGas;\n }\n /**\n * @_ignore:\n */\n orphanedEvent() {\n if (!this.isMined()) {\n throw new Error(\"\");\n }\n return createOrphanedBlockFilter(this);\n }\n}\n//////////////////////\n// Log\n/**\n * A **Log** in Ethereum represents an event that has been included in a\n * transaction using the ``LOG*`` opcodes, which are most commonly used by\n * Solidity's emit for announcing events.\n */\nexport class Log {\n /**\n * The provider connected to the log used to fetch additional details\n * if necessary.\n */\n provider;\n /**\n * The transaction hash of the transaction this log occurred in. Use the\n * [[Log-getTransaction]] to get the [[TransactionResponse]].\n */\n transactionHash;\n /**\n * The block hash of the block this log occurred in. Use the\n * [[Log-getBlock]] to get the [[Block]].\n */\n blockHash;\n /**\n * The block number of the block this log occurred in. It is preferred\n * to use the [[Block-hash]] when fetching the related [[Block]],\n * since in the case of an orphaned block, the block at that height may\n * have changed.\n */\n blockNumber;\n /**\n * If the **Log** represents a block that was removed due to an orphaned\n * block, this will be true.\n *\n * This can only happen within an orphan event listener.\n */\n removed;\n /**\n * The address of the contract that emitted this log.\n */\n address;\n /**\n * The data included in this log when it was emitted.\n */\n data;\n /**\n * The indexed topics included in this log when it was emitted.\n *\n * All topics are included in the bloom filters, so they can be\n * efficiently filtered using the [[Provider-getLogs]] method.\n */\n topics;\n /**\n * The index within the block this log occurred at. This is generally\n * not useful to developers, but can be used with the various roots\n * to proof inclusion within a block.\n */\n index;\n /**\n * The index within the transaction of this log.\n */\n transactionIndex;\n /**\n * @_ignore:\n */\n constructor(log, provider) {\n this.provider = provider;\n const topics = Object.freeze(log.topics.slice());\n defineProperties(this, {\n transactionHash: log.transactionHash,\n blockHash: log.blockHash,\n blockNumber: log.blockNumber,\n removed: log.removed,\n address: log.address,\n data: log.data,\n topics,\n index: log.index,\n transactionIndex: log.transactionIndex,\n });\n }\n /**\n * Returns a JSON-compatible object.\n */\n toJSON() {\n const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this;\n return {\n _type: \"log\",\n address, blockHash, blockNumber, data, index,\n removed, topics, transactionHash, transactionIndex\n };\n }\n /**\n * Returns the block that this log occurred in.\n */\n async getBlock() {\n const block = await this.provider.getBlock(this.blockHash);\n assert(!!block, \"failed to find transaction\", \"UNKNOWN_ERROR\", {});\n return block;\n }\n /**\n * Returns the transaction that this log occurred in.\n */\n async getTransaction() {\n const tx = await this.provider.getTransaction(this.transactionHash);\n assert(!!tx, \"failed to find transaction\", \"UNKNOWN_ERROR\", {});\n return tx;\n }\n /**\n * Returns the transaction receipt fot the transaction that this\n * log occurred in.\n */\n async getTransactionReceipt() {\n const receipt = await this.provider.getTransactionReceipt(this.transactionHash);\n assert(!!receipt, \"failed to find transaction receipt\", \"UNKNOWN_ERROR\", {});\n return receipt;\n }\n /**\n * @_ignore:\n */\n removedEvent() {\n return createRemovedLogFilter(this);\n }\n}\n//////////////////////\n// Transaction Receipt\n/*\nexport interface LegacyTransactionReceipt {\n byzantium: false;\n status: null;\n root: string;\n}\n\nexport interface ByzantiumTransactionReceipt {\n byzantium: true;\n status: number;\n root: null;\n}\n*/\n/**\n * A **TransactionReceipt** includes additional information about a\n * transaction that is only available after it has been mined.\n */\nexport class TransactionReceipt {\n /**\n * The provider connected to the log used to fetch additional details\n * if necessary.\n */\n provider;\n /**\n * The address the transaction was sent to.\n */\n to;\n /**\n * The sender of the transaction.\n */\n from;\n /**\n * The address of the contract if the transaction was directly\n * responsible for deploying one.\n *\n * This is non-null **only** if the ``to`` is empty and the ``data``\n * was successfully executed as initcode.\n */\n contractAddress;\n /**\n * The transaction hash.\n */\n hash;\n /**\n * The index of this transaction within the block transactions.\n */\n index;\n /**\n * The block hash of the [[Block]] this transaction was included in.\n */\n blockHash;\n /**\n * The block number of the [[Block]] this transaction was included in.\n */\n blockNumber;\n /**\n * The bloom filter bytes that represent all logs that occurred within\n * this transaction. This is generally not useful for most developers,\n * but can be used to validate the included logs.\n */\n logsBloom;\n /**\n * The actual amount of gas used by this transaction.\n *\n * When creating a transaction, the amount of gas that will be used can\n * only be approximated, but the sender must pay the gas fee for the\n * entire gas limit. After the transaction, the difference is refunded.\n */\n gasUsed;\n /**\n * The gas used for BLObs. See [[link-eip-4844]].\n */\n blobGasUsed;\n /**\n * The amount of gas used by all transactions within the block for this\n * and all transactions with a lower ``index``.\n *\n * This is generally not useful for developers but can be used to\n * validate certain aspects of execution.\n */\n cumulativeGasUsed;\n /**\n * The actual gas price used during execution.\n *\n * Due to the complexity of [[link-eip-1559]] this value can only\n * be caluclated after the transaction has been mined, snce the base\n * fee is protocol-enforced.\n */\n gasPrice;\n /**\n * The price paid per BLOB in gas. See [[link-eip-4844]].\n */\n blobGasPrice;\n /**\n * The [[link-eip-2718]] transaction type.\n */\n type;\n //readonly byzantium!: boolean;\n /**\n * The status of this transaction, indicating success (i.e. ``1``) or\n * a revert (i.e. ``0``).\n *\n * This is available in post-byzantium blocks, but some backends may\n * backfill this value.\n */\n status;\n /**\n * The root hash of this transaction.\n *\n * This is no present and was only included in pre-byzantium blocks, but\n * could be used to validate certain parts of the receipt.\n */\n root;\n #logs;\n /**\n * @_ignore:\n */\n constructor(tx, provider) {\n this.#logs = Object.freeze(tx.logs.map((log) => {\n return new Log(log, provider);\n }));\n let gasPrice = BN_0;\n if (tx.effectiveGasPrice != null) {\n gasPrice = tx.effectiveGasPrice;\n }\n else if (tx.gasPrice != null) {\n gasPrice = tx.gasPrice;\n }\n defineProperties(this, {\n provider,\n to: tx.to,\n from: tx.from,\n contractAddress: tx.contractAddress,\n hash: tx.hash,\n index: tx.index,\n blockHash: tx.blockHash,\n blockNumber: tx.blockNumber,\n logsBloom: tx.logsBloom,\n gasUsed: tx.gasUsed,\n cumulativeGasUsed: tx.cumulativeGasUsed,\n blobGasUsed: tx.blobGasUsed,\n gasPrice,\n blobGasPrice: tx.blobGasPrice,\n type: tx.type,\n //byzantium: tx.byzantium,\n status: tx.status,\n root: tx.root\n });\n }\n /**\n * The logs for this transaction.\n */\n get logs() { return this.#logs; }\n /**\n * Returns a JSON-compatible representation.\n */\n toJSON() {\n const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium, \n status, root } = this;\n return {\n _type: \"TransactionReceipt\",\n blockHash, blockNumber,\n //byzantium, \n contractAddress,\n cumulativeGasUsed: toJson(this.cumulativeGasUsed),\n from,\n gasPrice: toJson(this.gasPrice),\n blobGasUsed: toJson(this.blobGasUsed),\n blobGasPrice: toJson(this.blobGasPrice),\n gasUsed: toJson(this.gasUsed),\n hash, index, logs, logsBloom, root, status, to\n };\n }\n /**\n * @_ignore:\n */\n get length() { return this.logs.length; }\n [Symbol.iterator]() {\n let index = 0;\n return {\n next: () => {\n if (index < this.length) {\n return { value: this.logs[index++], done: false };\n }\n return { value: undefined, done: true };\n }\n };\n }\n /**\n * The total fee for this transaction, in wei.\n */\n get fee() {\n return this.gasUsed * this.gasPrice;\n }\n /**\n * Resolves to the block this transaction occurred in.\n */\n async getBlock() {\n const block = await this.provider.getBlock(this.blockHash);\n if (block == null) {\n throw new Error(\"TODO\");\n }\n return block;\n }\n /**\n * Resolves to the transaction this transaction occurred in.\n */\n async getTransaction() {\n const tx = await this.provider.getTransaction(this.hash);\n if (tx == null) {\n throw new Error(\"TODO\");\n }\n return tx;\n }\n /**\n * Resolves to the return value of the execution of this transaction.\n *\n * Support for this feature is limited, as it requires an archive node\n * with the ``debug_`` or ``trace_`` API enabled.\n */\n async getResult() {\n return (await this.provider.getTransactionResult(this.hash));\n }\n /**\n * Resolves to the number of confirmations this transaction has.\n */\n async confirmations() {\n return (await this.provider.getBlockNumber()) - this.blockNumber + 1;\n }\n /**\n * @_ignore:\n */\n removedEvent() {\n return createRemovedTransactionFilter(this);\n }\n /**\n * @_ignore:\n */\n reorderedEvent(other) {\n assert(!other || other.isMined(), \"unmined 'other' transction cannot be orphaned\", \"UNSUPPORTED_OPERATION\", { operation: \"reorderedEvent(other)\" });\n return createReorderedTransactionFilter(this, other);\n }\n}\n/**\n * A **TransactionResponse** includes all properties about a transaction\n * that was sent to the network, which may or may not be included in a\n * block.\n *\n * The [[TransactionResponse-isMined]] can be used to check if the\n * transaction has been mined as well as type guard that the otherwise\n * possibly ``null`` properties are defined.\n */\nexport class TransactionResponse {\n /**\n * The provider this is connected to, which will influence how its\n * methods will resolve its async inspection methods.\n */\n provider;\n /**\n * The block number of the block that this transaction was included in.\n *\n * This is ``null`` for pending transactions.\n */\n blockNumber;\n /**\n * The blockHash of the block that this transaction was included in.\n *\n * This is ``null`` for pending transactions.\n */\n blockHash;\n /**\n * The index within the block that this transaction resides at.\n */\n index;\n /**\n * The transaction hash.\n */\n hash;\n /**\n * The [[link-eip-2718]] transaction envelope type. This is\n * ``0`` for legacy transactions types.\n */\n type;\n /**\n * The receiver of this transaction.\n *\n * If ``null``, then the transaction is an initcode transaction.\n * This means the result of executing the [[data]] will be deployed\n * as a new contract on chain (assuming it does not revert) and the\n * address may be computed using [[getCreateAddress]].\n */\n to;\n /**\n * The sender of this transaction. It is implicitly computed\n * from the transaction pre-image hash (as the digest) and the\n * [[signature]] using ecrecover.\n */\n from;\n /**\n * The nonce, which is used to prevent replay attacks and offer\n * a method to ensure transactions from a given sender are explicitly\n * ordered.\n *\n * When sending a transaction, this must be equal to the number of\n * transactions ever sent by [[from]].\n */\n nonce;\n /**\n * The maximum units of gas this transaction can consume. If execution\n * exceeds this, the entries transaction is reverted and the sender\n * is charged for the full amount, despite not state changes being made.\n */\n gasLimit;\n /**\n * The gas price can have various values, depending on the network.\n *\n * In modern networks, for transactions that are included this is\n * the //effective gas price// (the fee per gas that was actually\n * charged), while for transactions that have not been included yet\n * is the [[maxFeePerGas]].\n *\n * For legacy transactions, or transactions on legacy networks, this\n * is the fee that will be charged per unit of gas the transaction\n * consumes.\n */\n gasPrice;\n /**\n * The maximum priority fee (per unit of gas) to allow a\n * validator to charge the sender. This is inclusive of the\n * [[maxFeeFeePerGas]].\n */\n maxPriorityFeePerGas;\n /**\n * The maximum fee (per unit of gas) to allow this transaction\n * to charge the sender.\n */\n maxFeePerGas;\n /**\n * The [[link-eip-4844]] max fee per BLOb gas.\n */\n maxFeePerBlobGas;\n /**\n * The data.\n */\n data;\n /**\n * The value, in wei. Use [[formatEther]] to format this value\n * as ether.\n */\n value;\n /**\n * The chain ID.\n */\n chainId;\n /**\n * The signature.\n */\n signature;\n /**\n * The [[link-eip-2930]] access list for transaction types that\n * support it, otherwise ``null``.\n */\n accessList;\n /**\n * The [[link-eip-4844]] BLOb versioned hashes.\n */\n blobVersionedHashes;\n #startBlock;\n /**\n * @_ignore:\n */\n constructor(tx, provider) {\n this.provider = provider;\n this.blockNumber = (tx.blockNumber != null) ? tx.blockNumber : null;\n this.blockHash = (tx.blockHash != null) ? tx.blockHash : null;\n this.hash = tx.hash;\n this.index = tx.index;\n this.type = tx.type;\n this.from = tx.from;\n this.to = tx.to || null;\n this.gasLimit = tx.gasLimit;\n this.nonce = tx.nonce;\n this.data = tx.data;\n this.value = tx.value;\n this.gasPrice = tx.gasPrice;\n this.maxPriorityFeePerGas = (tx.maxPriorityFeePerGas != null) ? tx.maxPriorityFeePerGas : null;\n this.maxFeePerGas = (tx.maxFeePerGas != null) ? tx.maxFeePerGas : null;\n this.maxFeePerBlobGas = (tx.maxFeePerBlobGas != null) ? tx.maxFeePerBlobGas : null;\n this.chainId = tx.chainId;\n this.signature = tx.signature;\n this.accessList = (tx.accessList != null) ? tx.accessList : null;\n this.blobVersionedHashes = (tx.blobVersionedHashes != null) ? tx.blobVersionedHashes : null;\n this.#startBlock = -1;\n }\n /**\n * Returns a JSON-compatible representation of this transaction.\n */\n toJSON() {\n const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, blobVersionedHashes } = this;\n return {\n _type: \"TransactionResponse\",\n accessList, blockNumber, blockHash,\n blobVersionedHashes,\n chainId: toJson(this.chainId),\n data, from,\n gasLimit: toJson(this.gasLimit),\n gasPrice: toJson(this.gasPrice),\n hash,\n maxFeePerGas: toJson(this.maxFeePerGas),\n maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas),\n maxFeePerBlobGas: toJson(this.maxFeePerBlobGas),\n nonce, signature, to, index, type,\n value: toJson(this.value),\n };\n }\n /**\n * Resolves to the Block that this transaction was included in.\n *\n * This will return null if the transaction has not been included yet.\n */\n async getBlock() {\n let blockNumber = this.blockNumber;\n if (blockNumber == null) {\n const tx = await this.getTransaction();\n if (tx) {\n blockNumber = tx.blockNumber;\n }\n }\n if (blockNumber == null) {\n return null;\n }\n const block = this.provider.getBlock(blockNumber);\n if (block == null) {\n throw new Error(\"TODO\");\n }\n return block;\n }\n /**\n * Resolves to this transaction being re-requested from the\n * provider. This can be used if you have an unmined transaction\n * and wish to get an up-to-date populated instance.\n */\n async getTransaction() {\n return this.provider.getTransaction(this.hash);\n }\n /**\n * Resolve to the number of confirmations this transaction has.\n */\n async confirmations() {\n if (this.blockNumber == null) {\n const { tx, blockNumber } = await resolveProperties({\n tx: this.getTransaction(),\n blockNumber: this.provider.getBlockNumber()\n });\n // Not mined yet...\n if (tx == null || tx.blockNumber == null) {\n return 0;\n }\n return blockNumber - tx.blockNumber + 1;\n }\n const blockNumber = await this.provider.getBlockNumber();\n return blockNumber - this.blockNumber + 1;\n }\n /**\n * Resolves once this transaction has been mined and has\n * %%confirms%% blocks including it (default: ``1``) with an\n * optional %%timeout%%.\n *\n * This can resolve to ``null`` only if %%confirms%% is ``0``\n * and the transaction has not been mined, otherwise this will\n * wait until enough confirmations have completed.\n */\n async wait(_confirms, _timeout) {\n const confirms = (_confirms == null) ? 1 : _confirms;\n const timeout = (_timeout == null) ? 0 : _timeout;\n let startBlock = this.#startBlock;\n let nextScan = -1;\n let stopScanning = (startBlock === -1) ? true : false;\n const checkReplacement = async () => {\n // Get the current transaction count for this sender\n if (stopScanning) {\n return null;\n }\n const { blockNumber, nonce } = await resolveProperties({\n blockNumber: this.provider.getBlockNumber(),\n nonce: this.provider.getTransactionCount(this.from)\n });\n // No transaction or our nonce has not been mined yet; but we\n // can start scanning later when we do start\n if (nonce < this.nonce) {\n startBlock = blockNumber;\n return;\n }\n // We were mined; no replacement\n if (stopScanning) {\n return null;\n }\n const mined = await this.getTransaction();\n if (mined && mined.blockNumber != null) {\n return;\n }\n // We were replaced; start scanning for that transaction\n // Starting to scan; look back a few extra blocks for safety\n if (nextScan === -1) {\n nextScan = startBlock - 3;\n if (nextScan < this.#startBlock) {\n nextScan = this.#startBlock;\n }\n }\n while (nextScan <= blockNumber) {\n // Get the next block to scan\n if (stopScanning) {\n return null;\n }\n const block = await this.provider.getBlock(nextScan, true);\n // This should not happen; but we'll try again shortly\n if (block == null) {\n return;\n }\n // We were mined; no replacement\n for (const hash of block) {\n if (hash === this.hash) {\n return;\n }\n }\n // Search for the transaction that replaced us\n for (let i = 0; i < block.length; i++) {\n const tx = await block.getTransaction(i);\n if (tx.from === this.from && tx.nonce === this.nonce) {\n // Get the receipt\n if (stopScanning) {\n return null;\n }\n const receipt = await this.provider.getTransactionReceipt(tx.hash);\n // This should not happen; but we'll try again shortly\n if (receipt == null) {\n return;\n }\n // We will retry this on the next block (this case could be optimized)\n if ((blockNumber - receipt.blockNumber + 1) < confirms) {\n return;\n }\n // The reason we were replaced\n let reason = \"replaced\";\n if (tx.data === this.data && tx.to === this.to && tx.value === this.value) {\n reason = \"repriced\";\n }\n else if (tx.data === \"0x\" && tx.from === tx.to && tx.value === BN_0) {\n reason = \"cancelled\";\n }\n assert(false, \"transaction was replaced\", \"TRANSACTION_REPLACED\", {\n cancelled: (reason === \"replaced\" || reason === \"cancelled\"),\n reason,\n replacement: tx.replaceableTransaction(startBlock),\n hash: tx.hash,\n receipt\n });\n }\n }\n nextScan++;\n }\n return;\n };\n const checkReceipt = (receipt) => {\n if (receipt == null || receipt.status !== 0) {\n return receipt;\n }\n assert(false, \"transaction execution reverted\", \"CALL_EXCEPTION\", {\n action: \"sendTransaction\",\n data: null, reason: null, invocation: null, revert: null,\n transaction: {\n to: receipt.to,\n from: receipt.from,\n data: \"\" // @TODO: in v7, split out sendTransaction properties\n }, receipt\n });\n };\n const receipt = await this.provider.getTransactionReceipt(this.hash);\n if (confirms === 0) {\n return checkReceipt(receipt);\n }\n if (receipt) {\n if ((await receipt.confirmations()) >= confirms) {\n return checkReceipt(receipt);\n }\n }\n else {\n // Check for a replacement; throws if a replacement was found\n await checkReplacement();\n // Allow null only when the confirms is 0\n if (confirms === 0) {\n return null;\n }\n }\n const waiter = new Promise((resolve, reject) => {\n // List of things to cancel when we have a result (one way or the other)\n const cancellers = [];\n const cancel = () => { cancellers.forEach((c) => c()); };\n // On cancel, stop scanning for replacements\n cancellers.push(() => { stopScanning = true; });\n // Set up any timeout requested\n if (timeout > 0) {\n const timer = setTimeout(() => {\n cancel();\n reject(makeError(\"wait for transaction timeout\", \"TIMEOUT\"));\n }, timeout);\n cancellers.push(() => { clearTimeout(timer); });\n }\n const txListener = async (receipt) => {\n // Done; return it!\n if ((await receipt.confirmations()) >= confirms) {\n cancel();\n try {\n resolve(checkReceipt(receipt));\n }\n catch (error) {\n reject(error);\n }\n }\n };\n cancellers.push(() => { this.provider.off(this.hash, txListener); });\n this.provider.on(this.hash, txListener);\n // We support replacement detection; start checking\n if (startBlock >= 0) {\n const replaceListener = async () => {\n try {\n // Check for a replacement; this throws only if one is found\n await checkReplacement();\n }\n catch (error) {\n // We were replaced (with enough confirms); re-throw the error\n if (isError(error, \"TRANSACTION_REPLACED\")) {\n cancel();\n reject(error);\n return;\n }\n }\n // Rescheudle a check on the next block\n if (!stopScanning) {\n this.provider.once(\"block\", replaceListener);\n }\n };\n cancellers.push(() => { this.provider.off(\"block\", replaceListener); });\n this.provider.once(\"block\", replaceListener);\n }\n });\n return await waiter;\n }\n /**\n * Returns ``true`` if this transaction has been included.\n *\n * This is effective only as of the time the TransactionResponse\n * was instantiated. To get up-to-date information, use\n * [[getTransaction]].\n *\n * This provides a Type Guard that this transaction will have\n * non-null property values for properties that are null for\n * unmined transactions.\n */\n isMined() {\n return (this.blockHash != null);\n }\n /**\n * Returns true if the transaction is a legacy (i.e. ``type == 0``)\n * transaction.\n *\n * This provides a Type Guard that this transaction will have\n * the ``null``-ness for hardfork-specific properties set correctly.\n */\n isLegacy() {\n return (this.type === 0);\n }\n /**\n * Returns true if the transaction is a Berlin (i.e. ``type == 1``)\n * transaction. See [[link-eip-2070]].\n *\n * This provides a Type Guard that this transaction will have\n * the ``null``-ness for hardfork-specific properties set correctly.\n */\n isBerlin() {\n return (this.type === 1);\n }\n /**\n * Returns true if the transaction is a London (i.e. ``type == 2``)\n * transaction. See [[link-eip-1559]].\n *\n * This provides a Type Guard that this transaction will have\n * the ``null``-ness for hardfork-specific properties set correctly.\n */\n isLondon() {\n return (this.type === 2);\n }\n /**\n * Returns true if hte transaction is a Cancun (i.e. ``type == 3``)\n * transaction. See [[link-eip-4844]].\n */\n isCancun() {\n return (this.type === 3);\n }\n /**\n * Returns a filter which can be used to listen for orphan events\n * that evict this transaction.\n */\n removedEvent() {\n assert(this.isMined(), \"unmined transaction canot be orphaned\", \"UNSUPPORTED_OPERATION\", { operation: \"removeEvent()\" });\n return createRemovedTransactionFilter(this);\n }\n /**\n * Returns a filter which can be used to listen for orphan events\n * that re-order this event against %%other%%.\n */\n reorderedEvent(other) {\n assert(this.isMined(), \"unmined transaction canot be orphaned\", \"UNSUPPORTED_OPERATION\", { operation: \"removeEvent()\" });\n assert(!other || other.isMined(), \"unmined 'other' transaction canot be orphaned\", \"UNSUPPORTED_OPERATION\", { operation: \"removeEvent()\" });\n return createReorderedTransactionFilter(this, other);\n }\n /**\n * Returns a new TransactionResponse instance which has the ability to\n * detect (and throw an error) if the transaction is replaced, which\n * will begin scanning at %%startBlock%%.\n *\n * This should generally not be used by developers and is intended\n * primarily for internal use. Setting an incorrect %%startBlock%% can\n * have devastating performance consequences if used incorrectly.\n */\n replaceableTransaction(startBlock) {\n assertArgument(Number.isInteger(startBlock) && startBlock >= 0, \"invalid startBlock\", \"startBlock\", startBlock);\n const tx = new TransactionResponse(this, this.provider);\n tx.#startBlock = startBlock;\n return tx;\n }\n}\nfunction createOrphanedBlockFilter(block) {\n return { orphan: \"drop-block\", hash: block.hash, number: block.number };\n}\nfunction createReorderedTransactionFilter(tx, other) {\n return { orphan: \"reorder-transaction\", tx, other };\n}\nfunction createRemovedTransactionFilter(tx) {\n return { orphan: \"drop-transaction\", tx };\n}\nfunction createRemovedLogFilter(log) {\n return { orphan: \"drop-log\", log: {\n transactionHash: log.transactionHash,\n blockHash: log.blockHash,\n blockNumber: log.blockNumber,\n address: log.address,\n data: log.data,\n topics: Object.freeze(log.topics.slice()),\n index: log.index\n } };\n}\n//# sourceMappingURL=provider.js.map","// import from provider.ts instead of index.ts to prevent circular dep\n// from EtherscanProvider\nimport { Log, TransactionReceipt, TransactionResponse } from \"../providers/provider.js\";\nimport { defineProperties, EventPayload } from \"../utils/index.js\";\n/**\n * An **EventLog** contains additional properties parsed from the [[Log]].\n */\nexport class EventLog extends Log {\n /**\n * The Contract Interface.\n */\n interface;\n /**\n * The matching event.\n */\n fragment;\n /**\n * The parsed arguments passed to the event by ``emit``.\n */\n args;\n /**\n * @_ignore:\n */\n constructor(log, iface, fragment) {\n super(log, log.provider);\n const args = iface.decodeEventLog(fragment, log.data, log.topics);\n defineProperties(this, { args, fragment, interface: iface });\n }\n /**\n * The name of the event.\n */\n get eventName() { return this.fragment.name; }\n /**\n * The signature of the event.\n */\n get eventSignature() { return this.fragment.format(); }\n}\n/**\n * An **EventLog** contains additional properties parsed from the [[Log]].\n */\nexport class UndecodedEventLog extends Log {\n /**\n * The error encounted when trying to decode the log.\n */\n error;\n /**\n * @_ignore:\n */\n constructor(log, error) {\n super(log, log.provider);\n defineProperties(this, { error });\n }\n}\n/**\n * A **ContractTransactionReceipt** includes the parsed logs from a\n * [[TransactionReceipt]].\n */\nexport class ContractTransactionReceipt extends TransactionReceipt {\n #iface;\n /**\n * @_ignore:\n */\n constructor(iface, provider, tx) {\n super(tx, provider);\n this.#iface = iface;\n }\n /**\n * The parsed logs for any [[Log]] which has a matching event in the\n * Contract ABI.\n */\n get logs() {\n return super.logs.map((log) => {\n const fragment = log.topics.length ? this.#iface.getEvent(log.topics[0]) : null;\n if (fragment) {\n try {\n return new EventLog(log, this.#iface, fragment);\n }\n catch (error) {\n return new UndecodedEventLog(log, error);\n }\n }\n return log;\n });\n }\n}\n/**\n * A **ContractTransactionResponse** will return a\n * [[ContractTransactionReceipt]] when waited on.\n */\nexport class ContractTransactionResponse extends TransactionResponse {\n #iface;\n /**\n * @_ignore:\n */\n constructor(iface, provider, tx) {\n super(tx, provider);\n this.#iface = iface;\n }\n /**\n * Resolves once this transaction has been mined and has\n * %%confirms%% blocks including it (default: ``1``) with an\n * optional %%timeout%%.\n *\n * This can resolve to ``null`` only if %%confirms%% is ``0``\n * and the transaction has not been mined, otherwise this will\n * wait until enough confirmations have completed.\n */\n async wait(confirms, timeout) {\n const receipt = await super.wait(confirms, timeout);\n if (receipt == null) {\n return null;\n }\n return new ContractTransactionReceipt(this.#iface, this.provider, receipt);\n }\n}\n/**\n * A **ContractUnknownEventPayload** is included as the last parameter to\n * Contract Events when the event does not match any events in the ABI.\n */\nexport class ContractUnknownEventPayload extends EventPayload {\n /**\n * The log with no matching events.\n */\n log;\n /**\n * @_event:\n */\n constructor(contract, listener, filter, log) {\n super(contract, listener, filter);\n defineProperties(this, { log });\n }\n /**\n * Resolves to the block the event occured in.\n */\n async getBlock() {\n return await this.log.getBlock();\n }\n /**\n * Resolves to the transaction the event occured in.\n */\n async getTransaction() {\n return await this.log.getTransaction();\n }\n /**\n * Resolves to the transaction receipt the event occured in.\n */\n async getTransactionReceipt() {\n return await this.log.getTransactionReceipt();\n }\n}\n/**\n * A **ContractEventPayload** is included as the last parameter to\n * Contract Events when the event is known.\n */\nexport class ContractEventPayload extends ContractUnknownEventPayload {\n /**\n * @_ignore:\n */\n constructor(contract, listener, filter, fragment, _log) {\n super(contract, listener, filter, new EventLog(_log, contract.interface, fragment));\n const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics);\n defineProperties(this, { args, fragment });\n }\n /**\n * The event name.\n */\n get eventName() {\n return this.fragment.name;\n }\n /**\n * The event signature.\n */\n get eventSignature() {\n return this.fragment.format();\n }\n}\n//# sourceMappingURL=wrappers.js.map","import { Interface, Typed } from \"../abi/index.js\";\nimport { isAddressable, resolveAddress } from \"../address/index.js\";\n// import from provider.ts instead of index.ts to prevent circular dep\n// from EtherscanProvider\nimport { copyRequest, Log } from \"../providers/provider.js\";\nimport { defineProperties, getBigInt, isCallException, isHexString, resolveProperties, isError, makeError, assert, assertArgument } from \"../utils/index.js\";\nimport { ContractEventPayload, ContractUnknownEventPayload, ContractTransactionResponse, EventLog, UndecodedEventLog } from \"./wrappers.js\";\nconst BN_0 = BigInt(0);\nfunction canCall(value) {\n return (value && typeof (value.call) === \"function\");\n}\nfunction canEstimate(value) {\n return (value && typeof (value.estimateGas) === \"function\");\n}\nfunction canResolve(value) {\n return (value && typeof (value.resolveName) === \"function\");\n}\nfunction canSend(value) {\n return (value && typeof (value.sendTransaction) === \"function\");\n}\nfunction getResolver(value) {\n if (value != null) {\n if (canResolve(value)) {\n return value;\n }\n if (value.provider) {\n return value.provider;\n }\n }\n return undefined;\n}\nclass PreparedTopicFilter {\n #filter;\n fragment;\n constructor(contract, fragment, args) {\n defineProperties(this, { fragment });\n if (fragment.inputs.length < args.length) {\n throw new Error(\"too many arguments\");\n }\n // Recursively descend into args and resolve any addresses\n const runner = getRunner(contract.runner, \"resolveName\");\n const resolver = canResolve(runner) ? runner : null;\n this.#filter = (async function () {\n const resolvedArgs = await Promise.all(fragment.inputs.map((param, index) => {\n const arg = args[index];\n if (arg == null) {\n return null;\n }\n return param.walkAsync(args[index], (type, value) => {\n if (type === \"address\") {\n if (Array.isArray(value)) {\n return Promise.all(value.map((v) => resolveAddress(v, resolver)));\n }\n return resolveAddress(value, resolver);\n }\n return value;\n });\n }));\n return contract.interface.encodeFilterTopics(fragment, resolvedArgs);\n })();\n }\n getTopicFilter() {\n return this.#filter;\n }\n}\n// A = Arguments passed in as a tuple\n// R = The result type of the call (i.e. if only one return type,\n// the qualified type, otherwise Result)\n// D = The type the default call will return (i.e. R for view/pure,\n// TransactionResponse otherwise)\n//export interface ContractMethod<A extends Array<any> = Array<any>, R = any, D extends R | ContractTransactionResponse = ContractTransactionResponse> {\nfunction getRunner(value, feature) {\n if (value == null) {\n return null;\n }\n if (typeof (value[feature]) === \"function\") {\n return value;\n }\n if (value.provider && typeof (value.provider[feature]) === \"function\") {\n return value.provider;\n }\n return null;\n}\nfunction getProvider(value) {\n if (value == null) {\n return null;\n }\n return value.provider || null;\n}\n/**\n * @_ignore:\n */\nexport async function copyOverrides(arg, allowed) {\n // Make sure the overrides passed in are a valid overrides object\n const _overrides = Typed.dereference(arg, \"overrides\");\n assertArgument(typeof (_overrides) === \"object\", \"invalid overrides parameter\", \"overrides\", arg);\n // Create a shallow copy (we'll deep-ify anything needed during normalizing)\n const overrides = copyRequest(_overrides);\n assertArgument(overrides.to == null || (allowed || []).indexOf(\"to\") >= 0, \"cannot override to\", \"overrides.to\", overrides.to);\n assertArgument(overrides.data == null || (allowed || []).indexOf(\"data\") >= 0, \"cannot override data\", \"overrides.data\", overrides.data);\n // Resolve any from\n if (overrides.from) {\n overrides.from = overrides.from;\n }\n return overrides;\n}\n/**\n * @_ignore:\n */\nexport async function resolveArgs(_runner, inputs, args) {\n // Recursively descend into args and resolve any addresses\n const runner = getRunner(_runner, \"resolveName\");\n const resolver = canResolve(runner) ? runner : null;\n return await Promise.all(inputs.map((param, index) => {\n return param.walkAsync(args[index], (type, value) => {\n value = Typed.dereference(value, type);\n if (type === \"address\") {\n return resolveAddress(value, resolver);\n }\n return value;\n });\n }));\n}\nfunction buildWrappedFallback(contract) {\n const populateTransaction = async function (overrides) {\n // If an overrides was passed in, copy it and normalize the values\n const tx = (await copyOverrides(overrides, [\"data\"]));\n tx.to = await contract.getAddress();\n if (tx.from) {\n tx.from = await resolveAddress(tx.from, getResolver(contract.runner));\n }\n const iface = contract.interface;\n const noValue = (getBigInt((tx.value || BN_0), \"overrides.value\") === BN_0);\n const noData = ((tx.data || \"0x\") === \"0x\");\n if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) {\n assertArgument(false, \"cannot send data to receive or send value to non-payable fallback\", \"overrides\", overrides);\n }\n assertArgument(iface.fallback || noData, \"cannot send data to receive-only contract\", \"overrides.data\", tx.data);\n // Only allow payable contracts to set non-zero value\n const payable = iface.receive || (iface.fallback && iface.fallback.payable);\n assertArgument(payable || noValue, \"cannot send value to non-payable fallback\", \"overrides.value\", tx.value);\n // Only allow fallback contracts to set non-empty data\n assertArgument(iface.fallback || noData, \"cannot send data to receive-only contract\", \"overrides.data\", tx.data);\n return tx;\n };\n const staticCall = async function (overrides) {\n const runner = getRunner(contract.runner, \"call\");\n assert(canCall(runner), \"contract runner does not support calling\", \"UNSUPPORTED_OPERATION\", { operation: \"call\" });\n const tx = await populateTransaction(overrides);\n try {\n return await runner.call(tx);\n }\n catch (error) {\n if (isCallException(error) && error.data) {\n throw contract.interface.makeError(error.data, tx);\n }\n throw error;\n }\n };\n const send = async function (overrides) {\n const runner = contract.runner;\n assert(canSend(runner), \"contract runner does not support sending transactions\", \"UNSUPPORTED_OPERATION\", { operation: \"sendTransaction\" });\n const tx = await runner.sendTransaction(await populateTransaction(overrides));\n const provider = getProvider(contract.runner);\n // @TODO: the provider can be null; make a custom dummy provider that will throw a\n // meaningful error\n return new ContractTransactionResponse(contract.interface, provider, tx);\n };\n const estimateGas = async function (overrides) {\n const runner = getRunner(contract.runner, \"estimateGas\");\n assert(canEstimate(runner), \"contract runner does not support gas estimation\", \"UNSUPPORTED_OPERATION\", { operation: \"estimateGas\" });\n return await runner.estimateGas(await populateTransaction(overrides));\n };\n const method = async (overrides) => {\n return await send(overrides);\n };\n defineProperties(method, {\n _contract: contract,\n estimateGas,\n populateTransaction,\n send, staticCall\n });\n return method;\n}\nfunction buildWrappedMethod(contract, key) {\n const getFragment = function (...args) {\n const fragment = contract.interface.getFunction(key, args);\n assert(fragment, \"no matching fragment\", \"UNSUPPORTED_OPERATION\", {\n operation: \"fragment\",\n info: { key, args }\n });\n return fragment;\n };\n const populateTransaction = async function (...args) {\n const fragment = getFragment(...args);\n // If an overrides was passed in, copy it and normalize the values\n let overrides = {};\n if (fragment.inputs.length + 1 === args.length) {\n overrides = await copyOverrides(args.pop());\n if (overrides.from) {\n overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner));\n }\n }\n if (fragment.inputs.length !== args.length) {\n throw new Error(\"internal error: fragment inputs doesn't match arguments; should not happen\");\n }\n const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args);\n return Object.assign({}, overrides, await resolveProperties({\n to: contract.getAddress(),\n data: contract.interface.encodeFunctionData(fragment, resolvedArgs)\n }));\n };\n const staticCall = async function (...args) {\n const result = await staticCallResult(...args);\n if (result.length === 1) {\n return result[0];\n }\n return result;\n };\n const send = async function (...args) {\n const runner = contract.runner;\n assert(canSend(runner), \"contract runner does not support sending transactions\", \"UNSUPPORTED_OPERATION\", { operation: \"sendTransaction\" });\n const tx = await runner.sendTransaction(await populateTransaction(...args));\n const provider = getProvider(contract.runner);\n // @TODO: the provider can be null; make a custom dummy provider that will throw a\n // meaningful error\n return new ContractTransactionResponse(contract.interface, provider, tx);\n };\n const estimateGas = async function (...args) {\n const runner = getRunner(contract.runner, \"estimateGas\");\n assert(canEstimate(runner), \"contract runner does not support gas estimation\", \"UNSUPPORTED_OPERATION\", { operation: \"estimateGas\" });\n return await runner.estimateGas(await populateTransaction(...args));\n };\n const staticCallResult = async function (...args) {\n const runner = getRunner(contract.runner, \"call\");\n assert(canCall(runner), \"contract runner does not support calling\", \"UNSUPPORTED_OPERATION\", { operation: \"call\" });\n const tx = await populateTransaction(...args);\n let result = \"0x\";\n try {\n result = await runner.call(tx);\n }\n catch (error) {\n if (isCallException(error) && error.data) {\n throw contract.interface.makeError(error.data, tx);\n }\n throw error;\n }\n const fragment = getFragment(...args);\n return contract.interface.decodeFunctionResult(fragment, result);\n };\n const method = async (...args) => {\n const fragment = getFragment(...args);\n if (fragment.constant) {\n return await staticCall(...args);\n }\n return await send(...args);\n };\n defineProperties(method, {\n name: contract.interface.getFunctionName(key),\n _contract: contract, _key: key,\n getFragment,\n estimateGas,\n populateTransaction,\n send, staticCall, staticCallResult,\n });\n // Only works on non-ambiguous keys (refined fragment is always non-ambiguous)\n Object.defineProperty(method, \"fragment\", {\n configurable: false,\n enumerable: true,\n get: () => {\n const fragment = contract.interface.getFunction(key);\n assert(fragment, \"no matching fragment\", \"UNSUPPORTED_OPERATION\", {\n operation: \"fragment\",\n info: { key }\n });\n return fragment;\n }\n });\n return method;\n}\nfunction buildWrappedEvent(contract, key) {\n const getFragment = function (...args) {\n const fragment = contract.interface.getEvent(key, args);\n assert(fragment, \"no matching fragment\", \"UNSUPPORTED_OPERATION\", {\n operation: \"fragment\",\n info: { key, args }\n });\n return fragment;\n };\n const method = function (...args) {\n return new PreparedTopicFilter(contract, getFragment(...args), args);\n };\n defineProperties(method, {\n name: contract.interface.getEventName(key),\n _contract: contract, _key: key,\n getFragment\n });\n // Only works on non-ambiguous keys (refined fragment is always non-ambiguous)\n Object.defineProperty(method, \"fragment\", {\n configurable: false,\n enumerable: true,\n get: () => {\n const fragment = contract.interface.getEvent(key);\n assert(fragment, \"no matching fragment\", \"UNSUPPORTED_OPERATION\", {\n operation: \"fragment\",\n info: { key }\n });\n return fragment;\n }\n });\n return method;\n}\n// The combination of TypeScrype, Private Fields and Proxies makes\n// the world go boom; so we hide variables with some trickery keeping\n// a symbol attached to each BaseContract which its sub-class (even\n// via a Proxy) can reach and use to look up its internal values.\nconst internal = Symbol.for(\"_ethersInternal_contract\");\nconst internalValues = new WeakMap();\nfunction setInternal(contract, values) {\n internalValues.set(contract[internal], values);\n}\nfunction getInternal(contract) {\n return internalValues.get(contract[internal]);\n}\nfunction isDeferred(value) {\n return (value && typeof (value) === \"object\" && (\"getTopicFilter\" in value) &&\n (typeof (value.getTopicFilter) === \"function\") && value.fragment);\n}\nasync function getSubInfo(contract, event) {\n let topics;\n let fragment = null;\n // Convert named events to topicHash and get the fragment for\n // events which need deconstructing.\n if (Array.isArray(event)) {\n const topicHashify = function (name) {\n if (isHexString(name, 32)) {\n return name;\n }\n const fragment = contract.interface.getEvent(name);\n assertArgument(fragment, \"unknown fragment\", \"name\", name);\n return fragment.topicHash;\n };\n // Array of Topics and Names; e.g. `[ \"0x1234...89ab\", \"Transfer(address)\" ]`\n topics = event.map((e) => {\n if (e == null) {\n return null;\n }\n if (Array.isArray(e)) {\n return e.map(topicHashify);\n }\n return topicHashify(e);\n });\n }\n else if (event === \"*\") {\n topics = [null];\n }\n else if (typeof (event) === \"string\") {\n if (isHexString(event, 32)) {\n // Topic Hash\n topics = [event];\n }\n else {\n // Name or Signature; e.g. `\"Transfer\", `\"Transfer(address)\"`\n fragment = contract.interface.getEvent(event);\n assertArgument(fragment, \"unknown fragment\", \"event\", event);\n topics = [fragment.topicHash];\n }\n }\n else if (isDeferred(event)) {\n // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)`\n topics = await event.getTopicFilter();\n }\n else if (\"fragment\" in event) {\n // ContractEvent; e.g. `contract.filter.Transfer`\n fragment = event.fragment;\n topics = [fragment.topicHash];\n }\n else {\n assertArgument(false, \"unknown event name\", \"event\", event);\n }\n // Normalize topics and sort TopicSets\n topics = topics.map((t) => {\n if (t == null) {\n return null;\n }\n if (Array.isArray(t)) {\n const items = Array.from(new Set(t.map((t) => t.toLowerCase())).values());\n if (items.length === 1) {\n return items[0];\n }\n items.sort();\n return items;\n }\n return t.toLowerCase();\n });\n const tag = topics.map((t) => {\n if (t == null) {\n return \"null\";\n }\n if (Array.isArray(t)) {\n return t.join(\"|\");\n }\n return t;\n }).join(\"&\");\n return { fragment, tag, topics };\n}\nasync function hasSub(contract, event) {\n const { subs } = getInternal(contract);\n return subs.get((await getSubInfo(contract, event)).tag) || null;\n}\nasync function getSub(contract, operation, event) {\n // Make sure our runner can actually subscribe to events\n const provider = getProvider(contract.runner);\n assert(provider, \"contract runner does not support subscribing\", \"UNSUPPORTED_OPERATION\", { operation });\n const { fragment, tag, topics } = await getSubInfo(contract, event);\n const { addr, subs } = getInternal(contract);\n let sub = subs.get(tag);\n if (!sub) {\n const address = (addr ? addr : contract);\n const filter = { address, topics };\n const listener = (log) => {\n let foundFragment = fragment;\n if (foundFragment == null) {\n try {\n foundFragment = contract.interface.getEvent(log.topics[0]);\n }\n catch (error) { }\n }\n // If fragment is null, we do not deconstruct the args to emit\n if (foundFragment) {\n const _foundFragment = foundFragment;\n const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : [];\n emit(contract, event, args, (listener) => {\n return new ContractEventPayload(contract, listener, event, _foundFragment, log);\n });\n }\n else {\n emit(contract, event, [], (listener) => {\n return new ContractUnknownEventPayload(contract, listener, event, log);\n });\n }\n };\n let starting = [];\n const start = () => {\n if (starting.length) {\n return;\n }\n starting.push(provider.on(filter, listener));\n };\n const stop = async () => {\n if (starting.length == 0) {\n return;\n }\n let started = starting;\n starting = [];\n await Promise.all(started);\n provider.off(filter, listener);\n };\n sub = { tag, listeners: [], start, stop };\n subs.set(tag, sub);\n }\n return sub;\n}\n// We use this to ensure one emit resolves before firing the next to\n// ensure correct ordering (note this cannot throw and just adds the\n// notice to the event queu using setTimeout).\nlet lastEmit = Promise.resolve();\nasync function _emit(contract, event, args, payloadFunc) {\n await lastEmit;\n const sub = await hasSub(contract, event);\n if (!sub) {\n return false;\n }\n const count = sub.listeners.length;\n sub.listeners = sub.listeners.filter(({ listener, once }) => {\n const passArgs = Array.from(args);\n if (payloadFunc) {\n passArgs.push(payloadFunc(once ? null : listener));\n }\n try {\n listener.call(contract, ...passArgs);\n }\n catch (error) { }\n return !once;\n });\n if (sub.listeners.length === 0) {\n sub.stop();\n getInternal(contract).subs.delete(sub.tag);\n }\n return (count > 0);\n}\nasync function emit(contract, event, args, payloadFunc) {\n try {\n await lastEmit;\n }\n catch (error) { }\n const resultPromise = _emit(contract, event, args, payloadFunc);\n lastEmit = resultPromise;\n return await resultPromise;\n}\nconst passProperties = [\"then\"];\nexport class BaseContract {\n /**\n * The target to connect to.\n *\n * This can be an address, ENS name or any [[Addressable]], such as\n * another contract. To get the resovled address, use the ``getAddress``\n * method.\n */\n target;\n /**\n * The contract Interface.\n */\n interface;\n /**\n * The connected runner. This is generally a [[Provider]] or a\n * [[Signer]], which dictates what operations are supported.\n *\n * For example, a **Contract** connected to a [[Provider]] may\n * only execute read-only operations.\n */\n runner;\n /**\n * All the Events available on this contract.\n */\n filters;\n /**\n * @_ignore:\n */\n [internal];\n /**\n * The fallback or receive function if any.\n */\n fallback;\n /**\n * Creates a new contract connected to %%target%% with the %%abi%% and\n * optionally connected to a %%runner%% to perform operations on behalf\n * of.\n */\n constructor(target, abi, runner, _deployTx) {\n assertArgument(typeof (target) === \"string\" || isAddressable(target), \"invalid value for Contract target\", \"target\", target);\n if (runner == null) {\n runner = null;\n }\n const iface = Interface.from(abi);\n defineProperties(this, { target, runner, interface: iface });\n Object.defineProperty(this, internal, { value: {} });\n let addrPromise;\n let addr = null;\n let deployTx = null;\n if (_deployTx) {\n const provider = getProvider(runner);\n // @TODO: the provider can be null; make a custom dummy provider that will throw a\n // meaningful error\n deployTx = new ContractTransactionResponse(this.interface, provider, _deployTx);\n }\n let subs = new Map();\n // Resolve the target as the address\n if (typeof (target) === \"string\") {\n if (isHexString(target)) {\n addr = target;\n addrPromise = Promise.resolve(target);\n }\n else {\n const resolver = getRunner(runner, \"resolveName\");\n if (!canResolve(resolver)) {\n throw makeError(\"contract runner does not support name resolution\", \"UNSUPPORTED_OPERATION\", {\n operation: \"resolveName\"\n });\n }\n addrPromise = resolver.resolveName(target).then((addr) => {\n if (addr == null) {\n throw makeError(\"an ENS name used for a contract target must be correctly configured\", \"UNCONFIGURED_NAME\", {\n value: target\n });\n }\n getInternal(this).addr = addr;\n return addr;\n });\n }\n }\n else {\n addrPromise = target.getAddress().then((addr) => {\n if (addr == null) {\n throw new Error(\"TODO\");\n }\n getInternal(this).addr = addr;\n return addr;\n });\n }\n // Set our private values\n setInternal(this, { addrPromise, addr, deployTx, subs });\n // Add the event filters\n const filters = new Proxy({}, {\n get: (target, prop, receiver) => {\n // Pass important checks (like `then` for Promise) through\n if (typeof (prop) === \"symbol\" || passProperties.indexOf(prop) >= 0) {\n return Reflect.get(target, prop, receiver);\n }\n try {\n return this.getEvent(prop);\n }\n catch (error) {\n if (!isError(error, \"INVALID_ARGUMENT\") || error.argument !== \"key\") {\n throw error;\n }\n }\n return undefined;\n },\n has: (target, prop) => {\n // Pass important checks (like `then` for Promise) through\n if (passProperties.indexOf(prop) >= 0) {\n return Reflect.has(target, prop);\n }\n return Reflect.has(target, prop) || this.interface.hasEvent(String(prop));\n }\n });\n defineProperties(this, { filters });\n defineProperties(this, {\n fallback: ((iface.receive || iface.fallback) ? (buildWrappedFallback(this)) : null)\n });\n // Return a Proxy that will respond to functions\n return new Proxy(this, {\n get: (target, prop, receiver) => {\n if (typeof (prop) === \"symbol\" || prop in target || passProperties.indexOf(prop) >= 0) {\n return Reflect.get(target, prop, receiver);\n }\n // Undefined properties should return undefined\n try {\n return target.getFunction(prop);\n }\n catch (error) {\n if (!isError(error, \"INVALID_ARGUMENT\") || error.argument !== \"key\") {\n throw error;\n }\n }\n return undefined;\n },\n has: (target, prop) => {\n if (typeof (prop) === \"symbol\" || prop in target || passProperties.indexOf(prop) >= 0) {\n return Reflect.has(target, prop);\n }\n return target.interface.hasFunction(prop);\n }\n });\n }\n /**\n * Return a new Contract instance with the same target and ABI, but\n * a different %%runner%%.\n */\n connect(runner) {\n return new BaseContract(this.target, this.interface, runner);\n }\n /**\n * Return a new Contract instance with the same ABI and runner, but\n * a different %%target%%.\n */\n attach(target) {\n return new BaseContract(target, this.interface, this.runner);\n }\n /**\n * Return the resolved address of this Contract.\n */\n async getAddress() { return await getInternal(this).addrPromise; }\n /**\n * Return the deployed bytecode or null if no bytecode is found.\n */\n async getDeployedCode() {\n const provider = getProvider(this.runner);\n assert(provider, \"runner does not support .provider\", \"UNSUPPORTED_OPERATION\", { operation: \"getDeployedCode\" });\n const code = await provider.getCode(await this.getAddress());\n if (code === \"0x\") {\n return null;\n }\n return code;\n }\n /**\n * Resolve to this Contract once the bytecode has been deployed, or\n * resolve immediately if already deployed.\n */\n async waitForDeployment() {\n // We have the deployement transaction; just use that (throws if deployement fails)\n const deployTx = this.deploymentTransaction();\n if (deployTx) {\n await deployTx.wait();\n return this;\n }\n // Check for code\n const code = await this.getDeployedCode();\n if (code != null) {\n return this;\n }\n // Make sure we can subscribe to a provider event\n const provider = getProvider(this.runner);\n assert(provider != null, \"contract runner does not support .provider\", \"UNSUPPORTED_OPERATION\", { operation: \"waitForDeployment\" });\n return new Promise((resolve, reject) => {\n const checkCode = async () => {\n try {\n const code = await this.getDeployedCode();\n if (code != null) {\n return resolve(this);\n }\n provider.once(\"block\", checkCode);\n }\n catch (error) {\n reject(error);\n }\n };\n checkCode();\n });\n }\n /**\n * Return the transaction used to deploy this contract.\n *\n * This is only available if this instance was returned from a\n * [[ContractFactory]].\n */\n deploymentTransaction() {\n return getInternal(this).deployTx;\n }\n /**\n * Return the function for a given name. This is useful when a contract\n * method name conflicts with a JavaScript name such as ``prototype`` or\n * when using a Contract programatically.\n */\n getFunction(key) {\n if (typeof (key) !== \"string\") {\n key = key.format();\n }\n const func = buildWrappedMethod(this, key);\n return func;\n }\n /**\n * Return the event for a given name. This is useful when a contract\n * event name conflicts with a JavaScript name such as ``prototype`` or\n * when using a Contract programatically.\n */\n getEvent(key) {\n if (typeof (key) !== \"string\") {\n key = key.format();\n }\n return buildWrappedEvent(this, key);\n }\n /**\n * @_ignore:\n */\n async queryTransaction(hash) {\n throw new Error(\"@TODO\");\n }\n /*\n // @TODO: this is a non-backwards compatible change, but will be added\n // in v7 and in a potential SmartContract class in an upcoming\n // v6 release\n async getTransactionReceipt(hash: string): Promise<null | ContractTransactionReceipt> {\n const provider = getProvider(this.runner);\n assert(provider, \"contract runner does not have a provider\",\n \"UNSUPPORTED_OPERATION\", { operation: \"queryTransaction\" });\n\n const receipt = await provider.getTransactionReceipt(hash);\n if (receipt == null) { return null; }\n\n return new ContractTransactionReceipt(this.interface, provider, receipt);\n }\n */\n /**\n * Provide historic access to event data for %%event%% in the range\n * %%fromBlock%% (default: ``0``) to %%toBlock%% (default: ``\"latest\"``)\n * inclusive.\n */\n async queryFilter(event, fromBlock, toBlock) {\n if (fromBlock == null) {\n fromBlock = 0;\n }\n if (toBlock == null) {\n toBlock = \"latest\";\n }\n const { addr, addrPromise } = getInternal(this);\n const address = (addr ? addr : (await addrPromise));\n const { fragment, topics } = await getSubInfo(this, event);\n const filter = { address, topics, fromBlock, toBlock };\n const provider = getProvider(this.runner);\n assert(provider, \"contract runner does not have a provider\", \"UNSUPPORTED_OPERATION\", { operation: \"queryFilter\" });\n return (await provider.getLogs(filter)).map((log) => {\n let foundFragment = fragment;\n if (foundFragment == null) {\n try {\n foundFragment = this.interface.getEvent(log.topics[0]);\n }\n catch (error) { }\n }\n if (foundFragment) {\n try {\n return new EventLog(log, this.interface, foundFragment);\n }\n catch (error) {\n return new UndecodedEventLog(log, error);\n }\n }\n return new Log(log, provider);\n });\n }\n /**\n * Add an event %%listener%% for the %%event%%.\n */\n async on(event, listener) {\n const sub = await getSub(this, \"on\", event);\n sub.listeners.push({ listener, once: false });\n sub.start();\n return this;\n }\n /**\n * Add an event %%listener%% for the %%event%%, but remove the listener\n * after it is fired once.\n */\n async once(event, listener) {\n const sub = await getSub(this, \"once\", event);\n sub.listeners.push({ listener, once: true });\n sub.start();\n return this;\n }\n /**\n * Emit an %%event%% calling all listeners with %%args%%.\n *\n * Resolves to ``true`` if any listeners were called.\n */\n async emit(event, ...args) {\n return await emit(this, event, args, null);\n }\n /**\n * Resolves to the number of listeners of %%event%% or the total number\n * of listeners if unspecified.\n */\n async listenerCount(event) {\n if (event) {\n const sub = await hasSub(this, event);\n if (!sub) {\n return 0;\n }\n return sub.listeners.length;\n }\n const { subs } = getInternal(this);\n let total = 0;\n for (const { listeners } of subs.values()) {\n total += listeners.length;\n }\n return total;\n }\n /**\n * Resolves to the listeners subscribed to %%event%% or all listeners\n * if unspecified.\n */\n async listeners(event) {\n if (event) {\n const sub = await hasSub(this, event);\n if (!sub) {\n return [];\n }\n return sub.listeners.map(({ listener }) => listener);\n }\n const { subs } = getInternal(this);\n let result = [];\n for (const { listeners } of subs.values()) {\n result = result.concat(listeners.map(({ listener }) => listener));\n }\n return result;\n }\n /**\n * Remove the %%listener%% from the listeners for %%event%% or remove\n * all listeners if unspecified.\n */\n async off(event, listener) {\n const sub = await hasSub(this, event);\n if (!sub) {\n return this;\n }\n if (listener) {\n const index = sub.listeners.map(({ listener }) => listener).indexOf(listener);\n if (index >= 0) {\n sub.listeners.splice(index, 1);\n }\n }\n if (listener == null || sub.listeners.length === 0) {\n sub.stop();\n getInternal(this).subs.delete(sub.tag);\n }\n return this;\n }\n /**\n * Remove all the listeners for %%event%% or remove all listeners if\n * unspecified.\n */\n async removeAllListeners(event) {\n if (event) {\n const sub = await hasSub(this, event);\n if (!sub) {\n return this;\n }\n sub.stop();\n getInternal(this).subs.delete(sub.tag);\n }\n else {\n const { subs } = getInternal(this);\n for (const { tag, stop } of subs.values()) {\n stop();\n subs.delete(tag);\n }\n }\n return this;\n }\n /**\n * Alias for [on].\n */\n async addListener(event, listener) {\n return await this.on(event, listener);\n }\n /**\n * Alias for [off].\n */\n async removeListener(event, listener) {\n return await this.off(event, listener);\n }\n /**\n * Create a new Class for the %%abi%%.\n */\n static buildClass(abi) {\n class CustomContract extends BaseContract {\n constructor(address, runner = null) {\n super(address, abi, runner);\n }\n }\n return CustomContract;\n }\n ;\n /**\n * Create a new BaseContract with a specified Interface.\n */\n static from(target, abi, runner) {\n if (runner == null) {\n runner = null;\n }\n const contract = new this(target, abi, runner);\n return contract;\n }\n}\nfunction _ContractBase() {\n return BaseContract;\n}\n/**\n * A [[BaseContract]] with no type guards on its methods or events.\n */\nexport class Contract extends _ContractBase() {\n}\n//# sourceMappingURL=contract.js.map","/**\n * ENS is a service which allows easy-to-remember names to map to\n * network addresses.\n *\n * @_section: api/providers/ens-resolver:ENS Resolver [about-ens-rsolver]\n */\nimport { getAddress } from \"../address/index.js\";\nimport { ZeroAddress } from \"../constants/index.js\";\nimport { Contract } from \"../contract/index.js\";\nimport { dnsEncode, namehash } from \"../hash/index.js\";\nimport { hexlify, isHexString, toBeHex, defineProperties, encodeBase58, assert, assertArgument, isError, FetchRequest } from \"../utils/index.js\";\n// @TODO: This should use the fetch-data:ipfs gateway\n// Trim off the ipfs:// prefix and return the default gateway URL\nfunction getIpfsLink(link) {\n if (link.match(/^ipfs:\\/\\/ipfs\\//i)) {\n link = link.substring(12);\n }\n else if (link.match(/^ipfs:\\/\\//i)) {\n link = link.substring(7);\n }\n else {\n assertArgument(false, \"unsupported IPFS format\", \"link\", link);\n }\n return `https:/\\/gateway.ipfs.io/ipfs/${link}`;\n}\n;\n;\n/**\n * A provider plugin super-class for processing multicoin address types.\n */\nexport class MulticoinProviderPlugin {\n /**\n * The name.\n */\n name;\n /**\n * Creates a new **MulticoinProviderPluing** for %%name%%.\n */\n constructor(name) {\n defineProperties(this, { name });\n }\n connect(proivder) {\n return this;\n }\n /**\n * Returns ``true`` if %%coinType%% is supported by this plugin.\n */\n supportsCoinType(coinType) {\n return false;\n }\n /**\n * Resolves to the encoded %%address%% for %%coinType%%.\n */\n async encodeAddress(coinType, address) {\n throw new Error(\"unsupported coin\");\n }\n /**\n * Resolves to the decoded %%data%% for %%coinType%%.\n */\n async decodeAddress(coinType, data) {\n throw new Error(\"unsupported coin\");\n }\n}\nconst BasicMulticoinPluginId = \"org.ethers.plugins.provider.BasicMulticoin\";\n/**\n * A **BasicMulticoinProviderPlugin** provides service for common\n * coin types, which do not require additional libraries to encode or\n * decode.\n */\nexport class BasicMulticoinProviderPlugin extends MulticoinProviderPlugin {\n /**\n * Creates a new **BasicMulticoinProviderPlugin**.\n */\n constructor() {\n super(BasicMulticoinPluginId);\n }\n}\nconst matcherIpfs = new RegExp(\"^(ipfs):/\\/(.*)$\", \"i\");\nconst matchers = [\n new RegExp(\"^(https):/\\/(.*)$\", \"i\"),\n new RegExp(\"^(data):(.*)$\", \"i\"),\n matcherIpfs,\n new RegExp(\"^eip155:[0-9]+/(erc[0-9]+):(.*)$\", \"i\"),\n];\n/**\n * A connected object to a resolved ENS name resolver, which can be\n * used to query additional details.\n */\nexport class EnsResolver {\n /**\n * The connected provider.\n */\n provider;\n /**\n * The address of the resolver.\n */\n address;\n /**\n * The name this resolver was resolved against.\n */\n name;\n // For EIP-2544 names, the ancestor that provided the resolver\n #supports2544;\n #resolver;\n constructor(provider, address, name) {\n defineProperties(this, { provider, address, name });\n this.#supports2544 = null;\n this.#resolver = new Contract(address, [\n \"function supportsInterface(bytes4) view returns (bool)\",\n \"function resolve(bytes, bytes) view returns (bytes)\",\n \"function addr(bytes32) view returns (address)\",\n \"function addr(bytes32, uint) view returns (bytes)\",\n \"function text(bytes32, string) view returns (string)\",\n \"function contenthash(bytes32) view returns (bytes)\",\n ], provider);\n }\n /**\n * Resolves to true if the resolver supports wildcard resolution.\n */\n async supportsWildcard() {\n if (this.#supports2544 == null) {\n this.#supports2544 = (async () => {\n try {\n return await this.#resolver.supportsInterface(\"0x9061b923\");\n }\n catch (error) {\n // Wildcard resolvers must understand supportsInterface\n // and return true.\n if (isError(error, \"CALL_EXCEPTION\")) {\n return false;\n }\n // Let future attempts try again...\n this.#supports2544 = null;\n throw error;\n }\n })();\n }\n return await this.#supports2544;\n }\n async #fetch(funcName, params) {\n params = (params || []).slice();\n const iface = this.#resolver.interface;\n // The first parameters is always the nodehash\n params.unshift(namehash(this.name));\n let fragment = null;\n if (await this.supportsWildcard()) {\n fragment = iface.getFunction(funcName);\n assert(fragment, \"missing fragment\", \"UNKNOWN_ERROR\", {\n info: { funcName }\n });\n params = [\n dnsEncode(this.name, 255),\n iface.encodeFunctionData(fragment, params)\n ];\n funcName = \"resolve(bytes,bytes)\";\n }\n params.push({\n enableCcipRead: true\n });\n try {\n const result = await this.#resolver[funcName](...params);\n if (fragment) {\n return iface.decodeFunctionResult(fragment, result)[0];\n }\n return result;\n }\n catch (error) {\n if (!isError(error, \"CALL_EXCEPTION\")) {\n throw error;\n }\n }\n return null;\n }\n /**\n * Resolves to the address for %%coinType%% or null if the\n * provided %%coinType%% has not been configured.\n */\n async getAddress(coinType) {\n if (coinType == null) {\n coinType = 60;\n }\n if (coinType === 60) {\n try {\n const result = await this.#fetch(\"addr(bytes32)\");\n // No address\n if (result == null || result === ZeroAddress) {\n return null;\n }\n return result;\n }\n catch (error) {\n if (isError(error, \"CALL_EXCEPTION\")) {\n return null;\n }\n throw error;\n }\n }\n // Try decoding its EVM canonical chain as an EVM chain address first\n if (coinType >= 0 && coinType < 0x80000000) {\n let ethCoinType = coinType + 0x80000000;\n const data = await this.#fetch(\"addr(bytes32,uint)\", [ethCoinType]);\n if (isHexString(data, 20)) {\n return getAddress(data);\n }\n }\n let coinPlugin = null;\n for (const plugin of this.provider.plugins) {\n if (!(plugin instanceof MulticoinProviderPlugin)) {\n continue;\n }\n if (plugin.supportsCoinType(coinType)) {\n coinPlugin = plugin;\n break;\n }\n }\n if (coinPlugin == null) {\n return null;\n }\n // keccak256(\"addr(bytes32,uint256\")\n const data = await this.#fetch(\"addr(bytes32,uint)\", [coinType]);\n // No address\n if (data == null || data === \"0x\") {\n return null;\n }\n // Compute the address\n const address = await coinPlugin.decodeAddress(coinType, data);\n if (address != null) {\n return address;\n }\n assert(false, `invalid coin data`, \"UNSUPPORTED_OPERATION\", {\n operation: `getAddress(${coinType})`,\n info: { coinType, data }\n });\n }\n /**\n * Resolves to the EIP-634 text record for %%key%%, or ``null``\n * if unconfigured.\n */\n async getText(key) {\n const data = await this.#fetch(\"text(bytes32,string)\", [key]);\n if (data == null || data === \"0x\") {\n return null;\n }\n return data;\n }\n /**\n * Rsolves to the content-hash or ``null`` if unconfigured.\n */\n async getContentHash() {\n // keccak256(\"contenthash()\")\n const data = await this.#fetch(\"contenthash(bytes32)\");\n // No contenthash\n if (data == null || data === \"0x\") {\n return null;\n }\n // IPFS (CID: 1, Type: 70=DAG-PB, 72=libp2p-key)\n const ipfs = data.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/);\n if (ipfs) {\n const scheme = (ipfs[1] === \"e3010170\") ? \"ipfs\" : \"ipns\";\n const length = parseInt(ipfs[4], 16);\n if (ipfs[5].length === length * 2) {\n return `${scheme}:/\\/${encodeBase58(\"0x\" + ipfs[2])}`;\n }\n }\n // Swarm (CID: 1, Type: swarm-manifest; hash/length hard-coded to keccak256/32)\n const swarm = data.match(/^0xe40101fa011b20([0-9a-f]*)$/);\n if (swarm && swarm[1].length === 64) {\n return `bzz:/\\/${swarm[1]}`;\n }\n assert(false, `invalid or unsupported content hash data`, \"UNSUPPORTED_OPERATION\", {\n operation: \"getContentHash()\",\n info: { data }\n });\n }\n /**\n * Resolves to the avatar url or ``null`` if the avatar is either\n * unconfigured or incorrectly configured (e.g. references an NFT\n * not owned by the address).\n *\n * If diagnosing issues with configurations, the [[_getAvatar]]\n * method may be useful.\n */\n async getAvatar() {\n const avatar = await this._getAvatar();\n return avatar.url;\n }\n /**\n * When resolving an avatar, there are many steps involved, such\n * fetching metadata and possibly validating ownership of an\n * NFT.\n *\n * This method can be used to examine each step and the value it\n * was working from.\n */\n async _getAvatar() {\n const linkage = [{ type: \"name\", value: this.name }];\n try {\n // test data for ricmoo.eth\n //const avatar = \"eip155:1/erc721:0x265385c7f4132228A0d54EB1A9e7460b91c0cC68/29233\";\n const avatar = await this.getText(\"avatar\");\n if (avatar == null) {\n linkage.push({ type: \"!avatar\", value: \"\" });\n return { url: null, linkage };\n }\n linkage.push({ type: \"avatar\", value: avatar });\n for (let i = 0; i < matchers.length; i++) {\n const match = avatar.match(matchers[i]);\n if (match == null) {\n continue;\n }\n const scheme = match[1].toLowerCase();\n switch (scheme) {\n case \"https\":\n case \"data\":\n linkage.push({ type: \"url\", value: avatar });\n return { linkage, url: avatar };\n case \"ipfs\": {\n const url = getIpfsLink(avatar);\n linkage.push({ type: \"ipfs\", value: avatar });\n linkage.push({ type: \"url\", value: url });\n return { linkage, url };\n }\n case \"erc721\":\n case \"erc1155\": {\n // Depending on the ERC type, use tokenURI(uint256) or url(uint256)\n const selector = (scheme === \"erc721\") ? \"tokenURI(uint256)\" : \"uri(uint256)\";\n linkage.push({ type: scheme, value: avatar });\n // The owner of this name\n const owner = await this.getAddress();\n if (owner == null) {\n linkage.push({ type: \"!owner\", value: \"\" });\n return { url: null, linkage };\n }\n const comps = (match[2] || \"\").split(\"/\");\n if (comps.length !== 2) {\n linkage.push({ type: `!${scheme}caip`, value: (match[2] || \"\") });\n return { url: null, linkage };\n }\n const tokenId = comps[1];\n const contract = new Contract(comps[0], [\n // ERC-721\n \"function tokenURI(uint) view returns (string)\",\n \"function ownerOf(uint) view returns (address)\",\n // ERC-1155\n \"function uri(uint) view returns (string)\",\n \"function balanceOf(address, uint256) view returns (uint)\"\n ], this.provider);\n // Check that this account owns the token\n if (scheme === \"erc721\") {\n const tokenOwner = await contract.ownerOf(tokenId);\n if (owner !== tokenOwner) {\n linkage.push({ type: \"!owner\", value: tokenOwner });\n return { url: null, linkage };\n }\n linkage.push({ type: \"owner\", value: tokenOwner });\n }\n else if (scheme === \"erc1155\") {\n const balance = await contract.balanceOf(owner, tokenId);\n if (!balance) {\n linkage.push({ type: \"!balance\", value: \"0\" });\n return { url: null, linkage };\n }\n linkage.push({ type: \"balance\", value: balance.toString() });\n }\n // Call the token contract for the metadata URL\n let metadataUrl = await contract[selector](tokenId);\n if (metadataUrl == null || metadataUrl === \"0x\") {\n linkage.push({ type: \"!metadata-url\", value: \"\" });\n return { url: null, linkage };\n }\n linkage.push({ type: \"metadata-url-base\", value: metadataUrl });\n // ERC-1155 allows a generic {id} in the URL\n if (scheme === \"erc1155\") {\n metadataUrl = metadataUrl.replace(\"{id}\", toBeHex(tokenId, 32).substring(2));\n linkage.push({ type: \"metadata-url-expanded\", value: metadataUrl });\n }\n // Transform IPFS metadata links\n if (metadataUrl.match(/^ipfs:/i)) {\n metadataUrl = getIpfsLink(metadataUrl);\n }\n linkage.push({ type: \"metadata-url\", value: metadataUrl });\n // Get the token metadata\n let metadata = {};\n const response = await (new FetchRequest(metadataUrl)).send();\n response.assertOk();\n try {\n metadata = response.bodyJson;\n }\n catch (error) {\n try {\n linkage.push({ type: \"!metadata\", value: response.bodyText });\n }\n catch (error) {\n const bytes = response.body;\n if (bytes) {\n linkage.push({ type: \"!metadata\", value: hexlify(bytes) });\n }\n return { url: null, linkage };\n }\n return { url: null, linkage };\n }\n if (!metadata) {\n linkage.push({ type: \"!metadata\", value: \"\" });\n return { url: null, linkage };\n }\n linkage.push({ type: \"metadata\", value: JSON.stringify(metadata) });\n // Pull the image URL out\n let imageUrl = metadata.image;\n if (typeof (imageUrl) !== \"string\") {\n linkage.push({ type: \"!imageUrl\", value: \"\" });\n return { url: null, linkage };\n }\n if (imageUrl.match(/^(https:\\/\\/|data:)/i)) {\n // Allow\n }\n else {\n // Transform IPFS link to gateway\n const ipfs = imageUrl.match(matcherIpfs);\n if (ipfs == null) {\n linkage.push({ type: \"!imageUrl-ipfs\", value: imageUrl });\n return { url: null, linkage };\n }\n linkage.push({ type: \"imageUrl-ipfs\", value: imageUrl });\n imageUrl = getIpfsLink(imageUrl);\n }\n linkage.push({ type: \"url\", value: imageUrl });\n return { linkage, url: imageUrl };\n }\n }\n }\n }\n catch (error) { }\n return { linkage, url: null };\n }\n static async getEnsAddress(provider) {\n const network = await provider.getNetwork();\n const ensPlugin = network.getPlugin(\"org.ethers.plugins.network.Ens\");\n // No ENS...\n assert(ensPlugin, \"network does not support ENS\", \"UNSUPPORTED_OPERATION\", {\n operation: \"getEnsAddress\", info: { network }\n });\n return ensPlugin.address;\n }\n static async #getResolver(provider, name) {\n const ensAddr = await EnsResolver.getEnsAddress(provider);\n try {\n const contract = new Contract(ensAddr, [\n \"function resolver(bytes32) view returns (address)\"\n ], provider);\n const addr = await contract.resolver(namehash(name), {\n enableCcipRead: true\n });\n if (addr === ZeroAddress) {\n return null;\n }\n return addr;\n }\n catch (error) {\n // ENS registry cannot throw errors on resolver(bytes32),\n // so probably a link error\n throw error;\n }\n return null;\n }\n /**\n * Resolve to the ENS resolver for %%name%% using %%provider%% or\n * ``null`` if unconfigured.\n */\n static async fromName(provider, name) {\n let currentName = name;\n while (true) {\n if (currentName === \"\" || currentName === \".\") {\n return null;\n }\n // Optimization since the eth node cannot change and does\n // not have a wildcard resolver\n if (name !== \"eth\" && currentName === \"eth\") {\n return null;\n }\n // Check the current node for a resolver\n const addr = await EnsResolver.#getResolver(provider, currentName);\n // Found a resolver!\n if (addr != null) {\n const resolver = new EnsResolver(provider, addr, name);\n // Legacy resolver found, using EIP-2544 so it isn't safe to use\n if (currentName !== name && !(await resolver.supportsWildcard())) {\n return null;\n }\n return resolver;\n }\n // Get the parent node\n currentName = currentName.split(\".\").slice(1).join(\".\");\n }\n }\n}\n//# sourceMappingURL=ens-resolver.js.map","/**\n * @_ignore\n */\nimport { getAddress, getCreateAddress } from \"../address/index.js\";\nimport { Signature } from \"../crypto/index.js\";\nimport { accessListify } from \"../transaction/index.js\";\nimport { getBigInt, getNumber, hexlify, isHexString, zeroPadValue, assert, assertArgument } from \"../utils/index.js\";\nconst BN_0 = BigInt(0);\nexport function allowNull(format, nullValue) {\n return (function (value) {\n if (value == null) {\n return nullValue;\n }\n return format(value);\n });\n}\nexport function arrayOf(format, allowNull) {\n return ((array) => {\n if (allowNull && array == null) {\n return null;\n }\n if (!Array.isArray(array)) {\n throw new Error(\"not an array\");\n }\n return array.map((i) => format(i));\n });\n}\n// Requires an object which matches a fleet of other formatters\n// Any FormatFunc may return `undefined` to have the value omitted\n// from the result object. Calls preserve `this`.\nexport function object(format, altNames) {\n return ((value) => {\n const result = {};\n for (const key in format) {\n let srcKey = key;\n if (altNames && key in altNames && !(srcKey in value)) {\n for (const altKey of altNames[key]) {\n if (altKey in value) {\n srcKey = altKey;\n break;\n }\n }\n }\n try {\n const nv = format[key](value[srcKey]);\n if (nv !== undefined) {\n result[key] = nv;\n }\n }\n catch (error) {\n const message = (error instanceof Error) ? error.message : \"not-an-error\";\n assert(false, `invalid value for value.${key} (${message})`, \"BAD_DATA\", { value });\n }\n }\n return result;\n });\n}\nexport function formatBoolean(value) {\n switch (value) {\n case true:\n case \"true\":\n return true;\n case false:\n case \"false\":\n return false;\n }\n assertArgument(false, `invalid boolean; ${JSON.stringify(value)}`, \"value\", value);\n}\nexport function formatData(value) {\n assertArgument(isHexString(value, true), \"invalid data\", \"value\", value);\n return value;\n}\nexport function formatHash(value) {\n assertArgument(isHexString(value, 32), \"invalid hash\", \"value\", value);\n return value;\n}\nexport function formatUint256(value) {\n if (!isHexString(value)) {\n throw new Error(\"invalid uint256\");\n }\n return zeroPadValue(value, 32);\n}\nconst _formatLog = object({\n address: getAddress,\n blockHash: formatHash,\n blockNumber: getNumber,\n data: formatData,\n index: getNumber,\n removed: allowNull(formatBoolean, false),\n topics: arrayOf(formatHash),\n transactionHash: formatHash,\n transactionIndex: getNumber,\n}, {\n index: [\"logIndex\"]\n});\nexport function formatLog(value) {\n return _formatLog(value);\n}\nconst _formatBlock = object({\n hash: allowNull(formatHash),\n parentHash: formatHash,\n parentBeaconBlockRoot: allowNull(formatHash, null),\n number: getNumber,\n timestamp: getNumber,\n nonce: allowNull(formatData),\n difficulty: getBigInt,\n gasLimit: getBigInt,\n gasUsed: getBigInt,\n stateRoot: allowNull(formatHash, null),\n receiptsRoot: allowNull(formatHash, null),\n blobGasUsed: allowNull(getBigInt, null),\n excessBlobGas: allowNull(getBigInt, null),\n miner: allowNull(getAddress),\n prevRandao: allowNull(formatHash, null),\n extraData: formatData,\n baseFeePerGas: allowNull(getBigInt)\n}, {\n prevRandao: [\"mixHash\"]\n});\nexport function formatBlock(value) {\n const result = _formatBlock(value);\n result.transactions = value.transactions.map((tx) => {\n if (typeof (tx) === \"string\") {\n return tx;\n }\n return formatTransactionResponse(tx);\n });\n return result;\n}\nconst _formatReceiptLog = object({\n transactionIndex: getNumber,\n blockNumber: getNumber,\n transactionHash: formatHash,\n address: getAddress,\n topics: arrayOf(formatHash),\n data: formatData,\n index: getNumber,\n blockHash: formatHash,\n}, {\n index: [\"logIndex\"]\n});\nexport function formatReceiptLog(value) {\n return _formatReceiptLog(value);\n}\nconst _formatTransactionReceipt = object({\n to: allowNull(getAddress, null),\n from: allowNull(getAddress, null),\n contractAddress: allowNull(getAddress, null),\n // should be allowNull(hash), but broken-EIP-658 support is handled in receipt\n index: getNumber,\n root: allowNull(hexlify),\n gasUsed: getBigInt,\n blobGasUsed: allowNull(getBigInt, null),\n logsBloom: allowNull(formatData),\n blockHash: formatHash,\n hash: formatHash,\n logs: arrayOf(formatReceiptLog),\n blockNumber: getNumber,\n //confirmations: allowNull(getNumber, null),\n cumulativeGasUsed: getBigInt,\n effectiveGasPrice: allowNull(getBigInt),\n blobGasPrice: allowNull(getBigInt, null),\n status: allowNull(getNumber),\n type: allowNull(getNumber, 0)\n}, {\n effectiveGasPrice: [\"gasPrice\"],\n hash: [\"transactionHash\"],\n index: [\"transactionIndex\"],\n});\nexport function formatTransactionReceipt(value) {\n return _formatTransactionReceipt(value);\n}\nexport function formatTransactionResponse(value) {\n // Some clients (TestRPC) do strange things like return 0x0 for the\n // 0 address; correct this to be a real address\n if (value.to && getBigInt(value.to) === BN_0) {\n value.to = \"0x0000000000000000000000000000000000000000\";\n }\n const result = object({\n hash: formatHash,\n // Some nodes do not return this, usually test nodes (like Ganache)\n index: allowNull(getNumber, undefined),\n type: (value) => {\n if (value === \"0x\" || value == null) {\n return 0;\n }\n return getNumber(value);\n },\n accessList: allowNull(accessListify, null),\n blobVersionedHashes: allowNull(arrayOf(formatHash, true), null),\n blockHash: allowNull(formatHash, null),\n blockNumber: allowNull(getNumber, null),\n transactionIndex: allowNull(getNumber, null),\n from: getAddress,\n // either (gasPrice) or (maxPriorityFeePerGas + maxFeePerGas) must be set\n gasPrice: allowNull(getBigInt),\n maxPriorityFeePerGas: allowNull(getBigInt),\n maxFeePerGas: allowNull(getBigInt),\n maxFeePerBlobGas: allowNull(getBigInt, null),\n gasLimit: getBigInt,\n to: allowNull(getAddress, null),\n value: getBigInt,\n nonce: getNumber,\n data: formatData,\n creates: allowNull(getAddress, null),\n chainId: allowNull(getBigInt, null)\n }, {\n data: [\"input\"],\n gasLimit: [\"gas\"],\n index: [\"transactionIndex\"]\n })(value);\n // If to and creates are empty, populate the creates from the value\n if (result.to == null && result.creates == null) {\n result.creates = getCreateAddress(result);\n }\n // @TODO: Check fee data\n // Add an access list to supported transaction types\n if ((value.type === 1 || value.type === 2) && value.accessList == null) {\n result.accessList = [];\n }\n // Compute the signature\n if (value.signature) {\n result.signature = Signature.from(value.signature);\n }\n else {\n result.signature = Signature.from(value);\n }\n // Some backends omit ChainId on legacy transactions, but we can compute it\n if (result.chainId == null) {\n const chainId = result.signature.legacyChainId;\n if (chainId != null) {\n result.chainId = chainId;\n }\n }\n // @TODO: check chainID\n /*\n if (value.chainId != null) {\n let chainId = value.chainId;\n\n if (isHexString(chainId)) {\n chainId = BigNumber.from(chainId).toNumber();\n }\n\n result.chainId = chainId;\n\n } else {\n let chainId = value.networkId;\n\n // geth-etc returns chainId\n if (chainId == null && result.v == null) {\n chainId = value.chainId;\n }\n\n if (isHexString(chainId)) {\n chainId = BigNumber.from(chainId).toNumber();\n }\n\n if (typeof(chainId) !== \"number\" && result.v != null) {\n chainId = (result.v - 35) / 2;\n if (chainId < 0) { chainId = 0; }\n chainId = parseInt(chainId);\n }\n\n if (typeof(chainId) !== \"number\") { chainId = 0; }\n\n result.chainId = chainId;\n }\n */\n // 0x0000... should actually be null\n if (result.blockHash && getBigInt(result.blockHash) === BN_0) {\n result.blockHash = null;\n }\n return result;\n}\n//# sourceMappingURL=format.js.map","import { keccak256 } from \"../crypto/index.js\";\nimport { concat, dataSlice, getBigInt, getBytes, encodeRlp, assertArgument } from \"../utils/index.js\";\nimport { getAddress } from \"./address.js\";\n// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed\n/**\n * Returns the address that would result from a ``CREATE`` for %%tx%%.\n *\n * This can be used to compute the address a contract will be\n * deployed to by an EOA when sending a deployment transaction (i.e.\n * when the ``to`` address is ``null``).\n *\n * This can also be used to compute the address a contract will be\n * deployed to by a contract, by using the contract's address as the\n * ``to`` and the contract's nonce.\n *\n * @example\n * from = \"0x8ba1f109551bD432803012645Ac136ddd64DBA72\";\n * nonce = 5;\n *\n * getCreateAddress({ from, nonce });\n * //_result:\n */\nexport function getCreateAddress(tx) {\n const from = getAddress(tx.from);\n const nonce = getBigInt(tx.nonce, \"tx.nonce\");\n let nonceHex = nonce.toString(16);\n if (nonceHex === \"0\") {\n nonceHex = \"0x\";\n }\n else if (nonceHex.length % 2) {\n nonceHex = \"0x0\" + nonceHex;\n }\n else {\n nonceHex = \"0x\" + nonceHex;\n }\n return getAddress(dataSlice(keccak256(encodeRlp([from, nonceHex])), 12));\n}\n/**\n * Returns the address that would result from a ``CREATE2`` operation\n * with the given %%from%%, %%salt%% and %%initCodeHash%%.\n *\n * To compute the %%initCodeHash%% from a contract's init code, use\n * the [[keccak256]] function.\n *\n * For a quick overview and example of ``CREATE2``, see [[link-ricmoo-wisps]].\n *\n * @example\n * // The address of the contract\n * from = \"0x8ba1f109551bD432803012645Ac136ddd64DBA72\"\n *\n * // The salt\n * salt = id(\"HelloWorld\")\n *\n * // The hash of the initCode\n * initCode = \"0x6394198df16000526103ff60206004601c335afa6040516060f3\";\n * initCodeHash = keccak256(initCode)\n *\n * getCreate2Address(from, salt, initCodeHash)\n * //_result:\n */\nexport function getCreate2Address(_from, _salt, _initCodeHash) {\n const from = getAddress(_from);\n const salt = getBytes(_salt, \"salt\");\n const initCodeHash = getBytes(_initCodeHash, \"initCodeHash\");\n assertArgument(salt.length === 32, \"salt must be 32 bytes\", \"salt\", _salt);\n assertArgument(initCodeHash.length === 32, \"initCodeHash must be 32 bytes\", \"initCodeHash\", _initCodeHash);\n return getAddress(dataSlice(keccak256(concat([\"0xff\", from, salt, initCodeHash])), 12));\n}\n//# sourceMappingURL=contract-address.js.map","import { defineProperties } from \"../utils/properties.js\";\nimport { assertArgument } from \"../utils/index.js\";\nconst EnsAddress = \"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e\";\n/**\n * A **NetworkPlugin** provides additional functionality on a [[Network]].\n */\nexport class NetworkPlugin {\n /**\n * The name of the plugin.\n *\n * It is recommended to use reverse-domain-notation, which permits\n * unique names with a known authority as well as hierarchal entries.\n */\n name;\n /**\n * Creates a new **NetworkPlugin**.\n */\n constructor(name) {\n defineProperties(this, { name });\n }\n /**\n * Creates a copy of this plugin.\n */\n clone() {\n return new NetworkPlugin(this.name);\n }\n}\n/**\n * A **GasCostPlugin** allows a network to provide alternative values when\n * computing the intrinsic gas required for a transaction.\n */\nexport class GasCostPlugin extends NetworkPlugin {\n /**\n * The block number to treat these values as valid from.\n *\n * This allows a hardfork to have updated values included as well as\n * mulutiple hardforks to be supported.\n */\n effectiveBlock;\n /**\n * The transactions base fee.\n */\n txBase;\n /**\n * The fee for creating a new account.\n */\n txCreate;\n /**\n * The fee per zero-byte in the data.\n */\n txDataZero;\n /**\n * The fee per non-zero-byte in the data.\n */\n txDataNonzero;\n /**\n * The fee per storage key in the [[link-eip-2930]] access list.\n */\n txAccessListStorageKey;\n /**\n * The fee per address in the [[link-eip-2930]] access list.\n */\n txAccessListAddress;\n /**\n * Creates a new GasCostPlugin from %%effectiveBlock%% until the\n * latest block or another GasCostPlugin supercedes that block number,\n * with the associated %%costs%%.\n */\n constructor(effectiveBlock, costs) {\n if (effectiveBlock == null) {\n effectiveBlock = 0;\n }\n super(`org.ethers.network.plugins.GasCost#${(effectiveBlock || 0)}`);\n const props = { effectiveBlock };\n function set(name, nullish) {\n let value = (costs || {})[name];\n if (value == null) {\n value = nullish;\n }\n assertArgument(typeof (value) === \"number\", `invalud value for ${name}`, \"costs\", costs);\n props[name] = value;\n }\n set(\"txBase\", 21000);\n set(\"txCreate\", 32000);\n set(\"txDataZero\", 4);\n set(\"txDataNonzero\", 16);\n set(\"txAccessListStorageKey\", 1900);\n set(\"txAccessListAddress\", 2400);\n defineProperties(this, props);\n }\n clone() {\n return new GasCostPlugin(this.effectiveBlock, this);\n }\n}\n/**\n * An **EnsPlugin** allows a [[Network]] to specify the ENS Registry\n * Contract address and the target network to use when using that\n * contract.\n *\n * Various testnets have their own instance of the contract to use, but\n * in general, the mainnet instance supports multi-chain addresses and\n * should be used.\n */\nexport class EnsPlugin extends NetworkPlugin {\n /**\n * The ENS Registrty Contract address.\n */\n address;\n /**\n * The chain ID that the ENS contract lives on.\n */\n targetNetwork;\n /**\n * Creates a new **EnsPlugin** connected to %%address%% on the\n * %%targetNetwork%%. The default ENS address and mainnet is used\n * if unspecified.\n */\n constructor(address, targetNetwork) {\n super(\"org.ethers.plugins.network.Ens\");\n defineProperties(this, {\n address: (address || EnsAddress),\n targetNetwork: ((targetNetwork == null) ? 1 : targetNetwork)\n });\n }\n clone() {\n return new EnsPlugin(this.address, this.targetNetwork);\n }\n}\n/**\n * A **FeeDataNetworkPlugin** allows a network to provide and alternate\n * means to specify its fee data.\n *\n * For example, a network which does not support [[link-eip-1559]] may\n * choose to use a Gas Station site to approximate the gas price.\n */\nexport class FeeDataNetworkPlugin extends NetworkPlugin {\n #feeDataFunc;\n /**\n * The fee data function provided to the constructor.\n */\n get feeDataFunc() {\n return this.#feeDataFunc;\n }\n /**\n * Creates a new **FeeDataNetworkPlugin**.\n */\n constructor(feeDataFunc) {\n super(\"org.ethers.plugins.network.FeeData\");\n this.#feeDataFunc = feeDataFunc;\n }\n /**\n * Resolves to the fee data.\n */\n async getFeeData(provider) {\n return await this.#feeDataFunc(provider);\n }\n clone() {\n return new FeeDataNetworkPlugin(this.#feeDataFunc);\n }\n}\nexport class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin {\n #url;\n #processFunc;\n /**\n * The URL to initialize the FetchRequest with in %%processFunc%%.\n */\n get url() { return this.#url; }\n /**\n * The callback to use when computing the FeeData.\n */\n get processFunc() { return this.#processFunc; }\n /**\n * Creates a new **FetchUrlFeeDataNetworkPlugin** which will\n * be used when computing the fee data for the network.\n */\n constructor(url, processFunc) {\n super(\"org.ethers.plugins.network.FetchUrlFeeDataPlugin\");\n this.#url = url;\n this.#processFunc = processFunc;\n }\n // We are immutable, so we can serve as our own clone\n clone() { return this; }\n}\n/*\nexport class CustomBlockNetworkPlugin extends NetworkPlugin {\n readonly #blockFunc: (provider: Provider, block: BlockParams<string>) => Block<string>;\n readonly #blockWithTxsFunc: (provider: Provider, block: BlockParams<TransactionResponseParams>) => Block<TransactionResponse>;\n\n constructor(blockFunc: (provider: Provider, block: BlockParams<string>) => Block<string>, blockWithTxsFunc: (provider: Provider, block: BlockParams<TransactionResponseParams>) => Block<TransactionResponse>) {\n super(\"org.ethers.network-plugins.custom-block\");\n this.#blockFunc = blockFunc;\n this.#blockWithTxsFunc = blockWithTxsFunc;\n }\n\n async getBlock(provider: Provider, block: BlockParams<string>): Promise<Block<string>> {\n return await this.#blockFunc(provider, block);\n }\n\n async getBlockions(provider: Provider, block: BlockParams<TransactionResponseParams>): Promise<Block<TransactionResponse>> {\n return await this.#blockWithTxsFunc(provider, block);\n }\n\n clone(): CustomBlockNetworkPlugin {\n return new CustomBlockNetworkPlugin(this.#blockFunc, this.#blockWithTxsFunc);\n }\n}\n*/\n//# sourceMappingURL=plugins-network.js.map","/**\n * A **Network** encapsulates the various properties required to\n * interact with a specific chain.\n *\n * @_subsection: api/providers:Networks [networks]\n */\nimport { accessListify } from \"../transaction/index.js\";\nimport { getBigInt, assert, assertArgument } from \"../utils/index.js\";\nimport { EnsPlugin, FetchUrlFeeDataNetworkPlugin, GasCostPlugin } from \"./plugins-network.js\";\n/* * * *\n// Networks which operation against an L2 can use this plugin to\n// specify how to access L1, for the purpose of resolving ENS,\n// for example.\nexport class LayerOneConnectionPlugin extends NetworkPlugin {\n readonly provider!: Provider;\n// @TODO: Rename to ChainAccess and allow for connecting to any chain\n constructor(provider: Provider) {\n super(\"org.ethers.plugins.layer-one-connection\");\n defineProperties<LayerOneConnectionPlugin>(this, { provider });\n }\n\n clone(): LayerOneConnectionPlugin {\n return new LayerOneConnectionPlugin(this.provider);\n }\n}\n*/\nconst Networks = new Map();\n/**\n * A **Network** provides access to a chain's properties and allows\n * for plug-ins to extend functionality.\n */\nexport class Network {\n #name;\n #chainId;\n #plugins;\n /**\n * Creates a new **Network** for %%name%% and %%chainId%%.\n */\n constructor(name, chainId) {\n this.#name = name;\n this.#chainId = getBigInt(chainId);\n this.#plugins = new Map();\n }\n /**\n * Returns a JSON-compatible representation of a Network.\n */\n toJSON() {\n return { name: this.name, chainId: String(this.chainId) };\n }\n /**\n * The network common name.\n *\n * This is the canonical name, as networks migh have multiple\n * names.\n */\n get name() { return this.#name; }\n set name(value) { this.#name = value; }\n /**\n * The network chain ID.\n */\n get chainId() { return this.#chainId; }\n set chainId(value) { this.#chainId = getBigInt(value, \"chainId\"); }\n /**\n * Returns true if %%other%% matches this network. Any chain ID\n * must match, and if no chain ID is present, the name must match.\n *\n * This method does not currently check for additional properties,\n * such as ENS address or plug-in compatibility.\n */\n matches(other) {\n if (other == null) {\n return false;\n }\n if (typeof (other) === \"string\") {\n try {\n return (this.chainId === getBigInt(other));\n }\n catch (error) { }\n return (this.name === other);\n }\n if (typeof (other) === \"number\" || typeof (other) === \"bigint\") {\n try {\n return (this.chainId === getBigInt(other));\n }\n catch (error) { }\n return false;\n }\n if (typeof (other) === \"object\") {\n if (other.chainId != null) {\n try {\n return (this.chainId === getBigInt(other.chainId));\n }\n catch (error) { }\n return false;\n }\n if (other.name != null) {\n return (this.name === other.name);\n }\n return false;\n }\n return false;\n }\n /**\n * Returns the list of plugins currently attached to this Network.\n */\n get plugins() {\n return Array.from(this.#plugins.values());\n }\n /**\n * Attach a new %%plugin%% to this Network. The network name\n * must be unique, excluding any fragment.\n */\n attachPlugin(plugin) {\n if (this.#plugins.get(plugin.name)) {\n throw new Error(`cannot replace existing plugin: ${plugin.name} `);\n }\n this.#plugins.set(plugin.name, plugin.clone());\n return this;\n }\n /**\n * Return the plugin, if any, matching %%name%% exactly. Plugins\n * with fragments will not be returned unless %%name%% includes\n * a fragment.\n */\n getPlugin(name) {\n return (this.#plugins.get(name)) || null;\n }\n /**\n * Gets a list of all plugins that match %%name%%, with otr without\n * a fragment.\n */\n getPlugins(basename) {\n return (this.plugins.filter((p) => (p.name.split(\"#\")[0] === basename)));\n }\n /**\n * Create a copy of this Network.\n */\n clone() {\n const clone = new Network(this.name, this.chainId);\n this.plugins.forEach((plugin) => {\n clone.attachPlugin(plugin.clone());\n });\n return clone;\n }\n /**\n * Compute the intrinsic gas required for a transaction.\n *\n * A GasCostPlugin can be attached to override the default\n * values.\n */\n computeIntrinsicGas(tx) {\n const costs = this.getPlugin(\"org.ethers.plugins.network.GasCost\") || (new GasCostPlugin());\n let gas = costs.txBase;\n if (tx.to == null) {\n gas += costs.txCreate;\n }\n if (tx.data) {\n for (let i = 2; i < tx.data.length; i += 2) {\n if (tx.data.substring(i, i + 2) === \"00\") {\n gas += costs.txDataZero;\n }\n else {\n gas += costs.txDataNonzero;\n }\n }\n }\n if (tx.accessList) {\n const accessList = accessListify(tx.accessList);\n for (const addr in accessList) {\n gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length;\n }\n }\n return gas;\n }\n /**\n * Returns a new Network for the %%network%% name or chainId.\n */\n static from(network) {\n injectCommonNetworks();\n // Default network\n if (network == null) {\n return Network.from(\"mainnet\");\n }\n // Canonical name or chain ID\n if (typeof (network) === \"number\") {\n network = BigInt(network);\n }\n if (typeof (network) === \"string\" || typeof (network) === \"bigint\") {\n const networkFunc = Networks.get(network);\n if (networkFunc) {\n return networkFunc();\n }\n if (typeof (network) === \"bigint\") {\n return new Network(\"unknown\", network);\n }\n assertArgument(false, \"unknown network\", \"network\", network);\n }\n // Clonable with network-like abilities\n if (typeof (network.clone) === \"function\") {\n const clone = network.clone();\n //if (typeof(network.name) !== \"string\" || typeof(network.chainId) !== \"number\") {\n //}\n return clone;\n }\n // Networkish\n if (typeof (network) === \"object\") {\n assertArgument(typeof (network.name) === \"string\" && typeof (network.chainId) === \"number\", \"invalid network object name or chainId\", \"network\", network);\n const custom = new Network((network.name), (network.chainId));\n if (network.ensAddress || network.ensNetwork != null) {\n custom.attachPlugin(new EnsPlugin(network.ensAddress, network.ensNetwork));\n }\n //if ((<any>network).layerOneConnection) {\n // custom.attachPlugin(new LayerOneConnectionPlugin((<any>network).layerOneConnection));\n //}\n return custom;\n }\n assertArgument(false, \"invalid network\", \"network\", network);\n }\n /**\n * Register %%nameOrChainId%% with a function which returns\n * an instance of a Network representing that chain.\n */\n static register(nameOrChainId, networkFunc) {\n if (typeof (nameOrChainId) === \"number\") {\n nameOrChainId = BigInt(nameOrChainId);\n }\n const existing = Networks.get(nameOrChainId);\n if (existing) {\n assertArgument(false, `conflicting network for ${JSON.stringify(existing.name)}`, \"nameOrChainId\", nameOrChainId);\n }\n Networks.set(nameOrChainId, networkFunc);\n }\n}\n// We don't want to bring in formatUnits because it is backed by\n// FixedNumber and we want to keep Networks tiny. The values\n// included by the Gas Stations are also IEEE 754 with lots of\n// rounding issues and exceed the strict checks formatUnits has.\nfunction parseUnits(_value, decimals) {\n const value = String(_value);\n if (!value.match(/^[0-9.]+$/)) {\n throw new Error(`invalid gwei value: ${_value}`);\n }\n // Break into [ whole, fraction ]\n const comps = value.split(\".\");\n if (comps.length === 1) {\n comps.push(\"\");\n }\n // More than 1 decimal point or too many fractional positions\n if (comps.length !== 2) {\n throw new Error(`invalid gwei value: ${_value}`);\n }\n // Pad the fraction to 9 decimalplaces\n while (comps[1].length < decimals) {\n comps[1] += \"0\";\n }\n // Too many decimals and some non-zero ending, take the ceiling\n if (comps[1].length > 9) {\n let frac = BigInt(comps[1].substring(0, 9));\n if (!comps[1].substring(9).match(/^0+$/)) {\n frac++;\n }\n comps[1] = frac.toString();\n }\n return BigInt(comps[0] + comps[1]);\n}\n// Used by Polygon to use a gas station for fee data\nfunction getGasStationPlugin(url) {\n return new FetchUrlFeeDataNetworkPlugin(url, async (fetchFeeData, provider, request) => {\n // Prevent Cloudflare from blocking our request in node.js\n request.setHeader(\"User-Agent\", \"ethers\");\n let response;\n try {\n const [_response, _feeData] = await Promise.all([\n request.send(), fetchFeeData()\n ]);\n response = _response;\n const payload = response.bodyJson.standard;\n const feeData = {\n gasPrice: _feeData.gasPrice,\n maxFeePerGas: parseUnits(payload.maxFee, 9),\n maxPriorityFeePerGas: parseUnits(payload.maxPriorityFee, 9),\n };\n return feeData;\n }\n catch (error) {\n assert(false, `error encountered with polygon gas station (${JSON.stringify(request.url)})`, \"SERVER_ERROR\", { request, response, error });\n }\n });\n}\n// See: https://chainlist.org\nlet injected = false;\nfunction injectCommonNetworks() {\n if (injected) {\n return;\n }\n injected = true;\n /// Register popular Ethereum networks\n function registerEth(name, chainId, options) {\n const func = function () {\n const network = new Network(name, chainId);\n // We use 0 to disable ENS\n if (options.ensNetwork != null) {\n network.attachPlugin(new EnsPlugin(null, options.ensNetwork));\n }\n network.attachPlugin(new GasCostPlugin());\n (options.plugins || []).forEach((plugin) => {\n network.attachPlugin(plugin);\n });\n return network;\n };\n // Register the network by name and chain ID\n Network.register(name, func);\n Network.register(chainId, func);\n if (options.altNames) {\n options.altNames.forEach((name) => {\n Network.register(name, func);\n });\n }\n }\n registerEth(\"mainnet\", 1, { ensNetwork: 1, altNames: [\"homestead\"] });\n registerEth(\"ropsten\", 3, { ensNetwork: 3 });\n registerEth(\"rinkeby\", 4, { ensNetwork: 4 });\n registerEth(\"goerli\", 5, { ensNetwork: 5 });\n registerEth(\"kovan\", 42, { ensNetwork: 42 });\n registerEth(\"sepolia\", 11155111, { ensNetwork: 11155111 });\n registerEth(\"holesky\", 17000, { ensNetwork: 17000 });\n registerEth(\"classic\", 61, {});\n registerEth(\"classicKotti\", 6, {});\n registerEth(\"arbitrum\", 42161, {\n ensNetwork: 1,\n });\n registerEth(\"arbitrum-goerli\", 421613, {});\n registerEth(\"arbitrum-sepolia\", 421614, {});\n registerEth(\"base\", 8453, { ensNetwork: 1 });\n registerEth(\"base-goerli\", 84531, {});\n registerEth(\"base-sepolia\", 84532, {});\n registerEth(\"bnb\", 56, { ensNetwork: 1 });\n registerEth(\"bnbt\", 97, {});\n registerEth(\"linea\", 59144, { ensNetwork: 1 });\n registerEth(\"linea-goerli\", 59140, {});\n registerEth(\"linea-sepolia\", 59141, {});\n registerEth(\"matic\", 137, {\n ensNetwork: 1,\n plugins: [\n getGasStationPlugin(\"https:/\\/gasstation.polygon.technology/v2\")\n ]\n });\n registerEth(\"matic-amoy\", 80002, {});\n registerEth(\"matic-mumbai\", 80001, {\n altNames: [\"maticMumbai\", \"maticmum\"],\n plugins: [\n getGasStationPlugin(\"https:/\\/gasstation-testnet.polygon.technology/v2\")\n ]\n });\n registerEth(\"optimism\", 10, {\n ensNetwork: 1,\n plugins: []\n });\n registerEth(\"optimism-goerli\", 420, {});\n registerEth(\"optimism-sepolia\", 11155420, {});\n registerEth(\"xdai\", 100, { ensNetwork: 1 });\n}\n//# sourceMappingURL=network.js.map","import { assert, isHexString } from \"../utils/index.js\";\nfunction copy(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n/**\n * Return the polling subscriber for common events.\n *\n * @_docloc: api/providers/abstract-provider\n */\nexport function getPollingSubscriber(provider, event) {\n if (event === \"block\") {\n return new PollingBlockSubscriber(provider);\n }\n if (isHexString(event, 32)) {\n return new PollingTransactionSubscriber(provider, event);\n }\n assert(false, \"unsupported polling event\", \"UNSUPPORTED_OPERATION\", {\n operation: \"getPollingSubscriber\", info: { event }\n });\n}\n// @TODO: refactor this\n/**\n * A **PollingBlockSubscriber** polls at a regular interval for a change\n * in the block number.\n *\n * @_docloc: api/providers/abstract-provider\n */\nexport class PollingBlockSubscriber {\n #provider;\n #poller;\n #interval;\n // The most recent block we have scanned for events. The value -2\n // indicates we still need to fetch an initial block number\n #blockNumber;\n /**\n * Create a new **PollingBlockSubscriber** attached to %%provider%%.\n */\n constructor(provider) {\n this.#provider = provider;\n this.#poller = null;\n this.#interval = 4000;\n this.#blockNumber = -2;\n }\n /**\n * The polling interval.\n */\n get pollingInterval() { return this.#interval; }\n set pollingInterval(value) { this.#interval = value; }\n async #poll() {\n try {\n const blockNumber = await this.#provider.getBlockNumber();\n // Bootstrap poll to setup our initial block number\n if (this.#blockNumber === -2) {\n this.#blockNumber = blockNumber;\n return;\n }\n // @TODO: Put a cap on the maximum number of events per loop?\n if (blockNumber !== this.#blockNumber) {\n for (let b = this.#blockNumber + 1; b <= blockNumber; b++) {\n // We have been stopped\n if (this.#poller == null) {\n return;\n }\n await this.#provider.emit(\"block\", b);\n }\n this.#blockNumber = blockNumber;\n }\n }\n catch (error) {\n // @TODO: Minor bump, add an \"error\" event to let subscribers\n // know things went awry.\n //console.log(error);\n }\n // We have been stopped\n if (this.#poller == null) {\n return;\n }\n this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);\n }\n start() {\n if (this.#poller) {\n return;\n }\n this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);\n this.#poll();\n }\n stop() {\n if (!this.#poller) {\n return;\n }\n this.#provider._clearTimeout(this.#poller);\n this.#poller = null;\n }\n pause(dropWhilePaused) {\n this.stop();\n if (dropWhilePaused) {\n this.#blockNumber = -2;\n }\n }\n resume() {\n this.start();\n }\n}\n/**\n * An **OnBlockSubscriber** can be sub-classed, with a [[_poll]]\n * implmentation which will be called on every new block.\n *\n * @_docloc: api/providers/abstract-provider\n */\nexport class OnBlockSubscriber {\n #provider;\n #poll;\n #running;\n /**\n * Create a new **OnBlockSubscriber** attached to %%provider%%.\n */\n constructor(provider) {\n this.#provider = provider;\n this.#running = false;\n this.#poll = (blockNumber) => {\n this._poll(blockNumber, this.#provider);\n };\n }\n /**\n * Called on every new block.\n */\n async _poll(blockNumber, provider) {\n throw new Error(\"sub-classes must override this\");\n }\n start() {\n if (this.#running) {\n return;\n }\n this.#running = true;\n this.#poll(-2);\n this.#provider.on(\"block\", this.#poll);\n }\n stop() {\n if (!this.#running) {\n return;\n }\n this.#running = false;\n this.#provider.off(\"block\", this.#poll);\n }\n pause(dropWhilePaused) { this.stop(); }\n resume() { this.start(); }\n}\nexport class PollingBlockTagSubscriber extends OnBlockSubscriber {\n #tag;\n #lastBlock;\n constructor(provider, tag) {\n super(provider);\n this.#tag = tag;\n this.#lastBlock = -2;\n }\n pause(dropWhilePaused) {\n if (dropWhilePaused) {\n this.#lastBlock = -2;\n }\n super.pause(dropWhilePaused);\n }\n async _poll(blockNumber, provider) {\n const block = await provider.getBlock(this.#tag);\n if (block == null) {\n return;\n }\n if (this.#lastBlock === -2) {\n this.#lastBlock = block.number;\n }\n else if (block.number > this.#lastBlock) {\n provider.emit(this.#tag, block.number);\n this.#lastBlock = block.number;\n }\n }\n}\n/**\n * @_ignore:\n *\n * @_docloc: api/providers/abstract-provider\n */\nexport class PollingOrphanSubscriber extends OnBlockSubscriber {\n #filter;\n constructor(provider, filter) {\n super(provider);\n this.#filter = copy(filter);\n }\n async _poll(blockNumber, provider) {\n throw new Error(\"@TODO\");\n console.log(this.#filter);\n }\n}\n/**\n * A **PollingTransactionSubscriber** will poll for a given transaction\n * hash for its receipt.\n *\n * @_docloc: api/providers/abstract-provider\n */\nexport class PollingTransactionSubscriber extends OnBlockSubscriber {\n #hash;\n /**\n * Create a new **PollingTransactionSubscriber** attached to\n * %%provider%%, listening for %%hash%%.\n */\n constructor(provider, hash) {\n super(provider);\n this.#hash = hash;\n }\n async _poll(blockNumber, provider) {\n const tx = await provider.getTransactionReceipt(this.#hash);\n if (tx) {\n provider.emit(this.#hash, tx);\n }\n }\n}\n/**\n * A **PollingEventSubscriber** will poll for a given filter for its logs.\n *\n * @_docloc: api/providers/abstract-provider\n */\nexport class PollingEventSubscriber {\n #provider;\n #filter;\n #poller;\n #running;\n // The most recent block we have scanned for events. The value -2\n // indicates we still need to fetch an initial block number\n #blockNumber;\n /**\n * Create a new **PollingTransactionSubscriber** attached to\n * %%provider%%, listening for %%filter%%.\n */\n constructor(provider, filter) {\n this.#provider = provider;\n this.#filter = copy(filter);\n this.#poller = this.#poll.bind(this);\n this.#running = false;\n this.#blockNumber = -2;\n }\n async #poll(blockNumber) {\n // The initial block hasn't been determined yet\n if (this.#blockNumber === -2) {\n return;\n }\n const filter = copy(this.#filter);\n filter.fromBlock = this.#blockNumber + 1;\n filter.toBlock = blockNumber;\n const logs = await this.#provider.getLogs(filter);\n // No logs could just mean the node has not indexed them yet,\n // so we keep a sliding window of 60 blocks to keep scanning\n if (logs.length === 0) {\n if (this.#blockNumber < blockNumber - 60) {\n this.#blockNumber = blockNumber - 60;\n }\n return;\n }\n for (const log of logs) {\n this.#provider.emit(this.#filter, log);\n // Only advance the block number when logs were found to\n // account for networks (like BNB and Polygon) which may\n // sacrifice event consistency for block event speed\n this.#blockNumber = log.blockNumber;\n }\n }\n start() {\n if (this.#running) {\n return;\n }\n this.#running = true;\n if (this.#blockNumber === -2) {\n this.#provider.getBlockNumber().then((blockNumber) => {\n this.#blockNumber = blockNumber;\n });\n }\n this.#provider.on(\"block\", this.#poller);\n }\n stop() {\n if (!this.#running) {\n return;\n }\n this.#running = false;\n this.#provider.off(\"block\", this.#poller);\n }\n pause(dropWhilePaused) {\n this.stop();\n if (dropWhilePaused) {\n this.#blockNumber = -2;\n }\n }\n resume() {\n this.start();\n }\n}\n//# sourceMappingURL=subscriber-polling.js.map","/**\n * The available providers should suffice for most developers purposes,\n * but the [[AbstractProvider]] class has many features which enable\n * sub-classing it for specific purposes.\n *\n * @_section: api/providers/abstract-provider: Subclassing Provider [abstract-provider]\n */\n// @TODO\n// Event coalescence\n// When we register an event with an async value (e.g. address is a Signer\n// or ENS name), we need to add it immeidately for the Event API, but also\n// need time to resolve the address. Upon resolving the address, we need to\n// migrate the listener to the static event. We also need to maintain a map\n// of Signer/ENS name to address so we can sync respond to listenerCount.\nimport { getAddress, resolveAddress } from \"../address/index.js\";\nimport { ZeroAddress } from \"../constants/index.js\";\nimport { Contract } from \"../contract/index.js\";\nimport { namehash } from \"../hash/index.js\";\nimport { Transaction } from \"../transaction/index.js\";\nimport { concat, dataLength, dataSlice, hexlify, isHexString, getBigInt, getBytes, getNumber, isCallException, isError, makeError, assert, assertArgument, FetchRequest, toBeArray, toQuantity, defineProperties, EventPayload, resolveProperties, toUtf8String } from \"../utils/index.js\";\nimport { EnsResolver } from \"./ens-resolver.js\";\nimport { formatBlock, formatLog, formatTransactionReceipt, formatTransactionResponse } from \"./format.js\";\nimport { Network } from \"./network.js\";\nimport { copyRequest, Block, FeeData, Log, TransactionReceipt, TransactionResponse } from \"./provider.js\";\nimport { PollingBlockSubscriber, PollingBlockTagSubscriber, PollingEventSubscriber, PollingOrphanSubscriber, PollingTransactionSubscriber } from \"./subscriber-polling.js\";\n// Constants\nconst BN_2 = BigInt(2);\nconst MAX_CCIP_REDIRECTS = 10;\nfunction isPromise(value) {\n return (value && typeof (value.then) === \"function\");\n}\nfunction getTag(prefix, value) {\n return prefix + \":\" + JSON.stringify(value, (k, v) => {\n if (v == null) {\n return \"null\";\n }\n if (typeof (v) === \"bigint\") {\n return `bigint:${v.toString()}`;\n }\n if (typeof (v) === \"string\") {\n return v.toLowerCase();\n }\n // Sort object keys\n if (typeof (v) === \"object\" && !Array.isArray(v)) {\n const keys = Object.keys(v);\n keys.sort();\n return keys.reduce((accum, key) => {\n accum[key] = v[key];\n return accum;\n }, {});\n }\n return v;\n });\n}\n/**\n * An **UnmanagedSubscriber** is useful for events which do not require\n * any additional management, such as ``\"debug\"`` which only requires\n * emit in synchronous event loop triggered calls.\n */\nexport class UnmanagedSubscriber {\n /**\n * The name fof the event.\n */\n name;\n /**\n * Create a new UnmanagedSubscriber with %%name%%.\n */\n constructor(name) { defineProperties(this, { name }); }\n start() { }\n stop() { }\n pause(dropWhilePaused) { }\n resume() { }\n}\nfunction copy(value) {\n return JSON.parse(JSON.stringify(value));\n}\nfunction concisify(items) {\n items = Array.from((new Set(items)).values());\n items.sort();\n return items;\n}\nasync function getSubscription(_event, provider) {\n if (_event == null) {\n throw new Error(\"invalid event\");\n }\n // Normalize topic array info an EventFilter\n if (Array.isArray(_event)) {\n _event = { topics: _event };\n }\n if (typeof (_event) === \"string\") {\n switch (_event) {\n case \"block\":\n case \"debug\":\n case \"error\":\n case \"finalized\":\n case \"network\":\n case \"pending\":\n case \"safe\": {\n return { type: _event, tag: _event };\n }\n }\n }\n if (isHexString(_event, 32)) {\n const hash = _event.toLowerCase();\n return { type: \"transaction\", tag: getTag(\"tx\", { hash }), hash };\n }\n if (_event.orphan) {\n const event = _event;\n // @TODO: Should lowercase and whatnot things here instead of copy...\n return { type: \"orphan\", tag: getTag(\"orphan\", event), filter: copy(event) };\n }\n if ((_event.address || _event.topics)) {\n const event = _event;\n const filter = {\n topics: ((event.topics || []).map((t) => {\n if (t == null) {\n return null;\n }\n if (Array.isArray(t)) {\n return concisify(t.map((t) => t.toLowerCase()));\n }\n return t.toLowerCase();\n }))\n };\n if (event.address) {\n const addresses = [];\n const promises = [];\n const addAddress = (addr) => {\n if (isHexString(addr)) {\n addresses.push(addr);\n }\n else {\n promises.push((async () => {\n addresses.push(await resolveAddress(addr, provider));\n })());\n }\n };\n if (Array.isArray(event.address)) {\n event.address.forEach(addAddress);\n }\n else {\n addAddress(event.address);\n }\n if (promises.length) {\n await Promise.all(promises);\n }\n filter.address = concisify(addresses.map((a) => a.toLowerCase()));\n }\n return { filter, tag: getTag(\"event\", filter), type: \"event\" };\n }\n assertArgument(false, \"unknown ProviderEvent\", \"event\", _event);\n}\nfunction getTime() { return (new Date()).getTime(); }\nconst defaultOptions = {\n cacheTimeout: 250,\n pollingInterval: 4000\n};\n/**\n * An **AbstractProvider** provides a base class for other sub-classes to\n * implement the [[Provider]] API by normalizing input arguments and\n * formatting output results as well as tracking events for consistent\n * behaviour on an eventually-consistent network.\n */\nexport class AbstractProvider {\n #subs;\n #plugins;\n // null=unpaused, true=paused+dropWhilePaused, false=paused\n #pausedState;\n #destroyed;\n #networkPromise;\n #anyNetwork;\n #performCache;\n // The most recent block number if running an event or -1 if no \"block\" event\n #lastBlockNumber;\n #nextTimer;\n #timers;\n #disableCcipRead;\n #options;\n /**\n * Create a new **AbstractProvider** connected to %%network%%, or\n * use the various network detection capabilities to discover the\n * [[Network]] if necessary.\n */\n constructor(_network, options) {\n this.#options = Object.assign({}, defaultOptions, options || {});\n if (_network === \"any\") {\n this.#anyNetwork = true;\n this.#networkPromise = null;\n }\n else if (_network) {\n const network = Network.from(_network);\n this.#anyNetwork = false;\n this.#networkPromise = Promise.resolve(network);\n setTimeout(() => { this.emit(\"network\", network, null); }, 0);\n }\n else {\n this.#anyNetwork = false;\n this.#networkPromise = null;\n }\n this.#lastBlockNumber = -1;\n this.#performCache = new Map();\n this.#subs = new Map();\n this.#plugins = new Map();\n this.#pausedState = null;\n this.#destroyed = false;\n this.#nextTimer = 1;\n this.#timers = new Map();\n this.#disableCcipRead = false;\n }\n get pollingInterval() { return this.#options.pollingInterval; }\n /**\n * Returns ``this``, to allow an **AbstractProvider** to implement\n * the [[ContractRunner]] interface.\n */\n get provider() { return this; }\n /**\n * Returns all the registered plug-ins.\n */\n get plugins() {\n return Array.from(this.#plugins.values());\n }\n /**\n * Attach a new plug-in.\n */\n attachPlugin(plugin) {\n if (this.#plugins.get(plugin.name)) {\n throw new Error(`cannot replace existing plugin: ${plugin.name} `);\n }\n this.#plugins.set(plugin.name, plugin.connect(this));\n return this;\n }\n /**\n * Get a plugin by name.\n */\n getPlugin(name) {\n return (this.#plugins.get(name)) || null;\n }\n /**\n * Prevent any CCIP-read operation, regardless of whether requested\n * in a [[call]] using ``enableCcipRead``.\n */\n get disableCcipRead() { return this.#disableCcipRead; }\n set disableCcipRead(value) { this.#disableCcipRead = !!value; }\n // Shares multiple identical requests made during the same 250ms\n async #perform(req) {\n const timeout = this.#options.cacheTimeout;\n // Caching disabled\n if (timeout < 0) {\n return await this._perform(req);\n }\n // Create a tag\n const tag = getTag(req.method, req);\n let perform = this.#performCache.get(tag);\n if (!perform) {\n perform = this._perform(req);\n this.#performCache.set(tag, perform);\n setTimeout(() => {\n if (this.#performCache.get(tag) === perform) {\n this.#performCache.delete(tag);\n }\n }, timeout);\n }\n return await perform;\n }\n /**\n * Resolves to the data for executing the CCIP-read operations.\n */\n async ccipReadFetch(tx, calldata, urls) {\n if (this.disableCcipRead || urls.length === 0 || tx.to == null) {\n return null;\n }\n const sender = tx.to.toLowerCase();\n const data = calldata.toLowerCase();\n const errorMessages = [];\n for (let i = 0; i < urls.length; i++) {\n const url = urls[i];\n // URL expansion\n const href = url.replace(\"{sender}\", sender).replace(\"{data}\", data);\n // If no {data} is present, use POST; otherwise GET\n //const json: string | null = (url.indexOf(\"{data}\") >= 0) ? null: JSON.stringify({ data, sender });\n //const result = await fetchJson({ url: href, errorPassThrough: true }, json, (value, response) => {\n // value.status = response.statusCode;\n // return value;\n //});\n const request = new FetchRequest(href);\n if (url.indexOf(\"{data}\") === -1) {\n request.body = { data, sender };\n }\n this.emit(\"debug\", { action: \"sendCcipReadFetchRequest\", request, index: i, urls });\n let errorMessage = \"unknown error\";\n // Fetch the resource...\n let resp;\n try {\n resp = await request.send();\n }\n catch (error) {\n // ...low-level fetch error (missing host, bad SSL, etc.),\n // so try next URL\n errorMessages.push(error.message);\n this.emit(\"debug\", { action: \"receiveCcipReadFetchError\", request, result: { error } });\n continue;\n }\n try {\n const result = resp.bodyJson;\n if (result.data) {\n this.emit(\"debug\", { action: \"receiveCcipReadFetchResult\", request, result });\n return result.data;\n }\n if (result.message) {\n errorMessage = result.message;\n }\n this.emit(\"debug\", { action: \"receiveCcipReadFetchError\", request, result });\n }\n catch (error) { }\n // 4xx indicates the result is not present; stop\n assert(resp.statusCode < 400 || resp.statusCode >= 500, `response not found during CCIP fetch: ${errorMessage}`, \"OFFCHAIN_FAULT\", { reason: \"404_MISSING_RESOURCE\", transaction: tx, info: { url, errorMessage } });\n // 5xx indicates server issue; try the next url\n errorMessages.push(errorMessage);\n }\n assert(false, `error encountered during CCIP fetch: ${errorMessages.map((m) => JSON.stringify(m)).join(\", \")}`, \"OFFCHAIN_FAULT\", {\n reason: \"500_SERVER_ERROR\",\n transaction: tx, info: { urls, errorMessages }\n });\n }\n /**\n * Provides the opportunity for a sub-class to wrap a block before\n * returning it, to add additional properties or an alternate\n * sub-class of [[Block]].\n */\n _wrapBlock(value, network) {\n return new Block(formatBlock(value), this);\n }\n /**\n * Provides the opportunity for a sub-class to wrap a log before\n * returning it, to add additional properties or an alternate\n * sub-class of [[Log]].\n */\n _wrapLog(value, network) {\n return new Log(formatLog(value), this);\n }\n /**\n * Provides the opportunity for a sub-class to wrap a transaction\n * receipt before returning it, to add additional properties or an\n * alternate sub-class of [[TransactionReceipt]].\n */\n _wrapTransactionReceipt(value, network) {\n return new TransactionReceipt(formatTransactionReceipt(value), this);\n }\n /**\n * Provides the opportunity for a sub-class to wrap a transaction\n * response before returning it, to add additional properties or an\n * alternate sub-class of [[TransactionResponse]].\n */\n _wrapTransactionResponse(tx, network) {\n return new TransactionResponse(formatTransactionResponse(tx), this);\n }\n /**\n * Resolves to the Network, forcing a network detection using whatever\n * technique the sub-class requires.\n *\n * Sub-classes **must** override this.\n */\n _detectNetwork() {\n assert(false, \"sub-classes must implement this\", \"UNSUPPORTED_OPERATION\", {\n operation: \"_detectNetwork\"\n });\n }\n /**\n * Sub-classes should use this to perform all built-in operations. All\n * methods sanitizes and normalizes the values passed into this.\n *\n * Sub-classes **must** override this.\n */\n async _perform(req) {\n assert(false, `unsupported method: ${req.method}`, \"UNSUPPORTED_OPERATION\", {\n operation: req.method,\n info: req\n });\n }\n // State\n async getBlockNumber() {\n const blockNumber = getNumber(await this.#perform({ method: \"getBlockNumber\" }), \"%response\");\n if (this.#lastBlockNumber >= 0) {\n this.#lastBlockNumber = blockNumber;\n }\n return blockNumber;\n }\n /**\n * Returns or resolves to the address for %%address%%, resolving ENS\n * names and [[Addressable]] objects and returning if already an\n * address.\n */\n _getAddress(address) {\n return resolveAddress(address, this);\n }\n /**\n * Returns or resolves to a valid block tag for %%blockTag%%, resolving\n * negative values and returning if already a valid block tag.\n */\n _getBlockTag(blockTag) {\n if (blockTag == null) {\n return \"latest\";\n }\n switch (blockTag) {\n case \"earliest\":\n return \"0x0\";\n case \"finalized\":\n case \"latest\":\n case \"pending\":\n case \"safe\":\n return blockTag;\n }\n if (isHexString(blockTag)) {\n if (isHexString(blockTag, 32)) {\n return blockTag;\n }\n return toQuantity(blockTag);\n }\n if (typeof (blockTag) === \"bigint\") {\n blockTag = getNumber(blockTag, \"blockTag\");\n }\n if (typeof (blockTag) === \"number\") {\n if (blockTag >= 0) {\n return toQuantity(blockTag);\n }\n if (this.#lastBlockNumber >= 0) {\n return toQuantity(this.#lastBlockNumber + blockTag);\n }\n return this.getBlockNumber().then((b) => toQuantity(b + blockTag));\n }\n assertArgument(false, \"invalid blockTag\", \"blockTag\", blockTag);\n }\n /**\n * Returns or resolves to a filter for %%filter%%, resolving any ENS\n * names or [[Addressable]] object and returning if already a valid\n * filter.\n */\n _getFilter(filter) {\n // Create a canonical representation of the topics\n const topics = (filter.topics || []).map((t) => {\n if (t == null) {\n return null;\n }\n if (Array.isArray(t)) {\n return concisify(t.map((t) => t.toLowerCase()));\n }\n return t.toLowerCase();\n });\n const blockHash = (\"blockHash\" in filter) ? filter.blockHash : undefined;\n const resolve = (_address, fromBlock, toBlock) => {\n let address = undefined;\n switch (_address.length) {\n case 0: break;\n case 1:\n address = _address[0];\n break;\n default:\n _address.sort();\n address = _address;\n }\n if (blockHash) {\n if (fromBlock != null || toBlock != null) {\n throw new Error(\"invalid filter\");\n }\n }\n const filter = {};\n if (address) {\n filter.address = address;\n }\n if (topics.length) {\n filter.topics = topics;\n }\n if (fromBlock) {\n filter.fromBlock = fromBlock;\n }\n if (toBlock) {\n filter.toBlock = toBlock;\n }\n if (blockHash) {\n filter.blockHash = blockHash;\n }\n return filter;\n };\n // Addresses could be async (ENS names or Addressables)\n let address = [];\n if (filter.address) {\n if (Array.isArray(filter.address)) {\n for (const addr of filter.address) {\n address.push(this._getAddress(addr));\n }\n }\n else {\n address.push(this._getAddress(filter.address));\n }\n }\n let fromBlock = undefined;\n if (\"fromBlock\" in filter) {\n fromBlock = this._getBlockTag(filter.fromBlock);\n }\n let toBlock = undefined;\n if (\"toBlock\" in filter) {\n toBlock = this._getBlockTag(filter.toBlock);\n }\n if (address.filter((a) => (typeof (a) !== \"string\")).length ||\n (fromBlock != null && typeof (fromBlock) !== \"string\") ||\n (toBlock != null && typeof (toBlock) !== \"string\")) {\n return Promise.all([Promise.all(address), fromBlock, toBlock]).then((result) => {\n return resolve(result[0], result[1], result[2]);\n });\n }\n return resolve(address, fromBlock, toBlock);\n }\n /**\n * Returns or resolves to a transaction for %%request%%, resolving\n * any ENS names or [[Addressable]] and returning if already a valid\n * transaction.\n */\n _getTransactionRequest(_request) {\n const request = copyRequest(_request);\n const promises = [];\n [\"to\", \"from\"].forEach((key) => {\n if (request[key] == null) {\n return;\n }\n const addr = resolveAddress(request[key], this);\n if (isPromise(addr)) {\n promises.push((async function () { request[key] = await addr; })());\n }\n else {\n request[key] = addr;\n }\n });\n if (request.blockTag != null) {\n const blockTag = this._getBlockTag(request.blockTag);\n if (isPromise(blockTag)) {\n promises.push((async function () { request.blockTag = await blockTag; })());\n }\n else {\n request.blockTag = blockTag;\n }\n }\n if (promises.length) {\n return (async function () {\n await Promise.all(promises);\n return request;\n })();\n }\n return request;\n }\n async getNetwork() {\n // No explicit network was set and this is our first time\n if (this.#networkPromise == null) {\n // Detect the current network (shared with all calls)\n const detectNetwork = (async () => {\n try {\n const network = await this._detectNetwork();\n this.emit(\"network\", network, null);\n return network;\n }\n catch (error) {\n if (this.#networkPromise === detectNetwork) {\n this.#networkPromise = null;\n }\n throw error;\n }\n })();\n this.#networkPromise = detectNetwork;\n return (await detectNetwork).clone();\n }\n const networkPromise = this.#networkPromise;\n const [expected, actual] = await Promise.all([\n networkPromise,\n this._detectNetwork() // The actual connected network\n ]);\n if (expected.chainId !== actual.chainId) {\n if (this.#anyNetwork) {\n // The \"any\" network can change, so notify listeners\n this.emit(\"network\", actual, expected);\n // Update the network if something else hasn't already changed it\n if (this.#networkPromise === networkPromise) {\n this.#networkPromise = Promise.resolve(actual);\n }\n }\n else {\n // Otherwise, we do not allow changes to the underlying network\n assert(false, `network changed: ${expected.chainId} => ${actual.chainId} `, \"NETWORK_ERROR\", {\n event: \"changed\"\n });\n }\n }\n return expected.clone();\n }\n async getFeeData() {\n const network = await this.getNetwork();\n const getFeeDataFunc = async () => {\n const { _block, gasPrice, priorityFee } = await resolveProperties({\n _block: this.#getBlock(\"latest\", false),\n gasPrice: ((async () => {\n try {\n const value = await this.#perform({ method: \"getGasPrice\" });\n return getBigInt(value, \"%response\");\n }\n catch (error) { }\n return null;\n })()),\n priorityFee: ((async () => {\n try {\n const value = await this.#perform({ method: \"getPriorityFee\" });\n return getBigInt(value, \"%response\");\n }\n catch (error) { }\n return null;\n })())\n });\n let maxFeePerGas = null;\n let maxPriorityFeePerGas = null;\n // These are the recommended EIP-1559 heuristics for fee data\n const block = this._wrapBlock(_block, network);\n if (block && block.baseFeePerGas) {\n maxPriorityFeePerGas = (priorityFee != null) ? priorityFee : BigInt(\"1000000000\");\n maxFeePerGas = (block.baseFeePerGas * BN_2) + maxPriorityFeePerGas;\n }\n return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas);\n };\n // Check for a FeeDataNetWorkPlugin\n const plugin = network.getPlugin(\"org.ethers.plugins.network.FetchUrlFeeDataPlugin\");\n if (plugin) {\n const req = new FetchRequest(plugin.url);\n const feeData = await plugin.processFunc(getFeeDataFunc, this, req);\n return new FeeData(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas);\n }\n return await getFeeDataFunc();\n }\n async estimateGas(_tx) {\n let tx = this._getTransactionRequest(_tx);\n if (isPromise(tx)) {\n tx = await tx;\n }\n return getBigInt(await this.#perform({\n method: \"estimateGas\", transaction: tx\n }), \"%response\");\n }\n async #call(tx, blockTag, attempt) {\n assert(attempt < MAX_CCIP_REDIRECTS, \"CCIP read exceeded maximum redirections\", \"OFFCHAIN_FAULT\", {\n reason: \"TOO_MANY_REDIRECTS\",\n transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true })\n });\n // This came in as a PerformActionTransaction, so to/from are safe; we can cast\n const transaction = copyRequest(tx);\n try {\n return hexlify(await this._perform({ method: \"call\", transaction, blockTag }));\n }\n catch (error) {\n // CCIP Read OffchainLookup\n if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === \"latest\" && transaction.to != null && dataSlice(error.data, 0, 4) === \"0x556f1830\") {\n const data = error.data;\n const txSender = await resolveAddress(transaction.to, this);\n // Parse the CCIP Read Arguments\n let ccipArgs;\n try {\n ccipArgs = parseOffchainLookup(dataSlice(error.data, 4));\n }\n catch (error) {\n assert(false, error.message, \"OFFCHAIN_FAULT\", {\n reason: \"BAD_DATA\", transaction, info: { data }\n });\n }\n // Check the sender of the OffchainLookup matches the transaction\n assert(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), \"CCIP Read sender mismatch\", \"CALL_EXCEPTION\", {\n action: \"call\",\n data,\n reason: \"OffchainLookup\",\n transaction: transaction,\n invocation: null,\n revert: {\n signature: \"OffchainLookup(address,string[],bytes,bytes4,bytes)\",\n name: \"OffchainLookup\",\n args: ccipArgs.errorArgs\n }\n });\n const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls);\n assert(ccipResult != null, \"CCIP Read failed to fetch data\", \"OFFCHAIN_FAULT\", {\n reason: \"FETCH_FAILED\", transaction, info: { data: error.data, errorArgs: ccipArgs.errorArgs }\n });\n const tx = {\n to: txSender,\n data: concat([ccipArgs.selector, encodeBytes([ccipResult, ccipArgs.extraData])])\n };\n this.emit(\"debug\", { action: \"sendCcipReadCall\", transaction: tx });\n try {\n const result = await this.#call(tx, blockTag, attempt + 1);\n this.emit(\"debug\", { action: \"receiveCcipReadCallResult\", transaction: Object.assign({}, tx), result });\n return result;\n }\n catch (error) {\n this.emit(\"debug\", { action: \"receiveCcipReadCallError\", transaction: Object.assign({}, tx), error });\n throw error;\n }\n }\n throw error;\n }\n }\n async #checkNetwork(promise) {\n const { value } = await resolveProperties({\n network: this.getNetwork(),\n value: promise\n });\n return value;\n }\n async call(_tx) {\n const { tx, blockTag } = await resolveProperties({\n tx: this._getTransactionRequest(_tx),\n blockTag: this._getBlockTag(_tx.blockTag)\n });\n return await this.#checkNetwork(this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1));\n }\n // Account\n async #getAccountValue(request, _address, _blockTag) {\n let address = this._getAddress(_address);\n let blockTag = this._getBlockTag(_blockTag);\n if (typeof (address) !== \"string\" || typeof (blockTag) !== \"string\") {\n [address, blockTag] = await Promise.all([address, blockTag]);\n }\n return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag })));\n }\n async getBalance(address, blockTag) {\n return getBigInt(await this.#getAccountValue({ method: \"getBalance\" }, address, blockTag), \"%response\");\n }\n async getTransactionCount(address, blockTag) {\n return getNumber(await this.#getAccountValue({ method: \"getTransactionCount\" }, address, blockTag), \"%response\");\n }\n async getCode(address, blockTag) {\n return hexlify(await this.#getAccountValue({ method: \"getCode\" }, address, blockTag));\n }\n async getStorage(address, _position, blockTag) {\n const position = getBigInt(_position, \"position\");\n return hexlify(await this.#getAccountValue({ method: \"getStorage\", position }, address, blockTag));\n }\n // Write\n async broadcastTransaction(signedTx) {\n const { blockNumber, hash, network } = await resolveProperties({\n blockNumber: this.getBlockNumber(),\n hash: this._perform({\n method: \"broadcastTransaction\",\n signedTransaction: signedTx\n }),\n network: this.getNetwork()\n });\n const tx = Transaction.from(signedTx);\n if (tx.hash !== hash) {\n throw new Error(\"@TODO: the returned hash did not match\");\n }\n return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber);\n }\n async #getBlock(block, includeTransactions) {\n // @TODO: Add CustomBlockPlugin check\n if (isHexString(block, 32)) {\n return await this.#perform({\n method: \"getBlock\", blockHash: block, includeTransactions\n });\n }\n let blockTag = this._getBlockTag(block);\n if (typeof (blockTag) !== \"string\") {\n blockTag = await blockTag;\n }\n return await this.#perform({\n method: \"getBlock\", blockTag, includeTransactions\n });\n }\n // Queries\n async getBlock(block, prefetchTxs) {\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#getBlock(block, !!prefetchTxs)\n });\n if (params == null) {\n return null;\n }\n return this._wrapBlock(params, network);\n }\n async getTransaction(hash) {\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#perform({ method: \"getTransaction\", hash })\n });\n if (params == null) {\n return null;\n }\n return this._wrapTransactionResponse(params, network);\n }\n async getTransactionReceipt(hash) {\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#perform({ method: \"getTransactionReceipt\", hash })\n });\n if (params == null) {\n return null;\n }\n // Some backends did not backfill the effectiveGasPrice into old transactions\n // in the receipt, so we look it up manually and inject it.\n if (params.gasPrice == null && params.effectiveGasPrice == null) {\n const tx = await this.#perform({ method: \"getTransaction\", hash });\n if (tx == null) {\n throw new Error(\"report this; could not find tx or effectiveGasPrice\");\n }\n params.effectiveGasPrice = tx.gasPrice;\n }\n return this._wrapTransactionReceipt(params, network);\n }\n async getTransactionResult(hash) {\n const { result } = await resolveProperties({\n network: this.getNetwork(),\n result: this.#perform({ method: \"getTransactionResult\", hash })\n });\n if (result == null) {\n return null;\n }\n return hexlify(result);\n }\n // Bloom-filter Queries\n async getLogs(_filter) {\n let filter = this._getFilter(_filter);\n if (isPromise(filter)) {\n filter = await filter;\n }\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#perform({ method: \"getLogs\", filter })\n });\n return params.map((p) => this._wrapLog(p, network));\n }\n // ENS\n _getProvider(chainId) {\n assert(false, \"provider cannot connect to target network\", \"UNSUPPORTED_OPERATION\", {\n operation: \"_getProvider()\"\n });\n }\n async getResolver(name) {\n return await EnsResolver.fromName(this, name);\n }\n async getAvatar(name) {\n const resolver = await this.getResolver(name);\n if (resolver) {\n return await resolver.getAvatar();\n }\n return null;\n }\n async resolveName(name) {\n const resolver = await this.getResolver(name);\n if (resolver) {\n return await resolver.getAddress();\n }\n return null;\n }\n async lookupAddress(address) {\n address = getAddress(address);\n const node = namehash(address.substring(2).toLowerCase() + \".addr.reverse\");\n try {\n const ensAddr = await EnsResolver.getEnsAddress(this);\n const ensContract = new Contract(ensAddr, [\n \"function resolver(bytes32) view returns (address)\"\n ], this);\n const resolver = await ensContract.resolver(node);\n if (resolver == null || resolver === ZeroAddress) {\n return null;\n }\n const resolverContract = new Contract(resolver, [\n \"function name(bytes32) view returns (string)\"\n ], this);\n const name = await resolverContract.name(node);\n // Failed forward resolution\n const check = await this.resolveName(name);\n if (check !== address) {\n return null;\n }\n return name;\n }\n catch (error) {\n // No data was returned from the resolver\n if (isError(error, \"BAD_DATA\") && error.value === \"0x\") {\n return null;\n }\n // Something reerted\n if (isError(error, \"CALL_EXCEPTION\")) {\n return null;\n }\n throw error;\n }\n return null;\n }\n async waitForTransaction(hash, _confirms, timeout) {\n const confirms = (_confirms != null) ? _confirms : 1;\n if (confirms === 0) {\n return this.getTransactionReceipt(hash);\n }\n return new Promise(async (resolve, reject) => {\n let timer = null;\n const listener = (async (blockNumber) => {\n try {\n const receipt = await this.getTransactionReceipt(hash);\n if (receipt != null) {\n if (blockNumber - receipt.blockNumber + 1 >= confirms) {\n resolve(receipt);\n //this.off(\"block\", listener);\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n return;\n }\n }\n }\n catch (error) {\n console.log(\"EEE\", error);\n }\n this.once(\"block\", listener);\n });\n if (timeout != null) {\n timer = setTimeout(() => {\n if (timer == null) {\n return;\n }\n timer = null;\n this.off(\"block\", listener);\n reject(makeError(\"timeout\", \"TIMEOUT\", { reason: \"timeout\" }));\n }, timeout);\n }\n listener(await this.getBlockNumber());\n });\n }\n async waitForBlock(blockTag) {\n assert(false, \"not implemented yet\", \"NOT_IMPLEMENTED\", {\n operation: \"waitForBlock\"\n });\n }\n /**\n * Clear a timer created using the [[_setTimeout]] method.\n */\n _clearTimeout(timerId) {\n const timer = this.#timers.get(timerId);\n if (!timer) {\n return;\n }\n if (timer.timer) {\n clearTimeout(timer.timer);\n }\n this.#timers.delete(timerId);\n }\n /**\n * Create a timer that will execute %%func%% after at least %%timeout%%\n * (in ms). If %%timeout%% is unspecified, then %%func%% will execute\n * in the next event loop.\n *\n * [Pausing](AbstractProvider-paused) the provider will pause any\n * associated timers.\n */\n _setTimeout(_func, timeout) {\n if (timeout == null) {\n timeout = 0;\n }\n const timerId = this.#nextTimer++;\n const func = () => {\n this.#timers.delete(timerId);\n _func();\n };\n if (this.paused) {\n this.#timers.set(timerId, { timer: null, func, time: timeout });\n }\n else {\n const timer = setTimeout(func, timeout);\n this.#timers.set(timerId, { timer, func, time: getTime() });\n }\n return timerId;\n }\n /**\n * Perform %%func%% on each subscriber.\n */\n _forEachSubscriber(func) {\n for (const sub of this.#subs.values()) {\n func(sub.subscriber);\n }\n }\n /**\n * Sub-classes may override this to customize subscription\n * implementations.\n */\n _getSubscriber(sub) {\n switch (sub.type) {\n case \"debug\":\n case \"error\":\n case \"network\":\n return new UnmanagedSubscriber(sub.type);\n case \"block\": {\n const subscriber = new PollingBlockSubscriber(this);\n subscriber.pollingInterval = this.pollingInterval;\n return subscriber;\n }\n case \"safe\":\n case \"finalized\":\n return new PollingBlockTagSubscriber(this, sub.type);\n case \"event\":\n return new PollingEventSubscriber(this, sub.filter);\n case \"transaction\":\n return new PollingTransactionSubscriber(this, sub.hash);\n case \"orphan\":\n return new PollingOrphanSubscriber(this, sub.filter);\n }\n throw new Error(`unsupported event: ${sub.type}`);\n }\n /**\n * If a [[Subscriber]] fails and needs to replace itself, this\n * method may be used.\n *\n * For example, this is used for providers when using the\n * ``eth_getFilterChanges`` method, which can return null if state\n * filters are not supported by the backend, allowing the Subscriber\n * to swap in a [[PollingEventSubscriber]].\n */\n _recoverSubscriber(oldSub, newSub) {\n for (const sub of this.#subs.values()) {\n if (sub.subscriber === oldSub) {\n if (sub.started) {\n sub.subscriber.stop();\n }\n sub.subscriber = newSub;\n if (sub.started) {\n newSub.start();\n }\n if (this.#pausedState != null) {\n newSub.pause(this.#pausedState);\n }\n break;\n }\n }\n }\n async #hasSub(event, emitArgs) {\n let sub = await getSubscription(event, this);\n // This is a log that is removing an existing log; we actually want\n // to emit an orphan event for the removed log\n if (sub.type === \"event\" && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) {\n sub = await getSubscription({ orphan: \"drop-log\", log: emitArgs[0] }, this);\n }\n return this.#subs.get(sub.tag) || null;\n }\n async #getSub(event) {\n const subscription = await getSubscription(event, this);\n // Prevent tampering with our tag in any subclass' _getSubscriber\n const tag = subscription.tag;\n let sub = this.#subs.get(tag);\n if (!sub) {\n const subscriber = this._getSubscriber(subscription);\n const addressableMap = new WeakMap();\n const nameMap = new Map();\n sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [] };\n this.#subs.set(tag, sub);\n }\n return sub;\n }\n async on(event, listener) {\n const sub = await this.#getSub(event);\n sub.listeners.push({ listener, once: false });\n if (!sub.started) {\n sub.subscriber.start();\n sub.started = true;\n if (this.#pausedState != null) {\n sub.subscriber.pause(this.#pausedState);\n }\n }\n return this;\n }\n async once(event, listener) {\n const sub = await this.#getSub(event);\n sub.listeners.push({ listener, once: true });\n if (!sub.started) {\n sub.subscriber.start();\n sub.started = true;\n if (this.#pausedState != null) {\n sub.subscriber.pause(this.#pausedState);\n }\n }\n return this;\n }\n async emit(event, ...args) {\n const sub = await this.#hasSub(event, args);\n // If there is not subscription or if a recent emit removed\n // the last of them (which also deleted the sub) do nothing\n if (!sub || sub.listeners.length === 0) {\n return false;\n }\n ;\n const count = sub.listeners.length;\n sub.listeners = sub.listeners.filter(({ listener, once }) => {\n const payload = new EventPayload(this, (once ? null : listener), event);\n try {\n listener.call(this, ...args, payload);\n }\n catch (error) { }\n return !once;\n });\n if (sub.listeners.length === 0) {\n if (sub.started) {\n sub.subscriber.stop();\n }\n this.#subs.delete(sub.tag);\n }\n return (count > 0);\n }\n async listenerCount(event) {\n if (event) {\n const sub = await this.#hasSub(event);\n if (!sub) {\n return 0;\n }\n return sub.listeners.length;\n }\n let total = 0;\n for (const { listeners } of this.#subs.values()) {\n total += listeners.length;\n }\n return total;\n }\n async listeners(event) {\n if (event) {\n const sub = await this.#hasSub(event);\n if (!sub) {\n return [];\n }\n return sub.listeners.map(({ listener }) => listener);\n }\n let result = [];\n for (const { listeners } of this.#subs.values()) {\n result = result.concat(listeners.map(({ listener }) => listener));\n }\n return result;\n }\n async off(event, listener) {\n const sub = await this.#hasSub(event);\n if (!sub) {\n return this;\n }\n if (listener) {\n const index = sub.listeners.map(({ listener }) => listener).indexOf(listener);\n if (index >= 0) {\n sub.listeners.splice(index, 1);\n }\n }\n if (!listener || sub.listeners.length === 0) {\n if (sub.started) {\n sub.subscriber.stop();\n }\n this.#subs.delete(sub.tag);\n }\n return this;\n }\n async removeAllListeners(event) {\n if (event) {\n const { tag, started, subscriber } = await this.#getSub(event);\n if (started) {\n subscriber.stop();\n }\n this.#subs.delete(tag);\n }\n else {\n for (const [tag, { started, subscriber }] of this.#subs) {\n if (started) {\n subscriber.stop();\n }\n this.#subs.delete(tag);\n }\n }\n return this;\n }\n // Alias for \"on\"\n async addListener(event, listener) {\n return await this.on(event, listener);\n }\n // Alias for \"off\"\n async removeListener(event, listener) {\n return this.off(event, listener);\n }\n /**\n * If this provider has been destroyed using the [[destroy]] method.\n *\n * Once destroyed, all resources are reclaimed, internal event loops\n * and timers are cleaned up and no further requests may be sent to\n * the provider.\n */\n get destroyed() {\n return this.#destroyed;\n }\n /**\n * Sub-classes may use this to shutdown any sockets or release their\n * resources and reject any pending requests.\n *\n * Sub-classes **must** call ``super.destroy()``.\n */\n destroy() {\n // Stop all listeners\n this.removeAllListeners();\n // Shut down all tiemrs\n for (const timerId of this.#timers.keys()) {\n this._clearTimeout(timerId);\n }\n this.#destroyed = true;\n }\n /**\n * Whether the provider is currently paused.\n *\n * A paused provider will not emit any events, and generally should\n * not make any requests to the network, but that is up to sub-classes\n * to manage.\n *\n * Setting ``paused = true`` is identical to calling ``.pause(false)``,\n * which will buffer any events that occur while paused until the\n * provider is unpaused.\n */\n get paused() { return (this.#pausedState != null); }\n set paused(pause) {\n if (!!pause === this.paused) {\n return;\n }\n if (this.paused) {\n this.resume();\n }\n else {\n this.pause(false);\n }\n }\n /**\n * Pause the provider. If %%dropWhilePaused%%, any events that occur\n * while paused are dropped, otherwise all events will be emitted once\n * the provider is unpaused.\n */\n pause(dropWhilePaused) {\n this.#lastBlockNumber = -1;\n if (this.#pausedState != null) {\n if (this.#pausedState == !!dropWhilePaused) {\n return;\n }\n assert(false, \"cannot change pause type; resume first\", \"UNSUPPORTED_OPERATION\", {\n operation: \"pause\"\n });\n }\n this._forEachSubscriber((s) => s.pause(dropWhilePaused));\n this.#pausedState = !!dropWhilePaused;\n for (const timer of this.#timers.values()) {\n // Clear the timer\n if (timer.timer) {\n clearTimeout(timer.timer);\n }\n // Remaining time needed for when we become unpaused\n timer.time = getTime() - timer.time;\n }\n }\n /**\n * Resume the provider.\n */\n resume() {\n if (this.#pausedState == null) {\n return;\n }\n this._forEachSubscriber((s) => s.resume());\n this.#pausedState = null;\n for (const timer of this.#timers.values()) {\n // Remaining time when we were paused\n let timeout = timer.time;\n if (timeout < 0) {\n timeout = 0;\n }\n // Start time (in cause paused, so we con compute remaininf time)\n timer.time = getTime();\n // Start the timer\n setTimeout(timer.func, timeout);\n }\n }\n}\nfunction _parseString(result, start) {\n try {\n const bytes = _parseBytes(result, start);\n if (bytes) {\n return toUtf8String(bytes);\n }\n }\n catch (error) { }\n return null;\n}\nfunction _parseBytes(result, start) {\n if (result === \"0x\") {\n return null;\n }\n try {\n const offset = getNumber(dataSlice(result, start, start + 32));\n const length = getNumber(dataSlice(result, offset, offset + 32));\n return dataSlice(result, offset + 32, offset + 32 + length);\n }\n catch (error) { }\n return null;\n}\nfunction numPad(value) {\n const result = toBeArray(value);\n if (result.length > 32) {\n throw new Error(\"internal; should not happen\");\n }\n const padded = new Uint8Array(32);\n padded.set(result, 32 - result.length);\n return padded;\n}\nfunction bytesPad(value) {\n if ((value.length % 32) === 0) {\n return value;\n }\n const result = new Uint8Array(Math.ceil(value.length / 32) * 32);\n result.set(value);\n return result;\n}\nconst empty = new Uint8Array([]);\n// ABI Encodes a series of (bytes, bytes, ...)\nfunction encodeBytes(datas) {\n const result = [];\n let byteCount = 0;\n // Add place-holders for pointers as we add items\n for (let i = 0; i < datas.length; i++) {\n result.push(empty);\n byteCount += 32;\n }\n for (let i = 0; i < datas.length; i++) {\n const data = getBytes(datas[i]);\n // Update the bytes offset\n result[i] = numPad(byteCount);\n // The length and padded value of data\n result.push(numPad(data.length));\n result.push(bytesPad(data));\n byteCount += 32 + Math.ceil(data.length / 32) * 32;\n }\n return concat(result);\n}\nconst zeros = \"0x0000000000000000000000000000000000000000000000000000000000000000\";\nfunction parseOffchainLookup(data) {\n const result = {\n sender: \"\", urls: [], calldata: \"\", selector: \"\", extraData: \"\", errorArgs: []\n };\n assert(dataLength(data) >= 5 * 32, \"insufficient OffchainLookup data\", \"OFFCHAIN_FAULT\", {\n reason: \"insufficient OffchainLookup data\"\n });\n const sender = dataSlice(data, 0, 32);\n assert(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), \"corrupt OffchainLookup sender\", \"OFFCHAIN_FAULT\", {\n reason: \"corrupt OffchainLookup sender\"\n });\n result.sender = dataSlice(sender, 12);\n // Read the URLs from the response\n try {\n const urls = [];\n const urlsOffset = getNumber(dataSlice(data, 32, 64));\n const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32));\n const urlsData = dataSlice(data, urlsOffset + 32);\n for (let u = 0; u < urlsLength; u++) {\n const url = _parseString(urlsData, u * 32);\n if (url == null) {\n throw new Error(\"abort\");\n }\n urls.push(url);\n }\n result.urls = urls;\n }\n catch (error) {\n assert(false, \"corrupt OffchainLookup urls\", \"OFFCHAIN_FAULT\", {\n reason: \"corrupt OffchainLookup urls\"\n });\n }\n // Get the CCIP calldata to forward\n try {\n const calldata = _parseBytes(data, 64);\n if (calldata == null) {\n throw new Error(\"abort\");\n }\n result.calldata = calldata;\n }\n catch (error) {\n assert(false, \"corrupt OffchainLookup calldata\", \"OFFCHAIN_FAULT\", {\n reason: \"corrupt OffchainLookup calldata\"\n });\n }\n // Get the callbackSelector (bytes4)\n assert(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), \"corrupt OffchainLookup callbaackSelector\", \"OFFCHAIN_FAULT\", {\n reason: \"corrupt OffchainLookup callbaackSelector\"\n });\n result.selector = dataSlice(data, 96, 100);\n // Get the extra data to send back to the contract as context\n try {\n const extraData = _parseBytes(data, 128);\n if (extraData == null) {\n throw new Error(\"abort\");\n }\n result.extraData = extraData;\n }\n catch (error) {\n assert(false, \"corrupt OffchainLookup extraData\", \"OFFCHAIN_FAULT\", {\n reason: \"corrupt OffchainLookup extraData\"\n });\n }\n result.errorArgs = \"sender,urls,calldata,selector,extraData\".split(/,/).map((k) => result[k]);\n return result;\n}\n//# sourceMappingURL=abstract-provider.js.map","/**\n * Generally the [[Wallet]] and [[JsonRpcSigner]] and their sub-classes\n * are sufficent for most developers, but this is provided to\n * fascilitate more complex Signers.\n *\n * @_section: api/providers/abstract-signer: Subclassing Signer [abstract-signer]\n */\nimport { resolveAddress } from \"../address/index.js\";\nimport { Transaction } from \"../transaction/index.js\";\nimport { defineProperties, getBigInt, resolveProperties, assert, assertArgument } from \"../utils/index.js\";\nimport { copyRequest } from \"./provider.js\";\nfunction checkProvider(signer, operation) {\n if (signer.provider) {\n return signer.provider;\n }\n assert(false, \"missing provider\", \"UNSUPPORTED_OPERATION\", { operation });\n}\nasync function populate(signer, tx) {\n let pop = copyRequest(tx);\n if (pop.to != null) {\n pop.to = resolveAddress(pop.to, signer);\n }\n if (pop.from != null) {\n const from = pop.from;\n pop.from = Promise.all([\n signer.getAddress(),\n resolveAddress(from, signer)\n ]).then(([address, from]) => {\n assertArgument(address.toLowerCase() === from.toLowerCase(), \"transaction from mismatch\", \"tx.from\", from);\n return address;\n });\n }\n else {\n pop.from = signer.getAddress();\n }\n return await resolveProperties(pop);\n}\n/**\n * An **AbstractSigner** includes most of teh functionality required\n * to get a [[Signer]] working as expected, but requires a few\n * Signer-specific methods be overridden.\n *\n */\nexport class AbstractSigner {\n /**\n * The provider this signer is connected to.\n */\n provider;\n /**\n * Creates a new Signer connected to %%provider%%.\n */\n constructor(provider) {\n defineProperties(this, { provider: (provider || null) });\n }\n async getNonce(blockTag) {\n return checkProvider(this, \"getTransactionCount\").getTransactionCount(await this.getAddress(), blockTag);\n }\n async populateCall(tx) {\n const pop = await populate(this, tx);\n return pop;\n }\n async populateTransaction(tx) {\n const provider = checkProvider(this, \"populateTransaction\");\n const pop = await populate(this, tx);\n if (pop.nonce == null) {\n pop.nonce = await this.getNonce(\"pending\");\n }\n if (pop.gasLimit == null) {\n pop.gasLimit = await this.estimateGas(pop);\n }\n // Populate the chain ID\n const network = await (this.provider).getNetwork();\n if (pop.chainId != null) {\n const chainId = getBigInt(pop.chainId);\n assertArgument(chainId === network.chainId, \"transaction chainId mismatch\", \"tx.chainId\", tx.chainId);\n }\n else {\n pop.chainId = network.chainId;\n }\n // Do not allow mixing pre-eip-1559 and eip-1559 properties\n const hasEip1559 = (pop.maxFeePerGas != null || pop.maxPriorityFeePerGas != null);\n if (pop.gasPrice != null && (pop.type === 2 || hasEip1559)) {\n assertArgument(false, \"eip-1559 transaction do not support gasPrice\", \"tx\", tx);\n }\n else if ((pop.type === 0 || pop.type === 1) && hasEip1559) {\n assertArgument(false, \"pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas\", \"tx\", tx);\n }\n if ((pop.type === 2 || pop.type == null) && (pop.maxFeePerGas != null && pop.maxPriorityFeePerGas != null)) {\n // Fully-formed EIP-1559 transaction (skip getFeeData)\n pop.type = 2;\n }\n else if (pop.type === 0 || pop.type === 1) {\n // Explicit Legacy or EIP-2930 transaction\n // We need to get fee data to determine things\n const feeData = await provider.getFeeData();\n assert(feeData.gasPrice != null, \"network does not support gasPrice\", \"UNSUPPORTED_OPERATION\", {\n operation: \"getGasPrice\"\n });\n // Populate missing gasPrice\n if (pop.gasPrice == null) {\n pop.gasPrice = feeData.gasPrice;\n }\n }\n else {\n // We need to get fee data to determine things\n const feeData = await provider.getFeeData();\n if (pop.type == null) {\n // We need to auto-detect the intended type of this transaction...\n if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) {\n // The network supports EIP-1559!\n // Upgrade transaction from null to eip-1559\n pop.type = 2;\n if (pop.gasPrice != null) {\n // Using legacy gasPrice property on an eip-1559 network,\n // so use gasPrice as both fee properties\n const gasPrice = pop.gasPrice;\n delete pop.gasPrice;\n pop.maxFeePerGas = gasPrice;\n pop.maxPriorityFeePerGas = gasPrice;\n }\n else {\n // Populate missing fee data\n if (pop.maxFeePerGas == null) {\n pop.maxFeePerGas = feeData.maxFeePerGas;\n }\n if (pop.maxPriorityFeePerGas == null) {\n pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;\n }\n }\n }\n else if (feeData.gasPrice != null) {\n // Network doesn't support EIP-1559...\n // ...but they are trying to use EIP-1559 properties\n assert(!hasEip1559, \"network does not support EIP-1559\", \"UNSUPPORTED_OPERATION\", {\n operation: \"populateTransaction\"\n });\n // Populate missing fee data\n if (pop.gasPrice == null) {\n pop.gasPrice = feeData.gasPrice;\n }\n // Explicitly set untyped transaction to legacy\n // @TODO: Maybe this shold allow type 1?\n pop.type = 0;\n }\n else {\n // getFeeData has failed us.\n assert(false, \"failed to get consistent fee data\", \"UNSUPPORTED_OPERATION\", {\n operation: \"signer.getFeeData\"\n });\n }\n }\n else if (pop.type === 2 || pop.type === 3) {\n // Explicitly using EIP-1559 or EIP-4844\n // Populate missing fee data\n if (pop.maxFeePerGas == null) {\n pop.maxFeePerGas = feeData.maxFeePerGas;\n }\n if (pop.maxPriorityFeePerGas == null) {\n pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;\n }\n }\n }\n //@TOOD: Don't await all over the place; save them up for\n // the end for better batching\n return await resolveProperties(pop);\n }\n async estimateGas(tx) {\n return checkProvider(this, \"estimateGas\").estimateGas(await this.populateCall(tx));\n }\n async call(tx) {\n return checkProvider(this, \"call\").call(await this.populateCall(tx));\n }\n async resolveName(name) {\n const provider = checkProvider(this, \"resolveName\");\n return await provider.resolveName(name);\n }\n async sendTransaction(tx) {\n const provider = checkProvider(this, \"sendTransaction\");\n const pop = await this.populateTransaction(tx);\n delete pop.from;\n const txObj = Transaction.from(pop);\n return await provider.broadcastTransaction(await this.signTransaction(txObj));\n }\n}\n/**\n * A **VoidSigner** is a class deisgned to allow an address to be used\n * in any API which accepts a Signer, but for which there are no\n * credentials available to perform any actual signing.\n *\n * This for example allow impersonating an account for the purpose of\n * static calls or estimating gas, but does not allow sending transactions.\n */\nexport class VoidSigner extends AbstractSigner {\n /**\n * The signer address.\n */\n address;\n /**\n * Creates a new **VoidSigner** with %%address%% attached to\n * %%provider%%.\n */\n constructor(address, provider) {\n super(provider);\n defineProperties(this, { address });\n }\n async getAddress() { return this.address; }\n connect(provider) {\n return new VoidSigner(this.address, provider);\n }\n #throwUnsupported(suffix, operation) {\n assert(false, `VoidSigner cannot sign ${suffix}`, \"UNSUPPORTED_OPERATION\", { operation });\n }\n async signTransaction(tx) {\n this.#throwUnsupported(\"transactions\", \"signTransaction\");\n }\n async signMessage(message) {\n this.#throwUnsupported(\"messages\", \"signMessage\");\n }\n async signTypedData(domain, types, value) {\n this.#throwUnsupported(\"typed-data\", \"signTypedData\");\n }\n}\n//# sourceMappingURL=abstract-signer.js.map","import { isError } from \"../utils/index.js\";\nimport { PollingEventSubscriber } from \"./subscriber-polling.js\";\nfunction copy(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n/**\n * Some backends support subscribing to events using a Filter ID.\n *\n * When subscribing with this technique, the node issues a unique\n * //Filter ID//. At this point the node dedicates resources to\n * the filter, so that periodic calls to follow up on the //Filter ID//\n * will receive any events since the last call.\n *\n * @_docloc: api/providers/abstract-provider\n */\nexport class FilterIdSubscriber {\n #provider;\n #filterIdPromise;\n #poller;\n #running;\n #network;\n #hault;\n /**\n * Creates a new **FilterIdSubscriber** which will used [[_subscribe]]\n * and [[_emitResults]] to setup the subscription and provide the event\n * to the %%provider%%.\n */\n constructor(provider) {\n this.#provider = provider;\n this.#filterIdPromise = null;\n this.#poller = this.#poll.bind(this);\n this.#running = false;\n this.#network = null;\n this.#hault = false;\n }\n /**\n * Sub-classes **must** override this to begin the subscription.\n */\n _subscribe(provider) {\n throw new Error(\"subclasses must override this\");\n }\n /**\n * Sub-classes **must** override this handle the events.\n */\n _emitResults(provider, result) {\n throw new Error(\"subclasses must override this\");\n }\n /**\n * Sub-classes **must** override this handle recovery on errors.\n */\n _recover(provider) {\n throw new Error(\"subclasses must override this\");\n }\n async #poll(blockNumber) {\n try {\n // Subscribe if necessary\n if (this.#filterIdPromise == null) {\n this.#filterIdPromise = this._subscribe(this.#provider);\n }\n // Get the Filter ID\n let filterId = null;\n try {\n filterId = await this.#filterIdPromise;\n }\n catch (error) {\n if (!isError(error, \"UNSUPPORTED_OPERATION\") || error.operation !== \"eth_newFilter\") {\n throw error;\n }\n }\n // The backend does not support Filter ID; downgrade to\n // polling\n if (filterId == null) {\n this.#filterIdPromise = null;\n this.#provider._recoverSubscriber(this, this._recover(this.#provider));\n return;\n }\n const network = await this.#provider.getNetwork();\n if (!this.#network) {\n this.#network = network;\n }\n if (this.#network.chainId !== network.chainId) {\n throw new Error(\"chaid changed\");\n }\n if (this.#hault) {\n return;\n }\n const result = await this.#provider.send(\"eth_getFilterChanges\", [filterId]);\n await this._emitResults(this.#provider, result);\n }\n catch (error) {\n console.log(\"@TODO\", error);\n }\n this.#provider.once(\"block\", this.#poller);\n }\n #teardown() {\n const filterIdPromise = this.#filterIdPromise;\n if (filterIdPromise) {\n this.#filterIdPromise = null;\n filterIdPromise.then((filterId) => {\n if (this.#provider.destroyed) {\n return;\n }\n this.#provider.send(\"eth_uninstallFilter\", [filterId]);\n });\n }\n }\n start() {\n if (this.#running) {\n return;\n }\n this.#running = true;\n this.#poll(-2);\n }\n stop() {\n if (!this.#running) {\n return;\n }\n this.#running = false;\n this.#hault = true;\n this.#teardown();\n this.#provider.off(\"block\", this.#poller);\n }\n pause(dropWhilePaused) {\n if (dropWhilePaused) {\n this.#teardown();\n }\n this.#provider.off(\"block\", this.#poller);\n }\n resume() { this.start(); }\n}\n/**\n * A **FilterIdSubscriber** for receiving contract events.\n *\n * @_docloc: api/providers/abstract-provider\n */\nexport class FilterIdEventSubscriber extends FilterIdSubscriber {\n #event;\n /**\n * Creates a new **FilterIdEventSubscriber** attached to %%provider%%\n * listening for %%filter%%.\n */\n constructor(provider, filter) {\n super(provider);\n this.#event = copy(filter);\n }\n _recover(provider) {\n return new PollingEventSubscriber(provider, this.#event);\n }\n async _subscribe(provider) {\n const filterId = await provider.send(\"eth_newFilter\", [this.#event]);\n return filterId;\n }\n async _emitResults(provider, results) {\n for (const result of results) {\n provider.emit(this.#event, provider._wrapLog(result, provider._network));\n }\n }\n}\n/**\n * A **FilterIdSubscriber** for receiving pending transactions events.\n *\n * @_docloc: api/providers/abstract-provider\n */\nexport class FilterIdPendingSubscriber extends FilterIdSubscriber {\n async _subscribe(provider) {\n return await provider.send(\"eth_newPendingTransactionFilter\", []);\n }\n async _emitResults(provider, results) {\n for (const result of results) {\n provider.emit(\"pending\", result);\n }\n }\n}\n//# sourceMappingURL=subscriber-filterid.js.map","/**\n * One of the most common ways to interact with the blockchain is\n * by a node running a JSON-RPC interface which can be connected to,\n * based on the transport, using:\n *\n * - HTTP or HTTPS - [[JsonRpcProvider]]\n * - WebSocket - [[WebSocketProvider]]\n * - IPC - [[IpcSocketProvider]]\n *\n * @_section: api/providers/jsonrpc:JSON-RPC Provider [about-jsonrpcProvider]\n */\n// @TODO:\n// - Add the batching API\n// https://playground.open-rpc.org/?schemaUrl=https://raw.githubusercontent.com/ethereum/eth1.0-apis/assembled-spec/openrpc.json&uiSchema%5BappBar%5D%5Bui:splitView%5D=true&uiSchema%5BappBar%5D%5Bui:input%5D=false&uiSchema%5BappBar%5D%5Bui:examplesDropdown%5D=false\nimport { AbiCoder } from \"../abi/index.js\";\nimport { getAddress, resolveAddress } from \"../address/index.js\";\nimport { TypedDataEncoder } from \"../hash/index.js\";\nimport { accessListify } from \"../transaction/index.js\";\nimport { defineProperties, getBigInt, hexlify, isHexString, toQuantity, toUtf8Bytes, isError, makeError, assert, assertArgument, FetchRequest, resolveProperties } from \"../utils/index.js\";\nimport { AbstractProvider, UnmanagedSubscriber } from \"./abstract-provider.js\";\nimport { AbstractSigner } from \"./abstract-signer.js\";\nimport { Network } from \"./network.js\";\nimport { FilterIdEventSubscriber, FilterIdPendingSubscriber } from \"./subscriber-filterid.js\";\nimport { PollingEventSubscriber } from \"./subscriber-polling.js\";\nconst Primitive = \"bigint,boolean,function,number,string,symbol\".split(/,/g);\n//const Methods = \"getAddress,then\".split(/,/g);\nfunction deepCopy(value) {\n if (value == null || Primitive.indexOf(typeof (value)) >= 0) {\n return value;\n }\n // Keep any Addressable\n if (typeof (value.getAddress) === \"function\") {\n return value;\n }\n if (Array.isArray(value)) {\n return (value.map(deepCopy));\n }\n if (typeof (value) === \"object\") {\n return Object.keys(value).reduce((accum, key) => {\n accum[key] = value[key];\n return accum;\n }, {});\n }\n throw new Error(`should not happen: ${value} (${typeof (value)})`);\n}\nfunction stall(duration) {\n return new Promise((resolve) => { setTimeout(resolve, duration); });\n}\nfunction getLowerCase(value) {\n if (value) {\n return value.toLowerCase();\n }\n return value;\n}\nfunction isPollable(value) {\n return (value && typeof (value.pollingInterval) === \"number\");\n}\nconst defaultOptions = {\n polling: false,\n staticNetwork: null,\n batchStallTime: 10,\n batchMaxSize: (1 << 20),\n batchMaxCount: 100,\n cacheTimeout: 250,\n pollingInterval: 4000\n};\n// @TODO: Unchecked Signers\nexport class JsonRpcSigner extends AbstractSigner {\n address;\n constructor(provider, address) {\n super(provider);\n address = getAddress(address);\n defineProperties(this, { address });\n }\n connect(provider) {\n assert(false, \"cannot reconnect JsonRpcSigner\", \"UNSUPPORTED_OPERATION\", {\n operation: \"signer.connect\"\n });\n }\n async getAddress() {\n return this.address;\n }\n // JSON-RPC will automatially fill in nonce, etc. so we just check from\n async populateTransaction(tx) {\n return await this.populateCall(tx);\n }\n // Returns just the hash of the transaction after sent, which is what\n // the bare JSON-RPC API does;\n async sendUncheckedTransaction(_tx) {\n const tx = deepCopy(_tx);\n const promises = [];\n // Make sure the from matches the sender\n if (tx.from) {\n const _from = tx.from;\n promises.push((async () => {\n const from = await resolveAddress(_from, this.provider);\n assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), \"from address mismatch\", \"transaction\", _tx);\n tx.from = from;\n })());\n }\n else {\n tx.from = this.address;\n }\n // The JSON-RPC for eth_sendTransaction uses 90000 gas; if the user\n // wishes to use this, it is easy to specify explicitly, otherwise\n // we look it up for them.\n if (tx.gasLimit == null) {\n promises.push((async () => {\n tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address });\n })());\n }\n // The address may be an ENS name or Addressable\n if (tx.to != null) {\n const _to = tx.to;\n promises.push((async () => {\n tx.to = await resolveAddress(_to, this.provider);\n })());\n }\n // Wait until all of our properties are filled in\n if (promises.length) {\n await Promise.all(promises);\n }\n const hexTx = this.provider.getRpcTransaction(tx);\n return this.provider.send(\"eth_sendTransaction\", [hexTx]);\n }\n async sendTransaction(tx) {\n // This cannot be mined any earlier than any recent block\n const blockNumber = await this.provider.getBlockNumber();\n // Send the transaction\n const hash = await this.sendUncheckedTransaction(tx);\n // Unfortunately, JSON-RPC only provides and opaque transaction hash\n // for a response, and we need the actual transaction, so we poll\n // for it; it should show up very quickly\n return await (new Promise((resolve, reject) => {\n const timeouts = [1000, 100];\n let invalids = 0;\n const checkTx = async () => {\n try {\n // Try getting the transaction\n const tx = await this.provider.getTransaction(hash);\n if (tx != null) {\n resolve(tx.replaceableTransaction(blockNumber));\n return;\n }\n }\n catch (error) {\n // If we were cancelled: stop polling.\n // If the data is bad: the node returns bad transactions\n // If the network changed: calling again will also fail\n // If unsupported: likely destroyed\n if (isError(error, \"CANCELLED\") || isError(error, \"BAD_DATA\") ||\n isError(error, \"NETWORK_ERROR\") || isError(error, \"UNSUPPORTED_OPERATION\")) {\n if (error.info == null) {\n error.info = {};\n }\n error.info.sendTransactionHash = hash;\n reject(error);\n return;\n }\n // Stop-gap for misbehaving backends; see #4513\n if (isError(error, \"INVALID_ARGUMENT\")) {\n invalids++;\n if (error.info == null) {\n error.info = {};\n }\n error.info.sendTransactionHash = hash;\n if (invalids > 10) {\n reject(error);\n return;\n }\n }\n // Notify anyone that cares; but we will try again, since\n // it is likely an intermittent service error\n this.provider.emit(\"error\", makeError(\"failed to fetch transation after sending (will try again)\", \"UNKNOWN_ERROR\", { error }));\n }\n // Wait another 4 seconds\n this.provider._setTimeout(() => { checkTx(); }, timeouts.pop() || 4000);\n };\n checkTx();\n }));\n }\n async signTransaction(_tx) {\n const tx = deepCopy(_tx);\n // Make sure the from matches the sender\n if (tx.from) {\n const from = await resolveAddress(tx.from, this.provider);\n assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), \"from address mismatch\", \"transaction\", _tx);\n tx.from = from;\n }\n else {\n tx.from = this.address;\n }\n const hexTx = this.provider.getRpcTransaction(tx);\n return await this.provider.send(\"eth_signTransaction\", [hexTx]);\n }\n async signMessage(_message) {\n const message = ((typeof (_message) === \"string\") ? toUtf8Bytes(_message) : _message);\n return await this.provider.send(\"personal_sign\", [\n hexlify(message), this.address.toLowerCase()\n ]);\n }\n async signTypedData(domain, types, _value) {\n const value = deepCopy(_value);\n // Populate any ENS names (in-place)\n const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (value) => {\n const address = await resolveAddress(value);\n assertArgument(address != null, \"TypedData does not support null address\", \"value\", value);\n return address;\n });\n return await this.provider.send(\"eth_signTypedData_v4\", [\n this.address.toLowerCase(),\n JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types, populated.value))\n ]);\n }\n async unlock(password) {\n return this.provider.send(\"personal_unlockAccount\", [\n this.address.toLowerCase(), password, null\n ]);\n }\n // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign\n async _legacySignMessage(_message) {\n const message = ((typeof (_message) === \"string\") ? toUtf8Bytes(_message) : _message);\n return await this.provider.send(\"eth_sign\", [\n this.address.toLowerCase(), hexlify(message)\n ]);\n }\n}\n/**\n * The JsonRpcApiProvider is an abstract class and **MUST** be\n * sub-classed.\n *\n * It provides the base for all JSON-RPC-based Provider interaction.\n *\n * Sub-classing Notes:\n * - a sub-class MUST override _send\n * - a sub-class MUST call the `_start()` method once connected\n */\nexport class JsonRpcApiProvider extends AbstractProvider {\n #options;\n // The next ID to use for the JSON-RPC ID field\n #nextId;\n // Payloads are queued and triggered in batches using the drainTimer\n #payloads;\n #drainTimer;\n #notReady;\n #network;\n #pendingDetectNetwork;\n #scheduleDrain() {\n if (this.#drainTimer) {\n return;\n }\n // If we aren't using batching, no harm in sending it immediately\n const stallTime = (this._getOption(\"batchMaxCount\") === 1) ? 0 : this._getOption(\"batchStallTime\");\n this.#drainTimer = setTimeout(() => {\n this.#drainTimer = null;\n const payloads = this.#payloads;\n this.#payloads = [];\n while (payloads.length) {\n // Create payload batches that satisfy our batch constraints\n const batch = [(payloads.shift())];\n while (payloads.length) {\n if (batch.length === this.#options.batchMaxCount) {\n break;\n }\n batch.push((payloads.shift()));\n const bytes = JSON.stringify(batch.map((p) => p.payload));\n if (bytes.length > this.#options.batchMaxSize) {\n payloads.unshift((batch.pop()));\n break;\n }\n }\n // Process the result to each payload\n (async () => {\n const payload = ((batch.length === 1) ? batch[0].payload : batch.map((p) => p.payload));\n this.emit(\"debug\", { action: \"sendRpcPayload\", payload });\n try {\n const result = await this._send(payload);\n this.emit(\"debug\", { action: \"receiveRpcResult\", result });\n // Process results in batch order\n for (const { resolve, reject, payload } of batch) {\n if (this.destroyed) {\n reject(makeError(\"provider destroyed; cancelled request\", \"UNSUPPORTED_OPERATION\", { operation: payload.method }));\n continue;\n }\n // Find the matching result\n const resp = result.filter((r) => (r.id === payload.id))[0];\n // No result; the node failed us in unexpected ways\n if (resp == null) {\n const error = makeError(\"missing response for request\", \"BAD_DATA\", {\n value: result, info: { payload }\n });\n this.emit(\"error\", error);\n reject(error);\n continue;\n }\n // The response is an error\n if (\"error\" in resp) {\n reject(this.getRpcError(payload, resp));\n continue;\n }\n // All good; send the result\n resolve(resp.result);\n }\n }\n catch (error) {\n this.emit(\"debug\", { action: \"receiveRpcError\", error });\n for (const { reject } of batch) {\n // @TODO: augment the error with the payload\n reject(error);\n }\n }\n })();\n }\n }, stallTime);\n }\n constructor(network, options) {\n super(network, options);\n this.#nextId = 1;\n this.#options = Object.assign({}, defaultOptions, options || {});\n this.#payloads = [];\n this.#drainTimer = null;\n this.#network = null;\n this.#pendingDetectNetwork = null;\n {\n let resolve = null;\n const promise = new Promise((_resolve) => {\n resolve = _resolve;\n });\n this.#notReady = { promise, resolve };\n }\n const staticNetwork = this._getOption(\"staticNetwork\");\n if (typeof (staticNetwork) === \"boolean\") {\n assertArgument(!staticNetwork || network !== \"any\", \"staticNetwork cannot be used on special network 'any'\", \"options\", options);\n if (staticNetwork && network != null) {\n this.#network = Network.from(network);\n }\n }\n else if (staticNetwork) {\n // Make sure any static network is compatbile with the provided netwrok\n assertArgument(network == null || staticNetwork.matches(network), \"staticNetwork MUST match network object\", \"options\", options);\n this.#network = staticNetwork;\n }\n }\n /**\n * Returns the value associated with the option %%key%%.\n *\n * Sub-classes can use this to inquire about configuration options.\n */\n _getOption(key) {\n return this.#options[key];\n }\n /**\n * Gets the [[Network]] this provider has committed to. On each call, the network\n * is detected, and if it has changed, the call will reject.\n */\n get _network() {\n assert(this.#network, \"network is not available yet\", \"NETWORK_ERROR\");\n return this.#network;\n }\n /**\n * Resolves to the non-normalized value by performing %%req%%.\n *\n * Sub-classes may override this to modify behavior of actions,\n * and should generally call ``super._perform`` as a fallback.\n */\n async _perform(req) {\n // Legacy networks do not like the type field being passed along (which\n // is fair), so we delete type if it is 0 and a non-EIP-1559 network\n if (req.method === \"call\" || req.method === \"estimateGas\") {\n let tx = req.transaction;\n if (tx && tx.type != null && getBigInt(tx.type)) {\n // If there are no EIP-1559 or newer properties, it might be pre-EIP-1559\n if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {\n const feeData = await this.getFeeData();\n if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) {\n // Network doesn't know about EIP-1559 (and hence type)\n req = Object.assign({}, req, {\n transaction: Object.assign({}, tx, { type: undefined })\n });\n }\n }\n }\n }\n const request = this.getRpcRequest(req);\n if (request != null) {\n return await this.send(request.method, request.args);\n }\n return super._perform(req);\n }\n /**\n * Sub-classes may override this; it detects the *actual* network that\n * we are **currently** connected to.\n *\n * Keep in mind that [[send]] may only be used once [[ready]], otherwise the\n * _send primitive must be used instead.\n */\n async _detectNetwork() {\n const network = this._getOption(\"staticNetwork\");\n if (network) {\n if (network === true) {\n if (this.#network) {\n return this.#network;\n }\n }\n else {\n return network;\n }\n }\n if (this.#pendingDetectNetwork) {\n return await this.#pendingDetectNetwork;\n }\n // If we are ready, use ``send``, which enabled requests to be batched\n if (this.ready) {\n this.#pendingDetectNetwork = (async () => {\n try {\n const result = Network.from(getBigInt(await this.send(\"eth_chainId\", [])));\n this.#pendingDetectNetwork = null;\n return result;\n }\n catch (error) {\n this.#pendingDetectNetwork = null;\n throw error;\n }\n })();\n return await this.#pendingDetectNetwork;\n }\n // We are not ready yet; use the primitive _send\n this.#pendingDetectNetwork = (async () => {\n const payload = {\n id: this.#nextId++, method: \"eth_chainId\", params: [], jsonrpc: \"2.0\"\n };\n this.emit(\"debug\", { action: \"sendRpcPayload\", payload });\n let result;\n try {\n result = (await this._send(payload))[0];\n this.#pendingDetectNetwork = null;\n }\n catch (error) {\n this.#pendingDetectNetwork = null;\n this.emit(\"debug\", { action: \"receiveRpcError\", error });\n throw error;\n }\n this.emit(\"debug\", { action: \"receiveRpcResult\", result });\n if (\"result\" in result) {\n return Network.from(getBigInt(result.result));\n }\n throw this.getRpcError(payload, result);\n })();\n return await this.#pendingDetectNetwork;\n }\n /**\n * Sub-classes **MUST** call this. Until [[_start]] has been called, no calls\n * will be passed to [[_send]] from [[send]]. If it is overridden, then\n * ``super._start()`` **MUST** be called.\n *\n * Calling it multiple times is safe and has no effect.\n */\n _start() {\n if (this.#notReady == null || this.#notReady.resolve == null) {\n return;\n }\n this.#notReady.resolve();\n this.#notReady = null;\n (async () => {\n // Bootstrap the network\n while (this.#network == null && !this.destroyed) {\n try {\n this.#network = await this._detectNetwork();\n }\n catch (error) {\n if (this.destroyed) {\n break;\n }\n console.log(\"JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)\");\n this.emit(\"error\", makeError(\"failed to bootstrap network detection\", \"NETWORK_ERROR\", { event: \"initial-network-discovery\", info: { error } }));\n await stall(1000);\n }\n }\n // Start dispatching requests\n this.#scheduleDrain();\n })();\n }\n /**\n * Resolves once the [[_start]] has been called. This can be used in\n * sub-classes to defer sending data until the connection has been\n * established.\n */\n async _waitUntilReady() {\n if (this.#notReady == null) {\n return;\n }\n return await this.#notReady.promise;\n }\n /**\n * Return a Subscriber that will manage the %%sub%%.\n *\n * Sub-classes may override this to modify the behavior of\n * subscription management.\n */\n _getSubscriber(sub) {\n // Pending Filters aren't availble via polling\n if (sub.type === \"pending\") {\n return new FilterIdPendingSubscriber(this);\n }\n if (sub.type === \"event\") {\n if (this._getOption(\"polling\")) {\n return new PollingEventSubscriber(this, sub.filter);\n }\n return new FilterIdEventSubscriber(this, sub.filter);\n }\n // Orphaned Logs are handled automatically, by the filter, since\n // logs with removed are emitted by it\n if (sub.type === \"orphan\" && sub.filter.orphan === \"drop-log\") {\n return new UnmanagedSubscriber(\"orphan\");\n }\n return super._getSubscriber(sub);\n }\n /**\n * Returns true only if the [[_start]] has been called.\n */\n get ready() { return this.#notReady == null; }\n /**\n * Returns %%tx%% as a normalized JSON-RPC transaction request,\n * which has all values hexlified and any numeric values converted\n * to Quantity values.\n */\n getRpcTransaction(tx) {\n const result = {};\n // JSON-RPC now requires numeric values to be \"quantity\" values\n [\"chainId\", \"gasLimit\", \"gasPrice\", \"type\", \"maxFeePerGas\", \"maxPriorityFeePerGas\", \"nonce\", \"value\"].forEach((key) => {\n if (tx[key] == null) {\n return;\n }\n let dstKey = key;\n if (key === \"gasLimit\") {\n dstKey = \"gas\";\n }\n result[dstKey] = toQuantity(getBigInt(tx[key], `tx.${key}`));\n });\n // Make sure addresses and data are lowercase\n [\"from\", \"to\", \"data\"].forEach((key) => {\n if (tx[key] == null) {\n return;\n }\n result[key] = hexlify(tx[key]);\n });\n // Normalize the access list object\n if (tx.accessList) {\n result[\"accessList\"] = accessListify(tx.accessList);\n }\n if (tx.blobVersionedHashes) {\n // @TODO: Remove this <any> case once EIP-4844 added to prepared tx\n result[\"blobVersionedHashes\"] = tx.blobVersionedHashes.map(h => h.toLowerCase());\n }\n // @TODO: blobs should probably also be copied over, optionally\n // accounting for the kzg property to backfill blobVersionedHashes\n // using the commitment. Or should that be left as an exercise to\n // the caller?\n return result;\n }\n /**\n * Returns the request method and arguments required to perform\n * %%req%%.\n */\n getRpcRequest(req) {\n switch (req.method) {\n case \"chainId\":\n return { method: \"eth_chainId\", args: [] };\n case \"getBlockNumber\":\n return { method: \"eth_blockNumber\", args: [] };\n case \"getGasPrice\":\n return { method: \"eth_gasPrice\", args: [] };\n case \"getPriorityFee\":\n return { method: \"eth_maxPriorityFeePerGas\", args: [] };\n case \"getBalance\":\n return {\n method: \"eth_getBalance\",\n args: [getLowerCase(req.address), req.blockTag]\n };\n case \"getTransactionCount\":\n return {\n method: \"eth_getTransactionCount\",\n args: [getLowerCase(req.address), req.blockTag]\n };\n case \"getCode\":\n return {\n method: \"eth_getCode\",\n args: [getLowerCase(req.address), req.blockTag]\n };\n case \"getStorage\":\n return {\n method: \"eth_getStorageAt\",\n args: [\n getLowerCase(req.address),\n (\"0x\" + req.position.toString(16)),\n req.blockTag\n ]\n };\n case \"broadcastTransaction\":\n return {\n method: \"eth_sendRawTransaction\",\n args: [req.signedTransaction]\n };\n case \"getBlock\":\n if (\"blockTag\" in req) {\n return {\n method: \"eth_getBlockByNumber\",\n args: [req.blockTag, !!req.includeTransactions]\n };\n }\n else if (\"blockHash\" in req) {\n return {\n method: \"eth_getBlockByHash\",\n args: [req.blockHash, !!req.includeTransactions]\n };\n }\n break;\n case \"getTransaction\":\n return {\n method: \"eth_getTransactionByHash\",\n args: [req.hash]\n };\n case \"getTransactionReceipt\":\n return {\n method: \"eth_getTransactionReceipt\",\n args: [req.hash]\n };\n case \"call\":\n return {\n method: \"eth_call\",\n args: [this.getRpcTransaction(req.transaction), req.blockTag]\n };\n case \"estimateGas\": {\n return {\n method: \"eth_estimateGas\",\n args: [this.getRpcTransaction(req.transaction)]\n };\n }\n case \"getLogs\":\n if (req.filter && req.filter.address != null) {\n if (Array.isArray(req.filter.address)) {\n req.filter.address = req.filter.address.map(getLowerCase);\n }\n else {\n req.filter.address = getLowerCase(req.filter.address);\n }\n }\n return { method: \"eth_getLogs\", args: [req.filter] };\n }\n return null;\n }\n /**\n * Returns an ethers-style Error for the given JSON-RPC error\n * %%payload%%, coalescing the various strings and error shapes\n * that different nodes return, coercing them into a machine-readable\n * standardized error.\n */\n getRpcError(payload, _error) {\n const { method } = payload;\n const { error } = _error;\n if (method === \"eth_estimateGas\" && error.message) {\n const msg = error.message;\n if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) {\n return makeError(\"insufficient funds\", \"INSUFFICIENT_FUNDS\", {\n transaction: (payload.params[0]),\n info: { payload, error }\n });\n }\n }\n if (method === \"eth_call\" || method === \"eth_estimateGas\") {\n const result = spelunkData(error);\n const e = AbiCoder.getBuiltinCallException((method === \"eth_call\") ? \"call\" : \"estimateGas\", (payload.params[0]), (result ? result.data : null));\n e.info = { error, payload };\n return e;\n }\n // Only estimateGas and call can return arbitrary contract-defined text, so now we\n // we can process text safely.\n const message = JSON.stringify(spelunkMessage(error));\n if (typeof (error.message) === \"string\" && error.message.match(/user denied|ethers-user-denied/i)) {\n const actionMap = {\n eth_sign: \"signMessage\",\n personal_sign: \"signMessage\",\n eth_signTypedData_v4: \"signTypedData\",\n eth_signTransaction: \"signTransaction\",\n eth_sendTransaction: \"sendTransaction\",\n eth_requestAccounts: \"requestAccess\",\n wallet_requestAccounts: \"requestAccess\",\n };\n return makeError(`user rejected action`, \"ACTION_REJECTED\", {\n action: (actionMap[method] || \"unknown\"),\n reason: \"rejected\",\n info: { payload, error }\n });\n }\n if (method === \"eth_sendRawTransaction\" || method === \"eth_sendTransaction\") {\n const transaction = (payload.params[0]);\n if (message.match(/insufficient funds|base fee exceeds gas limit/i)) {\n return makeError(\"insufficient funds for intrinsic transaction cost\", \"INSUFFICIENT_FUNDS\", {\n transaction, info: { error }\n });\n }\n if (message.match(/nonce/i) && message.match(/too low/i)) {\n return makeError(\"nonce has already been used\", \"NONCE_EXPIRED\", { transaction, info: { error } });\n }\n // \"replacement transaction underpriced\"\n if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) {\n return makeError(\"replacement fee too low\", \"REPLACEMENT_UNDERPRICED\", { transaction, info: { error } });\n }\n if (message.match(/only replay-protected/i)) {\n return makeError(\"legacy pre-eip-155 transactions not supported\", \"UNSUPPORTED_OPERATION\", {\n operation: method, info: { transaction, info: { error } }\n });\n }\n }\n let unsupported = !!message.match(/the method .* does not exist/i);\n if (!unsupported) {\n if (error && error.details && error.details.startsWith(\"Unauthorized method:\")) {\n unsupported = true;\n }\n }\n if (unsupported) {\n return makeError(\"unsupported operation\", \"UNSUPPORTED_OPERATION\", {\n operation: payload.method, info: { error, payload }\n });\n }\n return makeError(\"could not coalesce error\", \"UNKNOWN_ERROR\", { error, payload });\n }\n /**\n * Requests the %%method%% with %%params%% via the JSON-RPC protocol\n * over the underlying channel. This can be used to call methods\n * on the backend that do not have a high-level API within the Provider\n * API.\n *\n * This method queues requests according to the batch constraints\n * in the options, assigns the request a unique ID.\n *\n * **Do NOT override** this method in sub-classes; instead\n * override [[_send]] or force the options values in the\n * call to the constructor to modify this method's behavior.\n */\n send(method, params) {\n // @TODO: cache chainId?? purge on switch_networks\n // We have been destroyed; no operations are supported anymore\n if (this.destroyed) {\n return Promise.reject(makeError(\"provider destroyed; cancelled request\", \"UNSUPPORTED_OPERATION\", { operation: method }));\n }\n const id = this.#nextId++;\n const promise = new Promise((resolve, reject) => {\n this.#payloads.push({\n resolve, reject,\n payload: { method, params, id, jsonrpc: \"2.0\" }\n });\n });\n // If there is not a pending drainTimer, set one\n this.#scheduleDrain();\n return promise;\n }\n /**\n * Resolves to the [[Signer]] account for %%address%% managed by\n * the client.\n *\n * If the %%address%% is a number, it is used as an index in the\n * the accounts from [[listAccounts]].\n *\n * This can only be used on clients which manage accounts (such as\n * Geth with imported account or MetaMask).\n *\n * Throws if the account doesn't exist.\n */\n async getSigner(address) {\n if (address == null) {\n address = 0;\n }\n const accountsPromise = this.send(\"eth_accounts\", []);\n // Account index\n if (typeof (address) === \"number\") {\n const accounts = (await accountsPromise);\n if (address >= accounts.length) {\n throw new Error(\"no such account\");\n }\n return new JsonRpcSigner(this, accounts[address]);\n }\n const { accounts } = await resolveProperties({\n network: this.getNetwork(),\n accounts: accountsPromise\n });\n // Account address\n address = getAddress(address);\n for (const account of accounts) {\n if (getAddress(account) === address) {\n return new JsonRpcSigner(this, address);\n }\n }\n throw new Error(\"invalid account\");\n }\n async listAccounts() {\n const accounts = await this.send(\"eth_accounts\", []);\n return accounts.map((a) => new JsonRpcSigner(this, a));\n }\n destroy() {\n // Stop processing requests\n if (this.#drainTimer) {\n clearTimeout(this.#drainTimer);\n this.#drainTimer = null;\n }\n // Cancel all pending requests\n for (const { payload, reject } of this.#payloads) {\n reject(makeError(\"provider destroyed; cancelled request\", \"UNSUPPORTED_OPERATION\", { operation: payload.method }));\n }\n this.#payloads = [];\n // Parent clean-up\n super.destroy();\n }\n}\n// @TODO: remove this in v7, it is not exported because this functionality\n// is exposed in the JsonRpcApiProvider by setting polling to true. It should\n// be safe to remove regardless, because it isn't reachable, but just in case.\n/**\n * @_ignore:\n */\nexport class JsonRpcApiPollingProvider extends JsonRpcApiProvider {\n #pollingInterval;\n constructor(network, options) {\n super(network, options);\n let pollingInterval = this._getOption(\"pollingInterval\");\n if (pollingInterval == null) {\n pollingInterval = defaultOptions.pollingInterval;\n }\n this.#pollingInterval = pollingInterval;\n }\n _getSubscriber(sub) {\n const subscriber = super._getSubscriber(sub);\n if (isPollable(subscriber)) {\n subscriber.pollingInterval = this.#pollingInterval;\n }\n return subscriber;\n }\n /**\n * The polling interval (default: 4000 ms)\n */\n get pollingInterval() { return this.#pollingInterval; }\n set pollingInterval(value) {\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(\"invalid interval\");\n }\n this.#pollingInterval = value;\n this._forEachSubscriber((sub) => {\n if (isPollable(sub)) {\n sub.pollingInterval = this.#pollingInterval;\n }\n });\n }\n}\n/**\n * The JsonRpcProvider is one of the most common Providers,\n * which performs all operations over HTTP (or HTTPS) requests.\n *\n * Events are processed by polling the backend for the current block\n * number; when it advances, all block-base events are then checked\n * for updates.\n */\nexport class JsonRpcProvider extends JsonRpcApiPollingProvider {\n #connect;\n constructor(url, network, options) {\n if (url == null) {\n url = \"http:/\\/localhost:8545\";\n }\n super(network, options);\n if (typeof (url) === \"string\") {\n this.#connect = new FetchRequest(url);\n }\n else {\n this.#connect = url.clone();\n }\n }\n _getConnection() {\n return this.#connect.clone();\n }\n async send(method, params) {\n // All requests are over HTTP, so we can just start handling requests\n // We do this here rather than the constructor so that we don't send any\n // requests to the network (i.e. eth_chainId) until we absolutely have to.\n await this._start();\n return await super.send(method, params);\n }\n async _send(payload) {\n // Configure a POST connection for the requested method\n const request = this._getConnection();\n request.body = JSON.stringify(payload);\n request.setHeader(\"content-type\", \"application/json\");\n const response = await request.send();\n response.assertOk();\n let resp = response.bodyJson;\n if (!Array.isArray(resp)) {\n resp = [resp];\n }\n return resp;\n }\n}\nfunction spelunkData(value) {\n if (value == null) {\n return null;\n }\n // These *are* the droids we're looking for.\n if (typeof (value.message) === \"string\" && value.message.match(/revert/i) && isHexString(value.data)) {\n return { message: value.message, data: value.data };\n }\n // Spelunk further...\n if (typeof (value) === \"object\") {\n for (const key in value) {\n const result = spelunkData(value[key]);\n if (result) {\n return result;\n }\n }\n return null;\n }\n // Might be a JSON string we can further descend...\n if (typeof (value) === \"string\") {\n try {\n return spelunkData(JSON.parse(value));\n }\n catch (error) { }\n }\n return null;\n}\nfunction _spelunkMessage(value, result) {\n if (value == null) {\n return;\n }\n // These *are* the droids we're looking for.\n if (typeof (value.message) === \"string\") {\n result.push(value.message);\n }\n // Spelunk further...\n if (typeof (value) === \"object\") {\n for (const key in value) {\n _spelunkMessage(value[key], result);\n }\n }\n // Might be a JSON string we can further descend...\n if (typeof (value) === \"string\") {\n try {\n return _spelunkMessage(JSON.parse(value), result);\n }\n catch (error) { }\n }\n}\nfunction spelunkMessage(value) {\n const result = [];\n _spelunkMessage(value, result);\n return result;\n}\n//# sourceMappingURL=provider-jsonrpc.js.map","import { assertArgument } from \"../utils/index.js\";\nimport { JsonRpcApiPollingProvider } from \"./provider-jsonrpc.js\";\n;\n/**\n * A **BrowserProvider** is intended to wrap an injected provider which\n * adheres to the [[link-eip-1193]] standard, which most (if not all)\n * currently do.\n */\nexport class BrowserProvider extends JsonRpcApiPollingProvider {\n #request;\n /**\n * Connnect to the %%ethereum%% provider, optionally forcing the\n * %%network%%.\n */\n constructor(ethereum, network, _options) {\n // Copy the options\n const options = Object.assign({}, ((_options != null) ? _options : {}), { batchMaxCount: 1 });\n assertArgument(ethereum && ethereum.request, \"invalid EIP-1193 provider\", \"ethereum\", ethereum);\n super(network, options);\n this.#request = async (method, params) => {\n const payload = { method, params };\n this.emit(\"debug\", { action: \"sendEip1193Request\", payload });\n try {\n const result = await ethereum.request(payload);\n this.emit(\"debug\", { action: \"receiveEip1193Result\", result });\n return result;\n }\n catch (e) {\n const error = new Error(e.message);\n error.code = e.code;\n error.data = e.data;\n error.payload = payload;\n this.emit(\"debug\", { action: \"receiveEip1193Error\", error });\n throw error;\n }\n };\n }\n async send(method, params) {\n await this._start();\n return await super.send(method, params);\n }\n async _send(payload) {\n assertArgument(!Array.isArray(payload), \"EIP-1193 does not support batch request\", \"payload\", payload);\n try {\n const result = await this.#request(payload.method, payload.params || []);\n return [{ id: payload.id, result }];\n }\n catch (e) {\n return [{\n id: payload.id,\n error: { code: e.code, data: e.data, message: e.message }\n }];\n }\n }\n getRpcError(payload, error) {\n error = JSON.parse(JSON.stringify(error));\n // EIP-1193 gives us some machine-readable error codes, so rewrite\n // them into \n switch (error.error.code || -1) {\n case 4001:\n error.error.message = `ethers-user-denied: ${error.error.message}`;\n break;\n case 4200:\n error.error.message = `ethers-unsupported: ${error.error.message}`;\n break;\n }\n return super.getRpcError(payload, error);\n }\n /**\n * Resolves to ``true`` if the provider manages the %%address%%.\n */\n async hasSigner(address) {\n if (address == null) {\n address = 0;\n }\n const accounts = await this.send(\"eth_accounts\", []);\n if (typeof (address) === \"number\") {\n return (accounts.length > address);\n }\n address = address.toLowerCase();\n return accounts.filter((a) => (a.toLowerCase() === address)).length !== 0;\n }\n async getSigner(address) {\n if (address == null) {\n address = 0;\n }\n if (!(await this.hasSigner(address))) {\n try {\n //const resp = \n await this.#request(\"eth_requestAccounts\", []);\n //console.log(\"RESP\", resp);\n }\n catch (error) {\n const payload = error.payload;\n throw this.getRpcError(payload, { id: payload.id, error });\n }\n }\n return await super.getSigner(address);\n }\n}\n//# sourceMappingURL=provider-browser.js.map","import { getAddress, resolveAddress } from \"../address/index.js\";\nimport { hashMessage, TypedDataEncoder } from \"../hash/index.js\";\nimport { AbstractSigner, copyRequest } from \"../providers/index.js\";\nimport { computeAddress, Transaction } from \"../transaction/index.js\";\nimport { defineProperties, resolveProperties, assert, assertArgument } from \"../utils/index.js\";\n/**\n * The **BaseWallet** is a stream-lined implementation of a\n * [[Signer]] that operates with a private key.\n *\n * It is preferred to use the [[Wallet]] class, as it offers\n * additional functionality and simplifies loading a variety\n * of JSON formats, Mnemonic Phrases, etc.\n *\n * This class may be of use for those attempting to implement\n * a minimal Signer.\n */\nexport class BaseWallet extends AbstractSigner {\n /**\n * The wallet address.\n */\n address;\n #signingKey;\n /**\n * Creates a new BaseWallet for %%privateKey%%, optionally\n * connected to %%provider%%.\n *\n * If %%provider%% is not specified, only offline methods can\n * be used.\n */\n constructor(privateKey, provider) {\n super(provider);\n assertArgument(privateKey && typeof (privateKey.sign) === \"function\", \"invalid private key\", \"privateKey\", \"[ REDACTED ]\");\n this.#signingKey = privateKey;\n const address = computeAddress(this.signingKey.publicKey);\n defineProperties(this, { address });\n }\n // Store private values behind getters to reduce visibility\n // in console.log\n /**\n * The [[SigningKey]] used for signing payloads.\n */\n get signingKey() { return this.#signingKey; }\n /**\n * The private key for this wallet.\n */\n get privateKey() { return this.signingKey.privateKey; }\n async getAddress() { return this.address; }\n connect(provider) {\n return new BaseWallet(this.#signingKey, provider);\n }\n async signTransaction(tx) {\n tx = copyRequest(tx);\n // Replace any Addressable or ENS name with an address\n const { to, from } = await resolveProperties({\n to: (tx.to ? resolveAddress(tx.to, this.provider) : undefined),\n from: (tx.from ? resolveAddress(tx.from, this.provider) : undefined)\n });\n if (to != null) {\n tx.to = to;\n }\n if (from != null) {\n tx.from = from;\n }\n if (tx.from != null) {\n assertArgument(getAddress((tx.from)) === this.address, \"transaction from address mismatch\", \"tx.from\", tx.from);\n delete tx.from;\n }\n // Build the transaction\n const btx = Transaction.from(tx);\n btx.signature = this.signingKey.sign(btx.unsignedHash);\n return btx.serialized;\n }\n async signMessage(message) {\n return this.signMessageSync(message);\n }\n // @TODO: Add a secialized signTx and signTyped sync that enforces\n // all parameters are known?\n /**\n * Returns the signature for %%message%% signed with this wallet.\n */\n signMessageSync(message) {\n return this.signingKey.sign(hashMessage(message)).serialized;\n }\n async signTypedData(domain, types, value) {\n // Populate any ENS names\n const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (name) => {\n // @TODO: this should use resolveName; addresses don't\n // need a provider\n assert(this.provider != null, \"cannot resolve ENS names without a provider\", \"UNSUPPORTED_OPERATION\", {\n operation: \"resolveName\",\n info: { name }\n });\n const address = await this.provider.resolveName(name);\n assert(address != null, \"unconfigured ENS name\", \"UNCONFIGURED_NAME\", {\n value: name\n });\n return address;\n });\n return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types, populated.value)).serialized;\n }\n}\n//# sourceMappingURL=base-wallet.js.map","import { assertArgument } from \"../utils/index.js\";\nconst subsChrs = \" !#$%&'()*+,-./<=>?@[]^_`{|}~\";\nconst Word = /^[a-z]*$/i;\nfunction unfold(words, sep) {\n let initial = 97;\n return words.reduce((accum, word) => {\n if (word === sep) {\n initial++;\n }\n else if (word.match(Word)) {\n accum.push(String.fromCharCode(initial) + word);\n }\n else {\n initial = 97;\n accum.push(word);\n }\n return accum;\n }, []);\n}\n/**\n * @_ignore\n */\nexport function decode(data, subs) {\n // Replace all the substitutions with their expanded form\n for (let i = subsChrs.length - 1; i >= 0; i--) {\n data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2));\n }\n // Get all tle clumps; each suffix, first-increment and second-increment\n const clumps = [];\n const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => {\n if (semi) {\n for (let i = parseInt(semi); i >= 0; i--) {\n clumps.push(\";\");\n }\n }\n else {\n clumps.push(item.toLowerCase());\n }\n return \"\";\n });\n /* c8 ignore start */\n if (leftover) {\n throw new Error(`leftovers: ${JSON.stringify(leftover)}`);\n }\n /* c8 ignore stop */\n return unfold(unfold(clumps, \";\"), \":\");\n}\n/**\n * @_ignore\n */\nexport function decodeOwl(data) {\n assertArgument(data[0] === \"0\", \"unsupported auwl data\", \"data\", data);\n return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length));\n}\n//# sourceMappingURL=decode-owl.js.map","import { defineProperties } from \"../utils/index.js\";\n/**\n * A Wordlist represents a collection of language-specific\n * words used to encode and devoce [[link-bip-39]] encoded data\n * by mapping words to 11-bit values and vice versa.\n */\nexport class Wordlist {\n locale;\n /**\n * Creates a new Wordlist instance.\n *\n * Sub-classes MUST call this if they provide their own constructor,\n * passing in the locale string of the language.\n *\n * Generally there is no need to create instances of a Wordlist,\n * since each language-specific Wordlist creates an instance and\n * there is no state kept internally, so they are safe to share.\n */\n constructor(locale) {\n defineProperties(this, { locale });\n }\n /**\n * Sub-classes may override this to provide a language-specific\n * method for spliting %%phrase%% into individual words.\n *\n * By default, %%phrase%% is split using any sequences of\n * white-space as defined by regular expressions (i.e. ``/\\s+/``).\n */\n split(phrase) {\n return phrase.toLowerCase().split(/\\s+/g);\n }\n /**\n * Sub-classes may override this to provider a language-specific\n * method for joining %%words%% into a phrase.\n *\n * By default, %%words%% are joined by a single space.\n */\n join(words) {\n return words.join(\" \");\n }\n}\n//# sourceMappingURL=wordlist.js.map","// Use the encode-latin.js script to create the necessary\n// data files to be consumed by this class\nimport { id } from \"../hash/index.js\";\nimport { assertArgument } from \"../utils/index.js\";\nimport { decodeOwl } from \"./decode-owl.js\";\nimport { Wordlist } from \"./wordlist.js\";\n/**\n * An OWL format Wordlist is an encoding method that exploits\n * the general locality of alphabetically sorted words to\n * achieve a simple but effective means of compression.\n *\n * This class is generally not useful to most developers as\n * it is used mainly internally to keep Wordlists for languages\n * based on ASCII-7 small.\n *\n * If necessary, there are tools within the ``generation/`` folder\n * to create the necessary data.\n */\nexport class WordlistOwl extends Wordlist {\n #data;\n #checksum;\n /**\n * Creates a new Wordlist for %%locale%% using the OWL %%data%%\n * and validated against the %%checksum%%.\n */\n constructor(locale, data, checksum) {\n super(locale);\n this.#data = data;\n this.#checksum = checksum;\n this.#words = null;\n }\n /**\n * The OWL-encoded data.\n */\n get _data() { return this.#data; }\n /**\n * Decode all the words for the wordlist.\n */\n _decodeWords() {\n return decodeOwl(this.#data);\n }\n #words;\n #loadWords() {\n if (this.#words == null) {\n const words = this._decodeWords();\n // Verify the computed list matches the official list\n const checksum = id(words.join(\"\\n\") + \"\\n\");\n /* c8 ignore start */\n if (checksum !== this.#checksum) {\n throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`);\n }\n /* c8 ignore stop */\n this.#words = words;\n }\n return this.#words;\n }\n getWord(index) {\n const words = this.#loadWords();\n assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, \"index\", index);\n return words[index];\n }\n getWordIndex(word) {\n return this.#loadWords().indexOf(word);\n }\n}\n//# sourceMappingURL=wordlist-owl.js.map","import { WordlistOwl } from \"./wordlist-owl.js\";\nconst words = \"0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN<aNn RRelyRga(R*lSeS-SketTt!3A^AnAutyCau'ComeEfF%eG(Ha=H(dLie=LowLtN^Nef./TrayTt Twe&Y#d3Cyc!DKeNdOlogyRdR`Tt _{AdeAmeAnketA,EakE[IndOodO[omOu'UeUrUsh_rdAtDyIlMbNeNusOkO,Rd R(gRrowSsTtomUn)XY_{etA(AndA[A=EadEezeI{Id+IefIghtIngIskOccoliOk&OnzeOomO` OwnUsh2Bb!DdyD+tFf$oIldLbLkL!tNd!Nk Rd&Rg R,SS(e[SyTt Y Zz:Bba+B(B!CtusGeKe~LmM aMpNN$N)lNdyNn#NoeNvasNy#Pab!P.$Pta(RRb#RdRgoRpetRryRtSeShS(o/!Su$TT$ogT^Teg%yTt!UghtU'Ut]Ve3Il(gL yM|NsusNturyRe$Rta(_irAlkAmp]An+AosApt Ar+A'AtEapE{Ee'EfErryE,I{&IefIldIm}yOi)Oo'R#-U{!UnkUrn0G?Nnam#Rc!Tiz&TyVil_imApArifyAwAyE<ErkEv I{I|IffImbIn-IpO{OgO'O`OudOwnUbUmpU, Ut^_^A,C#utDeFfeeIlInL!@L%LumnMb(eMeMf%tM-Mm#Mp<yNc tNdu@NfirmNg*[N}@Nsid NtrolNv()OkOlPp PyR$ReRnR*@/Tt#U^UntryUp!Ur'Us(V Yo>_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M<dMi'Ni$Nti,NyP?tP&dPos.P`PutyRi=ScribeS tSignSkSpair/royTailTe@VelopVi)Vo>3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyO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+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOg<OtOwUsh0AllArtI!OkeOo`0A{AkeApIffOw0ApCc Ci$CkDaFtL?Ldi LidLut]L=Me#eNgOnRryRtUlUndUpUr)U`0A)A*Ati$AwnEakEci$EedEllEndH eI)Id IkeInIr.L.OilOns%O#OrtOtRayReadR(gY0Ua*UeezeUir*l_b!AdiumAffA+AirsAmpAndArtA>AyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NN<tNnisNtRm/Xt_nkAtEmeEnE%yE*EyIngIsOughtReeRi=RowUmbUnd 0CketDeG LtMb MeNyPRedSsueT!5A,BaccoDayDdl EGe` I!tK&MatoM%rowNeNgueNightOlO`PP-Pp!R^RnadoRtoi'SsT$Uri,W?dW WnY_{AdeAff-Ag-A(Ansf ApAshA=lAyEatEeEndI$IbeI{Igg ImIpOphyOub!U{UeUlyUmpetU,U`Y2BeIt]Mb!NaN}lRkeyRnRt!1El=EntyI)InI,O1PeP-$:5Ly5B*lla0Ab!Awa*C!Cov D DoFairFoldHappyIf%mIqueItIv 'KnownLo{TilUsu$Veil1Da>GradeHoldOnP Set1B<Ge0A+EEdEfulE![U$0Il.y:C<tCuumGueLidL!yL=NNishP%Rious/Ult3H-!L=tNd%Ntu*NueRbRifyRs]RyS'lT <3Ab!Br<tCiousCt%yDeoEw~a+Nta+Ol(Rtu$RusSaS.Su$T$Vid5C$I)IdLc<oLumeTeYa+:GeG#ItLk~LnutNtRfa*RmRri%ShSp/eT VeY3Al`Ap#ArA'lA` BDd(gEk&dIrdLcome/T_!AtEatEelEnE*IpIsp 0DeD`FeLd~NNdowNeNgNkNn Nt ReSdomSeShT}[5LfM<Nd OdOlRdRkRldRryR`_pE{E,!I,I>Ong::Rd3Ar~ow9UUngU`:3BraRo9NeO\";\nconst checksum = \"0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60\";\nlet wordlist = null;\n/**\n * The [[link-bip39-en]] for [mnemonic phrases](link-bip-39).\n *\n * @_docloc: api/wordlists\n */\nexport class LangEn extends WordlistOwl {\n /**\n * Creates a new instance of the English language Wordlist.\n *\n * This should be unnecessary most of the time as the exported\n * [[langEn]] should suffice.\n *\n * @_ignore:\n */\n constructor() { super(\"en\", words, checksum); }\n /**\n * Returns a singleton instance of a ``LangEn``, creating it\n * if this is the first time being called.\n */\n static wordlist() {\n if (wordlist == null) {\n wordlist = new LangEn();\n }\n return wordlist;\n }\n}\n//# sourceMappingURL=lang-en.js.map","import { pbkdf2, sha256 } from \"../crypto/index.js\";\nimport { defineProperties, getBytes, hexlify, assertNormalize, assertPrivate, assertArgument, toUtf8Bytes } from \"../utils/index.js\";\nimport { LangEn } from \"../wordlists/lang-en.js\";\n// Returns a byte with the MSB bits set\nfunction getUpperMask(bits) {\n return ((1 << bits) - 1) << (8 - bits) & 0xff;\n}\n// Returns a byte with the LSB bits set\nfunction getLowerMask(bits) {\n return ((1 << bits) - 1) & 0xff;\n}\nfunction mnemonicToEntropy(mnemonic, wordlist) {\n assertNormalize(\"NFKD\");\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n const words = wordlist.split(mnemonic);\n assertArgument((words.length % 3) === 0 && words.length >= 12 && words.length <= 24, \"invalid mnemonic length\", \"mnemonic\", \"[ REDACTED ]\");\n const entropy = new Uint8Array(Math.ceil(11 * words.length / 8));\n let offset = 0;\n for (let i = 0; i < words.length; i++) {\n let index = wordlist.getWordIndex(words[i].normalize(\"NFKD\"));\n assertArgument(index >= 0, `invalid mnemonic word at index ${i}`, \"mnemonic\", \"[ REDACTED ]\");\n for (let bit = 0; bit < 11; bit++) {\n if (index & (1 << (10 - bit))) {\n entropy[offset >> 3] |= (1 << (7 - (offset % 8)));\n }\n offset++;\n }\n }\n const entropyBits = 32 * words.length / 3;\n const checksumBits = words.length / 3;\n const checksumMask = getUpperMask(checksumBits);\n const checksum = getBytes(sha256(entropy.slice(0, entropyBits / 8)))[0] & checksumMask;\n assertArgument(checksum === (entropy[entropy.length - 1] & checksumMask), \"invalid mnemonic checksum\", \"mnemonic\", \"[ REDACTED ]\");\n return hexlify(entropy.slice(0, entropyBits / 8));\n}\nfunction entropyToMnemonic(entropy, wordlist) {\n assertArgument((entropy.length % 4) === 0 && entropy.length >= 16 && entropy.length <= 32, \"invalid entropy size\", \"entropy\", \"[ REDACTED ]\");\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n const indices = [0];\n let remainingBits = 11;\n for (let i = 0; i < entropy.length; i++) {\n // Consume the whole byte (with still more to go)\n if (remainingBits > 8) {\n indices[indices.length - 1] <<= 8;\n indices[indices.length - 1] |= entropy[i];\n remainingBits -= 8;\n // This byte will complete an 11-bit index\n }\n else {\n indices[indices.length - 1] <<= remainingBits;\n indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits);\n // Start the next word\n indices.push(entropy[i] & getLowerMask(8 - remainingBits));\n remainingBits += 3;\n }\n }\n // Compute the checksum bits\n const checksumBits = entropy.length / 4;\n const checksum = parseInt(sha256(entropy).substring(2, 4), 16) & getUpperMask(checksumBits);\n // Shift the checksum into the word indices\n indices[indices.length - 1] <<= checksumBits;\n indices[indices.length - 1] |= (checksum >> (8 - checksumBits));\n return wordlist.join(indices.map((index) => wordlist.getWord(index)));\n}\nconst _guard = {};\n/**\n * A **Mnemonic** wraps all properties required to compute [[link-bip-39]]\n * seeds and convert between phrases and entropy.\n */\nexport class Mnemonic {\n /**\n * The mnemonic phrase of 12, 15, 18, 21 or 24 words.\n *\n * Use the [[wordlist]] ``split`` method to get the individual words.\n */\n phrase;\n /**\n * The password used for this mnemonic. If no password is used this\n * is the empty string (i.e. ``\"\"``) as per the specification.\n */\n password;\n /**\n * The wordlist for this mnemonic.\n */\n wordlist;\n /**\n * The underlying entropy which the mnemonic encodes.\n */\n entropy;\n /**\n * @private\n */\n constructor(guard, entropy, phrase, password, wordlist) {\n if (password == null) {\n password = \"\";\n }\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n assertPrivate(guard, _guard, \"Mnemonic\");\n defineProperties(this, { phrase, password, wordlist, entropy });\n }\n /**\n * Returns the seed for the mnemonic.\n */\n computeSeed() {\n const salt = toUtf8Bytes(\"mnemonic\" + this.password, \"NFKD\");\n return pbkdf2(toUtf8Bytes(this.phrase, \"NFKD\"), salt, 2048, 64, \"sha512\");\n }\n /**\n * Creates a new Mnemonic for the %%phrase%%.\n *\n * The default %%password%% is the empty string and the default\n * wordlist is the [English wordlists](LangEn).\n */\n static fromPhrase(phrase, password, wordlist) {\n // Normalize the case and space; throws if invalid\n const entropy = mnemonicToEntropy(phrase, wordlist);\n phrase = entropyToMnemonic(getBytes(entropy), wordlist);\n return new Mnemonic(_guard, entropy, phrase, password, wordlist);\n }\n /**\n * Create a new **Mnemonic** from the %%entropy%%.\n *\n * The default %%password%% is the empty string and the default\n * wordlist is the [English wordlists](LangEn).\n */\n static fromEntropy(_entropy, password, wordlist) {\n const entropy = getBytes(_entropy, \"entropy\");\n const phrase = entropyToMnemonic(entropy, wordlist);\n return new Mnemonic(_guard, hexlify(entropy), phrase, password, wordlist);\n }\n /**\n * Returns the phrase for %%mnemonic%%.\n */\n static entropyToPhrase(_entropy, wordlist) {\n const entropy = getBytes(_entropy, \"entropy\");\n return entropyToMnemonic(entropy, wordlist);\n }\n /**\n * Returns the entropy for %%phrase%%.\n */\n static phraseToEntropy(phrase, wordlist) {\n return mnemonicToEntropy(phrase, wordlist);\n }\n /**\n * Returns true if %%phrase%% is a valid [[link-bip-39]] phrase.\n *\n * This checks all the provided words belong to the %%wordlist%%,\n * that the length is valid and the checksum is correct.\n */\n static isValidMnemonic(phrase, wordlist) {\n try {\n mnemonicToEntropy(phrase, wordlist);\n return true;\n }\n catch (error) { }\n return false;\n }\n}\n//# sourceMappingURL=mnemonic.js.map","/**\n * @_ignore\n */\nimport { getBytesCopy, assertArgument, toUtf8Bytes } from \"../utils/index.js\";\nexport function looseArrayify(hexString) {\n if (typeof (hexString) === \"string\" && !hexString.startsWith(\"0x\")) {\n hexString = \"0x\" + hexString;\n }\n return getBytesCopy(hexString);\n}\nexport function zpad(value, length) {\n value = String(value);\n while (value.length < length) {\n value = '0' + value;\n }\n return value;\n}\nexport function getPassword(password) {\n if (typeof (password) === 'string') {\n return toUtf8Bytes(password, \"NFKC\");\n }\n return getBytesCopy(password);\n}\nexport function spelunk(object, _path) {\n const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i);\n assertArgument(match != null, \"invalid path\", \"path\", _path);\n const path = match[1];\n const type = match[3];\n const reqd = (match[4] === \"!\");\n let cur = object;\n for (const comp of path.toLowerCase().split('.')) {\n // Search for a child object with a case-insensitive matching key\n if (Array.isArray(cur)) {\n if (!comp.match(/^[0-9]+$/)) {\n break;\n }\n cur = cur[parseInt(comp)];\n }\n else if (typeof (cur) === \"object\") {\n let found = null;\n for (const key in cur) {\n if (key.toLowerCase() === comp) {\n found = cur[key];\n break;\n }\n }\n cur = found;\n }\n else {\n cur = null;\n }\n if (cur == null) {\n break;\n }\n }\n assertArgument(!reqd || cur != null, \"missing required value\", \"path\", path);\n if (type && cur != null) {\n if (type === \"int\") {\n if (typeof (cur) === \"string\" && cur.match(/^-?[0-9]+$/)) {\n return parseInt(cur);\n }\n else if (Number.isSafeInteger(cur)) {\n return cur;\n }\n }\n if (type === \"number\") {\n if (typeof (cur) === \"string\" && cur.match(/^-?[0-9.]*$/)) {\n return parseFloat(cur);\n }\n }\n if (type === \"data\") {\n if (typeof (cur) === \"string\") {\n return looseArrayify(cur);\n }\n }\n if (type === \"array\" && Array.isArray(cur)) {\n return cur;\n }\n if (type === typeof (cur)) {\n return cur;\n }\n assertArgument(false, `wrong type found for ${type} `, \"path\", path);\n }\n return cur;\n}\n/*\nexport function follow(object: any, path: string): null | string {\n let currentChild = object;\n\n for (const comp of path.toLowerCase().split('/')) {\n\n // Search for a child object with a case-insensitive matching key\n let matchingChild = null;\n for (const key in currentChild) {\n if (key.toLowerCase() === comp) {\n matchingChild = currentChild[key];\n break;\n }\n }\n\n if (matchingChild === null) { return null; }\n\n currentChild = matchingChild;\n }\n\n return currentChild;\n}\n\n// \"path/to/something:type!\"\nexport function followRequired(data: any, path: string): string {\n const value = follow(data, path);\n if (value != null) { return value; }\n return logger.throwArgumentError(\"invalid value\", `data:${ path }`,\n JSON.stringify(data));\n}\n*/\n// See: https://www.ietf.org/rfc/rfc4122.txt (Section 4.4)\n/*\nexport function uuidV4(randomBytes: BytesLike): string {\n const bytes = getBytes(randomBytes, \"randomBytes\");\n\n // Section: 4.1.3:\n // - time_hi_and_version[12:16] = 0b0100\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n\n // Section 4.4\n // - clock_seq_hi_and_reserved[6] = 0b0\n // - clock_seq_hi_and_reserved[7] = 0b1\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n\n const value = hexlify(bytes);\n\n return [\n value.substring(2, 10),\n value.substring(10, 14),\n value.substring(14, 18),\n value.substring(18, 22),\n value.substring(22, 34),\n ].join(\"-\");\n}\n*/\n//# sourceMappingURL=utils.js.map","/**\n * The JSON Wallet formats allow a simple way to store the private\n * keys needed in Ethereum along with related information and allows\n * for extensible forms of encryption.\n *\n * These utilities facilitate decrypting and encrypting the most common\n * JSON Wallet formats.\n *\n * @_subsection: api/wallet:JSON Wallets [json-wallets]\n */\nimport { CTR } from \"aes-js\";\nimport { getAddress } from \"../address/index.js\";\nimport { keccak256, pbkdf2, randomBytes, scrypt, scryptSync } from \"../crypto/index.js\";\nimport { computeAddress } from \"../transaction/index.js\";\nimport { concat, getBytes, hexlify, uuidV4, assert, assertArgument } from \"../utils/index.js\";\nimport { getPassword, spelunk, zpad } from \"./utils.js\";\nimport { version } from \"../_version.js\";\nconst defaultPath = \"m/44'/60'/0'/0/0\";\n/**\n * Returns true if %%json%% is a valid JSON Keystore Wallet.\n */\nexport function isKeystoreJson(json) {\n try {\n const data = JSON.parse(json);\n const version = ((data.version != null) ? parseInt(data.version) : 0);\n if (version === 3) {\n return true;\n }\n }\n catch (error) { }\n return false;\n}\nfunction decrypt(data, key, ciphertext) {\n const cipher = spelunk(data, \"crypto.cipher:string\");\n if (cipher === \"aes-128-ctr\") {\n const iv = spelunk(data, \"crypto.cipherparams.iv:data!\");\n const aesCtr = new CTR(key, iv);\n return hexlify(aesCtr.decrypt(ciphertext));\n }\n assert(false, \"unsupported cipher\", \"UNSUPPORTED_OPERATION\", {\n operation: \"decrypt\"\n });\n}\nfunction getAccount(data, _key) {\n const key = getBytes(_key);\n const ciphertext = spelunk(data, \"crypto.ciphertext:data!\");\n const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2);\n assertArgument(computedMAC === spelunk(data, \"crypto.mac:string!\").toLowerCase(), \"incorrect password\", \"password\", \"[ REDACTED ]\");\n const privateKey = decrypt(data, key.slice(0, 16), ciphertext);\n const address = computeAddress(privateKey);\n if (data.address) {\n let check = data.address.toLowerCase();\n if (!check.startsWith(\"0x\")) {\n check = \"0x\" + check;\n }\n assertArgument(getAddress(check) === address, \"keystore address/privateKey mismatch\", \"address\", data.address);\n }\n const account = { address, privateKey };\n // Version 0.1 x-ethers metadata must contain an encrypted mnemonic phrase\n const version = spelunk(data, \"x-ethers.version:string\");\n if (version === \"0.1\") {\n const mnemonicKey = key.slice(32, 64);\n const mnemonicCiphertext = spelunk(data, \"x-ethers.mnemonicCiphertext:data!\");\n const mnemonicIv = spelunk(data, \"x-ethers.mnemonicCounter:data!\");\n const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv);\n account.mnemonic = {\n path: (spelunk(data, \"x-ethers.path:string\") || defaultPath),\n locale: (spelunk(data, \"x-ethers.locale:string\") || \"en\"),\n entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext)))\n };\n }\n return account;\n}\nfunction getDecryptKdfParams(data) {\n const kdf = spelunk(data, \"crypto.kdf:string\");\n if (kdf && typeof (kdf) === \"string\") {\n if (kdf.toLowerCase() === \"scrypt\") {\n const salt = spelunk(data, \"crypto.kdfparams.salt:data!\");\n const N = spelunk(data, \"crypto.kdfparams.n:int!\");\n const r = spelunk(data, \"crypto.kdfparams.r:int!\");\n const p = spelunk(data, \"crypto.kdfparams.p:int!\");\n // Make sure N is a power of 2\n assertArgument(N > 0 && (N & (N - 1)) === 0, \"invalid kdf.N\", \"kdf.N\", N);\n assertArgument(r > 0 && p > 0, \"invalid kdf\", \"kdf\", kdf);\n const dkLen = spelunk(data, \"crypto.kdfparams.dklen:int!\");\n assertArgument(dkLen === 32, \"invalid kdf.dklen\", \"kdf.dflen\", dkLen);\n return { name: \"scrypt\", salt, N, r, p, dkLen: 64 };\n }\n else if (kdf.toLowerCase() === \"pbkdf2\") {\n const salt = spelunk(data, \"crypto.kdfparams.salt:data!\");\n const prf = spelunk(data, \"crypto.kdfparams.prf:string!\");\n const algorithm = prf.split(\"-\").pop();\n assertArgument(algorithm === \"sha256\" || algorithm === \"sha512\", \"invalid kdf.pdf\", \"kdf.pdf\", prf);\n const count = spelunk(data, \"crypto.kdfparams.c:int!\");\n const dkLen = spelunk(data, \"crypto.kdfparams.dklen:int!\");\n assertArgument(dkLen === 32, \"invalid kdf.dklen\", \"kdf.dklen\", dkLen);\n return { name: \"pbkdf2\", salt, count, dkLen, algorithm };\n }\n }\n assertArgument(false, \"unsupported key-derivation function\", \"kdf\", kdf);\n}\n/**\n * Returns the account details for the JSON Keystore Wallet %%json%%\n * using %%password%%.\n *\n * It is preferred to use the [async version](decryptKeystoreJson)\n * instead, which allows a [[ProgressCallback]] to keep the user informed\n * as to the decryption status.\n *\n * This method will block the event loop (freezing all UI) until decryption\n * is complete, which can take quite some time, depending on the wallet\n * paramters and platform.\n */\nexport function decryptKeystoreJsonSync(json, _password) {\n const data = JSON.parse(json);\n const password = getPassword(_password);\n const params = getDecryptKdfParams(data);\n if (params.name === \"pbkdf2\") {\n const { salt, count, dkLen, algorithm } = params;\n const key = pbkdf2(password, salt, count, dkLen, algorithm);\n return getAccount(data, key);\n }\n assert(params.name === \"scrypt\", \"cannot be reached\", \"UNKNOWN_ERROR\", { params });\n const { salt, N, r, p, dkLen } = params;\n const key = scryptSync(password, salt, N, r, p, dkLen);\n return getAccount(data, key);\n}\nfunction stall(duration) {\n return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); });\n}\n/**\n * Resolves to the decrypted JSON Keystore Wallet %%json%% using the\n * %%password%%.\n *\n * If provided, %%progress%% will be called periodically during the\n * decrpytion to provide feedback, and if the function returns\n * ``false`` will halt decryption.\n *\n * The %%progressCallback%% will **always** receive ``0`` before\n * decryption begins and ``1`` when complete.\n */\nexport async function decryptKeystoreJson(json, _password, progress) {\n const data = JSON.parse(json);\n const password = getPassword(_password);\n const params = getDecryptKdfParams(data);\n if (params.name === \"pbkdf2\") {\n if (progress) {\n progress(0);\n await stall(0);\n }\n const { salt, count, dkLen, algorithm } = params;\n const key = pbkdf2(password, salt, count, dkLen, algorithm);\n if (progress) {\n progress(1);\n await stall(0);\n }\n return getAccount(data, key);\n }\n assert(params.name === \"scrypt\", \"cannot be reached\", \"UNKNOWN_ERROR\", { params });\n const { salt, N, r, p, dkLen } = params;\n const key = await scrypt(password, salt, N, r, p, dkLen, progress);\n return getAccount(data, key);\n}\nfunction getEncryptKdfParams(options) {\n // Check/generate the salt\n const salt = (options.salt != null) ? getBytes(options.salt, \"options.salt\") : randomBytes(32);\n // Override the scrypt password-based key derivation function parameters\n let N = (1 << 17), r = 8, p = 1;\n if (options.scrypt) {\n if (options.scrypt.N) {\n N = options.scrypt.N;\n }\n if (options.scrypt.r) {\n r = options.scrypt.r;\n }\n if (options.scrypt.p) {\n p = options.scrypt.p;\n }\n }\n assertArgument(typeof (N) === \"number\" && N > 0 && Number.isSafeInteger(N) && (BigInt(N) & BigInt(N - 1)) === BigInt(0), \"invalid scrypt N parameter\", \"options.N\", N);\n assertArgument(typeof (r) === \"number\" && r > 0 && Number.isSafeInteger(r), \"invalid scrypt r parameter\", \"options.r\", r);\n assertArgument(typeof (p) === \"number\" && p > 0 && Number.isSafeInteger(p), \"invalid scrypt p parameter\", \"options.p\", p);\n return { name: \"scrypt\", dkLen: 32, salt, N, r, p };\n}\nfunction _encryptKeystore(key, kdf, account, options) {\n const privateKey = getBytes(account.privateKey, \"privateKey\");\n // Override initialization vector\n const iv = (options.iv != null) ? getBytes(options.iv, \"options.iv\") : randomBytes(16);\n assertArgument(iv.length === 16, \"invalid options.iv length\", \"options.iv\", options.iv);\n // Override the uuid\n const uuidRandom = (options.uuid != null) ? getBytes(options.uuid, \"options.uuid\") : randomBytes(16);\n assertArgument(uuidRandom.length === 16, \"invalid options.uuid length\", \"options.uuid\", options.iv);\n // This will be used to encrypt the wallet (as per Web3 secret storage)\n // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix)\n // - 32 bytes AES key to encrypt mnemonic with (required here to be Ethers Wallet)\n const derivedKey = key.slice(0, 16);\n const macPrefix = key.slice(16, 32);\n // Encrypt the private key\n const aesCtr = new CTR(derivedKey, iv);\n const ciphertext = getBytes(aesCtr.encrypt(privateKey));\n // Compute the message authentication code, used to check the password\n const mac = keccak256(concat([macPrefix, ciphertext]));\n // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition\n const data = {\n address: account.address.substring(2).toLowerCase(),\n id: uuidV4(uuidRandom),\n version: 3,\n Crypto: {\n cipher: \"aes-128-ctr\",\n cipherparams: {\n iv: hexlify(iv).substring(2),\n },\n ciphertext: hexlify(ciphertext).substring(2),\n kdf: \"scrypt\",\n kdfparams: {\n salt: hexlify(kdf.salt).substring(2),\n n: kdf.N,\n dklen: 32,\n p: kdf.p,\n r: kdf.r\n },\n mac: mac.substring(2)\n }\n };\n // If we have a mnemonic, encrypt it into the JSON wallet\n if (account.mnemonic) {\n const client = (options.client != null) ? options.client : `ethers/${version}`;\n const path = account.mnemonic.path || defaultPath;\n const locale = account.mnemonic.locale || \"en\";\n const mnemonicKey = key.slice(32, 64);\n const entropy = getBytes(account.mnemonic.entropy, \"account.mnemonic.entropy\");\n const mnemonicIv = randomBytes(16);\n const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv);\n const mnemonicCiphertext = getBytes(mnemonicAesCtr.encrypt(entropy));\n const now = new Date();\n const timestamp = (now.getUTCFullYear() + \"-\" +\n zpad(now.getUTCMonth() + 1, 2) + \"-\" +\n zpad(now.getUTCDate(), 2) + \"T\" +\n zpad(now.getUTCHours(), 2) + \"-\" +\n zpad(now.getUTCMinutes(), 2) + \"-\" +\n zpad(now.getUTCSeconds(), 2) + \".0Z\");\n const gethFilename = (\"UTC--\" + timestamp + \"--\" + data.address);\n data[\"x-ethers\"] = {\n client, gethFilename, path, locale,\n mnemonicCounter: hexlify(mnemonicIv).substring(2),\n mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2),\n version: \"0.1\"\n };\n }\n return JSON.stringify(data);\n}\n/**\n * Return the JSON Keystore Wallet for %%account%% encrypted with\n * %%password%%.\n *\n * The %%options%% can be used to tune the password-based key\n * derivation function parameters, explicitly set the random values\n * used. Any provided [[ProgressCallback]] is ignord.\n */\nexport function encryptKeystoreJsonSync(account, password, options) {\n if (options == null) {\n options = {};\n }\n const passwordBytes = getPassword(password);\n const kdf = getEncryptKdfParams(options);\n const key = scryptSync(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64);\n return _encryptKeystore(getBytes(key), kdf, account, options);\n}\n/**\n * Resolved to the JSON Keystore Wallet for %%account%% encrypted\n * with %%password%%.\n *\n * The %%options%% can be used to tune the password-based key\n * derivation function parameters, explicitly set the random values\n * used and provide a [[ProgressCallback]] to receive periodic updates\n * on the completion status..\n */\nexport async function encryptKeystoreJson(account, password, options) {\n if (options == null) {\n options = {};\n }\n const passwordBytes = getPassword(password);\n const kdf = getEncryptKdfParams(options);\n const key = await scrypt(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64, options.progressCallback);\n return _encryptKeystore(getBytes(key), kdf, account, options);\n}\n//# sourceMappingURL=json-keystore.js.map","/**\n * Explain HD Wallets..\n *\n * @_subsection: api/wallet:HD Wallets [hd-wallets]\n */\nimport { computeHmac, randomBytes, ripemd160, SigningKey, sha256 } from \"../crypto/index.js\";\nimport { VoidSigner } from \"../providers/index.js\";\nimport { computeAddress } from \"../transaction/index.js\";\nimport { concat, dataSlice, decodeBase58, defineProperties, encodeBase58, getBytes, hexlify, isBytesLike, getNumber, toBeArray, toBigInt, toBeHex, assertPrivate, assert, assertArgument } from \"../utils/index.js\";\nimport { LangEn } from \"../wordlists/lang-en.js\";\nimport { BaseWallet } from \"./base-wallet.js\";\nimport { Mnemonic } from \"./mnemonic.js\";\nimport { encryptKeystoreJson, encryptKeystoreJsonSync, } from \"./json-keystore.js\";\n/**\n * The default derivation path for Ethereum HD Nodes. (i.e. ``\"m/44'/60'/0'/0/0\"``)\n */\nexport const defaultPath = \"m/44'/60'/0'/0/0\";\n// \"Bitcoin seed\"\nconst MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]);\nconst HardenedBit = 0x80000000;\nconst N = BigInt(\"0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141\");\nconst Nibbles = \"0123456789abcdef\";\nfunction zpad(value, length) {\n let result = \"\";\n while (value) {\n result = Nibbles[value % 16] + result;\n value = Math.trunc(value / 16);\n }\n while (result.length < length * 2) {\n result = \"0\" + result;\n }\n return \"0x\" + result;\n}\nfunction encodeBase58Check(_value) {\n const value = getBytes(_value);\n const check = dataSlice(sha256(sha256(value)), 0, 4);\n const bytes = concat([value, check]);\n return encodeBase58(bytes);\n}\nconst _guard = {};\nfunction ser_I(index, chainCode, publicKey, privateKey) {\n const data = new Uint8Array(37);\n if (index & HardenedBit) {\n assert(privateKey != null, \"cannot derive child of neutered node\", \"UNSUPPORTED_OPERATION\", {\n operation: \"deriveChild\"\n });\n // Data = 0x00 || ser_256(k_par)\n data.set(getBytes(privateKey), 1);\n }\n else {\n // Data = ser_p(point(k_par))\n data.set(getBytes(publicKey));\n }\n // Data += ser_32(i)\n for (let i = 24; i >= 0; i -= 8) {\n data[33 + (i >> 3)] = ((index >> (24 - i)) & 0xff);\n }\n const I = getBytes(computeHmac(\"sha512\", chainCode, data));\n return { IL: I.slice(0, 32), IR: I.slice(32) };\n}\nfunction derivePath(node, path) {\n const components = path.split(\"/\");\n assertArgument(components.length > 0, \"invalid path\", \"path\", path);\n if (components[0] === \"m\") {\n assertArgument(node.depth === 0, `cannot derive root path (i.e. path starting with \"m/\") for a node at non-zero depth ${node.depth}`, \"path\", path);\n components.shift();\n }\n let result = node;\n for (let i = 0; i < components.length; i++) {\n const component = components[i];\n if (component.match(/^[0-9]+'$/)) {\n const index = parseInt(component.substring(0, component.length - 1));\n assertArgument(index < HardenedBit, \"invalid path index\", `path[${i}]`, component);\n result = result.deriveChild(HardenedBit + index);\n }\n else if (component.match(/^[0-9]+$/)) {\n const index = parseInt(component);\n assertArgument(index < HardenedBit, \"invalid path index\", `path[${i}]`, component);\n result = result.deriveChild(index);\n }\n else {\n assertArgument(false, \"invalid path component\", `path[${i}]`, component);\n }\n }\n return result;\n}\n/**\n * An **HDNodeWallet** is a [[Signer]] backed by the private key derived\n * from an HD Node using the [[link-bip-32]] stantard.\n *\n * An HD Node forms a hierarchal structure with each HD Node having a\n * private key and the ability to derive child HD Nodes, defined by\n * a path indicating the index of each child.\n */\nexport class HDNodeWallet extends BaseWallet {\n /**\n * The compressed public key.\n */\n publicKey;\n /**\n * The fingerprint.\n *\n * A fingerprint allows quick qay to detect parent and child nodes,\n * but developers should be prepared to deal with collisions as it\n * is only 4 bytes.\n */\n fingerprint;\n /**\n * The parent fingerprint.\n */\n parentFingerprint;\n /**\n * The mnemonic used to create this HD Node, if available.\n *\n * Sources such as extended keys do not encode the mnemonic, in\n * which case this will be ``null``.\n */\n mnemonic;\n /**\n * The chaincode, which is effectively a public key used\n * to derive children.\n */\n chainCode;\n /**\n * The derivation path of this wallet.\n *\n * Since extended keys do not provide full path details, this\n * may be ``null``, if instantiated from a source that does not\n * encode it.\n */\n path;\n /**\n * The child index of this wallet. Values over ``2 *\\* 31`` indicate\n * the node is hardened.\n */\n index;\n /**\n * The depth of this wallet, which is the number of components\n * in its path.\n */\n depth;\n /**\n * @private\n */\n constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider) {\n super(signingKey, provider);\n assertPrivate(guard, _guard, \"HDNodeWallet\");\n defineProperties(this, { publicKey: signingKey.compressedPublicKey });\n const fingerprint = dataSlice(ripemd160(sha256(this.publicKey)), 0, 4);\n defineProperties(this, {\n parentFingerprint, fingerprint,\n chainCode, path, index, depth\n });\n defineProperties(this, { mnemonic });\n }\n connect(provider) {\n return new HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider);\n }\n #account() {\n const account = { address: this.address, privateKey: this.privateKey };\n const m = this.mnemonic;\n if (this.path && m && m.wordlist.locale === \"en\" && m.password === \"\") {\n account.mnemonic = {\n path: this.path,\n locale: \"en\",\n entropy: m.entropy\n };\n }\n return account;\n }\n /**\n * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with\n * %%password%%.\n *\n * If %%progressCallback%% is specified, it will receive periodic\n * updates as the encryption process progreses.\n */\n async encrypt(password, progressCallback) {\n return await encryptKeystoreJson(this.#account(), password, { progressCallback });\n }\n /**\n * Returns a [JSON Keystore Wallet](json-wallets) encryped with\n * %%password%%.\n *\n * It is preferred to use the [async version](encrypt) instead,\n * which allows a [[ProgressCallback]] to keep the user informed.\n *\n * This method will block the event loop (freezing all UI) until\n * it is complete, which may be a non-trivial duration.\n */\n encryptSync(password) {\n return encryptKeystoreJsonSync(this.#account(), password);\n }\n /**\n * The extended key.\n *\n * This key will begin with the prefix ``xpriv`` and can be used to\n * reconstruct this HD Node to derive its children.\n */\n get extendedKey() {\n // We only support the mainnet values for now, but if anyone needs\n // testnet values, let me know. I believe current sentiment is that\n // we should always use mainnet, and use BIP-44 to derive the network\n // - Mainnet: public=0x0488B21E, private=0x0488ADE4\n // - Testnet: public=0x043587CF, private=0x04358394\n assert(this.depth < 256, \"Depth too deep\", \"UNSUPPORTED_OPERATION\", { operation: \"extendedKey\" });\n return encodeBase58Check(concat([\n \"0x0488ADE4\", zpad(this.depth, 1), this.parentFingerprint,\n zpad(this.index, 4), this.chainCode,\n concat([\"0x00\", this.privateKey])\n ]));\n }\n /**\n * Returns true if this wallet has a path, providing a Type Guard\n * that the path is non-null.\n */\n hasPath() { return (this.path != null); }\n /**\n * Returns a neutered HD Node, which removes the private details\n * of an HD Node.\n *\n * A neutered node has no private key, but can be used to derive\n * child addresses and other public data about the HD Node.\n */\n neuter() {\n return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider);\n }\n /**\n * Return the child for %%index%%.\n */\n deriveChild(_index) {\n const index = getNumber(_index, \"index\");\n assertArgument(index <= 0xffffffff, \"invalid index\", \"index\", index);\n // Base path\n let path = this.path;\n if (path) {\n path += \"/\" + (index & ~HardenedBit);\n if (index & HardenedBit) {\n path += \"'\";\n }\n }\n const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey);\n const ki = new SigningKey(toBeHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32));\n return new HDNodeWallet(_guard, ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.mnemonic, this.provider);\n }\n /**\n * Return the HDNode for %%path%% from this node.\n */\n derivePath(path) {\n return derivePath(this, path);\n }\n static #fromSeed(_seed, mnemonic) {\n assertArgument(isBytesLike(_seed), \"invalid seed\", \"seed\", \"[REDACTED]\");\n const seed = getBytes(_seed, \"seed\");\n assertArgument(seed.length >= 16 && seed.length <= 64, \"invalid seed\", \"seed\", \"[REDACTED]\");\n const I = getBytes(computeHmac(\"sha512\", MasterSecret, seed));\n const signingKey = new SigningKey(hexlify(I.slice(0, 32)));\n return new HDNodeWallet(_guard, signingKey, \"0x00000000\", hexlify(I.slice(32)), \"m\", 0, 0, mnemonic, null);\n }\n /**\n * Creates a new HD Node from %%extendedKey%%.\n *\n * If the %%extendedKey%% will either have a prefix or ``xpub`` or\n * ``xpriv``, returning a neutered HD Node ([[HDNodeVoidWallet]])\n * or full HD Node ([[HDNodeWallet) respectively.\n */\n static fromExtendedKey(extendedKey) {\n const bytes = toBeArray(decodeBase58(extendedKey)); // @TODO: redact\n assertArgument(bytes.length === 82 || encodeBase58Check(bytes.slice(0, 78)) === extendedKey, \"invalid extended key\", \"extendedKey\", \"[ REDACTED ]\");\n const depth = bytes[4];\n const parentFingerprint = hexlify(bytes.slice(5, 9));\n const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16);\n const chainCode = hexlify(bytes.slice(13, 45));\n const key = bytes.slice(45, 78);\n switch (hexlify(bytes.slice(0, 4))) {\n // Public Key\n case \"0x0488b21e\":\n case \"0x043587cf\": {\n const publicKey = hexlify(key);\n return new HDNodeVoidWallet(_guard, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null);\n }\n // Private Key\n case \"0x0488ade4\":\n case \"0x04358394 \":\n if (key[0] !== 0) {\n break;\n }\n return new HDNodeWallet(_guard, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null);\n }\n assertArgument(false, \"invalid extended key prefix\", \"extendedKey\", \"[ REDACTED ]\");\n }\n /**\n * Creates a new random HDNode.\n */\n static createRandom(password, path, wordlist) {\n if (password == null) {\n password = \"\";\n }\n if (path == null) {\n path = defaultPath;\n }\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist);\n return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);\n }\n /**\n * Create an HD Node from %%mnemonic%%.\n */\n static fromMnemonic(mnemonic, path) {\n if (!path) {\n path = defaultPath;\n }\n return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);\n }\n /**\n * Creates an HD Node from a mnemonic %%phrase%%.\n */\n static fromPhrase(phrase, password, path, wordlist) {\n if (password == null) {\n password = \"\";\n }\n if (path == null) {\n path = defaultPath;\n }\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist);\n return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);\n }\n /**\n * Creates an HD Node from a %%seed%%.\n */\n static fromSeed(seed) {\n return HDNodeWallet.#fromSeed(seed, null);\n }\n}\n/**\n * A **HDNodeVoidWallet** cannot sign, but provides access to\n * the children nodes of a [[link-bip-32]] HD wallet addresses.\n *\n * The can be created by using an extended ``xpub`` key to\n * [[HDNodeWallet_fromExtendedKey]] or by\n * [nuetering](HDNodeWallet-neuter) a [[HDNodeWallet]].\n */\nexport class HDNodeVoidWallet extends VoidSigner {\n /**\n * The compressed public key.\n */\n publicKey;\n /**\n * The fingerprint.\n *\n * A fingerprint allows quick qay to detect parent and child nodes,\n * but developers should be prepared to deal with collisions as it\n * is only 4 bytes.\n */\n fingerprint;\n /**\n * The parent node fingerprint.\n */\n parentFingerprint;\n /**\n * The chaincode, which is effectively a public key used\n * to derive children.\n */\n chainCode;\n /**\n * The derivation path of this wallet.\n *\n * Since extended keys do not provider full path details, this\n * may be ``null``, if instantiated from a source that does not\n * enocde it.\n */\n path;\n /**\n * The child index of this wallet. Values over ``2 *\\* 31`` indicate\n * the node is hardened.\n */\n index;\n /**\n * The depth of this wallet, which is the number of components\n * in its path.\n */\n depth;\n /**\n * @private\n */\n constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider) {\n super(address, provider);\n assertPrivate(guard, _guard, \"HDNodeVoidWallet\");\n defineProperties(this, { publicKey });\n const fingerprint = dataSlice(ripemd160(sha256(publicKey)), 0, 4);\n defineProperties(this, {\n publicKey, fingerprint, parentFingerprint, chainCode, path, index, depth\n });\n }\n connect(provider) {\n return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider);\n }\n /**\n * The extended key.\n *\n * This key will begin with the prefix ``xpub`` and can be used to\n * reconstruct this neutered key to derive its children addresses.\n */\n get extendedKey() {\n // We only support the mainnet values for now, but if anyone needs\n // testnet values, let me know. I believe current sentiment is that\n // we should always use mainnet, and use BIP-44 to derive the network\n // - Mainnet: public=0x0488B21E, private=0x0488ADE4\n // - Testnet: public=0x043587CF, private=0x04358394\n assert(this.depth < 256, \"Depth too deep\", \"UNSUPPORTED_OPERATION\", { operation: \"extendedKey\" });\n return encodeBase58Check(concat([\n \"0x0488B21E\",\n zpad(this.depth, 1),\n this.parentFingerprint,\n zpad(this.index, 4),\n this.chainCode,\n this.publicKey,\n ]));\n }\n /**\n * Returns true if this wallet has a path, providing a Type Guard\n * that the path is non-null.\n */\n hasPath() { return (this.path != null); }\n /**\n * Return the child for %%index%%.\n */\n deriveChild(_index) {\n const index = getNumber(_index, \"index\");\n assertArgument(index <= 0xffffffff, \"invalid index\", \"index\", index);\n // Base path\n let path = this.path;\n if (path) {\n path += \"/\" + (index & ~HardenedBit);\n if (index & HardenedBit) {\n path += \"'\";\n }\n }\n const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null);\n const Ki = SigningKey.addPoints(IL, this.publicKey, true);\n const address = computeAddress(Ki);\n return new HDNodeVoidWallet(_guard, address, Ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.provider);\n }\n /**\n * Return the signer for %%path%% from this node.\n */\n derivePath(path) {\n return derivePath(this, path);\n }\n}\n/*\nexport class HDNodeWalletManager {\n #root: HDNodeWallet;\n\n constructor(phrase: string, password?: null | string, path?: null | string, locale?: null | Wordlist) {\n if (password == null) { password = \"\"; }\n if (path == null) { path = \"m/44'/60'/0'/0\"; }\n if (locale == null) { locale = LangEn.wordlist(); }\n this.#root = HDNodeWallet.fromPhrase(phrase, password, path, locale);\n }\n\n getSigner(index?: number): HDNodeWallet {\n return this.#root.deriveChild((index == null) ? 0: index);\n }\n}\n*/\n/**\n * Returns the [[link-bip-32]] path for the account at %%index%%.\n *\n * This is the pattern used by wallets like Ledger.\n *\n * There is also an [alternate pattern](getIndexedAccountPath) used by\n * some software.\n */\nexport function getAccountPath(_index) {\n const index = getNumber(_index, \"index\");\n assertArgument(index >= 0 && index < HardenedBit, \"invalid account index\", \"index\", index);\n return `m/44'/60'/${index}'/0/0`;\n}\n/**\n * Returns the path using an alternative pattern for deriving accounts,\n * at %%index%%.\n *\n * This derivation path uses the //index// component rather than the\n * //account// component to derive sequential accounts.\n *\n * This is the pattern used by wallets like MetaMask.\n */\nexport function getIndexedAccountPath(_index) {\n const index = getNumber(_index, \"index\");\n assertArgument(index >= 0 && index < HardenedBit, \"invalid account index\", \"index\", index);\n return `m/44'/60'/0'/0/${index}`;\n}\n//# sourceMappingURL=hdwallet.js.map","/**\n * @_subsection: api/wallet:JSON Wallets [json-wallets]\n */\nimport { CBC, pkcs7Strip } from \"aes-js\";\nimport { getAddress } from \"../address/index.js\";\nimport { pbkdf2 } from \"../crypto/index.js\";\nimport { id } from \"../hash/index.js\";\nimport { getBytes, assertArgument } from \"../utils/index.js\";\nimport { getPassword, looseArrayify, spelunk } from \"./utils.js\";\n/**\n * Returns true if %%json%% is a valid JSON Crowdsale wallet.\n */\nexport function isCrowdsaleJson(json) {\n try {\n const data = JSON.parse(json);\n if (data.encseed) {\n return true;\n }\n }\n catch (error) { }\n return false;\n}\n// See: https://github.com/ethereum/pyethsaletool\n/**\n * Before Ethereum launched, it was necessary to create a wallet\n * format for backers to use, which would be used to receive ether\n * as a reward for contributing to the project.\n *\n * The [[link-crowdsale]] format is now obsolete, but it is still\n * useful to support and the additional code is fairly trivial as\n * all the primitives required are used through core portions of\n * the library.\n */\nexport function decryptCrowdsaleJson(json, _password) {\n const data = JSON.parse(json);\n const password = getPassword(_password);\n // Ethereum Address\n const address = getAddress(spelunk(data, \"ethaddr:string!\"));\n // Encrypted Seed\n const encseed = looseArrayify(spelunk(data, \"encseed:string!\"));\n assertArgument(encseed && (encseed.length % 16) === 0, \"invalid encseed\", \"json\", json);\n const key = getBytes(pbkdf2(password, password, 2000, 32, \"sha256\")).slice(0, 16);\n const iv = encseed.slice(0, 16);\n const encryptedSeed = encseed.slice(16);\n // Decrypt the seed\n const aesCbc = new CBC(key, iv);\n const seed = pkcs7Strip(getBytes(aesCbc.decrypt(encryptedSeed)));\n // This wallet format is weird... Convert the binary encoded hex to a string.\n let seedHex = \"\";\n for (let i = 0; i < seed.length; i++) {\n seedHex += String.fromCharCode(seed[i]);\n }\n return { address, privateKey: id(seedHex) };\n}\n//# sourceMappingURL=json-crowdsale.js.map","import { SigningKey } from \"../crypto/index.js\";\nimport { assertArgument } from \"../utils/index.js\";\nimport { BaseWallet } from \"./base-wallet.js\";\nimport { HDNodeWallet } from \"./hdwallet.js\";\nimport { decryptCrowdsaleJson, isCrowdsaleJson } from \"./json-crowdsale.js\";\nimport { decryptKeystoreJson, decryptKeystoreJsonSync, encryptKeystoreJson, encryptKeystoreJsonSync, isKeystoreJson } from \"./json-keystore.js\";\nimport { Mnemonic } from \"./mnemonic.js\";\nfunction stall(duration) {\n return new Promise((resolve) => { setTimeout(() => { resolve(); }, duration); });\n}\n/**\n * A **Wallet** manages a single private key which is used to sign\n * transactions, messages and other common payloads.\n *\n * This class is generally the main entry point for developers\n * that wish to use a private key directly, as it can create\n * instances from a large variety of common sources, including\n * raw private key, [[link-bip-39]] mnemonics and encrypte JSON\n * wallets.\n */\nexport class Wallet extends BaseWallet {\n /**\n * Create a new wallet for the private %%key%%, optionally connected\n * to %%provider%%.\n */\n constructor(key, provider) {\n if (typeof (key) === \"string\" && !key.startsWith(\"0x\")) {\n key = \"0x\" + key;\n }\n let signingKey = (typeof (key) === \"string\") ? new SigningKey(key) : key;\n super(signingKey, provider);\n }\n connect(provider) {\n return new Wallet(this.signingKey, provider);\n }\n /**\n * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with\n * %%password%%.\n *\n * If %%progressCallback%% is specified, it will receive periodic\n * updates as the encryption process progreses.\n */\n async encrypt(password, progressCallback) {\n const account = { address: this.address, privateKey: this.privateKey };\n return await encryptKeystoreJson(account, password, { progressCallback });\n }\n /**\n * Returns a [JSON Keystore Wallet](json-wallets) encryped with\n * %%password%%.\n *\n * It is preferred to use the [async version](encrypt) instead,\n * which allows a [[ProgressCallback]] to keep the user informed.\n *\n * This method will block the event loop (freezing all UI) until\n * it is complete, which may be a non-trivial duration.\n */\n encryptSync(password) {\n const account = { address: this.address, privateKey: this.privateKey };\n return encryptKeystoreJsonSync(account, password);\n }\n static #fromAccount(account) {\n assertArgument(account, \"invalid JSON wallet\", \"json\", \"[ REDACTED ]\");\n if (\"mnemonic\" in account && account.mnemonic && account.mnemonic.locale === \"en\") {\n const mnemonic = Mnemonic.fromEntropy(account.mnemonic.entropy);\n const wallet = HDNodeWallet.fromMnemonic(mnemonic, account.mnemonic.path);\n if (wallet.address === account.address && wallet.privateKey === account.privateKey) {\n return wallet;\n }\n console.log(\"WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key\");\n }\n const wallet = new Wallet(account.privateKey);\n assertArgument(wallet.address === account.address, \"address/privateKey mismatch\", \"json\", \"[ REDACTED ]\");\n return wallet;\n }\n /**\n * Creates (asynchronously) a **Wallet** by decrypting the %%json%%\n * with %%password%%.\n *\n * If %%progress%% is provided, it is called periodically during\n * decryption so that any UI can be updated.\n */\n static async fromEncryptedJson(json, password, progress) {\n let account = null;\n if (isKeystoreJson(json)) {\n account = await decryptKeystoreJson(json, password, progress);\n }\n else if (isCrowdsaleJson(json)) {\n if (progress) {\n progress(0);\n await stall(0);\n }\n account = decryptCrowdsaleJson(json, password);\n if (progress) {\n progress(1);\n await stall(0);\n }\n }\n return Wallet.#fromAccount(account);\n }\n /**\n * Creates a **Wallet** by decrypting the %%json%% with %%password%%.\n *\n * The [[fromEncryptedJson]] method is preferred, as this method\n * will lock up and freeze the UI during decryption, which may take\n * some time.\n */\n static fromEncryptedJsonSync(json, password) {\n let account = null;\n if (isKeystoreJson(json)) {\n account = decryptKeystoreJsonSync(json, password);\n }\n else if (isCrowdsaleJson(json)) {\n account = decryptCrowdsaleJson(json, password);\n }\n else {\n assertArgument(false, \"invalid JSON wallet\", \"json\", \"[ REDACTED ]\");\n }\n return Wallet.#fromAccount(account);\n }\n /**\n * Creates a new random [[HDNodeWallet]] using the available\n * [cryptographic random source](randomBytes).\n *\n * If there is no crytographic random source, this will throw.\n */\n static createRandom(provider) {\n const wallet = HDNodeWallet.createRandom();\n if (provider) {\n return wallet.connect(provider);\n }\n return wallet;\n }\n /**\n * Creates a [[HDNodeWallet]] for %%phrase%%.\n */\n static fromPhrase(phrase, provider) {\n const wallet = HDNodeWallet.fromPhrase(phrase);\n if (provider) {\n return wallet.connect(provider);\n }\n return wallet;\n }\n}\n//# sourceMappingURL=wallet.js.map","let contractAddresses = {\r\n PROOF_OF_INTEGRITY_ADDRESS: \"0xe7f1725E7734CE288F8367e1Bb143E90bb3F0512\",\r\n STEALTH_ANNOUNCER_ADDRESS: \"0x5FbDB2315678afecb367f032d93F642f64180aa3\"\r\n};\r\n\r\nif (typeof window === 'undefined') {\r\n const { fileURLToPath } = require('url');\r\n const { dirname } = require('path');\r\n const { readFileSync } = require('fs');\r\n const { join } = require('path');\r\n\r\n try {\r\n const __filename = fileURLToPath(import.meta.url);\r\n const __dirname = dirname(__filename);\r\n const rawdata = readFileSync(join(__dirname, 'contract-address.json'), 'utf8');\r\n contractAddresses = JSON.parse(rawdata);\r\n console.log(\"Loaded contract addresses:\", contractAddresses);\r\n } catch (error) {\r\n console.warn(\"Warning: contract-address.json not found or invalid\");\r\n }\r\n}\r\n\r\nexport const LOCAL_CONFIG = {\r\n CHAIN_ID: 1337,\r\n PROOF_OF_INTEGRITY_ADDRESS: contractAddresses.PROOF_OF_INTEGRITY_ADDRESS,\r\n STEALTH_ANNOUNCER_ADDRESS: contractAddresses.STEALTH_ANNOUNCER_ADDRESS,\r\n RPC_URL: \"http://127.0.0.1:8545\",\r\n GUN_PEER: \"http://localhost:8765/gun\"\r\n}; ","import { LOCAL_CONFIG } from '../config/local.js';\r\n\r\n// Indirizzi di produzione per diverse chain\r\nexport const CHAIN_CONFIG = {\r\n optimismSepolia: {\r\n STEALTH_ANNOUNCER_ADDRESS: \"0xD0F2e9DA59d2DFECFdE67CcF17300BB6093A72f8\",\r\n PROOF_OF_INTEGRITY_ADDRESS: \"0x...\",\r\n RPC_URL: \"https://sepolia.optimism.io\",\r\n CHAIN_ID: 11155420\r\n },\r\n arbitrumSepolia: {\r\n STEALTH_ANNOUNCER_ADDRESS: \"0x...\",\r\n PROOF_OF_INTEGRITY_ADDRESS: \"0x...\",\r\n RPC_URL: \"https://sepolia-rollup.arbitrum.io/rpc\",\r\n CHAIN_ID: 421614\r\n },\r\n localhost: {\r\n RPC_URL: \"http://127.0.0.1:8545\",\r\n CHAIN_ID: 1337\r\n }\r\n};\r\n\r\n// Funzione per ottenere gli indirizzi corretti\r\nexport function getAddressesForChain(chainName) {\r\n let config;\r\n\r\n // Se è localhost, prova a caricare gli indirizzi locali\r\n if (chainName === 'localhost') {\r\n try {\r\n // Carica gli indirizzi dal file generato dal deploy locale\r\n const localAddresses = require('../config/contract-address.json');\r\n config = {\r\n ...CHAIN_CONFIG.localhost,\r\n ...localAddresses\r\n };\r\n console.log(\"Using local addresses:\", config);\r\n return config;\r\n } catch (err) {\r\n console.warn('No local addresses found');\r\n throw new Error('No local addresses found. Did you run local deployment?');\r\n }\r\n }\r\n\r\n // Altrimenti usa gli indirizzi di produzione\r\n config = CHAIN_CONFIG[chainName];\r\n if (!config) {\r\n throw new Error(`Chain ${chainName} not supported. Supported chains: ${Object.keys(CHAIN_CONFIG).join(', ')}`);\r\n }\r\n\r\n return config;\r\n}\r\n\r\n// Funzione helper per verificare se siamo in ambiente locale\r\nexport function isLocalEnvironment() {\r\n return process.env.NODE_ENV === 'development' && \r\n typeof window !== 'undefined' && \r\n window.location.hostname === 'localhost';\r\n}\r\n\r\nexport const STEALTH_ANNOUNCER_ABI = [\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"_devAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"constructor\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"senderPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"spendingPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"stealthAddress\",\r\n \"type\": \"address\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"timestamp\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"StealthPaymentAnnounced\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"newAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"DevAddressUpdated\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"newFee\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"DevFeeUpdated\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"senderPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"spendingPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"stealthAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"announcePayment\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"payable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"devAddress\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"devFee\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"getAnnouncementsCount\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"fromIndex\",\r\n \"type\": \"uint256\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"toIndex\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"getAnnouncementsInRange\",\r\n \"outputs\": [\r\n {\r\n \"components\": [\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"senderPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"string\",\r\n \"name\": \"spendingPublicKey\",\r\n \"type\": \"string\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"stealthAddress\",\r\n \"type\": \"address\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"timestamp\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"internalType\": \"struct StealthAnnouncer.StealthAnnouncement[]\",\r\n \"name\": \"\",\r\n \"type\": \"tuple[]\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"_newFee\",\r\n \"type\": \"uint256\"\r\n }\r\n ],\r\n \"name\": \"updateDevFee\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"_newAddress\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"updateDevAddress\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [],\r\n \"name\": \"withdrawStuckETH\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n }\r\n];\r\n\r\nexport const PROOF_OF_INTEGRITY_ABI = [\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes[]\",\r\n \"name\": \"nodeIds\",\r\n \"type\": \"bytes[]\"\r\n },\r\n {\r\n \"internalType\": \"bytes32[]\",\r\n \"name\": \"contentHashes\",\r\n \"type\": \"bytes32[]\"\r\n }\r\n ],\r\n \"name\": \"batchUpdateData\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"anonymous\": false,\r\n \"inputs\": [\r\n {\r\n \"indexed\": true,\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n },\r\n {\r\n \"indexed\": false,\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"contentHash\",\r\n \"type\": \"bytes32\"\r\n },\r\n {\r\n \"indexed\": false,\r\n \"internalType\": \"address\",\r\n \"name\": \"updater\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"name\": \"DataUpdated\",\r\n \"type\": \"event\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n }\r\n ],\r\n \"name\": \"getLatestRecord\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"\",\r\n \"type\": \"bytes32\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n },\r\n {\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"contentHash\",\r\n \"type\": \"bytes32\"\r\n }\r\n ],\r\n \"name\": \"updateData\",\r\n \"outputs\": [],\r\n \"stateMutability\": \"nonpayable\",\r\n \"type\": \"function\"\r\n },\r\n {\r\n \"inputs\": [\r\n {\r\n \"internalType\": \"bytes\",\r\n \"name\": \"nodeId\",\r\n \"type\": \"bytes\"\r\n },\r\n {\r\n \"internalType\": \"bytes32\",\r\n \"name\": \"contentHash\",\r\n \"type\": \"bytes32\"\r\n }\r\n ],\r\n \"name\": \"verifyData\",\r\n \"outputs\": [\r\n {\r\n \"internalType\": \"bool\",\r\n \"name\": \"\",\r\n \"type\": \"bool\"\r\n },\r\n {\r\n \"internalType\": \"uint256\",\r\n \"name\": \"\",\r\n \"type\": \"uint256\"\r\n },\r\n {\r\n \"internalType\": \"address\",\r\n \"name\": \"\",\r\n \"type\": \"address\"\r\n }\r\n ],\r\n \"stateMutability\": \"view\",\r\n \"type\": \"function\"\r\n }\r\n];\r\n\r\n\r\nexport const SHINE_OPTIMISM_SEPOLIA = \"0x43D838b683F772F08f321E5FA265ad3e333BE9C2\";\r\n","// =============================================\r\n// IMPORTS AND GLOBAL VARIABLES\r\n// =============================================\r\nimport Gun from \"gun\";\r\nimport SEA from \"gun/sea.js\";\r\nimport { ethers } from \"ethers\";\r\nimport { \r\n PROOF_OF_INTEGRITY_ABI, \r\n STEALTH_ANNOUNCER_ABI,\r\n getAddressesForChain,\r\n isLocalEnvironment \r\n} from \"./abis/abis.js\";\r\nimport { LOCAL_CONFIG } from \"./config/local.js\";\r\n\r\nlet rpcUrl = \"\";\r\nlet privateKey = \"\";\r\n\r\nexport const MESSAGE_TO_SIGN = \"Access GunDB with Ethereum\";\r\n\r\n// =============================================\r\n// UTILITY FUNCTIONS\r\n// =============================================\r\n/**\r\n * Generates a random node ID for GunDB\r\n * @returns {string} A random hexadecimal string\r\n */\r\nexport function generateRandomId() {\r\n return ethers.hexlify(ethers.randomBytes(32)).slice(2);\r\n}\r\n\r\n/**\r\n * Generates a password from a signature.\r\n * @param {string} signature - The signature to derive the password from.\r\n * @returns {string|null} The generated password or null if generation fails.\r\n */\r\nexport function generatePassword(signature) {\r\n try {\r\n const hexSignature = ethers.hexlify(signature);\r\n const hash = ethers.keccak256(hexSignature);\r\n console.log(\"Generated password:\", hash);\r\n return hash;\r\n } catch (error) {\r\n console.error(\"Error generating password:\", error);\r\n return null;\r\n }\r\n}\r\n\r\n/**\r\n * Converts a Gun private key to an Ethereum account.\r\n * @param {string} gunPrivateKey - The Gun private key in base64url format.\r\n * @returns {Object} An object containing the Ethereum account and public key.\r\n */\r\nexport function gunToEthAccount(gunPrivateKey) {\r\n // Function to convert base64url to hex\r\n const base64UrlToHex = (base64url) => {\r\n const padding = \"=\".repeat((4 - (base64url.length % 4)) % 4);\r\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\") + padding;\r\n const binary = atob(base64);\r\n return Array.from(binary, (char) =>\r\n char.charCodeAt(0).toString(16).padStart(2, \"0\")\r\n ).join(\"\");\r\n };\r\n\r\n // Convert Gun private key to hex format\r\n const hexPrivateKey = \"0x\" + base64UrlToHex(gunPrivateKey);\r\n\r\n // Create an Ethereum wallet from the private key\r\n const wallet = new ethers.Wallet(hexPrivateKey);\r\n\r\n // Get the public address (public key)\r\n const publicKey = wallet.address;\r\n\r\n return {\r\n account: wallet,\r\n publicKey: publicKey,\r\n privateKey: hexPrivateKey,\r\n };\r\n}\r\n\r\n/**\r\n * Gets an Ethereum signer based on current configuration\r\n * @returns {Promise<ethers.Signer>} The configured signer\r\n * @throws {Error} If no valid provider is found\r\n */\r\nexport const getSigner = async () => {\r\n if (rpcUrl && privateKey) {\r\n // Standalone mode with local provider\r\n const provider = new ethers.JsonRpcProvider(rpcUrl, {\r\n chainId: LOCAL_CONFIG.CHAIN_ID,\r\n name: \"localhost\"\r\n });\r\n return new ethers.Wallet(privateKey, provider);\r\n } else if (\r\n typeof window !== \"undefined\" &&\r\n typeof window.ethereum !== \"undefined\"\r\n ) {\r\n // Browser mode\r\n await window.ethereum.request({ method: \"eth_requestAccounts\" });\r\n const provider = new ethers.BrowserProvider(window.ethereum);\r\n return provider.getSigner();\r\n } else {\r\n throw new Error(\"No valid Ethereum provider found\");\r\n }\r\n};\r\n\r\n/**\r\n * Utility function to generate stealth address\r\n * @param {string} sharedSecret - The shared secret\r\n * @param {string} spendingPublicKey - The spending public key\r\n * @returns {Object} The stealth address and private key\r\n */\r\nexport function deriveStealthAddress(sharedSecret, spendingPublicKey) {\r\n try {\r\n // Convert shared secret to bytes\r\n const sharedSecretBytes = Buffer.from(sharedSecret, 'base64');\r\n \r\n // Generate stealth private key using shared secret and spending public key\r\n const stealthPrivateKey = ethers.keccak256(\r\n ethers.concat([\r\n sharedSecretBytes,\r\n ethers.getBytes(spendingPublicKey)\r\n ])\r\n );\r\n \r\n // Create stealth wallet\r\n const stealthWallet = new ethers.Wallet(stealthPrivateKey);\r\n\r\n console.log(\"Debug deriveStealthAddress:\", {\r\n sharedSecretHex: ethers.hexlify(sharedSecretBytes),\r\n spendingPublicKey,\r\n stealthPrivateKey,\r\n stealthAddress: stealthWallet.address\r\n });\r\n\r\n return {\r\n stealthPrivateKey,\r\n stealthAddress: stealthWallet.address,\r\n wallet: stealthWallet\r\n };\r\n } catch (error) {\r\n console.error(\"Error in deriveStealthAddress:\", error);\r\n throw error;\r\n }\r\n}\r\n\r\n// =============================================\r\n// BASIC GUN-ETH CHAIN METHODS\r\n// =============================================\r\n\r\n// Set the message to sign\r\nGun.chain.MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;\r\n\r\n/**\r\n * Sets standalone configuration for Gun.\r\n * @param {string} newRpcUrl - The new RPC URL.\r\n * @param {string} newPrivateKey - The new private key.\r\n * @returns {Gun} The Gun instance for chaining.\r\n */\r\nGun.chain.setSigner = function (newRpcUrl, newPrivateKey) {\r\n rpcUrl = newRpcUrl;\r\n privateKey = newPrivateKey;\r\n console.log(\"Standalone configuration set\");\r\n return this;\r\n};\r\n\r\nGun.chain.getSigner = getSigner();\r\n\r\n/**\r\n * Verifies an Ethereum signature.\r\n * @param {string} message - The original message that was signed.\r\n * @param {string} signature - The signature to verify.\r\n * @returns {Promise<string|null>} The recovered address or null if verification fails.\r\n */\r\nGun.chain.verifySignature = async function (message, signature) {\r\n try {\r\n const recoveredAddress = ethers.verifyMessage(message, signature);\r\n return recoveredAddress;\r\n } catch (error) {\r\n console.error(\"Error verifying signature:\", error);\r\n return null;\r\n }\r\n};\r\n\r\n/**\r\n * Generates a password from a signature.\r\n * @param {string} signature - The signature to derive the password from.\r\n * @returns {string|null} The generated password or null if generation fails.\r\n */\r\nGun.chain.generatePassword = function (signature) {\r\n return generatePassword(signature);\r\n};\r\n\r\n/**\r\n * Creates an Ethereum signature for a given message.\r\n * @param {string} message - The message to sign.\r\n * @returns {Promise<string|null>} The signature or null if signing fails.\r\n */\r\nGun.chain.createSignature = async function (message) {\r\n try {\r\n // Check if message matches MESSAGE_TO_SIGN\r\n if (message !== MESSAGE_TO_SIGN) {\r\n throw new Error(\"Invalid message, valid message is: \" + MESSAGE_TO_SIGN);\r\n }\r\n const signer = await getSigner();\r\n const signature = await signer.signMessage(message);\r\n console.log(\"Signature created:\", signature);\r\n return signature;\r\n } catch (error) {\r\n console.error(\"Error creating signature:\", error);\r\n return null;\r\n }\r\n};\r\n\r\n// =============================================\r\n// KEY PAIR MANAGEMENT\r\n// =============================================\r\n/**\r\n * Creates and stores an encrypted key pair for a given address.\r\n * @param {string} address - The Ethereum address to associate with the key pair.\r\n * @param {string} signature - The signature to use for encryption.\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.createAndStoreEncryptedPair = async function (address, signature) {\r\n try {\r\n const gun = this;\r\n const pair = await SEA.pair();\r\n const v_pair = await SEA.pair();\r\n const s_pair = await SEA.pair();\r\n const password = generatePassword(signature);\r\n\r\n // Save original SEA pairs\r\n const encryptedPair = await SEA.encrypt(JSON.stringify(pair), password);\r\n const encryptedV_pair = await SEA.encrypt(JSON.stringify(v_pair), password);\r\n const encryptedS_pair = await SEA.encrypt(JSON.stringify(s_pair), password);\r\n\r\n // Convert only to get Ethereum addresses\r\n const viewingAccount = gunToEthAccount(v_pair.priv);\r\n const spendingAccount = gunToEthAccount(s_pair.priv);\r\n\r\n gun.get(\"gun-eth\").get(\"users\").get(address).put({\r\n pair: encryptedPair,\r\n v_pair: encryptedV_pair,\r\n s_pair: encryptedS_pair,\r\n publicKeys: {\r\n viewingPublicKey: v_pair.epub, // Use SEA encryption public key\r\n viewingPublicKey: v_pair.epub, // Use SEA encryption public key\r\n spendingPublicKey: spendingAccount.publicKey, // Use Ethereum address\r\n ethViewingAddress: viewingAccount.publicKey // Also save Ethereum address\r\n }\r\n });\r\n\r\n console.log(\"Encrypted pairs and public keys stored for:\", address);\r\n } catch (error) {\r\n console.error(\"Error creating and storing encrypted pair:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Retrieves and decrypts a stored key pair for a given address.\r\n * @param {string} address - The Ethereum address associated with the key pair.\r\n * @param {string} signature - The signature to use for decryption.\r\n * @returns {Promise<Object|null>} The decrypted key pair or null if retrieval fails.\r\n */\r\nGun.chain.getAndDecryptPair = async function (address, signature) {\r\n try {\r\n const gun = this;\r\n const encryptedData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(address)\r\n .get(\"pair\")\r\n .then();\r\n if (!encryptedData) {\r\n throw new Error(\"No encrypted data found for this address\");\r\n }\r\n const password = generatePassword(signature);\r\n const decryptedPair = await SEA.decrypt(encryptedData, password);\r\n console.log(decryptedPair);\r\n return decryptedPair;\r\n } catch (error) {\r\n console.error(\"Error retrieving and decrypting pair:\", error);\r\n return null;\r\n }\r\n};\r\n\r\n// =============================================\r\n// PROOF OF INTEGRITY\r\n// =============================================\r\n/**\r\n * Proof of Integrity\r\n * @param {string} chain - The blockchain to use (e.g., \"optimismSepolia\").\r\n * @param {string} nodeId - The ID of the node to verify or write.\r\n * @param {Object} data - The data to write (if writing).\r\n * @param {Function} callback - Callback function to handle the result.\r\n * @returns {Gun} The Gun instance for chaining.\r\n */\r\nGun.chain.proof = function (chain, nodeId, data, callback) {\r\n console.log(\"Proof plugin called with:\", { chain, nodeId, data });\r\n\r\n if (typeof callback !== \"function\") {\r\n console.error(\"Callback must be a function\");\r\n return this;\r\n }\r\n\r\n try {\r\n // Usa getAddressesForChain per ottenere la configurazione corretta\r\n const chainConfig = getAddressesForChain(chain);\r\n console.log(`Using ${chain} configuration:`, chainConfig);\r\n\r\n // Usa gli indirizzi dalla configurazione\r\n const contract = new ethers.Contract(\r\n chainConfig.PROOF_OF_INTEGRITY_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n\r\n // Funzione per verificare on-chain\r\n const verifyOnChain = async (nodeId, contentHash) => {\r\n console.log(\"Verifying on chain:\", { nodeId, contentHash });\r\n const signer = await getSigner();\r\n const contract = new ethers.Contract(\r\n PROOF_CONTRACT_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n const [isValid, timestamp, updater] = await contract.verifyData(\r\n ethers.toUtf8Bytes(nodeId),\r\n contentHash\r\n );\r\n console.log(\"Verification result:\", { isValid, timestamp, updater });\r\n return { isValid, timestamp, updater };\r\n };\r\n\r\n // Funzione per scrivere on-chain\r\n const writeOnChain = async (nodeId, contentHash) => {\r\n console.log(\"Writing on chain:\", { nodeId, contentHash });\r\n const signer = await getSigner();\r\n const contract = new ethers.Contract(\r\n PROOF_CONTRACT_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n const tx = await contract.updateData(\r\n ethers.toUtf8Bytes(nodeId),\r\n contentHash\r\n );\r\n console.log(\"Transaction sent:\", tx.hash);\r\n const receipt = await tx.wait();\r\n console.log(\"Transaction confirmed:\", receipt);\r\n return tx;\r\n };\r\n\r\n // Funzione per ottenere l'ultimo record\r\n const getLatestRecord = async (nodeId) => {\r\n const signer = await getSigner();\r\n const contract = new ethers.Contract(\r\n PROOF_CONTRACT_ADDRESS,\r\n PROOF_OF_INTEGRITY_ABI,\r\n signer\r\n );\r\n const [contentHash, timestamp, updater] = await contract.getLatestRecord(\r\n ethers.toUtf8Bytes(nodeId)\r\n );\r\n console.log(\"Latest record from blockchain:\", {\r\n nodeId,\r\n contentHash,\r\n timestamp,\r\n updater,\r\n });\r\n return { contentHash, timestamp, updater };\r\n };\r\n\r\n \r\n if (nodeId && !data) {\r\n // Case 1: User passes only node\r\n gun.get(nodeId).once(async (existingData) => {\r\n if (!existingData) {\r\n if (callback) callback({ err: \"Node not found in GunDB\" });\r\n return;\r\n }\r\n\r\n console.log(\"existingData\", existingData);\r\n\r\n // Use stored contentHash instead of recalculating\r\n const contentHash = existingData._contentHash;\r\n console.log(\"contentHash\", contentHash);\r\n\r\n if (!contentHash) {\r\n if (callback) callback({ err: \"No content hash found for this node\" });\r\n return;\r\n }\r\n\r\n try {\r\n const { isValid, timestamp, updater } = await verifyOnChain(\r\n nodeId,\r\n contentHash\r\n );\r\n const latestRecord = await getLatestRecord(nodeId);\r\n\r\n if (isValid) {\r\n if (callback)\r\n callback({\r\n ok: true,\r\n message: \"Data verified on blockchain\",\r\n timestamp,\r\n updater,\r\n latestRecord,\r\n });\r\n } else {\r\n if (callback)\r\n callback({\r\n ok: false,\r\n message: \"Data not verified on blockchain\",\r\n latestRecord,\r\n });\r\n }\r\n } catch (error) {\r\n if (callback) callback({ err: error.message });\r\n }\r\n });\r\n } else if (data && !nodeId) {\r\n // Case 2: User passes only text (data)\r\n const newNodeId = generateRandomId();\r\n const dataString = JSON.stringify(data);\r\n const contentHash = ethers.keccak256(ethers.toUtf8Bytes(dataString));\r\n\r\n gun\r\n .get(newNodeId)\r\n .put({ ...data, _contentHash: contentHash }, async (ack) => {\r\n console.log(\"ack\", ack);\r\n if (ack.err) {\r\n if (callback) callback({ err: \"Error saving data to GunDB\" });\r\n return;\r\n }\r\n\r\n try {\r\n const tx = await writeOnChain(newNodeId, contentHash);\r\n if (callback)\r\n callback({\r\n ok: true,\r\n message: \"Data written to GunDB and blockchain\",\r\n nodeId: newNodeId,\r\n txHash: tx.hash,\r\n });\r\n } catch (error) {\r\n if (callback) callback({ err: error.message });\r\n }\r\n });\r\n } else {\r\n if (callback)\r\n callback({\r\n err: \"Invalid input. Provide either nodeId or data, not both.\",\r\n });\r\n }\r\n\r\n return gun;\r\n } catch (error) {\r\n callback({ err: error.message });\r\n return this;\r\n }\r\n};\r\n\r\n// =============================================\r\n// STEALTH ADDRESS CORE FUNCTIONS\r\n// =============================================\r\n/**\r\n * Converts a Gun private key to an Ethereum account.\r\n * @param {string} gunPrivateKey - The Gun private key in base64url format.\r\n * @returns {Object} An object containing the Ethereum account and public key.\r\n */\r\nGun.chain.gunToEthAccount = function (gunPrivateKey) {\r\n return gunToEthAccount(gunPrivateKey);\r\n};\r\n\r\n/**\r\n * Generate a stealth key and related key pairs\r\n * @param {string} recipientAddress - The recipient's Ethereum address\r\n * @param {string} signature - The sender's signature to access their keys\r\n * @returns {Promise<Object>} Object containing stealth addresses and keys\r\n */\r\nGun.chain.generateStealthAddress = async function (recipientAddress, signature) {\r\n try {\r\n const gun = this;\r\n \r\n // Get recipient's public keys\r\n const recipientData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(recipientAddress)\r\n .get(\"publicKeys\")\r\n .then();\r\n\r\n if (!recipientData || !recipientData.viewingPublicKey || !recipientData.spendingPublicKey) {\r\n throw new Error(\"Recipient's public keys not found\");\r\n }\r\n\r\n // Get sender's keys\r\n const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n const password = generatePassword(signature);\r\n \r\n const senderData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(senderAddress)\r\n .then();\r\n\r\n if (!senderData || !senderData.s_pair) {\r\n throw new Error(\"Sender's keys not found\");\r\n }\r\n\r\n // Decrypt sender's spending pair\r\n let spendingKeyPair;\r\n try {\r\n const decryptedData = await SEA.decrypt(senderData.s_pair, password);\r\n spendingKeyPair = typeof decryptedData === 'string' ? \r\n JSON.parse(decryptedData) : \r\n decryptedData;\r\n } catch (error) {\r\n console.error(\"Error decrypting spending pair:\", error);\r\n throw new Error(\"Unable to decrypt spending pair\");\r\n }\r\n\r\n // Generate shared secret using SEA ECDH with encryption public key\r\n const sharedSecret = await SEA.secret(recipientData.viewingPublicKey, spendingKeyPair);\r\n\r\n if (!sharedSecret) {\r\n throw new Error(\"Unable to generate shared secret\");\r\n }\r\n\r\n console.log(\"Generate shared secret:\", sharedSecret);\r\n\r\n const { stealthAddress } = deriveStealthAddress(\r\n sharedSecret,\r\n recipientData.spendingPublicKey\r\n );\r\n\r\n return {\r\n stealthAddress,\r\n senderPublicKey: spendingKeyPair.epub, // Use encryption public key\r\n spendingPublicKey: recipientData.spendingPublicKey\r\n };\r\n\r\n } catch (error) {\r\n console.error(\"Error generating stealth address:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Publish public keys needed to receive stealth payments\r\n * @param {string} signature - The signature to authenticate the user\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.publishStealthKeys = async function (signature) {\r\n try {\r\n const gun = this;\r\n const address = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n const password = generatePassword(signature);\r\n\r\n // Get encrypted key pairs\r\n const encryptedData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(address)\r\n .then();\r\n\r\n if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {\r\n throw new Error(\"Keys not found\");\r\n }\r\n\r\n // Decrypt viewing and spending pairs\r\n const viewingKeyPair = JSON.parse(\r\n await SEA.decrypt(encryptedData.v_pair, password)\r\n );\r\n const spendingKeyPair = JSON.parse(\r\n await SEA.decrypt(encryptedData.s_pair, password)\r\n );\r\n\r\n const viewingAccount = gunToEthAccount(viewingKeyPair.priv);\r\n const spendingAccount = gunToEthAccount(spendingKeyPair.priv);\r\n\r\n // Publish only public keys\r\n gun.get(\"gun-eth\").get(\"users\").get(address).get(\"publicKeys\").put({\r\n viewingPublicKey: viewingAccount.publicKey,\r\n spendingPublicKey: spendingAccount.publicKey,\r\n });\r\n\r\n console.log(\"Stealth public keys published successfully\");\r\n } catch (error) {\r\n console.error(\"Error publishing stealth keys:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n// =============================================\r\n// STEALTH PAYMENT FUNCTIONS\r\n// =============================================\r\n/**\r\n * Recover funds from a stealth address\r\n * @param {string} stealthAddress - The stealth address to recover funds from\r\n * @param {string} senderPublicKey - The sender's public key used to generate the address\r\n * @param {string} signature - The signature to decrypt private keys\r\n * @returns {Promise<Object>} Object containing wallet to access funds\r\n */\r\nGun.chain.recoverStealthFunds = async function (\r\n stealthAddress,\r\n senderPublicKey,\r\n signature,\r\n spendingPublicKey\r\n) {\r\n try {\r\n const gun = this;\r\n const password = generatePassword(signature);\r\n\r\n // Get own key pairs\r\n const myAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n const encryptedData = await gun\r\n .get(\"gun-eth\")\r\n .get(\"users\")\r\n .get(myAddress)\r\n .then();\r\n\r\n if (!encryptedData || !encryptedData.v_pair || !encryptedData.s_pair) {\r\n throw new Error(\"Keys not found\");\r\n }\r\n\r\n // Decrypt viewing and spending pairs\r\n let viewingKeyPair;\r\n try {\r\n const decryptedViewingData = await SEA.decrypt(encryptedData.v_pair, password);\r\n viewingKeyPair = typeof decryptedViewingData === 'string' ? \r\n JSON.parse(decryptedViewingData) : \r\n decryptedViewingData;\r\n } catch (error) {\r\n console.error(\"Error decrypting keys:\", error);\r\n throw new Error(\"Unable to decrypt keys\");\r\n }\r\n\r\n // Generate shared secret using SEA ECDH\r\n const sharedSecret = await SEA.secret(senderPublicKey, viewingKeyPair);\r\n\r\n if (!sharedSecret) {\r\n throw new Error(\"Unable to generate shared secret\");\r\n }\r\n\r\n console.log(\"Recover shared secret:\", sharedSecret);\r\n\r\n const { wallet, stealthAddress: recoveredAddress } = deriveStealthAddress(\r\n sharedSecret,\r\n spendingPublicKey\r\n );\r\n\r\n // Verify address matches\r\n if (recoveredAddress.toLowerCase() !== stealthAddress.toLowerCase()) {\r\n console.error(\"Mismatch:\", {\r\n recovered: recoveredAddress,\r\n expected: stealthAddress,\r\n sharedSecret\r\n });\r\n throw new Error(\"Recovered stealth address does not match\");\r\n }\r\n\r\n return {\r\n wallet,\r\n address: recoveredAddress,\r\n };\r\n } catch (error) {\r\n console.error(\"Error recovering stealth funds:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Announce a stealth payment\r\n * @param {string} stealthAddress - The generated stealth address\r\n * @param {string} senderPublicKey - The sender's public key\r\n * @param {string} spendingPublicKey - The spending public key\r\n * @param {string} signature - The sender's signature\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.announceStealthPayment = async function (\r\n stealthAddress,\r\n senderPublicKey,\r\n spendingPublicKey,\r\n signature,\r\n options = { onChain: false, chain: 'optimismSepolia' }\r\n) {\r\n try {\r\n const gun = this;\r\n const senderAddress = await this.verifySignature(MESSAGE_TO_SIGN, signature);\r\n\r\n if (options.onChain) {\r\n const signer = await getSigner();\r\n const chainConfig = getAddressesForChain(options.chain);\r\n \r\n const contract = new ethers.Contract(\r\n chainConfig.STEALTH_ANNOUNCER_ADDRESS,\r\n STEALTH_ANNOUNCER_ABI,\r\n signer\r\n );\r\n\r\n // Get dev fee from contract\r\n const devFee = await contract.devFee();\r\n console.log(\"Dev fee:\", devFee.toString());\r\n\r\n // Call contract\r\n const tx = await contract.announcePayment(\r\n senderPublicKey,\r\n spendingPublicKey,\r\n stealthAddress,\r\n { value: devFee }\r\n );\r\n \r\n console.log(\"Transaction sent:\", tx.hash);\r\n const receipt = await tx.wait();\r\n console.log(\"Transaction confirmed:\", receipt.hash);\r\n \r\n console.log(\"Stealth payment announced on-chain (dev fee paid)\");\r\n } else {\r\n // Off-chain announcement (GunDB)\r\n gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .set({\r\n stealthAddress,\r\n senderAddress,\r\n senderPublicKey,\r\n spendingPublicKey,\r\n timestamp: Date.now(),\r\n });\r\n console.log(\"Stealth payment announced off-chain\");\r\n }\r\n } catch (error) {\r\n console.error(\"Error announcing stealth payment:\", error);\r\n console.error(\"Error details:\", error.stack);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Get all stealth payments for an address\r\n * @param {string} signature - The signature to authenticate the user\r\n * @returns {Promise<Array>} List of stealth payments\r\n */\r\nGun.chain.getStealthPayments = async function (signature, options = { source: 'both' }) {\r\n try {\r\n const payments = [];\r\n\r\n if (options.source === 'onChain' || options.source === 'both') {\r\n // Get on-chain payments\r\n const signer = await getSigner();\r\n const contractAddress = process.env.NODE_ENV === 'development' \r\n ? LOCAL_CONFIG.STEALTH_ANNOUNCER_ADDRESS \r\n : STEALTH_ANNOUNCER_ADDRESS;\r\n\r\n const contract = new ethers.Contract(\r\n contractAddress,\r\n STEALTH_ANNOUNCER_ABI,\r\n signer\r\n );\r\n \r\n try {\r\n // Get total number of announcements\r\n const totalAnnouncements = await contract.getAnnouncementsCount();\r\n const totalCount = Number(totalAnnouncements.toString());\r\n console.log(\"Total on-chain announcements:\", totalCount);\r\n \r\n if (totalCount > 0) {\r\n // Get announcements in batches of 100\r\n const batchSize = 100;\r\n const lastIndex = totalCount - 1;\r\n \r\n for(let i = 0; i <= lastIndex; i += batchSize) {\r\n const toIndex = Math.min(i + batchSize - 1, lastIndex);\r\n const batch = await contract.getAnnouncementsInRange(i, toIndex);\r\n \r\n // For each announcement, try to decrypt\r\n for(const announcement of batch) {\r\n try {\r\n // Verify announcement is valid\r\n if (!announcement || !announcement.stealthAddress || \r\n !announcement.senderPublicKey || !announcement.spendingPublicKey) {\r\n console.log(\"Invalid announcement:\", announcement);\r\n continue;\r\n }\r\n\r\n // Try to recover funds to verify if announcement is for us\r\n const recoveredWallet = await this.recoverStealthFunds(\r\n announcement.stealthAddress,\r\n announcement.senderPublicKey,\r\n signature,\r\n announcement.spendingPublicKey\r\n );\r\n \r\n // If no errors thrown, announcement is for us\r\n payments.push({\r\n stealthAddress: announcement.stealthAddress,\r\n senderPublicKey: announcement.senderPublicKey,\r\n spendingPublicKey: announcement.spendingPublicKey,\r\n timestamp: Number(announcement.timestamp),\r\n source: 'onChain',\r\n wallet: recoveredWallet\r\n });\r\n\r\n } catch (e) {\r\n // Not for us, continue\r\n console.log(`Announcement not for us: ${announcement.stealthAddress}`);\r\n continue;\r\n }\r\n }\r\n }\r\n }\r\n } catch (error) {\r\n console.error(\"Error retrieving on-chain announcements:\", error);\r\n }\r\n }\r\n\r\n if (options.source === 'offChain' || options.source === 'both') {\r\n // Get off-chain payments\r\n const gun = this;\r\n const offChainPayments = await new Promise((resolve) => {\r\n const p = [];\r\n gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .get(recipientAddress)\r\n .map()\r\n .once((payment, id) => {\r\n if (payment?.stealthAddress) {\r\n p.push({ ...payment, id, source: 'offChain' });\r\n }\r\n });\r\n setTimeout(() => resolve(p), 2000);\r\n });\r\n \r\n payments.push(...offChainPayments);\r\n }\r\n\r\n console.log(`Found ${payments.length} stealth payments`);\r\n return payments;\r\n } catch (error) {\r\n console.error(\"Error retrieving stealth payments:\", error);\r\n throw error;\r\n }\r\n};\r\n\r\n/**\r\n * Clean up old stealth payments\r\n * @param {string} recipientAddress - The recipient's address\r\n * @returns {Promise<void>}\r\n */\r\nGun.chain.cleanStealthPayments = async function(recipientAddress) {\r\n try {\r\n const gun = this;\r\n const payments = await gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .get(recipientAddress)\r\n .map()\r\n .once()\r\n .then();\r\n\r\n // Remove empty or invalid nodes\r\n if (payments) {\r\n Object.keys(payments).forEach(async (key) => {\r\n const payment = payments[key];\r\n if (!payment || !payment.stealthAddress || !payment.senderPublicKey || !payment.spendingPublicKey) {\r\n await gun\r\n .get(\"gun-eth\")\r\n .get(\"stealth-payments\")\r\n .get(recipientAddress)\r\n .get(key)\r\n .put(null);\r\n }\r\n });\r\n }\r\n } catch (error) {\r\n console.error(\"Error cleaning stealth payments:\", error);\r\n }\r\n};\r\n\r\n// =============================================\r\n// EXPORTS\r\n// =============================================\r\n\r\n// Crea una classe GunEth che contiene tutti i metodi e le utility\r\nexport class GunEth {\r\n // Static utility methods\r\n static generateRandomId = generateRandomId;\r\n static generatePassword = generatePassword;\r\n static gunToEthAccount = gunToEthAccount;\r\n static getSigner = getSigner;\r\n static deriveStealthAddress = deriveStealthAddress;\r\n \r\n // Chain methods\r\n static chainMethods = {\r\n setSigner: Gun.chain.setSigner,\r\n getSigner: Gun.chain.getSigner,\r\n verifySignature: Gun.chain.verifySignature,\r\n generatePassword: Gun.chain.generatePassword,\r\n createSignature: Gun.chain.createSignature,\r\n createAndStoreEncryptedPair: Gun.chain.createAndStoreEncryptedPair,\r\n getAndDecryptPair: Gun.chain.getAndDecryptPair,\r\n proof: Gun.chain.proof,\r\n gunToEthAccount: Gun.chain.gunToEthAccount,\r\n generateStealthAddress: Gun.chain.generateStealthAddress,\r\n publishStealthKeys: Gun.chain.publishStealthKeys,\r\n recoverStealthFunds: Gun.chain.recoverStealthFunds,\r\n announceStealthPayment: Gun.chain.announceStealthPayment,\r\n getStealthPayments: Gun.chain.getStealthPayments,\r\n cleanStealthPayments: Gun.chain.cleanStealthPayments\r\n };\r\n\r\n // Constants\r\n static MESSAGE_TO_SIGN = MESSAGE_TO_SIGN;\r\n static PROOF_CONTRACT_ADDRESS = PROOF_CONTRACT_ADDRESS;\r\n static LOCAL_CONFIG = LOCAL_CONFIG;\r\n}\r\n\r\n// Esporta Gun come default\r\nexport default Gun;\r\n"],"names":["version","checkType","value","type","name","types","split","map","t","trim","i","length","error","Error","code","argument","async","resolveProperties","keys","Object","Promise","all","k","resolve","reduce","accum","v","index","defineProperties","target","values","key","defineProperty","enumerable","writable","stringify","Array","isArray","join","Uint8Array","HEX","result","toJSON","toString","BigInt","JSON","sort","isError","isCallException","makeError","message","info","shortMessage","details","push","TypeError","RangeError","assign","assert","check","assertArgument","assertArgumentCount","count","expectedCount","_normalizeForms","form","normalize","String","fromCharCode","assertNormalize","indexOf","operation","assertPrivate","givenGuard","guard","className","method","_getBytes","copy","match","offset","parseInt","substring","getBytes","getBytesCopy","isHexString","isBytesLike","HexCharacters","hexlify","data","bytes","concat","datas","d","dataLength","dataSlice","start","end","buffer","slice","zeroPad","left","fill","set","zeroPadValue","BN_0","BN_1","maxValue","toTwos","_value","_width","getBigInt","width","getNumber","limit","fault","mask","_bits","getUint","bits","Number","isInteger","e","Nibbles","toBigInt","toBeHex","toBeArray","hex","toQuantity","startsWith","Alphabet","Lookup","getAlpha","letter","BN_58","encodeBase58","EventPayload","filter","emitter","listener","constructor","this","removeListener","off","ignoreFunc","reason","output","badCodepoint","o","Utf8ErrorFuncs","freeze","ignore","replace","toUtf8Bytes","str","c","charCodeAt","c2","pair","toUtf8String","onError","codePoints","_bytes","extraLength","overlongMask","res","j","nextChar","getUtf8CodePoints","codePoint","defaultGetUrlFunc","createGetUrl","reData","RegExp","reIpfs","locked","dataGatewayFunc","url","signal","FetchResponse","decodeBase64","FetchRequest","getIpfsGatewayFunc","baseUrl","Gateways","ipfs","fetchSignals","WeakMap","FetchCancelSignal","listeners","cancelled","request","setTimeout","addListener","checkSignal","allowInsecure","gzip","headers","timeout","body","bodyType","creds","preflight","process","retry","throttle","getUrlFunc","undefined","hasBody","toUpperCase","encodeBase64","allowGzip","getHeader","toLowerCase","setHeader","clearHeaders","Symbol","iterator","next","done","credentials","setCredentials","username","password","allowInsecureAuthentication","preflightFunc","processFunc","retryFunc","slotInterval","maxAttempts","setThrottleParams","params","send","attempt","expires","delay","_request","_response","makeServerError","getTime","wait","req","clone","scheme","response","assertOk","resp","statusCode","statusMessage","location","redirect","retryAfter","Math","trunc","random","pow","stall","cancel","get","current","lockConfig","getGateway","registerGateway","func","registerGetUrl","getUrl","createGetUrlFunc","options","createDataGateway","createIpfsGatewayFunc","bodyText","bodyJson","parse","throwThrottleError","ok","requestUrl","responseBody","responseStatus","Date","hexlifyByte","unarrayifyInteger","_decodeChildren","childOffset","decoded","_decode","consumed","checkOffset","lengthLength","decodeRlp","_data","arrayifyInteger","unshift","_encode","object","payload","forEach","child","prototype","call","nibbles","encodeRlp","uuidV4","randomBytes","WordSize","Padding","passProperties","_guard","resultNames","getNames","setNames","names","throwError","wrapped","toObject","items","deep","item","Result","getValue","args","wrap","super","nameCounts","Map","proxy","Proxy","prop","receiver","Reflect","Function","apply","toArray","_names","callback","thisArg","fromItems","Coder","localName","dynamic","_throwError","Writer","writeData","appendWriter","writer","writeBytes","paddingOffset","writeValue","writeUpdatableValue","Reader","allowLoose","bytesRead","parent","maxInflation","incrementBytesRead","peekBytes","loose","alignedLength","ceil","subReader","reader","readBytes","readValue","readIndex","_computeHmac","algorithm","createHmac","update","digest","__computeHmac","computeHmac","_key","_","lock","register","_keccak256","keccak_256","__keccak256","keccak256","_ripemd160","noble_ripemd160","__ripemd160","ripemd160","_pbkdf2","salt","iterations","keylen","algo","pbkdf2Sync","__pbkdf2","pbkdf2","_password","_salt","_randomBytes","crypto_random","__randomBytes","lockedSync","lockedAsync","_scryptAsync","passwd","N","r","p","dkLen","onProgress","_nobleAsync","scryptAsync","_scryptSync","_nobleSync","scrypt","__scryptAsync","__scryptSync","_passwd","progress","H","scryptSync","_sha256","createHash","__sha256","locked256","sha256","ZeroAddress","ZeroHash","BN_2","BN_27","BN_28","BN_35","toUint256","Signature","s","networkV","legacyChainId","getChainId","yParity","yParityAndS","compactSerialized","serialized","for","_type","bv","getChainIdV","chainId","getNormalizedV","from","sig","assertError","_r","_v","SigningKey","privateKey","publicKey","computePublicKey","compressedPublicKey","sign","secp256k1","lowS","recovery","computeSharedSecret","other","pubKey","getSharedSecret","compressed","getPublicKey","pub","ProjectivePoint","fromHex","toRawBytes","recoverPublicKey","signature","secpSig","fromCompact","addRecoveryBit","toHex","addPoints","p0","p1","pub0","pub1","add","BN_36","getChecksumAddress","address","chars","expanded","hashed","ibanLookup","Base36","getAddress","block","checksum","ibanChecksum","fromBase36","isAddressable","checkAddress","promise","resolveAddress","resolver","resolveName","_gaurd","n","signed","Typed","b","size","_typedSymbol","gaurd","format","defaultValue","minValue","isBigInt","isData","isString","tupleName","arrayLength","uint8","uint16","uint24","uint32","uint40","uint48","uint56","uint64","uint72","uint80","uint88","uint96","uint104","uint112","uint120","uint128","uint136","uint144","uint152","uint160","uint168","uint176","uint184","uint192","uint200","uint208","uint216","uint224","uint232","uint240","uint248","uint256","uint","int8","int16","int24","int32","int40","int48","int56","int64","int72","int80","int88","int96","int104","int112","int120","int128","int136","int144","int152","int160","int168","int176","int184","int192","int200","int208","int216","int224","int232","int240","int248","int256","int","bytes1","bytes2","bytes3","bytes4","bytes5","bytes6","bytes7","bytes8","bytes9","bytes10","bytes11","bytes12","bytes13","bytes14","bytes15","bytes16","bytes17","bytes18","bytes19","bytes20","bytes21","bytes22","bytes23","bytes24","bytes25","bytes26","bytes27","bytes28","bytes29","bytes30","bytes31","bytes32","bool","string","array","tuple","overrides","isTyped","dereference","AddressCoder","encode","decode","AnonymousCoder","coder","pack","coders","arrayValues","unique","staticWriter","dynamicWriter","updateFuncs","dynamicOffset","updateFunc","baseOffset","unpack","baseReader","offsetReader","baseType","ArrayCoder","defaultChild","BooleanCoder","DynamicBytesCoder","BytesCoder","FixedBytesCoder","Empty","NullCoder","BN_MAX_UINT256","NumberCoder","maxUintValue","bounds","fromTwos","StringCoder","TupleCoder","uniqueNames","id","Zeros","checkComponent","comp","ensNameSplit","ens_normalize","ensNormalize","comps","last","namehash","pop","dnsEncode","_maxLength","accessSetify","addr","storageKeys","storageKey","accessListify","a","localeCompare","computeAddress","pubkey","recoverAddress","BN_MAX_UINT","BLOB_SIZE","getVersionedHash","hash","versioned","handleAddress","handleAccessList","param","handleNumber","handleUint","formatNumber","formatAccessList","formatHashes","_parseEipSignature","tx","fields","Transaction","to","nonce","gasLimit","gasPrice","maxPriorityFeePerGas","maxFeePerGas","accessList","maxFeePerBlobGas","blobVersionedHashes","kzg","blobs","typeName","_blobs","versionedHashes","blob","padded","commit","blobToKzgCommitment","proof","computeBlobKzgProof","commitment","getSerialized","unsignedHash","unsignedSerialized","fromPublicKey","isSigned","sidecar","inferType","legacy","_serializeLegacy","_serializeEip2930","_serializeEip1559","_serializeEip4844","inferTypes","hasGasPrice","hasFee","hasAccessList","hasBlob","isLegacy","isBerlin","isLondon","isCancun","_parseLegacy","_parseEip2930","_parseEip1559","fBlobs","fCommits","fProofs","_parseEip4844","hashMessage","padding","BN__1","hexTrue","hexFalse","domainFieldTypes","verifyingContract","domainFieldNames","checkString","domainChecks","isSafeInteger","getBaseEncoder","boundsUpper","boundsLower","padOffset","hexPadRight","encodeType","splitArray","base","prefix","TypedDataEncoder","primaryType","fullTypes","encoderCache","_types","links","parents","subtypes","Set","field","has","primaryTypes","checkCircular","found","subtype","delete","st","getEncoder","encoder","subEncoder","encodedType","encodeData","hashStruct","_visit","visit","getPrimaryType","hashDomain","domain","domainFields","EIP712Domain","resolveNames","ensCache","getPayload","domainValues","domainTypes","typesWithDomain","setify","KwVisibDeploy","_kwVisib","KwVisib","_kwTypes","KwTypes","_kwModifiers","KwModifiers","Keywords","SimpleTokens","regexWhitespacePrefix","regexNumberPrefix","regexIdPrefix","regexId","regexType","TokenString","tokens","reset","subTokenString","linkBack","linkNext","popKeyword","allowed","top","peek","text","popType","popParen","popParams","link","peekKeyword","peekType","token","lex","brackets","commas","cur","depth","suffix","allowSingle","included","consumeName","keyword","consumeKeywords","keywords","consumeMutability","modifiers","consumeParams","allowIndexed","ParamType","consumeGas","consumeEoi","regexArrayType","verifyBasicType","internal","ParamTypeInternal","ErrorFragmentInternal","EventFragmentInternal","ConstructorFragmentInternal","FallbackFragmentInternal","FunctionFragmentInternal","StructFragmentInternal","indexed","components","arrayChildren","isTuple","isIndexable","walk","_this","walkAsync","promises","setValue","childType","then","obj","isParamType","bracket","arrayMatch","Fragment","inputs","ConstructorFragment","ErrorFragment","EventFragment","FallbackFragment","FunctionFragment","StructFragment","isConstructor","isFragment","isEvent","isFunction","isStruct","NamedFragment","joinParams","selector","input","anonymous","topicHash","getTopicHash","payable","gas","stateMutability","errorObj","mutability","outputs","constant","getSelector","PanicReasons","paramTypeBytes","paramTypeNumber","defaultCoder","defaultMaxInflation","AbiCoder","getCoder","getDefaultValue","_setDefaultMaxInflation","defaultAbiCoder","getBuiltinCallException","action","abiCoder","revert","transaction","invocation","LogDescription","fragment","topic","TransactionDescription","ErrorDescription","Indexed","_isIndexed","isIndexed","BuiltinErrors","Interface","fragments","deploy","fallback","receive","errors","events","functions","abi","frags","console","log","getAbiCoder","bucket","minimal","f","formatJson","getFunction","forceUnique","matching","lastValue","valueLength","allowOptions","splice","lastArg","m","getFunctionName","hasFunction","forEachFunction","getEvent","eventTopic","getEventName","hasEvent","forEachEvent","getError","forEachError","_decodeParams","_encodeParams","encodeDeploy","decodeErrorResult","encodeErrorResult","decodeFunctionData","encodeFunctionData","decodeFunctionResult","ef","parsed","parseTransaction","encodeFunctionResult","encodeFilterTopics","topics","encodeTopic","encodeEventLog","dataTypes","dataValues","decodeEventLog","nonIndexed","resultIndexed","resultNonIndexed","nonIndexedIndex","indexedIndex","parseCallResult","parseLog","parseError","hexData","toJson","FeeData","copyRequest","bigIntKeys","numberKeys","blockTag","enableCcipRead","customData","Block","provider","number","timestamp","parentHash","parentBeaconBlockRoot","difficulty","gasUsed","stateRoot","receiptsRoot","blobGasUsed","excessBlobGas","miner","prevRandao","extraData","baseFeePerGas","transactions","TransactionResponse","prefetchedTransactions","txs","date","getTransaction","indexOrHash","getPrefetchedTransaction","isMined","orphanedEvent","orphan","Log","transactionHash","blockHash","blockNumber","removed","transactionIndex","getBlock","getTransactionReceipt","receipt","removedEvent","TransactionReceipt","contractAddress","logsBloom","cumulativeGasUsed","blobGasPrice","status","root","logs","effectiveGasPrice","fee","getResult","getTransactionResult","confirmations","getBlockNumber","createRemovedTransactionFilter","reorderedEvent","createReorderedTransactionFilter","startBlock","_confirms","_timeout","confirms","nextScan","stopScanning","checkReplacement","getTransactionCount","mined","replacement","replaceableTransaction","checkReceipt","waiter","reject","cancellers","timer","clearTimeout","txListener","on","replaceListener","once","EventLog","interface","iface","eventName","eventSignature","UndecodedEventLog","ContractTransactionReceipt","ContractTransactionResponse","ContractUnknownEventPayload","contract","ContractEventPayload","_log","canCall","canEstimate","canResolve","canSend","getResolver","PreparedTopicFilter","runner","getRunner","resolvedArgs","getTopicFilter","feature","getProvider","copyOverrides","arg","_overrides","buildWrappedFallback","populateTransaction","noValue","noData","sendTransaction","_contract","estimateGas","staticCall","buildWrappedMethod","getFragment","_runner","resolveArgs","staticCallResult","configurable","internalValues","getInternal","getSubInfo","event","topicHashify","tag","hasSub","subs","getSub","sub","foundFragment","_foundFragment","emit","starting","stop","started","lastEmit","payloadFunc","resultPromise","passArgs","_emit","BaseContract","filters","_deployTx","addrPromise","deployTx","connect","attach","getDeployedCode","getCode","waitForDeployment","deploymentTransaction","checkCode","buildWrappedEvent","queryTransaction","queryFilter","fromBlock","toBlock","getLogs","listenerCount","total","removeAllListeners","buildClass","Contract","_ContractBase","getIpfsLink","MulticoinProviderPlugin","proivder","supportsCoinType","coinType","encodeAddress","decodeAddress","matcherIpfs","matchers","EnsResolver","supports2544","supportsWildcard","supportsInterface","fetch","funcName","ethCoinType","coinPlugin","plugin","plugins","getText","getContentHash","swarm","getAvatar","_getAvatar","linkage","avatar","owner","tokenId","tokenOwner","ownerOf","balance","balanceOf","metadataUrl","metadata","imageUrl","image","getEnsAddress","network","getNetwork","ensPlugin","getPlugin","ensAddr","fromName","currentName","allowNull","nullValue","arrayOf","altNames","srcKey","altKey","nv","formatData","formatHash","_formatLog","_formatBlock","_formatReceiptLog","_formatTransactionReceipt","formatTransactionResponse","creates","nonceHex","getCreateAddress","NetworkPlugin","GasCostPlugin","effectiveBlock","txBase","txCreate","txDataZero","txDataNonzero","txAccessListStorageKey","txAccessListAddress","costs","props","nullish","EnsPlugin","targetNetwork","FetchUrlFeeDataNetworkPlugin","Networks","Network","matches","attachPlugin","getPlugins","basename","computeIntrinsicGas","injected","registerEth","ensNetwork","getGasStationPlugin","injectCommonNetworks","networkFunc","custom","ensAddress","nameOrChainId","existing","parseUnits","decimals","frac","fetchFeeData","_feeData","standard","maxFee","maxPriorityFee","PollingBlockSubscriber","poller","interval","pollingInterval","poll","_setTimeout","bind","_clearTimeout","pause","dropWhilePaused","resume","OnBlockSubscriber","running","_poll","PollingBlockTagSubscriber","lastBlock","PollingOrphanSubscriber","PollingTransactionSubscriber","PollingEventSubscriber","isPromise","getTag","UnmanagedSubscriber","concisify","getSubscription","_event","addresses","addAddress","defaultOptions","cacheTimeout","AbstractProvider","pausedState","destroyed","networkPromise","anyNetwork","performCache","lastBlockNumber","nextTimer","timers","disableCcipRead","_network","perform","_perform","ccipReadFetch","calldata","urls","sender","errorMessages","href","errorMessage","_wrapBlock","formatBlock","_wrapLog","formatLog","_wrapTransactionReceipt","formatTransactionReceipt","_wrapTransactionResponse","_detectNetwork","_getAddress","_getBlockTag","_getFilter","_address","_getTransactionRequest","detectNetwork","expected","actual","getFeeData","getFeeDataFunc","_block","priorityFee","feeData","_tx","txSender","ccipArgs","errorArgs","zeros","urlsOffset","urlsLength","urlsData","u","_parseString","_parseBytes","parseOffchainLookup","ccipResult","encodeBytes","checkNetwork","getAccountValue","_blockTag","getBalance","getStorage","_position","position","broadcastTransaction","signedTx","signedTransaction","includeTransactions","prefetchTxs","_filter","_getProvider","lookupAddress","node","ensContract","resolverContract","waitForTransaction","waitForBlock","timerId","_func","paused","time","_forEachSubscriber","subscriber","_getSubscriber","_recoverSubscriber","oldSub","newSub","emitArgs","subscription","addressableMap","nameMap","destroy","numPad","bytesPad","empty","byteCount","checkProvider","signer","populate","AbstractSigner","getNonce","populateCall","hasEip1559","txObj","signTransaction","VoidSigner","throwUnsupported","signMessage","signTypedData","FilterIdSubscriber","filterIdPromise","hault","_subscribe","_emitResults","_recover","filterId","teardown","FilterIdEventSubscriber","results","FilterIdPendingSubscriber","Primitive","deepCopy","duration","getLowerCase","isPollable","polling","staticNetwork","batchStallTime","batchMaxSize","batchMaxCount","JsonRpcSigner","sendUncheckedTransaction","_from","_to","hexTx","getRpcTransaction","timeouts","invalids","checkTx","sendTransactionHash","_message","populated","unlock","_legacySignMessage","JsonRpcApiProvider","nextId","payloads","drainTimer","notReady","pendingDetectNetwork","scheduleDrain","stallTime","_getOption","batch","shift","_send","getRpcError","_resolve","getRpcRequest","ready","jsonrpc","_start","_waitUntilReady","dstKey","h","_error","msg","spelunkData","_spelunkMessage","spelunkMessage","eth_sign","personal_sign","eth_signTypedData_v4","eth_signTransaction","eth_sendTransaction","eth_requestAccounts","wallet_requestAccounts","unsupported","getSigner","accountsPromise","accounts","account","listAccounts","JsonRpcApiPollingProvider","JsonRpcProvider","_getConnection","BrowserProvider","ethereum","_options","hasSigner","BaseWallet","signingKey","btx","signMessageSync","subsChrs","Word","unfold","words","sep","initial","word","decodeOwl","clumps","leftover","semi","Wordlist","locale","phrase","WordlistOwl","_decodeWords","loadWords","getWord","getWordIndex","wordlist","LangEn","getUpperMask","mnemonicToEntropy","mnemonic","entropy","bit","entropyBits","checksumMask","entropyToMnemonic","indices","remainingBits","checksumBits","Mnemonic","computeSeed","fromPhrase","fromEntropy","_entropy","entropyToPhrase","phraseToEntropy","isValidMnemonic","looseArrayify","hexString","zpad","getPassword","spelunk","_path","path","reqd","parseFloat","defaultPath","isKeystoreJson","json","getAccount","ciphertext","iv","CTR","decrypt","mnemonicKey","mnemonicCiphertext","mnemonicIv","mnemonicAesCtr","getDecryptKdfParams","kdf","prf","getEncryptKdfParams","_encryptKeystore","uuidRandom","uuid","derivedKey","macPrefix","encrypt","mac","Crypto","cipher","cipherparams","kdfparams","dklen","client","now","gethFilename","getUTCFullYear","getUTCMonth","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","mnemonicCounter","encryptKeystoreJsonSync","passwordBytes","encryptKeystoreJson","progressCallback","MasterSecret","HardenedBit","encodeBase58Check","ser_I","chainCode","I","IL","IR","derivePath","component","deriveChild","HDNodeWallet","fingerprint","parentFingerprint","encryptSync","extendedKey","hasPath","neuter","HDNodeVoidWallet","_index","ki","fromSeed","_seed","seed","fromExtendedKey","decodeBase58","createRandom","fromMnemonic","Ki","isCrowdsaleJson","encseed","decryptCrowdsaleJson","encryptedSeed","aesCbc","CBC","pkcs7Strip","seedHex","Wallet","fromAccount","wallet","fromEncryptedJson","decryptKeystoreJson","fromEncryptedJsonSync","decryptKeystoreJsonSync","contractAddresses","PROOF_OF_INTEGRITY_ADDRESS","STEALTH_ANNOUNCER_ADDRESS","window","fileURLToPath","require","dirname","readFileSync","__filename","document","pathToFileURL","_documentCurrentScript","tagName","src","URL","baseURI","rawdata","warn","LOCAL_CONFIG","CHAIN_ID","RPC_URL","GUN_PEER","CHAIN_CONFIG","optimismSepolia","arbitrumSepolia","localhost","getAddressesForChain","chainName","config","require$$0","err","STEALTH_ANNOUNCER_ABI","internalType","PROOF_OF_INTEGRITY_ABI","rpcUrl","MESSAGE_TO_SIGN","generateRandomId","ethers.hexlify","ethers.randomBytes","generatePassword","ethers.keccak256","gunToEthAccount","gunPrivateKey","hexPrivateKey","base64url","repeat","base64","binary","atob","char","padStart","base64UrlToHex","ethers.Wallet","ethers.JsonRpcProvider","ethers.BrowserProvider","deriveStealthAddress","sharedSecret","spendingPublicKey","sharedSecretBytes","Buffer","stealthPrivateKey","ethers.concat","ethers.getBytes","stealthWallet","sharedSecretHex","stealthAddress","Gun","chain","setSigner","newRpcUrl","newPrivateKey","verifySignature","recoveredAddress","ethers.verifyMessage","createSignature","createAndStoreEncryptedPair","gun","SEA","v_pair","s_pair","encryptedPair","encryptedV_pair","encryptedS_pair","viewingAccount","priv","spendingAccount","put","publicKeys","viewingPublicKey","epub","ethViewingAddress","getAndDecryptPair","encryptedData","decryptedPair","nodeId","chainConfig","ethers.Contract","verifyOnChain","contentHash","PROOF_CONTRACT_ADDRESS","isValid","updater","verifyData","ethers.toUtf8Bytes","writeOnChain","updateData","getLatestRecord","existingData","_contentHash","latestRecord","newNodeId","ack","txHash","generateStealthAddress","recipientAddress","recipientData","senderAddress","senderData","spendingKeyPair","decryptedData","secret","senderPublicKey","publishStealthKeys","viewingKeyPair","recoverStealthFunds","myAddress","decryptedViewingData","recovered","announceStealthPayment","onChain","devFee","announcePayment","stack","getStealthPayments","source","payments","env","NODE_ENV","totalAnnouncements","getAnnouncementsCount","totalCount","batchSize","lastIndex","toIndex","min","getAnnouncementsInRange","announcement","recoveredWallet","offChainPayments","payment","cleanStealthPayments","GunEth","static"],"mappings":"omCAIO,MAAMA,EAAU,SCCvB,SAASC,EAAUC,EAAOC,EAAMC,GAC5B,MAAMC,EAAQF,EAAKG,MAAM,KAAKC,KAAIC,GAAKA,EAAEC,SACzC,IAAK,IAAIC,EAAI,EAAGA,EAAIL,EAAMM,OAAQD,IAC9B,OAAQP,GACJ,IAAK,MACD,OACJ,IAAK,SACL,IAAK,UACL,IAAK,SACL,IAAK,SACD,UAAY,IAAWA,EACnB,OAIhB,MAAMS,EAAQ,IAAIC,MAAM,0BAA0BV,KAIlD,MAHAS,EAAME,KAAO,mBACbF,EAAMG,SAAW,SAASX,IAC1BQ,EAAMV,MAAQA,EACRU,CACV,CAKOI,eAAeC,EAAkBf,GACpC,MAAMgB,EAAOC,OAAOD,KAAKhB,GAEzB,aADsBkB,QAAQC,IAAIH,EAAKX,KAAKe,GAAMF,QAAQG,QAAQrB,EAAMoB,QACzDE,QAAO,CAACC,EAAOC,EA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