From 06449b59108e11dbea5a56dea2279d30acc2fe6e Mon Sep 17 00:00:00 2001 From: Juuddi Date: Thu, 5 Sep 2024 15:43:02 -0500 Subject: [PATCH 1/2] Add support for wss urls --- src/providers/provider-socket.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/providers/provider-socket.ts b/src/providers/provider-socket.ts index dcfa9926..f6c3b784 100644 --- a/src/providers/provider-socket.ts +++ b/src/providers/provider-socket.ts @@ -476,13 +476,13 @@ export class SocketProvider extends JsonRpcApiProvider { } validateUrl(url: string): void { - const urlPattern = /^(ws):\/\/[a-zA-Z0-9.-]+(:\d+)?$/; + const urlPattern = /^(wss?):\/\/[a-zA-Z0-9.-]+(:\d+)?$/; if (!urlPattern.test(url)) { let errorMessage = 'Invalid URL: '; - if (!/^ws:\/\//.test(url)) { - errorMessage += 'URL must start with ws://. '; + if (!/^wss?:\/\//.test(url)) { + errorMessage += 'URL must start with ws:// or wss://. '; } if (url.endsWith('/')) { From e0b5730e0501dbbfd796cde2ffaaaf29e37cfaa8 Mon Sep 17 00:00:00 2001 From: Juuddi Date: Fri, 6 Sep 2024 10:39:58 -0500 Subject: [PATCH 2/2] Remove committed dist files --- dist/quais.js | 31264 --------------------------------- dist/quais.js.map | 1 - dist/quais.min.js | 1 - dist/quais.umd.js | 31449 ---------------------------------- dist/quais.umd.js.map | 1 - dist/quais.umd.min.js | 1 - dist/wordlists-extra.js | 1555 -- dist/wordlists-extra.js.map | 1 - dist/wordlists-extra.min.js | 1 - 9 files changed, 64274 deletions(-) delete mode 100644 dist/quais.js delete mode 100644 dist/quais.js.map delete mode 100644 dist/quais.min.js delete mode 100644 dist/quais.umd.js delete mode 100644 dist/quais.umd.js.map delete mode 100644 dist/quais.umd.min.js delete mode 100644 dist/wordlists-extra.js delete mode 100644 dist/wordlists-extra.js.map delete mode 100644 dist/wordlists-extra.min.js diff --git a/dist/quais.js b/dist/quais.js deleted file mode 100644 index 151dbb6a..00000000 --- a/dist/quais.js +++ /dev/null @@ -1,31264 +0,0 @@ -const __$G = (typeof globalThis !== 'undefined' ? globalThis: typeof window !== 'undefined' ? window: typeof global !== 'undefined' ? global: typeof self !== 'undefined' ? self: {}); -import * as pb_1 from 'google-protobuf'; - -/* Do NOT modify this file; see /src/_admin/update-version.ts */ -/** - * The current version of quais. - * - * @ignore - */ -const version = '1.0.0-alpha.5'; - -/** - * Property helper functions. - */ -function checkType(value, type, name) { - const types = type.split('|').map((t) => t.trim()); - for (let i = 0; i < types.length; i++) { - switch (type) { - case 'any': - return; - case 'bigint': - case 'boolean': - case 'number': - case 'string': - if (typeof value === type) { - return; - } - } - } - const error = new Error(`invalid value for type ${type}`); - error.code = 'INVALID_ARGUMENT'; - error.argument = `value.${name}`; - error.value = value; - throw error; -} -/** - * Resolves to a new object that is a copy of `value`, but with all values resolved. - * - * @category Utils - * @param {Object} value - The object to resolve. - * - * @returns {Promise} The resolved object. - */ -async function resolveProperties(value) { - const keys = Object.keys(value); - const results = await Promise.all(keys.map((k) => Promise.resolve(value[k]))); - return results.reduce((accum, v, index) => { - accum[keys[index]] = v; - return accum; - }, {}); -} -// Crawl up the constructor chain to find a static method -function getStatic(ctor, key) { - for (let i = 0; i < 32; i++) { - if (ctor[key]) { - return ctor[key]; - } - if (!ctor.prototype || typeof ctor.prototype !== 'object') { - break; - } - ctor = Object.getPrototypeOf(ctor.prototype).constructor; - } - return null; -} -/** - * Assigns the `values` to `target` as read-only values. - * - * It `types` is specified, the values are checked. - * - * @category Utils - * @param {Object} target - The target object to assign to. - * @param {Object} values - The values to assign. - * @param {Object} types - The types to check. - */ -function defineProperties(target, values, types) { - for (const key in values) { - const value = values[key]; - const type = types ? types[key] : null; - if (type) { - checkType(value, type, key); - } - Object.defineProperty(target, key, { enumerable: true, value, writable: false }); - } -} - -/** - * All errors in quais include properties to ensure they are both human-readable (i.e. `.message`) and machine-readable - * (i.e. `.code`). - * - * The {@link isError | **isError**} function can be used to check the error `code` and provide a type guard for the - * properties present on that error interface. - */ -function stringify(value) { - if (value == null) { - return 'null'; - } - if (Array.isArray(value)) { - return '[ ' + value.map(stringify).join(', ') + ' ]'; - } - if (value instanceof Uint8Array) { - const HEX = '0123456789abcdef'; - let result = '0x'; - for (let i = 0; i < value.length; i++) { - result += HEX[value[i] >> 4]; - result += HEX[value[i] & 0xf]; - } - return result; - } - if (typeof value === 'object' && typeof value.toJSON === 'function') { - return stringify(value.toJSON()); - } - switch (typeof value) { - case 'boolean': - case 'symbol': - return value.toString(); - case 'bigint': - return BigInt(value).toString(); - case 'number': - return value.toString(); - case 'string': - return JSON.stringify(value); - case 'object': { - const keys = Object.keys(value); - keys.sort(); - return '{ ' + keys.map((k) => `${stringify(k)}: ${stringify(value[k])}`).join(', ') + ' }'; - } - } - return `[ COULD NOT SERIALIZE ]`; -} -/** - * Returns true if the `error` matches an error thrown by quais that matches the error `code`. - * - * In TypeScript environments, this can be used to check that `error` matches an quaisError type, which means the - * expected properties will be set. - * - * @category Utils - * @example - * - * ```ts - * try { - * // code.... - * } catch (e) { - * if (isError(e, 'CALL_EXCEPTION')) { - * // The Type Guard has validated this object - * console.log(e.data); - * } - * } - * ``` - * - * @see [ErrorCodes](api:ErrorCode) - */ -function isError(error, code) { - return error && error.code === code; -} -/** - * Returns true if `error` is a {@link CallExceptionError | **CallExceptionError**}. - * - * @category Utils - */ -function isCallException(error) { - return isError(error, 'CALL_EXCEPTION'); -} -/** - * Returns a new Error configured to the format quais emits errors, with the `message`, {@link ErrorCode | **ErrorCode**} - * `code` and additional properties for the corresponding quaisError. - * - * Each error in quais includes the version of quais, a machine-readable {@link ErrorCode | **ErrorCode**}, and depending - * on `code`, additional required properties. The error message will also include the `message`, quais version, `code` - * and all additional properties, serialized. - * - * @category Utils - * @param {string} message - The error message. - * @param {ErrorCode} code - The error code. - * @param {ErrorInfo} [info] - Additional properties for the error. - * @returns {T} The new error. - */ -function makeError(message, code, info) { - const shortMessage = message; - { - const details = []; - if (info) { - if ('message' in info || 'code' in info || 'name' in info) { - throw new Error(`value will overwrite populated values: ${stringify(info)}`); - } - for (const key in info) { - if (key === 'shortMessage') { - continue; - } - const value = info[key]; - details.push(key + '=' + stringify(value)); - } - } - details.push(`code=${code}`); - details.push(`version=${version}`); - if (details.length) { - message += ' (' + details.join(', ') + ')'; - } - } - let error; - switch (code) { - case 'INVALID_ARGUMENT': - error = new TypeError(message); - break; - case 'NUMERIC_FAULT': - case 'BUFFER_OVERRUN': - error = new RangeError(message); - break; - default: - error = new Error(message); - } - defineProperties(error, { code }); - if (info) { - Object.assign(error, info); - } - if (error.shortMessage == null) { - defineProperties(error, { shortMessage }); - } - return error; -} -/** - * Throws an quaisError with `message`, `code` and additional error `info` when `check` is falsish.. - * - * @category Utils - * @param {unknown} check - The value to check. - * @param {string} message - The error message. - * @param {ErrorCode} code - The error code. - * @param {ErrorInfo} [info] - Additional properties for the error. - * @throws {T} Throws the error if `check` is falsish. - */ -function assert(check, message, code, info) { - if (!check) { - throw makeError(message, code, info); - } -} -/** - * A simple helper to simply ensuring provided arguments match expected constraints, throwing if not. - * - * In TypeScript environments, the `check` has been asserted true, so any further code does not need additional - * compile-time checks. - * - * @category Utils - * @param {unknown} check - The value to check. - * @param {string} message - The error message. - * @param {string} name - The name of the argument. - * @param {unknown} value - The value of the argument. - * @throws {InvalidArgumentError} Throws if `check` is falsish. - */ -function assertArgument(check, message, name, value) { - assert(check, message, 'INVALID_ARGUMENT', { argument: name, value: value }); -} -function assertArgumentCount(count, expectedCount, message) { - if (message == null) { - message = ''; - } - if (message) { - message = ': ' + message; - } - assert(count >= expectedCount, 'missing arguemnt' + message, 'MISSING_ARGUMENT', { - count: count, - expectedCount: expectedCount, - }); - assert(count <= expectedCount, 'too many arguemnts' + message, 'UNEXPECTED_ARGUMENT', { - count: count, - expectedCount: expectedCount, - }); -} -const _normalizeForms = ['NFD', 'NFC', 'NFKD', 'NFKC'].reduce((accum, form) => { - try { - // General test for normalize - /* c8 ignore start */ - if ('test'.normalize(form) !== 'test') { - throw new Error('bad'); - } - /* c8 ignore stop */ - if (form === 'NFD') { - const check = String.fromCharCode(0xe9).normalize('NFD'); - const expected = String.fromCharCode(0x65, 0x0301); - /* c8 ignore start */ - if (check !== expected) { - throw new Error('broken'); - } - /* c8 ignore stop */ - } - accum.push(form); - // eslint-disable-next-line no-empty - } - catch (error) { } - return accum; -}, []); -/** - * Throws if the normalization `form` is not supported. - * - * @category Utils - * @param {string} form - The normalization form. - * @throws {UnsupportedOperationError} Throws if the form is not supported. - */ -function assertNormalize(form) { - assert(_normalizeForms.indexOf(form) >= 0, 'platform missing String.prototype.normalize', 'UNSUPPORTED_OPERATION', { - operation: 'String.prototype.normalize', - info: { form }, - }); -} -/** - * Many classes use file-scoped values to guard the constructor, making it effectively private. This facilitates that - * pattern by ensuring the `givenGuard` matches the file-scoped `guard`, throwing if not, indicating the `className%% if - * provided. - * - * @category Utils - * @param {any} givenGuard - The guard provided to the constructor. - * @param {any} guard - The file-scoped guard. - * @param {string} [className] - The class name. - * @throws {UnsupportedOperationError} Throws if the guards do not match. - */ -function assertPrivate(givenGuard, guard, className) { - if (className == null) { - className = ''; - } - if (givenGuard !== guard) { - let method = className, operation = 'new'; - if (className) { - method += '.'; - operation += ' ' + className; - } - assert(false, `private constructor; use ${method}from* methods`, 'UNSUPPORTED_OPERATION', { - operation, - }); - } -} - -/** - * Some data helpers. - */ -/** - * Converts a BytesLike value to a Uint8Array. - * - * @ignore - * @category Utils - * @param {BytesLike} value - The value to convert. - * @param {string} [name] - The name of the value for error context. - * @param {boolean} [copy] - Whether to create a copy of the value. - * - * @returns {Uint8Array} The converted Uint8Array. - * @throws {Error} If the value is not a valid BytesLike. - */ -function _getBytes(value, name, copy) { - if (value instanceof Uint8Array) { - if (copy) { - return new Uint8Array(value); - } - return value; - } - if (typeof value === 'string' && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) { - const result = new Uint8Array((value.length - 2) / 2); - let offset = 2; - for (let i = 0; i < result.length; i++) { - result[i] = parseInt(value.substring(offset, offset + 2), 16); - offset += 2; - } - return result; - } - assertArgument(false, 'invalid BytesLike value', name || 'value', value); -} -/** - * Get a typed Uint8Array for `value`. If already a Uint8Array the original `value` is returned; if a copy is required - * use {@link getBytesCopy | **getBytesCopy**}. - * - * @category Utils - * @param {BytesLike} value - The value to convert to a Uint8Array. - * @param {string} [name] - The name of the value for error context. - * - * @returns {Uint8Array} The typed Uint8Array. - */ -function getBytes(value, name) { - return _getBytes(value, name, false); -} -/** - * Get a typed Uint8Array for `value`, creating a copy if necessary to prevent any modifications of the returned value - * from being reflected elsewhere. - * - * @category Utils - * @param {BytesLike} value - The value to convert to a Uint8Array. - * @param {string} [name] - The name of the value for error context. - * - * @returns {Uint8Array} The typed Uint8Array. - */ -function getBytesCopy(value, name) { - return _getBytes(value, name, true); -} -/** - * Returns true if `value` is a valid {@link HexString | **HexString**}. - * - * If `length` is `true` or a number, it also checks that `value` is a valid {@link DataHexString | **DataHexString**} of - * `length` (if a number) bytes of data (e.g. `0x1234` is 2 bytes). - * - * @category Utils - * @param {any} value - The value to check. - * @param {number | boolean} [length] - The expected length of the data. - * - * @returns {boolean} True if the value is a valid {@link HexString | **HexString**}. - */ -function isHexString(value, length) { - if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { - return false; - } - if (typeof length === 'number' && value.length !== 2 + 2 * length) { - return false; - } - if (length === true && value.length % 2 !== 0) { - return false; - } - return true; -} -/** - * Returns true if `value` is a valid representation of arbitrary data (i.e. a valid - * {@link DataHexString | **DataHexString**} or a Uint8Array). - * - * @category Utils - * @param {any} value - The value to check. - * - * @returns {boolean} True if the value is a valid {@link DataHexString | **DataHexString**}. - */ -function isBytesLike(value) { - return isHexString(value, true) || value instanceof Uint8Array; -} -const HexCharacters = '0123456789abcdef'; -/** - * Returns a {@link DataHexString | **DataHexString**} representation of `data`. - * - * @category Utils - * @param {BytesLike} data - The data to convert to a hex string. - * - * @returns {string} The hex string. - */ -function hexlify(data) { - const bytes = getBytes(data); - let result = '0x'; - for (let i = 0; i < bytes.length; i++) { - const v = bytes[i]; - result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; - } - return result; -} -/** - * Returns a {@link DataHexString | **DataHexString** } by concatenating all values within `data`. - * - * @category Utils - * @param {ReadonlyArray} datas - The data to concatenate. - * - * @returns {string} The concatenated data. - */ -function concat(datas) { - return '0x' + datas.map((d) => hexlify(d).substring(2)).join(''); -} -/** - * Returns the length of `data`, in bytes. - * - * @category Utils - * @param {BytesLike} data - The data to get the length of. - * - * @returns {number} The length of the data. - */ -function dataLength(data) { - if (isHexString(data, true)) { - return (data.length - 2) / 2; - } - return getBytes(data).length; -} -/** - * Returns a {@link DataHexString | **DataHexString** } by slicing `data` from the `start` offset to the `end` offset. - * - * By default `start` is 0 and `end` is the length of `data`. - * - * @category Utils - * @param {BytesLike} data - The data to slice. - * @param {number} [start] - The start offset. - * @param {number} [end] - The end offset. - * - * @returns {string} The sliced data. - * @throws {Error} If the end offset is beyond the data bounds. - */ -function dataSlice(data, start, end) { - const bytes = getBytes(data); - if (end != null && end > bytes.length) { - assert(false, 'cannot slice beyond data bounds', 'BUFFER_OVERRUN', { - buffer: bytes, - length: bytes.length, - offset: end, - }); - } - return hexlify(bytes.slice(start == null ? 0 : start, end == null ? bytes.length : end)); -} -/** - * Return the {@link DataHexString | **DataHexString**} result by stripping all **leading** zero bytes from `data`. - * - * @category Utils - * @param {BytesLike} data - The data to strip. - * - * @returns {string} The stripped data. - */ -function stripZerosLeft(data) { - let bytes = hexlify(data).substring(2); - while (bytes.startsWith('00')) { - bytes = bytes.substring(2); - } - return '0x' + bytes; -} -/** - * Pads the data to the specified length. - * - * @ignore - * @category Utils - * @param {BytesLike} data - The data to pad. - * @param {number} length - The length to pad to. - * @param {boolean} left - Whether to pad on the left. - * - * @returns {string} The padded data. - * @throws {Error} If the padding exceeds data length. - */ -function zeroPad(data, length, left) { - const bytes = getBytes(data); - assert(length >= bytes.length, 'padding exceeds data length', 'BUFFER_OVERRUN', { - buffer: new Uint8Array(bytes), - length: length, - offset: length + 1, - }); - const result = new Uint8Array(length); - result.fill(0); - if (left) { - result.set(bytes, length - bytes.length); - } - else { - result.set(bytes, 0); - } - return hexlify(result); -} -/** - * Return the {@link DataHexString | **DataHexString**} of `data` padded on the **left** to `length` bytes. - * - * If `data` already exceeds `length`, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown. - * - * This pads data the same as **values** are in Solidity (e.g. `uint128`). - * - * @category Utils - * @param {BytesLike} data - The data to pad. - * @param {number} length - The length to pad to. - * - * @returns {string} The padded data. - */ -function zeroPadValue(data, length) { - return zeroPad(data, length, true); -} -/** - * Return the {@link DataHexString | **DataHexString**} of `data` padded on the **right** to `length` bytes. - * - * If `data` already exceeds %%length%%, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown. - * - * This pads data the same as **bytes** are in Solidity (e.g. `bytes16`). - * - * @category Utils - * @param {BytesLike} data - The data to pad. - * @param {number} length - The length to pad to. - * - * @returns {string} The padded data. - */ -function zeroPadBytes(data, length) { - return zeroPad(data, length, false); -} - -/** - * When an {@link EventEmitterable | **EventEmitterable**} triggers a Listener, the callback always ahas one additional - * argument passed, which is an **EventPayload**. - * - * @category Utils - */ -class EventPayload { - /** - * The event filter. - */ - filter; - /** - * The **EventEmitterable**. - */ - emitter; - #listener; - /** - * Create a new **EventPayload** for `emitter` with the `listener` and for `filter`. - */ - constructor(emitter, listener, filter) { - this.#listener = listener; - defineProperties(this, { emitter, filter }); - } - /** - * Unregister the triggered listener for future events. - */ - async removeListener() { - if (this.#listener == null) { - return; - } - await this.emitter.off(this.filter, this.#listener); - } -} - -function decodeBase64(textData) { - textData = atob(textData); - const data = new Uint8Array(textData.length); - for (let i = 0; i < textData.length; i++) { - data[i] = textData.charCodeAt(i); - } - return getBytes(data); -} -function encodeBase64(_data) { - const data = getBytes(_data); - let textData = ''; - for (let i = 0; i < data.length; i++) { - textData += String.fromCharCode(data[i]); - } - return btoa(textData); -} - -/** - * Provides utility functions for encoding and decoding strings in the Bytes32 format. - * - * @category Application Binary Interface - */ -/** - * Encodes a string as a Bytes32 string. This is used to encode ABI data. - * - * @category Encoding - * @param {string} text - The string to encode. - * - * @returns {string} The Bytes32-encoded string. - * @throws {Error} If the string is too long to fit in a Bytes32 format. - */ -function encodeBytes32(text) { - // Get the bytes - const bytes = toUtf8Bytes(text); - // Check we have room for null-termination - if (bytes.length > 31) { - throw new Error('bytes32 string must be less than 32 bytes'); - } - // Zero-pad (implicitly null-terminates) - return zeroPadBytes(bytes, 32); -} -/** - * Decodes a Bytes32-encoded string into a regular string. This is used to decode ABI-encoded data. - * - * @category Encoding - * @param {BytesLike} _bytes - The Bytes32-encoded data. - * - * @returns {string} The decoded string. - * @throws {Error} If the input is not exactly 32 bytes long or lacks a null terminator. - */ -function decodeBytes32(_bytes) { - const data = getBytes(_bytes, 'bytes'); - // Must be 32 bytes with a null-termination - if (data.length !== 32) { - throw new Error('invalid bytes32 - not 32 bytes long'); - } - if (data[31] !== 0) { - throw new Error('invalid bytes32 string - no null terminator'); - } - // Find the null termination - let length = 31; - while (data[length - 1] === 0) { - length--; - } - // Determine the string value - return toUtf8String(data.slice(0, length)); -} - -/** - * Some mathematic operations. - */ -const BN_0$8 = BigInt(0); -const BN_1$4 = BigInt(1); -//const BN_Max256 = (BN_1 << BigInt(256)) - BN_1; -// IEEE 754 support 53-bits of mantissa -const maxValue = 0x1fffffffffffff; -/** - * Convert `value` from a twos-compliment representation of `width` bits to its value. - * - * If the highest bit is `1`, the result will be negative. - * - * @category Utils - * @param {BigNumberish} _value - The value to convert. - * @param {Numeric} _width - The width of the value in bits. - * @returns {bigint} The value. - * @throws {Error} If the value is too large for the width. - */ -function fromTwos(_value, _width) { - const value = getUint(_value, 'value'); - const width = BigInt(getNumber(_width, 'width')); - assert(value >> width === BN_0$8, 'overflow', 'NUMERIC_FAULT', { - operation: 'fromTwos', - fault: 'overflow', - value: _value, - }); - // Top bit set; treat as a negative value - if (value >> (width - BN_1$4)) { - const mask = (BN_1$4 << width) - BN_1$4; - return -((~value & mask) + BN_1$4); - } - return value; -} -/** - * Convert `value` to a twos-compliment representation of `width` bits. - * - * The result will always be positive. - * - * @category Utils - * @param {BigNumberish} _value - The value to convert. - * @param {Numeric} _width - The width of the value in bits. - * @returns {bigint} The value. - * @throws {Error} If the value is too large for the width. - */ -function toTwos(_value, _width) { - let value = getBigInt(_value, 'value'); - const width = BigInt(getNumber(_width, 'width')); - const limit = BN_1$4 << (width - BN_1$4); - if (value < BN_0$8) { - value = -value; - assert(value <= limit, 'too low', 'NUMERIC_FAULT', { - operation: 'toTwos', - fault: 'overflow', - value: _value, - }); - const mask = (BN_1$4 << width) - BN_1$4; - return (~value & mask) + BN_1$4; - } - else { - assert(value < limit, 'too high', 'NUMERIC_FAULT', { - operation: 'toTwos', - fault: 'overflow', - value: _value, - }); - } - return value; -} -/** - * Mask `value` with a bitmask of `bits` ones. - * - * @category Utils - * @param {BigNumberish} _value - The value to mask. - * @param {Numeric} _bits - The number of bits to mask. - * @returns {bigint} The masked value. - */ -function mask(_value, _bits) { - const value = getUint(_value, 'value'); - const bits = BigInt(getNumber(_bits, 'bits')); - return value & ((BN_1$4 << bits) - BN_1$4); -} -/** - * Gets a BigInt from `value`. If it is an invalid value for a BigInt, then an ArgumentError will be thrown for `name`. - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @param {string} name - The name of the value. - * @returns {bigint} The value. - */ -function getBigInt(value, name) { - switch (typeof value) { - case 'bigint': - return value; - case 'number': - assertArgument(Number.isInteger(value), 'underflow', name || 'value', value); - assertArgument(value >= -maxValue && value <= maxValue, 'overflow', name || 'value', value); - return BigInt(value); - case 'string': - try { - if (value === '') { - throw new Error('empty string'); - } - if (value[0] === '-' && value[1] !== '-') { - return -BigInt(value.substring(1)); - } - return BigInt(value); - } - catch (e) { - assertArgument(false, `invalid BigNumberish string: ${e.message}`, name || 'value', value); - } - } - assertArgument(false, 'invalid BigNumberish value', name || 'value', value); -} -/** - * Returns absolute value of bigint `value`. - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @returns {bigint} The absolute value. - */ -function bigIntAbs(value) { - value = getBigInt(value); - // if value is negative (including -0), return -value, else return value - if (value === -BN_0$8 || value < BN_0$8) { - return -value; - } - return value; -} -/** - * Returns `value` as a bigint, validating it is valid as a bigint value and that it is positive. - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @param {string} name - The name of the value. - * @returns {bigint} The value. - * @throws {Error} If the value is negative. - */ -function getUint(value, name) { - const result = getBigInt(value, name); - assert(result >= BN_0$8, 'unsigned value cannot be negative', 'NUMERIC_FAULT', { - fault: 'overflow', - operation: 'getUint', - value, - }); - return result; -} -const Nibbles$1 = '0123456789abcdef'; -/** - * Converts `value` to a BigInt. If `value` is a Uint8Array, it is treated as Big Endian data. - * - * @category Utils - * @param {BigNumberish | Uint8Array} value - The value to convert. - * @returns {bigint} The value. - */ -function toBigInt(value) { - if (value instanceof Uint8Array) { - let result = '0x0'; - for (const v of value) { - result += Nibbles$1[v >> 4]; - result += Nibbles$1[v & 0x0f]; - } - return BigInt(result); - } - return getBigInt(value); -} -/** - * Gets a number from `value`. If it is an invalid value for a number, then an ArgumentError will be thrown for `name`. - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @param {string} name - The name of the value. - * @returns {number} The value. - * @throws {Error} If the value is invalid. - * @throws {Error} If the value is too large. - */ -function getNumber(value, name) { - switch (typeof value) { - case 'bigint': - assertArgument(value >= -maxValue && value <= maxValue, 'overflow', name || 'value', value); - return Number(value); - case 'number': - assertArgument(Number.isInteger(value), 'underflow', name || 'value', value); - assertArgument(value >= -maxValue && value <= maxValue, 'overflow', name || 'value', value); - return value; - case 'string': - try { - if (value === '') { - throw new Error('empty string'); - } - return getNumber(BigInt(value), name); - } - catch (e) { - assertArgument(false, `invalid numeric string: ${e.message}`, name || 'value', value); - } - } - assertArgument(false, 'invalid numeric value', name || 'value', value); -} -/** - * Converts `value` to a number. If `value` is a Uint8Array, it is treated as Big Endian data. Throws if the value is - * not safe. - * - * @category Utils - * @param {BigNumberish | Uint8Array} value - The value to convert. - * @returns {number} The value. - * @throws {Error} If the value is not safe to convert to a number. - */ -function toNumber(value) { - return getNumber(toBigInt(value)); -} -/** - * Converts `value` to a Big Endian hexstring, optionally padded to `width` bytes. - * - * @category Utils - * @param {BigNumberish} _value - The value to convert. - * @param {Numeric} _width - The width of the value in bytes. - * @returns {string} The hexstring. - * @throws {Error} If the value exceeds the width. - */ -function toBeHex(_value, _width) { - const value = getUint(_value, 'value'); - let result = value.toString(16); - if (_width == null) { - // Ensure the value is of even length - if (result.length % 2) { - result = '0' + result; - } - } - else { - const width = getNumber(_width, 'width'); - assert(width * 2 >= result.length, `value exceeds width (${width} bytes)`, 'NUMERIC_FAULT', { - operation: 'toBeHex', - fault: 'overflow', - value: _value, - }); - // Pad the value to the required width - while (result.length < width * 2) { - result = '0' + result; - } - } - return '0x' + result; -} -/** - * Converts `value` to a Big Endian Uint8Array. - * - * @category Utils - * @param {BigNumberish} _value - The value to convert. - * @returns {Uint8Array} The value. - */ -function toBeArray(_value) { - const value = getUint(_value, 'value'); - if (value === BN_0$8) { - return new Uint8Array([]); - } - let hex = value.toString(16); - if (hex.length % 2) { - hex = '0' + hex; - } - const result = new Uint8Array(hex.length / 2); - for (let i = 0; i < result.length; i++) { - const offset = i * 2; - result[i] = parseInt(hex.substring(offset, offset + 2), 16); - } - return result; -} -/** - * Returns a `HexString` for `value` safe to use as a Quantity. - * - * A Quantity does not have and leading 0 values unless the value is the literal value `0x0`. This is most commonly used - * for JSSON-RPC numeric values. - * - * @category Utils - * @param {BigNumberish | Uint8Array} value - The value to convert. - * @returns {string} The quantity. - */ -function toQuantity(value) { - let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2); - while (result.startsWith('0')) { - result = result.substring(1); - } - if (result === '') { - result = '0'; - } - return '0x' + result; -} - -/** - * The [Base58 Encoding](https://en.bitcoinwiki.org/wiki/Base58) scheme allows a **numeric** value to be encoded as a - * compact string using a radix of 58 using only alpha-numeric characters. Confusingly similar characters are omitted - * (i.e. `"l0O"`). - * - * Note that Base58 encodes a **numeric** value, not arbitrary bytes, since any zero-bytes on the left would get - * removed. To mitigate this issue most schemes that use Base58 choose specific high-order values to ensure non-zero - * prefixes. - */ -const Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; -let Lookup = null; -function getAlpha(letter) { - if (Lookup == null) { - Lookup = {}; - for (let i = 0; i < Alphabet.length; i++) { - Lookup[Alphabet[i]] = BigInt(i); - } - } - const result = Lookup[letter]; - assertArgument(result != null, `invalid base58 value`, 'letter', letter); - return result; -} -const BN_0$7 = BigInt(0); -const BN_58 = BigInt(58); -/** - * Encode `value` as a Base58-encoded string. - * - * @category Encoding - * @param {BytesLike} _value - The value to encode. - * - * @returns {string} The Base58-encoded string. - */ -function encodeBase58(_value) { - const bytes = getBytes(_value); - let value = toBigInt(bytes); - let result = ''; - while (value) { - result = Alphabet[Number(value % BN_58)] + result; - value /= BN_58; - } - // Account for leading padding zeros - for (let i = 0; i < bytes.length; i++) { - if (bytes[i]) { - break; - } - result = Alphabet[0] + result; - } - return result; -} -/** - * Decode the Base58-encoded `value`. - * - * @category Encoding - * @param {string} value - The Base58-encoded value. - * - * @returns {bigint} The decoded value. - */ -function decodeBase58(value) { - let result = BN_0$7; - for (let i = 0; i < value.length; i++) { - result *= BN_58; - result += getAlpha(value[i]); - } - return result; -} - -/** - * Generated by the protoc-gen-ts. DO NOT EDIT! - * compiler version: 4.25.3 - * source: proto_common.proto - * git: https://github.com/thesayyn/protoc-gen-ts */ -var common; -(function (common) { - class ProtoLocation extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - } - } - get value() { - return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set value(value) { - pb_1.Message.setField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoLocation({}); - if (data.value != null) { - message.value = data.value; - } - return message; - } - toObject() { - const data = {}; - if (this.value != null) { - data.value = this.value; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.value.length) - writer.writeBytes(1, this.value); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLocation(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.value = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoLocation.deserialize(bytes); - } - } - common.ProtoLocation = ProtoLocation; - class ProtoHash extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - } - } - get value() { - return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set value(value) { - pb_1.Message.setField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoHash({}); - if (data.value != null) { - message.value = data.value; - } - return message; - } - toObject() { - const data = {}; - if (this.value != null) { - data.value = this.value; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.value.length) - writer.writeBytes(1, this.value); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHash(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.value = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoHash.deserialize(bytes); - } - } - common.ProtoHash = ProtoHash; - class ProtoHashes extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("hashes" in data && data.hashes != undefined) { - this.hashes = data.hashes; - } - } - } - get hashes() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoHash, 1); - } - set hashes(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoHashes({}); - if (data.hashes != null) { - message.hashes = data.hashes.map(item => ProtoHash.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.hashes != null) { - data.hashes = this.hashes.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.hashes.length) - writer.writeRepeatedMessage(1, this.hashes, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHashes(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.hashes, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoHash.deserialize(reader), ProtoHash)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoHashes.deserialize(bytes); - } - } - common.ProtoHashes = ProtoHashes; - class ProtoAddress extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - } - } - get value() { - return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set value(value) { - pb_1.Message.setField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoAddress({}); - if (data.value != null) { - message.value = data.value; - } - return message; - } - toObject() { - const data = {}; - if (this.value != null) { - data.value = this.value; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.value.length) - writer.writeBytes(1, this.value); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoAddress(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.value = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoAddress.deserialize(bytes); - } - } - common.ProtoAddress = ProtoAddress; - class ProtoNumber extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - } - } - get value() { - return pb_1.Message.getFieldWithDefault(this, 1, 0); - } - set value(value) { - pb_1.Message.setField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoNumber({}); - if (data.value != null) { - message.value = data.value; - } - return message; - } - toObject() { - const data = {}; - if (this.value != null) { - data.value = this.value; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.value != 0) - writer.writeUint64(1, this.value); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoNumber(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.value = reader.readUint64(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoNumber.deserialize(bytes); - } - } - common.ProtoNumber = ProtoNumber; - class ProtoLocations extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("locations" in data && data.locations != undefined) { - this.locations = data.locations; - } - } - } - get locations() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoLocation, 1); - } - set locations(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoLocations({}); - if (data.locations != null) { - message.locations = data.locations.map(item => ProtoLocation.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.locations != null) { - data.locations = this.locations.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.locations.length) - writer.writeRepeatedMessage(1, this.locations, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLocations(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.locations, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoLocation.deserialize(reader), ProtoLocation)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoLocations.deserialize(bytes); - } - } - common.ProtoLocations = ProtoLocations; -})(common || (common = {})); - -/** - * Generated by the protoc-gen-ts. DO NOT EDIT! - * compiler version: 4.25.3 - * source: proto_block.proto - * git: https://github.com/thesayyn/protoc-gen-ts */ -var block; -(function (block) { - class ProtoHeader extends pb_1.Message { - #one_of_decls = [[2], [3], [4], [5], [6], [7], [9], [10], [14], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1, 8, 11, 12, 13, 15], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("parent_hash" in data && data.parent_hash != undefined) { - this.parent_hash = data.parent_hash; - } - if ("uncle_hash" in data && data.uncle_hash != undefined) { - this.uncle_hash = data.uncle_hash; - } - if ("coinbase" in data && data.coinbase != undefined) { - this.coinbase = data.coinbase; - } - if ("evm_root" in data && data.evm_root != undefined) { - this.evm_root = data.evm_root; - } - if ("tx_hash" in data && data.tx_hash != undefined) { - this.tx_hash = data.tx_hash; - } - if ("etx_hash" in data && data.etx_hash != undefined) { - this.etx_hash = data.etx_hash; - } - if ("etx_rollup_hash" in data && data.etx_rollup_hash != undefined) { - this.etx_rollup_hash = data.etx_rollup_hash; - } - if ("manifest_hash" in data && data.manifest_hash != undefined) { - this.manifest_hash = data.manifest_hash; - } - if ("receipt_hash" in data && data.receipt_hash != undefined) { - this.receipt_hash = data.receipt_hash; - } - if ("difficulty" in data && data.difficulty != undefined) { - this.difficulty = data.difficulty; - } - if ("parent_entropy" in data && data.parent_entropy != undefined) { - this.parent_entropy = data.parent_entropy; - } - if ("parent_delta_s" in data && data.parent_delta_s != undefined) { - this.parent_delta_s = data.parent_delta_s; - } - if ("parent_uncled_sub_delta_s" in data && data.parent_uncled_sub_delta_s != undefined) { - this.parent_uncled_sub_delta_s = data.parent_uncled_sub_delta_s; - } - if ("uncled_s" in data && data.uncled_s != undefined) { - this.uncled_s = data.uncled_s; - } - if ("number" in data && data.number != undefined) { - this.number = data.number; - } - if ("gas_limit" in data && data.gas_limit != undefined) { - this.gas_limit = data.gas_limit; - } - if ("gas_used" in data && data.gas_used != undefined) { - this.gas_used = data.gas_used; - } - if ("base_fee" in data && data.base_fee != undefined) { - this.base_fee = data.base_fee; - } - if ("location" in data && data.location != undefined) { - this.location = data.location; - } - if ("extra" in data && data.extra != undefined) { - this.extra = data.extra; - } - if ("mix_hash" in data && data.mix_hash != undefined) { - this.mix_hash = data.mix_hash; - } - if ("nonce" in data && data.nonce != undefined) { - this.nonce = data.nonce; - } - if ("utxo_root" in data && data.utxo_root != undefined) { - this.utxo_root = data.utxo_root; - } - if ("etx_set_hash" in data && data.etx_set_hash != undefined) { - this.etx_set_hash = data.etx_set_hash; - } - if ("efficiency_score" in data && data.efficiency_score != undefined) { - this.efficiency_score = data.efficiency_score; - } - if ("threshold_count" in data && data.threshold_count != undefined) { - this.threshold_count = data.threshold_count; - } - if ("expansion_number" in data && data.expansion_number != undefined) { - this.expansion_number = data.expansion_number; - } - if ("etx_eligible_slices" in data && data.etx_eligible_slices != undefined) { - this.etx_eligible_slices = data.etx_eligible_slices; - } - if ("prime_terminus" in data && data.prime_terminus != undefined) { - this.prime_terminus = data.prime_terminus; - } - if ("interlink_root_hash" in data && data.interlink_root_hash != undefined) { - this.interlink_root_hash = data.interlink_root_hash; - } - } - } - get parent_hash() { - return pb_1.Message.getRepeatedWrapperField(this, common.ProtoHash, 1); - } - set parent_hash(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - get uncle_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 2); - } - set uncle_hash(value) { - pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[0], value); - } - get has_uncle_hash() { - return pb_1.Message.getField(this, 2) != null; - } - get coinbase() { - return pb_1.Message.getFieldWithDefault(this, 3, new Uint8Array(0)); - } - set coinbase(value) { - pb_1.Message.setOneofField(this, 3, this.#one_of_decls[1], value); - } - get has_coinbase() { - return pb_1.Message.getField(this, 3) != null; - } - get evm_root() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 4); - } - set evm_root(value) { - pb_1.Message.setOneofWrapperField(this, 4, this.#one_of_decls[2], value); - } - get has_evm_root() { - return pb_1.Message.getField(this, 4) != null; - } - get tx_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 5); - } - set tx_hash(value) { - pb_1.Message.setOneofWrapperField(this, 5, this.#one_of_decls[3], value); - } - get has_tx_hash() { - return pb_1.Message.getField(this, 5) != null; - } - get etx_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 6); - } - set etx_hash(value) { - pb_1.Message.setOneofWrapperField(this, 6, this.#one_of_decls[4], value); - } - get has_etx_hash() { - return pb_1.Message.getField(this, 6) != null; - } - get etx_rollup_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 7); - } - set etx_rollup_hash(value) { - pb_1.Message.setOneofWrapperField(this, 7, this.#one_of_decls[5], value); - } - get has_etx_rollup_hash() { - return pb_1.Message.getField(this, 7) != null; - } - get manifest_hash() { - return pb_1.Message.getRepeatedWrapperField(this, common.ProtoHash, 8); - } - set manifest_hash(value) { - pb_1.Message.setRepeatedWrapperField(this, 8, value); - } - get receipt_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 9); - } - set receipt_hash(value) { - pb_1.Message.setOneofWrapperField(this, 9, this.#one_of_decls[6], value); - } - get has_receipt_hash() { - return pb_1.Message.getField(this, 9) != null; - } - get difficulty() { - return pb_1.Message.getFieldWithDefault(this, 10, new Uint8Array(0)); - } - set difficulty(value) { - pb_1.Message.setOneofField(this, 10, this.#one_of_decls[7], value); - } - get has_difficulty() { - return pb_1.Message.getField(this, 10) != null; - } - get parent_entropy() { - return pb_1.Message.getFieldWithDefault(this, 11, []); - } - set parent_entropy(value) { - pb_1.Message.setField(this, 11, value); - } - get parent_delta_s() { - return pb_1.Message.getFieldWithDefault(this, 12, []); - } - set parent_delta_s(value) { - pb_1.Message.setField(this, 12, value); - } - get parent_uncled_sub_delta_s() { - return pb_1.Message.getFieldWithDefault(this, 13, []); - } - set parent_uncled_sub_delta_s(value) { - pb_1.Message.setField(this, 13, value); - } - get uncled_s() { - return pb_1.Message.getFieldWithDefault(this, 14, new Uint8Array(0)); - } - set uncled_s(value) { - pb_1.Message.setOneofField(this, 14, this.#one_of_decls[8], value); - } - get has_uncled_s() { - return pb_1.Message.getField(this, 14) != null; - } - get number() { - return pb_1.Message.getFieldWithDefault(this, 15, []); - } - set number(value) { - pb_1.Message.setField(this, 15, value); - } - get gas_limit() { - return pb_1.Message.getFieldWithDefault(this, 16, 0); - } - set gas_limit(value) { - pb_1.Message.setOneofField(this, 16, this.#one_of_decls[9], value); - } - get has_gas_limit() { - return pb_1.Message.getField(this, 16) != null; - } - get gas_used() { - return pb_1.Message.getFieldWithDefault(this, 17, 0); - } - set gas_used(value) { - pb_1.Message.setOneofField(this, 17, this.#one_of_decls[10], value); - } - get has_gas_used() { - return pb_1.Message.getField(this, 17) != null; - } - get base_fee() { - return pb_1.Message.getFieldWithDefault(this, 18, new Uint8Array(0)); - } - set base_fee(value) { - pb_1.Message.setOneofField(this, 18, this.#one_of_decls[11], value); - } - get has_base_fee() { - return pb_1.Message.getField(this, 18) != null; - } - get location() { - return pb_1.Message.getWrapperField(this, common.ProtoLocation, 19); - } - set location(value) { - pb_1.Message.setOneofWrapperField(this, 19, this.#one_of_decls[12], value); - } - get has_location() { - return pb_1.Message.getField(this, 19) != null; - } - get extra() { - return pb_1.Message.getFieldWithDefault(this, 20, new Uint8Array(0)); - } - set extra(value) { - pb_1.Message.setOneofField(this, 20, this.#one_of_decls[13], value); - } - get has_extra() { - return pb_1.Message.getField(this, 20) != null; - } - get mix_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 21); - } - set mix_hash(value) { - pb_1.Message.setOneofWrapperField(this, 21, this.#one_of_decls[14], value); - } - get has_mix_hash() { - return pb_1.Message.getField(this, 21) != null; - } - get nonce() { - return pb_1.Message.getFieldWithDefault(this, 22, 0); - } - set nonce(value) { - pb_1.Message.setOneofField(this, 22, this.#one_of_decls[15], value); - } - get has_nonce() { - return pb_1.Message.getField(this, 22) != null; - } - get utxo_root() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 23); - } - set utxo_root(value) { - pb_1.Message.setOneofWrapperField(this, 23, this.#one_of_decls[16], value); - } - get has_utxo_root() { - return pb_1.Message.getField(this, 23) != null; - } - get etx_set_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 24); - } - set etx_set_hash(value) { - pb_1.Message.setOneofWrapperField(this, 24, this.#one_of_decls[17], value); - } - get has_etx_set_hash() { - return pb_1.Message.getField(this, 24) != null; - } - get efficiency_score() { - return pb_1.Message.getFieldWithDefault(this, 25, 0); - } - set efficiency_score(value) { - pb_1.Message.setOneofField(this, 25, this.#one_of_decls[18], value); - } - get has_efficiency_score() { - return pb_1.Message.getField(this, 25) != null; - } - get threshold_count() { - return pb_1.Message.getFieldWithDefault(this, 26, 0); - } - set threshold_count(value) { - pb_1.Message.setOneofField(this, 26, this.#one_of_decls[19], value); - } - get has_threshold_count() { - return pb_1.Message.getField(this, 26) != null; - } - get expansion_number() { - return pb_1.Message.getFieldWithDefault(this, 27, 0); - } - set expansion_number(value) { - pb_1.Message.setOneofField(this, 27, this.#one_of_decls[20], value); - } - get has_expansion_number() { - return pb_1.Message.getField(this, 27) != null; - } - get etx_eligible_slices() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 28); - } - set etx_eligible_slices(value) { - pb_1.Message.setOneofWrapperField(this, 28, this.#one_of_decls[21], value); - } - get has_etx_eligible_slices() { - return pb_1.Message.getField(this, 28) != null; - } - get prime_terminus() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 29); - } - set prime_terminus(value) { - pb_1.Message.setOneofWrapperField(this, 29, this.#one_of_decls[22], value); - } - get has_prime_terminus() { - return pb_1.Message.getField(this, 29) != null; - } - get interlink_root_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 30); - } - set interlink_root_hash(value) { - pb_1.Message.setOneofWrapperField(this, 30, this.#one_of_decls[23], value); - } - get has_interlink_root_hash() { - return pb_1.Message.getField(this, 30) != null; - } - get _uncle_hash() { - const cases = { - 0: "none", - 2: "uncle_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - get _coinbase() { - const cases = { - 0: "none", - 3: "coinbase" - }; - return cases[pb_1.Message.computeOneofCase(this, [3])]; - } - get _evm_root() { - const cases = { - 0: "none", - 4: "evm_root" - }; - return cases[pb_1.Message.computeOneofCase(this, [4])]; - } - get _tx_hash() { - const cases = { - 0: "none", - 5: "tx_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [5])]; - } - get _etx_hash() { - const cases = { - 0: "none", - 6: "etx_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [6])]; - } - get _etx_rollup_hash() { - const cases = { - 0: "none", - 7: "etx_rollup_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [7])]; - } - get _receipt_hash() { - const cases = { - 0: "none", - 9: "receipt_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [9])]; - } - get _difficulty() { - const cases = { - 0: "none", - 10: "difficulty" - }; - return cases[pb_1.Message.computeOneofCase(this, [10])]; - } - get _uncled_s() { - const cases = { - 0: "none", - 14: "uncled_s" - }; - return cases[pb_1.Message.computeOneofCase(this, [14])]; - } - get _gas_limit() { - const cases = { - 0: "none", - 16: "gas_limit" - }; - return cases[pb_1.Message.computeOneofCase(this, [16])]; - } - get _gas_used() { - const cases = { - 0: "none", - 17: "gas_used" - }; - return cases[pb_1.Message.computeOneofCase(this, [17])]; - } - get _base_fee() { - const cases = { - 0: "none", - 18: "base_fee" - }; - return cases[pb_1.Message.computeOneofCase(this, [18])]; - } - get _location() { - const cases = { - 0: "none", - 19: "location" - }; - return cases[pb_1.Message.computeOneofCase(this, [19])]; - } - get _extra() { - const cases = { - 0: "none", - 20: "extra" - }; - return cases[pb_1.Message.computeOneofCase(this, [20])]; - } - get _mix_hash() { - const cases = { - 0: "none", - 21: "mix_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [21])]; - } - get _nonce() { - const cases = { - 0: "none", - 22: "nonce" - }; - return cases[pb_1.Message.computeOneofCase(this, [22])]; - } - get _utxo_root() { - const cases = { - 0: "none", - 23: "utxo_root" - }; - return cases[pb_1.Message.computeOneofCase(this, [23])]; - } - get _etx_set_hash() { - const cases = { - 0: "none", - 24: "etx_set_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [24])]; - } - get _efficiency_score() { - const cases = { - 0: "none", - 25: "efficiency_score" - }; - return cases[pb_1.Message.computeOneofCase(this, [25])]; - } - get _threshold_count() { - const cases = { - 0: "none", - 26: "threshold_count" - }; - return cases[pb_1.Message.computeOneofCase(this, [26])]; - } - get _expansion_number() { - const cases = { - 0: "none", - 27: "expansion_number" - }; - return cases[pb_1.Message.computeOneofCase(this, [27])]; - } - get _etx_eligible_slices() { - const cases = { - 0: "none", - 28: "etx_eligible_slices" - }; - return cases[pb_1.Message.computeOneofCase(this, [28])]; - } - get _prime_terminus() { - const cases = { - 0: "none", - 29: "prime_terminus" - }; - return cases[pb_1.Message.computeOneofCase(this, [29])]; - } - get _interlink_root_hash() { - const cases = { - 0: "none", - 30: "interlink_root_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [30])]; - } - static fromObject(data) { - const message = new ProtoHeader({}); - if (data.parent_hash != null) { - message.parent_hash = data.parent_hash.map(item => common.ProtoHash.fromObject(item)); - } - if (data.uncle_hash != null) { - message.uncle_hash = common.ProtoHash.fromObject(data.uncle_hash); - } - if (data.coinbase != null) { - message.coinbase = data.coinbase; - } - if (data.evm_root != null) { - message.evm_root = common.ProtoHash.fromObject(data.evm_root); - } - if (data.tx_hash != null) { - message.tx_hash = common.ProtoHash.fromObject(data.tx_hash); - } - if (data.etx_hash != null) { - message.etx_hash = common.ProtoHash.fromObject(data.etx_hash); - } - if (data.etx_rollup_hash != null) { - message.etx_rollup_hash = common.ProtoHash.fromObject(data.etx_rollup_hash); - } - if (data.manifest_hash != null) { - message.manifest_hash = data.manifest_hash.map(item => common.ProtoHash.fromObject(item)); - } - if (data.receipt_hash != null) { - message.receipt_hash = common.ProtoHash.fromObject(data.receipt_hash); - } - if (data.difficulty != null) { - message.difficulty = data.difficulty; - } - if (data.parent_entropy != null) { - message.parent_entropy = data.parent_entropy; - } - if (data.parent_delta_s != null) { - message.parent_delta_s = data.parent_delta_s; - } - if (data.parent_uncled_sub_delta_s != null) { - message.parent_uncled_sub_delta_s = data.parent_uncled_sub_delta_s; - } - if (data.uncled_s != null) { - message.uncled_s = data.uncled_s; - } - if (data.number != null) { - message.number = data.number; - } - if (data.gas_limit != null) { - message.gas_limit = data.gas_limit; - } - if (data.gas_used != null) { - message.gas_used = data.gas_used; - } - if (data.base_fee != null) { - message.base_fee = data.base_fee; - } - if (data.location != null) { - message.location = common.ProtoLocation.fromObject(data.location); - } - if (data.extra != null) { - message.extra = data.extra; - } - if (data.mix_hash != null) { - message.mix_hash = common.ProtoHash.fromObject(data.mix_hash); - } - if (data.nonce != null) { - message.nonce = data.nonce; - } - if (data.utxo_root != null) { - message.utxo_root = common.ProtoHash.fromObject(data.utxo_root); - } - if (data.etx_set_hash != null) { - message.etx_set_hash = common.ProtoHash.fromObject(data.etx_set_hash); - } - if (data.efficiency_score != null) { - message.efficiency_score = data.efficiency_score; - } - if (data.threshold_count != null) { - message.threshold_count = data.threshold_count; - } - if (data.expansion_number != null) { - message.expansion_number = data.expansion_number; - } - if (data.etx_eligible_slices != null) { - message.etx_eligible_slices = common.ProtoHash.fromObject(data.etx_eligible_slices); - } - if (data.prime_terminus != null) { - message.prime_terminus = common.ProtoHash.fromObject(data.prime_terminus); - } - if (data.interlink_root_hash != null) { - message.interlink_root_hash = common.ProtoHash.fromObject(data.interlink_root_hash); - } - return message; - } - toObject() { - const data = {}; - if (this.parent_hash != null) { - data.parent_hash = this.parent_hash.map((item) => item.toObject()); - } - if (this.uncle_hash != null) { - data.uncle_hash = this.uncle_hash.toObject(); - } - if (this.coinbase != null) { - data.coinbase = this.coinbase; - } - if (this.evm_root != null) { - data.evm_root = this.evm_root.toObject(); - } - if (this.tx_hash != null) { - data.tx_hash = this.tx_hash.toObject(); - } - if (this.etx_hash != null) { - data.etx_hash = this.etx_hash.toObject(); - } - if (this.etx_rollup_hash != null) { - data.etx_rollup_hash = this.etx_rollup_hash.toObject(); - } - if (this.manifest_hash != null) { - data.manifest_hash = this.manifest_hash.map((item) => item.toObject()); - } - if (this.receipt_hash != null) { - data.receipt_hash = this.receipt_hash.toObject(); - } - if (this.difficulty != null) { - data.difficulty = this.difficulty; - } - if (this.parent_entropy != null) { - data.parent_entropy = this.parent_entropy; - } - if (this.parent_delta_s != null) { - data.parent_delta_s = this.parent_delta_s; - } - if (this.parent_uncled_sub_delta_s != null) { - data.parent_uncled_sub_delta_s = this.parent_uncled_sub_delta_s; - } - if (this.uncled_s != null) { - data.uncled_s = this.uncled_s; - } - if (this.number != null) { - data.number = this.number; - } - if (this.gas_limit != null) { - data.gas_limit = this.gas_limit; - } - if (this.gas_used != null) { - data.gas_used = this.gas_used; - } - if (this.base_fee != null) { - data.base_fee = this.base_fee; - } - if (this.location != null) { - data.location = this.location.toObject(); - } - if (this.extra != null) { - data.extra = this.extra; - } - if (this.mix_hash != null) { - data.mix_hash = this.mix_hash.toObject(); - } - if (this.nonce != null) { - data.nonce = this.nonce; - } - if (this.utxo_root != null) { - data.utxo_root = this.utxo_root.toObject(); - } - if (this.etx_set_hash != null) { - data.etx_set_hash = this.etx_set_hash.toObject(); - } - if (this.efficiency_score != null) { - data.efficiency_score = this.efficiency_score; - } - if (this.threshold_count != null) { - data.threshold_count = this.threshold_count; - } - if (this.expansion_number != null) { - data.expansion_number = this.expansion_number; - } - if (this.etx_eligible_slices != null) { - data.etx_eligible_slices = this.etx_eligible_slices.toObject(); - } - if (this.prime_terminus != null) { - data.prime_terminus = this.prime_terminus.toObject(); - } - if (this.interlink_root_hash != null) { - data.interlink_root_hash = this.interlink_root_hash.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.parent_hash.length) - writer.writeRepeatedMessage(1, this.parent_hash, (item) => item.serialize(writer)); - if (this.has_uncle_hash) - writer.writeMessage(2, this.uncle_hash, () => this.uncle_hash.serialize(writer)); - if (this.has_coinbase) - writer.writeBytes(3, this.coinbase); - if (this.has_evm_root) - writer.writeMessage(4, this.evm_root, () => this.evm_root.serialize(writer)); - if (this.has_tx_hash) - writer.writeMessage(5, this.tx_hash, () => this.tx_hash.serialize(writer)); - if (this.has_etx_hash) - writer.writeMessage(6, this.etx_hash, () => this.etx_hash.serialize(writer)); - if (this.has_etx_rollup_hash) - writer.writeMessage(7, this.etx_rollup_hash, () => this.etx_rollup_hash.serialize(writer)); - if (this.manifest_hash.length) - writer.writeRepeatedMessage(8, this.manifest_hash, (item) => item.serialize(writer)); - if (this.has_receipt_hash) - writer.writeMessage(9, this.receipt_hash, () => this.receipt_hash.serialize(writer)); - if (this.has_difficulty) - writer.writeBytes(10, this.difficulty); - if (this.parent_entropy.length) - writer.writeRepeatedBytes(11, this.parent_entropy); - if (this.parent_delta_s.length) - writer.writeRepeatedBytes(12, this.parent_delta_s); - if (this.parent_uncled_sub_delta_s.length) - writer.writeRepeatedBytes(13, this.parent_uncled_sub_delta_s); - if (this.has_uncled_s) - writer.writeBytes(14, this.uncled_s); - if (this.number.length) - writer.writeRepeatedBytes(15, this.number); - if (this.has_gas_limit) - writer.writeUint64(16, this.gas_limit); - if (this.has_gas_used) - writer.writeUint64(17, this.gas_used); - if (this.has_base_fee) - writer.writeBytes(18, this.base_fee); - if (this.has_location) - writer.writeMessage(19, this.location, () => this.location.serialize(writer)); - if (this.has_extra) - writer.writeBytes(20, this.extra); - if (this.has_mix_hash) - writer.writeMessage(21, this.mix_hash, () => this.mix_hash.serialize(writer)); - if (this.has_nonce) - writer.writeUint64(22, this.nonce); - if (this.has_utxo_root) - writer.writeMessage(23, this.utxo_root, () => this.utxo_root.serialize(writer)); - if (this.has_etx_set_hash) - writer.writeMessage(24, this.etx_set_hash, () => this.etx_set_hash.serialize(writer)); - if (this.has_efficiency_score) - writer.writeUint64(25, this.efficiency_score); - if (this.has_threshold_count) - writer.writeUint64(26, this.threshold_count); - if (this.has_expansion_number) - writer.writeUint64(27, this.expansion_number); - if (this.has_etx_eligible_slices) - writer.writeMessage(28, this.etx_eligible_slices, () => this.etx_eligible_slices.serialize(writer)); - if (this.has_prime_terminus) - writer.writeMessage(29, this.prime_terminus, () => this.prime_terminus.serialize(writer)); - if (this.has_interlink_root_hash) - writer.writeMessage(30, this.interlink_root_hash, () => this.interlink_root_hash.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHeader(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.parent_hash, () => pb_1.Message.addToRepeatedWrapperField(message, 1, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - case 2: - reader.readMessage(message.uncle_hash, () => message.uncle_hash = common.ProtoHash.deserialize(reader)); - break; - case 3: - message.coinbase = reader.readBytes(); - break; - case 4: - reader.readMessage(message.evm_root, () => message.evm_root = common.ProtoHash.deserialize(reader)); - break; - case 5: - reader.readMessage(message.tx_hash, () => message.tx_hash = common.ProtoHash.deserialize(reader)); - break; - case 6: - reader.readMessage(message.etx_hash, () => message.etx_hash = common.ProtoHash.deserialize(reader)); - break; - case 7: - reader.readMessage(message.etx_rollup_hash, () => message.etx_rollup_hash = common.ProtoHash.deserialize(reader)); - break; - case 8: - reader.readMessage(message.manifest_hash, () => pb_1.Message.addToRepeatedWrapperField(message, 8, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - case 9: - reader.readMessage(message.receipt_hash, () => message.receipt_hash = common.ProtoHash.deserialize(reader)); - break; - case 10: - message.difficulty = reader.readBytes(); - break; - case 11: - pb_1.Message.addToRepeatedField(message, 11, reader.readBytes()); - break; - case 12: - pb_1.Message.addToRepeatedField(message, 12, reader.readBytes()); - break; - case 13: - pb_1.Message.addToRepeatedField(message, 13, reader.readBytes()); - break; - case 14: - message.uncled_s = reader.readBytes(); - break; - case 15: - pb_1.Message.addToRepeatedField(message, 15, reader.readBytes()); - break; - case 16: - message.gas_limit = reader.readUint64(); - break; - case 17: - message.gas_used = reader.readUint64(); - break; - case 18: - message.base_fee = reader.readBytes(); - break; - case 19: - reader.readMessage(message.location, () => message.location = common.ProtoLocation.deserialize(reader)); - break; - case 20: - message.extra = reader.readBytes(); - break; - case 21: - reader.readMessage(message.mix_hash, () => message.mix_hash = common.ProtoHash.deserialize(reader)); - break; - case 22: - message.nonce = reader.readUint64(); - break; - case 23: - reader.readMessage(message.utxo_root, () => message.utxo_root = common.ProtoHash.deserialize(reader)); - break; - case 24: - reader.readMessage(message.etx_set_hash, () => message.etx_set_hash = common.ProtoHash.deserialize(reader)); - break; - case 25: - message.efficiency_score = reader.readUint64(); - break; - case 26: - message.threshold_count = reader.readUint64(); - break; - case 27: - message.expansion_number = reader.readUint64(); - break; - case 28: - reader.readMessage(message.etx_eligible_slices, () => message.etx_eligible_slices = common.ProtoHash.deserialize(reader)); - break; - case 29: - reader.readMessage(message.prime_terminus, () => message.prime_terminus = common.ProtoHash.deserialize(reader)); - break; - case 30: - reader.readMessage(message.interlink_root_hash, () => message.interlink_root_hash = common.ProtoHash.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoHeader.deserialize(bytes); - } - } - block.ProtoHeader = ProtoHeader; - class ProtoTransaction extends pb_1.Message { - #one_of_decls = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("type" in data && data.type != undefined) { - this.type = data.type; - } - if ("to" in data && data.to != undefined) { - this.to = data.to; - } - if ("nonce" in data && data.nonce != undefined) { - this.nonce = data.nonce; - } - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - if ("gas" in data && data.gas != undefined) { - this.gas = data.gas; - } - if ("data" in data && data.data != undefined) { - this.data = data.data; - } - if ("chain_id" in data && data.chain_id != undefined) { - this.chain_id = data.chain_id; - } - if ("gas_fee_cap" in data && data.gas_fee_cap != undefined) { - this.gas_fee_cap = data.gas_fee_cap; - } - if ("gas_tip_cap" in data && data.gas_tip_cap != undefined) { - this.gas_tip_cap = data.gas_tip_cap; - } - if ("access_list" in data && data.access_list != undefined) { - this.access_list = data.access_list; - } - if ("v" in data && data.v != undefined) { - this.v = data.v; - } - if ("r" in data && data.r != undefined) { - this.r = data.r; - } - if ("s" in data && data.s != undefined) { - this.s = data.s; - } - if ("originating_tx_hash" in data && data.originating_tx_hash != undefined) { - this.originating_tx_hash = data.originating_tx_hash; - } - if ("etx_index" in data && data.etx_index != undefined) { - this.etx_index = data.etx_index; - } - if ("tx_ins" in data && data.tx_ins != undefined) { - this.tx_ins = data.tx_ins; - } - if ("tx_outs" in data && data.tx_outs != undefined) { - this.tx_outs = data.tx_outs; - } - if ("signature" in data && data.signature != undefined) { - this.signature = data.signature; - } - if ("etx_sender" in data && data.etx_sender != undefined) { - this.etx_sender = data.etx_sender; - } - } - } - get type() { - return pb_1.Message.getFieldWithDefault(this, 1, 0); - } - set type(value) { - pb_1.Message.setOneofField(this, 1, this.#one_of_decls[0], value); - } - get has_type() { - return pb_1.Message.getField(this, 1) != null; - } - get to() { - return pb_1.Message.getFieldWithDefault(this, 2, new Uint8Array(0)); - } - set to(value) { - pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value); - } - get has_to() { - return pb_1.Message.getField(this, 2) != null; - } - get nonce() { - return pb_1.Message.getFieldWithDefault(this, 3, 0); - } - set nonce(value) { - pb_1.Message.setOneofField(this, 3, this.#one_of_decls[2], value); - } - get has_nonce() { - return pb_1.Message.getField(this, 3) != null; - } - get value() { - return pb_1.Message.getFieldWithDefault(this, 4, new Uint8Array(0)); - } - set value(value) { - pb_1.Message.setOneofField(this, 4, this.#one_of_decls[3], value); - } - get has_value() { - return pb_1.Message.getField(this, 4) != null; - } - get gas() { - return pb_1.Message.getFieldWithDefault(this, 5, 0); - } - set gas(value) { - pb_1.Message.setOneofField(this, 5, this.#one_of_decls[4], value); - } - get has_gas() { - return pb_1.Message.getField(this, 5) != null; - } - get data() { - return pb_1.Message.getFieldWithDefault(this, 6, new Uint8Array(0)); - } - set data(value) { - pb_1.Message.setOneofField(this, 6, this.#one_of_decls[5], value); - } - get has_data() { - return pb_1.Message.getField(this, 6) != null; - } - get chain_id() { - return pb_1.Message.getFieldWithDefault(this, 7, new Uint8Array(0)); - } - set chain_id(value) { - pb_1.Message.setOneofField(this, 7, this.#one_of_decls[6], value); - } - get has_chain_id() { - return pb_1.Message.getField(this, 7) != null; - } - get gas_fee_cap() { - return pb_1.Message.getFieldWithDefault(this, 8, new Uint8Array(0)); - } - set gas_fee_cap(value) { - pb_1.Message.setOneofField(this, 8, this.#one_of_decls[7], value); - } - get has_gas_fee_cap() { - return pb_1.Message.getField(this, 8) != null; - } - get gas_tip_cap() { - return pb_1.Message.getFieldWithDefault(this, 9, new Uint8Array(0)); - } - set gas_tip_cap(value) { - pb_1.Message.setOneofField(this, 9, this.#one_of_decls[8], value); - } - get has_gas_tip_cap() { - return pb_1.Message.getField(this, 9) != null; - } - get access_list() { - return pb_1.Message.getWrapperField(this, ProtoAccessList, 10); - } - set access_list(value) { - pb_1.Message.setOneofWrapperField(this, 10, this.#one_of_decls[9], value); - } - get has_access_list() { - return pb_1.Message.getField(this, 10) != null; - } - get v() { - return pb_1.Message.getFieldWithDefault(this, 11, new Uint8Array(0)); - } - set v(value) { - pb_1.Message.setOneofField(this, 11, this.#one_of_decls[10], value); - } - get has_v() { - return pb_1.Message.getField(this, 11) != null; - } - get r() { - return pb_1.Message.getFieldWithDefault(this, 12, new Uint8Array(0)); - } - set r(value) { - pb_1.Message.setOneofField(this, 12, this.#one_of_decls[11], value); - } - get has_r() { - return pb_1.Message.getField(this, 12) != null; - } - get s() { - return pb_1.Message.getFieldWithDefault(this, 13, new Uint8Array(0)); - } - set s(value) { - pb_1.Message.setOneofField(this, 13, this.#one_of_decls[12], value); - } - get has_s() { - return pb_1.Message.getField(this, 13) != null; - } - get originating_tx_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 14); - } - set originating_tx_hash(value) { - pb_1.Message.setOneofWrapperField(this, 14, this.#one_of_decls[13], value); - } - get has_originating_tx_hash() { - return pb_1.Message.getField(this, 14) != null; - } - get etx_index() { - return pb_1.Message.getFieldWithDefault(this, 15, 0); - } - set etx_index(value) { - pb_1.Message.setOneofField(this, 15, this.#one_of_decls[14], value); - } - get has_etx_index() { - return pb_1.Message.getField(this, 15) != null; - } - get tx_ins() { - return pb_1.Message.getWrapperField(this, ProtoTxIns, 16); - } - set tx_ins(value) { - pb_1.Message.setOneofWrapperField(this, 16, this.#one_of_decls[15], value); - } - get has_tx_ins() { - return pb_1.Message.getField(this, 16) != null; - } - get tx_outs() { - return pb_1.Message.getWrapperField(this, ProtoTxOuts, 17); - } - set tx_outs(value) { - pb_1.Message.setOneofWrapperField(this, 17, this.#one_of_decls[16], value); - } - get has_tx_outs() { - return pb_1.Message.getField(this, 17) != null; - } - get signature() { - return pb_1.Message.getFieldWithDefault(this, 18, new Uint8Array(0)); - } - set signature(value) { - pb_1.Message.setOneofField(this, 18, this.#one_of_decls[17], value); - } - get has_signature() { - return pb_1.Message.getField(this, 18) != null; - } - get etx_sender() { - return pb_1.Message.getFieldWithDefault(this, 19, new Uint8Array(0)); - } - set etx_sender(value) { - pb_1.Message.setOneofField(this, 19, this.#one_of_decls[18], value); - } - get has_etx_sender() { - return pb_1.Message.getField(this, 19) != null; - } - get _type() { - const cases = { - 0: "none", - 1: "type" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _to() { - const cases = { - 0: "none", - 2: "to" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - get _nonce() { - const cases = { - 0: "none", - 3: "nonce" - }; - return cases[pb_1.Message.computeOneofCase(this, [3])]; - } - get _value() { - const cases = { - 0: "none", - 4: "value" - }; - return cases[pb_1.Message.computeOneofCase(this, [4])]; - } - get _gas() { - const cases = { - 0: "none", - 5: "gas" - }; - return cases[pb_1.Message.computeOneofCase(this, [5])]; - } - get _data() { - const cases = { - 0: "none", - 6: "data" - }; - return cases[pb_1.Message.computeOneofCase(this, [6])]; - } - get _chain_id() { - const cases = { - 0: "none", - 7: "chain_id" - }; - return cases[pb_1.Message.computeOneofCase(this, [7])]; - } - get _gas_fee_cap() { - const cases = { - 0: "none", - 8: "gas_fee_cap" - }; - return cases[pb_1.Message.computeOneofCase(this, [8])]; - } - get _gas_tip_cap() { - const cases = { - 0: "none", - 9: "gas_tip_cap" - }; - return cases[pb_1.Message.computeOneofCase(this, [9])]; - } - get _access_list() { - const cases = { - 0: "none", - 10: "access_list" - }; - return cases[pb_1.Message.computeOneofCase(this, [10])]; - } - get _v() { - const cases = { - 0: "none", - 11: "v" - }; - return cases[pb_1.Message.computeOneofCase(this, [11])]; - } - get _r() { - const cases = { - 0: "none", - 12: "r" - }; - return cases[pb_1.Message.computeOneofCase(this, [12])]; - } - get _s() { - const cases = { - 0: "none", - 13: "s" - }; - return cases[pb_1.Message.computeOneofCase(this, [13])]; - } - get _originating_tx_hash() { - const cases = { - 0: "none", - 14: "originating_tx_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [14])]; - } - get _etx_index() { - const cases = { - 0: "none", - 15: "etx_index" - }; - return cases[pb_1.Message.computeOneofCase(this, [15])]; - } - get _tx_ins() { - const cases = { - 0: "none", - 16: "tx_ins" - }; - return cases[pb_1.Message.computeOneofCase(this, [16])]; - } - get _tx_outs() { - const cases = { - 0: "none", - 17: "tx_outs" - }; - return cases[pb_1.Message.computeOneofCase(this, [17])]; - } - get _signature() { - const cases = { - 0: "none", - 18: "signature" - }; - return cases[pb_1.Message.computeOneofCase(this, [18])]; - } - get _etx_sender() { - const cases = { - 0: "none", - 19: "etx_sender" - }; - return cases[pb_1.Message.computeOneofCase(this, [19])]; - } - static fromObject(data) { - const message = new ProtoTransaction({}); - if (data.type != null) { - message.type = data.type; - } - if (data.to != null) { - message.to = data.to; - } - if (data.nonce != null) { - message.nonce = data.nonce; - } - if (data.value != null) { - message.value = data.value; - } - if (data.gas != null) { - message.gas = data.gas; - } - if (data.data != null) { - message.data = data.data; - } - if (data.chain_id != null) { - message.chain_id = data.chain_id; - } - if (data.gas_fee_cap != null) { - message.gas_fee_cap = data.gas_fee_cap; - } - if (data.gas_tip_cap != null) { - message.gas_tip_cap = data.gas_tip_cap; - } - if (data.access_list != null) { - message.access_list = ProtoAccessList.fromObject(data.access_list); - } - if (data.v != null) { - message.v = data.v; - } - if (data.r != null) { - message.r = data.r; - } - if (data.s != null) { - message.s = data.s; - } - if (data.originating_tx_hash != null) { - message.originating_tx_hash = common.ProtoHash.fromObject(data.originating_tx_hash); - } - if (data.etx_index != null) { - message.etx_index = data.etx_index; - } - if (data.tx_ins != null) { - message.tx_ins = ProtoTxIns.fromObject(data.tx_ins); - } - if (data.tx_outs != null) { - message.tx_outs = ProtoTxOuts.fromObject(data.tx_outs); - } - if (data.signature != null) { - message.signature = data.signature; - } - if (data.etx_sender != null) { - message.etx_sender = data.etx_sender; - } - return message; - } - toObject() { - const data = {}; - if (this.type != null) { - data.type = this.type; - } - if (this.to != null) { - data.to = this.to; - } - if (this.nonce != null) { - data.nonce = this.nonce; - } - if (this.value != null) { - data.value = this.value; - } - if (this.gas != null) { - data.gas = this.gas; - } - if (this.data != null) { - data.data = this.data; - } - if (this.chain_id != null) { - data.chain_id = this.chain_id; - } - if (this.gas_fee_cap != null) { - data.gas_fee_cap = this.gas_fee_cap; - } - if (this.gas_tip_cap != null) { - data.gas_tip_cap = this.gas_tip_cap; - } - if (this.access_list != null) { - data.access_list = this.access_list.toObject(); - } - if (this.v != null) { - data.v = this.v; - } - if (this.r != null) { - data.r = this.r; - } - if (this.s != null) { - data.s = this.s; - } - if (this.originating_tx_hash != null) { - data.originating_tx_hash = this.originating_tx_hash.toObject(); - } - if (this.etx_index != null) { - data.etx_index = this.etx_index; - } - if (this.tx_ins != null) { - data.tx_ins = this.tx_ins.toObject(); - } - if (this.tx_outs != null) { - data.tx_outs = this.tx_outs.toObject(); - } - if (this.signature != null) { - data.signature = this.signature; - } - if (this.etx_sender != null) { - data.etx_sender = this.etx_sender; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_type) - writer.writeUint64(1, this.type); - if (this.has_to) - writer.writeBytes(2, this.to); - if (this.has_nonce) - writer.writeUint64(3, this.nonce); - if (this.has_value) - writer.writeBytes(4, this.value); - if (this.has_gas) - writer.writeUint64(5, this.gas); - if (this.has_data) - writer.writeBytes(6, this.data); - if (this.has_chain_id) - writer.writeBytes(7, this.chain_id); - if (this.has_gas_fee_cap) - writer.writeBytes(8, this.gas_fee_cap); - if (this.has_gas_tip_cap) - writer.writeBytes(9, this.gas_tip_cap); - if (this.has_access_list) - writer.writeMessage(10, this.access_list, () => this.access_list.serialize(writer)); - if (this.has_v) - writer.writeBytes(11, this.v); - if (this.has_r) - writer.writeBytes(12, this.r); - if (this.has_s) - writer.writeBytes(13, this.s); - if (this.has_originating_tx_hash) - writer.writeMessage(14, this.originating_tx_hash, () => this.originating_tx_hash.serialize(writer)); - if (this.has_etx_index) - writer.writeUint32(15, this.etx_index); - if (this.has_tx_ins) - writer.writeMessage(16, this.tx_ins, () => this.tx_ins.serialize(writer)); - if (this.has_tx_outs) - writer.writeMessage(17, this.tx_outs, () => this.tx_outs.serialize(writer)); - if (this.has_signature) - writer.writeBytes(18, this.signature); - if (this.has_etx_sender) - writer.writeBytes(19, this.etx_sender); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTransaction(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.type = reader.readUint64(); - break; - case 2: - message.to = reader.readBytes(); - break; - case 3: - message.nonce = reader.readUint64(); - break; - case 4: - message.value = reader.readBytes(); - break; - case 5: - message.gas = reader.readUint64(); - break; - case 6: - message.data = reader.readBytes(); - break; - case 7: - message.chain_id = reader.readBytes(); - break; - case 8: - message.gas_fee_cap = reader.readBytes(); - break; - case 9: - message.gas_tip_cap = reader.readBytes(); - break; - case 10: - reader.readMessage(message.access_list, () => message.access_list = ProtoAccessList.deserialize(reader)); - break; - case 11: - message.v = reader.readBytes(); - break; - case 12: - message.r = reader.readBytes(); - break; - case 13: - message.s = reader.readBytes(); - break; - case 14: - reader.readMessage(message.originating_tx_hash, () => message.originating_tx_hash = common.ProtoHash.deserialize(reader)); - break; - case 15: - message.etx_index = reader.readUint32(); - break; - case 16: - reader.readMessage(message.tx_ins, () => message.tx_ins = ProtoTxIns.deserialize(reader)); - break; - case 17: - reader.readMessage(message.tx_outs, () => message.tx_outs = ProtoTxOuts.deserialize(reader)); - break; - case 18: - message.signature = reader.readBytes(); - break; - case 19: - message.etx_sender = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTransaction.deserialize(bytes); - } - } - block.ProtoTransaction = ProtoTransaction; - class ProtoTransactions extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("transactions" in data && data.transactions != undefined) { - this.transactions = data.transactions; - } - } - } - get transactions() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoTransaction, 1); - } - set transactions(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoTransactions({}); - if (data.transactions != null) { - message.transactions = data.transactions.map(item => ProtoTransaction.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.transactions != null) { - data.transactions = this.transactions.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.transactions.length) - writer.writeRepeatedMessage(1, this.transactions, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTransactions(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.transactions, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoTransaction.deserialize(reader), ProtoTransaction)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTransactions.deserialize(bytes); - } - } - block.ProtoTransactions = ProtoTransactions; - class ProtoHeaders extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("headers" in data && data.headers != undefined) { - this.headers = data.headers; - } - } - } - get headers() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoHeader, 1); - } - set headers(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoHeaders({}); - if (data.headers != null) { - message.headers = data.headers.map(item => ProtoHeader.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.headers != null) { - data.headers = this.headers.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.headers.length) - writer.writeRepeatedMessage(1, this.headers, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHeaders(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.headers, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoHeader.deserialize(reader), ProtoHeader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoHeaders.deserialize(bytes); - } - } - block.ProtoHeaders = ProtoHeaders; - class ProtoManifest extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("manifest" in data && data.manifest != undefined) { - this.manifest = data.manifest; - } - } - } - get manifest() { - return pb_1.Message.getRepeatedWrapperField(this, common.ProtoHash, 1); - } - set manifest(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoManifest({}); - if (data.manifest != null) { - message.manifest = data.manifest.map(item => common.ProtoHash.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.manifest != null) { - data.manifest = this.manifest.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.manifest.length) - writer.writeRepeatedMessage(1, this.manifest, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoManifest(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.manifest, () => pb_1.Message.addToRepeatedWrapperField(message, 1, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoManifest.deserialize(bytes); - } - } - block.ProtoManifest = ProtoManifest; - class ProtoAccessList extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("access_tuples" in data && data.access_tuples != undefined) { - this.access_tuples = data.access_tuples; - } - } - } - get access_tuples() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoAccessTuple, 1); - } - set access_tuples(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoAccessList({}); - if (data.access_tuples != null) { - message.access_tuples = data.access_tuples.map(item => ProtoAccessTuple.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.access_tuples != null) { - data.access_tuples = this.access_tuples.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.access_tuples.length) - writer.writeRepeatedMessage(1, this.access_tuples, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoAccessList(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.access_tuples, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoAccessTuple.deserialize(reader), ProtoAccessTuple)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoAccessList.deserialize(bytes); - } - } - block.ProtoAccessList = ProtoAccessList; - class ProtoWorkObjectHeader extends pb_1.Message { - #one_of_decls = [[1], [2], [3], [4], [5], [6], [7], [8], [9]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("header_hash" in data && data.header_hash != undefined) { - this.header_hash = data.header_hash; - } - if ("parent_hash" in data && data.parent_hash != undefined) { - this.parent_hash = data.parent_hash; - } - if ("number" in data && data.number != undefined) { - this.number = data.number; - } - if ("difficulty" in data && data.difficulty != undefined) { - this.difficulty = data.difficulty; - } - if ("tx_hash" in data && data.tx_hash != undefined) { - this.tx_hash = data.tx_hash; - } - if ("nonce" in data && data.nonce != undefined) { - this.nonce = data.nonce; - } - if ("location" in data && data.location != undefined) { - this.location = data.location; - } - if ("mix_hash" in data && data.mix_hash != undefined) { - this.mix_hash = data.mix_hash; - } - if ("time" in data && data.time != undefined) { - this.time = data.time; - } - } - } - get header_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 1); - } - set header_hash(value) { - pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_header_hash() { - return pb_1.Message.getField(this, 1) != null; - } - get parent_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 2); - } - set parent_hash(value) { - pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_parent_hash() { - return pb_1.Message.getField(this, 2) != null; - } - get number() { - return pb_1.Message.getFieldWithDefault(this, 3, new Uint8Array(0)); - } - set number(value) { - pb_1.Message.setOneofField(this, 3, this.#one_of_decls[2], value); - } - get has_number() { - return pb_1.Message.getField(this, 3) != null; - } - get difficulty() { - return pb_1.Message.getFieldWithDefault(this, 4, new Uint8Array(0)); - } - set difficulty(value) { - pb_1.Message.setOneofField(this, 4, this.#one_of_decls[3], value); - } - get has_difficulty() { - return pb_1.Message.getField(this, 4) != null; - } - get tx_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 5); - } - set tx_hash(value) { - pb_1.Message.setOneofWrapperField(this, 5, this.#one_of_decls[4], value); - } - get has_tx_hash() { - return pb_1.Message.getField(this, 5) != null; - } - get nonce() { - return pb_1.Message.getFieldWithDefault(this, 6, 0); - } - set nonce(value) { - pb_1.Message.setOneofField(this, 6, this.#one_of_decls[5], value); - } - get has_nonce() { - return pb_1.Message.getField(this, 6) != null; - } - get location() { - return pb_1.Message.getWrapperField(this, common.ProtoLocation, 7); - } - set location(value) { - pb_1.Message.setOneofWrapperField(this, 7, this.#one_of_decls[6], value); - } - get has_location() { - return pb_1.Message.getField(this, 7) != null; - } - get mix_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 8); - } - set mix_hash(value) { - pb_1.Message.setOneofWrapperField(this, 8, this.#one_of_decls[7], value); - } - get has_mix_hash() { - return pb_1.Message.getField(this, 8) != null; - } - get time() { - return pb_1.Message.getFieldWithDefault(this, 9, 0); - } - set time(value) { - pb_1.Message.setOneofField(this, 9, this.#one_of_decls[8], value); - } - get has_time() { - return pb_1.Message.getField(this, 9) != null; - } - get _header_hash() { - const cases = { - 0: "none", - 1: "header_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _parent_hash() { - const cases = { - 0: "none", - 2: "parent_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - get _number() { - const cases = { - 0: "none", - 3: "number" - }; - return cases[pb_1.Message.computeOneofCase(this, [3])]; - } - get _difficulty() { - const cases = { - 0: "none", - 4: "difficulty" - }; - return cases[pb_1.Message.computeOneofCase(this, [4])]; - } - get _tx_hash() { - const cases = { - 0: "none", - 5: "tx_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [5])]; - } - get _nonce() { - const cases = { - 0: "none", - 6: "nonce" - }; - return cases[pb_1.Message.computeOneofCase(this, [6])]; - } - get _location() { - const cases = { - 0: "none", - 7: "location" - }; - return cases[pb_1.Message.computeOneofCase(this, [7])]; - } - get _mix_hash() { - const cases = { - 0: "none", - 8: "mix_hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [8])]; - } - get _time() { - const cases = { - 0: "none", - 9: "time" - }; - return cases[pb_1.Message.computeOneofCase(this, [9])]; - } - static fromObject(data) { - const message = new ProtoWorkObjectHeader({}); - if (data.header_hash != null) { - message.header_hash = common.ProtoHash.fromObject(data.header_hash); - } - if (data.parent_hash != null) { - message.parent_hash = common.ProtoHash.fromObject(data.parent_hash); - } - if (data.number != null) { - message.number = data.number; - } - if (data.difficulty != null) { - message.difficulty = data.difficulty; - } - if (data.tx_hash != null) { - message.tx_hash = common.ProtoHash.fromObject(data.tx_hash); - } - if (data.nonce != null) { - message.nonce = data.nonce; - } - if (data.location != null) { - message.location = common.ProtoLocation.fromObject(data.location); - } - if (data.mix_hash != null) { - message.mix_hash = common.ProtoHash.fromObject(data.mix_hash); - } - if (data.time != null) { - message.time = data.time; - } - return message; - } - toObject() { - const data = {}; - if (this.header_hash != null) { - data.header_hash = this.header_hash.toObject(); - } - if (this.parent_hash != null) { - data.parent_hash = this.parent_hash.toObject(); - } - if (this.number != null) { - data.number = this.number; - } - if (this.difficulty != null) { - data.difficulty = this.difficulty; - } - if (this.tx_hash != null) { - data.tx_hash = this.tx_hash.toObject(); - } - if (this.nonce != null) { - data.nonce = this.nonce; - } - if (this.location != null) { - data.location = this.location.toObject(); - } - if (this.mix_hash != null) { - data.mix_hash = this.mix_hash.toObject(); - } - if (this.time != null) { - data.time = this.time; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_header_hash) - writer.writeMessage(1, this.header_hash, () => this.header_hash.serialize(writer)); - if (this.has_parent_hash) - writer.writeMessage(2, this.parent_hash, () => this.parent_hash.serialize(writer)); - if (this.has_number) - writer.writeBytes(3, this.number); - if (this.has_difficulty) - writer.writeBytes(4, this.difficulty); - if (this.has_tx_hash) - writer.writeMessage(5, this.tx_hash, () => this.tx_hash.serialize(writer)); - if (this.has_nonce) - writer.writeUint64(6, this.nonce); - if (this.has_location) - writer.writeMessage(7, this.location, () => this.location.serialize(writer)); - if (this.has_mix_hash) - writer.writeMessage(8, this.mix_hash, () => this.mix_hash.serialize(writer)); - if (this.has_time) - writer.writeUint64(9, this.time); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjectHeader(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.header_hash, () => message.header_hash = common.ProtoHash.deserialize(reader)); - break; - case 2: - reader.readMessage(message.parent_hash, () => message.parent_hash = common.ProtoHash.deserialize(reader)); - break; - case 3: - message.number = reader.readBytes(); - break; - case 4: - message.difficulty = reader.readBytes(); - break; - case 5: - reader.readMessage(message.tx_hash, () => message.tx_hash = common.ProtoHash.deserialize(reader)); - break; - case 6: - message.nonce = reader.readUint64(); - break; - case 7: - reader.readMessage(message.location, () => message.location = common.ProtoLocation.deserialize(reader)); - break; - case 8: - reader.readMessage(message.mix_hash, () => message.mix_hash = common.ProtoHash.deserialize(reader)); - break; - case 9: - message.time = reader.readUint64(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObjectHeader.deserialize(bytes); - } - } - block.ProtoWorkObjectHeader = ProtoWorkObjectHeader; - class ProtoWorkObjectHeaders extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("wo_headers" in data && data.wo_headers != undefined) { - this.wo_headers = data.wo_headers; - } - } - } - get wo_headers() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoWorkObjectHeader, 1); - } - set wo_headers(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoWorkObjectHeaders({}); - if (data.wo_headers != null) { - message.wo_headers = data.wo_headers.map(item => ProtoWorkObjectHeader.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.wo_headers != null) { - data.wo_headers = this.wo_headers.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.wo_headers.length) - writer.writeRepeatedMessage(1, this.wo_headers, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjectHeaders(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.wo_headers, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoWorkObjectHeader.deserialize(reader), ProtoWorkObjectHeader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObjectHeaders.deserialize(bytes); - } - } - block.ProtoWorkObjectHeaders = ProtoWorkObjectHeaders; - class ProtoWorkObjectBody extends pb_1.Message { - #one_of_decls = [[1], [2], [3], [4], [5], [6]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("header" in data && data.header != undefined) { - this.header = data.header; - } - if ("transactions" in data && data.transactions != undefined) { - this.transactions = data.transactions; - } - if ("uncles" in data && data.uncles != undefined) { - this.uncles = data.uncles; - } - if ("ext_transactions" in data && data.ext_transactions != undefined) { - this.ext_transactions = data.ext_transactions; - } - if ("manifest" in data && data.manifest != undefined) { - this.manifest = data.manifest; - } - if ("interlink_hashes" in data && data.interlink_hashes != undefined) { - this.interlink_hashes = data.interlink_hashes; - } - } - } - get header() { - return pb_1.Message.getWrapperField(this, ProtoHeader, 1); - } - set header(value) { - pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_header() { - return pb_1.Message.getField(this, 1) != null; - } - get transactions() { - return pb_1.Message.getWrapperField(this, ProtoTransactions, 2); - } - set transactions(value) { - pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_transactions() { - return pb_1.Message.getField(this, 2) != null; - } - get uncles() { - return pb_1.Message.getWrapperField(this, ProtoWorkObjectHeaders, 3); - } - set uncles(value) { - pb_1.Message.setOneofWrapperField(this, 3, this.#one_of_decls[2], value); - } - get has_uncles() { - return pb_1.Message.getField(this, 3) != null; - } - get ext_transactions() { - return pb_1.Message.getWrapperField(this, ProtoTransactions, 4); - } - set ext_transactions(value) { - pb_1.Message.setOneofWrapperField(this, 4, this.#one_of_decls[3], value); - } - get has_ext_transactions() { - return pb_1.Message.getField(this, 4) != null; - } - get manifest() { - return pb_1.Message.getWrapperField(this, ProtoManifest, 5); - } - set manifest(value) { - pb_1.Message.setOneofWrapperField(this, 5, this.#one_of_decls[4], value); - } - get has_manifest() { - return pb_1.Message.getField(this, 5) != null; - } - get interlink_hashes() { - return pb_1.Message.getWrapperField(this, common.ProtoHashes, 6); - } - set interlink_hashes(value) { - pb_1.Message.setOneofWrapperField(this, 6, this.#one_of_decls[5], value); - } - get has_interlink_hashes() { - return pb_1.Message.getField(this, 6) != null; - } - get _header() { - const cases = { - 0: "none", - 1: "header" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _transactions() { - const cases = { - 0: "none", - 2: "transactions" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - get _uncles() { - const cases = { - 0: "none", - 3: "uncles" - }; - return cases[pb_1.Message.computeOneofCase(this, [3])]; - } - get _ext_transactions() { - const cases = { - 0: "none", - 4: "ext_transactions" - }; - return cases[pb_1.Message.computeOneofCase(this, [4])]; - } - get _manifest() { - const cases = { - 0: "none", - 5: "manifest" - }; - return cases[pb_1.Message.computeOneofCase(this, [5])]; - } - get _interlink_hashes() { - const cases = { - 0: "none", - 6: "interlink_hashes" - }; - return cases[pb_1.Message.computeOneofCase(this, [6])]; - } - static fromObject(data) { - const message = new ProtoWorkObjectBody({}); - if (data.header != null) { - message.header = ProtoHeader.fromObject(data.header); - } - if (data.transactions != null) { - message.transactions = ProtoTransactions.fromObject(data.transactions); - } - if (data.uncles != null) { - message.uncles = ProtoWorkObjectHeaders.fromObject(data.uncles); - } - if (data.ext_transactions != null) { - message.ext_transactions = ProtoTransactions.fromObject(data.ext_transactions); - } - if (data.manifest != null) { - message.manifest = ProtoManifest.fromObject(data.manifest); - } - if (data.interlink_hashes != null) { - message.interlink_hashes = common.ProtoHashes.fromObject(data.interlink_hashes); - } - return message; - } - toObject() { - const data = {}; - if (this.header != null) { - data.header = this.header.toObject(); - } - if (this.transactions != null) { - data.transactions = this.transactions.toObject(); - } - if (this.uncles != null) { - data.uncles = this.uncles.toObject(); - } - if (this.ext_transactions != null) { - data.ext_transactions = this.ext_transactions.toObject(); - } - if (this.manifest != null) { - data.manifest = this.manifest.toObject(); - } - if (this.interlink_hashes != null) { - data.interlink_hashes = this.interlink_hashes.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_header) - writer.writeMessage(1, this.header, () => this.header.serialize(writer)); - if (this.has_transactions) - writer.writeMessage(2, this.transactions, () => this.transactions.serialize(writer)); - if (this.has_uncles) - writer.writeMessage(3, this.uncles, () => this.uncles.serialize(writer)); - if (this.has_ext_transactions) - writer.writeMessage(4, this.ext_transactions, () => this.ext_transactions.serialize(writer)); - if (this.has_manifest) - writer.writeMessage(5, this.manifest, () => this.manifest.serialize(writer)); - if (this.has_interlink_hashes) - writer.writeMessage(6, this.interlink_hashes, () => this.interlink_hashes.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjectBody(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.header, () => message.header = ProtoHeader.deserialize(reader)); - break; - case 2: - reader.readMessage(message.transactions, () => message.transactions = ProtoTransactions.deserialize(reader)); - break; - case 3: - reader.readMessage(message.uncles, () => message.uncles = ProtoWorkObjectHeaders.deserialize(reader)); - break; - case 4: - reader.readMessage(message.ext_transactions, () => message.ext_transactions = ProtoTransactions.deserialize(reader)); - break; - case 5: - reader.readMessage(message.manifest, () => message.manifest = ProtoManifest.deserialize(reader)); - break; - case 6: - reader.readMessage(message.interlink_hashes, () => message.interlink_hashes = common.ProtoHashes.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObjectBody.deserialize(bytes); - } - } - block.ProtoWorkObjectBody = ProtoWorkObjectBody; - class ProtoWorkObject extends pb_1.Message { - #one_of_decls = [[1], [2], [3]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("wo_header" in data && data.wo_header != undefined) { - this.wo_header = data.wo_header; - } - if ("wo_body" in data && data.wo_body != undefined) { - this.wo_body = data.wo_body; - } - if ("tx" in data && data.tx != undefined) { - this.tx = data.tx; - } - } - } - get wo_header() { - return pb_1.Message.getWrapperField(this, ProtoWorkObjectHeader, 1); - } - set wo_header(value) { - pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_wo_header() { - return pb_1.Message.getField(this, 1) != null; - } - get wo_body() { - return pb_1.Message.getWrapperField(this, ProtoWorkObjectBody, 2); - } - set wo_body(value) { - pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_wo_body() { - return pb_1.Message.getField(this, 2) != null; - } - get tx() { - return pb_1.Message.getWrapperField(this, ProtoTransaction, 3); - } - set tx(value) { - pb_1.Message.setOneofWrapperField(this, 3, this.#one_of_decls[2], value); - } - get has_tx() { - return pb_1.Message.getField(this, 3) != null; - } - get _wo_header() { - const cases = { - 0: "none", - 1: "wo_header" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _wo_body() { - const cases = { - 0: "none", - 2: "wo_body" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - get _tx() { - const cases = { - 0: "none", - 3: "tx" - }; - return cases[pb_1.Message.computeOneofCase(this, [3])]; - } - static fromObject(data) { - const message = new ProtoWorkObject({}); - if (data.wo_header != null) { - message.wo_header = ProtoWorkObjectHeader.fromObject(data.wo_header); - } - if (data.wo_body != null) { - message.wo_body = ProtoWorkObjectBody.fromObject(data.wo_body); - } - if (data.tx != null) { - message.tx = ProtoTransaction.fromObject(data.tx); - } - return message; - } - toObject() { - const data = {}; - if (this.wo_header != null) { - data.wo_header = this.wo_header.toObject(); - } - if (this.wo_body != null) { - data.wo_body = this.wo_body.toObject(); - } - if (this.tx != null) { - data.tx = this.tx.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_wo_header) - writer.writeMessage(1, this.wo_header, () => this.wo_header.serialize(writer)); - if (this.has_wo_body) - writer.writeMessage(2, this.wo_body, () => this.wo_body.serialize(writer)); - if (this.has_tx) - writer.writeMessage(3, this.tx, () => this.tx.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObject(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.wo_header, () => message.wo_header = ProtoWorkObjectHeader.deserialize(reader)); - break; - case 2: - reader.readMessage(message.wo_body, () => message.wo_body = ProtoWorkObjectBody.deserialize(reader)); - break; - case 3: - reader.readMessage(message.tx, () => message.tx = ProtoTransaction.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObject.deserialize(bytes); - } - } - block.ProtoWorkObject = ProtoWorkObject; - class ProtoWorkObjects extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("work_objects" in data && data.work_objects != undefined) { - this.work_objects = data.work_objects; - } - } - } - get work_objects() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoWorkObject, 1); - } - set work_objects(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoWorkObjects({}); - if (data.work_objects != null) { - message.work_objects = data.work_objects.map(item => ProtoWorkObject.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.work_objects != null) { - data.work_objects = this.work_objects.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.work_objects.length) - writer.writeRepeatedMessage(1, this.work_objects, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjects(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.work_objects, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoWorkObject.deserialize(reader), ProtoWorkObject)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObjects.deserialize(bytes); - } - } - block.ProtoWorkObjects = ProtoWorkObjects; - class ProtoAccessTuple extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("address" in data && data.address != undefined) { - this.address = data.address; - } - if ("storage_key" in data && data.storage_key != undefined) { - this.storage_key = data.storage_key; - } - } - } - get address() { - return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set address(value) { - pb_1.Message.setField(this, 1, value); - } - get storage_key() { - return pb_1.Message.getRepeatedWrapperField(this, common.ProtoHash, 2); - } - set storage_key(value) { - pb_1.Message.setRepeatedWrapperField(this, 2, value); - } - static fromObject(data) { - const message = new ProtoAccessTuple({}); - if (data.address != null) { - message.address = data.address; - } - if (data.storage_key != null) { - message.storage_key = data.storage_key.map(item => common.ProtoHash.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.address != null) { - data.address = this.address; - } - if (this.storage_key != null) { - data.storage_key = this.storage_key.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.address.length) - writer.writeBytes(1, this.address); - if (this.storage_key.length) - writer.writeRepeatedMessage(2, this.storage_key, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoAccessTuple(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.address = reader.readBytes(); - break; - case 2: - reader.readMessage(message.storage_key, () => pb_1.Message.addToRepeatedWrapperField(message, 2, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoAccessTuple.deserialize(bytes); - } - } - block.ProtoAccessTuple = ProtoAccessTuple; - class ProtoReceiptForStorage extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("post_state_or_status" in data && data.post_state_or_status != undefined) { - this.post_state_or_status = data.post_state_or_status; - } - if ("cumulative_gas_used" in data && data.cumulative_gas_used != undefined) { - this.cumulative_gas_used = data.cumulative_gas_used; - } - if ("tx_hash" in data && data.tx_hash != undefined) { - this.tx_hash = data.tx_hash; - } - if ("contract_address" in data && data.contract_address != undefined) { - this.contract_address = data.contract_address; - } - if ("logs" in data && data.logs != undefined) { - this.logs = data.logs; - } - if ("etxs" in data && data.etxs != undefined) { - this.etxs = data.etxs; - } - if ("gas_used" in data && data.gas_used != undefined) { - this.gas_used = data.gas_used; - } - } - } - get post_state_or_status() { - return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set post_state_or_status(value) { - pb_1.Message.setField(this, 1, value); - } - get cumulative_gas_used() { - return pb_1.Message.getFieldWithDefault(this, 2, 0); - } - set cumulative_gas_used(value) { - pb_1.Message.setField(this, 2, value); - } - get tx_hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 3); - } - set tx_hash(value) { - pb_1.Message.setWrapperField(this, 3, value); - } - get has_tx_hash() { - return pb_1.Message.getField(this, 3) != null; - } - get contract_address() { - return pb_1.Message.getWrapperField(this, common.ProtoAddress, 4); - } - set contract_address(value) { - pb_1.Message.setWrapperField(this, 4, value); - } - get has_contract_address() { - return pb_1.Message.getField(this, 4) != null; - } - get logs() { - return pb_1.Message.getWrapperField(this, ProtoLogsForStorage, 5); - } - set logs(value) { - pb_1.Message.setWrapperField(this, 5, value); - } - get has_logs() { - return pb_1.Message.getField(this, 5) != null; - } - get etxs() { - return pb_1.Message.getWrapperField(this, ProtoTransactions, 6); - } - set etxs(value) { - pb_1.Message.setWrapperField(this, 6, value); - } - get has_etxs() { - return pb_1.Message.getField(this, 6) != null; - } - get gas_used() { - return pb_1.Message.getFieldWithDefault(this, 7, 0); - } - set gas_used(value) { - pb_1.Message.setField(this, 7, value); - } - static fromObject(data) { - const message = new ProtoReceiptForStorage({}); - if (data.post_state_or_status != null) { - message.post_state_or_status = data.post_state_or_status; - } - if (data.cumulative_gas_used != null) { - message.cumulative_gas_used = data.cumulative_gas_used; - } - if (data.tx_hash != null) { - message.tx_hash = common.ProtoHash.fromObject(data.tx_hash); - } - if (data.contract_address != null) { - message.contract_address = common.ProtoAddress.fromObject(data.contract_address); - } - if (data.logs != null) { - message.logs = ProtoLogsForStorage.fromObject(data.logs); - } - if (data.etxs != null) { - message.etxs = ProtoTransactions.fromObject(data.etxs); - } - if (data.gas_used != null) { - message.gas_used = data.gas_used; - } - return message; - } - toObject() { - const data = {}; - if (this.post_state_or_status != null) { - data.post_state_or_status = this.post_state_or_status; - } - if (this.cumulative_gas_used != null) { - data.cumulative_gas_used = this.cumulative_gas_used; - } - if (this.tx_hash != null) { - data.tx_hash = this.tx_hash.toObject(); - } - if (this.contract_address != null) { - data.contract_address = this.contract_address.toObject(); - } - if (this.logs != null) { - data.logs = this.logs.toObject(); - } - if (this.etxs != null) { - data.etxs = this.etxs.toObject(); - } - if (this.gas_used != null) { - data.gas_used = this.gas_used; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.post_state_or_status.length) - writer.writeBytes(1, this.post_state_or_status); - if (this.cumulative_gas_used != 0) - writer.writeUint64(2, this.cumulative_gas_used); - if (this.has_tx_hash) - writer.writeMessage(3, this.tx_hash, () => this.tx_hash.serialize(writer)); - if (this.has_contract_address) - writer.writeMessage(4, this.contract_address, () => this.contract_address.serialize(writer)); - if (this.has_logs) - writer.writeMessage(5, this.logs, () => this.logs.serialize(writer)); - if (this.has_etxs) - writer.writeMessage(6, this.etxs, () => this.etxs.serialize(writer)); - if (this.gas_used != 0) - writer.writeUint64(7, this.gas_used); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoReceiptForStorage(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.post_state_or_status = reader.readBytes(); - break; - case 2: - message.cumulative_gas_used = reader.readUint64(); - break; - case 3: - reader.readMessage(message.tx_hash, () => message.tx_hash = common.ProtoHash.deserialize(reader)); - break; - case 4: - reader.readMessage(message.contract_address, () => message.contract_address = common.ProtoAddress.deserialize(reader)); - break; - case 5: - reader.readMessage(message.logs, () => message.logs = ProtoLogsForStorage.deserialize(reader)); - break; - case 6: - reader.readMessage(message.etxs, () => message.etxs = ProtoTransactions.deserialize(reader)); - break; - case 7: - message.gas_used = reader.readUint64(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoReceiptForStorage.deserialize(bytes); - } - } - block.ProtoReceiptForStorage = ProtoReceiptForStorage; - class ProtoReceiptsForStorage extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("receipts" in data && data.receipts != undefined) { - this.receipts = data.receipts; - } - } - } - get receipts() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoReceiptForStorage, 1); - } - set receipts(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoReceiptsForStorage({}); - if (data.receipts != null) { - message.receipts = data.receipts.map(item => ProtoReceiptForStorage.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.receipts != null) { - data.receipts = this.receipts.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.receipts.length) - writer.writeRepeatedMessage(1, this.receipts, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoReceiptsForStorage(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.receipts, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoReceiptForStorage.deserialize(reader), ProtoReceiptForStorage)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoReceiptsForStorage.deserialize(bytes); - } - } - block.ProtoReceiptsForStorage = ProtoReceiptsForStorage; - class ProtoLogForStorage extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("address" in data && data.address != undefined) { - this.address = data.address; - } - if ("topics" in data && data.topics != undefined) { - this.topics = data.topics; - } - if ("data" in data && data.data != undefined) { - this.data = data.data; - } - } - } - get address() { - return pb_1.Message.getWrapperField(this, common.ProtoAddress, 1); - } - set address(value) { - pb_1.Message.setWrapperField(this, 1, value); - } - get has_address() { - return pb_1.Message.getField(this, 1) != null; - } - get topics() { - return pb_1.Message.getRepeatedWrapperField(this, common.ProtoHash, 2); - } - set topics(value) { - pb_1.Message.setRepeatedWrapperField(this, 2, value); - } - get data() { - return pb_1.Message.getFieldWithDefault(this, 3, new Uint8Array(0)); - } - set data(value) { - pb_1.Message.setField(this, 3, value); - } - static fromObject(data) { - const message = new ProtoLogForStorage({}); - if (data.address != null) { - message.address = common.ProtoAddress.fromObject(data.address); - } - if (data.topics != null) { - message.topics = data.topics.map(item => common.ProtoHash.fromObject(item)); - } - if (data.data != null) { - message.data = data.data; - } - return message; - } - toObject() { - const data = {}; - if (this.address != null) { - data.address = this.address.toObject(); - } - if (this.topics != null) { - data.topics = this.topics.map((item) => item.toObject()); - } - if (this.data != null) { - data.data = this.data; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_address) - writer.writeMessage(1, this.address, () => this.address.serialize(writer)); - if (this.topics.length) - writer.writeRepeatedMessage(2, this.topics, (item) => item.serialize(writer)); - if (this.data.length) - writer.writeBytes(3, this.data); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLogForStorage(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.address, () => message.address = common.ProtoAddress.deserialize(reader)); - break; - case 2: - reader.readMessage(message.topics, () => pb_1.Message.addToRepeatedWrapperField(message, 2, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - case 3: - message.data = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoLogForStorage.deserialize(bytes); - } - } - block.ProtoLogForStorage = ProtoLogForStorage; - class ProtoLogsForStorage extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("logs" in data && data.logs != undefined) { - this.logs = data.logs; - } - } - } - get logs() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoLogForStorage, 1); - } - set logs(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoLogsForStorage({}); - if (data.logs != null) { - message.logs = data.logs.map(item => ProtoLogForStorage.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.logs != null) { - data.logs = this.logs.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.logs.length) - writer.writeRepeatedMessage(1, this.logs, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLogsForStorage(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.logs, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoLogForStorage.deserialize(reader), ProtoLogForStorage)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoLogsForStorage.deserialize(bytes); - } - } - block.ProtoLogsForStorage = ProtoLogsForStorage; - class ProtoPendingHeader extends pb_1.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("wo" in data && data.wo != undefined) { - this.wo = data.wo; - } - if ("termini" in data && data.termini != undefined) { - this.termini = data.termini; - } - } - } - get wo() { - return pb_1.Message.getWrapperField(this, ProtoWorkObject, 1); - } - set wo(value) { - pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_wo() { - return pb_1.Message.getField(this, 1) != null; - } - get termini() { - return pb_1.Message.getWrapperField(this, ProtoTermini, 2); - } - set termini(value) { - pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_termini() { - return pb_1.Message.getField(this, 2) != null; - } - get _wo() { - const cases = { - 0: "none", - 1: "wo" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _termini() { - const cases = { - 0: "none", - 2: "termini" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoPendingHeader({}); - if (data.wo != null) { - message.wo = ProtoWorkObject.fromObject(data.wo); - } - if (data.termini != null) { - message.termini = ProtoTermini.fromObject(data.termini); - } - return message; - } - toObject() { - const data = {}; - if (this.wo != null) { - data.wo = this.wo.toObject(); - } - if (this.termini != null) { - data.termini = this.termini.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_wo) - writer.writeMessage(1, this.wo, () => this.wo.serialize(writer)); - if (this.has_termini) - writer.writeMessage(2, this.termini, () => this.termini.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoPendingHeader(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.wo, () => message.wo = ProtoWorkObject.deserialize(reader)); - break; - case 2: - reader.readMessage(message.termini, () => message.termini = ProtoTermini.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoPendingHeader.deserialize(bytes); - } - } - block.ProtoPendingHeader = ProtoPendingHeader; - class ProtoTermini extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1, 2], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("dom_termini" in data && data.dom_termini != undefined) { - this.dom_termini = data.dom_termini; - } - if ("sub_termini" in data && data.sub_termini != undefined) { - this.sub_termini = data.sub_termini; - } - } - } - get dom_termini() { - return pb_1.Message.getRepeatedWrapperField(this, common.ProtoHash, 1); - } - set dom_termini(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - get sub_termini() { - return pb_1.Message.getRepeatedWrapperField(this, common.ProtoHash, 2); - } - set sub_termini(value) { - pb_1.Message.setRepeatedWrapperField(this, 2, value); - } - static fromObject(data) { - const message = new ProtoTermini({}); - if (data.dom_termini != null) { - message.dom_termini = data.dom_termini.map(item => common.ProtoHash.fromObject(item)); - } - if (data.sub_termini != null) { - message.sub_termini = data.sub_termini.map(item => common.ProtoHash.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.dom_termini != null) { - data.dom_termini = this.dom_termini.map((item) => item.toObject()); - } - if (this.sub_termini != null) { - data.sub_termini = this.sub_termini.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.dom_termini.length) - writer.writeRepeatedMessage(1, this.dom_termini, (item) => item.serialize(writer)); - if (this.sub_termini.length) - writer.writeRepeatedMessage(2, this.sub_termini, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTermini(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.dom_termini, () => pb_1.Message.addToRepeatedWrapperField(message, 1, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - case 2: - reader.readMessage(message.sub_termini, () => pb_1.Message.addToRepeatedWrapperField(message, 2, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTermini.deserialize(bytes); - } - } - block.ProtoTermini = ProtoTermini; - class ProtoEtxSet extends pb_1.Message { - #one_of_decls = [[1]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("etx_hashes" in data && data.etx_hashes != undefined) { - this.etx_hashes = data.etx_hashes; - } - } - } - get etx_hashes() { - return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set etx_hashes(value) { - pb_1.Message.setOneofField(this, 1, this.#one_of_decls[0], value); - } - get has_etx_hashes() { - return pb_1.Message.getField(this, 1) != null; - } - get _etx_hashes() { - const cases = { - 0: "none", - 1: "etx_hashes" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - static fromObject(data) { - const message = new ProtoEtxSet({}); - if (data.etx_hashes != null) { - message.etx_hashes = data.etx_hashes; - } - return message; - } - toObject() { - const data = {}; - if (this.etx_hashes != null) { - data.etx_hashes = this.etx_hashes; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_etx_hashes) - writer.writeBytes(1, this.etx_hashes); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoEtxSet(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.etx_hashes = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoEtxSet.deserialize(bytes); - } - } - block.ProtoEtxSet = ProtoEtxSet; - class ProtoPendingEtxs extends pb_1.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("header" in data && data.header != undefined) { - this.header = data.header; - } - if ("etxs" in data && data.etxs != undefined) { - this.etxs = data.etxs; - } - } - } - get header() { - return pb_1.Message.getWrapperField(this, ProtoWorkObject, 1); - } - set header(value) { - pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_header() { - return pb_1.Message.getField(this, 1) != null; - } - get etxs() { - return pb_1.Message.getWrapperField(this, ProtoTransactions, 2); - } - set etxs(value) { - pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_etxs() { - return pb_1.Message.getField(this, 2) != null; - } - get _header() { - const cases = { - 0: "none", - 1: "header" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _etxs() { - const cases = { - 0: "none", - 2: "etxs" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoPendingEtxs({}); - if (data.header != null) { - message.header = ProtoWorkObject.fromObject(data.header); - } - if (data.etxs != null) { - message.etxs = ProtoTransactions.fromObject(data.etxs); - } - return message; - } - toObject() { - const data = {}; - if (this.header != null) { - data.header = this.header.toObject(); - } - if (this.etxs != null) { - data.etxs = this.etxs.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_header) - writer.writeMessage(1, this.header, () => this.header.serialize(writer)); - if (this.has_etxs) - writer.writeMessage(2, this.etxs, () => this.etxs.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoPendingEtxs(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.header, () => message.header = ProtoWorkObject.deserialize(reader)); - break; - case 2: - reader.readMessage(message.etxs, () => message.etxs = ProtoTransactions.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoPendingEtxs.deserialize(bytes); - } - } - block.ProtoPendingEtxs = ProtoPendingEtxs; - class ProtoPendingEtxsRollup extends pb_1.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("header" in data && data.header != undefined) { - this.header = data.header; - } - if ("etxs_rollup" in data && data.etxs_rollup != undefined) { - this.etxs_rollup = data.etxs_rollup; - } - } - } - get header() { - return pb_1.Message.getWrapperField(this, ProtoWorkObject, 1); - } - set header(value) { - pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_header() { - return pb_1.Message.getField(this, 1) != null; - } - get etxs_rollup() { - return pb_1.Message.getWrapperField(this, ProtoTransactions, 2); - } - set etxs_rollup(value) { - pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_etxs_rollup() { - return pb_1.Message.getField(this, 2) != null; - } - get _header() { - const cases = { - 0: "none", - 1: "header" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _etxs_rollup() { - const cases = { - 0: "none", - 2: "etxs_rollup" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoPendingEtxsRollup({}); - if (data.header != null) { - message.header = ProtoWorkObject.fromObject(data.header); - } - if (data.etxs_rollup != null) { - message.etxs_rollup = ProtoTransactions.fromObject(data.etxs_rollup); - } - return message; - } - toObject() { - const data = {}; - if (this.header != null) { - data.header = this.header.toObject(); - } - if (this.etxs_rollup != null) { - data.etxs_rollup = this.etxs_rollup.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_header) - writer.writeMessage(1, this.header, () => this.header.serialize(writer)); - if (this.has_etxs_rollup) - writer.writeMessage(2, this.etxs_rollup, () => this.etxs_rollup.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoPendingEtxsRollup(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.header, () => message.header = ProtoWorkObject.deserialize(reader)); - break; - case 2: - reader.readMessage(message.etxs_rollup, () => message.etxs_rollup = ProtoTransactions.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoPendingEtxsRollup.deserialize(bytes); - } - } - block.ProtoPendingEtxsRollup = ProtoPendingEtxsRollup; - class ProtoTxIns extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("tx_ins" in data && data.tx_ins != undefined) { - this.tx_ins = data.tx_ins; - } - } - } - get tx_ins() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoTxIn, 1); - } - set tx_ins(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoTxIns({}); - if (data.tx_ins != null) { - message.tx_ins = data.tx_ins.map(item => ProtoTxIn.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.tx_ins != null) { - data.tx_ins = this.tx_ins.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.tx_ins.length) - writer.writeRepeatedMessage(1, this.tx_ins, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxIns(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.tx_ins, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoTxIn.deserialize(reader), ProtoTxIn)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTxIns.deserialize(bytes); - } - } - block.ProtoTxIns = ProtoTxIns; - class ProtoTxOuts extends pb_1.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("tx_outs" in data && data.tx_outs != undefined) { - this.tx_outs = data.tx_outs; - } - } - } - get tx_outs() { - return pb_1.Message.getRepeatedWrapperField(this, ProtoTxOut, 1); - } - set tx_outs(value) { - pb_1.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoTxOuts({}); - if (data.tx_outs != null) { - message.tx_outs = data.tx_outs.map(item => ProtoTxOut.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.tx_outs != null) { - data.tx_outs = this.tx_outs.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.tx_outs.length) - writer.writeRepeatedMessage(1, this.tx_outs, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxOuts(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.tx_outs, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoTxOut.deserialize(reader), ProtoTxOut)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTxOuts.deserialize(bytes); - } - } - block.ProtoTxOuts = ProtoTxOuts; - class ProtoTxIn extends pb_1.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("previous_out_point" in data && data.previous_out_point != undefined) { - this.previous_out_point = data.previous_out_point; - } - if ("pub_key" in data && data.pub_key != undefined) { - this.pub_key = data.pub_key; - } - } - } - get previous_out_point() { - return pb_1.Message.getWrapperField(this, ProtoOutPoint, 1); - } - set previous_out_point(value) { - pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_previous_out_point() { - return pb_1.Message.getField(this, 1) != null; - } - get pub_key() { - return pb_1.Message.getFieldWithDefault(this, 2, new Uint8Array(0)); - } - set pub_key(value) { - pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value); - } - get has_pub_key() { - return pb_1.Message.getField(this, 2) != null; - } - get _previous_out_point() { - const cases = { - 0: "none", - 1: "previous_out_point" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _pub_key() { - const cases = { - 0: "none", - 2: "pub_key" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoTxIn({}); - if (data.previous_out_point != null) { - message.previous_out_point = ProtoOutPoint.fromObject(data.previous_out_point); - } - if (data.pub_key != null) { - message.pub_key = data.pub_key; - } - return message; - } - toObject() { - const data = {}; - if (this.previous_out_point != null) { - data.previous_out_point = this.previous_out_point.toObject(); - } - if (this.pub_key != null) { - data.pub_key = this.pub_key; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_previous_out_point) - writer.writeMessage(1, this.previous_out_point, () => this.previous_out_point.serialize(writer)); - if (this.has_pub_key) - writer.writeBytes(2, this.pub_key); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxIn(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.previous_out_point, () => message.previous_out_point = ProtoOutPoint.deserialize(reader)); - break; - case 2: - message.pub_key = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTxIn.deserialize(bytes); - } - } - block.ProtoTxIn = ProtoTxIn; - class ProtoOutPoint extends pb_1.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("hash" in data && data.hash != undefined) { - this.hash = data.hash; - } - if ("index" in data && data.index != undefined) { - this.index = data.index; - } - } - } - get hash() { - return pb_1.Message.getWrapperField(this, common.ProtoHash, 1); - } - set hash(value) { - pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_hash() { - return pb_1.Message.getField(this, 1) != null; - } - get index() { - return pb_1.Message.getFieldWithDefault(this, 2, 0); - } - set index(value) { - pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value); - } - get has_index() { - return pb_1.Message.getField(this, 2) != null; - } - get _hash() { - const cases = { - 0: "none", - 1: "hash" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _index() { - const cases = { - 0: "none", - 2: "index" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoOutPoint({}); - if (data.hash != null) { - message.hash = common.ProtoHash.fromObject(data.hash); - } - if (data.index != null) { - message.index = data.index; - } - return message; - } - toObject() { - const data = {}; - if (this.hash != null) { - data.hash = this.hash.toObject(); - } - if (this.index != null) { - data.index = this.index; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_hash) - writer.writeMessage(1, this.hash, () => this.hash.serialize(writer)); - if (this.has_index) - writer.writeUint32(2, this.index); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoOutPoint(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.hash, () => message.hash = common.ProtoHash.deserialize(reader)); - break; - case 2: - message.index = reader.readUint32(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoOutPoint.deserialize(bytes); - } - } - block.ProtoOutPoint = ProtoOutPoint; - class ProtoTxOut extends pb_1.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("denomination" in data && data.denomination != undefined) { - this.denomination = data.denomination; - } - if ("address" in data && data.address != undefined) { - this.address = data.address; - } - } - } - get denomination() { - return pb_1.Message.getFieldWithDefault(this, 1, 0); - } - set denomination(value) { - pb_1.Message.setOneofField(this, 1, this.#one_of_decls[0], value); - } - get has_denomination() { - return pb_1.Message.getField(this, 1) != null; - } - get address() { - return pb_1.Message.getFieldWithDefault(this, 2, new Uint8Array(0)); - } - set address(value) { - pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value); - } - get has_address() { - return pb_1.Message.getField(this, 2) != null; - } - get _denomination() { - const cases = { - 0: "none", - 1: "denomination" - }; - return cases[pb_1.Message.computeOneofCase(this, [1])]; - } - get _address() { - const cases = { - 0: "none", - 2: "address" - }; - return cases[pb_1.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoTxOut({}); - if (data.denomination != null) { - message.denomination = data.denomination; - } - if (data.address != null) { - message.address = data.address; - } - return message; - } - toObject() { - const data = {}; - if (this.denomination != null) { - data.denomination = this.denomination; - } - if (this.address != null) { - data.address = this.address; - } - return data; - } - serialize(w) { - const writer = w || new pb_1.BinaryWriter(); - if (this.has_denomination) - writer.writeUint32(1, this.denomination); - if (this.has_address) - writer.writeBytes(2, this.address); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxOut(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.denomination = reader.readUint32(); - break; - case 2: - message.address = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTxOut.deserialize(bytes); - } - } - block.ProtoTxOut = ProtoTxOut; -})(block || (block = {})); - -/** - * @category Encoding - * @param {ProtoTransaction} protoTx - The signed constructed transaction - * @returns {string} - The Protobuf encoded transaction - */ -function encodeProtoTransaction(protoTx) { - const tx = block.ProtoTransaction.fromObject(protoTx); - return hexlify(tx.serialize()); -} - -/** - * @category Encoding - * @param {Uint8Array} bytes - The Protobuf encoded transaction - * @returns {ProtoTransaction} - The decoded transaction - */ -function decodeProtoTransaction(bytes) { - const tx = block.ProtoTransaction.deserialize(bytes); - const result = tx.toObject(); - if (result.to?.length == 0) { - result.to = null; - } - return result; -} - -/** - * Using strings in Ethereum (or any security-basd system) requires additional care. These utilities attempt to mitigate - * some of the safety issues as well as provide the ability to recover and analyse strings. - * - * @subsection api/utils:Strings and UTF-8 [about-strings] - */ -// `output` and `badCodepoint` are passed to calls below, but not used in the function -function errorFunc(reason, offset, bytes, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -output, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -badCodepoint) { - assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, 'bytes', bytes); -} -// `output` and `badCodepoint` are passed to calls below, but not used in the function -function ignoreFunc(reason, offset, bytes, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -output, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -badCodepoint) { - // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes - if (reason === 'BAD_PREFIX' || reason === 'UNEXPECTED_CONTINUE') { - let i = 0; - for (let o = offset + 1; o < bytes.length; o++) { - if (bytes[o] >> 6 !== 0x02) { - break; - } - i++; - } - return i; - } - // This byte runs us past the end of the string, so just jump to the end - // (but the first byte was read already read and therefore skipped) - if (reason === 'OVERRUN') { - return bytes.length - offset - 1; - } - // Nothing to skip - return 0; -} -function replaceFunc(reason, offset, bytes, output, badCodepoint) { - // Overlong representations are otherwise "valid" code points; just non-deistingtished - if (reason === 'OVERLONG') { - assertArgument(typeof badCodepoint === 'number', 'invalid bad code point for replacement', 'badCodepoint', badCodepoint); - output.push(badCodepoint); - return 0; - } - // Put the replacement character into the output - output.push(0xfffd); - // Otherwise, process as if ignoring errors - return ignoreFunc(reason, offset, bytes); -} -/** - * A handful of popular, built-in UTF-8 error handling strategies. - * - * **`"error"`** - throws on ANY illegal UTF-8 sequence or non-canonical (overlong) codepoints (this is the default) - * - * **`"ignore"`** - silently drops any illegal UTF-8 sequence and accepts non-canonical (overlong) codepoints - * - * **`"replace"`** - replace any illegal UTF-8 sequence with the UTF-8 replacement character (i.e. `"\\ufffd"`) and - * accepts non-canonical (overlong) codepoints - * - * @category Encoding - * @returns Record<"error" | "ignore" | "replace", Utf8ErrorFunc> - */ -const Utf8ErrorFuncs = Object.freeze({ - error: errorFunc, - ignore: ignoreFunc, - replace: replaceFunc, -}); -// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 -function getUtf8CodePoints(_bytes, onError) { - if (onError == null) { - onError = Utf8ErrorFuncs.error; - } - const bytes = getBytes(_bytes, 'bytes'); - const result = []; - let i = 0; - // Invalid bytes are ignored - while (i < bytes.length) { - const c = bytes[i++]; - // 0xxx xxxx - if (c >> 7 === 0) { - result.push(c); - continue; - } - // Multibyte; how many bytes left for this character? - let extraLength = null; - let overlongMask = null; - // 110x xxxx 10xx xxxx - if ((c & 0xe0) === 0xc0) { - extraLength = 1; - overlongMask = 0x7f; - // 1110 xxxx 10xx xxxx 10xx xxxx - } - else if ((c & 0xf0) === 0xe0) { - extraLength = 2; - overlongMask = 0x7ff; - // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx - } - else if ((c & 0xf8) === 0xf0) { - extraLength = 3; - overlongMask = 0xffff; - } - else { - if ((c & 0xc0) === 0x80) { - i += onError('UNEXPECTED_CONTINUE', i - 1, bytes, result); - } - else { - i += onError('BAD_PREFIX', i - 1, bytes, result); - } - continue; - } - // Do we have enough bytes in our data? - if (i - 1 + extraLength >= bytes.length) { - i += onError('OVERRUN', i - 1, bytes, result); - continue; - } - // Remove the length prefix from the char - let res = c & ((1 << (8 - extraLength - 1)) - 1); - for (let j = 0; j < extraLength; j++) { - const nextChar = bytes[i]; - // Invalid continuation byte - if ((nextChar & 0xc0) != 0x80) { - i += onError('MISSING_CONTINUE', i, bytes, result); - res = null; - break; - } - res = (res << 6) | (nextChar & 0x3f); - i++; - } - // See above loop for invalid continuation byte - if (res === null) { - continue; - } - // Maximum code point - if (res > 0x10ffff) { - i += onError('OUT_OF_RANGE', i - 1 - extraLength, bytes, result, res); - continue; - } - // Reserved for UTF-16 surrogate halves - if (res >= 0xd800 && res <= 0xdfff) { - i += onError('UTF16_SURROGATE', i - 1 - extraLength, bytes, result, res); - continue; - } - // Check for overlong sequences (more bytes than needed) - if (res <= overlongMask) { - i += onError('OVERLONG', i - 1 - extraLength, bytes, result, res); - continue; - } - result.push(res); - } - return result; -} -// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array -/** - * Returns the UTF-8 byte representation of `str`. - * - * If `form` is specified, the string is normalized. - * - * @category Encoding - * @param {string} str - The string to convert. - * @param {UnicodeNormalizationForm} [form] - The normalization form to use. - * - * @returns {Uint8Array} The UTF-8 byte representation. - * @throws {Error} If the UTF-8 conversion fails. - */ -function toUtf8Bytes(str, form) { - if (form != null) { - assertNormalize(form); - str = str.normalize(form); - } - const result = []; - for (let i = 0; i < str.length; i++) { - const c = str.charCodeAt(i); - if (c < 0x80) { - result.push(c); - } - else if (c < 0x800) { - result.push((c >> 6) | 0xc0); - result.push((c & 0x3f) | 0x80); - } - else if ((c & 0xfc00) == 0xd800) { - i++; - const c2 = str.charCodeAt(i); - assertArgument(i < str.length && (c2 & 0xfc00) === 0xdc00, 'invalid surrogate pair', 'str', str); - // Surrogate Pair - const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); - result.push((pair >> 18) | 0xf0); - result.push(((pair >> 12) & 0x3f) | 0x80); - result.push(((pair >> 6) & 0x3f) | 0x80); - result.push((pair & 0x3f) | 0x80); - } - else { - result.push((c >> 12) | 0xe0); - result.push(((c >> 6) & 0x3f) | 0x80); - result.push((c & 0x3f) | 0x80); - } - } - return new Uint8Array(result); -} -/** - * @ignore - */ -function _toUtf8String(codePoints) { - return codePoints - .map((codePoint) => { - if (codePoint <= 0xffff) { - return String.fromCharCode(codePoint); - } - codePoint -= 0x10000; - return String.fromCharCode(((codePoint >> 10) & 0x3ff) + 0xd800, (codePoint & 0x3ff) + 0xdc00); - }) - .join(''); -} -/** - * Returns the string represented by the UTF-8 data `bytes`. - * - * When `onError` function is specified, it is called on UTF-8 errors allowing recovery using the - * {@link Utf8ErrorFunc | **Utf8ErrorFunc**} API. (default: [error](Utf8ErrorFuncs)) - * - * @category Encoding - * @param {BytesLike} bytes - The UTF-8 data to convert. - * @param {Utf8ErrorFunc} [onError] - The error handling function. - * - * @returns {string} The string. - */ -function toUtf8String(bytes, onError) { - return _toUtf8String(getUtf8CodePoints(bytes, onError)); -} -/** - * Returns the UTF-8 code-points for `str`. - * - * If `form` is specified, the string is normalized. - * - * @category Encoding - * @param {string} str - The string to convert. - * @param {UnicodeNormalizationForm} [form] - The normalization form to use. - * - * @returns {number[]} The UTF-8 code-points. - */ -function toUtf8CodePoints(str, form) { - return getUtf8CodePoints(toUtf8Bytes(str, form)); -} - -// @TODO: timeout is completely ignored; start a Promise.any with a reject? -// TODO: `options` is not used; remove? -// eslint-disable-next-line @typescript-eslint/no-unused-vars -function createGetUrl(options) { - async function getUrl(req, _signal) { - const protocol = req.url.split(':')[0].toLowerCase(); - assert(protocol === 'http' || protocol === 'https', `unsupported protocol ${protocol}`, 'UNSUPPORTED_OPERATION', { - info: { protocol }, - operation: 'request', - }); - assert(protocol === 'https' || !req.credentials || req.allowInsecureAuthentication, 'insecure authorized connections unsupported', 'UNSUPPORTED_OPERATION', { - operation: 'request', - }); - let signal = undefined; - if (_signal) { - const controller = new AbortController(); - signal = controller.signal; - _signal.addListener(() => { - controller.abort(); - }); - } - const init = { - method: req.method, - headers: new Headers(Array.from(req)), - body: req.body || undefined, - signal, - }; - const resp = await fetch(req.url, init); - const headers = {}; - resp.headers.forEach((value, key) => { - headers[key.toLowerCase()] = value; - }); - const respBody = await resp.arrayBuffer(); - const body = respBody == null ? null : new Uint8Array(respBody); - return { - statusCode: resp.status, - statusMessage: resp.statusText, - headers, - body, - }; - } - return getUrl; -} - -/** - * Fetching content from the web is environment-specific, so quais provides an abstraction that each environment can - * implement to provide this service. - * - * On [Node.js](https://nodejs.org/), the `http` and `https` libs are used to create a request object, register event - * listeners and process data and populate the {@link FetchResponse | **FetchResponse**}. - * - * In a browser, the [DOM fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) is used, and the resulting - * `Promise` is waited on to retrieve the payload. - * - * The {@link FetchRequest | **FetchRequest**} is responsible for handling many common situations, such as redirects, - * server throttling, authentication, etc. - * - * It also handles common gateways, such as IPFS and data URIs. - */ -const MAX_ATTEMPTS = 12; -const SLOT_INTERVAL = 250; -// The global FetchGetUrlFunc implementation. -let defaultGetUrlFunc = createGetUrl(); -const reData = new RegExp('^data:([^;:]*)?(;base64)?,(.*)$', 'i'); -const reIpfs = new RegExp('^ipfs://(ipfs/)?(.*)$', 'i'); -// If locked, new Gateways cannot be added -let locked$5 = false; -// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs -// TODO: `signal` is not used; remove? -// eslint-disable-next-line @typescript-eslint/no-unused-vars -async function dataGatewayFunc(url, signal) { - try { - const match = url.match(reData); - if (!match) { - throw new Error('invalid data'); - } - return new FetchResponse(200, 'OK', { - 'content-type': match[1] || 'text/plain', - }, match[2] ? decodeBase64(match[3]) : unpercent(match[3])); - } - catch (error) { - return new FetchResponse(599, 'BAD REQUEST (invalid data: URI)', {}, null, new FetchRequest(url)); - } -} -/** - * Returns a {@link FetchGatewayFunc | **FetchGatewayFunc**} for fetching content from a standard IPFS gateway hosted at - * `baseUrl`. - * - * @category Utils - * @param {string} baseUrl - The base URL of the IPFS gateway. - * @returns {FetchGatewayFunc} The gateway function. - */ -function getIpfsGatewayFunc(baseUrl) { - // TODO: `signal` is not used; remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async function gatewayIpfs(url, signal) { - try { - const match = url.match(reIpfs); - if (!match) { - throw new Error('invalid link'); - } - return new FetchRequest(`${baseUrl}${match[2]}`); - } - catch (error) { - return new FetchResponse(599, 'BAD REQUEST (invalid IPFS URI)', {}, null, new FetchRequest(url)); - } - } - return gatewayIpfs; -} -const Gateways = { - data: dataGatewayFunc, - ipfs: getIpfsGatewayFunc('https://gateway.ipfs.io/ipfs/'), -}; -const fetchSignals = new WeakMap(); -/** - * @ignore - */ -class FetchCancelSignal { - #listeners; - #cancelled; - constructor(request) { - this.#listeners = []; - this.#cancelled = false; - fetchSignals.set(request, () => { - if (this.#cancelled) { - return; - } - this.#cancelled = true; - for (const listener of this.#listeners) { - setTimeout(() => { - listener(); - }, 0); - } - this.#listeners = []; - }); - } - addListener(listener) { - assert(!this.#cancelled, 'singal already cancelled', 'UNSUPPORTED_OPERATION', { - operation: 'fetchCancelSignal.addCancelListener', - }); - this.#listeners.push(listener); - } - get cancelled() { - return this.#cancelled; - } - checkSignal() { - assert(!this.cancelled, 'cancelled', 'CANCELLED', {}); - } -} -// Check the signal, throwing if it is cancelled -function checkSignal(signal) { - if (signal == null) { - throw new Error('missing signal; should not happen'); - } - signal.checkSignal(); - return signal; -} -/** - * Represents a request for a resource using a URI. - * - * By default, the supported schemes are `HTTP`, `HTTPS`, `data:`, and `IPFS:`. - * - * Additional schemes can be added globally using {@link registerGateway | **registerGateway**}. - * - * @category Utils - * @example - * - * ```ts - * req = new FetchRequest('https://www.ricmoo.com'); - * resp = await req.send(); - * resp.body.length; - * ``` - */ -class FetchRequest { - #allowInsecure; - #gzip; - #headers; - #method; - #timeout; - #url; - #body; - #bodyType; - #creds; - // Hooks - #preflight; - #process; - #retry; - #signal; - #throttle; - #getUrlFunc; - /** - * The fetch URL to request. - */ - get url() { - return this.#url; - } - set url(url) { - this.#url = String(url); - } - /** - * The fetch body, if any, to send as the request body. (default: null) - * - * When setting a body, the intrinsic `Content-Type` is automatically set and will be used if **not overridden** by - * setting a custom header. - * - * If `body` is null, the body is cleared (along with the intrinsic `Content-Type`). - * - * If `body` is a string, the intrinsic `Content-Type` is set to `text/plain`. - * - * If `body` is a Uint8Array, the intrinsic `Content-Type` is set to `application/octet-stream`. - * - * If `body` is any other object, the intrinsic `Content-Type` is set to `application/json`. - */ - get body() { - if (this.#body == null) { - return null; - } - return new Uint8Array(this.#body); - } - set body(body) { - if (body == null) { - this.#body = undefined; - this.#bodyType = undefined; - } - else if (typeof body === 'string') { - this.#body = toUtf8Bytes(body); - this.#bodyType = 'text/plain'; - } - else if (body instanceof Uint8Array) { - this.#body = body; - this.#bodyType = 'application/octet-stream'; - } - else if (typeof body === 'object') { - this.#body = toUtf8Bytes(JSON.stringify(body)); - this.#bodyType = 'application/json'; - } - else { - throw new Error('invalid body'); - } - } - /** - * Returns true if the request has a body. - */ - hasBody() { - return this.#body != null; - } - /** - * The HTTP method to use when requesting the URI. If no method has been explicitly set, then `GET` is used if the - * body is null and `POST` otherwise. - */ - get method() { - if (this.#method) { - return this.#method; - } - if (this.hasBody()) { - return 'POST'; - } - return 'GET'; - } - set method(method) { - if (method == null) { - method = ''; - } - this.#method = String(method).toUpperCase(); - } - /** - * The headers that will be used when requesting the URI. All keys are lower-case. - * - * This object is a copy, so any changes will **NOT** be reflected in the `FetchRequest`. - * - * To set a header entry, use the `setHeader` method. - */ - get headers() { - const headers = Object.assign({}, this.#headers); - if (this.#creds) { - headers['authorization'] = `Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`; - } - if (this.allowGzip) { - headers['accept-encoding'] = 'gzip'; - } - if (headers['content-type'] == null && this.#bodyType) { - headers['content-type'] = this.#bodyType; - } - if (this.body) { - headers['content-length'] = String(this.body.length); - } - return headers; - } - /** - * Get the header for `key`, ignoring case. - * - * @param {string} key - The header key to retrieve. - * @returns {string} The header value. - */ - getHeader(key) { - return this.headers[key.toLowerCase()]; - } - /** - * Set the header for `key` to `value`. All values are coerced to a string. - * - * @param {string} key - The header key to set. - * @param {string | number} value - The header value to set. - */ - setHeader(key, value) { - this.#headers[String(key).toLowerCase()] = String(value); - } - /** - * Clear all headers, resetting all intrinsic headers. - */ - clearHeaders() { - this.#headers = {}; - } - [Symbol.iterator]() { - const headers = this.headers; - const keys = Object.keys(headers); - let index = 0; - return { - next: () => { - if (index < keys.length) { - const key = keys[index++]; - return { - value: [key, headers[key]], - done: false, - }; - } - return { value: undefined, done: true }; - }, - }; - } - /** - * The value that will be sent for the `Authorization` header. - * - * To set the credentials, use the `setCredentials` method. - */ - get credentials() { - return this.#creds || null; - } - /** - * Sets an `Authorization` for `username` with `password`. - * - * @param {string} username - The username to use for basic authentication. - * @param {string} password - The password to use for basic authentication. - * @throws {Error} If the `username` contains a colon. - */ - setCredentials(username, password) { - assertArgument(!username.match(/:/), 'invalid basic authentication username', 'username', '[REDACTED]'); - this.#creds = `${username}:${password}`; - } - /** - * Enable and request gzip-encoded responses. The response will automatically be decompressed. (default: true) - */ - get allowGzip() { - return this.#gzip; - } - set allowGzip(value) { - this.#gzip = !!value; - } - /** - * Allow `Authentication` credentials to be sent over insecure channels. (default: false) - */ - get allowInsecureAuthentication() { - return !!this.#allowInsecure; - } - set allowInsecureAuthentication(value) { - this.#allowInsecure = !!value; - } - /** - * The timeout (in milliseconds) to wait for a complete response. (default: 5 minutes) - */ - get timeout() { - return this.#timeout; - } - set timeout(timeout) { - assertArgument(timeout >= 0, 'timeout must be non-zero', 'timeout', timeout); - this.#timeout = timeout; - } - /** - * This function is called prior to each request, for example during a redirection or retry in case of server - * throttling. - * - * This offers an opportunity to populate headers or update content before sending a request. - */ - get preflightFunc() { - return this.#preflight || null; - } - set preflightFunc(preflight) { - this.#preflight = preflight; - } - /** - * This function is called after each response, offering an opportunity to provide client-level throttling or - * updating response data. - * - * Any error thrown in this causes the `send()` to throw. - * - * To schedule a retry attempt (assuming the maximum retry limit has not been reached), use - * {@link FetchResponse.throwThrottleError | **FetchResponse.throwThrottleError**}. - */ - get processFunc() { - return this.#process || null; - } - set processFunc(process) { - this.#process = process; - } - /** - * This function is called on each retry attempt. - */ - get retryFunc() { - return this.#retry || null; - } - set retryFunc(retry) { - this.#retry = retry; - } - /** - * This function is called to fetch content from HTTP and HTTPS URLs and is platform specific (e.g. nodejs vs - * browsers). - * - * This is by default the currently registered global getUrl function, which can be changed using - * {@link registerGetUrl | **registerGetUrl**}. If this has been set, setting is to `null` will cause this - * FetchRequest (and any future clones) to revert back to using the currently registered global getUrl function. - * - * Setting this is generally not necessary, but may be useful for developers that wish to intercept requests or to - * configurege a proxy or other agent. - */ - get getUrlFunc() { - return this.#getUrlFunc || defaultGetUrlFunc; - } - set getUrlFunc(value) { - this.#getUrlFunc = value; - } - /** - * Create a new FetchRequest instance with default values. - * - * Once created, each property may be set before issuing a `.send()` to make the request. - */ - constructor(url) { - this.#url = String(url); - this.#allowInsecure = false; - this.#gzip = true; - this.#headers = {}; - this.#method = ''; - this.#timeout = 300000; - this.#throttle = { - slotInterval: SLOT_INTERVAL, - maxAttempts: MAX_ATTEMPTS, - }; - this.#getUrlFunc = null; - } - toString() { - return ``; - } - /** - * Update the throttle parameters used to determine maximum attempts and exponential-backoff properties. - * - * @param {FetchThrottleParams} params - The throttle parameters to set. - * @throws {Error} If the `slotInterval` is not a positive integer. - */ - setThrottleParams(params) { - if (params.slotInterval != null) { - this.#throttle.slotInterval = params.slotInterval; - } - if (params.maxAttempts != null) { - this.#throttle.maxAttempts = params.maxAttempts; - } - } - async #send(attempt, expires, delay, _request, _response) { - if (attempt >= this.#throttle.maxAttempts) { - return _response.makeServerError('exceeded maximum retry limit'); - } - assert(getTime$1() <= expires, 'timeout', 'TIMEOUT', { - operation: 'request.send', - reason: 'timeout', - request: _request, - }); - if (delay > 0) { - await wait(delay); - } - let req = this.clone(); - const scheme = (req.url.split(':')[0] || '').toLowerCase(); - // Process any Gateways - if (scheme in Gateways) { - const result = await Gateways[scheme](req.url, checkSignal(_request.#signal)); - if (result instanceof FetchResponse) { - let response = result; - if (this.processFunc) { - checkSignal(_request.#signal); - try { - response = await this.processFunc(req, response); - } - catch (error) { - // Something went wrong during processing; throw a 5xx server error - if (error.throttle == null || typeof error.stall !== 'number') { - response.makeServerError('error in post-processing function', error).assertOk(); - } - // Ignore throttling - } - } - return response; - } - req = result; - } - // We have a preflight function; update the request - if (this.preflightFunc) { - req = await this.preflightFunc(req); - } - const resp = await this.getUrlFunc(req, checkSignal(_request.#signal)); - let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request); - if (response.statusCode === 301 || response.statusCode === 302) { - // Redirect - try { - const location = response.headers.location || ''; - return req.redirect(location).#send(attempt + 1, expires, 0, _request, response); - // eslint-disable-next-line no-empty - } - catch (error) { } - // Things won't get any better on another attempt; abort - return response; - } - else if (response.statusCode === 429) { - // Throttle - if (this.retryFunc == null || (await this.retryFunc(req, response, attempt))) { - const retryAfter = response.headers['retry-after']; - let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); - if (typeof retryAfter === 'string' && retryAfter.match(/^[1-9][0-9]*$/)) { - delay = parseInt(retryAfter); - } - return req.clone().#send(attempt + 1, expires, delay, _request, response); - } - } - if (this.processFunc) { - checkSignal(_request.#signal); - try { - response = await this.processFunc(req, response); - } - catch (error) { - // Something went wrong during processing; throw a 5xx server error - if (error.throttle == null || typeof error.stall !== 'number') { - response.makeServerError('error in post-processing function', error).assertOk(); - } - // Throttle - let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); - if (error.stall >= 0) { - delay = error.stall; - } - return req.clone().#send(attempt + 1, expires, delay, _request, response); - } - } - return response; - } - /** - * Resolves to the response by sending the request. - */ - send() { - assert(this.#signal == null, 'request already sent', 'UNSUPPORTED_OPERATION', { - operation: 'fetchRequest.send', - }); - this.#signal = new FetchCancelSignal(this); - return this.#send(0, getTime$1() + this.timeout, 0, this, new FetchResponse(0, '', {}, null, this)); - } - /** - * Cancels the inflight response, causing a `CANCELLED` error to be rejected from the - * {@link FetchRequest.send | **send**}. - */ - cancel() { - assert(this.#signal != null, 'request has not been sent', 'UNSUPPORTED_OPERATION', { - operation: 'fetchRequest.cancel', - }); - const signal = fetchSignals.get(this); - if (!signal) { - throw new Error('missing signal; should not happen'); - } - signal(); - } - /** - * Returns a new {@link FetchRequest | **FetchRequest**} that represents the redirection to `location`. - * - * @param {string} location - The location to redirect to. - * @returns {FetchRequest} The new request. - */ - redirect(location) { - // Redirection; for now we only support absolute locations - const current = this.url.split(':')[0].toLowerCase(); - const target = location.split(':')[0].toLowerCase(); - // Don't allow redirecting: - // - non-GET requests - // - downgrading the security (e.g. https => http) - // - to non-HTTP (or non-HTTPS) protocols [this could be relaxed?] - assert(this.method === 'GET' && (current !== 'https' || target !== 'http') && location.match(/^https?:/), `unsupported redirect`, 'UNSUPPORTED_OPERATION', { - operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`, - }); - // Create a copy of this request, with a new URL - const req = new FetchRequest(location); - req.method = 'GET'; - req.allowGzip = this.allowGzip; - req.timeout = this.timeout; - req.#headers = Object.assign({}, this.#headers); - if (this.#body) { - req.#body = new Uint8Array(this.#body); - } - req.#bodyType = this.#bodyType; - return req; - } - /** - * Create a new copy of this request. - * - * @returns {FetchRequest} The new request. - */ - clone() { - const clone = new FetchRequest(this.url); - // Preserve "default method" (i.e. null) - clone.#method = this.#method; - // Preserve "default body" with type, copying the Uint8Array is present - if (this.#body) { - clone.#body = this.#body; - } - clone.#bodyType = this.#bodyType; - // Preserve "default headers" - clone.#headers = Object.assign({}, this.#headers); - // Credentials is readonly, so we copy internally - clone.#creds = this.#creds; - if (this.allowGzip) { - clone.allowGzip = true; - } - clone.timeout = this.timeout; - if (this.allowInsecureAuthentication) { - clone.allowInsecureAuthentication = true; - } - clone.#preflight = this.#preflight; - clone.#process = this.#process; - clone.#retry = this.#retry; - clone.#getUrlFunc = this.#getUrlFunc; - return clone; - } - /** - * Locks all static configuration for gateways and FetchGetUrlFunc registration. - */ - static lockConfig() { - locked$5 = true; - } - /** - * Get the current Gateway function for `scheme`. - * - * @param {string} scheme - The scheme to get the gateway for. - * @returns {FetchGatewayFunc | null} The gateway function, or null if not found. - */ - static getGateway(scheme) { - return Gateways[scheme.toLowerCase()] || null; - } - /** - * Use the `func` when fetching URIs using `scheme`. - * - * This method affects all requests globally. - * - * If {@link FetchRequest.lockConfig | **lockConfig**} has been called, no change is made and this throws. - * - * @param {string} scheme - The scheme to register the gateway for. - * @param {FetchGatewayFunc} func - The gateway function to use. - * @throws {Error} If the scheme is `http` or `https`. - */ - static registerGateway(scheme, func) { - scheme = scheme.toLowerCase(); - if (scheme === 'http' || scheme === 'https') { - throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); - } - if (locked$5) { - throw new Error('gateways locked'); - } - Gateways[scheme] = func; - } - /** - * Use `getUrl` when fetching URIs over HTTP and HTTPS requests. - * - * This method affects all requests globally. - * - * If {@link FetchRequest.lockConfig | **lockConfig**} has been called, no change is made and this throws. - * - * @param {FetchGetUrlFunc} getUrl - The function to use for fetching HTTP and HTTPS URIs. - * @throws {Error} If the gateways are locked. - */ - static registerGetUrl(getUrl) { - if (locked$5) { - throw new Error('gateways locked'); - } - defaultGetUrlFunc = getUrl; - } - /** - * Creates a getUrl function that fetches content from HTTP and HTTPS URLs. - * - * The available `options` are dependent on the platform implementation of the default getUrl function. - * - * This is not generally something that is needed, but is useful when trying to customize simple behaviour when - * fetching HTTP content. - * - * @param {Record} [options] - The options to use when creating the getUrl function. - * @returns {FetchGetUrlFunc} The getUrl function. - * @throws {Error} If the gateways are locked. - */ - static createGetUrlFunc(options) { - return createGetUrl(); - } - /** - * Creates a function that can "fetch" data URIs. - * - * Note that this is automatically done internally to support data URIs, so it is not necessary to register it. - * - * This is not generally something that is needed, but may be useful in a wrapper to perfom custom data URI - * functionality. - * - * @returns {FetchGatewayFunc} The gateway function. - */ - static createDataGateway() { - return dataGatewayFunc; - } - /** - * Creates a function that will fetch IPFS (unvalidated) from a custom gateway baseUrl. - * - * The default IPFS gateway used internally is `"https:/\/gateway.ipfs.io/ipfs/"`. - * - * @param {string} baseUrl - The base URL of the IPFS gateway. - * @returns {FetchGatewayFunc} The gateway function. - */ - static createIpfsGatewayFunc(baseUrl) { - return getIpfsGatewayFunc(baseUrl); - } -} -/** - * The response for a FetchRequest. - * - * @category Utils - */ -class FetchResponse { - #statusCode; - #statusMessage; - #headers; - #body; - #request; - #error; - toString() { - return ``; - } - /** - * The response status code. - */ - get statusCode() { - return this.#statusCode; - } - /** - * The response status message. - */ - get statusMessage() { - return this.#statusMessage; - } - /** - * The response headers. All keys are lower-case. - */ - get headers() { - return Object.assign({}, this.#headers); - } - /** - * The response body, or `null` if there was no body. - */ - get body() { - return this.#body == null ? null : new Uint8Array(this.#body); - } - /** - * The response body as a UTF-8 encoded string, or the empty string (i.e. `""`) if there was no body. - * - * An error is thrown if the body is invalid UTF-8 data. - */ - get bodyText() { - try { - return this.#body == null ? '' : toUtf8String(this.#body); - } - catch (error) { - assert(false, 'response body is not valid UTF-8 data', 'UNSUPPORTED_OPERATION', { - operation: 'bodyText', - info: { response: this }, - }); - } - } - /** - * The response body, decoded as JSON. - * - * An error is thrown if the body is invalid JSON-encoded data or if there was no body. - */ - get bodyJson() { - try { - return JSON.parse(this.bodyText); - } - catch (error) { - assert(false, 'response body is not valid JSON', 'UNSUPPORTED_OPERATION', { - operation: 'bodyJson', - info: { response: this }, - }); - } - } - [Symbol.iterator]() { - const headers = this.headers; - const keys = Object.keys(headers); - let index = 0; - return { - next: () => { - if (index < keys.length) { - const key = keys[index++]; - return { - value: [key, headers[key]], - done: false, - }; - } - return { value: undefined, done: true }; - }, - }; - } - constructor(statusCode, statusMessage, headers, body, request) { - this.#statusCode = statusCode; - this.#statusMessage = statusMessage; - this.#headers = Object.keys(headers).reduce((accum, k) => { - accum[k.toLowerCase()] = String(headers[k]); - return accum; - }, {}); - this.#body = body == null ? null : new Uint8Array(body); - this.#request = request || null; - this.#error = { message: '' }; - } - /** - * Return a Response with matching headers and body, but with an error status code (i.e. 599) and `message` with an - * optional `error`. - * - * @param {string} [message] - The error message to use. - * @param {Error} [error] - The error to use. - * @returns {FetchResponse} The error response. - */ - makeServerError(message, error) { - let statusMessage; - if (!message) { - message = `${this.statusCode} ${this.statusMessage}`; - statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; - } - else { - statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; - } - const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined); - response.#error = { message, error }; - return response; - } - /** - * If called within a [request.processFunc](FetchRequest-processFunc) call, causes the request to retry as if - * throttled for `stall` milliseconds. - * - * @param {string} [message] - The error message to use. - * @param {number} [stall] - The number of milliseconds to stall before retrying. - * @throws {Error} If `stall` is not a non-negative integer. - */ - throwThrottleError(message, stall) { - if (stall == null) { - stall = -1; - } - else { - assertArgument(Number.isInteger(stall) && stall >= 0, 'invalid stall timeout', 'stall', stall); - } - const error = new Error(message || 'throttling requests'); - defineProperties(error, { stall, throttle: true }); - throw error; - } - /** - * Get the header value for `key`, ignoring case. - * - * @param {string} key - The header key to retrieve. - * @returns {string} The header value. - */ - getHeader(key) { - return this.headers[key.toLowerCase()]; - } - /** - * Returns true if the response has a body. - * - * @returns {boolean} True if the response has a body. - * @throws {Error} If the body is invalid UTF-8 data. - */ - hasBody() { - return this.#body != null; - } - /** - * The request made for this response. - */ - get request() { - return this.#request; - } - /** - * Returns true if this response was a success statusCode. - */ - ok() { - return this.#error.message === '' && this.statusCode >= 200 && this.statusCode < 300; - } - /** - * Throws a `SERVER_ERROR` if this response is not ok. - * - * @throws {Error} If the response is not ok. - */ - assertOk() { - if (this.ok()) { - return; - } - // eslint-disable-next-line prefer-const - let { message, error } = this.#error; - if (message === '') { - message = `server response ${this.statusCode} ${this.statusMessage}`; - } - assert(false, message, 'SERVER_ERROR', { - request: this.request || 'unknown request', - response: this, - error, - }); - } -} -function getTime$1() { - return new Date().getTime(); -} -function unpercent(value) { - return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => { - return String.fromCharCode(parseInt(code, 16)); - })); -} -function wait(delay) { - return new Promise((resolve) => setTimeout(resolve, delay)); -} - -/** - * The **FixedNumber** class permits using values with decimal places, using fixed-pont math. - * - * Fixed-point math is still based on integers under-the-hood, but uses an internal offset to store fractional - * components below, and each operation corrects for this after each operation. - */ -const BN_N1 = BigInt(-1); -const BN_0$6 = BigInt(0); -const BN_1$3 = BigInt(1); -const BN_5 = BigInt(5); -const _guard$7 = {}; -// Constant to pull zeros from for multipliers -let Zeros = '0000'; -while (Zeros.length < 80) { - Zeros += Zeros; -} -// Returns a string "1" followed by decimal "0"s -function getTens(decimals) { - let result = Zeros; - while (result.length < decimals) { - result += result; - } - return BigInt('1' + result.substring(0, decimals)); -} -function checkValue(val, format, safeOp) { - const width = BigInt(format.width); - if (format.signed) { - const limit = BN_1$3 << (width - BN_1$3); - assert(safeOp == null || (val >= -limit && val < limit), 'overflow', 'NUMERIC_FAULT', { - operation: safeOp, - fault: 'overflow', - value: val, - }); - if (val > BN_0$6) { - val = fromTwos(mask(val, width), width); - } - else { - val = -fromTwos(mask(-val, width), width); - } - } - else { - const limit = BN_1$3 << width; - assert(safeOp == null || (val >= 0 && val < limit), 'overflow', 'NUMERIC_FAULT', { - operation: safeOp, - fault: 'overflow', - value: val, - }); - val = ((val % limit) + limit) % limit & (limit - BN_1$3); - } - return val; -} -function getFormat(value) { - if (typeof value === 'number') { - value = `fixed128x${value}`; - } - let signed = true; - let width = 128; - let decimals = 18; - if (typeof value === 'string') { - // Parse the format string - if (value === 'fixed') ; - else if (value === 'ufixed') { - signed = false; - } - else { - const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); - assertArgument(match, 'invalid fixed format', 'format', value); - signed = match[1] !== 'u'; - width = parseInt(match[2]); - decimals = parseInt(match[3]); - } - } - else if (value) { - // Extract the values from the object - const v = value; - const check = (key, type, defaultValue) => { - if (v[key] == null) { - return defaultValue; - } - assertArgument(typeof v[key] === type, 'invalid fixed format (' + key + ' not ' + type + ')', 'format.' + key, v[key]); - return v[key]; - }; - signed = check('signed', 'boolean', signed); - width = check('width', 'number', width); - decimals = check('decimals', 'number', decimals); - } - assertArgument(width % 8 === 0, 'invalid FixedNumber width (not byte aligned)', 'format.width', width); - assertArgument(decimals <= 80, 'invalid FixedNumber decimals (too large)', 'format.decimals', decimals); - const name = (signed ? '' : 'u') + 'fixed' + String(width) + 'x' + String(decimals); - return { signed, width, decimals, name }; -} -function toString(val, decimals) { - let negative = ''; - if (val < BN_0$6) { - negative = '-'; - val *= BN_N1; - } - let str = val.toString(); - // No decimal point for whole values - if (decimals === 0) { - return negative + str; - } - // Pad out to the whole component (including a whole digit) - while (str.length <= decimals) { - str = Zeros + str; - } - // Insert the decimal point - const index = str.length - decimals; - str = str.substring(0, index) + '.' + str.substring(index); - // Trim the whole component (leaving at least one 0) - while (str[0] === '0' && str[1] !== '.') { - str = str.substring(1); - } - // Trim the decimal component (leaving at least one 0) - while (str[str.length - 1] === '0' && str[str.length - 2] !== '.') { - str = str.substring(0, str.length - 1); - } - return negative + str; -} -/** - * A FixedNumber represents a value over its {@link FixedFormat | **FixedFormat**} arithmetic field. - * - * A FixedNumber can be used to perform math, losslessly, on values which have decmial places. - * - * A FixedNumber has a fixed bit-width to store values in, and stores all values internally by multiplying the value by - * 10 raised to the power of `decimals`. - * - * If operations are performed that cause a value to grow too high (close to positive infinity) or too low (close to - * negative infinity), the value is said to overflow. - * - * For example, an 8-bit signed value, with 0 decimals may only be within the range `-128` to `127`; so `-128 - 1` will - * overflow and become `127`. Likewise, `127 + 1` will overflow and become `-127`. - * - * Many operation have a normal and unsafe variant. The normal variant will throw a - * [NumericFaultError](../interfaces/NumericFaultError) on any overflow, while the unsafe variant will silently allow - * overflow, corrupting its value value. - * - * If operations are performed that cause a value to become too small (close to zero), the value loses precison and is - * said to underflow. - * - * For example, an value with 1 decimal place may store a number as small as `0.1`, but the value of `0.1 / 2` is - * `0.05`, which cannot fit into 1 decimal place, so underflow occurs which means precision is lost and the value - * becomes `0`. - * - * Some operations have a normal and signalling variant. The normal variant will silently ignore underflow, while the - * signalling variant will thow a [NumericFaultError](../interfaces/NumericFaultError) on underflow. - * - * @category Utils - */ -class FixedNumber { - /** - * The specific fixed-point arithmetic field for this value. - */ - format; - #format; - // The actual value (accounting for decimals) - #val; - // A base-10 value to multiple values by to maintain the magnitude - #tens; - /** - * This is a property so console.log shows a human-meaningful value. - * - * @ignore - */ - _value; - // Use this when changing this file to get some typing info, - // but then switch to any to mask the internal type - // constructor(guard: any, value: bigint, format: _FixedFormat) { - /** - * @ignore - */ - constructor(guard, value, format) { - assertPrivate(guard, _guard$7, 'FixedNumber'); - this.#val = value; - this.#format = format; - const _value = toString(value, format.decimals); - defineProperties(this, { format: format.name, _value }); - this.#tens = getTens(format.decimals); - } - /** - * If true, negative values are permitted, otherwise only positive values and zero are allowed. - */ - get signed() { - return this.#format.signed; - } - /** - * The number of bits available to store the value. - */ - get width() { - return this.#format.width; - } - /** - * The number of decimal places in the fixed-point arithment field. - */ - get decimals() { - return this.#format.decimals; - } - /** - * The value as an integer, based on the smallest unit the {@link FixedNumber.decimals | **decimals**} allow. - */ - get value() { - return this.#val; - } - #checkFormat(other) { - assertArgument(this.format === other.format, 'incompatible format; use fixedNumber.toFormat', 'other', other); - } - #checkValue(val, safeOp) { - val = checkValue(val, this.#format, safeOp); - return new FixedNumber(_guard$7, val, this.#format); - } - #add(o, safeOp) { - this.#checkFormat(o); - return this.#checkValue(this.#val + o.#val, safeOp); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` added to `other`, ignoring overflow. - * - * @param {FixedNumber} other - The value to add to `this`. - * @returns {FixedNumber} The result of the addition. - */ - addUnsafe(other) { - return this.#add(other); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` added to `other`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to add to `this`. - * @returns {FixedNumber} The result of the addition. - */ - add(other) { - return this.#add(other, 'add'); - } - #sub(o, safeOp) { - this.#checkFormat(o); - return this.#checkValue(this.#val - o.#val, safeOp); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `other` subtracted from `this`, ignoring - * overflow. - * - * @param {FixedNumber} other - The value to subtract from `this`. - * @returns {FixedNumber} The result of the subtraction. - */ - subUnsafe(other) { - return this.#sub(other); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `other` subtracted from `this`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to subtract from `this`. - * @returns {FixedNumber} The result of the subtraction. - */ - sub(other) { - return this.#sub(other, 'sub'); - } - #mul(o, safeOp) { - this.#checkFormat(o); - return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`, ignoring - * overflow and underflow (precision loss). - * - * @param {FixedNumber} other - The value to multiply `this` by. - * @returns {FixedNumber} The result of the multiplication. - */ - mulUnsafe(other) { - return this.#mul(other); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to multiply `this` by. - * @returns {FixedNumber} The result of the multiplication. - */ - mul(other) { - return this.#mul(other, 'mul'); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs or if underflow (precision - * loss) occurs. - * - * @param {FixedNumber} other - The value to multiply `this` by. - * @returns {FixedNumber} The result of the multiplication. - * @throws {NumericFaultError} Thrown if overflow or underflow occurs. - * @throws {NumericFaultError} Thrown if division by 0 occurs. - */ - mulSignal(other) { - this.#checkFormat(other); - const value = this.#val * other.#val; - assert(value % this.#tens === BN_0$6, 'precision lost during signalling mul', 'NUMERIC_FAULT', { - operation: 'mulSignal', - fault: 'underflow', - value: this, - }); - return this.#checkValue(value / this.#tens, 'mulSignal'); - } - #div(o, safeOp) { - assert(o.#val !== BN_0$6, 'division by zero', 'NUMERIC_FAULT', { - operation: 'div', - fault: 'divide-by-zero', - value: this, - }); - this.#checkFormat(o); - return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`, ignoring - * underflow (precision loss). A [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to divide `this` by. - * @returns {FixedNumber} The result of the division. - */ - divUnsafe(other) { - return this.#div(other); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`, ignoring - * underflow (precision loss). A [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to divide `this` by. - * @returns {FixedNumber} The result of the division. - */ - div(other) { - return this.#div(other, 'div'); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if underflow (precision loss) occurs. - * - * @param {FixedNumber} other - The value to divide `this` by. - * @returns {FixedNumber} The result of the division. - * @throws {NumericFaultError} Thrown if underflow occurs. - */ - divSignal(other) { - assert(other.#val !== BN_0$6, 'division by zero', 'NUMERIC_FAULT', { - operation: 'div', - fault: 'divide-by-zero', - value: this, - }); - this.#checkFormat(other); - const value = this.#val * this.#tens; - assert(value % other.#val === BN_0$6, 'precision lost during signalling div', 'NUMERIC_FAULT', { - operation: 'divSignal', - fault: 'underflow', - value: this, - }); - return this.#checkValue(value / other.#val, 'divSignal'); - } - /** - * Returns a comparison result between `this` and `other`. - * - * This is suitable for use in sorting, where `-1` implies `this` is smaller, `1` implies `this` is larger and `0` - * implies both are equal. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {number} The comparison result. - */ - cmp(other) { - let a = this.value, b = other.value; - // Coerce a and b to the same magnitude - const delta = this.decimals - other.decimals; - if (delta > 0) { - b *= getTens(delta); - } - else if (delta < 0) { - a *= getTens(-delta); - } - // Comnpare - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; - } - /** - * Returns true if `other` is equal to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is equal to `this`. - */ - eq(other) { - return this.cmp(other) === 0; - } - /** - * Returns true if `other` is less than to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is less than to `this`. - */ - lt(other) { - return this.cmp(other) < 0; - } - /** - * Returns true if `other` is less than or equal to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is less than or equal to `this`. - */ - lte(other) { - return this.cmp(other) <= 0; - } - /** - * Returns true if `other` is greater than to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is greater than to `this`. - */ - gt(other) { - return this.cmp(other) > 0; - } - /** - * Returns true if `other` is greater than or equal to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is greater than or equal to `this`. - */ - gte(other) { - return this.cmp(other) >= 0; - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} which is the largest **integer** that is less than or equal to - * `this`. - * - * The decimal component of the result will always be `0`. - * - * @returns {FixedNumber} The floored value. - */ - floor() { - let val = this.#val; - if (this.#val < BN_0$6) { - val -= this.#tens - BN_1$3; - } - val = (this.#val / this.#tens) * this.#tens; - return this.#checkValue(val, 'floor'); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} which is the smallest **integer** that is greater than or - * equal to `this`. - * - * The decimal component of the result will always be `0`. - * - * @returns {FixedNumber} The ceiling value. - */ - ceiling() { - let val = this.#val; - if (this.#val > BN_0$6) { - val += this.#tens - BN_1$3; - } - val = (this.#val / this.#tens) * this.#tens; - return this.#checkValue(val, 'ceiling'); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the decimal component rounded up on ties at `decimals` - * places. - * - * @param {number} [decimals] - The number of decimal places to round to. - * @returns {FixedNumber} The rounded value. - */ - round(decimals) { - if (decimals == null) { - decimals = 0; - } - // Not enough precision to not already be rounded - if (decimals >= this.decimals) { - return this; - } - const delta = this.decimals - decimals; - const bump = BN_5 * getTens(delta - 1); - let value = this.value + bump; - const tens = getTens(delta); - value = (value / tens) * tens; - checkValue(value, this.#format, 'round'); - return new FixedNumber(_guard$7, value, this.#format); - } - /** - * Returns true if `this` is equal to `0`. - * - * @returns {boolean} True if `this` is equal to `0`. - */ - isZero() { - return this.#val === BN_0$6; - } - /** - * Returns true if `this` is less than `0`. - * - * @returns {boolean} True if `this` is less than `0`. - */ - isNegative() { - return this.#val < BN_0$6; - } - /** - * Returns the string representation of `this`. - * - * @returns {string} The string representation. - */ - toString() { - return this._value; - } - /** - * Returns a float approximation. - * - * Due to IEEE 754 precission (or lack thereof), this function can only return an approximation and most values will - * contain rounding errors. - * - * @returns {number} The float approximation. - */ - toUnsafeFloat() { - return parseFloat(this.toString()); - } - /** - * Return a new {@link FixedNumber | **FixedNumber**} with the same value but has had its field set to `format`. - * - * This will throw if the value cannot fit into `format`. - * - * @param {FixedFormat} format - The new format for the value. - */ - toFormat(format) { - return FixedNumber.fromString(this.toString(), format); - } - /** - * Creates a new {@link FixedNumber | **FixedNumber**} for `value` divided by `decimal` places with `format`. - * - * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` (once adjusted for `decimals`) - * cannot fit in `format`, either due to overflow or underflow (precision loss). - * - * @param {BigNumberish} _value - The value to create a FixedNumber for. - * @param {Numeric} [_decimals] - The number of decimal places in `value`. - * @param {FixedFormat} [_format] - The format for the FixedNumber. - * @returns {FixedNumber} The FixedNumber for `value`. - */ - static fromValue(_value, _decimals, _format) { - const decimals = _decimals == null ? 0 : getNumber(_decimals); - const format = getFormat(_format); - let value = getBigInt(_value, 'value'); - const delta = decimals - format.decimals; - if (delta > 0) { - const tens = getTens(delta); - assert(value % tens === BN_0$6, 'value loses precision for format', 'NUMERIC_FAULT', { - operation: 'fromValue', - fault: 'underflow', - value: _value, - }); - value /= tens; - } - else if (delta < 0) { - value *= getTens(-delta); - } - checkValue(value, format, 'fromValue'); - return new FixedNumber(_guard$7, value, format); - } - /** - * Creates a new {@link FixedNumber | **FixedNumber**} for `value` with `format`. - * - * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` cannot fit in `format`, either - * due to overflow or underflow (precision loss). - * - * @param {BigNumberish} _value - The value to create a FixedNumber for. - * @param {FixedFormat} [_format] - The format for the FixedNumber. - * @returns {FixedNumber} The FixedNumber for `value`. - */ - static fromString(_value, _format) { - const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/); - assertArgument(match && match[2].length + match[3].length > 0, 'invalid FixedNumber string value', 'value', _value); - const format = getFormat(_format); - const whole = match[2] || '0'; - let decimal = match[3] || ''; - // Pad out the decimals - while (decimal.length < format.decimals) { - decimal += Zeros; - } - // Check precision is safe - assert(decimal.substring(format.decimals).match(/^0*$/), 'too many decimals for format', 'NUMERIC_FAULT', { - operation: 'fromString', - fault: 'underflow', - value: _value, - }); - // Remove extra padding - decimal = decimal.substring(0, format.decimals); - const value = BigInt(match[1] + whole + decimal); - checkValue(value, format, 'fromString'); - return new FixedNumber(_guard$7, value, format); - } - /** - * Creates a new {@link FixedNumber | **FixedNumber**} with the big-endian representation `value` with `format`. - * - * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` cannot fit in `format` due to - * overflow. - * - * @param {BytesLike} _value - The big-endian representation of the value. - * @param {FixedFormat} [_format] - The format for the FixedNumber. - * @returns {FixedNumber} The FixedNumber for `value`. - */ - static fromBytes(_value, _format) { - let value = toBigInt(getBytes(_value, 'value')); - const format = getFormat(_format); - if (format.signed) { - value = fromTwos(value, format.width); - } - checkValue(value, format, 'fromBytes'); - return new FixedNumber(_guard$7, value, format); - } -} - -/** - * Most interactions with Ethereum requires integer values, which use the smallest magnitude unit. - * - * For example, imagine dealing with dollars and cents. Since dollars are divisible, non-integer values are possible, - * such as `$10.77`. By using the smallest indivisible unit (i.e. cents), the value can be kept as the integer `1077`. - * - * When receiving decimal input from the user (as a decimal string), the value should be converted to an integer and - * when showing a user a value, the integer value should be converted to a decimal string. - * - * This creates a clear distinction, between values to be used by code (integers) and values used for display logic to - * users (decimals). - * - * The native unit in Ethereum, ether is divisible to 18 decimal places, where each individual unit is called a wei. - */ -const names = ['wei', 'kwei', 'mwei', 'gwei', 'szabo', 'finney', 'ether']; -/** - * Converts `value` into a decimal string, assuming `unit` decimal places. The `unit` may be the number of decimal - * places or the name of a unit (e.g. `"gwei"` for 9 decimal places). - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @param {string | Numeric} [unit=18] - The unit to convert to. Default is `18` - * @returns {string} The converted value. - * @throws {Error} If the unit is invalid. - */ -function formatUnits(value, unit) { - let decimals = 18; - if (typeof unit === 'string') { - const index = names.indexOf(unit); - assertArgument(index >= 0, 'invalid unit', 'unit', unit); - decimals = 3 * index; - } - else if (unit != null) { - decimals = getNumber(unit, 'unit'); - } - return FixedNumber.fromValue(value, decimals, { decimals, width: 512 }).toString(); -} -/** - * Converts the decimal string `value` to a BigInt, assuming `unit` decimal places. The `unit` may the number of decimal - * places or the name of a unit (e.g. `"gwei"` for 9 decimal places). - * - * @category Utils - * @param {string} value - The value to convert. - * @param {string | Numeric} [unit=18] - The unit to convert from. Default is `18` - * @returns {bigint} The converted value. - * @throws {Error} If the unit is invalid. - * @throws {Error} If the value is not a string. - */ -function parseUnits(value, unit) { - assertArgument(typeof value === 'string', 'value must be a string', 'value', value); - let decimals = 18; - if (typeof unit === 'string') { - const index = names.indexOf(unit); - assertArgument(index >= 0, 'invalid unit', 'unit', unit); - decimals = 3 * index; - } - else if (unit != null) { - decimals = getNumber(unit, 'unit'); - } - return FixedNumber.fromString(value, { decimals, width: 512 }).value; -} -/** - * Converts `value` into a decimal string sing 18 decimal places. - * - * @category Utils - * @param {BigNumberish} wei - The value to convert. - * @returns {string} The converted value. - */ -function formatQuai(wei) { - return formatUnits(wei, 18); -} -/** - * Converts the decimal string `quai` to a BigInt, using 18 decimal places. - * - * @category Utils - * @param {string} ether - The value to convert. - * @returns {bigint} The converted value. - */ -function parseQuai(ether) { - return parseUnits(ether, 18); -} - -/** - * Explain UUID and link to RFC here. - */ -/** - * Returns the version 4 [UUID](https://www.ietf.org/rfc/rfc4122.txt) for the `randomBytes`. - * - * @category Utils - * @param {BytesLike} randomBytes - The random bytes to use. - * - * @returns {string} The UUID. - */ -function uuidV4(randomBytes) { - const bytes = getBytes(randomBytes, 'randomBytes'); - // Section: 4.1.3: - // - time_hi_and_version[12:16] = 0b0100 - bytes[6] = (bytes[6] & 0x0f) | 0x40; - // Section 4.4 - // - clock_seq_hi_and_reserved[6] = 0b0 - // - clock_seq_hi_and_reserved[7] = 0b1 - bytes[8] = (bytes[8] & 0x3f) | 0x80; - const value = hexlify(bytes); - return [ - value.substring(2, 10), - value.substring(10, 14), - value.substring(14, 18), - value.substring(18, 22), - value.substring(22, 34), - ].join('-'); -} - -/** - * A zone is the lowest level shard within the Quai network hierarchy. Zones are the only shards in the network that - * accept user transactions. The value is a hexadecimal string representing the encoded value of the zone. Read more - * [here](https://github.com/quai-network/qips/blob/master/qip-0002.md). - * - * @category Constants - */ -var Zone; -(function (Zone) { - Zone["Cyprus1"] = "0x00"; - Zone["Cyprus2"] = "0x01"; - Zone["Cyprus3"] = "0x02"; - Zone["Paxos1"] = "0x10"; - Zone["Paxos2"] = "0x11"; - Zone["Paxos3"] = "0x12"; - Zone["Hydra1"] = "0x20"; - Zone["Hydra2"] = "0x21"; - Zone["Hydra3"] = "0x22"; -})(Zone || (Zone = {})); -var Ledger; -(function (Ledger) { - Ledger[Ledger["Quai"] = 0] = "Quai"; - Ledger[Ledger["Qi"] = 1] = "Qi"; -})(Ledger || (Ledger = {})); -function zoneFromBytes(zone) { - switch (zone) { - case '0x00': - return Zone.Cyprus1; - case '0x01': - return Zone.Cyprus2; - case '0x02': - return Zone.Cyprus3; - case '0x10': - return Zone.Paxos1; - case '0x11': - return Zone.Paxos2; - case '0x12': - return Zone.Paxos3; - case '0x20': - return Zone.Hydra1; - case '0x21': - return Zone.Hydra2; - case '0x22': - return Zone.Hydra3; - default: - throw new Error(`Invalid zone: ${zone}`); - } -} -const ZoneData = [ - { - name: 'Cyprus One', - nickname: 'cyprus1', - shard: 'zone-0-0', - context: 2, - byte: '0x00', //0000 0000 region-0 zone-0 - }, - { - name: 'Cyprus Two', - nickname: 'cyprus2', - shard: 'zone-0-1', - context: 2, - byte: '0x01', // 0000 0001 region-0 zone-1 - }, - { - name: 'Cyprus Three', - nickname: 'cyprus3', - shard: 'zone-0-2', - context: 2, - byte: '0x02', // 0000 0010 region-0 zone-2 - }, - { - name: 'Paxos One', - nickname: 'paxos1', - shard: 'zone-1-0', - context: 2, - byte: '0x10', // 0001 0000 region-1 zone-0 - }, - { - name: 'Paxos Two', - nickname: 'paxos2', - shard: 'zone-1-1', - context: 2, - byte: '0x11', // 0001 0001 region-1 zone-1 - }, - { - name: 'Paxos Three', - nickname: 'paxos3', - shard: 'zone-1-2', - context: 2, - byte: '0x12', // 0001 0010 region-1 zone-2 - }, - { - name: 'Hydra One', - nickname: 'hydra1', - shard: 'zone-2-0', - context: 2, - byte: '0x20', // 0010 0000 region-2 zone-0 - }, - { - name: 'Hydra Two', - nickname: 'hydra2', - shard: 'zone-2-1', - context: 2, - byte: '0x21', // 0010 0001 region-2 zone-1 - }, - { - name: 'Hydra Three', - nickname: 'hydra3', - shard: 'zone-2-2', - context: 2, - byte: '0x22', // 0010 0010 region-2 zone-2 - }, -]; -function toZone(shard) { - return zoneFromBytes(ZoneData.find((it) => it.name == shard || it.byte == shard || it.nickname == shard || it.shard == shard) - ?.byte || ''); -} - -function number(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); -} -function bytes(b, ...lengths) { - if (!(b instanceof Uint8Array)) - throw new Error('Expected Uint8Array'); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); -} -function hash(hash) { - if (typeof hash !== 'function' || typeof hash.create !== 'function') - throw new Error('Hash should be wrapped by utils.wrapConstructor'); - number(hash.outputLen); - number(hash.blockLen); -} -function exists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error('Hash instance has been destroyed'); - if (checkFinished && instance.finished) - throw new Error('Hash#digest() has already been called'); -} -function output(out, instance) { - bytes(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); - } -} - -const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; - -/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. -// node.js versions earlier than v19 don't declare it in global scope. -// For node.js, package.json#exports field mapping rewrites import -// from `crypto` to `cryptoNode`, which imports native module. -// Makes the utils un-importable in browsers without a bundler. -// Once node.js 18 is deprecated, we can just drop the import. -const u8a$1 = (a) => a instanceof Uint8Array; -const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -// Cast array to view -const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); -// The rotate right (circular right shift) operation for uint32 -const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); -// big-endian hardware is rare. Just in case someone still decides to run hashes: -// early-throw an error because we don't support BE yet. -const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; -if (!isLE) - throw new Error('Non little-endian hardware is not supported'); -// There is no setImmediate in browser and setTimeout is slow. -// call of async fn will return Promise, which will be fullfiled only on -// next scheduler queue processing step and this is exactly what we need. -const nextTick = async () => { }; -// Returns control to thread each 'tick' ms to avoid blocking -async function asyncLoop(iters, tick, cb) { - let ts = Date.now(); - for (let i = 0; i < iters; i++) { - cb(i); - // Date.now() is not monotonic, so in case if clock goes backwards we return return control too - const diff = Date.now() - ts; - if (diff >= 0 && diff < tick) - continue; - await nextTick(); - ts += diff; - } -} -/** - * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) - */ -function utf8ToBytes$1(str) { - if (typeof str !== 'string') - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 -} -/** - * Normalizes (non-hex) string or Uint8Array to Uint8Array. - * Warning: when Uint8Array is passed, it would NOT get copied. - * Keep in mind for future mutable operations. - */ -function toBytes(data) { - if (typeof data === 'string') - data = utf8ToBytes$1(data); - if (!u8a$1(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; -} -/** - * Copies several Uint8Arrays into one. - */ -function concatBytes$1(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; // walk through each item, ensure they have proper type - arrays.forEach((a) => { - if (!u8a$1(a)) - throw new Error('Uint8Array expected'); - r.set(a, pad); - pad += a.length; - }); - return r; -} -// For runtime check if class implements interface -class Hash { - // Safe version that clones internal state - clone() { - return this._cloneInto(); - } -} -const toStr = {}.toString; -function checkOpts(defaults, opts) { - if (opts !== undefined && toStr.call(opts) !== '[object Object]') - throw new Error('Options should be object or undefined'); - const merged = Object.assign(defaults, opts); - return merged; -} -function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; -} -/** - * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. - */ -function randomBytes$2(bytesLength = 32) { - if (crypto$1 && typeof crypto$1.getRandomValues === 'function') { - return crypto$1.getRandomValues(new Uint8Array(bytesLength)); - } - throw new Error('crypto.getRandomValues must be defined'); -} - -// HMAC (RFC 2104) -class HMAC extends Hash { - constructor(hash$1, _key) { - super(); - this.finished = false; - this.destroyed = false; - hash(hash$1); - const key = toBytes(_key); - this.iHash = hash$1.create(); - if (typeof this.iHash.update !== 'function') - throw new Error('Expected instance of class which extends utils.Hash'); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - // blockLen can be bigger than outputLen - pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 0x36; - this.iHash.update(pad); - // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone - this.oHash = hash$1.create(); - // Undo internal XOR && apply outer XOR - for (let i = 0; i < pad.length; i++) - pad[i] ^= 0x36 ^ 0x5c; - this.oHash.update(pad); - pad.fill(0); - } - update(buf) { - exists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - exists(this); - bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - // Create new instance without calling constructor since key already in state and we don't know it. - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } -} -/** - * HMAC: RFC2104 message authentication code. - * @param hash - function that would be used e.g. sha256 - * @param key - message key - * @param message - message data - */ -const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); -hmac.create = (hash, key) => new HMAC(hash, key); - -// Common prologue and epilogue for sync/async functions -function pbkdf2Init(hash$1, _password, _salt, _opts) { - hash(hash$1); - const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); - const { c, dkLen, asyncTick } = opts; - number(c); - number(dkLen); - number(asyncTick); - if (c < 1) - throw new Error('PBKDF2: iterations (c) should be >= 1'); - const password = toBytes(_password); - const salt = toBytes(_salt); - // DK = PBKDF2(PRF, Password, Salt, c, dkLen); - const DK = new Uint8Array(dkLen); - // U1 = PRF(Password, Salt + INT_32_BE(i)) - const PRF = hmac.create(hash$1, password); - const PRFSalt = PRF._cloneInto().update(salt); - return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; -} -function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { - PRF.destroy(); - PRFSalt.destroy(); - if (prfW) - prfW.destroy(); - u.fill(0); - return DK; -} -/** - * PBKDF2-HMAC: RFC 2898 key derivation function - * @param hash - hash function that would be used e.g. sha256 - * @param password - password from which a derived key is generated - * @param salt - cryptographic salt - * @param opts - {c, dkLen} where c is work factor and dkLen is output message size - */ -function pbkdf2$1(hash, password, salt, opts) { - const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); - let prfW; // Working copy - const arr = new Uint8Array(4); - const view = createView(arr); - const u = new Uint8Array(PRF.outputLen); - // DK = T1 + T2 + ⋯ + Tdklen/hlen - for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { - // Ti = F(Password, Salt, c, i) - const Ti = DK.subarray(pos, pos + PRF.outputLen); - view.setInt32(0, ti, false); - // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc - // U1 = PRF(Password, Salt + INT_32_BE(i)) - (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); - Ti.set(u.subarray(0, Ti.length)); - for (let ui = 1; ui < c; ui++) { - // Uc = PRF(Password, Uc−1) - PRF._cloneInto(prfW).update(u).digestInto(u); - for (let i = 0; i < Ti.length; i++) - Ti[i] ^= u[i]; - } - } - return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); -} - -// Polyfill for Safari 14 -function setBigUint64(view, byteOffset, value, isLE) { - if (typeof view.setBigUint64 === 'function') - return view.setBigUint64(byteOffset, value, isLE); - const _32n = BigInt(32); - const _u32_max = BigInt(0xffffffff); - const wh = Number((value >> _32n) & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE ? 4 : 0; - const l = isLE ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE); - view.setUint32(byteOffset + l, wl, isLE); -} -// Base SHA2 class (RFC 6234) -class SHA2 extends Hash { - constructor(blockLen, outputLen, padOffset, isLE) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - exists(this); - const { view, buffer, blockLen } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len;) { - const take = Math.min(blockLen - this.pos, len - pos); - // Fast path: we have at least one block in input, cast it to view and process - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - exists(this); - output(out, this); - this.finished = true; - // Padding - // We can avoid allocation of buffer for padding completely if it - // was previously not allocated here. But it won't change performance. - const { buffer, view, blockLen, isLE } = this; - let { pos } = this; - // append the bit '1' to the message - buffer[pos++] = 0b10000000; - this.buffer.subarray(pos).fill(0); - // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - // Pad until full block byte with zeros - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; - // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that - // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. - // So we just write lowest 64 bits of that value. - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT - if (len % 4) - throw new Error('_sha2: outputLen should be aligned to 32bit'); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error('_sha2: outputLen bigger than state'); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } -} - -// SHA2-256 need to try 2^128 hashes to execute birthday attack. -// BTC network is doing 2^67 hashes/sec as per early 2023. -// Choice: a ? b : c -const Chi = (a, b, c) => (a & b) ^ (~a & c); -// Majority function, true if any two inpust is true -const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); -// Round constants: -// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) -// prettier-ignore -const SHA256_K = /* @__PURE__ */ new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]); -// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): -// prettier-ignore -const IV = /* @__PURE__ */ new Uint32Array([ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 -]); -// Temporary buffer, not used to store anything between runs -// Named this way because it matches specification. -const SHA256_W = /* @__PURE__ */ new Uint32Array(64); -class SHA256 extends SHA2 { - constructor() { - super(64, 32, 8, false); - // We cannot use array here since array allows indexing by variable - // which means optimizer/compiler cannot use registers. - this.A = IV[0] | 0; - this.B = IV[1] | 0; - this.C = IV[2] | 0; - this.D = IV[3] | 0; - this.E = IV[4] | 0; - this.F = IV[5] | 0; - this.G = IV[6] | 0; - this.H = IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - // prettier-ignore - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array - for (let i = 0; i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); - SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; - } - // Compression function main loop, 64 rounds - let { A, B, C, D, E, F, G, H } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = (sigma0 + Maj(A, B, C)) | 0; - H = G; - G = F; - F = E; - E = (D + T1) | 0; - D = C; - C = B; - B = A; - A = (T1 + T2) | 0; - } - // Add the compressed chunk to the current hash value - A = (A + this.A) | 0; - B = (B + this.B) | 0; - C = (C + this.C) | 0; - D = (D + this.D) | 0; - E = (E + this.E) | 0; - F = (F + this.F) | 0; - G = (G + this.G) | 0; - H = (H + this.H) | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - SHA256_W.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } -} -/** - * SHA2-256 hash function - * @param message - data that would be hashed - */ -const sha256$1 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); - -const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); -const _32n = /* @__PURE__ */ BigInt(32); -// We are not using BigUint64Array, because they are extremely slow as per 2022 -function fromBig(n, le = false) { - if (le) - return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; - return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; -} -function split(lst, le = false) { - let Ah = new Uint32Array(lst.length); - let Al = new Uint32Array(lst.length); - for (let i = 0; i < lst.length; i++) { - const { h, l } = fromBig(lst[i], le); - [Ah[i], Al[i]] = [h, l]; - } - return [Ah, Al]; -} -const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); -// for Shift in [0, 32) -const shrSH = (h, _l, s) => h >>> s; -const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); -// Right rotate for Shift in [1, 32) -const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); -const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); -// Right rotate for Shift in (32, 64), NOTE: 32 is special case. -const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); -const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); -// Right rotate for shift===32 (just swaps l&h) -const rotr32H = (_h, l) => l; -const rotr32L = (h, _l) => h; -// Left rotate for Shift in [1, 32) -const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); -const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); -// Left rotate for Shift in (32, 64), NOTE: 32 is special case. -const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); -const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); -// JS uses 32-bit signed integers for bitwise operations which means we cannot -// simple take carry out of low bit sum by shift, we need to use division. -function add(Ah, Al, Bh, Bl) { - const l = (Al >>> 0) + (Bl >>> 0); - return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; -} -// Addition with more than 2 elements -const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); -const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; -const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); -const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; -const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); -const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; -// prettier-ignore -const u64 = { - fromBig, split, toBig, - shrSH, shrSL, - rotrSH, rotrSL, rotrBH, rotrBL, - rotr32H, rotr32L, - rotlSH, rotlSL, rotlBH, rotlBL, - add, add3L, add3H, add4L, add4H, add5H, add5L, -}; - -// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): -// prettier-ignore -const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ - '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', - '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', - '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', - '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', - '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', - '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', - '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', - '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', - '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', - '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', - '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', - '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', - '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', - '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', - '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', - '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', - '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', - '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', - '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', - '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' -].map(n => BigInt(n))))(); -// Temporary buffer, not used to store anything between runs -const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); -const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); -class SHA512 extends SHA2 { - constructor() { - super(128, 64, 16, false); - // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. - // Also looks cleaner and easier to verify with spec. - // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): - // h -- high 32 bits, l -- low 32 bits - this.Ah = 0x6a09e667 | 0; - this.Al = 0xf3bcc908 | 0; - this.Bh = 0xbb67ae85 | 0; - this.Bl = 0x84caa73b | 0; - this.Ch = 0x3c6ef372 | 0; - this.Cl = 0xfe94f82b | 0; - this.Dh = 0xa54ff53a | 0; - this.Dl = 0x5f1d36f1 | 0; - this.Eh = 0x510e527f | 0; - this.El = 0xade682d1 | 0; - this.Fh = 0x9b05688c | 0; - this.Fl = 0x2b3e6c1f | 0; - this.Gh = 0x1f83d9ab | 0; - this.Gl = 0xfb41bd6b | 0; - this.Hh = 0x5be0cd19 | 0; - this.Hl = 0x137e2179 | 0; - } - // prettier-ignore - get() { - const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; - } - // prettier-ignore - set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { - this.Ah = Ah | 0; - this.Al = Al | 0; - this.Bh = Bh | 0; - this.Bl = Bl | 0; - this.Ch = Ch | 0; - this.Cl = Cl | 0; - this.Dh = Dh | 0; - this.Dl = Dl | 0; - this.Eh = Eh | 0; - this.El = El | 0; - this.Fh = Fh | 0; - this.Fl = Fl | 0; - this.Gh = Gh | 0; - this.Gl = Gl | 0; - this.Hh = Hh | 0; - this.Hl = Hl | 0; - } - process(view, offset) { - // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array - for (let i = 0; i < 16; i++, offset += 4) { - SHA512_W_H[i] = view.getUint32(offset); - SHA512_W_L[i] = view.getUint32((offset += 4)); - } - for (let i = 16; i < 80; i++) { - // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) - const W15h = SHA512_W_H[i - 15] | 0; - const W15l = SHA512_W_L[i - 15] | 0; - const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); - const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); - // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) - const W2h = SHA512_W_H[i - 2] | 0; - const W2l = SHA512_W_L[i - 2] | 0; - const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); - const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); - // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; - const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); - const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); - SHA512_W_H[i] = SUMh | 0; - SHA512_W_L[i] = SUMl | 0; - } - let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - // Compression function main loop, 80 rounds - for (let i = 0; i < 80; i++) { - // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) - const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); - const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); - //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; - const CHIh = (Eh & Fh) ^ (~Eh & Gh); - const CHIl = (El & Fl) ^ (~El & Gl); - // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] - // prettier-ignore - const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); - const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); - const T1l = T1ll | 0; - // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) - const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); - const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); - const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); - const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); - Hh = Gh | 0; - Hl = Gl | 0; - Gh = Fh | 0; - Gl = Fl | 0; - Fh = Eh | 0; - Fl = El | 0; - ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); - Dh = Ch | 0; - Dl = Cl | 0; - Ch = Bh | 0; - Cl = Bl | 0; - Bh = Ah | 0; - Bl = Al | 0; - const All = u64.add3L(T1l, sigma0l, MAJl); - Ah = u64.add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } - // Add the compressed chunk to the current hash value - ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); - ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); - ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); - ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); - ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); - ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); - ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); - ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); - this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); - } - roundClean() { - SHA512_W_H.fill(0); - SHA512_W_L.fill(0); - } - destroy() { - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } -} -const sha512$1 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); - -/* Browser Crypto Shims */ -function getGlobal$1() { - if (typeof self !== 'undefined') { - return self; - } - if (typeof window !== 'undefined') { - return window; - } - if (typeof global !== 'undefined') { - return global; - } - throw new Error('unable to locate global object'); -} -const anyGlobal = getGlobal$1(); -const crypto = anyGlobal.crypto || anyGlobal.msCrypto; -function createHash(algo) { - switch (algo) { - case 'sha256': - return sha256$1.create(); - case 'sha512': - return sha512$1.create(); - } - assertArgument(false, 'invalid hashing algorithm name', 'algorithm', algo); -} -function createHmac(_algo, key) { - const algo = { sha256: sha256$1, sha512: sha512$1 }[_algo]; - assertArgument(algo != null, 'invalid hmac algorithm', 'algorithm', _algo); - return hmac.create(algo, key); -} -function pbkdf2Sync(password, salt, iterations, keylen, _algo) { - const algo = { sha256: sha256$1, sha512: sha512$1 }[_algo]; - assertArgument(algo != null, 'invalid pbkdf2 algorithm', 'algorithm', _algo); - return pbkdf2$1(algo, password, salt, { c: iterations, dkLen: keylen }); -} -function randomBytes$1(length) { - assert(crypto != null, 'platform does not support secure random numbers', 'UNSUPPORTED_OPERATION', { - operation: 'randomBytes', - }); - assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, 'invalid length', 'length', length); - const result = new Uint8Array(length); - crypto.getRandomValues(result); - return result; -} - -/** - * An **HMAC** enables verification that a given key was used to authenticate a payload. - * - * @see {@link https://en.wikipedia.org/wiki/HMAC | HMAC - Wikipedia} - */ -let locked$4 = false; -const _computeHmac = function (algorithm, key, data) { - return createHmac(algorithm, key).update(data).digest(); -}; -let __computeHmac = _computeHmac; -/** - * Return the HMAC for `data` using the `key` key with the underlying `algo` used for compression. - * - * @category Crypto - * @example - * - * ```js - * key = id('some-secret'); - * - * // Compute the HMAC - * computeHmac('sha256', key, '0x1337'); - * - * // To compute the HMAC of UTF-8 data, the data must be - * // converted to UTF-8 bytes - * computeHmac('sha256', key, toUtf8Bytes('Hello World')); - * ``` - * - * @param {'sha256' | 'sha512'} algorithm - The algorithm to use for compression. - * @param {BytesLike} _key - The key to use for the HMAC. - * @param {BytesLike} _data - The data to authenticate. - * @returns {string} The HMAC of the data. - */ -function computeHmac(algorithm, _key, _data) { - const key = getBytes(_key, 'key'); - const data = getBytes(_data, 'data'); - return hexlify(__computeHmac(algorithm, key, data)); -} -computeHmac._ = _computeHmac; -computeHmac.lock = function () { - locked$4 = true; -}; -computeHmac.register = function (func) { - if (locked$4) { - throw new Error('computeHmac is locked'); - } - __computeHmac = func; -}; -Object.freeze(computeHmac); - -// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. -// It's called a sponge function. -// Various per round constants calculations -const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; -const _0n$6 = /* @__PURE__ */ BigInt(0); -const _1n$6 = /* @__PURE__ */ BigInt(1); -const _2n$4 = /* @__PURE__ */ BigInt(2); -const _7n$1 = /* @__PURE__ */ BigInt(7); -const _256n = /* @__PURE__ */ BigInt(256); -const _0x71n = /* @__PURE__ */ BigInt(0x71); -for (let round = 0, R = _1n$6, x = 1, y = 0; round < 24; round++) { - // Pi - [x, y] = [y, (2 * x + 3 * y) % 5]; - SHA3_PI.push(2 * (5 * y + x)); - // Rotational - SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); - // Iota - let t = _0n$6; - for (let j = 0; j < 7; j++) { - R = ((R << _1n$6) ^ ((R >> _7n$1) * _0x71n)) % _256n; - if (R & _2n$4) - t ^= _1n$6 << ((_1n$6 << /* @__PURE__ */ BigInt(j)) - _1n$6); - } - _SHA3_IOTA.push(t); -} -const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); -// Left rotation (without 0, 32, 64) -const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); -const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); -// Same as keccakf1600, but allows to skip some rounds -function keccakP(s, rounds = 24) { - const B = new Uint32Array(5 * 2); - // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) - for (let round = 24 - rounds; round < 24; round++) { - // Theta θ - for (let x = 0; x < 10; x++) - B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; - for (let x = 0; x < 10; x += 2) { - const idx1 = (x + 8) % 10; - const idx0 = (x + 2) % 10; - const B0 = B[idx0]; - const B1 = B[idx0 + 1]; - const Th = rotlH(B0, B1, 1) ^ B[idx1]; - const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; - for (let y = 0; y < 50; y += 10) { - s[x + y] ^= Th; - s[x + y + 1] ^= Tl; - } - } - // Rho (ρ) and Pi (π) - let curH = s[2]; - let curL = s[3]; - for (let t = 0; t < 24; t++) { - const shift = SHA3_ROTL[t]; - const Th = rotlH(curH, curL, shift); - const Tl = rotlL(curH, curL, shift); - const PI = SHA3_PI[t]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = Th; - s[PI + 1] = Tl; - } - // Chi (χ) - for (let y = 0; y < 50; y += 10) { - for (let x = 0; x < 10; x++) - B[x] = s[y + x]; - for (let x = 0; x < 10; x++) - s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; - } - // Iota (ι) - s[0] ^= SHA3_IOTA_H[round]; - s[1] ^= SHA3_IOTA_L[round]; - } - B.fill(0); -} -class Keccak extends Hash { - // NOTE: we accept arguments in bytes instead of bits here. - constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { - super(); - this.blockLen = blockLen; - this.suffix = suffix; - this.outputLen = outputLen; - this.enableXOF = enableXOF; - this.rounds = rounds; - this.pos = 0; - this.posOut = 0; - this.finished = false; - this.destroyed = false; - // Can be passed from user as dkLen - number(outputLen); - // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes - if (0 >= this.blockLen || this.blockLen >= 200) - throw new Error('Sha3 supports only keccak-f1600 function'); - this.state = new Uint8Array(200); - this.state32 = u32(this.state); - } - keccak() { - keccakP(this.state32, this.rounds); - this.posOut = 0; - this.pos = 0; - } - update(data) { - exists(this); - const { blockLen, state } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len;) { - const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0; i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); - } - return this; - } - finish() { - if (this.finished) - return; - this.finished = true; - const { state, suffix, pos, blockLen } = this; - // Do the padding - state[pos] ^= suffix; - if ((suffix & 0x80) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 0x80; - this.keccak(); - } - writeInto(out) { - exists(this, false); - bytes(out); - this.finish(); - const bufferOut = this.state; - const { blockLen } = this; - for (let pos = 0, len = out.length; pos < len;) { - if (this.posOut >= blockLen) - this.keccak(); - const take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; - } - return out; - } - xofInto(out) { - // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF - if (!this.enableXOF) - throw new Error('XOF is not possible for this instance'); - return this.writeInto(out); - } - xof(bytes) { - number(bytes); - return this.xofInto(new Uint8Array(bytes)); - } - digestInto(out) { - output(out, this); - if (this.finished) - throw new Error('digest() was already called'); - this.writeInto(out); - this.destroy(); - return out; - } - digest() { - return this.digestInto(new Uint8Array(this.outputLen)); - } - destroy() { - this.destroyed = true; - this.state.fill(0); - } - _cloneInto(to) { - const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); - to.state32.set(this.state32); - to.pos = this.pos; - to.posOut = this.posOut; - to.finished = this.finished; - to.rounds = rounds; - // Suffix can change in cSHAKE - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.destroyed = this.destroyed; - return to; - } -} -const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); -/** - * keccak-256 hash function. Different from SHA3-256. - * @param message - that would be hashed - */ -const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); - -/** - * Cryptographic hashing functions - */ -let locked$3 = false; -const _keccak256 = function (data) { - return keccak_256(data); -}; -let __keccak256 = _keccak256; -/** - * Compute the cryptographic KECCAK256 hash of `data`. - * - * The `data` **must** be a data representation, to compute the hash of UTF-8 data use the [**id**}(../functions/id) - * function. - * - * @category Crypto - * @example - * - * ```ts - * keccak256('0x'); - * - * keccak256('0x1337'); - * - * keccak256(new Uint8Array([0x13, 0x37])); - * - * // Strings are assumed to be DataHexString, otherwise it will - * // throw. To hash UTF-8 data, see the note above. - * keccak256('Hello World'); - * ``` - * - * @param {BytesLike} _data - The data to hash. - * @returns DataHexstring - * @returns {string} The hash of the data. - */ -function keccak256(_data) { - const data = getBytes(_data, 'data'); - return hexlify(__keccak256(data)); -} -keccak256._ = _keccak256; -keccak256.lock = function () { - locked$3 = true; -}; -keccak256.register = function (func) { - if (locked$3) { - throw new TypeError('keccak256 is locked'); - } - __keccak256 = func; -}; -Object.freeze(keccak256); - -// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html -// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf -const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); -const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); -const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); -let idxL = [Id]; -let idxR = [Pi]; -for (let i = 0; i < 4; i++) - for (let j of [idxL, idxR]) - j.push(j[i].map((k) => Rho[k])); -const shifts = /* @__PURE__ */ [ - [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], - [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], - [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], - [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], - [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], -].map((i) => new Uint8Array(i)); -const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); -const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); -const Kl = /* @__PURE__ */ new Uint32Array([ - 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, -]); -const Kr = /* @__PURE__ */ new Uint32Array([ - 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, -]); -// The rotate left (circular left shift) operation for uint32 -const rotl$1 = (word, shift) => (word << shift) | (word >>> (32 - shift)); -// It's called f() in spec. -function f(group, x, y, z) { - if (group === 0) - return x ^ y ^ z; - else if (group === 1) - return (x & y) | (~x & z); - else if (group === 2) - return (x | ~y) ^ z; - else if (group === 3) - return (x & z) | (y & ~z); - else - return x ^ (y | ~z); -} -// Temporary buffer, not used to store anything between runs -const BUF = /* @__PURE__ */ new Uint32Array(16); -class RIPEMD160 extends SHA2 { - constructor() { - super(64, 20, 8, true); - this.h0 = 0x67452301 | 0; - this.h1 = 0xefcdab89 | 0; - this.h2 = 0x98badcfe | 0; - this.h3 = 0x10325476 | 0; - this.h4 = 0xc3d2e1f0 | 0; - } - get() { - const { h0, h1, h2, h3, h4 } = this; - return [h0, h1, h2, h3, h4]; - } - set(h0, h1, h2, h3, h4) { - this.h0 = h0 | 0; - this.h1 = h1 | 0; - this.h2 = h2 | 0; - this.h3 = h3 | 0; - this.h4 = h4 | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - BUF[i] = view.getUint32(offset, true); - // prettier-ignore - let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; - // Instead of iterating 0 to 80, we split it into 5 groups - // And use the groups in constants, functions, etc. Much simpler - for (let group = 0; group < 5; group++) { - const rGroup = 4 - group; - const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore - const rl = idxL[group], rr = idxR[group]; // prettier-ignore - const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore - for (let i = 0; i < 16; i++) { - const tl = (rotl$1(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; - al = el, el = dl, dl = rotl$1(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore - } - // 2 loops are 10% faster - for (let i = 0; i < 16; i++) { - const tr = (rotl$1(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; - ar = er, er = dr, dr = rotl$1(cr, 10) | 0, cr = br, br = tr; // prettier-ignore - } - } - // Add the compressed chunk to the current hash value - this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); - } - roundClean() { - BUF.fill(0); - } - destroy() { - this.destroyed = true; - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0); - } -} -/** - * RIPEMD-160 - a hash function from 1990s. - * @param message - msg that would be hashed - */ -const ripemd160$1 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); - -let locked$2 = false; -const _ripemd160 = function (data) { - return ripemd160$1(data); -}; -let __ripemd160 = _ripemd160; -/** - * Compute the cryptographic RIPEMD-160 hash of `data`. - * - * @category Crypto - * @example - * - * ```ts - * ripemd160('0x'); - * - * ripemd160('0x1337'); - * - * ripemd160(new Uint8Array([0x13, 0x37])); - * ``` - * - * @param {BytesLike} _data - The data to hash. - * @returns DataHexstring - * @returns {string} The hash of the data. - */ -function ripemd160(_data) { - const data = getBytes(_data, 'data'); - return hexlify(__ripemd160(data)); -} -ripemd160._ = _ripemd160; -ripemd160.lock = function () { - locked$2 = true; -}; -ripemd160.register = function (func) { - if (locked$2) { - throw new TypeError('ripemd160 is locked'); - } - __ripemd160 = func; -}; -Object.freeze(ripemd160); - -/** - * A **Password-Based Key-Derivation Function** is designed to create a sequence of bytes suitible as a **key** from a - * human-rememberable password. - */ -let locked$1 = false; -const _pbkdf2 = function (password, salt, iterations, keylen, algo) { - return pbkdf2Sync(password, salt, iterations, keylen, algo); -}; -let __pbkdf2 = _pbkdf2; -/** - * Return the [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) for `keylen` bytes for `password` using the `salt` and - * using `iterations` of `algo`. - * - * This PBKDF is outdated and should not be used in new projects, but is required to decrypt older files. - * - * @category Crypto - * @example - * - * ```ts - * // The password must be converted to bytes, and it is generally - * // best practices to ensure the string has been normalized. Many - * // formats explicitly indicate the normalization form to use. - * password = 'hello'; - * passwordBytes = toUtf8Bytes(password, 'NFKC'); - * - * salt = id('some-salt'); - * - * // Compute the PBKDF2 - * pbkdf2(passwordBytes, salt, 1024, 16, 'sha256'); - * ``` - * - * @param {BytesLike} _password - The password to use. - * @param {BytesLike} _salt - The salt to use. - * @param {number} iterations - The number of iterations to use. - * @param {number} keylen - The length of the key to generate. - * @param {'sha256' | 'sha512'} algo - The algorithm to use. - * @returns {string} The key derived from the password. - */ -function pbkdf2(_password, _salt, iterations, keylen, algo) { - const password = getBytes(_password, 'password'); - const salt = getBytes(_salt, 'salt'); - return hexlify(__pbkdf2(password, salt, iterations, keylen, algo)); -} -pbkdf2._ = _pbkdf2; -pbkdf2.lock = function () { - locked$1 = true; -}; -pbkdf2.register = function (func) { - if (locked$1) { - throw new Error('pbkdf2 is locked'); - } - __pbkdf2 = func; -}; -Object.freeze(pbkdf2); - -/** - * A **Cryptographically Secure Random Value** is one that has been generated with additional care take to prevent - * side-channels from allowing others to detect it and prevent others from through coincidence generate the same - * values. - */ -let locked = false; -const _randomBytes = function (length) { - return new Uint8Array(randomBytes$1(length)); -}; -let __randomBytes = _randomBytes; -/** - * Return `length` bytes of cryptographically secure random data. - * - * @category Crypto - * @example - * - * ```ts - * randomBytes(8); - * ``` - * - * @param {number} length - The number of bytes to generate. - * @returns {Uint8Array} The random bytes. - */ -function randomBytes(length) { - return __randomBytes(length); -} -randomBytes._ = _randomBytes; -randomBytes.lock = function () { - locked = true; -}; -randomBytes.register = function (func) { - if (locked) { - throw new Error('randomBytes is locked'); - } - __randomBytes = func; -}; -Object.freeze(randomBytes); - -// RFC 7914 Scrypt KDF -// Left rotate for uint32 -const rotl = (a, b) => (a << b) | (a >>> (32 - b)); -// The main Scrypt loop: uses Salsa extensively. -// Six versions of the function were tried, this is the fastest one. -// prettier-ignore -function XorAndSalsa(prev, pi, input, ii, out, oi) { - // Based on https://cr.yp.to/salsa20.html - // Xor blocks - let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; - let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; - let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; - let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; - let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; - let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; - let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; - let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; - // Save state to temporary variables (salsa) - let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; - // Main loop (salsa) - for (let i = 0; i < 8; i += 2) { - x04 ^= rotl(x00 + x12 | 0, 7); - x08 ^= rotl(x04 + x00 | 0, 9); - x12 ^= rotl(x08 + x04 | 0, 13); - x00 ^= rotl(x12 + x08 | 0, 18); - x09 ^= rotl(x05 + x01 | 0, 7); - x13 ^= rotl(x09 + x05 | 0, 9); - x01 ^= rotl(x13 + x09 | 0, 13); - x05 ^= rotl(x01 + x13 | 0, 18); - x14 ^= rotl(x10 + x06 | 0, 7); - x02 ^= rotl(x14 + x10 | 0, 9); - x06 ^= rotl(x02 + x14 | 0, 13); - x10 ^= rotl(x06 + x02 | 0, 18); - x03 ^= rotl(x15 + x11 | 0, 7); - x07 ^= rotl(x03 + x15 | 0, 9); - x11 ^= rotl(x07 + x03 | 0, 13); - x15 ^= rotl(x11 + x07 | 0, 18); - x01 ^= rotl(x00 + x03 | 0, 7); - x02 ^= rotl(x01 + x00 | 0, 9); - x03 ^= rotl(x02 + x01 | 0, 13); - x00 ^= rotl(x03 + x02 | 0, 18); - x06 ^= rotl(x05 + x04 | 0, 7); - x07 ^= rotl(x06 + x05 | 0, 9); - x04 ^= rotl(x07 + x06 | 0, 13); - x05 ^= rotl(x04 + x07 | 0, 18); - x11 ^= rotl(x10 + x09 | 0, 7); - x08 ^= rotl(x11 + x10 | 0, 9); - x09 ^= rotl(x08 + x11 | 0, 13); - x10 ^= rotl(x09 + x08 | 0, 18); - x12 ^= rotl(x15 + x14 | 0, 7); - x13 ^= rotl(x12 + x15 | 0, 9); - x14 ^= rotl(x13 + x12 | 0, 13); - x15 ^= rotl(x14 + x13 | 0, 18); - } - // Write output (salsa) - out[oi++] = (y00 + x00) | 0; - out[oi++] = (y01 + x01) | 0; - out[oi++] = (y02 + x02) | 0; - out[oi++] = (y03 + x03) | 0; - out[oi++] = (y04 + x04) | 0; - out[oi++] = (y05 + x05) | 0; - out[oi++] = (y06 + x06) | 0; - out[oi++] = (y07 + x07) | 0; - out[oi++] = (y08 + x08) | 0; - out[oi++] = (y09 + x09) | 0; - out[oi++] = (y10 + x10) | 0; - out[oi++] = (y11 + x11) | 0; - out[oi++] = (y12 + x12) | 0; - out[oi++] = (y13 + x13) | 0; - out[oi++] = (y14 + x14) | 0; - out[oi++] = (y15 + x15) | 0; -} -function BlockMix(input, ii, out, oi, r) { - // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) - let head = oi + 0; - let tail = oi + 16 * r; - for (let i = 0; i < 16; i++) - out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] - for (let i = 0; i < r; i++, head += 16, ii += 16) { - // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 - XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) - if (i > 0) - tail += 16; // First iteration overwrites tmp value in tail - XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) - } -} -// Common prologue and epilogue for sync/async functions -function scryptInit(password, salt, _opts) { - // Maxmem - 1GB+1KB by default - const opts = checkOpts({ - dkLen: 32, - asyncTick: 10, - maxmem: 1024 ** 3 + 1024, - }, _opts); - const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; - number(N); - number(r); - number(p); - number(dkLen); - number(asyncTick); - number(maxmem); - if (onProgress !== undefined && typeof onProgress !== 'function') - throw new Error('progressCb should be function'); - const blockSize = 128 * r; - const blockSize32 = blockSize / 4; - if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { - // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function - // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. - throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); - } - if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { - throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); - } - if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { - throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); - } - const memUsed = blockSize * (N + p); - if (memUsed > maxmem) { - throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); - } - // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) - // Since it has only one iteration there is no reason to use async variant - const B = pbkdf2$1(sha256$1, password, salt, { c: 1, dkLen: blockSize * p }); - const B32 = u32(B); - // Re-used between parallel iterations. Array(iterations) of B - const V = u32(new Uint8Array(blockSize * N)); - const tmp = u32(new Uint8Array(blockSize)); - let blockMixCb = () => { }; - if (onProgress) { - const totalBlockMix = 2 * N * p; - // Invoke callback if progress changes from 10.01 to 10.02 - // Allows to draw smooth progress bar on up to 8K screen - const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); - let blockMixCnt = 0; - blockMixCb = () => { - blockMixCnt++; - if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) - onProgress(blockMixCnt / totalBlockMix); - }; - } - return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; -} -function scryptOutput(password, dkLen, B, V, tmp) { - const res = pbkdf2$1(sha256$1, password, B, { c: 1, dkLen }); - B.fill(0); - V.fill(0); - tmp.fill(0); - return res; -} -/** - * Scrypt KDF from RFC 7914. - * @param password - pass - * @param salt - salt - * @param opts - parameters - * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) - * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance - * - `p` is parallelization factor (1 is common) - * - `dkLen` is output key length in bytes e.g. 32. - * - `asyncTick` - (default: 10) max time in ms for which async function can block execution - * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt - * - `onProgress` - callback function that would be executed for progress report - * @returns Derived key - */ -function scrypt$1(password, salt, opts) { - const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); - for (let pi = 0; pi < p; pi++) { - const Pi = blockSize32 * pi; - for (let i = 0; i < blockSize32; i++) - V[i] = B32[Pi + i]; // V[0] = B[i] - for (let i = 0, pos = 0; i < N - 1; i++) { - BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); - blockMixCb(); - } - BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element - blockMixCb(); - for (let i = 0; i < N; i++) { - // First u32 of the last 64-byte block (u32 is LE) - const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations - for (let k = 0; k < blockSize32; k++) - tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] - BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) - blockMixCb(); - } - } - return scryptOutput(password, dkLen, B, V, tmp); -} -/** - * Scrypt KDF from RFC 7914. - */ -async function scryptAsync(password, salt, opts) { - const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); - for (let pi = 0; pi < p; pi++) { - const Pi = blockSize32 * pi; - for (let i = 0; i < blockSize32; i++) - V[i] = B32[Pi + i]; // V[0] = B[i] - let pos = 0; - await asyncLoop(N - 1, asyncTick, () => { - BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); - blockMixCb(); - }); - BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element - blockMixCb(); - await asyncLoop(N, asyncTick, () => { - // First u32 of the last 64-byte block (u32 is LE) - const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations - for (let k = 0; k < blockSize32; k++) - tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] - BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) - blockMixCb(); - }); - } - return scryptOutput(password, dkLen, B, V, tmp); -} - -let lockedSync = false, lockedAsync = false; -const _scryptAsync = async function (passwd, salt, N, r, p, dkLen, onProgress) { - return await scryptAsync(passwd, salt, { N, r, p, dkLen, onProgress }); -}; -const _scryptSync = function (passwd, salt, N, r, p, dkLen) { - return scrypt$1(passwd, salt, { N, r, p, dkLen }); -}; -let __scryptAsync = _scryptAsync; -let __scryptSync = _scryptSync; -/** - * The [scrypt PBKDF](https://en.wikipedia.org/wiki/Scrypt) uses a memory and cpu hard method of derivation to increase - * the resource cost to brute-force a password for a given key. - * - * This means this algorithm is intentionally slow, and can be tuned to become slower. As computation and memory speed - * improve over time, increasing the difficulty maintains the cost of an attacker. - * - * For example, if a target time of 5 seconds is used, a legitimate user which knows their password requires only 5 - * seconds to unlock their account. A 6 character password has 68 billion possibilities, which would require an attacker - * to invest over 10,000 years of CPU time. This is of course a crude example (as password generally aren't random), but - * demonstrates to value of imposing large costs to decryption. - * - * For this reason, if building a UI which involved decrypting or encrypting datsa using scrypt, it is recommended to - * use a [**ProgressCallback**](../types-aliases/ProgressCallback) (as event short periods can seem lik an eternity if - * the UI freezes). Including the phrase //"decrypting"// in the UI can also help, assuring the user their waiting is - * for a good reason. - * - * @category Crypto - * @example - * - * ```ts - * // The password must be converted to bytes, and it is generally - * // best practices to ensure the string has been normalized. Many - * // formats explicitly indicate the normalization form to use. - * password = 'hello'; - * passwordBytes = toUtf8Bytes(password, 'NFKC'); - * - * salt = id('some-salt'); - * - * // Compute the scrypt - * scrypt(passwordBytes, salt, 1024, 8, 1, 16); - * ``` - * - * @param {BytesLike} _passwd - The password to use. - * @param {BytesLike} _salt - The salt to use. - * @param {number} N - The CPU/memory cost parameter. - * @param {number} r - The block size parameter. - * @param {number} p - The parallelization parameter. - * @param {number} dkLen - The length of the key to generate. - * @param {ProgressCallback} [progress] - A callback to update the progress. - * @returns {Promise} The key derived from the password. - */ -async function scrypt(_passwd, _salt, N, r, p, dkLen, progress) { - const passwd = getBytes(_passwd, 'passwd'); - const salt = getBytes(_salt, 'salt'); - return hexlify(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress)); -} -scrypt._ = _scryptAsync; -scrypt.lock = function () { - lockedAsync = true; -}; -scrypt.register = function (func) { - if (lockedAsync) { - throw new Error('scrypt is locked'); - } - __scryptAsync = func; -}; -Object.freeze(scrypt); -/** - * Provides a synchronous variant of {@link scrypt | **scrypt**}. - * - * This will completely lock up and freeze the UI in a browser and will prevent any event loop from progressing. For - * this reason, it is preferred to use the [async variant](scrypt). - * - * @category Crypto - * @example - * - * ```ts - * // The password must be converted to bytes, and it is generally - * // best practices to ensure the string has been normalized. Many - * // formats explicitly indicate the normalization form to use. - * password = 'hello'; - * passwordBytes = toUtf8Bytes(password, 'NFKC'); - * - * salt = id('some-salt'); - * - * // Compute the scrypt - * scryptSync(passwordBytes, salt, 1024, 8, 1, 16); - * ``` - * - * @param {BytesLike} _passwd - The password to use. - * @param {BytesLike} _salt - The salt to use. - * @param {number} N - The CPU/memory cost parameter. - * @param {number} r - The block size parameter. - * @param {number} p - The parallelization parameter. - * @param {number} dkLen - The length of the key to generate. - * @returns {string} The key derived from the password. - */ -function scryptSync(_passwd, _salt, N, r, p, dkLen) { - const passwd = getBytes(_passwd, 'passwd'); - const salt = getBytes(_salt, 'salt'); - return hexlify(__scryptSync(passwd, salt, N, r, p, dkLen)); -} -scryptSync._ = _scryptSync; -scryptSync.lock = function () { - lockedSync = true; -}; -scryptSync.register = function (func) { - if (lockedSync) { - throw new Error('scryptSync is locked'); - } - __scryptSync = func; -}; -Object.freeze(scryptSync); - -const _sha256 = function (data) { - return createHash('sha256').update(data).digest(); -}; -const _sha512 = function (data) { - return createHash('sha512').update(data).digest(); -}; -let __sha256 = _sha256; -let __sha512 = _sha512; -let locked256 = false, locked512 = false; -/** - * Compute the cryptographic SHA2-256 hash of `data`. - * - * @category Crypto - * @example - * - * ```ts - * sha256('0x'); - * - * sha256('0x1337'); - * - * sha256(new Uint8Array([0x13, 0x37])); - * ``` - * - * @param {BytesLike} _data - The data to hash. - * @returns {string} The hash of the data. - */ -function sha256(_data) { - const data = getBytes(_data, 'data'); - return hexlify(__sha256(data)); -} -sha256._ = _sha256; -sha256.lock = function () { - locked256 = true; -}; -sha256.register = function (func) { - if (locked256) { - throw new Error('sha256 is locked'); - } - __sha256 = func; -}; -Object.freeze(sha256); -/** - * Compute the cryptographic SHA2-512 hash of `data`. - * - * @category Crypto - * @example - * - * ```ts - * sha512('0x'); - * - * sha512('0x1337'); - * - * sha512(new Uint8Array([0x13, 0x37])); - * ``` - * - * @param {BytesLike} _data - The data to hash. - * @returns {string} The hash of the data. - */ -function sha512(_data) { - const data = getBytes(_data, 'data'); - return hexlify(__sha512(data)); -} -sha512._ = _sha512; -sha512.lock = function () { - locked512 = true; -}; -sha512.register = function (func) { - if (locked512) { - throw new Error('sha512 is locked'); - } - __sha512 = func; -}; -Object.freeze(sha256); - -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -// 100 lines of code in the file are duplicated from noble-hashes (utils). -// This is OK: `abstract` directory does not use noble-hashes. -// User may opt-in into using different hashing library. This way, noble-hashes -// won't be included into their bundle. -const _0n$5 = BigInt(0); -const _1n$5 = BigInt(1); -const _2n$3 = BigInt(2); -const u8a = (a) => a instanceof Uint8Array; -const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); -/** - * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' - */ -function bytesToHex(bytes) { - if (!u8a(bytes)) - throw new Error('Uint8Array expected'); - // pre-caching improves the speed 6x - let hex = ''; - for (let i = 0; i < bytes.length; i++) { - hex += hexes[bytes[i]]; - } - return hex; -} -function numberToHexUnpadded(num) { - const hex = num.toString(16); - return hex.length & 1 ? `0${hex}` : hex; -} -function hexToNumber(hex) { - if (typeof hex !== 'string') - throw new Error('hex string expected, got ' + typeof hex); - // Big Endian - return BigInt(hex === '' ? '0' : `0x${hex}`); -} -/** - * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) - */ -function hexToBytes(hex) { - if (typeof hex !== 'string') - throw new Error('hex string expected, got ' + typeof hex); - const len = hex.length; - if (len % 2) - throw new Error('padded hex string expected, got unpadded hex of length ' + len); - const array = new Uint8Array(len / 2); - for (let i = 0; i < array.length; i++) { - const j = i * 2; - const hexByte = hex.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error('Invalid byte sequence'); - array[i] = byte; - } - return array; -} -// BE: Big Endian, LE: Little Endian -function bytesToNumberBE(bytes) { - return hexToNumber(bytesToHex(bytes)); -} -function bytesToNumberLE(bytes) { - if (!u8a(bytes)) - throw new Error('Uint8Array expected'); - return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); -} -function numberToBytesBE(n, len) { - return hexToBytes(n.toString(16).padStart(len * 2, '0')); -} -function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); -} -// Unpadded, rarely used -function numberToVarBytesBE(n) { - return hexToBytes(numberToHexUnpadded(n)); -} -/** - * Takes hex string or Uint8Array, converts to Uint8Array. - * Validates output length. - * Will throw error for other types. - * @param title descriptive title for an error e.g. 'private key' - * @param hex hex string or Uint8Array - * @param expectedLength optional, will compare to result array's length - * @returns - */ -function ensureBytes(title, hex, expectedLength) { - let res; - if (typeof hex === 'string') { - try { - res = hexToBytes(hex); - } - catch (e) { - throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); - } - } - else if (u8a(hex)) { - // Uint8Array.from() instead of hash.slice() because node.js Buffer - // is instance of Uint8Array, and its slice() creates **mutable** copy - res = Uint8Array.from(hex); - } - else { - throw new Error(`${title} must be hex string or Uint8Array`); - } - const len = res.length; - if (typeof expectedLength === 'number' && len !== expectedLength) - throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); - return res; -} -/** - * Copies several Uint8Arrays into one. - */ -function concatBytes(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; // walk through each item, ensure they have proper type - arrays.forEach((a) => { - if (!u8a(a)) - throw new Error('Uint8Array expected'); - r.set(a, pad); - pad += a.length; - }); - return r; -} -function equalBytes(b1, b2) { - // We don't care about timing attacks here - if (b1.length !== b2.length) - return false; - for (let i = 0; i < b1.length; i++) - if (b1[i] !== b2[i]) - return false; - return true; -} -/** - * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) - */ -function utf8ToBytes(str) { - if (typeof str !== 'string') - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 -} -// Bit operations -/** - * Calculates amount of bits in a bigint. - * Same as `n.toString(2).length` - */ -function bitLen(n) { - let len; - for (len = 0; n > _0n$5; n >>= _1n$5, len += 1) - ; - return len; -} -/** - * Gets single bit at position. - * NOTE: first bit position is 0 (same as arrays) - * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` - */ -function bitGet(n, pos) { - return (n >> BigInt(pos)) & _1n$5; -} -/** - * Sets single bit at position. - */ -const bitSet = (n, pos, value) => { - return n | ((value ? _1n$5 : _0n$5) << BigInt(pos)); -}; -/** - * Calculate mask for N bits. Not using ** operator with bigints because of old engines. - * Same as BigInt(`0b${Array(i).fill('1').join('')}`) - */ -const bitMask = (n) => (_2n$3 << BigInt(n - 1)) - _1n$5; -// DRBG -const u8n = (data) => new Uint8Array(data); // creates Uint8Array -const u8fr = (arr) => Uint8Array.from(arr); // another shortcut -/** - * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. - * @returns function that will call DRBG until 2nd arg returns something meaningful - * @example - * const drbg = createHmacDRBG(32, 32, hmac); - * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined - */ -function createHmacDrbg(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== 'number' || hashLen < 2) - throw new Error('hashLen must be a number'); - if (typeof qByteLen !== 'number' || qByteLen < 2) - throw new Error('qByteLen must be a number'); - if (typeof hmacFn !== 'function') - throw new Error('hmacFn must be a function'); - // Step B, Step C: set hashLen to 8*ceil(hlen/8) - let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. - let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same - let i = 0; // Iterations counter, will throw when over 1000 - const reset = () => { - v.fill(1); - k.fill(0); - i = 0; - }; - const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) - const reseed = (seed = u8n()) => { - // HMAC-DRBG reseed() function. Steps D-G - k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) - v = h(); // v = hmac(k || v) - if (seed.length === 0) - return; - k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) - v = h(); // v = hmac(k || v) - }; - const gen = () => { - // HMAC-DRBG generate() function - if (i++ >= 1000) - throw new Error('drbg: tried 1000 values'); - let len = 0; - const out = []; - while (len < qByteLen) { - v = h(); - const sl = v.slice(); - out.push(sl); - len += v.length; - } - return concatBytes(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); // Steps D-G - let res = undefined; // Step H: grind until k is in [1..n-1] - while (!(res = pred(gen()))) - reseed(); - reset(); - return res; - }; - return genUntil; -} -// Validating curves and fields -const validatorFns = { - bigint: (val) => typeof val === 'bigint', - function: (val) => typeof val === 'function', - boolean: (val) => typeof val === 'boolean', - string: (val) => typeof val === 'string', - stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array, - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object) => object.Fp.isValid(val), - hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), -}; -// type Record = { [P in K]: T; } -function validateObject(object, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== 'function') - throw new Error(`Invalid validator "${type}", expected function`); - const val = object[fieldName]; - if (isOptional && val === undefined) - return; - if (!checkVal(val, object)) { - throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); - } - }; - for (const [fieldName, type] of Object.entries(validators)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object; -} -// validate type tests -// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; -// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! -// // Should fail type-check -// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); -// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); -// const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); -// const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); - -var ut = /*#__PURE__*/Object.freeze({ - __proto__: null, - bitGet: bitGet, - bitLen: bitLen, - bitMask: bitMask, - bitSet: bitSet, - bytesToHex: bytesToHex, - bytesToNumberBE: bytesToNumberBE, - bytesToNumberLE: bytesToNumberLE, - concatBytes: concatBytes, - createHmacDrbg: createHmacDrbg, - ensureBytes: ensureBytes, - equalBytes: equalBytes, - hexToBytes: hexToBytes, - hexToNumber: hexToNumber, - numberToBytesBE: numberToBytesBE, - numberToBytesLE: numberToBytesLE, - numberToHexUnpadded: numberToHexUnpadded, - numberToVarBytesBE: numberToVarBytesBE, - utf8ToBytes: utf8ToBytes, - validateObject: validateObject -}); - -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -// Utilities for modular arithmetics and finite fields -// prettier-ignore -const _0n$4 = BigInt(0), _1n$4 = BigInt(1), _2n$2 = BigInt(2), _3n$2 = BigInt(3); -// prettier-ignore -const _4n = BigInt(4), _5n$1 = BigInt(5), _8n = BigInt(8); -// prettier-ignore -BigInt(9); BigInt(16); -// Calculates a modulo b -function mod(a, b) { - const result = a % b; - return result >= _0n$4 ? result : b + result; -} -/** - * Efficiently raise num to power and do modular division. - * Unsafe in some contexts: uses ladder, so can expose bigint bits. - * @example - * pow(2n, 6n, 11n) // 64n % 11n == 9n - */ -// TODO: use field version && remove -function pow(num, power, modulo) { - if (modulo <= _0n$4 || power < _0n$4) - throw new Error('Expected power/modulo > 0'); - if (modulo === _1n$4) - return _0n$4; - let res = _1n$4; - while (power > _0n$4) { - if (power & _1n$4) - res = (res * num) % modulo; - num = (num * num) % modulo; - power >>= _1n$4; - } - return res; -} -// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) -function pow2(x, power, modulo) { - let res = x; - while (power-- > _0n$4) { - res *= res; - res %= modulo; - } - return res; -} -// Inverses number over modulo -function invert(number, modulo) { - if (number === _0n$4 || modulo <= _0n$4) { - throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); - } - // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ - // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. - let a = mod(number, modulo); - let b = modulo; - // prettier-ignore - let x = _0n$4, u = _1n$4; - while (a !== _0n$4) { - // JIT applies optimization if those two lines follow each other - const q = b / a; - const r = b % a; - const m = x - u * q; - // prettier-ignore - b = a, a = r, x = u, u = m; - } - const gcd = b; - if (gcd !== _1n$4) - throw new Error('invert: does not exist'); - return mod(x, modulo); -} -/** - * Tonelli-Shanks square root search algorithm. - * 1. https://eprint.iacr.org/2012/685.pdf (page 12) - * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks - * Will start an infinite loop if field order P is not prime. - * @param P field order - * @returns function that takes field Fp (created from P) and number n - */ -function tonelliShanks(P) { - // Legendre constant: used to calculate Legendre symbol (a | p), - // which denotes the value of a^((p-1)/2) (mod p). - // (a | p) ≡ 1 if a is a square (mod p) - // (a | p) ≡ -1 if a is not a square (mod p) - // (a | p) ≡ 0 if a ≡ 0 (mod p) - const legendreC = (P - _1n$4) / _2n$2; - let Q, S, Z; - // Step 1: By factoring out powers of 2 from p - 1, - // find q and s such that p - 1 = q*(2^s) with q odd - for (Q = P - _1n$4, S = 0; Q % _2n$2 === _0n$4; Q /= _2n$2, S++) - ; - // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq - for (Z = _2n$2; Z < P && pow(Z, legendreC, P) !== P - _1n$4; Z++) - ; - // Fast-path - if (S === 1) { - const p1div4 = (P + _1n$4) / _4n; - return function tonelliFast(Fp, n) { - const root = Fp.pow(n, p1div4); - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error('Cannot find square root'); - return root; - }; - } - // Slow-path - const Q1div2 = (Q + _1n$4) / _2n$2; - return function tonelliSlow(Fp, n) { - // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 - if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) - throw new Error('Cannot find square root'); - let r = S; - // TODO: will fail at Fp2/etc - let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b - let x = Fp.pow(n, Q1div2); // first guess at the square root - let b = Fp.pow(n, Q); // first guess at the fudge factor - while (!Fp.eql(b, Fp.ONE)) { - if (Fp.eql(b, Fp.ZERO)) - return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) - // Find m such b^(2^m)==1 - let m = 1; - for (let t2 = Fp.sqr(b); m < r; m++) { - if (Fp.eql(t2, Fp.ONE)) - break; - t2 = Fp.sqr(t2); // t2 *= t2 - } - // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow - const ge = Fp.pow(g, _1n$4 << BigInt(r - m - 1)); // ge = 2^(r-m-1) - g = Fp.sqr(ge); // g = ge * ge - x = Fp.mul(x, ge); // x *= ge - b = Fp.mul(b, g); // b *= g - r = m; - } - return x; - }; -} -function FpSqrt(P) { - // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. - // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). - // P ≡ 3 (mod 4) - // √n = n^((P+1)/4) - if (P % _4n === _3n$2) { - // Not all roots possible! - // const ORDER = - // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; - // const NUM = 72057594037927816n; - const p1div4 = (P + _1n$4) / _4n; - return function sqrt3mod4(Fp, n) { - const root = Fp.pow(n, p1div4); - // Throw if root**2 != n - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error('Cannot find square root'); - return root; - }; - } - // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) - if (P % _8n === _5n$1) { - const c1 = (P - _5n$1) / _8n; - return function sqrt5mod8(Fp, n) { - const n2 = Fp.mul(n, _2n$2); - const v = Fp.pow(n2, c1); - const nv = Fp.mul(n, v); - const i = Fp.mul(Fp.mul(nv, _2n$2), v); - const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error('Cannot find square root'); - return root; - }; - } - // Other cases: Tonelli-Shanks algorithm - return tonelliShanks(P); -} -// prettier-ignore -const FIELD_FIELDS = [ - 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', - 'eql', 'add', 'sub', 'mul', 'pow', 'div', - 'addN', 'subN', 'mulN', 'sqrN' -]; -function validateField(field) { - const initial = { - ORDER: 'bigint', - MASK: 'bigint', - BYTES: 'isSafeInteger', - BITS: 'isSafeInteger', - }; - const opts = FIELD_FIELDS.reduce((map, val) => { - map[val] = 'function'; - return map; - }, initial); - return validateObject(field, opts); -} -// Generic field functions -/** - * Same as `pow` but for Fp: non-constant-time. - * Unsafe in some contexts: uses ladder, so can expose bigint bits. - */ -function FpPow(f, num, power) { - // Should have same speed as pow for bigints - // TODO: benchmark! - if (power < _0n$4) - throw new Error('Expected power > 0'); - if (power === _0n$4) - return f.ONE; - if (power === _1n$4) - return num; - let p = f.ONE; - let d = num; - while (power > _0n$4) { - if (power & _1n$4) - p = f.mul(p, d); - d = f.sqr(d); - power >>= _1n$4; - } - return p; -} -/** - * Efficiently invert an array of Field elements. - * `inv(0)` will return `undefined` here: make sure to throw an error. - */ -function FpInvertBatch(f, nums) { - const tmp = new Array(nums.length); - // Walk from first to last, multiply them by each other MOD p - const lastMultiplied = nums.reduce((acc, num, i) => { - if (f.is0(num)) - return acc; - tmp[i] = acc; - return f.mul(acc, num); - }, f.ONE); - // Invert last element - const inverted = f.inv(lastMultiplied); - // Walk from last to first, multiply them by inverted each other MOD p - nums.reduceRight((acc, num, i) => { - if (f.is0(num)) - return acc; - tmp[i] = f.mul(acc, tmp[i]); - return f.mul(acc, num); - }, inverted); - return tmp; -} -// CURVE.n lengths -function nLength(n, nBitLength) { - // Bit size, byte size of CURVE.n - const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; -} -/** - * Initializes a finite field over prime. **Non-primes are not supported.** - * Do not init in loop: slow. Very fragile: always run a benchmark on a change. - * Major performance optimizations: - * * a) denormalized operations like mulN instead of mul - * * b) same object shape: never add or remove keys - * * c) Object.freeze - * @param ORDER prime positive bigint - * @param bitLen how many bits the field consumes - * @param isLE (def: false) if encoding / decoding should be in little-endian - * @param redef optional faster redefinitions of sqrt and other methods - */ -function Field(ORDER, bitLen, isLE = false, redef = {}) { - if (ORDER <= _0n$4) - throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); - if (BYTES > 2048) - throw new Error('Field lengths over 2048 bytes are not supported'); - const sqrtP = FpSqrt(ORDER); - const f = Object.freeze({ - ORDER, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n$4, - ONE: _1n$4, - create: (num) => mod(num, ORDER), - isValid: (num) => { - if (typeof num !== 'bigint') - throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); - return _0n$4 <= num && num < ORDER; // 0 is valid element, but it's not invertible - }, - is0: (num) => num === _0n$4, - isOdd: (num) => (num & _1n$4) === _1n$4, - neg: (num) => mod(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod(num * num, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num, power) => FpPow(f, num, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - // Same as above, but doesn't normalize - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert(num, ORDER), - sqrt: redef.sqrt || ((n) => sqrtP(f, n)), - invertBatch: (lst) => FpInvertBatch(f, lst), - // TODO: do we really need constant cmov? - // We don't have const-time bigints anyway, so probably will be not very useful - cmov: (a, b, c) => (c ? b : a), - toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), - fromBytes: (bytes) => { - if (bytes.length !== BYTES) - throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); - return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); - }, - }); - return Object.freeze(f); -} -/** - * Returns total number of bytes consumed by the field element. - * For example, 32 bytes for usual 256-bit weierstrass curve. - * @param fieldOrder number of field elements, usually CURVE.n - * @returns byte length of field - */ -function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== 'bigint') - throw new Error('field order must be bigint'); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); -} -/** - * Returns minimal amount of bytes that can be safely reduced - * by field order. - * Should be 2^-128 for 128-bit curve such as P256. - * @param fieldOrder number of field elements, usually CURVE.n - * @returns byte length of target hash - */ -function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); -} -/** - * "Constant-time" private key generation utility. - * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF - * and convert them into private scalar, with the modulo bias being negligible. - * Needs at least 48 bytes of input for 32-byte private key. - * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ - * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final - * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 - * @param hash hash output from SHA3 or a similar function - * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) - * @param isLE interpret hash bytes as LE num - * @returns valid private scalar - */ -function mapHashToField(key, fieldOrder, isLE = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. - if (len < 16 || len < minLen || len > 1024) - throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); - const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); - // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 - const reduced = mod(num, fieldOrder - _1n$4) + _1n$4; - return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); -} - -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -// Abelian group utilities -const _0n$3 = BigInt(0); -const _1n$3 = BigInt(1); -// Elliptic curve multiplication of Point by scalar. Fragile. -// Scalars should always be less than curve order: this should be checked inside of a curve itself. -// Creates precomputation tables for fast multiplication: -// - private scalar is split by fixed size windows of W bits -// - every window point is collected from window's table & added to accumulator -// - since windows are different, same point inside tables won't be accessed more than once per calc -// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) -// - +1 window is neccessary for wNAF -// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication -// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow -// windows to be in different memory locations -function wNAF(c, bits) { - const constTimeNegate = (condition, item) => { - const neg = item.negate(); - return condition ? neg : item; - }; - const opts = (W) => { - const windows = Math.ceil(bits / W) + 1; // +1, because - const windowSize = 2 ** (W - 1); // -1 because we skip zero - return { windows, windowSize }; - }; - return { - constTimeNegate, - // non-const time multiplication ladder - unsafeLadder(elm, n) { - let p = c.ZERO; - let d = elm; - while (n > _0n$3) { - if (n & _1n$3) - p = p.add(d); - d = d.double(); - n >>= _1n$3; - } - return p; - }, - /** - * Creates a wNAF precomputation window. Used for caching. - * Default window size is set by `utils.precompute()` and is equal to 8. - * Number of precomputed points depends on the curve size: - * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: - * - 𝑊 is the window size - * - 𝑛 is the bitlength of the curve order. - * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. - * @returns precomputed point tables flattened to a single array - */ - precomputeWindow(elm, W) { - const { windows, windowSize } = opts(W); - const points = []; - let p = elm; - let base = p; - for (let window = 0; window < windows; window++) { - base = p; - points.push(base); - // =1, because we skip zero - for (let i = 1; i < windowSize; i++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - }, - /** - * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. - * @param W window size - * @param precomputes precomputed tables - * @param n scalar (we don't check here, but should be less than curve order) - * @returns real and fake (for const-time) points - */ - wNAF(W, precomputes, n) { - // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise - // But need to carefully remove other checks before wNAF. ORDER == bits here - const { windows, windowSize } = opts(W); - let p = c.ZERO; - let f = c.BASE; - const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. - const maxNumber = 2 ** W; - const shiftBy = BigInt(W); - for (let window = 0; window < windows; window++) { - const offset = window * windowSize; - // Extract W bits. - let wbits = Number(n & mask); - // Shift number by W bits. - n >>= shiftBy; - // If the bits are bigger than max size, we'll split those. - // +224 => 256 - 32 - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n$3; - } - // This code was first written with assumption that 'f' and 'p' will never be infinity point: - // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, - // there is negate now: it is possible that negated element from low value - // would be the same as high element, which will create carry into next window. - // It's not obvious how this can fail, but still worth investigating later. - // Check if we're onto Zero point. - // Add random point inside current window to f. - const offset1 = offset; - const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero - const cond1 = window % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - // The most important part for const-time getPublicKey - f = f.add(constTimeNegate(cond1, precomputes[offset1])); - } - else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); - } - } - // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() - // Even if the variable is still unused, there are some checks which will - // throw an exception, so compiler needs to prove they won't happen, which is hard. - // At this point there is a way to F be infinity-point even if p is not, - // which makes it less const-time: around 1 bigint multiply. - return { p, f }; - }, - wNAFCached(P, precomputesMap, n, transform) { - // @ts-ignore - const W = P._WINDOW_SIZE || 1; - // Calculate precomputes on a first run, reuse them after - let comp = precomputesMap.get(P); - if (!comp) { - comp = this.precomputeWindow(P, W); - if (W !== 1) { - precomputesMap.set(P, transform(comp)); - } - } - return this.wNAF(W, comp, n); - }, - }; -} -function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: 'bigint', - h: 'bigint', - Gx: 'field', - Gy: 'field', - }, { - nBitLength: 'isSafeInteger', - nByteLength: 'isSafeInteger', - }); - // Set defaults - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER }, - }); -} - -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -// Short Weierstrass curve. The formula is: y² = x³ + ax + b -function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: 'field', - b: 'field', - }, { - allowedPrivateKeyLengths: 'array', - wrapPrivateKey: 'boolean', - isTorsionFree: 'function', - clearCofactor: 'function', - allowInfinityPoint: 'boolean', - fromBytes: 'function', - toBytes: 'function', - }); - const { endo, Fp, a } = opts; - if (endo) { - if (!Fp.eql(a, Fp.ZERO)) { - throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); - } - if (typeof endo !== 'object' || - typeof endo.beta !== 'bigint' || - typeof endo.splitScalar !== 'function') { - throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); - } - } - return Object.freeze({ ...opts }); -} -// ASN.1 DER encoding utilities -const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; -const DER = { - // asn.1 DER encoding utils - Err: class DERErr extends Error { - constructor(m = '') { - super(m); - } - }, - _parseInt(data) { - const { Err: E } = DER; - if (data.length < 2 || data[0] !== 0x02) - throw new E('Invalid signature integer tag'); - const len = data[1]; - const res = data.subarray(2, len + 2); - if (!len || res.length !== len) - throw new E('Invalid signature integer: wrong length'); - // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, - // since we always use positive integers here. It must always be empty: - // - add zero byte if exists - // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) - if (res[0] & 0b10000000) - throw new E('Invalid signature integer: negative'); - if (res[0] === 0x00 && !(res[1] & 0b10000000)) - throw new E('Invalid signature integer: unnecessary leading zero'); - return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left - }, - toSig(hex) { - // parse DER signature - const { Err: E } = DER; - const data = typeof hex === 'string' ? h2b(hex) : hex; - if (!(data instanceof Uint8Array)) - throw new Error('ui8a expected'); - let l = data.length; - if (l < 2 || data[0] != 0x30) - throw new E('Invalid signature tag'); - if (data[1] !== l - 2) - throw new E('Invalid signature: incorrect length'); - const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); - const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); - if (rBytesLeft.length) - throw new E('Invalid signature: left bytes after parsing'); - return { r, s }; - }, - hexFromSig(sig) { - // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' - const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); - const h = (num) => { - const hex = num.toString(16); - return hex.length & 1 ? `0${hex}` : hex; - }; - const s = slice(h(sig.s)); - const r = slice(h(sig.r)); - const shl = s.length / 2; - const rhl = r.length / 2; - const sl = h(shl); - const rl = h(rhl); - return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; - }, -}; -// Be friendly to bad ECMAScript parsers by not using bigint literals -// prettier-ignore -const _0n$2 = BigInt(0), _1n$2 = BigInt(1); BigInt(2); const _3n$1 = BigInt(3); BigInt(4); -function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ - const toBytes = CURVE.toBytes || - ((_c, point, _isCompressed) => { - const a = point.toAffine(); - return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); - }); - const fromBytes = CURVE.fromBytes || - ((bytes) => { - // const head = bytes[0]; - const tail = bytes.subarray(1); - // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); - const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); - const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); - return { x, y }; - }); - /** - * y² = x³ + ax + b: Short weierstrass curve formula - * @returns y² - */ - function weierstrassEquation(x) { - const { a, b } = CURVE; - const x2 = Fp.sqr(x); // x * x - const x3 = Fp.mul(x2, x); // x2 * x - return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b - } - // Validate whether the passed curve params are valid. - // We check if curve equation works for generator point. - // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. - // ProjectivePoint class has not been initialized yet. - if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error('bad generator point: equation left != right'); - // Valid group elements reside in range 1..n-1 - function isWithinCurveOrder(num) { - return typeof num === 'bigint' && _0n$2 < num && num < CURVE.n; - } - function assertGE(num) { - if (!isWithinCurveOrder(num)) - throw new Error('Expected valid bigint: 0 < bigint < curve.n'); - } - // Validates if priv key is valid and converts it to bigint. - // Supports options allowedPrivateKeyLengths and wrapPrivateKey. - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; - if (lengths && typeof key !== 'bigint') { - if (key instanceof Uint8Array) - key = bytesToHex(key); - // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes - if (typeof key !== 'string' || !lengths.includes(key.length)) - throw new Error('Invalid key'); - key = key.padStart(nByteLength * 2, '0'); - } - let num; - try { - num = - typeof key === 'bigint' - ? key - : bytesToNumberBE(ensureBytes('private key', key, nByteLength)); - } - catch (error) { - throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); - } - if (wrapPrivateKey) - num = mod(num, n); // disabled by default, enabled for BLS - assertGE(num); // num in range [1..N-1] - return num; - } - const pointPrecomputes = new Map(); - function assertPrjPoint(other) { - if (!(other instanceof Point)) - throw new Error('ProjectivePoint expected'); - } - /** - * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) - * Default Point works in 2d / affine coordinates: (x, y) - * We're doing calculations in projective, because its operations don't require costly inversion. - */ - class Point { - constructor(px, py, pz) { - this.px = px; - this.py = py; - this.pz = pz; - if (px == null || !Fp.isValid(px)) - throw new Error('x required'); - if (py == null || !Fp.isValid(py)) - throw new Error('y required'); - if (pz == null || !Fp.isValid(pz)) - throw new Error('z required'); - } - // Does not validate if the point is on-curve. - // Use fromHex instead, or call assertValidity() later. - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp.isValid(x) || !Fp.isValid(y)) - throw new Error('invalid affine point'); - if (p instanceof Point) - throw new Error('projective point not allowed'); - const is0 = (i) => Fp.eql(i, Fp.ZERO); - // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) - if (is0(x) && is0(y)) - return Point.ZERO; - return new Point(x, y, Fp.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - /** - * Takes a bunch of Projective Points but executes only one - * inversion on all of them. Inversion is very slow operation, - * so this improves performance massively. - * Optimization: converts a list of projective points to a list of identical points with Z=1. - */ - static normalizeZ(points) { - const toInv = Fp.invertBatch(points.map((p) => p.pz)); - return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); - } - /** - * Converts hash string or Uint8Array to Point. - * @param hex short/long ECDSA hex - */ - static fromHex(hex) { - const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); - P.assertValidity(); - return P; - } - // Multiplies generator point by privateKey. - static fromPrivateKey(privateKey) { - return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - // "Private method", don't use it directly - _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes.delete(this); - } - // A point on curve is valid if it conforms to equation. - assertValidity() { - if (this.is0()) { - // (0, 1, 0) aka ZERO is invalid in most contexts. - // In BLS, ZERO can be serialized, so we allow it. - // (0, 0, 0) is wrong representation of ZERO and is always invalid. - if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) - return; - throw new Error('bad point: ZERO'); - } - // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` - const { x, y } = this.toAffine(); - // Check if x, y are valid field elements - if (!Fp.isValid(x) || !Fp.isValid(y)) - throw new Error('bad point: x or y not FE'); - const left = Fp.sqr(y); // y² - const right = weierstrassEquation(x); // x³ + ax + b - if (!Fp.eql(left, right)) - throw new Error('bad point: equation left != right'); - if (!this.isTorsionFree()) - throw new Error('bad point: not in prime-order subgroup'); - } - hasEvenY() { - const { y } = this.toAffine(); - if (Fp.isOdd) - return !Fp.isOdd(y); - throw new Error("Field doesn't support isOdd"); - } - /** - * Compare one point to another. - */ - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); - const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); - return U1 && U2; - } - /** - * Flips point to one corresponding to (x, -y) in Affine coordinates. - */ - negate() { - return new Point(this.px, Fp.neg(this.py), this.pz); - } - // Renes-Costello-Batina exception-free doubling formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 3 - // Cost: 8M + 3S + 3*a + 2*b3 + 15add. - double() { - const { a, b } = CURVE; - const b3 = Fp.mul(b, _3n$1); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore - let t0 = Fp.mul(X1, X1); // step 1 - let t1 = Fp.mul(Y1, Y1); - let t2 = Fp.mul(Z1, Z1); - let t3 = Fp.mul(X1, Y1); - t3 = Fp.add(t3, t3); // step 5 - Z3 = Fp.mul(X1, Z1); - Z3 = Fp.add(Z3, Z3); - X3 = Fp.mul(a, Z3); - Y3 = Fp.mul(b3, t2); - Y3 = Fp.add(X3, Y3); // step 10 - X3 = Fp.sub(t1, Y3); - Y3 = Fp.add(t1, Y3); - Y3 = Fp.mul(X3, Y3); - X3 = Fp.mul(t3, X3); - Z3 = Fp.mul(b3, Z3); // step 15 - t2 = Fp.mul(a, t2); - t3 = Fp.sub(t0, t2); - t3 = Fp.mul(a, t3); - t3 = Fp.add(t3, Z3); - Z3 = Fp.add(t0, t0); // step 20 - t0 = Fp.add(Z3, t0); - t0 = Fp.add(t0, t2); - t0 = Fp.mul(t0, t3); - Y3 = Fp.add(Y3, t0); - t2 = Fp.mul(Y1, Z1); // step 25 - t2 = Fp.add(t2, t2); - t0 = Fp.mul(t2, t3); - X3 = Fp.sub(X3, t0); - Z3 = Fp.mul(t2, t1); - Z3 = Fp.add(Z3, Z3); // step 30 - Z3 = Fp.add(Z3, Z3); - return new Point(X3, Y3, Z3); - } - // Renes-Costello-Batina exception-free addition formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 1 - // Cost: 12M + 0S + 3*a + 3*b3 + 23add. - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore - const a = CURVE.a; - const b3 = Fp.mul(CURVE.b, _3n$1); - let t0 = Fp.mul(X1, X2); // step 1 - let t1 = Fp.mul(Y1, Y2); - let t2 = Fp.mul(Z1, Z2); - let t3 = Fp.add(X1, Y1); - let t4 = Fp.add(X2, Y2); // step 5 - t3 = Fp.mul(t3, t4); - t4 = Fp.add(t0, t1); - t3 = Fp.sub(t3, t4); - t4 = Fp.add(X1, Z1); - let t5 = Fp.add(X2, Z2); // step 10 - t4 = Fp.mul(t4, t5); - t5 = Fp.add(t0, t2); - t4 = Fp.sub(t4, t5); - t5 = Fp.add(Y1, Z1); - X3 = Fp.add(Y2, Z2); // step 15 - t5 = Fp.mul(t5, X3); - X3 = Fp.add(t1, t2); - t5 = Fp.sub(t5, X3); - Z3 = Fp.mul(a, t4); - X3 = Fp.mul(b3, t2); // step 20 - Z3 = Fp.add(X3, Z3); - X3 = Fp.sub(t1, Z3); - Z3 = Fp.add(t1, Z3); - Y3 = Fp.mul(X3, Z3); - t1 = Fp.add(t0, t0); // step 25 - t1 = Fp.add(t1, t0); - t2 = Fp.mul(a, t2); - t4 = Fp.mul(b3, t4); - t1 = Fp.add(t1, t2); - t2 = Fp.sub(t0, t2); // step 30 - t2 = Fp.mul(a, t2); - t4 = Fp.add(t4, t2); - t0 = Fp.mul(t1, t4); - Y3 = Fp.add(Y3, t0); - t0 = Fp.mul(t5, t4); // step 35 - X3 = Fp.mul(t3, X3); - X3 = Fp.sub(X3, t0); - t0 = Fp.mul(t3, t1); - Z3 = Fp.mul(t5, Z3); - Z3 = Fp.add(Z3, t0); // step 40 - return new Point(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point.ZERO); - } - wNAF(n) { - return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { - const toInv = Fp.invertBatch(comp.map((p) => p.pz)); - return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); - }); - } - /** - * Non-constant-time multiplication. Uses double-and-add algorithm. - * It's faster, but should only be used when you don't care about - * an exposed private key e.g. sig verification, which works over *public* keys. - */ - multiplyUnsafe(n) { - const I = Point.ZERO; - if (n === _0n$2) - return I; - assertGE(n); // Will throw on 0 - if (n === _1n$2) - return this; - const { endo } = CURVE; - if (!endo) - return wnaf.unsafeLadder(this, n); - // Apply endomorphism - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let k1p = I; - let k2p = I; - let d = this; - while (k1 > _0n$2 || k2 > _0n$2) { - if (k1 & _1n$2) - k1p = k1p.add(d); - if (k2 & _1n$2) - k2p = k2p.add(d); - d = d.double(); - k1 >>= _1n$2; - k2 >>= _1n$2; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - /** - * Constant time multiplication. - * Uses wNAF method. Windowed method may be 10% faster, - * but takes 2x longer to generate and consumes 2x memory. - * Uses precomputes when available. - * Uses endomorphism for Koblitz curves. - * @param scalar by which the point would be multiplied - * @returns New point - */ - multiply(scalar) { - assertGE(scalar); - let n = scalar; - let point, fake; // Fake point is used to const-time mult - const { endo } = CURVE; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } - else { - const { p, f } = this.wNAF(n); - point = p; - fake = f; - } - // Normalize `z` for both points, but return only real one - return Point.normalizeZ([point, fake])[0]; - } - /** - * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. - * Not using Strauss-Shamir trick: precomputation tables are faster. - * The trick could be useful if both P and Q are not G (not in our case). - * @returns non-zero affine point - */ - multiplyAndAddUnsafe(Q, a, b) { - const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes - const mul = (P, a // Select faster multiply() method - ) => (a === _0n$2 || a === _1n$2 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); - const sum = mul(this, a).add(mul(Q, b)); - return sum.is0() ? undefined : sum; - } - // Converts Projective point to affine (x, y) coordinates. - // Can accept precomputed Z^-1 - for example, from invertBatch. - // (x, y, z) ∋ (x=x/z, y=y/z) - toAffine(iz) { - const { px: x, py: y, pz: z } = this; - const is0 = this.is0(); - // If invZ was 0, we return zero point. However we still want to execute - // all operations, so we replace invZ with a random number, 1. - if (iz == null) - iz = is0 ? Fp.ONE : Fp.inv(z); - const ax = Fp.mul(x, iz); - const ay = Fp.mul(y, iz); - const zz = Fp.mul(z, iz); - if (is0) - return { x: Fp.ZERO, y: Fp.ZERO }; - if (!Fp.eql(zz, Fp.ONE)) - throw new Error('invZ was invalid'); - return { x: ax, y: ay }; - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n$2) - return true; // No subgroups, always torsion-free - if (isTorsionFree) - return isTorsionFree(Point, this); - throw new Error('isTorsionFree() has not been declared for the elliptic curve'); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n$2) - return this; // Fast-path - if (clearCofactor) - return clearCofactor(Point, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - this.assertValidity(); - return toBytes(Point, this, isCompressed); - } - toHex(isCompressed = true) { - return bytesToHex(this.toRawBytes(isCompressed)); - } - } - Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); - Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); - // Validate if generator point is on curve - return { - CURVE, - ProjectivePoint: Point, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder, - }; -} -function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: 'hash', - hmac: 'function', - randomBytes: 'function', - }, { - bits2int: 'function', - bits2int_modN: 'function', - lowS: 'boolean', - }); - return Object.freeze({ lowS: true, ...opts }); -} -function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 - const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 - function isValidFieldElement(num) { - return _0n$2 < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE - } - function modN(a) { - return mod(a, CURVE_ORDER); - } - function invN(a) { - return invert(a, CURVE_ORDER); - } - const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ - ...CURVE, - toBytes(_c, point, isCompressed) { - const a = point.toAffine(); - const x = Fp.toBytes(a.x); - const cat = concatBytes; - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); - } - else { - return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); - } - }, - fromBytes(bytes) { - const len = bytes.length; - const head = bytes[0]; - const tail = bytes.subarray(1); - // this.assertValidity() is done inside of fromHex - if (len === compressedLen && (head === 0x02 || head === 0x03)) { - const x = bytesToNumberBE(tail); - if (!isValidFieldElement(x)) - throw new Error('Point is not on curve'); - const y2 = weierstrassEquation(x); // y² = x³ + ax + b - let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 - const isYOdd = (y & _1n$2) === _1n$2; - // ECDSA - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp.neg(y); - return { x, y }; - } - else if (len === uncompressedLen && head === 0x04) { - const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); - const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); - return { x, y }; - } - else { - throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); - } - }, - }); - const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number) { - const HALF = CURVE_ORDER >> _1n$2; - return number > HALF; - } - function normalizeS(s) { - return isBiggerThanHalfOrder(s) ? modN(-s) : s; - } - // slice bytes num - const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); - /** - * ECDSA signature with its (r, s) properties. Supports DER & compact representations. - */ - class Signature { - constructor(r, s, recovery) { - this.r = r; - this.s = s; - this.recovery = recovery; - this.assertValidity(); - } - // pair (bytes of r, bytes of s) - static fromCompact(hex) { - const l = CURVE.nByteLength; - hex = ensureBytes('compactSignature', hex, l * 2); - return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); - } - // DER encoded ECDSA signature - // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script - static fromDER(hex) { - const { r, s } = DER.toSig(ensureBytes('DER', hex)); - return new Signature(r, s); - } - assertValidity() { - // can use assertGE here - if (!isWithinCurveOrder(this.r)) - throw new Error('r must be 0 < r < CURVE.n'); - if (!isWithinCurveOrder(this.s)) - throw new Error('s must be 0 < s < CURVE.n'); - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r, s, recovery: rec } = this; - const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error('recovery id invalid'); - const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; - if (radj >= Fp.ORDER) - throw new Error('recovery id 2 or 3 invalid'); - const prefix = (rec & 1) === 0 ? '02' : '03'; - const R = Point.fromHex(prefix + numToNByteStr(radj)); - const ir = invN(radj); // r^-1 - const u1 = modN(-h * ir); // -hr^-1 - const u2 = modN(s * ir); // sr^-1 - const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) - if (!Q) - throw new Error('point at infinify'); // unsafe is fine: no priv data leaked - Q.assertValidity(); - return Q; - } - // Signatures should be low-s, to prevent malleability. - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; - } - // DER-encoded - toDERRawBytes() { - return hexToBytes(this.toDERHex()); - } - toDERHex() { - return DER.hexFromSig({ r: this.r, s: this.s }); - } - // padded bytes of r, then padded bytes of s - toCompactRawBytes() { - return hexToBytes(this.toCompactHex()); - } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); - } - } - const utils = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } - catch (error) { - return false; - } - }, - normPrivateKeyToScalar: normPrivateKeyToScalar, - /** - * Produces cryptographically secure private key from random of size - * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. - */ - randomPrivateKey: () => { - const length = getMinHashLength(CURVE.n); - return mapHashToField(CURVE.randomBytes(length), CURVE.n); - }, - /** - * Creates precompute table for an arbitrary EC point. Makes point "cached". - * Allows to massively speed-up `point.multiply(scalar)`. - * @returns cached point - * @example - * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); - * fast.multiply(privKey); // much faster ECDH now - */ - precompute(windowSize = 8, point = Point.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here - return point; - }, - }; - /** - * Computes public key for a private key. Checks for validity of the private key. - * @param privateKey private key - * @param isCompressed whether to return compact (default), or full key - * @returns Public key, full when isCompressed=false; short when isCompressed=true - */ - function getPublicKey(privateKey, isCompressed = true) { - return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - /** - * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. - */ - function isProbPub(item) { - const arr = item instanceof Uint8Array; - const str = typeof item === 'string'; - const len = (arr || str) && item.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item instanceof Point) - return true; - return false; - } - /** - * ECDH (Elliptic Curve Diffie Hellman). - * Computes shared public key from private key and public key. - * Checks: 1) private key validity 2) shared key is on-curve. - * Does NOT hash the result. - * @param privateA private key - * @param publicB different public key - * @param isCompressed whether to return compact (default), or full key - * @returns shared public key - */ - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error('first arg must be private key'); - if (!isProbPub(publicB)) - throw new Error('second arg must be public key'); - const b = Point.fromHex(publicB); // check for being on-curve - return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); - } - // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. - // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. - // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. - // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors - const bits2int = CURVE.bits2int || - function (bytes) { - // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) - // for some cases, since bytes.length * 8 is not actual bitLength. - const num = bytesToNumberBE(bytes); // check for == u8 done here - const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE.bits2int_modN || - function (bytes) { - return modN(bits2int(bytes)); // can't use bytesToNumberBE here - }; - // NOTE: pads output with zero as per spec - const ORDER_MASK = bitMask(CURVE.nBitLength); - /** - * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. - */ - function int2octets(num) { - if (typeof num !== 'bigint') - throw new Error('bigint expected'); - if (!(_0n$2 <= num && num < ORDER_MASK)) - throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); - // works with order, can have different size than numToField! - return numberToBytesBE(num, CURVE.nByteLength); - } - // Steps A, D of RFC6979 3.2 - // Creates RFC6979 seed; converts msg/privKey to numbers. - // Used only in sign, not in verify. - // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. - // Also it can be bigger for P224 + SHA256 - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (['recovered', 'canonical'].some((k) => k in opts)) - throw new Error('sign() legacy options not supported'); - const { hash, randomBytes } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default - if (lowS == null) - lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash - msgHash = ensureBytes('msgHash', msgHash); - if (prehash) - msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); - // We can't later call bits2octets, since nested bits2int is broken for curves - // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. - // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) - const h1int = bits2int_modN(msgHash); - const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint - const seedArgs = [int2octets(d), int2octets(h1int)]; - // extraEntropy. RFC6979 3.6: additional k' (optional). - if (ent != null) { - // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') - const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is - seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes - } - const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2 - const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! - // Converts signature params into point w r/s, checks result for validity. - function k2sig(kBytes) { - // RFC 6979 Section 3.2, step 3: k = bits2int(T) - const k = bits2int(kBytes); // Cannot use fields methods, since it is group element - if (!isWithinCurveOrder(k)) - return; // Important: all mod() calls here must be done over N - const ik = invN(k); // k^-1 mod n - const q = Point.BASE.multiply(k).toAffine(); // q = Gk - const r = modN(q.x); // r = q.x mod n - if (r === _0n$2) - return; - // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to - // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: - // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT - const s = modN(ik * modN(m + r * d)); // Not using blinding here - if (s === _0n$2) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$2); // recovery bit (2 or 3, when q.x > n) - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = normalizeS(s); // if lowS was passed, ensure s is always - recovery ^= 1; // // in the bottom half of N - } - return new Signature(r, normS, recovery); // use normS, not s - } - return { seed, k2sig }; - } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - /** - * Signs message hash with a private key. - * ``` - * sign(m, d, k) where - * (x, y) = G × k - * r = x mod n - * s = (m + dr)/k mod n - * ``` - * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. - * @param privKey private key - * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. - * @returns signature with recovery param - */ - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. - const C = CURVE; - const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); - return drbg(seed, k2sig); // Steps B, C, D, E, F, G - } - // Enable precomputes. Slows down first publicKey computation by 20ms. - Point.BASE._setWindowSize(8); - // utils.precompute(8, ProjectivePoint.BASE) - /** - * Verifies a signature against message hash and public key. - * Rejects lowS signatures by default: to override, - * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: - * - * ``` - * verify(r, s, h, P) where - * U1 = hs^-1 mod n - * U2 = rs^-1 mod n - * R = U1⋅G - U2⋅P - * mod(R.x, n) == r - * ``` - */ - function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { - const sg = signature; - msgHash = ensureBytes('msgHash', msgHash); - publicKey = ensureBytes('publicKey', publicKey); - if ('strict' in opts) - throw new Error('options.strict was renamed to lowS'); - const { lowS, prehash } = opts; - let _sig = undefined; - let P; - try { - if (typeof sg === 'string' || sg instanceof Uint8Array) { - // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). - // Since DER can also be 2*nByteLength bytes, we check for it first. - try { - _sig = Signature.fromDER(sg); - } - catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; - _sig = Signature.fromCompact(sg); - } - } - else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { - const { r, s } = sg; - _sig = new Signature(r, s); - } - else { - throw new Error('PARSE'); - } - P = Point.fromHex(publicKey); - } - catch (error) { - if (error.message === 'PARSE') - throw new Error(`signature must be Signature instance, Uint8Array or hex string`); - return false; - } - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r, s } = _sig; - const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element - const is = invN(s); // s^-1 - const u1 = modN(h * is); // u1 = hs^-1 mod n - const u2 = modN(r * is); // u2 = rs^-1 mod n - const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P - if (!R) - return false; - const v = modN(R.x); - return v === r; - } - return { - CURVE, - getPublicKey, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point, - Signature, - utils, - }; -} - -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -// connects noble-curves to noble-hashes -function getHash(hash) { - return { - hash, - hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)), - randomBytes: randomBytes$2, - }; -} -function createCurve(curveDef, defHash) { - const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); - return Object.freeze({ ...create(defHash), create }); -} - -/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); -const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); -const _1n$1 = BigInt(1); -const _2n$1 = BigInt(2); -const divNearest = (a, b) => (a + b / _2n$1) / b; -/** - * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. - * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] - */ -function sqrtMod(y) { - const P = secp256k1P; - // prettier-ignore - const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - // prettier-ignore - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = (y * y * y) % P; // x^3, 11 - const b3 = (b2 * b2 * y) % P; // x^7 - const b6 = (pow2(b3, _3n, P) * b3) % P; - const b9 = (pow2(b6, _3n, P) * b3) % P; - const b11 = (pow2(b9, _2n$1, P) * b2) % P; - const b22 = (pow2(b11, _11n, P) * b11) % P; - const b44 = (pow2(b22, _22n, P) * b22) % P; - const b88 = (pow2(b44, _44n, P) * b44) % P; - const b176 = (pow2(b88, _88n, P) * b88) % P; - const b220 = (pow2(b176, _44n, P) * b44) % P; - const b223 = (pow2(b220, _3n, P) * b3) % P; - const t1 = (pow2(b223, _23n, P) * b22) % P; - const t2 = (pow2(t1, _6n, P) * b2) % P; - const root = pow2(t2, _2n$1, P); - if (!Fp.eql(Fp.sqr(root), y)) - throw new Error('Cannot find square root'); - return root; -} -const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); -const secp256k1 = createCurve({ - a: BigInt(0), - b: BigInt(7), - Fp, - n: secp256k1N, - // Base point (x, y) aka generator point - Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), - Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), - h: BigInt(1), - lowS: true, - /** - * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. - * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. - * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. - * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 - */ - endo: { - beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), - splitScalar: (k) => { - const n = secp256k1N; - const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); - const b1 = -_1n$1 * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); - const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); - const b2 = a1; - const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = mod(k - c1 * a1 - c2 * a2, n); - let k2 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k2 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k2 = n - k2; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error('splitScalar: Endomorphism failed, k=' + k); - } - return { k1neg, k1, k2neg, k2 }; - }, - }, -}, sha256$1); -// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. -// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki -const _0n$1 = BigInt(0); -const fe = (x) => typeof x === 'bigint' && _0n$1 < x && x < secp256k1P; -const ge = (x) => typeof x === 'bigint' && _0n$1 < x && x < secp256k1N; -/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ -const TAGGED_HASH_PREFIXES = {}; -function taggedHash$1(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === undefined) { - const tagH = sha256$1(Uint8Array.from(tag, (c) => c.charCodeAt(0))); - tagP = concatBytes(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } - return sha256$1(concatBytes(tagP, ...messages)); -} -// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 -const pointToBytes = (point) => point.toRawBytes(true).slice(1); -const numTo32b = (n) => numberToBytesBE(n, 32); -const modP = (x) => mod(x, secp256k1P); -const modN = (x) => mod(x, secp256k1N); -const Point = secp256k1.ProjectivePoint; -const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); -// Calculate point, scalar and bytes -function schnorrGetExtPubKey(priv) { - let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey - let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside - const scalar = p.hasEvenY() ? d_ : modN(-d_); - return { scalar: scalar, bytes: pointToBytes(p) }; -} -/** - * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. - * @returns valid point checked for being on-curve - */ -function lift_x(x) { - if (!fe(x)) - throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. - const xx = modP(x * x); - const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. - let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. - if (y % _2n$1 !== _0n$1) - y = modP(-y); // Return the unique point P such that x(P) = x and - const p = new Point(x, y, _1n$1); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. - p.assertValidity(); - return p; -} -/** - * Create tagged hash, convert it to bigint, reduce modulo-n. - */ -function challenge(...args) { - return modN(bytesToNumberBE(taggedHash$1('BIP0340/challenge', ...args))); -} -/** - * Schnorr public key is just `x` coordinate of Point as per BIP340. - */ -function schnorrGetPublicKey(privateKey) { - return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) -} -/** - * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. - * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. - */ -function schnorrSign(message, privateKey, auxRand = randomBytes$2(32)) { - const m = ensureBytes('message', message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder - const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array - const t = numTo32b(d ^ bytesToNumberBE(taggedHash$1('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) - const rand = taggedHash$1('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) - const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n - if (k_ === _0n$1) - throw new Error('sign failed: k is zero'); // Fail if k' = 0. - const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. - const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. - const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). - sig.set(rx, 0); - sig.set(numTo32b(modN(k + e * d)), 32); - // If Verify(bytes(P), m, sig) (see below) returns failure, abort - if (!schnorrVerify(sig, m, px)) - throw new Error('sign: Invalid signature produced'); - return sig; -} -/** - * Verifies Schnorr signature. - * Will swallow errors & return false except for initial type validation of arguments. - */ -function schnorrVerify(signature, message, publicKey) { - const sig = ensureBytes('signature', signature, 64); - const m = ensureBytes('message', message); - const pub = ensureBytes('publicKey', publicKey, 32); - try { - const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails - const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. - if (!fe(r)) - return false; - const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. - if (!ge(s)) - return false; - const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n - const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P - if (!R || !R.hasEvenY() || R.toAffine().x !== r) - return false; // -eP == (n-e)P - return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. - } - catch (error) { - return false; - } -} -const schnorr = /* @__PURE__ */ (() => ({ - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - utils: { - randomPrivateKey: secp256k1.utils.randomPrivateKey, - lift_x, - pointToBytes, - numberToBytesBE, - bytesToNumberBE, - taggedHash: taggedHash$1, - mod, - }, -}))(); - -/** - * A constant for the zero address. - * - * (**i.e.** `"0x0000000000000000000000000000000000000000"`) - * - * @category Constants - */ -const ZeroAddress = '0x0000000000000000000000000000000000000000'; - -/** - * A constant for the zero hash. - * - * (**i.e.** `"0x0000000000000000000000000000000000000000000000000000000000000000"`) - * - * @category Constants - */ -const ZeroHash = '0x0000000000000000000000000000000000000000000000000000000000000000'; - -/** - * A constant for the order N for the secp256k1 curve. - * - * (**i.e.** `0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n`) - * - * @category Constants - */ -const N$1 = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); -/** - * A constant for the number of wei in a single ether. - * - * (**i.e.** `1000000000000000000n`) - * - * @category Constants - */ -const WeiPerEther = BigInt('1000000000000000000'); -/** - * A constant for the maximum value for a `uint256`. - * - * (**i.e.** `0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn`) - * - * @category Constants - */ -const MaxUint256 = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); -/** - * A constant for the minimum value for an `int256`. - * - * (**i.e.** `-8000000000000000000000000000000000000000000000000000000000000000n`) - * - * @category Constants - */ -const MinInt256 = BigInt('0x8000000000000000000000000000000000000000000000000000000000000000') * BigInt(-1); -/** - * A constant for the maximum value for an `int256`. - * - * (**i.e.** `0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn`) - * - * @category Constants - */ -const MaxInt256 = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); - -// NFKC (composed) // (decomposed) -/** - * A constant for the ether symbol (normalized using NFKC). - * - * (**i.e.** `"\\u039e"`) - * - * @category Constants - */ -const quaisymbol = '\u039e'; // "\uD835\uDF63"; -/** - * A constant for the Quai Network equivalent of the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal message - * prefix. - * - * (**i.e.** `"\\x19Quai Signed Message:\\n"`) - * - * @category Constants - */ -const MessagePrefix = '\x19Quai Signed Message:\n'; -/** - * A constant for the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal message prefix. - * - * (**i.e.** `"\\x19Ethereum Signed Message:\\n"`) - * - * @category Constants - */ -const EthMessagePrefix = '\x19Ethereum Signed Message:\n'; - -/** - * A shard represents a chain within the Quai network hierarchy. A shard refer to the Prime chain, a region under the - * Prime chain, or a Zone within a region. The value is a hexadecimal string representing the encoded value of the - * shard. Read more [here](https://github.com/quai-network/qips/blob/master/qip-0002.md). - * - * @category Constants - */ -var Shard; -(function (Shard) { - Shard["Cyprus"] = "0x0"; - Shard["Cyprus1"] = "0x00"; - Shard["Cyprus2"] = "0x01"; - Shard["Cyprus3"] = "0x02"; - Shard["Paxos"] = "0x1"; - Shard["Paxos1"] = "0x10"; - Shard["Paxos2"] = "0x11"; - Shard["Paxos3"] = "0x12"; - Shard["Hydra"] = "0x2"; - Shard["Hydra1"] = "0x20"; - Shard["Hydra2"] = "0x21"; - Shard["Hydra3"] = "0x22"; - Shard["Prime"] = "0x"; -})(Shard || (Shard = {})); -function shardFromBytes(shard) { - switch (shard) { - case '0x': - return Shard.Prime; - case '0x0': - return Shard.Cyprus; - case '0x1': - return Shard.Paxos; - case '0x2': - return Shard.Hydra; - case '0x00': - return Shard.Cyprus1; - case '0x01': - return Shard.Cyprus2; - case '0x02': - return Shard.Cyprus3; - case '0x10': - return Shard.Paxos1; - case '0x11': - return Shard.Paxos2; - case '0x12': - return Shard.Paxos3; - case '0x20': - return Shard.Hydra1; - case '0x21': - return Shard.Hydra2; - case '0x22': - return Shard.Hydra3; - default: - throw new Error('Invalid shard'); - } -} -/** - * Constant data that defines each shard within the network. - * - * @category Constants - */ -const ShardData = [ - ...ZoneData, - { - name: 'Cyprus', - nickname: 'cyprus', - shard: 'region-0', - context: 2, - byte: '0x0', - }, - { - name: 'Paxos', - nickname: 'paxos', - shard: 'region-1', - context: 2, - byte: '0x1', - }, - { - name: 'Hydra', - nickname: 'hydra', - shard: 'region-2', - context: 2, - byte: '0x2', - }, - { - name: 'Prime', - nickname: 'prime', - shard: 'prime', - context: 2, - byte: '0x', - }, -]; -function toShard(shard) { - return shardFromBytes(ShardData.find((it) => it.name == shard || it.byte == shard || it.nickname == shard || it.shard == shard) - ?.byte || ''); -} -function fromShard(shard, key) { - return ShardData.find((it) => it.byte == shard)?.[key] || ''; -} - -// Constants -const BN_0$5 = BigInt(0); -const BN_1$2 = BigInt(1); -const BN_2$1 = BigInt(2); -const BN_27 = BigInt(27); -const BN_28 = BigInt(28); -const BN_35 = BigInt(35); -const _guard$6 = {}; -function toUint256(value) { - return zeroPadValue(toBeArray(value), 32); -} -/** - * A Signature @TODO - * - * @category Crypto - */ -class Signature { - #r; - #s; - #v; - #networkV; - /** - * The `r` value for a signautre. - * - * This represents the `x` coordinate of a "reference" or challenge point, from which the `y` can be computed. - */ - get r() { - return this.#r; - } - set r(value) { - assertArgument(dataLength(value) === 32, 'invalid r', 'value', value); - this.#r = hexlify(value); - } - /** - * The `s` value for a signature. - */ - get s() { - return this.#s; - } - set s(_value) { - assertArgument(dataLength(_value) === 32, 'invalid s', 'value', _value); - const value = hexlify(_value); - assertArgument(parseInt(value.substring(0, 3)) < 8, 'non-canonical s', 'value', value); - this.#s = value; - } - /** - * The `v` value for a signature. - * - * Since a given `x` value for `r` has two possible values for its correspondin `y`, the `v` indicates which of the - * two `y` values to use. - * - * It is normalized to the values `27` or `28` for legacy purposes. - */ - get v() { - return this.#v; - } - set v(value) { - const v = getNumber(value, 'value'); - assertArgument(v === 27 || v === 28, 'invalid v', 'v', value); - this.#v = v; - } - /** - * The EIP-155 `v` for legacy transactions. For non-legacy transactions, this value is `null`. - */ - get networkV() { - return this.#networkV; - } - /** - * The chain ID for EIP-155 legacy transactions. For non-legacy transactions, this value is `null`. - */ - get legacyChainId() { - const v = this.networkV; - if (v == null) { - return null; - } - return Signature.getChainId(v); - } - /** - * The `yParity` for the signature. - * - * See `v` for more details on how this value is used. - */ - get yParity() { - return this.v === 27 ? 0 : 1; - } - /** - * The [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098) compact representation of the `yParity` and `s` compacted - * into a single `bytes32`. - */ - get yParityAndS() { - // The EIP-2098 compact representation - const yParityAndS = getBytes(this.s); - if (this.yParity) { - yParityAndS[0] |= 0x80; - } - return hexlify(yParityAndS); - } - /** - * The [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098) compact representation. - */ - get compactSerialized() { - return concat([this.r, this.yParityAndS]); - } - /** - * The serialized representation. - */ - get serialized() { - return concat([this.r, this.s, this.yParity ? '0x1c' : '0x1b']); - } - /** - * @ignore - */ - constructor(guard, r, s, v) { - assertPrivate(guard, _guard$6, 'Signature'); - this.#r = r; - this.#s = s; - this.#v = v; - this.#networkV = null; - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`; - } - /** - * Returns a new identical {@link Signature | **Signature**}. - */ - clone() { - const clone = new Signature(_guard$6, this.r, this.s, this.v); - if (this.networkV) { - clone.#networkV = this.networkV; - } - return clone; - } - /** - * Returns a representation that is compatible with `JSON.stringify`. - */ - toJSON() { - const networkV = this.networkV; - return { - _type: 'signature', - networkV: networkV != null ? networkV.toString() : null, - r: this.r, - s: this.s, - v: this.v, - }; - } - /** - * Compute the chain ID from the `v` in a legacy EIP-155 transactions. - * - * @example - * - * ```ts - * Signature.getChainId(45); - * - * Signature.getChainId(46); - * ``` - * - * @param {BigNumberish} v - The `v` value from the signature. - * @returns {bigint} The chain ID. - */ - static getChainId(v) { - const bv = getBigInt(v, 'v'); - // The v is not an EIP-155 v, so it is the unspecified chain ID - if (bv == BN_27 || bv == BN_28) { - return BN_0$5; - } - // Bad value for an EIP-155 v - assertArgument(bv >= BN_35, 'invalid EIP-155 v', 'v', v); - return (bv - BN_35) / BN_2$1; - } - /** - * Compute the `v` for a chain ID for a legacy EIP-155 transactions. - * - * Legacy transactions which use [EIP-155](https://eips.ethereum.org/EIPS/eip-155) hijack the `v` property to - * include the chain ID. - * - * @example - * - * ```ts - * Signature.getChainIdV(5, 27); - * - * Signature.getChainIdV(5, 28); - * ``` - * - * @param {BigNumberish} chainId - The chain ID. - * @param {27 | 28} v - The `v` value. - * @returns {bigint} The `v` value. - */ - static getChainIdV(chainId, v) { - return getBigInt(chainId) * BN_2$1 + BigInt(35 + v - 27); - } - /** - * Compute the normalized legacy transaction `v` from a `yParirty`, a legacy transaction `v` or a legacy - * [EIP-155](https://eips.ethereum.org/EIPS/eip-155) transaction. - * - * @example - * - * ```ts - * // The values 0 and 1 imply v is actually yParity - * Signature.getNormalizedV(0); - * - * // Legacy non-EIP-1559 transaction (i.e. 27 or 28) - * Signature.getNormalizedV(27); - * - * // Legacy EIP-155 transaction (i.e. >= 35) - * Signature.getNormalizedV(46); - * - * // Invalid values throw - * Signature.getNormalizedV(5); - * ``` - * - * @param {BigNumberish} v - The `v` value. - * @returns {27 | 28} The normalized `v` value. - * @throws {Error} Thrown if the `v` is invalid. - */ - static getNormalizedV(v) { - const bv = getBigInt(v); - if (bv === BN_0$5 || bv === BN_27) { - return 27; - } - if (bv === BN_1$2 || bv === BN_28) { - return 28; - } - assertArgument(bv >= BN_35, 'invalid v', 'v', v); - // Otherwise, EIP-155 v means odd is 27 and even is 28 - return bv & BN_1$2 ? 27 : 28; - } - /** - * Creates a new {@link Signature | **Signature**}. - * - * If no `sig` is provided, a new {@link Signature | **Signature**} is created with default values. - * - * If `sig` is a string, it is parsed. - * - * @param {SignatureLike} [sig] - The signature to create. - * @returns {Signature} The new signature. - */ - static from(sig) { - function assertError(check, message) { - assertArgument(check, message, 'signature', sig); - } - if (sig == null) { - return new Signature(_guard$6, ZeroHash, ZeroHash, 27); - } - if (typeof sig === 'string') { - const bytes = getBytes(sig, 'signature'); - if (bytes.length === 64) { - const r = hexlify(bytes.slice(0, 32)); - const s = bytes.slice(32, 64); - const v = s[0] & 0x80 ? 28 : 27; - s[0] &= 0x7f; - return new Signature(_guard$6, r, hexlify(s), v); - } - if (bytes.length === 65) { - const r = hexlify(bytes.slice(0, 32)); - const s = bytes.slice(32, 64); - assertError((s[0] & 0x80) === 0, 'non-canonical s'); - const v = Signature.getNormalizedV(bytes[64]); - return new Signature(_guard$6, r, hexlify(s), v); - } - assertError(false, 'invalid raw signature length'); - } - if (sig instanceof Signature) { - return sig.clone(); - } - // Get r - const _r = sig.r; - assertError(_r != null, 'missing r'); - const r = toUint256(_r); - // Get s; by any means necessary (we check consistency below) - const s = (function (s, yParityAndS) { - if (s != null) { - return toUint256(s); - } - if (yParityAndS != null) { - assertError(isHexString(yParityAndS, 32), 'invalid yParityAndS'); - const bytes = getBytes(yParityAndS); - bytes[0] &= 0x7f; - return hexlify(bytes); - } - assertError(false, 'missing s'); - })(sig.s, sig.yParityAndS); - assertError((getBytes(s)[0] & 0x80) == 0, 'non-canonical s'); - // Get v; by any means necessary (we check consistency below) - const { networkV, v } = (function (_v, yParityAndS, yParity) { - if (_v != null) { - const v = getBigInt(_v); - return { - networkV: v >= BN_35 ? v : undefined, - v: Signature.getNormalizedV(v), - }; - } - if (yParityAndS != null) { - assertError(isHexString(yParityAndS, 32), 'invalid yParityAndS'); - return { v: getBytes(yParityAndS)[0] & 0x80 ? 28 : 27 }; - } - if (yParity != null) { - switch (yParity) { - case 0: - return { v: 27 }; - case 1: - return { v: 28 }; - } - assertError(false, 'invalid yParity'); - } - assertError(false, 'missing v'); - })(sig.v, sig.yParityAndS, sig.yParity); - const result = new Signature(_guard$6, r, s, v); - if (networkV) { - result.#networkV = networkV; - } - // If multiple of v, yParity, yParityAndS we given, check they match - assertError(!('yParity' in sig && sig.yParity !== result.yParity), 'yParity mismatch'); - assertError(!('yParityAndS' in sig && sig.yParityAndS !== result.yParityAndS), 'yParityAndS mismatch'); - return result; - } -} - -/** - * Add details about signing here. - */ -/** - * A **SigningKey** provides high-level access to the elliptic curve cryptography (ECC) operations and key management. - * - * @category Crypto - */ -class SigningKey { - #privateKey; - /** - * Creates a new **SigningKey** for `privateKey`. - */ - constructor(privateKey) { - assertArgument(dataLength(privateKey) === 32, 'invalid private key', 'privateKey', '[REDACTED]'); - this.#privateKey = hexlify(privateKey); - } - /** - * The private key. - */ - get privateKey() { - return this.#privateKey; - } - /** - * The uncompressed public key. - * - * This will always begin with the prefix `0x04` and be 132 characters long (the `0x` prefix and 130 hexadecimal - * nibbles). - */ - get publicKey() { - return SigningKey.computePublicKey(this.#privateKey); - } - /** - * The compressed public key. - * - * This will always begin with either the prefix `0x02` or `0x03` and be 68 characters long (the `0x` prefix and 33 - * hexadecimal nibbles) - */ - get compressedPublicKey() { - return SigningKey.computePublicKey(this.#privateKey, true); - } - /** - * Return the signature of the signed `digest`. - * - * @param {BytesLike} digest - The data to sign. - * @returns {Signature} The signature of the data. - * @throws {Error} If the digest is not 32 bytes long. - */ - sign(digest) { - assertArgument(dataLength(digest) === 32, 'invalid digest length', 'digest', digest); - const sig = secp256k1.sign(getBytesCopy(digest), getBytesCopy(this.#privateKey), { - lowS: true, - }); - return Signature.from({ - r: toBeHex('0x' + sig.r.toString(16), 32), - s: toBeHex('0x' + sig.s.toString(16), 32), - v: sig.recovery ? 0x1c : 0x1b, - }); - } - /** - * Returns the [ECDH](https://en.wikipedia.org/wiki/Elliptic-curve_Diffie-Hellman) shared secret between this - * private key and the `other` key. - * - * The `other` key may be any type of key, a raw public key, a compressed/uncompressed pubic key or aprivate key. - * - * Best practice is usually to use a cryptographic hash on the returned value before using it as a symetric secret. - * - * @example - * - * ```ts - * sign1 = new SigningKey(id('some-secret-1')); - * sign2 = new SigningKey(id('some-secret-2')); - * - * // Notice that privA.computeSharedSecret(pubB)... - * sign1.computeSharedSecret(sign2.publicKey); - * - * // ...is equal to privB.computeSharedSecret(pubA). - * sign2.computeSharedSecret(sign1.publicKey); - * ``` - * - * @param {BytesLike} other - The other key to compute the shared secret with. - * @returns {string} The shared secret. - */ - computeSharedSecret(other) { - const pubKey = SigningKey.computePublicKey(other); - return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey), getBytes(pubKey), false)); - } - /** - * Compute the public key for `key`, optionally `compressed`. - * - * The `key` may be any type of key, a raw public key, a compressed/uncompressed public key or private key. - * - * @example - * - * ```ts - * sign = new SigningKey(id('some-secret')); - * - * // Compute the uncompressed public key for a private key - * SigningKey.computePublicKey(sign.privateKey); - * - * // Compute the compressed public key for a private key - * SigningKey.computePublicKey(sign.privateKey, true); - * - * // Compute the uncompressed public key - * SigningKey.computePublicKey(sign.publicKey, false); - * - * // Compute the Compressed a public key - * SigningKey.computePublicKey(sign.publicKey, true); - * ``` - * - * @param {BytesLike} key - The key to compute the public key for. - * @param {boolean} [compressed] - Whether to return the compressed public key. - * @returns {string} The public key. - */ - static computePublicKey(key, compressed) { - let bytes = getBytes(key, 'key'); - // private key - if (bytes.length === 32) { - const pubKey = secp256k1.getPublicKey(bytes, !!compressed); - return hexlify(pubKey); - } - // raw public key; use uncompressed key with 0x04 prefix - if (bytes.length === 64) { - const pub = new Uint8Array(65); - pub[0] = 0x04; - pub.set(bytes, 1); - bytes = pub; - } - const point = secp256k1.ProjectivePoint.fromHex(bytes); - return hexlify(point.toRawBytes(compressed)); - } - /** - * Returns the public key for the private key which produced the `signature` for the given `digest`. - * - * @example - * - * ```ts - * key = new SigningKey(id('some-secret')); - * digest = id('hello world'); - * sig = key.sign(digest); - * - * // Notice the signer public key... - * key.publicKey; - * - * // ...is equal to the recovered public key - * SigningKey.recoverPublicKey(digest, sig); - * ``` - * - * @param {BytesLike} digest - The data that was signed. - * @param {SignatureLike} signature - The signature of the data. - * @returns {string} The public key. - */ - static recoverPublicKey(digest, signature) { - assertArgument(dataLength(digest) === 32, 'invalid digest length', 'digest', digest); - const sig = Signature.from(signature); - let secpSig = secp256k1.Signature.fromCompact(getBytesCopy(concat([sig.r, sig.s]))); - secpSig = secpSig.addRecoveryBit(sig.yParity); - const pubKey = secpSig.recoverPublicKey(getBytesCopy(digest)); - assertArgument(pubKey != null, 'invalid signautre for digest', 'signature', signature); - return '0x' + pubKey.toHex(false); - } - /** - * Returns the point resulting from adding the ellipic curve points `p0` and `p1`. - * - * This is not a common function most developers should require, but can be useful for certain privacy-specific - * techniques. - * - * For example, it is used by [**QuaiHDWallet**](../classes/QuaiHDWallet) to compute child addresses from parent - * public keys and chain codes. - * - * @param {BytesLike} p0 - The first point to add. - * @param {BytesLike} p1 - The second point to add. - * @param {boolean} [compressed] - Whether to return the compressed public key. - * @returns {string} The sum of the points. - */ - static addPoints(p0, p1, compressed) { - const pub0 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p0).substring(2)); - const pub1 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p1).substring(2)); - return '0x' + pub0.add(pub1).toHex(!!compressed); - } -} - -// BigInt / Uint8Array versions of Crypto functions that do not require point -// math. If your JS interpreter has BigInt, you can use all of these. If not, -// you'll need to either shim it in or override more of these functions. -// Idea from noble-secp256k1, be nice to bad JS parsers -const _0n = BigInt(0); -const _1n = BigInt(1); -const _2n = BigInt(2); -const _3n = BigInt(3); -const _5n = BigInt(5); -const _7n = BigInt(7); -const _64n = BigInt(64); -const _64mask = BigInt('0xFFFFFFFFFFFFFFFF'); -const CURVE = { - b: BigInt(7), - P: BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'), - n: BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141'), -}; -// Big Endian -function read32b(bytes) { - if (bytes.length !== 32) - throw new Error(`Expected 32-bytes, not ${bytes.length}`); - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length); - let b = view.getBigUint64(0); - for (let offs = 8; offs < bytes.length; offs += 8) { - b <<= _64n; - b += view.getBigUint64(offs); - } - return b; -} -function write32b(num, dest = new Uint8Array(32)) { - // All input values are modulo P or n, so no bounds checking needed - const view = new DataView(dest.buffer, dest.byteOffset, dest.length); - for (let offs = 24; offs >= 0; offs -= 8) { - view.setBigUint64(offs, num & _64mask); - num >>= _64n; - } - return dest; -} -function readScalar(bytes) { - const a = read32b(bytes); - if (a >= CURVE.n) - throw new Error('Expected value mod n'); - return a; -} -function readSecret(bytes) { - const a = readScalar(bytes); - if (a === 0n) - throw new Error('Expected non-zero'); - return a; -} -// The short Weierstrass form curve equation simplifes to y^2 = x^3 + 7. -function secp256k1Right(x) { - const x2 = (x * x) % CURVE.P; - const x3 = (x2 * x) % CURVE.P; - return (x3 + CURVE.b) % CURVE.P; -} -// For prime P, the Jacobi Symbol of 'a' is 1 if and only if 'a' is a quadratic -// residue mod P, ie. there exists a value 'x' for whom x^2 = a. -function jacobiSymbol(a) { - if (a === _0n) - return 0; // Vanishingly improbable - let p = CURVE.P; - let sign = 1; - // This algorithm is fairly heavily optimized, so don't simplify it w/o benchmarking - for (;;) { - let and3; - // Handle runs of zeros efficiently w/o flipping sign each time - for (and3 = a & _3n; and3 === _0n; a >>= _2n, and3 = a & _3n) - ; - // If there's one more zero, shift it off and flip the sign - if (and3 === _2n) { - a >>= _1n; - const pand7 = p & _7n; - if (pand7 === _3n || pand7 === _5n) - sign = -sign; - } - if (a === _1n) - break; - if ((_3n & a) === _3n && (_3n & p) === _3n) - sign = -sign; - [a, p] = [p % a, a]; - } - return sign > 0 ? 1 : -1; -} -function isPoint(p) { - if (p.length < 33) - return false; - const t = p[0]; - if (p.length === 33) { - return (t === 0x02 || t === 0x03) && isXOnlyPoint(p.subarray(1)); - } - if (t !== 0x04 || p.length !== 65) - return false; - const x = read32b(p.subarray(1, 33)); - if (x === _0n) - return false; - if (x >= CURVE.P) - return false; - const y = read32b(p.subarray(33)); - if (y === _0n) - return false; - if (y >= CURVE.P) - return false; - const left = (y * y) % CURVE.P; - const right = secp256k1Right(x); - return left === right; -} -function isXOnlyPoint(p) { - if (p.length !== 32) - return false; - const x = read32b(p); - if (x === _0n) - return false; - if (x >= CURVE.P) - return false; - const y2 = secp256k1Right(x); - return jacobiSymbol(y2) === 1; // If sqrt(y^2) exists, x is on the curve. -} -function scalarAdd(a, b) { - const aN = readScalar(a); - const bN = readScalar(b); - const sum = (aN + bN) % CURVE.n; - return write32b(sum); -} -function scalarMultiply(a, b) { - const aN = readScalar(a); - const bN = readScalar(b); - const product = (aN * bN) % CURVE.n; - return write32b(product); -} -function scalarNegate(a) { - const aN = readScalar(a); - const negated = aN === _0n ? _0n : CURVE.n - aN; - return write32b(negated); -} -function scalarMod(a) { - const aN = read32b(a); - const remainder = aN % CURVE.n; - return write32b(remainder); -} -function isScalar(t) { - try { - readScalar(t); - return true; - } - catch { - return false; - } -} -function isSecret(s) { - try { - readSecret(s); - return true; - } - catch { - return false; - } -} -function pointNegate(p) { - // hasEvenY does basic structure check, so start there - const even = hasEvenY(p); - // `from` because node.Buffer.slice doesn't copy but looks like a Uint8Array - const negated = Uint8Array.from(p); - if (p.length === 33) { - negated[0] = even ? 3 : 2; - } - else if (p.length === 65) { - const y = read32b(p.subarray(33)); - if (y >= CURVE.P) - throw new Error('Expected Y coordinate mod P'); - const minusY = y === _0n ? _0n : CURVE.P - y; - write32b(minusY, negated.subarray(33)); - } - return negated; -} -function pointX(p) { - if (p.length === 32) - return p; - hasEvenY(p); // hasEvenY throws if not well structured - return p.slice(1, 33); -} -function hasEvenY(p) { - if (p.length === 33) { - if (p[0] === 2) - return true; - else if (p[0] === 3) - return false; - else - throw new Error('Wrong first byte to be a point'); - } - if (p.length === 65) { - if (p[0] !== 4) - throw new Error('Wrong first byte to be point'); - return p[64] % 2 === 0; - } - throw new Error('Wrong length to be a point'); -} -function pointMultiplyUnsafe(p, a, compress) { - try { - const product = secp256k1.ProjectivePoint.fromHex(p).multiplyAndAddUnsafe(secp256k1.ProjectivePoint.ZERO, BigInt(`0x${Buffer.from(a).toString('hex')}`), BigInt(1)); - if (!product) - return null; - return product.toRawBytes(compress); - } - catch { - return null; - } -} -function pointMultiplyAndAddUnsafe(p1, a, p2, compress) { - try { - const p2p = secp256k1.ProjectivePoint.fromHex(p2); - const p = secp256k1.ProjectivePoint.fromHex(p1).multiplyAndAddUnsafe(p2p, BigInt(`0x${Buffer.from(a).toString('hex')}`), BigInt(1)); - if (!p) - return null; - return p.toRawBytes(compress); - } - catch { - return null; - } -} -function pointAdd(a, b, compress) { - try { - return secp256k1.ProjectivePoint.fromHex(a).add(secp256k1.ProjectivePoint.fromHex(b)).toRawBytes(compress); - } - catch { - return null; - } -} -function pointAddTweak(p, tweak, compress) { - try { - const P = secp256k1.ProjectivePoint.fromHex(p); - const t = readSecret(tweak); - const Q = secp256k1.ProjectivePoint.BASE.multiplyAndAddUnsafe(P, t, 1n); - if (!Q) - throw new Error('Tweaked point at infinity'); - return Q.toRawBytes(compress); - } - catch { - return null; - } -} -function pointCompress(p, compress = true) { - return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(compress); -} -function liftX(p) { - try { - return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(false); - } - catch { - return null; - } -} -function getPublicKey(s, compress) { - try { - return secp256k1.getPublicKey(s, compress); - } - catch { - return null; - } -} -function taggedHash(tag, ...messages) { - return schnorr.utils.taggedHash(tag, ...messages); -} -function sha256Hash(...messages) { - const h = sha256$1.create(); - for (const message of messages) - h.update(message); - return h.digest(); -} -const musigCrypto = { - read32b, - write32b, - readScalar, - readSecret, - secp256k1Right, - jacobiSymbol, - isPoint, - isXOnlyPoint, - scalarAdd, - scalarMultiply, - scalarNegate, - scalarMod, - isScalar, - isSecret, - pointNegate, - pointX, - hasEvenY, - pointMultiplyUnsafe, - pointMultiplyAndAddUnsafe, - pointAdd, - pointAddTweak, - pointCompress, - liftX, - getPublicKey, - taggedHash, - sha256: sha256Hash, -}; - -/** - * A fundamental building block of Ethereum is the underlying cryptographic primitives. - */ -/** - * Once called, prevents any future change to the underlying cryptographic primitives using the `.register` feature for - * hooks. - * - * @category Crypto - */ -function lock() { - computeHmac.lock(); - keccak256.lock(); - pbkdf2.lock(); - randomBytes.lock(); - ripemd160.lock(); - scrypt.lock(); - scryptSync.lock(); - sha256.lock(); - sha512.lock(); - randomBytes.lock(); -} - -function formatMixedCaseChecksumAddress(address) { - address = address.toLowerCase(); - const chars = address.substring(2).split(''); - const expanded = new Uint8Array(40); - for (let i = 0; i < 40; i++) { - expanded[i] = chars[i].charCodeAt(0); - } - const hashed = getBytes(keccak256(expanded)); - for (let i = 0; i < 40; i += 2) { - if (hashed[i >> 1] >> 4 >= 8) { - chars[i] = chars[i].toUpperCase(); - } - if ((hashed[i >> 1] & 0x0f) >= 8) { - chars[i + 1] = chars[i + 1].toUpperCase(); - } - } - return '0x' + chars.join(''); -} -/** - * Returns a normalized and checksumed address for `address`. This accepts non-checksum addressesa and checksum - * addresses. - * - * The checksum in Quai uses the capitalization (upper-case vs lower-case) of the characters within an address to encode - * its checksum, which offers, on average, a checksum of 15-bits. - * - * If `address` contains both upper-case and lower-case, it is assumed to already be a checksum address and its checksum - * is validated, and if the address fails its expected checksum an error is thrown. - * - * If you wish the checksum of `address` to be ignore, it should be converted to lower-case (i.e. `.toLowercase()`) - * before being passed in. This should be a very rare situation though, that you wish to bypass the safeguards in place - * to protect against an address that has been incorrectly copied from another source. - * - * @category Address - * @example - * - * ```js - * // Adds the checksum (via upper-casing specific letters) - * getAddress('0x8ba1f109551bd432803012645ac136ddd64dba72'); - * - * // Throws an error if an address contains mixed case, - * // but the checksum fails - * getAddress('0x8Ba1f109551bD432803012645Ac136ddd64DBA72'); - * ``` - */ -function getAddress(address) { - assertArgument(typeof address === 'string', 'invalid address', 'address', address); - if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { - // Missing the 0x prefix - if (!address.startsWith('0x')) { - address = '0x' + address; - } - const result = formatMixedCaseChecksumAddress(address); - // If original address is mix cased and recomputed version doesn't - // match the original this could indicate a potential typo or mispaste. - assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, 'invalid address checksum', 'address', address); - return result; - } - assertArgument(false, 'invalid address string format', 'address', address); -} -function getContractAddress(from, nonce, data) { - const nonceBytes = zeroPadValue(toBeHex(toBigInt(nonce)), 8); - return getAddress(dataSlice(keccak256(concat([getAddress(from), nonceBytes, stripZerosLeft(data)])), 12)); -} -/** - * Returns the address for the `key`. - * - * The key may be any standard form of public key or a private key. - * - * @category Address - * @param {string | SigningKey} key - The key to compute the address for. - * @returns {string} The address. - */ -function computeAddress(key) { - let pubkey; - if (typeof key === 'string') { - pubkey = SigningKey.computePublicKey(key, false); - } - else { - pubkey = key.publicKey; - } - return getAddress(keccak256('0x' + pubkey.substring(4)).substring(26)); -} -/** - * Returns the recovered address for the private key that was used to sign `digest` that resulted in `signature`. - * - * @category Address - * @param {BytesLike} digest - The digest of the message. - * @param {SignatureLike} signature - The signature. - * @returns {string} The address. - */ -function recoverAddress(digest, signature) { - return computeAddress(SigningKey.recoverPublicKey(digest, signature)); -} - -/** - * Returns true if `value` is an object which implements the [**Addressable**](../interfaces/Addressable) interface. - * - * @category Address - * @example - * - * ```js - * // Wallets and AbstractSigner sub-classes - * isAddressable(Wallet.createRandom()); - * - * // Contracts - * contract = new Contract('0x643aA0A61eADCC9Cc202D1915D942d35D005400C', [], provider); - * isAddressable(contract); - * ``` - * - * @param {any} value - The value to check. - * @returns {boolean} True if the value is an Addressable. - */ -function isAddressable(value) { - return value && typeof value.getAddress === 'function'; -} -/** - * Returns true if `value` is a valid address. - * - * @category Address - * @example - * - * ```js - * // Valid address - * isAddress('0x8ba1f109551bD432803012645Ac136ddd64DBA72'); - * - * // Invalid checksum - * isAddress('0x8Ba1f109551bD432803012645Ac136ddd64DBa72'); - * ``` - * - * @param {any} value - The value to check. - * @returns {boolean} True if the value is a valid address. - */ -function isAddress(value) { - try { - getAddress(value); - return true; - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; -} -async function checkAddress(target, promise) { - const result = await promise; - if (result == null || result === '0x0000000000000000000000000000000000000000') { - assertArgument(false, 'invalid AddressLike value; did not resolve to a value address', 'target', target); - } - return result; -} -/** - * Resolves to an address for the `target`, which may be any supported address type, an - * [**Addressable**](../interfaces/Addressable) or a Promise which resolves to an address. - * - * @category Address - * @example - * - * ```js - * addr = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; - * - * // Addresses are return synchronously - * resolveAddress(addr, provider); - * - * // Address promises are resolved asynchronously - * resolveAddress(Promise.resolve(addr)); - * - * // Addressable objects are resolved asynchronously - * contract = new Contract(addr, []); - * resolveAddress(contract, provider); - * ``` - * - * @param {AddressLike} target - The target to resolve to an address. - * @returns {string | Promise} The resolved address. - */ -function resolveAddress(target) { - if (typeof target === 'string') { - if (target.match(/^0x[0-9a-f]{40}$/i)) { - return target; - } - } - else if (isAddressable(target)) { - return checkAddress(target, target.getAddress()); - } - else if (target && typeof target.then === 'function') { - return checkAddress(target, target); - } - assertArgument(false, 'unsupported addressable value', 'target', target); -} -/** - * Checks if the address is a valid mixed case checksummed address. - * - * @category Address - * @param address - The address to validate. - * @returns True if the address is a valid mixed case checksummed address. - */ -function validateAddress(address) { - assertArgument(typeof address === 'string', 'address must be string', 'address', address); - assertArgument(Boolean(address.match(/^(0x)?[0-9a-fA-F]{40}$/)), 'invalid address string format', 'address', address); - assertArgument(formatMixedCaseChecksumAddress(address) === address, 'invalid address checksum', 'address', address); -} -/** - * Checks whether a given address is in the Qi ledger scope by checking the 9th bit of the address. - * - * @category Address - * @param {string} address - The address to check - * @returns {boolean} True if the address is in the Qi ledger scope, false otherwise. - */ -function isQiAddress(address) { - const secondByte = address.substring(4, 6); - const binaryString = parseInt(secondByte, 16).toString(2).padStart(8, '0'); - const isUTXO = binaryString[0] === '1'; - return isUTXO; -} -/** - * Checks whether a given address is in the Quai ledger scope by checking the 9th bit of the address. - * - * @category Address - * @param {string} address - The address to check - * @returns {boolean} True if the address is in the Quai ledger scope, false otherwise. - */ -function isQuaiAddress(address) { - return !isQiAddress(address); -} - -/** - * Retrieves the shard information for a given address based on its byte prefix. The function parses the address to - * extract its byte prefix, then filters the ShardData to find a matching shard entry. If no matching shard is found, it - * returns null. - * - * @category Utils - * @param {string} address - The blockchain address to be analyzed. The address should start with "0x" followed by the - * hexadecimal representation. - * @returns {Object | null} An object containing the shard information, or null if no - */ -function getZoneForAddress(address) { - try { - return toZone(address.slice(0, 4)); - } - catch (error) { - return null; - } -} -/** - * Extracts both zone and UTXO information from a given blockchain address. This function first determines the address's - * zone by its byte prefix, then checks the 9th bit of the address to ascertain if it's a UTXO or non-UTXO address. - * - * @category Utils - * @param {string} address - The blockchain address to be analyzed, expected to start with "0x" followed by its - * hexadecimal representation. - * @returns {Object | null} An object containing the zone and UTXO information, or null if no address is found. - */ -function getAddressDetails(address) { - const isQiLedger = (parseInt(address.substring(4, 5), 16) & 0x1) === Ledger.Qi; - return { zone: toZone(address.substring(0, 4)), ledger: isQiLedger ? Ledger.Qi : Ledger.Quai }; -} -/** - * Determines the transaction type based on the sender and recipient addresses. The function checks if both addresses - * are UTXO addresses, in which case it returns 2. If only the sender address is a UTXO address, it returns 1. - * Otherwise, it returns 0. - * - * @category Utils - * @param {string | null} from - The sender address. If null, the function returns 0. - * @param {string | null} to - The recipient address. If null, the function returns 0. - * @returns {number} The transaction type based on the addresses. - */ -function getTxType(from, to) { - if (from === null || to === null) - return 0; - const senderAddressIsQi = isQiAddress(from); - const recipientAddressIsQi = isQiAddress(to); - switch (true) { - case senderAddressIsQi && recipientAddressIsQi: - return 2; - case senderAddressIsQi && !recipientAddressIsQi: - return 1; - default: - return 0; - } -} -/** - * Location of a chain within the Quai hierarchy - * - * Prime = [] region[0] = [0] zone[1,2] = [1, 2] - * - * @param shard - The shard to get the location for - * @returns The location of the chain within the Quai hierarchy - */ -function getNodeLocationFromZone(zone) { - const zoneId = zone.slice(2); - if (zoneId.length > 2) { - throw new Error(`Invalid zone: ${zone}`); - } - else if (zoneId.length === 0) { - return []; - } - return zoneId.split('').map(Number); -} -function getZoneFromNodeLocation(location) { - if (location.length > 2) { - throw new Error('Invalid location'); - } - return toZone(`0x${location.join('')}`); -} - -/** - * @ignore - */ -const WordSize = 32; -const Padding = new Uint8Array(WordSize); -// Properties used to immediate pass through to the underlying object -// - `then` is used to detect if an object is a Promise for await -const passProperties$1 = ['then']; -const _guard$5 = {}; -function throwError(name, error) { - const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`); - wrapped.error = error; - throw wrapped; -} -/** - * A {@link Result | **Result**} is a sub-class of Array, which allows accessing any of its values either positionally by - * its index or, if keys are provided by its name. - * - * @category Application Binary Interface - */ -class Result extends Array { - #names; - /** - * @ignore - */ - constructor(...args) { - // To properly sub-class Array so the other built-in - // functions work, the constructor has to behave fairly - // well. So, in the event we are created via fromItems() - // we build the read-only Result object we want, but on - // any other input, we use the default constructor - // constructor(guard: any, items: Array, keys?: Array); - const guard = args[0]; - let items = args[1]; - let names = (args[2] || []).slice(); - let wrap = true; - if (guard !== _guard$5) { - items = args; - names = []; - wrap = false; - } - // Can't just pass in ...items since an array of length 1 - // is a special case in the super. - super(items.length); - items.forEach((item, index) => { - this[index] = item; - }); - // Find all unique keys - const nameCounts = names.reduce((accum, name) => { - if (typeof name === 'string') { - accum.set(name, (accum.get(name) || 0) + 1); - } - return accum; - }, new Map()); - // Remove any key thats not unique - this.#names = Object.freeze(items.map((item, index) => { - const name = names[index]; - if (name != null && nameCounts.get(name) === 1) { - return name; - } - return null; - })); - if (!wrap) { - return; - } - // A wrapped Result is immutable - Object.freeze(this); - // Proxy indices and names so we can trap deferred errors - return new Proxy(this, { - get: (target, prop, receiver) => { - if (typeof prop === 'string') { - // Index accessor - if (prop.match(/^[0-9]+$/)) { - const index = getNumber(prop, '%index'); - if (index < 0 || index >= this.length) { - throw new RangeError('out of result range'); - } - const item = target[index]; - if (item instanceof Error) { - throwError(`index ${index}`, item); - } - return item; - } - // Pass important checks (like `then` for Promise) through - if (passProperties$1.indexOf(prop) >= 0) { - return Reflect.get(target, prop, receiver); - } - const value = target[prop]; - if (value instanceof Function) { - // Make sure functions work with private variables - // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#no_private_property_forwarding - return function (...args) { - return value.apply(this === receiver ? target : this, args); - }; - } - else if (!(prop in target)) { - // Possible name accessor - return target.getValue.apply(this === receiver ? target : this, [prop]); - } - } - return Reflect.get(target, prop, receiver); - }, - }); - } - /** - * Returns the Result as a normal Array. - * - * This will throw if there are any outstanding deferred errors. - */ - toArray() { - const result = []; - this.forEach((item, index) => { - if (item instanceof Error) { - throwError(`index ${index}`, item); - } - result.push(item); - }); - return result; - } - /** - * Returns the Result as an Object with each name-value pair. - * - * This will throw if any value is unnamed, or if there are any outstanding deferred errors. - */ - toObject() { - return this.#names.reduce( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (accum, name, index) => { - assert(name != null, 'value at index ${ index } unnamed', 'UNSUPPORTED_OPERATION', { - operation: 'toObject()', - }); - // Add values for names that don't conflict - if (!(name in accum)) { - accum[name] = this.getValue(name); - } - return accum; - }, {}); - } - /** - * @ignore - */ - slice(start, end) { - if (start == null) { - start = 0; - } - if (start < 0) { - start += this.length; - if (start < 0) { - start = 0; - } - } - if (end == null) { - end = this.length; - } - if (end < 0) { - end += this.length; - if (end < 0) { - end = 0; - } - } - if (end > this.length) { - end = this.length; - } - const result = [], names = []; - for (let i = start; i < end; i++) { - result.push(this[i]); - names.push(this.#names[i]); - } - return new Result(_guard$5, result, names); - } - /** - * @ignore - */ - filter(callback, thisArg) { - const result = [], names = []; - for (let i = 0; i < this.length; i++) { - const item = this[i]; - if (item instanceof Error) { - throwError(`index ${i}`, item); - } - if (callback.call(thisArg, item, i, this)) { - result.push(item); - names.push(this.#names[i]); - } - } - return new Result(_guard$5, result, names); - } - /** - * @ignore - */ - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint - map(callback, thisArg) { - const result = []; - for (let i = 0; i < this.length; i++) { - const item = this[i]; - if (item instanceof Error) { - throwError(`index ${i}`, item); - } - result.push(callback.call(thisArg, item, i, this)); - } - return result; - } - /** - * Returns the value for `name`. - * - * Since it is possible to have a key whose name conflicts with a method on a {@link Result | **Result**} or its - * superclass Array, or any JavaScript keyword, this ensures all named values are still accessible by name. - * - * @param {string} name - The name of the value to retrieve. - * - * @returns The value for `name`. - */ - getValue(name) { - const index = this.#names.indexOf(name); - if (index === -1) { - return undefined; - } - const value = this[index]; - if (value instanceof Error) { - throwError(`property ${JSON.stringify(name)}`, value.error); - } - return value; - } - /** - * Creates a new {@link Result | **Result**} for `items` with each entry also accessible by its corresponding name in - * `keys`. - * - * @param {any[]} items - The items to include in the Result. - * @param {(null | string)[]} [keys] - The names for each item in `items`. - * - * @returns The new Result. - */ - static fromItems(items, keys) { - return new Result(_guard$5, items, keys); - } -} -/** - * Returns all errors found in a {@link Result | **Result**}. - * - * Since certain errors encountered when creating a {@link Result | **Result**} do not impact the ability to continue - * parsing data, they are deferred until they are actually accessed. Hence a faulty string in an Event that is never - * used does not impact the program flow. - * - * However, sometimes it may be useful to access, identify or validate correctness of a {@link Result | **Result**}. - * - * @category Application Binary Interface - * @param {Result} result - The Result to check for errors. - * - * @returns An array of objects with the path to the error and the error itself. - */ -function checkResultErrors(result) { - // Find the first error (if any) - const errors = []; - const checkErrors = function (path, object) { - if (!Array.isArray(object)) { - return; - } - for (const key in object) { - const childPath = path.slice(); - childPath.push(key); - try { - checkErrors(childPath, object[key]); - } - catch (error) { - errors.push({ path: childPath, error: error }); - } - } - }; - checkErrors([], result); - return errors; -} -function getValue$1(value) { - let bytes = toBeArray(value); - assert(bytes.length <= WordSize, 'value out-of-bounds', 'BUFFER_OVERRUN', { - buffer: bytes, - length: WordSize, - offset: bytes.length, - }); - if (bytes.length !== WordSize) { - bytes = getBytesCopy(concat([Padding.slice(bytes.length % WordSize), bytes])); - } - return bytes; -} -/** - * @ignore - */ -class Coder { - // The coder name: - // - address, uint256, tuple, array, etc. - name; - // The fully expanded type, including composite types: - // - address, uint256, tuple(address,bytes), uint256[3][4][], etc. - type; - // The localName bound in the signature, in this example it is "baz": - // - tuple(address foo, uint bar) baz - localName; - // Whether this type is dynamic: - // - Dynamic: bytes, string, address[], tuple(boolean[]), etc. - // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8) - dynamic; - constructor(name, type, localName, dynamic) { - defineProperties(this, { name, type, localName, dynamic }, { - name: 'string', - type: 'string', - localName: 'string', - dynamic: 'boolean', - }); - } - _throwError(message, value) { - assertArgument(false, message, this.localName, value); - } -} -/** - * @ignore - */ -class Writer { - // An array of WordSize lengthed objects to concatenation - #data; - #dataLength; - constructor() { - this.#data = []; - this.#dataLength = 0; - } - get data() { - return concat(this.#data); - } - get length() { - return this.#dataLength; - } - #writeData(data) { - this.#data.push(data); - this.#dataLength += data.length; - return data.length; - } - appendWriter(writer) { - return this.#writeData(getBytesCopy(writer.data)); - } - // Arrayish item; pad on the right to *nearest* WordSize - writeBytes(value) { - let bytes = getBytesCopy(value); - const paddingOffset = bytes.length % WordSize; - if (paddingOffset) { - bytes = getBytesCopy(concat([bytes, Padding.slice(paddingOffset)])); - } - return this.#writeData(bytes); - } - // Numeric item; pad on the left *to* WordSize - writeValue(value) { - return this.#writeData(getValue$1(value)); - } - // Inserts a numeric place-holder, returning a callback that can - // be used to asjust the value later - writeUpdatableValue() { - const offset = this.#data.length; - this.#data.push(Padding); - this.#dataLength += WordSize; - return (value) => { - this.#data[offset] = getValue$1(value); - }; - } -} -/** - * @ignore - */ -class Reader { - // Allows incomplete unpadded data to be read; otherwise an error - // is raised if attempting to overrun the buffer. This is required - // to deal with an old Solidity bug, in which event data for - // external (not public thoguh) was tightly packed. - allowLoose; - #data; - #offset; - #bytesRead; - #parent; - #maxInflation; - constructor(data, allowLoose, maxInflation) { - defineProperties(this, { allowLoose: !!allowLoose }); - this.#data = getBytesCopy(data); - this.#bytesRead = 0; - this.#parent = null; - this.#maxInflation = maxInflation != null ? maxInflation : 1024; - this.#offset = 0; - } - get data() { - return hexlify(this.#data); - } - get dataLength() { - return this.#data.length; - } - get consumed() { - return this.#offset; - } - get bytes() { - return new Uint8Array(this.#data); - } - #incrementBytesRead(count) { - if (this.#parent) { - return this.#parent.#incrementBytesRead(count); - } - this.#bytesRead += count; - // Check for excessive inflation (see: #4537) - assert(this.#maxInflation < 1 || this.#bytesRead <= this.#maxInflation * this.dataLength, - // eslint-disable-next-line no-useless-escape - `compressed ABI data exceeds inflation ratio of ${this.#maxInflation} ( see: https:/\/github.com/ethers-io/ethers.js/issues/4537 )`, 'BUFFER_OVERRUN', { - buffer: getBytesCopy(this.#data), - offset: this.#offset, - length: count, - info: { - bytesRead: this.#bytesRead, - dataLength: this.dataLength, - }, - }); - } - #peekBytes(offset, length, loose) { - let alignedLength = Math.ceil(length / WordSize) * WordSize; - if (this.#offset + alignedLength > this.#data.length) { - if (this.allowLoose && loose && this.#offset + length <= this.#data.length) { - alignedLength = length; - } - else { - assert(false, 'data out-of-bounds', 'BUFFER_OVERRUN', { - buffer: getBytesCopy(this.#data), - length: this.#data.length, - offset: this.#offset + alignedLength, - }); - } - } - return this.#data.slice(this.#offset, this.#offset + alignedLength); - } - // Create a sub-reader with the same underlying data, but offset - subReader(offset) { - const reader = new Reader(this.#data.slice(this.#offset + offset), this.allowLoose, this.#maxInflation); - reader.#parent = this; - return reader; - } - // Read bytes - readBytes(length, loose) { - const bytes = this.#peekBytes(0, length, !!loose); - this.#incrementBytesRead(length); - this.#offset += bytes.length; - // @TODO: Make sure the length..end bytes are all 0? - return bytes.slice(0, length); - } - // Read a numeric values - readValue() { - return toBigInt(this.readBytes(WordSize)); - } - readIndex() { - return toNumber(this.readBytes(WordSize)); - } -} - -// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed -/** - * Returns the address that would result from a `CREATE` for `tx`. - * - * This can be used to compute the address a contract will be deployed to by an EOA when sending a deployment - * transaction (i.e. when the `to` address is `null`). - * - * This can also be used to compute the address a contract will be deployed to by a contract, by using the contract's - * address as the `to` and the contract's nonce. - * - * @category Address - * @example - * - * ```js - * from = '0x8ba1f109551bD432803012645Ac136ddd64DBA72'; - * nonce = 5; - * - * getCreateAddress({ from, nonce }); - * ``` - * - * @param {object} tx - The transaction object. - * @param {string} tx.from - The address of the sender. - * @param {BigNumberish} tx.nonce - The nonce of the sender. - * @param {string} [tx.data] - The data of the transaction. - */ -function getCreateAddress(tx) { - const from = getAddress(tx.from); - const nonce = getBigInt(tx.nonce, 'tx.nonce'); - const nonceBytes = bigEndianNonce(nonce); - const fromBytes = getBytes(from); - const codeBytes = tx.data ? getBytes(tx.data) : new Uint8Array(); - const concatenated = new Uint8Array([...fromBytes, ...nonceBytes, ...codeBytes]); - const hash = keccak256(concatenated); - return getAddress(dataSlice(hash, 12)); -} -/** - * Returns the address that would result from a `CREATE2` operation with the given `from`, `salt` and `initCodeHash`. - * - * To compute the `initCodeHash` from a contract's init code, use the [**keccak256**](../functions/keccak256) function. - * - * For a quick overview and example of `CREATE2`, see [Wisps: The Magical World of - * Create2](https://blog.ricmoo.com/wisps-the-magical-world-of-create2-5c2177027604). - * - * @category Address - * @example - * - * ```js - * // The address of the contract - * from = '0x8ba1f109551bD432803012645Ac136ddd64DBA72'; - * - * // The salt - * salt = id('HelloWorld'); - * - * // The hash of the initCode - * initCode = '0x6394198df16000526103ff60206004601c335afa6040516060f3'; - * initCodeHash = keccak256(initCode); - * - * getCreate2Address(from, salt, initCodeHash); - * ``` - * - * @param {string} _from - The address of the sender. - * @param {BytesLike} _salt - The salt value. - * @param {BytesLike} _initCodeHash - The hash of the init code. - * @returns {string} The computed address. - * @throws {Error} If the salt is not exactly 32 bytes long. - * @throws {Error} If the initCodeHash is not exactly 32 bytes long. - */ -function getCreate2Address(_from, _salt, _initCodeHash) { - const from = getAddress(_from); - const salt = getBytes(_salt, 'salt'); - const initCodeHash = getBytes(_initCodeHash, 'initCodeHash'); - assertArgument(salt.length === 32, 'salt must be 32 bytes', 'salt', _salt); - assertArgument(initCodeHash.length === 32, 'initCodeHash must be 32 bytes', 'initCodeHash', _initCodeHash); - return getAddress(dataSlice(keccak256(concat(['0xff', from, salt, initCodeHash])), 12)); -} -// Helper function to convert a BigInt nonce to a big-endian byte array -function bigEndianNonce(nonce) { - const buffer = new ArrayBuffer(8); - const view = new DataView(buffer); - view.setBigUint64(0, nonce, false); - return new Uint8Array(buffer); -} - -/** - * A Typed object allows a value to have its type explicitly specified. - * - * For example, in Solidity, the value `45` could represent a `uint8` or a `uint256`. The value `0x1234` could represent - * a `bytes2` or `bytes`. - * - * Since JavaScript has no meaningful way to explicitly inform any APIs which what the type is, this allows transparent - * interoperation with Soldity. - * - * @category Application Binary Interface - */ -const _guard$4 = {}; -function n(value, width) { - let signed = false; - if (width < 0) { - signed = true; - width *= -1; - } - // @TODO: Check range is valid for value - return new Typed(_guard$4, `${signed ? '' : 'u'}int${width}`, value, { signed, width }); -} -function b(value, size) { - // @TODO: Check range is valid for value - return new Typed(_guard$4, `bytes${size ? size : ''}`, value, { size }); -} -const _typedSymbol = Symbol.for('_quais_typed'); -/** - * The **Typed** class to wrap values providing explicit type information. - * - * @category Application Binary Interface - */ -class Typed { - /** - * The type, as a Solidity-compatible type. - */ - type; - /** - * The actual value. - */ - value; - #options; - /** - * @ignore - */ - _typedSymbol; - /** - * @ignore - */ - constructor(guard, type, value, options) { - if (options == null) { - options = null; - } - assertPrivate(_guard$4, guard, 'Typed'); - defineProperties(this, { _typedSymbol, type, value }); - this.#options = options; - // Check the value is valid - this.format(); - } - /** - * Format the type as a Human-Readable type. - * - * @returns The human-readable type for the provided type. - * @throws If the type is array or dynamic array. - */ - format() { - if (this.type === 'array') { - throw new Error(''); - } - else if (this.type === 'dynamicArray') { - throw new Error(''); - } - else if (this.type === 'tuple') { - return `tuple(${this.value.map((v) => v.format()).join(',')})`; - } - return this.type; - } - /** - * The default value returned by this type. - * - * @returns The default value for this type. - */ - defaultValue() { - return 0; - } - /** - * The minimum value for numeric types. - * - * @returns The minimum value for the provided numeric type. - */ - minValue() { - return 0; - } - /** - * The maximum value for numeric types. - * - * @returns The maximum value for the provided numeric type. - */ - maxValue() { - return 0; - } - /** - * Returns whether this is a {@link TypedBigInt | **TypedBigInt**}. If true, a type guard is provided. - * - * @returns `true` if this is a big integer. - */ - isBigInt() { - return !!this.type.match(/^u?int[0-9]+$/); - } - /** - * Returns whether this is a {@link TypedData | **TypedData**}. If true, a type guard is provided. - * - * @returns {boolean} `true` if this is a number. - */ - isData() { - return this.type.startsWith('bytes'); - } - /** - * Return whether this is a {@link TypedString | **TypedString**}. If true, a type guard is provided. - * - * @returns {boolean} `true` if this is a string. - */ - isString() { - return this.type === 'string'; - } - /** - * Returns the tuple name. - * - * @returns {boolean} The tuple name if this is a tuple. - * @throws If this is not a tuple. - */ - get tupleName() { - if (this.type !== 'tuple') { - throw TypeError('not a tuple'); - } - return this.#options; - } - /** - * Returns the length of a typed array. - * - * @returns {number} The length of the array type or `-1` if it is dynamic. - * @throws If this is not an array. - */ - get arrayLength() { - if (this.type !== 'array') { - throw TypeError('not an array'); - } - if (this.#options === true) { - return -1; - } - if (this.#options === false) { - return this.value.length; - } - return null; - } - /** - * Returns a new **Typed** of `type` with the `value`. - * - * @param {string} type - The type to use. - * @param {any} value - The value to use. - */ - static from(type, value) { - return new Typed(_guard$4, type, value); - } - /** - * Return a new `uint8` type for v. - * - * @param {BigNumberish} v - The value to convert to a `uint8`. - * - * @returns {uint8} A new `uint8` type for `v`. - */ - static uint8(v) { - return n(v, 8); - } - /** - * Return a new `uint16` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint16`. - * - * @returns A new `uint16` type for `v`. - */ - static uint16(v) { - return n(v, 16); - } - /** - * Return a new `uint24` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint24`. - * - * @returns A new `uint24` type for `v`. - */ - static uint24(v) { - return n(v, 24); - } - /** - * Return a new `uint32` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint32`. - * - * @returns A new `uint32` type for `v`. - */ - static uint32(v) { - return n(v, 32); - } - /** - * Return a new `uint40` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint40`. - * - * @returns A new `uint40` type for `v`. - */ - static uint40(v) { - return n(v, 40); - } - /** - * Return a new `uint48` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint48`. - * - * @returns A new `uint48` type for `v`. - */ - static uint48(v) { - return n(v, 48); - } - /** - * Return a new `uint56` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint56`. - * - * @returns A new `uint56` type for `v`. - */ - static uint56(v) { - return n(v, 56); - } - /** - * Return a new `uint64` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint64`. - * - * @returns A new `uint64` type for `v`. - */ - static uint64(v) { - return n(v, 64); - } - /** - * Return a new `uint72` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint72`. - * - * @returns A new `uint72` type for `v`. - */ - static uint72(v) { - return n(v, 72); - } - /** - * Return a new `uint80` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint80`. - * - * @returns A new `uint80` type for `v`. - */ - static uint80(v) { - return n(v, 80); - } - /** - * Return a new `uint88` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint88`. - * - * @returns A new `uint88` type for `v`. - */ - static uint88(v) { - return n(v, 88); - } - /** - * Return a new `uint96` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint96`. - * - * @returns A new `uint96` type for `v`. - */ - static uint96(v) { - return n(v, 96); - } - /** - * Return a new `uint104` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint104`. - * - * @returns A new `uint104` type for `v`. - */ - static uint104(v) { - return n(v, 104); - } - /** - * Return a new `uint112` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint112`. - * - * @returns A new `uint112` type for `v`. - */ - static uint112(v) { - return n(v, 112); - } - /** - * Return a new `uint120` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint120`. - * - * @returns A new `uint120` type for `v`. - */ - static uint120(v) { - return n(v, 120); - } - /** - * Return a new `uint128` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint128`. - * - * @returns A new `uint128` type for `v`. - */ - static uint128(v) { - return n(v, 128); - } - /** - * Return a new `uint136` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint136`. - * - * @returns A new `uint136` type for `v`. - */ - static uint136(v) { - return n(v, 136); - } - /** - * Return a new `uint144` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint144`. - * - * @returns A new `uint144` type for `v`. - */ - static uint144(v) { - return n(v, 144); - } - /** - * Return a new `uint152` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint152`. - * - * @returns A new `uint152` type for `v`. - */ - static uint152(v) { - return n(v, 152); - } - /** - * Return a new `uint160` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint160`. - * - * @returns A new `uint160` type for `v`. - */ - static uint160(v) { - return n(v, 160); - } - /** - * Return a new `uint168` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint168`. - * - * @returns A new `uint168` type for `v`. - */ - static uint168(v) { - return n(v, 168); - } - /** - * Return a new `uint176` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint176`. - * - * @returns A new `uint176` type for `v`. - */ - static uint176(v) { - return n(v, 176); - } - /** - * Return a new `uint184` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint184`. - * - * @returns A new `uint184` type for `v`. - */ - static uint184(v) { - return n(v, 184); - } - /** - * Return a new `uint192` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint192`. - * - * @returns A new `uint192` type for `v`. - */ - static uint192(v) { - return n(v, 192); - } - /** - * Return a new `uint200` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint200`. - * - * @returns A new `uint200` type for `v`. - */ - static uint200(v) { - return n(v, 200); - } - /** - * Return a new `uint208` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint208`. - * - * @returns A new `uint208` type for `v`. - */ - static uint208(v) { - return n(v, 208); - } - /** - * Return a new `uint216` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint216`. - * - * @returns A new `uint216` type for `v`. - */ - static uint216(v) { - return n(v, 216); - } - /** - * Return a new `uint224` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint224`. - * - * @returns A new `uint224` type for `v`. - */ - static uint224(v) { - return n(v, 224); - } - /** - * Return a new `uint232` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint232`. - * - * @returns A new `uint232` type for `v`. - */ - static uint232(v) { - return n(v, 232); - } - /** - * Return a new `uint240` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint240`. - * - * @returns A new `uint240` type for `v`. - */ - static uint240(v) { - return n(v, 240); - } - /** - * Return a new `uint248` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint248`. - * - * @returns A new `uint248` type for `v`. - */ - static uint248(v) { - return n(v, 248); - } - /** - * Return a new `uint256` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint256`. - * - * @returns A new `uint256` type for `v`. - */ - static uint256(v) { - return n(v, 256); - } - /** - * Return a new `uint256` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint256`. - * - * @returns A new `uint256` type for `v`. - */ - static uint(v) { - return n(v, 256); - } - /** - * Return a new `int8` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int8`. - * - * @returns A new `int8` type for `v`. - */ - static int8(v) { - return n(v, -8); - } - /** - * Return a new `int16` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int16`. - * - * @returns A new `int16` type for `v`. - */ - static int16(v) { - return n(v, -16); - } - /** - * Return a new `int24` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int24`. - * - * @returns A new `int24` type for `v`. - */ - static int24(v) { - return n(v, -24); - } - /** - * Return a new `int32` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int32`. - * - * @returns A new `int32` type for `v`. - */ - static int32(v) { - return n(v, -32); - } - /** - * Return a new `int40` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int40`. - * - * @returns A new `int40` type for `v`. - */ - static int40(v) { - return n(v, -40); - } - /** - * Return a new `int48` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int48`. - * - * @returns A new `int48` type for `v`. - */ - static int48(v) { - return n(v, -48); - } - /** - * Return a new `int56` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int56`. - * - * @returns A new `int56` type for `v`. - */ - static int56(v) { - return n(v, -56); - } - /** - * Return a new `int64` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int64`. - * - * @returns A new `int64` type for `v`. - */ - static int64(v) { - return n(v, -64); - } - /** - * Return a new `int72` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int72`. - * - * @returns A new `int72` type for `v`. - */ - static int72(v) { - return n(v, -72); - } - /** - * Return a new `int80` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int80`. - * - * @returns A new `int80` type for `v`. - */ - static int80(v) { - return n(v, -80); - } - /** - * Return a new `int88` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int88`. - * - * @returns A new `int88` type for `v`. - */ - static int88(v) { - return n(v, -88); - } - /** - * Return a new `int96` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int96`. - * - * @returns A new `int96` type for `v`. - */ - static int96(v) { - return n(v, -96); - } - /** - * Return a new `int104` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int104`. - * - * @returns A new `int104` type for `v`. - */ - static int104(v) { - return n(v, -104); - } - /** - * Return a new `int112` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int112`. - * - * @returns A new `int112` type for `v`. - */ - static int112(v) { - return n(v, -112); - } - /** - * Return a new `int120` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int120`. - * - * @returns A new `int120` type for `v`. - */ - static int120(v) { - return n(v, -120); - } - /** - * Return a new `int128` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int128`. - * - * @returns A new `int128` type for `v`. - */ - static int128(v) { - return n(v, -128); - } - /** - * Return a new `int136` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int136`. - * - * @returns A new `int136` type for `v`. - */ - static int136(v) { - return n(v, -136); - } - /** - * Return a new `int144` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int144`. - * - * @returns A new `int144` type for `v`. - */ - static int144(v) { - return n(v, -144); - } - /** - * Return a new `int152` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int152`. - * - * @returns A new `int152` type for `v`. - */ - static int152(v) { - return n(v, -152); - } - /** - * Return a new `int160` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int160`. - * - * @returns A new `int160` type for `v`. - */ - static int160(v) { - return n(v, -160); - } - /** - * Return a new `int168` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int168`. - * - * @returns A new `int168` type for `v`. - */ - static int168(v) { - return n(v, -168); - } - /** - * Return a new `int176` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int176`. - * - * @returns A new `int176` type for `v`. - */ - static int176(v) { - return n(v, -176); - } - /** - * Return a new `int184` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int184`. - * - * @returns A new `int184` type for `v`. - */ - static int184(v) { - return n(v, -184); - } - /** - * Return a new `int192` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int192`. - * - * @returns A new `int192` type for `v`. - */ - static int192(v) { - return n(v, -192); - } - /** - * Return a new `int200` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int200`. - * - * @returns A new `int200` type for `v`. - */ - static int200(v) { - return n(v, -200); - } - /** - * Return a new `int208` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int208`. - * - * @returns A new `int208` type for `v`. - */ - static int208(v) { - return n(v, -208); - } - /** - * Return a new `int216` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int216`. - * - * @returns A new `int216` type for `v`. - */ - static int216(v) { - return n(v, -216); - } - /** - * Return a new `int224` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int224`. - * - * @returns A new `int224` type for `v`. - */ - static int224(v) { - return n(v, -224); - } - /** - * Return a new `int232` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int232`. - * - * @returns A new `int232` type for `v`. - */ - static int232(v) { - return n(v, -232); - } - /** - * Return a new `int240` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int240`. - * - * @returns A new `int240` type for `v`. - */ - static int240(v) { - return n(v, -240); - } - /** - * Return a new `int248` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int248`. - * - * @returns A new `int248` type for `v`. - */ - static int248(v) { - return n(v, -248); - } - /** - * Return a new `int256` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int256`. - * - * @returns A new `int256` type for `v`. - */ - static int256(v) { - return n(v, -256); - } - /** - * Return a new `int256` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int256`. - * - * @returns A new `int256` type for `v`. - */ - static int(v) { - return n(v, -256); - } - /** - * Return a new `bytes1` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes1`. - * - * @returns A new `bytes1` type for `v`. - */ - static bytes1(v) { - return b(v, 1); - } - /** - * Return a new `bytes2` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes2`. - * - * @returns A new `bytes2` type for `v`. - */ - static bytes2(v) { - return b(v, 2); - } - /** - * Return a new `bytes3` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes3`. - * - * @returns A new `bytes3` type for `v`. - */ - static bytes3(v) { - return b(v, 3); - } - /** - * Return a new `bytes4` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes4`. - * - * @returns A new `bytes4` type for `v`. - */ - static bytes4(v) { - return b(v, 4); - } - /** - * Return a new `bytes5` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes5`. - * - * @returns A new `bytes5` type for `v`. - */ - static bytes5(v) { - return b(v, 5); - } - /** - * Return a new `bytes6` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes6`. - * - * @returns A new `bytes6` type for `v`. - */ - static bytes6(v) { - return b(v, 6); - } - /** - * Return a new `bytes7` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes7`. - * - * @returns A new `bytes7` type for `v`. - */ - static bytes7(v) { - return b(v, 7); - } - /** - * Return a new `bytes8` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes8`. - * - * @returns A new `bytes8` type for `v`. - */ - static bytes8(v) { - return b(v, 8); - } - /** - * Return a new `bytes9` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes9`. - * - * @returns A new `bytes9` type for `v`. - */ - static bytes9(v) { - return b(v, 9); - } - /** - * Return a new `bytes10` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes10`. - * - * @returns A new `bytes10` type for `v`. - */ - static bytes10(v) { - return b(v, 10); - } - /** - * Return a new `bytes11` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes11`. - * - * @returns A new `bytes11` type for `v`. - */ - static bytes11(v) { - return b(v, 11); - } - /** - * Return a new `bytes12` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes12`. - * - * @returns A new `bytes12` type for `v`. - */ - static bytes12(v) { - return b(v, 12); - } - /** - * Return a new `bytes13` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes13`. - * - * @returns A new `bytes13` type for `v`. - */ - static bytes13(v) { - return b(v, 13); - } - /** - * Return a new `bytes14` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes14`. - * - * @returns A new `bytes14` type for `v`. - */ - static bytes14(v) { - return b(v, 14); - } - /** - * Return a new `bytes15` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes15`. - * - * @returns A new `bytes15` type for `v`. - */ - static bytes15(v) { - return b(v, 15); - } - /** - * Return a new `bytes16` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes16`. - * - * @returns A new `bytes16` type for `v`. - */ - static bytes16(v) { - return b(v, 16); - } - /** - * Return a new `bytes17` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes17`. - * - * @returns A new `bytes17` type for `v`. - */ - static bytes17(v) { - return b(v, 17); - } - /** - * Return a new `bytes18` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes18`. - * - * @returns A new `bytes18` type for `v`. - */ - static bytes18(v) { - return b(v, 18); - } - /** - * Return a new `bytes19` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes19`. - * - * @returns A new `bytes19` type for `v`. - */ - static bytes19(v) { - return b(v, 19); - } - /** - * Return a new `bytes20` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes20`. - * - * @returns A new `bytes20` type for `v`. - */ - static bytes20(v) { - return b(v, 20); - } - /** - * Return a new `bytes21` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes21`. - * - * @returns A new `bytes21` type for `v`. - */ - static bytes21(v) { - return b(v, 21); - } - /** - * Return a new `bytes22` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes22`. - * - * @returns A new `bytes22` type for `v`. - */ - static bytes22(v) { - return b(v, 22); - } - /** - * Return a new `bytes23` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes23`. - * - * @returns A new `bytes23` type for `v`. - */ - static bytes23(v) { - return b(v, 23); - } - /** - * Return a new `bytes24` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes24`. - * - * @returns A new `bytes24` type for `v`. - */ - static bytes24(v) { - return b(v, 24); - } - /** - * Return a new `bytes25` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes25`. - * - * @returns A new `bytes25` type for `v`. - */ - static bytes25(v) { - return b(v, 25); - } - /** - * Return a new `bytes26` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes26`. - * - * @returns A new `bytes26` type for `v`. - */ - static bytes26(v) { - return b(v, 26); - } - /** - * Return a new `bytes27` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes27`. - * - * @returns A new `bytes27` type for `v`. - */ - static bytes27(v) { - return b(v, 27); - } - /** - * Return a new `bytes28` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes28`. - * - * @returns A new `bytes28` type for `v`. - */ - static bytes28(v) { - return b(v, 28); - } - /** - * Return a new `bytes29` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes29`. - * - * @returns A new `bytes29` type for `v`. - */ - static bytes29(v) { - return b(v, 29); - } - /** - * Return a new `bytes30` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes30`. - * - * @returns A new `bytes30` type for `v`. - */ - static bytes30(v) { - return b(v, 30); - } - /** - * Return a new `bytes31` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes31`. - * - * @returns A new `bytes31` type for `v`. - */ - static bytes31(v) { - return b(v, 31); - } - /** - * Return a new `bytes32` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes32`. - * - * @returns A new `bytes32` type for `v`. - */ - static bytes32(v) { - return b(v, 32); - } - /** - * Return a new `address` type for `v`. - * - * @param {BytesLike} v - The value to convert to an `address`. - * - * @returns A new `address` type for `v`. - */ - static address(v) { - return new Typed(_guard$4, 'address', v); - } - /** - * Return a new `bool` type for `v`. - * - * @param {any} v - The value to convert to a `bool`. - * - * @returns A new `bool` type for `v`. - */ - static bool(v) { - return new Typed(_guard$4, 'bool', !!v); - } - /** - * Return a new `bytes` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes`. - * - * @returns A new `bytes` type for `v`. - */ - static bytes(v) { - return new Typed(_guard$4, 'bytes', v); - } - /** - * Return a new `string` type for `v`. - * - * @param {string} v - The value to convert to a `string`. - * - * @returns A new `string` type for `v`. - */ - static string(v) { - return new Typed(_guard$4, 'string', v); - } - /** - * Return a new `array` type for v, allowing dynamic length. - * - * @param {(any | Typed)[]} v - The value to convert to an `array`. - * @param {null | boolean} dynamic - Whether the array is dynamic. - * - * @returns A new `array` type for `v`. - */ - static array(v, dynamic) { - throw new Error('not implemented yet'); - } - /** - * Return a new `tuple` type for v, with the optional name. - * - * @param {(any | Typed)[]} v - The value to convert to a `tuple`. - * @param {string} name - The name of the tuple. - * - * @returns A new `tuple` type for `v`. - */ - static tuple(v, name) { - throw new Error('not implemented yet'); - } - /** - * Return a new `overrides` type with the provided properties. - * - * @param {Record} v - A record containing the properties to be included in the `overrides` type. - * - * @returns A new `overrides` type with the given properties. - */ - static overrides(v) { - return new Typed(_guard$4, 'overrides', Object.assign({}, v)); - } - /** - * Returns true only if `value` is a {@link Typed | **Typed**} instance. - * - * @param {any} value - The value to check. - * - * @returns {boolean} True if `value` is a {@link Typed | **Typed**} instance. - */ - static isTyped(value) { - return value && typeof value === 'object' && '_typedSymbol' in value && value._typedSymbol === _typedSymbol; - } - /** - * If the value is a {@link Typed | **Typed**} instance, validates the underlying value and returns it, otherwise - * returns value directly. - * - * This is useful for functions that with to accept either a {@link Typed | **Typed**} object or values. - * - * @param {Typed | T} value - The value to dereference. - * @param {string} type - The dereferenced value. - */ - static dereference(value, type) { - if (Typed.isTyped(value)) { - if (value.type !== type) { - throw new Error(`invalid type: expected ${type}, got ${value.type}`); - } - return value.value; - } - return value; - } -} - -/** - * @ignore - */ -class AddressCoder extends Coder { - constructor(localName) { - super("address", "address", localName, false); - } - defaultValue() { - return "0x0000000000000000000000000000000000000000"; - } - encode(writer, _value) { - let value = Typed.dereference(_value, "string"); - try { - value = getAddress(value); - } - catch (error) { - return this._throwError(error.message, _value); - } - return writer.writeValue(value); - } - decode(reader) { - return getAddress(toBeHex(reader.readValue(), 20)); - } -} - -/** - * Clones the functionality of an existing Coder, but without a localName - * - * @ignore - */ -class AnonymousCoder extends Coder { - coder; - constructor(coder) { - super(coder.name, coder.type, "_", coder.dynamic); - this.coder = coder; - } - defaultValue() { - return this.coder.defaultValue(); - } - encode(writer, value) { - return this.coder.encode(writer, value); - } - decode(reader) { - return this.coder.decode(reader); - } -} - -/** - * @ignore - */ -function pack(writer, coders, values) { - let arrayValues = []; - if (Array.isArray(values)) { - arrayValues = values; - } - else if (values && typeof (values) === "object") { - let unique = {}; - arrayValues = coders.map((coder) => { - const name = coder.localName; - assert(name, "cannot encode object for signature with missing names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); - assert(!unique[name], "cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); - unique[name] = true; - return values[name]; - }); - } - else { - assertArgument(false, "invalid tuple value", "tuple", values); - } - assertArgument(coders.length === arrayValues.length, "types/value length mismatch", "tuple", values); - let staticWriter = new Writer(); - let dynamicWriter = new Writer(); - let updateFuncs = []; - coders.forEach((coder, index) => { - let value = arrayValues[index]; - if (coder.dynamic) { - // Get current dynamic offset (for the future pointer) - let dynamicOffset = dynamicWriter.length; - // Encode the dynamic value into the dynamicWriter - coder.encode(dynamicWriter, value); - // Prepare to populate the correct offset once we are done - let updateFunc = staticWriter.writeUpdatableValue(); - updateFuncs.push((baseOffset) => { - updateFunc(baseOffset + dynamicOffset); - }); - } - else { - coder.encode(staticWriter, value); - } - }); - // Backfill all the dynamic offsets, now that we know the static length - updateFuncs.forEach((func) => { func(staticWriter.length); }); - let length = writer.appendWriter(staticWriter); - length += writer.appendWriter(dynamicWriter); - return length; -} -/** - * @ignore - */ -function unpack(reader, coders) { - let values = []; - let keys = []; - // A reader anchored to this base - let baseReader = reader.subReader(0); - coders.forEach((coder) => { - let value = null; - if (coder.dynamic) { - let offset = reader.readIndex(); - let offsetReader = baseReader.subReader(offset); - try { - value = coder.decode(offsetReader); - } - catch (error) { - // Cannot recover from this - if (isError(error, "BUFFER_OVERRUN")) { - throw error; - } - value = error; - value.baseType = coder.name; - value.name = coder.localName; - value.type = coder.type; - } - } - else { - try { - value = coder.decode(reader); - } - catch (error) { - // Cannot recover from this - if (isError(error, "BUFFER_OVERRUN")) { - throw error; - } - value = error; - value.baseType = coder.name; - value.name = coder.localName; - value.type = coder.type; - } - } - if (value == undefined) { - throw new Error("investigate"); - } - values.push(value); - keys.push(coder.localName || null); - }); - return Result.fromItems(values, keys); -} -/** - * @ignore - */ -class ArrayCoder extends Coder { - coder; - length; - constructor(coder, length, localName) { - const type = (coder.type + "[" + (length >= 0 ? length : "") + "]"); - const dynamic = (length === -1 || coder.dynamic); - super("array", type, localName, dynamic); - defineProperties(this, { coder, length }); - } - defaultValue() { - // Verifies the child coder is valid (even if the array is dynamic or 0-length) - const defaultChild = this.coder.defaultValue(); - const result = []; - for (let i = 0; i < this.length; i++) { - result.push(defaultChild); - } - return result; - } - encode(writer, _value) { - const value = Typed.dereference(_value, "array"); - if (!Array.isArray(value)) { - this._throwError("expected array value", value); - } - let count = this.length; - if (count === -1) { - count = value.length; - writer.writeValue(value.length); - } - assertArgumentCount(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : "")); - let coders = []; - for (let i = 0; i < value.length; i++) { - coders.push(this.coder); - } - return pack(writer, coders, value); - } - decode(reader) { - let count = this.length; - if (count === -1) { - count = reader.readIndex(); - // Check that there is *roughly* enough data to ensure - // stray random data is not being read as a length. Each - // slot requires at least 32 bytes for their value (or 32 - // bytes as a link to the data). This could use a much - // tighter bound, but we are erroring on the side of safety. - assert(count * WordSize <= reader.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: reader.bytes, offset: count * WordSize, length: reader.dataLength }); - } - let coders = []; - for (let i = 0; i < count; i++) { - coders.push(new AnonymousCoder(this.coder)); - } - return unpack(reader, coders); - } -} - -/** - * @ignore - */ -class BooleanCoder extends Coder { - constructor(localName) { - super("bool", "bool", localName, false); - } - defaultValue() { - return false; - } - encode(writer, _value) { - const value = Typed.dereference(_value, "bool"); - return writer.writeValue(value ? 1 : 0); - } - decode(reader) { - return !!reader.readValue(); - } -} - -/** - * @ignore - */ -class DynamicBytesCoder extends Coder { - constructor(type, localName) { - super(type, type, localName, true); - } - defaultValue() { - return "0x"; - } - encode(writer, value) { - value = getBytesCopy(value); - let length = writer.writeValue(value.length); - length += writer.writeBytes(value); - return length; - } - decode(reader) { - return reader.readBytes(reader.readIndex(), true); - } -} -/** - * @ignore - */ -class BytesCoder extends DynamicBytesCoder { - constructor(localName) { - super("bytes", localName); - } - decode(reader) { - return hexlify(super.decode(reader)); - } -} - -/** - * @ignore - */ -class FixedBytesCoder extends Coder { - size; - constructor(size, localName) { - let name = "bytes" + String(size); - super(name, name, localName, false); - defineProperties(this, { size }, { size: "number" }); - } - defaultValue() { - return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2); - } - encode(writer, _value) { - let data = getBytesCopy(Typed.dereference(_value, this.type)); - if (data.length !== this.size) { - this._throwError("incorrect data length", _value); - } - return writer.writeBytes(data); - } - decode(reader) { - return hexlify(reader.readBytes(this.size)); - } -} - -const Empty = new Uint8Array([]); -/** - * @ignore - */ -class NullCoder extends Coder { - constructor(localName) { - super("null", "", localName, false); - } - defaultValue() { - return null; - } - encode(writer, value) { - if (value != null) { - this._throwError("not null", value); - } - return writer.writeBytes(Empty); - } - decode(reader) { - reader.readBytes(0); - return null; - } -} - -const BN_0$4 = BigInt(0); -const BN_1$1 = BigInt(1); -const BN_MAX_UINT256$1 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -/** - * @ignore - */ -class NumberCoder extends Coder { - size; - signed; - constructor(size, signed, localName) { - const name = ((signed ? "int" : "uint") + (size * 8)); - super(name, name, localName, false); - defineProperties(this, { size, signed }, { size: "number", signed: "boolean" }); - } - defaultValue() { - return 0; - } - encode(writer, _value) { - let value = getBigInt(Typed.dereference(_value, this.type)); - // Check bounds are safe for encoding - let maxUintValue = mask(BN_MAX_UINT256$1, WordSize * 8); - if (this.signed) { - let bounds = mask(maxUintValue, (this.size * 8) - 1); - if (value > bounds || value < -(bounds + BN_1$1)) { - this._throwError("value out-of-bounds", _value); - } - value = toTwos(value, 8 * WordSize); - } - else if (value < BN_0$4 || value > mask(maxUintValue, this.size * 8)) { - this._throwError("value out-of-bounds", _value); - } - return writer.writeValue(value); - } - decode(reader) { - let value = mask(reader.readValue(), this.size * 8); - if (this.signed) { - value = fromTwos(value, this.size * 8); - } - return value; - } -} - -/** - * @ignore - */ -class StringCoder extends DynamicBytesCoder { - constructor(localName) { - super("string", localName); - } - defaultValue() { - return ""; - } - encode(writer, _value) { - return super.encode(writer, toUtf8Bytes(Typed.dereference(_value, "string"))); - } - decode(reader) { - return toUtf8String(super.decode(reader)); - } -} - -/** - * @ignore - */ -class TupleCoder extends Coder { - coders; - constructor(coders, localName) { - let dynamic = false; - const types = []; - coders.forEach((coder) => { - if (coder.dynamic) { - dynamic = true; - } - types.push(coder.type); - }); - const type = ("tuple(" + types.join(",") + ")"); - super("tuple", type, localName, dynamic); - defineProperties(this, { coders: Object.freeze(coders.slice()) }); - } - defaultValue() { - const values = []; - this.coders.forEach((coder) => { - values.push(coder.defaultValue()); - }); - // We only output named properties for uniquely named coders - const uniqueNames = this.coders.reduce((accum, coder) => { - const name = coder.localName; - if (name) { - if (!accum[name]) { - accum[name] = 0; - } - accum[name]++; - } - return accum; - }, {}); - // Add named values - this.coders.forEach((coder, index) => { - let name = coder.localName; - if (!name || uniqueNames[name] !== 1) { - return; - } - if (name === "length") { - name = "_length"; - } - if (values[name] != null) { - return; - } - values[name] = values[index]; - }); - return Object.freeze(values); - } - encode(writer, _value) { - const value = Typed.dereference(_value, "tuple"); - return pack(writer, this.coders, value); - } - decode(reader) { - return unpack(reader, this.coders); - } -} - -/** - * A simple hashing function which operates on UTF-8 strings to compute an 32-byte identifier. - * - * This simply computes the {@link toUtf8Bytes | **UTF-8 bytes**} and computes the {@link keccak256 | **keccak256**}. - * - * @category Hash - * @example - * - * ```ts - * id('hello world'); - * ``` - * - * @param {string} value - The string to hash. - * @returns {string} The 32-byte identifier. - */ -function id(value) { - return keccak256(toUtf8Bytes(value)); -} - -/** - * Computes the Quai Network equivalent of the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal-sign message - * digest to sign. - * - * This prefixes the message with {@link MessagePrefix | **MessagePrefix**} and the decimal length of `message` and - * computes the {@link keccak256 | **keccak256**} digest. - * - * If `message` is a string, it is converted to its UTF-8 bytes first. To compute the digest of a - * [**DataHexString**](../types-aliases/DataHex), it must be converted to [**bytes**](../functions/getBytes). - * - * @category Hash - * @example - * - * ```ts - * hashMessage('Hello World'); - * - * // Hashes the SIX (6) string characters, i.e. - * // [ "0", "x", "4", "2", "4", "3" ] - * hashMessage('0x4243'); - * - * // Hashes the TWO (2) bytes [ 0x42, 0x43 ]... - * hashMessage(getBytes('0x4243')); - * - * // ...which is equal to using data - * hashMessage(new Uint8Array([0x42, 0x43])); - * ``` - * - * @param {Uint8Array | string} message - The message to hash. - * @returns {string} The message digest. - */ -function hashMessage(message) { - if (typeof message === 'string') { - message = toUtf8Bytes(message); - } - return keccak256(concat([toUtf8Bytes(MessagePrefix), toUtf8Bytes(String(message.length)), message])); -} -/** - * Return the address of the private key that produced the signature `sig` during signing for `message`. - * - * @category Hash - * @param {Uint8Array | string} message - The message that was signed. - * @param {SignatureLike} sig - The signature to verify. - * @returns {string} The address of the signer. - */ -function verifyMessage(message, sig) { - const digest = hashMessage(message); - return recoverAddress(digest, sig); -} -/** - * Computes the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal-sign message digest to sign. - * - * This prefixes the message with {@link EthMessagePrefix | **EthMessagePrefix**} and the decimal length of `message` and - * computes the {@link keccak256 | **keccak256**} digest. - * - * If `message` is a string, it is converted to its UTF-8 bytes first. To compute the digest of a - * [**DataHexString**](../types-aliases/DataHex), it must be converted to [**bytes**](../functions/getBytes). - * - * This is the same as `hashMessage` except it uses `EthMessagePrefix` instead of `MessagePrefix` and is available for - * broader compatibility with EVM signing practices. - * - * @category Hash - * @param message - * @returns - */ -function ethHashMessage(message) { - if (typeof message === 'string') { - message = toUtf8Bytes(message); - } - return keccak256(concat([toUtf8Bytes(EthMessagePrefix), toUtf8Bytes(String(message.length)), message])); -} -/** - * Return the address of the private key that produced the signature `sig` during signing for `message`. - * - * This is the same as `verifyMessage` except it uses `EthMessagePrefix` instead of `MessagePrefix` and is available for - * broader compatibility with EVM signing practices. - * - * @category Hash - * @param message - The message that was signed. - * @param sig - The signature to verify. - * @returns {string} The address of the signer. - */ -function ethVerifyMessage(message, sig) { - const digest = ethHashMessage(message); - return recoverAddress(digest, sig); -} - -const regexBytes = new RegExp('^bytes([0-9]+)$'); -const regexNumber = new RegExp('^(u?int)([0-9]*)$'); -const regexArray = new RegExp('^(.*)\\[([0-9]*)\\]$'); -function _pack(type, value, isArray) { - switch (type) { - case 'address': - if (isArray) { - return getBytes(zeroPadValue(value, 32)); - } - return getBytes(getAddress(value)); - case 'string': - return toUtf8Bytes(value); - case 'bytes': - return getBytes(value); - case 'bool': - value = value ? '0x01' : '0x00'; - if (isArray) { - return getBytes(zeroPadValue(value, 32)); - } - return getBytes(value); - } - let match = type.match(regexNumber); - if (match) { - const signed = match[1] === 'int'; - let size = parseInt(match[2] || '256'); - assertArgument((!match[2] || match[2] === String(size)) && size % 8 === 0 && size !== 0 && size <= 256, 'invalid number type', 'type', type); - if (isArray) { - size = 256; - } - if (signed) { - value = toTwos(value, size); - } - return getBytes(zeroPadValue(toBeArray(value), size / 8)); - } - match = type.match(regexBytes); - if (match) { - const size = parseInt(match[1]); - assertArgument(String(size) === match[1] && size !== 0 && size <= 32, 'invalid bytes type', 'type', type); - assertArgument(dataLength(value) === size, `invalid value for ${type}`, 'value', value); - if (isArray) { - return getBytes(zeroPadBytes(value, 32)); - } - return value; - } - match = type.match(regexArray); - if (match && Array.isArray(value)) { - const baseType = match[1]; - const count = parseInt(match[2] || String(value.length)); - assertArgument(count === value.length, `invalid array length for ${type}`, 'value', value); - const result = []; - value.forEach(function (value) { - result.push(_pack(baseType, value, true)); - }); - return getBytes(concat(result)); - } - assertArgument(false, 'invalid type', 'type', type); -} -// @TODO: Array Enum -/** - * Computes the [Non-Standard Packed - * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) representation of `values` - * respectively to their `types`. - * - * @category Hash - * @example - * - * ```ts - * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72'; - * solidityPacked(['address', 'uint'], [addr, 45]); - * ``` - * - * @param {string[]} types - The types of the values. - * @param {ReadonlyArray} values - The values to pack. - * @returns {string} The packed values. - */ -function solidityPacked(types, values) { - assertArgument(types.length === values.length, 'wrong number of values; expected ${ types.length }', 'values', values); - const tight = []; - types.forEach(function (type, index) { - tight.push(_pack(type, values[index])); - }); - return hexlify(concat(tight)); -} -/** - * Computes the [Non-Standard Packed - * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) - * [**keccak256**](../functions/keccak256) hash of `values` respectively to their `types`. - * - * @category Hash - * @example - * - * ```ts - * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72'; - * solidityPackedKeccak256(['address', 'uint'], [addr, 45]); - * ``` - * - * @param {ReadonlyArray} types - The types of the values. - * @param {ReadonlyArray} values - The values to hash. - * @returns {string} The hash of the packed values. - */ -function solidityPackedKeccak256(types, values) { - return keccak256(solidityPacked(types, values)); -} -/** - * Computes the [Non-Standard Packed - * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) [sha256](../functions/sha256) - * hash of `values` respectively to their `types`. - * - * @category Hash - * @example - * - * ```ts - * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72'; - * solidityPackedSha256(['address', 'uint'], [addr, 45]); - * ``` - * - * @param {ReadonlyArray} types - The types of the values. - * @param {ReadonlyArray} values - The values to hash. - * @returns {string} The hash of the packed values. - */ -function solidityPackedSha256(types, values) { - return sha256(solidityPacked(types, values)); -} - -//import { TypedDataDomain, TypedDataField } from "@quaisproject/providerabstract-signer"; -const padding = new Uint8Array(32); -padding.fill(0); -const BN__1 = BigInt(-1); -const BN_0$3 = BigInt(0); -const BN_1 = BigInt(1); -const BN_MAX_UINT256 = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); -function hexPadRight(value) { - const bytes = getBytes(value); - const padOffset = bytes.length % 32; - if (padOffset) { - return concat([bytes, padding.slice(padOffset)]); - } - return hexlify(bytes); -} -const hexTrue = toBeHex(BN_1, 32); -const hexFalse = toBeHex(BN_0$3, 32); -const domainFieldTypes = { - name: 'string', - version: 'string', - chainId: 'uint256', - verifyingContract: 'address', - salt: 'bytes32', -}; -const domainFieldNames = ['name', 'version', 'chainId', 'verifyingContract', 'salt']; -function checkString(key) { - return function (value) { - assertArgument(typeof value === 'string', `invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); - return value; - }; -} -const domainChecks = { - name: checkString('name'), - version: checkString('version'), - chainId: function (_value) { - const value = getBigInt(_value, 'domain.chainId'); - assertArgument(value >= 0, 'invalid chain ID', 'domain.chainId', _value); - if (Number.isSafeInteger(value)) { - return Number(value); - } - return toQuantity(value); - }, - verifyingContract: function (value) { - try { - return getAddress(value); - // eslint-disable-next-line no-empty - } - catch (error) { } - assertArgument(false, `invalid domain value "verifyingContract"`, 'domain.verifyingContract', value); - }, - salt: function (value) { - const bytes = getBytes(value, 'domain.salt'); - assertArgument(bytes.length === 32, `invalid domain value "salt"`, 'domain.salt', value); - return hexlify(bytes); - }, -}; -function getBaseEncoder(type) { - // intXX and uintXX - { - const match = type.match(/^(u?)int(\d*)$/); - if (match) { - const signed = match[1] === ''; - const width = parseInt(match[2] || '256'); - assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && (match[2] == null || match[2] === String(width)), 'invalid numeric width', 'type', type); - const boundsUpper = mask(BN_MAX_UINT256, signed ? width - 1 : width); - const boundsLower = signed ? (boundsUpper + BN_1) * BN__1 : BN_0$3; - return function (_value) { - const value = getBigInt(_value, 'value'); - assertArgument(value >= boundsLower && value <= boundsUpper, `value out-of-bounds for ${type}`, 'value', value); - return toBeHex(signed ? toTwos(value, 256) : value, 32); - }; - } - } - // bytesXX - { - const match = type.match(/^bytes(\d+)$/); - if (match) { - const width = parseInt(match[1]); - assertArgument(width !== 0 && width <= 32 && match[1] === String(width), 'invalid bytes width', 'type', type); - return function (value) { - const bytes = getBytes(value); - assertArgument(bytes.length === width, `invalid length for ${type}`, 'value', value); - return hexPadRight(value); - }; - } - } - switch (type) { - case 'address': - return function (value) { - return zeroPadValue(getAddress(value), 32); - }; - case 'bool': - return function (value) { - return !value ? hexFalse : hexTrue; - }; - case 'bytes': - return function (value) { - return keccak256(value); - }; - case 'string': - return function (value) { - return id(value); - }; - } - return null; -} -function encodeType(name, fields) { - return `${name}(${fields.map(({ name, type }) => type + ' ' + name).join(',')})`; -} -/** - * A **TypedDataEncode** prepares and encodes [EIP-712](https://eips.ethereum.org/EIPS/eip-712) payloads for signed - * typed data. - * - * This is useful for those that wish to compute various components of a typed data hash, primary types, or - * sub-components, but generally the higher level [`Signer.signTypedData`](../classes/Signer#signTypedData) is more - * useful. - * - * @category Hash - */ -class TypedDataEncoder { - /** - * The primary type for the structured {@link types | **types**}. - * - * This is derived automatically from the {@link types | **types**}, since no recursion is possible, once the DAG for - * the types is consturcted internally, the primary type must be the only remaining type with no parent nodes. - */ - primaryType; - #types; - /** - * The types. - */ - get types() { - return JSON.parse(this.#types); - } - #fullTypes; - #encoderCache; - /** - * Create a new **TypedDataEncoder** for `types`. - * - * This performs all necessary checking that types are valid and do not violate the - * [EIP-712](https://eips.ethereum.org/EIPS/eip-712) structural constraints as well as computes the - * {@link primaryType | **primaryType**}. - */ - constructor(types) { - this.#types = JSON.stringify(types); - this.#fullTypes = new Map(); - this.#encoderCache = new Map(); - // Link struct types to their direct child structs - const links = new Map(); - // Link structs to structs which contain them as a child - const parents = new Map(); - // Link all subtypes within a given struct - const subtypes = new Map(); - Object.keys(types).forEach((type) => { - links.set(type, new Set()); - parents.set(type, []); - subtypes.set(type, new Set()); - }); - for (const name in types) { - const uniqueNames = new Set(); - for (const field of types[name]) { - // Check each field has a unique name - assertArgument(!uniqueNames.has(field.name), `duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, 'types', types); - uniqueNames.add(field.name); - // Get the base type (drop any array specifiers) - const baseType = field.type.match(/^([^\x5b]*)(\x5b|$)/)[1] || null; - assertArgument(baseType !== name, `circular type reference to ${JSON.stringify(baseType)}`, 'types', types); - // Is this a base encoding type? - const encoder = getBaseEncoder(baseType); - if (encoder) { - continue; - } - assertArgument(parents.has(baseType), `unknown type ${JSON.stringify(baseType)}`, 'types', types); - // Add linkage - parents.get(baseType).push(name); - links.get(name).add(baseType); - } - } - // Deduce the primary type - const primaryTypes = Array.from(parents.keys()).filter((n) => parents.get(n).length === 0); - assertArgument(primaryTypes.length !== 0, 'missing primary type', 'types', types); - assertArgument(primaryTypes.length === 1, `ambiguous primary types or unused types: ${primaryTypes.map((t) => JSON.stringify(t)).join(', ')}`, 'types', types); - defineProperties(this, { primaryType: primaryTypes[0] }); - // Check for circular type references - function checkCircular(type, found) { - assertArgument(!found.has(type), `circular type reference to ${JSON.stringify(type)}`, 'types', types); - found.add(type); - for (const child of links.get(type)) { - if (!parents.has(child)) { - continue; - } - // Recursively check children - checkCircular(child, found); - // Mark all ancestors as having this decendant - for (const subtype of found) { - subtypes.get(subtype).add(child); - } - } - found.delete(type); - } - checkCircular(this.primaryType, new Set()); - // Compute each fully describe type - for (const [name, set] of subtypes) { - const st = Array.from(set); - st.sort(); - this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join('')); - } - } - /** - * Returnthe encoder for the specific `type`. - * - * @param {string} type - The type to get the encoder for. - * - * @returns {(value: any) => string} The encoder for the type. - */ - getEncoder(type) { - let encoder = this.#encoderCache.get(type); - if (!encoder) { - encoder = this.#getEncoder(type); - this.#encoderCache.set(type, encoder); - } - return encoder; - } - #getEncoder(type) { - // Basic encoder type (address, bool, uint256, etc) - { - const encoder = getBaseEncoder(type); - if (encoder) { - return encoder; - } - } - // Array - const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); - if (match) { - const subtype = match[1]; - const subEncoder = this.getEncoder(subtype); - return (value) => { - assertArgument(!match[3] || parseInt(match[3]) === value.length, `array length mismatch; expected length ${parseInt(match[3])}`, 'value', value); - let result = value.map(subEncoder); - if (this.#fullTypes.has(subtype)) { - result = result.map(keccak256); - } - return keccak256(concat(result)); - }; - } - // Struct - const fields = this.types[type]; - if (fields) { - const encodedType = id(this.#fullTypes.get(type)); - return (value) => { - const values = fields.map(({ name, type }) => { - const result = this.getEncoder(type)(value[name]); - if (this.#fullTypes.has(type)) { - return keccak256(result); - } - return result; - }); - values.unshift(encodedType); - return concat(values); - }; - } - assertArgument(false, `unknown type: ${type}`, 'type', type); - } - /** - * Return the full type for `name`. - * - * @param {string} name - The name to get the full type for. - * - * @returns {string} The full type. - */ - encodeType(name) { - const result = this.#fullTypes.get(name); - assertArgument(result, `unknown type: ${JSON.stringify(name)}`, 'name', name); - return result; - } - /** - * Return the encoded `value` for the `type`. - * - * @param {string} type - The type to encode the value for. - * @param {any} value - The value to encode. - * - * @returns {string} The encoded value. - */ - encodeData(type, value) { - return this.getEncoder(type)(value); - } - /** - * Returns the hash of `value` for the type of `name`. - * - * @param {string} name - The name of the type. - * @param {Record} value - The value to hash. - * - * @returns {string} The hash of the value. - */ - hashStruct(name, value) { - return keccak256(this.encodeData(name, value)); - } - /** - * Return the fulled encoded `value` for the {@link types | **types**}. - * - * @param {Record} value - The value to encode. - * - * @returns {string} The encoded value. - */ - encode(value) { - return this.encodeData(this.primaryType, value); - } - /** - * Return the hash of the fully encoded `value` for the {@link types | **types**}. - * - * @param {Record} value - The value to hash. - * - * @returns {string} The hash of the value. - */ - hash(value) { - return this.hashStruct(this.primaryType, value); - } - /** - * @ignore - */ - _visit(type, value, callback) { - // Basic encoder type (address, bool, uint256, etc) - { - const encoder = getBaseEncoder(type); - if (encoder) { - return callback(type, value); - } - } - // Array - const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); - if (match) { - assertArgument(!match[3] || parseInt(match[3]) === value.length, `array length mismatch; expected length ${parseInt(match[3])}`, 'value', value); - return value.map((v) => this._visit(match[1], v, callback)); - } - // Struct - const fields = this.types[type]; - if (fields) { - return fields.reduce((accum, { name, type }) => { - accum[name] = this._visit(type, value[name], callback); - return accum; - }, {}); - } - assertArgument(false, `unknown type: ${type}`, 'type', type); - } - /** - * Call `calback` for each value in `value`, passing the type and component within `value`. - * - * This is useful for replacing addresses or other transformation that may be desired on each component, based on - * its type. - * - * @param {Record} value - The value to visit. - * @param {(type: string, data: any) => any} callback - The callback to call for each value. - * - * @returns {any} The result of the callback. - */ - visit(value, callback) { - return this._visit(this.primaryType, value, callback); - } - /** - * Create a new **TypedDataEncoder** for `types`. - * - * @param {Record} types - The types to encode. - * - * @returns {TypedDataEncoder} The encoder for the types. - * @throws {Error} If the types are invalid. - */ - static from(types) { - return new TypedDataEncoder(types); - } - /** - * Return the primary type for `types`. - * - * @param {Record} types - The types to get the primary type for. - * - * @returns {string} The primary type. - * @throws {Error} If the types are invalid. - */ - static getPrimaryType(types) { - return TypedDataEncoder.from(types).primaryType; - } - /** - * Return the hashed struct for `value` using `types` and `name`. - * - * @param {string} name - The name of the type. - * @param {Record} types - The types to hash. - * @param {Record} value - The value to hash. - * - * @returns {string} The hash of the value. - */ - static hashStruct(name, types, value) { - return TypedDataEncoder.from(types).hashStruct(name, value); - } - /** - * Return the domain hash for `domain`. - * - * @param {TypedDataDomain} domain - The domain to hash. - * - * @returns {string} The hash of the domain. - * @throws {Error} If the domain is invalid. - */ - static hashDomain(domain) { - const domainFields = []; - for (const name in domain) { - if (domain[name] == null) { - continue; - } - const type = domainFieldTypes[name]; - assertArgument(type, `invalid typed-data domain key: ${JSON.stringify(name)}`, 'domain', domain); - domainFields.push({ name, type }); - } - domainFields.sort((a, b) => { - return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); - }); - return TypedDataEncoder.hashStruct('EIP712Domain', { EIP712Domain: domainFields }, domain); - } - /** - * Return the fully encoded [EIP-712](https://eips.ethereum.org/EIPS/eip-712) `value` for `types` with `domain`. - * - * @param {TypedDataDomain} domain - The domain to use. - * @param {Record} types - The types to encode. - * @param {Record} value - The value to encode. - * - * @returns {string} The encoded value. - */ - static encode(domain, types, value) { - return concat(['0x1901', TypedDataEncoder.hashDomain(domain), TypedDataEncoder.from(types).hash(value)]); - } - /** - * Return the hash of the fully encoded [EIP-712](https://eips.ethereum.org/EIPS/eip-712) `value` for `types` with - * `domain`. - * - * @param {TypedDataDomain} domain - The domain to use. - * @param {Record} types - The types to hash. - * @param {Record} value - The value to hash. - * - * @returns {string} The hash of the value. - */ - static hash(domain, types, value) { - return keccak256(TypedDataEncoder.encode(domain, types, value)); - } - /** - * Returns the JSON-encoded payload expected by nodes which implement the JSON-RPC - * [EIP-712](https://eips.ethereum.org/EIPS/eip-712) method. - * - * @param {TypedDataDomain} domain - The domain to use. - * @param {Record} types - The types to encode. - * @param {Record} value - The value to encode. - * - * @returns {any} The JSON-encoded payload. - */ - static getPayload(domain, types, value) { - // Validate the domain fields - TypedDataEncoder.hashDomain(domain); - // Derive the EIP712Domain Struct reference type - const domainValues = {}; - const domainTypes = []; - domainFieldNames.forEach((name) => { - const value = domain[name]; - if (value == null) { - return; - } - domainValues[name] = domainChecks[name](value); - domainTypes.push({ name, type: domainFieldTypes[name] }); - }); - const encoder = TypedDataEncoder.from(types); - const typesWithDomain = Object.assign({}, types); - assertArgument(typesWithDomain.EIP712Domain == null, 'types must not contain EIP712Domain type', 'types.EIP712Domain', types); - typesWithDomain.EIP712Domain = domainTypes; - // Validate the data structures and types - encoder.encode(value); - return { - types: typesWithDomain, - domain: domainValues, - primaryType: encoder.primaryType, - message: encoder.visit(value, (type, value) => { - // bytes - if (type.match(/^bytes(\d*)/)) { - return hexlify(getBytes(value)); - } - // uint or int - if (type.match(/^u?int/)) { - return getBigInt(value).toString(); - } - switch (type) { - case 'address': - return value.toLowerCase(); - case 'bool': - return !!value; - case 'string': - assertArgument(typeof value === 'string', 'invalid string', 'value', value); - return value; - } - assertArgument(false, 'unsupported type', 'type', type); - }), - }; - } -} -/** - * Compute the address used to sign the typed data for the `signature`. - * - * @category Hash - * @param {TypedDataDomain} domain - The domain of the typed data. - * @param {Record} types - The types of the typed data. - * @param {Record} value - The value of the typed data. - * @param {SignatureLike} signature - The signature to verify. - * - * @returns {string} The address that signed the typed data. - */ -function verifyTypedData(domain, types, value, signature) { - return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature); -} - -/** - * A fragment is a single item from an ABI, which may represent any of: - * - * - {@link FunctionFragment | Functions} - * - {@link EventFragment | Events} - * - {@link ConstructorFragment | Constructors} - * - Custom {@link ErrorFragment | Errors} - * - {@link FallbackFragment | Fallback or Recieve} functions - * - * @category Application Binary Interface - */ -// [ "a", "b" ] => { "a": 1, "b": 1 } -function setify(items) { - const result = new Set(); - items.forEach((k) => result.add(k)); - return Object.freeze(result); -} -const _kwVisibDeploy = 'external public payable'; -const KwVisibDeploy = setify(_kwVisibDeploy.split(' ')); -// Visibility Keywords -const _kwVisib = 'constant external internal payable private public pure view'; -const KwVisib = setify(_kwVisib.split(' ')); -const _kwTypes = 'constructor error event fallback function receive struct'; -const KwTypes = setify(_kwTypes.split(' ')); -const _kwModifiers = 'calldata memory storage payable indexed'; -const KwModifiers = setify(_kwModifiers.split(' ')); -const _kwOther = 'tuple returns'; -// All Keywords -const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(' '); -const Keywords = setify(_keywords.split(' ')); -// Single character tokens -const SimpleTokens = { - '(': 'OPEN_PAREN', - ')': 'CLOSE_PAREN', - '[': 'OPEN_BRACKET', - ']': 'CLOSE_BRACKET', - ',': 'COMMA', - '@': 'AT', -}; -// Parser regexes to consume the next token -const regexWhitespacePrefix = new RegExp('^(\\s*)'); -const regexNumberPrefix = new RegExp('^([0-9]+)'); -const regexIdPrefix = new RegExp('^([a-zA-Z$_][a-zA-Z0-9$_]*)'); -// Parser regexs to check validity -const regexId = new RegExp('^([a-zA-Z$_][a-zA-Z0-9$_]*)$'); -const regexType = new RegExp('^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$'); -/** - * Represents a parsed list of tokens. - * - * @category Application Binary Interface - */ -class TokenString { - #offset; - #tokens; - get offset() { - return this.#offset; - } - get length() { - return this.#tokens.length - this.#offset; - } - constructor(tokens) { - this.#offset = 0; - this.#tokens = tokens.slice(); - } - /** - * Returns a clone of the current token string. - * - * @returns {TokenString} A cloned TokenString object. - */ - clone() { - return new TokenString(this.#tokens); - } - reset() { - this.#offset = 0; - } - /** - * @ignore - */ - #subTokenString(from = 0, to = 0) { - return new TokenString(this.#tokens.slice(from, to).map((t) => { - return Object.freeze(Object.assign({}, t, { - match: t.match - from, - linkBack: t.linkBack - from, - linkNext: t.linkNext - from, - })); - })); - } - // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens - popKeyword(allowed) { - const top = this.peek(); - if (top.type !== 'KEYWORD' || !allowed.has(top.text)) { - throw new Error(`expected keyword ${top.text}`); - } - return this.pop().text; - } - // Pops and returns the value of the next token if it is `type`; throws if out of tokens - popType(type) { - if (this.peek().type !== type) { - throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`); - } - return this.pop().text; - } - // Pops and returns a "(" TOKENS ")" - popParen() { - const top = this.peek(); - if (top.type !== 'OPEN_PAREN') { - throw new Error('bad start'); - } - const result = this.#subTokenString(this.#offset + 1, top.match + 1); - this.#offset = top.match + 1; - return result; - } - // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")" - popParams() { - const top = this.peek(); - if (top.type !== 'OPEN_PAREN') { - throw new Error('bad start'); - } - const result = []; - while (this.#offset < top.match - 1) { - const link = this.peek().linkNext; - result.push(this.#subTokenString(this.#offset + 1, link)); - this.#offset = link; - } - this.#offset = top.match + 1; - return result; - } - // Returns the top Token, throwing if out of tokens - peek() { - if (this.#offset >= this.#tokens.length) { - throw new Error('out-of-bounds'); - } - return this.#tokens[this.#offset]; - } - // Returns the next value, if it is a keyword in `allowed` - peekKeyword(allowed) { - const top = this.peekType('KEYWORD'); - return top != null && allowed.has(top) ? top : null; - } - // Returns the value of the next token if it is `type` - peekType(type) { - if (this.length === 0) { - return null; - } - const top = this.peek(); - return top.type === type ? top.text : null; - } - // Returns the next token; throws if out of tokens - pop() { - const result = this.peek(); - this.#offset++; - return result; - } - toString() { - const tokens = []; - for (let i = this.#offset; i < this.#tokens.length; i++) { - const token = this.#tokens[i]; - tokens.push(`${token.type}:${token.text}`); - } - return ``; - } -} -function lex(text) { - const tokens = []; - const throwError = (message) => { - const token = offset < text.length ? JSON.stringify(text[offset]) : '$EOI'; - throw new Error(`invalid token ${token} at ${offset}: ${message}`); - }; - const brackets = []; - const commas = []; - let offset = 0; - while (offset < text.length) { - // Strip off any leading whitespace - let cur = text.substring(offset); - let match = cur.match(regexWhitespacePrefix); - if (match) { - offset += match[1].length; - cur = text.substring(offset); - } - const token = { - depth: brackets.length, - linkBack: -1, - linkNext: -1, - match: -1, - type: '', - text: '', - offset, - value: -1, - }; - tokens.push(token); - const type = SimpleTokens[cur[0]] || ''; - if (type) { - token.type = type; - token.text = cur[0]; - offset++; - if (type === 'OPEN_PAREN') { - brackets.push(tokens.length - 1); - commas.push(tokens.length - 1); - } - else if (type == 'CLOSE_PAREN') { - if (brackets.length === 0) { - throwError('no matching open bracket'); - } - token.match = brackets.pop(); - tokens[token.match].match = tokens.length - 1; - token.depth--; - token.linkBack = commas.pop(); - tokens[token.linkBack].linkNext = tokens.length - 1; - } - else if (type === 'COMMA') { - token.linkBack = commas.pop(); - tokens[token.linkBack].linkNext = tokens.length - 1; - commas.push(tokens.length - 1); - } - else if (type === 'OPEN_BRACKET') { - token.type = 'BRACKET'; - } - else if (type === 'CLOSE_BRACKET') { - // Remove the CLOSE_BRACKET - let suffix = tokens.pop().text; - if (tokens.length > 0 && tokens[tokens.length - 1].type === 'NUMBER') { - const value = tokens.pop().text; - suffix = value + suffix; - tokens[tokens.length - 1].value = getNumber(value); - } - if (tokens.length === 0 || tokens[tokens.length - 1].type !== 'BRACKET') { - throw new Error('missing opening bracket'); - } - tokens[tokens.length - 1].text += suffix; - } - continue; - } - match = cur.match(regexIdPrefix); - if (match) { - token.text = match[1]; - offset += token.text.length; - if (Keywords.has(token.text)) { - token.type = 'KEYWORD'; - continue; - } - if (token.text.match(regexType)) { - token.type = 'TYPE'; - continue; - } - token.type = 'ID'; - continue; - } - match = cur.match(regexNumberPrefix); - if (match) { - token.text = match[1]; - token.type = 'NUMBER'; - offset += token.text.length; - continue; - } - throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`); - } - return new TokenString(tokens.map((t) => Object.freeze(t))); -} -// Check only one of `allowed` is in `set` -function allowSingle(set, allowed) { - const included = []; - for (const key in allowed.keys()) { - if (set.has(key)) { - included.push(key); - } - } - if (included.length > 1) { - throw new Error(`conflicting types: ${included.join(', ')}`); - } -} -// Functions to process a Solidity Signature TokenString from left-to-right for... -// ...the name with an optional type, returning the name -function consumeName(type, tokens) { - if (tokens.peekKeyword(KwTypes)) { - const keyword = tokens.pop().text; - if (keyword !== type) { - throw new Error(`expected ${type}, got ${keyword}`); - } - } - return tokens.popType('ID'); -} -// ...all keywords matching allowed, returning the keywords -function consumeKeywords(tokens, allowed) { - const keywords = new Set(); - // eslint-disable-next-line no-constant-condition - while (true) { - const keyword = tokens.peekType('KEYWORD'); - if (keyword == null || (allowed && !allowed.has(keyword))) { - break; - } - tokens.pop(); - if (keywords.has(keyword)) { - throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`); - } - keywords.add(keyword); - } - return Object.freeze(keywords); -} -// ...all visibility keywords, returning the coalesced mutability -function consumeMutability(tokens) { - const modifiers = consumeKeywords(tokens, KwVisib); - // Detect conflicting modifiers - allowSingle(modifiers, setify('constant payable nonpayable'.split(' '))); - allowSingle(modifiers, setify('pure view payable nonpayable'.split(' '))); - // Process mutability states - if (modifiers.has('view')) { - return 'view'; - } - if (modifiers.has('pure')) { - return 'pure'; - } - if (modifiers.has('payable')) { - return 'payable'; - } - if (modifiers.has('nonpayable')) { - return 'nonpayable'; - } - // Process legacy `constant` last - if (modifiers.has('constant')) { - return 'view'; - } - return 'nonpayable'; -} -// ...a parameter list, returning the ParamType list -function consumeParams(tokens, allowIndexed) { - return tokens.popParams().map((t) => ParamType.from(t, allowIndexed)); -} -// ...a gas limit, returning a BigNumber or null if none -function consumeGas(tokens) { - if (tokens.peekType('AT')) { - tokens.pop(); - if (tokens.peekType('NUMBER')) { - return getBigInt(tokens.pop().text); - } - throw new Error('invalid gas'); - } - return null; -} -function consumeEoi(tokens) { - if (tokens.length) { - throw new Error(`unexpected tokens: ${tokens.toString()}`); - } -} -const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/); -function verifyBasicType(type) { - const match = type.match(regexType); - assertArgument(match, 'invalid type', 'type', type); - if (type === 'uint') { - return 'uint256'; - } - if (type === 'int') { - return 'int256'; - } - if (match[2]) { - // bytesXX - const length = parseInt(match[2]); - assertArgument(length !== 0 && length <= 32, 'invalid bytes length', 'type', type); - } - else if (match[3]) { - // intXX or uintXX - const size = parseInt(match[3]); - assertArgument(size !== 0 && size <= 256 && size % 8 === 0, 'invalid numeric width', 'type', type); - } - return type; -} -// Make the Fragment constructors effectively private -const _guard$3 = {}; -const internal$1 = Symbol.for('_quais_internal'); -const ParamTypeInternal = '_ParamTypeInternal'; -const ErrorFragmentInternal = '_ErrorInternal'; -const EventFragmentInternal = '_EventInternal'; -const ConstructorFragmentInternal = '_ConstructorInternal'; -const FallbackFragmentInternal = '_FallbackInternal'; -const FunctionFragmentInternal = '_FunctionInternal'; -const StructFragmentInternal = '_StructInternal'; -/** - * Each input and output of a {@link Fragment | **Fragment**} is an Array of {@link ParamType | **ParamType**}. - * - * @category Application Binary Interface - */ -class ParamType { - /** - * The local name of the parameter (or `""` if unbound) - */ - name; - /** - * The fully qualified type (e.g. `"address"`, `"tuple(address)"`, `"uint256[3][]"`) - */ - type; - /** - * The base type (e.g. `"address"`, `"tuple"`, `"array"`) - */ - baseType; - /** - * True if the parameters is indexed. - * - * For non-indexable types this is `null`. - */ - indexed; - /** - * The components for the tuple. - * - * For non-tuple types this is `null`. - */ - components; - /** - * The array length, or `-1` for dynamic-lengthed arrays. - * - * For non-array types this is `null`. - */ - arrayLength; - /** - * The type of each child in the array. - * - * For non-array types this is `null`. - */ - arrayChildren; - /** - * @ignore - */ - constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren) { - assertPrivate(guard, _guard$3, 'ParamType'); - Object.defineProperty(this, internal$1, { value: ParamTypeInternal }); - if (components) { - components = Object.freeze(components.slice()); - } - if (baseType === 'array') { - if (arrayLength == null || arrayChildren == null) { - throw new Error(''); - } - } - else if (arrayLength != null || arrayChildren != null) { - throw new Error(''); - } - if (baseType === 'tuple') { - if (components == null) { - throw new Error(''); - } - } - else if (components != null) { - throw new Error(''); - } - defineProperties(this, { - name, - type, - baseType, - indexed, - components, - arrayLength, - arrayChildren, - }); - } - /** - * Return a string representation of this type. - * - * For example, - * - * `sighash" => "(uint256,address)"` - * - * `"minimal" => "tuple(uint256,address) indexed"` - * - * `"full" => "tuple(uint256 foo, address bar) indexed baz"` - * - * @returns {string} The formatted type. - */ - format(format) { - if (format == null) { - format = 'sighash'; - } - if (format === 'json') { - const name = this.name || ''; - if (this.isArray()) { - const result = JSON.parse(this.arrayChildren.format('json')); - result.name = name; - result.type += `[${this.arrayLength < 0 ? '' : String(this.arrayLength)}]`; - return JSON.stringify(result); - } - const result = { - type: this.baseType === 'tuple' ? 'tuple' : this.type, - name, - }; - if (typeof this.indexed === 'boolean') { - result.indexed = this.indexed; - } - if (this.isTuple()) { - result.components = this.components.map((c) => JSON.parse(c.format(format))); - } - return JSON.stringify(result); - } - let result = ''; - // Array - if (this.isArray()) { - result += this.arrayChildren.format(format); - result += `[${this.arrayLength < 0 ? '' : String(this.arrayLength)}]`; - } - else { - if (this.isTuple()) { - result += - '(' + this.components.map((comp) => comp.format(format)).join(format === 'full' ? ', ' : ',') + ')'; - } - else { - result += this.type; - } - } - if (format !== 'sighash') { - if (this.indexed === true) { - result += ' indexed'; - } - if (format === 'full' && this.name) { - result += ' ' + this.name; - } - } - return result; - } - /** - * This provides a type guard ensuring that {@link arrayChildren | **arrayChildren**} and - * {@link arrayLength | **arrayLength**} are non-null. - * - * @returns {boolean} True if this is an Array type. - */ - isArray() { - return this.baseType === 'array'; - } - /** - * This provides a type guard ensuring that {@link components | **components**} is non-null. - * - * @returns {boolean} True if this is a Tuple type. - */ - isTuple() { - return this.baseType === 'tuple'; - } - /** - * This provides a type guard ensuring that {@link indexed | **indexed**} is non-null. - * - * @returns {boolean} True if this is an Indexable type. - */ - isIndexable() { - return this.indexed != null; - } - /** - * Walks the **ParamType** with `value`, calling `process` on each type, destructing the `value` recursively. - */ - walk(value, process) { - if (this.isArray()) { - if (!Array.isArray(value)) { - throw new Error('invalid array value'); - } - if (this.arrayLength !== -1 && value.length !== this.arrayLength) { - throw new Error('array is wrong length'); - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - const _this = this; - return value.map((v) => _this.arrayChildren.walk(v, process)); - } - if (this.isTuple()) { - if (!Array.isArray(value)) { - throw new Error('invalid tuple value'); - } - if (value.length !== this.components.length) { - throw new Error('array is wrong length'); - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - const _this = this; - return value.map((v, i) => _this.components[i].walk(v, process)); - } - return process(this.type, value); - } - /** - * @ignore - */ - #walkAsync(promises, value, process, setValue) { - if (this.isArray()) { - if (!Array.isArray(value)) { - throw new Error('invalid array value'); - } - if (this.arrayLength !== -1 && value.length !== this.arrayLength) { - throw new Error('array is wrong length'); - } - const childType = this.arrayChildren; - const result = value.slice(); - result.forEach((value, index) => { - childType.#walkAsync(promises, value, process, (value) => { - result[index] = value; - }); - }); - setValue(result); - return; - } - if (this.isTuple()) { - const components = this.components; - // Convert the object into an array - let result; - if (Array.isArray(value)) { - result = value.slice(); - } - else { - if (value == null || typeof value !== 'object') { - throw new Error('invalid tuple value'); - } - result = components.map((param) => { - if (!param.name) { - throw new Error('cannot use object value with unnamed components'); - } - if (!(param.name in value)) { - throw new Error(`missing value for component ${param.name}`); - } - return value[param.name]; - }); - } - if (result.length !== this.components.length) { - throw new Error('array is wrong length'); - } - result.forEach((value, index) => { - components[index].#walkAsync(promises, value, process, (value) => { - result[index] = value; - }); - }); - setValue(result); - return; - } - const result = process(this.type, value); - if (result.then) { - promises.push((async function () { - setValue(await result); - })()); - } - else { - setValue(result); - } - } - /** - * Walks the **ParamType** with `value`, asynchronously calling `process` on each type, destructing the `value` - * recursively. - * - * This can be used to resolve ENS naes by walking and resolving each `"address"` type. - */ - async walkAsync(value, process) { - const promises = []; - const result = [value]; - this.#walkAsync(promises, value, process, (value) => { - result[0] = value; - }); - if (promises.length) { - await Promise.all(promises); - } - return result[0]; - } - /** - * Creates a new **ParamType** for `obj`. - * - * If `allowIndexed` then the `indexed` keyword is permitted, otherwise the `indexed` keyword will throw an error. - */ - static from(obj, allowIndexed) { - if (ParamType.isParamType(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return ParamType.from(lex(obj), allowIndexed); - } - catch (error) { - assertArgument(false, 'invalid param type', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - let type = '', baseType = ''; - let comps = null; - if (consumeKeywords(obj, setify(['tuple'])).has('tuple') || obj.peekType('OPEN_PAREN')) { - // Tuple - baseType = 'tuple'; - comps = obj.popParams().map((t) => ParamType.from(t)); - type = `tuple(${comps.map((c) => c.format()).join(',')})`; - } - else { - // Normal - type = verifyBasicType(obj.popType('TYPE')); - baseType = type; - } - // Check for Array - let arrayChildren = null; - let arrayLength = null; - while (obj.length && obj.peekType('BRACKET')) { - const bracket = obj.pop(); //arrays[i]; - arrayChildren = new ParamType(_guard$3, '', type, baseType, null, comps, arrayLength, arrayChildren); - arrayLength = bracket.value; - type += bracket.text; - baseType = 'array'; - comps = null; - } - let indexed = null; - const keywords = consumeKeywords(obj, KwModifiers); - if (keywords.has('indexed')) { - if (!allowIndexed) { - throw new Error(''); - } - indexed = true; - } - const name = obj.peekType('ID') ? obj.pop().text : ''; - if (obj.length) { - throw new Error('leftover tokens'); - } - return new ParamType(_guard$3, name, type, baseType, indexed, comps, arrayLength, arrayChildren); - } - const name = obj.name; - assertArgument(!name || (typeof name === 'string' && name.match(regexId)), 'invalid name', 'obj.name', name); - let indexed = obj.indexed; - if (indexed != null) { - assertArgument(allowIndexed, 'parameter cannot be indexed', 'obj.indexed', obj.indexed); - indexed = !!indexed; - } - let type = obj.type; - const arrayMatch = type.match(regexArrayType); - if (arrayMatch) { - const arrayLength = parseInt(arrayMatch[2] || '-1'); - const arrayChildren = ParamType.from({ - type: arrayMatch[1], - components: obj.components, - }); - return new ParamType(_guard$3, name || '', type, 'array', indexed, null, arrayLength, arrayChildren); - } - if (type === 'tuple' || type.startsWith('tuple(' /* fix: ) */) || type.startsWith('(' /* fix: ) */)) { - const comps = obj.components != null ? obj.components.map((c) => ParamType.from(c)) : null; - const tuple = new ParamType(_guard$3, name || '', type, 'tuple', indexed, comps, null, null); - // @TODO: use lexer to validate and normalize type - return tuple; - } - type = verifyBasicType(obj.type); - return new ParamType(_guard$3, name || '', type, type, indexed, null, null, null); - } - /** - * Returns true if `value` is a **ParamType**. - */ - static isParamType(value) { - return value && value[internal$1] === ParamTypeInternal; - } -} -/** - * An abstract class to represent An individual fragment from a parse ABI. - * - * @category Application Binary Interface - */ -class Fragment { - /** - * The type of the fragment. - */ - type; - /** - * The inputs for the fragment. - */ - inputs; - /** - * @ignore - */ - constructor(guard, type, inputs) { - assertPrivate(guard, _guard$3, 'Fragment'); - inputs = Object.freeze(inputs.slice()); - defineProperties(this, { type, inputs }); - } - /** - * Creates a new **Fragment** for `obj`, wich can be any supported ABI frgament type. - */ - static from(obj) { - if (typeof obj === 'string') { - // Try parsing JSON... - try { - Fragment.from(JSON.parse(obj)); - // eslint-disable-next-line no-empty - } - catch (e) { } - // ...otherwise, use the human-readable lexer - return Fragment.from(lex(obj)); - } - if (obj instanceof TokenString) { - // Human-readable ABI (already lexed) - const type = obj.peekKeyword(KwTypes); - switch (type) { - case 'constructor': - return ConstructorFragment.from(obj); - case 'error': - return ErrorFragment.from(obj); - case 'event': - return EventFragment.from(obj); - case 'fallback': - case 'receive': - return FallbackFragment.from(obj); - case 'function': - return FunctionFragment.from(obj); - case 'struct': - return StructFragment.from(obj); - } - } - else if (typeof obj === 'object') { - // JSON ABI - switch (obj.type) { - case 'constructor': - return ConstructorFragment.from(obj); - case 'error': - return ErrorFragment.from(obj); - case 'event': - return EventFragment.from(obj); - case 'fallback': - case 'receive': - return FallbackFragment.from(obj); - case 'function': - return FunctionFragment.from(obj); - case 'struct': - return StructFragment.from(obj); - } - assert(false, `unsupported type: ${obj.type}`, 'UNSUPPORTED_OPERATION', { - operation: 'Fragment.from', - }); - } - assertArgument(false, 'unsupported frgament object', 'obj', obj); - } - /** - * Returns true if `value` is a {@link ConstructorFragment | **ConstructorFragment**}. - */ - static isConstructor(value) { - return ConstructorFragment.isFragment(value); - } - /** - * Returns true if `value` is an {@link ErrorFragment | **ErrorFragment**}. - */ - static isError(value) { - return ErrorFragment.isFragment(value); - } - /** - * Returns true if `value` is an {@link EventFragment | **EventFragment**}. - */ - static isEvent(value) { - return EventFragment.isFragment(value); - } - /** - * Returns true if `value` is a {@link FunctionFragment | **FunctionFragment**}. - */ - static isFunction(value) { - return FunctionFragment.isFragment(value); - } - /** - * Returns true if `value` is a {@link StructFragment | **StructFragment**}. - */ - static isStruct(value) { - return StructFragment.isFragment(value); - } -} -/** - * An abstract class to represent An individual fragment which has a name from a parse ABI. - * - * @category Application Binary Interface - */ -class NamedFragment extends Fragment { - /** - * The name of the fragment. - */ - name; - /** - * @ignore - */ - constructor(guard, type, name, inputs) { - super(guard, type, inputs); - assertArgument(typeof name === 'string' && name.match(regexId), 'invalid identifier', 'name', name); - inputs = Object.freeze(inputs.slice()); - defineProperties(this, { name }); - } -} -function joinParams(format, params) { - return '(' + params.map((p) => p.format(format)).join(format === 'full' ? ', ' : ',') + ')'; -} -/** - * A Fragment which represents a _Custom Error_. - * - * @category Application Binary Interface - */ -class ErrorFragment extends NamedFragment { - /** - * @ignore - */ - constructor(guard, name, inputs) { - super(guard, 'error', name, inputs); - Object.defineProperty(this, internal$1, { value: ErrorFragmentInternal }); - } - /** - * The Custom Error selector. - */ - get selector() { - return id(this.format('sighash')).substring(0, 10); - } - /** - * Returns a string representation of this fragment as `format`. - */ - format(format) { - if (format == null) { - format = 'sighash'; - } - if (format === 'json') { - return JSON.stringify({ - type: 'error', - name: this.name, - inputs: this.inputs.map((input) => JSON.parse(input.format(format))), - }); - } - const result = []; - if (format !== 'sighash') { - result.push('error'); - } - result.push(this.name + joinParams(format, this.inputs)); - return result.join(' '); - } - /** - * Returns a new **ErrorFragment** for `obj`. - */ - static from(obj) { - if (ErrorFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - return ErrorFragment.from(lex(obj)); - } - else if (obj instanceof TokenString) { - const name = consumeName('error', obj); - const inputs = consumeParams(obj); - consumeEoi(obj); - return new ErrorFragment(_guard$3, name, inputs); - } - return new ErrorFragment(_guard$3, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); - } - /** - * Returns `true` and provides a type guard if `value` is an **ErrorFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === ErrorFragmentInternal; - } -} -/** - * A Fragment which represents an Event. - * - * @category Application Binary Interface - */ -class EventFragment extends NamedFragment { - /** - * Whether this event is anonymous. - */ - anonymous; - /** - * @ignore - */ - constructor(guard, name, inputs, anonymous) { - super(guard, 'event', name, inputs); - Object.defineProperty(this, internal$1, { value: EventFragmentInternal }); - defineProperties(this, { anonymous }); - } - /** - * The Event topic hash. - */ - get topicHash() { - return id(this.format('sighash')); - } - /** - * Returns a string representation of this event as `format`. - */ - format(format) { - if (format == null) { - format = 'sighash'; - } - if (format === 'json') { - return JSON.stringify({ - type: 'event', - anonymous: this.anonymous, - name: this.name, - inputs: this.inputs.map((i) => JSON.parse(i.format(format))), - }); - } - const result = []; - if (format !== 'sighash') { - result.push('event'); - } - result.push(this.name + joinParams(format, this.inputs)); - if (format !== 'sighash' && this.anonymous) { - result.push('anonymous'); - } - return result.join(' '); - } - /** - * Return the topic hash for an event with `name` and `params`. - */ - static getTopicHash(name, params) { - params = (params || []).map((p) => ParamType.from(p)); - const fragment = new EventFragment(_guard$3, name, params, false); - return fragment.topicHash; - } - /** - * Returns a new **EventFragment** for `obj`. - */ - static from(obj) { - if (EventFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return EventFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid event fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - const name = consumeName('event', obj); - const inputs = consumeParams(obj, true); - const anonymous = !!consumeKeywords(obj, setify(['anonymous'])).has('anonymous'); - consumeEoi(obj); - return new EventFragment(_guard$3, name, inputs, anonymous); - } - return new EventFragment(_guard$3, obj.name, obj.inputs ? obj.inputs.map((p) => ParamType.from(p, true)) : [], !!obj.anonymous); - } - /** - * Returns `true` and provides a type guard if `value` is an **EventFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === EventFragmentInternal; - } -} -/** - * A Fragment which represents a constructor. - * - * @category Application Binary Interface - */ -class ConstructorFragment extends Fragment { - /** - * Whether the constructor can receive an endowment. - */ - payable; - /** - * The recommended gas limit for deployment or `null`. - */ - gas; - /** - * @ignore - */ - constructor(guard, type, inputs, payable, gas) { - super(guard, type, inputs); - Object.defineProperty(this, internal$1, { value: ConstructorFragmentInternal }); - defineProperties(this, { payable, gas }); - } - /** - * Returns a string representation of this constructor as `format`. - */ - format(format) { - assert(format != null && format !== 'sighash', 'cannot format a constructor for sighash', 'UNSUPPORTED_OPERATION', { operation: 'format(sighash)' }); - if (format === 'json') { - return JSON.stringify({ - type: 'constructor', - stateMutability: this.payable ? 'payable' : 'undefined', - payable: this.payable, - gas: this.gas != null ? this.gas : undefined, - inputs: this.inputs.map((i) => JSON.parse(i.format(format))), - }); - } - const result = [`constructor${joinParams(format, this.inputs)}`]; - if (this.payable) { - result.push('payable'); - } - if (this.gas != null) { - result.push(`@${this.gas.toString()}`); - } - return result.join(' '); - } - /** - * Returns a new **ConstructorFragment** for `obj`. - */ - static from(obj) { - if (ConstructorFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return ConstructorFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid constuctor fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - consumeKeywords(obj, setify(['constructor'])); - const inputs = consumeParams(obj); - const payable = !!consumeKeywords(obj, KwVisibDeploy).has('payable'); - const gas = consumeGas(obj); - consumeEoi(obj); - return new ConstructorFragment(_guard$3, 'constructor', inputs, payable, gas); - } - return new ConstructorFragment(_guard$3, 'constructor', obj.inputs ? obj.inputs.map(ParamType.from) : [], !!obj.payable, obj.gas != null ? obj.gas : null); - } - /** - * Returns `true` and provides a type guard if `value` is a **ConstructorFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === ConstructorFragmentInternal; - } -} -/** - * A Fragment which represents a method. - * - * @category Application Binary Interface - */ -class FallbackFragment extends Fragment { - /** - * If the function can be sent value during invocation. - */ - payable; - constructor(guard, inputs, payable) { - super(guard, 'fallback', inputs); - Object.defineProperty(this, internal$1, { value: FallbackFragmentInternal }); - defineProperties(this, { payable }); - } - /** - * Returns a string representation of this fallback as `format`. - */ - format(format) { - const type = this.inputs.length === 0 ? 'receive' : 'fallback'; - if (format === 'json') { - const stateMutability = this.payable ? 'payable' : 'nonpayable'; - return JSON.stringify({ type, stateMutability }); - } - return `${type}()${this.payable ? ' payable' : ''}`; - } - /** - * Returns a new **FallbackFragment** for `obj`. - */ - static from(obj) { - if (FallbackFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return FallbackFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid fallback fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - const errorObj = obj.toString(); - const topIsValid = obj.peekKeyword(setify(['fallback', 'receive'])); - assertArgument(topIsValid, 'type must be fallback or receive', 'obj', errorObj); - const type = obj.popKeyword(setify(['fallback', 'receive'])); - // receive() - if (type === 'receive') { - const inputs = consumeParams(obj); - assertArgument(inputs.length === 0, `receive cannot have arguments`, 'obj.inputs', inputs); - consumeKeywords(obj, setify(['payable'])); - consumeEoi(obj); - return new FallbackFragment(_guard$3, [], true); - } - // fallback() [payable] - // fallback(bytes) [payable] returns (bytes) - let inputs = consumeParams(obj); - if (inputs.length) { - assertArgument(inputs.length === 1 && inputs[0].type === 'bytes', 'invalid fallback inputs', 'obj.inputs', inputs.map((i) => i.format('minimal')).join(', ')); - } - else { - inputs = [ParamType.from('bytes')]; - } - const mutability = consumeMutability(obj); - assertArgument(mutability === 'nonpayable' || mutability === 'payable', 'fallback cannot be constants', 'obj.stateMutability', mutability); - if (consumeKeywords(obj, setify(['returns'])).has('returns')) { - const outputs = consumeParams(obj); - assertArgument(outputs.length === 1 && outputs[0].type === 'bytes', 'invalid fallback outputs', 'obj.outputs', outputs.map((i) => i.format('minimal')).join(', ')); - } - consumeEoi(obj); - return new FallbackFragment(_guard$3, inputs, mutability === 'payable'); - } - if (obj.type === 'receive') { - return new FallbackFragment(_guard$3, [], true); - } - if (obj.type === 'fallback') { - const inputs = [ParamType.from('bytes')]; - const payable = obj.stateMutability === 'payable'; - return new FallbackFragment(_guard$3, inputs, payable); - } - assertArgument(false, 'invalid fallback description', 'obj', obj); - } - /** - * Returns `true` and provides a type guard if `value` is a **FallbackFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === FallbackFragmentInternal; - } -} -/** - * A Fragment which represents a method. - * - * @category Application Binary Interface - */ -class FunctionFragment extends NamedFragment { - /** - * If the function is constant (e.g. `pure` or `view` functions). - */ - constant; - /** - * The returned types for the result of calling this function. - */ - outputs; - /** - * The state mutability (e.g. `payable`, `nonpayable`, `view` or `pure`) - */ - stateMutability; - /** - * If the function can be sent value during invocation. - */ - payable; - /** - * The recommended gas limit to send when calling this function. - */ - gas; - /** - * @ignore - */ - constructor(guard, name, stateMutability, inputs, outputs, gas) { - super(guard, 'function', name, inputs); - Object.defineProperty(this, internal$1, { value: FunctionFragmentInternal }); - outputs = Object.freeze(outputs.slice()); - const constant = stateMutability === 'view' || stateMutability === 'pure'; - const payable = stateMutability === 'payable'; - defineProperties(this, { constant, gas, outputs, payable, stateMutability }); - } - /** - * The Function selector. - */ - get selector() { - return id(this.format('sighash')).substring(0, 10); - } - /** - * Returns a string representation of this function as `format`. - */ - format(format) { - if (format == null) { - format = 'sighash'; - } - if (format === 'json') { - return JSON.stringify({ - type: 'function', - name: this.name, - constant: this.constant, - stateMutability: this.stateMutability !== 'nonpayable' ? this.stateMutability : undefined, - payable: this.payable, - gas: this.gas != null ? this.gas : undefined, - inputs: this.inputs.map((i) => JSON.parse(i.format(format))), - outputs: this.outputs.map((o) => JSON.parse(o.format(format))), - }); - } - const result = []; - if (format !== 'sighash') { - result.push('function'); - } - result.push(this.name + joinParams(format, this.inputs)); - if (format !== 'sighash') { - if (this.stateMutability !== 'nonpayable') { - result.push(this.stateMutability); - } - if (this.outputs && this.outputs.length) { - result.push('returns'); - result.push(joinParams(format, this.outputs)); - } - if (this.gas != null) { - result.push(`@${this.gas.toString()}`); - } - } - return result.join(' '); - } - /** - * Return the selector for a function with `name` and `params`. - */ - static getSelector(name, params) { - params = (params || []).map((p) => ParamType.from(p)); - const fragment = new FunctionFragment(_guard$3, name, 'view', params, [], null); - return fragment.selector; - } - /** - * Returns a new **FunctionFragment** for `obj`. - */ - static from(obj) { - if (FunctionFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return FunctionFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid function fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - const name = consumeName('function', obj); - const inputs = consumeParams(obj); - const mutability = consumeMutability(obj); - let outputs = []; - if (consumeKeywords(obj, setify(['returns'])).has('returns')) { - outputs = consumeParams(obj); - } - const gas = consumeGas(obj); - consumeEoi(obj); - return new FunctionFragment(_guard$3, name, mutability, inputs, outputs, gas); - } - let stateMutability = obj.stateMutability; - // Use legacy Solidity ABI logic if stateMutability is missing - if (stateMutability == null) { - stateMutability = 'payable'; - if (typeof obj.constant === 'boolean') { - stateMutability = 'view'; - if (!obj.constant) { - stateMutability = 'payable'; - if (typeof obj.payable === 'boolean' && !obj.payable) { - stateMutability = 'nonpayable'; - } - } - } - else if (typeof obj.payable === 'boolean' && !obj.payable) { - stateMutability = 'nonpayable'; - } - } - // @TODO: verifyState for stateMutability (e.g. throw if - // payable: false but stateMutability is "nonpayable") - return new FunctionFragment(_guard$3, obj.name, stateMutability, obj.inputs ? obj.inputs.map(ParamType.from) : [], obj.outputs ? obj.outputs.map(ParamType.from) : [], obj.gas != null ? obj.gas : null); - } - /** - * Returns `true` and provides a type guard if `value` is a **FunctionFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === FunctionFragmentInternal; - } -} -/** - * A Fragment which represents a structure. - * - * @category Application Binary Interface - */ -class StructFragment extends NamedFragment { - /** - * @ignore - */ - constructor(guard, name, inputs) { - super(guard, 'struct', name, inputs); - Object.defineProperty(this, internal$1, { value: StructFragmentInternal }); - } - /** - * Returns a string representation of this struct as `format`. - */ - format() { - throw new Error('@TODO'); - } - /** - * Returns a new **StructFragment** for `obj`. - */ - static from(obj) { - if (typeof obj === 'string') { - try { - return StructFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid struct fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - const name = consumeName('struct', obj); - const inputs = consumeParams(obj); - consumeEoi(obj); - return new StructFragment(_guard$3, name, inputs); - } - return new StructFragment(_guard$3, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); - } - // @TODO: fix this return type - /** - * Returns `true` and provides a type guard if `value` is a **StructFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === StructFragmentInternal; - } -} - -/** - * When sending values to or receiving values from a [Contract](../classes/Contract), the data is generally encoded - * using the [ABI - * Specification](https://docs.soliditylang.org/en/v0.8.19/abi-spec.html#formal-specification-of-the-encoding). - * - * The AbiCoder provides a utility to encode values to ABI data and decode values from ABI data. - * - * Most of the time, developers should favor the [Contract](../classes/Contract) class, which further abstracts the - * finer details of ABI data. - * - * @category Application Binary Interface - */ -// https://docs.soliditylang.org/en/v0.8.17/control-structures.html -const PanicReasons$1 = new Map(); -PanicReasons$1.set(0x00, 'GENERIC_PANIC'); -PanicReasons$1.set(0x01, 'ASSERT_FALSE'); -PanicReasons$1.set(0x11, 'OVERFLOW'); -PanicReasons$1.set(0x12, 'DIVIDE_BY_ZERO'); -PanicReasons$1.set(0x21, 'ENUM_RANGE_ERROR'); -PanicReasons$1.set(0x22, 'BAD_STORAGE_DATA'); -PanicReasons$1.set(0x31, 'STACK_UNDERFLOW'); -PanicReasons$1.set(0x32, 'ARRAY_RANGE_ERROR'); -PanicReasons$1.set(0x41, 'OUT_OF_MEMORY'); -PanicReasons$1.set(0x51, 'UNINITIALIZED_FUNCTION_CALL'); -const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); -const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); -let defaultCoder = null; -let defaultMaxInflation = 1024; -function getBuiltinCallException(action, tx, data, abiCoder) { - let message = 'missing revert data'; - let reason = null; - const invocation = null; - let revert = null; - if (data) { - message = 'execution reverted'; - const bytes = getBytes(data); - data = hexlify(data); - if (bytes.length === 0) { - message += ' (no data present; likely require(false) occurred'; - reason = 'require(false)'; - } - else if (bytes.length % 32 !== 4) { - message += ' (could not decode reason; invalid data length)'; - } - else if (hexlify(bytes.slice(0, 4)) === '0x08c379a0') { - // Error(string) - try { - reason = abiCoder.decode(['string'], bytes.slice(4))[0]; - revert = { - signature: 'Error(string)', - name: 'Error', - args: [reason], - }; - message += `: ${JSON.stringify(reason)}`; - } - catch (error) { - message += ' (could not decode reason; invalid string data)'; - } - } - else if (hexlify(bytes.slice(0, 4)) === '0x4e487b71') { - // Panic(uint256) - try { - const code = Number(abiCoder.decode(['uint256'], bytes.slice(4))[0]); - revert = { - signature: 'Panic(uint256)', - name: 'Panic', - args: [code], - }; - reason = `Panic due to ${PanicReasons$1.get(code) || 'UNKNOWN'}(${code})`; - message += `: ${reason}`; - } - catch (error) { - message += ' (could not decode panic code)'; - } - } - else { - message += ' (unknown custom error)'; - } - } - const transaction = { - to: tx.to ? getAddress(tx.to) : null, - data: tx.data || '0x', - }; - if (tx.from) { - transaction.from = getAddress(tx.from); - } - return makeError(message, 'CALL_EXCEPTION', { - action, - data, - reason, - transaction, - invocation, - revert, - }); -} -/** - * The **AbiCoder** is a low-level class responsible for encoding JavaScript values into binary data and decoding binary - * data into JavaScript values. - * - * @category Application Binary Interface - */ -class AbiCoder { - #getCoder(param) { - if (param.isArray()) { - return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name); - } - if (param.isTuple()) { - return new TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name); - } - switch (param.baseType) { - case 'address': - return new AddressCoder(param.name); - case 'bool': - return new BooleanCoder(param.name); - case 'string': - return new StringCoder(param.name); - case 'bytes': - return new BytesCoder(param.name); - case '': - return new NullCoder(param.name); - } - // u?int[0-9]* - let match = param.type.match(paramTypeNumber); - if (match) { - const size = parseInt(match[2] || '256'); - assertArgument(size !== 0 && size <= 256 && size % 8 === 0, 'invalid ' + match[1] + ' bit length', 'param', param); - return new NumberCoder(size / 8, match[1] === 'int', param.name); - } - // bytes[0-9]+ - match = param.type.match(paramTypeBytes); - if (match) { - const size = parseInt(match[1]); - assertArgument(size !== 0 && size <= 32, 'invalid bytes length', 'param', param); - return new FixedBytesCoder(size, param.name); - } - assertArgument(false, 'invalid type', 'type', param.type); - } - /** - * Get the default values for the given types. For example, a `uint` is by default `0` and `bool` is by default - * `false`. - * - * @param {(string | ParamType)[]} types - Array of parameter types to get default values for. - * @returns {Result} The default values corresponding to the given types. - */ - getDefaultValue(types) { - const coders = types.map((type) => this.#getCoder(ParamType.from(type))); - const coder = new TupleCoder(coders, '_'); - return coder.defaultValue(); - } - /** - * Encode the values as the specified types into ABI data. - * - * @param {(string | ParamType)[]} types - Array of parameter types. - * @param {any[]} values - Array of values to encode. - * @returns {string} The encoded data in hexadecimal format. - */ - encode(types, values) { - assertArgumentCount(values.length, types.length, 'types/values length mismatch'); - const coders = types.map((type) => this.#getCoder(ParamType.from(type))); - const coder = new TupleCoder(coders, '_'); - const writer = new Writer(); - coder.encode(writer, values); - return writer.data; - } - /** - * Decode the ABI data as the types into values. - * - * If loose decoding is enabled, then strict padding is not enforced. Some older versions of Solidity incorrectly - * padded event data emitted from `external` functions. - * - * @param {(string | ParamType)[]} types - Array of parameter types. - * @param {BytesLike} data - The ABI data to decode. - * @param {boolean} [loose=false] - Enable loose decoding. Default is `false` - * @returns {Result} The decoded values. - */ - decode(types, data, loose) { - const coders = types.map((type) => this.#getCoder(ParamType.from(type))); - const coder = new TupleCoder(coders, '_'); - return coder.decode(new Reader(data, loose, defaultMaxInflation)); - } - /** - * Set the default maximum inflation factor. - * - * @ignore - * @param {number} value - The new inflation factor. - */ - static _setDefaultMaxInflation(value) { - assertArgument(typeof value === 'number' && Number.isInteger(value), 'invalid defaultMaxInflation factor', 'value', value); - defaultMaxInflation = value; - } - /** - * Returns the shared singleton instance of a default {@link AbiCoder | **AbiCoder**}. - * - * On the first call, the instance is created internally. - * - * @returns {AbiCoder} The default ABI coder instance. - */ - static defaultAbiCoder() { - if (defaultCoder == null) { - defaultCoder = new AbiCoder(); - } - return defaultCoder; - } - /** - * Returns a quais-compatible {@link CallExceptionError | **CallExceptionError**} for the given result data. - * - * @param {CallExceptionAction} action - The action that triggered the exception. - * @param {Object} tx - The transaction information. - * @param {BytesLike | null} data - The data associated with the call exception. - * @returns {CallExceptionError} The corresponding call exception error. - */ - static getBuiltinCallException(action, tx, data) { - return getBuiltinCallException(action, tx, data, AbiCoder.defaultAbiCoder()); - } -} - -/** - * The Interface class is a low-level class that accepts an ABI and provides all the necessary functionality to encode - * and decode paramaters to and results from methods, events and errors. - * - * It also provides several convenience methods to automatically search and find matching transactions and events to - * parse them. - * - * @category Application Binary Interface - */ -/** - * When using the {@link Interface.parseLog | **Interface.parseLog**} to automatically match a Log to its event for - * parsing, a **LogDescription** is returned. - * - * @category Application Binary Interface - */ -class LogDescription { - /** - * The matching fragment for the `topic0`. - */ - fragment; - /** - * The name of the Event. - */ - name; - /** - * The full Event signature. - */ - signature; - /** - * The topic hash for the Event. - */ - topic; - /** - * The arguments passed into the Event with `emit`. - */ - args; - /** - * @ignore - */ - constructor(fragment, topic, args) { - const name = fragment.name, signature = fragment.format(); - defineProperties(this, { - fragment, - name, - signature, - topic, - args, - }); - } -} -/** - * When using the {@link Interface.parseTransaction | **Interface.parseTransaction**} to automatically match a - * transaction data to its function for parsing, a **TransactionDescription** is returned. - * - * @category Application Binary Interface - */ -class TransactionDescription { - /** - * The matching fragment from the transaction `data`. - */ - fragment; - /** - * The name of the Function from the transaction `data`. - */ - name; - /** - * The arguments passed to the Function from the transaction `data`. - */ - args; - /** - * The full Function signature from the transaction `data`. - */ - signature; - /** - * The selector for the Function from the transaction `data`. - */ - selector; - /** - * The `value` (in wei) from the transaction. - */ - value; - /** - * @ignore - */ - constructor(fragment, selector, args, value) { - const name = fragment.name, signature = fragment.format(); - defineProperties(this, { - fragment, - name, - args, - signature, - selector, - value, - }); - } -} -/** - * When using the {@link Interface.parseError | **Interface.parseError**} to automatically match an error for a call - * result for parsing, an **ErrorDescription** is returned. - * - * @category Application Binary Interface - */ -class ErrorDescription { - /** - * The matching fragment. - */ - fragment; - /** - * The name of the Error. - */ - name; - /** - * The arguments passed to the Error with `revert`. - */ - args; - /** - * The full Error signature. - */ - signature; - /** - * The selector for the Error. - */ - selector; - /** - * @ignore - */ - constructor(fragment, selector, args) { - const name = fragment.name, signature = fragment.format(); - defineProperties(this, { - fragment, - name, - args, - signature, - selector, - }); - } -} -/** - * An **Indexed** is used as a value when a value that does not fit within a topic (i.e. not a fixed-length, 32-byte - * type). It is the `keccak256` of the value, and used for types such as arrays, tuples, bytes and strings. - * - * @category Application Binary Interface - */ -class Indexed { - /** - * The `keccak256` of the value logged. - */ - hash; - /** - * @ignore - */ - _isIndexed; - /** - * Check if a value is an **Indexed** This provides a Type Guard for property access. - * - * @param value - The value to check. - * - * @returns `true` if the value is an **Indexed**. - */ - static isIndexed(value) { - return !!(value && value._isIndexed); - } - /** - * @ignore - */ - constructor(hash) { - defineProperties(this, { hash, _isIndexed: true }); - } -} -// https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require -const PanicReasons = { - '0': 'generic panic', - '1': 'assert(false)', - '17': 'arithmetic overflow', - '18': 'division or modulo by zero', - '33': 'enum overflow', - '34': 'invalid encoded storage byte array accessed', - '49': 'out-of-bounds array access; popping on an empty array', - '50': 'out-of-bounds access of an array or bytesN', - '65': 'out of memory', - '81': 'uninitialized function', -}; -const BuiltinErrors = { - '0x08c379a0': { - signature: 'Error(string)', - name: 'Error', - inputs: ['string'], - reason: (message) => { - return `reverted with reason string ${JSON.stringify(message)}`; - }, - }, - '0x4e487b71': { - signature: 'Panic(uint256)', - name: 'Panic', - inputs: ['uint256'], - reason: (code) => { - let reason = 'unknown panic code'; - if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) { - reason = PanicReasons[code.toString()]; - } - return `reverted with panic code 0x${code.toString(16)} (${reason})`; - }, - }, -}; -/** - * An Interface abstracts many of the low-level details for encoding and decoding the data on the blockchain. - * - * An ABI provides information on how to encode data to send to a Contract, how to decode the results and events and how - * to interpret revert errors. - * - * The ABI can be specified by {@link InterfaceAbi | any supported format}. - * - * @category Application Binary Interface - */ -class Interface { - /** - * All the Contract ABI members (i.e. methods, events, errors, etc). - */ - fragments; - /** - * The Contract constructor. - */ - deploy; - /** - * The Fallback method, if any. - */ - fallback; - /** - * If receiving ether is supported. - */ - receive; - #errors; - #events; - #functions; - // #structs: Map; - #abiCoder; - /** - * Create a new Interface for the fragments. - * - * @param {InterfaceAbi} fragments - The ABI fragments. - */ - constructor(fragments) { - let abi = []; - if (typeof fragments === 'string') { - abi = JSON.parse(fragments); - } - else { - abi = fragments; - } - this.#functions = new Map(); - this.#errors = new Map(); - this.#events = new Map(); - const frags = []; - for (const a of abi) { - try { - frags.push(Fragment.from(a)); - } - catch (error) { - console.log('Error parsing ABI fragment', error); - } - } - defineProperties(this, { - fragments: Object.freeze(frags), - }); - let fallback = null; - let receive = false; - this.#abiCoder = this.getAbiCoder(); - // Add all fragments by their signature - this.fragments.forEach((fragment, index) => { - let bucket; - switch (fragment.type) { - case 'constructor': - if (this.deploy) { - console.log('duplicate definition - constructor'); - return; - } - defineProperties(this, { deploy: fragment }); - return; - case 'fallback': - if (fragment.inputs.length === 0) { - receive = true; - } - else { - assertArgument(!fallback || fragment.payable !== fallback.payable, 'conflicting fallback fragments', `fragments[${index}]`, fragment); - fallback = fragment; - receive = fallback.payable; - } - return; - case 'function': - bucket = this.#functions; - break; - case 'event': - bucket = this.#events; - break; - case 'error': - bucket = this.#errors; - break; - default: - return; - } - // Two identical entries; ignore it - const signature = fragment.format(); - if (bucket.has(signature)) { - return; - } - bucket.set(signature, fragment); - }); - // If we do not have a constructor add a default - if (!this.deploy) { - defineProperties(this, { - deploy: ConstructorFragment.from('constructor()'), - }); - } - defineProperties(this, { fallback, receive }); - } - /** - * Returns the entire Human-Readable ABI, as an array of signatures, optionally as `minimal` strings, which removes - * parameter names and unneceesary spaces. - */ - format(minimal) { - const format = minimal ? 'minimal' : 'full'; - const abi = this.fragments.map((f) => f.format(format)); - return abi; - } - /** - * Return the JSON-encoded ABI. This is the format Solidiy returns. - */ - formatJson() { - const abi = this.fragments.map((f) => f.format('json')); - // We need to re-bundle the JSON fragments a bit - return JSON.stringify(abi.map((j) => JSON.parse(j))); - } - /** - * The ABI coder that will be used to encode and decode binary data. - */ - getAbiCoder() { - return AbiCoder.defaultAbiCoder(); - } - // Find a function definition by any means necessary (unless it is ambiguous) - #getFunction(key, values, forceUnique) { - // Selector - if (isHexString(key)) { - const selector = key.toLowerCase(); - for (const fragment of this.#functions.values()) { - if (selector === fragment.selector) { - return fragment; - } - } - return null; - } - // It is a bare name, look up the function (will return null if ambiguous) - if (key.indexOf('(') === -1) { - const matching = []; - for (const [name, fragment] of this.#functions) { - if (name.split('(' /* fix:) */)[0] === key) { - matching.push(fragment); - } - } - if (values) { - const lastValue = values.length > 0 ? values[values.length - 1] : null; - let valueLength = values.length; - let allowOptions = true; - if (Typed.isTyped(lastValue) && lastValue.type === 'overrides') { - allowOptions = false; - valueLength--; - } - // Remove all matches that don't have a compatible length. The args - // may contain an overrides, so the match may have n or n - 1 parameters - for (let i = matching.length - 1; i >= 0; i--) { - const inputs = matching[i].inputs.length; - if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) { - matching.splice(i, 1); - } - } - // Remove all matches that don't match the Typed signature - for (let i = matching.length - 1; i >= 0; i--) { - const inputs = matching[i].inputs; - for (let j = 0; j < values.length; j++) { - // Not a typed value - if (!Typed.isTyped(values[j])) { - continue; - } - // We are past the inputs - if (j >= inputs.length) { - if (values[j].type === 'overrides') { - continue; - } - matching.splice(i, 1); - break; - } - // Make sure the value type matches the input type - if (values[j].type !== inputs[j].baseType) { - matching.splice(i, 1); - break; - } - } - } - } - // We found a single matching signature with an overrides, but the - // last value is something that cannot possibly be an options - if (matching.length === 1 && values && values.length !== matching[0].inputs.length) { - const lastArg = values[values.length - 1]; - if (lastArg == null || Array.isArray(lastArg) || typeof lastArg !== 'object') { - matching.splice(0, 1); - } - } - if (matching.length === 0) { - return null; - } - if (matching.length > 1 && forceUnique) { - const matchStr = matching.map((m) => JSON.stringify(m.format())).join(', '); - assertArgument(false, `ambiguous function description (i.e. matches ${matchStr})`, 'key', key); - } - return matching[0]; - } - // Normalize the signature and lookup the function - const result = this.#functions.get(FunctionFragment.from(key).format()); - if (result) { - return result; - } - return null; - } - /** - * Get the function name for `key`, which may be a function selector, function name or function signature that - * belongs to the ABI. - */ - getFunctionName(key) { - const fragment = this.#getFunction(key, null, false); - assertArgument(fragment, 'no matching function', 'key', key); - return fragment.name; - } - /** - * Returns true if `key` (a function selector, function name or function signature) is present in the ABI. - * - * In the case of a function name, the name may be ambiguous, so accessing the - * {@link FunctionFragment | **FunctionFragment**} may require refinement. - */ - hasFunction(key) { - return !!this.#getFunction(key, null, false); - } - /** - * Get the {@link FunctionFragment | **FunctionFragment**} for `key`, which may be a function selector, function name - * or function signature that belongs to the ABI. - * - * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple functions match by - * name. - * - * If the `key` and `values` do not refine to a single function in the ABI, this will throw. - */ - getFunction(key, values) { - return this.#getFunction(key, values || null, true); - } - /** - * Iterate over all functions, calling `callback`, sorted by their name. - */ - forEachFunction(callback) { - const names = Array.from(this.#functions.keys()); - names.sort((a, b) => a.localeCompare(b)); - for (let i = 0; i < names.length; i++) { - const name = names[i]; - callback(this.#functions.get(name), i); - } - } - // Find an event definition by any means necessary (unless it is ambiguous) - #getEvent(key, values, forceUnique) { - // EventTopic - if (isHexString(key)) { - const eventTopic = key.toLowerCase(); - for (const fragment of this.#events.values()) { - if (eventTopic === fragment.topicHash) { - return fragment; - } - } - return null; - } - // It is a bare name, look up the function (will return null if ambiguous) - if (key.indexOf('(') === -1) { - const matching = []; - for (const [name, fragment] of this.#events) { - if (name.split('(' /* fix:) */)[0] === key) { - matching.push(fragment); - } - } - if (values) { - // Remove all matches that don't have a compatible length. - for (let i = matching.length - 1; i >= 0; i--) { - if (matching[i].inputs.length < values.length) { - matching.splice(i, 1); - } - } - // Remove all matches that don't match the Typed signature - for (let i = matching.length - 1; i >= 0; i--) { - const inputs = matching[i].inputs; - for (let j = 0; j < values.length; j++) { - // Not a typed value - if (!Typed.isTyped(values[j])) { - continue; - } - // Make sure the value type matches the input type - if (values[j].type !== inputs[j].baseType) { - matching.splice(i, 1); - break; - } - } - } - } - if (matching.length === 0) { - return null; - } - if (matching.length > 1 && forceUnique) { - const matchStr = matching.map((m) => JSON.stringify(m.format())).join(', '); - assertArgument(false, `ambiguous event description (i.e. matches ${matchStr})`, 'key', key); - } - return matching[0]; - } - // Normalize the signature and lookup the function - const result = this.#events.get(EventFragment.from(key).format()); - if (result) { - return result; - } - return null; - } - /** - * Get the event name for `key`, which may be a topic hash, event name or event signature that belongs to the ABI. - */ - getEventName(key) { - const fragment = this.#getEvent(key, null, false); - assertArgument(fragment, 'no matching event', 'key', key); - return fragment.name; - } - /** - * Returns true if `key` (an event topic hash, event name or event signature) is present in the ABI. - * - * In the case of an event name, the name may be ambiguous, so accessing the - * {@link EventFragment | **EventFragment**} may require refinement. - */ - hasEvent(key) { - return !!this.#getEvent(key, null, false); - } - /** - * Get the {@link EventFragment | **EventFragment**} for `key`, which may be a topic hash, event name or event - * signature that belongs to the ABI. - * - * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple events match by name. - * - * If the `key` and `values` do not refine to a single event in the ABI, this will throw. - */ - getEvent(key, values) { - return this.#getEvent(key, values || null, true); - } - /** - * Iterate over all events, calling `callback`, sorted by their name. - */ - forEachEvent(callback) { - const names = Array.from(this.#events.keys()); - names.sort((a, b) => a.localeCompare(b)); - for (let i = 0; i < names.length; i++) { - const name = names[i]; - callback(this.#events.get(name), i); - } - } - /** - * Get the {@link ErrorFragment | **ErroFragment**} for `key`, which may be an error selector, error name or error - * signature that belongs to the ABI. - * - * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple errors match by name. - * - * If the `key` and `values` do not refine to a single error in the ABI, this will throw. - */ - // TODO: `values` is not used, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getError(key, values) { - if (isHexString(key)) { - const selector = key.toLowerCase(); - if (BuiltinErrors[selector]) { - return ErrorFragment.from(BuiltinErrors[selector].signature); - } - for (const fragment of this.#errors.values()) { - if (selector === fragment.selector) { - return fragment; - } - } - return null; - } - // It is a bare name, look up the function (will return null if ambiguous) - if (key.indexOf('(') === -1) { - const matching = []; - for (const [name, fragment] of this.#errors) { - if (name.split('(' /* fix:) */)[0] === key) { - matching.push(fragment); - } - } - if (matching.length === 0) { - if (key === 'Error') { - return ErrorFragment.from('error Error(string)'); - } - if (key === 'Panic') { - return ErrorFragment.from('error Panic(uint256)'); - } - return null; - } - else if (matching.length > 1) { - const matchStr = matching.map((m) => JSON.stringify(m.format())).join(', '); - assertArgument(false, `ambiguous error description (i.e. ${matchStr})`, 'name', key); - } - return matching[0]; - } - // Normalize the signature and lookup the function - key = ErrorFragment.from(key).format(); - if (key === 'Error(string)') { - return ErrorFragment.from('error Error(string)'); - } - if (key === 'Panic(uint256)') { - return ErrorFragment.from('error Panic(uint256)'); - } - const result = this.#errors.get(key); - if (result) { - return result; - } - return null; - } - /** - * Iterate over all errors, calling `callback`, sorted by their name. - */ - forEachError(callback) { - const names = Array.from(this.#errors.keys()); - names.sort((a, b) => a.localeCompare(b)); - for (let i = 0; i < names.length; i++) { - const name = names[i]; - callback(this.#errors.get(name), i); - } - } - /** - * @ignore - */ - _decodeParams(params, data) { - return this.#abiCoder.decode(params, data); - } - /** - * @ignore - */ - _encodeParams(params, values) { - return this.#abiCoder.encode(params, values); - } - /** - * Encodes a `tx.data` object for deploying the Contract with the `values` as the constructor arguments. - */ - encodeDeploy(values) { - return this._encodeParams(this.deploy.inputs, values || []); - } - /** - * Decodes the result `data` (e.g. from an `quai_call`) for the specified error (see {@link getError | **getError**} - * for valid values for `key`). - * - * Most developers should prefer the {@link parseCallResult | **parseCallResult**} method instead, which will - * automatically detect a `CALL_EXCEPTION` and throw the corresponding error. - */ - decodeErrorResult(fragment, data) { - if (typeof fragment === 'string') { - const f = this.getError(fragment); - assertArgument(f, 'unknown error', 'fragment', fragment); - fragment = f; - } - assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match error ${fragment.name}.`, 'data', data); - return this._decodeParams(fragment.inputs, dataSlice(data, 4)); - } - /** - * Encodes the transaction revert data for a call result that reverted from the the Contract with the sepcified - * `error` (see {@link getError | **getError**} for valid values for `fragment`) with the `values`. - * - * This is generally not used by most developers, unless trying to mock a result from a Contract. - */ - encodeErrorResult(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getError(fragment); - assertArgument(f, 'unknown error', 'fragment', fragment); - fragment = f; - } - return concat([fragment.selector, this._encodeParams(fragment.inputs, values || [])]); - } - /** - * Decodes the `data` from a transaction `tx.data` for the function specified (see - * {@link getFunction | **getFunction**} for valid values for `fragment`). - * - * Most developers should prefer the {@link parseTransaction | **parseTransaction**} method instead, which will - * automatically detect the fragment. - */ - decodeFunctionData(fragment, data) { - if (typeof fragment === 'string') { - const f = this.getFunction(fragment); - assertArgument(f, 'unknown function', 'fragment', fragment); - fragment = f; - } - assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match function ${fragment.name}.`, 'data', data); - return this._decodeParams(fragment.inputs, dataSlice(data, 4)); - } - /** - * Encodes the `tx.data` for a transaction that calls the function specified (see - * {@link getFunction | **getFunction**} for valid values for `fragment`) with the `values`. - */ - encodeFunctionData(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getFunction(fragment); - assertArgument(f, 'unknown function', 'fragment', fragment); - fragment = f; - } - return concat([fragment.selector, this._encodeParams(fragment.inputs, values || [])]); - } - /** - * Decodes the result `data` (e.g. from an `quai_call`) for the specified function (see - * {@link getFunction | **getFunction**} for valid values for `key`). - * - * Most developers should prefer the {@link parseCallResult | **parseCallResult**} method instead, which will - * automatically detect a `CALL_EXCEPTION` and throw the corresponding error. - */ - decodeFunctionResult(fragment, data) { - if (typeof fragment === 'string') { - const f = this.getFunction(fragment); - assertArgument(f, 'unknown function', 'fragment', fragment); - fragment = f; - } - let message = 'invalid length for result data'; - const bytes = getBytesCopy(data); - if (bytes.length % 32 === 0) { - try { - return this.#abiCoder.decode(fragment.outputs, bytes); - } - catch (error) { - message = 'could not decode result data'; - } - } - // Call returned data with no error, but the data is junk - assert(false, message, 'BAD_DATA', { - value: hexlify(bytes), - info: { method: fragment.name, signature: fragment.format() }, - }); - } - makeError(_data, tx) { - const data = getBytes(_data, 'data'); - const error = AbiCoder.getBuiltinCallException('call', tx, data); - // Not a built-in error; try finding a custom error - const customPrefix = 'execution reverted (unknown custom error)'; - if (error.message.startsWith(customPrefix)) { - const selector = hexlify(data.slice(0, 4)); - const ef = this.getError(selector); - if (ef) { - try { - const args = this.#abiCoder.decode(ef.inputs, data.slice(4)); - error.revert = { - name: ef.name, - signature: ef.format(), - args, - }; - error.reason = error.revert.signature; - error.message = `execution reverted: ${error.reason}`; - } - catch (e) { - error.message = `execution reverted (coult not decode custom error)`; - } - } - } - // Add the invocation, if available - const parsed = this.parseTransaction(tx); - if (parsed) { - error.invocation = { - method: parsed.name, - signature: parsed.signature, - args: parsed.args, - }; - } - return error; - } - /** - * Encodes the result data (e.g. from an `quai_call`) for the specified function (see - * {@link getFunction | **getFunction**} for valid values for `fragment`) with `values`. - * - * This is generally not used by most developers, unless trying to mock a result from a Contract. - */ - encodeFunctionResult(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getFunction(fragment); - assertArgument(f, 'unknown function', 'fragment', fragment); - fragment = f; - } - return hexlify(this.#abiCoder.encode(fragment.outputs, values || [])); - } - // Create the filter for the event with search criteria (e.g. for quai_filterLog) - encodeFilterTopics(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getEvent(fragment); - assertArgument(f, 'unknown event', 'eventFragment', fragment); - fragment = f; - } - assert(values.length <= fragment.inputs.length, `too many arguments for ${fragment.format()}`, 'UNEXPECTED_ARGUMENT', { count: values.length, expectedCount: fragment.inputs.length }); - const topics = []; - if (!fragment.anonymous) { - topics.push(fragment.topicHash); - } - // @TODO: Use the coders for this; to properly support tuples, etc. - const encodeTopic = (param, value) => { - if (param.type === 'string') { - return id(value); - } - else if (param.type === 'bytes') { - return keccak256(hexlify(value)); - } - if (param.type === 'bool' && typeof value === 'boolean') { - value = value ? '0x01' : '0x00'; - } - else if (param.type.match(/^u?int/)) { - value = toBeHex(value); // @TODO: Should this toTwos?? - } - else if (param.type.match(/^bytes/)) { - value = zeroPadBytes(value, 32); - } - else if (param.type === 'address') { - // Check addresses are valid - this.#abiCoder.encode(['address'], [value]); - } - return zeroPadValue(hexlify(value), 32); - }; - values.forEach((value, index) => { - const param = fragment.inputs[index]; - if (!param.indexed) { - assertArgument(value == null, 'cannot filter non-indexed parameters; must be null', 'contract.' + param.name, value); - return; - } - if (value == null) { - topics.push(null); - } - else if (param.baseType === 'array' || param.baseType === 'tuple') { - assertArgument(false, 'filtering with tuples or arrays not supported', 'contract.' + param.name, value); - } - else if (Array.isArray(value)) { - topics.push(value.map((value) => encodeTopic(param, value))); - } - else { - topics.push(encodeTopic(param, value)); - } - }); - // Trim off trailing nulls - while (topics.length && topics[topics.length - 1] === null) { - topics.pop(); - } - return topics; - } - encodeEventLog(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getEvent(fragment); - assertArgument(f, 'unknown event', 'eventFragment', fragment); - fragment = f; - } - const topics = []; - const dataTypes = []; - const dataValues = []; - if (!fragment.anonymous) { - topics.push(fragment.topicHash); - } - assertArgument(values.length === fragment.inputs.length, 'event arguments/values mismatch', 'values', values); - fragment.inputs.forEach((param, index) => { - const value = values[index]; - if (param.indexed) { - if (param.type === 'string') { - topics.push(id(value)); - } - else if (param.type === 'bytes') { - topics.push(keccak256(value)); - } - else if (param.baseType === 'tuple' || param.baseType === 'array') { - // @TODO - throw new Error('not implemented'); - } - else { - topics.push(this.#abiCoder.encode([param.type], [value])); - } - } - else { - dataTypes.push(param); - dataValues.push(value); - } - }); - return { - data: this.#abiCoder.encode(dataTypes, dataValues), - topics: topics, - }; - } - // Decode a filter for the event and the search criteria - decodeEventLog(fragment, data, topics) { - if (typeof fragment === 'string') { - const f = this.getEvent(fragment); - assertArgument(f, 'unknown event', 'eventFragment', fragment); - fragment = f; - } - if (topics != null && !fragment.anonymous) { - const eventTopic = fragment.topicHash; - assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic, 'fragment/topic mismatch', 'topics[0]', topics[0]); - topics = topics.slice(1); - } - const indexed = []; - const nonIndexed = []; - const dynamic = []; - // TODO: `index` is not used, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - fragment.inputs.forEach((param, index) => { - if (param.indexed) { - if (param.type === 'string' || - param.type === 'bytes' || - param.baseType === 'tuple' || - param.baseType === 'array') { - indexed.push(ParamType.from({ type: 'bytes32', name: param.name })); - dynamic.push(true); - } - else { - indexed.push(param); - dynamic.push(false); - } - } - else { - nonIndexed.push(param); - dynamic.push(false); - } - }); - const resultIndexed = topics != null ? this.#abiCoder.decode(indexed, concat(topics)) : null; - const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true); - //const result: (Array & { [ key: string ]: any }) = [ ]; - const values = []; - const keys = []; - let nonIndexedIndex = 0, indexedIndex = 0; - fragment.inputs.forEach((param, index) => { - let value = null; - if (param.indexed) { - if (resultIndexed == null) { - value = new Indexed(null); - } - else if (dynamic[index]) { - value = new Indexed(resultIndexed[indexedIndex++]); - } - else { - try { - value = resultIndexed[indexedIndex++]; - } - catch (error) { - value = error; - } - } - } - else { - try { - value = resultNonIndexed[nonIndexedIndex++]; - } - catch (error) { - value = error; - } - } - values.push(value); - keys.push(param.name || null); - }); - return Result.fromItems(values, keys); - } - /** - * Parses a transaction, finding the matching function and extracts the parameter values along with other useful - * function details. - * - * If the matching function cannot be found, return null. - */ - parseTransaction(tx) { - const data = getBytes(tx.data, 'tx.data'); - const value = getBigInt(tx.value != null ? tx.value : 0, 'tx.value'); - const fragment = this.getFunction(hexlify(data.slice(0, 4))); - if (!fragment) { - return null; - } - const args = this.#abiCoder.decode(fragment.inputs, data.slice(4)); - return new TransactionDescription(fragment, fragment.selector, args, value); - } - // TODO: not implemented - // eslint-disable-next-line @typescript-eslint/no-unused-vars - parseCallResult(data) { - throw new Error('@TODO'); - } - /** - * Parses a receipt log, finding the matching event and extracts the parameter values along with other useful event - * details. - * - * If the matching event cannot be found, returns null. - */ - parseLog(log) { - const fragment = this.getEvent(log.topics[0]); - if (!fragment || fragment.anonymous) { - return null; - } - // @TODO: If anonymous, and the only method, and the input count matches, should we parse? - // Probably not, because just because it is the only event in the ABI does - // not mean we have the full ABI; maybe just a fragment? - return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics)); - } - /** - * Parses a revert data, finding the matching error and extracts the parameter values along with other useful error - * details. - * - * If the matching error cannot be found, returns null. - */ - parseError(data) { - const hexData = hexlify(data); - const fragment = this.getError(dataSlice(hexData, 0, 4)); - if (!fragment) { - return null; - } - const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4)); - return new ErrorDescription(fragment, fragment.selector, args); - } - /** - * Creates a new {@link Interface | **Interface**} from the ABI `value`. - * - * The `value` may be provided as an existing {@link Interface | **Interface**} object, a JSON-encoded ABI or any - * Human-Readable ABI format. - */ - static from(value) { - // Already an Interface, which is immutable - if (value instanceof Interface) { - return value; - } - // JSON - if (typeof value === 'string') { - return new Interface(JSON.parse(value)); - } - // Maybe an interface from an older version, or from a symlinked copy - if (typeof value.format === 'function') { - return new Interface(value.format('json')); - } - // Array of fragments - return new Interface(value); - } -} - -/** - * Converts an address and storage keys into an access set. - * - * @param {string} addr - The address to validate and convert. - * @param {Array} storageKeys - The storage keys to validate and convert. - * @returns {{ address: string; storageKeys: Array }} The access set. - */ -function accessSetify(addr, storageKeys) { - validateAddress(addr); - return { - address: getAddress(addr), - storageKeys: storageKeys.map((storageKey, index) => { - assertArgument(isHexString(storageKey, 32), 'invalid slot', `storageKeys[${index}]`, storageKey); - return storageKey.toLowerCase(); - }), - }; -} -/** - * Returns an {@link AccessList | **AccessList**} from any quasi-supported access-list structure. - * - * @category Transaction - * @param {AccessListish} value - The value to convert to an access list. - * @returns {AccessList} The access list. - * @throws {Error} If the value is not a valid access list. - */ -function accessListify(value) { - if (Array.isArray(value)) { - return value.map((set, index) => { - if (Array.isArray(set)) { - assertArgument(set.length === 2, 'invalid slot set', `value[${index}]`, set); - return accessSetify(set[0], set[1]); - } - assertArgument(set != null && typeof set === 'object', 'invalid address-slot set', 'value', value); - return accessSetify(set.address, set.storageKeys); - }); - } - assertArgument(value != null && typeof value === 'object', 'invalid access list', 'value', value); - const result = Object.keys(value).map((addr) => { - const storageKeys = value[addr].reduce((accum, storageKey) => { - accum[storageKey] = true; - return accum; - }, {}); - return accessSetify(addr, Object.keys(storageKeys).sort()); - }); - result.sort((a, b) => a.address.localeCompare(b.address)); - return result; -} - -/** - * An **AbstractTransaction** describes the common operations to be executed on Quai and Qi ledgers by an Externally - * Owned Account (EOA). This class must be subclassed by concrete implementations of transactions on each ledger. - */ -class AbstractTransaction { - _type; - _signature; - _chainId; - /** - * The transaction type. - * - * If null, the type will be automatically inferred based on explicit properties. - */ - get type() { - return this._type; - } - set type(value) { - switch (value) { - case null: - this._type = null; - break; - case 0: - case 'standard': - this._type = 0; - break; - case 2: - case 'utxo': - this._type = 2; - break; - default: - assertArgument(false, 'unsupported transaction type', 'type', value); - } - } - /** - * The name of the transaction type. - */ - get typeName() { - switch (this.type) { - case 0: - return 'standard'; - case 1: - return 'external'; - case 2: - return 'utxo'; - } - return null; - } - /** - * The chain ID this transaction is valid on. - */ - get chainId() { - return this._chainId; - } - set chainId(value) { - this._chainId = getBigInt(value); - } - /** - * If signed, the signature for this transaction. - */ - get signature() { - return (this._signature || null); - } - set signature(value) { - if (typeof value === 'string') { - this._signature = value; - } - else { - this._signature = (value == null ? null : Signature.from(value)); - } - } - /** - * Creates a new Transaction with default values. - */ - constructor() { - this._type = null; - this._chainId = BigInt(0); - this._signature = null; - } - /** - * The pre-image hash of this transaction. - * - * This is the digest that a [Signer](../interfaces/Signer) must sign to authorize this transaction. - */ - get digest() { - return keccak256(this.unsignedSerialized); - } - /** - * Returns true if signed. - * - * This provides a Type Guard that properties requiring a signed transaction are non-null. - * - * @returns {boolean} Indicates if the transaction is signed. - */ - isSigned() { - return this.signature != null; - } - /** - * The serialized transaction. - * - * This throws if the transaction is unsigned. For the pre-image, use - * {@link AbstractTransaction.unsignedSerialized | **unsignedSerialized** }. - */ - get serialized() { - assert(this.signature != null, 'cannot serialize unsigned transaction; maybe you meant .unsignedSerialized', 'UNSUPPORTED_OPERATION', { operation: '.serialized' }); - return encodeProtoTransaction(this.toProtobuf(true)); - } - /** - * The transaction pre-image. - * - * The hash of this is the digest which needs to be signed to authorize this transaction. - */ - get unsignedSerialized() { - return encodeProtoTransaction(this.toProtobuf(false)); - } - /** - * Return the most "likely" type; currently the highest supported transaction type. - * - * @returns {number} The inferred transaction type. - */ - inferType() { - return this.inferTypes().pop(); - } - /** - * Check if the transaction is external. - * - * @returns {boolean} True if the transaction is external. - */ - get isExternal() { - return this.destZone !== undefined && this.originZone !== this.destZone; - } -} - -/** - * List of supported Qi denominations. - * - * @category Transaction - */ -const denominations = [ - BigInt(1), - BigInt(5), - BigInt(10), - BigInt(50), - BigInt(100), - BigInt(250), - BigInt(500), - BigInt(1000), - BigInt(5000), - BigInt(10000), - BigInt(20000), - BigInt(50000), - BigInt(100000), - BigInt(1000000), - BigInt(10000000), - BigInt(100000000), - BigInt(1000000000), // 1000000 Qi -]; -/** - * Checks if the provided denomination is valid. - * - * @category Transaction - * @param {bigint} denomination - The denomination to check. - * @returns {boolean} True if the denomination is valid, false otherwise. - */ -function isValidDenomination(denomination) { - return denominations.includes(denomination); -} -/** - * Handles conversion of string to bigint, specifically for transaction parameters. - * - * @ignore - * @category Transaction - * @param {string} value - The value to convert. - * @param {string} param - The parameter name. - * @returns {bigint} The converted value. - */ -function handleBigInt(value, param) { - if (value === '0x') { - return BigInt(0); - } - return getBigInt(value, param); -} -/** - * Given a value, returns an array of supported denominations that sum to the value. - * - * @category Transaction - * @param {bigint} value - The value to denominate. - * @returns {bigint[]} An array of denominations that sum to the value. - * @throws {Error} If the value is less than or equal to 0 or cannot be matched with available denominations. - */ -function denominate(value) { - if (value <= BigInt(0)) { - throw new Error('Value must be greater than 0'); - } - const result = []; - let remainingValue = value; - // Iterate through denominations in descending order - for (let i = denominations.length - 1; i >= 0; i--) { - const denomination = denominations[i]; - // Add the denomination to the result array as many times as possible - while (remainingValue >= denomination) { - result.push(denomination); - remainingValue -= denomination; - } - } - if (remainingValue > 0) { - throw new Error('Unable to match the value with available denominations'); - } - return result; -} -/** - * Represents a UTXO (Unspent Transaction Output). - * - * @category Transaction - * @implements {UTXOLike} - */ -class UTXO { - #txhash; - #index; - #address; - #denomination; - /** - * Gets the transaction hash. - * - * @returns {null | string} The transaction hash. - */ - get txhash() { - return this.#txhash; - } - /** - * Sets the transaction hash. - * - * @param {null | string} value - The transaction hash. - */ - set txhash(value) { - this.#txhash = value; - } - /** - * Gets the index. - * - * @returns {null | number} The index. - */ - get index() { - return this.#index; - } - /** - * Sets the index. - * - * @param {null | number} value - The index. - */ - set index(value) { - this.#index = value; - } - /** - * Gets the address. - * - * @returns {string} The address. - */ - get address() { - return this.#address || ''; - } - /** - * Sets the address. - * - * @param {string} value - The address. - * @throws {Error} If the address is invalid. - */ - set address(value) { - validateAddress(value); - this.#address = value; - } - /** - * Gets the denomination. - * - * @returns {null | bigint} The denomination. - */ - get denomination() { - return this.#denomination; - } - /** - * Sets the denomination. - * - * @param {null | BigNumberish} value - The denomination. - * @throws {Error} If the denomination value is invalid. - */ - set denomination(value) { - if (value == null) { - this.#denomination = null; - return; - } - const denominationBigInt = handleBigInt(value.toString(), 'denomination'); - if (!isValidDenomination(denominationBigInt)) { - throw new Error('Invalid denomination value'); - } - this.#denomination = denominationBigInt; - } - /** - * Constructs a new UTXO instance with null properties. - */ - constructor() { - this.#txhash = null; - this.#index = null; - this.#address = null; - this.#denomination = null; - } - /** - * Converts the UTXO instance to a JSON object. - * - * @returns {any} A JSON representation of the UTXO instance. - */ - toJSON() { - return { - txhash: this.txhash, - index: this.index, - address: this.address, - denomination: this.denomination, - }; - } - /** - * Creates a UTXO instance from a UTXOLike object. - * - * @param {UTXOLike} utxo - The UTXOLike object to convert. - * @returns {UTXO} The UTXO instance. - */ - static from(utxo) { - if (utxo === null) { - return new UTXO(); - } - const result = utxo instanceof UTXO ? utxo : new UTXO(); - if (utxo.txhash != null) { - result.txhash = utxo.txhash; - } - if (utxo.index != null) { - result.index = utxo.index; - } - if (utxo.address != null && utxo.address !== '') { - result.address = utxo.address; - } - if (utxo.denomination != null) { - result.denomination = utxo.denomination; - } - return result; - } -} - -/** - * An **AbstractCoinSelector** provides a base class for other sub-classes to implement the functionality for selecting - * UTXOs for a spend and to properly handle spend and change outputs. - * - * This class is abstract and should not be used directly. Sub-classes should implement the - * {@link AbstractCoinSelector#performSelection | **performSelection**} method to provide the actual coin selection - * logic. - * - * @category Transaction - * @abstract - */ -class AbstractCoinSelector { - #availableUXTOs; - #spendOutputs; - #changeOutputs; - /** - * Gets the available UTXOs. - * @returns {UTXO[]} The available UTXOs. - */ - get availableUXTOs() { - return this.#availableUXTOs; - } - /** - * Sets the available UTXOs. - * @param {UTXOLike[]} value - The UTXOs to set. - */ - set availableUXTOs(value) { - this.#availableUXTOs = value.map((val) => { - const utxo = UTXO.from(val); - this._validateUTXO(utxo); - return utxo; - }); - } - /** - * Gets the spend outputs. - * @returns {UTXO[]} The spend outputs. - */ - get spendOutputs() { - return this.#spendOutputs; - } - /** - * Sets the spend outputs. - * @param {UTXOLike[]} value - The spend outputs to set. - */ - set spendOutputs(value) { - this.#spendOutputs = value.map((utxo) => UTXO.from(utxo)); - } - /** - * Gets the change outputs. - * @returns {UTXO[]} The change outputs. - */ - get changeOutputs() { - return this.#changeOutputs; - } - /** - * Sets the change outputs. - * @param {UTXOLike[]} value - The change outputs to set. - */ - set changeOutputs(value) { - this.#changeOutputs = value.map((utxo) => UTXO.from(utxo)); - } - /** - * Constructs a new AbstractCoinSelector instance with an empty UTXO array. - * @param {UTXOEntry[]} [availableUXTOs=[]] - The initial available UTXOs. - */ - constructor(availableUXTOs = []) { - this.#availableUXTOs = availableUXTOs.map((val) => { - const utxo = UTXO.from(val); - this._validateUTXO(utxo); - return utxo; - }); - this.#spendOutputs = []; - this.#changeOutputs = []; - } - /** - * Validates the provided UTXO instance. In order to be valid for coin selection, the UTXO must have a valid address - * and denomination. - * - * @param {UTXO} utxo - The UTXO to validate. - * @throws {Error} If the UTXO is invalid. - * @protected - */ - _validateUTXO(utxo) { - if (utxo.address == null) { - throw new Error('UTXO address is required'); - } - if (utxo.denomination == null) { - throw new Error('UTXO denomination is required'); - } - } -} - -/** - * The FewestCoinSelector class provides a coin selection algorithm that selects the fewest UTXOs required to meet the - * target amount. This algorithm is useful for minimizing the size of the transaction and the fees associated with it. - * - * This class is a sub-class of {@link AbstractCoinSelector | **AbstractCoinSelector** } and implements the - * {@link AbstractCoinSelector.performSelection | **performSelection** } method to provide the actual coin selection - * logic. - * - * @category Transaction - */ -class FewestCoinSelector extends AbstractCoinSelector { - /** - * The largest first coin selection algorithm. - * - * This algorithm selects the largest UTXOs first, and continues to select UTXOs until the target amount is reached. - * If the total value of the selected UTXOs is greater than the target amount, the remaining value is returned as a - * change output. - * - * @param {SpendTarget} target - The target amount to spend. - * - * @returns {SelectedCoinsResult} The selected UTXOs and change outputs. - */ - performSelection(target) { - this.validateTarget(target); - this.validateUTXOs(); - const sortedUTXOs = this.sortUTXOsByDenomination(this.availableUXTOs, 'desc'); - let totalValue = BigInt(0); - let selectedUTXOs = []; - // Get UTXOs that meets or exceeds the target value - const UTXOsEqualOrGreaterThanTarget = sortedUTXOs.filter((utxo) => utxo.denomination && utxo.denomination >= target.value); - if (UTXOsEqualOrGreaterThanTarget.length > 0) { - // Find the smallest UTXO that meets or exceeds the target value - const optimalUTXO = UTXOsEqualOrGreaterThanTarget.reduce((minDenominationUTXO, currentUTXO) => { - if (!currentUTXO.denomination) - return minDenominationUTXO; - return currentUTXO.denomination < minDenominationUTXO.denomination ? currentUTXO : minDenominationUTXO; - }, UTXOsEqualOrGreaterThanTarget[0]); // Initialize with the first UTXO in the list - selectedUTXOs.push(optimalUTXO); - totalValue += optimalUTXO.denomination; - } - else { - // If no single UTXO meets or exceeds the target, aggregate smaller denominations - // until the target is met/exceeded or there are no more UTXOs to aggregate - while (sortedUTXOs.length > 0 && totalValue < target.value) { - const nextOptimalUTXO = sortedUTXOs.reduce((closest, utxo) => { - if (!utxo.denomination) - return closest; - // Prioritize UTXOs that bring totalValue closer to target.value - const absThisDiff = bigIntAbs(target.value - (totalValue + utxo.denomination)); - const currentClosestDiff = closest && closest.denomination - ? bigIntAbs(target.value - (totalValue + closest.denomination)) - : BigInt(Infinity); - return absThisDiff < currentClosestDiff ? utxo : closest; - }, sortedUTXOs[0]); - // Add the selected UTXO to the selection and update totalValue - selectedUTXOs.push(nextOptimalUTXO); - totalValue += nextOptimalUTXO.denomination; - // Remove the selected UTXO from the list of available UTXOs - const index = sortedUTXOs.findIndex((utxo) => utxo.denomination === nextOptimalUTXO.denomination && utxo.address === nextOptimalUTXO.address); - sortedUTXOs.splice(index, 1); - } - } - // Check if the selected UTXOs meet or exceed the target amount - if (totalValue < target.value) { - throw new Error('Insufficient funds'); - } - // Check if any denominations can be removed from the input set and it still remain valid - selectedUTXOs = this.sortUTXOsByDenomination(selectedUTXOs, 'asc'); - let runningTotal = totalValue; - let lastRemovableIndex = -1; // Index of the last UTXO that can be removed - // Iterate through selectedUTXOs to find the last removable UTXO - for (let i = 0; i < selectedUTXOs.length; i++) { - const utxo = selectedUTXOs[i]; - if (utxo.denomination) { - if (runningTotal - utxo.denomination >= target.value) { - runningTotal -= utxo.denomination; - lastRemovableIndex = i; - } - else { - // Once a UTXO makes the total less than target.value, stop the loop - break; - } - } - } - if (lastRemovableIndex >= 0) { - totalValue -= selectedUTXOs[lastRemovableIndex].denomination; - selectedUTXOs.splice(lastRemovableIndex, 1); - } - // Break down the total spend into properly denominatated UTXOs - const spendDenominations = denominate(target.value); - this.spendOutputs = spendDenominations.map((denomination) => { - const utxo = new UTXO(); - utxo.denomination = denomination; - utxo.address = target.address; - return utxo; - }); - // Calculate change to be returned - const change = totalValue - target.value; - // If there's change, break it down into properly denominatated UTXOs - if (change > BigInt(0)) { - const changeDenominations = denominate(change); - this.changeOutputs = changeDenominations.map((denomination) => { - const utxo = new UTXO(); - utxo.denomination = denomination; - // We do not have access to change addresses here so leave it null - return utxo; - }); - } - else { - this.changeOutputs = []; - } - return { - inputs: selectedUTXOs, - spendOutputs: this.spendOutputs, - changeOutputs: this.changeOutputs, - }; - } - /** - * Sorts UTXOs by their denomination. - * - * @param {UTXO[]} utxos - The UTXOs to sort. - * @param {'asc' | 'desc'} direction - The direction to sort ('asc' for ascending, 'desc' for descending). - * @returns {UTXO[]} The sorted UTXOs. - */ - sortUTXOsByDenomination(utxos, direction) { - if (direction === 'asc') { - return [...utxos].sort((a, b) => { - const diff = (a.denomination ?? BigInt(0)) - (b.denomination ?? BigInt(0)); - return diff > 0 ? 1 : diff < 0 ? -1 : 0; - }); - } - return [...utxos].sort((a, b) => { - const diff = (b.denomination ?? BigInt(0)) - (a.denomination ?? BigInt(0)); - return diff > 0 ? 1 : diff < 0 ? -1 : 0; - }); - } - /** - * Validates the target amount. - * - * @param {SpendTarget} target - The target amount to validate. - * @throws Will throw an error if the target amount is less than or equal to 0. - */ - validateTarget(target) { - if (target.value <= BigInt(0)) { - throw new Error('Target amount must be greater than 0'); - } - } - /** - * Validates the available UTXOs. - * - * @throws Will throw an error if there are no available UTXOs. - */ - validateUTXOs() { - if (this.availableUXTOs.length === 0) { - throw new Error('No UTXOs available'); - } - } -} - -/** - * @ignore - */ -const BN_0$2 = BigInt(0); -function allowNull(format, nullValue) { - return function (value) { - if (value == null) { - return nullValue; - } - return format(value); - }; -} -function arrayOf(format) { - return (array) => { - if (!Array.isArray(array)) { - throw new Error('not an array'); - } - return array.map((i) => format(i)); - }; -} -// Requires an object which matches a fleet of other formatters -// Any FormatFunc may return `undefined` to have the value omitted -// from the result object. Calls preserve `this`. -function object(format, altNames) { - return (value) => { - const result = {}; - for (const key in format) { - let srcKey = key; - if (altNames && key in altNames && !(srcKey in value)) { - for (const altKey of altNames[key]) { - if (altKey in value) { - srcKey = altKey; - break; - } - } - } - try { - const nv = format[key](value[srcKey]); - if (nv !== undefined) { - result[key] = nv; - } - } - catch (error) { - const message = error instanceof Error ? error.message : 'not-an-error'; - assert(false, `invalid value for value.${key} (${message})`, 'BAD_DATA', { value }); - } - } - return result; - }; -} -function formatBoolean(value) { - switch (value) { - case true: - case 'true': - return true; - case false: - case 'false': - return false; - } - assertArgument(false, `invalid boolean; ${JSON.stringify(value)}`, 'value', value); -} -function formatData(value) { - assertArgument(isHexString(value), 'invalid data', 'value', value); - return value; -} -function formatHash(value) { - assertArgument(isHexString(value, 32), 'invalid hash', 'value', value); - return value; -} -function handleNumber(_value, param) { - if (_value === '0x') { - return 0; - } - return getNumber(_value, param); -} -function formatNumber(_value, name) { - const value = getBigInt(_value, 'value'); - const result = toBeArray(value); - assertArgument(result.length <= 32, `value too large`, `tx.${name}`, value); - return result; -} -const _formatLog = object({ - address: getAddress, - blockHash: formatHash, - blockNumber: getNumber, - data: formatData, - index: getNumber, - removed: allowNull(formatBoolean, false), - topics: arrayOf(formatHash), - transactionHash: formatHash, - transactionIndex: getNumber, -}, { - index: ['logIndex'], -}); -function formatLog(value) { - return _formatLog(value); -} -const _formatHeader = object({ - baseFeePerGas: getBigInt, - efficiencyScore: getBigInt, - etxEligibleSlices: formatHash, - etxSetRoot: formatHash, - evmRoot: formatHash, - expansionNumber: getNumber, - extRollupRoot: formatHash, - extTransactionsRoot: formatHash, - extraData: formatData, - gasLimit: getBigInt, - gasUsed: getBigInt, - hash: formatHash, - interlinkRootHash: formatHash, - manifestHash: arrayOf(formatHash), - number: arrayOf(getNumber), - parentDeltaS: arrayOf(getBigInt), - parentEntropy: arrayOf(getBigInt), - parentHash: arrayOf(formatHash), - parentUncledS: arrayOf(allowNull(getBigInt)), - parentUncledSubDeltaS: arrayOf(getBigInt), - primeTerminus: formatHash, - receiptsRoot: formatHash, - sha3Uncles: formatHash, - size: getBigInt, - thresholdCount: getBigInt, - transactionsRoot: formatHash, - uncledS: getBigInt, - utxoRoot: formatHash, -}); -const _formatUncle = object({ - coinbase: allowNull(getAddress), - difficulty: getBigInt, - headerHash: formatHash, - location: formatData, - mixHash: formatHash, - nonce: formatData, - number: getNumber, - parentHash: formatHash, - primeTerminusNumber: getNumber, - time: getBigInt, - txHash: formatHash, - workShare: formatBoolean, -}); -const _formatWoHeader = object({ - coinbase: getAddress, - difficulty: getNumber, - headerHash: formatHash, - location: formatData, - mixHash: formatHash, - nonce: formatData, - number: getNumber, - parentHash: formatHash, - primeTerminusNumber: getNumber, - time: formatData, - txHash: formatHash, -}); -const _formatBlock = object({ - extTransactions: arrayOf((tx) => { - if (typeof tx === 'string') { - return formatHash(tx); - } - return formatExternalTransactionResponse(tx); - }), - hash: formatHash, - header: _formatHeader, - interlinkHashes: arrayOf(formatHash), - order: getNumber, - size: getBigInt, - subManifest: arrayOf(formatData), - totalEntropy: getBigInt, - transactions: arrayOf((tx) => { - if (typeof tx === 'string') { - return formatHash(tx); - } - return formatTransactionResponse(tx); - }), - uncles: allowNull(arrayOf(_formatUncle), []), - woHeader: _formatWoHeader, -}); -function formatBlock(value) { - const result = _formatBlock(value); - result.transactions = value.transactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - if ('originatingTxHash' in tx) { - return formatExternalTransactionResponse(tx); - } - return formatTransactionResponse(tx); - }); - result.extTransactions = value.extTransactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - return formatExternalTransactionResponse(tx); - }); - return result; -} -const _formatReceiptLog = object({ - transactionIndex: getNumber, - blockNumber: getNumber, - transactionHash: formatHash, - address: getAddress, - topics: arrayOf(formatHash), - data: formatData, - index: getNumber, - blockHash: formatHash, -}, { - index: ['logIndex'], -}); -function formatReceiptLog(value) { - return _formatReceiptLog(value); -} -const _formatEtx = object({ - type: allowNull(getNumber, 0), - nonce: allowNull(getNumber), - gasPrice: allowNull(getBigInt), - maxPriorityFeePerGas: allowNull(getBigInt), - maxFeePerGas: allowNull(getBigInt), - gas: allowNull(getBigInt), - value: allowNull(getBigInt, BN_0$2), - input: allowNull(formatData), - to: allowNull(getAddress, null), - accessList: allowNull(accessListify, null), - isCoinbase: allowNull(getNumber, 0), - sender: getAddress, - originatingTxHash: formatHash, - etxIndex: getNumber, - chainId: allowNull(getBigInt, null), - hash: formatHash, -}, { - from: ['sender'], -}); -function formatEtx(value) { - return _formatEtx(value); -} -const _formatTransactionReceipt = object({ - to: allowNull(getAddress, null), - from: allowNull(getAddress, null), - contractAddress: allowNull(getAddress, null), - index: getNumber, - gasUsed: getBigInt, - logsBloom: allowNull(formatData), - blockHash: formatHash, - hash: formatHash, - logs: arrayOf(formatReceiptLog), - blockNumber: getNumber, - cumulativeGasUsed: getBigInt, - effectiveGasPrice: allowNull(getBigInt), - status: allowNull(getNumber), - type: allowNull(getNumber, 0), - etxs: (value) => (value === null ? [] : arrayOf(formatEtx)(value)), -}, { - hash: ['transactionHash'], - index: ['transactionIndex'], -}); -function formatTransactionReceipt(value) { - const result = _formatTransactionReceipt(value); - return result; -} -function formatExternalTransactionResponse(value) { - const result = object({ - hash: formatHash, - type: (value) => { - if (value === '0x' || value == null) { - return 0; - } - return parseInt(value, 16); - }, - accessList: allowNull(accessListify, null), - blockHash: allowNull(formatHash, null), - blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null), - index: allowNull((value) => (value ? BigInt(value) : null), null), - from: allowNull(getAddress, null), - sender: allowNull(getAddress, null), - maxPriorityFeePerGas: allowNull((value) => (value ? BigInt(value) : null)), - maxFeePerGas: allowNull((value) => (value ? BigInt(value) : null)), - gasLimit: allowNull((value) => (value ? BigInt(value) : null), null), - to: allowNull(getAddress, null), - value: allowNull((value) => (value ? BigInt(value) : null), null), - nonce: allowNull((value) => (value ? parseInt(value, 10) : null), null), - creates: allowNull(getAddress, null), - chainId: allowNull((value) => (value ? BigInt(value) : null), null), - isCoinbase: allowNull((value) => (value ? parseInt(value, 10) : null), null), - originatingTxHash: allowNull(formatHash, null), - etxIndex: allowNull((value) => (value ? parseInt(value, 10) : null), null), - etxType: allowNull((value) => value, null), - data: (value) => value, - }, { - data: ['input'], - gasLimit: ['gas'], - index: ['transactionIndex'], - })(value); - // 0x0000... should actually be null - if (result.blockHash && getBigInt(result.blockHash) === BN_0$2) { - result.blockHash = null; - } - return result; -} -function formatTransactionResponse(value) { - // Determine if it is a Quai or Qi transaction based on the type - const transactionType = parseInt(value.type, 16); - let result; - if (transactionType === 0x0 || transactionType === 0x1) { - // QuaiTransactionResponseParams - result = object({ - hash: formatHash, - type: (value) => { - if (value === '0x' || value == null) { - return 0; - } - return parseInt(value, 16); - }, - accessList: allowNull(accessListify, null), - blockHash: allowNull(formatHash, null), - blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null), - index: allowNull((value) => (value ? BigInt(value) : null), null), - from: allowNull(getAddress, null), - sender: allowNull(getAddress, null), - maxPriorityFeePerGas: allowNull((value) => (value ? BigInt(value) : null)), - maxFeePerGas: allowNull((value) => (value ? BigInt(value) : null)), - gasLimit: allowNull((value) => (value ? BigInt(value) : null), null), - to: allowNull(getAddress, null), - value: allowNull((value) => (value ? BigInt(value) : null), null), - nonce: allowNull((value) => (value ? parseInt(value, 10) : null), null), - creates: allowNull(getAddress, null), - chainId: allowNull((value) => (value ? BigInt(value) : null), null), - etxType: allowNull((value) => value, null), - data: (value) => value, - }, { - data: ['input'], - gasLimit: ['gas'], - index: ['transactionIndex'], - })(value); - // Add an access list to supported transaction types - if ((value.type === 0 || value.type === 2) && value.accessList == null) { - result.accessList = []; - } - // Compute the signature - if (value.signature) { - result.signature = Signature.from(value.signature); - // Some backends omit ChainId on legacy transactions, but we can compute it - if (result.chainId == null) { - const chainId = result.signature.legacyChainId; - if (chainId != null) { - result.chainId = chainId; - } - } - } - // 0x0000... should actually be null - if (result.blockHash && getBigInt(result.blockHash) === BN_0$2) { - result.blockHash = null; - } - } - else if (transactionType === 0x2) { - // QiTransactionResponseParams - result = object({ - hash: formatHash, - type: (value) => { - if (value === '0x' || value == null) { - return 0; - } - return parseInt(value, 16); - }, - blockHash: allowNull(formatHash, null), - blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null), - index: allowNull((value) => (value ? BigInt(value) : null), null), - chainId: allowNull((value) => (value ? BigInt(value) : null), null), - signature: (value) => value, - txInputs: allowNull((value) => value.map(_formatTxInput), null), - txOutputs: allowNull((value) => value.map(_formatTxOutput), null), - }, { - index: ['transactionIndex'], - signature: ['utxoSignature'], - txInputs: ['inputs'], - txOutputs: ['outputs'], - })(value); - } - else { - throw new Error('Unknown transaction type'); - } - return result; -} -const _formatTxInput = object({ - txhash: formatTxHash, - index: formatIndex, - pubkey: hexlify, -}, { - txhash: ['PreviousOutPoint', 'TxHash'], - index: ['PreviousOutPoint', 'Index'], - pubkey: ['PubKey'], -}); -function extractTxHash(value) { - if (value && value.TxHash) { - return value.TxHash; - } - throw new Error('Invalid PreviousOutPoint'); -} -function formatTxHash(value) { - return formatHash(extractTxHash(value)); -} -function extractIndex(value) { - if (value && value.Index !== undefined) { - return value.Index; - } - throw new Error('Invalid PreviousOutPoint'); -} -function formatIndex(value) { - return getNumber(extractIndex(value)); -} -const _formatTxOutput = object({ - address: (addr) => hexlify(getAddress(addr)), - denomination: getNumber, -}); - -/** - * Class representing a QiTransaction. - * - * @category Transaction - * @extends {AbstractTransaction} - * @implements {QiTransactionLike} - */ -class QiTransaction extends AbstractTransaction { - #txInputs; - #txOutputs; - /** - * Get transaction inputs. - * - * @returns {TxInput[]} The transaction inputs. - */ - get txInputs() { - return (this.#txInputs ?? []).map((entry) => ({ ...entry })); - } - /** - * Set transaction inputs. - * - * @param {TxInput[] | null} value - The transaction inputs. - * @throws {Error} If the value is not an array. - */ - set txInputs(value) { - if (!Array.isArray(value)) { - throw new Error('txInputs must be an array'); - } - this.#txInputs = value.map((entry) => ({ ...entry })); - } - /** - * Get transaction outputs. - * - * @returns {TxOutput[]} The transaction outputs. - */ - get txOutputs() { - return (this.#txOutputs ?? []).map((output) => ({ ...output })); - } - /** - * Set transaction outputs. - * - * @param {TxOutput[] | null} value - The transaction outputs. - * @throws {Error} If the value is not an array. - */ - set txOutputs(value) { - if (!Array.isArray(value)) { - throw new Error('txOutputs must be an array'); - } - this.#txOutputs = value.map((output) => ({ ...output })); - } - /** - * Get the permuted hash of the transaction as specified by QIP-0010. - * - * @returns {string | null} The transaction hash. - * @throws {Error} If the transaction has no inputs or outputs, or if cross-zone & cross-ledger transactions are not - * supported. - * @see {@link [QIP0010](https://github.com/quai-network/qips/blob/master/qip-0010.md)} - */ - get hash() { - if (this.signature == null) { - return null; - } - if (this.txInputs.length < 1 || this.txOutputs.length < 1) { - throw new Error('Transaction must have at least one input and one output'); - } - const senderAddr = computeAddress(this.txInputs[0].pubkey || ''); - if (!this.destZone || !this.originZone) { - throw new Error(`Invalid zones: origin ${this.originZone} -> destination ${this.destZone} (address: ${senderAddr})`); - } - const isSameLedger = isQiAddress(senderAddr) === isQiAddress(hexlify(this.txOutputs[0].address) || ''); - if (this.isExternal && !isSameLedger) { - throw new Error('Cross-zone & cross-ledger transactions are not supported'); - } - const hexString = this.serialized.startsWith('0x') ? this.serialized.substring(2) : this.serialized; - const dataBuffer = Buffer.from(hexString, 'hex'); - const hashHex = keccak256(dataBuffer); - const hashBuffer = Buffer.from(hashHex.substring(2), 'hex'); - const origin = this.originZone ? parseInt(this.originZone.slice(2), 16) : 0; - hashBuffer[0] = origin; - hashBuffer[1] |= 0x80; - hashBuffer[2] = origin; - hashBuffer[3] |= 0x80; - return '0x' + hashBuffer.toString('hex'); - } - /** - * Get the zone of the sender address. - * - * @returns {Zone | undefined} The origin zone. - */ - get originZone() { - const senderAddr = computeAddress(this.txInputs[0].pubkey || ''); - const zone = getZoneForAddress(senderAddr); - return zone ?? undefined; - } - /** - * Get the zone of the recipient address. - * - * @returns {Zone | undefined} The destination zone. - */ - get destZone() { - const zone = getZoneForAddress(this.txOutputs[0].address); - return zone ?? undefined; - } - /** - * Creates a new Transaction with default values. - */ - constructor() { - super(); - this.#txInputs = []; - this.#txOutputs = []; - } - /** - * Validates the explicit properties and returns a list of compatible transaction types. - * - * @returns {number[]} The compatible transaction types. - */ - inferTypes() { - const types = []; - // Explicit type - if (this.type != null) { - types.push(this.type); - } - else { - types.push(2); - } - types.sort(); - return types; - } - /** - * Create a copy of this transaction. - * - * @returns {QiTransaction} The cloned transaction. - */ - clone() { - return QiTransaction.from(this); - } - /** - * Return a JSON-friendly object. - * - * @returns {QiTransactionLike} The JSON-friendly object. - */ - toJSON() { - const s = (v) => { - if (v == null) { - return null; - } - return v.toString(); - }; - return { - type: this.type, - chainId: s(this.chainId), - signature: this.signature ? this.signature : null, - hash: this.hash, - txInputs: this.txInputs, - txOutputs: this.txOutputs, - }; - } - /** - * Return a protobuf-friendly JSON object. - * - * @param {boolean} [includeSignature=true] - Whether to include the signature. Default is `true` - * @returns {ProtoTransaction} The protobuf-friendly JSON object. - */ - toProtobuf(includeSignature = true) { - const protoTx = { - type: this.type || 2, - chain_id: formatNumber(this.chainId || 0, 'chainId'), - tx_ins: { - tx_ins: this.txInputs.map((input) => ({ - previous_out_point: { - hash: { value: getBytes(input.txhash) }, - index: input.index, - }, - pub_key: getBytes(input.pubkey), - })), - }, - tx_outs: { - tx_outs: this.txOutputs.map((output) => ({ - address: getBytes(output.address), - denomination: output.denomination, - })), - }, - }; - if (this.signature && includeSignature) { - protoTx.signature = getBytes(this.signature); - } - return protoTx; - } - /** - * Create a Transaction from a serialized transaction or a Transaction-like object. - * - * @param {string | QiTransactionLike} tx - The transaction to decode. - * @returns {QiTransaction} The decoded transaction. - * @throws {Error} If the transaction is unsigned and defines a hash. - */ - static from(tx) { - if (typeof tx === 'string') { - const decodedProtoTx = decodeProtoTransaction(getBytes(tx)); - return QiTransaction.fromProto(decodedProtoTx); - } - const result = new QiTransaction(); - if (tx.type != null) { - result.type = tx.type; - } - if (tx.chainId != null) { - result.chainId = tx.chainId; - } - if (tx.signature != null && tx.signature !== '') { - result.signature = tx.signature; - } - if (tx.txInputs != null) { - result.txInputs = tx.txInputs; - } - if (tx.txOutputs != null) { - result.txOutputs = tx.txOutputs; - } - if (tx.hash != null) { - assertArgument(result.isSigned(), 'unsigned transaction cannot define hash', 'tx', tx); - } - return result; - } - /** - * Create a Transaction from a ProtoTransaction object. - * - * @param {ProtoTransaction} protoTx - The transaction to decode. - * @returns {QiTransaction} The decoded transaction. - */ - static fromProto(protoTx) { - const tx = new QiTransaction(); - tx.type = protoTx.type; - tx.chainId = toBigInt(protoTx.chain_id); - if (protoTx.type == 2) { - tx.txInputs = - protoTx.tx_ins?.tx_ins.map((input) => ({ - txhash: hexlify(input.previous_out_point.hash.value), - index: input.previous_out_point.index, - pubkey: hexlify(input.pub_key), - })) ?? []; - tx.txOutputs = - protoTx.tx_outs?.tx_outs.map((output) => ({ - address: hexlify(output.address), - denomination: output.denomination, - })) ?? []; - } - if (protoTx.signature) { - tx.signature = hexlify(protoTx.signature); - } - return tx; - } -} - -/** - * Parses a signature from an array of fields. - * - * @ignore - * @param {string[]} fields - The fields to parse. - * @returns {Signature} The parsed signature. - */ -function _parseSignature(fields) { - let yParity; - try { - yParity = handleNumber(fields[0], 'yParity'); - if (yParity !== 0 && yParity !== 1) { - throw new Error('bad yParity'); - } - } - catch (error) { - assertArgument(false, 'invalid yParity', 'yParity', fields[0]); - } - const r = zeroPadValue(fields[1], 32); - const s = zeroPadValue(fields[2], 32); - return Signature.from({ r, s, yParity }); -} -/** - * Represents a Quai transaction. - * - * @category Transaction - */ -class QuaiTransaction extends AbstractTransaction { - #to; - #data; - #nonce; - #gasLimit; - #gasPrice; - #maxPriorityFeePerGas; - #maxFeePerGas; - #value; - #accessList; - from; - /** - * The `to` address for the transaction or `null` if the transaction is an `init` transaction. - * - * @type {null | string} - */ - get to() { - return this.#to; - } - set to(value) { - if (value !== null) - validateAddress(value); - this.#to = value; - } - /** - * The permuted hash of the transaction as specified by - * [QIP-0010](https://github.com/quai-network/qips/blob/master/qip-0010.md). - * - * @type {null | string} - * @throws {Error} If the transaction is not signed. - */ - get hash() { - if (this.signature == null) - return null; - if (!this.originZone) { - throw new Error('Invalid Zone for from address'); - } - if (!this.from) { - throw new Error('Missing from address'); - } - const isSameLedger = !this.to || isQuaiAddress(this.from) === isQuaiAddress(this.to); - if (this.isExternal && !isSameLedger) { - throw new Error('Cross-zone & cross-ledger transactions are not supported'); - } - const hexString = this.serialized.startsWith('0x') ? this.serialized.substring(2) : this.serialized; - const dataBuffer = Buffer.from(hexString, 'hex'); - const hashHex = keccak256(dataBuffer); - const hashBuffer = Buffer.from(hashHex.substring(2), 'hex'); - const origin = this.originZone ? parseInt(this.originZone.slice(2), 16) : 0; - hashBuffer[0] = origin; - hashBuffer[1] &= 0x7f; - hashBuffer[2] = origin; - hashBuffer[3] &= 0x7f; - return '0x' + hashBuffer.toString('hex'); - } - /** - * The zone of the sender address - * - * @type {Zone | undefined} - */ - get originZone() { - const zone = this.from ? getZoneForAddress(this.from) : undefined; - return zone ?? undefined; - } - /** - * The zone of the recipient address - * - * @type {Zone | undefined} - */ - get destZone() { - const zone = this.to !== null ? getZoneForAddress(this.to || '') : undefined; - return zone ?? undefined; - } - /** - * The transaction nonce. - * - * @type {number} - */ - get nonce() { - return this.#nonce; - } - set nonce(value) { - this.#nonce = getNumber(value, 'value'); - } - /** - * The gas limit. - * - * @type {bigint} - */ - get gasLimit() { - return this.#gasLimit; - } - set gasLimit(value) { - this.#gasLimit = getBigInt(value); - } - /** - * The gas price. - * - * On legacy networks this defines the fee that will be paid. On EIP-1559 networks, this should be `null`. - * - * @type {null | bigint} - */ - get gasPrice() { - const value = this.#gasPrice; - return value; - } - set gasPrice(value) { - this.#gasPrice = value == null ? null : getBigInt(value, 'gasPrice'); - } - /** - * The maximum priority fee per unit of gas to pay. On legacy networks this should be `null`. - * - * @type {null | bigint} - */ - get maxPriorityFeePerGas() { - const value = this.#maxPriorityFeePerGas; - if (value == null) { - return null; - } - return value; - } - set maxPriorityFeePerGas(value) { - this.#maxPriorityFeePerGas = value == null ? null : getBigInt(value, 'maxPriorityFeePerGas'); - } - /** - * The maximum total fee per unit of gas to pay. On legacy networks this should be `null`. - * - * @type {null | bigint} - */ - get maxFeePerGas() { - const value = this.#maxFeePerGas; - if (value == null) { - return null; - } - return value; - } - set maxFeePerGas(value) { - this.#maxFeePerGas = value == null ? null : getBigInt(value, 'maxFeePerGas'); - } - /** - * The transaction data. For `init` transactions this is the deployment code. - * - * @type {string} - */ - get data() { - return this.#data; - } - set data(value) { - this.#data = hexlify(value); - } - /** - * The amount of ether to send in this transactions. - * - * @type {bigint} - */ - get value() { - return this.#value; - } - set value(value) { - this.#value = getBigInt(value, 'value'); - } - /** - * The access list. - * - * An access list permits discounted (but pre-paid) access to bytecode and state variable access within contract - * execution. - * - * @type {null | AccessList} - */ - get accessList() { - const value = this.#accessList || null; - if (value == null) { - return null; - } - return value; - } - set accessList(value) { - this.#accessList = value == null ? null : accessListify(value); - } - /** - * Creates a new Transaction with default values. - * - * @param {string} [from] - The sender address. - */ - constructor(from) { - super(); - this.#to = null; - this.#nonce = 0; - this.#gasLimit = BigInt(0); - this.#gasPrice = null; - this.#maxPriorityFeePerGas = null; - this.#maxFeePerGas = null; - this.#data = '0x'; - this.#value = BigInt(0); - this.#accessList = null; - this.from = from; - } - /** - * Validates the explicit properties and returns a list of compatible transaction types. - * - * @returns {number[]} The compatible transaction types. - */ - inferTypes() { - if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) { - assert(this.maxFeePerGas >= this.maxPriorityFeePerGas, 'priorityFee cannot be more than maxFee', 'BAD_DATA', { value: this }); - } - assert(this.type !== 0 && this.type !== 1, 'transaction type cannot have externalGasLimit, externalGasTip, externalGasPrice, externalData, or externalAccessList', 'BAD_DATA', { value: this }); - const types = []; - // Explicit type - if (this.type != null) { - types.push(this.type); - } - else { - types.push(0); - } - types.sort(); - return types; - } - /** - * Create a copy of this transaction. - * - * @returns {QuaiTransaction} The cloned transaction. - */ - clone() { - return QuaiTransaction.from(this); - } - /** - * Return a JSON-friendly object. - * - * @returns {QuaiTransactionLike} The JSON-friendly object. - */ - toJSON() { - const s = (v) => { - if (v == null) { - return null; - } - return v.toString(); - }; - return { - type: this.type, - to: this.to, - from: this.from, - data: this.data, - nonce: this.nonce, - gasLimit: s(this.gasLimit), - gasPrice: s(this.gasPrice), - maxPriorityFeePerGas: s(this.maxPriorityFeePerGas), - maxFeePerGas: s(this.maxFeePerGas), - value: s(this.value), - chainId: s(this.chainId), - signature: this.signature ? this.signature.toJSON() : null, - hash: this.hash, - accessList: this.accessList, - }; - } - /** - * Return a protobuf-friendly JSON object. - * - * @param {boolean} [includeSignature=true] - Whether to include the signature. Default is `true` - * @returns {ProtoTransaction} The protobuf-friendly JSON object. - */ - toProtobuf(includeSignature = true) { - const protoTx = { - type: this.type || 0, - chain_id: formatNumber(this.chainId || 0, 'chainId'), - nonce: this.nonce || 0, - gas_tip_cap: formatNumber(this.maxPriorityFeePerGas || 0, 'maxPriorityFeePerGas'), - gas_fee_cap: formatNumber(this.maxFeePerGas || 0, 'maxFeePerGas'), - gas: Number(this.gasLimit || 0), - to: this.to != null ? getBytes(this.to) : null, - value: formatNumber(this.value || 0, 'value'), - data: getBytes(this.data || '0x'), - access_list: { access_tuples: [] }, - }; - if (this.signature && includeSignature) { - protoTx.v = formatNumber(this.signature.yParity, 'yParity'); - protoTx.r = toBeArray(this.signature.r); - protoTx.s = toBeArray(this.signature.s); - } - return protoTx; - } - /** - * Create a **Transaction** from a serialized transaction or a Transaction-like object. - * - * @param {string | QuaiTransactionLike} tx - The transaction to decode. - * @returns {QuaiTransaction} The decoded transaction. - */ - static from(tx) { - if (typeof tx === 'string') { - const decodedProtoTx = decodeProtoTransaction(getBytes(tx)); - return QuaiTransaction.fromProto(decodedProtoTx); - } - const result = new QuaiTransaction(tx.from); - if (tx.type != null) { - result.type = tx.type; - } - if (tx.to != null) { - validateAddress(tx.to); - result.to = tx.to; - } - if (tx.nonce != null) { - result.nonce = tx.nonce; - } - if (tx.gasLimit != null) { - result.gasLimit = tx.gasLimit; - } - if (tx.maxPriorityFeePerGas != null) { - result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas; - } - if (tx.maxFeePerGas != null) { - result.maxFeePerGas = tx.maxFeePerGas; - } - if (tx.data != null && tx.data !== '') { - result.data = tx.data; - } - if (tx.value != null) { - result.value = tx.value; - } - if (tx.chainId != null) { - result.chainId = tx.chainId; - } - if (tx.signature != null) { - result.signature = Signature.from(tx.signature); - } - if (tx.accessList != null) { - result.accessList = tx.accessList; - } - if (tx.hash != null) { - assertArgument(result.isSigned(), 'unsigned transaction cannot define hash', 'tx', tx); - } - if (tx.from != null) { - assertArgument(isQuaiAddress(tx.from), 'from address must be a Quai address', 'tx.from', tx.from); - assertArgument((result.from || '').toLowerCase() === (tx.from || '').toLowerCase(), 'from mismatch', 'tx', tx); - result.from = tx.from; - } - return result; - } - /** - * Create a **Transaction** from a ProtoTransaction object. - * - * @param {ProtoTransaction} protoTx - The transaction to decode. - * @returns {QuaiTransaction} The decoded transaction. - */ - static fromProto(protoTx) { - // TODO: Fix this because new tx instance requires a 'from' address - let signature = null; - let address = ''; - if (protoTx.v && protoTx.r && protoTx.s) { - // check if protoTx.r is zero - if (protoTx.r.reduce((acc, val) => (acc += val), 0) == 0) { - throw new Error('Proto decoding only supported for signed transactions'); - } - const signatureFields = [hexlify(protoTx.v), hexlify(protoTx.r), hexlify(protoTx.s)]; - signature = _parseSignature(signatureFields); - const protoTxCopy = structuredClone(protoTx); - delete protoTxCopy.v; - delete protoTxCopy.r; - delete protoTxCopy.s; - delete protoTxCopy.signature; - delete protoTxCopy.etx_sender; - delete protoTxCopy.etx_index; - address = recoverAddress(keccak256(encodeProtoTransaction(protoTxCopy)), signature); - } - const tx = new QuaiTransaction(address); - if (signature) { - tx.signature = signature; - } - if (protoTx.to !== null) { - const toAddr = hexlify(protoTx.to); - tx.to = getAddress(toAddr); - } - tx.type = protoTx.type; - tx.chainId = toBigInt(protoTx.chain_id); - tx.nonce = Number(protoTx.nonce); - tx.maxPriorityFeePerGas = toBigInt(protoTx.gas_tip_cap); - tx.maxFeePerGas = toBigInt(protoTx.gas_fee_cap); - tx.gasLimit = toBigInt(protoTx.gas); - tx.value = protoTx.value !== null ? toBigInt(protoTx.value) : BigInt(0); - tx.data = hexlify(protoTx.data); - tx.accessList = protoTx.access_list.access_tuples.map((tuple) => ({ - address: hexlify(tuple.address), - storageKeys: tuple.storage_key.map((key) => hexlify(key)), - })); - return tx; - } -} - -const BN_0$1 = BigInt(0); -/** - * Get the value if it is not null or undefined. - * - * @ignore - * @param {undefined | null | T} value - The value to check. - * @returns {null | T} The value if not null or undefined, otherwise null. - */ -function getValue(value) { - if (value == null) { - return null; - } - return value; -} -/** - * Convert a value to a JSON-friendly string. - * - * @ignore - * @param {null | bigint | string} value - The value to convert. - * @returns {null | string} The JSON-friendly string or null. - */ -function toJson(value) { - if (value == null) { - return null; - } - return value.toString(); -} -/** - * A **FeeData** wraps all the fee-related values associated with the network. - * - * @category Providers - */ -class FeeData { - /** - * The gas price for legacy networks. - */ - gasPrice; - /** - * The maximum fee to pay per gas. - * - * The base fee per gas is defined by the network and based on congestion, increasing the cost during times of heavy - * load and lowering when less busy. - * - * The actual fee per gas will be the base fee for the block and the priority fee, up to the max fee per gas. - * - * This will be `null` on legacy networks (i.e. [pre-EIP-1559](https://eips.ethereum.org/EIPS/eip-1559)) - */ - maxFeePerGas; - /** - * The additional amount to pay per gas to encourage a validator to include the transaction. - * - * The purpose of this is to compensate the validator for the adjusted risk for including a given transaction. - * - * This will be `null` on legacy networks (i.e. [pre-EIP-1559](https://eips.ethereum.org/EIPS/eip-1559)) - */ - maxPriorityFeePerGas; - /** - * Creates a new FeeData for `gasPrice`, `maxFeePerGas` and `maxPriorityFeePerGas`. - * - * @param {null | bigint} [gasPrice] - The gas price. - * @param {null | bigint} [maxFeePerGas] - The maximum fee per gas. - * @param {null | bigint} [maxPriorityFeePerGas] - The maximum priority fee per gas. - */ - constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { - defineProperties(this, { - gasPrice: getValue(gasPrice), - maxFeePerGas: getValue(maxFeePerGas), - maxPriorityFeePerGas: getValue(maxPriorityFeePerGas), - }); - } - /** - * Returns a JSON-friendly value. - * - * @returns {any} The JSON-friendly value. - */ - toJSON() { - const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; - return { - _type: 'FeeData', - gasPrice: toJson(gasPrice), - maxFeePerGas: toJson(maxFeePerGas), - maxPriorityFeePerGas: toJson(maxPriorityFeePerGas), - }; - } -} -/** - * Determines the address from a transaction request. - * - * @param {TransactionRequest} tx - The transaction request. - * @returns {AddressLike} The address from the transaction request. - * @throws {Error} If unable to determine the address. - */ -function addressFromTransactionRequest(tx) { - if ('from' in tx && !!tx.from) { - return tx.from; - } - if ('txInputs' in tx && !!tx.txInputs) { - return computeAddress(tx.txInputs[0].pubkey); - } - if ('to' in tx && !!tx.to) { - return tx.to; - } - throw new Error('Unable to determine address from transaction inputs, from or to field'); -} -/** - * Returns a copy of `req` with all properties coerced to their strict types. - * - * @category Providers - * @param {TransactionRequest} req - The transaction request to copy. - * @returns {PreparedTransactionRequest} The prepared transaction request. - * @throws {Error} If the request is invalid. - */ -function copyRequest(req) { - const result = {}; - // These could be addresses or Addressables - if ('to' in req && req.to) { - result.to = req.to; - } - if ('from' in req && req.from) { - result.from = req.from; - } - if ('data' in req && req.data) { - result.data = hexlify(req.data); - } - const bigIntKeys = 'chainId,gasLimit,gasPrice,maxFeePerGas,maxPriorityFeePerGas,value'.split(/,/); - for (const key of bigIntKeys) { - if (!(key in req) || req[key] == null) { - continue; - } - result[key] = getBigInt(req[key], `request.${key}`); - } - const numberKeys = 'type,nonce'.split(/,/); - for (const key of numberKeys) { - if (!(key in req) || req[key] == null) { - continue; - } - result[key] = getNumber(req[key], `request.${key}`); - } - if ('accessList' in req && req.accessList) { - result.accessList = accessListify(req.accessList); - } - if ('blockTag' in req) { - result.blockTag = req.blockTag; - } - if ('customData' in req) { - result.customData = req.customData; - } - if ('txInputs' in req && req.txInputs) { - result.txInputs = req.txInputs.map((entry) => ({ ...entry })); - } - if ('txOutputs' in req && req.txOutputs) { - result.txOutputs = req.txOutputs.map((entry) => ({ ...entry })); - } - return result; -} -/** - * Represents the header of a block. - * - * @category Providers - */ -class BlockHeader { - baseFeePerGas; - efficiencyScore; - etxEligibleSlices; - etxSetRoot; - evmRoot; - expansionNumber; - extRollupRoot; - extTransactionsRoot; - extraData; - gasLimit; - gasUsed; - hash; - interlinkRootHash; - manifestHash; - number; - parentDeltaS; - parentEntropy; - parentHash; - parentUncledS; - parentUncledSubDeltaS; - primeTerminus; - receiptsRoot; - sha3Uncles; - size; - thresholdCount; - transactionsRoot; - uncledS; - utxoRoot; - constructor(params) { - this.baseFeePerGas = params.baseFeePerGas; - this.efficiencyScore = params.efficiencyScore; - this.etxEligibleSlices = params.etxEligibleSlices; - this.etxSetRoot = params.etxSetRoot; - this.evmRoot = params.evmRoot; - this.expansionNumber = params.expansionNumber; - this.extRollupRoot = params.extRollupRoot; - this.extTransactionsRoot = params.extTransactionsRoot; - this.extraData = params.extraData; - this.gasLimit = params.gasLimit; - this.gasUsed = params.gasUsed; - this.hash = params.hash; - this.interlinkRootHash = params.interlinkRootHash; - this.manifestHash = params.manifestHash; - this.number = params.number; - this.parentDeltaS = params.parentDeltaS; - this.parentEntropy = params.parentEntropy; - this.parentHash = params.parentHash; - this.parentUncledS = params.parentUncledS; - this.parentUncledSubDeltaS = params.parentUncledSubDeltaS; - this.primeTerminus = params.primeTerminus; - this.receiptsRoot = params.receiptsRoot; - this.sha3Uncles = params.sha3Uncles; - this.size = params.size; - this.thresholdCount = params.thresholdCount; - this.transactionsRoot = params.transactionsRoot; - this.uncledS = params.uncledS; - this.utxoRoot = params.utxoRoot; - } - toJSON() { - return { - baseFeePerGas: this.baseFeePerGas, - efficiencyScore: this.efficiencyScore, - etxEligibleSlices: this.etxEligibleSlices, - etxSetRoot: this.etxSetRoot, - evmRoot: this.evmRoot, - expansionNumber: this.expansionNumber, - extRollupRoot: this.extRollupRoot, - extTransactionsRoot: this.extTransactionsRoot, - extraData: this.extraData, - gasLimit: this.gasLimit, - gasUsed: this.gasUsed, - hash: this.hash, - interlinkRootHash: this.interlinkRootHash, - manifestHash: this.manifestHash, - number: this.number, - parentDeltaS: this.parentDeltaS, - parentEntropy: this.parentEntropy, - parentHash: this.parentHash, - parentUncledS: this.parentUncledS, - parentUncledSubDeltaS: this.parentUncledSubDeltaS, - primeTerminus: this.primeTerminus, - receiptsRoot: this.receiptsRoot, - sha3Uncles: this.sha3Uncles, - size: this.size, - thresholdCount: this.thresholdCount, - transactionsRoot: this.transactionsRoot, - uncledS: this.uncledS, - utxoRoot: this.utxoRoot, - }; - } -} -/** - * Represents the header of a work object. - * - * @category Providers - */ -class WoHeader { - difficulty; - headerHash; - location; - mixHash; - nonce; - number; - parentHash; - time; - txHash; - /** - * Creates a new WoHeader instance. - * - * @param {WoHeaderParams} params - The parameters for the WoHeader. - */ - constructor(params) { - this.difficulty = params.difficulty; - this.headerHash = params.headerHash; - this.location = params.location; - this.mixHash = params.mixHash; - this.nonce = params.nonce; - this.number = params.number; - this.parentHash = params.parentHash; - this.time = params.time; - this.txHash = params.txHash; - } - toJSON() { - return { - difficulty: this.difficulty, - headerHash: this.headerHash, - location: this.location, - mixHash: this.mixHash, - nonce: this.nonce, - number: this.number, - parentHash: this.parentHash, - time: this.time, - txHash: this.txHash, - }; - } -} -/** - * A **Block** represents the data associated with a full block on Ethereum. - * - * @category Providers - */ -class Block { - #extTransactions; - hash; - header; - interlinkHashes; // New parameter - order; - size; - subManifest; - totalEntropy; - #transactions; - uncles; - woHeader; // New nested parameter structure - /** - * The provider connected to the block used to fetch additional details if necessary. - */ - provider; - /** - * Create a new **Block** object. - * - * This should generally not be necessary as the unless implementing a low-level library. - * - * @param {BlockParams} block - The block parameters. - * @param {Provider} provider - The provider. - */ - constructor(block, provider) { - this.#transactions = block.transactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - if ('originatingTxHash' in tx) { - return new ExternalTransactionResponse(tx, provider); - } - if ('from' in tx) { - return new QuaiTransactionResponse(tx, provider); - } - return new QiTransactionResponse(tx, provider); - }); - this.#extTransactions = block.extTransactions.map((tx) => { - if (typeof tx !== 'string') { - return new ExternalTransactionResponse(tx, provider); - } - return tx; - }); - this.hash = block.hash; - this.header = new BlockHeader(block.header); - this.interlinkHashes = block.interlinkHashes; - this.order = block.order; - this.size = block.size; - this.subManifest = block.subManifest; - this.totalEntropy = block.totalEntropy; - this.uncles = block.uncles; - this.woHeader = new WoHeader(block.woHeader); - this.provider = provider; - } - /** - * Returns the list of transaction hashes, in the order they were executed within the block. - * - * @returns {ReadonlyArray} The list of transaction hashes. - */ - get transactions() { - return this.#transactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - return tx.hash; - }); - } - /** - * Returns the list of extended transaction hashes, in the order they were executed within the block. - * - * @returns {ReadonlyArray} The list of extended transaction hashes. - */ - get extTransactions() { - return this.#extTransactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - return tx.hash; - }); - } - /** - * Returns the complete transactions, in the order they were executed within the block. - * - * This is only available for blocks which prefetched transactions, by passing `true` to `prefetchTxs` into - * {@link Provider.getBlock | **getBlock**}. - * - * @returns {TransactionResponse[]} The list of prefetched transactions. - * @throws {Error} If the transactions were not prefetched. - */ - get prefetchedTransactions() { - const txs = this.#transactions.slice(); - // Doesn't matter... - if (txs.length === 0) { - return []; - } - // Make sure we prefetched the transactions - assert(typeof txs[0] === 'object', 'transactions were not prefetched with block request', 'UNSUPPORTED_OPERATION', { - operation: 'transactionResponses()', - }); - return txs; - } - /** - * Returns the complete extended transactions, in the order they were executed within the block. - * - * This is only available for blocks which prefetched transactions, by passing `true` to `prefetchTxs` into - * {@link Provider.getBlock | **getBlock**}. - * - * @returns {TransactionResponse[]} The list of prefetched extended transactions. - * @throws {Error} If the transactions were not prefetched. - */ - get prefetchedExtTransactions() { - const txs = this.#extTransactions.slice(); - // Doesn't matter... - if (txs.length === 0) { - return []; - } - // Make sure we prefetched the transactions - assert(typeof txs[0] === 'object', 'transactions were not prefetched with block request', 'UNSUPPORTED_OPERATION', { - operation: 'transactionResponses()', - }); - return txs; - } - /** - * Returns a JSON-friendly value. - * - * @returns {any} The JSON-friendly value. - */ - toJSON() { - const { hash, header, interlinkHashes, order, size, subManifest, totalEntropy, uncles, woHeader } = this; - // Using getters to retrieve the transactions and extTransactions - const transactions = this.transactions; - const extTransactions = this.extTransactions; - return { - _type: 'Block', - hash, - header: header.toJSON(), - interlinkHashes, - order, - size: toJson(size), - subManifest, - totalEntropy: toJson(totalEntropy), - uncles, - woHeader: woHeader.toJSON(), - transactions, - extTransactions, // Includes the extended transaction hashes or full transactions based on the prefetched data - }; - } - [Symbol.iterator]() { - let index = 0; - const txs = this.transactions; - return { - next: () => { - if (index < this.length) { - return { - value: txs[index++], - done: false, - }; - } - return { value: undefined, done: true }; - }, - }; - } - /** - * The number of transactions in this block. - * - * @returns {number} The number of transactions. - */ - get length() { - return this.#transactions.length; - } - /** - * The [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) this block was - * included at. - * - * @returns {null | Date} The date this block was included at, or null if the timestamp is not available. - */ - get date() { - const timestampHex = this.woHeader.time; - if (!timestampHex) { - return null; - } - const timestamp = parseInt(timestampHex, 16); - return new Date(timestamp * 1000); - } - /** - * Get the transaction at `index` within this block. - * - * @param {number | string} indexOrHash - The index or hash of the transaction. - * @returns {Promise} A promise resolving to the transaction. - * @throws {Error} If the transaction is not found. - */ - async getTransaction(indexOrHash) { - // Find the internal value by its index or hash - let tx = undefined; - if (typeof indexOrHash === 'number') { - tx = this.#transactions[indexOrHash]; - } - else { - const hash = indexOrHash.toLowerCase(); - for (const v of this.#transactions) { - if (typeof v === 'string') { - if (v !== hash) { - continue; - } - tx = v; - break; - } - else { - if (v.hash === hash) { - continue; - } - tx = v; - break; - } - } - } - if (tx == null) { - throw new Error('no such tx'); - } - if (typeof tx === 'string') { - return await this.provider.getTransaction(tx); - } - else { - return tx; - } - } - /** - * Get the extended transaction at `index` within this block. - * - * @param {number | string} indexOrHash - The index or hash of the extended transaction. - * @returns {Promise} A promise resolving to the extended transaction. - * @throws {Error} If the extended transaction is not found. - */ - async getExtTransaction(indexOrHash) { - // Find the internal value by its index or hash - let tx = undefined; - if (typeof indexOrHash === 'number') { - tx = this.#extTransactions[indexOrHash]; - } - else { - const hash = indexOrHash.toLowerCase(); - for (const v of this.#extTransactions) { - if (typeof v === 'string') { - if (v !== hash) { - continue; - } - tx = v; - break; - } - else { - if (v.hash === hash) { - continue; - } - tx = v; - break; - } - } - } - if (tx == null) { - throw new Error('no such tx'); - } - if (typeof tx === 'string') { - throw new Error("External Transaction isn't prefetched"); - } - else { - return tx; - } - } - /** - * If a **Block** was fetched with a request to include the transactions this will allow synchronous access to those - * transactions. - * - * If the transactions were not prefetched, this will throw. - * - * @param {number | string} indexOrHash - The index or hash of the transaction. - * @returns {TransactionResponse} The transaction. - * @throws {Error} If the transaction is not found. - */ - getPrefetchedTransaction(indexOrHash) { - const txs = this.prefetchedTransactions; - if (typeof indexOrHash === 'number') { - return txs[indexOrHash]; - } - indexOrHash = indexOrHash.toLowerCase(); - for (const tx of txs) { - if (tx.hash === indexOrHash) { - return tx; - } - } - assertArgument(false, 'no matching transaction', 'indexOrHash', indexOrHash); - } - /** - * Returns true if this block been mined. This provides a type guard for all properties on a - * {@link MinedBlock | **MinedBlock**}. - * - * @returns {boolean} True if the block has been mined. - */ - isMined() { - return !!this.header.hash; - } - /** - * @ignore - */ - orphanedEvent() { - if (!this.isMined() || !this.woHeader.number) { - throw new Error(''); - } - return createOrphanedBlockFilter({ - hash: this.header.hash, - number: parseInt(this.woHeader.number, 16), - }); - } -} -////////////////////// -// Log -/** - * A **Log** in Ethereum represents an event that has been included in a transaction using the `LOG*` opcodes, which are - * most commonly used by Solidity's emit for announcing events. - * - * @category Providers - */ -class Log { - /** - * The provider connected to the log used to fetch additional details if necessary. - */ - provider; - /** - * The transaction hash of the transaction this log occurred in. Use the - * {@link Log.getTransaction | **Log.getTransaction**} to get the - * {@link TransactionResponse | **TransactionResponse}. - */ - transactionHash; - /** - * The block hash of the block this log occurred in. Use the {@link Log.getBlock | **Log.getBlock**} to get the - * {@link Block | **Block**}. - */ - blockHash; - /** - * The block number of the block this log occurred in. It is preferred to use the {@link Block.hash | **Block.hash**} - * when fetching the related {@link Block | **Block**}, since in the case of an orphaned block, the block at that - * height may have changed. - */ - blockNumber; - /** - * If the **Log** represents a block that was removed due to an orphaned block, this will be true. - * - * This can only happen within an orphan event listener. - */ - removed; - /** - * The address of the contract that emitted this log. - */ - address; - /** - * The data included in this log when it was emitted. - */ - data; - /** - * The indexed topics included in this log when it was emitted. - * - * All topics are included in the bloom filters, so they can be efficiently filtered using the - * {@link Provider.getLogs | **Provider.getLogs**} method. - */ - topics; - /** - * The index within the block this log occurred at. This is generally not useful to developers, but can be used with - * the various roots to proof inclusion within a block. - */ - index; - /** - * The index within the transaction of this log. - */ - transactionIndex; - /** - * @ignore - */ - constructor(log, provider) { - this.provider = provider; - const topics = Object.freeze(log.topics.slice()); - defineProperties(this, { - transactionHash: log.transactionHash, - blockHash: log.blockHash, - blockNumber: log.blockNumber, - removed: log.removed, - address: log.address, - data: log.data, - topics, - index: log.index, - transactionIndex: log.transactionIndex, - }); - } - /** - * Returns a JSON-compatible object. - */ - toJSON() { - const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this; - return { - _type: 'log', - address, - blockHash, - blockNumber, - data, - index, - removed, - topics, - transactionHash, - transactionIndex, - }; - } - /** - * Returns the block that this log occurred in. - * - * @param {Shard} shard - The shard to fetch the block from. - * @returns {Promise} A promise resolving to the block. - */ - async getBlock(shard) { - const block = await this.provider.getBlock(shard, this.blockHash); - assert(!!block, 'failed to find transaction', 'UNKNOWN_ERROR', {}); - return block; - } - /** - * Returns the transaction that this log occurred in. - * - * @returns {Promise} A promise resolving to the transaction. - */ - async getTransaction() { - const tx = await this.provider.getTransaction(this.transactionHash); - assert(!!tx, 'failed to find transaction', 'UNKNOWN_ERROR', {}); - return tx; - } - /** - * Returns the transaction receipt fot the transaction that this log occurred in. - * - * @returns {Promise} A promise resolving to the transaction receipt. - */ - async getTransactionReceipt() { - const receipt = await this.provider.getTransactionReceipt(this.transactionHash); - assert(!!receipt, 'failed to find transaction receipt', 'UNKNOWN_ERROR', {}); - return receipt; - } - /** - * @ignore - */ - removedEvent() { - return createRemovedLogFilter(this); - } -} -////////////////////// -// Transaction Receipt -function zoneFromHash(hash) { - return toZone(hash.slice(0, 4)); -} -/** - * A **TransactionReceipt** includes additional information about a transaction that is only available after it has been - * mined. - * - * @category Providers - */ -class TransactionReceipt { - /** - * The provider connected to the log used to fetch additional details if necessary. - */ - provider; - /** - * The address the transaction was sent to. - */ - to; - /** - * The sender of the transaction. - */ - from; - /** - * The address of the contract if the transaction was directly responsible for deploying one. - * - * This is non-null **only** if the `to` is empty and the `data` was successfully executed as initcode. - */ - contractAddress; - /** - * The transaction hash. - */ - hash; - /** - * The index of this transaction within the block transactions. - */ - index; - /** - * The block hash of the {@link Block | **Block**} this transaction was included in. - */ - blockHash; - /** - * The block number of the {@link Block | **Block**} this transaction was included in. - */ - blockNumber; - /** - * The bloom filter bytes that represent all logs that occurred within this transaction. This is generally not - * useful for most developers, but can be used to validate the included logs. - */ - logsBloom; - /** - * The actual amount of gas used by this transaction. - * - * When creating a transaction, the amount of gas that will be used can only be approximated, but the sender must - * pay the gas fee for the entire gas limit. After the transaction, the difference is refunded. - */ - gasUsed; - /** - * The amount of gas used by all transactions within the block for this and all transactions with a lower `index`. - * - * This is generally not useful for developers but can be used to validate certain aspects of execution. - */ - cumulativeGasUsed; - /** - * The actual gas price used during execution. - * - * Due to the complexity of [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) this value can only be caluclated - * after the transaction has been mined, snce the base fee is protocol-enforced. - */ - gasPrice; - /** - * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction type. - */ - type; - //readonly byzantium!: boolean; - /** - * The status of this transaction, indicating success (i.e. `1`) or a revert (i.e. `0`). - * - * This is available in post-byzantium blocks, but some backends may backfill this value. - */ - status; - /** - * The root hash of this transaction. - * - * This is no present and was only included in pre-byzantium blocks, but could be used to validate certain parts of - * the receipt. - */ - #logs; - etxs = []; - /** - * @ignore - */ - constructor(tx, provider) { - this.#logs = Object.freeze(tx.logs.map((log) => { - return new Log(log, provider); - })); - let gasPrice = BN_0$1; - if (tx.effectiveGasPrice != null) { - gasPrice = tx.effectiveGasPrice; - } - else if (tx.gasPrice != null) { - gasPrice = tx.gasPrice; - } - const etxs = tx.etxs - ? tx.etxs.map((etx) => { - const safeConvert = (value, name) => { - try { - if (value != null) { - return BigInt(value); - } - return null; - } - catch (error) { - console.error(`Conversion to BigInt failed for ${name}: ${value}, error: ${error}`); - return null; - } - }; - return { - type: etx.type, - nonce: etx.nonce, - gasPrice: safeConvert(etx.gasPrice, 'gasPrice'), - maxPriorityFeePerGas: safeConvert(etx.maxPriorityFeePerGas, 'maxPriorityFeePerGas'), - maxFeePerGas: safeConvert(etx.maxFeePerGas, 'maxFeePerGas'), - gas: safeConvert(etx.gas, 'gas'), - value: safeConvert(etx.value, 'value'), - input: etx.input, - to: etx.to, - accessList: etx.accessList, - chainId: safeConvert(etx.chainId, 'chainId'), - sender: etx.sender, - hash: etx.hash, - isCoinbase: etx.isCoinbase, - originatingTxHash: etx.originatingTxHash, - etxIndex: etx.etxIndex, - }; - }) - : []; - defineProperties(this, { - provider, - to: tx.to, - from: tx.from, - contractAddress: tx.contractAddress, - hash: tx.hash, - index: tx.index, - blockHash: tx.blockHash, - blockNumber: tx.blockNumber, - logsBloom: tx.logsBloom, - gasUsed: tx.gasUsed, - cumulativeGasUsed: tx.cumulativeGasUsed, - gasPrice, - etxs: etxs, - type: tx.type, - status: tx.status, - }); - } - /** - * The logs for this transaction. - */ - get logs() { - return this.#logs; - } - /** - * Returns a JSON-compatible representation. - */ - toJSON() { - const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium, - status, etxs, } = this; - return { - _type: 'TransactionReceipt', - blockHash, - blockNumber, - contractAddress, - cumulativeGasUsed: toJson(this.cumulativeGasUsed), - from, - gasPrice: toJson(this.gasPrice), - gasUsed: toJson(this.gasUsed), - hash, - index, - logs, - logsBloom, - status, - to, - etxs: etxs ?? [], - }; - } - /** - * @ignore - */ - get length() { - return this.logs.length; - } - [Symbol.iterator]() { - let index = 0; - return { - next: () => { - if (index < this.length) { - return { value: this.logs[index++], done: false }; - } - return { value: undefined, done: true }; - }, - }; - } - /** - * The total fee for this transaction, in wei. - */ - get fee() { - return this.gasUsed * this.gasPrice; - } - /** - * Resolves to the block this transaction occurred in. - * - * @param {Shard} shard - The shard to fetch the block from. - * @returns {Promise} A promise resolving to the block. - * @throws {Error} If the block is not found. - */ - async getBlock(shard) { - const block = await this.provider.getBlock(shard, this.blockHash); - if (block == null) { - throw new Error('TODO'); - } - return block; - } - /** - * Resolves to the transaction this transaction occurred in. - * - * @returns {Promise} A promise resolving to the transaction. - * @throws {Error} If the transaction is not found. - */ - async getTransaction() { - const tx = await this.provider.getTransaction(this.hash); - if (tx == null) { - throw new Error('TODO'); - } - return tx; - } - /** - * Resolves to the return value of the execution of this transaction. - * - * Support for this feature is limited, as it requires an archive node with the `debug_` or `trace_` API enabled. - * - * @returns {Promise} A promise resolving to the return value of the transaction. - * @throws {Error} If the transaction is not found. - */ - async getResult() { - return await this.provider.getTransactionResult(this.hash); - } - /** - * Resolves to the number of confirmations this transaction has. - * - * @returns {Promise} A promise resolving to the number of confirmations. - * @throws {Error} If the block is not found. - */ - async confirmations() { - const zone = zoneFromHash(this.hash); - return (await this.provider.getBlockNumber(toShard(zone))) - this.blockNumber + 1; - } - /** - * @ignore - */ - removedEvent() { - return createRemovedTransactionFilter(this); - } - /** - * @ignore - */ - reorderedEvent(other) { - assert(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", 'UNSUPPORTED_OPERATION', { - operation: 'reorderedEvent(other)', - }); - return createReorderedTransactionFilter(this, other); - } -} -class ExternalTransactionResponse { - /** - * The provider this is connected to, which will influence how its methods will resolve its async inspection - * methods. - */ - provider; - /** - * The block number of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockNumber; - /** - * The blockHash of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockHash; - /** - * The index within the block that this transaction resides at. - */ - index; - /** - * The transaction hash. - */ - hash; - /** - * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy - * transactions types. - */ - type; - /** - * The receiver of this transaction. - * - * If `null`, then the transaction is an initcode transaction. This means the result of executing the - * {@link ExternalTransactionResponse.data | **data** } will be deployed as a new contract on chain (assuming it does - * not revert) and the address may be computed using [getCreateAddress](../functions/getCreateAddress). - */ - to; - /** - * The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and - * the {@link QuaiTransactionResponse.signature | **signature** } using ecrecover. - */ - from; - /** - * The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender - * are explicitly ordered. - * - * When sending a transaction, this must be equal to the number of transactions ever sent by - * {@link ExternalTransactionResponse.from | **from** }. - */ - nonce; - /** - * The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is - * reverted and the sender is charged for the full amount, despite not state changes being made. - */ - gasLimit; - /** - * The data. - */ - data; - /** - * The value, in wei. Use [formatEther](../functions/formatEther) to format this value as ether. - */ - value; - /** - * The chain ID. - */ - chainId; - /** - * The signature. - */ - signature; - /** - * The [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list for transaction types that support it, - * otherwise `null`. - */ - accessList; - etxType; - isCoinbase; - originatingTxHash; - sender; - etxIndex; - startBlock; - /** - * @ignore - */ - constructor(tx, provider) { - this.provider = provider; - this.blockNumber = tx.blockNumber != null ? tx.blockNumber : null; - this.blockHash = tx.blockHash != null ? tx.blockHash : null; - this.hash = tx.hash; - this.index = tx.index; - this.type = tx.type; - this.from = tx.from; - this.to = tx.to || null; - this.gasLimit = tx.gasLimit; - this.nonce = tx.nonce; - this.data = tx.data; - this.value = tx.value; - this.chainId = tx.chainId; - this.signature = tx.signature; - this.accessList = tx.accessList != null ? tx.accessList : null; - this.startBlock = -1; - this.originatingTxHash = tx.originatingTxHash != null ? tx.originatingTxHash : null; - this.isCoinbase = tx.isCoinbase != null ? tx.isCoinbase : null; - this.etxType = tx.etxType != null ? tx.etxType : null; - this.sender = tx.sender; - this.etxIndex = tx.etxIndex; - } - /** - * Returns a JSON-compatible representation of this transaction. - */ - toJSON() { - const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, etxType, isCoinbase, originatingTxHash, etxIndex, sender, } = this; - const result = { - _type: 'TransactionReceipt', - accessList, - blockNumber, - blockHash, - chainId: toJson(this.chainId), - data, - from, - gasLimit: toJson(this.gasLimit), - hash, - nonce, - signature, - to, - index, - type, - etxType, - isCoinbase, - originatingTxHash, - sender, - etxIndex, - value: toJson(this.value), - }; - return result; - } - replaceableTransaction(startBlock) { - assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock); - const tx = new ExternalTransactionResponse(this, this.provider); - tx.startBlock = startBlock; - return tx; - } -} -/** - * A **QuaiTransactionResponse** includes all properties about a Quai transaction that was sent to the network, which - * may or may not be included in a block. - * - * The {@link TransactionResponse.isMined | **TransactionResponse.isMined**} can be used to check if the transaction has - * been mined as well as type guard that the otherwise possibly `null` properties are defined. - * - * @category Providers - */ -class QuaiTransactionResponse { - /** - * The provider this is connected to, which will influence how its methods will resolve its async inspection - * methods. - */ - provider; - /** - * The block number of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockNumber; - /** - * The blockHash of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockHash; - /** - * The index within the block that this transaction resides at. - */ - index; - /** - * The transaction hash. - */ - hash; - /** - * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy - * transactions types. - */ - type; - /** - * The receiver of this transaction. - * - * If `null`, then the transaction is an initcode transaction. This means the result of executing the - * {@link QuaiTransactionResponse.data | **data** } will be deployed as a new contract on chain (assuming it does not - * revert) and the address may be computed using [getCreateAddress](../functions/getCreateAddress). - */ - to; - /** - * The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and - * the {@link QuaiTransactionResponse.signature | **signature** } using ecrecover. - */ - from; - /** - * The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender - * are explicitly ordered. - * - * When sending a transaction, this must be equal to the number of transactions ever sent by - * {@link QuaiTransactionResponse.from | **from** }. - */ - nonce; - /** - * The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is - * reverted and the sender is charged for the full amount, despite not state changes being made. - */ - gasLimit; - /** - * The maximum priority fee (per unit of gas) to allow a validator to charge the sender. This is inclusive of the - * {@link QuaiTransactionResponse.maxFeePerGas | **maxFeePerGas** }. - */ - maxPriorityFeePerGas; - /** - * The maximum fee (per unit of gas) to allow this transaction to charge the sender. - */ - maxFeePerGas; - /** - * The data. - */ - data; - /** - * The value, in wei. Use [formatEther](../functions/formatEther) to format this value as ether. - */ - value; - /** - * The chain ID. - */ - chainId; - /** - * The signature. - */ - signature; - /** - * The [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list for transaction types that support it, - * otherwise `null`. - */ - accessList; - etxType; - sender; - originatingTxHash; - startBlock; - /** - * @ignore - */ - constructor(tx, provider) { - this.provider = provider; - this.blockNumber = tx.blockNumber != null ? tx.blockNumber : null; - this.blockHash = tx.blockHash != null ? tx.blockHash : null; - this.hash = tx.hash; - this.index = tx.index; - this.type = tx.type; - this.from = tx.from; - this.to = tx.to || null; - this.gasLimit = tx.gasLimit; - this.nonce = tx.nonce; - this.data = tx.data; - this.value = tx.value; - this.maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? tx.maxPriorityFeePerGas : null; - this.maxFeePerGas = tx.maxFeePerGas != null ? tx.maxFeePerGas : null; - this.chainId = tx.chainId; - this.signature = tx.signature; - this.accessList = tx.accessList != null ? tx.accessList : null; - this.startBlock = -1; - this.etxType = tx.etxType != null ? tx.etxType : null; - } - /** - * Returns a JSON-compatible representation of this transaction. - */ - toJSON() { - const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList } = this; - const result = { - _type: 'TransactionReceipt', - accessList, - blockNumber, - blockHash, - chainId: toJson(this.chainId), - data, - from, - gasLimit: toJson(this.gasLimit), - hash, - maxFeePerGas: toJson(this.maxFeePerGas), - maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), - nonce, - signature, - to, - index, - type, - value: toJson(this.value), - }; - return result; - } - /** - * Resolves to the Block that this transaction was included in. - * - * This will return null if the transaction has not been included yet. - * - * @param {Shard} shard - The shard to fetch the block from. - * @returns {null | Promise} A promise resolving to the block. - */ - async getBlock(shard) { - let blockNumber = this.blockNumber; - if (blockNumber == null) { - const tx = await this.getTransaction(); - if (tx) { - blockNumber = tx.blockNumber; - } - } - if (blockNumber == null) { - return null; - } - const block = this.provider.getBlock(shard, blockNumber); - if (block == null) { - throw new Error('TODO'); - } - return block; - } - /** - * Resolves to this transaction being re-requested from the provider. This can be used if you have an unmined - * transaction and wish to get an up-to-date populated instance. - * - * @returns {null | Promise} A promise resolving to the transaction, or null if not found. - */ - async getTransaction() { - const transaction = this.provider.getTransaction(this.hash); - if (transaction instanceof QuaiTransactionResponse) { - return transaction; - } - else { - return null; - } - } - /** - * Resolve to the number of confirmations this transaction has. - * - * @returns {Promise} A promise resolving to the number of confirmations. - * @throws {Error} If the block is not found. - */ - async confirmations() { - const zone = zoneFromHash(this.hash); - if (this.blockNumber == null) { - const { tx, blockNumber } = await resolveProperties({ - tx: this.getTransaction(), - blockNumber: this.provider.getBlockNumber(toShard(zone)), - }); - // Not mined yet... - if (tx == null || tx.blockNumber == null) { - return 0; - } - return blockNumber - tx.blockNumber + 1; - } - const blockNumber = await this.provider.getBlockNumber(toShard(zone)); - return blockNumber - this.blockNumber + 1; - } - /** - * Resolves once this transaction has been mined and has `confirms` blocks including it (default: `1`) with an - * optional `timeout`. - * - * This can resolve to `null` only if `confirms` is `0` and the transaction has not been mined, otherwise this will - * wait until enough confirmations have completed. - * - * @param {number} [_confirms] - The number of confirmations to wait for. - * @param {number} [_timeout] - The number of milliseconds to wait before rejecting. - * @returns {Promise} A promise resolving to the transaction receipt. - * @throws {Error} If the transaction was replaced, repriced, or cancelled. - */ - async wait(_confirms, _timeout) { - const confirms = _confirms == null ? 1 : _confirms; - const timeout = _timeout == null ? 0 : _timeout; - let startBlock = this.startBlock; - let nextScan = -1; - let stopScanning = startBlock === -1 ? true : false; - const zone = zoneFromHash(this.hash); - const checkReplacement = async () => { - // Get the current transaction count for this sender - if (stopScanning) { - return null; - } - const { blockNumber, nonce } = await resolveProperties({ - blockNumber: this.provider.getBlockNumber(toShard(zone)), - nonce: this.provider.getTransactionCount(this.from), - }); - // No transaction or our nonce has not been mined yet; but we - // can start scanning later when we do start - if (nonce < this.nonce) { - startBlock = blockNumber; - return; - } - // We were mined; no replacement - if (stopScanning) { - return null; - } - const mined = await this.getTransaction(); - if (mined && mined.blockNumber != null) { - return; - } - // We were replaced; start scanning for that transaction - // Starting to scan; look back a few extra blocks for safety - if (nextScan === -1) { - nextScan = startBlock - 3; - if (nextScan < this.startBlock) { - nextScan = this.startBlock; - } - } - while (nextScan <= blockNumber) { - // Get the next block to scan - if (stopScanning) { - return null; - } - const block = await this.provider.getBlock(toShard(zone), nextScan, true); - // This should not happen; but we'll try again shortly - if (block == null) { - return; - } - // We were mined; no replacement - for (const hash of block) { - if (hash === this.hash) { - return; - } - } - // Search for the transaction that replaced us - for (let i = 0; i < block.length; i++) { - const tx = await block.getTransaction(i); - if ('from' in tx && tx.from === this.from && tx.nonce === this.nonce) { - // Get the receipt - if (stopScanning) { - return null; - } - const receipt = await this.provider.getTransactionReceipt(tx.hash); - // This should not happen; but we'll try again shortly - if (receipt == null) { - return; - } - // We will retry this on the next block (this case could be optimized) - if (blockNumber - receipt.blockNumber + 1 < confirms) { - return; - } - // The reason we were replaced - let reason = 'replaced'; - if (tx.data === this.data && tx.to === this.to && tx.value === this.value) { - reason = 'repriced'; - } - else if (tx.data === '0x' && tx.from === tx.to && tx.value === BN_0$1) { - reason = 'cancelled'; - } - assert(false, 'transaction was replaced', 'TRANSACTION_REPLACED', { - cancelled: reason === 'replaced' || reason === 'cancelled', - reason, - replacement: tx.replaceableTransaction(startBlock), - hash: tx.hash, - receipt, - }); - } - } - nextScan++; - } - return; - }; - const checkReceipt = (receipt) => { - if (receipt == null || receipt.status !== 0) { - return receipt; - } - assert(false, 'transaction execution reverted', 'CALL_EXCEPTION', { - action: 'sendTransaction', - data: null, - reason: null, - invocation: null, - revert: null, - transaction: { - to: receipt.to, - from: receipt.from, - data: '', // @TODO: in v7, split out sendTransaction properties - }, - receipt, - }); - }; - const receipt = await this.provider.getTransactionReceipt(this.hash); - if (confirms === 0) { - return checkReceipt(receipt); - } - if (receipt) { - if ((await receipt.confirmations()) >= confirms) { - return checkReceipt(receipt); - } - } - else { - // Check for a replacement; throws if a replacement was found - await checkReplacement(); - // Allow null only when the confirms is 0 - if (confirms === 0) { - return null; - } - } - const waiter = new Promise((resolve, reject) => { - // List of things to cancel when we have a result (one way or the other) - const cancellers = []; - const cancel = () => { - cancellers.forEach((c) => c()); - }; - // On cancel, stop scanning for replacements - cancellers.push(() => { - stopScanning = true; - }); - // Set up any timeout requested - if (timeout > 0) { - const timer = setTimeout(() => { - cancel(); - reject(makeError('wait for transaction timeout', 'TIMEOUT')); - }, timeout); - cancellers.push(() => { - clearTimeout(timer); - }); - } - const txListener = async (receipt) => { - // Done; return it! - if ((await receipt.confirmations()) >= confirms) { - cancel(); - try { - resolve(checkReceipt(receipt)); - } - catch (error) { - reject(error); - } - } - }; - cancellers.push(() => { - this.provider.off(this.hash, txListener); - }); - this.provider.on(this.hash, txListener); - // We support replacement detection; start checking - if (startBlock >= 0) { - const replaceListener = async () => { - try { - // Check for a replacement; this throws only if one is found - await checkReplacement(); - } - catch (error) { - // We were replaced (with enough confirms); re-throw the error - if (isError(error, 'TRANSACTION_REPLACED')) { - cancel(); - reject(error); - return; - } - } - // Rescheudle a check on the next block - if (!stopScanning) { - this.provider.once('block', replaceListener); - } - }; - cancellers.push(() => { - this.provider.off('block', replaceListener); - }); - this.provider.once('block', replaceListener); - } - }); - return await waiter; - } - /** - * Returns `true` if this transaction has been included. - * - * This is effective only as of the time the TransactionResponse was instantiated. To get up-to-date information, - * use {@link QuaiTransactionResponse.getTransaction | **getTransaction**}. - * - * This provides a Type Guard that this transaction will have non-null property values for properties that are null - * for unmined transactions. - * - * @returns {QuaiMinedTransactionResponse} True if the transaction has been mined. - * @throws {Error} If the transaction was replaced, repriced, or cancelled. - */ - isMined() { - return this.blockHash != null; - } - /** - * Returns a filter which can be used to listen for orphan events that evict this transaction. - * - * @returns {OrphanFilter} The orphan filter. - */ - removedEvent() { - assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - return createRemovedTransactionFilter(this); - } - /** - * Returns a filter which can be used to listen for orphan events that re-order this event against `other`. - * - * @param {TransactionResponse} [other] - The other transaction to compare against. - * @returns {OrphanFilter} The orphan filter. - */ - reorderedEvent(other) { - assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - return createReorderedTransactionFilter(this, other); - } - /** - * Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the - * transaction is replaced, which will begin scanning at `startBlock`. - * - * This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect - * `startBlock` can have devastating performance consequences if used incorrectly. - * - * @param {number} startBlock - The block number to start scanning for replacements. - * @returns {QuaiTransactionResponse} The replaceable transaction. - */ - replaceableTransaction(startBlock) { - assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock); - const tx = new QuaiTransactionResponse(this, this.provider); - tx.startBlock = startBlock; - return tx; - } -} -/** - * A **QiTransactionResponse** includes all properties about a Qi transaction that was sent to the network, which may or - * may not be included in a block. - * - * The {@link TransactionResponse.isMined | **TransactionResponse.isMined**} can be used to check if the transaction has - * been mined as well as type guard that the otherwise possibly `null` properties are defined. - * - * @category Providers - */ -class QiTransactionResponse { - /** - * The provider this is connected to, which will influence how its methods will resolve its async inspection - * methods. - */ - provider; - /** - * The block number of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockNumber; - /** - * The blockHash of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockHash; - /** - * The index within the block that this transaction resides at. - */ - index; - /** - * The transaction hash. - */ - hash; - /** - * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy - * transactions types. - */ - type; - /** - * The chain ID. - */ - chainId; - /** - * The signature. - */ - signature; - txInputs; - txOutputs; - startBlock; - /** - * @ignore - */ - constructor(tx, provider) { - this.provider = provider; - this.blockNumber = tx.blockNumber != null ? tx.blockNumber : null; - this.blockHash = tx.blockHash != null ? tx.blockHash : null; - this.hash = tx.hash; - this.index = tx.index; - this.type = tx.type; - this.chainId = tx.chainId; - this.signature = tx.signature; - this.startBlock = -1; - this.txInputs = tx.txInputs; - this.txOutputs = tx.txOutputs; - } - /** - * Returns a JSON-compatible representation of this transaction. - */ - toJSON() { - const { blockNumber, blockHash, index, hash, type, signature, txInputs, txOutputs } = this; - const result = { - _type: 'TransactionReceipt', - blockNumber, - blockHash, - chainId: toJson(this.chainId), - hash, - signature, - index, - type, - txInputs: JSON.parse(JSON.stringify(txInputs)), - txOutputs: JSON.parse(JSON.stringify(txOutputs)), - }; - return result; - } - /** - * Resolves to the Block that this transaction was included in. - * - * This will return null if the transaction has not been included yet. - * - * @param {Shard} shard - The shard to fetch the block from. - * @returns {null | Promise} A promise resolving to the block or null if not found. - */ - async getBlock(shard) { - let blockNumber = this.blockNumber; - if (blockNumber == null) { - const tx = await this.getTransaction(); - if (tx) { - blockNumber = tx.blockNumber; - } - } - if (blockNumber == null) { - return null; - } - const block = this.provider.getBlock(shard, blockNumber); - if (block == null) { - throw new Error('TODO'); - } - return block; - } - /** - * Resolves to this transaction being re-requested from the provider. This can be used if you have an unmined - * transaction and wish to get an up-to-date populated instance. - * - * @returns {null | Promise} A promise resolving to the transaction, or null if not found. - * @throws {Error} If the transaction is not found. - */ - async getTransaction() { - const transaction = this.provider.getTransaction(this.hash); - if (transaction instanceof QiTransactionResponse) { - return transaction; - } - else { - return null; - } - } - /** - * Resolve to the number of confirmations this transaction has. - * - * @returns {Promise} A promise resolving to the number of confirmations. - */ - async confirmations() { - const zone = zoneFromHash(this.hash); - if (this.blockNumber == null) { - const { tx, blockNumber } = await resolveProperties({ - tx: this.getTransaction(), - blockNumber: this.provider.getBlockNumber(toShard(zone)), - }); - // Not mined yet... - if (tx == null || tx.blockNumber == null) { - return 0; - } - return blockNumber - tx.blockNumber + 1; - } - const blockNumber = await this.provider.getBlockNumber(toShard(zone)); - return blockNumber - this.blockNumber + 1; - } - /** - * Returns `true` if this transaction has been included. - * - * This is effective only as of the time the TransactionResponse was instantiated. To get up-to-date information, - * use {@link QiTransactionResponse.getTransaction | **getTransaction**}. - * - * This provides a Type Guard that this transaction will have non-null property values for properties that are null - * for unmined transactions. - * - * @returns {QiMinedTransactionResponse} True if the transaction has been mined or false otherwise. - */ - isMined() { - return this.blockHash != null; - } - /** - * Returns a filter which can be used to listen for orphan events that evict this transaction. - * - * @returns {OrphanFilter} The orphan filter. - */ - removedEvent() { - assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - return createRemovedTransactionFilter(this); - } - /** - * Returns a filter which can be used to listen for orphan events that re-order this event against `other`. - * - * @param {TransactionResponse} [other] - The other transaction to compare against. - * @returns {OrphanFilter} The orphan filter. - */ - reorderedEvent(other) { - assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - return createReorderedTransactionFilter(this, other); - } - /** - * Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the - * transaction is replaced, which will begin scanning at `startBlock`. - * - * This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect - * `startBlock` can have devastating performance consequences if used incorrectly. - * - * @param {number} startBlock - The block number to start scanning for replacements. - * @returns {QiTransactionResponse} The replaceable transaction. - */ - replaceableTransaction(startBlock) { - assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock); - const tx = new QiTransactionResponse(this, this.provider); - tx.startBlock = startBlock; - return tx; - } -} -function createOrphanedBlockFilter(block) { - return { orphan: 'drop-block', hash: block.hash, number: block.number }; -} -function createReorderedTransactionFilter(tx, other) { - return { orphan: 'reorder-transaction', tx, other }; -} -function createRemovedTransactionFilter(tx) { - return { orphan: 'drop-transaction', tx }; -} -function createRemovedLogFilter(log) { - return { - orphan: 'drop-log', - log: { - transactionHash: log.transactionHash, - blockHash: log.blockHash, - blockNumber: log.blockNumber, - address: log.address, - data: log.data, - topics: Object.freeze(log.topics.slice()), - index: log.index, - }, - }; -} -function getZoneFromEventFilter(filter) { - let zone = null; - if (filter.nodeLocation) { - zone = getZoneFromNodeLocation(filter.nodeLocation); - } - else if (filter.address) { - let address; - if (Array.isArray(filter.address)) { - address = filter.address[0]; - } - else { - address = filter.address; - } - const addressZone = getZoneForAddress(address); - if (addressZone) { - zone = toZone(addressZone); - } - else { - return null; - } - } - return zone; -} - -// import from provider.ts instead of index.ts to prevent circular dep -// from quaiscanProvider -/** - * An **EventLog** contains additional properties parsed from the {@link Log | **Log**}. - * - * @category Contract - */ -class EventLog extends Log { - /** - * The Contract Interface. - */ - interface; - /** - * The matching event. - */ - fragment; - /** - * The parsed arguments passed to the event by `emit`. - */ - args; - /** - * @ignore - */ - constructor(log, iface, fragment) { - super(log, log.provider); - const args = iface.decodeEventLog(fragment, log.data, log.topics); - defineProperties(this, { args, fragment, interface: iface }); - } - /** - * The name of the event. - */ - get eventName() { - return this.fragment.name; - } - /** - * The signature of the event. - */ - get eventSignature() { - return this.fragment.format(); - } -} -/** - * An **EventLog** contains additional properties parsed from the {@link Log | **Log**}. - * - * @category Contract - */ -class UndecodedEventLog extends Log { - /** - * The error encounted when trying to decode the log. - */ - error; - /** - * @ignore - */ - constructor(log, error) { - super(log, log.provider); - defineProperties(this, { error }); - } -} -/** - * A **ContractTransactionReceipt** includes the parsed logs from a {@link TransactionReceipt | **TransactionReceipt**}. - * - * @category Contract - */ -class ContractTransactionReceipt extends TransactionReceipt { - #iface; - /** - * @ignore - */ - constructor(iface, provider, tx) { - super(tx, provider); - this.#iface = iface; - } - /** - * The parsed logs for any {@link Log | **Log**} which has a matching event in the Contract ABI. - */ - get logs() { - return super.logs.map((log) => { - const fragment = log.topics.length ? this.#iface.getEvent(log.topics[0]) : null; - if (fragment) { - try { - return new EventLog(log, this.#iface, fragment); - } - catch (error) { - return new UndecodedEventLog(log, error); - } - } - return log; - }); - } -} -/** - * A **ContractTransactionResponse** will return a {@link ContractTransactionReceipt | **ContractTransactionReceipt**} - * when waited on. - * - * @category Contract - */ -class ContractTransactionResponse extends QuaiTransactionResponse { - #iface; - /** - * @ignore - */ - constructor(iface, provider, tx) { - super(tx, provider); - this.#iface = iface; - } - /** - * Resolves once this transaction has been mined and has `confirms` blocks including it (default: `1`) with an - * optional `timeout`. - * - * This can resolve to `null` only if `confirms` is `0` and the transaction has not been mined, otherwise this will - * wait until enough confirmations have completed. - * - * @param {number} confirms - The number of confirmations to wait for. - * - * @returns {Promise} The transaction receipt, or `null` if `confirms` is `0`. - */ - async wait(confirms) { - const receipt = await super.wait(confirms); - if (receipt == null) { - return null; - } - return new ContractTransactionReceipt(this.#iface, this.provider, receipt); - } -} -/** - * A **ContractUnknownEventPayload** is included as the last parameter to Contract Events when the event does not match - * any events in the ABI. - * - * @category Contract - */ -class ContractUnknownEventPayload extends EventPayload { - /** - * The log with no matching events. - */ - log; - /** - * @ignore - */ - constructor(contract, listener, filter, log) { - super(contract, listener, filter); - defineProperties(this, { log }); - } - /** - * Resolves to the block the event occured in. - * - * @param {Shard} shard - The shard to get the block from. - * - * @returns {Promise} A promise resolving to the block the event occured in. - */ - async getBlock(shard) { - return await this.log.getBlock(shard); - } - /** - * Resolves to the transaction the event occured in. - * - * @returns {Promise} A promise resolving to the transaction the event occured in. - */ - async getTransaction() { - return await this.log.getTransaction(); - } - /** - * Resolves to the transaction receipt the event occured in. - * - * @returns {Promise} A promise resolving to the transaction receipt the event occured in. - */ - async getTransactionReceipt() { - return await this.log.getTransactionReceipt(); - } -} -/** - * A **ContractEventPayload** is included as the last parameter to Contract Events when the event is known. - * - * @category Contract - */ -class ContractEventPayload extends ContractUnknownEventPayload { - /** - * @ignore - */ - constructor(contract, listener, filter, fragment, _log) { - super(contract, listener, filter, new EventLog(_log, contract.interface, fragment)); - const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics); - defineProperties(this, { args, fragment }); - } - /** - * The event name. - */ - get eventName() { - return this.fragment.name; - } - /** - * The event signature. - */ - get eventSignature() { - return this.fragment.format(); - } -} - -const BN_0 = BigInt(0); -/** - * Check if the value can call transactions. - * - * @param {any} value - The value to check. - * @returns {value is ContractRunnerCaller} True if the value can call transactions. - */ -function canCall(value) { - return value && typeof value.call === 'function'; -} -/** - * Check if the value can estimate gas. - * - * @param {any} value - The value to check. - * @returns {value is ContractRunnerEstimater} True if the value can estimate gas. - */ -function canEstimate(value) { - return value && typeof value.estimateGas === 'function'; -} -/** - * Check if the value can send transactions. - * - * @param {any} value - The value to check. - * @returns {value is ContractRunnerSender} True if the value can send transactions. - */ -function canSend(value) { - return value && typeof value.sendTransaction === 'function'; -} -/** - * Class representing a prepared topic filter. - * - * @implements {DeferredTopicFilter} - */ -class PreparedTopicFilter { - #filter; - fragment; - /** - * @ignore - */ - constructor(contract, fragment, args) { - defineProperties(this, { fragment }); - if (fragment.inputs.length < args.length) { - throw new Error('too many arguments'); - } - this.#filter = (async function () { - const resolvedArgs = await Promise.all(fragment.inputs.map((param, index) => { - const arg = args[index]; - if (arg == null) { - return null; - } - return param.walkAsync(args[index], (type, value) => { - if (type === 'address') { - if (Array.isArray(value)) { - return Promise.all(value.map((v) => resolveAddress(v))); - } - return resolveAddress(value); - } - return value; - }); - })); - return contract.interface.encodeFilterTopics(fragment, resolvedArgs); - })(); - } - /** - * Get the topic filter. - * - * @returns {Promise} The topic filter. - */ - getTopicFilter() { - return this.#filter; - } -} -/** - * Get the runner for a specific feature. - * - * @param {any} value - The value to check. - * @param {keyof ContractRunner} feature - The feature to check for. - * @returns {null | T} The runner if available, otherwise null. - */ -function getRunner(value, feature) { - if (value == null) { - return null; - } - if (typeof value[feature] === 'function') { - return value; - } - if (value.provider && typeof value.provider[feature] === 'function') { - return value.provider; - } - return null; -} -/** - * Get the provider from a contract runner. - * - * @param {null | ContractRunner} value - The contract runner. - * @returns {null | Provider} The provider if available, otherwise null. - */ -function getProvider(value) { - if (value == null) { - return null; - } - return value.provider || null; -} -/** - * @ignore Copy overrides and validate them. - * @param {any} arg - The argument containing overrides. - * @param {string[]} [allowed] - The allowed override keys. - * @returns {Promise>} The copied and validated overrides. - * @throws {Error} If the overrides are invalid. - */ -async function copyOverrides(arg, allowed) { - // Make sure the overrides passed in are a valid overrides object - const _overrides = Typed.dereference(arg, 'overrides'); - assertArgument(typeof _overrides === 'object', 'invalid overrides parameter', 'overrides', arg); - // Create a shallow copy (we'll deep-ify anything needed during normalizing) - const overrides = copyRequest(_overrides); - assertArgument(!('to' in overrides) || overrides.to == null || (allowed || []).indexOf('to') >= 0, 'cannot override to', 'overrides.to', overrides); - assertArgument(!('data' in overrides) || overrides.data == null || (allowed || []).indexOf('data') >= 0, 'cannot override data', 'overrides.data', overrides); - // Resolve any from - if ('from' in overrides && overrides.from) { - overrides.from = await overrides.from; - } - return overrides; -} -/** - * @ignore Resolve arguments for a contract runner. - * @param {null | ContractRunner} _runner - The contract runner. - * @param {ReadonlyArray} inputs - The input parameter types. - * @param {any[]} args - The arguments to resolve. - * @returns {Promise} The resolved arguments. - */ -async function resolveArgs(_runner, inputs, args) { - // Recursively descend into args and resolve any addresses - return await Promise.all(inputs.map((param, index) => { - return param.walkAsync(args[index], (type, value) => { - value = Typed.dereference(value, type); - if (type === 'address') { - return resolveAddress(value); - } - return value; - }); - })); -} -/** - * Build a wrapped fallback method for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @returns {WrappedFallback} The wrapped fallback method. - */ -function buildWrappedFallback(contract) { - /** - * Populate a transaction with overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The populated transaction. - * @throws {Error} If the overrides are invalid. - */ - const populateTransaction = async function (overrides) { - // If an overrides was passed in, copy it and normalize the values - const tx = await copyOverrides(overrides, ['data']); - tx.to = await contract.getAddress(); - validateAddress(tx.to); - if (tx.from) { - tx.from = await resolveAddress(tx.from); - validateAddress(tx.from); - } - const iface = contract.interface; - const noValue = getBigInt(tx.value || BN_0, 'overrides.value') === BN_0; - const noData = (tx.data || '0x') === '0x'; - if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) { - assertArgument(false, 'cannot send data to receive or send value to non-payable fallback', 'overrides', overrides); - } - assertArgument(iface.fallback || noData, 'cannot send data to receive-only contract', 'overrides.data', tx.data); - // Only allow payable contracts to set non-zero value - const payable = iface.receive || (iface.fallback && iface.fallback.payable); - assertArgument(payable || noValue, 'cannot send value to non-payable fallback', 'overrides.value', tx.value); - // Only allow fallback contracts to set non-empty data - assertArgument(iface.fallback || noData, 'cannot send data to receive-only contract', 'overrides.data', tx.data); - return tx; - }; - /** - * Perform a static call with the given overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The result of the static call. - * @throws {Error} If the call fails. - */ - const staticCall = async function (overrides) { - const runner = getRunner(contract.runner, 'call'); - assert(canCall(runner), 'contract runner does not support calling', 'UNSUPPORTED_OPERATION', { - operation: 'call', - }); - const tx = await populateTransaction(overrides); - try { - return await runner.call(tx); - } - catch (error) { - if (isCallException(error) && error.data) { - throw contract.interface.makeError(error.data, tx); - } - throw error; - } - }; - /** - * Send a transaction with the given overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The transaction response. - * @throws {Error} If the transaction fails. - */ - const send = async function (overrides) { - const runner = contract.runner; - assert(canSend(runner), 'contract runner does not support sending transactions', 'UNSUPPORTED_OPERATION', { - operation: 'sendTransaction', - }); - const tx = (await runner.sendTransaction(await populateTransaction(overrides))); - const provider = getProvider(contract.runner); - // @TODO: the provider can be null; make a custom dummy provider that will throw a - // meaningful error - return new ContractTransactionResponse(contract.interface, provider, tx); - }; - /** - * Estimate the gas required for a transaction with the given overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The estimated gas. - * @throws {Error} If the gas estimation fails. - */ - const estimateGas = async function (overrides) { - const runner = getRunner(contract.runner, 'estimateGas'); - assert(canEstimate(runner), 'contract runner does not support gas estimation', 'UNSUPPORTED_OPERATION', { - operation: 'estimateGas', - }); - return await runner.estimateGas(await populateTransaction(overrides)); - }; - /** - * Send a transaction with the given overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The transaction response. - * @throws {Error} If the transaction fails. - */ - const method = async (overrides) => { - return await send(overrides); - }; - defineProperties(method, { - _contract: contract, - estimateGas, - populateTransaction, - send, - staticCall, - }); - return method; -} -/** - * Build a wrapped method for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @param {string} key - The method key. - * @returns {BaseContractMethod} The wrapped method. - */ -function buildWrappedMethod(contract, key) { - /** - * Get the function fragment for the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {FunctionFragment} The function fragment. - * @throws {Error} If no matching fragment is found. - */ - const getFragment = function (...args) { - const fragment = contract.interface.getFunction(key, args); - assert(fragment, 'no matching fragment', 'UNSUPPORTED_OPERATION', { - operation: 'fragment', - info: { key, args }, - }); - return fragment; - }; - /** - * Populate a transaction with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The populated transaction. - * @throws {Error} If the arguments are invalid. - */ - const populateTransaction = async function (...args) { - const fragment = getFragment(...args); - // If an overrides was passed in, copy it and normalize the values - let overrides; - if (fragment.inputs.length + 1 === args.length) { - overrides = await copyOverrides(args.pop()); - const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); - return Object.assign({}, overrides, await resolveProperties({ - to: contract.getAddress(), - data: contract.interface.encodeFunctionData(fragment, resolvedArgs), - })); - } - if (fragment.inputs.length !== args.length) { - throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); - } - const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); - return await resolveProperties({ - to: contract.getAddress(), - from: args.pop()?.from, - data: contract.interface.encodeFunctionData(fragment, resolvedArgs), - }); - }; - /** - * Perform a static call with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The result of the static call. - * @throws {Error} If the call fails. - */ - const staticCall = async function (...args) { - const result = await staticCallResult(...args); - if (result.length === 1) { - return result[0]; - } - return result; - }; - /** - * Send a transaction with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The transaction response. - * @throws {Error} If the transaction fails. - */ - const send = async function (...args) { - const runner = contract.runner; - assert(canSend(runner), 'contract runner does not support sending transactions', 'UNSUPPORTED_OPERATION', { - operation: 'sendTransaction', - }); - const pop = await populateTransaction(...args); - if (!pop.from && 'address' in runner && typeof runner.address === 'string') { - pop.from = await resolveAddress(runner.address); - } - const tx = (await runner.sendTransaction(await pop)); - const provider = getProvider(contract.runner); - // @TODO: the provider can be null; make a custom dummy provider that will throw a - // meaningful error - return new ContractTransactionResponse(contract.interface, provider, tx); - }; - /** - * Estimate the gas required for a transaction with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The estimated gas. - * @throws {Error} If the gas estimation fails. - */ - const estimateGas = async function (...args) { - const runner = getRunner(contract.runner, 'estimateGas'); - assert(canEstimate(runner), 'contract runner does not support gas estimation', 'UNSUPPORTED_OPERATION', { - operation: 'estimateGas', - }); - return await runner.estimateGas(await populateTransaction(...args)); - }; - /** - * Perform a static call and return the result with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The result of the static call. - * @throws {Error} If the call fails. - */ - const staticCallResult = async function (...args) { - const runner = getRunner(contract.runner, 'call'); - assert(canCall(runner), 'contract runner does not support calling', 'UNSUPPORTED_OPERATION', { - operation: 'call', - }); - const tx = await populateTransaction(...args); - if (!tx.from && 'address' in runner && typeof runner.address === 'string') { - tx.from = await resolveAddress(runner.address); - } - let result = '0x'; - try { - result = await runner.call(tx); - } - catch (error) { - if (isCallException(error) && error.data) { - throw contract.interface.makeError(error.data, tx); - } - throw error; - } - const fragment = getFragment(...args); - return contract.interface.decodeFunctionResult(fragment, result); - }; - /** - * Send a transaction or perform a static call based on the method arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The result of the method call. - * @throws {Error} If the method call fails. - */ - const method = async (...args) => { - const fragment = getFragment(...args); - if (fragment.constant) { - return await staticCall(...args); - } - return await send(...args); - }; - defineProperties(method, { - name: contract.interface.getFunctionName(key), - _contract: contract, - _key: key, - getFragment, - estimateGas, - populateTransaction, - send, - staticCall, - staticCallResult, - }); - // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) - Object.defineProperty(method, 'fragment', { - configurable: false, - enumerable: true, - get: () => { - const fragment = contract.interface.getFunction(key); - assert(fragment, 'no matching fragment', 'UNSUPPORTED_OPERATION', { - operation: 'fragment', - info: { key }, - }); - return fragment; - }, - }); - return method; -} -/** - * Build a wrapped event for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @param {string} key - The event key. - * @returns {ContractEvent} The wrapped event. - */ -function buildWrappedEvent(contract, key) { - /** - * Get the event fragment for the given arguments. - * - * @param {...ContractEventArgs} args - The event arguments. - * @returns {EventFragment} The event fragment. - * @throws {Error} If no matching fragment is found. - */ - const getFragment = function (...args) { - const fragment = contract.interface.getEvent(key, args); - assert(fragment, 'no matching fragment', 'UNSUPPORTED_OPERATION', { - operation: 'fragment', - info: { key, args }, - }); - return fragment; - }; - /** - * Create a prepared topic filter for the event. - * - * @param {...ContractMethodArgs} args - The event arguments. - * @returns {PreparedTopicFilter} The prepared topic filter. - */ - const method = function (...args) { - return new PreparedTopicFilter(contract, getFragment(...args), args); - }; - defineProperties(method, { - name: contract.interface.getEventName(key), - _contract: contract, - _key: key, - getFragment, - }); - // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) - Object.defineProperty(method, 'fragment', { - configurable: false, - enumerable: true, - get: () => { - const fragment = contract.interface.getEvent(key); - assert(fragment, 'no matching fragment', 'UNSUPPORTED_OPERATION', { - operation: 'fragment', - info: { key }, - }); - return fragment; - }, - }); - return method; -} -// The combination of TypeScrype, Private Fields and Proxies makes -// the world go boom; so we hide variables with some trickery keeping -// a symbol attached to each BaseContract which its sub-class (even -// via a Proxy) can reach and use to look up its internal values. -const internal = Symbol.for('_quaisInternal_contract'); -const internalValues = new WeakMap(); -/** - * Set internal values for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @param {Internal} values - The internal values. - */ -function setInternal(contract, values) { - internalValues.set(contract[internal], values); -} -/** - * Get internal values for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @returns {Internal} The internal values. - */ -function getInternal(contract) { - return internalValues.get(contract[internal]); -} -/** - * Check if a value is a deferred topic filter. - * - * @param {any} value - The value to check. - * @returns {value is DeferredTopicFilter} True if the value is a deferred topic filter. - */ -function isDeferred(value) { - return (value && - typeof value === 'object' && - 'getTopicFilter' in value && - typeof value.getTopicFilter === 'function' && - value.fragment); -} -/** - * Get subscription information for an event. - * - * @param {BaseContract} contract - The contract instance. - * @param {ContractEventName} event - The event name. - * @returns {Promise<{ fragment: null | EventFragment; tag: string; topics: TopicFilter }>} The subscription - * information. - * @throws {Error} If the event name is unknown. - */ -async function getSubInfo(contract, event) { - let topics; - let fragment = null; - // Convert named events to topicHash and get the fragment for - // events which need deconstructing. - if (Array.isArray(event)) { - const topicHashify = function (name) { - if (isHexString(name, 32)) { - return name; - } - const fragment = contract.interface.getEvent(name); - assertArgument(fragment, 'unknown fragment', 'name', name); - return fragment.topicHash; - }; - // Array of Topics and Names; e.g. `[ "0x1234...89ab", "Transfer(address)" ]` - topics = event.map((e) => { - if (e == null) { - return null; - } - if (Array.isArray(e)) { - return e.map(topicHashify); - } - return topicHashify(e); - }); - } - else if (event === '*') { - topics = [null]; - } - else if (typeof event === 'string') { - if (isHexString(event, 32)) { - // Topic Hash - topics = [event]; - } - else { - // Name or Signature; e.g. `"Transfer", `"Transfer(address)"` - fragment = contract.interface.getEvent(event); - assertArgument(fragment, 'unknown fragment', 'event', event); - topics = [fragment.topicHash]; - } - } - else if (isDeferred(event)) { - // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)` - topics = await event.getTopicFilter(); - } - else if (event && 'fragment' in event) { - // ContractEvent; e.g. `contract.filter.Transfer` - fragment = event.fragment; - topics = [fragment.topicHash]; - } - else { - assertArgument(false, 'unknown event name', 'event', event); - } - // Normalize topics and sort TopicSets - topics = topics.map((t) => { - if (t == null) { - return null; - } - if (Array.isArray(t)) { - const items = Array.from(new Set(t.map((t) => t.toLowerCase())).values()); - if (items.length === 1) { - return items[0]; - } - items.sort(); - return items; - } - return t.toLowerCase(); - }); - const tag = topics - .map((t) => { - if (t == null) { - return 'null'; - } - if (Array.isArray(t)) { - return t.join('|'); - } - return t; - }) - .join('&'); - return { fragment, tag, topics }; -} -/** - * Check if a contract has a subscription for an event. - * - * @param {BaseContract} contract - The contract instance. - * @param {ContractEventName} event - The event name. - * @returns {Promise} The subscription if available, otherwise null. - */ -async function hasSub(contract, event) { - const { subs } = getInternal(contract); - return subs.get((await getSubInfo(contract, event)).tag) || null; -} -/** - * Get a subscription for an event. - * - * @param {BaseContract} contract - The contract instance. - * @param {string} operation - The operation name. - * @param {ContractEventName} event - The event name. - * @returns {Promise} The subscription. - * @throws {Error} If the contract runner does not support subscribing. - */ -async function getSub(contract, operation, event) { - // Make sure our runner can actually subscribe to events - const provider = getProvider(contract.runner); - assert(provider, 'contract runner does not support subscribing', 'UNSUPPORTED_OPERATION', { operation }); - const { fragment, tag, topics } = await getSubInfo(contract, event); - const { addr, subs } = getInternal(contract); - let sub = subs.get(tag); - if (!sub) { - const address = addr ? addr : contract; - const filter = { address, topics }; - const listener = (log) => { - let foundFragment = fragment; - if (foundFragment == null) { - try { - foundFragment = contract.interface.getEvent(log.topics[0]); - // eslint-disable-next-line no-empty - } - catch (error) { } - } - // If fragment is null, we do not deconstruct the args to emit - if (foundFragment) { - const _foundFragment = foundFragment; - const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : []; - emit(contract, event, args, (listener) => { - return new ContractEventPayload(contract, listener, event, _foundFragment, log); - }); - } - else { - emit(contract, event, [], (listener) => { - return new ContractUnknownEventPayload(contract, listener, event, log); - }); - } - }; - const zone = getZoneForAddress(await resolveAddress(address)); - let starting = []; - const start = () => { - if (starting.length) { - return; - } - starting.push(provider.on(filter, listener, zone)); - }; - const stop = async () => { - if (starting.length == 0) { - return; - } - const started = starting; - starting = []; - await Promise.all(started); - provider.off(filter, listener, zone); - }; - sub = { tag, listeners: [], start, stop }; - subs.set(tag, sub); - } - return sub; -} -/** - * We use this to ensure one emit resolves before firing the next to ensure correct ordering (note this cannot throw and - * just adds the notice to the event queue using setTimeout). - */ -let lastEmit = Promise.resolve(); -/** - * Emit an event with the given arguments and payload function. - * - * @ignore - * @param {BaseContract} contract - The contract instance. - * @param {ContractEventName} event - The event name. - * @param {any[]} args - The arguments to pass to the listeners. - * @param {null | PayloadFunc} payloadFunc - The payload function. - * @returns {Promise} Resolves to true if any listeners were called. - */ -async function _emit(contract, event, args, payloadFunc) { - await lastEmit; - const sub = await hasSub(contract, event); - if (!sub) { - return false; - } - const count = sub.listeners.length; - sub.listeners = sub.listeners.filter(({ listener, once }) => { - const passArgs = Array.from(args); - if (payloadFunc) { - passArgs.push(payloadFunc(once ? null : listener)); - } - try { - listener.call(contract, ...passArgs); - // eslint-disable-next-line no-empty - } - catch (error) { } - return !once; - }); - if (sub.listeners.length === 0) { - sub.stop(); - getInternal(contract).subs.delete(sub.tag); - } - return count > 0; -} -/** - * Emit an event with the given arguments and payload function. - * - * @param {BaseContract} contract - The contract instance. - * @param {ContractEventName} event - The event name. - * @param {any[]} args - The arguments to pass to the listeners. - * @param {null | PayloadFunc} payloadFunc - The payload function. - * @returns {Promise} Resolves to true if any listeners were called. - */ -async function emit(contract, event, args, payloadFunc) { - try { - await lastEmit; - // eslint-disable-next-line no-empty - } - catch (error) { } - const resultPromise = _emit(contract, event, args, payloadFunc); - lastEmit = resultPromise; - return await resultPromise; -} -const passProperties = ['then']; -/** - * Creates a new contract connected to target with the abi and optionally connected to a runner to perform operations on - * behalf of. - * - * @category Contract - */ -class BaseContract { - /** - * The target to connect to. - * - * This can be an address or any [Addressable](../interfaces/Addressable), such as another contract. To get the - * resolved address, use the `getAddress` method. - */ - target; - /** - * The contract Interface. - */ - interface; - /** - * The connected runner. This is generally a [**Provider**](../interfaces/Provider) or a - * [**Signer**](../interfaces/Signer), which dictates what operations are supported. - * - * For example, a **Contract** connected to a [**Provider**](../interfaces/Provider) may only execute read-only - * operations. - */ - runner; - /** - * All the Events available on this contract. - */ - filters; - /** - * @ignore - */ - [internal]; - /** - * The fallback or receive function if any. - */ - fallback; - /** - * Creates a new contract connected to `target` with the `abi` and optionally connected to a `runner` to perform - * operations on behalf of. - * - * @ignore - */ - constructor(target, abi, runner, _deployTx) { - assertArgument(typeof target === 'string' || isAddressable(target), 'invalid value for Contract target', 'target', target); - if (runner == null) { - runner = null; - } - const iface = Interface.from(abi); - defineProperties(this, { target, runner, interface: iface }); - Object.defineProperty(this, internal, { value: {} }); - let addrPromise; - let addr = null; - let deployTx = null; - if (_deployTx) { - const provider = getProvider(runner); - // @TODO: the provider can be null; make a custom dummy provider that will throw a - // meaningful error - deployTx = new ContractTransactionResponse(this.interface, provider, _deployTx); - } - const subs = new Map(); - // Resolve the target as the address - if (typeof target === 'string') { - addr = target; - addrPromise = Promise.resolve(target); - } - else { - addrPromise = target.getAddress().then((addr) => { - if (addr == null) { - throw new Error('TODO'); - } - getInternal(this).addr = addr; - return addr; - }); - } - // Set our private values - setInternal(this, { addrPromise, addr, deployTx, subs }); - // Add the event filters - const filters = new Proxy({}, { - get: (target, prop, receiver) => { - // Pass important checks (like `then` for Promise) through - if (typeof prop === 'symbol' || passProperties.indexOf(prop) >= 0) { - return Reflect.get(target, prop, receiver); - } - try { - return this.getEvent(prop); - } - catch (error) { - if (!isError(error, 'INVALID_ARGUMENT') || error.argument !== 'key') { - throw error; - } - } - return undefined; - }, - has: (target, prop) => { - // Pass important checks (like `then` for Promise) through - if (passProperties.indexOf(prop) >= 0) { - return Reflect.has(target, prop); - } - return Reflect.has(target, prop) || this.interface.hasEvent(String(prop)); - }, - }); - defineProperties(this, { filters }); - defineProperties(this, { - fallback: iface.receive || iface.fallback ? buildWrappedFallback(this) : null, - }); - // Return a Proxy that will respond to functions - return new Proxy(this, { - get: (target, prop, receiver) => { - if (typeof prop === 'symbol' || prop in target || passProperties.indexOf(prop) >= 0) { - return Reflect.get(target, prop, receiver); - } - // Undefined properties should return undefined - try { - return target.getFunction(prop); - } - catch (error) { - if (!isError(error, 'INVALID_ARGUMENT') || error.argument !== 'key') { - throw error; - } - } - return undefined; - }, - has: (target, prop) => { - if (typeof prop === 'symbol' || prop in target || passProperties.indexOf(prop) >= 0) { - return Reflect.has(target, prop); - } - return target.interface.hasFunction(prop); - }, - }); - } - /** - * Return a new Contract instance with the same target and ABI, but a different `runner`. - * - * @param {null | ContractRunner} runner - The runner to use. - * @returns {BaseContract} The new contract instance. - */ - connect(runner) { - return new BaseContract(this.target, this.interface, runner); - } - /** - * Return a new Contract instance with the same ABI and runner, but a different `target`. - * - * @param {string | Addressable} target - The target to connect to. - * @returns {BaseContract} The new contract instance. - */ - attach(target) { - return new BaseContract(target, this.interface, this.runner); - } - /** - * Return the resolved address of this Contract. - * - * @returns {Promise} The resolved address. - */ - async getAddress() { - return await getInternal(this).addrPromise; - } - /** - * Return the deployed bytecode or null if no bytecode is found. - * - * @returns {Promise} The deployed bytecode or null. - * @throws {Error} If the runner does not support .provider. - */ - async getDeployedCode() { - const provider = getProvider(this.runner); - assert(provider, 'runner does not support .provider', 'UNSUPPORTED_OPERATION', { - operation: 'getDeployedCode', - }); - const code = await provider.getCode(await this.getAddress()); - if (code === '0x') { - return null; - } - return code; - } - /** - * Resolve to this Contract once the bytecode has been deployed, or resolve immediately if already deployed. - * - * @returns {Promise} The contract instance. - * @throws {Error} If the contract runner does not support .provider. - */ - async waitForDeployment() { - // We have the deployment transaction; just use that (throws if deployment fails) - const deployTx = this.deploymentTransaction(); - if (deployTx) { - await deployTx.wait(); - return this; - } - // Check for code - const code = await this.getDeployedCode(); - if (code != null) { - return this; - } - // Make sure we can subscribe to a provider event - const provider = getProvider(this.runner); - assert(provider != null, 'contract runner does not support .provider', 'UNSUPPORTED_OPERATION', { - operation: 'waitForDeployment', - }); - return new Promise((resolve, reject) => { - const checkCode = async () => { - try { - const code = await this.getDeployedCode(); - if (code != null) { - return resolve(this); - } - provider.once('block', checkCode); - } - catch (error) { - reject(error); - } - }; - checkCode(); - }); - } - /** - * Return the transaction used to deploy this contract. - * - * This is only available if this instance was returned from a [**ContractFactor**](../classes/ContractFactory). - * - * @returns The transaction used to deploy this contract or `null`. - */ - deploymentTransaction() { - return getInternal(this).deployTx; - } - /** - * Return the function for a given name. This is useful when a contract method name conflicts with a JavaScript name - * such as `prototype` or when using a Contract programatically. - * - * @param {string | FunctionFragment} key - The name of the function to return. - * @returns The function for the given name. - */ - getFunction(key) { - if (typeof key !== 'string') { - key = key.format(); - } - const func = buildWrappedMethod(this, key); - return func; - } - /** - * Return the event for a given name. This is useful when a contract event name conflicts with a JavaScript name - * such as `prototype` or when using a Contract programatically. - * - * @param {string | EventFragment} key - The name of the event to return. - * @returns The event for the given name. - */ - getEvent(key) { - if (typeof key !== 'string') { - key = key.format(); - } - return buildWrappedEvent(this, key); - } - /** - * @ignore - */ - // TODO: implement - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async queryTransaction(hash) { - throw new Error('@TODO'); - } - /** - * Provide historic access to event data for `event` in the range `fromBlock` (default: `0`) to `toBlock` (default: - * `"latest"`) inclusive. - * - * @param {Zone} zone - The zone to query. - * @param {ContractEventName} event - The event to query. - * @param {BlockTag} fromBlock - The block to start querying from. - * @param {BlockTag} toBlock - The block to stop querying at. - * @returns An array of event logs. - */ - async queryFilter(event, fromBlock, toBlock) { - if (fromBlock == null) { - fromBlock = 0; - } - if (toBlock == null) { - toBlock = 'latest'; - } - const { addr, addrPromise } = getInternal(this); - const address = addr ? addr : await addrPromise; - const { fragment, topics } = await getSubInfo(this, event); - const zone = getZoneForAddress(address); - const filter = { address, topics, fromBlock, toBlock, nodeLocation: getNodeLocationFromZone(zone) }; - const provider = getProvider(this.runner); - assert(provider, 'contract runner does not have a provider', 'UNSUPPORTED_OPERATION', { - operation: 'queryFilter', - }); - return (await provider.getLogs(filter)).map((log) => { - let foundFragment = fragment; - if (foundFragment == null) { - try { - foundFragment = this.interface.getEvent(log.topics[0]); - // eslint-disable-next-line no-empty - } - catch (error) { } - } - if (foundFragment) { - try { - return new EventLog(log, this.interface, foundFragment); - } - catch (error) { - return new UndecodedEventLog(log, error); - } - } - return new Log(log, provider); - }); - } - /** - * Add an event `listener` for the `event`. - * - * @param {ContractEventName} event - The event to listen for. - * @param {Listener} listener - The listener to call when the event is emitted. - * @returns This contract instance. - */ - async on(event, listener) { - const sub = await getSub(this, 'on', event); - sub.listeners.push({ listener, once: false }); - sub.start(); - return this; - } - /** - * Add an event `listener` for the `event`, but remove the listener after it is fired once. - * - * @param {ContractEventName} event - The event to listen for. - * @param {Listener} listener - The listener to call when the event is emitted. - */ - async once(event, listener) { - const sub = await getSub(this, 'once', event); - sub.listeners.push({ listener, once: true }); - sub.start(); - return this; - } - /** - * Emit an `event` calling all listeners with `args`. - * - * Resolves to `true` if any listeners were called. - * - * @param {ContractEventName} event - The event to emit. - * @param {any[]} args - The arguments to pass to the listeners. - * @returns `true` if any listeners were called. - */ - async emit(event, ...args) { - return await emit(this, event, args, null); - } - /** - * Resolves to the number of listeners of `event` or the total number of listeners if unspecified. - * - * @param {ContractEventName} event - The event to count listeners for. - * @returns {number} The number of listeners. - */ - async listenerCount(event) { - if (event) { - const sub = await hasSub(this, event); - if (!sub) { - return 0; - } - return sub.listeners.length; - } - const { subs } = getInternal(this); - let total = 0; - for (const { listeners } of subs.values()) { - total += listeners.length; - } - return total; - } - /** - * Resolves to the listeners subscribed to `event` or all listeners if unspecified. - * - * @param {ContractEventName} event - The event to get listeners for. - * @returns {Listener[]} The listeners. - */ - async listeners(event) { - if (event) { - const sub = await hasSub(this, event); - if (!sub) { - return []; - } - return sub.listeners.map(({ listener }) => listener); - } - const { subs } = getInternal(this); - let result = []; - for (const { listeners } of subs.values()) { - result = result.concat(listeners.map(({ listener }) => listener)); - } - return result; - } - /** - * Remove the `listener` from the listeners for `event` or remove all listeners if unspecified. - * - * @param {ContractEventName} event - The event to remove the listener from. - * @param {Listener} listener - The listener to remove. - * @returns This contract instance. - */ - async off(event, listener) { - const sub = await hasSub(this, event); - if (!sub) { - return this; - } - if (listener) { - const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); - if (index >= 0) { - sub.listeners.splice(index, 1); - } - } - if (listener == null || sub.listeners.length === 0) { - sub.stop(); - getInternal(this).subs.delete(sub.tag); - } - return this; - } - /** - * Remove all the listeners for `event` or remove all listeners if unspecified. - * - * @param {ContractEventName} event - The event to remove the listeners from. - * @returns This contract instance. - */ - async removeAllListeners(event) { - if (event) { - const sub = await hasSub(this, event); - if (!sub) { - return this; - } - sub.stop(); - getInternal(this).subs.delete(sub.tag); - } - else { - const { subs } = getInternal(this); - for (const { tag, stop } of subs.values()) { - stop(); - subs.delete(tag); - } - } - return this; - } - /** - * Alias for {@link BaseContract.on | **on**}. - * - * @param {ContractEventName} event - The event to listen for. - * @param {Listener} listener - The listener to call when the event is emitted. - */ - async addListener(event, listener) { - return await this.on(event, listener); - } - /** - * Alias for {@link BaseContract.off | **off**}. - * - * @param {ContractEventName} event - The event to remove the listener from. - * @param {Listener} listener - The listener to remove. - */ - async removeListener(event, listener) { - return await this.off(event, listener); - } - /** - * Create a new Class for the `abi`. - * - * @param {Interface | InterfaceAbi} abi - The ABI to create the class from. - * @returns The new Class for the ABI. - */ - static buildClass(abi) { - class CustomContract extends BaseContract { - constructor(address, runner = null) { - super(address, abi, runner); - } - } - return CustomContract; - } - /** - * Create a new BaseContract with a specified Interface. - * - * @param {string} target - The target to connect to. - * @param {Interface | InterfaceAbi} abi - The ABI to use. - * @param {null | ContractRunner} runner - The runner to use. - * @returns The new BaseContract. - */ - static from(target, abi, runner) { - if (runner == null) { - runner = null; - } - const contract = new this(target, abi, runner); - return contract; - } -} -function _ContractBase() { - return BaseContract; -} -/** - * A {@link BaseContract | **BaseContract**} with no type guards on its methods or events. - * - * @category Contract - */ -class Contract extends _ContractBase() { -} - -/** - * Generally the [Wallet](../classes/Wallet) and [JsonRpcSigner](../classes/JsonRpcSigner) and their sub-classes are - * sufficent for most developers, but this is provided to fascilitate more complex Signers. - */ -function checkProvider(signer, operation) { - if (signer.provider) { - return signer.provider; - } - assert(false, 'missing provider', 'UNSUPPORTED_OPERATION', { operation }); -} -async function populate(signer, tx) { - const pop = copyRequest(tx); - if (pop.to != null) { - pop.to = resolveAddress(pop.to); - validateAddress(pop.to); - } - if (pop.from != null) { - const from = pop.from; - pop.from = await Promise.all([signer.getAddress(), resolveAddress(from)]).then(([address, from]) => { - assertArgument(address.toLowerCase() === from.toLowerCase(), 'transaction from mismatch', 'tx.from', from); - return address; - }); - } - else { - pop.from = await signer.getAddress(); - } - validateAddress(pop.from); - return await resolveProperties(pop); -} -/** - * An **AbstractSigner** includes most of teh functionality required to get a {@link Signer | **Signer**} working as - * expected, but requires a few Signer-specific methods be overridden. - * - * @category Signers - */ -class AbstractSigner { - /** - * The provider this signer is connected to. - */ - provider; - /** - * Creates a new Signer connected to `provider`. - */ - constructor(provider) { - defineProperties(this, { provider: provider || null }); - } - /** - * @ignore - */ - _getAddress(address) { - return resolveAddress(address); - } - async zoneFromAddress(_address) { - const address = this._getAddress(_address); - return toZone((await address).slice(0, 4)); - } - async getNonce(blockTag) { - return checkProvider(this, 'getTransactionCount').getTransactionCount(await this.getAddress(), blockTag); - } - async populateCall(tx) { - const pop = await populate(this, tx); - return pop; - } - async populateQuaiTransaction(tx) { - const provider = checkProvider(this, 'populateTransaction'); - const zone = await this.zoneFromAddress(tx.from); - const pop = (await populate(this, tx)); - if (pop.type == null) { - pop.type = await getTxType(pop.from ?? null, pop.to ?? null); - } - if (pop.nonce == null) { - pop.nonce = await this.getNonce('pending'); - } - if (pop.type == null) { - pop.type = getTxType(pop.from ?? null, pop.to ?? null); - } - if (pop.gasLimit == null) { - if (pop.type == 0) - pop.gasLimit = await this.estimateGas(pop); - else { - //Special cases for type 2 tx to bypass address out of scope in the node - const temp = pop.to; - pop.to = '0x0000000000000000000000000000000000000000'; - pop.gasLimit = getBigInt(2 * Number(await this.estimateGas(pop))); - pop.to = temp; - } - } - // Populate the chain ID - const network = await this.provider.getNetwork(); - if (pop.chainId != null) { - const chainId = getBigInt(pop.chainId); - assertArgument(chainId === network.chainId, 'transaction chainId mismatch', 'tx.chainId', zone); - } - else { - pop.chainId = network.chainId; - } - if (pop.maxFeePerGas == null || pop.maxPriorityFeePerGas == null) { - const feeData = await provider.getFeeData(zone); - if (pop.maxFeePerGas == null) { - pop.maxFeePerGas = feeData.maxFeePerGas; - } - if (pop.maxPriorityFeePerGas == null) { - pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas || 10n; - } - } - //@TOOD: Don't await all over the place; save them up for - // the end for better batching - return await resolveProperties(pop); - } - async estimateGas(tx) { - return checkProvider(this, 'estimateGas').estimateGas(await this.populateCall(tx)); - } - async call(tx) { - return checkProvider(this, 'call').call(await this.populateCall(tx)); - } - async sendTransaction(tx) { - const provider = checkProvider(this, 'sendTransaction'); - const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx)); - const pop = await this.populateQuaiTransaction(tx); - const txObj = QuaiTransaction.from(pop); - const sender = await this.getAddress(); - const signedTx = await this.signTransaction(txObj); - return await provider.broadcastTransaction(zone, signedTx, sender); - } -} -/** - * A **VoidSigner** is a class deisgned to allow an address to be used in any API which accepts a Signer, but for which - * there are no credentials available to perform any actual signing. - * - * This for example allow impersonating an account for the purpose of static calls or estimating gas, but does not allow - * sending transactions. - * - * @category Signers - */ -class VoidSigner extends AbstractSigner { - /** - * The signer address. - */ - address; - /** - * Creates a new **VoidSigner** with `address` attached to `provider`. - */ - constructor(address, provider) { - super(provider); - defineProperties(this, { address }); - } - async getAddress() { - return this.address; - } - connect(provider) { - return new VoidSigner(this.address, provider); - } - #throwUnsupported(suffix, operation) { - assert(false, `VoidSigner cannot sign ${suffix}`, 'UNSUPPORTED_OPERATION', { operation }); - } - // TODO: `domain`, `types` and `value` are not used, remove? - // TODO: this function only throws, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async signTransaction(tx) { - this.#throwUnsupported('transactions', 'signTransaction'); - } - // TODO: `domain`, `types` and `value` are not used, remove? - // TODO: this function only throws, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async signMessage(message) { - this.#throwUnsupported('messages', 'signMessage'); - } - // TODO: `domain`, `types` and `value` are not used, remove? - // TODO: this function only throws, remove? - async signTypedData( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - domain, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - types, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - value) { - this.#throwUnsupported('typed-data', 'signTypedData'); - } -} - -/** - * The **BaseWallet** is a stream-lined implementation of a {@link AbstractSigner} that operates with a private - * key. - * - * It is preferred to use the {@link Wallet} class, as it offers additional functionality and simplifies - * loading a variety of JSON formats, Mnemonic Phrases, etc. - * - * This class may be of use for those attempting to implement a minimal Signer. - * - * @category Wallet - */ -class BaseWallet extends AbstractSigner { - /** - * The wallet address. - * @type {string} - * @readonly - */ - #address; - /** - * The signing key used for signing payloads. - * @type {SigningKey} - * @readonly - */ - #signingKey; - /** - * Creates a new BaseWallet for `privateKey`, optionally connected to `provider`. - * - * If `provider` is not specified, only offline methods can be used. - * - * @param {SigningKey} privateKey - The private key for the wallet. - * @param {null | Provider} [provider] - The provider to connect to. - */ - constructor(privateKey, provider) { - super(provider); - assertArgument(privateKey && typeof privateKey.sign === 'function', 'invalid private key', 'privateKey', '[ REDACTED ]'); - this.#signingKey = privateKey; - this.#address = computeAddress(this.signingKey.publicKey); - } - // Store private values behind getters to reduce visibility - /** - * The address of this wallet. - * @type {string} - * @readonly - */ - get address() { - return this.#address; - } - /** - * The {@link SigningKey | **SigningKey**} used for signing payloads. - * @type {SigningKey} - * @readonly - */ - get signingKey() { - return this.#signingKey; - } - /** - * The private key for this wallet. - * @type {string} - * @readonly - */ - get privateKey() { - return this.signingKey.privateKey; - } - // TODO: `_zone` is not used, should it be removed? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - /** - * Returns the address of this wallet. - * - * @param {string} [_zone] - The zone (optional). - * @returns {Promise} The wallet address. - */ - async getAddress(_zone) { - return this.#address; - } - /** - * Connects the wallet to a provider. - * - * @param {null | Provider} provider - The provider to connect to. - * @returns {BaseWallet} The connected wallet. - */ - connect(provider) { - return new BaseWallet(this.#signingKey, provider); - } - /** - * Signs a transaction. - * - * @param {QuaiTransactionRequest} tx - The transaction request. - * @returns {Promise} The signed transaction. - */ - async signTransaction(tx) { - // Replace any Addressable with an address - const { to, from } = await resolveProperties({ - to: tx.to ? resolveAddress(tx.to) : undefined, - from: tx.from ? resolveAddress(tx.from) : undefined, - }); - if (to !== undefined) { - validateAddress(to); - tx.to = to; - } - if (from !== undefined) { - assertArgument(getAddress(from) === this.#address, 'transaction from address mismatch', 'tx.from', from); - } - else { - // No `from` specified, use the wallet's address - tx.from = this.#address; - } - const btx = QuaiTransaction.from(tx); - const digest = keccak256(btx.unsignedSerialized); - btx.signature = this.signingKey.sign(digest); - return btx.serialized; - } - /** - * Signs a message. - * - * @param {string | Uint8Array} message - The message to sign. - * @returns {Promise} The signed message. - * @async - */ - async signMessage(message) { - return this.signMessageSync(message); - } - // @TODO: Add a secialized signTx and signTyped sync that enforces - // all parameters are known? - /** - * Returns the signature for `message` signed with this wallet. - * - * @param {string | Uint8Array} message - The message to sign. - * @returns {string} The serialized signature. - */ - signMessageSync(message) { - return this.signingKey.sign(hashMessage(message)).serialized; - } - /** - * Signs typed data. - * - * @param {TypedDataDomain} domain - The domain of the typed data. - * @param {Record>} types - The types of the typed data. - * @param {Record} value - The value of the typed data. - * @returns {Promise} The signed typed data. - * @async - */ - async signTypedData(domain, types, value) { - return this.signingKey.sign(TypedDataEncoder.hash(domain, types, value)).serialized; - } -} - -const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; -const Word = /^[a-z]*$/i; -function unfold(words, sep) { - let initial = 97; - return words.reduce((accum, word) => { - if (word === sep) { - initial++; - } - else if (word.match(Word)) { - accum.push(String.fromCharCode(initial) + word); - } - else { - initial = 97; - accum.push(word); - } - return accum; - }, []); -} -/** - * @ignore - */ -function decode(data, subs) { - // Replace all the substitutions with their expanded form - for (let i = subsChrs.length - 1; i >= 0; i--) { - data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); - } - // Get all tle clumps; each suffix, first-increment and second-increment - const clumps = []; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => { - if (semi) { - for (let i = parseInt(semi); i >= 0; i--) { - clumps.push(';'); - } - } - else { - clumps.push(item.toLowerCase()); - } - return ''; - }); - /* c8 ignore start */ - if (leftover) { - throw new Error(`leftovers: ${JSON.stringify(leftover)}`); - } - /* c8 ignore stop */ - return unfold(unfold(clumps, ';'), ':'); -} -/** - * @ignore - */ -function decodeOwl(data) { - assertArgument(data[0] === '0', 'unsupported auwl data', 'data', data); - return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); -} - -/** - * A Wordlist represents a collection of language-specific words used to encode and devoce - * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) encoded data by mapping words to 11-bit values and vice versa. - * - * @category Wordlists - */ -class Wordlist { - locale; - /** - * Creates a new Wordlist instance. - * - * Sub-classes MUST call this if they provide their own constructor, passing in the locale string of the language. - * - * Generally there is no need to create instances of a Wordlist, since each language-specific Wordlist creates an - * instance and there is no state kept internally, so they are safe to share. - */ - constructor(locale) { - defineProperties(this, { locale }); - } - /** - * Sub-classes may override this to provide a language-specific method for spliting `phrase` into individual words. - * - * By default, `phrase` is split using any sequences of white-space as defined by regular expressions (i.e. - * `/\s+/`). - * - * @param {string} phrase - The phrase to split. - * - * @returns {string[]} The split words in the phrase. - */ - split(phrase) { - return phrase.toLowerCase().split(/\s+/g); - } - /** - * Sub-classes may override this to provider a language-specific method for joining `words` into a phrase. - * - * By default, `words` are joined by a single space. - * - * @param {string[]} words - The words to join. - * - * @returns {string} The joined phrase. - */ - join(words) { - return words.join(' '); - } -} - -// Use the encode-latin.js script to create the necessary -// data files to be consumed by this class -/** - * An OWL format Wordlist is an encoding method that exploits the general locality of alphabetically sorted words to - * achieve a simple but effective means of compression. - * - * This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages - * based on ASCII-7 small. - * - * If necessary, there are tools within the `generation/` folder to create the necessary data. - * - * @category Wordlists - */ -class WordlistOwl extends Wordlist { - #data; - #checksum; - /** - * Creates a new Wordlist for `locale` using the OWL `data` and validated against the `checksum`. - */ - constructor(locale, data, checksum) { - super(locale); - this.#data = data; - this.#checksum = checksum; - this.#words = null; - } - /** - * The OWL-encoded data. - * - * @ignore - */ - get _data() { - return this.#data; - } - /** - * Decode all the words for the wordlist. - */ - _decodeWords() { - return decodeOwl(this.#data); - } - #words; - #loadWords() { - if (this.#words == null) { - const words = this._decodeWords(); - // Verify the computed list matches the official list - const checksum = id(words.join('\n') + '\n'); - /* c8 ignore start */ - if (checksum !== this.#checksum) { - throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); - } - /* c8 ignore stop */ - this.#words = words; - } - return this.#words; - } - getWord(index) { - const words = this.#loadWords(); - assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, 'index', index); - return words[index]; - } - getWordIndex(word) { - return this.#loadWords().indexOf(word); - } -} - -const words$1 = "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_{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 M3AgramAlAm#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/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-PM&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryFN Noc|PutQuirySSue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+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)IdeIghtImOgAyEakEelEmEpE*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~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO"; -const checksum$1 = '0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60'; -let wordlist$1 = null; -/** - * The [English wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt) for [mnemonic - * phrases](https://en.bitcoin.it/wiki/BIP_0039). - * - * @category Wordlists - */ -class LangEn extends WordlistOwl { - /** - * Creates a new instance of the English language Wordlist. - * - * This should be unnecessary most of the time as the exported {@link langEn} should suffice. - * - * @ignore - */ - constructor() { - super('en', words$1, checksum$1); - } - /** - * Returns a singleton instance of a `LangEn`, creating it if this is the first time being called. - */ - static wordlist() { - if (wordlist$1 == null) { - wordlist$1 = new LangEn(); - } - return wordlist$1; - } -} - -/** - * Returns a byte with the MSB bits set. - * - * @param {number} bits - The number of bits to set. - * @returns {number} The byte with the MSB bits set. - */ -function getUpperMask(bits) { - return (((1 << bits) - 1) << (8 - bits)) & 0xff; -} -/** - * Returns a byte with the LSB bits set. - * - * @param {number} bits - The number of bits to set. - * @returns {number} The byte with the LSB bits set. - */ -function getLowerMask(bits) { - return ((1 << bits) - 1) & 0xff; -} -/** - * Converts a mnemonic phrase to entropy. - * - * @param {string} mnemonic - The mnemonic phrase. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {string} The entropy. - */ -function mnemonicToEntropy(mnemonic, wordlist) { - assertNormalize('NFKD'); - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const words = wordlist.split(mnemonic); - assertArgument(words.length % 3 === 0 && words.length >= 12 && words.length <= 24, 'invalid mnemonic length', 'mnemonic', '[ REDACTED ]'); - const entropy = new Uint8Array(Math.ceil((11 * words.length) / 8)); - let offset = 0; - for (let i = 0; i < words.length; i++) { - const index = wordlist.getWordIndex(words[i].normalize('NFKD')); - assertArgument(index >= 0, `invalid mnemonic word at index ${i}`, 'mnemonic', '[ REDACTED ]'); - for (let bit = 0; bit < 11; bit++) { - if (index & (1 << (10 - bit))) { - entropy[offset >> 3] |= 1 << (7 - (offset % 8)); - } - offset++; - } - } - const entropyBits = (32 * words.length) / 3; - const checksumBits = words.length / 3; - const checksumMask = getUpperMask(checksumBits); - const checksum = getBytes(sha256(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; - assertArgument(checksum === (entropy[entropy.length - 1] & checksumMask), 'invalid mnemonic checksum', 'mnemonic', '[ REDACTED ]'); - return hexlify(entropy.slice(0, entropyBits / 8)); -} -/** - * Converts entropy to a mnemonic phrase. - * - * @param {Uint8Array} entropy - The entropy. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {string} The mnemonic phrase. - */ -function entropyToMnemonic(entropy, wordlist) { - assertArgument(entropy.length % 4 === 0 && entropy.length >= 16 && entropy.length <= 32, 'invalid entropy size', 'entropy', '[ REDACTED ]'); - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const indices = [0]; - let remainingBits = 11; - for (let i = 0; i < entropy.length; i++) { - // Consume the whole byte (with still more to go) - if (remainingBits > 8) { - indices[indices.length - 1] <<= 8; - indices[indices.length - 1] |= entropy[i]; - remainingBits -= 8; - // This byte will complete an 11-bit index - } - else { - indices[indices.length - 1] <<= remainingBits; - indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits); - // Start the next word - indices.push(entropy[i] & getLowerMask(8 - remainingBits)); - remainingBits += 3; - } - } - // Compute the checksum bits - const checksumBits = entropy.length / 4; - const checksum = parseInt(sha256(entropy).substring(2, 4), 16) & getUpperMask(checksumBits); - // Shift the checksum into the word indices - indices[indices.length - 1] <<= checksumBits; - indices[indices.length - 1] |= checksum >> (8 - checksumBits); - return wordlist.join(indices.map((index) => wordlist.getWord(index))); -} -const _guard$2 = {}; -/** - * A **Mnemonic** wraps all properties required to compute [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) seeds and - * convert between phrases and entropy. - * - * @category Wallet - */ -class Mnemonic { - /** - * The mnemonic phrase of 12, 15, 18, 21 or 24 words. - * - * Use the {@link wordlist | **wordlist**} `split` method to get the individual words. - */ - phrase; - /** - * The password used for this mnemonic. If no password is used this is the empty string (i.e. `""`) as per the - * specification. - */ - password; - /** - * The wordlist for this mnemonic. - */ - wordlist; - /** - * The underlying entropy which the mnemonic encodes. - */ - entropy; - /** - * @param {any} guard - The guard object. - * @param {string} entropy - The entropy. - * @param {string} phrase - The mnemonic phrase. - * @param {string} [password] - The password for the mnemonic. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - */ - constructor(guard, entropy, phrase, password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - assertPrivate(guard, _guard$2, 'Mnemonic'); - defineProperties(this, { phrase, password, wordlist, entropy }); - } - /** - * Returns the seed for the mnemonic. - * - * @returns {string} The seed. - */ - computeSeed() { - const salt = toUtf8Bytes('mnemonic' + this.password, 'NFKD'); - return pbkdf2(toUtf8Bytes(this.phrase, 'NFKD'), salt, 2048, 64, 'sha512'); - } - /** - * Creates a new Mnemonic for the `phrase`. - * - * The default `password` is the empty string and the default wordlist is the {@link LangEn | **English wordlist**}. - * - * @param {string} phrase - The mnemonic phrase. - * @param {string} [password] - The password for the mnemonic. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {Mnemonic} The new Mnemonic object. - */ - static fromPhrase(phrase, password, wordlist) { - // Normalize the case and space; throws if invalid - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - if (password == null) { - password = ''; - } - const entropy = mnemonicToEntropy(phrase, wordlist); - phrase = entropyToMnemonic(getBytes(entropy), wordlist); - return new Mnemonic(_guard$2, entropy, phrase, password, wordlist); - } - /** - * Create a new **Mnemonic** from the `entropy`. - * - * The default `password` is the empty string and the default wordlist is the [{@link LangEn | **English wordlist**}. - * - * @param {BytesLike} _entropy - The entropy for the mnemonic. - * @param {string} [password] - The password for the mnemonic. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {Mnemonic} The new Mnemonic object. - */ - static fromEntropy(_entropy, password, wordlist) { - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - if (password == null) { - password = ''; - } - const entropy = getBytes(_entropy, 'entropy'); - const phrase = entropyToMnemonic(entropy, wordlist); - return new Mnemonic(_guard$2, hexlify(entropy), phrase, password, wordlist); - } - /** - * Returns the phrase for `mnemonic`. - * - * @param {BytesLike} _entropy - The entropy for the mnemonic. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {string} The mnemonic phrase. - */ - static entropyToPhrase(_entropy, wordlist) { - const entropy = getBytes(_entropy, 'entropy'); - return entropyToMnemonic(entropy, wordlist); - } - /** - * Returns the entropy for `phrase`. - * - * @param {string} phrase - The mnemonic phrase. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {string} The entropy. - */ - static phraseToEntropy(phrase, wordlist) { - return mnemonicToEntropy(phrase, wordlist); - } - /** - * Returns true if `phrase` is a valid [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) phrase. - * - * This checks all the provided words belong to the `wordlist`, that the length is valid and the checksum is - * correct. - * - * @param {string} phrase - The mnemonic phrase. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {boolean} True if the phrase is valid. - * @throws {Error} If the phrase is invalid. - */ - static isValidMnemonic(phrase, wordlist) { - try { - mnemonicToEntropy(phrase, wordlist); - return true; - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; - } -} - -/*! MIT License. Copyright 2015-2022 Richard Moore . See LICENSE.txt. */ -var __classPrivateFieldGet$1 = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __classPrivateFieldSet$1 = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var _AES_key, _AES_Kd, _AES_Ke; -// Number of rounds by keysize -const numberOfRounds = { 16: 10, 24: 12, 32: 14 }; -// Round constant words -const rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91]; -// S-box and Inverse S-box (S is for Substitution) -const S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]; -const Si = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d]; -// Transformations for encryption -const T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a]; -const T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616]; -const T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16]; -const T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c]; -// Transformations for decryption -const T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742]; -const T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857]; -const T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8]; -const T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0]; -// Transformations for decryption key expansion -const U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]; -const U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697]; -const U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46]; -const U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d]; -function convertToInt32(bytes) { - const result = []; - for (let i = 0; i < bytes.length; i += 4) { - result.push((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]); - } - return result; -} -class AES { - get key() { return __classPrivateFieldGet$1(this, _AES_key, "f").slice(); } - constructor(key) { - _AES_key.set(this, void 0); - _AES_Kd.set(this, void 0); - _AES_Ke.set(this, void 0); - if (!(this instanceof AES)) { - throw Error('AES must be instanitated with `new`'); - } - __classPrivateFieldSet$1(this, _AES_key, new Uint8Array(key), "f"); - const rounds = numberOfRounds[this.key.length]; - if (rounds == null) { - throw new TypeError('invalid key size (must be 16, 24 or 32 bytes)'); - } - // encryption round keys - __classPrivateFieldSet$1(this, _AES_Ke, [], "f"); - // decryption round keys - __classPrivateFieldSet$1(this, _AES_Kd, [], "f"); - for (let i = 0; i <= rounds; i++) { - __classPrivateFieldGet$1(this, _AES_Ke, "f").push([0, 0, 0, 0]); - __classPrivateFieldGet$1(this, _AES_Kd, "f").push([0, 0, 0, 0]); - } - const roundKeyCount = (rounds + 1) * 4; - const KC = this.key.length / 4; - // convert the key into ints - const tk = convertToInt32(this.key); - // copy values into round key arrays - let index; - for (let i = 0; i < KC; i++) { - index = i >> 2; - __classPrivateFieldGet$1(this, _AES_Ke, "f")[index][i % 4] = tk[i]; - __classPrivateFieldGet$1(this, _AES_Kd, "f")[rounds - index][i % 4] = tk[i]; - } - // key expansion (fips-197 section 5.2) - let rconpointer = 0; - let t = KC, tt; - while (t < roundKeyCount) { - tt = tk[KC - 1]; - tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^ - (S[(tt >> 8) & 0xFF] << 16) ^ - (S[tt & 0xFF] << 8) ^ - S[(tt >> 24) & 0xFF] ^ - (rcon[rconpointer] << 24)); - rconpointer += 1; - // key expansion (for non-256 bit) - if (KC != 8) { - for (let i = 1; i < KC; i++) { - tk[i] ^= tk[i - 1]; - } - // key expansion for 256-bit keys is "slightly different" (fips-197) - } - else { - for (let i = 1; i < (KC / 2); i++) { - tk[i] ^= tk[i - 1]; - } - tt = tk[(KC / 2) - 1]; - tk[KC / 2] ^= (S[tt & 0xFF] ^ - (S[(tt >> 8) & 0xFF] << 8) ^ - (S[(tt >> 16) & 0xFF] << 16) ^ - (S[(tt >> 24) & 0xFF] << 24)); - for (let i = (KC / 2) + 1; i < KC; i++) { - tk[i] ^= tk[i - 1]; - } - } - // copy values into round key arrays - let i = 0, r, c; - while (i < KC && t < roundKeyCount) { - r = t >> 2; - c = t % 4; - __classPrivateFieldGet$1(this, _AES_Ke, "f")[r][c] = tk[i]; - __classPrivateFieldGet$1(this, _AES_Kd, "f")[rounds - r][c] = tk[i++]; - t++; - } - } - // inverse-cipher-ify the decryption round key (fips-197 section 5.3) - for (let r = 1; r < rounds; r++) { - for (let c = 0; c < 4; c++) { - tt = __classPrivateFieldGet$1(this, _AES_Kd, "f")[r][c]; - __classPrivateFieldGet$1(this, _AES_Kd, "f")[r][c] = (U1[(tt >> 24) & 0xFF] ^ - U2[(tt >> 16) & 0xFF] ^ - U3[(tt >> 8) & 0xFF] ^ - U4[tt & 0xFF]); - } - } - } - encrypt(plaintext) { - if (plaintext.length != 16) { - throw new TypeError('invalid plaintext size (must be 16 bytes)'); - } - const rounds = __classPrivateFieldGet$1(this, _AES_Ke, "f").length - 1; - const a = [0, 0, 0, 0]; - // convert plaintext to (ints ^ key) - let t = convertToInt32(plaintext); - for (let i = 0; i < 4; i++) { - t[i] ^= __classPrivateFieldGet$1(this, _AES_Ke, "f")[0][i]; - } - // apply round transforms - for (let r = 1; r < rounds; r++) { - for (let i = 0; i < 4; i++) { - a[i] = (T1[(t[i] >> 24) & 0xff] ^ - T2[(t[(i + 1) % 4] >> 16) & 0xff] ^ - T3[(t[(i + 2) % 4] >> 8) & 0xff] ^ - T4[t[(i + 3) % 4] & 0xff] ^ - __classPrivateFieldGet$1(this, _AES_Ke, "f")[r][i]); - } - t = a.slice(); - } - // the last round is special - const result = new Uint8Array(16); - let tt = 0; - for (let i = 0; i < 4; i++) { - tt = __classPrivateFieldGet$1(this, _AES_Ke, "f")[rounds][i]; - result[4 * i] = (S[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; - result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; - result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; - result[4 * i + 3] = (S[t[(i + 3) % 4] & 0xff] ^ tt) & 0xff; - } - return result; - } - decrypt(ciphertext) { - if (ciphertext.length != 16) { - throw new TypeError('invalid ciphertext size (must be 16 bytes)'); - } - const rounds = __classPrivateFieldGet$1(this, _AES_Kd, "f").length - 1; - const a = [0, 0, 0, 0]; - // convert plaintext to (ints ^ key) - let t = convertToInt32(ciphertext); - for (let i = 0; i < 4; i++) { - t[i] ^= __classPrivateFieldGet$1(this, _AES_Kd, "f")[0][i]; - } - // apply round transforms - for (let r = 1; r < rounds; r++) { - for (let i = 0; i < 4; i++) { - a[i] = (T5[(t[i] >> 24) & 0xff] ^ - T6[(t[(i + 3) % 4] >> 16) & 0xff] ^ - T7[(t[(i + 2) % 4] >> 8) & 0xff] ^ - T8[t[(i + 1) % 4] & 0xff] ^ - __classPrivateFieldGet$1(this, _AES_Kd, "f")[r][i]); - } - t = a.slice(); - } - // the last round is special - const result = new Uint8Array(16); - let tt = 0; - for (let i = 0; i < 4; i++) { - tt = __classPrivateFieldGet$1(this, _AES_Kd, "f")[rounds][i]; - result[4 * i] = (Si[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; - result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; - result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; - result[4 * i + 3] = (Si[t[(i + 1) % 4] & 0xff] ^ tt) & 0xff; - } - return result; - } -} -_AES_key = new WeakMap(), _AES_Kd = new WeakMap(), _AES_Ke = new WeakMap(); - -class ModeOfOperation { - constructor(name, key, cls) { - if (cls && !(this instanceof cls)) { - throw new Error(`${name} must be instantiated with "new"`); - } - Object.defineProperties(this, { - aes: { enumerable: true, value: new AES(key) }, - name: { enumerable: true, value: name } - }); - } -} - -// Counter Mode -var __classPrivateFieldSet = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var __classPrivateFieldGet = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _CTR_remaining, _CTR_remainingIndex, _CTR_counter; -class CTR extends ModeOfOperation { - constructor(key, initialValue) { - super("CTR", key, CTR); - // Remaining bytes for the one-time pad - _CTR_remaining.set(this, void 0); - _CTR_remainingIndex.set(this, void 0); - // The current counter - _CTR_counter.set(this, void 0); - __classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), "f"); - __classPrivateFieldGet(this, _CTR_counter, "f").fill(0); - __classPrivateFieldSet(this, _CTR_remaining, __classPrivateFieldGet(this, _CTR_counter, "f"), "f"); // This will be discarded immediately - __classPrivateFieldSet(this, _CTR_remainingIndex, 16, "f"); - if (initialValue == null) { - initialValue = 1; - } - if (typeof (initialValue) === "number") { - this.setCounterValue(initialValue); - } - else { - this.setCounterBytes(initialValue); - } - } - get counter() { return new Uint8Array(__classPrivateFieldGet(this, _CTR_counter, "f")); } - setCounterValue(value) { - if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) { - throw new TypeError("invalid counter initial integer value"); - } - for (let index = 15; index >= 0; --index) { - __classPrivateFieldGet(this, _CTR_counter, "f")[index] = value % 256; - value = Math.floor(value / 256); - } - } - setCounterBytes(value) { - if (value.length !== 16) { - throw new TypeError("invalid counter initial Uint8Array value length"); - } - __classPrivateFieldGet(this, _CTR_counter, "f").set(value); - } - increment() { - for (let i = 15; i >= 0; i--) { - if (__classPrivateFieldGet(this, _CTR_counter, "f")[i] === 255) { - __classPrivateFieldGet(this, _CTR_counter, "f")[i] = 0; - } - else { - __classPrivateFieldGet(this, _CTR_counter, "f")[i]++; - break; - } - } - } - encrypt(plaintext) { - var _a, _b; - const crypttext = new Uint8Array(plaintext); - for (let i = 0; i < crypttext.length; i++) { - if (__classPrivateFieldGet(this, _CTR_remainingIndex, "f") === 16) { - __classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet(this, _CTR_counter, "f")), "f"); - __classPrivateFieldSet(this, _CTR_remainingIndex, 0, "f"); - this.increment(); - } - crypttext[i] ^= __classPrivateFieldGet(this, _CTR_remaining, "f")[__classPrivateFieldSet(this, _CTR_remainingIndex, (_b = __classPrivateFieldGet(this, _CTR_remainingIndex, "f"), _a = _b++, _b), "f"), _a]; - } - return crypttext; - } - decrypt(ciphertext) { - return this.encrypt(ciphertext); - } -} -_CTR_remaining = new WeakMap(), _CTR_remainingIndex = new WeakMap(), _CTR_counter = new WeakMap(); - -/** - * @module wallet/utils - */ -/** - * Converts a hex string to a Uint8Array. If the string does not start with '0x', it adds it. - * @param {string} hexString - The hex string to convert. - * @returns {Uint8Array} The resulting byte array. - */ -function looseArrayify(hexString) { - if (typeof hexString === 'string' && !hexString.startsWith('0x')) { - hexString = '0x' + hexString; - } - return getBytesCopy(hexString); -} -/** - * Converts a password to a Uint8Array. If the password is a string, it converts it to UTF-8 bytes. - * @param {string|Uint8Array} password - The password to convert. - * @returns {Uint8Array} The resulting byte array. - */ -function getPassword(password) { - if (typeof password === 'string') { - return toUtf8Bytes(password, 'NFKC'); - } - return getBytesCopy(password); -} -/** - * Traverses an object based on a path and returns the value at that path. - * @param {any} object - The object to traverse. - * @param {string} _path - The path to traverse. - * @returns {T} The value at the specified path. - */ -function spelunk(object, _path) { - const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i); - assertArgument(match != null, 'invalid path', 'path', _path); - const path = match[1]; - const type = match[3]; - const reqd = match[4] === '!'; - let cur = object; - for (const comp of path.toLowerCase().split('.')) { - // Search for a child object with a case-insensitive matching key - if (Array.isArray(cur)) { - if (!comp.match(/^[0-9]+$/)) { - break; - } - cur = cur[parseInt(comp)]; - } - else if (typeof cur === 'object') { - let found = null; - for (const key in cur) { - if (key.toLowerCase() === comp) { - found = cur[key]; - break; - } - } - cur = found; - } - else { - cur = null; - } - if (cur == null) { - break; - } - } - assertArgument(!reqd || cur != null, 'missing required value', 'path', path); - if (type && cur != null) { - if (type === 'int') { - if (typeof cur === 'string' && cur.match(/^-?[0-9]+$/)) { - return parseInt(cur); - } - else if (Number.isSafeInteger(cur)) { - return cur; - } - } - if (type === 'number') { - if (typeof cur === 'string' && cur.match(/^-?[0-9.]*$/)) { - return parseFloat(cur); - } - } - if (type === 'data') { - if (typeof cur === 'string') { - return looseArrayify(cur); - } - } - if (type === 'array' && Array.isArray(cur)) { - return cur; - } - if (type === typeof cur) { - return cur; - } - assertArgument(false, `wrong type found for ${type} `, 'path', path); - } - return cur; -} -/** Constant N used in cryptographic operations */ -BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); -/** - * Pads a value with leading zeros to a specified length. - * @param {string|number} value - The value to pad. - * @param {number} length - The desired length. - * @returns {string} The padded value. - */ -function zpad$1(value, length) { - // Determine if the value is hexadecimal - const isHex = typeof value === 'string' && value.startsWith('0x'); - // Handle hexadecimal values - if (isHex) { - let hexValue = value.substring(2); // Remove the "0x" prefix - while (hexValue.length < length * 2) { - // Hexadecimal characters count double - hexValue = '0' + hexValue; - } - return '0x' + hexValue; - } - // Handle numbers or non-hexadecimal strings - let result = String(value); - while (result.length < length) { - result = '0' + result; - } - return result; -} - -/** - * The JSON Wallet formats allow a simple way to store the private keys needed in Ethereum along with related - * information and allows for extensible forms of encryption. - * - * These utilities facilitate decrypting and encrypting the most common JSON Wallet formats. - */ -const defaultPath = "m/44'/994'/0'/0/0"; -/** - * Returns true if `json` is a valid JSON Keystore Wallet. - * - * @category Wallet - * @param {string} json - The JSON data to check. - * - * @returns {boolean} True if the JSON data is a valid Keystore Wallet. - */ -function isKeystoreJson(json) { - try { - const data = JSON.parse(json); - const version = data.version != null ? parseInt(data.version) : 0; - if (version === 3) { - return true; - } - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; -} -/** - * Decrypts the given ciphertext using the provided key and data. - * - * @param {any} data - The data containing encryption parameters. - * @param {Uint8Array} key - The key to use for decryption. - * @param {Uint8Array} ciphertext - The ciphertext to decrypt. - * - * @returns {string} The decrypted data as a hex string. - */ -function decrypt(data, key, ciphertext) { - const cipher = spelunk(data, 'crypto.cipher:string'); - if (cipher === 'aes-128-ctr') { - const iv = spelunk(data, 'crypto.cipherparams.iv:data!'); - const aesCtr = new CTR(key, iv); - return hexlify(aesCtr.decrypt(ciphertext)); - } - assert(false, 'unsupported cipher', 'UNSUPPORTED_OPERATION', { - operation: 'decrypt', - }); -} -/** - * Retrieves the account details from the given data and key. - * - * @param {any} data - The data containing account information. - * @param {string} _key - The key to use for decryption. - * - * @returns {KeystoreAccount} The decrypted account details. - */ -function getAccount(data, _key) { - const key = getBytes(_key); - const ciphertext = spelunk(data, 'crypto.ciphertext:data!'); - const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2); - assertArgument(computedMAC === spelunk(data, 'crypto.mac:string!').toLowerCase(), 'incorrect password', 'password', '[ REDACTED ]'); - const privateKey = decrypt(data, key.slice(0, 16), ciphertext); - const address = computeAddress(privateKey); - if (data.address) { - let check = data.address.toLowerCase(); - if (!check.startsWith('0x')) { - check = '0x' + check; - } - assertArgument(getAddress(check) === address, 'keystore address/privateKey mismatch', 'address', data.address); - } - const account = { address, privateKey }; - // Version 0.1 x-quais metadata must contain an encrypted mnemonic phrase - const version = spelunk(data, 'x-quais.version:string'); - if (version === '0.1') { - const mnemonicKey = key.slice(32, 64); - const mnemonicCiphertext = spelunk(data, 'x-quais.mnemonicCiphertext:data!'); - const mnemonicIv = spelunk(data, 'x-quais.mnemonicCounter:data!'); - const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); - account.mnemonic = { - path: spelunk(data, 'x-quais.path:string') || defaultPath, - locale: spelunk(data, 'x-quais.locale:string') || 'en', - entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))), - }; - } - return account; -} -/** - * Retrieves the key derivation function parameters from the given data. - * - * @param {any} data - The data containing KDF parameters. - * - * @returns {KdfParams} The key derivation function parameters. - */ -function getDecryptKdfParams(data) { - const kdf = spelunk(data, 'crypto.kdf:string'); - if (kdf && typeof kdf === 'string') { - if (kdf.toLowerCase() === 'scrypt') { - const salt = spelunk(data, 'crypto.kdfparams.salt:data!'); - const N = spelunk(data, 'crypto.kdfparams.n:int!'); - const r = spelunk(data, 'crypto.kdfparams.r:int!'); - const p = spelunk(data, 'crypto.kdfparams.p:int!'); - // Make sure N is a power of 2 - assertArgument(N > 0 && (N & (N - 1)) === 0, 'invalid kdf.N', 'kdf.N', N); - assertArgument(r > 0 && p > 0, 'invalid kdf', 'kdf', kdf); - const dkLen = spelunk(data, 'crypto.kdfparams.dklen:int!'); - assertArgument(dkLen === 32, 'invalid kdf.dklen', 'kdf.dflen', dkLen); - return { name: 'scrypt', salt, N, r, p, dkLen: 64 }; - } - else if (kdf.toLowerCase() === 'pbkdf2') { - const salt = spelunk(data, 'crypto.kdfparams.salt:data!'); - const prf = spelunk(data, 'crypto.kdfparams.prf:string!'); - const algorithm = prf.split('-').pop(); - assertArgument(algorithm === 'sha256' || algorithm === 'sha512', 'invalid kdf.pdf', 'kdf.pdf', prf); - const count = spelunk(data, 'crypto.kdfparams.c:int!'); - const dkLen = spelunk(data, 'crypto.kdfparams.dklen:int!'); - assertArgument(dkLen === 32, 'invalid kdf.dklen', 'kdf.dklen', dkLen); - return { name: 'pbkdf2', salt, count, dkLen, algorithm }; - } - } - assertArgument(false, 'unsupported key-derivation function', 'kdf', kdf); -} -/** - * Returns the account details for the JSON Keystore Wallet `json` using `password`. - * - * It is preferred to use the {@link decryptKeystoreJson | **async version**} instead, which allows a - * {@link ProgressCallback | **ProgressCallback} to keep the user informed as to the decryption status. - * - * This method will block the event loop (freezing all UI) until decryption is complete, which can take quite some time, - * depending on the wallet paramters and platform. - * - * @category Wallet - * @param {string} json - The JSON data to decrypt. - * @param {string | Uint8Array} _password - The password to decrypt the JSON data. - * - * @returns {KeystoreAccount} The decrypted account. - */ -function decryptKeystoreJsonSync(json, _password) { - const data = JSON.parse(json); - const password = getPassword(_password); - const params = getDecryptKdfParams(data); - if (params.name === 'pbkdf2') { - const { salt, count, dkLen, algorithm } = params; - const key = pbkdf2(password, salt, count, dkLen, algorithm); - return getAccount(data, key); - } - assert(params.name === 'scrypt', 'cannot be reached', 'UNKNOWN_ERROR', { params }); - const { salt, N, r, p, dkLen } = params; - const key = scryptSync(password, salt, N, r, p, dkLen); - return getAccount(data, key); -} -/** - * Pauses execution for the specified duration. - * - * @param {number} duration - The duration to stall in milliseconds. - * - * @returns {Promise} A promise that resolves after the specified duration. - */ -function stall$1(duration) { - return new Promise((resolve) => { - setTimeout(() => { - resolve(); - }, duration); - }); -} -/** - * Resolves to the decrypted JSON Keystore Wallet `json` using the `password`. - * - * If provided, `progress` will be called periodically during the decrpytion to provide feedback, and if the function - * returns `false` will halt decryption. - * - * The `progressCallback` will **always** receive `0` before decryption begins and `1` when complete. - * - * @category Wallet - * @param {string} json - The JSON data to decrypt. - * @param {string | Uint8Array} _password - The password to decrypt the JSON data. - * @param {ProgressCallback} [progress] - The callback to receive progress updates. - * - * @returns {Promise} The decrypted account. - */ -async function decryptKeystoreJson(json, _password, progress) { - const data = JSON.parse(json); - const password = getPassword(_password); - const params = getDecryptKdfParams(data); - if (params.name === 'pbkdf2') { - if (progress) { - progress(0); - await stall$1(0); - } - const { salt, count, dkLen, algorithm } = params; - const key = pbkdf2(password, salt, count, dkLen, algorithm); - if (progress) { - progress(1); - await stall$1(0); - } - return getAccount(data, key); - } - assert(params.name === 'scrypt', 'cannot be reached', 'UNKNOWN_ERROR', { params }); - const { salt, N, r, p, dkLen } = params; - const key = await scrypt(password, salt, N, r, p, dkLen, progress); - return getAccount(data, key); -} -/** - * Retrieves the key derivation function parameters for encryption. - * - * @param {EncryptOptions} options - The encryption options. - * - * @returns {ScryptParams} The key derivation function parameters. - */ -function getEncryptKdfParams(options) { - // Check/generate the salt - const salt = options.salt != null ? getBytes(options.salt, 'options.salt') : randomBytes(32); - // Override the scrypt password-based key derivation function parameters - let N = 1 << 17, r = 8, p = 1; - if (options.scrypt) { - if (options.scrypt.N) { - N = options.scrypt.N; - } - if (options.scrypt.r) { - r = options.scrypt.r; - } - if (options.scrypt.p) { - p = options.scrypt.p; - } - } - assertArgument(typeof N === 'number' && N > 0 && Number.isSafeInteger(N) && (BigInt(N) & BigInt(N - 1)) === BigInt(0), 'invalid scrypt N parameter', 'options.N', N); - assertArgument(typeof r === 'number' && r > 0 && Number.isSafeInteger(r), 'invalid scrypt r parameter', 'options.r', r); - assertArgument(typeof p === 'number' && p > 0 && Number.isSafeInteger(p), 'invalid scrypt p parameter', 'options.p', p); - return { name: 'scrypt', dkLen: 32, salt, N, r, p }; -} -/** - * Encrypts the keystore with the given key, KDF parameters, account, and options. - * - * @ignore - * @param {Uint8Array} key - The key to use for encryption. - * @param {ScryptParams} kdf - The key derivation function parameters. - * @param {KeystoreAccount} account - The account to encrypt. - * @param {EncryptOptions} options - The encryption options. - * - * @returns {any} The encrypted keystore data. - */ -function _encryptKeystore(key, kdf, account, options) { - const privateKey = getBytes(account.privateKey, 'privateKey'); - // Override initialization vector - const iv = options.iv != null ? getBytes(options.iv, 'options.iv') : randomBytes(16); - assertArgument(iv.length === 16, 'invalid options.iv length', 'options.iv', options.iv); - // Override the uuid - const uuidRandom = options.uuid != null ? getBytes(options.uuid, 'options.uuid') : randomBytes(16); - assertArgument(uuidRandom.length === 16, 'invalid options.uuid length', 'options.uuid', options.iv); - // This will be used to encrypt the wallet (as per Web3 secret storage) - // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix) - // - 32 bytes AES key to encrypt mnemonic with (required here to be quais Wallet) - const derivedKey = key.slice(0, 16); - const macPrefix = key.slice(16, 32); - // Encrypt the private key - const aesCtr = new CTR(derivedKey, iv); - const ciphertext = getBytes(aesCtr.encrypt(privateKey)); - // Compute the message authentication code, used to check the password - const mac = keccak256(concat([macPrefix, ciphertext])); - // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition - const data = { - address: account.address.substring(2).toLowerCase(), - id: uuidV4(uuidRandom), - version: 3, - Crypto: { - cipher: 'aes-128-ctr', - cipherparams: { - iv: hexlify(iv).substring(2), - }, - ciphertext: hexlify(ciphertext).substring(2), - kdf: 'scrypt', - kdfparams: { - salt: hexlify(kdf.salt).substring(2), - n: kdf.N, - dklen: 32, - p: kdf.p, - r: kdf.r, - }, - mac: mac.substring(2), - }, - }; - // If we have a mnemonic, encrypt it into the JSON wallet - if (account.mnemonic) { - const client = options.client != null ? options.client : `quais/${version}`; - const path = account.mnemonic.path || defaultPath; - const locale = account.mnemonic.locale || 'en'; - const mnemonicKey = key.slice(32, 64); - const entropy = getBytes(account.mnemonic.entropy, 'account.mnemonic.entropy'); - const mnemonicIv = randomBytes(16); - const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); - const mnemonicCiphertext = getBytes(mnemonicAesCtr.encrypt(entropy)); - const now = new Date(); - const timestamp = now.getUTCFullYear() + - '-' + - zpad$1(now.getUTCMonth() + 1, 2) + - '-' + - zpad$1(now.getUTCDate(), 2) + - 'T' + - zpad$1(now.getUTCHours(), 2) + - '-' + - zpad$1(now.getUTCMinutes(), 2) + - '-' + - zpad$1(now.getUTCSeconds(), 2) + - '.0Z'; - const gethFilename = 'UTC--' + timestamp + '--' + data.address; - data['x-quais'] = { - client, - gethFilename, - path, - locale, - mnemonicCounter: hexlify(mnemonicIv).substring(2), - mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2), - version: '0.1', - }; - } - return JSON.stringify(data); -} -/** - * Return the JSON Keystore Wallet for `account` encrypted with `password`. - * - * The `options` can be used to tune the password-based key derivation function parameters, explicitly set the random - * values used. Any provided {@link ProgressCallback | **ProgressCallback**} is ignored. - * - * @category Wallet - * @param {KeystoreAccount} account - The account to encrypt. - * @param {string | Uint8Array} password - The password to encrypt the JSON data. - * @param {EncryptOptions} [options] - The options to use when encrypting the JSON data. - * - * @returns {string} The encrypted JSON data. - */ -function encryptKeystoreJsonSync(account, password, options) { - if (options == null) { - options = {}; - } - const passwordBytes = getPassword(password); - const kdf = getEncryptKdfParams(options); - const key = scryptSync(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64); - return _encryptKeystore(getBytes(key), kdf, account, options); -} -/** - * Resolved to the JSON Keystore Wallet for `account` encrypted with `password`. - * - * The `options` can be used to tune the password-based key derivation function parameters, explicitly set the random - * values used and provide a {@link ProgressCallback | **ProgressCallback**} to receive periodic updates on the - * completion status.. - * - * @category Wallet - * @param {KeystoreAccount} account - The account to encrypt. - * @param {string | Uint8Array} password - The password to encrypt the JSON data. - * @param {EncryptOptions} [options] - The options to use when encrypting the JSON data. - * - * @returns {Promise} The encrypted JSON data. - */ -async function encryptKeystoreJson(account, password, options) { - if (options == null) { - options = {}; - } - const passwordBytes = getPassword(password); - const kdf = getEncryptKdfParams(options); - const key = await scrypt(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64, options.progressCallback); - return _encryptKeystore(getBytes(key), kdf, account, options); -} - -// "Bitcoin seed" -const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]); -const HardenedBit = 0x80000000; -const N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); -const Nibbles = '0123456789abcdef'; -function zpad(value, length) { - let result = ''; - while (value) { - result = Nibbles[value % 16] + result; - value = Math.trunc(value / 16); - } - while (result.length < length * 2) { - result = '0' + result; - } - return '0x' + result; -} -function encodeBase58Check(_value) { - const value = getBytes(_value); - const check = dataSlice(sha256(sha256(value)), 0, 4); - const bytes = concat([value, check]); - return encodeBase58(bytes); -} -const _guard$1 = {}; -function ser_I(index, chainCode, publicKey, privateKey) { - const data = new Uint8Array(37); - if (index & HardenedBit) { - assert(privateKey != null, 'cannot derive child of neutered node', 'UNSUPPORTED_OPERATION', { - operation: 'deriveChild', - }); - // Data = 0x00 || ser_256(k_par) - data.set(getBytes(privateKey), 1); - } - else { - // Data = ser_p(point(k_par)) - data.set(getBytes(publicKey)); - } - // Data += ser_32(i) - for (let i = 24; i >= 0; i -= 8) { - data[33 + (i >> 3)] = (index >> (24 - i)) & 0xff; - } - const I = getBytes(computeHmac('sha512', chainCode, data)); - return { IL: I.slice(0, 32), IR: I.slice(32) }; -} -function derivePath(node, path) { - const components = path.split('/'); - assertArgument(components.length > 0, 'invalid path', 'path', path); - if (components[0] === 'm') { - 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); - components.shift(); - } - let result = node; - for (let i = 0; i < components.length; i++) { - const component = components[i]; - if (component.match(/^[0-9]+'$/)) { - const index = parseInt(component.substring(0, component.length - 1)); - assertArgument(index < HardenedBit, 'invalid path index', `path[${i}]`, component); - result = result.deriveChild(HardenedBit + index); - } - else if (component.match(/^[0-9]+$/)) { - const index = parseInt(component); - assertArgument(index < HardenedBit, 'invalid path index', `path[${i}]`, component); - result = result.deriveChild(index); - } - else { - assertArgument(false, 'invalid path component', `path[${i}]`, component); - } - } - return result; -} -/** - * An **HDNodeWallet** is a [[Signer]] backed by the private key derived from an HD Node using the [[link-bip-32]] - * standard. - * - * An HD Node forms a hierarchical structure with each HD Node having a private key and the ability to derive child HD - * Nodes, defined by a path indicating the index of each child. - */ -class HDNodeWallet extends BaseWallet { - /** - * The compressed public key. - * - * @type {string} - */ - publicKey; - /** - * The fingerprint. - * - * A fingerprint allows a quick way to detect parent and child nodes, but developers should be prepared to deal with - * collisions as it is only 4 bytes. - * - * @type {string} - */ - fingerprint; - /** - * The parent fingerprint. - * - * @type {string} - */ - parentFingerprint; - /** - * The mnemonic used to create this HD Node, if available. - * - * Sources such as extended keys do not encode the mnemonic, in which case this will be `null`. - * - * @type {null | Mnemonic} - */ - mnemonic; - /** - * The chaincode, which is effectively a public key used to derive children. - * - * @type {string} - */ - chainCode; - /** - * The derivation path of this wallet. - * - * Since extended keys do not provide full path details, this may be `null`, if instantiated from a source that does - * not encode it. - * - * @type {null | string} - */ - path; - /** - * The child index of this wallet. Values over `2 ** 31` indicate the node is hardened. - * - * @type {number} - */ - index; - /** - * The depth of this wallet, which is the number of components in its path. - * - * @type {number} - */ - depth; - /** - * @param {any} guard - * @param {SigningKey} signingKey - * @param {string} parentFingerprint - * @param {string} chainCode - * @param {null | string} path - * @param {number} index - * @param {number} depth - * @param {null | Mnemonic} mnemonic - * @param {null | Provider} provider - * @ignore - */ - constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider) { - super(signingKey, provider); - assertPrivate(guard, _guard$1, 'HDNodeWallet'); - defineProperties(this, { publicKey: signingKey.compressedPublicKey }); - const fingerprint = dataSlice(ripemd160(sha256(this.publicKey)), 0, 4); - defineProperties(this, { - parentFingerprint, - fingerprint, - chainCode, - path, - index, - depth, - }); - defineProperties(this, { mnemonic }); - } - /** - * Connects the wallet to a provider. - * - * @param {null | Provider} provider - * - * @returns {HDNodeWallet} - */ - connect(provider) { - return new HDNodeWallet(_guard$1, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider); - } - /** - * @returns {KeystoreAccount} - * @ignore - */ - #account() { - const account = { address: this.address, privateKey: this.privateKey }; - const m = this.mnemonic; - if (this.path && m && m.wordlist.locale === 'en' && m.password === '') { - account.mnemonic = { - path: this.path, - locale: 'en', - entropy: m.entropy, - }; - } - return account; - } - /** - * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with `password`. - * - * If `progressCallback` is specified, it will receive periodic updates as the encryption process progresses. - * - * @param {Uint8Array | string} password - * @param {ProgressCallback} [progressCallback] - * - * @returns {Promise} - */ - async encrypt(password, progressCallback) { - return await encryptKeystoreJson(this.#account(), password, { progressCallback }); - } - /** - * Returns a [JSON Keystore Wallet](json-wallets) encrypted with `password`. - * - * It is preferred to use the [async version](encrypt) instead, which allows a `ProgressCallback` to keep the user - * informed. - * - * This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial - * duration. - * - * @param {Uint8Array | string} password - * - * @returns {string} - */ - encryptSync(password) { - return encryptKeystoreJsonSync(this.#account(), password); - } - /** - * The extended key. - * - * This key will begin with the prefix `xpriv` and can be used to reconstruct this HD Node to derive its children. - * - * @returns {string} - */ - get extendedKey() { - // We only support the mainnet values for now, but if anyone needs - // testnet values, let me know. I believe current sentiment is that - // we should always use mainnet, and use BIP-44 to derive the network - // - Mainnet: public=0x0488B21E, private=0x0488ADE4 - // - Testnet: public=0x043587CF, private=0x04358394 - assert(this.depth < 256, 'Depth too deep', 'UNSUPPORTED_OPERATION', { - operation: 'extendedKey', - }); - return encodeBase58Check(concat([ - '0x0488ADE4', - zpad(this.depth, 1), - this.parentFingerprint, - zpad(this.index, 4), - this.chainCode, - concat(['0x00', this.privateKey]), - ])); - } - /** - * Returns true if this wallet has a path, providing a Type Guard that the path is non-null. - * - * @returns {boolean} - */ - hasPath() { - return this.path != null; - } - /** - * Returns a neutered HD Node, which removes the private details of an HD Node. - * - * A neutered node has no private key, but can be used to derive child addresses and other public data about the HD - * Node. - * - * @returns {HDNodeVoidWallet} - */ - neuter() { - return new HDNodeVoidWallet(_guard$1, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider); - } - /** - * Return the child for `index`. - * - * @param {Numeric} _index - * - * @returns {HDNodeWallet} - */ - deriveChild(_index) { - const index = getNumber(_index, 'index'); - assertArgument(index <= 0xffffffff, 'invalid index', 'index', index); - // Base path - let path = this.path; - if (path) { - path += '/' + (index & ~HardenedBit); - if (index & HardenedBit) { - path += "'"; - } - } - const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey); - const ki = new SigningKey(toBeHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32)); - return new HDNodeWallet(_guard$1, ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.mnemonic, this.provider); - } - /** - * Return the HDNode for `path` from this node. - * - * @param {string} path - * - * @returns {HDNodeWallet} - */ - derivePath(path) { - return derivePath(this, path); - } - /** - - * @param {BytesLike} _seed - * @param {null | Mnemonic} mnemonic - * - * @returns {HDNodeWallet} - * @ignore - */ - static #fromSeed(_seed, mnemonic) { - assertArgument(isBytesLike(_seed), 'invalid seed', 'seed', '[REDACTED]'); - const seed = getBytes(_seed, 'seed'); - assertArgument(seed.length >= 16 && seed.length <= 64, 'invalid seed', 'seed', '[REDACTED]'); - const I = getBytes(computeHmac('sha512', MasterSecret, seed)); - const signingKey = new SigningKey(hexlify(I.slice(0, 32))); - return new HDNodeWallet(_guard$1, signingKey, '0x00000000', hexlify(I.slice(32)), 'm', 0, 0, mnemonic, null); - } - /** - * Creates a new HD Node from `extendedKey`. - * - * If the `extendedKey` will either have a prefix or `xpub` or `xpriv`, returning a neutered HD Node - * ([[HDNodeVoidWallet]]) or full HD Node ([[HDNodeWallet]]) respectively. - * - * @param {string} extendedKey - * - * @returns {HDNodeWallet | HDNodeVoidWallet} - */ - static fromExtendedKey(extendedKey) { - const bytes = toBeArray(decodeBase58(extendedKey)); // @TODO: redact - assertArgument(bytes.length === 82 || encodeBase58Check(bytes.slice(0, 78)) === extendedKey, 'invalid extended key', 'extendedKey', '[ REDACTED ]'); - const depth = bytes[4]; - const parentFingerprint = hexlify(bytes.slice(5, 9)); - const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16); - const chainCode = hexlify(bytes.slice(13, 45)); - const key = bytes.slice(45, 78); - switch (hexlify(bytes.slice(0, 4))) { - // Public Key - case '0x0488b21e': - case '0x043587cf': { - const publicKey = hexlify(key); - return new HDNodeVoidWallet(_guard$1, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null); - } - // Private Key - case '0x0488ade4': - case '0x04358394 ': - if (key[0] !== 0) { - break; - } - return new HDNodeWallet(_guard$1, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null); - } - assertArgument(false, 'invalid extended key prefix', 'extendedKey', '[ REDACTED ]'); - } - /** - * Creates a new random HDNode. - * - * @param {string} path - * @param {string} [password] - * @param {Wordlist} [wordlist] - * - * @returns {HDNodeWallet} - */ - static createRandom(path, password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist); - return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); - } - /** - * Create an HD Node from `mnemonic`. - * - * @param {Mnemonic} mnemonic - * @param {string} path - * - * @returns {HDNodeWallet} - */ - static fromMnemonic(mnemonic, path) { - return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); - } - /** - * Creates an HD Node from a mnemonic `phrase`. - * - * @param {string} phrase - * @param {string} path - * @param {string} [password] - * @param {Wordlist} [wordlist] - * - * @returns {HDNodeWallet} - */ - static fromPhrase(phrase, path, password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist); - return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); - } - /** - * Creates an HD Node from a `seed`. - * - * @param {BytesLike} seed - * - * @returns {HDNodeWallet} - */ - static fromSeed(seed) { - return HDNodeWallet.#fromSeed(seed, null); - } -} -/** - * A **HDNodeVoidWallet** cannot sign, but provides access to the children nodes of a [[link-bip-32]] HD wallet - * addresses. - * - * They can be created by using an extended `xpub` key to [[HDNodeWallet_fromExtendedKey]] or by - * [neutering](HDNodeWallet-neuter) a [[HDNodeWallet]]. - */ -class HDNodeVoidWallet extends VoidSigner { - /** - * The compressed public key. - * - * @type {string} - */ - publicKey; - /** - * The fingerprint. - * - * A fingerprint allows a quick way to detect parent and child nodes, but developers should be prepared to deal with - * collisions as it is only 4 bytes. - * - * @type {string} - */ - fingerprint; - /** - * The parent node fingerprint. - * - * @type {string} - */ - parentFingerprint; - /** - * The chaincode, which is effectively a public key used to derive children. - * - * @type {string} - */ - chainCode; - /** - * The derivation path of this wallet. - * - * Since extended keys do not provide full path details, this may be `null`, if instantiated from a source that does - * not encode it. - * - * @type {null | string} - */ - path; - /** - * The child index of this wallet. Values over `2 ** 31` indicate the node is hardened. - * - * @type {number} - */ - index; - /** - * The depth of this wallet, which is the number of components in its path. - * - * @type {number} - */ - depth; - /** - * @param {any} guard - * @param {string} address - * @param {string} publicKey - * @param {string} parentFingerprint - * @param {string} chainCode - * @param {null | string} path - * @param {number} index - * @param {number} depth - * @param {null | Provider} provider - * @ignore - */ - constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider) { - super(address, provider); - assertPrivate(guard, _guard$1, 'HDNodeVoidWallet'); - defineProperties(this, { publicKey }); - const fingerprint = dataSlice(ripemd160(sha256(publicKey)), 0, 4); - defineProperties(this, { - publicKey, - fingerprint, - parentFingerprint, - chainCode, - path, - index, - depth, - }); - } - /** - * Connects the wallet to a provider. - * - * @param {null | Provider} provider - * - * @returns {HDNodeVoidWallet} - */ - connect(provider) { - return new HDNodeVoidWallet(_guard$1, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider); - } - /** - * The extended key. - * - * This key will begin with the prefix `xpub` and can be used to reconstruct this neutered key to derive its - * children addresses. - * - * @returns {string} - */ - get extendedKey() { - // We only support the mainnet values for now, but if anyone needs - // testnet values, let me know. I believe current sentiment is that - // we should always use mainnet, and use BIP-44 to derive the network - // - Mainnet: public=0x0488B21E, private=0x0488ADE4 - // - Testnet: public=0x043587CF, private=0x04358394 - assert(this.depth < 256, 'Depth too deep', 'UNSUPPORTED_OPERATION', { operation: 'extendedKey' }); - return encodeBase58Check(concat([ - '0x0488B21E', - zpad(this.depth, 1), - this.parentFingerprint, - zpad(this.index, 4), - this.chainCode, - this.publicKey, - ])); - } - /** - * Returns true if this wallet has a path, providing a Type Guard that the path is non-null. - * - * @returns {boolean} - */ - hasPath() { - return this.path != null; - } - /** - * Return the child for `index`. - * - * @param {Numeric} _index - * - * @returns {HDNodeVoidWallet} - */ - deriveChild(_index) { - const index = getNumber(_index, 'index'); - assertArgument(index <= 0xffffffff, 'invalid index', 'index', index); - // Base path - let path = this.path; - if (path) { - path += '/' + (index & ~HardenedBit); - if (index & HardenedBit) { - path += "'"; - } - } - const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null); - const Ki = SigningKey.addPoints(IL, this.publicKey, true); - const address = computeAddress(Ki); - return new HDNodeVoidWallet(_guard$1, address, Ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.provider); - } - /** - * Return the signer for `path` from this node. - * - * @param {string} path - * - * @returns {HDNodeVoidWallet} - */ - derivePath(path) { - return derivePath(this, path); - } -} - -/** - * Constant to represent the maximum attempt to derive an address. - */ -const MAX_ADDRESS_DERIVATION_ATTEMPTS = 10000000; -const _guard = {}; -/** - * Abstract class representing a Hierarchical Deterministic (HD) wallet. - */ -class AbstractHDWallet { - static _version = 1; - static _coinType; - // Map of addresses to address info - _addresses = new Map(); - /** - * Root node of the HD wallet. - */ - _root; - provider; - /** - * @param {HDNodeWallet} root - The root node of the HD wallet. - * @param {Provider} [provider] - The provider for the HD wallet. - */ - constructor(guard, root, provider) { - assertPrivate(guard, _guard, 'AbstractHDWallet'); - this._root = root; - this.provider = provider; - } - /** - * Returns the parent path for a given coin type. - * - * @param {number} coinType - The coin type. - * @returns {string} The parent path. - */ - static parentPath(coinType) { - return `m/44'/${coinType}'`; - } - /** - * Returns the coin type of the wallet. - * - * @returns {AllowedCoinType} The coin type. - */ - coinType() { - return this.constructor._coinType; - } - /** - * Returns the extended public key of the root node of the HD wallet. - * - * @returns {string} The extended public key. - */ - get xPub() { - return this._root.extendedKey; - } - /** - * Derives the next valid address node for a specified account, starting index, and zone. The method ensures the - * derived address belongs to the correct shard and ledger, as defined by the Quai blockchain specifications. - * - * @param {number} account - The account number from which to derive the address node. - * @param {number} startingIndex - The index from which to start deriving addresses. - * @param {Zone} zone - The zone (shard) for which the address should be valid. - * @param {boolean} [isChange=false] - Whether to derive a change address. Default is `false` - * @returns {HDNodeWallet} - The derived HD node wallet containing a valid address for the specified zone. - * @throws {Error} If a valid address for the specified zone cannot be derived within the allowed attempts. - */ - deriveNextAddressNode(account, startingIndex, zone, isChange = false) { - const changeIndex = isChange ? 1 : 0; - const changeNode = this._root.deriveChild(account).deriveChild(changeIndex); - let addrIndex = startingIndex; - let addressNode; - const isValidAddressForZone = (address) => { - const addressZone = getZoneForAddress(address); - if (!addressZone) { - return false; - } - const isCorrectShard = addressZone === zone; - const isCorrectLedger = this.coinType() === 969 ? isQiAddress(address) : !isQiAddress(address); - return isCorrectShard && isCorrectLedger; - }; - for (let attempts = 0; attempts < MAX_ADDRESS_DERIVATION_ATTEMPTS; attempts++) { - addressNode = changeNode.deriveChild(addrIndex++); - if (isValidAddressForZone(addressNode.address)) { - return addressNode; - } - } - throw new Error(`Failed to derive a valid address for the zone ${zone} after ${MAX_ADDRESS_DERIVATION_ATTEMPTS} attempts.`); - } - /** - * Adds an address to the wallet. - * - * @param {number} account - The account number. - * @param {number} addressIndex - The address index. - * @param {boolean} [isChange=false] - Whether the address is a change address. Default is `false` - * @returns {NeuteredAddressInfo} The added address info. - */ - addAddress(account, addressIndex, isChange = false) { - return this._addAddress(this._addresses, account, addressIndex, isChange); - } - /** - * Helper method to add an address to the wallet address map. - * - * @param {Map} addressMap - The address map. - * @param {number} account - The account number. - * @param {number} addressIndex - The address index. - * @param {boolean} [isChange=false] - Whether the address is a change address. Default is `false` - * @returns {NeuteredAddressInfo} The added address info. - * @throws {Error} If the address for the index already exists. - */ - _addAddress(addressMap, account, addressIndex, isChange = false) { - // check if address already exists for the index - this._addresses.forEach((addressInfo) => { - if (addressInfo.index === addressIndex) { - throw new Error(`Address for index ${addressIndex} already exists`); - } - }); - // derive the address node and validate the zone - const changeIndex = isChange ? 1 : 0; - const addressNode = this._root.deriveChild(account).deriveChild(changeIndex).deriveChild(addressIndex); - const zone = getZoneForAddress(addressNode.address); - if (!zone) { - throw new Error(`Failed to derive a valid address zone for the index ${addressIndex}`); - } - return this.createAndStoreAddressInfo(addressNode, account, zone, isChange, addressMap); - } - /** - * Promise that resolves to the next address for the specified account and zone. - * - * @param {number} account - The index of the account for which to retrieve the next address. - * @param {Zone} zone - The zone in which to retrieve the next address. - * @returns {Promise} The next neutered address information. - */ - async getNextAddress(account, zone) { - return Promise.resolve(this._getNextAddress(account, zone, false, this._addresses)); - } - /** - * Synchronously retrieves the next address for the specified account and zone. - * - * @param {number} account - The index of the account for which to retrieve the next address. - * @param {Zone} zone - The zone in which to retrieve the next address. - * @returns {NeuteredAddressInfo} The next neutered address information. - */ - getNextAddressSync(account, zone) { - return this._getNextAddress(account, zone, false, this._addresses); - } - /** - * Derives and returns the next address information for the specified account and zone. - * - * @param {number} accountIndex - The index of the account for which the address is being generated. - * @param {Zone} zone - The zone in which the address is to be used. - * @param {boolean} isChange - A flag indicating whether the address is a change address. - * @param {Map} addressMap - A map storing the neutered address information. - * @returns {NeuteredAddressInfo} The derived neutered address information. - * @throws {Error} If the zone is invalid. - */ - _getNextAddress(accountIndex, zone, isChange, addressMap) { - this.validateZone(zone); - const lastIndex = this.getLastAddressIndex(addressMap, zone, accountIndex, isChange); - const addressNode = this.deriveNextAddressNode(accountIndex, lastIndex + 1, zone, isChange); - return this.createAndStoreAddressInfo(addressNode, accountIndex, zone, isChange, addressMap); - } - /** - * Gets the address info for a given address. - * - * @param {string} address - The address. - * @returns {NeuteredAddressInfo | null} The address info or null if not found. - */ - getAddressInfo(address) { - const addressInfo = this._addresses.get(address); - if (!addressInfo) { - return null; - } - return addressInfo; - } - /** - * Returns the private key for a given address. This method should be used with caution as it exposes the private - * key to the user. - * - * @param {string} address - The address associated with the desired private key. - * @returns {string} The private key. - */ - getPrivateKey(address) { - const hdNode = this._getHDNodeForAddress(address); - return hdNode.privateKey; - } - /** - * Gets the addresses for a given account. - * - * @param {number} account - The account number. - * @returns {NeuteredAddressInfo[]} The addresses for the account. - */ - getAddressesForAccount(account) { - const addresses = this._addresses.values(); - return Array.from(addresses).filter((addressInfo) => addressInfo.account === account); - } - /** - * Gets the addresses for a given zone. - * - * @param {Zone} zone - The zone. - * @returns {NeuteredAddressInfo[]} The addresses for the zone. - */ - getAddressesForZone(zone) { - this.validateZone(zone); - const addresses = this._addresses.values(); - return Array.from(addresses).filter((addressInfo) => addressInfo.zone === zone); - } - /** - * Creates an instance of the HD wallet. - * - * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet. - * @param {Mnemonic} mnemonic - The mnemonic. - * @returns {T} The created instance. - */ - static createInstance(mnemonic) { - const coinType = this._coinType; - const root = HDNodeWallet.fromMnemonic(mnemonic, this.parentPath(coinType)); - return new this(_guard, root); - } - /** - * Creates an HD wallet from a mnemonic. - * - * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet. - * @param {Mnemonic} mnemonic - The mnemonic. - * @returns {T} The created instance. - */ - static fromMnemonic(mnemonic) { - return this.createInstance(mnemonic); - } - /** - * Creates a random HD wallet. - * - * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet. - * @param {string} [password] - The password. - * @param {Wordlist} [wordlist] - The wordlist. - * @returns {T} The created instance. - */ - static createRandom(password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist); - return this.createInstance(mnemonic); - } - /** - * Creates an HD wallet from a phrase. - * - * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet. - * @param {string} phrase - The phrase. - * @param {string} [password] - The password. - * @param {Wordlist} [wordlist] - The wordlist. - * @returns {T} The created instance. - */ - static fromPhrase(phrase, password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist); - return this.createInstance(mnemonic); - } - /** - * Connects the wallet to a provider. - * - * @param {Provider} provider - The provider. - */ - connect(provider) { - this.provider = provider; - } - /** - * Validates the zone. - * - * @param {Zone} zone - The zone. - * @throws {Error} If the zone is invalid. - */ - validateZone(zone) { - if (!Object.values(Zone).includes(zone)) { - throw new Error(`Invalid zone: ${zone}`); - } - } - /** - * Derives and returns the Hierarchical Deterministic (HD) node wallet associated with a given address. - * - * This method fetches the account and address information from the wallet's internal storage, derives the - * appropriate change node based on whether the address is a change address, and further derives the final HD node - * using the address index. - * - * @param {string} addr - The address for which to derive the HD node. - * @returns {HDNodeWallet} The derived HD node wallet corresponding to the given address. - * @throws {Error} If the given address is not known to the wallet. - * @throws {Error} If the account associated with the address is not found. - */ - _getHDNodeForAddress(addr) { - const addressInfo = this._addresses.get(addr); - if (!addressInfo) { - throw new Error(`Address ${addr} is not known to this wallet`); - } - const changeIndex = addressInfo.change ? 1 : 0; - return this._root.deriveChild(addressInfo.account).deriveChild(changeIndex).deriveChild(addressInfo.index); - } - /** - * Serializes the HD wallet state into a format suitable for storage or transmission. - * - * @returns {SerializedHDWallet} An object representing the serialized state of the HD wallet, including version, - * mnemonic phrase, coin type, and addresses. - */ - serialize() { - const addresses = Array.from(this._addresses.values()); - return { - version: this.constructor._version, - phrase: this._root.mnemonic.phrase, - coinType: this.coinType(), - addresses: addresses, - }; - } - /** - * Deserializes a serialized HD wallet object and reconstructs the wallet instance. This method must be implemented - * in the subclass. - * - * @param {SerializedHDWallet} _serialized - The serialized object representing the state of an HD wallet. - * @returns {AbstractHDWallet} An instance of AbstractHDWallet. - * @throws {Error} This method must be implemented in the subclass. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static async deserialize(_serialized) { - throw new Error('deserialize method must be implemented in the subclass'); - } - /** - * Validates the version and coinType of the serialized wallet. - * - * @param {SerializedHDWallet} serialized - The serialized wallet data to be validated. - * @throws {Error} If the version or coinType of the serialized wallet does not match the expected values. - * @protected - * @static - */ - static validateSerializedWallet(serialized) { - if (serialized.version !== this._version) { - throw new Error(`Invalid version ${serialized.version} for wallet (expected ${this._version})`); - } - if (serialized.coinType !== this._coinType) { - throw new Error(`Invalid coinType ${serialized.coinType} for wallet (expected ${this._coinType})`); - } - } - /** - * Imports addresses from a serialized wallet into the addresses map. Before adding the addresses, a validation is - * performed to ensure the address, public key, and zone match the expected values. - * - * @param {Map} addressMap - The map where the addresses will be imported. - * @param {NeuteredAddressInfo[]} addresses - The array of addresses to be imported, each containing account, index, - * change, address, pubKey, and zone information. - * @throws {Error} If there is a mismatch between the expected and actual address, public key, or zone. - * @protected - */ - importSerializedAddresses(addressMap, addresses) { - for (const addressInfo of addresses) { - const newAddressInfo = this._addAddress(addressMap, addressInfo.account, addressInfo.index, addressInfo.change); - // validate the address info - if (addressInfo.address !== newAddressInfo.address) { - throw new Error(`Address mismatch: ${addressInfo.address} != ${newAddressInfo.address}`); - } - if (addressInfo.pubKey !== newAddressInfo.pubKey) { - throw new Error(`Public key mismatch: ${addressInfo.pubKey} != ${newAddressInfo.pubKey}`); - } - if (addressInfo.zone !== newAddressInfo.zone) { - throw new Error(`Zone mismatch: ${addressInfo.zone} != ${newAddressInfo.zone}`); - } - } - } - /** - * Retrieves the highest address index from the given address map for a specified zone, account, and change type. - * - * This method filters the address map based on the provided zone, account, and change type, then determines the - * maximum address index from the filtered addresses. - * - * @param {Map} addressMap - The map containing address information, where the key is - * an address string and the value is a NeuteredAddressInfo object. - * @param {Zone} zone - The specific zone to filter the addresses by. - * @param {number} account - The account number to filter the addresses by. - * @param {boolean} isChange - A boolean indicating whether to filter for change addresses (true) or receiving - * addresses (false). - * @returns {number} - The highest address index for the specified criteria, or -1 if no addresses match. - * @protected - */ - getLastAddressIndex(addressMap, zone, account, isChange) { - const addresses = Array.from(addressMap.values()).filter((addressInfo) => addressInfo.account === account && addressInfo.zone === zone && addressInfo.change === isChange); - return addresses.reduce((maxIndex, addressInfo) => Math.max(maxIndex, addressInfo.index), -1); - } - /** - * Creates and stores address information in the address map for a specified account, zone, and change type. - * - * This method constructs a NeuteredAddressInfo object using the provided HDNodeWallet and other parameters, then - * stores this information in the provided address map. - * - * @param {HDNodeWallet} addressNode - The HDNodeWallet object containing the address and public key information. - * @param {number} account - The account number to associate with the address. - * @param {Zone} zone - The specific zone to associate with the address. - * @param {boolean} isChange - A boolean indicating whether the address is a change address (true) or a receiving - * address (false). - * @param {Map} addressMap - The map to store the created NeuteredAddressInfo, with the - * address as the key. - * @returns {NeuteredAddressInfo} - The created NeuteredAddressInfo object. - * @protected - */ - createAndStoreAddressInfo(addressNode, account, zone, isChange, addressMap) { - const neuteredAddressInfo = { - pubKey: addressNode.publicKey, - address: addressNode.address, - account, - index: addressNode.index, - change: isChange, - zone, - }; - addressMap.set(neuteredAddressInfo.address, neuteredAddressInfo); - return neuteredAddressInfo; - } -} - -/** - * The Quai HD wallet is a BIP44-compliant hierarchical deterministic wallet used for managing a set of addresses in the - * Quai ledger. This is the easiest way to manage the interaction of managing accounts and addresses on the Quai - * network, however, if your use case requires a single address Quai address, you can use the {@link Wallet} class. - * - * The Quai HD wallet supports: - * - * - Adding accounts to the wallet heierchy - * - Generating addresses for a specific account in any {@link Zone} - * - Signing and sending transactions for any address in the wallet - * - Signing and verifying EIP1193 typed data for any address in the wallet. - * - Serializing the wallet to JSON and deserializing it back to a wallet instance. - * - * @category Wallet - * @example - * - * ```ts - * import { QuaiHDWallet, Zone } from 'quais'; - * - * const wallet = new QuaiHDWallet(); - * const cyrpus1Address = await wallet.getNextAddress(0, Zone.Cyrpus1); // get the first address in the Cyrpus1 zone - * await wallet.sendTransaction({ from: address, to: '0x...', value: 100 }); // send a transaction - * const serializedWallet = wallet.serialize(); // serialize current (account/address) state of the wallet - * . - * . - * . - * const deserializedWallet = QuaiHDWallet.deserialize(serializedWallet); // create a new wallet instance from the serialized data - * ``` - */ -class QuaiHDWallet extends AbstractHDWallet { - /** - * The version of the wallet. - * - * @type {number} - * @static - */ - static _version = 1; - /** - * The coin type for the wallet. - * - * @type {AllowedCoinType} - * @static - */ - static _coinType = 994; - /** - * Create a QuaiHDWallet instance. - * - * @param {HDNodeWallet} root - The root HD node wallet. - * @param {Provider} [provider] - The provider. - */ - constructor(guard, root, provider) { - super(guard, root, provider); - } - /** - * Sign a transaction. - * - * @param {QuaiTransactionRequest} tx - The transaction request. - * @returns {Promise} A promise that resolves to the signed transaction. - */ - async signTransaction(tx) { - const from = await resolveAddress(tx.from); - const fromNode = this._getHDNodeForAddress(from); - const signedTx = await fromNode.signTransaction(tx); - return signedTx; - } - /** - * Send a transaction. - * - * @param {QuaiTransactionRequest} tx - The transaction request. - * @returns {Promise} A promise that resolves to the transaction response. - * @throws {Error} If the provider is not set. - */ - async sendTransaction(tx) { - if (!this.provider) { - throw new Error('Provider is not set'); - } - const from = await resolveAddress(tx.from); - const fromNode = this._getHDNodeForAddress(from); - const fromNodeConnected = fromNode.connect(this.provider); - return await fromNodeConnected.sendTransaction(tx); - } - /** - * Sign a message. - * - * @param {string} address - The address. - * @param {string | Uint8Array} message - The message to sign. - * @returns {Promise} A promise that resolves to the signed message. - */ - async signMessage(address, message) { - const addrNode = this._getHDNodeForAddress(address); - return await addrNode.signMessage(message); - } - /** - * Deserializes the given serialized HD wallet data into an instance of QuaiHDWallet. - * - * @async - * @param {SerializedHDWallet} serialized - The serialized wallet data to be deserialized. - * @returns {Promise} A promise that resolves to an instance of QuaiHDWallet. - * @throws {Error} If validation of the serialized wallet data fails or if deserialization fails. - * @public - * @static - */ - static async deserialize(serialized) { - super.validateSerializedWallet(serialized); - // create the wallet instance - const mnemonic = Mnemonic.fromPhrase(serialized.phrase); - const path = this.parentPath(serialized.coinType); - const root = HDNodeWallet.fromMnemonic(mnemonic, path); - const wallet = new this(_guard, root); - // import the addresses - wallet.importSerializedAddresses(wallet._addresses, serialized.addresses); - return wallet; - } - /** - * Signs typed data using the private key associated with the given address. - * - * @param {string} address - The address for which the typed data is to be signed. - * @param {TypedDataDomain} domain - The domain information of the typed data, defining the scope of the signature. - * @param {Record} types - The types of the data to be signed, mapping each data type name - * to its fields. - * @param {Record} value - The actual data to be signed. - * @returns {Promise} A promise that resolves to the signed data in string format. - * @throws {Error} If the address does not correspond to a valid HD node or if signing fails. - */ - async signTypedData(address, domain, types, value) { - const addrNode = this._getHDNodeForAddress(address); - return addrNode.signTypedData(domain, types, value); - } -} - -/** - * A **Wallet** manages a single private key which is used to sign transactions, messages and other common payloads. - * - * This class is generally the main entry point for developers that wish to use a private key directly, as it can create - * instances from a large variety of common sources, including raw private key, - * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) mnemonics and encrypted JSON wallets. - * - * @category Wallet - */ -class Wallet extends BaseWallet { - /** - * Create a new wallet for the private `key`, optionally connected to `provider`. - * - * @param {string | SigningKey} key - The private key. - * @param {null | Provider} [provider] - The provider to connect to. - */ - constructor(key, provider) { - if (typeof key === 'string' && !key.startsWith('0x')) { - key = '0x' + key; - } - const signingKey = typeof key === 'string' ? new SigningKey(key) : key; - super(signingKey, provider); - } - /** - * Connects the wallet to a provider. - * - * @param {null | Provider} provider - The provider to connect to. - * - * @returns {Wallet} The connected wallet. - */ - connect(provider) { - return new Wallet(this.signingKey, provider); - } - /** - * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with `password`. - * - * If `progressCallback` is specified, it will receive periodic updates as the encryption process progresses. - * - * @param {Uint8Array | string} password - The password to encrypt the wallet with. - * @param {ProgressCallback} [progressCallback] - An optional callback to keep the user informed. - * - * @returns {Promise} The encrypted JSON wallet. - */ - async encrypt(password, progressCallback) { - const account = { address: this.address, privateKey: this.privateKey }; - return await encryptKeystoreJson(account, password, { progressCallback }); - } - /** - * Returns a [JSON Keystore Wallet](json-wallets) encrypted with `password`. - * - * It is preferred to use the [async version](encrypt) instead, which allows a - * {@link ProgressCallback | **ProgressCallback**} to keep the user informed. - * - * This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial - * duration. - * - * @param {Uint8Array | string} password - The password to encrypt the wallet with. - * - * @returns {string} The encrypted JSON wallet. - */ - encryptSync(password) { - const account = { address: this.address, privateKey: this.privateKey }; - return encryptKeystoreJsonSync(account, password); - } - /** - * Creates a wallet from a keystore account. - * - * @ignore - * @param {KeystoreAccount} account - The keystore account. - * - * @returns {Wallet} The wallet instance. - */ - static #fromAccount(account) { - assertArgument(account, 'invalid JSON wallet', 'json', '[ REDACTED ]'); - const wallet = new Wallet(account.privateKey); - assertArgument(wallet.address === account.address, 'address/privateKey mismatch', 'json', '[ REDACTED ]'); - return wallet; - } - /** - * Creates (asynchronously) a **Wallet** by decrypting the `json` with `password`. - * - * If `progress` is provided, it is called periodically during decryption so that any UI can be updated. - * - * @param {string} json - The JSON data to decrypt. - * @param {Uint8Array | string} password - The password to decrypt the JSON data. - * @param {ProgressCallback} [progress] - An optional callback to keep the user informed. - * - * @returns {Promise} The decrypted wallet. - */ - static async fromEncryptedJson(json, password, progress) { - let account; - if (isKeystoreJson(json)) { - account = await decryptKeystoreJson(json, password, progress); - return Wallet.#fromAccount(account); - } - throw new Error('invalid JSON wallet'); - } - /** - * Creates a **Wallet** by decrypting the `json` with `password`. - * - * The {@link Wallet.fromEncryptedJson | **fromEncryptedJson**} method is preferred, as this method will lock up and - * freeze the UI during decryption, which may take some time. - * - * @param {string} json - The JSON data to decrypt. - * @param {Uint8Array | string} password - The password to decrypt the JSON data. - * - * @returns {QuaiHDWallet | Wallet} The decrypted wallet. - */ - static fromEncryptedJsonSync(json, password) { - let account = null; - if (isKeystoreJson(json)) { - account = decryptKeystoreJsonSync(json, password); - } - else { - assertArgument(false, 'invalid JSON wallet', 'json', '[ REDACTED ]'); - } - return Wallet.#fromAccount(account); - } -} - -/*! musig-js - MIT License (c) 2022 Brandon Black */ -const TAGS = { - challenge: 'BIP0340/challenge', - keyagg_list: 'KeyAgg list', - keyagg_coef: 'KeyAgg coefficient', - musig_aux: 'MuSig/aux', - musig_nonce: 'MuSig/nonce', - musig_deterministic_nonce: 'MuSig/deterministic/nonce', - musig_noncecoef: 'MuSig/noncecoef', -}; -function compare32b(a, b) { - if (a.length !== 32 || b.length !== 32) throw new Error('Invalid array'); - const aD = new DataView(a.buffer, a.byteOffset, a.length); - const bD = new DataView(b.buffer, b.byteOffset, b.length); - for (let i = 0; i < 8; i++) { - const cmp = aD.getUint32(i * 4) - bD.getUint32(i * 4); - if (cmp !== 0) return cmp; - } - return 0; -} -function compare33b(a, b) { - if (a.length !== 33 || b.length !== 33) throw new Error('Invalid array'); - const cmp = a[0] - b[0]; - if (cmp !== 0) return cmp; - return compare32b(a.subarray(1), b.subarray(1)); -} -const makeSessionId = - typeof self === 'object' && (self.crypto || self.msCrypto) - ? () => (self.crypto || self.msCrypto).getRandomValues(new Uint8Array(32)) - : () => require('crypto').randomBytes(32); -const _keyAggCache = new WeakMap(); -const _coefCache = new WeakMap(); -const _nonceCache = new WeakMap(); -const _sessionCache = new WeakMap(); -function MuSigFactory(ecc) { - const CPOINT_INF = new Uint8Array(33); - const SCALAR_0 = new Uint8Array(32); - const SCALAR_1 = new Uint8Array(32); - SCALAR_1[31] = 1; - ecc.scalarNegate(SCALAR_1); - function keyAggCoeff(publicKeys, publicKey) { - let coefCache = _coefCache.get(publicKeys); - if (coefCache === undefined) { - coefCache = new Map(); - _coefCache.set(publicKeys, coefCache); - } - let coefficient = coefCache.get(publicKey); - if (coefficient) return coefficient; - coefficient = SCALAR_1; - let secondPublicKey; - let publicKeyHash; - let keyAggCache = _keyAggCache.get(publicKeys); - if (keyAggCache === undefined) { - const pkIdx2 = publicKeys.findIndex((pk) => compare33b(pk, publicKeys[0]) !== 0); - secondPublicKey = publicKeys[pkIdx2]; - publicKeyHash = ecc.taggedHash(TAGS.keyagg_list, ...publicKeys); - keyAggCache = { publicKeyHash, secondPublicKey }; - _keyAggCache.set(publicKeys, keyAggCache); - } else { - ({ publicKeyHash, secondPublicKey } = keyAggCache); - } - if (secondPublicKey === undefined || compare33b(publicKey, secondPublicKey) !== 0) - coefficient = ecc.taggedHash(TAGS.keyagg_coef, publicKeyHash, publicKey); - coefCache.set(publicKey, coefficient); - return coefficient; - } - function addTweak(ctx, t) { - const tweak = 'tweak' in t ? t : { tweak: t }; - if (!ecc.isScalar(tweak.tweak)) - throw new TypeError('Expected tweak to be a valid scalar with curve order'); - let { gacc, tacc } = ctx; - let aggPublicKey = ctx.aggPublicKey; - if (!ecc.hasEvenY(aggPublicKey) && tweak.xOnly) { - gacc = ecc.scalarNegate(gacc); - tacc = ecc.scalarNegate(tacc); - aggPublicKey = ecc.pointNegate(aggPublicKey); - } - aggPublicKey = ecc.pointAddTweak(aggPublicKey, tweak.tweak, false); - if (aggPublicKey === null) throw new Error('Unexpected point at infinity during tweaking'); - tacc = ecc.scalarAdd(tweak.tweak, tacc); - return { aggPublicKey, gacc, tacc }; - } - function keyAgg(publicKeys, ...tweaks) { - checkArgs({ publicKeys }); - const multipliedPublicKeys = publicKeys.map((publicKey) => { - const coefficient = keyAggCoeff(publicKeys, publicKey); - let multipliedPublicKey; - if (compare32b(coefficient, SCALAR_1) === 0) { - multipliedPublicKey = publicKey; - } else { - multipliedPublicKey = ecc.pointMultiplyUnsafe(publicKey, coefficient, false); - } - if (multipliedPublicKey === null) throw new Error('Point at infinity during aggregation'); - return multipliedPublicKey; - }); - const aggPublicKey = multipliedPublicKeys.reduce((a, b) => { - const next = ecc.pointAdd(a, b, false); - if (next === null) throw new Error('Point at infinity during aggregation'); - return next; - }); - return tweaks.reduce((ctx, tweak) => addTweak(ctx, tweak), { - aggPublicKey, - gacc: SCALAR_1, - tacc: SCALAR_0, - }); - } - function getSessionValues(sessionKey) { - const sessionValues = _sessionCache.get(sessionKey); - if (!sessionValues) throw new Error('Invalid session key, please call `startSigningSession`'); - return sessionValues; - } - function nonceAgg(publicNonces) { - checkArgs({ publicNonces }); - const aggNonces = [publicNonces[0].subarray(0, 33), publicNonces[0].subarray(33)]; - for (let i = 1; i < publicNonces.length; i++) { - if (aggNonces[0] !== null) - aggNonces[0] = ecc.pointAdd(aggNonces[0], publicNonces[i].subarray(0, 33), false); - if (aggNonces[1] !== null) - aggNonces[1] = ecc.pointAdd(aggNonces[1], publicNonces[i].subarray(33), false); - } - const aggNonce = new Uint8Array(66); - if (aggNonces[0] !== null) aggNonce.set(ecc.pointCompress(aggNonces[0]), 0); - if (aggNonces[1] !== null) aggNonce.set(ecc.pointCompress(aggNonces[1]), 33); - return aggNonce; - } - function startSigningSessionInner(aggNonce, msg, publicKeys, ctx) { - const pubKeyX = ecc.pointX(ctx.aggPublicKey); - const coefficient = ecc.taggedHash(TAGS.musig_noncecoef, aggNonce, pubKeyX, msg); - const aggNonces = [aggNonce.subarray(0, 33), aggNonce.subarray(33)]; - let r = null; - if (compare33b(aggNonces[1], CPOINT_INF) !== 0 && compare33b(aggNonces[0], CPOINT_INF) !== 0) { - r = ecc.pointMultiplyAndAddUnsafe(aggNonces[1], coefficient, aggNonces[0], false); - } else if (compare33b(aggNonces[0], CPOINT_INF) !== 0) { - r = ecc.pointCompress(aggNonces[0], false); - } else if (compare33b(aggNonces[1], CPOINT_INF) !== 0) { - r = ecc.pointMultiplyUnsafe(aggNonces[1], coefficient, false); - } - if (r === null) r = ecc.getPublicKey(SCALAR_1, false); - if (r === null) throw new Error('Failed to get G'); - const challenge = ecc.scalarMod(ecc.taggedHash(TAGS.challenge, ecc.pointX(r), pubKeyX, msg)); - const key = { publicKey: ctx.aggPublicKey, aggNonce, msg }; - _sessionCache.set(key, { ...ctx, coefficient, challenge, finalNonce: r, publicKeys }); - return key; - } - function partialVerifyInner({ sig, publicKey, publicNonces, sessionKey }) { - const { aggPublicKey, gacc, challenge, coefficient, finalNonce, publicKeys } = - getSessionValues(sessionKey); - const rePrime = ecc.pointMultiplyAndAddUnsafe( - publicNonces[1], - coefficient, - publicNonces[0], - false - ); - if (rePrime === null) throw new Error('Unexpected public nonce at infinity'); - const re = ecc.hasEvenY(finalNonce) ? rePrime : ecc.pointNegate(rePrime); - const a = keyAggCoeff(publicKeys, publicKey); - const g = ecc.hasEvenY(aggPublicKey) ? gacc : ecc.scalarNegate(gacc); - const ea = ecc.scalarMultiply(challenge, a); - const eag = ecc.scalarMultiply(ea, g); - const ver = ecc.pointMultiplyAndAddUnsafe(publicKey, eag, re, true); - if (ver === null) throw new Error('Unexpected verification point at infinity'); - const sG = ecc.getPublicKey(sig, true); - if (sG === null) throw new Error('Unexpected signature point at infinity'); - return compare33b(ver, sG) === 0; - } - function partialSignInner({ secretKey, publicKey, secretNonces, sessionKey }) { - const { aggPublicKey, gacc, challenge, coefficient, finalNonce, publicKeys } = - getSessionValues(sessionKey); - const [k1, k2] = secretNonces.map((k) => (ecc.hasEvenY(finalNonce) ? k : ecc.scalarNegate(k))); - const a = keyAggCoeff(publicKeys, publicKey); - const g = ecc.hasEvenY(aggPublicKey) ? gacc : ecc.scalarNegate(gacc); - const d = ecc.scalarMultiply(g, secretKey); - const bk2 = ecc.scalarMultiply(coefficient, k2); - const k1bk2 = ecc.scalarAdd(k1, bk2); - const ea = ecc.scalarMultiply(challenge, a); - const ead = ecc.scalarMultiply(ea, d); - const sig = ecc.scalarAdd(k1bk2, ead); - return sig; - } - function partialSign({ secretKey, publicNonce, sessionKey, verify = true }) { - checkArgs({ publicNonce, secretKey }); - const secretNonce = _nonceCache.get(publicNonce); - if (secretNonce === undefined) - throw new Error('No secret nonce found for specified public nonce'); - _nonceCache.delete(publicNonce); - const publicKey = ecc.getPublicKey(secretKey, true); - if (publicKey === null) throw new Error('Invalid secret key, no corresponding public key'); - if (compare33b(publicKey, secretNonce.subarray(64)) !== 0) - throw new Error('Secret nonce pubkey mismatch'); - const secretNonces = [secretNonce.subarray(0, 32), secretNonce.subarray(32, 64)]; - const sig = partialSignInner({ - secretKey, - publicKey, - secretNonces, - sessionKey, - }); - if (verify) { - const publicNonces = [publicNonce.subarray(0, 33), publicNonce.subarray(33)]; - const valid = partialVerifyInner({ - sig, - publicKey, - publicNonces, - sessionKey, - }); - if (!valid) throw new Error('Partial signature failed verification'); - } - return sig; - } - function deterministicSign({ - secretKey, - aggOtherNonce, - publicKeys, - tweaks = [], - msg, - rand, - verify = true, - nonceOnly = false, - }) { - checkArgs({ rand, secretKey, aggOtherNonce }); - const publicKey = ecc.getPublicKey(secretKey, true); - if (publicKey === null) throw new Error('Secret key has no corresponding public key'); - let secretKeyPrime; - if (rand !== undefined) { - secretKeyPrime = ecc.taggedHash(TAGS.musig_aux, rand); - for (let i = 0; i < 32; i++) { - secretKeyPrime[i] = secretKeyPrime[i] ^ secretKey[i]; - } - } else { - secretKeyPrime = secretKey; - } - const ctx = keyAgg(publicKeys, ...tweaks); - const aggPublicKey = ecc.pointX(ctx.aggPublicKey); - const mLength = new Uint8Array(8); - new DataView(mLength.buffer).setBigUint64(0, BigInt(msg.length)); - const secretNonce = new Uint8Array(97); - const publicNonce = new Uint8Array(66); - for (let i = 0; i < 2; i++) { - const kH = ecc.taggedHash( - TAGS.musig_deterministic_nonce, - ...[secretKeyPrime, aggOtherNonce, aggPublicKey, mLength, msg, Uint8Array.of(i)] - ); - const k = ecc.scalarMod(kH); - if (compare32b(SCALAR_0, k) === 0) throw new Error('0 secret nonce'); - const pub = ecc.getPublicKey(k, true); - if (pub === null) throw new Error('Secret nonce has no corresponding public nonce'); - secretNonce.set(k, i * 32); - publicNonce.set(pub, i * 33); - } - secretNonce.set(publicKey, 64); - if (nonceOnly) return { publicNonce }; - _nonceCache.set(publicNonce, secretNonce); - const aggNonce = nonceAgg([aggOtherNonce, publicNonce]); - const sessionKey = startSigningSessionInner(aggNonce, msg, publicKeys, ctx); - const sig = partialSign({ - secretKey, - publicNonce, - sessionKey, - verify, - }); - return { sig, sessionKey, publicNonce }; - } - const pubKeyArgs = ['publicKey', 'publicKeys']; - const scalarArgs = ['tweak', 'sig', 'sigs', 'tacc', 'gacc']; - const otherArgs32b = ['xOnlyPublicKey', 'rand', 'sessionId']; - const args32b = ['secretKey', ...scalarArgs, ...otherArgs32b]; - const pubNonceArgs = ['publicNonce', 'publicNonces', 'aggNonce', 'aggOtherNonce', 'finalNonce']; - const argLengths = new Map(); - args32b.forEach((a) => argLengths.set(a, 32)); - pubKeyArgs.forEach((a) => argLengths.set(a, 33)); - pubNonceArgs.forEach((a) => argLengths.set(a, 66)); - argLengths.set('secretNonce', 97); - argLengths.set('aggPublicKey', 65); - const scalarNames = new Set(); - scalarArgs.forEach((n) => scalarNames.add(n)); - function checkArgs(args) { - for (let [name, values] of Object.entries(args)) { - if (values === undefined) continue; - values = Array.isArray(values) ? values : [values]; - if (values.length === 0) throw new TypeError(`0-length ${name}s not supported`); - for (const value of values) { - if (argLengths.get(name) !== value.length) - throw new TypeError(`Invalid ${name} length (${value.length})`); - if (name === 'secretKey') { - if (!ecc.isSecret(value)) throw new TypeError(`Invalid secretKey`); - } else if (name === 'secretNonce') { - for (let i = 0; i < 64; i += 32) - if (!ecc.isSecret(value.subarray(i, i + 32))) - throw new TypeError(`Invalid secretNonce`); - } else if (scalarNames.has(name)) { - for (let i = 0; i < value.length; i += 32) - if (!ecc.isScalar(value.subarray(i, i + 32))) throw new TypeError(`Invalid ${name}`); - } - } - } - } - return { - getXOnlyPubkey: (ctx) => { - if ('aggPublicKey' in ctx) return ecc.pointX(ctx.aggPublicKey); - return ecc.pointX(getSessionValues(ctx).aggPublicKey); - }, - getPlainPubkey: (ctx) => { - if ('aggPublicKey' in ctx) return ecc.pointCompress(ctx.aggPublicKey); - return ecc.pointCompress(getSessionValues(ctx).aggPublicKey); - }, - keySort: (publicKeys) => { - checkArgs({ publicKeys }); - return [...publicKeys].sort((a, b) => compare33b(a, b)); - }, - keyAgg, - addTweaks: (ctx, ...tweaks) => { - checkArgs(ctx); - return tweaks.reduce((c, tweak) => addTweak(c, tweak), ctx); - }, - nonceGen: ({ - sessionId = makeSessionId(), - secretKey, - publicKey, - xOnlyPublicKey, - msg, - extraInput, - }) => { - if (extraInput !== undefined && extraInput.length > Math.pow(2, 32) - 1) - throw new TypeError('extraInput is limited to 2^32-1 bytes'); - checkArgs({ sessionId, secretKey, publicKey, xOnlyPublicKey }); - let rand; - if (secretKey !== undefined) { - rand = ecc.taggedHash(TAGS.musig_aux, sessionId); - for (let i = 0; i < 32; i++) { - rand[i] = rand[i] ^ secretKey[i]; - } - } else { - rand = sessionId; - } - if (xOnlyPublicKey === undefined) xOnlyPublicKey = new Uint8Array(); - const mPrefixed = [Uint8Array.of(0)]; - if (msg !== undefined) { - mPrefixed[0][0] = 1; - mPrefixed.push(new Uint8Array(8)); - new DataView(mPrefixed[1].buffer).setBigUint64(0, BigInt(msg.length)); - mPrefixed.push(msg); - } - if (extraInput === undefined) extraInput = new Uint8Array(); - const eLength = new Uint8Array(4); - new DataView(eLength.buffer).setUint32(0, extraInput.length); - const secretNonce = new Uint8Array(97); - const publicNonce = new Uint8Array(66); - for (let i = 0; i < 2; i++) { - const kH = ecc.taggedHash( - TAGS.musig_nonce, - rand, - Uint8Array.of(publicKey.length), - publicKey, - Uint8Array.of(xOnlyPublicKey.length), - xOnlyPublicKey, - ...mPrefixed, - eLength, - extraInput, - Uint8Array.of(i) - ); - const k = ecc.scalarMod(kH); - if (compare32b(SCALAR_0, k) === 0) throw new Error('0 secret nonce'); - const pub = ecc.getPublicKey(k, true); - if (pub === null) throw new Error('Secret nonce has no corresponding public nonce'); - secretNonce.set(k, i * 32); - publicNonce.set(pub, i * 33); - } - secretNonce.set(publicKey, 64); - _nonceCache.set(publicNonce, secretNonce); - return publicNonce; - }, - addExternalNonce: (publicNonce, secretNonce) => { - checkArgs({ publicNonce, secretNonce }); - _nonceCache.set(publicNonce, secretNonce); - }, - deterministicNonceGen: (args) => deterministicSign({ ...args, nonceOnly: true }), - deterministicSign, - nonceAgg, - startSigningSession: (aggNonce, msg, publicKeys, ...tweaks) => { - checkArgs({ aggNonce }); - const ctx = keyAgg(publicKeys, ...tweaks); - return startSigningSessionInner(aggNonce, msg, publicKeys, ctx); - }, - partialSign, - partialVerify: ({ sig, publicKey, publicNonce, sessionKey }) => { - checkArgs({ sig, publicKey, publicNonce }); - const publicNonces = [publicNonce.subarray(0, 33), publicNonce.subarray(33)]; - const valid = partialVerifyInner({ - sig, - publicKey, - publicNonces, - sessionKey, - }); - return valid; - }, - signAgg: (sigs, sessionKey) => { - checkArgs({ sigs }); - const { aggPublicKey, tacc, challenge, finalNonce } = getSessionValues(sessionKey); - let sPart = ecc.scalarMultiply(challenge, tacc); - if (!ecc.hasEvenY(aggPublicKey)) { - sPart = ecc.scalarNegate(sPart); - } - const aggS = sigs.reduce((a, b) => ecc.scalarAdd(a, b), sPart); - const sig = new Uint8Array(64); - sig.set(ecc.pointX(finalNonce), 0); - sig.set(aggS, 32); - return sig; - }, - }; -} - -/** - * The Qi HD wallet is a BIP44-compliant hierarchical deterministic wallet used for managing a set of addresses in the - * Qi ledger. This is wallet implementation is the primary way to interact with the Qi UTXO ledger on the Quai network. - * - * The Qi HD wallet supports: - * - * - Adding accounts to the wallet heierchy - * - Generating addresses for a specific account in any {@link Zone} - * - Signing and sending transactions for any address in the wallet - * - Serializing the wallet to JSON and deserializing it back to a wallet instance. - * - * @category Wallet - * @example - * - * ```ts - * import { QiHDWallet, Zone } from 'quais'; - * - * const wallet = new QiHDWallet(); - * const cyrpus1Address = await wallet.getNextAddress(0, Zone.Cyrpus1); // get the first address in the Cyrpus1 zone - * await wallet.sendTransaction({ txInputs: [...], txOutputs: [...] }); // send a transaction - * const serializedWallet = wallet.serialize(); // serialize current (account/address) state of the wallet - * . - * . - * . - * const deserializedWallet = QiHDWallet.deserialize(serializedWallet); // create a new wallet instance from the serialized data - * ``` - */ -class QiHDWallet extends AbstractHDWallet { - /** - * @ignore - * @type {number} - */ - static _version = 1; - /** - * @ignore - * @type {number} - */ - static _GAP_LIMIT = 20; - /** - * @ignore - * @type {AllowedCoinType} - */ - static _coinType = 969; - /** - * Map of change addresses to address info. - * - * @ignore - * @type {Map} - */ - _changeAddresses = new Map(); - /** - * Array of gap addresses. - * - * @ignore - * @type {NeuteredAddressInfo[]} - */ - _gapChangeAddresses = []; - /** - * Array of gap change addresses. - * - * @ignore - * @type {NeuteredAddressInfo[]} - */ - _gapAddresses = []; - /** - * Array of outpoint information. - * - * @ignore - * @type {OutpointInfo[]} - */ - _outpoints = []; - /** - * @ignore - * @param {HDNodeWallet} root - The root HDNodeWallet. - * @param {Provider} [provider] - The provider (optional). - */ - constructor(guard, root, provider) { - super(guard, root, provider); - } - /** - * Promise that resolves to the next change address for the specified account and zone. - * - * @param {number} account - The index of the account for which to retrieve the next change address. - * @param {Zone} zone - The zone in which to retrieve the next change address. - * @returns {Promise} The next change neutered address information. - */ - async getNextChangeAddress(account, zone) { - return Promise.resolve(this._getNextAddress(account, zone, true, this._changeAddresses)); - } - /** - * Synchronously retrieves the next change address for the specified account and zone. - * - * @param {number} account - The index of the account for which to retrieve the next change address. - * @param {Zone} zone - The zone in which to retrieve the next change address. - * @returns {NeuteredAddressInfo} The next change neutered address information. - */ - getNextChangeAddressSync(account, zone) { - return this._getNextAddress(account, zone, true, this._changeAddresses); - } - /** - * Imports an array of outpoints. - * - * @param {OutpointInfo[]} outpoints - The outpoints to import. - */ - importOutpoints(outpoints) { - this.validateOutpointInfo(outpoints); - this._outpoints.push(...outpoints); - } - /** - * Gets the outpoints for the specified zone. - * - * @param {Zone} zone - The zone. - * @returns {OutpointInfo[]} The outpoints for the zone. - */ - getOutpoints(zone) { - this.validateZone(zone); - return this._outpoints.filter((outpoint) => outpoint.zone === zone); - } - /** - * Signs a Qi transaction and returns the serialized transaction. - * - * @param {QiTransactionRequest} tx - The transaction to sign. - * @returns {Promise} The serialized transaction. - * @throws {Error} If the UTXO transaction is invalid. - */ - async signTransaction(tx) { - const txobj = QiTransaction.from(tx); - if (!txobj.txInputs || txobj.txInputs.length == 0 || !txobj.txOutputs) - throw new Error('Invalid UTXO transaction, missing inputs or outputs'); - const hash = keccak_256(txobj.unsignedSerialized); - let signature; - if (txobj.txInputs.length == 1) { - signature = this.createSchnorrSignature(txobj.txInputs[0], hash); - } - else { - signature = this.createMuSigSignature(txobj, hash); - } - txobj.signature = signature; - return txobj.serialized; - } - /** - * Sends a Qi transaction. - * - * @param {QiTransactionRequest} tx - The transaction to send. - * @returns {Promise} The transaction response. - * @throws {Error} If the provider is not set or if the transaction has no inputs. - */ - async sendTransaction(tx) { - if (!this.provider) { - throw new Error('Provider is not set'); - } - if (!tx.txInputs || tx.txInputs.length === 0) { - throw new Error('Transaction has no inputs'); - } - const input = tx.txInputs[0]; - const address = computeAddress(input.pubkey); - const shard = getZoneForAddress(address); - if (!shard) { - throw new Error(`Address ${address} not found in any shard`); - } - // verify all inputs are from the same shard - if (tx.txInputs.some((input) => getZoneForAddress(computeAddress(input.pubkey)) !== shard)) { - throw new Error('All inputs must be from the same shard'); - } - const signedTx = await this.signTransaction(tx); - return await this.provider.broadcastTransaction(shard, signedTx); - } - /** - * Returns a schnorr signature for the given message and private key. - * - * @ignore - * @param {TxInput} input - The transaction input. - * @param {Uint8Array} hash - The hash of the message. - * @returns {string} The schnorr signature. - */ - createSchnorrSignature(input, hash) { - const privKey = this.getPrivateKeyForTxInput(input); - const signature = schnorr.sign(hash, getBytes(privKey)); - return hexlify(signature); - } - /** - * Returns a MuSig signature for the given message and private keys corresponding to the input addresses. - * - * @ignore - * @param {QiTransaction} tx - The Qi transaction. - * @param {Uint8Array} hash - The hash of the message. - * @returns {string} The MuSig signature. - */ - createMuSigSignature(tx, hash) { - const musig = MuSigFactory(musigCrypto); - // Collect private keys corresponding to the pubkeys found on the inputs - const privKeysSet = new Set(); - tx.txInputs.forEach((input) => { - const privKey = this.getPrivateKeyForTxInput(input); - privKeysSet.add(privKey); - }); - const privKeys = Array.from(privKeysSet); - // Create an array of public keys corresponding to the private keys for musig aggregation - const pubKeys = privKeys - .map((privKey) => musigCrypto.getPublicKey(getBytes(privKey), true)) - .filter((pubKey) => pubKey !== null); - // Generate nonces for each public key - const nonces = pubKeys.map((pk) => musig.nonceGen({ publicKey: getBytes(pk) })); - const aggNonce = musig.nonceAgg(nonces); - const signingSession = musig.startSigningSession(aggNonce, hash, pubKeys); - // Create partial signatures for each private key - const partialSignatures = privKeys.map((sk, index) => musig.partialSign({ - secretKey: getBytes(sk || ''), - publicNonce: nonces[index], - sessionKey: signingSession, - verify: true, - })); - // Aggregate the partial signatures into a final aggregated signature - const finalSignature = musig.signAgg(partialSignatures, signingSession); - return hexlify(finalSignature); - } - /** - * Retrieves the private key for a given transaction input. - * - * This method derives the private key for a transaction input by following these steps: - * - * 1. Ensures the input contains a public key. - * 2. Computes the address from the public key. - * 3. Fetches address information associated with the computed address. - * 4. Derives the hierarchical deterministic (HD) node corresponding to the address. - * 5. Returns the private key of the derived HD node. - * - * @ignore - * @param {TxInput} input - The transaction input containing the public key. - * @returns {string} The private key corresponding to the transaction input. - * @throws {Error} If the input does not contain a public key or if the address information cannot be found. - */ - getPrivateKeyForTxInput(input) { - if (!input.pubkey) - throw new Error('Missing public key for input'); - const address = computeAddress(input.pubkey); - // get address info - const addressInfo = this.getAddressInfo(address); - if (!addressInfo) - throw new Error(`Address not found: ${address}`); - // derive an HDNode for the address and get the private key - const changeIndex = addressInfo.change ? 1 : 0; - const addressNode = this._root - .deriveChild(addressInfo.account) - .deriveChild(changeIndex) - .deriveChild(addressInfo.index); - return addressNode.privateKey; - } - /** - * Scans the specified zone for addresses with unspent outputs. Starting at index 0, it will generate new addresses - * until the gap limit is reached for both gap and change addresses. - * - * @param {Zone} zone - The zone in which to scan for addresses. - * @param {number} [account=0] - The index of the account to scan. Default is `0` - * @returns {Promise} A promise that resolves when the scan is complete. - * @throws {Error} If the zone is invalid. - */ - async scan(zone, account = 0) { - this.validateZone(zone); - // flush the existing addresses and outpoints - this._addresses = new Map(); - this._changeAddresses = new Map(); - this._gapAddresses = []; - this._gapChangeAddresses = []; - this._outpoints = []; - await this._scan(zone, account); - } - /** - * Scans the specified zone for addresses with unspent outputs. Starting at the last address index, it will generate - * new addresses until the gap limit is reached for both gap and change addresses. If no account is specified, it - * will scan all accounts known to the wallet. - * - * @param {Zone} zone - The zone in which to sync addresses. - * @param {number} [account] - The index of the account to sync. If not specified, all accounts will be scanned. - * @returns {Promise} A promise that resolves when the sync is complete. - * @throws {Error} If the zone is invalid. - */ - async sync(zone, account) { - this.validateZone(zone); - // if no account is specified, scan all accounts. - if (account === undefined) { - const addressInfos = Array.from(this._addresses.values()); - const accounts = addressInfos.reduce((unique, info) => { - if (!unique.includes(info.account)) { - unique.push(info.account); - } - return unique; - }, []); - for (const acc of accounts) { - await this._scan(zone, acc); - } - } - else { - await this._scan(zone, account); - } - return; - } - /** - * Internal method to scan the specified zone for addresses with unspent outputs. This method handles the actual - * scanning logic, generating new addresses until the gap limit is reached for both gap and change addresses. - * - * @param {Zone} zone - The zone in which to scan for addresses. - * @param {number} [account=0] - The index of the account to scan. Default is `0` - * @returns {Promise} A promise that resolves when the scan is complete. - * @throws {Error} If the provider is not set. - */ - async _scan(zone, account = 0) { - if (!this.provider) - throw new Error('Provider not set'); - let gapAddressesCount = 0; - let changeGapAddressesCount = 0; - while (gapAddressesCount < QiHDWallet._GAP_LIMIT || changeGapAddressesCount < QiHDWallet._GAP_LIMIT) { - [gapAddressesCount, changeGapAddressesCount] = await Promise.all([ - gapAddressesCount < QiHDWallet._GAP_LIMIT - ? this.scanAddress(zone, account, false, gapAddressesCount) - : gapAddressesCount, - changeGapAddressesCount < QiHDWallet._GAP_LIMIT - ? this.scanAddress(zone, account, true, changeGapAddressesCount) - : changeGapAddressesCount, - ]); - } - } - /** - * Scans for the next address in the specified zone and account, checking for associated outpoints, and updates the - * address count and gap addresses accordingly. - * - * @param {Zone} zone - The zone in which the address is being scanned. - * @param {number} account - The index of the account for which the address is being scanned. - * @param {boolean} isChange - A flag indicating whether the address is a change address. - * @param {number} addressesCount - The current count of addresses scanned. - * @returns {Promise} A promise that resolves to the updated address count. - * @throws {Error} If an error occurs during the address scanning or outpoints retrieval process. - */ - async scanAddress(zone, account, isChange, addressesCount) { - const addressMap = isChange ? this._changeAddresses : this._addresses; - const addressInfo = this._getNextAddress(account, zone, isChange, addressMap); - const outpoints = await this.getOutpointsByAddress(addressInfo.address); - if (outpoints.length > 0) { - this.importOutpoints(outpoints.map((outpoint) => ({ - outpoint, - address: addressInfo.address, - zone, - account, - }))); - addressesCount = 0; - isChange ? (this._gapChangeAddresses = []) : (this._gapAddresses = []); - } - else { - addressesCount++; - isChange ? this._gapChangeAddresses.push(addressInfo) : this._gapAddresses.push(addressInfo); - } - return addressesCount; - } - /** - * Queries the network node for the outpoints of the specified address. - * - * @ignore - * @param {string} address - The address to query. - * @returns {Promise} The outpoints for the address. - * @throws {Error} If the query fails. - */ - async getOutpointsByAddress(address) { - try { - const outpointsMap = await this.provider.getOutpointsByAddress(address); - if (!outpointsMap) { - return []; - } - return Object.values(outpointsMap); - } - catch (error) { - throw new Error(`Failed to get outpoints for address: ${address} - error: ${error}`); - } - } - /** - * Gets the change addresses for the specified zone. - * - * @param {Zone} zone - The zone. - * @returns {NeuteredAddressInfo[]} The change addresses for the zone. - */ - getChangeAddressesForZone(zone) { - this.validateZone(zone); - const changeAddresses = this._changeAddresses.values(); - return Array.from(changeAddresses).filter((addressInfo) => addressInfo.zone === zone); - } - /** - * Gets the gap addresses for the specified zone. - * - * @param {Zone} zone - The zone. - * @returns {NeuteredAddressInfo[]} The gap addresses for the zone. - */ - getGapAddressesForZone(zone) { - this.validateZone(zone); - const gapAddresses = this._gapAddresses.filter((addressInfo) => addressInfo.zone === zone); - return gapAddresses; - } - /** - * Gets the gap change addresses for the specified zone. - * - * @param {Zone} zone - The zone. - * @returns {NeuteredAddressInfo[]} The gap change addresses for the zone. - */ - getGapChangeAddressesForZone(zone) { - this.validateZone(zone); - const gapChangeAddresses = this._gapChangeAddresses.filter((addressInfo) => addressInfo.zone === zone); - return gapChangeAddresses; - } - /** - * Signs a message using the private key associated with the given address. - * - * @param {string} address - The address for which the message is to be signed. - * @param {string | Uint8Array} message - The message to be signed, either as a string or Uint8Array. - * @returns {Promise} A promise that resolves to the signature of the message in hexadecimal string format. - * @throws {Error} If the address does not correspond to a valid HD node or if signing fails. - */ - async signMessage(address, message) { - const addrNode = this._getHDNodeForAddress(address); - const privKey = addrNode.privateKey; - const digest = keccak_256(message); - const signature = schnorr.sign(digest, getBytes(privKey)); - return hexlify(signature); - } - /** - * Serializes the HD wallet state into a format suitable for storage or transmission. - * - * @returns {SerializedQiHDWallet} An object representing the serialized state of the HD wallet, including - * outpoints, change addresses, gap addresses, and other inherited properties. - */ - serialize() { - const hdwalletSerialized = super.serialize(); - return { - outpoints: this._outpoints, - changeAddresses: Array.from(this._changeAddresses.values()), - gapAddresses: this._gapAddresses, - gapChangeAddresses: this._gapChangeAddresses, - ...hdwalletSerialized, - }; - } - /** - * Deserializes a serialized QiHDWallet object and reconstructs the wallet instance. - * - * @param {SerializedQiHDWallet} serialized - The serialized object representing the state of a QiHDWallet. - * @returns {Promise} A promise that resolves to a reconstructed QiHDWallet instance. - * @throws {Error} If the serialized data is invalid or if any addresses in the gap addresses or gap change - * addresses do not exist in the wallet. - */ - static async deserialize(serialized) { - super.validateSerializedWallet(serialized); - // create the wallet instance - const mnemonic = Mnemonic.fromPhrase(serialized.phrase); - const path = this.parentPath(serialized.coinType); - const root = HDNodeWallet.fromMnemonic(mnemonic, path); - const wallet = new this(_guard, root); - // import the addresses - wallet.importSerializedAddresses(wallet._addresses, serialized.addresses); - // import the change addresses - wallet.importSerializedAddresses(wallet._changeAddresses, serialized.changeAddresses); - // import the gap addresses, verifying they already exist in the wallet - for (const gapAddressInfo of serialized.gapAddresses) { - const gapAddress = gapAddressInfo.address; - if (!wallet._addresses.has(gapAddress)) { - throw new Error(`Address ${gapAddress} not found in wallet`); - } - wallet._gapAddresses.push(gapAddressInfo); - } - // import the gap change addresses, verifying they already exist in the wallet - for (const gapChangeAddressInfo of serialized.gapChangeAddresses) { - const gapChangeAddress = gapChangeAddressInfo.address; - if (!wallet._changeAddresses.has(gapChangeAddress)) { - throw new Error(`Address ${gapChangeAddress} not found in wallet`); - } - wallet._gapChangeAddresses.push(gapChangeAddressInfo); - } - // validate the outpoints and import them - wallet.validateOutpointInfo(serialized.outpoints); - wallet._outpoints.push(...serialized.outpoints); - return wallet; - } - /** - * Validates an array of OutpointInfo objects. This method checks the validity of each OutpointInfo object by - * performing the following validations: - * - * - Validates the zone using the `validateZone` method. - * - Checks if the address exists in the wallet. - * - Checks if the account (if provided) exists in the wallet. - * - Validates the Outpoint by ensuring that `Txhash`, `Index`, and `Denomination` are not null. - * - * @ignore - * @param {OutpointInfo[]} outpointInfo - An array of OutpointInfo objects to be validated. - * @throws {Error} If any of the validations fail, an error is thrown with a descriptive message. - */ - validateOutpointInfo(outpointInfo) { - outpointInfo.forEach((info) => { - // validate zone - this.validateZone(info.zone); - // validate address and account - const addressInfo = this.getAddressInfo(info.address); - if (!addressInfo) { - throw new Error(`Address ${info.address} not found in wallet`); - } - if (info.account !== undefined && info.account !== addressInfo.account) { - throw new Error(`Account ${info.account} not found for address ${info.address}`); - } - // validate Outpoint - if (info.outpoint.txhash == null || info.outpoint.index == null || info.outpoint.denomination == null) { - throw new Error(`Invalid Outpoint: ${JSON.stringify(info)} `); - } - }); - } -} - -/** - * A **Network** encapsulates the various properties required to interact with a specific chain. - * @category Providers - */ -const Networks = new Map(); -/** - * A **Network** provides access to a chain's properties and allows for plug-ins to extend functionality. - * - * @category Providers - */ -class Network { - #name; - #chainId; - /** - * Creates a new **Network** for `name` and `chainId`. - * @param {string} name - The network name. - * @param {BigNumberish} chainId - The network chain ID. - */ - constructor(name, chainId) { - this.#name = name; - this.#chainId = getBigInt(chainId); - } - /** - * Returns a JSON-compatible representation of a Network. - * @returns {Object} The JSON representation of the network. - */ - toJSON() { - return { name: this.name, chainId: String(this.chainId) }; - } - /** - * The network common name. - * - * This is the canonical name, as networks might have multiple names. - * @returns {string} The network name. - */ - get name() { - return this.#name; - } - /** - * Sets the network name. - * @param {string} value - The new network name. - */ - set name(value) { - this.#name = value; - } - /** - * The network chain ID. - * @returns {bigint} The network chain ID. - */ - get chainId() { - return this.#chainId; - } - /** - * Sets the network chain ID. - * @param {BigNumberish} value - The new network chain ID. - */ - set chainId(value) { - this.#chainId = getBigInt(value, 'chainId'); - } - /** - * Returns true if `other` matches this network. Any chain ID must match, and if no chain ID is present, the name - * must match. - * - * This method does not currently check for additional properties, such as plug-in compatibility. - * - * @param {Networkish} other - The network to compare. - * @returns {boolean} True if the networks match. - * @ignore - */ - matches(other) { - if (other == null) { - return false; - } - if (typeof other === 'string') { - try { - return this.chainId === getBigInt(other); - // eslint-disable-next-line no-empty - } - catch (error) { } - return this.name === other; - } - if (typeof other === 'number' || typeof other === 'bigint') { - try { - return this.chainId === getBigInt(other); - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; - } - if (typeof other === 'object') { - if (other.chainId != null) { - try { - return this.chainId === getBigInt(other.chainId); - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; - } - if (other.name != null) { - return this.name === other.name; - } - return false; - } - return false; - } - /** - * Create a copy of this Network. - * @returns {Network} A new Network instance. - */ - clone() { - const clone = new Network(this.name, this.chainId); - return clone; - } - /** - * Returns a new Network for the `network` name or chainId. - * - * @param {Networkish} [network] - The network to get. - * @returns {Network} The Network instance. - * @throws {Error} If the network is invalid. - */ - static from(network) { - // Default network - if (network == null) { - return Network.from('mainnet'); - } - // Canonical name or chain ID - if (typeof network === 'number') { - network = BigInt(network); - } - if (typeof network === 'string' || typeof network === 'bigint') { - const networkFunc = Networks.get(network); - if (networkFunc) { - return networkFunc(); - } - if (typeof network === 'bigint') { - return new Network('unknown', network); - } - assertArgument(false, 'unknown network', 'network', network); - } - // Clonable with network-like abilities - if (typeof network.clone === 'function') { - const clone = network.clone(); - return clone; - } - // Networkish - if (typeof network === 'object') { - assertArgument(typeof network.name === 'string' && typeof network.chainId === 'number', 'invalid network object name or chainId', 'network', network); - const custom = new Network(network.name, network.chainId); - return custom; - } - assertArgument(false, 'invalid network', 'network', network); - } - /** - * Register `nameOrChainId` with a function which returns an instance of a Network representing that chain. - * - * @param {string | number | bigint} nameOrChainId - The name or chain ID to register. - * @param {() => Network} networkFunc - The function to create the Network. - * @throws {Error} If a network is already registered for `nameOrChainId`. - */ - static register(nameOrChainId, networkFunc) { - if (typeof nameOrChainId === 'number') { - nameOrChainId = BigInt(nameOrChainId); - } - const existing = Networks.get(nameOrChainId); - if (existing) { - assertArgument(false, `conflicting network for ${JSON.stringify(existing.name)}`, 'nameOrChainId', nameOrChainId); - } - Networks.set(nameOrChainId, networkFunc); - } -} - -/** - * Deep copies an object. - * - * @param {any} obj - The object to copy. - * @returns {any} The copied object. - */ -function copy$2(obj) { - return JSON.parse(JSON.stringify(obj)); -} -/** - * A **PollingBlockSubscriber** polls at a regular interval for a change in the block number. - * - * @category Providers - */ -class PollingBlockSubscriber { - #provider; - #poller; - #interval; - #zone; - // The most recent block we have scanned for events. The value -2 - // indicates we still need to fetch an initial block number - #blockNumber; - /** - * Create a new **PollingBlockSubscriber** attached to `provider`. - * - * @ignore - */ - constructor(provider, zone) { - this.#provider = provider; - this.#zone = zone; - this.#poller = null; - this.#interval = 4000; - this.#blockNumber = -2; - } - /** - * The polling interval. - * - * @returns {number} The current polling interval. - */ - get pollingInterval() { - return this.#interval; - } - /** - * Sets the polling interval. - * - * @param {number} value - The new polling interval. - */ - set pollingInterval(value) { - this.#interval = value; - } - /** - * Polls for new blocks. - * - * @ignore - * @returns {Promise} A promise that resolves when polling is complete. - */ - async #poll() { - try { - const blockNumber = await this.#provider.getBlockNumber(toShard(this.#zone)); - // Bootstrap poll to setup our initial block number - if (this.#blockNumber === -2) { - this.#blockNumber = blockNumber; - return; - } - // @TODO: Put a cap on the maximum number of events per loop? - if (blockNumber !== this.#blockNumber) { - for (let b = this.#blockNumber + 1; b <= blockNumber; b++) { - // We have been stopped - if (this.#poller == null) { - return; - } - await this.#provider.emit('block', this.#zone, b); - } - this.#blockNumber = blockNumber; - } - } - catch (error) { - // @TODO: Minor bump, add an "error" event to let subscribers - // know things went awry. - } - // We have been stopped - if (this.#poller == null) { - return; - } - this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); - } - /** - * Starts the polling process. - */ - start() { - if (this.#poller) { - return; - } - this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); - this.#poll(); - } - /** - * Stops the polling process. - */ - stop() { - if (!this.#poller) { - return; - } - this.#provider._clearTimeout(this.#poller); - this.#poller = null; - } - /** - * Pauses the polling process. - * - * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused. - */ - pause(dropWhilePaused) { - this.stop(); - if (dropWhilePaused) { - this.#blockNumber = -2; - } - } - /** - * Resumes the polling process. - */ - resume() { - this.start(); - } -} -/** - * An **OnBlockSubscriber** can be sub-classed, with a {@link OnBlockSubscriber._poll | **_poll**} implementation which - * will be called on every new block. - * - * @category Providers - */ -class OnBlockSubscriber { - #provider; - #poll; - #running; - #zone; - /** - * Create a new **OnBlockSubscriber** attached to `provider`. - * - * @ignore - */ - constructor(provider, zone) { - this.#provider = provider; - this.#zone = zone; - this.#running = false; - this.#poll = (blockNumber) => { - this._poll(blockNumber, this.#provider); - }; - } - /** - * Called on every new block. - * - * @ignore - * @param {number} blockNumber - The block number. - * @param {AbstractProvider} provider - The provider. - * @returns {Promise} A promise that resolves when the poll is complete. - * @throws {Error} If the method is not overridden by a subclass. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _poll(blockNumber, provider) { - throw new Error('sub-classes must override this'); - } - /** - * Starts the subscriber. - */ - start() { - if (this.#running) { - return; - } - this.#running = true; - this.#poll(-2); - this.#provider.on('block', this.#poll, this.#zone); - } - /** - * Stops the subscriber. - */ - stop() { - if (!this.#running) { - return; - } - this.#running = false; - this.#provider.off('block', this.#poll, this.#zone); - } - /** - * Pauses the subscriber. - * - * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - pause(dropWhilePaused) { - this.stop(); - } - /** - * Resumes the subscriber. - */ - resume() { - this.start(); - } -} -/** - * @ignore - */ -class PollingOrphanSubscriber extends OnBlockSubscriber { - #filter; - /** - * Create a new **PollingOrphanSubscriber** attached to `provider`, listening for `filter`. - * - * @ignore - */ - constructor(provider, filter, zone) { - super(provider, zone); - this.#filter = copy$2(filter); - } - /** - * Polls for orphaned blocks. - * - * @ignore - * @param {number} blockNumber - The block number. - * @param {AbstractProvider} provider - The provider. - * @returns {Promise} A promise that resolves when the poll is complete. - * @throws {Error} If the method is not implemented. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _poll(blockNumber, provider) { - throw new Error('@TODO'); - } -} -/** - * A **PollingTransactionSubscriber** will poll for a given transaction hash for its receipt. - * - * @category Providers - */ -class PollingTransactionSubscriber extends OnBlockSubscriber { - #hash; - /** - * Create a new **PollingTransactionSubscriber** attached to `provider`, listening for `hash`. - * - * @ignore - */ - constructor(provider, hash, zone) { - super(provider, zone); - this.#hash = hash; - } - /** - * Polls for the transaction receipt. - * - * @ignore - * @param {number} blockNumber - The block number. - * @param {AbstractProvider} provider - The provider. - * @returns {Promise} A promise that resolves when the poll is complete. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _poll(blockNumber, provider) { - const tx = await provider.getTransactionReceipt(this.#hash); - if (tx) { - provider.emit(this.#hash, toZone(this.#hash.slice(0, 4)), tx); - } - } -} -/** - * A **PollingEventSubscriber** will poll for a given filter for its logs. - * - * @category Providers - */ -class PollingEventSubscriber { - #provider; - #filter; - #poller; - #running; - #blockNumber; - #zone; - /** - * Create a new **PollingEventSubscriber** attached to `provider`, listening for `filter`. - * - * @ignore - */ - constructor(provider, filter) { - this.#provider = provider; - this.#filter = copy$2(filter); - this.#poller = this.#poll.bind(this); - this.#running = false; - this.#blockNumber = -2; - const zone = getZoneFromEventFilter(this.#filter); - if (zone) { - this.#zone = zone; - } - else { - throw new Error('Unable to determine zone for event filter'); - } - } - /** - * Polls for logs based on the filter. - * - * @ignore - * @param {number} blockNumber - The block number. - * @returns {Promise} A promise that resolves when the poll is complete. - */ - async #poll(blockNumber) { - // The initial block hasn't been determined yet - if (this.#blockNumber === -2) { - return; - } - const filter = copy$2(this.#filter); - filter.fromBlock = this.#blockNumber + 1; - filter.toBlock = blockNumber; - const logs = await this.#provider.getLogs(filter); - // No logs could just mean the node has not indexed them yet, - // so we keep a sliding window of 60 blocks to keep scanning - if (logs.length === 0) { - if (this.#blockNumber < blockNumber - 60) { - this.#blockNumber = blockNumber - 60; - } - return; - } - for (const log of logs) { - this.#provider.emit(this.#filter, getZoneFromNodeLocation(this.#filter.nodeLocation), log); - // Only advance the block number when logs were found to - // account for networks (like BNB and Polygon) which may - // sacrifice event consistency for block event speed - this.#blockNumber = log.blockNumber; - } - } - /** - * Starts the subscriber. - */ - start() { - if (this.#running) { - return; - } - this.#running = true; - if (this.#blockNumber === -2) { - this.#provider.getBlockNumber(toShard(this.#zone)).then((blockNumber) => { - this.#blockNumber = blockNumber; - }); - } - this.#provider.on('block', this.#poller, this.#zone); - } - /** - * Stops the subscriber. - */ - stop() { - if (!this.#running) { - return; - } - this.#running = false; - this.#provider.off('block', this.#poller, this.#zone); - } - /** - * Pauses the subscriber. - * - * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused. - */ - pause(dropWhilePaused) { - this.stop(); - if (dropWhilePaused) { - this.#blockNumber = -2; - } - } - /** - * Resumes the subscriber. - */ - resume() { - this.start(); - } -} - -/** - * The available providers should suffice for most developers purposes, but the - * {@link AbstractProvider | **AbstractProvider**} class has many features which enable sub-classing it for specific - * purposes. - */ -/** - * Event coalescence When we register an event with an async value (e.g. address is a Signer), we need to add it - * immediately for the Event API, but also need time to resolve the address. Upon resolving the address, we need to - * migrate the listener to the static event. We also need to maintain a map of Signer to address so we can sync respond - * to listenerCount. - */ -/** - * Constants - */ -const BN_2 = BigInt(2); -/** - * Check if a value is a Promise. - * - * @param {any} value - The value to check. - * @returns {boolean} True if the value is a Promise, false otherwise. - */ -function isPromise(value) { - return value && typeof value.then === 'function'; -} -/** - * Get a tag string based on a prefix and value. - * - * @param {string} prefix - The prefix for the tag. - * @param {any} value - The value to include in the tag. - * @returns {string} The generated tag. - */ -function getTag(prefix, value) { - return (prefix + - ':' + - JSON.stringify(value, (k, v) => { - if (v == null) { - return 'null'; - } - if (typeof v === 'bigint') { - return `bigint:${v.toString()}`; - } - if (typeof v === 'string') { - return v.toLowerCase(); - } - // Sort object keys - if (typeof v === 'object' && !Array.isArray(v)) { - const keys = Object.keys(v); - keys.sort(); - return keys.reduce((accum, key) => { - accum[key] = v[key]; - return accum; - }, {}); - } - return v; - })); -} -/** - * An **UnmanagedSubscriber** is useful for events which do not require any additional management, such as `"debug"` - * which only requires emit in synchronous event loop triggered calls. - * - * @category Providers - */ -class UnmanagedSubscriber { - /** - * The name of the event. - */ - name; - /** - * Create a new UnmanagedSubscriber with `name`. - * - * @param {string} name - The name of the event. - */ - constructor(name) { - defineProperties(this, { name }); - } - start() { } - stop() { } - // todo `dropWhilePaused` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - pause(dropWhilePaused) { } - resume() { } -} -/** - * Create a deep copy of a value. - * - * @param {T} value - The value to copy. - * @returns {T} The copied value. - */ -function copy$1(value) { - return JSON.parse(JSON.stringify(value)); -} -/** - * Remove duplicates and sort an array of strings. - * - * @param {string[]} items - The array of strings. - * @returns {string[]} The concisified array. - */ -function concisify(items) { - items = Array.from(new Set(items).values()); - items.sort(); - return items; -} -// todo `provider` is not used, remove or re-write -// eslint-disable-next-line @typescript-eslint/no-unused-vars -async function getSubscription(_event, zone) { - if (_event == null) { - throw new Error('invalid event'); - } - // Normalize topic array info an EventFilter - if (Array.isArray(_event)) { - _event = { topics: _event }; - } - if (typeof _event === 'string') { - if (_event === 'debug') { - return { type: _event, tag: _event }; - } - switch (_event) { - case 'block': - case 'pending': - if (!zone) { - throw new Error('zone is required for block and pending events'); - } - return { type: 'block', tag: _event, zone }; - case 'error': - case 'finalized': - case 'network': - case 'safe': { - return { type: _event, tag: _event }; - } - } - } - if (isHexString(_event, 32)) { - const hash = _event.toLowerCase(); - zone = toZone(hash.slice(0, 4)); - return { type: 'transaction', tag: getTag('tx', { hash }), hash, zone }; - } - if (_event.orphan) { - const event = _event; - if (!zone) { - const hash = event.hash || - event.tx.hash || - event.other?.hash || - event.log.transactionHash || - null; - if (hash == null) { - throw new Error('orphan event must specify a hash'); - } - zone = toZone(hash.slice(0, 4)); - } - // @todo Should lowercase and whatnot things here instead of copy... - return { type: 'orphan', tag: getTag('orphan', event), filter: copy$1(event), zone }; - } - if (_event.address || _event.topics) { - const event = _event; - const filter = { - topics: (event.topics || []).map((t) => { - if (t == null) { - return null; - } - if (Array.isArray(t)) { - return concisify(t.map((t) => t.toLowerCase())); - } - return t.toLowerCase(); - }), - }; - if (event.nodeLocation) { - filter.nodeLocation = event.nodeLocation; - } - if (event.address) { - const addresses = []; - const promises = []; - const addAddress = (addr) => { - if (isHexString(addr)) { - addresses.push(formatMixedCaseChecksumAddress(addr)); - } - else { - promises.push((async () => { - addresses.push(formatMixedCaseChecksumAddress(await resolveAddress(addr))); - })()); - } - }; - if (Array.isArray(event.address)) { - event.address.forEach(addAddress); - } - else { - addAddress(event.address); - } - if (promises.length) { - await Promise.all(promises); - } - if (!zone) { - zone = toZone(addresses[0].slice(0, 4)); - } - filter.address = concisify(addresses.map((a) => a.toLowerCase())); - if (!filter.nodeLocation) { - filter.nodeLocation = getNodeLocationFromZone(zone); - } - } - else { - if (!zone) { - throw new Error('zone is required for event'); - } - } - return { filter, tag: getTag('event', filter), type: 'event', zone }; - } - assertArgument(false, 'unknown ProviderEvent', 'event', _event); -} -/** - * Get the current time in milliseconds. - * - * @returns {number} The current time in milliseconds. - */ -function getTime() { - return new Date().getTime(); -} -const defaultOptions$1 = { - cacheTimeout: 250, - pollingInterval: 4000, - usePathing: false, -}; -/** - * An **AbstractProvider** provides a base class for other sub-classes to implement the {@link Provider | **Provider**} - * API by normalizing input arguments and formatting output results as well as tracking events for consistent behaviour - * on an eventually-consistent network. - * - * @category Providers - */ -class AbstractProvider { - /** - * @ignore - */ - _urlMap; - #connect; - #subs; - // null=unpaused, true=paused+dropWhilePaused, false=paused - #pausedState; - #destroyed; - #networkPromise; - #anyNetwork; - #performCache; - // The most recent block number if running an event or -1 if no "block" event - #lastBlockNumber; - #nextTimer; - #timers; - #options; - _initFailed; - initResolvePromise; - initRejectPromise; - initPromise; - /** - * Create a new **AbstractProvider** connected to `network`, or use the various network detection capabilities to - * discover the {@link Network | **Network**} if necessary. - * - * @param _network - The network to connect to, or `"any"` to - * @param options - The options to configure the provider. - */ - constructor(_network, options) { - this._initFailed = false; - this.#options = Object.assign({}, defaultOptions$1, options || {}); - if (_network === 'any') { - this.#anyNetwork = true; - this.#networkPromise = null; - } - else if (_network) { - const network = Network.from(_network); - this.#anyNetwork = false; - this.#networkPromise = Promise.resolve(network); - setTimeout(() => { - this.emit('network', undefined, network, null); - }, 0); - } - else { - this.#anyNetwork = false; - this.#networkPromise = null; - } - this.#lastBlockNumber = -1; - this.#performCache = new Map(); - this.#subs = new Map(); - this.#pausedState = null; - this.#destroyed = false; - this.#nextTimer = 1; - this.#timers = new Map(); - this.#connect = []; - this._urlMap = new Map(); - this.initResolvePromise = null; - this.initRejectPromise = null; - this.initPromise = new Promise((resolve, reject) => { - this.initResolvePromise = resolve; - this.initRejectPromise = reject; - }); - } - /** - * Initialize the URL map with the provided URLs. - * - * @param {U} urls - The URLs to initialize the map with. - * @returns {Promise} A promise that resolves when the map is initialized. - */ - async initialize(urls) { - try { - const primeSuffix = this.#options.usePathing ? `/${fromShard(Shard.Prime, 'nickname')}` : ':9001'; - if (urls instanceof FetchRequest) { - urls.url = urls.url.split(':')[0] + ':' + urls.url.split(':')[1] + primeSuffix; - this._urlMap.set(Shard.Prime, urls); - this.#connect.push(urls); - const shards = await this.getRunningLocations(); - shards.forEach((shard) => { - const port = 9200 + 20 * shard[0] + shard[1]; - const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`); - const shardSuffix = this.#options.usePathing ? `/${fromShard(shardEnum, 'nickname')}` : `:${port}`; - this._urlMap.set(shardEnum, new FetchRequest(urls.url.split(':')[0] + ':' + urls.url.split(':')[1] + shardSuffix)); - }); - return; - } - if (Array.isArray(urls)) { - for (const url of urls) { - const primeUrl = url.split(':')[0] + ':' + url.split(':')[1] + primeSuffix; - const primeConnect = new FetchRequest(primeUrl); - this._urlMap.set(Shard.Prime, primeConnect); - this.#connect.push(primeConnect); - const shards = await this.getRunningLocations(); - shards.forEach((shard) => { - const port = 9200 + 20 * shard[0] + shard[1]; - const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`); - const shardSuffix = this.#options.usePathing - ? `/${fromShard(shardEnum, 'nickname')}` - : `:${port}`; - this._urlMap.set(toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`), new FetchRequest(url.split(':')[0] + ':' + url.split(':')[1] + shardSuffix)); - }); - } - } - if (this.initResolvePromise) - this.initResolvePromise(); - } - catch (error) { - this._initFailed = true; - console.log('Error initializing URL map:', error); - if (this.initRejectPromise) - this.initRejectPromise(error); - } - } - /** - * Get the list of connected FetchRequests. - * - * @returns {FetchRequest[]} The list of connected FetchRequests. - */ - get connect() { - return this.#connect; - } - /** - * Get the zone from an address. - * - * @param {AddressLike} _address - The address to get the zone from. - * @returns {Promise} A promise that resolves to the zone. - */ - async zoneFromAddress(_address) { - const address = this._getAddress(_address); - return toZone((await address).slice(0, 4)); - } - /** - * Get the shard from a hash. - * - * @param {string} hash - The hash to get the shard from. - * @returns {Shard} The shard. - */ - shardFromHash(hash) { - return toShard(hash.slice(0, 4)); - } - /** - * Get the zone from a hash. - * - * @param {string} hash - The hash to get the zone from. - * @returns {Zone} The zone. - */ - zoneFromHash(hash) { - return toZone(hash.slice(0, 4)); - } - /** - * Get the latest Quai rate for a zone. - * - * @param {Zone} zone - The zone to get the rate for. - * @param {number} [amt=1] - The amount to get the rate for. Default is `1` - * @returns {Promise} A promise that resolves to the latest Quai rate. - */ - async getLatestQuaiRate(zone, amt = 1) { - const blockNumber = await this.getBlockNumber(toShard(zone)); - return this.getQuaiRateAtBlock(zone, blockNumber, amt); - } - /** - * Get the Quai rate at a specific block. - * - * @param {Zone} zone - The zone to get the rate for. - * @param {BlockTag} blockTag - The block tag to get the rate at. - * @param {number} [amt=1] - The amount to get the rate for. Default is `1` - * @returns {Promise} A promise that resolves to the Quai rate at the specified block. - */ - async getQuaiRateAtBlock(zone, blockTag, amt = 1) { - let resolvedBlockTag = this._getBlockTag(toShard(zone), blockTag); - if (typeof resolvedBlockTag !== 'string') { - resolvedBlockTag = await resolvedBlockTag; - } - return await this.#perform({ - method: 'getQuaiRateAtBlock', - blockTag: resolvedBlockTag, - amt, - zone: zone, - }); - } - /** - * Get the protocol expansion number. - * - * @returns {Promise} A promise that resolves to the protocol expansion number. - */ - async getProtocolExpansionNumber() { - return await this.#perform({ - method: 'getProtocolExpansionNumber', - }); - } - /** - * Get the latest Qi rate for a zone. - * - * @param {Zone} zone - The zone to get the rate for. - * @param {number} [amt=1] - The amount to get the rate for. Default is `1` - * @returns {Promise} A promise that resolves to the latest Qi rate. - */ - async getLatestQiRate(zone, amt = 1) { - const blockNumber = await this.getBlockNumber(toShard(zone)); - return this.getQiRateAtBlock(zone, blockNumber, amt); - } - /** - * Get the Qi rate at a specific block. - * - * @param {Zone} zone - The zone to get the rate for. - * @param {BlockTag} blockTag - The block tag to get the rate at. - * @param {number} [amt=1] - The amount to get the rate for. Default is `1` - * @returns {Promise} A promise that resolves to the Qi rate at the specified block. - */ - async getQiRateAtBlock(zone, blockTag, amt = 1) { - let resolvedBlockTag = this._getBlockTag(toShard(zone), blockTag); - if (typeof resolvedBlockTag !== 'string') { - resolvedBlockTag = await resolvedBlockTag; - } - return await this.#perform({ - method: 'getQiRateAtBlock', - blockTag: resolvedBlockTag, - amt, - zone: zone, - }); - } - /** - * Get the polling interval. - * - * @returns {number} The polling interval. - */ - get pollingInterval() { - return this.#options.pollingInterval; - } - /** - * Returns `this`, to allow an **AbstractProvider** to implement the [Contract Runner](../classes/ContractRunner) - * interface. - * - * @returns {this} The provider instance. - */ - get provider() { - return this; - } - /** - * Shares multiple identical requests made during the same 250ms. - * - * @ignore - * @param {PerformActionRequest} req - The request to perform. - * @returns {Promise} A promise that resolves to the result of the operation. - */ - async #perform(req) { - const timeout = this.#options.cacheTimeout; - // Caching disabled - if (timeout < 0) { - return await this._perform(req); - } - // Create a tag - const tag = getTag(req.method, req); - let perform = this.#performCache.get(tag); - if (!perform || tag.includes('pending') || tag.includes('latest')) { - perform = this._perform(req); - this.#performCache.set(tag, perform); - setTimeout(() => { - if (this.#performCache.get(tag) === perform) { - this.#performCache.delete(tag); - } - }, timeout); - } - return await perform; - } - /** - * Provides the opportunity for a sub-class to wrap a block before returning it, to add additional properties or an - * alternate sub-class of {@link Block | **Block**}. - * - * @ignore - * @param {BlockParams} value - The block to wrap. - * @param {Network} network - The network the block was on. - * @returns {Block} The wrapped block. - */ - // @todo `network` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _wrapBlock(value, network) { - // Handle known node by -> remove null values from the number array - value.header.number = Array.isArray(value.header.number) - ? value.header.number.filter((n) => n != null) - : value.header.number; - return new Block(formatBlock(value), this); - } - /** - * Provides the opportunity for a sub-class to wrap a log before returning it, to add additional properties or an - * alternate sub-class of {@link Log | **Log**}. - * - * @ignore - * @param {LogParams} value - The log to wrap. - * @param {Network} network - The network the log was on. - * @returns {Log} The wrapped log. - */ - // @todo `network` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _wrapLog(value, network) { - return new Log(formatLog(value), this); - } - /** - * Provides the opportunity for a sub-class to wrap a transaction receipt before returning it, to add additional - * properties or an {@link TransactionReceipt | **TransactionReceipt**}. - * - * @ignore - * @param {TransactionReceiptParams} value - The transaction receipt to wrap. - * @param {Network} network - The network the transaction was on. - * @returns {TransactionReceipt} The wrapped transaction receipt. - */ - // @todo `network` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _wrapTransactionReceipt(value, network) { - const formattedReceipt = formatTransactionReceipt(value); - return new TransactionReceipt(formattedReceipt, this); - } - /** - * Provides the opportunity for a sub-class to wrap a transaction response before returning it, to add additional - * properties or an alternate sub-class of {@link TransactionResponse | **TransactionResponse**}. - * - * @ignore - * @param {TransactionResponseParams} tx - The transaction response to wrap. - * @param {Network} network - The network the transaction was on. - * @returns {TransactionResponse} The wrapped transaction response. - */ - // TODO: `newtork` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _wrapTransactionResponse(tx, network) { - if ('from' in tx) { - return new QuaiTransactionResponse(formatTransactionResponse(tx), this); - } - else { - return new QiTransactionResponse(formatTransactionResponse(tx), this); - } - } - /** - * Resolves to the Network, forcing a network detection using whatever technique the sub-class requires. - * - * Sub-classes **must** override this. - * - * @ignore - * @param {Shard} [shard] - The shard to use for the network detection. - * @returns {Promise} A promise resolving to the network. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _detectNetwork() { - assert(false, 'sub-classes must implement this', 'UNSUPPORTED_OPERATION', { - operation: '_detectNetwork', - }); - } - /** - * Sub-classes should use this to perform all built-in operations. All methods sanitizes and normalizes the values - * passed into this. - * - * Sub-classes **must** override this. - * - * @ignore - * @param {PerformActionRequest} req - The request to perform. - * @returns {Promise} A promise resolving to the result of the operation. - */ - async _perform(req) { - assert(false, `unsupported method: ${req.method}`, 'UNSUPPORTED_OPERATION', { - operation: req.method, - info: req, - }); - } - // State - async getBlockNumber(shard) { - const blockNumber = getNumber(await this.#perform({ method: 'getBlockNumber', shard: shard }), '%response'); - if (this.#lastBlockNumber >= 0) { - this.#lastBlockNumber = blockNumber; - } - return blockNumber; - } - /** - * Returns or resolves to the address for `address`, resolving {@link Addressable | **Addressable**} objects and - * returning if already an address. - * - * @ignore - * @param {AddressLike} address - The address to normalize. - * @returns {string | Promise} The normalized address. - */ - _getAddress(address) { - return resolveAddress(address); - } - /** - * Returns or resolves to a valid block tag for `blockTag`, resolving negative values and returning if already a - * valid block tag. - * - * @ignore - * @param {Shard} [shard] - The shard to use for the block tag. - * @param {BlockTag} [blockTag] - The block tag to normalize. - * @returns {string | Promise} A promise that resolves to a valid block tag. - */ - _getBlockTag(shard, blockTag) { - if (blockTag == null) { - return 'latest'; - } - switch (blockTag) { - case 'earliest': - return '0x0'; - case 'finalized': - case 'latest': - case 'pending': - case 'safe': - return blockTag; - } - if (isHexString(blockTag)) { - if (isHexString(blockTag, 32)) { - return blockTag; - } - return toQuantity(blockTag); - } - if (typeof blockTag === 'bigint') { - blockTag = getNumber(blockTag, 'blockTag'); - } - if (typeof blockTag === 'number') { - if (blockTag >= 0) { - return toQuantity(blockTag); - } - if (this.#lastBlockNumber >= 0) { - return toQuantity(this.#lastBlockNumber + blockTag); - } - return this.getBlockNumber(shard).then((b) => toQuantity(b + blockTag)); - } - assertArgument(false, 'invalid blockTag', 'blockTag', blockTag); - } - /** - * Returns or resolves to a filter for `filter`, resolving any {@link Addressable | **Addressable**} object and - * returning if already a valid filter. - * - * @ignore - * @param {Filter | FilterByBlockHash} filter - The filter to normalize. - * @returns {PerformActionFilter | Promise} A promise that resolves to a valid filter. - */ - _getFilter(filter) { - // Create a canonical representation of the topics - const topics = (filter.topics || []).map((t) => { - if (t == null) { - return null; - } - if (Array.isArray(t)) { - return concisify(t.map((t) => t.toLowerCase())); - } - return t.toLowerCase(); - }); - const blockHash = 'blockHash' in filter ? filter.blockHash : undefined; - const resolve = (_address, fromBlock, toBlock, nodeLocation) => { - let address = undefined; - switch (_address.length) { - case 0: - break; - case 1: - address = _address[0]; - break; - default: - _address.sort(); - address = _address; - } - if (blockHash) { - if (fromBlock != null || toBlock != null) { - throw new Error('invalid filter'); - } - } - const filter = {}; - if (address) { - filter.address = address; - } - if (topics.length) { - filter.topics = topics; - } - if (fromBlock) { - filter.fromBlock = fromBlock; - } - if (toBlock) { - filter.toBlock = toBlock; - } - if (blockHash) { - filter.blockHash = blockHash; - } - if (nodeLocation) { - filter.nodeLocation = nodeLocation; - } - return filter; - }; - // Addresses could be async (Addressables) - const address = []; - if (filter.address) { - if (Array.isArray(filter.address)) { - for (const addr of filter.address) { - address.push(this._getAddress(addr)); - } - } - else { - address.push(this._getAddress(filter.address)); - } - } - const zone = getZoneFromNodeLocation(filter.nodeLocation); - let fromBlock = undefined; - if ('fromBlock' in filter) { - fromBlock = this._getBlockTag(toShard(zone), filter.fromBlock); - } - let toBlock = undefined; - if ('toBlock' in filter) { - toBlock = this._getBlockTag(toShard(zone), filter.toBlock); - } - let nodeLocation = undefined; - if (filter.nodeLocation) { - nodeLocation = filter.nodeLocation; - } - if (address.filter((a) => typeof a !== 'string').length || - (fromBlock != null && typeof fromBlock !== 'string') || - (toBlock != null && typeof toBlock !== 'string')) { - return Promise.all([Promise.all(address), fromBlock, toBlock, nodeLocation]).then((result) => { - return resolve(result[0], result[1], result[2], result[3]); - }); - } - return resolve(address, fromBlock, toBlock, nodeLocation); - } - /** - * Returns or resovles to a transaction for `request`, resolving any {@link Addressable | **Addressable**} and - * returning if already a valid transaction. - * - * @ignore - * @param {PerformActionTransaction} _request - The transaction to normalize. - * @returns {PerformActionTransaction | Promise} A promise that resolves to a valid - * transaction. - */ - _getTransactionRequest(_request) { - const request = copyRequest(_request); - const promises = []; - ['to', 'from', 'inputs', 'outputs'].forEach((key) => { - if (request[key] == null) { - return; - } - const addr = Array.isArray(request[key]) - ? 'address' in request[key][0] - ? request[key].map((it) => it.address) - : request[key].map((it) => computeAddress(it.pubkey)) - : resolveAddress(request[key]); - if (isPromise(addr)) { - if (Array.isArray(addr)) { - for (let i = 0; i < addr.length; i++) { - promises.push((async function () { - request[key][i].address = await addr[i]; - })()); - } - } - else { - promises.push((async function () { - request[key] = await addr; - })()); - } - } - else { - request[key] = addr; - } - }); - if (request.blockTag != null) { - const blockTag = this._getBlockTag(toShard(request.chainId.toString()), request.blockTag); - if (isPromise(blockTag)) { - promises.push((async function () { - request.blockTag = await blockTag; - })()); - } - else { - request.blockTag = blockTag; - } - } - if (promises.length) { - return (async function () { - await Promise.all(promises); - return request; - })(); - } - return request; - } - async getNetwork() { - // No explicit network was set and this is our first time - if (this.#networkPromise == null) { - // Detect the current network (shared with all calls) - const detectNetwork = (async () => { - try { - const network = await this._detectNetwork(); - this.emit('network', undefined, network, null); - return network; - } - catch (error) { - if (this.#networkPromise === detectNetwork) { - this.#networkPromise = null; - } - throw error; - } - })(); - this.#networkPromise = detectNetwork; - return (await detectNetwork).clone(); - } - const networkPromise = this.#networkPromise; - const [expected, actual] = await Promise.all([ - networkPromise, - this._detectNetwork(), // The actual connected network - ]); - if (expected.chainId !== actual.chainId) { - if (this.#anyNetwork) { - // The "any" network can change, so notify listeners - this.emit('network', undefined, actual, expected); - // Update the network if something else hasn't already changed it - if (this.#networkPromise === networkPromise) { - this.#networkPromise = Promise.resolve(actual); - } - } - else { - // Otherwise, we do not allow changes to the underlying network - assert(false, `network changed: ${expected.chainId} => ${actual.chainId} `, 'NETWORK_ERROR', { - event: 'changed', - }); - } - } - return expected.clone(); - } - async _getRunningLocations(shard, now) { - now = now ? now : false; - return await this.#perform(shard - ? { method: 'getRunningLocations', shard: shard, now: now } - : { method: 'getRunningLocations', now: now }); - } - async getRunningLocations(shard) { - return await this._getRunningLocations(shard); - } - async getProtocolTrieExpansionCount(shard) { - return await this.#perform({ method: 'getProtocolTrieExpansionCount', shard: shard }); - } - async getFeeData(zone, txType = true) { - const getFeeDataFunc = async () => { - const { gasPrice, priorityFee } = await resolveProperties({ - gasPrice: (async () => { - try { - const value = await this.#perform({ method: 'getGasPrice', txType, zone: zone }); - return getBigInt(value, '%response'); - } - catch (error) { - console.log(error); - } - return null; - })(), - priorityFee: (async () => { - try { - const value = txType - ? await this.#perform({ method: 'getMaxPriorityFeePerGas', zone: zone }) - : 0; - return getBigInt(value, '%response'); - // eslint-disable-next-line no-empty - } - catch (error) { } - return null; - })(), - }); - if (gasPrice == null) { - throw new Error('could not determine gasPrice'); - } - let maxFeePerGas = null; - let maxPriorityFeePerGas = null; - // These are the recommended EIP-1559 heuristics for fee data - maxPriorityFeePerGas = priorityFee != null ? priorityFee : BigInt('1000000000'); - maxFeePerGas = gasPrice * BN_2 + maxPriorityFeePerGas; - return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); - }; - return await getFeeDataFunc(); - } - async estimateGas(_tx) { - let tx = this._getTransactionRequest(_tx); - if (isPromise(tx)) { - tx = await tx; - } - const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx)); - return getBigInt(await this.#perform({ - method: 'estimateGas', - transaction: tx, - zone: zone, - }), '%response'); - } - // TODO: `attempt` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async #call(tx, blockTag, attempt, zone) { - // This came in as a PerformActionTransaction, so to/from are safe; we can cast - const transaction = copyRequest(tx); - return hexlify(await this._perform({ method: 'call', transaction, blockTag, zone })); - } - // TODO: `shard` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async #checkNetwork(promise, shard) { - const { value } = await resolveProperties({ - network: this.getNetwork(), - value: promise, - }); - return value; - } - async call(_tx) { - const zone = await this.zoneFromAddress(addressFromTransactionRequest(_tx)); - const shard = toShard(zone); - const { tx, blockTag } = await resolveProperties({ - tx: this._getTransactionRequest(_tx), - blockTag: this._getBlockTag(shard, _tx.blockTag), - }); - return await this.#checkNetwork(this.#call(tx, blockTag, -1, zone), shard); - } - // Account - async #getAccountValue(request, _address, _blockTag) { - let address = this._getAddress(_address); - const zone = await this.zoneFromAddress(_address); - const shard = toShard(zone); - let blockTag = this._getBlockTag(shard, _blockTag); - if (typeof address !== 'string' || typeof blockTag !== 'string') { - [address, blockTag] = await Promise.all([address, blockTag]); - } - return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag, zone: zone })), shard); - } - async getBalance(address, blockTag) { - return getBigInt(await this.#getAccountValue({ method: 'getBalance' }, address, blockTag), '%response'); - } - async getOutpointsByAddress(address) { - const outpoints = await this.#getAccountValue({ method: 'getOutpointsByAddress' }, address, 'latest'); - const outpointsArray = Array.isArray(outpoints) ? outpoints : []; - return outpointsArray.map((outpoint) => ({ - txhash: outpoint.Txhash, - index: outpoint.Index, - denomination: outpoint.Denomination, - })); - } - async getTransactionCount(address, blockTag) { - return getNumber(await this.#getAccountValue({ method: 'getTransactionCount' }, address, blockTag), '%response'); - } - async getCode(address, blockTag) { - return hexlify(await this.#getAccountValue({ method: 'getCode' }, address, blockTag)); - } - async getStorage(address, _position, blockTag) { - const position = getBigInt(_position, 'position'); - return hexlify(await this.#getAccountValue({ method: 'getStorage', position }, address, blockTag)); - } - async getPendingHeader() { - return await this.#perform({ method: 'getPendingHeader' }); - } - async getTxPoolContent(zone) { - return await this.#perform({ method: 'getTxPoolContent', zone: zone }); - } - async txPoolInspect(zone) { - return await this.#perform({ method: 'txPoolInspect', zone: zone }); - } - // Write - async broadcastTransaction(zone, signedTx) { - const type = decodeProtoTransaction(getBytes(signedTx)).type; - const { blockNumber, hash, network } = await resolveProperties({ - blockNumber: this.getBlockNumber(toShard(zone)), - hash: this._perform({ - method: 'broadcastTransaction', - signedTransaction: signedTx, - zone: zone, - }), - network: this.getNetwork(), - }); - const tx = type == 2 ? QiTransaction.from(signedTx) : QuaiTransaction.from(signedTx); - this.#validateTransactionHash(tx.hash || '', hash); - return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber); - } - #validateTransactionHash(computedHash, nodehash) { - if (computedHash !== nodehash) { - throw new Error('Transaction hash mismatch'); - } - } - validateUrl(url) { - const urlPattern = /^(https?):\/\/[a-zA-Z0-9.-]+(:\d+)?$/; - if (!urlPattern.test(url)) { - let errorMessage = 'Invalid URL: '; - if (!/^https?:\/\//.test(url)) { - errorMessage += 'URL must start with http:// or https://. '; - } - if (url.endsWith('/')) { - errorMessage += 'URL should not end with a /. '; - } - if (/\/[^/]+/.test(url)) { - errorMessage += 'URL should not contain a path, query string, or fragment. '; - } - throw new Error(errorMessage.trim()); - } - } - async #getBlock(shard, block, includeTransactions) { - if (isHexString(block, 32)) { - return await this.#perform({ - method: 'getBlock', - blockHash: block, - includeTransactions, - shard: shard, - }); - } - let blockTag = this._getBlockTag(shard, block); - if (typeof blockTag !== 'string') { - blockTag = await blockTag; - } - return await this.#perform({ - method: 'getBlock', - blockTag, - includeTransactions, - shard: shard, - }); - } - // Queries - async getBlock(shard, block, prefetchTxs) { - const { network, params } = await resolveProperties({ - network: this.getNetwork(), - params: this.#getBlock(shard, block, !!prefetchTxs), - }); - if (params == null) { - return null; - } - return this._wrapBlock(params, network); - } - async getTransaction(hash) { - const zone = toZone(this.shardFromHash(hash)); - const { network, params } = await resolveProperties({ - network: this.getNetwork(), - params: this.#perform({ method: 'getTransaction', hash, zone: zone }), - }); - if (params == null) { - return null; - } - return this._wrapTransactionResponse(params, network); - } - async getTransactionReceipt(hash) { - const zone = toZone(this.shardFromHash(hash)); - const { network, params } = await resolveProperties({ - network: this.getNetwork(), - params: this.#perform({ method: 'getTransactionReceipt', hash, zone: zone }), - }); - if (params == null) { - return null; - } - // Some backends did not backfill the effectiveGasPrice in to old transactions - // in the receipt, so we look it up manually and inject it. - if (params.gasPrice == null && params.effectiveGasPrice == null) { - const tx = await this.#perform({ method: 'getTransaction', hash, zone: zone }); - if (tx == null) { - throw new Error('report this; could not find tx or effectiveGasPrice'); - } - params.effectiveGasPrice = tx.gasPrice; - } - return this._wrapTransactionReceipt(params, network); - } - async getTransactionResult(hash) { - const zone = toZone(this.shardFromHash(hash)); - const { result } = await resolveProperties({ - network: this.getNetwork(), - result: this.#perform({ method: 'getTransactionResult', hash, zone: zone }), - }); - if (result == null) { - return null; - } - return hexlify(result); - } - // Bloom-filter Queries - async getLogs(_filter) { - let filter = this._getFilter(_filter); - if (isPromise(filter)) { - filter = await filter; - } - const { network, params } = await resolveProperties({ - network: this.getNetwork(), - params: this.#perform({ - method: 'getLogs', - filter, - zone: getZoneFromNodeLocation(filter.nodeLocation), - }), - }); - return params.map((p) => this._wrapLog(p, network)); - } - /** - * @ignore - */ - // TODO: unsupported, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _getProvider(chainId) { - assert(false, 'provider cannot connect to target network', 'UNSUPPORTED_OPERATION', { - operation: '_getProvider()', - }); - } - async waitForTransaction(hash, _confirms, timeout) { - const zone = this.zoneFromHash(hash); - const confirms = _confirms != null ? _confirms : 1; - if (confirms === 0) { - return this.getTransactionReceipt(hash); - } - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - let timer = null; - const listener = async (blockNumber) => { - try { - const receipt = await this.getTransactionReceipt(hash); - if (receipt != null) { - if (blockNumber - receipt.blockNumber + 1 >= confirms) { - resolve(receipt); - //this.off("block", listener); - if (timer) { - clearTimeout(timer); - timer = null; - } - return; - } - } - } - catch (error) { - console.log('Error occured while waiting for transaction:', error); - } - this.once('block', listener, zone); - }; - if (timeout != null) { - timer = setTimeout(() => { - if (timer == null) { - return; - } - timer = null; - this.off('block', listener, zone); - reject(makeError('timeout', 'TIMEOUT', { reason: 'timeout' })); - }, timeout); - } - listener(await this.getBlockNumber(toShard(zone))); - }); - } - // TODO: not implemented yet - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async waitForBlock(shard, blockTag) { - assert(false, 'not implemented yet', 'NOT_IMPLEMENTED', { - operation: 'waitForBlock', - }); - } - /** - * Clear a timer created using the {@link AbstractProvider._setTimeout | **_setTimeout**} method. - * - * @param {number} timerId - The ID of the timer to clear. - */ - _clearTimeout(timerId) { - const timer = this.#timers.get(timerId); - if (!timer) { - return; - } - if (timer.timer) { - clearTimeout(timer.timer); - } - this.#timers.delete(timerId); - } - /** - * Create a timer that will execute `func` after at least `timeout` (in ms). If `timeout` is unspecified, then - * `func` will execute in the next event loop. - * - * {@link AbstractProvider.pause | **Pausing**} the provider will pause any associated timers. - * - * @ignore - * @ignore - * @param {() => void} _func - The function to execute. - * @param {number} [timeout] - The time to wait before executing `func`. - * @returns {number} The ID of the timer. - */ - _setTimeout(_func, timeout) { - if (timeout == null) { - timeout = 0; - } - const timerId = this.#nextTimer++; - const func = () => { - this.#timers.delete(timerId); - _func(); - }; - if (this.paused) { - this.#timers.set(timerId, { timer: null, func, time: timeout }); - } - else { - const timer = setTimeout(func, timeout); - this.#timers.set(timerId, { timer, func, time: getTime() }); - } - return timerId; - } - /** - * Perform `func` on each subscriber. - * - * @ignore - * @param {(s: Subscriber) => void} func - The function to perform. - */ - _forEachSubscriber(func) { - for (const sub of this.#subs.values()) { - func(sub.subscriber); - } - } - /** - * Sub-classes may override this to customize subscription implementations. - * - * @ignore - * @param {Subscription} sub - The subscription to get the subscriber for. - */ - _getSubscriber(sub) { - switch (sub.type) { - case 'debug': - case 'error': - case 'network': - return new UnmanagedSubscriber(sub.type); - case 'block': { - const subscriber = new PollingBlockSubscriber(this, sub.zone); - subscriber.pollingInterval = this.pollingInterval; - return subscriber; - } - //! TODO: implement this for quais - // case "safe": case "finalized": - // return new PollingBlockTagSubscriber(this, sub.type); - case 'event': - return new PollingEventSubscriber(this, sub.filter); - case 'transaction': - return new PollingTransactionSubscriber(this, sub.hash, sub.zone); - case 'orphan': - return new PollingOrphanSubscriber(this, sub.filter, sub.zone); - } - throw new Error(`unsupported event: ${sub.type}`); - } - /** - * If a {@link Subscriber | **Subscriber**} fails and needs to replace itself, this method may be used. - * - * For example, this is used for providers when using the `quai_getFilterChanges` method, which can return null if - * state filters are not supported by the backend, allowing the Subscriber to swap in a `PollingEventSubscriber`. - * - * @ignore - * @param {Subscriber} oldSub - The subscriber to replace. - * @param {Subscriber} newSub - The new subscriber. - */ - _recoverSubscriber(oldSub, newSub) { - for (const sub of this.#subs.values()) { - if (sub.subscriber === oldSub) { - if (sub.started) { - sub.subscriber.stop(); - } - sub.subscriber = newSub; - if (sub.started) { - newSub.start(); - } - if (this.#pausedState != null) { - newSub.pause(this.#pausedState); - } - break; - } - } - } - async #hasSub(event, emitArgs, zone) { - let sub = await getSubscription(event, zone); - // This is a log that is removing an existing log; we actually want - // to emit an orphan event for the removed log - if (sub.type === 'event' && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) { - sub = await getSubscription({ orphan: 'drop-log', log: emitArgs[0] }, zone); - } - return this.#subs.get(sub.tag) || null; - } - async #getSub(event, zone) { - const subscription = await getSubscription(event, zone); - // Prevent tampering with our tag in any subclass' _getSubscriber - const tag = subscription.tag; - let sub = this.#subs.get(tag); - if (!sub) { - const subscriber = this._getSubscriber(subscription); - const addressableMap = new WeakMap(); - const nameMap = new Map(); - sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [], zone: subscription.zone }; - this.#subs.set(tag, sub); - } - return sub; - } - async on(event, listener, zone) { - const sub = await this.#getSub(event, zone); - sub.listeners.push({ listener, once: false }); - if (!sub.started) { - sub.subscriber.start(); - sub.started = true; - if (this.#pausedState != null) { - sub.subscriber.pause(this.#pausedState); - } - } - return this; - } - async once(event, listener, zone) { - const sub = await this.#getSub(event, zone); - sub.listeners.push({ listener, once: true }); - if (!sub.started) { - sub.subscriber.start(); - sub.started = true; - if (this.#pausedState != null) { - sub.subscriber.pause(this.#pausedState); - } - } - return this; - } - async emit(event, zone, ...args) { - const sub = await this.#hasSub(event, args, zone); - // If there is not subscription or if a recent emit removed - // the last of them (which also deleted the sub) do nothing - if (!sub || sub.listeners.length === 0) { - return false; - } - const count = sub.listeners.length; - sub.listeners = sub.listeners.filter(({ listener, once }) => { - const payload = new EventPayload(this, once ? null : listener, event); - try { - listener.call(this, ...args, payload); - // eslint-disable-next-line no-empty - } - catch (error) { } - return !once; - }); - if (sub.listeners.length === 0) { - if (sub.started) { - sub.subscriber.stop(); - } - this.#subs.delete(sub.tag); - } - return count > 0; - } - async listenerCount(event) { - if (event) { - const sub = await this.#hasSub(event); - if (!sub) { - return 0; - } - return sub.listeners.length; - } - let total = 0; - for (const { listeners } of this.#subs.values()) { - total += listeners.length; - } - return total; - } - async listeners(event) { - if (event) { - const sub = await this.#hasSub(event); - if (!sub) { - return []; - } - return sub.listeners.map(({ listener }) => listener); - } - let result = []; - for (const { listeners } of this.#subs.values()) { - result = result.concat(listeners.map(({ listener }) => listener)); - } - return result; - } - async off(event, listener, zone) { - const sub = await this.#hasSub(event, [], zone); - if (!sub) { - return this; - } - if (listener) { - const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); - if (index >= 0) { - sub.listeners.splice(index, 1); - } - } - if (!listener || sub.listeners.length === 0) { - if (sub.started) { - sub.subscriber.stop(); - } - this.#subs.delete(sub.tag); - } - return this; - } - async removeAllListeners(event) { - if (event) { - const { tag, started, subscriber } = await this.#getSub(event); - if (started) { - subscriber.stop(); - } - this.#subs.delete(tag); - } - else { - for (const [tag, { started, subscriber }] of this.#subs) { - if (started) { - subscriber.stop(); - } - this.#subs.delete(tag); - } - } - return this; - } - // Alias for "on" - async addListener(event, listener, zone) { - return await this.on(event, listener, zone); - } - // Alias for "off" - async removeListener(event, listener, zone) { - return this.off(event, listener, zone); - } - /** - * If this provider has been destroyed using the {@link AbstractProvider.destroy | **destroy**} method. - * - * Once destroyed, all resources are reclaimed, internal event loops and timers are cleaned up and no further - * requests may be sent to the provider. - */ - get destroyed() { - return this.#destroyed; - } - /** - * Sub-classes may use this to shutdown any sockets or release their resources and reject any pending requests. - * - * Sub-classes **must** call `super.destroy()`. - */ - destroy() { - // Stop all listeners - this.removeAllListeners(); - // Shut down all tiemrs - for (const timerId of this.#timers.keys()) { - this._clearTimeout(timerId); - } - this.#destroyed = true; - } - /** - * Whether the provider is currently paused. - * - * A paused provider will not emit any events, and generally should not make any requests to the network, but that - * is up to sub-classes to manage. - * - * Setting `paused = true` is identical to calling `.pause(false)`, which will buffer any events that occur while - * paused until the provider is unpaused. - * - * @returns {boolean} Whether the provider is paused. - */ - get paused() { - return this.#pausedState != null; - } - set paused(pause) { - if (!!pause === this.paused) { - return; - } - if (this.paused) { - this.resume(); - } - else { - this.pause(false); - } - } - /** - * Pause the provider. If `dropWhilePaused`, any events that occur while paused are dropped, otherwise all events - * will be emitted once the provider is unpaused. - * - * @param {boolean} [dropWhilePaused] - Whether to drop events while paused. - */ - pause(dropWhilePaused) { - this.#lastBlockNumber = -1; - if (this.#pausedState != null) { - if (this.#pausedState == !!dropWhilePaused) { - return; - } - assert(false, 'cannot change pause type; resume first', 'UNSUPPORTED_OPERATION', { - operation: 'pause', - }); - } - this._forEachSubscriber((s) => s.pause(dropWhilePaused)); - this.#pausedState = !!dropWhilePaused; - for (const timer of this.#timers.values()) { - // Clear the timer - if (timer.timer) { - clearTimeout(timer.timer); - } - // Remaining time needed for when we become unpaused - timer.time = getTime() - timer.time; - } - } - /** - * Resume the provider. - */ - resume() { - if (this.#pausedState == null) { - return; - } - this._forEachSubscriber((s) => s.resume()); - this.#pausedState = null; - for (const timer of this.#timers.values()) { - // Remaining time when we were paused - let timeout = timer.time; - if (timeout < 0) { - timeout = 0; - } - // Start time (in cause paused, so we con compute remaininf time) - timer.time = getTime(); - // Start the timer - setTimeout(timer.func, timeout); - } - } -} - -/** - * Deep copies an object. - * - * @param {any} obj - The object to copy. - * @returns {any} A deep copy of the object. - */ -function copy(obj) { - return JSON.parse(JSON.stringify(obj)); -} -/** - * Some backends support subscribing to events using a Filter ID. - * - * When subscribing with this technique, the node issues a unique **Filter ID**. At this point the node dedicates - * resources to the filter, so that periodic calls to follow up on the **Filter ID** will receive any events since the - * last call. - * - * @category Providers - */ -class FilterIdSubscriber { - #provider; - #filterIdPromise; - #poller; - #running; - #network; - #hault; - zone; - /** - * @ignore Creates A new **FilterIdSubscriber** which will use {@link FilterIdSubscriber._subscribe | **_subscribe**} - * and {@link FilterIdSubscriber._emitResults | **_emitResults**} to setup the subscription and provide the event - * to the `provider`. - * @param {JsonRpcApiProvider} provider - The provider to use. - */ - constructor(provider, zone) { - this.#provider = provider; - this.#filterIdPromise = null; - this.#poller = this.#poll.bind(this); - this.#running = false; - this.#network = null; - this.#hault = false; - this.zone = zone; - } - /** - * Sub-classes **must** override this to begin the subscription. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @returns {Promise} A promise that resolves to the subscription ID. - * @throws {Error} If the method is not overridden. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _subscribe(provider) { - throw new Error('subclasses must override this'); - } - /** - * Sub-classes **must** override this to handle the events. - * - * @ignore - * @param {AbstractProvider} provider - The provider to use. - * @param {any[]} result - The results to handle. - * @returns {Promise} A promise that resolves when the results are handled. - * @throws {Error} If the method is not overridden. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _emitResults(provider, result) { - throw new Error('subclasses must override this'); - } - /** - * Sub-classes **must** override this to handle recovery on errors. - * - * @ignore - * @param {AbstractProvider} provider - The provider to use. - * @returns {Subscriber} The recovered subscriber. - * @throws {Error} If the method is not overridden. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _recover(provider) { - throw new Error('subclasses must override this'); - } - /** - * Polls for new events. - * - * @ignore - * @param {number} blockNumber - The block number to poll from. - * @returns {Promise} A promise that resolves when polling is complete. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async #poll(blockNumber) { - try { - // Subscribe if necessary - if (this.#filterIdPromise == null) { - this.#filterIdPromise = this._subscribe(this.#provider); - } - // Get the Filter ID - let filterId = null; - try { - filterId = await this.#filterIdPromise; - } - catch (error) { - if (!isError(error, 'UNSUPPORTED_OPERATION') || error.operation !== 'quai_newFilter') { - throw error; - } - } - // The backend does not support Filter ID; downgrade to - // polling - if (filterId == null) { - this.#filterIdPromise = null; - this.#provider._recoverSubscriber(this, this._recover(this.#provider)); - return; - } - const network = await this.#provider.getNetwork(); - if (!this.#network) { - this.#network = network; - } - if (this.#network.chainId !== network.chainId) { - throw new Error('chain changed'); - } - if (this.#hault) { - return; - } - const result = await this.#provider.send('quai_getFilterChanges', [filterId]); - await this._emitResults(this.#provider, result); - } - catch (error) { - console.log('@TODO', error); - } - this.#provider.once('block', this.#poller, this.zone); - } - /** - * Tears down the subscription. - * - * @ignore - */ - #teardown() { - const filterIdPromise = this.#filterIdPromise; - if (filterIdPromise) { - this.#filterIdPromise = null; - filterIdPromise.then((filterId) => { - this.#provider.send('quai_uninstallFilter', [filterId]); - }); - } - } - /** - * Starts the subscriber. - */ - start() { - if (this.#running) { - return; - } - this.#running = true; - this.#poll(-2); - } - /** - * Stops the subscriber. - */ - stop() { - if (!this.#running) { - return; - } - this.#running = false; - this.#hault = true; - this.#teardown(); - this.#provider.off('block', this.#poller, this.zone); - } - /** - * Pauses the subscriber. - * - * @param {boolean} [dropWhilePaused] - Whether to drop the subscription while paused. - */ - pause(dropWhilePaused) { - if (dropWhilePaused) { - this.#teardown(); - } - this.#provider.off('block', this.#poller, this.zone); - } - /** - * Resumes the subscriber. - */ - resume() { - this.start(); - } -} -/** - * A **FilterIdSubscriber** for receiving contract events. - * - * @category Providers - */ -class FilterIdEventSubscriber extends FilterIdSubscriber { - #event; - /** - * @ignore Creates A new **FilterIdEventSubscriber** attached to `provider` listening for `filter`. - * @param {JsonRpcApiProvider} provider - The provider to use. - * @param {EventFilter} filter - The event filter to use. - */ - constructor(provider, filter) { - const zone = getZoneFromEventFilter(filter); - if (zone == null) { - throw new Error('Unable to determine zone for event filter'); - } - super(provider, zone); - this.#event = copy(filter); - } - /** - * Recovers the subscriber. - * - * @ignore - * @param {AbstractProvider} provider - The provider to use. - * @returns {Subscriber} The recovered subscriber. - */ - _recover(provider) { - return new PollingEventSubscriber(provider, this.#event); - } - /** - * Subscribes to the event filter. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @returns {Promise} A promise that resolves to the subscription ID. - */ - async _subscribe(provider) { - const filterId = await provider.send('quai_newFilter', [this.#event]); - return filterId; - } - /** - * Emits the results of the event filter. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @param {any[]} results - The results to emit. - * @returns {Promise} A promise that resolves when the results are emitted. - */ - async _emitResults(provider, results) { - for (const result of results) { - provider.emit(this.#event, this.zone, provider._wrapLog(result, provider._network)); - } - } -} -/** - * A **FilterIdSubscriber** for receiving pending transactions events. - * - * @category Providers - */ -class FilterIdPendingSubscriber extends FilterIdSubscriber { - /** - * Subscribes to the pending transactions filter. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @returns {Promise} A promise that resolves to the subscription ID. - */ - async _subscribe(provider) { - return await provider.send('quai_newPendingTransactionFilter', []); - } - /** - * Emits the results of the pending transactions filter. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @param {any[]} results - The results to emit. - * @returns {Promise} A promise that resolves when the results are emitted. - */ - async _emitResults(provider, results) { - for (const result of results) { - provider.emit('pending', this.zone, result); - } - } -} - -/** - * One of the most common ways to interact with the blockchain is by a node running a JSON-RPC interface which can be - * connected to, based on the transport, using: - * - * - HTTP or HTTPS - {@link JsonRpcProvider | **JsonRpcProvider**} - * - WebSocket - {@link WebSocketProvider | **WebSocketProvider**} - * - IPC - {@link IpcSocketProvider | **IpcSocketProvider**} - */ -// @TODO: -// - Add the batching API -// 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 -const Primitive = 'bigint,boolean,function,number,string,symbol'.split(/,/g); -/** - * Deeply copies a value. - * - * @ignore - * @param {T} value - The value to copy. - * @returns {T} The copied value. - */ -function deepCopy(value) { - if (value == null || Primitive.indexOf(typeof value) >= 0) { - return value; - } - // Keep any Addressable - if (typeof value.getAddress === 'function') { - return value; - } - if (Array.isArray(value)) { - return value.map(deepCopy); - } - if (typeof value === 'object') { - return Object.keys(value).reduce((accum, key) => { - accum[key] = value[key]; - return accum; - }, {}); - } - throw new Error(`should not happen: ${value} (${typeof value})`); -} -/** - * Stalls execution for a specified duration. - * - * @ignore - * @param {number} duration - The duration to stall in milliseconds. - * @returns {Promise} A promise that resolves after the duration. - */ -function stall(duration) { - return new Promise((resolve) => { - setTimeout(resolve, duration); - }); -} -const defaultOptions = { - staticNetwork: null, - batchStallTime: 10, - batchMaxSize: 1 << 20, - batchMaxCount: 100, - cacheTimeout: 250, - usePathing: false, -}; -// @TODO: Unchecked Signers -/** - * A signer that uses JSON-RPC to sign transactions and messages. - * - * @category Providers - */ -class JsonRpcSigner extends AbstractSigner { - address; - /** - * Creates a new JsonRpcSigner instance. - * - * @param {JsonRpcApiProvider} provider - The JSON-RPC provider. - * @param {string} address - The address of the signer. - */ - constructor(provider, address) { - super(provider); - address = getAddress(address); - defineProperties(this, { address }); - } - /** - * Connects the signer to a provider. - * - * @param {null | Provider} provider - The provider to connect to. - * @returns {Signer} The connected signer. - * @throws {Error} If the signer cannot be reconnected. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - connect(provider) { - assert(false, 'cannot reconnect JsonRpcSigner', 'UNSUPPORTED_OPERATION', { - operation: 'signer.connect', - }); - } - /** - * Gets the address of the signer. - * - * @returns {Promise} The address of the signer. - */ - async getAddress() { - return this.address; - } - /** - * Populates a Quai transaction. - * - * @ignore - * @param {QuaiTransactionRequest} tx - The transaction request. - * @returns {Promise} The populated transaction. - */ - async populateQuaiTransaction(tx) { - return (await this.populateCall(tx)); - } - /** - * Sends an unchecked transaction. - * - * @ignore - * @param {TransactionRequest} _tx - The transaction request. - * @returns {Promise} The transaction hash. - */ - async sendUncheckedTransaction(_tx) { - const tx = deepCopy(_tx); - const promises = []; - if ('from' in tx) { - // Make sure the from matches the sender - if (tx.from) { - const _from = tx.from; - promises.push((async () => { - const from = await resolveAddress(_from); - assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), 'from address mismatch', 'transaction', _tx); - tx.from = from; - })()); - } - else { - tx.from = this.address; - } - // The JSON-RPC for quai_sendTransaction uses 90000 gas; if the user - // wishes to use this, it is easy to specify explicitly, otherwise - // we look it up for them. - if (tx.gasLimit == null) { - promises.push((async () => { - tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address }); - })()); - } - // The address may be an ENS name or Addressable - if (tx.to != null) { - const _to = tx.to; - promises.push((async () => { - tx.to = await resolveAddress(_to); - })()); - } - } - // Wait until all of our properties are filled in - if (promises.length) { - await Promise.all(promises); - } - const hexTx = this.provider.getRpcTransaction(tx); - return this.provider.send('quai_sendTransaction', [hexTx]); - } - /** - * Sends a transaction. - * - * @param {TransactionRequest} tx - The transaction request. - * @returns {Promise} The transaction response. - * @throws {Error} If the transaction cannot be sent. - */ - async sendTransaction(tx) { - const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx)); - // This cannot be mined any earlier than any recent block - const blockNumber = await this.provider.getBlockNumber(toShard(zone)); - // Send the transaction - const hash = await this.sendUncheckedTransaction(tx); - // Unfortunately, JSON-RPC only provides and opaque transaction hash - // for a response, and we need the actual transaction, so we poll - // for it; it should show up very quickly - return await new Promise((resolve, reject) => { - const timeouts = [1000, 100]; - let invalids = 0; - const checkTx = async () => { - try { - // Try getting the transaction - const tx = await this.provider.getTransaction(hash); - if (tx != null) { - resolve(tx.replaceableTransaction(blockNumber)); - return; - } - } - catch (error) { - // If we were cancelled: stop polling. - // If the data is bad: the node returns bad transactions - // If the network changed: calling again will also fail - // If unsupported: likely destroyed - if (isError(error, 'CANCELLED') || - isError(error, 'BAD_DATA') || - isError(error, 'NETWORK_ERROR') || - isError(error, 'UNSUPPORTED_OPERATION')) { - if (error.info == null) { - error.info = {}; - } - error.info.sendTransactionHash = hash; - reject(error); - return; - } - // Stop-gap for misbehaving backends; see #4513 - if (isError(error, 'INVALID_ARGUMENT')) { - invalids++; - if (error.info == null) { - error.info = {}; - } - error.info.sendTransactionHash = hash; - if (invalids > 10) { - reject(error); - return; - } - } - // Notify anyone that cares; but we will try again, since - // it is likely an intermittent service error - this.provider.emit('error', zoneFromHash(hash), makeError('failed to fetch transation after sending (will try again)', 'UNKNOWN_ERROR', { - error, - })); - } - // Wait another 4 seconds - this.provider._setTimeout(() => { - checkTx(); - }, timeouts.pop() || 4000); - }; - checkTx(); - }); - } - /** - * Signs a transaction. - * - * @param {TransactionRequest} _tx - The transaction request. - * @returns {Promise} The signed transaction. - * @throws {Error} If the transaction cannot be signed. - */ - async signTransaction(_tx) { - const tx = deepCopy(_tx); - // QuaiTransactionRequest - if ('from' in tx) { - if (tx.from) { - const from = await resolveAddress(tx.from); - assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), 'from address mismatch', 'transaction', _tx); - tx.from = from; - } - else { - tx.from = this.address; - } - } - else { - throw new Error('No QI signing implementation in provider-jsonrpc'); - } - const hexTx = this.provider.getRpcTransaction(tx); - return await this.provider.send('quai_signTransaction', [hexTx]); - } - /** - * Signs a message. - * - * @param {string | Uint8Array} _message - The message to sign. - * @returns {Promise} The signed message. - */ - async signMessage(_message) { - const message = typeof _message === 'string' ? toUtf8Bytes(_message) : _message; - return await this.provider.send('personal_sign', [hexlify(message), this.address.toLowerCase()]); - } - /** - * Signs typed data. - * - * @param {TypedDataDomain} domain - The domain of the typed data. - * @param {Record} types - The types of the typed data. - * @param {Record} _value - The value of the typed data. - * @returns {Promise} The signed typed data. - */ - async signTypedData(domain, types, _value) { - const value = deepCopy(_value); - return await this.provider.send('quai_signTypedData_v4', [ - this.address.toLowerCase(), - JSON.stringify(TypedDataEncoder.getPayload(domain, types, value)), - ]); - } - /** - * Unlocks the account. - * - * @param {string} password - The password to unlock the account. - * @returns {Promise} True if the account is unlocked, false otherwise. - */ - async unlock(password) { - return this.provider.send('personal_unlockAccount', [this.address.toLowerCase(), password, null]); - } - /** - * Signs a message using the legacy method. - * - * @ignore - * @param {string | Uint8Array} _message - The message to sign. - * @returns {Promise} The signed message. - */ - async _legacySignMessage(_message) { - const message = typeof _message === 'string' ? toUtf8Bytes(_message) : _message; - return await this.provider.send('quai_sign', [this.address.toLowerCase(), hexlify(message)]); - } -} -/** - * The JsonRpcApiProvider is an abstract class and **MUST** be sub-classed. - * - * It provides the base for all JSON-RPC-based Provider interaction. - * - * Sub-classing Notes: - * - * - A sub-class MUST override _send - * - A sub-class MUST call the `_start()` method once connected - * - * @category Providers - */ -class JsonRpcApiProvider extends AbstractProvider { - #options; - // The next ID to use for the JSON-RPC ID field - #nextId; - // Payloads are queued and triggered in batches using the drainTimer - #payloads; - #drainTimer; - #notReady; - #network; - #pendingDetectNetwork; - /** - * Schedules the draining of the payload queue. - * - * @ignore - */ - #scheduleDrain() { - if (this.#drainTimer) { - return; - } - // If we aren't using batching, no harm in sending it immediately - const stallTime = this._getOption('batchMaxCount') === 1 ? 0 : this._getOption('batchStallTime'); - this.#drainTimer = setTimeout(() => { - this.#drainTimer = null; - const payloads = this.#payloads; - this.#payloads = []; - while (payloads.length) { - // Create payload batches that satisfy our batch constraints - const batch = [payloads.shift()]; - while (payloads.length) { - if (batch.length === this.#options.batchMaxCount) { - break; - } - batch.push(payloads.shift()); - const bytes = JSON.stringify(batch.map((p) => p.payload)); - if (bytes.length > this.#options.batchMaxSize) { - payloads.unshift(batch.pop()); - break; - } - } - // Process the result to each payload - (async () => { - const payloadMap = new Map(); - const nowPayloadMap = new Map(); - for (let i = 0; i < batch.length; i++) { - if (batch[i].now) { - if (!nowPayloadMap.has(batch[i].shard)) { - if (batch[i].payload != null) { - nowPayloadMap.set(batch[i].shard, [batch[i].payload]); - } - } - else { - nowPayloadMap.get(batch[i].shard)?.push(batch[i].payload); - } - } - else { - if (!payloadMap.has(batch[i].shard)) { - if (batch[i].payload != null) { - payloadMap.set(batch[i].shard, [batch[i].payload]); - } - } - else { - payloadMap.get(batch[i].shard)?.push(batch[i].payload); - } - } - } - const rawResult = []; - const processPayloads = async (key, value, now) => { - const payload = value.length === 1 ? value[0] : value; - const shard = key ? toShard(key) : Shard.Prime; - const zone = shard.length < 4 ? undefined : toZone(shard); - this.emit('debug', zone, { action: 'sendRpcPayload', payload }); - rawResult.push(await this._send(payload, shard, now)); - this.emit('debug', zone, { action: 'receiveRpcResult', payload }); - }; - await Promise.all(Array.from(nowPayloadMap) - .map(async ([key, value]) => { - await processPayloads(key, value, true); - }) - .concat(Array.from(payloadMap).map(async ([key, value]) => { - await processPayloads(key, value); - }))); - const result = rawResult.flat(); - let lastZone; - try { - // Process results in batch order - for (const { resolve, reject, payload, shard } of batch) { - if (this.destroyed) { - reject(makeError('provider destroyed; cancelled request', 'UNSUPPORTED_OPERATION', { - operation: payload.method, - })); - continue; - } - if (shard) { - lastZone = shard.length < 4 ? undefined : toZone(shard); - } - else { - lastZone = undefined; - } - // Find the matching result - const resp = result.filter((r) => r.id === payload.id)[0]; - // No result; the node failed us in unexpected ways - if (resp == null) { - const error = makeError('missing response for request', 'BAD_DATA', { - value: result, - info: { payload }, - }); - this.emit('error', lastZone, error); - reject(error); - continue; - } - // The response is an error - if ('error' in resp) { - reject(this.getRpcError(payload, resp, shard)); - continue; - } - // All good; send the result - resolve(resp.result); - } - } - catch (error) { - this.emit('debug', lastZone, { action: 'receiveRpcError', error }); - for (const { reject } of batch) { - // @TODO: augment the error with the payload - reject(error); - } - } - })(); - } - }, stallTime); - } - /** - * Creates a new JsonRpcApiProvider instance. - * - * @param {Networkish} [network] - The network to connect to. - * @param {JsonRpcApiProviderOptions} [options] - The options for the provider. - */ - constructor(network, options) { - super(network, options); - this.#nextId = 1; - this.#options = Object.assign({}, defaultOptions, options || {}); - this.#payloads = []; - this.#drainTimer = null; - this.#network = null; - this.#pendingDetectNetwork = null; - { - let resolve = null; - const promise = new Promise((_resolve) => { - resolve = _resolve; - }); - this.#notReady = { promise, resolve }; - } - const staticNetwork = this._getOption('staticNetwork'); - if (typeof staticNetwork === 'boolean') { - assertArgument(!staticNetwork || network !== 'any', "staticNetwork cannot be used on special network 'any'", 'options', options); - if (staticNetwork && network != null) { - this.#network = Network.from(network); - } - } - else if (staticNetwork) { - // Make sure any static network is compatbile with the provided netwrok - assertArgument(network == null || staticNetwork.matches(network), 'staticNetwork MUST match network object', 'options', options); - this.#network = staticNetwork; - } - } - /** - * Returns the value associated with the option `key`. - * - * Sub-classes can use this to inquire about configuration options. - * - * @ignore - * @param {keyof JsonRpcApiProviderOptions} key - The option key. - * @returns {JsonRpcApiProviderOptions[key]} The option value. - */ - _getOption(key) { - return this.#options[key]; - } - /** - * Gets the {@link Network | **Network**} this provider has committed to. On each call, the network is detected, and - * if it has changed, the call will reject. - * - * @ignore - * @returns {Network} The network. - * @throws {Error} If the network is not available yet. - */ - get _network() { - assert(this.#network, 'network is not available yet', 'NETWORK_ERROR'); - return this.#network; - } - /** - * Resolves to the non-normalized value by performing `req`. - * - * Sub-classes may override this to modify behavior of actions, and should generally call `super._perform` as a - * fallback. - * - * @ignore - * @param {PerformActionRequest} req - The request to perform. - * @returns {Promise} The result of the request. - * @throws {Error} If the request fails. - */ - async _perform(req) { - // Legacy networks do not like the type field being passed along (which - // is fair), so we delete type if it is 0 and a non-EIP-1559 network - if (req.method !== 'getRunningLocations') { - await this.initPromise; - } - if (req.method === 'call' || req.method === 'estimateGas') { - const tx = req.transaction; - if (tx && tx.type != null && getBigInt(tx.type)) { - // If there are no EIP-1559 properties, it might be non-EIP-a559 - if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { - const feeData = await this.getFeeData(req.zone); - if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { - // Network doesn't know about EIP-1559 (and hence type) - req = Object.assign({}, req, { - transaction: Object.assign({}, tx, { type: undefined }), - }); - } - } - } - } - const request = this.getRpcRequest(req); - if (request != null) { - const shard = 'shard' in req ? req.shard : 'zone' in req ? toShard(req.zone) : undefined; - if (req.method === 'getRunningLocations') { - return await this.send(request.method, request.args, shard, req.now); - } - else { - return await this.send(request.method, request.args, shard); - } - } - return super._perform(req); - } - /** - * Sub-classes may override this; it detects the _actual_ network that we are **currently** connected to. - * - * Keep in mind that {@link JsonRpcApiProvider.send | **send**} may only be used once - * {@link JsonRpcApiProvider.ready | **ready**}, otherwise the _send primitive must be used instead. - * - * @ignore - * @returns {Promise} The detected network. - * @throws {Error} If network detection fails. - */ - async _detectNetwork() { - const network = this._getOption('staticNetwork'); - if (network) { - if (network === true) { - if (this.#network) { - return this.#network; - } - } - else { - return network; - } - } - if (this.#pendingDetectNetwork) { - return await this.#pendingDetectNetwork; - } - // If we are ready, use `send`, which enabled requests to be batched - if (this.ready) { - this.#pendingDetectNetwork = (async () => { - try { - const result = Network.from(getBigInt(await this.send('quai_chainId', []))); - this.#pendingDetectNetwork = null; - return result; - } - catch (error) { - this.#pendingDetectNetwork = null; - throw error; - } - })(); - return await this.#pendingDetectNetwork; - } - // We are not ready yet; use the primitive _send - this.#pendingDetectNetwork = (async () => { - const payload = { - id: this.#nextId++, - method: 'quai_chainId', - params: [], - jsonrpc: '2.0', - }; - this.emit('debug', undefined, { action: 'sendRpcPayload', payload }); - let result; - try { - result = (await this._send(payload))[0]; - this.#pendingDetectNetwork = null; - } - catch (error) { - this.#pendingDetectNetwork = null; - this.emit('debug', undefined, { action: 'receiveRpcError', error }); - throw error; - } - this.emit('debug', undefined, { action: 'receiveRpcResult', result }); - if ('result' in result) { - return Network.from(getBigInt(result.result)); - } - throw this.getRpcError(payload, result); - })(); - return await this.#pendingDetectNetwork; - } - /** - * Sub-classes **MUST** call this. Until {@link JsonRpcApiProvider._start | **_start**} has been called, no calls - * will be passed to {@link JsonRpcApiProvider._send | **_send**} from {@link JsonRpcApiProvider.send | **send**} . If - * it is overridden, then `super._start()` **MUST** be called. - * - * Calling it multiple times is safe and has no effect. - * - * @ignore - */ - _start() { - if (this.#notReady == null || this.#notReady.resolve == null) { - return; - } - this.#notReady.resolve(); - this.#notReady = null; - (async () => { - let retries = 0; - const maxRetries = 5; - while (this.#network == null && !this.destroyed && retries < maxRetries) { - try { - this.#network = await this._detectNetwork(); - } - catch (error) { - if (this.destroyed) { - break; - } - 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)'); - this.emit('error', undefined, makeError('failed to bootstrap network detection', 'NETWORK_ERROR', { - event: 'initial-network-discovery', - info: { error }, - })); - await stall(1000); - retries++; - } - } - if (retries >= maxRetries) { - throw new Error('Failed to detect network after maximum retries'); - } - // Start dispatching requests - this.#scheduleDrain(); - })(); - } - /** - * Resolves once the {@link JsonRpcApiProvider._start | **_start**} has been called. This can be used in sub-classes - * to defer sending data until the connection has been established. - * - * @ignore - * @returns {Promise} A promise that resolves once the provider is ready. - */ - async _waitUntilReady() { - if (this._initFailed) { - throw new Error('Provider failed to initialize on creation. Run initialize or create a new provider.'); - } - await this.initPromise; - } - /** - * Return a Subscriber that will manage the `sub`. - * - * Sub-classes may override this to modify the behavior of subscription management. - * - * @ignore - * @param {Subscription} sub - The subscription to manage. - * @returns {Subscriber} The subscriber that will manage the subscription. - */ - _getSubscriber(sub) { - // Pending Filters aren't availble via polling - if (sub.type === 'pending') { - return new FilterIdPendingSubscriber(this, sub.zone); - } - if (sub.type === 'event') { - return new FilterIdEventSubscriber(this, sub.filter); - } - // Orphaned Logs are handled automatically, by the filter, since - // logs with removed are emitted by it - if (sub.type === 'orphan' && sub.filter.orphan === 'drop-log') { - return new UnmanagedSubscriber('orphan'); - } - return super._getSubscriber(sub); - } - /** - * Returns true only if the {@link JsonRpcApiProvider._start | **_start**} has been called. - * - * @returns {boolean} True if the provider is ready. - */ - get ready() { - return this.#notReady == null; - } - /** - * Returns `tx` as a normalized JSON-RPC transaction request, which has all values hexlified and any numeric values - * converted to Quantity values. - * - * @ignore - * @param {TransactionRequest} tx - The transaction to normalize. - * @returns {JsonRpcTransactionRequest} The normalized transaction. - * @throws {Error} If the transaction is invalid. - */ - getRpcTransaction(tx) { - const result = {}; - if ('from' in tx || ('to' in tx && 'data' in tx)) { - // JSON-RPC now requires numeric values to be "quantity" values - [ - 'chainId', - 'gasLimit', - 'gasPrice', - 'type', - 'maxFeePerGas', - 'maxPriorityFeePerGas', - 'nonce', - 'value', - ].forEach((key) => { - if (tx[key] == null) { - return; - } - let dstKey = key; - if (key === 'gasLimit') { - dstKey = 'gas'; - } - result[dstKey] = toQuantity(getBigInt(tx[key], `tx.${key}`)); - }); - // Make sure addresses and data are lowercase - ['from', 'to', 'data'].forEach((key) => { - if (tx[key] == null) { - return; - } - result[key] = hexlify(tx[key]); - }); - // Normalize the access list object - if ('accessList' in tx && tx.accessList) { - result['accessList'] = accessListify(tx.accessList); - } - } - else { - throw new Error('No Qi getRPCTransaction implementation yet'); - } - return result; - } - /** - * Returns the request method and arguments required to perform `req`. - * - * @ignore - * @param {PerformActionRequest} req - The request to perform. - * @returns {null | { method: string; args: any[] }} The method and arguments to use. - * @throws {Error} If the request is not supported or invalid. - */ - getRpcRequest(req) { - switch (req.method) { - case 'chainId': - return { method: 'quai_chainId', args: [] }; - case 'getBlockNumber': - return { method: 'quai_blockNumber', args: [] }; - case 'getGasPrice': - return { - method: 'quai_baseFee', - args: [req.txType], - }; - case 'getMaxPriorityFeePerGas': - return { method: 'quai_maxPriorityFeePerGas', args: [] }; - case 'getPendingHeader': - return { method: 'quai_getPendingHeader', args: [] }; - case 'getBalance': - return { - method: 'quai_getBalance', - args: [req.address, req.blockTag], - }; - case 'getOutpointsByAddress': - return { - method: 'quai_getOutpointsByAddress', - args: [req.address], - }; - case 'getTransactionCount': - return { - method: 'quai_getTransactionCount', - args: [req.address, req.blockTag], - }; - case 'getCode': - return { - method: 'quai_getCode', - args: [req.address, req.blockTag], - }; - case 'getStorage': - return { - method: 'quai_getStorageAt', - args: [req.address, '0x' + req.position.toString(16), req.blockTag], - }; - case 'broadcastTransaction': - return { - method: 'quai_sendRawTransaction', - args: [req.signedTransaction], - }; - case 'getBlock': - if ('blockTag' in req) { - return { - method: 'quai_getBlockByNumber', - args: [req.blockTag, !!req.includeTransactions], - }; - } - else if ('blockHash' in req) { - return { - method: 'quai_getBlockByHash', - args: [req.blockHash, !!req.includeTransactions], - }; - } - break; - case 'getTransaction': - return { - method: 'quai_getTransactionByHash', - args: [req.hash], - }; - case 'getTransactionReceipt': - return { - method: 'quai_getTransactionReceipt', - args: [req.hash], - }; - case 'call': - return { - method: 'quai_call', - args: [this.getRpcTransaction(req.transaction), req.blockTag], - }; - case 'estimateGas': { - return { - method: 'quai_estimateGas', - args: [this.getRpcTransaction(req.transaction)], - }; - } - case 'getRunningLocations': { - return { - method: 'quai_listRunningChains', - args: [], - }; - } - case 'getProtocolTrieExpansionCount': { - return { - method: 'quai_getProtocolExpansionNumber', - args: [], - }; - } - case 'getProtocolExpansionNumber': { - return { - method: 'quai_getProtocolExpansionNumber', - args: [], - }; - } - case 'getQiRateAtBlock': { - return { - method: 'quai_qiRateAtBlock', - args: [req.blockTag, req.amt], - }; - } - case 'getQuaiRateAtBlock': { - return { - method: 'quai_quaiRateAtBlock', - args: [req.blockTag, req.amt], - }; - } - case 'getLogs': - return { method: 'quai_getLogs', args: [req.filter] }; - case 'getTxPoolContent': - return { method: 'txpool_content', args: [] }; - case 'txPoolInspect': - return { method: 'txpool_inspect', args: [] }; - } - return null; - } - /** - * Returns an quais-style Error for the given JSON-RPC error `payload`, coalescing the various strings and error - * shapes that different nodes return, coercing them into a machine-readable standardized error. - * - * @ignore - * @param {JsonRpcPayload} payload - The payload that was sent. - * @param {JsonRpcError} _error - The error that was received. - * @returns {Error} The coalesced error. - */ - getRpcError(payload, _error, shard) { - const { method } = payload; - const { error } = _error; - if (method === 'quai_estimateGas' && error.message) { - const msg = error.message; - if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) { - return makeError('insufficient funds', 'INSUFFICIENT_FUNDS', { - transaction: payload.params[0], - info: { payload, error, shard }, - }); - } - } - if (method === 'quai_call' || method === 'quai_estimateGas') { - const result = spelunkData(error); - const e = AbiCoder.getBuiltinCallException(method === 'quai_call' ? 'call' : 'estimateGas', payload.params[0], result ? result.data : null); - e.info = { error, payload, shard }; - return e; - } - // Only estimateGas and call can return arbitrary contract-defined text, so now we - // we can process text safely. - const message = JSON.stringify(spelunkMessage(error)); - if (method === 'quai_getTransactionByHash' && error.message && error.message.match(/transaction not found/i)) { - return makeError('transaction not found', 'TRANSACTION_NOT_FOUND', { info: { payload, error, shard } }); - } - if (typeof error.message === 'string' && error.message.match(/user denied|quais-user-denied/i)) { - const actionMap = { - quai_sign: 'signMessage', - personal_sign: 'signMessage', - quai_signTypedData_v4: 'signTypedData', - quai_signTransaction: 'signTransaction', - quai_sendTransaction: 'sendTransaction', - quai_requestAccounts: 'requestAccess', - wallet_requestAccounts: 'requestAccess', - }; - return makeError(`user rejected action`, 'ACTION_REJECTED', { - action: actionMap[method] || 'unknown', - reason: 'rejected', - info: { payload, error, shard }, - }); - } - if (method === 'quai_sendRawTransaction' || method === 'quai_sendTransaction') { - const transaction = payload.params[0]; - if (message.match(/insufficient funds|base fee exceeds gas limit/i)) { - return makeError('insufficient funds for intrinsic transaction cost', 'INSUFFICIENT_FUNDS', { - transaction, - info: { error, shard }, - }); - } - if (message.match(/nonce/i) && message.match(/too low/i)) { - return makeError('nonce has already been used', 'NONCE_EXPIRED', { - transaction, - info: { error, shard }, - }); - } - // "replacement transaction underpriced" - if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) { - return makeError('replacement fee too low', 'REPLACEMENT_UNDERPRICED', { - transaction, - info: { error, shard }, - }); - } - if (message.match(/only replay-protected/i)) { - return makeError('legacy pre-eip-155 transactions not supported', 'UNSUPPORTED_OPERATION', { - operation: method, - info: { transaction, info: { error, shard } }, - }); - } - if (message.match(/already known/i)) { - return makeError('transaction already known', 'TRANSACTION_ALREADY_KNOWN', { info: { error, shard } }); - } - } - let unsupported = !!message.match(/the method .* does not exist/i); - if (!unsupported) { - if (error && error.details && error.details.startsWith('Unauthorized method:')) { - unsupported = true; - } - } - if (unsupported) { - return makeError('unsupported operation', 'UNSUPPORTED_OPERATION', { - operation: payload.method, - info: { error, payload, shard }, - }); - } - if (message.match('Provider failed to initialize on creation. Run initialize or create a new provider.')) { - return makeError('Provider failed to initialize on creation. Run initUrlMap or create a new provider.', 'PROVIDER_FAILED_TO_INITIALIZE', { - info: { payload, error, shard }, - }); - } - return makeError('could not coalesce error', 'UNKNOWN_ERROR', { error, payload, shard }); - } - /** - * Requests the `method` with `params` via the JSON-RPC protocol over the underlying channel. This can be used to - * call methods on the backend that do not have a high-level API within the Provider API. - * - * This method queues requests according to the batch constraints in the options, assigns the request a unique ID. - * - * **Do NOT override** this method in sub-classes; instead override {@link JsonRpcApiProvider._send | **_send**} or - * force the options values in the call to the constructor to modify this method's behavior. - * - * @param {string} method - The method to call. - * @param {any[] | Record} params - The parameters to pass to the method. - * @param {Shard} shard - The shard to send the request to. - * @param {boolean} now - If true, the request will be sent immediately. - * @returns {Promise} A promise that resolves to the result of the method call. - */ - send(method, params, shard, now) { - const continueSend = () => { - if (this.destroyed) { - return Promise.reject(makeError('provider destroyed; cancelled request', 'UNSUPPORTED_OPERATION', { operation: method })); - } - const id = this.#nextId++; - const promise = new Promise((resolve, reject) => { - this.#payloads.push({ - resolve, - reject, - payload: { method, params, id, jsonrpc: '2.0' }, - shard: shard, - now: now, - }); - }); - // If there is not a pending drainTimer, set one - this.#scheduleDrain(); - return promise; - }; - // @TODO: cache chainId?? purge on switch_networks - // We have been destroyed; no operations are supported anymore - if (method !== 'quai_listRunningChains') { - return this.initPromise.then(() => { - return continueSend(); - }); - } - else { - return continueSend(); - } - } - /** - * Returns a JsonRpcSigner for the given address. - * - * @param {number | string} [address] - The address or index of the account. - * @returns {Promise} A promise that resolves to the JsonRpcSigner. - * @throws {Error} If the account is invalid. - */ - async getSigner(address) { - if (address == null) { - address = 0; - } - const accountsPromise = this.send('quai_accounts', []); - // Account index - if (typeof address === 'number') { - const accounts = await accountsPromise; - if (address >= accounts.length) { - throw new Error('no such account'); - } - return new JsonRpcSigner(this, accounts[address]); - } - const { accounts } = await resolveProperties({ - network: this.getNetwork(), - accounts: accountsPromise, - }); - // Account address - address = getAddress(address); - for (const account of accounts) { - if (getAddress(account) === address) { - return new JsonRpcSigner(this, address); - } - } - throw new Error('invalid account'); - } - /** - * Returns a list of JsonRpcSigners for all accounts. - * - * @returns {Promise} A promise that resolves to an array of JsonRpcSigners. - */ - async listAccounts() { - const accounts = await this.send('quai_accounts', []); - return accounts.map((a) => new JsonRpcSigner(this, a)); - } - /** - * Destroys the provider, stopping all processing and canceling all pending requests. - */ - destroy() { - // Stop processing requests - if (this.#drainTimer) { - clearTimeout(this.#drainTimer); - this.#drainTimer = null; - } - // Cancel all pending requests - for (const { payload, reject } of this.#payloads) { - reject(makeError('provider destroyed; cancelled request', 'UNSUPPORTED_OPERATION', { - operation: payload.method, - })); - } - this.#payloads = []; - // Parent clean-up - super.destroy(); - } -} -/** - * The JsonRpcProvider is one of the most common Providers, which performs all operations over HTTP (or HTTPS) requests. - * - * Events are processed by polling the backend for the current block number; when it advances, all block-base events are - * then checked for updates. - * - * @category Providers - */ -class JsonRpcProvider extends JsonRpcApiProvider { - constructor(urls, network, options) { - if (urls == null) { - urls = ['http://localhost:8545']; - } - super(network, options); - if (Array.isArray(urls)) { - urls.forEach((url) => { - this.validateUrl(url); - }); - this.initialize(urls); - } - else if (typeof urls === 'string') { - this.validateUrl(urls); - this.initialize([urls]); - } - else { - this.validateUrl(urls.url); - this.initialize(urls.clone()); - } - } - _getSubscriber(sub) { - const subscriber = super._getSubscriber(sub); - return subscriber; - } - _getConnection(shard) { - if (this._initFailed) { - throw new Error('Provider failed to initialize on creation. Run initUrlMap or create a new provider.'); - } - let connection; - if (shard !== undefined) { - connection = this._urlMap.get(shard) ?? this.connect[this.connect.length - 1].clone(); - } - else { - connection = this.connect[this.connect.length - 1].clone(); - } - return new FetchRequest(connection.url); - } - async send(method, params, shard, now) { - // All requests are over HTTP, so we can just start handling requests - // We do this here rather than the constructor so that we don't send any - // requests to the network (i.e. quai_chainId) until we absolutely have to. - await this._start(); - return await super.send(method, params, shard, now); - } - async _send(payload, shard) { - // Configure a POST connection for the requested method - const request = this._getConnection(shard); - request.body = JSON.stringify(payload); - request.setHeader('content-type', 'application/json'); - const response = await request.send(); - response.assertOk(); - let resp = response.bodyJson; - if (!Array.isArray(resp)) { - resp = [resp]; - } - return resp; - } -} -function spelunkData(value) { - if (value == null) { - return null; - } - // These *are* the droids we're looking for. - if (typeof value.message === 'string' && value.message.match(/revert/i) && isHexString(value.data)) { - return { message: value.message, data: value.data }; - } - // Spelunk further... - if (typeof value === 'object') { - for (const key in value) { - const result = spelunkData(value[key]); - if (result) { - return result; - } - } - return null; - } - // Might be a JSON string we can further descend... - if (typeof value === 'string') { - try { - return spelunkData(JSON.parse(value)); - // eslint-disable-next-line no-empty - } - catch (error) { } - } - return null; -} -function _spelunkMessage(value, result) { - if (value == null) { - return; - } - // These *are* the droids we're looking for. - if (typeof value.message === 'string') { - result.push(value.message); - } - // Spelunk further... - if (typeof value === 'object') { - for (const key in value) { - _spelunkMessage(value[key], result); - } - } - // Might be a JSON string we can further descend... - if (typeof value === 'string') { - try { - return _spelunkMessage(JSON.parse(value), result); - // eslint-disable-next-line no-empty - } - catch (error) { } - } -} -function spelunkMessage(value) { - const result = []; - _spelunkMessage(value, result); - return result; -} - -// A = Arguments to the constructor -// I = Interface of deployed contracts -/** - * A **ContractFactory** is used to deploy a Contract to the blockchain. - * - * @category Contract - */ -class ContractFactory { - /** - * The Contract Interface. - */ - interface; - /** - * The Contract deployment bytecode. Often called the initcode. - */ - bytecode; - /** - * The ContractRunner to deploy the Contract as. - */ - runner; - /** - * Create a new **ContractFactory** with `abi` and `bytecode`, optionally connected to `runner`. - * - * The `bytecode` may be the `bytecode` property within the standard Solidity JSON output. - */ - constructor(abi, bytecode, runner) { - const iface = Interface.from(abi); - // Dereference Solidity bytecode objects and allow a missing `0x`-prefix - if (bytecode instanceof Uint8Array) { - bytecode = hexlify(getBytes(bytecode)); - } - else { - if (typeof bytecode === 'object') { - bytecode = bytecode.object; - } - if (!bytecode.startsWith('0x')) { - bytecode = '0x' + bytecode; - } - bytecode = hexlify(getBytes(bytecode)); - } - defineProperties(this, { - bytecode, - interface: iface, - runner: runner || null, - }); - } - attach(target) { - return new BaseContract(target, this.interface, this.runner); - } - /** - * Resolves to the transaction to deploy the contract, passing `args` into the constructor. - * - * @param {ContractMethods} args - The arguments to the constructor. - * @returns {Promise} A promise resolving to the deployment transaction. - */ - async getDeployTransaction(...args) { - let overrides; - const fragment = this.interface.deploy; - if (fragment.inputs.length + 1 === args.length) { - overrides = await copyOverrides(args.pop()); - const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); - const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); - return Object.assign({}, overrides, { data }); - } - if (fragment.inputs.length !== args.length) { - throw new Error('incorrect number of arguments to constructor'); - } - const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); - const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); - const from = args.pop()?.from || undefined; - return Object.assign({}, from, { data }); - } - /** - * Resolves to the Contract deployed by passing `args` into the constructor. - * - * This will resovle to the Contract before it has been deployed to the network, so the - * [baseContract.waitForDeployment](../classes/BaseContract#waitForDeployment) should be used before sending any - * transactions to it. - * - * @param {ContractMethods} args - The arguments to the constructor. - * @returns {Promise< - * BaseContract & { deploymentTransaction(): ContractTransactionResponse } & Omit - * >} - * A promise resolving to the Contract. - */ - async deploy(...args) { - const tx = await this.getDeployTransaction(...args); - assert(this.runner && typeof this.runner.sendTransaction === 'function', 'factory runner does not support sending transactions', 'UNSUPPORTED_OPERATION', { - operation: 'sendTransaction', - }); - if (this.runner instanceof Wallet || this.runner instanceof JsonRpcSigner) { - validateAddress(this.runner.address); - tx.from = this.runner.address; - } - const grindedTx = await this.grindContractAddress(tx); - const sentTx = await this.runner.sendTransaction(grindedTx); - const address = getStatic(this.constructor, 'getContractAddress')?.(tx); - return new BaseContract(address, this.interface, this.runner, sentTx); - } - static getContractAddress(transaction) { - return getContractAddress(transaction.from, BigInt(transaction.nonce), // Fix: Convert BigInt to bigint - transaction.data); - } - async grindContractAddress(tx) { - if (tx.nonce == null && tx.from) { - tx.nonce = await this.runner?.provider?.getTransactionCount(tx.from); - } - const sender = String(tx.from); - const toShard = getZoneForAddress(sender); - let i = 0; - const startingData = tx.data; - while (i < 10000) { - const contractAddress = getContractAddress(sender, BigInt(tx.nonce || 0), tx.data || ''); - const contractShard = getZoneForAddress(contractAddress); - const utxo = isQiAddress(contractAddress); - if (contractShard === toShard && !utxo) { - return tx; - } - const salt = randomBytes(32); - tx.data = hexlify(concat([String(startingData), salt])); - i++; - } - return tx; - } - /** - * Return a new **ContractFactory** with the same ABI and bytecode, but connected to `runner`. - * - * @param {ContractRunner} runner - The runner to connect to. - * @returns {ContractFactory} A new ContractFactory. - */ - connect(runner) { - return new ContractFactory(this.interface, this.bytecode, runner); - } - /** - * Create a new **ContractFactory** from the standard Solidity JSON output. - * - * @param {any} output - The Solidity JSON output. - * @param {ContractRunner} runner - The runner to connect to. - * @returns {ContractFactory} A new ContractFactory. - */ - static fromSolidity(output, runner) { - assertArgument(output != null, 'bad compiler output', 'output', output); - if (typeof output === 'string') { - output = JSON.parse(output); - } - const abi = output.abi; - let bytecode = ''; - if (output.bytecode) { - bytecode = output.bytecode; - } - else if (output.evm && output.evm.bytecode) { - bytecode = output.evm.bytecode; - } - return new this(abi, bytecode, runner); - } -} - -/** - * A **BrowserProvider** is intended to wrap an injected provider which adheres to the - * [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) standard, which most (if not all) currently do. - * - * @category Providers - * @class - * @extends JsonRpcApiProvider - */ -class BrowserProvider extends JsonRpcApiProvider { - #request; - /** - * Connect to the `ethereum` provider, optionally forcing the `network`. - * - * @class - * @param {Eip1193Provider} ethereum - The EIP-1193 provider. - * @param {Networkish} [network] - The network to connect to. - */ - constructor(ethereum, network) { - super(network, { batchMaxCount: 1 }); - this.#request = async (method, params) => { - const payload = { method, params }; - this.emit('debug', undefined, { action: 'sendEip1193Request', payload }); - try { - const result = await ethereum.request(payload); - this.emit('debug', undefined, { action: 'receiveEip1193Result', result }); - return result; - } - catch (e) { - const error = new Error(e.message); - error.code = e.code; - error.data = e.data; - error.payload = payload; - this.emit('debug', undefined, { action: 'receiveEip1193Error', error }); - throw error; - } - }; - } - /** - * Resolves to `true` if the provider manages the `address`. - * - * @param {number | string} address - The address to check. - * @returns {Promise} Resolves to `true` if the provider manages the `address`. - */ - async hasSigner(address) { - if (address == null) { - address = 0; - } - const accounts = await this.send('quai_accounts', []); - if (typeof address === 'number') { - return accounts.length > address; - } - address = address.toLowerCase(); - return accounts.filter((a) => a.toLowerCase() === address).length !== 0; - } - /** - * Sends a JSON-RPC request. - * - * @param {string} method - The method name. - * @param {any[] | Record} params - The parameters for the method. - * @returns {Promise} The result of the request. - */ - async send(method, params) { - await this._start(); - return await super.send(method, params); - } - /** - * Sends a JSON-RPC payload. - * - * @ignore - * @ignore - * @param {JsonRpcPayload | JsonRpcPayload[]} payload - The JSON-RPC payload. - * @returns {Promise<(JsonRpcResult | JsonRpcError)[]>} The result of the request. - */ - async _send(payload) { - assertArgument(!Array.isArray(payload), 'EIP-1193 does not support batch request', 'payload', payload); - try { - const result = await this.#request(payload.method, payload.params || []); - return [{ id: payload.id, result }]; - } - catch (e) { - return [ - { - id: payload.id, - error: { code: e.code, data: e.data, message: e.message }, - }, - ]; - } - } - /** - * Gets the RPC error. - * - * @param {JsonRpcPayload} payload - The JSON-RPC payload. - * @param {JsonRpcError} error - The JSON-RPC error. - * @returns {Error} The RPC error. - */ - getRpcError(payload, error) { - error = JSON.parse(JSON.stringify(error)); - // EIP-1193 gives us some machine-readable error codes, so rewrite - // them into - switch (error.error.code || -1) { - case 4001: - error.error.message = `quais-user-denied: ${error.error.message}`; - break; - case 4200: - error.error.message = `quais-unsupported: ${error.error.message}`; - break; - } - return super.getRpcError(payload, error); - } - /** - * Gets the signer for the given address. - * - * @param {number | string} [address] - The address to get the signer for. - * @returns {Promise} The signer for the address. - */ - async getSigner(address) { - if (address == null) { - address = 0; - } - if (!(await this.hasSigner(address))) { - try { - await this.#request('quai_requestAccounts', []); - } - catch (error) { - const payload = error.payload; - throw this.getRpcError(payload, { id: payload.id, error }); - } - } - return await super.getSigner(address); - } -} - -/** - * A **SocketSubscriber** uses a socket transport to handle events and should use - * {@link SocketSubscriber._emit | **_emit**} to manage the events. - * - * - A sub-class MUST call the `_start()` method once connected - * - A sub-class MUST override the `_write(string)` method - * - A sub-class MUST call `_processMessage(string)` for each message - * - * @category Providers - */ -class SocketSubscriber { - #provider; - #filter; - /** - * The filter. - * - * @type {any[]} - */ - get filter() { - return JSON.parse(this.#filter); - } - #filterId; - #paused; - #emitPromise; - zone; - shard; - /** - * Creates a new **SocketSubscriber** attached to `provider` listening to `filter`. - * - * @param {SocketProvider} provider - The socket provider. - * @param {any[]} filter - The filter. - */ - constructor(provider, filter, zone) { - this.#provider = provider; - this.#filter = JSON.stringify(filter); - this.#filterId = null; - this.#paused = null; - this.#emitPromise = null; - this.zone = zone; - this.shard = toShard(zone); - } - /** - * Start the subscriber. - */ - start() { - this.#filterId = this.#provider.send('quai_subscribe', this.filter, this.shard).then((filterId) => { - this.#provider._register(filterId, this); - return filterId; - }); - } - /** - * Stop the subscriber. - */ - stop() { - this.#filterId.then((filterId) => { - this.#provider.send('quai_unsubscribe', [filterId], this.shard); - }); - this.#filterId = null; - } - /** - * Pause the subscriber. - * - * @param {boolean} [dropWhilePaused] - Whether to drop logs while paused. - */ - pause(dropWhilePaused) { - assert(dropWhilePaused, 'preserve logs while paused not supported by SocketSubscriber yet', 'UNSUPPORTED_OPERATION', { operation: 'pause(false)' }); - this.#paused = !!dropWhilePaused; - } - /** - * Resume the subscriber. - */ - resume() { - this.#paused = null; - } - /** - * Handle incoming messages. - * - * @ignore - * @param {any} message - The message to handle. - */ - _handleMessage(message) { - if (this.#filterId == null) { - return; - } - if (this.#paused === null) { - let emitPromise = this.#emitPromise; - if (emitPromise == null) { - emitPromise = this._emit(this.#provider, message); - } - else { - emitPromise = emitPromise.then(async () => { - await this._emit(this.#provider, message); - }); - } - this.#emitPromise = emitPromise.then(() => { - if (this.#emitPromise === emitPromise) { - this.#emitPromise = null; - } - }); - } - } - /** - * Sub-classes **must** override this to emit the events on the provider. - * - * @abstract - * @param {SocketProvider} provider - The socket provider. - * @param {any} message - The message to emit. - * @returns {Promise} - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _emit(provider, message) { - throw new Error('sub-classes must implement this; _emit'); - } -} -/** - * A **SocketBlockSubscriber** listens for `newHeads` events and emits `"block"` events. - * - * @category Providers - */ -class SocketBlockSubscriber extends SocketSubscriber { - /** - * Creates a new **SocketBlockSubscriber**. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - */ - constructor(provider, zone) { - super(provider, ['newHeads'], zone); - } - /** - * Emit the block event. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - * @param {any} message - The message to emit. - * @returns {Promise} - */ - async _emit(provider, message) { - provider.emit('block', this.zone, parseInt(message.woHeader.number)); - } -} -/** - * A **SocketPendingSubscriber** listens for pending transactions and emits `"pending"` events. - * - * @category Providers - */ -class SocketPendingSubscriber extends SocketSubscriber { - /** - * Creates a new **SocketPendingSubscriber**. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - */ - constructor(provider, zone) { - super(provider, ['newPendingTransactions'], zone); - } - /** - * Emit the pending event. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - * @param {any} message - The message to emit. - * @returns {Promise} - */ - async _emit(provider, message) { - provider.emit('pending', message); - } -} -/** - * A **SocketEventSubscriber** listens for event logs. - * - * @category Providers - */ -class SocketEventSubscriber extends SocketSubscriber { - #logFilter; - /** - * The filter. - * - * @type {EventFilter} - */ - get logFilter() { - return JSON.parse(this.#logFilter); - } - /** - * Creates a new **SocketEventSubscriber**. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - * @param {EventFilter} filter - The event filter. - */ - constructor(provider, filter, zone) { - super(provider, ['logs', filter], zone); - this.#logFilter = JSON.stringify(filter); - } - /** - * Emit the event log. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - * @param {any} message - The message to emit. - * @returns {Promise} - */ - async _emit(provider, message) { - provider.emit(this.logFilter, this.zone, provider._wrapLog(message, provider._network)); - } -} -/** - * A **SocketProvider** is backed by a long-lived connection over a socket, which can subscribe and receive real-time - * messages over its communication channel. - * - * @category Providers - */ -class SocketProvider extends JsonRpcApiProvider { - #callbacks; - // Maps each filterId to its subscriber - #subs; - // If any events come in before a subscriber has finished - // registering, queue them - #pending; - /** - * Creates a new **SocketProvider** connected to `network`. - * - * If unspecified, the network will be discovered. - * - * @param {Networkish} [network] - The network to connect to. - * @param {JsonRpcApiProviderOptions} [_options] - The options for the provider. - */ - constructor(network, _options) { - // Copy the options - const options = Object.assign({}, _options != null ? _options : {}); - // Support for batches is generally not supported for - // connection-base providers; if this changes in the future - // the _send should be updated to reflect this - assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1, 'sockets-based providers do not support batches', 'options.batchMaxCount', _options); - options.batchMaxCount = 1; - // Socket-based Providers (generally) cannot change their network, - // since they have a long-lived connection; but let people override - // this if they have just cause. - if (options.staticNetwork == null) { - options.staticNetwork = true; - } - super(network, options); - this.#callbacks = new Map(); - this.#subs = new Map(); - this.#pending = new Map(); - } - /** - * Get the subscriber for a given subscription. - * - * @ignore - * @param {Subscription} sub - The subscription. - * @returns {Subscriber} The subscriber. - */ - _getSubscriber(sub) { - switch (sub.type) { - case 'close': - return new UnmanagedSubscriber('close'); - case 'block': - return new SocketBlockSubscriber(this, sub.zone); - case 'pending': - return new SocketPendingSubscriber(this, sub.zone); - case 'event': - return new SocketEventSubscriber(this, sub.filter, sub.zone); - case 'orphan': - // Handled auto-matically within AbstractProvider - // when the log.removed = true - if (sub.filter.orphan === 'drop-log') { - return new UnmanagedSubscriber('drop-log'); - } - } - return super._getSubscriber(sub); - } - /** - * Register a new subscriber. This is used internally by Subscribers and generally is unnecessary unless extending - * capabilities. - * - * @ignore - * @param {number | string} filterId - The filter ID. - * @param {SocketSubscriber} subscriber - The subscriber. - */ - _register(filterId, subscriber) { - this.#subs.set(filterId, subscriber); - const pending = this.#pending.get(filterId); - if (pending) { - for (const message of pending) { - subscriber._handleMessage(message); - } - this.#pending.delete(filterId); - } - } - /** - * Send a JSON-RPC payload. - * - * @ignore - * @param {JsonRpcPayload | JsonRpcPayload[]} payload - The payload to send. - * @param {Shard} [shard] - The shard. - * @param {boolean} [now] - Whether to send immediately. - * @returns {Promise<(JsonRpcResult | JsonRpcError)[]>} The result or error. - */ - async _send(payload, shard, now) { - if (this._initFailed) { - console.log('Provider failed to initialize on creation. Run initialize or create a new provider.'); - return [ - { - id: Array.isArray(payload) ? payload[0].id : payload.id, - error: { - code: -32000, - message: 'Provider failed to initialize on creation. Run initialize or create a new provider.', - }, - }, - ]; - } - // WebSocket provider doesn't accept batches - assertArgument(!Array.isArray(payload), 'WebSocket does not support batch send', 'payload', payload); - // @TODO: stringify payloads here and store to prevent mutations - // Prepare a promise to respond to - const promise = new Promise((resolve, reject) => { - this.#callbacks.set(payload.id, { payload, resolve, reject }); - }); - // Wait until the socket is connected before writing to it - try { - if (!now) { - await this._waitUntilReady(); - } - } - catch (error) { - this.#callbacks.delete(payload.id); - return [ - { - id: Array.isArray(payload) ? payload[0].id : payload.id, - error: { - code: -32000, - message: 'Provider failed to initialize on creation. Run initialize or create a new provider.', - }, - }, - ]; - } - // Write the request to the socket - await this._write(JSON.stringify(payload), shard); - return [await promise]; - } - /** - * Sub-classes **must** call this with messages received over their transport to be processed and dispatched. - * - * @ignore - * @param {string} message - The message to process. - */ - async _processMessage(message) { - const result = JSON.parse(message); - if (result && typeof result === 'object' && 'id' in result) { - const callback = this.#callbacks.get(result.id); - if (callback == null) { - this.emit('error', undefined, makeError('received result for unknown id', 'UNKNOWN_ERROR', { - reasonCode: 'UNKNOWN_ID', - result, - })); - return; - } - this.#callbacks.delete(result.id); - callback.resolve(result); - } - else if (result && result.method === 'quai_subscription') { - const filterId = result.params.subscription; - const subscriber = this.#subs.get(filterId); - if (subscriber) { - subscriber._handleMessage(result.params.result); - } - else { - let pending = this.#pending.get(filterId); - if (pending == null) { - pending = []; - this.#pending.set(filterId, pending); - } - pending.push(result.params.result); - } - } - else { - this.emit('error', undefined, makeError('received unexpected message', 'UNKNOWN_ERROR', { - reasonCode: 'UNEXPECTED_MESSAGE', - result, - })); - return; - } - } - /** - * Sub-classes **must** override this to send `message` over their transport. - * - * @ignore - * @param {string} message - The message to send. - * @param {Shard} [shard] - The shard. - * @returns {Promise} - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _write(message, shard) { - throw new Error('sub-classes must override this'); - } - validateUrl(url) { - const urlPattern = /^(ws):\/\/[a-zA-Z0-9.-]+(:\d+)?$/; - if (!urlPattern.test(url)) { - let errorMessage = 'Invalid URL: '; - if (!/^ws:\/\//.test(url)) { - errorMessage += 'URL must start with ws://. '; - } - if (url.endsWith('/')) { - errorMessage += 'URL should not end with a /. '; - } - if (/\/[^/]+/.test(url)) { - errorMessage += 'URL should not contain a path, query string, or fragment. '; - } - throw new Error(errorMessage.trim()); - } - } -} - -function getGlobal() { - if (typeof self !== 'undefined') { - return self; - } - if (typeof window !== 'undefined') { - return window; - } - if (typeof global !== 'undefined') { - return global; - } - throw new Error('unable to locate global object'); -} -const _WebSocket = getGlobal().WebSocket; - -/** - * A JSON-RPC provider which is backed by a WebSocket. - * - * WebSockets are often preferred because they retain a live connection to a server, which permits more instant access - * to events. - * - * However, this incurs higher server infrastructure costs, so additional resources may be required to host your own - * WebSocket nodes and many third-party services charge additional fees for WebSocket endpoints. - * - * @category Providers - * @extends SocketProvider - */ -class WebSocketProvider extends SocketProvider { - #websockets; - /** - * A map to track the readiness of each shard. - * - * @type {Map} - */ - readyMap = new Map(); - /** - * Get the array of WebSocketLike objects. - * - * @returns {WebSocketLike[]} The array of WebSocketLike objects. - * @throws {Error} If the websocket is closed. - */ - get websocket() { - if (this.#websockets == null) { - throw new Error('websocket closed'); - } - return this.#websockets; - } - /** - * Create a new WebSocketProvider. - * - * @param {string | string[] | WebSocketLike | WebSocketCreator} url - The URL(s) or WebSocket object or creator. - * @param {Networkish} [network] - The network to connect to. - * @param {JsonRpcApiProviderOptions} [options] - The options for the JSON-RPC API provider. - */ - constructor(url, network, options) { - super(network, options); - this.#websockets = []; - if (typeof url === 'string') { - this.validateUrl(url); - } - else if (Array.isArray(url)) { - url.forEach((it) => this.validateUrl(it)); - } - else if (typeof url === 'function') { - this.validateUrl(url().url); - } - else { - this.validateUrl(url.url); - } - this.initialize(typeof url === 'string' ? [url] : url); - } - /** - * Initialize a WebSocket connection for a shard. - * - * @ignore - * @param {WebSocketLike} websocket - The WebSocket object. - * @param {Shard} shard - The shard identifier. - */ - initWebSocket(websocket, shard) { - websocket.onerror = (error) => { - console.log('WebsocketProvider error', error); - websocket.close(); - }; - websocket.onopen = async () => { - try { - await this._start(); - this.resume(); - this.readyMap.set(shard, true); - } - catch (error) { - console.log('failed to start WebsocketProvider', error); - this.readyMap.set(shard, false); - // @TODO: now what? Attempt reconnect? - } - }; - websocket.onmessage = (message) => { - this._processMessage(message.data); - }; - } - /** - * Wait until the shard is ready. Max wait time is ~8 seconds. - * - * @param {Shard} shard - The shard identifier. - * @returns {Promise} A promise that resolves when the shard is ready. - * @throws {Error} If the shard is not ready within the timeout period. - */ - async waitShardReady(shard) { - let count = 0; - while (!this.readyMap.get(shard)) { - await new Promise((resolve) => setTimeout(resolve, Math.pow(2, count))); - if (count > 11) { - throw new Error('Timeout waiting for shard to be ready'); - } - count++; - } - } - /** - * Initialize the URL map with WebSocket connections. - * - * @ignore - * @param {U} urls - The URLs or WebSocket object or creator. - * @returns {Promise} A promise that resolves when the URL map is initialized. - */ - async initialize(urls) { - //clear websockets - this.#websockets = []; - this._urlMap.clear(); - try { - const primeSuffix = this._getOption('usePathing') ? `/${fromShard(Shard.Prime, 'nickname')}` : ':8001'; - const createWebSocket = (baseUrl, suffix) => { - const tempWs = new _WebSocket(`${baseUrl}${suffix}`); - return tempWs; - // wait 2 minutes - }; - const initShardWebSockets = async (baseUrl) => { - const shards = await this._getRunningLocations(Shard.Prime, true); - await Promise.all(shards.map(async (shard) => { - const port = 8200 + 20 * shard[0] + shard[1]; - const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`); - const shardSuffix = this._getOption('usePathing') - ? `/${fromShard(shardEnum, 'nickname')}` - : `:${port}`; - const shardUrl = baseUrl.split(':').slice(0, 2).join(':'); - const websocket = createWebSocket(shardUrl, shardSuffix); - this.initWebSocket(websocket, shardEnum); - this.#websockets.push(websocket); - this._urlMap.set(shardEnum, websocket); - try { - await this.waitShardReady(shardEnum); - } - catch (error) { - console.log('failed to waitShardReady', error); - this._initFailed = true; - } - })); - }; - if (Array.isArray(urls)) { - for (const url of urls) { - const baseUrl = `${url.split(':')[0]}:${url.split(':')[1]}`; - const primeWebsocket = createWebSocket(baseUrl, primeSuffix); - this.initWebSocket(primeWebsocket, Shard.Prime); - this.#websockets.push(primeWebsocket); - this._urlMap.set(Shard.Prime, primeWebsocket); - await this.waitShardReady(Shard.Prime); - await initShardWebSockets(baseUrl); - } - } - else if (typeof urls === 'function') { - const primeWebsocket = urls(); - this.initWebSocket(primeWebsocket, Shard.Prime); - this.#websockets.push(primeWebsocket); - this._urlMap.set(Shard.Prime, primeWebsocket); - await this.waitShardReady(Shard.Prime); - const baseUrl = this.#websockets[0].url.split(':').slice(0, 2).join(':'); - await initShardWebSockets(baseUrl); - } - else { - const primeWebsocket = urls; - this.initWebSocket(primeWebsocket, Shard.Prime); - this.#websockets.push(primeWebsocket); - this._urlMap.set(Shard.Prime, primeWebsocket); - await this.waitShardReady(Shard.Prime); - const baseUrl = primeWebsocket.url.split(':').slice(0, 2).join(':'); - await initShardWebSockets(baseUrl); - } - if (this.initResolvePromise) - this.initResolvePromise(); - } - catch (error) { - this._initFailed = true; - console.log('failed to initialize', error); - //clear websockets - this.#websockets = []; - if (this.initRejectPromise) - this.initRejectPromise(error); - return; - } - } - /** - * Write a message to the WebSocket. - * - * @ignore - * @param {string} message - The message to send. - * @param {Shard} [shard] - The shard identifier. - * @returns {Promise} A promise that resolves when the message is sent. - * @throws {Error} If the WebSocket is closed or the shard is not found. - */ - async _write(message, shard) { - if (this.websocket.length < 1) { - throw new Error('Websocket closed'); - } - if (shard && !this._urlMap.has(shard)) { - throw new Error('Shard not found'); - } - const websocket = shard ? this._urlMap.get(shard) : this.websocket[this.websocket.length - 1]; - if (!websocket) { - throw new Error('Websocket is undefined'); - } - if (shard) { - await this.waitShardReady(shard); - } - websocket.send(message); - } - /** - * Destroy the WebSocket connections and clean up resources. - * - * @returns {Promise} A promise that resolves when the WebSocket connections are closed. - */ - async destroy() { - this.#websockets.forEach((it) => it.close()); - this.#websockets = []; - super.destroy(); - } -} - -const Base64 = ')!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'; -/** - * @ignore - */ -function decodeBits(width, data) { - const maxValue = (1 << width) - 1; - const result = []; - let accum = 0, bits = 0, flood = 0; - for (let i = 0; i < data.length; i++) { - // Accumulate 6 bits of data - accum = (accum << 6) | Base64.indexOf(data[i]); - bits += 6; - // While we have enough for a word... - while (bits >= width) { - // ...read the word - const value = accum >> (bits - width); - accum &= (1 << (bits - width)) - 1; - bits -= width; - // A value of 0 indicates we exceeded maxValue, it - // floods over into the next value - if (value === 0) { - flood += maxValue; - } - else { - result.push(value + flood); - flood = 0; - } - } - } - return result; -} - -/** - * @ignore - */ -function decodeOwlA(data, accents) { - let words = decodeOwl(data).join(','); - // Inject the accents - accents.split(/,/g).forEach((accent) => { - const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); - assertArgument(match !== null, 'internal error parsing accents', 'accents', accents); - let posOffset = 0; - const positions = decodeBits(parseInt(match[3]), match[4]); - const charCode = parseInt(match[2]); - const regex = new RegExp(`([${match[1]}])`, 'g'); - words = words.replace(regex, (all, letter) => { - const rem = --positions[posOffset]; - if (rem === 0) { - letter = String.fromCharCode(letter.charCodeAt(0), charCode); - posOffset++; - } - return letter; - }); - }); - return words.split(','); -} - -/** - * An OWL-A format Wordlist extends the OWL format to add an overlay onto an OWL format Wordlist to support diacritic - * marks. - * - * This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages - * based on latin-1 small. - * - * If necessary, there are tools within the `generation/` folder to create the necessary data. - * - * @category Wordlists - */ -class WordlistOwlA extends WordlistOwl { - #accent; - /** - * Creates a new Wordlist for `locale` using the OWLA `data` and `accent` data and validated against the `checksum`. - */ - constructor(locale, data, accent, checksum) { - super(locale, data, checksum); - this.#accent = accent; - } - /** - * The OWLA-encoded accent data. - * - * @ignore - */ - get _accent() { - return this.#accent; - } - /** - * Decode all the words for the wordlist. - * - * @ignore - */ - _decodeWords() { - return decodeOwlA(this._data, this._accent); - } -} - -const words = "0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_LoAmpuAnc]ApaAr]I>Is)IvoOqueOzaUle%Up 0Cl.EgoE=EnEr#F[G +M->NeN%P_sR>Rue]SneTaU{d2Am^AnA+AseAveI,)ImaInica2B_Cc~|i'Ci`CoDigoDoF_G!He)JinJoL/ch/eg$Lg Lin/l LmoLum`Mba)M!Mi{Mo&Mpr-deNej}g-oc!Nsej}t PaPi(az.Rba%RchoR&nR.(r!S!SmosS%2AneoAt!E Ec!Ei&EmaIaIm,Ip%IsisOmoOnicaOque%U&Uz2Ad+Ar#At+BoBr*| aEl=En#Er{Es%EvaId Lebr/p/#Mb_Mpl*N-e%O%P.Pul( R$Se'Sf[zVaVi'5BleCeL^Ming}N Ra&Rm*RAu%EchaOrO%U*UjoU^2B@CaGa%G.L$Lle#N&Rm(+Rtun(z SaTo2AcaA'AsaAtisAveIe%Il=IpeIsI#OG Gu!aJaMb_Ng}^Nr((mig('St?Yo5E>ElgaEr%ENgl-$Nt Pit!R S#V,?Zg :7Lo5A]:B$C$C[DoD+nG #GrimaGu`I>M!Mi`Mp --ch-gos%NzaPizRgoRvaStimaTaTexT*U_lV Zo3AlCc~|eC#rErG~Gumb_Ja'Ngu-#NaOnOp &S~TalT[VeY,{3B!%dB+C^D!Di EnzoGaG!oMaMi)M.Mp$NceN&Ne-go)N}t!`Qui&SoS%T!aT$T+2AgaAmaAn#AveEg En Ev Or Ov!Uv@2BoC~CoCu[GicaG+MbrizM}jaTe5|aC*G J}-esPaSt+ToZ:Ce%|oD!aD_Du+Est+F@G@GoIzL{dLe%Ll/oMaMboMutN>N&Nej Ng-iquiNj N}Re(f?Rg,Ri&RmolR+nR)sRzoSaSc aSivoT T!@TizTrizXimoY^Z^ca3|aDal]D$Du]J?]J^L,/.M^i-^NsajeN)NuRca&R,gueRi#SS.TaT!To&T+Zc]3E&ElEmb+G/Lag+Lit Ll.M}-!}im}u#OpeR SaS!@S?SmoTadTo5|?aC~DaDe=HoJ LdeL!Li'M,#Mi- c-ed-j-#NoRad(d!Re'R*R+Rs(%lScaStr TivoV!V?Zo5|oD EbleE]Er)Est[G_J!L/e%L%N&Nec(alRoScu=SeoSgoSicaS=:C C~D IpeRanj(izRr SalTalTivoTu[lUseaValVeVi{d3C$Ct G Goc$G+OnRv$ToUt+V V!a3|oDoEb]E#NezNoTi&Vel5Bleza|eMin(i(m()TaTic@Va#Ve]V$5BeCaCleoD?=DoE[EveEzLoM!oTr@:Sis0EC~E[In On!T TicaUes#1Ac~A&rAlBi%CaD,EjaGa'G@Gul=I,)Ig,Il]OQues%Uga0Ad@Cu+Ez'OT[0O'Ro1EjaU=1I&Ige'0En)0O':C#D_El]Gi`GoIsJ oLabr/>Le%Li&Lm/om/p NNalNi>Nt!-ue=PaPelP?]Que)R Rcel(edR*RoRpa&RqueR[foR)S SeoS~SoS%TaT$Tr@UsaU%VoYa<3A#nCa&C!a|oDalD*G IneL L{'Le/ig+LlejoLoLuc--s N.OnOrPi'Que'R(ch(d!Rez(f?Ri>Rl(mizEgun%Em$EnsaE|!oD^Eb=Er%Es#Lg/*Lm.LpoLrNd*N%P #Pet*PoN{PaP!oSaScaSt+T 5BiB^DoE{G*I&In/e%LoMboM^Ptu[TaTi`:Ba&B!B$BleC GazG[&L/&L!oL*Lm.L.Ls/#LudLv Mb-c~Ndi-e Ng_Ni{dN}#PoQueRdin()nSt_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv! 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 values resolved.\n *\n * @category Utils\n * @param {Object} value - The object to resolve.\n *\n * @returns {Promise} The resolved object.\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// Crawl up the constructor chain to find a static method\nexport function getStatic(ctor, key) {\n for (let i = 0; i < 32; i++) {\n if (ctor[key]) {\n return ctor[key];\n }\n if (!ctor.prototype || typeof ctor.prototype !== 'object') {\n break;\n }\n ctor = Object.getPrototypeOf(ctor.prototype).constructor;\n }\n return null;\n}\n/**\n * Assigns the `values` to `target` as read-only values.\n *\n * It `types` is specified, the values are checked.\n *\n * @category Utils\n * @param {Object} target - The target object to assign to.\n * @param {Object} values - The values to assign.\n * @param {Object} types - The types to check.\n */\nexport function defineProperties(target, values, types) {\n for (const key in values) {\n const 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 quais include properties to ensure they are both human-readable (i.e. `.message`) and machine-readable\n * (i.e. `.code`).\n *\n * The {@link isError | **isError**} function can be used to check the error `code` and provide a type guard for the\n * properties present on that error interface.\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 quais that matches the error `code`.\n *\n * In TypeScript environments, this can be used to check that `error` matches an quaisError type, which means the\n * expected properties will be set.\n *\n * @category Utils\n * @example\n *\n * ```ts\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 * ```\n *\n * @see [ErrorCodes](api:ErrorCode)\n */\nexport function isError(error, code) {\n return error && error.code === code;\n}\n/**\n * Returns true if `error` is a {@link CallExceptionError | **CallExceptionError**}.\n *\n * @category Utils\n */\nexport function isCallException(error) {\n return isError(error, 'CALL_EXCEPTION');\n}\n/**\n * Returns a new Error configured to the format quais emits errors, with the `message`, {@link ErrorCode | **ErrorCode**}\n * `code` and additional properties for the corresponding quaisError.\n *\n * Each error in quais includes the version of quais, a machine-readable {@link ErrorCode | **ErrorCode**}, and depending\n * on `code`, additional required properties. The error message will also include the `message`, quais version, `code`\n * and all additional properties, serialized.\n *\n * @category Utils\n * @param {string} message - The error message.\n * @param {ErrorCode} code - The error code.\n * @param {ErrorInfo} [info] - Additional properties for the error.\n * @returns {T} The new error.\n */\nexport function makeError(message, code, info) {\n const 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 details.push(key + '=' + stringify(value));\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 quaisError with `message`, `code` and additional error `info` when `check` is falsish..\n *\n * @category Utils\n * @param {unknown} check - The value to check.\n * @param {string} message - The error message.\n * @param {ErrorCode} code - The error code.\n * @param {ErrorInfo} [info] - Additional properties for the error.\n * @throws {T} Throws the error if `check` is falsish.\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 constraints, throwing if not.\n *\n * In TypeScript environments, the `check` has been asserted true, so any further code does not need additional\n * compile-time checks.\n *\n * @category Utils\n * @param {unknown} check - The value to check.\n * @param {string} message - The error message.\n * @param {string} name - The name of the argument.\n * @param {unknown} value - The value of the argument.\n * @throws {InvalidArgumentError} Throws if `check` is falsish.\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 arguemnts' + 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 /* 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 // eslint-disable-next-line no-empty\n }\n catch (error) { }\n return accum;\n}, []);\n/**\n * Throws if the normalization `form` is not supported.\n *\n * @category Utils\n * @param {string} form - The normalization form.\n * @throws {UnsupportedOperationError} Throws if the 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',\n info: { form },\n });\n}\n/**\n * Many classes use file-scoped values to guard the constructor, making it effectively private. This facilitates that\n * pattern by ensuring the `givenGuard` matches the file-scoped `guard`, throwing if not, indicating the `className%% if\n * provided.\n *\n * @category Utils\n * @param {any} givenGuard - The guard provided to the constructor.\n * @param {any} guard - The file-scoped guard.\n * @param {string} [className] - The class name.\n * @throws {UnsupportedOperationError} Throws if the guards do not match.\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 */\nimport { assert, assertArgument } from './errors.js';\n/**\n * Converts a BytesLike value to a Uint8Array.\n *\n * @ignore\n * @category Utils\n * @param {BytesLike} value - The value to convert.\n * @param {string} [name] - The name of the value for error context.\n * @param {boolean} [copy] - Whether to create a copy of the value.\n *\n * @returns {Uint8Array} The converted Uint8Array.\n * @throws {Error} If the value is not a valid BytesLike.\n */\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 the original `value` is returned; if a copy is required\n * use {@link getBytesCopy | **getBytesCopy**}.\n *\n * @category Utils\n * @param {BytesLike} value - The value to convert to a Uint8Array.\n * @param {string} [name] - The name of the value for error context.\n *\n * @returns {Uint8Array} The typed Uint8Array.\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 to prevent any modifications of the returned value\n * from being reflected elsewhere.\n *\n * @category Utils\n * @param {BytesLike} value - The value to convert to a Uint8Array.\n * @param {string} [name] - The name of the value for error context.\n *\n * @returns {Uint8Array} The typed Uint8Array.\n */\nexport function getBytesCopy(value, name) {\n return _getBytes(value, name, true);\n}\n/**\n * Returns true if `value` is a valid {@link HexString | **HexString**}.\n *\n * If `length` is `true` or a number, it also checks that `value` is a valid {@link DataHexString | **DataHexString**} of\n * `length` (if a number) bytes of data (e.g. `0x1234` is 2 bytes).\n *\n * @category Utils\n * @param {any} value - The value to check.\n * @param {number | boolean} [length] - The expected length of the data.\n *\n * @returns {boolean} True if the value is a valid {@link HexString | **HexString**}.\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 data (i.e. a valid\n * {@link DataHexString | **DataHexString**} or a Uint8Array).\n *\n * @category Utils\n * @param {any} value - The value to check.\n *\n * @returns {boolean} True if the value is a valid {@link DataHexString | **DataHexString**}.\n */\nexport function isBytesLike(value) {\n return isHexString(value, true) || value instanceof Uint8Array;\n}\nconst HexCharacters = '0123456789abcdef';\n/**\n * Returns a {@link DataHexString | **DataHexString**} representation of `data`.\n *\n * @category Utils\n * @param {BytesLike} data - The data to convert to a hex string.\n *\n * @returns {string} The hex string.\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 {@link DataHexString | **DataHexString** } by concatenating all values within `data`.\n *\n * @category Utils\n * @param {ReadonlyArray} datas - The data to concatenate.\n *\n * @returns {string} The concatenated 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 *\n * @category Utils\n * @param {BytesLike} data - The data to get the length of.\n *\n * @returns {number} The length of the data.\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 {@link DataHexString | **DataHexString** } by slicing `data` from the `start` offset to the `end` offset.\n *\n * By default `start` is 0 and `end` is the length of `data`.\n *\n * @category Utils\n * @param {BytesLike} data - The data to slice.\n * @param {number} [start] - The start offset.\n * @param {number} [end] - The end offset.\n *\n * @returns {string} The sliced data.\n * @throws {Error} If the end offset is beyond the data bounds.\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,\n length: bytes.length,\n offset: end,\n });\n }\n return hexlify(bytes.slice(start == null ? 0 : start, end == null ? bytes.length : end));\n}\n/**\n * Return the {@link DataHexString | **DataHexString**} result by stripping all **leading** zero bytes from `data`.\n *\n * @category Utils\n * @param {BytesLike} data - The data to strip.\n *\n * @returns {string} The stripped 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}\n/**\n * Pads the data to the specified length.\n *\n * @ignore\n * @category Utils\n * @param {BytesLike} data - The data to pad.\n * @param {number} length - The length to pad to.\n * @param {boolean} left - Whether to pad on the left.\n *\n * @returns {string} The padded data.\n * @throws {Error} If the padding exceeds data length.\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 {@link DataHexString | **DataHexString**} of `data` padded on the **left** to `length` bytes.\n *\n * If `data` already exceeds `length`, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown.\n *\n * This pads data the same as **values** are in Solidity (e.g. `uint128`).\n *\n * @category Utils\n * @param {BytesLike} data - The data to pad.\n * @param {number} length - The length to pad to.\n *\n * @returns {string} The padded data.\n */\nexport function zeroPadValue(data, length) {\n return zeroPad(data, length, true);\n}\n/**\n * Return the {@link DataHexString | **DataHexString**} of `data` padded on the **right** to `length` bytes.\n *\n * If `data` already exceeds %%length%%, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown.\n *\n * This pads data the same as **bytes** are in Solidity (e.g. `bytes16`).\n *\n * @category Utils\n * @param {BytesLike} data - The data to pad.\n * @param {number} length - The length to pad to.\n *\n * @returns {string} The padded data.\n */\nexport function zeroPadBytes(data, length) {\n return zeroPad(data, length, false);\n}\n//# sourceMappingURL=data.js.map","import { defineProperties } from './properties.js';\n/**\n * When an {@link EventEmitterable | **EventEmitterable**} triggers a Listener, the callback always ahas one additional\n * argument passed, which is an **EventPayload**.\n *\n * @category Utils\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 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","import { getBytes } from '../utils/data.js';\nexport function decodeBase64(textData) {\n textData = atob(textData);\n const data = new Uint8Array(textData.length);\n for (let i = 0; i < textData.length; i++) {\n data[i] = textData.charCodeAt(i);\n }\n return getBytes(data);\n}\nexport function encodeBase64(_data) {\n const data = getBytes(_data);\n let textData = '';\n for (let i = 0; i < data.length; i++) {\n textData += String.fromCharCode(data[i]);\n }\n return btoa(textData);\n}\n//# sourceMappingURL=base64-browser.js.map","/**\n * Provides utility functions for encoding and decoding strings in the Bytes32 format.\n *\n * @category Application Binary Interface\n */\nimport { getBytes, zeroPadBytes } from '../utils/index.js';\nimport { toUtf8Bytes, toUtf8String } from './index.js';\n/**\n * Encodes a string as a Bytes32 string. This is used to encode ABI data.\n *\n * @category Encoding\n * @param {string} text - The string to encode.\n *\n * @returns {string} The Bytes32-encoded string.\n * @throws {Error} If the string is too long to fit in a Bytes32 format.\n */\nexport function encodeBytes32(text) {\n // Get the bytes\n const bytes = toUtf8Bytes(text);\n // Check we have room for null-termination\n if (bytes.length > 31) {\n throw new Error('bytes32 string must be less than 32 bytes');\n }\n // Zero-pad (implicitly null-terminates)\n return zeroPadBytes(bytes, 32);\n}\n/**\n * Decodes a Bytes32-encoded string into a regular string. This is used to decode ABI-encoded data.\n *\n * @category Encoding\n * @param {BytesLike} _bytes - The Bytes32-encoded data.\n *\n * @returns {string} The decoded string.\n * @throws {Error} If the input is not exactly 32 bytes long or lacks a null terminator.\n */\nexport function decodeBytes32(_bytes) {\n const data = getBytes(_bytes, 'bytes');\n // Must be 32 bytes with a null-termination\n if (data.length !== 32) {\n throw new Error('invalid bytes32 - not 32 bytes long');\n }\n if (data[31] !== 0) {\n throw new Error('invalid bytes32 string - no null terminator');\n }\n // Find the null termination\n let length = 31;\n while (data[length - 1] === 0) {\n length--;\n }\n // Determine the string value\n return toUtf8String(data.slice(0, length));\n}\n//# sourceMappingURL=bytes32.js.map","/**\n * Some mathematic operations.\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` bits to its value.\n *\n * If the highest bit is `1`, the result will be negative.\n *\n * @category Utils\n * @param {BigNumberish} _value - The value to convert.\n * @param {Numeric} _width - The width of the value in bits.\n * @returns {bigint} The value.\n * @throws {Error} If the value is too large for the width.\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',\n fault: 'overflow',\n 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 `width` bits.\n *\n * The result will always be positive.\n *\n * @category Utils\n * @param {BigNumberish} _value - The value to convert.\n * @param {Numeric} _width - The width of the value in bits.\n * @returns {bigint} The value.\n * @throws {Error} If the value is too large for the width.\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',\n fault: 'overflow',\n 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',\n fault: 'overflow',\n value: _value,\n });\n }\n return value;\n}\n/**\n * Mask `value` with a bitmask of `bits` ones.\n *\n * @category Utils\n * @param {BigNumberish} _value - The value to mask.\n * @param {Numeric} _bits - The number of bits to mask.\n * @returns {bigint} The masked value.\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 a BigInt, then an ArgumentError will be thrown for `name`.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @param {string} name - The name of the value.\n * @returns {bigint} The value.\n */\nexport function getBigInt(value, name) {\n switch (typeof value) {\n case 'bigint':\n 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 absolute value of bigint `value`.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @returns {bigint} The absolute value.\n */\nexport function bigIntAbs(value) {\n value = getBigInt(value);\n // if value is negative (including -0), return -value, else return value\n if (value === -BN_0 || value < BN_0) {\n return -value;\n }\n return value;\n}\n/**\n * Returns `value` as a bigint, validating it is valid as a bigint value and that it is positive.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @param {string} name - The name of the value.\n * @returns {bigint} The value.\n * @throws {Error} If the value is negative.\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',\n operation: 'getUint',\n value,\n });\n return result;\n}\nconst Nibbles = '0123456789abcdef';\n/**\n * Converts `value` to a BigInt. If `value` is a Uint8Array, it is treated as Big Endian data.\n *\n * @category Utils\n * @param {BigNumberish | Uint8Array} value - The value to convert.\n * @returns {bigint} The value.\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 a number, then an ArgumentError will be thrown for `name`.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @param {string} name - The name of the value.\n * @returns {number} The value.\n * @throws {Error} If the value is invalid.\n * @throws {Error} If the value is too large.\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 is treated as Big Endian data. Throws if the value is\n * not safe.\n *\n * @category Utils\n * @param {BigNumberish | Uint8Array} value - The value to convert.\n * @returns {number} The value.\n * @throws {Error} If the value is not safe to convert to a number.\n */\nexport function toNumber(value) {\n return getNumber(toBigInt(value));\n}\n/**\n * Converts `value` to a Big Endian hexstring, optionally padded to `width` bytes.\n *\n * @category Utils\n * @param {BigNumberish} _value - The value to convert.\n * @param {Numeric} _width - The width of the value in bytes.\n * @returns {string} The hexstring.\n * @throws {Error} If the value exceeds the width.\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 *\n * @category Utils\n * @param {BigNumberish} _value - The value to convert.\n * @returns {Uint8Array} The value.\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 the literal value `0x0`. This is most commonly used\n * for JSSON-RPC numeric values.\n *\n * @category Utils\n * @param {BigNumberish | Uint8Array} value - The value to convert.\n * @returns {string} The quantity.\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](https://en.bitcoinwiki.org/wiki/Base58) scheme allows a **numeric** value to be encoded as a\n * compact string using a radix of 58 using only alpha-numeric characters. Confusingly similar characters are omitted\n * (i.e. `\"l0O\"`).\n *\n * Note that Base58 encodes a **numeric** value, not arbitrary bytes, since any zero-bytes on the left would get\n * removed. To mitigate this issue most schemes that use Base58 choose specific high-order values to ensure non-zero\n * prefixes.\n */\nimport { getBytes } from '../utils/data.js';\nimport { assertArgument } from '../utils/errors.js';\nimport { toBigInt } from '../utils/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 *\n * @category Encoding\n * @param {BytesLike} _value - The value to encode.\n *\n * @returns {string} The 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 *\n * @category Encoding\n * @param {string} value - The Base58-encoded value.\n *\n * @returns {bigint} The decoded 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 * Generated by the protoc-gen-ts. DO NOT EDIT!\n * compiler version: 4.25.3\n * source: proto_common.proto\n * git: https://github.com/thesayyn/protoc-gen-ts */\nimport * as pb_1 from \"google-protobuf\";\nexport var common;\n(function (common) {\n class ProtoLocation extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n }\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set value(value) {\n pb_1.Message.setField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoLocation({});\n if (data.value != null) {\n message.value = data.value;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.value != null) {\n data.value = this.value;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.value.length)\n writer.writeBytes(1, this.value);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLocation();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.value = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoLocation.deserialize(bytes);\n }\n }\n common.ProtoLocation = ProtoLocation;\n class ProtoHash extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n }\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set value(value) {\n pb_1.Message.setField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoHash({});\n if (data.value != null) {\n message.value = data.value;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.value != null) {\n data.value = this.value;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.value.length)\n writer.writeBytes(1, this.value);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHash();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.value = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoHash.deserialize(bytes);\n }\n }\n common.ProtoHash = ProtoHash;\n class ProtoHashes extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"hashes\" in data && data.hashes != undefined) {\n this.hashes = data.hashes;\n }\n }\n }\n get hashes() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoHash, 1);\n }\n set hashes(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoHashes({});\n if (data.hashes != null) {\n message.hashes = data.hashes.map(item => ProtoHash.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.hashes != null) {\n data.hashes = this.hashes.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.hashes.length)\n writer.writeRepeatedMessage(1, this.hashes, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHashes();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.hashes, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoHash.deserialize(reader), ProtoHash));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoHashes.deserialize(bytes);\n }\n }\n common.ProtoHashes = ProtoHashes;\n class ProtoAddress extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n }\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set value(value) {\n pb_1.Message.setField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoAddress({});\n if (data.value != null) {\n message.value = data.value;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.value != null) {\n data.value = this.value;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.value.length)\n writer.writeBytes(1, this.value);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoAddress();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.value = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoAddress.deserialize(bytes);\n }\n }\n common.ProtoAddress = ProtoAddress;\n class ProtoNumber extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n }\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 1, 0);\n }\n set value(value) {\n pb_1.Message.setField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoNumber({});\n if (data.value != null) {\n message.value = data.value;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.value != null) {\n data.value = this.value;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.value != 0)\n writer.writeUint64(1, this.value);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoNumber();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.value = reader.readUint64();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoNumber.deserialize(bytes);\n }\n }\n common.ProtoNumber = ProtoNumber;\n class ProtoLocations extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"locations\" in data && data.locations != undefined) {\n this.locations = data.locations;\n }\n }\n }\n get locations() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoLocation, 1);\n }\n set locations(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoLocations({});\n if (data.locations != null) {\n message.locations = data.locations.map(item => ProtoLocation.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.locations != null) {\n data.locations = this.locations.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.locations.length)\n writer.writeRepeatedMessage(1, this.locations, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLocations();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.locations, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoLocation.deserialize(reader), ProtoLocation));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoLocations.deserialize(bytes);\n }\n }\n common.ProtoLocations = ProtoLocations;\n})(common || (common = {}));\n//# sourceMappingURL=proto_common.js.map","/**\n * Generated by the protoc-gen-ts. DO NOT EDIT!\n * compiler version: 4.25.3\n * source: proto_block.proto\n * git: https://github.com/thesayyn/protoc-gen-ts */\nimport * as dependency_1 from \"./proto_common.js\";\nimport * as pb_1 from \"google-protobuf\";\nexport var block;\n(function (block) {\n class ProtoHeader extends pb_1.Message {\n #one_of_decls = [[2], [3], [4], [5], [6], [7], [9], [10], [14], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1, 8, 11, 12, 13, 15], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"parent_hash\" in data && data.parent_hash != undefined) {\n this.parent_hash = data.parent_hash;\n }\n if (\"uncle_hash\" in data && data.uncle_hash != undefined) {\n this.uncle_hash = data.uncle_hash;\n }\n if (\"coinbase\" in data && data.coinbase != undefined) {\n this.coinbase = data.coinbase;\n }\n if (\"evm_root\" in data && data.evm_root != undefined) {\n this.evm_root = data.evm_root;\n }\n if (\"tx_hash\" in data && data.tx_hash != undefined) {\n this.tx_hash = data.tx_hash;\n }\n if (\"etx_hash\" in data && data.etx_hash != undefined) {\n this.etx_hash = data.etx_hash;\n }\n if (\"etx_rollup_hash\" in data && data.etx_rollup_hash != undefined) {\n this.etx_rollup_hash = data.etx_rollup_hash;\n }\n if (\"manifest_hash\" in data && data.manifest_hash != undefined) {\n this.manifest_hash = data.manifest_hash;\n }\n if (\"receipt_hash\" in data && data.receipt_hash != undefined) {\n this.receipt_hash = data.receipt_hash;\n }\n if (\"difficulty\" in data && data.difficulty != undefined) {\n this.difficulty = data.difficulty;\n }\n if (\"parent_entropy\" in data && data.parent_entropy != undefined) {\n this.parent_entropy = data.parent_entropy;\n }\n if (\"parent_delta_s\" in data && data.parent_delta_s != undefined) {\n this.parent_delta_s = data.parent_delta_s;\n }\n if (\"parent_uncled_sub_delta_s\" in data && data.parent_uncled_sub_delta_s != undefined) {\n this.parent_uncled_sub_delta_s = data.parent_uncled_sub_delta_s;\n }\n if (\"uncled_s\" in data && data.uncled_s != undefined) {\n this.uncled_s = data.uncled_s;\n }\n if (\"number\" in data && data.number != undefined) {\n this.number = data.number;\n }\n if (\"gas_limit\" in data && data.gas_limit != undefined) {\n this.gas_limit = data.gas_limit;\n }\n if (\"gas_used\" in data && data.gas_used != undefined) {\n this.gas_used = data.gas_used;\n }\n if (\"base_fee\" in data && data.base_fee != undefined) {\n this.base_fee = data.base_fee;\n }\n if (\"location\" in data && data.location != undefined) {\n this.location = data.location;\n }\n if (\"extra\" in data && data.extra != undefined) {\n this.extra = data.extra;\n }\n if (\"mix_hash\" in data && data.mix_hash != undefined) {\n this.mix_hash = data.mix_hash;\n }\n if (\"nonce\" in data && data.nonce != undefined) {\n this.nonce = data.nonce;\n }\n if (\"utxo_root\" in data && data.utxo_root != undefined) {\n this.utxo_root = data.utxo_root;\n }\n if (\"etx_set_hash\" in data && data.etx_set_hash != undefined) {\n this.etx_set_hash = data.etx_set_hash;\n }\n if (\"efficiency_score\" in data && data.efficiency_score != undefined) {\n this.efficiency_score = data.efficiency_score;\n }\n if (\"threshold_count\" in data && data.threshold_count != undefined) {\n this.threshold_count = data.threshold_count;\n }\n if (\"expansion_number\" in data && data.expansion_number != undefined) {\n this.expansion_number = data.expansion_number;\n }\n if (\"etx_eligible_slices\" in data && data.etx_eligible_slices != undefined) {\n this.etx_eligible_slices = data.etx_eligible_slices;\n }\n if (\"prime_terminus\" in data && data.prime_terminus != undefined) {\n this.prime_terminus = data.prime_terminus;\n }\n if (\"interlink_root_hash\" in data && data.interlink_root_hash != undefined) {\n this.interlink_root_hash = data.interlink_root_hash;\n }\n }\n }\n get parent_hash() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set parent_hash(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n get uncle_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set uncle_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[0], value);\n }\n get has_uncle_hash() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get coinbase() {\n return pb_1.Message.getFieldWithDefault(this, 3, new Uint8Array(0));\n }\n set coinbase(value) {\n pb_1.Message.setOneofField(this, 3, this.#one_of_decls[1], value);\n }\n get has_coinbase() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get evm_root() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 4);\n }\n set evm_root(value) {\n pb_1.Message.setOneofWrapperField(this, 4, this.#one_of_decls[2], value);\n }\n get has_evm_root() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get tx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 5);\n }\n set tx_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 5, this.#one_of_decls[3], value);\n }\n get has_tx_hash() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get etx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 6);\n }\n set etx_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 6, this.#one_of_decls[4], value);\n }\n get has_etx_hash() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get etx_rollup_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 7);\n }\n set etx_rollup_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 7, this.#one_of_decls[5], value);\n }\n get has_etx_rollup_hash() {\n return pb_1.Message.getField(this, 7) != null;\n }\n get manifest_hash() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 8);\n }\n set manifest_hash(value) {\n pb_1.Message.setRepeatedWrapperField(this, 8, value);\n }\n get receipt_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 9);\n }\n set receipt_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 9, this.#one_of_decls[6], value);\n }\n get has_receipt_hash() {\n return pb_1.Message.getField(this, 9) != null;\n }\n get difficulty() {\n return pb_1.Message.getFieldWithDefault(this, 10, new Uint8Array(0));\n }\n set difficulty(value) {\n pb_1.Message.setOneofField(this, 10, this.#one_of_decls[7], value);\n }\n get has_difficulty() {\n return pb_1.Message.getField(this, 10) != null;\n }\n get parent_entropy() {\n return pb_1.Message.getFieldWithDefault(this, 11, []);\n }\n set parent_entropy(value) {\n pb_1.Message.setField(this, 11, value);\n }\n get parent_delta_s() {\n return pb_1.Message.getFieldWithDefault(this, 12, []);\n }\n set parent_delta_s(value) {\n pb_1.Message.setField(this, 12, value);\n }\n get parent_uncled_sub_delta_s() {\n return pb_1.Message.getFieldWithDefault(this, 13, []);\n }\n set parent_uncled_sub_delta_s(value) {\n pb_1.Message.setField(this, 13, value);\n }\n get uncled_s() {\n return pb_1.Message.getFieldWithDefault(this, 14, new Uint8Array(0));\n }\n set uncled_s(value) {\n pb_1.Message.setOneofField(this, 14, this.#one_of_decls[8], value);\n }\n get has_uncled_s() {\n return pb_1.Message.getField(this, 14) != null;\n }\n get number() {\n return pb_1.Message.getFieldWithDefault(this, 15, []);\n }\n set number(value) {\n pb_1.Message.setField(this, 15, value);\n }\n get gas_limit() {\n return pb_1.Message.getFieldWithDefault(this, 16, 0);\n }\n set gas_limit(value) {\n pb_1.Message.setOneofField(this, 16, this.#one_of_decls[9], value);\n }\n get has_gas_limit() {\n return pb_1.Message.getField(this, 16) != null;\n }\n get gas_used() {\n return pb_1.Message.getFieldWithDefault(this, 17, 0);\n }\n set gas_used(value) {\n pb_1.Message.setOneofField(this, 17, this.#one_of_decls[10], value);\n }\n get has_gas_used() {\n return pb_1.Message.getField(this, 17) != null;\n }\n get base_fee() {\n return pb_1.Message.getFieldWithDefault(this, 18, new Uint8Array(0));\n }\n set base_fee(value) {\n pb_1.Message.setOneofField(this, 18, this.#one_of_decls[11], value);\n }\n get has_base_fee() {\n return pb_1.Message.getField(this, 18) != null;\n }\n get location() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoLocation, 19);\n }\n set location(value) {\n pb_1.Message.setOneofWrapperField(this, 19, this.#one_of_decls[12], value);\n }\n get has_location() {\n return pb_1.Message.getField(this, 19) != null;\n }\n get extra() {\n return pb_1.Message.getFieldWithDefault(this, 20, new Uint8Array(0));\n }\n set extra(value) {\n pb_1.Message.setOneofField(this, 20, this.#one_of_decls[13], value);\n }\n get has_extra() {\n return pb_1.Message.getField(this, 20) != null;\n }\n get mix_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 21);\n }\n set mix_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 21, this.#one_of_decls[14], value);\n }\n get has_mix_hash() {\n return pb_1.Message.getField(this, 21) != null;\n }\n get nonce() {\n return pb_1.Message.getFieldWithDefault(this, 22, 0);\n }\n set nonce(value) {\n pb_1.Message.setOneofField(this, 22, this.#one_of_decls[15], value);\n }\n get has_nonce() {\n return pb_1.Message.getField(this, 22) != null;\n }\n get utxo_root() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 23);\n }\n set utxo_root(value) {\n pb_1.Message.setOneofWrapperField(this, 23, this.#one_of_decls[16], value);\n }\n get has_utxo_root() {\n return pb_1.Message.getField(this, 23) != null;\n }\n get etx_set_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 24);\n }\n set etx_set_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 24, this.#one_of_decls[17], value);\n }\n get has_etx_set_hash() {\n return pb_1.Message.getField(this, 24) != null;\n }\n get efficiency_score() {\n return pb_1.Message.getFieldWithDefault(this, 25, 0);\n }\n set efficiency_score(value) {\n pb_1.Message.setOneofField(this, 25, this.#one_of_decls[18], value);\n }\n get has_efficiency_score() {\n return pb_1.Message.getField(this, 25) != null;\n }\n get threshold_count() {\n return pb_1.Message.getFieldWithDefault(this, 26, 0);\n }\n set threshold_count(value) {\n pb_1.Message.setOneofField(this, 26, this.#one_of_decls[19], value);\n }\n get has_threshold_count() {\n return pb_1.Message.getField(this, 26) != null;\n }\n get expansion_number() {\n return pb_1.Message.getFieldWithDefault(this, 27, 0);\n }\n set expansion_number(value) {\n pb_1.Message.setOneofField(this, 27, this.#one_of_decls[20], value);\n }\n get has_expansion_number() {\n return pb_1.Message.getField(this, 27) != null;\n }\n get etx_eligible_slices() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 28);\n }\n set etx_eligible_slices(value) {\n pb_1.Message.setOneofWrapperField(this, 28, this.#one_of_decls[21], value);\n }\n get has_etx_eligible_slices() {\n return pb_1.Message.getField(this, 28) != null;\n }\n get prime_terminus() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 29);\n }\n set prime_terminus(value) {\n pb_1.Message.setOneofWrapperField(this, 29, this.#one_of_decls[22], value);\n }\n get has_prime_terminus() {\n return pb_1.Message.getField(this, 29) != null;\n }\n get interlink_root_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 30);\n }\n set interlink_root_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 30, this.#one_of_decls[23], value);\n }\n get has_interlink_root_hash() {\n return pb_1.Message.getField(this, 30) != null;\n }\n get _uncle_hash() {\n const cases = {\n 0: \"none\",\n 2: \"uncle_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _coinbase() {\n const cases = {\n 0: \"none\",\n 3: \"coinbase\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n get _evm_root() {\n const cases = {\n 0: \"none\",\n 4: \"evm_root\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [4])];\n }\n get _tx_hash() {\n const cases = {\n 0: \"none\",\n 5: \"tx_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [5])];\n }\n get _etx_hash() {\n const cases = {\n 0: \"none\",\n 6: \"etx_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [6])];\n }\n get _etx_rollup_hash() {\n const cases = {\n 0: \"none\",\n 7: \"etx_rollup_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [7])];\n }\n get _receipt_hash() {\n const cases = {\n 0: \"none\",\n 9: \"receipt_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [9])];\n }\n get _difficulty() {\n const cases = {\n 0: \"none\",\n 10: \"difficulty\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [10])];\n }\n get _uncled_s() {\n const cases = {\n 0: \"none\",\n 14: \"uncled_s\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [14])];\n }\n get _gas_limit() {\n const cases = {\n 0: \"none\",\n 16: \"gas_limit\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [16])];\n }\n get _gas_used() {\n const cases = {\n 0: \"none\",\n 17: \"gas_used\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [17])];\n }\n get _base_fee() {\n const cases = {\n 0: \"none\",\n 18: \"base_fee\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [18])];\n }\n get _location() {\n const cases = {\n 0: \"none\",\n 19: \"location\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [19])];\n }\n get _extra() {\n const cases = {\n 0: \"none\",\n 20: \"extra\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [20])];\n }\n get _mix_hash() {\n const cases = {\n 0: \"none\",\n 21: \"mix_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [21])];\n }\n get _nonce() {\n const cases = {\n 0: \"none\",\n 22: \"nonce\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [22])];\n }\n get _utxo_root() {\n const cases = {\n 0: \"none\",\n 23: \"utxo_root\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [23])];\n }\n get _etx_set_hash() {\n const cases = {\n 0: \"none\",\n 24: \"etx_set_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [24])];\n }\n get _efficiency_score() {\n const cases = {\n 0: \"none\",\n 25: \"efficiency_score\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [25])];\n }\n get _threshold_count() {\n const cases = {\n 0: \"none\",\n 26: \"threshold_count\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [26])];\n }\n get _expansion_number() {\n const cases = {\n 0: \"none\",\n 27: \"expansion_number\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [27])];\n }\n get _etx_eligible_slices() {\n const cases = {\n 0: \"none\",\n 28: \"etx_eligible_slices\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [28])];\n }\n get _prime_terminus() {\n const cases = {\n 0: \"none\",\n 29: \"prime_terminus\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [29])];\n }\n get _interlink_root_hash() {\n const cases = {\n 0: \"none\",\n 30: \"interlink_root_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [30])];\n }\n static fromObject(data) {\n const message = new ProtoHeader({});\n if (data.parent_hash != null) {\n message.parent_hash = data.parent_hash.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n if (data.uncle_hash != null) {\n message.uncle_hash = dependency_1.common.ProtoHash.fromObject(data.uncle_hash);\n }\n if (data.coinbase != null) {\n message.coinbase = data.coinbase;\n }\n if (data.evm_root != null) {\n message.evm_root = dependency_1.common.ProtoHash.fromObject(data.evm_root);\n }\n if (data.tx_hash != null) {\n message.tx_hash = dependency_1.common.ProtoHash.fromObject(data.tx_hash);\n }\n if (data.etx_hash != null) {\n message.etx_hash = dependency_1.common.ProtoHash.fromObject(data.etx_hash);\n }\n if (data.etx_rollup_hash != null) {\n message.etx_rollup_hash = dependency_1.common.ProtoHash.fromObject(data.etx_rollup_hash);\n }\n if (data.manifest_hash != null) {\n message.manifest_hash = data.manifest_hash.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n if (data.receipt_hash != null) {\n message.receipt_hash = dependency_1.common.ProtoHash.fromObject(data.receipt_hash);\n }\n if (data.difficulty != null) {\n message.difficulty = data.difficulty;\n }\n if (data.parent_entropy != null) {\n message.parent_entropy = data.parent_entropy;\n }\n if (data.parent_delta_s != null) {\n message.parent_delta_s = data.parent_delta_s;\n }\n if (data.parent_uncled_sub_delta_s != null) {\n message.parent_uncled_sub_delta_s = data.parent_uncled_sub_delta_s;\n }\n if (data.uncled_s != null) {\n message.uncled_s = data.uncled_s;\n }\n if (data.number != null) {\n message.number = data.number;\n }\n if (data.gas_limit != null) {\n message.gas_limit = data.gas_limit;\n }\n if (data.gas_used != null) {\n message.gas_used = data.gas_used;\n }\n if (data.base_fee != null) {\n message.base_fee = data.base_fee;\n }\n if (data.location != null) {\n message.location = dependency_1.common.ProtoLocation.fromObject(data.location);\n }\n if (data.extra != null) {\n message.extra = data.extra;\n }\n if (data.mix_hash != null) {\n message.mix_hash = dependency_1.common.ProtoHash.fromObject(data.mix_hash);\n }\n if (data.nonce != null) {\n message.nonce = data.nonce;\n }\n if (data.utxo_root != null) {\n message.utxo_root = dependency_1.common.ProtoHash.fromObject(data.utxo_root);\n }\n if (data.etx_set_hash != null) {\n message.etx_set_hash = dependency_1.common.ProtoHash.fromObject(data.etx_set_hash);\n }\n if (data.efficiency_score != null) {\n message.efficiency_score = data.efficiency_score;\n }\n if (data.threshold_count != null) {\n message.threshold_count = data.threshold_count;\n }\n if (data.expansion_number != null) {\n message.expansion_number = data.expansion_number;\n }\n if (data.etx_eligible_slices != null) {\n message.etx_eligible_slices = dependency_1.common.ProtoHash.fromObject(data.etx_eligible_slices);\n }\n if (data.prime_terminus != null) {\n message.prime_terminus = dependency_1.common.ProtoHash.fromObject(data.prime_terminus);\n }\n if (data.interlink_root_hash != null) {\n message.interlink_root_hash = dependency_1.common.ProtoHash.fromObject(data.interlink_root_hash);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.parent_hash != null) {\n data.parent_hash = this.parent_hash.map((item) => item.toObject());\n }\n if (this.uncle_hash != null) {\n data.uncle_hash = this.uncle_hash.toObject();\n }\n if (this.coinbase != null) {\n data.coinbase = this.coinbase;\n }\n if (this.evm_root != null) {\n data.evm_root = this.evm_root.toObject();\n }\n if (this.tx_hash != null) {\n data.tx_hash = this.tx_hash.toObject();\n }\n if (this.etx_hash != null) {\n data.etx_hash = this.etx_hash.toObject();\n }\n if (this.etx_rollup_hash != null) {\n data.etx_rollup_hash = this.etx_rollup_hash.toObject();\n }\n if (this.manifest_hash != null) {\n data.manifest_hash = this.manifest_hash.map((item) => item.toObject());\n }\n if (this.receipt_hash != null) {\n data.receipt_hash = this.receipt_hash.toObject();\n }\n if (this.difficulty != null) {\n data.difficulty = this.difficulty;\n }\n if (this.parent_entropy != null) {\n data.parent_entropy = this.parent_entropy;\n }\n if (this.parent_delta_s != null) {\n data.parent_delta_s = this.parent_delta_s;\n }\n if (this.parent_uncled_sub_delta_s != null) {\n data.parent_uncled_sub_delta_s = this.parent_uncled_sub_delta_s;\n }\n if (this.uncled_s != null) {\n data.uncled_s = this.uncled_s;\n }\n if (this.number != null) {\n data.number = this.number;\n }\n if (this.gas_limit != null) {\n data.gas_limit = this.gas_limit;\n }\n if (this.gas_used != null) {\n data.gas_used = this.gas_used;\n }\n if (this.base_fee != null) {\n data.base_fee = this.base_fee;\n }\n if (this.location != null) {\n data.location = this.location.toObject();\n }\n if (this.extra != null) {\n data.extra = this.extra;\n }\n if (this.mix_hash != null) {\n data.mix_hash = this.mix_hash.toObject();\n }\n if (this.nonce != null) {\n data.nonce = this.nonce;\n }\n if (this.utxo_root != null) {\n data.utxo_root = this.utxo_root.toObject();\n }\n if (this.etx_set_hash != null) {\n data.etx_set_hash = this.etx_set_hash.toObject();\n }\n if (this.efficiency_score != null) {\n data.efficiency_score = this.efficiency_score;\n }\n if (this.threshold_count != null) {\n data.threshold_count = this.threshold_count;\n }\n if (this.expansion_number != null) {\n data.expansion_number = this.expansion_number;\n }\n if (this.etx_eligible_slices != null) {\n data.etx_eligible_slices = this.etx_eligible_slices.toObject();\n }\n if (this.prime_terminus != null) {\n data.prime_terminus = this.prime_terminus.toObject();\n }\n if (this.interlink_root_hash != null) {\n data.interlink_root_hash = this.interlink_root_hash.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.parent_hash.length)\n writer.writeRepeatedMessage(1, this.parent_hash, (item) => item.serialize(writer));\n if (this.has_uncle_hash)\n writer.writeMessage(2, this.uncle_hash, () => this.uncle_hash.serialize(writer));\n if (this.has_coinbase)\n writer.writeBytes(3, this.coinbase);\n if (this.has_evm_root)\n writer.writeMessage(4, this.evm_root, () => this.evm_root.serialize(writer));\n if (this.has_tx_hash)\n writer.writeMessage(5, this.tx_hash, () => this.tx_hash.serialize(writer));\n if (this.has_etx_hash)\n writer.writeMessage(6, this.etx_hash, () => this.etx_hash.serialize(writer));\n if (this.has_etx_rollup_hash)\n writer.writeMessage(7, this.etx_rollup_hash, () => this.etx_rollup_hash.serialize(writer));\n if (this.manifest_hash.length)\n writer.writeRepeatedMessage(8, this.manifest_hash, (item) => item.serialize(writer));\n if (this.has_receipt_hash)\n writer.writeMessage(9, this.receipt_hash, () => this.receipt_hash.serialize(writer));\n if (this.has_difficulty)\n writer.writeBytes(10, this.difficulty);\n if (this.parent_entropy.length)\n writer.writeRepeatedBytes(11, this.parent_entropy);\n if (this.parent_delta_s.length)\n writer.writeRepeatedBytes(12, this.parent_delta_s);\n if (this.parent_uncled_sub_delta_s.length)\n writer.writeRepeatedBytes(13, this.parent_uncled_sub_delta_s);\n if (this.has_uncled_s)\n writer.writeBytes(14, this.uncled_s);\n if (this.number.length)\n writer.writeRepeatedBytes(15, this.number);\n if (this.has_gas_limit)\n writer.writeUint64(16, this.gas_limit);\n if (this.has_gas_used)\n writer.writeUint64(17, this.gas_used);\n if (this.has_base_fee)\n writer.writeBytes(18, this.base_fee);\n if (this.has_location)\n writer.writeMessage(19, this.location, () => this.location.serialize(writer));\n if (this.has_extra)\n writer.writeBytes(20, this.extra);\n if (this.has_mix_hash)\n writer.writeMessage(21, this.mix_hash, () => this.mix_hash.serialize(writer));\n if (this.has_nonce)\n writer.writeUint64(22, this.nonce);\n if (this.has_utxo_root)\n writer.writeMessage(23, this.utxo_root, () => this.utxo_root.serialize(writer));\n if (this.has_etx_set_hash)\n writer.writeMessage(24, this.etx_set_hash, () => this.etx_set_hash.serialize(writer));\n if (this.has_efficiency_score)\n writer.writeUint64(25, this.efficiency_score);\n if (this.has_threshold_count)\n writer.writeUint64(26, this.threshold_count);\n if (this.has_expansion_number)\n writer.writeUint64(27, this.expansion_number);\n if (this.has_etx_eligible_slices)\n writer.writeMessage(28, this.etx_eligible_slices, () => this.etx_eligible_slices.serialize(writer));\n if (this.has_prime_terminus)\n writer.writeMessage(29, this.prime_terminus, () => this.prime_terminus.serialize(writer));\n if (this.has_interlink_root_hash)\n writer.writeMessage(30, this.interlink_root_hash, () => this.interlink_root_hash.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHeader();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.parent_hash, () => pb_1.Message.addToRepeatedWrapperField(message, 1, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n case 2:\n reader.readMessage(message.uncle_hash, () => message.uncle_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 3:\n message.coinbase = reader.readBytes();\n break;\n case 4:\n reader.readMessage(message.evm_root, () => message.evm_root = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 5:\n reader.readMessage(message.tx_hash, () => message.tx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 6:\n reader.readMessage(message.etx_hash, () => message.etx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 7:\n reader.readMessage(message.etx_rollup_hash, () => message.etx_rollup_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 8:\n reader.readMessage(message.manifest_hash, () => pb_1.Message.addToRepeatedWrapperField(message, 8, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n case 9:\n reader.readMessage(message.receipt_hash, () => message.receipt_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 10:\n message.difficulty = reader.readBytes();\n break;\n case 11:\n pb_1.Message.addToRepeatedField(message, 11, reader.readBytes());\n break;\n case 12:\n pb_1.Message.addToRepeatedField(message, 12, reader.readBytes());\n break;\n case 13:\n pb_1.Message.addToRepeatedField(message, 13, reader.readBytes());\n break;\n case 14:\n message.uncled_s = reader.readBytes();\n break;\n case 15:\n pb_1.Message.addToRepeatedField(message, 15, reader.readBytes());\n break;\n case 16:\n message.gas_limit = reader.readUint64();\n break;\n case 17:\n message.gas_used = reader.readUint64();\n break;\n case 18:\n message.base_fee = reader.readBytes();\n break;\n case 19:\n reader.readMessage(message.location, () => message.location = dependency_1.common.ProtoLocation.deserialize(reader));\n break;\n case 20:\n message.extra = reader.readBytes();\n break;\n case 21:\n reader.readMessage(message.mix_hash, () => message.mix_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 22:\n message.nonce = reader.readUint64();\n break;\n case 23:\n reader.readMessage(message.utxo_root, () => message.utxo_root = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 24:\n reader.readMessage(message.etx_set_hash, () => message.etx_set_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 25:\n message.efficiency_score = reader.readUint64();\n break;\n case 26:\n message.threshold_count = reader.readUint64();\n break;\n case 27:\n message.expansion_number = reader.readUint64();\n break;\n case 28:\n reader.readMessage(message.etx_eligible_slices, () => message.etx_eligible_slices = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 29:\n reader.readMessage(message.prime_terminus, () => message.prime_terminus = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 30:\n reader.readMessage(message.interlink_root_hash, () => message.interlink_root_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoHeader.deserialize(bytes);\n }\n }\n block.ProtoHeader = ProtoHeader;\n class ProtoTransaction extends pb_1.Message {\n #one_of_decls = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"type\" in data && data.type != undefined) {\n this.type = data.type;\n }\n if (\"to\" in data && data.to != undefined) {\n this.to = data.to;\n }\n if (\"nonce\" in data && data.nonce != undefined) {\n this.nonce = data.nonce;\n }\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n if (\"gas\" in data && data.gas != undefined) {\n this.gas = data.gas;\n }\n if (\"data\" in data && data.data != undefined) {\n this.data = data.data;\n }\n if (\"chain_id\" in data && data.chain_id != undefined) {\n this.chain_id = data.chain_id;\n }\n if (\"gas_fee_cap\" in data && data.gas_fee_cap != undefined) {\n this.gas_fee_cap = data.gas_fee_cap;\n }\n if (\"gas_tip_cap\" in data && data.gas_tip_cap != undefined) {\n this.gas_tip_cap = data.gas_tip_cap;\n }\n if (\"access_list\" in data && data.access_list != undefined) {\n this.access_list = data.access_list;\n }\n if (\"v\" in data && data.v != undefined) {\n this.v = data.v;\n }\n if (\"r\" in data && data.r != undefined) {\n this.r = data.r;\n }\n if (\"s\" in data && data.s != undefined) {\n this.s = data.s;\n }\n if (\"originating_tx_hash\" in data && data.originating_tx_hash != undefined) {\n this.originating_tx_hash = data.originating_tx_hash;\n }\n if (\"etx_index\" in data && data.etx_index != undefined) {\n this.etx_index = data.etx_index;\n }\n if (\"tx_ins\" in data && data.tx_ins != undefined) {\n this.tx_ins = data.tx_ins;\n }\n if (\"tx_outs\" in data && data.tx_outs != undefined) {\n this.tx_outs = data.tx_outs;\n }\n if (\"signature\" in data && data.signature != undefined) {\n this.signature = data.signature;\n }\n if (\"etx_sender\" in data && data.etx_sender != undefined) {\n this.etx_sender = data.etx_sender;\n }\n }\n }\n get type() {\n return pb_1.Message.getFieldWithDefault(this, 1, 0);\n }\n set type(value) {\n pb_1.Message.setOneofField(this, 1, this.#one_of_decls[0], value);\n }\n get has_type() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get to() {\n return pb_1.Message.getFieldWithDefault(this, 2, new Uint8Array(0));\n }\n set to(value) {\n pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value);\n }\n get has_to() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get nonce() {\n return pb_1.Message.getFieldWithDefault(this, 3, 0);\n }\n set nonce(value) {\n pb_1.Message.setOneofField(this, 3, this.#one_of_decls[2], value);\n }\n get has_nonce() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 4, new Uint8Array(0));\n }\n set value(value) {\n pb_1.Message.setOneofField(this, 4, this.#one_of_decls[3], value);\n }\n get has_value() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get gas() {\n return pb_1.Message.getFieldWithDefault(this, 5, 0);\n }\n set gas(value) {\n pb_1.Message.setOneofField(this, 5, this.#one_of_decls[4], value);\n }\n get has_gas() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get data() {\n return pb_1.Message.getFieldWithDefault(this, 6, new Uint8Array(0));\n }\n set data(value) {\n pb_1.Message.setOneofField(this, 6, this.#one_of_decls[5], value);\n }\n get has_data() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get chain_id() {\n return pb_1.Message.getFieldWithDefault(this, 7, new Uint8Array(0));\n }\n set chain_id(value) {\n pb_1.Message.setOneofField(this, 7, this.#one_of_decls[6], value);\n }\n get has_chain_id() {\n return pb_1.Message.getField(this, 7) != null;\n }\n get gas_fee_cap() {\n return pb_1.Message.getFieldWithDefault(this, 8, new Uint8Array(0));\n }\n set gas_fee_cap(value) {\n pb_1.Message.setOneofField(this, 8, this.#one_of_decls[7], value);\n }\n get has_gas_fee_cap() {\n return pb_1.Message.getField(this, 8) != null;\n }\n get gas_tip_cap() {\n return pb_1.Message.getFieldWithDefault(this, 9, new Uint8Array(0));\n }\n set gas_tip_cap(value) {\n pb_1.Message.setOneofField(this, 9, this.#one_of_decls[8], value);\n }\n get has_gas_tip_cap() {\n return pb_1.Message.getField(this, 9) != null;\n }\n get access_list() {\n return pb_1.Message.getWrapperField(this, ProtoAccessList, 10);\n }\n set access_list(value) {\n pb_1.Message.setOneofWrapperField(this, 10, this.#one_of_decls[9], value);\n }\n get has_access_list() {\n return pb_1.Message.getField(this, 10) != null;\n }\n get v() {\n return pb_1.Message.getFieldWithDefault(this, 11, new Uint8Array(0));\n }\n set v(value) {\n pb_1.Message.setOneofField(this, 11, this.#one_of_decls[10], value);\n }\n get has_v() {\n return pb_1.Message.getField(this, 11) != null;\n }\n get r() {\n return pb_1.Message.getFieldWithDefault(this, 12, new Uint8Array(0));\n }\n set r(value) {\n pb_1.Message.setOneofField(this, 12, this.#one_of_decls[11], value);\n }\n get has_r() {\n return pb_1.Message.getField(this, 12) != null;\n }\n get s() {\n return pb_1.Message.getFieldWithDefault(this, 13, new Uint8Array(0));\n }\n set s(value) {\n pb_1.Message.setOneofField(this, 13, this.#one_of_decls[12], value);\n }\n get has_s() {\n return pb_1.Message.getField(this, 13) != null;\n }\n get originating_tx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 14);\n }\n set originating_tx_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 14, this.#one_of_decls[13], value);\n }\n get has_originating_tx_hash() {\n return pb_1.Message.getField(this, 14) != null;\n }\n get etx_index() {\n return pb_1.Message.getFieldWithDefault(this, 15, 0);\n }\n set etx_index(value) {\n pb_1.Message.setOneofField(this, 15, this.#one_of_decls[14], value);\n }\n get has_etx_index() {\n return pb_1.Message.getField(this, 15) != null;\n }\n get tx_ins() {\n return pb_1.Message.getWrapperField(this, ProtoTxIns, 16);\n }\n set tx_ins(value) {\n pb_1.Message.setOneofWrapperField(this, 16, this.#one_of_decls[15], value);\n }\n get has_tx_ins() {\n return pb_1.Message.getField(this, 16) != null;\n }\n get tx_outs() {\n return pb_1.Message.getWrapperField(this, ProtoTxOuts, 17);\n }\n set tx_outs(value) {\n pb_1.Message.setOneofWrapperField(this, 17, this.#one_of_decls[16], value);\n }\n get has_tx_outs() {\n return pb_1.Message.getField(this, 17) != null;\n }\n get signature() {\n return pb_1.Message.getFieldWithDefault(this, 18, new Uint8Array(0));\n }\n set signature(value) {\n pb_1.Message.setOneofField(this, 18, this.#one_of_decls[17], value);\n }\n get has_signature() {\n return pb_1.Message.getField(this, 18) != null;\n }\n get etx_sender() {\n return pb_1.Message.getFieldWithDefault(this, 19, new Uint8Array(0));\n }\n set etx_sender(value) {\n pb_1.Message.setOneofField(this, 19, this.#one_of_decls[18], value);\n }\n get has_etx_sender() {\n return pb_1.Message.getField(this, 19) != null;\n }\n get _type() {\n const cases = {\n 0: \"none\",\n 1: \"type\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _to() {\n const cases = {\n 0: \"none\",\n 2: \"to\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _nonce() {\n const cases = {\n 0: \"none\",\n 3: \"nonce\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n get _value() {\n const cases = {\n 0: \"none\",\n 4: \"value\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [4])];\n }\n get _gas() {\n const cases = {\n 0: \"none\",\n 5: \"gas\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [5])];\n }\n get _data() {\n const cases = {\n 0: \"none\",\n 6: \"data\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [6])];\n }\n get _chain_id() {\n const cases = {\n 0: \"none\",\n 7: \"chain_id\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [7])];\n }\n get _gas_fee_cap() {\n const cases = {\n 0: \"none\",\n 8: \"gas_fee_cap\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [8])];\n }\n get _gas_tip_cap() {\n const cases = {\n 0: \"none\",\n 9: \"gas_tip_cap\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [9])];\n }\n get _access_list() {\n const cases = {\n 0: \"none\",\n 10: \"access_list\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [10])];\n }\n get _v() {\n const cases = {\n 0: \"none\",\n 11: \"v\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [11])];\n }\n get _r() {\n const cases = {\n 0: \"none\",\n 12: \"r\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [12])];\n }\n get _s() {\n const cases = {\n 0: \"none\",\n 13: \"s\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [13])];\n }\n get _originating_tx_hash() {\n const cases = {\n 0: \"none\",\n 14: \"originating_tx_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [14])];\n }\n get _etx_index() {\n const cases = {\n 0: \"none\",\n 15: \"etx_index\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [15])];\n }\n get _tx_ins() {\n const cases = {\n 0: \"none\",\n 16: \"tx_ins\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [16])];\n }\n get _tx_outs() {\n const cases = {\n 0: \"none\",\n 17: \"tx_outs\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [17])];\n }\n get _signature() {\n const cases = {\n 0: \"none\",\n 18: \"signature\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [18])];\n }\n get _etx_sender() {\n const cases = {\n 0: \"none\",\n 19: \"etx_sender\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [19])];\n }\n static fromObject(data) {\n const message = new ProtoTransaction({});\n if (data.type != null) {\n message.type = data.type;\n }\n if (data.to != null) {\n message.to = data.to;\n }\n if (data.nonce != null) {\n message.nonce = data.nonce;\n }\n if (data.value != null) {\n message.value = data.value;\n }\n if (data.gas != null) {\n message.gas = data.gas;\n }\n if (data.data != null) {\n message.data = data.data;\n }\n if (data.chain_id != null) {\n message.chain_id = data.chain_id;\n }\n if (data.gas_fee_cap != null) {\n message.gas_fee_cap = data.gas_fee_cap;\n }\n if (data.gas_tip_cap != null) {\n message.gas_tip_cap = data.gas_tip_cap;\n }\n if (data.access_list != null) {\n message.access_list = ProtoAccessList.fromObject(data.access_list);\n }\n if (data.v != null) {\n message.v = data.v;\n }\n if (data.r != null) {\n message.r = data.r;\n }\n if (data.s != null) {\n message.s = data.s;\n }\n if (data.originating_tx_hash != null) {\n message.originating_tx_hash = dependency_1.common.ProtoHash.fromObject(data.originating_tx_hash);\n }\n if (data.etx_index != null) {\n message.etx_index = data.etx_index;\n }\n if (data.tx_ins != null) {\n message.tx_ins = ProtoTxIns.fromObject(data.tx_ins);\n }\n if (data.tx_outs != null) {\n message.tx_outs = ProtoTxOuts.fromObject(data.tx_outs);\n }\n if (data.signature != null) {\n message.signature = data.signature;\n }\n if (data.etx_sender != null) {\n message.etx_sender = data.etx_sender;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.type != null) {\n data.type = this.type;\n }\n if (this.to != null) {\n data.to = this.to;\n }\n if (this.nonce != null) {\n data.nonce = this.nonce;\n }\n if (this.value != null) {\n data.value = this.value;\n }\n if (this.gas != null) {\n data.gas = this.gas;\n }\n if (this.data != null) {\n data.data = this.data;\n }\n if (this.chain_id != null) {\n data.chain_id = this.chain_id;\n }\n if (this.gas_fee_cap != null) {\n data.gas_fee_cap = this.gas_fee_cap;\n }\n if (this.gas_tip_cap != null) {\n data.gas_tip_cap = this.gas_tip_cap;\n }\n if (this.access_list != null) {\n data.access_list = this.access_list.toObject();\n }\n if (this.v != null) {\n data.v = this.v;\n }\n if (this.r != null) {\n data.r = this.r;\n }\n if (this.s != null) {\n data.s = this.s;\n }\n if (this.originating_tx_hash != null) {\n data.originating_tx_hash = this.originating_tx_hash.toObject();\n }\n if (this.etx_index != null) {\n data.etx_index = this.etx_index;\n }\n if (this.tx_ins != null) {\n data.tx_ins = this.tx_ins.toObject();\n }\n if (this.tx_outs != null) {\n data.tx_outs = this.tx_outs.toObject();\n }\n if (this.signature != null) {\n data.signature = this.signature;\n }\n if (this.etx_sender != null) {\n data.etx_sender = this.etx_sender;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_type)\n writer.writeUint64(1, this.type);\n if (this.has_to)\n writer.writeBytes(2, this.to);\n if (this.has_nonce)\n writer.writeUint64(3, this.nonce);\n if (this.has_value)\n writer.writeBytes(4, this.value);\n if (this.has_gas)\n writer.writeUint64(5, this.gas);\n if (this.has_data)\n writer.writeBytes(6, this.data);\n if (this.has_chain_id)\n writer.writeBytes(7, this.chain_id);\n if (this.has_gas_fee_cap)\n writer.writeBytes(8, this.gas_fee_cap);\n if (this.has_gas_tip_cap)\n writer.writeBytes(9, this.gas_tip_cap);\n if (this.has_access_list)\n writer.writeMessage(10, this.access_list, () => this.access_list.serialize(writer));\n if (this.has_v)\n writer.writeBytes(11, this.v);\n if (this.has_r)\n writer.writeBytes(12, this.r);\n if (this.has_s)\n writer.writeBytes(13, this.s);\n if (this.has_originating_tx_hash)\n writer.writeMessage(14, this.originating_tx_hash, () => this.originating_tx_hash.serialize(writer));\n if (this.has_etx_index)\n writer.writeUint32(15, this.etx_index);\n if (this.has_tx_ins)\n writer.writeMessage(16, this.tx_ins, () => this.tx_ins.serialize(writer));\n if (this.has_tx_outs)\n writer.writeMessage(17, this.tx_outs, () => this.tx_outs.serialize(writer));\n if (this.has_signature)\n writer.writeBytes(18, this.signature);\n if (this.has_etx_sender)\n writer.writeBytes(19, this.etx_sender);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTransaction();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.type = reader.readUint64();\n break;\n case 2:\n message.to = reader.readBytes();\n break;\n case 3:\n message.nonce = reader.readUint64();\n break;\n case 4:\n message.value = reader.readBytes();\n break;\n case 5:\n message.gas = reader.readUint64();\n break;\n case 6:\n message.data = reader.readBytes();\n break;\n case 7:\n message.chain_id = reader.readBytes();\n break;\n case 8:\n message.gas_fee_cap = reader.readBytes();\n break;\n case 9:\n message.gas_tip_cap = reader.readBytes();\n break;\n case 10:\n reader.readMessage(message.access_list, () => message.access_list = ProtoAccessList.deserialize(reader));\n break;\n case 11:\n message.v = reader.readBytes();\n break;\n case 12:\n message.r = reader.readBytes();\n break;\n case 13:\n message.s = reader.readBytes();\n break;\n case 14:\n reader.readMessage(message.originating_tx_hash, () => message.originating_tx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 15:\n message.etx_index = reader.readUint32();\n break;\n case 16:\n reader.readMessage(message.tx_ins, () => message.tx_ins = ProtoTxIns.deserialize(reader));\n break;\n case 17:\n reader.readMessage(message.tx_outs, () => message.tx_outs = ProtoTxOuts.deserialize(reader));\n break;\n case 18:\n message.signature = reader.readBytes();\n break;\n case 19:\n message.etx_sender = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTransaction.deserialize(bytes);\n }\n }\n block.ProtoTransaction = ProtoTransaction;\n class ProtoTransactions extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"transactions\" in data && data.transactions != undefined) {\n this.transactions = data.transactions;\n }\n }\n }\n get transactions() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoTransaction, 1);\n }\n set transactions(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoTransactions({});\n if (data.transactions != null) {\n message.transactions = data.transactions.map(item => ProtoTransaction.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.transactions != null) {\n data.transactions = this.transactions.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.transactions.length)\n writer.writeRepeatedMessage(1, this.transactions, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTransactions();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.transactions, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoTransaction.deserialize(reader), ProtoTransaction));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTransactions.deserialize(bytes);\n }\n }\n block.ProtoTransactions = ProtoTransactions;\n class ProtoHeaders extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"headers\" in data && data.headers != undefined) {\n this.headers = data.headers;\n }\n }\n }\n get headers() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoHeader, 1);\n }\n set headers(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoHeaders({});\n if (data.headers != null) {\n message.headers = data.headers.map(item => ProtoHeader.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.headers != null) {\n data.headers = this.headers.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.headers.length)\n writer.writeRepeatedMessage(1, this.headers, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHeaders();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.headers, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoHeader.deserialize(reader), ProtoHeader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoHeaders.deserialize(bytes);\n }\n }\n block.ProtoHeaders = ProtoHeaders;\n class ProtoManifest extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"manifest\" in data && data.manifest != undefined) {\n this.manifest = data.manifest;\n }\n }\n }\n get manifest() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set manifest(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoManifest({});\n if (data.manifest != null) {\n message.manifest = data.manifest.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.manifest != null) {\n data.manifest = this.manifest.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.manifest.length)\n writer.writeRepeatedMessage(1, this.manifest, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoManifest();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.manifest, () => pb_1.Message.addToRepeatedWrapperField(message, 1, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoManifest.deserialize(bytes);\n }\n }\n block.ProtoManifest = ProtoManifest;\n class ProtoAccessList extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"access_tuples\" in data && data.access_tuples != undefined) {\n this.access_tuples = data.access_tuples;\n }\n }\n }\n get access_tuples() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoAccessTuple, 1);\n }\n set access_tuples(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoAccessList({});\n if (data.access_tuples != null) {\n message.access_tuples = data.access_tuples.map(item => ProtoAccessTuple.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.access_tuples != null) {\n data.access_tuples = this.access_tuples.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.access_tuples.length)\n writer.writeRepeatedMessage(1, this.access_tuples, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoAccessList();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.access_tuples, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoAccessTuple.deserialize(reader), ProtoAccessTuple));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoAccessList.deserialize(bytes);\n }\n }\n block.ProtoAccessList = ProtoAccessList;\n class ProtoWorkObjectHeader extends pb_1.Message {\n #one_of_decls = [[1], [2], [3], [4], [5], [6], [7], [8], [9]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"header_hash\" in data && data.header_hash != undefined) {\n this.header_hash = data.header_hash;\n }\n if (\"parent_hash\" in data && data.parent_hash != undefined) {\n this.parent_hash = data.parent_hash;\n }\n if (\"number\" in data && data.number != undefined) {\n this.number = data.number;\n }\n if (\"difficulty\" in data && data.difficulty != undefined) {\n this.difficulty = data.difficulty;\n }\n if (\"tx_hash\" in data && data.tx_hash != undefined) {\n this.tx_hash = data.tx_hash;\n }\n if (\"nonce\" in data && data.nonce != undefined) {\n this.nonce = data.nonce;\n }\n if (\"location\" in data && data.location != undefined) {\n this.location = data.location;\n }\n if (\"mix_hash\" in data && data.mix_hash != undefined) {\n this.mix_hash = data.mix_hash;\n }\n if (\"time\" in data && data.time != undefined) {\n this.time = data.time;\n }\n }\n }\n get header_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set header_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_header_hash() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get parent_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set parent_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_parent_hash() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get number() {\n return pb_1.Message.getFieldWithDefault(this, 3, new Uint8Array(0));\n }\n set number(value) {\n pb_1.Message.setOneofField(this, 3, this.#one_of_decls[2], value);\n }\n get has_number() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get difficulty() {\n return pb_1.Message.getFieldWithDefault(this, 4, new Uint8Array(0));\n }\n set difficulty(value) {\n pb_1.Message.setOneofField(this, 4, this.#one_of_decls[3], value);\n }\n get has_difficulty() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get tx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 5);\n }\n set tx_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 5, this.#one_of_decls[4], value);\n }\n get has_tx_hash() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get nonce() {\n return pb_1.Message.getFieldWithDefault(this, 6, 0);\n }\n set nonce(value) {\n pb_1.Message.setOneofField(this, 6, this.#one_of_decls[5], value);\n }\n get has_nonce() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get location() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoLocation, 7);\n }\n set location(value) {\n pb_1.Message.setOneofWrapperField(this, 7, this.#one_of_decls[6], value);\n }\n get has_location() {\n return pb_1.Message.getField(this, 7) != null;\n }\n get mix_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 8);\n }\n set mix_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 8, this.#one_of_decls[7], value);\n }\n get has_mix_hash() {\n return pb_1.Message.getField(this, 8) != null;\n }\n get time() {\n return pb_1.Message.getFieldWithDefault(this, 9, 0);\n }\n set time(value) {\n pb_1.Message.setOneofField(this, 9, this.#one_of_decls[8], value);\n }\n get has_time() {\n return pb_1.Message.getField(this, 9) != null;\n }\n get _header_hash() {\n const cases = {\n 0: \"none\",\n 1: \"header_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _parent_hash() {\n const cases = {\n 0: \"none\",\n 2: \"parent_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _number() {\n const cases = {\n 0: \"none\",\n 3: \"number\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n get _difficulty() {\n const cases = {\n 0: \"none\",\n 4: \"difficulty\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [4])];\n }\n get _tx_hash() {\n const cases = {\n 0: \"none\",\n 5: \"tx_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [5])];\n }\n get _nonce() {\n const cases = {\n 0: \"none\",\n 6: \"nonce\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [6])];\n }\n get _location() {\n const cases = {\n 0: \"none\",\n 7: \"location\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [7])];\n }\n get _mix_hash() {\n const cases = {\n 0: \"none\",\n 8: \"mix_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [8])];\n }\n get _time() {\n const cases = {\n 0: \"none\",\n 9: \"time\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [9])];\n }\n static fromObject(data) {\n const message = new ProtoWorkObjectHeader({});\n if (data.header_hash != null) {\n message.header_hash = dependency_1.common.ProtoHash.fromObject(data.header_hash);\n }\n if (data.parent_hash != null) {\n message.parent_hash = dependency_1.common.ProtoHash.fromObject(data.parent_hash);\n }\n if (data.number != null) {\n message.number = data.number;\n }\n if (data.difficulty != null) {\n message.difficulty = data.difficulty;\n }\n if (data.tx_hash != null) {\n message.tx_hash = dependency_1.common.ProtoHash.fromObject(data.tx_hash);\n }\n if (data.nonce != null) {\n message.nonce = data.nonce;\n }\n if (data.location != null) {\n message.location = dependency_1.common.ProtoLocation.fromObject(data.location);\n }\n if (data.mix_hash != null) {\n message.mix_hash = dependency_1.common.ProtoHash.fromObject(data.mix_hash);\n }\n if (data.time != null) {\n message.time = data.time;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.header_hash != null) {\n data.header_hash = this.header_hash.toObject();\n }\n if (this.parent_hash != null) {\n data.parent_hash = this.parent_hash.toObject();\n }\n if (this.number != null) {\n data.number = this.number;\n }\n if (this.difficulty != null) {\n data.difficulty = this.difficulty;\n }\n if (this.tx_hash != null) {\n data.tx_hash = this.tx_hash.toObject();\n }\n if (this.nonce != null) {\n data.nonce = this.nonce;\n }\n if (this.location != null) {\n data.location = this.location.toObject();\n }\n if (this.mix_hash != null) {\n data.mix_hash = this.mix_hash.toObject();\n }\n if (this.time != null) {\n data.time = this.time;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_header_hash)\n writer.writeMessage(1, this.header_hash, () => this.header_hash.serialize(writer));\n if (this.has_parent_hash)\n writer.writeMessage(2, this.parent_hash, () => this.parent_hash.serialize(writer));\n if (this.has_number)\n writer.writeBytes(3, this.number);\n if (this.has_difficulty)\n writer.writeBytes(4, this.difficulty);\n if (this.has_tx_hash)\n writer.writeMessage(5, this.tx_hash, () => this.tx_hash.serialize(writer));\n if (this.has_nonce)\n writer.writeUint64(6, this.nonce);\n if (this.has_location)\n writer.writeMessage(7, this.location, () => this.location.serialize(writer));\n if (this.has_mix_hash)\n writer.writeMessage(8, this.mix_hash, () => this.mix_hash.serialize(writer));\n if (this.has_time)\n writer.writeUint64(9, this.time);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjectHeader();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.header_hash, () => message.header_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.parent_hash, () => message.parent_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 3:\n message.number = reader.readBytes();\n break;\n case 4:\n message.difficulty = reader.readBytes();\n break;\n case 5:\n reader.readMessage(message.tx_hash, () => message.tx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 6:\n message.nonce = reader.readUint64();\n break;\n case 7:\n reader.readMessage(message.location, () => message.location = dependency_1.common.ProtoLocation.deserialize(reader));\n break;\n case 8:\n reader.readMessage(message.mix_hash, () => message.mix_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 9:\n message.time = reader.readUint64();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObjectHeader.deserialize(bytes);\n }\n }\n block.ProtoWorkObjectHeader = ProtoWorkObjectHeader;\n class ProtoWorkObjectHeaders extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"wo_headers\" in data && data.wo_headers != undefined) {\n this.wo_headers = data.wo_headers;\n }\n }\n }\n get wo_headers() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoWorkObjectHeader, 1);\n }\n set wo_headers(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoWorkObjectHeaders({});\n if (data.wo_headers != null) {\n message.wo_headers = data.wo_headers.map(item => ProtoWorkObjectHeader.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.wo_headers != null) {\n data.wo_headers = this.wo_headers.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.wo_headers.length)\n writer.writeRepeatedMessage(1, this.wo_headers, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjectHeaders();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.wo_headers, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoWorkObjectHeader.deserialize(reader), ProtoWorkObjectHeader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObjectHeaders.deserialize(bytes);\n }\n }\n block.ProtoWorkObjectHeaders = ProtoWorkObjectHeaders;\n class ProtoWorkObjectBody extends pb_1.Message {\n #one_of_decls = [[1], [2], [3], [4], [5], [6]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"header\" in data && data.header != undefined) {\n this.header = data.header;\n }\n if (\"transactions\" in data && data.transactions != undefined) {\n this.transactions = data.transactions;\n }\n if (\"uncles\" in data && data.uncles != undefined) {\n this.uncles = data.uncles;\n }\n if (\"ext_transactions\" in data && data.ext_transactions != undefined) {\n this.ext_transactions = data.ext_transactions;\n }\n if (\"manifest\" in data && data.manifest != undefined) {\n this.manifest = data.manifest;\n }\n if (\"interlink_hashes\" in data && data.interlink_hashes != undefined) {\n this.interlink_hashes = data.interlink_hashes;\n }\n }\n }\n get header() {\n return pb_1.Message.getWrapperField(this, ProtoHeader, 1);\n }\n set header(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_header() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get transactions() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 2);\n }\n set transactions(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_transactions() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get uncles() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObjectHeaders, 3);\n }\n set uncles(value) {\n pb_1.Message.setOneofWrapperField(this, 3, this.#one_of_decls[2], value);\n }\n get has_uncles() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get ext_transactions() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 4);\n }\n set ext_transactions(value) {\n pb_1.Message.setOneofWrapperField(this, 4, this.#one_of_decls[3], value);\n }\n get has_ext_transactions() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get manifest() {\n return pb_1.Message.getWrapperField(this, ProtoManifest, 5);\n }\n set manifest(value) {\n pb_1.Message.setOneofWrapperField(this, 5, this.#one_of_decls[4], value);\n }\n get has_manifest() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get interlink_hashes() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHashes, 6);\n }\n set interlink_hashes(value) {\n pb_1.Message.setOneofWrapperField(this, 6, this.#one_of_decls[5], value);\n }\n get has_interlink_hashes() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get _header() {\n const cases = {\n 0: \"none\",\n 1: \"header\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _transactions() {\n const cases = {\n 0: \"none\",\n 2: \"transactions\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _uncles() {\n const cases = {\n 0: \"none\",\n 3: \"uncles\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n get _ext_transactions() {\n const cases = {\n 0: \"none\",\n 4: \"ext_transactions\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [4])];\n }\n get _manifest() {\n const cases = {\n 0: \"none\",\n 5: \"manifest\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [5])];\n }\n get _interlink_hashes() {\n const cases = {\n 0: \"none\",\n 6: \"interlink_hashes\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [6])];\n }\n static fromObject(data) {\n const message = new ProtoWorkObjectBody({});\n if (data.header != null) {\n message.header = ProtoHeader.fromObject(data.header);\n }\n if (data.transactions != null) {\n message.transactions = ProtoTransactions.fromObject(data.transactions);\n }\n if (data.uncles != null) {\n message.uncles = ProtoWorkObjectHeaders.fromObject(data.uncles);\n }\n if (data.ext_transactions != null) {\n message.ext_transactions = ProtoTransactions.fromObject(data.ext_transactions);\n }\n if (data.manifest != null) {\n message.manifest = ProtoManifest.fromObject(data.manifest);\n }\n if (data.interlink_hashes != null) {\n message.interlink_hashes = dependency_1.common.ProtoHashes.fromObject(data.interlink_hashes);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.header != null) {\n data.header = this.header.toObject();\n }\n if (this.transactions != null) {\n data.transactions = this.transactions.toObject();\n }\n if (this.uncles != null) {\n data.uncles = this.uncles.toObject();\n }\n if (this.ext_transactions != null) {\n data.ext_transactions = this.ext_transactions.toObject();\n }\n if (this.manifest != null) {\n data.manifest = this.manifest.toObject();\n }\n if (this.interlink_hashes != null) {\n data.interlink_hashes = this.interlink_hashes.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_header)\n writer.writeMessage(1, this.header, () => this.header.serialize(writer));\n if (this.has_transactions)\n writer.writeMessage(2, this.transactions, () => this.transactions.serialize(writer));\n if (this.has_uncles)\n writer.writeMessage(3, this.uncles, () => this.uncles.serialize(writer));\n if (this.has_ext_transactions)\n writer.writeMessage(4, this.ext_transactions, () => this.ext_transactions.serialize(writer));\n if (this.has_manifest)\n writer.writeMessage(5, this.manifest, () => this.manifest.serialize(writer));\n if (this.has_interlink_hashes)\n writer.writeMessage(6, this.interlink_hashes, () => this.interlink_hashes.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjectBody();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.header, () => message.header = ProtoHeader.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.transactions, () => message.transactions = ProtoTransactions.deserialize(reader));\n break;\n case 3:\n reader.readMessage(message.uncles, () => message.uncles = ProtoWorkObjectHeaders.deserialize(reader));\n break;\n case 4:\n reader.readMessage(message.ext_transactions, () => message.ext_transactions = ProtoTransactions.deserialize(reader));\n break;\n case 5:\n reader.readMessage(message.manifest, () => message.manifest = ProtoManifest.deserialize(reader));\n break;\n case 6:\n reader.readMessage(message.interlink_hashes, () => message.interlink_hashes = dependency_1.common.ProtoHashes.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObjectBody.deserialize(bytes);\n }\n }\n block.ProtoWorkObjectBody = ProtoWorkObjectBody;\n class ProtoWorkObject extends pb_1.Message {\n #one_of_decls = [[1], [2], [3]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"wo_header\" in data && data.wo_header != undefined) {\n this.wo_header = data.wo_header;\n }\n if (\"wo_body\" in data && data.wo_body != undefined) {\n this.wo_body = data.wo_body;\n }\n if (\"tx\" in data && data.tx != undefined) {\n this.tx = data.tx;\n }\n }\n }\n get wo_header() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObjectHeader, 1);\n }\n set wo_header(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_wo_header() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get wo_body() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObjectBody, 2);\n }\n set wo_body(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_wo_body() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get tx() {\n return pb_1.Message.getWrapperField(this, ProtoTransaction, 3);\n }\n set tx(value) {\n pb_1.Message.setOneofWrapperField(this, 3, this.#one_of_decls[2], value);\n }\n get has_tx() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get _wo_header() {\n const cases = {\n 0: \"none\",\n 1: \"wo_header\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _wo_body() {\n const cases = {\n 0: \"none\",\n 2: \"wo_body\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _tx() {\n const cases = {\n 0: \"none\",\n 3: \"tx\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n static fromObject(data) {\n const message = new ProtoWorkObject({});\n if (data.wo_header != null) {\n message.wo_header = ProtoWorkObjectHeader.fromObject(data.wo_header);\n }\n if (data.wo_body != null) {\n message.wo_body = ProtoWorkObjectBody.fromObject(data.wo_body);\n }\n if (data.tx != null) {\n message.tx = ProtoTransaction.fromObject(data.tx);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.wo_header != null) {\n data.wo_header = this.wo_header.toObject();\n }\n if (this.wo_body != null) {\n data.wo_body = this.wo_body.toObject();\n }\n if (this.tx != null) {\n data.tx = this.tx.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_wo_header)\n writer.writeMessage(1, this.wo_header, () => this.wo_header.serialize(writer));\n if (this.has_wo_body)\n writer.writeMessage(2, this.wo_body, () => this.wo_body.serialize(writer));\n if (this.has_tx)\n writer.writeMessage(3, this.tx, () => this.tx.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObject();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.wo_header, () => message.wo_header = ProtoWorkObjectHeader.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.wo_body, () => message.wo_body = ProtoWorkObjectBody.deserialize(reader));\n break;\n case 3:\n reader.readMessage(message.tx, () => message.tx = ProtoTransaction.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObject.deserialize(bytes);\n }\n }\n block.ProtoWorkObject = ProtoWorkObject;\n class ProtoWorkObjects extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"work_objects\" in data && data.work_objects != undefined) {\n this.work_objects = data.work_objects;\n }\n }\n }\n get work_objects() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoWorkObject, 1);\n }\n set work_objects(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoWorkObjects({});\n if (data.work_objects != null) {\n message.work_objects = data.work_objects.map(item => ProtoWorkObject.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.work_objects != null) {\n data.work_objects = this.work_objects.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.work_objects.length)\n writer.writeRepeatedMessage(1, this.work_objects, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjects();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.work_objects, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoWorkObject.deserialize(reader), ProtoWorkObject));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObjects.deserialize(bytes);\n }\n }\n block.ProtoWorkObjects = ProtoWorkObjects;\n class ProtoAccessTuple extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"address\" in data && data.address != undefined) {\n this.address = data.address;\n }\n if (\"storage_key\" in data && data.storage_key != undefined) {\n this.storage_key = data.storage_key;\n }\n }\n }\n get address() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set address(value) {\n pb_1.Message.setField(this, 1, value);\n }\n get storage_key() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set storage_key(value) {\n pb_1.Message.setRepeatedWrapperField(this, 2, value);\n }\n static fromObject(data) {\n const message = new ProtoAccessTuple({});\n if (data.address != null) {\n message.address = data.address;\n }\n if (data.storage_key != null) {\n message.storage_key = data.storage_key.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.address != null) {\n data.address = this.address;\n }\n if (this.storage_key != null) {\n data.storage_key = this.storage_key.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.address.length)\n writer.writeBytes(1, this.address);\n if (this.storage_key.length)\n writer.writeRepeatedMessage(2, this.storage_key, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoAccessTuple();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.address = reader.readBytes();\n break;\n case 2:\n reader.readMessage(message.storage_key, () => pb_1.Message.addToRepeatedWrapperField(message, 2, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoAccessTuple.deserialize(bytes);\n }\n }\n block.ProtoAccessTuple = ProtoAccessTuple;\n class ProtoReceiptForStorage extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"post_state_or_status\" in data && data.post_state_or_status != undefined) {\n this.post_state_or_status = data.post_state_or_status;\n }\n if (\"cumulative_gas_used\" in data && data.cumulative_gas_used != undefined) {\n this.cumulative_gas_used = data.cumulative_gas_used;\n }\n if (\"tx_hash\" in data && data.tx_hash != undefined) {\n this.tx_hash = data.tx_hash;\n }\n if (\"contract_address\" in data && data.contract_address != undefined) {\n this.contract_address = data.contract_address;\n }\n if (\"logs\" in data && data.logs != undefined) {\n this.logs = data.logs;\n }\n if (\"etxs\" in data && data.etxs != undefined) {\n this.etxs = data.etxs;\n }\n if (\"gas_used\" in data && data.gas_used != undefined) {\n this.gas_used = data.gas_used;\n }\n }\n }\n get post_state_or_status() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set post_state_or_status(value) {\n pb_1.Message.setField(this, 1, value);\n }\n get cumulative_gas_used() {\n return pb_1.Message.getFieldWithDefault(this, 2, 0);\n }\n set cumulative_gas_used(value) {\n pb_1.Message.setField(this, 2, value);\n }\n get tx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 3);\n }\n set tx_hash(value) {\n pb_1.Message.setWrapperField(this, 3, value);\n }\n get has_tx_hash() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get contract_address() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoAddress, 4);\n }\n set contract_address(value) {\n pb_1.Message.setWrapperField(this, 4, value);\n }\n get has_contract_address() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get logs() {\n return pb_1.Message.getWrapperField(this, ProtoLogsForStorage, 5);\n }\n set logs(value) {\n pb_1.Message.setWrapperField(this, 5, value);\n }\n get has_logs() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get etxs() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 6);\n }\n set etxs(value) {\n pb_1.Message.setWrapperField(this, 6, value);\n }\n get has_etxs() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get gas_used() {\n return pb_1.Message.getFieldWithDefault(this, 7, 0);\n }\n set gas_used(value) {\n pb_1.Message.setField(this, 7, value);\n }\n static fromObject(data) {\n const message = new ProtoReceiptForStorage({});\n if (data.post_state_or_status != null) {\n message.post_state_or_status = data.post_state_or_status;\n }\n if (data.cumulative_gas_used != null) {\n message.cumulative_gas_used = data.cumulative_gas_used;\n }\n if (data.tx_hash != null) {\n message.tx_hash = dependency_1.common.ProtoHash.fromObject(data.tx_hash);\n }\n if (data.contract_address != null) {\n message.contract_address = dependency_1.common.ProtoAddress.fromObject(data.contract_address);\n }\n if (data.logs != null) {\n message.logs = ProtoLogsForStorage.fromObject(data.logs);\n }\n if (data.etxs != null) {\n message.etxs = ProtoTransactions.fromObject(data.etxs);\n }\n if (data.gas_used != null) {\n message.gas_used = data.gas_used;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.post_state_or_status != null) {\n data.post_state_or_status = this.post_state_or_status;\n }\n if (this.cumulative_gas_used != null) {\n data.cumulative_gas_used = this.cumulative_gas_used;\n }\n if (this.tx_hash != null) {\n data.tx_hash = this.tx_hash.toObject();\n }\n if (this.contract_address != null) {\n data.contract_address = this.contract_address.toObject();\n }\n if (this.logs != null) {\n data.logs = this.logs.toObject();\n }\n if (this.etxs != null) {\n data.etxs = this.etxs.toObject();\n }\n if (this.gas_used != null) {\n data.gas_used = this.gas_used;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.post_state_or_status.length)\n writer.writeBytes(1, this.post_state_or_status);\n if (this.cumulative_gas_used != 0)\n writer.writeUint64(2, this.cumulative_gas_used);\n if (this.has_tx_hash)\n writer.writeMessage(3, this.tx_hash, () => this.tx_hash.serialize(writer));\n if (this.has_contract_address)\n writer.writeMessage(4, this.contract_address, () => this.contract_address.serialize(writer));\n if (this.has_logs)\n writer.writeMessage(5, this.logs, () => this.logs.serialize(writer));\n if (this.has_etxs)\n writer.writeMessage(6, this.etxs, () => this.etxs.serialize(writer));\n if (this.gas_used != 0)\n writer.writeUint64(7, this.gas_used);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoReceiptForStorage();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.post_state_or_status = reader.readBytes();\n break;\n case 2:\n message.cumulative_gas_used = reader.readUint64();\n break;\n case 3:\n reader.readMessage(message.tx_hash, () => message.tx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 4:\n reader.readMessage(message.contract_address, () => message.contract_address = dependency_1.common.ProtoAddress.deserialize(reader));\n break;\n case 5:\n reader.readMessage(message.logs, () => message.logs = ProtoLogsForStorage.deserialize(reader));\n break;\n case 6:\n reader.readMessage(message.etxs, () => message.etxs = ProtoTransactions.deserialize(reader));\n break;\n case 7:\n message.gas_used = reader.readUint64();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoReceiptForStorage.deserialize(bytes);\n }\n }\n block.ProtoReceiptForStorage = ProtoReceiptForStorage;\n class ProtoReceiptsForStorage extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"receipts\" in data && data.receipts != undefined) {\n this.receipts = data.receipts;\n }\n }\n }\n get receipts() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoReceiptForStorage, 1);\n }\n set receipts(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoReceiptsForStorage({});\n if (data.receipts != null) {\n message.receipts = data.receipts.map(item => ProtoReceiptForStorage.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.receipts != null) {\n data.receipts = this.receipts.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.receipts.length)\n writer.writeRepeatedMessage(1, this.receipts, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoReceiptsForStorage();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.receipts, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoReceiptForStorage.deserialize(reader), ProtoReceiptForStorage));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoReceiptsForStorage.deserialize(bytes);\n }\n }\n block.ProtoReceiptsForStorage = ProtoReceiptsForStorage;\n class ProtoLogForStorage extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"address\" in data && data.address != undefined) {\n this.address = data.address;\n }\n if (\"topics\" in data && data.topics != undefined) {\n this.topics = data.topics;\n }\n if (\"data\" in data && data.data != undefined) {\n this.data = data.data;\n }\n }\n }\n get address() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoAddress, 1);\n }\n set address(value) {\n pb_1.Message.setWrapperField(this, 1, value);\n }\n get has_address() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get topics() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set topics(value) {\n pb_1.Message.setRepeatedWrapperField(this, 2, value);\n }\n get data() {\n return pb_1.Message.getFieldWithDefault(this, 3, new Uint8Array(0));\n }\n set data(value) {\n pb_1.Message.setField(this, 3, value);\n }\n static fromObject(data) {\n const message = new ProtoLogForStorage({});\n if (data.address != null) {\n message.address = dependency_1.common.ProtoAddress.fromObject(data.address);\n }\n if (data.topics != null) {\n message.topics = data.topics.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n if (data.data != null) {\n message.data = data.data;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.address != null) {\n data.address = this.address.toObject();\n }\n if (this.topics != null) {\n data.topics = this.topics.map((item) => item.toObject());\n }\n if (this.data != null) {\n data.data = this.data;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_address)\n writer.writeMessage(1, this.address, () => this.address.serialize(writer));\n if (this.topics.length)\n writer.writeRepeatedMessage(2, this.topics, (item) => item.serialize(writer));\n if (this.data.length)\n writer.writeBytes(3, this.data);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLogForStorage();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.address, () => message.address = dependency_1.common.ProtoAddress.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.topics, () => pb_1.Message.addToRepeatedWrapperField(message, 2, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n case 3:\n message.data = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoLogForStorage.deserialize(bytes);\n }\n }\n block.ProtoLogForStorage = ProtoLogForStorage;\n class ProtoLogsForStorage extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"logs\" in data && data.logs != undefined) {\n this.logs = data.logs;\n }\n }\n }\n get logs() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoLogForStorage, 1);\n }\n set logs(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoLogsForStorage({});\n if (data.logs != null) {\n message.logs = data.logs.map(item => ProtoLogForStorage.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.logs != null) {\n data.logs = this.logs.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.logs.length)\n writer.writeRepeatedMessage(1, this.logs, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLogsForStorage();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.logs, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoLogForStorage.deserialize(reader), ProtoLogForStorage));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoLogsForStorage.deserialize(bytes);\n }\n }\n block.ProtoLogsForStorage = ProtoLogsForStorage;\n class ProtoPendingHeader extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"wo\" in data && data.wo != undefined) {\n this.wo = data.wo;\n }\n if (\"termini\" in data && data.termini != undefined) {\n this.termini = data.termini;\n }\n }\n }\n get wo() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObject, 1);\n }\n set wo(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_wo() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get termini() {\n return pb_1.Message.getWrapperField(this, ProtoTermini, 2);\n }\n set termini(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_termini() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _wo() {\n const cases = {\n 0: \"none\",\n 1: \"wo\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _termini() {\n const cases = {\n 0: \"none\",\n 2: \"termini\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoPendingHeader({});\n if (data.wo != null) {\n message.wo = ProtoWorkObject.fromObject(data.wo);\n }\n if (data.termini != null) {\n message.termini = ProtoTermini.fromObject(data.termini);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.wo != null) {\n data.wo = this.wo.toObject();\n }\n if (this.termini != null) {\n data.termini = this.termini.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_wo)\n writer.writeMessage(1, this.wo, () => this.wo.serialize(writer));\n if (this.has_termini)\n writer.writeMessage(2, this.termini, () => this.termini.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoPendingHeader();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.wo, () => message.wo = ProtoWorkObject.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.termini, () => message.termini = ProtoTermini.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoPendingHeader.deserialize(bytes);\n }\n }\n block.ProtoPendingHeader = ProtoPendingHeader;\n class ProtoTermini extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1, 2], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"dom_termini\" in data && data.dom_termini != undefined) {\n this.dom_termini = data.dom_termini;\n }\n if (\"sub_termini\" in data && data.sub_termini != undefined) {\n this.sub_termini = data.sub_termini;\n }\n }\n }\n get dom_termini() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set dom_termini(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n get sub_termini() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set sub_termini(value) {\n pb_1.Message.setRepeatedWrapperField(this, 2, value);\n }\n static fromObject(data) {\n const message = new ProtoTermini({});\n if (data.dom_termini != null) {\n message.dom_termini = data.dom_termini.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n if (data.sub_termini != null) {\n message.sub_termini = data.sub_termini.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.dom_termini != null) {\n data.dom_termini = this.dom_termini.map((item) => item.toObject());\n }\n if (this.sub_termini != null) {\n data.sub_termini = this.sub_termini.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.dom_termini.length)\n writer.writeRepeatedMessage(1, this.dom_termini, (item) => item.serialize(writer));\n if (this.sub_termini.length)\n writer.writeRepeatedMessage(2, this.sub_termini, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTermini();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.dom_termini, () => pb_1.Message.addToRepeatedWrapperField(message, 1, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n case 2:\n reader.readMessage(message.sub_termini, () => pb_1.Message.addToRepeatedWrapperField(message, 2, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTermini.deserialize(bytes);\n }\n }\n block.ProtoTermini = ProtoTermini;\n class ProtoEtxSet extends pb_1.Message {\n #one_of_decls = [[1]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"etx_hashes\" in data && data.etx_hashes != undefined) {\n this.etx_hashes = data.etx_hashes;\n }\n }\n }\n get etx_hashes() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set etx_hashes(value) {\n pb_1.Message.setOneofField(this, 1, this.#one_of_decls[0], value);\n }\n get has_etx_hashes() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get _etx_hashes() {\n const cases = {\n 0: \"none\",\n 1: \"etx_hashes\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n static fromObject(data) {\n const message = new ProtoEtxSet({});\n if (data.etx_hashes != null) {\n message.etx_hashes = data.etx_hashes;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.etx_hashes != null) {\n data.etx_hashes = this.etx_hashes;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_etx_hashes)\n writer.writeBytes(1, this.etx_hashes);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoEtxSet();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.etx_hashes = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoEtxSet.deserialize(bytes);\n }\n }\n block.ProtoEtxSet = ProtoEtxSet;\n class ProtoPendingEtxs extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"header\" in data && data.header != undefined) {\n this.header = data.header;\n }\n if (\"etxs\" in data && data.etxs != undefined) {\n this.etxs = data.etxs;\n }\n }\n }\n get header() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObject, 1);\n }\n set header(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_header() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get etxs() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 2);\n }\n set etxs(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_etxs() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _header() {\n const cases = {\n 0: \"none\",\n 1: \"header\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _etxs() {\n const cases = {\n 0: \"none\",\n 2: \"etxs\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoPendingEtxs({});\n if (data.header != null) {\n message.header = ProtoWorkObject.fromObject(data.header);\n }\n if (data.etxs != null) {\n message.etxs = ProtoTransactions.fromObject(data.etxs);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.header != null) {\n data.header = this.header.toObject();\n }\n if (this.etxs != null) {\n data.etxs = this.etxs.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_header)\n writer.writeMessage(1, this.header, () => this.header.serialize(writer));\n if (this.has_etxs)\n writer.writeMessage(2, this.etxs, () => this.etxs.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoPendingEtxs();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.header, () => message.header = ProtoWorkObject.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.etxs, () => message.etxs = ProtoTransactions.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoPendingEtxs.deserialize(bytes);\n }\n }\n block.ProtoPendingEtxs = ProtoPendingEtxs;\n class ProtoPendingEtxsRollup extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"header\" in data && data.header != undefined) {\n this.header = data.header;\n }\n if (\"etxs_rollup\" in data && data.etxs_rollup != undefined) {\n this.etxs_rollup = data.etxs_rollup;\n }\n }\n }\n get header() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObject, 1);\n }\n set header(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_header() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get etxs_rollup() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 2);\n }\n set etxs_rollup(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_etxs_rollup() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _header() {\n const cases = {\n 0: \"none\",\n 1: \"header\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _etxs_rollup() {\n const cases = {\n 0: \"none\",\n 2: \"etxs_rollup\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoPendingEtxsRollup({});\n if (data.header != null) {\n message.header = ProtoWorkObject.fromObject(data.header);\n }\n if (data.etxs_rollup != null) {\n message.etxs_rollup = ProtoTransactions.fromObject(data.etxs_rollup);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.header != null) {\n data.header = this.header.toObject();\n }\n if (this.etxs_rollup != null) {\n data.etxs_rollup = this.etxs_rollup.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_header)\n writer.writeMessage(1, this.header, () => this.header.serialize(writer));\n if (this.has_etxs_rollup)\n writer.writeMessage(2, this.etxs_rollup, () => this.etxs_rollup.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoPendingEtxsRollup();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.header, () => message.header = ProtoWorkObject.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.etxs_rollup, () => message.etxs_rollup = ProtoTransactions.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoPendingEtxsRollup.deserialize(bytes);\n }\n }\n block.ProtoPendingEtxsRollup = ProtoPendingEtxsRollup;\n class ProtoTxIns extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"tx_ins\" in data && data.tx_ins != undefined) {\n this.tx_ins = data.tx_ins;\n }\n }\n }\n get tx_ins() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoTxIn, 1);\n }\n set tx_ins(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoTxIns({});\n if (data.tx_ins != null) {\n message.tx_ins = data.tx_ins.map(item => ProtoTxIn.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.tx_ins != null) {\n data.tx_ins = this.tx_ins.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.tx_ins.length)\n writer.writeRepeatedMessage(1, this.tx_ins, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxIns();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.tx_ins, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoTxIn.deserialize(reader), ProtoTxIn));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTxIns.deserialize(bytes);\n }\n }\n block.ProtoTxIns = ProtoTxIns;\n class ProtoTxOuts extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"tx_outs\" in data && data.tx_outs != undefined) {\n this.tx_outs = data.tx_outs;\n }\n }\n }\n get tx_outs() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoTxOut, 1);\n }\n set tx_outs(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoTxOuts({});\n if (data.tx_outs != null) {\n message.tx_outs = data.tx_outs.map(item => ProtoTxOut.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.tx_outs != null) {\n data.tx_outs = this.tx_outs.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.tx_outs.length)\n writer.writeRepeatedMessage(1, this.tx_outs, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxOuts();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.tx_outs, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoTxOut.deserialize(reader), ProtoTxOut));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTxOuts.deserialize(bytes);\n }\n }\n block.ProtoTxOuts = ProtoTxOuts;\n class ProtoTxIn extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"previous_out_point\" in data && data.previous_out_point != undefined) {\n this.previous_out_point = data.previous_out_point;\n }\n if (\"pub_key\" in data && data.pub_key != undefined) {\n this.pub_key = data.pub_key;\n }\n }\n }\n get previous_out_point() {\n return pb_1.Message.getWrapperField(this, ProtoOutPoint, 1);\n }\n set previous_out_point(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_previous_out_point() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get pub_key() {\n return pb_1.Message.getFieldWithDefault(this, 2, new Uint8Array(0));\n }\n set pub_key(value) {\n pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value);\n }\n get has_pub_key() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _previous_out_point() {\n const cases = {\n 0: \"none\",\n 1: \"previous_out_point\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _pub_key() {\n const cases = {\n 0: \"none\",\n 2: \"pub_key\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoTxIn({});\n if (data.previous_out_point != null) {\n message.previous_out_point = ProtoOutPoint.fromObject(data.previous_out_point);\n }\n if (data.pub_key != null) {\n message.pub_key = data.pub_key;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.previous_out_point != null) {\n data.previous_out_point = this.previous_out_point.toObject();\n }\n if (this.pub_key != null) {\n data.pub_key = this.pub_key;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_previous_out_point)\n writer.writeMessage(1, this.previous_out_point, () => this.previous_out_point.serialize(writer));\n if (this.has_pub_key)\n writer.writeBytes(2, this.pub_key);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxIn();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.previous_out_point, () => message.previous_out_point = ProtoOutPoint.deserialize(reader));\n break;\n case 2:\n message.pub_key = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTxIn.deserialize(bytes);\n }\n }\n block.ProtoTxIn = ProtoTxIn;\n class ProtoOutPoint extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"hash\" in data && data.hash != undefined) {\n this.hash = data.hash;\n }\n if (\"index\" in data && data.index != undefined) {\n this.index = data.index;\n }\n }\n }\n get hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set hash(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_hash() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get index() {\n return pb_1.Message.getFieldWithDefault(this, 2, 0);\n }\n set index(value) {\n pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value);\n }\n get has_index() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _hash() {\n const cases = {\n 0: \"none\",\n 1: \"hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _index() {\n const cases = {\n 0: \"none\",\n 2: \"index\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoOutPoint({});\n if (data.hash != null) {\n message.hash = dependency_1.common.ProtoHash.fromObject(data.hash);\n }\n if (data.index != null) {\n message.index = data.index;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.hash != null) {\n data.hash = this.hash.toObject();\n }\n if (this.index != null) {\n data.index = this.index;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_hash)\n writer.writeMessage(1, this.hash, () => this.hash.serialize(writer));\n if (this.has_index)\n writer.writeUint32(2, this.index);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoOutPoint();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.hash, () => message.hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 2:\n message.index = reader.readUint32();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoOutPoint.deserialize(bytes);\n }\n }\n block.ProtoOutPoint = ProtoOutPoint;\n class ProtoTxOut extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"denomination\" in data && data.denomination != undefined) {\n this.denomination = data.denomination;\n }\n if (\"address\" in data && data.address != undefined) {\n this.address = data.address;\n }\n }\n }\n get denomination() {\n return pb_1.Message.getFieldWithDefault(this, 1, 0);\n }\n set denomination(value) {\n pb_1.Message.setOneofField(this, 1, this.#one_of_decls[0], value);\n }\n get has_denomination() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get address() {\n return pb_1.Message.getFieldWithDefault(this, 2, new Uint8Array(0));\n }\n set address(value) {\n pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value);\n }\n get has_address() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _denomination() {\n const cases = {\n 0: \"none\",\n 1: \"denomination\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _address() {\n const cases = {\n 0: \"none\",\n 2: \"address\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoTxOut({});\n if (data.denomination != null) {\n message.denomination = data.denomination;\n }\n if (data.address != null) {\n message.address = data.address;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.denomination != null) {\n data.denomination = this.denomination;\n }\n if (this.address != null) {\n data.address = this.address;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_denomination)\n writer.writeUint32(1, this.denomination);\n if (this.has_address)\n writer.writeBytes(2, this.address);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxOut();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.denomination = reader.readUint32();\n break;\n case 2:\n message.address = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTxOut.deserialize(bytes);\n }\n }\n block.ProtoTxOut = ProtoTxOut;\n})(block || (block = {}));\n//# sourceMappingURL=proto_block.js.map","import { hexlify } from '../utils/index.js';\nimport * as Proto from './protoc/proto_block.js';\n/**\n * @category Encoding\n * @param {ProtoTransaction} protoTx - The signed constructed transaction\n * @returns {string} - The Protobuf encoded transaction\n */\nexport function encodeProtoTransaction(protoTx) {\n const tx = Proto.block.ProtoTransaction.fromObject(protoTx);\n return hexlify(tx.serialize());\n}\n/**\n * @category Encoding\n * @param {ProtoWorkObject} protoWo - The constructed WorkObject\n * @returns {string} - The Protobuf encoded WorkObject\n */\nexport function encodeProtoWorkObject(protoWo) {\n const wo = Proto.block.ProtoWorkObject.fromObject(protoWo);\n return hexlify(wo.serialize());\n}\n//# sourceMappingURL=proto-encode.js.map","import * as Proto from './protoc/proto_block.js';\n/**\n * @category Encoding\n * @param {Uint8Array} bytes - The Protobuf encoded transaction\n * @returns {ProtoTransaction} - The decoded transaction\n */\nexport function decodeProtoTransaction(bytes) {\n const tx = Proto.block.ProtoTransaction.deserialize(bytes);\n const result = tx.toObject();\n if (result.to?.length == 0) {\n result.to = null;\n }\n return result;\n}\n/**\n * @category Encoding\n * @param {Uint8Array} bytes - The Protobuf encoded work object\n * @returns {ProtoWorkObject} - The decoded work object\n */\nexport function decodeProtoWorkObject(bytes) {\n const wo = Proto.block.ProtoWorkObject.deserialize(bytes);\n return wo.toObject();\n}\n//# sourceMappingURL=proto-decode.js.map","/**\n * Using strings in Ethereum (or any security-basd system) requires additional care. These utilities attempt to mitigate\n * some of the safety issues as well as provide the ability to recover and analyse strings.\n *\n * @subsection api/utils:Strings and UTF-8 [about-strings]\n */\nimport { getBytes } from '../utils/data.js';\nimport { assertArgument, assertNormalize } from '../utils/errors.js';\n// `output` and `badCodepoint` are passed to calls below, but not used in the function\nfunction errorFunc(reason, offset, bytes, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\noutput, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nbadCodepoint) {\n assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, 'bytes', bytes);\n}\n// `output` and `badCodepoint` are passed to calls below, but not used in the function\nfunction ignoreFunc(reason, offset, bytes, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\noutput, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nbadCodepoint) {\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 non-canonical (overlong) codepoints (this is the default)\n *\n * **`\"ignore\"`** - silently drops any illegal UTF-8 sequence and accepts non-canonical (overlong) codepoints\n *\n * **`\"replace\"`** - replace any illegal UTF-8 sequence with the UTF-8 replacement character (i.e. `\"\\\\ufffd\"`) and\n * accepts non-canonical (overlong) codepoints\n *\n * @category Encoding\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 const 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 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 *\n * @category Encoding\n * @param {string} str - The string to convert.\n * @param {UnicodeNormalizationForm} [form] - The normalization form to use.\n *\n * @returns {Uint8Array} The UTF-8 byte representation.\n * @throws {Error} If the UTF-8 conversion fails.\n */\nexport function toUtf8Bytes(str, form) {\n if (form != null) {\n assertNormalize(form);\n str = str.normalize(form);\n }\n const 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 * @ignore\n */\nfunction _toUtf8String(codePoints) {\n return codePoints\n .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 })\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 errors allowing recovery using the\n * {@link Utf8ErrorFunc | **Utf8ErrorFunc**} API. (default: [error](Utf8ErrorFuncs))\n *\n * @category Encoding\n * @param {BytesLike} bytes - The UTF-8 data to convert.\n * @param {Utf8ErrorFunc} [onError] - The error handling function.\n *\n * @returns {string} The string.\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 *\n * @category Encoding\n * @param {string} str - The string to convert.\n * @param {UnicodeNormalizationForm} [form] - The normalization form to use.\n *\n * @returns {number[]} The UTF-8 code-points.\n */\nexport function toUtf8CodePoints(str, form) {\n return getUtf8CodePoints(toUtf8Bytes(str, form));\n}\n//# sourceMappingURL=utf8.js.map","import { assert } from './errors.js';\n// @TODO: timeout is completely ignored; start a Promise.any with a reject?\n// TODO: `options` is not used; remove?\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function createGetUrl(options) {\n async function getUrl(req, _signal) {\n const protocol = req.url.split(':')[0].toLowerCase();\n assert(protocol === 'http' || protocol === 'https', `unsupported protocol ${protocol}`, 'UNSUPPORTED_OPERATION', {\n info: { protocol },\n operation: 'request',\n });\n assert(protocol === 'https' || !req.credentials || req.allowInsecureAuthentication, 'insecure authorized connections unsupported', 'UNSUPPORTED_OPERATION', {\n operation: 'request',\n });\n let signal = undefined;\n if (_signal) {\n const controller = new AbortController();\n signal = controller.signal;\n _signal.addListener(() => {\n controller.abort();\n });\n }\n const init = {\n method: req.method,\n headers: new Headers(Array.from(req)),\n body: req.body || undefined,\n signal,\n };\n const resp = await fetch(req.url, init);\n const headers = {};\n resp.headers.forEach((value, key) => {\n headers[key.toLowerCase()] = value;\n });\n const respBody = await resp.arrayBuffer();\n const body = respBody == null ? null : new Uint8Array(respBody);\n return {\n statusCode: resp.status,\n statusMessage: resp.statusText,\n headers,\n body,\n };\n }\n return getUrl;\n}\n// @TODO: remove in v7; provided for backwards compat\nconst defaultGetUrl = createGetUrl({});\nexport async function getUrl(req, _signal) {\n return defaultGetUrl(req, _signal);\n}\n//# sourceMappingURL=geturl-browser.js.map","/**\n * Fetching content from the web is environment-specific, so quais provides an abstraction that each environment can\n * implement to provide this service.\n *\n * On [Node.js](https://nodejs.org/), the `http` and `https` libs are used to create a request object, register event\n * listeners and process data and populate the {@link FetchResponse | **FetchResponse**}.\n *\n * In a browser, the [DOM fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) is used, and the resulting\n * `Promise` is waited on to retrieve the payload.\n *\n * The {@link FetchRequest | **FetchRequest**} is responsible for handling many common situations, such as redirects,\n * server throttling, authentication, etc.\n *\n * It also handles common gateways, such as IPFS and data URIs.\n */\nimport { decodeBase64, encodeBase64 } from '../encoding/base64.js';\nimport { hexlify } from './data.js';\nimport { assert, assertArgument } from './errors.js';\nimport { defineProperties } from './properties.js';\nimport { toUtf8Bytes, toUtf8String } from '../encoding/index.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\n// TODO: `signal` is not used; remove?\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\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 {@link FetchGatewayFunc | **FetchGatewayFunc**} for fetching content from a standard IPFS gateway hosted at\n * `baseUrl`.\n *\n * @category Utils\n * @param {string} baseUrl - The base URL of the IPFS gateway.\n * @returns {FetchGatewayFunc} The gateway function.\n */\nfunction getIpfsGatewayFunc(baseUrl) {\n // TODO: `signal` is not used; remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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(() => {\n listener();\n }, 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() {\n return this.#cancelled;\n }\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:`, and `IPFS:`.\n *\n * Additional schemes can be added globally using {@link registerGateway | **registerGateway**}.\n *\n * @category Utils\n * @example\n *\n * ```ts\n * req = new FetchRequest('https://www.ricmoo.com');\n * resp = await req.send();\n * resp.body.length;\n * ```\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() {\n return this.#url;\n }\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 set and will be used if **not overridden** by\n * setting a custom header.\n *\n * If `body` is null, the body is cleared (along with the intrinsic `Content-Type`).\n *\n * If `body` is a string, the intrinsic `Content-Type` is set to `text/plain`.\n *\n * If `body` is a Uint8Array, the intrinsic `Content-Type` is set to `application/octet-stream`.\n *\n * If `body` is any other object, the intrinsic `Content-Type` is 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 has been explicitly set, then `GET` is used if the\n * body is 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 keys are lower-case.\n *\n * This object is a copy, so any changes will **NOT** be reflected 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 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 * @param {string} key - The header key to retrieve.\n * @returns {string} The header value.\n */\n getHeader(key) {\n return this.headers[key.toLowerCase()];\n }\n /**\n * Set the header for `key` to `value`. All values are coerced to a string.\n *\n * @param {string} key - The header key to set.\n * @param {string | number} value - The header value to set.\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]],\n 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 * @param {string} username - The username to use for basic authentication.\n * @param {string} password - The password to use for basic authentication.\n * @throws {Error} If the `username` contains a colon.\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 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 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. (default: 5 minutes)\n */\n get timeout() {\n return this.#timeout;\n }\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 during a redirection or retry in case of server\n * throttling.\n *\n * This offers an opportunity to populate headers or update 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 opportunity to provide client-level throttling or\n * updating 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 has not been reached), use\n * {@link FetchResponse.throwThrottleError | **FetchResponse.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 HTTPS URLs and is platform specific (e.g. nodejs vs\n * browsers).\n *\n * This is by default the currently registered global getUrl function, which can be changed using\n * {@link registerGetUrl | **registerGetUrl**}. If this has been set, setting is to `null` will cause this\n * FetchRequest (and any future clones) to revert back to using the currently registered global getUrl function.\n *\n * Setting this is generally not necessary, but may be useful 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 `.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 ``;\n }\n /**\n * Update the throttle parameters used to determine maximum attempts and exponential-backoff properties.\n *\n * @param {FetchThrottleParams} params - The throttle parameters to set.\n * @throws {Error} If the `slotInterval` is not a positive integer.\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',\n reason: 'timeout',\n 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 // eslint-disable-next-line no-empty\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 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', {\n operation: 'fetchRequest.send',\n });\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` error to be rejected from the\n * {@link FetchRequest.send | **send**}.\n */\n cancel() {\n assert(this.#signal != null, 'request has not been sent', 'UNSUPPORTED_OPERATION', {\n operation: 'fetchRequest.cancel',\n });\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 {@link FetchRequest | **FetchRequest**} that represents the redirection to `location`.\n *\n * @param {string} location - The location to redirect to.\n * @returns {FetchRequest} The new request.\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 return req;\n }\n /**\n * Create a new copy of this request.\n *\n * @returns {FetchRequest} The new 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.#getUrlFunc = this.#getUrlFunc;\n return clone;\n }\n /**\n * Locks all static configuration for gateways and FetchGetUrlFunc registration.\n */\n static lockConfig() {\n locked = true;\n }\n /**\n * Get the current Gateway function for `scheme`.\n *\n * @param {string} scheme - The scheme to get the gateway for.\n * @returns {FetchGatewayFunc | null} The gateway function, or null if not found.\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 {@link FetchRequest.lockConfig | **lockConfig**} has been called, no change is made and this throws.\n *\n * @param {string} scheme - The scheme to register the gateway for.\n * @param {FetchGatewayFunc} func - The gateway function to use.\n * @throws {Error} If the scheme is `http` or `https`.\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 {@link FetchRequest.lockConfig | **lockConfig**} has been called, no change is made and this throws.\n *\n * @param {FetchGetUrlFunc} getUrl - The function to use for fetching HTTP and HTTPS URIs.\n * @throws {Error} If the gateways are locked.\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 HTTPS URLs.\n *\n * The available `options` are dependent on the platform implementation of the default getUrl function.\n *\n * This is not generally something that is needed, but is useful when trying to customize simple behaviour when\n * fetching HTTP content.\n *\n * @param {Record} [options] - The options to use when creating the getUrl function.\n * @returns {FetchGetUrlFunc} The getUrl function.\n * @throws {Error} If the gateways are locked.\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 data URIs, so it is not necessary to register it.\n *\n * This is not generally something that is needed, but may be useful in a wrapper to perfom custom data URI\n * functionality.\n *\n * @returns {FetchGatewayFunc} The gateway function.\n */\n static createDataGateway() {\n return dataGatewayFunc;\n }\n /**\n * Creates a function that will fetch IPFS (unvalidated) from a custom gateway baseUrl.\n *\n * The default IPFS gateway used internally is `\"https:/\\/gateway.ipfs.io/ipfs/\"`.\n *\n * @param {string} baseUrl - The base URL of the IPFS gateway.\n * @returns {FetchGatewayFunc} The gateway function.\n */\n static createIpfsGatewayFunc(baseUrl) {\n return getIpfsGatewayFunc(baseUrl);\n }\n}\n/**\n * The response for a FetchRequest.\n *\n * @category Utils\n */\nexport class FetchResponse {\n #statusCode;\n #statusMessage;\n #headers;\n #body;\n #request;\n #error;\n toString() {\n return ``;\n }\n /**\n * The response status code.\n */\n get statusCode() {\n return this.#statusCode;\n }\n /**\n * The response status message.\n */\n get statusMessage() {\n return this.#statusMessage;\n }\n /**\n * The response headers. All keys are lower-case.\n */\n get headers() {\n return Object.assign({}, this.#headers);\n }\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 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',\n 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 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',\n 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]],\n 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 an error status code (i.e. 599) and `message` with an\n * optional `error`.\n *\n * @param {string} [message] - The error message to use.\n * @param {Error} [error] - The error to use.\n * @returns {FetchResponse} The error response.\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) call, causes the request to retry as if\n * throttled for `stall` milliseconds.\n *\n * @param {string} [message] - The error message to use.\n * @param {number} [stall] - The number of milliseconds to stall before retrying.\n * @throws {Error} If `stall` is not a non-negative integer.\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 * @param {string} key - The header key to retrieve.\n * @returns {string} The header value.\n */\n getHeader(key) {\n return this.headers[key.toLowerCase()];\n }\n /**\n * Returns true if the response has a body.\n *\n * @returns {boolean} True if the response has a body.\n * @throws {Error} If the body is invalid UTF-8 data.\n */\n hasBody() {\n return this.#body != null;\n }\n /**\n * The request made for this response.\n */\n get request() {\n return this.#request;\n }\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 * @throws {Error} If the response is not ok.\n */\n assertOk() {\n if (this.ok()) {\n return;\n }\n // eslint-disable-next-line prefer-const\n let { message, error } = this.#error;\n if (message === '') {\n message = `server response ${this.statusCode} ${this.statusMessage}`;\n }\n assert(false, message, 'SERVER_ERROR', {\n request: this.request || 'unknown request',\n response: this,\n error,\n });\n }\n}\nfunction getTime() {\n return new Date().getTime();\n}\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","/**\n * The **FixedNumber** class permits using values with decimal places, using fixed-pont math.\n *\n * Fixed-point math is still based on integers under-the-hood, but uses an internal offset to store fractional\n * components below, and each operation corrects for this after each operation.\n */\nimport { getBytes } from './data.js';\nimport { assert, assertArgument, assertPrivate } from './errors.js';\nimport { getBigInt, getNumber, fromTwos, mask, toBigInt } from './maths.js';\nimport { defineProperties } from './properties.js';\nconst BN_N1 = BigInt(-1);\nconst BN_0 = BigInt(0);\nconst BN_1 = BigInt(1);\nconst BN_5 = BigInt(5);\nconst _guard = {};\n// Constant to pull zeros from for multipliers\nlet Zeros = '0000';\nwhile (Zeros.length < 80) {\n Zeros += Zeros;\n}\n// Returns a string \"1\" followed by decimal \"0\"s\nfunction getTens(decimals) {\n let result = Zeros;\n while (result.length < decimals) {\n result += result;\n }\n return BigInt('1' + result.substring(0, decimals));\n}\nfunction checkValue(val, format, safeOp) {\n const width = BigInt(format.width);\n if (format.signed) {\n const limit = BN_1 << (width - BN_1);\n assert(safeOp == null || (val >= -limit && val < limit), 'overflow', 'NUMERIC_FAULT', {\n operation: safeOp,\n fault: 'overflow',\n value: val,\n });\n if (val > BN_0) {\n val = fromTwos(mask(val, width), width);\n }\n else {\n val = -fromTwos(mask(-val, width), width);\n }\n }\n else {\n const limit = BN_1 << width;\n assert(safeOp == null || (val >= 0 && val < limit), 'overflow', 'NUMERIC_FAULT', {\n operation: safeOp,\n fault: 'overflow',\n value: val,\n });\n val = ((val % limit) + limit) % limit & (limit - BN_1);\n }\n return val;\n}\nfunction getFormat(value) {\n if (typeof value === 'number') {\n value = `fixed128x${value}`;\n }\n let signed = true;\n let width = 128;\n let decimals = 18;\n if (typeof value === 'string') {\n // Parse the format string\n if (value === 'fixed') {\n // defaults...\n }\n else if (value === 'ufixed') {\n signed = false;\n }\n else {\n const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);\n assertArgument(match, 'invalid fixed format', 'format', value);\n signed = match[1] !== 'u';\n width = parseInt(match[2]);\n decimals = parseInt(match[3]);\n }\n }\n else if (value) {\n // Extract the values from the object\n const v = value;\n const check = (key, type, defaultValue) => {\n if (v[key] == null) {\n return defaultValue;\n }\n assertArgument(typeof v[key] === type, 'invalid fixed format (' + key + ' not ' + type + ')', 'format.' + key, v[key]);\n return v[key];\n };\n signed = check('signed', 'boolean', signed);\n width = check('width', 'number', width);\n decimals = check('decimals', 'number', decimals);\n }\n assertArgument(width % 8 === 0, 'invalid FixedNumber width (not byte aligned)', 'format.width', width);\n assertArgument(decimals <= 80, 'invalid FixedNumber decimals (too large)', 'format.decimals', decimals);\n const name = (signed ? '' : 'u') + 'fixed' + String(width) + 'x' + String(decimals);\n return { signed, width, decimals, name };\n}\nfunction toString(val, decimals) {\n let negative = '';\n if (val < BN_0) {\n negative = '-';\n val *= BN_N1;\n }\n let str = val.toString();\n // No decimal point for whole values\n if (decimals === 0) {\n return negative + str;\n }\n // Pad out to the whole component (including a whole digit)\n while (str.length <= decimals) {\n str = Zeros + str;\n }\n // Insert the decimal point\n const index = str.length - decimals;\n str = str.substring(0, index) + '.' + str.substring(index);\n // Trim the whole component (leaving at least one 0)\n while (str[0] === '0' && str[1] !== '.') {\n str = str.substring(1);\n }\n // Trim the decimal component (leaving at least one 0)\n while (str[str.length - 1] === '0' && str[str.length - 2] !== '.') {\n str = str.substring(0, str.length - 1);\n }\n return negative + str;\n}\n/**\n * A FixedNumber represents a value over its {@link FixedFormat | **FixedFormat**} arithmetic field.\n *\n * A FixedNumber can be used to perform math, losslessly, on values which have decmial places.\n *\n * A FixedNumber has a fixed bit-width to store values in, and stores all values internally by multiplying the value by\n * 10 raised to the power of `decimals`.\n *\n * If operations are performed that cause a value to grow too high (close to positive infinity) or too low (close to\n * negative infinity), the value is said to overflow.\n *\n * For example, an 8-bit signed value, with 0 decimals may only be within the range `-128` to `127`; so `-128 - 1` will\n * overflow and become `127`. Likewise, `127 + 1` will overflow and become `-127`.\n *\n * Many operation have a normal and unsafe variant. The normal variant will throw a\n * [NumericFaultError](../interfaces/NumericFaultError) on any overflow, while the unsafe variant will silently allow\n * overflow, corrupting its value value.\n *\n * If operations are performed that cause a value to become too small (close to zero), the value loses precison and is\n * said to underflow.\n *\n * For example, an value with 1 decimal place may store a number as small as `0.1`, but the value of `0.1 / 2` is\n * `0.05`, which cannot fit into 1 decimal place, so underflow occurs which means precision is lost and the value\n * becomes `0`.\n *\n * Some operations have a normal and signalling variant. The normal variant will silently ignore underflow, while the\n * signalling variant will thow a [NumericFaultError](../interfaces/NumericFaultError) on underflow.\n *\n * @category Utils\n */\nexport class FixedNumber {\n /**\n * The specific fixed-point arithmetic field for this value.\n */\n format;\n #format;\n // The actual value (accounting for decimals)\n #val;\n // A base-10 value to multiple values by to maintain the magnitude\n #tens;\n /**\n * This is a property so console.log shows a human-meaningful value.\n *\n * @ignore\n */\n _value;\n // Use this when changing this file to get some typing info,\n // but then switch to any to mask the internal type\n // constructor(guard: any, value: bigint, format: _FixedFormat) {\n /**\n * @ignore\n */\n constructor(guard, value, format) {\n assertPrivate(guard, _guard, 'FixedNumber');\n this.#val = value;\n this.#format = format;\n const _value = toString(value, format.decimals);\n defineProperties(this, { format: format.name, _value });\n this.#tens = getTens(format.decimals);\n }\n /**\n * If true, negative values are permitted, otherwise only positive values and zero are allowed.\n */\n get signed() {\n return this.#format.signed;\n }\n /**\n * The number of bits available to store the value.\n */\n get width() {\n return this.#format.width;\n }\n /**\n * The number of decimal places in the fixed-point arithment field.\n */\n get decimals() {\n return this.#format.decimals;\n }\n /**\n * The value as an integer, based on the smallest unit the {@link FixedNumber.decimals | **decimals**} allow.\n */\n get value() {\n return this.#val;\n }\n #checkFormat(other) {\n assertArgument(this.format === other.format, 'incompatible format; use fixedNumber.toFormat', 'other', other);\n }\n #checkValue(val, safeOp) {\n val = checkValue(val, this.#format, safeOp);\n return new FixedNumber(_guard, val, this.#format);\n }\n #add(o, safeOp) {\n this.#checkFormat(o);\n return this.#checkValue(this.#val + o.#val, safeOp);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` added to `other`, ignoring overflow.\n *\n * @param {FixedNumber} other - The value to add to `this`.\n * @returns {FixedNumber} The result of the addition.\n */\n addUnsafe(other) {\n return this.#add(other);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` added to `other`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to add to `this`.\n * @returns {FixedNumber} The result of the addition.\n */\n add(other) {\n return this.#add(other, 'add');\n }\n #sub(o, safeOp) {\n this.#checkFormat(o);\n return this.#checkValue(this.#val - o.#val, safeOp);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `other` subtracted from `this`, ignoring\n * overflow.\n *\n * @param {FixedNumber} other - The value to subtract from `this`.\n * @returns {FixedNumber} The result of the subtraction.\n */\n subUnsafe(other) {\n return this.#sub(other);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `other` subtracted from `this`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to subtract from `this`.\n * @returns {FixedNumber} The result of the subtraction.\n */\n sub(other) {\n return this.#sub(other, 'sub');\n }\n #mul(o, safeOp) {\n this.#checkFormat(o);\n return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`, ignoring\n * overflow and underflow (precision loss).\n *\n * @param {FixedNumber} other - The value to multiply `this` by.\n * @returns {FixedNumber} The result of the multiplication.\n */\n mulUnsafe(other) {\n return this.#mul(other);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to multiply `this` by.\n * @returns {FixedNumber} The result of the multiplication.\n */\n mul(other) {\n return this.#mul(other, 'mul');\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs or if underflow (precision\n * loss) occurs.\n *\n * @param {FixedNumber} other - The value to multiply `this` by.\n * @returns {FixedNumber} The result of the multiplication.\n * @throws {NumericFaultError} Thrown if overflow or underflow occurs.\n * @throws {NumericFaultError} Thrown if division by 0 occurs.\n */\n mulSignal(other) {\n this.#checkFormat(other);\n const value = this.#val * other.#val;\n assert(value % this.#tens === BN_0, 'precision lost during signalling mul', 'NUMERIC_FAULT', {\n operation: 'mulSignal',\n fault: 'underflow',\n value: this,\n });\n return this.#checkValue(value / this.#tens, 'mulSignal');\n }\n #div(o, safeOp) {\n assert(o.#val !== BN_0, 'division by zero', 'NUMERIC_FAULT', {\n operation: 'div',\n fault: 'divide-by-zero',\n value: this,\n });\n this.#checkFormat(o);\n return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`, ignoring\n * underflow (precision loss). A [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to divide `this` by.\n * @returns {FixedNumber} The result of the division.\n */\n divUnsafe(other) {\n return this.#div(other);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`, ignoring\n * underflow (precision loss). A [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to divide `this` by.\n * @returns {FixedNumber} The result of the division.\n */\n div(other) {\n return this.#div(other, 'div');\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if underflow (precision loss) occurs.\n *\n * @param {FixedNumber} other - The value to divide `this` by.\n * @returns {FixedNumber} The result of the division.\n * @throws {NumericFaultError} Thrown if underflow occurs.\n */\n divSignal(other) {\n assert(other.#val !== BN_0, 'division by zero', 'NUMERIC_FAULT', {\n operation: 'div',\n fault: 'divide-by-zero',\n value: this,\n });\n this.#checkFormat(other);\n const value = this.#val * this.#tens;\n assert(value % other.#val === BN_0, 'precision lost during signalling div', 'NUMERIC_FAULT', {\n operation: 'divSignal',\n fault: 'underflow',\n value: this,\n });\n return this.#checkValue(value / other.#val, 'divSignal');\n }\n /**\n * Returns a comparison result between `this` and `other`.\n *\n * This is suitable for use in sorting, where `-1` implies `this` is smaller, `1` implies `this` is larger and `0`\n * implies both are equal.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {number} The comparison result.\n */\n cmp(other) {\n let a = this.value, b = other.value;\n // Coerce a and b to the same magnitude\n const delta = this.decimals - other.decimals;\n if (delta > 0) {\n b *= getTens(delta);\n }\n else if (delta < 0) {\n a *= getTens(-delta);\n }\n // Comnpare\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n }\n /**\n * Returns true if `other` is equal to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is equal to `this`.\n */\n eq(other) {\n return this.cmp(other) === 0;\n }\n /**\n * Returns true if `other` is less than to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is less than to `this`.\n */\n lt(other) {\n return this.cmp(other) < 0;\n }\n /**\n * Returns true if `other` is less than or equal to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is less than or equal to `this`.\n */\n lte(other) {\n return this.cmp(other) <= 0;\n }\n /**\n * Returns true if `other` is greater than to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is greater than to `this`.\n */\n gt(other) {\n return this.cmp(other) > 0;\n }\n /**\n * Returns true if `other` is greater than or equal to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is greater than or equal to `this`.\n */\n gte(other) {\n return this.cmp(other) >= 0;\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} which is the largest **integer** that is less than or equal to\n * `this`.\n *\n * The decimal component of the result will always be `0`.\n *\n * @returns {FixedNumber} The floored value.\n */\n floor() {\n let val = this.#val;\n if (this.#val < BN_0) {\n val -= this.#tens - BN_1;\n }\n val = (this.#val / this.#tens) * this.#tens;\n return this.#checkValue(val, 'floor');\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} which is the smallest **integer** that is greater than or\n * equal to `this`.\n *\n * The decimal component of the result will always be `0`.\n *\n * @returns {FixedNumber} The ceiling value.\n */\n ceiling() {\n let val = this.#val;\n if (this.#val > BN_0) {\n val += this.#tens - BN_1;\n }\n val = (this.#val / this.#tens) * this.#tens;\n return this.#checkValue(val, 'ceiling');\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the decimal component rounded up on ties at `decimals`\n * places.\n *\n * @param {number} [decimals] - The number of decimal places to round to.\n * @returns {FixedNumber} The rounded value.\n */\n round(decimals) {\n if (decimals == null) {\n decimals = 0;\n }\n // Not enough precision to not already be rounded\n if (decimals >= this.decimals) {\n return this;\n }\n const delta = this.decimals - decimals;\n const bump = BN_5 * getTens(delta - 1);\n let value = this.value + bump;\n const tens = getTens(delta);\n value = (value / tens) * tens;\n checkValue(value, this.#format, 'round');\n return new FixedNumber(_guard, value, this.#format);\n }\n /**\n * Returns true if `this` is equal to `0`.\n *\n * @returns {boolean} True if `this` is equal to `0`.\n */\n isZero() {\n return this.#val === BN_0;\n }\n /**\n * Returns true if `this` is less than `0`.\n *\n * @returns {boolean} True if `this` is less than `0`.\n */\n isNegative() {\n return this.#val < BN_0;\n }\n /**\n * Returns the string representation of `this`.\n *\n * @returns {string} The string representation.\n */\n toString() {\n return this._value;\n }\n /**\n * Returns a float approximation.\n *\n * Due to IEEE 754 precission (or lack thereof), this function can only return an approximation and most values will\n * contain rounding errors.\n *\n * @returns {number} The float approximation.\n */\n toUnsafeFloat() {\n return parseFloat(this.toString());\n }\n /**\n * Return a new {@link FixedNumber | **FixedNumber**} with the same value but has had its field set to `format`.\n *\n * This will throw if the value cannot fit into `format`.\n *\n * @param {FixedFormat} format - The new format for the value.\n */\n toFormat(format) {\n return FixedNumber.fromString(this.toString(), format);\n }\n /**\n * Creates a new {@link FixedNumber | **FixedNumber**} for `value` divided by `decimal` places with `format`.\n *\n * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` (once adjusted for `decimals`)\n * cannot fit in `format`, either due to overflow or underflow (precision loss).\n *\n * @param {BigNumberish} _value - The value to create a FixedNumber for.\n * @param {Numeric} [_decimals] - The number of decimal places in `value`.\n * @param {FixedFormat} [_format] - The format for the FixedNumber.\n * @returns {FixedNumber} The FixedNumber for `value`.\n */\n static fromValue(_value, _decimals, _format) {\n const decimals = _decimals == null ? 0 : getNumber(_decimals);\n const format = getFormat(_format);\n let value = getBigInt(_value, 'value');\n const delta = decimals - format.decimals;\n if (delta > 0) {\n const tens = getTens(delta);\n assert(value % tens === BN_0, 'value loses precision for format', 'NUMERIC_FAULT', {\n operation: 'fromValue',\n fault: 'underflow',\n value: _value,\n });\n value /= tens;\n }\n else if (delta < 0) {\n value *= getTens(-delta);\n }\n checkValue(value, format, 'fromValue');\n return new FixedNumber(_guard, value, format);\n }\n /**\n * Creates a new {@link FixedNumber | **FixedNumber**} for `value` with `format`.\n *\n * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` cannot fit in `format`, either\n * due to overflow or underflow (precision loss).\n *\n * @param {BigNumberish} _value - The value to create a FixedNumber for.\n * @param {FixedFormat} [_format] - The format for the FixedNumber.\n * @returns {FixedNumber} The FixedNumber for `value`.\n */\n static fromString(_value, _format) {\n const match = _value.match(/^(-?)([0-9]*)\\.?([0-9]*)$/);\n assertArgument(match && match[2].length + match[3].length > 0, 'invalid FixedNumber string value', 'value', _value);\n const format = getFormat(_format);\n const whole = match[2] || '0';\n let decimal = match[3] || '';\n // Pad out the decimals\n while (decimal.length < format.decimals) {\n decimal += Zeros;\n }\n // Check precision is safe\n assert(decimal.substring(format.decimals).match(/^0*$/), 'too many decimals for format', 'NUMERIC_FAULT', {\n operation: 'fromString',\n fault: 'underflow',\n value: _value,\n });\n // Remove extra padding\n decimal = decimal.substring(0, format.decimals);\n const value = BigInt(match[1] + whole + decimal);\n checkValue(value, format, 'fromString');\n return new FixedNumber(_guard, value, format);\n }\n /**\n * Creates a new {@link FixedNumber | **FixedNumber**} with the big-endian representation `value` with `format`.\n *\n * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` cannot fit in `format` due to\n * overflow.\n *\n * @param {BytesLike} _value - The big-endian representation of the value.\n * @param {FixedFormat} [_format] - The format for the FixedNumber.\n * @returns {FixedNumber} The FixedNumber for `value`.\n */\n static fromBytes(_value, _format) {\n let value = toBigInt(getBytes(_value, 'value'));\n const format = getFormat(_format);\n if (format.signed) {\n value = fromTwos(value, format.width);\n }\n checkValue(value, format, 'fromBytes');\n return new FixedNumber(_guard, value, format);\n }\n}\n//# sourceMappingURL=fixednumber.js.map","/**\n * Most interactions with Ethereum requires integer values, which use the smallest magnitude unit.\n *\n * For example, imagine dealing with dollars and cents. Since dollars are divisible, non-integer values are possible,\n * such as `$10.77`. By using the smallest indivisible unit (i.e. cents), the value can be kept as the integer `1077`.\n *\n * When receiving decimal input from the user (as a decimal string), the value should be converted to an integer and\n * when showing a user a value, the integer value should be converted to a decimal string.\n *\n * This creates a clear distinction, between values to be used by code (integers) and values used for display logic to\n * users (decimals).\n *\n * The native unit in Ethereum, ether is divisible to 18 decimal places, where each individual unit is called a wei.\n */\nimport { assertArgument } from './errors.js';\nimport { FixedNumber } from './fixednumber.js';\nimport { getNumber } from './maths.js';\nconst names = ['wei', 'kwei', 'mwei', 'gwei', 'szabo', 'finney', 'ether'];\n/**\n * Converts `value` into a decimal string, assuming `unit` decimal places. The `unit` may be the number of decimal\n * places or the name of a unit (e.g. `\"gwei\"` for 9 decimal places).\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @param {string | Numeric} [unit=18] - The unit to convert to. Default is `18`\n * @returns {string} The converted value.\n * @throws {Error} If the unit is invalid.\n */\nexport function formatUnits(value, unit) {\n let decimals = 18;\n if (typeof unit === 'string') {\n const index = names.indexOf(unit);\n assertArgument(index >= 0, 'invalid unit', 'unit', unit);\n decimals = 3 * index;\n }\n else if (unit != null) {\n decimals = getNumber(unit, 'unit');\n }\n return FixedNumber.fromValue(value, decimals, { decimals, width: 512 }).toString();\n}\n/**\n * Converts the decimal string `value` to a BigInt, assuming `unit` decimal places. The `unit` may the number of decimal\n * places or the name of a unit (e.g. `\"gwei\"` for 9 decimal places).\n *\n * @category Utils\n * @param {string} value - The value to convert.\n * @param {string | Numeric} [unit=18] - The unit to convert from. Default is `18`\n * @returns {bigint} The converted value.\n * @throws {Error} If the unit is invalid.\n * @throws {Error} If the value is not a string.\n */\nexport function parseUnits(value, unit) {\n assertArgument(typeof value === 'string', 'value must be a string', 'value', value);\n let decimals = 18;\n if (typeof unit === 'string') {\n const index = names.indexOf(unit);\n assertArgument(index >= 0, 'invalid unit', 'unit', unit);\n decimals = 3 * index;\n }\n else if (unit != null) {\n decimals = getNumber(unit, 'unit');\n }\n return FixedNumber.fromString(value, { decimals, width: 512 }).value;\n}\n/**\n * Converts `value` into a decimal string sing 18 decimal places.\n *\n * @category Utils\n * @param {BigNumberish} wei - The value to convert.\n * @returns {string} The converted value.\n */\nexport function formatQuai(wei) {\n return formatUnits(wei, 18);\n}\n/**\n * Converts `value` into a decimal string using 3 decimal places.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @returns {string} The converted value.\n */\nexport function formatQi(value) {\n return formatUnits(value, 3);\n}\n/**\n * Converts the decimal string `quai` to a BigInt, using 18 decimal places.\n *\n * @category Utils\n * @param {string} ether - The value to convert.\n * @returns {bigint} The converted value.\n */\nexport function parseQuai(ether) {\n return parseUnits(ether, 18);\n}\n/**\n * Converts `value` into a decimal string using 3 decimal places.\n *\n * @category Utils\n * @param {string} value - The value to convert.\n * @returns {bigint} The converted value.\n */\nexport function parseQi(value) {\n return parseUnits(value, 3);\n}\n//# sourceMappingURL=units.js.map","/**\n * Explain UUID and link to RFC here.\n */\nimport { getBytes, hexlify } from './data.js';\n/**\n * Returns the version 4 [UUID](https://www.ietf.org/rfc/rfc4122.txt) for the `randomBytes`.\n *\n * @category Utils\n * @param {BytesLike} randomBytes - The random bytes to use.\n *\n * @returns {string} The UUID.\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","/**\n * A zone is the lowest level shard within the Quai network hierarchy. Zones are the only shards in the network that\n * accept user transactions. The value is a hexadecimal string representing the encoded value of the zone. Read more\n * [here](https://github.com/quai-network/qips/blob/master/qip-0002.md).\n *\n * @category Constants\n */\nexport var Zone;\n(function (Zone) {\n Zone[\"Cyprus1\"] = \"0x00\";\n Zone[\"Cyprus2\"] = \"0x01\";\n Zone[\"Cyprus3\"] = \"0x02\";\n Zone[\"Paxos1\"] = \"0x10\";\n Zone[\"Paxos2\"] = \"0x11\";\n Zone[\"Paxos3\"] = \"0x12\";\n Zone[\"Hydra1\"] = \"0x20\";\n Zone[\"Hydra2\"] = \"0x21\";\n Zone[\"Hydra3\"] = \"0x22\";\n})(Zone || (Zone = {}));\nexport var Ledger;\n(function (Ledger) {\n Ledger[Ledger[\"Quai\"] = 0] = \"Quai\";\n Ledger[Ledger[\"Qi\"] = 1] = \"Qi\";\n})(Ledger || (Ledger = {}));\nfunction zoneFromBytes(zone) {\n switch (zone) {\n case '0x00':\n return Zone.Cyprus1;\n case '0x01':\n return Zone.Cyprus2;\n case '0x02':\n return Zone.Cyprus3;\n case '0x10':\n return Zone.Paxos1;\n case '0x11':\n return Zone.Paxos2;\n case '0x12':\n return Zone.Paxos3;\n case '0x20':\n return Zone.Hydra1;\n case '0x21':\n return Zone.Hydra2;\n case '0x22':\n return Zone.Hydra3;\n default:\n throw new Error(`Invalid zone: ${zone}`);\n }\n}\nexport const ZoneData = [\n {\n name: 'Cyprus One',\n nickname: 'cyprus1',\n shard: 'zone-0-0',\n context: 2,\n byte: '0x00', //0000 0000 region-0 zone-0\n },\n {\n name: 'Cyprus Two',\n nickname: 'cyprus2',\n shard: 'zone-0-1',\n context: 2,\n byte: '0x01', // 0000 0001 region-0 zone-1\n },\n {\n name: 'Cyprus Three',\n nickname: 'cyprus3',\n shard: 'zone-0-2',\n context: 2,\n byte: '0x02', // 0000 0010 region-0 zone-2\n },\n {\n name: 'Paxos One',\n nickname: 'paxos1',\n shard: 'zone-1-0',\n context: 2,\n byte: '0x10', // 0001 0000 region-1 zone-0\n },\n {\n name: 'Paxos Two',\n nickname: 'paxos2',\n shard: 'zone-1-1',\n context: 2,\n byte: '0x11', // 0001 0001 region-1 zone-1\n },\n {\n name: 'Paxos Three',\n nickname: 'paxos3',\n shard: 'zone-1-2',\n context: 2,\n byte: '0x12', // 0001 0010 region-1 zone-2\n },\n {\n name: 'Hydra One',\n nickname: 'hydra1',\n shard: 'zone-2-0',\n context: 2,\n byte: '0x20', // 0010 0000 region-2 zone-0\n },\n {\n name: 'Hydra Two',\n nickname: 'hydra2',\n shard: 'zone-2-1',\n context: 2,\n byte: '0x21', // 0010 0001 region-2 zone-1\n },\n {\n name: 'Hydra Three',\n nickname: 'hydra3',\n shard: 'zone-2-2',\n context: 2,\n byte: '0x22', // 0010 0010 region-2 zone-2\n },\n];\nexport function toZone(shard) {\n return zoneFromBytes(ZoneData.find((it) => it.name == shard || it.byte == shard || it.nickname == shard || it.shard == shard)\n ?.byte || '');\n}\nexport function fromZone(zone, key) {\n return ZoneData.find((it) => it.byte == zone)?.[key] || '';\n}\n//# sourceMappingURL=zones.js.map","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`Wrong positive integer: ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`Expected boolean, not ${b}`);\n}\nfunction bytes(b, ...lengths) {\n if (!(b instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nconst u8a = (a) => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n if (!u8a(data))\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { hmac } from './hmac.js';\nimport { createView, toBytes, checkOpts, asyncLoop } from './utils.js';\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n assertHash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n assertNumber(c);\n assertNumber(dkLen);\n assertNumber(asyncTick);\n if (c < 1)\n throw new Error('PBKDF2: iterations (c) should be >= 1');\n const password = toBytes(_password);\n const salt = toBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\nfunction pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW)\n prfW.destroy();\n u.fill(0);\n return DK;\n}\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n */\nexport function pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\nexport async function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n//# sourceMappingURL=pbkdf2.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Base SHA2 class (RFC 6234)\nexport class SHA2 extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_sha2.js.map","import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Choice: a ? b : c\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2 {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { SHA2 } from './_sha2.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends SHA2 {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/* Browser Crypto Shims */\nimport { hmac } from '@noble/hashes/hmac';\nimport { pbkdf2 } from '@noble/hashes/pbkdf2';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { assert, assertArgument } from '../utils/index.js';\nfunction getGlobal() {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('unable to locate global object');\n}\nconst anyGlobal = getGlobal();\nconst crypto = anyGlobal.crypto || anyGlobal.msCrypto;\nexport function createHash(algo) {\n switch (algo) {\n case 'sha256':\n return sha256.create();\n case 'sha512':\n return sha512.create();\n }\n assertArgument(false, 'invalid hashing algorithm name', 'algorithm', algo);\n}\nexport function createHmac(_algo, key) {\n const algo = { sha256, sha512 }[_algo];\n assertArgument(algo != null, 'invalid hmac algorithm', 'algorithm', _algo);\n return hmac.create(algo, key);\n}\nexport function pbkdf2Sync(password, salt, iterations, keylen, _algo) {\n const algo = { sha256, sha512 }[_algo];\n assertArgument(algo != null, 'invalid pbkdf2 algorithm', 'algorithm', _algo);\n return pbkdf2(algo, password, salt, { c: iterations, dkLen: keylen });\n}\nexport function randomBytes(length) {\n assert(crypto != null, 'platform does not support secure random numbers', 'UNSUPPORTED_OPERATION', {\n operation: 'randomBytes',\n });\n assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, 'invalid length', 'length', length);\n const result = new Uint8Array(length);\n crypto.getRandomValues(result);\n return result;\n}\n//# sourceMappingURL=crypto-browser.js.map","/**\n * An **HMAC** enables verification that a given key was used to authenticate a payload.\n *\n * @see {@link https://en.wikipedia.org/wiki/HMAC | HMAC - Wikipedia}\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 `algo` used for compression.\n *\n * @category Crypto\n * @example\n *\n * ```js\n * key = id('some-secret');\n *\n * // Compute the HMAC\n * computeHmac('sha256', key, '0x1337');\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 * ```\n *\n * @param {'sha256' | 'sha512'} algorithm - The algorithm to use for compression.\n * @param {BytesLike} _key - The key to use for the HMAC.\n * @param {BytesLike} _data - The data to authenticate.\n * @returns {string} The HMAC of the data.\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 () {\n locked = true;\n};\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","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n keccakP(this.state32, this.rounds);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","/**\n * Cryptographic hashing functions\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 hash of UTF-8 data use the [**id**}(../functions/id)\n * function.\n *\n * @category Crypto\n * @example\n *\n * ```ts\n * keccak256('0x');\n *\n * keccak256('0x1337');\n *\n * keccak256(new Uint8Array([0x13, 0x37]));\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 * ```\n *\n * @param {BytesLike} _data - The data to hash.\n * @returns DataHexstring\n * @returns {string} The hash of the data.\n */\nexport function keccak256(_data) {\n const data = getBytes(_data, 'data');\n return hexlify(__keccak256(data));\n}\nkeccak256._ = _keccak256;\nkeccak256.lock = function () {\n locked = true;\n};\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 { SHA2 } from './_sha2.js';\nimport { wrapConstructor } from './utils.js';\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\nconst Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);\nconst Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i);\nconst Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);\nlet idxL = [Id];\nlet idxR = [Pi];\nfor (let i = 0; i < 4; i++)\n for (let j of [idxL, idxR])\n j.push(j[i].map((k) => Rho[k]));\nconst shifts = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => new Uint8Array(i));\nconst shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst Kl = /* @__PURE__ */ new Uint32Array([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr = /* @__PURE__ */ new Uint32Array([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// The rotate left (circular left shift) operation for uint32\nconst rotl = (word, shift) => (word << shift) | (word >>> (32 - shift));\n// It's called f() in spec.\nfunction f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n else if (group === 1)\n return (x & y) | (~x & z);\n else if (group === 2)\n return (x | ~y) ^ z;\n else if (group === 3)\n return (x & z) | (y & ~z);\n else\n return x ^ (y | ~z);\n}\n// Temporary buffer, not used to store anything between runs\nconst BUF = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends SHA2 {\n constructor() {\n super(64, 20, 8, true);\n this.h0 = 0x67452301 | 0;\n this.h1 = 0xefcdab89 | 0;\n this.h2 = 0x98badcfe | 0;\n this.h3 = 0x10325476 | 0;\n this.h4 = 0xc3d2e1f0 | 0;\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n BUF.fill(0);\n }\n destroy() {\n this.destroyed = true;\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a hash function from 1990s.\n * @param message - msg that would be hashed\n */\nexport const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());\n//# sourceMappingURL=ripemd160.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 * @category Crypto\n * @example\n *\n * ```ts\n * ripemd160('0x');\n *\n * ripemd160('0x1337');\n *\n * ripemd160(new Uint8Array([0x13, 0x37]));\n * ```\n *\n * @param {BytesLike} _data - The data to hash.\n * @returns DataHexstring\n * @returns {string} The hash of the data.\n */\nexport function ripemd160(_data) {\n const data = getBytes(_data, 'data');\n return hexlify(__ripemd160(data));\n}\nripemd160._ = _ripemd160;\nripemd160.lock = function () {\n locked = true;\n};\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 a sequence of bytes suitible as a **key** from a\n * human-rememberable password.\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 [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) for `keylen` bytes for `password` using the `salt` and\n * using `iterations` of `algo`.\n *\n * This PBKDF is outdated and should not be used in new projects, but is required to decrypt older files.\n *\n * @category Crypto\n * @example\n *\n * ```ts\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 * ```\n *\n * @param {BytesLike} _password - The password to use.\n * @param {BytesLike} _salt - The salt to use.\n * @param {number} iterations - The number of iterations to use.\n * @param {number} keylen - The length of the key to generate.\n * @param {'sha256' | 'sha512'} algo - The algorithm to use.\n * @returns {string} The key derived from the password.\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 () {\n locked = true;\n};\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 generated with additional care take to prevent\n * side-channels from allowing others to detect it and prevent others from through coincidence generate the same\n * values.\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 * @category Crypto\n * @example\n *\n * ```ts\n * randomBytes(8);\n * ```\n *\n * @param {number} length - The number of bytes to generate.\n * @returns {Uint8Array} The random bytes.\n */\nexport function randomBytes(length) {\n return __randomBytes(length);\n}\nrandomBytes._ = _randomBytes;\nrandomBytes.lock = function () {\n locked = true;\n};\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 { number as assertNumber } from './_assert.js';\nimport { sha256 } from './sha256.js';\nimport { pbkdf2 } from './pbkdf2.js';\nimport { asyncLoop, checkOpts, u32 } from './utils.js';\n// RFC 7914 Scrypt KDF\n// Left rotate for uint32\nconst rotl = (a, b) => (a << b) | (a >>> (32 - b));\n// The main Scrypt loop: uses Salsa extensively.\n// Six versions of the function were tried, this is the fastest one.\n// prettier-ignore\nfunction XorAndSalsa(prev, pi, input, ii, out, oi) {\n // Based on https://cr.yp.to/salsa20.html\n // Xor blocks\n let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];\n let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];\n let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];\n let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];\n let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];\n let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];\n let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];\n let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];\n // Save state to temporary variables (salsa)\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n // Main loop (salsa)\n for (let i = 0; i < 8; i += 2) {\n x04 ^= rotl(x00 + x12 | 0, 7);\n x08 ^= rotl(x04 + x00 | 0, 9);\n x12 ^= rotl(x08 + x04 | 0, 13);\n x00 ^= rotl(x12 + x08 | 0, 18);\n x09 ^= rotl(x05 + x01 | 0, 7);\n x13 ^= rotl(x09 + x05 | 0, 9);\n x01 ^= rotl(x13 + x09 | 0, 13);\n x05 ^= rotl(x01 + x13 | 0, 18);\n x14 ^= rotl(x10 + x06 | 0, 7);\n x02 ^= rotl(x14 + x10 | 0, 9);\n x06 ^= rotl(x02 + x14 | 0, 13);\n x10 ^= rotl(x06 + x02 | 0, 18);\n x03 ^= rotl(x15 + x11 | 0, 7);\n x07 ^= rotl(x03 + x15 | 0, 9);\n x11 ^= rotl(x07 + x03 | 0, 13);\n x15 ^= rotl(x11 + x07 | 0, 18);\n x01 ^= rotl(x00 + x03 | 0, 7);\n x02 ^= rotl(x01 + x00 | 0, 9);\n x03 ^= rotl(x02 + x01 | 0, 13);\n x00 ^= rotl(x03 + x02 | 0, 18);\n x06 ^= rotl(x05 + x04 | 0, 7);\n x07 ^= rotl(x06 + x05 | 0, 9);\n x04 ^= rotl(x07 + x06 | 0, 13);\n x05 ^= rotl(x04 + x07 | 0, 18);\n x11 ^= rotl(x10 + x09 | 0, 7);\n x08 ^= rotl(x11 + x10 | 0, 9);\n x09 ^= rotl(x08 + x11 | 0, 13);\n x10 ^= rotl(x09 + x08 | 0, 18);\n x12 ^= rotl(x15 + x14 | 0, 7);\n x13 ^= rotl(x12 + x15 | 0, 9);\n x14 ^= rotl(x13 + x12 | 0, 13);\n x15 ^= rotl(x14 + x13 | 0, 18);\n }\n // Write output (salsa)\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\nfunction BlockMix(input, ii, out, oi, r) {\n // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)\n let head = oi + 0;\n let tail = oi + 16 * r;\n for (let i = 0; i < 16; i++)\n out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]\n for (let i = 0; i < r; i++, head += 16, ii += 16) {\n // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1\n XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])\n if (i > 0)\n tail += 16; // First iteration overwrites tmp value in tail\n XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])\n }\n}\n// Common prologue and epilogue for sync/async functions\nfunction scryptInit(password, salt, _opts) {\n // Maxmem - 1GB+1KB by default\n const opts = checkOpts({\n dkLen: 32,\n asyncTick: 10,\n maxmem: 1024 ** 3 + 1024,\n }, _opts);\n const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;\n assertNumber(N);\n assertNumber(r);\n assertNumber(p);\n assertNumber(dkLen);\n assertNumber(asyncTick);\n assertNumber(maxmem);\n if (onProgress !== undefined && typeof onProgress !== 'function')\n throw new Error('progressCb should be function');\n const blockSize = 128 * r;\n const blockSize32 = blockSize / 4;\n if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) {\n // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function\n // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future.\n throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32');\n }\n if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) {\n throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');\n }\n if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) {\n throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');\n }\n const memUsed = blockSize * (N + p);\n if (memUsed > maxmem) {\n throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`);\n }\n // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)\n // Since it has only one iteration there is no reason to use async variant\n const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });\n const B32 = u32(B);\n // Re-used between parallel iterations. Array(iterations) of B\n const V = u32(new Uint8Array(blockSize * N));\n const tmp = u32(new Uint8Array(blockSize));\n let blockMixCb = () => { };\n if (onProgress) {\n const totalBlockMix = 2 * N * p;\n // Invoke callback if progress changes from 10.01 to 10.02\n // Allows to draw smooth progress bar on up to 8K screen\n const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);\n let blockMixCnt = 0;\n blockMixCb = () => {\n blockMixCnt++;\n if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))\n onProgress(blockMixCnt / totalBlockMix);\n };\n }\n return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };\n}\nfunction scryptOutput(password, dkLen, B, V, tmp) {\n const res = pbkdf2(sha256, password, B, { c: 1, dkLen });\n B.fill(0);\n V.fill(0);\n tmp.fill(0);\n return res;\n}\n/**\n * Scrypt KDF from RFC 7914.\n * @param password - pass\n * @param salt - salt\n * @param opts - parameters\n * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)\n * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance\n * - `p` is parallelization factor (1 is common)\n * - `dkLen` is output key length in bytes e.g. 32.\n * - `asyncTick` - (default: 10) max time in ms for which async function can block execution\n * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt\n * - `onProgress` - callback function that would be executed for progress report\n * @returns Derived key\n */\nexport function scrypt(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n for (let i = 0, pos = 0; i < N - 1; i++) {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n }\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n for (let i = 0; i < N; i++) {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n }\n }\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n/**\n * Scrypt KDF from RFC 7914.\n */\nexport async function scryptAsync(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n let pos = 0;\n await asyncLoop(N - 1, asyncTick, () => {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n });\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n await asyncLoop(N, asyncTick, () => {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n });\n }\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n//# sourceMappingURL=scrypt.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 [scrypt PBKDF](https://en.wikipedia.org/wiki/Scrypt) uses a memory and cpu hard method of derivation to increase\n * the resource cost to brute-force a password for a given key.\n *\n * This means this algorithm is intentionally slow, and can be tuned to become slower. As computation and memory speed\n * improve over time, 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 which knows their password requires only 5\n * seconds to unlock their account. A 6 character password has 68 billion possibilities, which would require an attacker\n * to invest over 10,000 years of CPU time. This is of course a crude example (as password generally aren't random), but\n * demonstrates to value of imposing large costs to decryption.\n *\n * For this reason, if building a UI which involved decrypting or encrypting datsa using scrypt, it is recommended to\n * use a [**ProgressCallback**](../types-aliases/ProgressCallback) (as event short periods can seem lik an eternity if\n * the UI freezes). Including the phrase //\"decrypting\"// in the UI can also help, assuring the user their waiting is\n * for a good reason.\n *\n * @category Crypto\n * @example\n *\n * ```ts\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 * ```\n *\n * @param {BytesLike} _passwd - The password to use.\n * @param {BytesLike} _salt - The salt to use.\n * @param {number} N - The CPU/memory cost parameter.\n * @param {number} r - The block size parameter.\n * @param {number} p - The parallelization parameter.\n * @param {number} dkLen - The length of the key to generate.\n * @param {ProgressCallback} [progress] - A callback to update the progress.\n * @returns {Promise} The key derived from the password.\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 () {\n lockedAsync = true;\n};\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 {@link scrypt | **scrypt**}.\n *\n * This will completely lock up and freeze the UI in a browser and will prevent any event loop from progressing. For\n * this reason, it is preferred to use the [async variant](scrypt).\n *\n * @category Crypto\n * @example\n *\n * ```ts\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 * ```\n *\n * @param {BytesLike} _passwd - The password to use.\n * @param {BytesLike} _salt - The salt to use.\n * @param {number} N - The CPU/memory cost parameter.\n * @param {number} r - The block size parameter.\n * @param {number} p - The parallelization parameter.\n * @param {number} dkLen - The length of the key to generate.\n * @returns {string} The key derived from the password.\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 () {\n lockedSync = true;\n};\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 * @category Crypto\n * @example\n *\n * ```ts\n * sha256('0x');\n *\n * sha256('0x1337');\n *\n * sha256(new Uint8Array([0x13, 0x37]));\n * ```\n *\n * @param {BytesLike} _data - The data to hash.\n * @returns {string} The hash of the data.\n */\nexport function sha256(_data) {\n const data = getBytes(_data, 'data');\n return hexlify(__sha256(data));\n}\nsha256._ = _sha256;\nsha256.lock = function () {\n locked256 = true;\n};\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 * @category Crypto\n * @example\n *\n * ```ts\n * sha512('0x');\n *\n * sha512('0x1337');\n *\n * sha512(new Uint8Array([0x13, 0x37]));\n * ```\n *\n * @param {BytesLike} _data - The data to hash.\n * @returns {string} The hash of the data.\n */\nexport function sha512(_data) {\n const data = getBytes(_data, 'data');\n return hexlify(__sha512(data));\n}\nsha512._ = _sha512;\nsha512.lock = function () {\n locked512 = true;\n};\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","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst u8a = (a) => a instanceof Uint8Array;\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (u8a(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\nexport function equalBytes(b1, b2) {\n // We don't care about timing attacks here\n if (b1.length !== b2.length)\n return false;\n for (let i = 0; i < b1.length; i++)\n if (b1[i] !== b2[i])\n return false;\n return true;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n, pos, value) => {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n};\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array,\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, numberToBytesBE, numberToBytesLE, bytesToNumberBE, bytesToNumberLE, ensureBytes, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x) => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, precomputesMap, n, transform) {\n // @ts-ignore\n const W = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes } from './utils.js';\nimport { wNAF, validateBasic } from './curve.js';\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data) {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02)\n throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len)\n throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000)\n throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n if (!(data instanceof Uint8Array))\n throw new Error('ui8a expected');\n let l = data.length;\n if (l < 2 || data[0] != 0x30)\n throw new E('Invalid signature tag');\n if (data[1] !== l - 2)\n throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig) {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num) {\n if (!isWithinCurveOrder(num))\n throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (key instanceof Uint8Array)\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n const pointPrecomputes = new Map();\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n) {\n const I = Point.ZERO;\n if (n === _0n)\n return I;\n assertGE(n); // Will throw on 0\n if (n === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, n);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n assertGE(scalar);\n let n = scalar;\n let point, fake; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function isValidFieldElement(num) {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r))\n throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s))\n throw new Error('s must be 0 < s < CURVE.n');\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = item instanceof Uint8Array;\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n if (typeof num !== 'bigint')\n throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || sg instanceof Uint8Array) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\nexport const secp256k1 = createCurve({\n a: BigInt(0),\n b: BigInt(7),\n Fp,\n n: secp256k1N,\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true,\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n if (!fe(x))\n throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!fe(r))\n return false;\n const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!ge(s))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","/**\n * A constant for the zero address.\n *\n * (**i.e.** `\"0x0000000000000000000000000000000000000000\"`)\n *\n * @category Constants\n */\nexport const ZeroAddress = '0x0000000000000000000000000000000000000000';\n//# sourceMappingURL=addresses.js.map","/**\n * A constant for the zero hash.\n *\n * (**i.e.** `\"0x0000000000000000000000000000000000000000000000000000000000000000\"`)\n *\n * @category Constants\n */\nexport const ZeroHash = '0x0000000000000000000000000000000000000000000000000000000000000000';\n//# sourceMappingURL=hashes.js.map","/**\n * A constant for the order N for the secp256k1 curve.\n *\n * (**i.e.** `0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n`)\n *\n * @category Constants\n */\nexport const N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\n/**\n * A constant for the number of wei in a single ether.\n *\n * (**i.e.** `1000000000000000000n`)\n *\n * @category Constants\n */\nexport const WeiPerEther = BigInt('1000000000000000000');\n/**\n * A constant for the maximum value for a `uint256`.\n *\n * (**i.e.** `0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn`)\n *\n * @category Constants\n */\nexport const MaxUint256 = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\n/**\n * A constant for the minimum value for an `int256`.\n *\n * (**i.e.** `-8000000000000000000000000000000000000000000000000000000000000000n`)\n *\n * @category Constants\n */\nexport const MinInt256 = BigInt('0x8000000000000000000000000000000000000000000000000000000000000000') * BigInt(-1);\n/**\n * A constant for the maximum value for an `int256`.\n *\n * (**i.e.** `0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn`)\n *\n * @category Constants\n */\nexport const MaxInt256 = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\n//# sourceMappingURL=numbers.js.map","// NFKC (composed) // (decomposed)\n/**\n * A constant for the ether symbol (normalized using NFKC).\n *\n * (**i.e.** `\"\\\\u039e\"`)\n *\n * @category Constants\n */\nexport const quaisymbol = '\\u039e'; // \"\\uD835\\uDF63\";\n/**\n * A constant for the Quai Network equivalent of the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal message\n * prefix.\n *\n * (**i.e.** `\"\\\\x19Quai Signed Message:\\\\n\"`)\n *\n * @category Constants\n */\nexport const MessagePrefix = '\\x19Quai Signed Message:\\n';\n/**\n * A constant for the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal message prefix.\n *\n * (**i.e.** `\"\\\\x19Ethereum Signed Message:\\\\n\"`)\n *\n * @category Constants\n */\nexport const EthMessagePrefix = '\\x19Ethereum Signed Message:\\n';\n//# sourceMappingURL=strings.js.map","import { ZoneData } from './zones.js';\n/**\n * A shard represents a chain within the Quai network hierarchy. A shard refer to the Prime chain, a region under the\n * Prime chain, or a Zone within a region. The value is a hexadecimal string representing the encoded value of the\n * shard. Read more [here](https://github.com/quai-network/qips/blob/master/qip-0002.md).\n *\n * @category Constants\n */\nexport var Shard;\n(function (Shard) {\n Shard[\"Cyprus\"] = \"0x0\";\n Shard[\"Cyprus1\"] = \"0x00\";\n Shard[\"Cyprus2\"] = \"0x01\";\n Shard[\"Cyprus3\"] = \"0x02\";\n Shard[\"Paxos\"] = \"0x1\";\n Shard[\"Paxos1\"] = \"0x10\";\n Shard[\"Paxos2\"] = \"0x11\";\n Shard[\"Paxos3\"] = \"0x12\";\n Shard[\"Hydra\"] = \"0x2\";\n Shard[\"Hydra1\"] = \"0x20\";\n Shard[\"Hydra2\"] = \"0x21\";\n Shard[\"Hydra3\"] = \"0x22\";\n Shard[\"Prime\"] = \"0x\";\n})(Shard || (Shard = {}));\nfunction shardFromBytes(shard) {\n switch (shard) {\n case '0x':\n return Shard.Prime;\n case '0x0':\n return Shard.Cyprus;\n case '0x1':\n return Shard.Paxos;\n case '0x2':\n return Shard.Hydra;\n case '0x00':\n return Shard.Cyprus1;\n case '0x01':\n return Shard.Cyprus2;\n case '0x02':\n return Shard.Cyprus3;\n case '0x10':\n return Shard.Paxos1;\n case '0x11':\n return Shard.Paxos2;\n case '0x12':\n return Shard.Paxos3;\n case '0x20':\n return Shard.Hydra1;\n case '0x21':\n return Shard.Hydra2;\n case '0x22':\n return Shard.Hydra3;\n default:\n throw new Error('Invalid shard');\n }\n}\n/**\n * Constant data that defines each shard within the network.\n *\n * @category Constants\n */\nexport const ShardData = [\n ...ZoneData,\n {\n name: 'Cyprus',\n nickname: 'cyprus',\n shard: 'region-0',\n context: 2,\n byte: '0x0',\n },\n {\n name: 'Paxos',\n nickname: 'paxos',\n shard: 'region-1',\n context: 2,\n byte: '0x1',\n },\n {\n name: 'Hydra',\n nickname: 'hydra',\n shard: 'region-2',\n context: 2,\n byte: '0x2',\n },\n {\n name: 'Prime',\n nickname: 'prime',\n shard: 'prime',\n context: 2,\n byte: '0x',\n },\n];\nexport function toShard(shard) {\n return shardFromBytes(ShardData.find((it) => it.name == shard || it.byte == shard || it.nickname == shard || it.shard == shard)\n ?.byte || '');\n}\nexport function fromShard(shard, key) {\n return ShardData.find((it) => it.byte == shard)?.[key] || '';\n}\n//# sourceMappingURL=shards.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 * @category Crypto\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 challenge point, from which the `y` can be computed.\n */\n get r() {\n return this.#r;\n }\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() {\n return this.#s;\n }\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 its correspondin `y`, the `v` indicates which of the\n * two `y` values to use.\n *\n * It is normalized to the values `27` or `28` for legacy purposes.\n */\n get v() {\n return this.#v;\n }\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 transactions, this value is `null`.\n */\n get networkV() {\n return this.#networkV;\n }\n /**\n * The chain ID for EIP-155 legacy transactions. For non-legacy 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 [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098) compact representation of the `yParity` and `s` compacted\n * 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 [EIP-2098](https://eips.ethereum.org/EIPS/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 * @ignore\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 {@link Signature | **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,\n s: this.s,\n v: this.v,\n };\n }\n /**\n * Compute the chain ID from the `v` in a legacy EIP-155 transactions.\n *\n * @example\n *\n * ```ts\n * Signature.getChainId(45);\n *\n * Signature.getChainId(46);\n * ```\n *\n * @param {BigNumberish} v - The `v` value from the signature.\n * @returns {bigint} The chain ID.\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 [EIP-155](https://eips.ethereum.org/EIPS/eip-155) hijack the `v` property to\n * include the chain ID.\n *\n * @example\n *\n * ```ts\n * Signature.getChainIdV(5, 27);\n *\n * Signature.getChainIdV(5, 28);\n * ```\n *\n * @param {BigNumberish} chainId - The chain ID.\n * @param {27 | 28} v - The `v` value.\n * @returns {bigint} The `v` value.\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`, a legacy transaction `v` or a legacy\n * [EIP-155](https://eips.ethereum.org/EIPS/eip-155) transaction.\n *\n * @example\n *\n * ```ts\n * // The values 0 and 1 imply v is actually yParity\n * Signature.getNormalizedV(0);\n *\n * // Legacy non-EIP-1559 transaction (i.e. 27 or 28)\n * Signature.getNormalizedV(27);\n *\n * // Legacy EIP-155 transaction (i.e. >= 35)\n * Signature.getNormalizedV(46);\n *\n * // Invalid values throw\n * Signature.getNormalizedV(5);\n * ```\n *\n * @param {BigNumberish} v - The `v` value.\n * @returns {27 | 28} The normalized `v` value.\n * @throws {Error} Thrown if the `v` is invalid.\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 {@link Signature | **Signature**}.\n *\n * If no `sig` is provided, a new {@link Signature | **Signature**} is created with default values.\n *\n * If `sig` is a string, it is parsed.\n *\n * @param {SignatureLike} [sig] - The signature to create.\n * @returns {Signature} The new signature.\n */\n static from(sig) {\n function assertError(check, message) {\n assertArgument(check, message, 'signature', sig);\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 (yParity) {\n case 0:\n return { v: 27 };\n case 1:\n 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(!('yParity' in sig && sig.yParity !== result.yParity), 'yParity mismatch');\n assertError(!('yParityAndS' in sig && sig.yParityAndS !== result.yParityAndS), 'yParityAndS mismatch');\n return result;\n }\n}\n//# sourceMappingURL=signature.js.map","/**\n * Add details about signing here.\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 cryptography (ECC) operations and key management.\n *\n * @category Crypto\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() {\n return this.#privateKey;\n }\n /**\n * The uncompressed public key.\n *\n * This will always begin with the prefix `0x04` and be 132 characters long (the `0x` prefix and 130 hexadecimal\n * nibbles).\n */\n get publicKey() {\n return SigningKey.computePublicKey(this.#privateKey);\n }\n /**\n * The compressed public key.\n *\n * This will always begin with either the prefix `0x02` or `0x03` and be 68 characters long (the `0x` prefix and 33\n * hexadecimal nibbles)\n */\n get compressedPublicKey() {\n return SigningKey.computePublicKey(this.#privateKey, true);\n }\n /**\n * Return the signature of the signed `digest`.\n *\n * @param {BytesLike} digest - The data to sign.\n * @returns {Signature} The signature of the data.\n * @throws {Error} If the digest is not 32 bytes long.\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('0x' + sig.r.toString(16), 32),\n s: toBeHex('0x' + sig.s.toString(16), 32),\n v: sig.recovery ? 0x1c : 0x1b,\n });\n }\n /**\n * Returns the [ECDH](https://en.wikipedia.org/wiki/Elliptic-curve_Diffie-Hellman) 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, a compressed/uncompressed pubic key or aprivate key.\n *\n * Best practice is usually to use a cryptographic hash on the returned value before using it as a symetric secret.\n *\n * @example\n *\n * ```ts\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 *\n * // ...is equal to privB.computeSharedSecret(pubA).\n * sign2.computeSharedSecret(sign1.publicKey);\n * ```\n *\n * @param {BytesLike} other - The other key to compute the shared secret with.\n * @returns {string} The shared secret.\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 compressed/uncompressed public key or private key.\n *\n * @example\n *\n * ```ts\n * sign = new SigningKey(id('some-secret'));\n *\n * // Compute the uncompressed public key for a private key\n * SigningKey.computePublicKey(sign.privateKey);\n *\n * // Compute the compressed public key for a private key\n * SigningKey.computePublicKey(sign.privateKey, true);\n *\n * // Compute the uncompressed public key\n * SigningKey.computePublicKey(sign.publicKey, false);\n *\n * // Compute the Compressed a public key\n * SigningKey.computePublicKey(sign.publicKey, true);\n * ```\n *\n * @param {BytesLike} key - The key to compute the public key for.\n * @param {boolean} [compressed] - Whether to return the compressed public key.\n * @returns {string} The public key.\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 `signature` for the given `digest`.\n *\n * @example\n *\n * ```ts\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 *\n * // ...is equal to the recovered public key\n * SigningKey.recoverPublicKey(digest, sig);\n * ```\n *\n * @param {BytesLike} digest - The data that was signed.\n * @param {SignatureLike} signature - The signature of the data.\n * @returns {string} The public key.\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 `p0` and `p1`.\n *\n * This is not a common function most developers should require, but can be useful for certain privacy-specific\n * techniques.\n *\n * For example, it is used by [**QuaiHDWallet**](../classes/QuaiHDWallet) to compute child addresses from parent\n * public keys and chain codes.\n *\n * @param {BytesLike} p0 - The first point to add.\n * @param {BytesLike} p1 - The second point to add.\n * @param {boolean} [compressed] - Whether to return the compressed public key.\n * @returns {string} The sum of the points.\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 { sha256 } from '@noble/hashes/sha256';\nimport { secp256k1, schnorr } from '@noble/curves/secp256k1';\n// BigInt / Uint8Array versions of Crypto functions that do not require point\n// math. If your JS interpreter has BigInt, you can use all of these. If not,\n// you'll need to either shim it in or override more of these functions.\n// Idea from noble-secp256k1, be nice to bad JS parsers\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _3n = BigInt(3);\nconst _5n = BigInt(5);\nconst _7n = BigInt(7);\nconst _64n = BigInt(64);\nconst _64mask = BigInt('0xFFFFFFFFFFFFFFFF');\nconst CURVE = {\n b: BigInt(7),\n P: BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'),\n n: BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141'),\n};\n// Big Endian\nfunction read32b(bytes) {\n if (bytes.length !== 32)\n throw new Error(`Expected 32-bytes, not ${bytes.length}`);\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);\n let b = view.getBigUint64(0);\n for (let offs = 8; offs < bytes.length; offs += 8) {\n b <<= _64n;\n b += view.getBigUint64(offs);\n }\n return b;\n}\nfunction write32b(num, dest = new Uint8Array(32)) {\n // All input values are modulo P or n, so no bounds checking needed\n const view = new DataView(dest.buffer, dest.byteOffset, dest.length);\n for (let offs = 24; offs >= 0; offs -= 8) {\n view.setBigUint64(offs, num & _64mask);\n num >>= _64n;\n }\n return dest;\n}\nfunction readScalar(bytes) {\n const a = read32b(bytes);\n if (a >= CURVE.n)\n throw new Error('Expected value mod n');\n return a;\n}\nfunction readSecret(bytes) {\n const a = readScalar(bytes);\n if (a === 0n)\n throw new Error('Expected non-zero');\n return a;\n}\n// The short Weierstrass form curve equation simplifes to y^2 = x^3 + 7.\nfunction secp256k1Right(x) {\n const x2 = (x * x) % CURVE.P;\n const x3 = (x2 * x) % CURVE.P;\n return (x3 + CURVE.b) % CURVE.P;\n}\n// For prime P, the Jacobi Symbol of 'a' is 1 if and only if 'a' is a quadratic\n// residue mod P, ie. there exists a value 'x' for whom x^2 = a.\nfunction jacobiSymbol(a) {\n if (a === _0n)\n return 0; // Vanishingly improbable\n let p = CURVE.P;\n let sign = 1;\n // This algorithm is fairly heavily optimized, so don't simplify it w/o benchmarking\n for (;;) {\n let and3;\n // Handle runs of zeros efficiently w/o flipping sign each time\n for (and3 = a & _3n; and3 === _0n; a >>= _2n, and3 = a & _3n)\n ;\n // If there's one more zero, shift it off and flip the sign\n if (and3 === _2n) {\n a >>= _1n;\n const pand7 = p & _7n;\n if (pand7 === _3n || pand7 === _5n)\n sign = -sign;\n }\n if (a === _1n)\n break;\n if ((_3n & a) === _3n && (_3n & p) === _3n)\n sign = -sign;\n [a, p] = [p % a, a];\n }\n return sign > 0 ? 1 : -1;\n}\nfunction isPoint(p) {\n if (p.length < 33)\n return false;\n const t = p[0];\n if (p.length === 33) {\n return (t === 0x02 || t === 0x03) && isXOnlyPoint(p.subarray(1));\n }\n if (t !== 0x04 || p.length !== 65)\n return false;\n const x = read32b(p.subarray(1, 33));\n if (x === _0n)\n return false;\n if (x >= CURVE.P)\n return false;\n const y = read32b(p.subarray(33));\n if (y === _0n)\n return false;\n if (y >= CURVE.P)\n return false;\n const left = (y * y) % CURVE.P;\n const right = secp256k1Right(x);\n return left === right;\n}\nfunction isXOnlyPoint(p) {\n if (p.length !== 32)\n return false;\n const x = read32b(p);\n if (x === _0n)\n return false;\n if (x >= CURVE.P)\n return false;\n const y2 = secp256k1Right(x);\n return jacobiSymbol(y2) === 1; // If sqrt(y^2) exists, x is on the curve.\n}\nfunction scalarAdd(a, b) {\n const aN = readScalar(a);\n const bN = readScalar(b);\n const sum = (aN + bN) % CURVE.n;\n return write32b(sum);\n}\nfunction scalarMultiply(a, b) {\n const aN = readScalar(a);\n const bN = readScalar(b);\n const product = (aN * bN) % CURVE.n;\n return write32b(product);\n}\nfunction scalarNegate(a) {\n const aN = readScalar(a);\n const negated = aN === _0n ? _0n : CURVE.n - aN;\n return write32b(negated);\n}\nfunction scalarMod(a) {\n const aN = read32b(a);\n const remainder = aN % CURVE.n;\n return write32b(remainder);\n}\nfunction isScalar(t) {\n try {\n readScalar(t);\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isSecret(s) {\n try {\n readSecret(s);\n return true;\n }\n catch {\n return false;\n }\n}\nfunction pointNegate(p) {\n // hasEvenY does basic structure check, so start there\n const even = hasEvenY(p);\n // `from` because node.Buffer.slice doesn't copy but looks like a Uint8Array\n const negated = Uint8Array.from(p);\n if (p.length === 33) {\n negated[0] = even ? 3 : 2;\n }\n else if (p.length === 65) {\n const y = read32b(p.subarray(33));\n if (y >= CURVE.P)\n throw new Error('Expected Y coordinate mod P');\n const minusY = y === _0n ? _0n : CURVE.P - y;\n write32b(minusY, negated.subarray(33));\n }\n return negated;\n}\nfunction pointX(p) {\n if (p.length === 32)\n return p;\n hasEvenY(p); // hasEvenY throws if not well structured\n return p.slice(1, 33);\n}\nfunction hasEvenY(p) {\n if (p.length === 33) {\n if (p[0] === 2)\n return true;\n else if (p[0] === 3)\n return false;\n else\n throw new Error('Wrong first byte to be a point');\n }\n if (p.length === 65) {\n if (p[0] !== 4)\n throw new Error('Wrong first byte to be point');\n return p[64] % 2 === 0;\n }\n throw new Error('Wrong length to be a point');\n}\nfunction pointMultiplyUnsafe(p, a, compress) {\n try {\n const product = secp256k1.ProjectivePoint.fromHex(p).multiplyAndAddUnsafe(secp256k1.ProjectivePoint.ZERO, BigInt(`0x${Buffer.from(a).toString('hex')}`), BigInt(1));\n if (!product)\n return null;\n return product.toRawBytes(compress);\n }\n catch {\n return null;\n }\n}\nfunction pointMultiplyAndAddUnsafe(p1, a, p2, compress) {\n try {\n const p2p = secp256k1.ProjectivePoint.fromHex(p2);\n const p = secp256k1.ProjectivePoint.fromHex(p1).multiplyAndAddUnsafe(p2p, BigInt(`0x${Buffer.from(a).toString('hex')}`), BigInt(1));\n if (!p)\n return null;\n return p.toRawBytes(compress);\n }\n catch {\n return null;\n }\n}\nfunction pointAdd(a, b, compress) {\n try {\n return secp256k1.ProjectivePoint.fromHex(a).add(secp256k1.ProjectivePoint.fromHex(b)).toRawBytes(compress);\n }\n catch {\n return null;\n }\n}\nfunction pointAddTweak(p, tweak, compress) {\n try {\n const P = secp256k1.ProjectivePoint.fromHex(p);\n const t = readSecret(tweak);\n const Q = secp256k1.ProjectivePoint.BASE.multiplyAndAddUnsafe(P, t, 1n);\n if (!Q)\n throw new Error('Tweaked point at infinity');\n return Q.toRawBytes(compress);\n }\n catch {\n return null;\n }\n}\nfunction pointCompress(p, compress = true) {\n return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(compress);\n}\nfunction liftX(p) {\n try {\n return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(false);\n }\n catch {\n return null;\n }\n}\nfunction getPublicKey(s, compress) {\n try {\n return secp256k1.getPublicKey(s, compress);\n }\n catch {\n return null;\n }\n}\nfunction taggedHash(tag, ...messages) {\n return schnorr.utils.taggedHash(tag, ...messages);\n}\nfunction sha256Hash(...messages) {\n const h = sha256.create();\n for (const message of messages)\n h.update(message);\n return h.digest();\n}\nexport const musigCrypto = {\n read32b,\n write32b,\n readScalar,\n readSecret,\n secp256k1Right,\n jacobiSymbol,\n isPoint,\n isXOnlyPoint,\n scalarAdd,\n scalarMultiply,\n scalarNegate,\n scalarMod,\n isScalar,\n isSecret,\n pointNegate,\n pointX,\n hasEvenY,\n pointMultiplyUnsafe,\n pointMultiplyAndAddUnsafe,\n pointAdd,\n pointAddTweak,\n pointCompress,\n liftX,\n getPublicKey,\n taggedHash,\n sha256: sha256Hash,\n};\n//# sourceMappingURL=musig.js.map","/**\n * A fundamental building block of Ethereum is the underlying cryptographic primitives.\n */\nnull;\n// We import all these so we can export lock()\nimport { computeHmac } from './hmac.js';\nimport { keccak256 } from './keccak.js';\nimport { ripemd160 } from './ripemd160.js';\nimport { pbkdf2 } from './pbkdf2.js';\nimport { randomBytes } from './random.js';\nimport { scrypt, scryptSync } from './scrypt.js';\nimport { sha256, sha512 } from './sha2.js';\nexport { computeHmac, randomBytes, keccak256, ripemd160, sha256, sha512, pbkdf2, scrypt, scryptSync };\nexport { SigningKey } from './signing-key.js';\nexport { Signature } from './signature.js';\n/**\n * Once called, prevents any future change to the underlying cryptographic primitives using the `.register` feature for\n * hooks.\n *\n * @category Crypto\n */\nfunction lock() {\n computeHmac.lock();\n keccak256.lock();\n pbkdf2.lock();\n randomBytes.lock();\n ripemd160.lock();\n scrypt.lock();\n scryptSync.lock();\n sha256.lock();\n sha512.lock();\n randomBytes.lock();\n}\nexport { lock };\nexport { musigCrypto } from './musig.js';\n//# sourceMappingURL=index.js.map","import { keccak256, SigningKey } from '../crypto/index.js';\nimport { getBytes, assertArgument, concat, zeroPadValue, dataSlice, toBigInt, toBeHex, stripZerosLeft, } from '../utils/index.js';\nexport function formatMixedCaseChecksumAddress(address) {\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/**\n * Returns a normalized and checksumed address for `address`. This accepts non-checksum addressesa and checksum\n * addresses.\n *\n * The checksum in Quai uses the capitalization (upper-case 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 assumed to already be a checksum address and its checksum\n * is validated, and if the address fails its expected checksum an error is thrown.\n *\n * If you wish the checksum of `address` to be ignore, it should be converted to lower-case (i.e. `.toLowercase()`)\n * before being passed in. This should be a very rare situation though, that you wish to bypass the safeguards in place\n * to protect against an address that has been incorrectly copied from another source.\n *\n * @category Address\n * @example\n *\n * ```js\n * // Adds the checksum (via upper-casing specific letters)\n * getAddress('0x8ba1f109551bd432803012645ac136ddd64dba72');\n *\n * // Throws an error if an address contains mixed case,\n * // but the checksum fails\n * getAddress('0x8Ba1f109551bD432803012645Ac136ddd64DBA72');\n * ```\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 = formatMixedCaseChecksumAddress(address);\n // If original address is mix cased and recomputed version doesn't\n // match the original this could indicate a potential typo or mispaste.\n assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, 'invalid address checksum', 'address', address);\n return result;\n }\n assertArgument(false, 'invalid address string format', 'address', address);\n}\nexport function getContractAddress(from, nonce, data) {\n const nonceBytes = zeroPadValue(toBeHex(toBigInt(nonce)), 8);\n return getAddress(dataSlice(keccak256(concat([getAddress(from), nonceBytes, stripZerosLeft(data)])), 12));\n}\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 *\n * @category Address\n * @param {string | SigningKey} key - The key to compute the address for.\n * @returns {string} The address.\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 used to sign `digest` that resulted in `signature`.\n *\n * @category Address\n * @param {BytesLike} digest - The digest of the message.\n * @param {SignatureLike} signature - The signature.\n * @returns {string} The address.\n */\nexport function recoverAddress(digest, signature) {\n return computeAddress(SigningKey.recoverPublicKey(digest, signature));\n}\n//# sourceMappingURL=address.js.map","import { assertArgument } from '../utils/index.js';\nimport { formatMixedCaseChecksumAddress, getAddress } from './address.js';\n/**\n * Returns true if `value` is an object which implements the [**Addressable**](../interfaces/Addressable) interface.\n *\n * @category Address\n * @example\n *\n * ```js\n * // Wallets and AbstractSigner sub-classes\n * isAddressable(Wallet.createRandom());\n *\n * // Contracts\n * contract = new Contract('0x643aA0A61eADCC9Cc202D1915D942d35D005400C', [], provider);\n * isAddressable(contract);\n * ```\n *\n * @param {any} value - The value to check.\n * @returns {boolean} True if the value is an Addressable.\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 * @category Address\n * @example\n *\n * ```js\n * // Valid address\n * isAddress('0x8ba1f109551bD432803012645Ac136ddd64DBA72');\n *\n * // Invalid checksum\n * isAddress('0x8Ba1f109551bD432803012645Ac136ddd64DBa72');\n * ```\n *\n * @param {any} value - The value to check.\n * @returns {boolean} True if the value is a valid address.\n */\nexport function isAddress(value) {\n try {\n getAddress(value);\n return true;\n // eslint-disable-next-line no-empty\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 assertArgument(false, 'invalid AddressLike value; did not resolve to a value address', 'target', target);\n }\n return result;\n}\n/**\n * Resolves to an address for the `target`, which may be any supported address type, an\n * [**Addressable**](../interfaces/Addressable) or a Promise which resolves to an address.\n *\n * @category Address\n * @example\n *\n * ```js\n * addr = '0x6B175474E89094C44Da98b954EedeAC495271d0F';\n *\n * // Addresses are return synchronously\n * resolveAddress(addr, provider);\n *\n * // Address promises are resolved asynchronously\n * resolveAddress(Promise.resolve(addr));\n *\n * // Addressable objects are resolved asynchronously\n * contract = new Contract(addr, []);\n * resolveAddress(contract, provider);\n * ```\n *\n * @param {AddressLike} target - The target to resolve to an address.\n * @returns {string | Promise} The resolved address.\n */\nexport function resolveAddress(target) {\n if (typeof target === 'string') {\n if (target.match(/^0x[0-9a-f]{40}$/i)) {\n return target;\n }\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/**\n * Checks if the address is a valid mixed case checksummed address.\n *\n * @category Address\n * @param address - The address to validate.\n * @returns True if the address is a valid mixed case checksummed address.\n */\nexport function validateAddress(address) {\n assertArgument(typeof address === 'string', 'address must be string', 'address', address);\n assertArgument(Boolean(address.match(/^(0x)?[0-9a-fA-F]{40}$/)), 'invalid address string format', 'address', address);\n assertArgument(formatMixedCaseChecksumAddress(address) === address, 'invalid address checksum', 'address', address);\n}\n/**\n * Checks whether a given address is in the Qi ledger scope by checking the 9th bit of the address.\n *\n * @category Address\n * @param {string} address - The address to check\n * @returns {boolean} True if the address is in the Qi ledger scope, false otherwise.\n */\nexport function isQiAddress(address) {\n const secondByte = address.substring(4, 6);\n const binaryString = parseInt(secondByte, 16).toString(2).padStart(8, '0');\n const isUTXO = binaryString[0] === '1';\n return isUTXO;\n}\n/**\n * Checks whether a given address is in the Quai ledger scope by checking the 9th bit of the address.\n *\n * @category Address\n * @param {string} address - The address to check\n * @returns {boolean} True if the address is in the Quai ledger scope, false otherwise.\n */\nexport function isQuaiAddress(address) {\n return !isQiAddress(address);\n}\n//# sourceMappingURL=checks.js.map","import { Ledger, toZone } from '../constants/zones.js';\nimport { isQiAddress } from '../address/checks.js';\n/**\n * Retrieves the shard information for a given address based on its byte prefix. The function parses the address to\n * extract its byte prefix, then filters the ShardData to find a matching shard entry. If no matching shard is found, it\n * returns null.\n *\n * @category Utils\n * @param {string} address - The blockchain address to be analyzed. The address should start with \"0x\" followed by the\n * hexadecimal representation.\n * @returns {Object | null} An object containing the shard information, or null if no\n */\nexport function getZoneForAddress(address) {\n try {\n return toZone(address.slice(0, 4));\n }\n catch (error) {\n return null;\n }\n}\n/**\n * Extracts both zone and UTXO information from a given blockchain address. This function first determines the address's\n * zone by its byte prefix, then checks the 9th bit of the address to ascertain if it's a UTXO or non-UTXO address.\n *\n * @category Utils\n * @param {string} address - The blockchain address to be analyzed, expected to start with \"0x\" followed by its\n * hexadecimal representation.\n * @returns {Object | null} An object containing the zone and UTXO information, or null if no address is found.\n */\nexport function getAddressDetails(address) {\n const isQiLedger = (parseInt(address.substring(4, 5), 16) & 0x1) === Ledger.Qi;\n return { zone: toZone(address.substring(0, 4)), ledger: isQiLedger ? Ledger.Qi : Ledger.Quai };\n}\n/**\n * Determines the transaction type based on the sender and recipient addresses. The function checks if both addresses\n * are UTXO addresses, in which case it returns 2. If only the sender address is a UTXO address, it returns 1.\n * Otherwise, it returns 0.\n *\n * @category Utils\n * @param {string | null} from - The sender address. If null, the function returns 0.\n * @param {string | null} to - The recipient address. If null, the function returns 0.\n * @returns {number} The transaction type based on the addresses.\n */\nexport function getTxType(from, to) {\n if (from === null || to === null)\n return 0;\n const senderAddressIsQi = isQiAddress(from);\n const recipientAddressIsQi = isQiAddress(to);\n switch (true) {\n case senderAddressIsQi && recipientAddressIsQi:\n return 2;\n case senderAddressIsQi && !recipientAddressIsQi:\n return 1;\n default:\n return 0;\n }\n}\n/**\n * Location of a chain within the Quai hierarchy\n *\n * Prime = [] region[0] = [0] zone[1,2] = [1, 2]\n *\n * @param shard - The shard to get the location for\n * @returns The location of the chain within the Quai hierarchy\n */\nexport function getNodeLocationFromZone(zone) {\n const zoneId = zone.slice(2);\n if (zoneId.length > 2) {\n throw new Error(`Invalid zone: ${zone}`);\n }\n else if (zoneId.length === 0) {\n return [];\n }\n return zoneId.split('').map(Number);\n}\nexport function getZoneFromNodeLocation(location) {\n if (location.length > 2) {\n throw new Error('Invalid location');\n }\n return toZone(`0x${location.join('')}`);\n}\n//# sourceMappingURL=shards.js.map","import { defineProperties, concat, getBytesCopy, getNumber, hexlify, toBeArray, toBigInt, toNumber, assert, assertArgument, } 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 = {};\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}\n/**\n * A {@link Result | **Result**} is a sub-class of Array, which allows accessing any of its values either positionally by\n * its index or, if keys are provided by its name.\n *\n * @category Application Binary Interface\n */\nexport class Result extends Array {\n #names;\n /**\n * @ignore\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, keys?: Array);\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) => {\n this[index] = item;\n });\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 this.#names = 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 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 return 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 }\n /**\n * Returns the Result as a normal Array.\n *\n * This will throw if there are any outstanding deferred errors.\n */\n toArray() {\n const result = [];\n this.forEach((item, index) => {\n if (item instanceof Error) {\n throwError(`index ${index}`, item);\n }\n result.push(item);\n });\n return result;\n }\n /**\n * Returns the Result as an Object with each name-value pair.\n *\n * This will throw if any value is unnamed, or if there are any outstanding deferred errors.\n */\n toObject() {\n return this.#names.reduce(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n (accum, name, index) => {\n assert(name != null, 'value at index ${ index } unnamed', 'UNSUPPORTED_OPERATION', {\n operation: 'toObject()',\n });\n // Add values for names that don't conflict\n if (!(name in accum)) {\n accum[name] = this.getValue(name);\n }\n return accum;\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 result = [], names = [];\n for (let i = start; i < end; i++) {\n result.push(this[i]);\n names.push(this.#names[i]);\n }\n return new Result(_guard, result, names);\n }\n /**\n * @ignore\n */\n filter(callback, thisArg) {\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(this.#names[i]);\n }\n }\n return new Result(_guard, result, names);\n }\n /**\n * @ignore\n */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint\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 a method on a {@link Result | **Result**} or its\n * superclass Array, or any JavaScript keyword, this ensures all named values are still accessible by name.\n *\n * @param {string} name - The name of the value to retrieve.\n *\n * @returns The value for `name`.\n */\n getValue(name) {\n const index = this.#names.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 {@link Result | **Result**} for `items` with each entry also accessible by its corresponding name in\n * `keys`.\n *\n * @param {any[]} items - The items to include in the Result.\n * @param {(null | string)[]} [keys] - The names for each item in `items`.\n *\n * @returns The new Result.\n */\n static fromItems(items, keys) {\n return new Result(_guard, items, keys);\n }\n}\n/**\n * Returns all errors found in a {@link Result | **Result**}.\n *\n * Since certain errors encountered when creating a {@link Result | **Result**} do not impact the ability to continue\n * parsing data, they are deferred until they are actually accessed. Hence a faulty string in an Event that is never\n * used does not impact the program flow.\n *\n * However, sometimes it may be useful to access, identify or validate correctness of a {@link Result | **Result**}.\n *\n * @category Application Binary Interface\n * @param {Result} result - The Result to check for errors.\n *\n * @returns An array of objects with the path to the error and the error itself.\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 (const 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', {\n buffer: bytes,\n length: WordSize,\n offset: bytes.length,\n });\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',\n type: 'string',\n localName: 'string',\n 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() {\n return this.#dataLength;\n }\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() {\n return hexlify(this.#data);\n }\n get dataLength() {\n return this.#data.length;\n }\n get consumed() {\n return this.#offset;\n }\n get bytes() {\n return new Uint8Array(this.#data);\n }\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, \n // eslint-disable-next-line no-useless-escape\n `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),\n offset: this.#offset,\n length: count,\n 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 const 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","import { keccak256 } from '../crypto/index.js';\nimport { concat, dataSlice, getBigInt, getBytes, 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 deployed to by an EOA when sending a deployment\n * transaction (i.e. when the `to` address is `null`).\n *\n * This can also be used to compute the address a contract will be deployed to by a contract, by using the contract's\n * address as the `to` and the contract's nonce.\n *\n * @category Address\n * @example\n *\n * ```js\n * from = '0x8ba1f109551bD432803012645Ac136ddd64DBA72';\n * nonce = 5;\n *\n * getCreateAddress({ from, nonce });\n * ```\n *\n * @param {object} tx - The transaction object.\n * @param {string} tx.from - The address of the sender.\n * @param {BigNumberish} tx.nonce - The nonce of the sender.\n * @param {string} [tx.data] - The data of the transaction.\n */\nexport function getCreateAddress(tx) {\n const from = getAddress(tx.from);\n const nonce = getBigInt(tx.nonce, 'tx.nonce');\n const nonceBytes = bigEndianNonce(nonce);\n const fromBytes = getBytes(from);\n const codeBytes = tx.data ? getBytes(tx.data) : new Uint8Array();\n const concatenated = new Uint8Array([...fromBytes, ...nonceBytes, ...codeBytes]);\n const hash = keccak256(concatenated);\n return getAddress(dataSlice(hash, 12));\n}\n/**\n * Returns the address that would result from a `CREATE2` operation with the given `from`, `salt` and `initCodeHash`.\n *\n * To compute the `initCodeHash` from a contract's init code, use the [**keccak256**](../functions/keccak256) function.\n *\n * For a quick overview and example of `CREATE2`, see [Wisps: The Magical World of\n * Create2](https://blog.ricmoo.com/wisps-the-magical-world-of-create2-5c2177027604).\n *\n * @category Address\n * @example\n *\n * ```js\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 * ```\n *\n * @param {string} _from - The address of the sender.\n * @param {BytesLike} _salt - The salt value.\n * @param {BytesLike} _initCodeHash - The hash of the init code.\n * @returns {string} The computed address.\n * @throws {Error} If the salt is not exactly 32 bytes long.\n * @throws {Error} If the initCodeHash is not exactly 32 bytes long.\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// Helper function to convert a BigInt nonce to a big-endian byte array\nfunction bigEndianNonce(nonce) {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n view.setBigUint64(0, nonce, false);\n return new Uint8Array(buffer);\n}\n//# sourceMappingURL=contract-address.js.map","/**\n * A Typed object allows a value to have its type explicitly specified.\n *\n * For example, in Solidity, the value `45` could represent a `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 APIs which what the type is, this allows transparent\n * interoperation with Soldity.\n *\n * @category Application Binary Interface\n */\nimport { assertPrivate, defineProperties } from '../utils/index.js';\nconst _guard = {};\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(_guard, `${signed ? '' : 'u'}int${width}`, value, { signed, width });\n}\nfunction b(value, size) {\n // @TODO: Check range is valid for value\n return new Typed(_guard, `bytes${size ? size : ''}`, value, { size });\n}\nconst _typedSymbol = Symbol.for('_quais_typed');\n/**\n * The **Typed** class to wrap values providing explicit type information.\n *\n * @category Application Binary Interface\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(guard, type, value, options) {\n if (options == null) {\n options = null;\n }\n assertPrivate(_guard, guard, '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 * @returns The human-readable type for the provided type.\n * @throws If the type is array or dynamic array.\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 * @returns The default value for this type.\n */\n defaultValue() {\n return 0;\n }\n /**\n * The minimum value for numeric types.\n *\n * @returns The minimum value for the provided numeric type.\n */\n minValue() {\n return 0;\n }\n /**\n * The maximum value for numeric types.\n *\n * @returns The maximum value for the provided numeric type.\n */\n maxValue() {\n return 0;\n }\n /**\n * Returns whether this is a {@link TypedBigInt | **TypedBigInt**}. If true, a type guard is provided.\n *\n * @returns `true` if this is a big integer.\n */\n isBigInt() {\n return !!this.type.match(/^u?int[0-9]+$/);\n }\n /**\n * Returns whether this is a {@link TypedData | **TypedData**}. If true, a type guard is provided.\n *\n * @returns {boolean} `true` if this is a number.\n */\n isData() {\n return this.type.startsWith('bytes');\n }\n /**\n * Return whether this is a {@link TypedString | **TypedString**}. If true, a type guard is provided.\n *\n * @returns {boolean} `true` if this is a string.\n */\n isString() {\n return this.type === 'string';\n }\n /**\n * Returns the tuple name.\n *\n * @returns {boolean} The tuple name if this is a tuple.\n * @throws If this is not a tuple.\n */\n get tupleName() {\n if (this.type !== 'tuple') {\n throw TypeError('not a tuple');\n }\n return this.#options;\n }\n /**\n * Returns the length of a typed array.\n *\n * @returns {number} The length of the array type or `-1` if it is dynamic.\n * @throws If this 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 * @param {string} type - The type to use.\n * @param {any} value - The value to use.\n */\n static from(type, value) {\n return new Typed(_guard, type, value);\n }\n /**\n * Return a new `uint8` type for v.\n *\n * @param {BigNumberish} v - The value to convert to a `uint8`.\n *\n * @returns {uint8} A new `uint8` type for `v`.\n */\n static uint8(v) {\n return n(v, 8);\n }\n /**\n * Return a new `uint16` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint16`.\n *\n * @returns A new `uint16` type for `v`.\n */\n static uint16(v) {\n return n(v, 16);\n }\n /**\n * Return a new `uint24` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint24`.\n *\n * @returns A new `uint24` type for `v`.\n */\n static uint24(v) {\n return n(v, 24);\n }\n /**\n * Return a new `uint32` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint32`.\n *\n * @returns A new `uint32` type for `v`.\n */\n static uint32(v) {\n return n(v, 32);\n }\n /**\n * Return a new `uint40` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint40`.\n *\n * @returns A new `uint40` type for `v`.\n */\n static uint40(v) {\n return n(v, 40);\n }\n /**\n * Return a new `uint48` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint48`.\n *\n * @returns A new `uint48` type for `v`.\n */\n static uint48(v) {\n return n(v, 48);\n }\n /**\n * Return a new `uint56` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint56`.\n *\n * @returns A new `uint56` type for `v`.\n */\n static uint56(v) {\n return n(v, 56);\n }\n /**\n * Return a new `uint64` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint64`.\n *\n * @returns A new `uint64` type for `v`.\n */\n static uint64(v) {\n return n(v, 64);\n }\n /**\n * Return a new `uint72` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint72`.\n *\n * @returns A new `uint72` type for `v`.\n */\n static uint72(v) {\n return n(v, 72);\n }\n /**\n * Return a new `uint80` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint80`.\n *\n * @returns A new `uint80` type for `v`.\n */\n static uint80(v) {\n return n(v, 80);\n }\n /**\n * Return a new `uint88` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint88`.\n *\n * @returns A new `uint88` type for `v`.\n */\n static uint88(v) {\n return n(v, 88);\n }\n /**\n * Return a new `uint96` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint96`.\n *\n * @returns A new `uint96` type for `v`.\n */\n static uint96(v) {\n return n(v, 96);\n }\n /**\n * Return a new `uint104` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint104`.\n *\n * @returns A new `uint104` type for `v`.\n */\n static uint104(v) {\n return n(v, 104);\n }\n /**\n * Return a new `uint112` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint112`.\n *\n * @returns A new `uint112` type for `v`.\n */\n static uint112(v) {\n return n(v, 112);\n }\n /**\n * Return a new `uint120` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint120`.\n *\n * @returns A new `uint120` type for `v`.\n */\n static uint120(v) {\n return n(v, 120);\n }\n /**\n * Return a new `uint128` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint128`.\n *\n * @returns A new `uint128` type for `v`.\n */\n static uint128(v) {\n return n(v, 128);\n }\n /**\n * Return a new `uint136` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint136`.\n *\n * @returns A new `uint136` type for `v`.\n */\n static uint136(v) {\n return n(v, 136);\n }\n /**\n * Return a new `uint144` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint144`.\n *\n * @returns A new `uint144` type for `v`.\n */\n static uint144(v) {\n return n(v, 144);\n }\n /**\n * Return a new `uint152` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint152`.\n *\n * @returns A new `uint152` type for `v`.\n */\n static uint152(v) {\n return n(v, 152);\n }\n /**\n * Return a new `uint160` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint160`.\n *\n * @returns A new `uint160` type for `v`.\n */\n static uint160(v) {\n return n(v, 160);\n }\n /**\n * Return a new `uint168` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint168`.\n *\n * @returns A new `uint168` type for `v`.\n */\n static uint168(v) {\n return n(v, 168);\n }\n /**\n * Return a new `uint176` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint176`.\n *\n * @returns A new `uint176` type for `v`.\n */\n static uint176(v) {\n return n(v, 176);\n }\n /**\n * Return a new `uint184` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint184`.\n *\n * @returns A new `uint184` type for `v`.\n */\n static uint184(v) {\n return n(v, 184);\n }\n /**\n * Return a new `uint192` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint192`.\n *\n * @returns A new `uint192` type for `v`.\n */\n static uint192(v) {\n return n(v, 192);\n }\n /**\n * Return a new `uint200` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint200`.\n *\n * @returns A new `uint200` type for `v`.\n */\n static uint200(v) {\n return n(v, 200);\n }\n /**\n * Return a new `uint208` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint208`.\n *\n * @returns A new `uint208` type for `v`.\n */\n static uint208(v) {\n return n(v, 208);\n }\n /**\n * Return a new `uint216` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint216`.\n *\n * @returns A new `uint216` type for `v`.\n */\n static uint216(v) {\n return n(v, 216);\n }\n /**\n * Return a new `uint224` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint224`.\n *\n * @returns A new `uint224` type for `v`.\n */\n static uint224(v) {\n return n(v, 224);\n }\n /**\n * Return a new `uint232` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint232`.\n *\n * @returns A new `uint232` type for `v`.\n */\n static uint232(v) {\n return n(v, 232);\n }\n /**\n * Return a new `uint240` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint240`.\n *\n * @returns A new `uint240` type for `v`.\n */\n static uint240(v) {\n return n(v, 240);\n }\n /**\n * Return a new `uint248` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint248`.\n *\n * @returns A new `uint248` type for `v`.\n */\n static uint248(v) {\n return n(v, 248);\n }\n /**\n * Return a new `uint256` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint256`.\n *\n * @returns A new `uint256` type for `v`.\n */\n static uint256(v) {\n return n(v, 256);\n }\n /**\n * Return a new `uint256` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint256`.\n *\n * @returns A new `uint256` type for `v`.\n */\n static uint(v) {\n return n(v, 256);\n }\n /**\n * Return a new `int8` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int8`.\n *\n * @returns A new `int8` type for `v`.\n */\n static int8(v) {\n return n(v, -8);\n }\n /**\n * Return a new `int16` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int16`.\n *\n * @returns A new `int16` type for `v`.\n */\n static int16(v) {\n return n(v, -16);\n }\n /**\n * Return a new `int24` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int24`.\n *\n * @returns A new `int24` type for `v`.\n */\n static int24(v) {\n return n(v, -24);\n }\n /**\n * Return a new `int32` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int32`.\n *\n * @returns A new `int32` type for `v`.\n */\n static int32(v) {\n return n(v, -32);\n }\n /**\n * Return a new `int40` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int40`.\n *\n * @returns A new `int40` type for `v`.\n */\n static int40(v) {\n return n(v, -40);\n }\n /**\n * Return a new `int48` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int48`.\n *\n * @returns A new `int48` type for `v`.\n */\n static int48(v) {\n return n(v, -48);\n }\n /**\n * Return a new `int56` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int56`.\n *\n * @returns A new `int56` type for `v`.\n */\n static int56(v) {\n return n(v, -56);\n }\n /**\n * Return a new `int64` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int64`.\n *\n * @returns A new `int64` type for `v`.\n */\n static int64(v) {\n return n(v, -64);\n }\n /**\n * Return a new `int72` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int72`.\n *\n * @returns A new `int72` type for `v`.\n */\n static int72(v) {\n return n(v, -72);\n }\n /**\n * Return a new `int80` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int80`.\n *\n * @returns A new `int80` type for `v`.\n */\n static int80(v) {\n return n(v, -80);\n }\n /**\n * Return a new `int88` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int88`.\n *\n * @returns A new `int88` type for `v`.\n */\n static int88(v) {\n return n(v, -88);\n }\n /**\n * Return a new `int96` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int96`.\n *\n * @returns A new `int96` type for `v`.\n */\n static int96(v) {\n return n(v, -96);\n }\n /**\n * Return a new `int104` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int104`.\n *\n * @returns A new `int104` type for `v`.\n */\n static int104(v) {\n return n(v, -104);\n }\n /**\n * Return a new `int112` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int112`.\n *\n * @returns A new `int112` type for `v`.\n */\n static int112(v) {\n return n(v, -112);\n }\n /**\n * Return a new `int120` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int120`.\n *\n * @returns A new `int120` type for `v`.\n */\n static int120(v) {\n return n(v, -120);\n }\n /**\n * Return a new `int128` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int128`.\n *\n * @returns A new `int128` type for `v`.\n */\n static int128(v) {\n return n(v, -128);\n }\n /**\n * Return a new `int136` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int136`.\n *\n * @returns A new `int136` type for `v`.\n */\n static int136(v) {\n return n(v, -136);\n }\n /**\n * Return a new `int144` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int144`.\n *\n * @returns A new `int144` type for `v`.\n */\n static int144(v) {\n return n(v, -144);\n }\n /**\n * Return a new `int152` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int152`.\n *\n * @returns A new `int152` type for `v`.\n */\n static int152(v) {\n return n(v, -152);\n }\n /**\n * Return a new `int160` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int160`.\n *\n * @returns A new `int160` type for `v`.\n */\n static int160(v) {\n return n(v, -160);\n }\n /**\n * Return a new `int168` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int168`.\n *\n * @returns A new `int168` type for `v`.\n */\n static int168(v) {\n return n(v, -168);\n }\n /**\n * Return a new `int176` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int176`.\n *\n * @returns A new `int176` type for `v`.\n */\n static int176(v) {\n return n(v, -176);\n }\n /**\n * Return a new `int184` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int184`.\n *\n * @returns A new `int184` type for `v`.\n */\n static int184(v) {\n return n(v, -184);\n }\n /**\n * Return a new `int192` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int192`.\n *\n * @returns A new `int192` type for `v`.\n */\n static int192(v) {\n return n(v, -192);\n }\n /**\n * Return a new `int200` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int200`.\n *\n * @returns A new `int200` type for `v`.\n */\n static int200(v) {\n return n(v, -200);\n }\n /**\n * Return a new `int208` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int208`.\n *\n * @returns A new `int208` type for `v`.\n */\n static int208(v) {\n return n(v, -208);\n }\n /**\n * Return a new `int216` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int216`.\n *\n * @returns A new `int216` type for `v`.\n */\n static int216(v) {\n return n(v, -216);\n }\n /**\n * Return a new `int224` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int224`.\n *\n * @returns A new `int224` type for `v`.\n */\n static int224(v) {\n return n(v, -224);\n }\n /**\n * Return a new `int232` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int232`.\n *\n * @returns A new `int232` type for `v`.\n */\n static int232(v) {\n return n(v, -232);\n }\n /**\n * Return a new `int240` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int240`.\n *\n * @returns A new `int240` type for `v`.\n */\n static int240(v) {\n return n(v, -240);\n }\n /**\n * Return a new `int248` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int248`.\n *\n * @returns A new `int248` type for `v`.\n */\n static int248(v) {\n return n(v, -248);\n }\n /**\n * Return a new `int256` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int256`.\n *\n * @returns A new `int256` type for `v`.\n */\n static int256(v) {\n return n(v, -256);\n }\n /**\n * Return a new `int256` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int256`.\n *\n * @returns A new `int256` type for `v`.\n */\n static int(v) {\n return n(v, -256);\n }\n /**\n * Return a new `bytes1` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes1`.\n *\n * @returns A new `bytes1` type for `v`.\n */\n static bytes1(v) {\n return b(v, 1);\n }\n /**\n * Return a new `bytes2` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes2`.\n *\n * @returns A new `bytes2` type for `v`.\n */\n static bytes2(v) {\n return b(v, 2);\n }\n /**\n * Return a new `bytes3` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes3`.\n *\n * @returns A new `bytes3` type for `v`.\n */\n static bytes3(v) {\n return b(v, 3);\n }\n /**\n * Return a new `bytes4` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes4`.\n *\n * @returns A new `bytes4` type for `v`.\n */\n static bytes4(v) {\n return b(v, 4);\n }\n /**\n * Return a new `bytes5` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes5`.\n *\n * @returns A new `bytes5` type for `v`.\n */\n static bytes5(v) {\n return b(v, 5);\n }\n /**\n * Return a new `bytes6` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes6`.\n *\n * @returns A new `bytes6` type for `v`.\n */\n static bytes6(v) {\n return b(v, 6);\n }\n /**\n * Return a new `bytes7` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes7`.\n *\n * @returns A new `bytes7` type for `v`.\n */\n static bytes7(v) {\n return b(v, 7);\n }\n /**\n * Return a new `bytes8` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes8`.\n *\n * @returns A new `bytes8` type for `v`.\n */\n static bytes8(v) {\n return b(v, 8);\n }\n /**\n * Return a new `bytes9` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes9`.\n *\n * @returns A new `bytes9` type for `v`.\n */\n static bytes9(v) {\n return b(v, 9);\n }\n /**\n * Return a new `bytes10` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes10`.\n *\n * @returns A new `bytes10` type for `v`.\n */\n static bytes10(v) {\n return b(v, 10);\n }\n /**\n * Return a new `bytes11` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes11`.\n *\n * @returns A new `bytes11` type for `v`.\n */\n static bytes11(v) {\n return b(v, 11);\n }\n /**\n * Return a new `bytes12` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes12`.\n *\n * @returns A new `bytes12` type for `v`.\n */\n static bytes12(v) {\n return b(v, 12);\n }\n /**\n * Return a new `bytes13` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes13`.\n *\n * @returns A new `bytes13` type for `v`.\n */\n static bytes13(v) {\n return b(v, 13);\n }\n /**\n * Return a new `bytes14` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes14`.\n *\n * @returns A new `bytes14` type for `v`.\n */\n static bytes14(v) {\n return b(v, 14);\n }\n /**\n * Return a new `bytes15` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes15`.\n *\n * @returns A new `bytes15` type for `v`.\n */\n static bytes15(v) {\n return b(v, 15);\n }\n /**\n * Return a new `bytes16` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes16`.\n *\n * @returns A new `bytes16` type for `v`.\n */\n static bytes16(v) {\n return b(v, 16);\n }\n /**\n * Return a new `bytes17` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes17`.\n *\n * @returns A new `bytes17` type for `v`.\n */\n static bytes17(v) {\n return b(v, 17);\n }\n /**\n * Return a new `bytes18` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes18`.\n *\n * @returns A new `bytes18` type for `v`.\n */\n static bytes18(v) {\n return b(v, 18);\n }\n /**\n * Return a new `bytes19` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes19`.\n *\n * @returns A new `bytes19` type for `v`.\n */\n static bytes19(v) {\n return b(v, 19);\n }\n /**\n * Return a new `bytes20` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes20`.\n *\n * @returns A new `bytes20` type for `v`.\n */\n static bytes20(v) {\n return b(v, 20);\n }\n /**\n * Return a new `bytes21` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes21`.\n *\n * @returns A new `bytes21` type for `v`.\n */\n static bytes21(v) {\n return b(v, 21);\n }\n /**\n * Return a new `bytes22` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes22`.\n *\n * @returns A new `bytes22` type for `v`.\n */\n static bytes22(v) {\n return b(v, 22);\n }\n /**\n * Return a new `bytes23` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes23`.\n *\n * @returns A new `bytes23` type for `v`.\n */\n static bytes23(v) {\n return b(v, 23);\n }\n /**\n * Return a new `bytes24` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes24`.\n *\n * @returns A new `bytes24` type for `v`.\n */\n static bytes24(v) {\n return b(v, 24);\n }\n /**\n * Return a new `bytes25` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes25`.\n *\n * @returns A new `bytes25` type for `v`.\n */\n static bytes25(v) {\n return b(v, 25);\n }\n /**\n * Return a new `bytes26` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes26`.\n *\n * @returns A new `bytes26` type for `v`.\n */\n static bytes26(v) {\n return b(v, 26);\n }\n /**\n * Return a new `bytes27` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes27`.\n *\n * @returns A new `bytes27` type for `v`.\n */\n static bytes27(v) {\n return b(v, 27);\n }\n /**\n * Return a new `bytes28` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes28`.\n *\n * @returns A new `bytes28` type for `v`.\n */\n static bytes28(v) {\n return b(v, 28);\n }\n /**\n * Return a new `bytes29` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes29`.\n *\n * @returns A new `bytes29` type for `v`.\n */\n static bytes29(v) {\n return b(v, 29);\n }\n /**\n * Return a new `bytes30` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes30`.\n *\n * @returns A new `bytes30` type for `v`.\n */\n static bytes30(v) {\n return b(v, 30);\n }\n /**\n * Return a new `bytes31` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes31`.\n *\n * @returns A new `bytes31` type for `v`.\n */\n static bytes31(v) {\n return b(v, 31);\n }\n /**\n * Return a new `bytes32` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes32`.\n *\n * @returns A new `bytes32` type for `v`.\n */\n static bytes32(v) {\n return b(v, 32);\n }\n /**\n * Return a new `address` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to an `address`.\n *\n * @returns A new `address` type for `v`.\n */\n static address(v) {\n return new Typed(_guard, 'address', v);\n }\n /**\n * Return a new `bool` type for `v`.\n *\n * @param {any} v - The value to convert to a `bool`.\n *\n * @returns A new `bool` type for `v`.\n */\n static bool(v) {\n return new Typed(_guard, 'bool', !!v);\n }\n /**\n * Return a new `bytes` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes`.\n *\n * @returns A new `bytes` type for `v`.\n */\n static bytes(v) {\n return new Typed(_guard, 'bytes', v);\n }\n /**\n * Return a new `string` type for `v`.\n *\n * @param {string} v - The value to convert to a `string`.\n *\n * @returns A new `string` type for `v`.\n */\n static string(v) {\n return new Typed(_guard, 'string', v);\n }\n /**\n * Return a new `array` type for v, allowing dynamic length.\n *\n * @param {(any | Typed)[]} v - The value to convert to an `array`.\n * @param {null | boolean} dynamic - Whether the array is dynamic.\n *\n * @returns A new `array` type for `v`.\n */\n static array(v, dynamic) {\n throw new Error('not implemented yet');\n return new Typed(_guard, 'array', v, dynamic);\n }\n /**\n * Return a new `tuple` type for v, with the optional name.\n *\n * @param {(any | Typed)[]} v - The value to convert to a `tuple`.\n * @param {string} name - The name of the tuple.\n *\n * @returns A new `tuple` type for `v`.\n */\n static tuple(v, name) {\n throw new Error('not implemented yet');\n return new Typed(_guard, 'tuple', v, name);\n }\n /**\n * Return a new `overrides` type with the provided properties.\n *\n * @param {Record} v - A record containing the properties to be included in the `overrides` type.\n *\n * @returns A new `overrides` type with the given properties.\n */\n static overrides(v) {\n return new Typed(_guard, 'overrides', Object.assign({}, v));\n }\n /**\n * Returns true only if `value` is a {@link Typed | **Typed**} instance.\n *\n * @param {any} value - The value to check.\n *\n * @returns {boolean} True if `value` is a {@link Typed | **Typed**} instance.\n */\n static isTyped(value) {\n return value && typeof value === 'object' && '_typedSymbol' in value && value._typedSymbol === _typedSymbol;\n }\n /**\n * If the value is a {@link Typed | **Typed**} instance, validates the underlying value and returns it, otherwise\n * returns value directly.\n *\n * This is useful for functions that with to accept either a {@link Typed | **Typed**} object or values.\n *\n * @param {Typed | T} value - The value to dereference.\n * @param {string} type - The dereferenced value.\n */\n static dereference(value, type) {\n if (Typed.isTyped(value)) {\n if (value.type !== type) {\n throw new Error(`invalid type: expected ${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 \"../../encoding/index.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 '../encoding/index.js';\n/**\n * A simple hashing function which operates on UTF-8 strings to compute an 32-byte identifier.\n *\n * This simply computes the {@link toUtf8Bytes | **UTF-8 bytes**} and computes the {@link keccak256 | **keccak256**}.\n *\n * @category Hash\n * @example\n *\n * ```ts\n * id('hello world');\n * ```\n *\n * @param {string} value - The string to hash.\n * @returns {string} The 32-byte identifier.\n */\nexport function id(value) {\n return keccak256(toUtf8Bytes(value));\n}\n//# sourceMappingURL=id.js.map","import { keccak256 } from '../crypto/index.js';\nimport { MessagePrefix } from '../constants/index.js';\nimport { recoverAddress } from '../address/index.js';\nimport { concat } from '../utils/index.js';\nimport { toUtf8Bytes } from '../encoding/index.js';\nimport { EthMessagePrefix } from '../constants/strings.js';\n/**\n * Computes the Quai Network equivalent of the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal-sign message\n * digest to sign.\n *\n * This prefixes the message with {@link MessagePrefix | **MessagePrefix**} and the decimal length of `message` and\n * computes the {@link keccak256 | **keccak256**} digest.\n *\n * If `message` is a string, it is converted to its UTF-8 bytes first. To compute the digest of a\n * [**DataHexString**](../types-aliases/DataHex), it must be converted to [**bytes**](../functions/getBytes).\n *\n * @category Hash\n * @example\n *\n * ```ts\n * hashMessage('Hello World');\n *\n * // Hashes the SIX (6) string characters, i.e.\n * // [ \"0\", \"x\", \"4\", \"2\", \"4\", \"3\" ]\n * hashMessage('0x4243');\n *\n * // Hashes the TWO (2) bytes [ 0x42, 0x43 ]...\n * hashMessage(getBytes('0x4243'));\n *\n * // ...which is equal to using data\n * hashMessage(new Uint8Array([0x42, 0x43]));\n * ```\n *\n * @param {Uint8Array | string} message - The message to hash.\n * @returns {string} The message digest.\n */\nexport function hashMessage(message) {\n if (typeof message === 'string') {\n message = toUtf8Bytes(message);\n }\n return keccak256(concat([toUtf8Bytes(MessagePrefix), toUtf8Bytes(String(message.length)), message]));\n}\n/**\n * Return the address of the private key that produced the signature `sig` during signing for `message`.\n *\n * @category Hash\n * @param {Uint8Array | string} message - The message that was signed.\n * @param {SignatureLike} sig - The signature to verify.\n * @returns {string} The address of the signer.\n */\nexport function verifyMessage(message, sig) {\n const digest = hashMessage(message);\n return recoverAddress(digest, sig);\n}\n/**\n * Computes the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal-sign message digest to sign.\n *\n * This prefixes the message with {@link EthMessagePrefix | **EthMessagePrefix**} and the decimal length of `message` and\n * computes the {@link keccak256 | **keccak256**} digest.\n *\n * If `message` is a string, it is converted to its UTF-8 bytes first. To compute the digest of a\n * [**DataHexString**](../types-aliases/DataHex), it must be converted to [**bytes**](../functions/getBytes).\n *\n * This is the same as `hashMessage` except it uses `EthMessagePrefix` instead of `MessagePrefix` and is available for\n * broader compatibility with EVM signing practices.\n *\n * @category Hash\n * @param message\n * @returns\n */\nexport function ethHashMessage(message) {\n if (typeof message === 'string') {\n message = toUtf8Bytes(message);\n }\n return keccak256(concat([toUtf8Bytes(EthMessagePrefix), toUtf8Bytes(String(message.length)), message]));\n}\n/**\n * Return the address of the private key that produced the signature `sig` during signing for `message`.\n *\n * This is the same as `verifyMessage` except it uses `EthMessagePrefix` instead of `MessagePrefix` and is available for\n * broader compatibility with EVM signing practices.\n *\n * @category Hash\n * @param message - The message that was signed.\n * @param sig - The signature to verify.\n * @returns {string} The address of the signer.\n */\nexport function ethVerifyMessage(message, sig) {\n const digest = ethHashMessage(message);\n return recoverAddress(digest, sig);\n}\n//# sourceMappingURL=message.js.map","import { getAddress } from '../address/index.js';\nimport { keccak256 as _keccak256, sha256 as _sha256 } from '../crypto/index.js';\nimport { concat, dataLength, getBytes, hexlify, toBeArray, toTwos, zeroPadBytes, zeroPadValue, assertArgument, } from '../utils/index.js';\nimport { toUtf8Bytes } from '../encoding/index.js';\nconst regexBytes = new RegExp('^bytes([0-9]+)$');\nconst regexNumber = new RegExp('^(u?int)([0-9]*)$');\nconst regexArray = new RegExp('^(.*)\\\\[([0-9]*)\\\\]$');\nfunction _pack(type, value, isArray) {\n switch (type) {\n case 'address':\n if (isArray) {\n return getBytes(zeroPadValue(value, 32));\n }\n return getBytes(getAddress(value));\n case 'string':\n return toUtf8Bytes(value);\n case 'bytes':\n return getBytes(value);\n case 'bool':\n value = value ? '0x01' : '0x00';\n if (isArray) {\n return getBytes(zeroPadValue(value, 32));\n }\n return getBytes(value);\n }\n let match = type.match(regexNumber);\n if (match) {\n const signed = match[1] === 'int';\n let size = parseInt(match[2] || '256');\n assertArgument((!match[2] || match[2] === String(size)) && size % 8 === 0 && size !== 0 && size <= 256, 'invalid number type', 'type', type);\n if (isArray) {\n size = 256;\n }\n if (signed) {\n value = toTwos(value, size);\n }\n return getBytes(zeroPadValue(toBeArray(value), size / 8));\n }\n match = type.match(regexBytes);\n if (match) {\n const size = parseInt(match[1]);\n assertArgument(String(size) === match[1] && size !== 0 && size <= 32, 'invalid bytes type', 'type', type);\n assertArgument(dataLength(value) === size, `invalid value for ${type}`, 'value', value);\n if (isArray) {\n return getBytes(zeroPadBytes(value, 32));\n }\n return value;\n }\n match = type.match(regexArray);\n if (match && Array.isArray(value)) {\n const baseType = match[1];\n const count = parseInt(match[2] || String(value.length));\n assertArgument(count === value.length, `invalid array length for ${type}`, 'value', value);\n const result = [];\n value.forEach(function (value) {\n result.push(_pack(baseType, value, true));\n });\n return getBytes(concat(result));\n }\n assertArgument(false, 'invalid type', 'type', type);\n}\n// @TODO: Array Enum\n/**\n * Computes the [Non-Standard Packed\n * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) representation of `values`\n * respectively to their `types`.\n *\n * @category Hash\n * @example\n *\n * ```ts\n * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72';\n * solidityPacked(['address', 'uint'], [addr, 45]);\n * ```\n *\n * @param {string[]} types - The types of the values.\n * @param {ReadonlyArray} values - The values to pack.\n * @returns {string} The packed values.\n */\nexport function solidityPacked(types, values) {\n assertArgument(types.length === values.length, 'wrong number of values; expected ${ types.length }', 'values', values);\n const tight = [];\n types.forEach(function (type, index) {\n tight.push(_pack(type, values[index]));\n });\n return hexlify(concat(tight));\n}\n/**\n * Computes the [Non-Standard Packed\n * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode)\n * [**keccak256**](../functions/keccak256) hash of `values` respectively to their `types`.\n *\n * @category Hash\n * @example\n *\n * ```ts\n * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72';\n * solidityPackedKeccak256(['address', 'uint'], [addr, 45]);\n * ```\n *\n * @param {ReadonlyArray} types - The types of the values.\n * @param {ReadonlyArray} values - The values to hash.\n * @returns {string} The hash of the packed values.\n */\nexport function solidityPackedKeccak256(types, values) {\n return _keccak256(solidityPacked(types, values));\n}\n/**\n * Computes the [Non-Standard Packed\n * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) [sha256](../functions/sha256)\n * hash of `values` respectively to their `types`.\n *\n * @category Hash\n * @example\n *\n * ```ts\n * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72';\n * solidityPackedSha256(['address', 'uint'], [addr, 45]);\n * ```\n *\n * @param {ReadonlyArray} types - The types of the values.\n * @param {ReadonlyArray} values - The values to hash.\n * @returns {string} The hash of the packed values.\n */\nexport function solidityPackedSha256(types, values) {\n return _sha256(solidityPacked(types, values));\n}\n//# sourceMappingURL=solidity.js.map","//import { TypedDataDomain, TypedDataField } from \"@quaisproject/providerabstract-signer\";\nimport { getAddress } from '../address/index.js';\nimport { keccak256 } from '../crypto/index.js';\nimport { recoverAddress } from '../address/index.js';\nimport { concat, defineProperties, getBigInt, getBytes, hexlify, 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');\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 = ['name', 'version', 'chainId', 'verifyingContract', 'salt'];\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);\n // eslint-disable-next-line no-empty\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] || '256');\n assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && (match[2] == null || 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':\n return function (value) {\n return zeroPadValue(getAddress(value), 32);\n };\n case 'bool':\n return function (value) {\n return !value ? hexFalse : hexTrue;\n };\n case 'bytes':\n return function (value) {\n return keccak256(value);\n };\n case 'string':\n 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/**\n * A **TypedDataEncode** prepares and encodes [EIP-712](https://eips.ethereum.org/EIPS/eip-712) payloads for signed\n * typed data.\n *\n * This is useful for those that wish to compute various components of a typed data hash, primary types, or\n * sub-components, but generally the higher level [`Signer.signTypedData`](../classes/Signer#signTypedData) is more\n * useful.\n *\n * @category Hash\n */\nexport class TypedDataEncoder {\n /**\n * The primary type for the structured {@link types | **types**}.\n *\n * This is derived automatically from the {@link types | **types**}, since no recursion is possible, once the DAG for\n * the types is consturcted internally, the primary type must be the only remaining type with 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 do not violate the\n * [EIP-712](https://eips.ethereum.org/EIPS/eip-712) structural constraints as well as computes the\n * {@link primaryType | **primaryType**}.\n */\n constructor(types) {\n this.#types = JSON.stringify(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 Object.keys(types).forEach((type) => {\n links.set(type, new Set());\n parents.set(type, []);\n subtypes.set(type, new Set());\n });\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 = field.type.match(/^([^\\x5b]*)(\\x5b|$)/)[1] || null;\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 * @param {string} type - The type to get the encoder for.\n *\n * @returns {(value: any) => string} The encoder for the 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 match = type.match(/^(.*)(\\x5b(\\d*)\\x5d)$/);\n if (match) {\n const subtype = match[1];\n const subEncoder = this.getEncoder(subtype);\n return (value) => {\n assertArgument(!match[3] || parseInt(match[3]) === value.length, `array length mismatch; expected length ${parseInt(match[3])}`, '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 * @param {string} name - The name to get the full type for.\n *\n * @returns {string} The full type.\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 * @param {string} type - The type to encode the value for.\n * @param {any} value - The value to encode.\n *\n * @returns {string} The encoded value.\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 * @param {string} name - The name of the type.\n * @param {Record} value - The value to hash.\n *\n * @returns {string} The hash of the value.\n */\n hashStruct(name, value) {\n return keccak256(this.encodeData(name, value));\n }\n /**\n * Return the fulled encoded `value` for the {@link types | **types**}.\n *\n * @param {Record} value - The value to encode.\n *\n * @returns {string} The encoded value.\n */\n encode(value) {\n return this.encodeData(this.primaryType, value);\n }\n /**\n * Return the hash of the fully encoded `value` for the {@link types | **types**}.\n *\n * @param {Record} value - The value to hash.\n *\n * @returns {string} The hash of the value.\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 match = type.match(/^(.*)(\\x5b(\\d*)\\x5d)$/);\n if (match) {\n assertArgument(!match[3] || parseInt(match[3]) === value.length, `array length mismatch; expected length ${parseInt(match[3])}`, 'value', value);\n return value.map((v) => this._visit(match[1], 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 component within `value`.\n *\n * This is useful for replacing addresses or other transformation that may be desired on each component, based on\n * its type.\n *\n * @param {Record} value - The value to visit.\n * @param {(type: string, data: any) => any} callback - The callback to call for each value.\n *\n * @returns {any} The result of the callback.\n */\n visit(value, callback) {\n return this._visit(this.primaryType, value, callback);\n }\n /**\n * Create a new **TypedDataEncoder** for `types`.\n *\n * @param {Record} types - The types to encode.\n *\n * @returns {TypedDataEncoder} The encoder for the types.\n * @throws {Error} If the types are invalid.\n */\n static from(types) {\n return new TypedDataEncoder(types);\n }\n /**\n * Return the primary type for `types`.\n *\n * @param {Record} types - The types to get the primary type for.\n *\n * @returns {string} The primary type.\n * @throws {Error} If the types are invalid.\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 * @param {string} name - The name of the type.\n * @param {Record} types - The types to hash.\n * @param {Record} value - The value to hash.\n *\n * @returns {string} The hash of the value.\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 * @param {TypedDataDomain} domain - The domain to hash.\n *\n * @returns {string} The hash of the domain.\n * @throws {Error} If the domain is invalid.\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 [EIP-712](https://eips.ethereum.org/EIPS/eip-712) `value` for `types` with `domain`.\n *\n * @param {TypedDataDomain} domain - The domain to use.\n * @param {Record} types - The types to encode.\n * @param {Record} value - The value to encode.\n *\n * @returns {string} The encoded value.\n */\n static encode(domain, types, value) {\n return concat(['0x1901', TypedDataEncoder.hashDomain(domain), TypedDataEncoder.from(types).hash(value)]);\n }\n /**\n * Return the hash of the fully encoded [EIP-712](https://eips.ethereum.org/EIPS/eip-712) `value` for `types` with\n * `domain`.\n *\n * @param {TypedDataDomain} domain - The domain to use.\n * @param {Record} types - The types to hash.\n * @param {Record} value - The value to hash.\n *\n * @returns {string} The hash of the value.\n */\n static hash(domain, types, value) {\n return keccak256(TypedDataEncoder.encode(domain, types, value));\n }\n /**\n * Returns the JSON-encoded payload expected by nodes which implement the JSON-RPC\n * [EIP-712](https://eips.ethereum.org/EIPS/eip-712) method.\n *\n * @param {TypedDataDomain} domain - The domain to use.\n * @param {Record} types - The types to encode.\n * @param {Record} value - The value to encode.\n *\n * @returns {any} The JSON-encoded payload.\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 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 *\n * @category Hash\n * @param {TypedDataDomain} domain - The domain of the typed data.\n * @param {Record} types - The types of the typed data.\n * @param {Record} value - The value of the typed data.\n * @param {SignatureLike} signature - The signature to verify.\n *\n * @returns {string} The address that signed the typed data.\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 * - {@link FunctionFragment | Functions}\n * - {@link EventFragment | Events}\n * - {@link ConstructorFragment | Constructors}\n * - Custom {@link ErrorFragment | Errors}\n * - {@link FallbackFragment | Fallback or Recieve} functions\n *\n * @category Application Binary Interface\n */\nimport { defineProperties, getBigInt, getNumber, assert, assertPrivate, assertArgument } from '../utils/index.js';\nimport { id } from '../hash/index.js';\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';\nconst KwVisibDeploy = setify(_kwVisibDeploy.split(' '));\n// Visibility Keywords\nconst _kwVisib = 'constant external internal payable private public pure view';\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',\n ')': 'CLOSE_PAREN',\n '[': 'OPEN_BRACKET',\n ']': 'CLOSE_BRACKET',\n ',': 'COMMA',\n '@': '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]*))$');\n/**\n * Represents a parsed list of tokens.\n *\n * @category Application Binary Interface\n */\nclass TokenString {\n #offset;\n #tokens;\n get offset() {\n return this.#offset;\n }\n get length() {\n return this.#tokens.length - this.#offset;\n }\n constructor(tokens) {\n this.#offset = 0;\n this.#tokens = tokens.slice();\n }\n /**\n * Returns a clone of the current token string.\n *\n * @returns {TokenString} A cloned TokenString object.\n */\n clone() {\n return new TokenString(this.#tokens);\n }\n reset() {\n this.#offset = 0;\n }\n /**\n * @ignore\n */\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 throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`);\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 ``;\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 const brackets = [];\n const 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 = {\n depth: brackets.length,\n linkBack: -1,\n linkNext: -1,\n match: -1,\n type: '',\n text: '',\n offset,\n value: -1,\n };\n tokens.push(token);\n const 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 const 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 // eslint-disable-next-line no-constant-condition\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 const 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: ${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('_quais_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 {@link Fragment | **Fragment**} is an Array of {@link ParamType | **ParamType**}.\n *\n * @category Application Binary Interface\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)\"`, `\"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 * @ignore\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,\n type,\n baseType,\n indexed,\n components,\n arrayLength,\n 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 * @returns {string} The formatted type.\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 +=\n '(' + 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 * This provides a type guard ensuring that {@link arrayChildren | **arrayChildren**} and\n * {@link arrayLength | **arrayLength**} are non-null.\n *\n * @returns {boolean} True if this is an Array type.\n */\n isArray() {\n return this.baseType === 'array';\n }\n /**\n * This provides a type guard ensuring that {@link components | **components**} is non-null.\n *\n * @returns {boolean} True if this is a Tuple type.\n */\n isTuple() {\n return this.baseType === 'tuple';\n }\n /**\n * This provides a type guard ensuring that {@link indexed | **indexed**} is non-null.\n *\n * @returns {boolean} True if this is an Indexable type.\n */\n isIndexable() {\n return this.indexed != null;\n }\n /**\n * Walks the **ParamType** with `value`, calling `process` 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 // eslint-disable-next-line @typescript-eslint/no-this-alias\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 // eslint-disable-next-line @typescript-eslint/no-this-alias\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 /**\n * @ignore\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 () {\n setValue(await result);\n })());\n }\n else {\n setValue(result);\n }\n }\n /**\n * Walks the **ParamType** with `value`, asynchronously calling `process` on each type, destructing the `value`\n * recursively.\n *\n * This can be used to resolve ENS naes by walking and resolving each `\"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, 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 const 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 *\n * @category Application Binary Interface\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 * @ignore\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 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 // eslint-disable-next-line no-empty\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':\n return ConstructorFragment.from(obj);\n case 'error':\n return ErrorFragment.from(obj);\n case 'event':\n return EventFragment.from(obj);\n case 'fallback':\n case 'receive':\n return FallbackFragment.from(obj);\n case 'function':\n return FunctionFragment.from(obj);\n case 'struct':\n return StructFragment.from(obj);\n }\n }\n else if (typeof obj === 'object') {\n // JSON ABI\n switch (obj.type) {\n case 'constructor':\n return ConstructorFragment.from(obj);\n case 'error':\n return ErrorFragment.from(obj);\n case 'event':\n return EventFragment.from(obj);\n case 'fallback':\n case 'receive':\n return FallbackFragment.from(obj);\n case 'function':\n return FunctionFragment.from(obj);\n case 'struct':\n 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 {@link ConstructorFragment | **ConstructorFragment**}.\n */\n static isConstructor(value) {\n return ConstructorFragment.isFragment(value);\n }\n /**\n * Returns true if `value` is an {@link ErrorFragment | **ErrorFragment**}.\n */\n static isError(value) {\n return ErrorFragment.isFragment(value);\n }\n /**\n * Returns true if `value` is an {@link EventFragment | **EventFragment**}.\n */\n static isEvent(value) {\n return EventFragment.isFragment(value);\n }\n /**\n * Returns true if `value` is a {@link FunctionFragment | **FunctionFragment**}.\n */\n static isFunction(value) {\n return FunctionFragment.isFragment(value);\n }\n /**\n * Returns true if `value` is a {@link StructFragment | **StructFragment**}.\n */\n static isStruct(value) {\n return StructFragment.isFragment(value);\n }\n}\n/**\n * An abstract class to represent An individual fragment which has a name from a parse ABI.\n *\n * @category Application Binary Interface\n */\nexport class NamedFragment extends Fragment {\n /**\n * The name of the fragment.\n */\n name;\n /**\n * @ignore\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 *\n * @category Application Binary Interface\n */\nexport class ErrorFragment extends NamedFragment {\n /**\n * @ignore\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 **ErrorFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === ErrorFragmentInternal;\n }\n}\n/**\n * A Fragment which represents an Event.\n *\n * @category Application Binary Interface\n */\nexport class EventFragment extends NamedFragment {\n /**\n * Whether this event is anonymous.\n */\n anonymous;\n /**\n * @ignore\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 **EventFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === EventFragmentInternal;\n }\n}\n/**\n * A Fragment which represents a constructor.\n *\n * @category Application Binary Interface\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 * @ignore\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 **ConstructorFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === ConstructorFragmentInternal;\n }\n}\n/**\n * A Fragment which represents a method.\n *\n * @category Application Binary Interface\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 **FallbackFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === FallbackFragmentInternal;\n }\n}\n/**\n * A Fragment which represents a method.\n *\n * @category Application Binary Interface\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` 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 * @ignore\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 **FunctionFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === FunctionFragmentInternal;\n }\n}\n/**\n * A Fragment which represents a structure.\n *\n * @category Application Binary Interface\n */\nexport class StructFragment extends NamedFragment {\n /**\n * @ignore\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 **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](../classes/Contract), the data is generally encoded\n * using the [ABI\n * Specification](https://docs.soliditylang.org/en/v0.8.19/abi-spec.html#formal-specification-of-the-encoding).\n *\n * The AbiCoder provides a utility to encode values to ABI data and decode values from ABI data.\n *\n * Most of the time, developers should favor the [Contract](../classes/Contract) class, which further abstracts the\n * finer details of ABI data.\n *\n * @category Application Binary Interface\n */\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,\n data,\n reason,\n transaction,\n invocation,\n revert,\n });\n}\n/**\n * The **AbiCoder** is a low-level class responsible for encoding JavaScript values into binary data and decoding binary\n * data into JavaScript values.\n *\n * @category Application Binary Interface\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 const 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 const 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. For example, a `uint` is by default `0` and `bool` is by default\n * `false`.\n *\n * @param {(string | ParamType)[]} types - Array of parameter types to get default values for.\n * @returns {Result} The default values corresponding to the given types.\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 specified types into ABI data.\n *\n * @param {(string | ParamType)[]} types - Array of parameter types.\n * @param {any[]} values - Array of values to encode.\n * @returns {string} The encoded data in hexadecimal format.\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 not enforced. Some older versions of Solidity incorrectly\n * padded event data emitted from `external` functions.\n *\n * @param {(string | ParamType)[]} types - Array of parameter types.\n * @param {BytesLike} data - The ABI data to decode.\n * @param {boolean} [loose=false] - Enable loose decoding. Default is `false`\n * @returns {Result} The decoded values.\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 /**\n * Set the default maximum inflation factor.\n *\n * @ignore\n * @param {number} value - The new inflation factor.\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 {@link AbiCoder | **AbiCoder**}.\n *\n * On the first call, the instance is created internally.\n *\n * @returns {AbiCoder} The default ABI coder instance.\n */\n static defaultAbiCoder() {\n if (defaultCoder == null) {\n defaultCoder = new AbiCoder();\n }\n return defaultCoder;\n }\n /**\n * Returns a quais-compatible {@link CallExceptionError | **CallExceptionError**} for the given result data.\n *\n * @param {CallExceptionAction} action - The action that triggered the exception.\n * @param {Object} tx - The transaction information.\n * @param {BytesLike | null} data - The data associated with the call exception.\n * @returns {CallExceptionError} The corresponding call exception error.\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 ABI and provides all the necessary functionality to encode\n * and decode paramaters to and results from methods, events and errors.\n *\n * It also provides several convenience methods to automatically search and find matching transactions and events to\n * parse them.\n *\n * @category Application Binary Interface\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 {@link Interface.parseLog | **Interface.parseLog**} to automatically match a Log to its event for\n * parsing, a **LogDescription** is returned.\n *\n * @category Application Binary Interface\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,\n name,\n signature,\n topic,\n args,\n });\n }\n}\n/**\n * When using the {@link Interface.parseTransaction | **Interface.parseTransaction**} to automatically match a\n * transaction data to its function for parsing, a **TransactionDescription** is returned.\n *\n * @category Application Binary Interface\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,\n name,\n args,\n signature,\n selector,\n value,\n });\n }\n}\n/**\n * When using the {@link Interface.parseError | **Interface.parseError**} to automatically match an error for a call\n * result for parsing, an **ErrorDescription** is returned.\n *\n * @category Application Binary Interface\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,\n name,\n args,\n signature,\n selector,\n });\n }\n}\n/**\n * An **Indexed** is used as a value when a value that does not fit within a topic (i.e. not a fixed-length, 32-byte\n * type). It is the `keccak256` of the value, and used for types such as arrays, tuples, bytes and strings.\n *\n * @category Application Binary Interface\n */\nexport class Indexed {\n /**\n * The `keccak256` of the value logged.\n */\n hash;\n /**\n * @ignore\n */\n _isIndexed;\n /**\n * Check if a value is an **Indexed** This provides a Type Guard for property access.\n *\n * @param value - The value to check.\n *\n * @returns `true` if the value is an **Indexed**.\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 encoding and decoding the data on the blockchain.\n *\n * An ABI provides information on how to encode data to send to a Contract, how to decode the results and events and how\n * to interpret revert errors.\n *\n * The ABI can be specified by {@link InterfaceAbi | any supported format}.\n *\n * @category Application Binary Interface\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;\n #abiCoder;\n /**\n * Create a new Interface for the fragments.\n *\n * @param {InterfaceAbi} fragments - The ABI 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 const frags = [];\n for (const a of abi) {\n try {\n frags.push(Fragment.from(a));\n }\n catch (error) {\n console.log('Error parsing ABI fragment', error);\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 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 bucket = this.#functions;\n break;\n case 'event':\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 signatures, optionally as `minimal` strings, which removes\n * 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 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 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, function name or function signature that\n * 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 function signature) is present in the ABI.\n *\n * In the case of a function name, the name may be ambiguous, so accessing the\n * {@link FunctionFragment | **FunctionFragment**} may require refinement.\n */\n hasFunction(key) {\n return !!this.#getFunction(key, null, false);\n }\n /**\n * Get the {@link FunctionFragment | **FunctionFragment**} for `key`, which may be a function selector, function name\n * or function signature that belongs to the ABI.\n *\n * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple functions match by\n * name.\n *\n * If the `key` and `values` do not refine to a single function in 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, 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 event signature) is present in the ABI.\n *\n * In the case of an event name, the name may be ambiguous, so accessing the\n * {@link EventFragment | **EventFragment**} may require refinement.\n */\n hasEvent(key) {\n return !!this.#getEvent(key, null, false);\n }\n /**\n * Get the {@link EventFragment | **EventFragment**} for `key`, which may be a topic hash, event name or event\n * signature that belongs to the ABI.\n *\n * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple events match by name.\n *\n * If the `key` and `values` do not refine to a single event in 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 {@link ErrorFragment | **ErroFragment**} for `key`, which may be an error selector, error name or error\n * signature that belongs to the ABI.\n *\n * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple errors match by name.\n *\n * If the `key` and `values` do not refine to a single error in the ABI, this will throw.\n */\n // TODO: `values` is not used, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 /**\n * @ignore\n */\n _decodeParams(params, data) {\n return this.#abiCoder.decode(params, data);\n }\n /**\n * @ignore\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 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 `quai_call`) for the specified error (see {@link getError | **getError**}\n * for valid values for `key`).\n *\n * Most developers should prefer the {@link parseCallResult | **parseCallResult**} method instead, which will\n * automatically detect a `CALL_EXCEPTION` and throw the 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 reverted from the the Contract with the sepcified\n * `error` (see {@link getError | **getError**} for valid values for `fragment`) with the `values`.\n *\n * This is generally not used by most developers, unless trying to mock 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([fragment.selector, this._encodeParams(fragment.inputs, values || [])]);\n }\n /**\n * Decodes the `data` from a transaction `tx.data` for the function specified (see\n * {@link getFunction | **getFunction**} for valid values for `fragment`).\n *\n * Most developers should prefer the {@link parseTransaction | **parseTransaction**} method instead, which will\n * 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 specified (see\n * {@link getFunction | **getFunction**} for valid values for `fragment`) with 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([fragment.selector, this._encodeParams(fragment.inputs, values || [])]);\n }\n /**\n * Decodes the result `data` (e.g. from an `quai_call`) for the specified function (see\n * {@link getFunction | **getFunction**} for valid values for `key`).\n *\n * Most developers should prefer the {@link parseCallResult | **parseCallResult**} method instead, which will\n * automatically detect a `CALL_EXCEPTION` and throw the 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,\n signature: ef.format(),\n 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 `quai_call`) for the specified function (see\n * {@link getFunction | **getFunction**} for valid values for `fragment`) with `values`.\n *\n * This is generally not used by most developers, unless trying to mock 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 // Create the filter for the event with search criteria (e.g. for quai_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 // TODO: `index` is not used, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n fragment.inputs.forEach((param, index) => {\n if (param.indexed) {\n if (param.type === 'string' ||\n param.type === 'bytes' ||\n param.baseType === 'tuple' ||\n 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 & { [ 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 the parameter values along with other useful\n * 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 // TODO: not implemented\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n parseCallResult(data) {\n throw new Error('@TODO');\n }\n /**\n * Parses a receipt log, finding the matching event and extracts the parameter values along with other useful event\n * 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 the parameter values along with other useful error\n * 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 {@link Interface | **Interface**} from the ABI `value`.\n *\n * The `value` may be provided as an existing {@link Interface | **Interface**} object, a JSON-encoded ABI or any\n * 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 // Maybe an interface from an older version, or from a symlinked copy\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 { validateAddress } from '../address/index.js';\nimport { getAddress } from '../address/index.js';\nimport { assertArgument, isHexString } from '../utils/index.js';\n/**\n * Converts an address and storage keys into an access set.\n *\n * @param {string} addr - The address to validate and convert.\n * @param {Array} storageKeys - The storage keys to validate and convert.\n * @returns {{ address: string; storageKeys: Array }} The access set.\n */\nfunction accessSetify(addr, storageKeys) {\n validateAddress(addr);\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 an {@link AccessList | **AccessList**} from any quasi-supported access-list structure.\n *\n * @category Transaction\n * @param {AccessListish} value - The value to convert to an access list.\n * @returns {AccessList} The access list.\n * @throws {Error} If the value is not a valid access list.\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 { keccak256, Signature } from '../crypto/index.js';\nimport { getBigInt, assert, assertArgument } from '../utils/index.js';\nimport { encodeProtoTransaction } from '../encoding/proto-encode.js';\n/**\n * An **AbstractTransaction** describes the common operations to be executed on Quai and Qi ledgers by an Externally\n * Owned Account (EOA). This class must be subclassed by concrete implementations of transactions on each ledger.\n */\nexport class AbstractTransaction {\n _type;\n _signature;\n _chainId;\n /**\n * The transaction type.\n *\n * If null, the type will be automatically inferred based on explicit properties.\n */\n get type() {\n return this._type;\n }\n set type(value) {\n switch (value) {\n case null:\n this._type = null;\n break;\n case 0:\n case 'standard':\n this._type = 0;\n break;\n case 2:\n case 'utxo':\n this._type = 2;\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:\n return 'standard';\n case 1:\n return 'external';\n case 2:\n return 'utxo';\n }\n return null;\n }\n /**\n * The chain ID this transaction is valid on.\n */\n get chainId() {\n return this._chainId;\n }\n set chainId(value) {\n this._chainId = getBigInt(value);\n }\n /**\n * If signed, the signature for this transaction.\n */\n get signature() {\n return (this._signature || null);\n }\n set signature(value) {\n if (typeof value === 'string') {\n this._signature = value;\n }\n else {\n this._signature = (value == null ? null : Signature.from(value));\n }\n }\n /**\n * Creates a new Transaction with default values.\n */\n constructor() {\n this._type = null;\n this._chainId = BigInt(0);\n this._signature = null;\n }\n /**\n * The pre-image hash of this transaction.\n *\n * This is the digest that a [Signer](../interfaces/Signer) must sign to authorize this transaction.\n */\n get digest() {\n return keccak256(this.unsignedSerialized);\n }\n /**\n * Returns true if signed.\n *\n * This provides a Type Guard that properties requiring a signed transaction are non-null.\n *\n * @returns {boolean} Indicates if the transaction is signed.\n */\n isSigned() {\n return this.signature != null;\n }\n /**\n * The serialized transaction.\n *\n * This throws if the transaction is unsigned. For the pre-image, use\n * {@link AbstractTransaction.unsignedSerialized | **unsignedSerialized** }.\n */\n get serialized() {\n assert(this.signature != null, 'cannot serialize unsigned transaction; maybe you meant .unsignedSerialized', 'UNSUPPORTED_OPERATION', { operation: '.serialized' });\n return encodeProtoTransaction(this.toProtobuf(true));\n }\n /**\n * The transaction pre-image.\n *\n * The hash of this is the digest which needs to be signed to authorize this transaction.\n */\n get unsignedSerialized() {\n return encodeProtoTransaction(this.toProtobuf(false));\n }\n /**\n * Return the most \"likely\" type; currently the highest supported transaction type.\n *\n * @returns {number} The inferred transaction type.\n */\n inferType() {\n return this.inferTypes().pop();\n }\n /**\n * Check if the transaction is external.\n *\n * @returns {boolean} True if the transaction is external.\n */\n get isExternal() {\n return this.destZone !== undefined && this.originZone !== this.destZone;\n }\n}\n//# sourceMappingURL=abstract-transaction.js.map","import { validateAddress } from '../address/index.js';\nimport { getBigInt } from '../utils/index.js';\n/**\n * List of supported Qi denominations.\n *\n * @category Transaction\n */\nexport const denominations = [\n BigInt(1),\n BigInt(5),\n BigInt(10),\n BigInt(50),\n BigInt(100),\n BigInt(250),\n BigInt(500),\n BigInt(1000),\n BigInt(5000),\n BigInt(10000),\n BigInt(20000),\n BigInt(50000),\n BigInt(100000),\n BigInt(1000000),\n BigInt(10000000),\n BigInt(100000000),\n BigInt(1000000000), // 1000000 Qi\n];\n/**\n * Checks if the provided denomination is valid.\n *\n * @category Transaction\n * @param {bigint} denomination - The denomination to check.\n * @returns {boolean} True if the denomination is valid, false otherwise.\n */\nfunction isValidDenomination(denomination) {\n return denominations.includes(denomination);\n}\n/**\n * Handles conversion of string to bigint, specifically for transaction parameters.\n *\n * @ignore\n * @category Transaction\n * @param {string} value - The value to convert.\n * @param {string} param - The parameter name.\n * @returns {bigint} The converted value.\n */\nfunction handleBigInt(value, param) {\n if (value === '0x') {\n return BigInt(0);\n }\n return getBigInt(value, param);\n}\n/**\n * Given a value, returns an array of supported denominations that sum to the value.\n *\n * @category Transaction\n * @param {bigint} value - The value to denominate.\n * @returns {bigint[]} An array of denominations that sum to the value.\n * @throws {Error} If the value is less than or equal to 0 or cannot be matched with available denominations.\n */\nexport function denominate(value) {\n if (value <= BigInt(0)) {\n throw new Error('Value must be greater than 0');\n }\n const result = [];\n let remainingValue = value;\n // Iterate through denominations in descending order\n for (let i = denominations.length - 1; i >= 0; i--) {\n const denomination = denominations[i];\n // Add the denomination to the result array as many times as possible\n while (remainingValue >= denomination) {\n result.push(denomination);\n remainingValue -= denomination;\n }\n }\n if (remainingValue > 0) {\n throw new Error('Unable to match the value with available denominations');\n }\n return result;\n}\n/**\n * Represents a UTXO (Unspent Transaction Output).\n *\n * @category Transaction\n * @implements {UTXOLike}\n */\nexport class UTXO {\n #txhash;\n #index;\n #address;\n #denomination;\n /**\n * Gets the transaction hash.\n *\n * @returns {null | string} The transaction hash.\n */\n get txhash() {\n return this.#txhash;\n }\n /**\n * Sets the transaction hash.\n *\n * @param {null | string} value - The transaction hash.\n */\n set txhash(value) {\n this.#txhash = value;\n }\n /**\n * Gets the index.\n *\n * @returns {null | number} The index.\n */\n get index() {\n return this.#index;\n }\n /**\n * Sets the index.\n *\n * @param {null | number} value - The index.\n */\n set index(value) {\n this.#index = value;\n }\n /**\n * Gets the address.\n *\n * @returns {string} The address.\n */\n get address() {\n return this.#address || '';\n }\n /**\n * Sets the address.\n *\n * @param {string} value - The address.\n * @throws {Error} If the address is invalid.\n */\n set address(value) {\n validateAddress(value);\n this.#address = value;\n }\n /**\n * Gets the denomination.\n *\n * @returns {null | bigint} The denomination.\n */\n get denomination() {\n return this.#denomination;\n }\n /**\n * Sets the denomination.\n *\n * @param {null | BigNumberish} value - The denomination.\n * @throws {Error} If the denomination value is invalid.\n */\n set denomination(value) {\n if (value == null) {\n this.#denomination = null;\n return;\n }\n const denominationBigInt = handleBigInt(value.toString(), 'denomination');\n if (!isValidDenomination(denominationBigInt)) {\n throw new Error('Invalid denomination value');\n }\n this.#denomination = denominationBigInt;\n }\n /**\n * Constructs a new UTXO instance with null properties.\n */\n constructor() {\n this.#txhash = null;\n this.#index = null;\n this.#address = null;\n this.#denomination = null;\n }\n /**\n * Converts the UTXO instance to a JSON object.\n *\n * @returns {any} A JSON representation of the UTXO instance.\n */\n toJSON() {\n return {\n txhash: this.txhash,\n index: this.index,\n address: this.address,\n denomination: this.denomination,\n };\n }\n /**\n * Creates a UTXO instance from a UTXOLike object.\n *\n * @param {UTXOLike} utxo - The UTXOLike object to convert.\n * @returns {UTXO} The UTXO instance.\n */\n static from(utxo) {\n if (utxo === null) {\n return new UTXO();\n }\n const result = utxo instanceof UTXO ? utxo : new UTXO();\n if (utxo.txhash != null) {\n result.txhash = utxo.txhash;\n }\n if (utxo.index != null) {\n result.index = utxo.index;\n }\n if (utxo.address != null && utxo.address !== '') {\n result.address = utxo.address;\n }\n if (utxo.denomination != null) {\n result.denomination = utxo.denomination;\n }\n return result;\n }\n}\n//# sourceMappingURL=utxo.js.map","import { UTXO } from './utxo.js';\n/**\n * An **AbstractCoinSelector** provides a base class for other sub-classes to implement the functionality for selecting\n * UTXOs for a spend and to properly handle spend and change outputs.\n *\n * This class is abstract and should not be used directly. Sub-classes should implement the\n * {@link AbstractCoinSelector#performSelection | **performSelection**} method to provide the actual coin selection\n * logic.\n *\n * @category Transaction\n * @abstract\n */\nexport class AbstractCoinSelector {\n #availableUXTOs;\n #spendOutputs;\n #changeOutputs;\n /**\n * Gets the available UTXOs.\n * @returns {UTXO[]} The available UTXOs.\n */\n get availableUXTOs() {\n return this.#availableUXTOs;\n }\n /**\n * Sets the available UTXOs.\n * @param {UTXOLike[]} value - The UTXOs to set.\n */\n set availableUXTOs(value) {\n this.#availableUXTOs = value.map((val) => {\n const utxo = UTXO.from(val);\n this._validateUTXO(utxo);\n return utxo;\n });\n }\n /**\n * Gets the spend outputs.\n * @returns {UTXO[]} The spend outputs.\n */\n get spendOutputs() {\n return this.#spendOutputs;\n }\n /**\n * Sets the spend outputs.\n * @param {UTXOLike[]} value - The spend outputs to set.\n */\n set spendOutputs(value) {\n this.#spendOutputs = value.map((utxo) => UTXO.from(utxo));\n }\n /**\n * Gets the change outputs.\n * @returns {UTXO[]} The change outputs.\n */\n get changeOutputs() {\n return this.#changeOutputs;\n }\n /**\n * Sets the change outputs.\n * @param {UTXOLike[]} value - The change outputs to set.\n */\n set changeOutputs(value) {\n this.#changeOutputs = value.map((utxo) => UTXO.from(utxo));\n }\n /**\n * Constructs a new AbstractCoinSelector instance with an empty UTXO array.\n * @param {UTXOEntry[]} [availableUXTOs=[]] - The initial available UTXOs.\n */\n constructor(availableUXTOs = []) {\n this.#availableUXTOs = availableUXTOs.map((val) => {\n const utxo = UTXO.from(val);\n this._validateUTXO(utxo);\n return utxo;\n });\n this.#spendOutputs = [];\n this.#changeOutputs = [];\n }\n /**\n * Validates the provided UTXO instance. In order to be valid for coin selection, the UTXO must have a valid address\n * and denomination.\n *\n * @param {UTXO} utxo - The UTXO to validate.\n * @throws {Error} If the UTXO is invalid.\n * @protected\n */\n _validateUTXO(utxo) {\n if (utxo.address == null) {\n throw new Error('UTXO address is required');\n }\n if (utxo.denomination == null) {\n throw new Error('UTXO denomination is required');\n }\n }\n}\n//# sourceMappingURL=abstract-coinselector.js.map","import { bigIntAbs } from '../utils/maths.js';\nimport { AbstractCoinSelector } from './abstract-coinselector.js';\nimport { UTXO, denominate } from './utxo.js';\n/**\n * The FewestCoinSelector class provides a coin selection algorithm that selects the fewest UTXOs required to meet the\n * target amount. This algorithm is useful for minimizing the size of the transaction and the fees associated with it.\n *\n * This class is a sub-class of {@link AbstractCoinSelector | **AbstractCoinSelector** } and implements the\n * {@link AbstractCoinSelector.performSelection | **performSelection** } method to provide the actual coin selection\n * logic.\n *\n * @category Transaction\n */\nexport class FewestCoinSelector extends AbstractCoinSelector {\n /**\n * The largest first coin selection algorithm.\n *\n * This algorithm selects the largest UTXOs first, and continues to select UTXOs until the target amount is reached.\n * If the total value of the selected UTXOs is greater than the target amount, the remaining value is returned as a\n * change output.\n *\n * @param {SpendTarget} target - The target amount to spend.\n *\n * @returns {SelectedCoinsResult} The selected UTXOs and change outputs.\n */\n performSelection(target) {\n this.validateTarget(target);\n this.validateUTXOs();\n const sortedUTXOs = this.sortUTXOsByDenomination(this.availableUXTOs, 'desc');\n let totalValue = BigInt(0);\n let selectedUTXOs = [];\n // Get UTXOs that meets or exceeds the target value\n const UTXOsEqualOrGreaterThanTarget = sortedUTXOs.filter((utxo) => utxo.denomination && utxo.denomination >= target.value);\n if (UTXOsEqualOrGreaterThanTarget.length > 0) {\n // Find the smallest UTXO that meets or exceeds the target value\n const optimalUTXO = UTXOsEqualOrGreaterThanTarget.reduce((minDenominationUTXO, currentUTXO) => {\n if (!currentUTXO.denomination)\n return minDenominationUTXO;\n return currentUTXO.denomination < minDenominationUTXO.denomination ? currentUTXO : minDenominationUTXO;\n }, UTXOsEqualOrGreaterThanTarget[0]); // Initialize with the first UTXO in the list\n selectedUTXOs.push(optimalUTXO);\n totalValue += optimalUTXO.denomination;\n }\n else {\n // If no single UTXO meets or exceeds the target, aggregate smaller denominations\n // until the target is met/exceeded or there are no more UTXOs to aggregate\n while (sortedUTXOs.length > 0 && totalValue < target.value) {\n const nextOptimalUTXO = sortedUTXOs.reduce((closest, utxo) => {\n if (!utxo.denomination)\n return closest;\n // Prioritize UTXOs that bring totalValue closer to target.value\n const absThisDiff = bigIntAbs(target.value - (totalValue + utxo.denomination));\n const currentClosestDiff = closest && closest.denomination\n ? bigIntAbs(target.value - (totalValue + closest.denomination))\n : BigInt(Infinity);\n return absThisDiff < currentClosestDiff ? utxo : closest;\n }, sortedUTXOs[0]);\n // Add the selected UTXO to the selection and update totalValue\n selectedUTXOs.push(nextOptimalUTXO);\n totalValue += nextOptimalUTXO.denomination;\n // Remove the selected UTXO from the list of available UTXOs\n const index = sortedUTXOs.findIndex((utxo) => utxo.denomination === nextOptimalUTXO.denomination && utxo.address === nextOptimalUTXO.address);\n sortedUTXOs.splice(index, 1);\n }\n }\n // Check if the selected UTXOs meet or exceed the target amount\n if (totalValue < target.value) {\n throw new Error('Insufficient funds');\n }\n // Check if any denominations can be removed from the input set and it still remain valid\n selectedUTXOs = this.sortUTXOsByDenomination(selectedUTXOs, 'asc');\n let runningTotal = totalValue;\n let lastRemovableIndex = -1; // Index of the last UTXO that can be removed\n // Iterate through selectedUTXOs to find the last removable UTXO\n for (let i = 0; i < selectedUTXOs.length; i++) {\n const utxo = selectedUTXOs[i];\n if (utxo.denomination) {\n if (runningTotal - utxo.denomination >= target.value) {\n runningTotal -= utxo.denomination;\n lastRemovableIndex = i;\n }\n else {\n // Once a UTXO makes the total less than target.value, stop the loop\n break;\n }\n }\n }\n if (lastRemovableIndex >= 0) {\n totalValue -= selectedUTXOs[lastRemovableIndex].denomination;\n selectedUTXOs.splice(lastRemovableIndex, 1);\n }\n // Break down the total spend into properly denominatated UTXOs\n const spendDenominations = denominate(target.value);\n this.spendOutputs = spendDenominations.map((denomination) => {\n const utxo = new UTXO();\n utxo.denomination = denomination;\n utxo.address = target.address;\n return utxo;\n });\n // Calculate change to be returned\n const change = totalValue - target.value;\n // If there's change, break it down into properly denominatated UTXOs\n if (change > BigInt(0)) {\n const changeDenominations = denominate(change);\n this.changeOutputs = changeDenominations.map((denomination) => {\n const utxo = new UTXO();\n utxo.denomination = denomination;\n // We do not have access to change addresses here so leave it null\n return utxo;\n });\n }\n else {\n this.changeOutputs = [];\n }\n return {\n inputs: selectedUTXOs,\n spendOutputs: this.spendOutputs,\n changeOutputs: this.changeOutputs,\n };\n }\n /**\n * Sorts UTXOs by their denomination.\n *\n * @param {UTXO[]} utxos - The UTXOs to sort.\n * @param {'asc' | 'desc'} direction - The direction to sort ('asc' for ascending, 'desc' for descending).\n * @returns {UTXO[]} The sorted UTXOs.\n */\n sortUTXOsByDenomination(utxos, direction) {\n if (direction === 'asc') {\n return [...utxos].sort((a, b) => {\n const diff = (a.denomination ?? BigInt(0)) - (b.denomination ?? BigInt(0));\n return diff > 0 ? 1 : diff < 0 ? -1 : 0;\n });\n }\n return [...utxos].sort((a, b) => {\n const diff = (b.denomination ?? BigInt(0)) - (a.denomination ?? BigInt(0));\n return diff > 0 ? 1 : diff < 0 ? -1 : 0;\n });\n }\n /**\n * Validates the target amount.\n *\n * @param {SpendTarget} target - The target amount to validate.\n * @throws Will throw an error if the target amount is less than or equal to 0.\n */\n validateTarget(target) {\n if (target.value <= BigInt(0)) {\n throw new Error('Target amount must be greater than 0');\n }\n }\n /**\n * Validates the available UTXOs.\n *\n * @throws Will throw an error if there are no available UTXOs.\n */\n validateUTXOs() {\n if (this.availableUXTOs.length === 0) {\n throw new Error('No UTXOs available');\n }\n }\n}\n//# sourceMappingURL=coinselector-fewest.js.map","/**\n * @ignore\n */\nimport { getAddress } from '../address/index.js';\nimport { Signature } from '../crypto/index.js';\nimport { accessListify } from '../transaction/index.js';\nimport { hexlify } from '../utils/data.js';\nimport { getBigInt, getNumber, isHexString, zeroPadValue, assert, assertArgument, toBeArray, } 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) {\n return (array) => {\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), '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}\nexport function handleNumber(_value, param) {\n if (_value === '0x') {\n return 0;\n }\n return getNumber(_value, param);\n}\nexport function 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}\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 _formatHeader = object({\n baseFeePerGas: getBigInt,\n efficiencyScore: getBigInt,\n etxEligibleSlices: formatHash,\n etxSetRoot: formatHash,\n evmRoot: formatHash,\n expansionNumber: getNumber,\n extRollupRoot: formatHash,\n extTransactionsRoot: formatHash,\n extraData: formatData,\n gasLimit: getBigInt,\n gasUsed: getBigInt,\n hash: formatHash,\n interlinkRootHash: formatHash,\n manifestHash: arrayOf(formatHash),\n number: arrayOf(getNumber),\n parentDeltaS: arrayOf(getBigInt),\n parentEntropy: arrayOf(getBigInt),\n parentHash: arrayOf(formatHash),\n parentUncledS: arrayOf(allowNull(getBigInt)),\n parentUncledSubDeltaS: arrayOf(getBigInt),\n primeTerminus: formatHash,\n receiptsRoot: formatHash,\n sha3Uncles: formatHash,\n size: getBigInt,\n thresholdCount: getBigInt,\n transactionsRoot: formatHash,\n uncledS: getBigInt,\n utxoRoot: formatHash,\n});\nconst _formatUncle = object({\n coinbase: allowNull(getAddress),\n difficulty: getBigInt,\n headerHash: formatHash,\n location: formatData,\n mixHash: formatHash,\n nonce: formatData,\n number: getNumber,\n parentHash: formatHash,\n primeTerminusNumber: getNumber,\n time: getBigInt,\n txHash: formatHash,\n workShare: formatBoolean,\n});\nconst _formatWoHeader = object({\n coinbase: getAddress,\n difficulty: getNumber,\n headerHash: formatHash,\n location: formatData,\n mixHash: formatHash,\n nonce: formatData,\n number: getNumber,\n parentHash: formatHash,\n primeTerminusNumber: getNumber,\n time: formatData,\n txHash: formatHash,\n});\nconst _formatBlock = object({\n extTransactions: arrayOf((tx) => {\n if (typeof tx === 'string') {\n return formatHash(tx);\n }\n return formatExternalTransactionResponse(tx);\n }),\n hash: formatHash,\n header: _formatHeader,\n interlinkHashes: arrayOf(formatHash),\n order: getNumber,\n size: getBigInt,\n subManifest: arrayOf(formatData),\n totalEntropy: getBigInt,\n transactions: arrayOf((tx) => {\n if (typeof tx === 'string') {\n return formatHash(tx);\n }\n return formatTransactionResponse(tx);\n }),\n uncles: allowNull(arrayOf(_formatUncle), []),\n woHeader: _formatWoHeader,\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 if ('originatingTxHash' in tx) {\n return formatExternalTransactionResponse(tx);\n }\n return formatTransactionResponse(tx);\n });\n result.extTransactions = value.extTransactions.map((tx) => {\n if (typeof tx === 'string') {\n return tx;\n }\n return formatExternalTransactionResponse(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 _formatEtx = object({\n type: allowNull(getNumber, 0),\n nonce: allowNull(getNumber),\n gasPrice: allowNull(getBigInt),\n maxPriorityFeePerGas: allowNull(getBigInt),\n maxFeePerGas: allowNull(getBigInt),\n gas: allowNull(getBigInt),\n value: allowNull(getBigInt, BN_0),\n input: allowNull(formatData),\n to: allowNull(getAddress, null),\n accessList: allowNull(accessListify, null),\n isCoinbase: allowNull(getNumber, 0),\n sender: getAddress,\n originatingTxHash: formatHash,\n etxIndex: getNumber,\n chainId: allowNull(getBigInt, null),\n hash: formatHash,\n}, {\n from: ['sender'],\n});\nexport function formatEtx(value) {\n return _formatEtx(value);\n}\nconst _formatTransactionReceipt = object({\n to: allowNull(getAddress, null),\n from: allowNull(getAddress, null),\n contractAddress: allowNull(getAddress, null),\n index: getNumber,\n gasUsed: getBigInt,\n logsBloom: allowNull(formatData),\n blockHash: formatHash,\n hash: formatHash,\n logs: arrayOf(formatReceiptLog),\n blockNumber: getNumber,\n cumulativeGasUsed: getBigInt,\n effectiveGasPrice: allowNull(getBigInt),\n status: allowNull(getNumber),\n type: allowNull(getNumber, 0),\n etxs: (value) => (value === null ? [] : arrayOf(formatEtx)(value)),\n}, {\n hash: ['transactionHash'],\n index: ['transactionIndex'],\n});\nexport function formatTransactionReceipt(value) {\n const result = _formatTransactionReceipt(value);\n return result;\n}\nexport function formatExternalTransactionResponse(value) {\n const result = object({\n hash: formatHash,\n type: (value) => {\n if (value === '0x' || value == null) {\n return 0;\n }\n return parseInt(value, 16);\n },\n accessList: allowNull(accessListify, null),\n blockHash: allowNull(formatHash, null),\n blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null),\n index: allowNull((value) => (value ? BigInt(value) : null), null),\n from: allowNull(getAddress, null),\n sender: allowNull(getAddress, null),\n maxPriorityFeePerGas: allowNull((value) => (value ? BigInt(value) : null)),\n maxFeePerGas: allowNull((value) => (value ? BigInt(value) : null)),\n gasLimit: allowNull((value) => (value ? BigInt(value) : null), null),\n to: allowNull(getAddress, null),\n value: allowNull((value) => (value ? BigInt(value) : null), null),\n nonce: allowNull((value) => (value ? parseInt(value, 10) : null), null),\n creates: allowNull(getAddress, null),\n chainId: allowNull((value) => (value ? BigInt(value) : null), null),\n isCoinbase: allowNull((value) => (value ? parseInt(value, 10) : null), null),\n originatingTxHash: allowNull(formatHash, null),\n etxIndex: allowNull((value) => (value ? parseInt(value, 10) : null), null),\n etxType: allowNull((value) => value, null),\n data: (value) => value,\n }, {\n data: ['input'],\n gasLimit: ['gas'],\n index: ['transactionIndex'],\n })(value);\n // 0x0000... should actually be null\n if (result.blockHash && getBigInt(result.blockHash) === BN_0) {\n result.blockHash = null;\n }\n return result;\n}\nexport function formatTransactionResponse(value) {\n // Determine if it is a Quai or Qi transaction based on the type\n const transactionType = parseInt(value.type, 16);\n let result;\n if (transactionType === 0x0 || transactionType === 0x1) {\n // QuaiTransactionResponseParams\n result = object({\n hash: formatHash,\n type: (value) => {\n if (value === '0x' || value == null) {\n return 0;\n }\n return parseInt(value, 16);\n },\n accessList: allowNull(accessListify, null),\n blockHash: allowNull(formatHash, null),\n blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null),\n index: allowNull((value) => (value ? BigInt(value) : null), null),\n from: allowNull(getAddress, null),\n sender: allowNull(getAddress, null),\n maxPriorityFeePerGas: allowNull((value) => (value ? BigInt(value) : null)),\n maxFeePerGas: allowNull((value) => (value ? BigInt(value) : null)),\n gasLimit: allowNull((value) => (value ? BigInt(value) : null), null),\n to: allowNull(getAddress, null),\n value: allowNull((value) => (value ? BigInt(value) : null), null),\n nonce: allowNull((value) => (value ? parseInt(value, 10) : null), null),\n creates: allowNull(getAddress, null),\n chainId: allowNull((value) => (value ? BigInt(value) : null), null),\n etxType: allowNull((value) => value, null),\n data: (value) => value,\n }, {\n data: ['input'],\n gasLimit: ['gas'],\n index: ['transactionIndex'],\n })(value);\n // Add an access list to supported transaction types\n if ((value.type === 0 || 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 // 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 }\n // 0x0000... should actually be null\n if (result.blockHash && getBigInt(result.blockHash) === BN_0) {\n result.blockHash = null;\n }\n }\n else if (transactionType === 0x2) {\n // QiTransactionResponseParams\n result = object({\n hash: formatHash,\n type: (value) => {\n if (value === '0x' || value == null) {\n return 0;\n }\n return parseInt(value, 16);\n },\n blockHash: allowNull(formatHash, null),\n blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null),\n index: allowNull((value) => (value ? BigInt(value) : null), null),\n chainId: allowNull((value) => (value ? BigInt(value) : null), null),\n signature: (value) => value,\n txInputs: allowNull((value) => value.map(_formatTxInput), null),\n txOutputs: allowNull((value) => value.map(_formatTxOutput), null),\n }, {\n index: ['transactionIndex'],\n signature: ['utxoSignature'],\n txInputs: ['inputs'],\n txOutputs: ['outputs'],\n })(value);\n }\n else {\n throw new Error('Unknown transaction type');\n }\n return result;\n}\nconst _formatTxInput = object({\n txhash: formatTxHash,\n index: formatIndex,\n pubkey: hexlify,\n}, {\n txhash: ['PreviousOutPoint', 'TxHash'],\n index: ['PreviousOutPoint', 'Index'],\n pubkey: ['PubKey'],\n});\nfunction extractTxHash(value) {\n if (value && value.TxHash) {\n return value.TxHash;\n }\n throw new Error('Invalid PreviousOutPoint');\n}\nfunction formatTxHash(value) {\n return formatHash(extractTxHash(value));\n}\nfunction extractIndex(value) {\n if (value && value.Index !== undefined) {\n return value.Index;\n }\n throw new Error('Invalid PreviousOutPoint');\n}\nfunction formatIndex(value) {\n return getNumber(extractIndex(value));\n}\nconst _formatTxOutput = object({\n address: (addr) => hexlify(getAddress(addr)),\n denomination: getNumber,\n});\n//# sourceMappingURL=format.js.map","import { keccak256 } from '../crypto/index.js';\nimport { AbstractTransaction } from './index.js';\nimport { assertArgument, getBytes, getZoneForAddress, hexlify, toBigInt } from '../utils/index.js';\nimport { decodeProtoTransaction } from '../encoding/index.js';\nimport { formatNumber } from '../providers/format.js';\nimport { computeAddress, isQiAddress } from '../address/index.js';\n/**\n * Class representing a QiTransaction.\n *\n * @category Transaction\n * @extends {AbstractTransaction}\n * @implements {QiTransactionLike}\n */\nexport class QiTransaction extends AbstractTransaction {\n #txInputs;\n #txOutputs;\n /**\n * Get transaction inputs.\n *\n * @returns {TxInput[]} The transaction inputs.\n */\n get txInputs() {\n return (this.#txInputs ?? []).map((entry) => ({ ...entry }));\n }\n /**\n * Set transaction inputs.\n *\n * @param {TxInput[] | null} value - The transaction inputs.\n * @throws {Error} If the value is not an array.\n */\n set txInputs(value) {\n if (!Array.isArray(value)) {\n throw new Error('txInputs must be an array');\n }\n this.#txInputs = value.map((entry) => ({ ...entry }));\n }\n /**\n * Get transaction outputs.\n *\n * @returns {TxOutput[]} The transaction outputs.\n */\n get txOutputs() {\n return (this.#txOutputs ?? []).map((output) => ({ ...output }));\n }\n /**\n * Set transaction outputs.\n *\n * @param {TxOutput[] | null} value - The transaction outputs.\n * @throws {Error} If the value is not an array.\n */\n set txOutputs(value) {\n if (!Array.isArray(value)) {\n throw new Error('txOutputs must be an array');\n }\n this.#txOutputs = value.map((output) => ({ ...output }));\n }\n /**\n * Get the permuted hash of the transaction as specified by QIP-0010.\n *\n * @returns {string | null} The transaction hash.\n * @throws {Error} If the transaction has no inputs or outputs, or if cross-zone & cross-ledger transactions are not\n * supported.\n * @see {@link [QIP0010](https://github.com/quai-network/qips/blob/master/qip-0010.md)}\n */\n get hash() {\n if (this.signature == null) {\n return null;\n }\n if (this.txInputs.length < 1 || this.txOutputs.length < 1) {\n throw new Error('Transaction must have at least one input and one output');\n }\n const senderAddr = computeAddress(this.txInputs[0].pubkey || '');\n if (!this.destZone || !this.originZone) {\n throw new Error(`Invalid zones: origin ${this.originZone} -> destination ${this.destZone} (address: ${senderAddr})`);\n }\n const isSameLedger = isQiAddress(senderAddr) === isQiAddress(hexlify(this.txOutputs[0].address) || '');\n if (this.isExternal && !isSameLedger) {\n throw new Error('Cross-zone & cross-ledger transactions are not supported');\n }\n const hexString = this.serialized.startsWith('0x') ? this.serialized.substring(2) : this.serialized;\n const dataBuffer = Buffer.from(hexString, 'hex');\n const hashHex = keccak256(dataBuffer);\n const hashBuffer = Buffer.from(hashHex.substring(2), 'hex');\n const origin = this.originZone ? parseInt(this.originZone.slice(2), 16) : 0;\n hashBuffer[0] = origin;\n hashBuffer[1] |= 0x80;\n hashBuffer[2] = origin;\n hashBuffer[3] |= 0x80;\n return '0x' + hashBuffer.toString('hex');\n }\n /**\n * Get the zone of the sender address.\n *\n * @returns {Zone | undefined} The origin zone.\n */\n get originZone() {\n const senderAddr = computeAddress(this.txInputs[0].pubkey || '');\n const zone = getZoneForAddress(senderAddr);\n return zone ?? undefined;\n }\n /**\n * Get the zone of the recipient address.\n *\n * @returns {Zone | undefined} The destination zone.\n */\n get destZone() {\n const zone = getZoneForAddress(this.txOutputs[0].address);\n return zone ?? undefined;\n }\n /**\n * Creates a new Transaction with default values.\n */\n constructor() {\n super();\n this.#txInputs = [];\n this.#txOutputs = [];\n }\n /**\n * Validates the explicit properties and returns a list of compatible transaction types.\n *\n * @returns {number[]} The compatible transaction types.\n */\n inferTypes() {\n const types = [];\n // Explicit type\n if (this.type != null) {\n types.push(this.type);\n }\n else {\n types.push(2);\n }\n types.sort();\n return types;\n }\n /**\n * Create a copy of this transaction.\n *\n * @returns {QiTransaction} The cloned transaction.\n */\n clone() {\n return QiTransaction.from(this);\n }\n /**\n * Return a JSON-friendly object.\n *\n * @returns {QiTransactionLike} The 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 chainId: s(this.chainId),\n signature: this.signature ? this.signature : null,\n hash: this.hash,\n txInputs: this.txInputs,\n txOutputs: this.txOutputs,\n };\n }\n /**\n * Return a protobuf-friendly JSON object.\n *\n * @param {boolean} [includeSignature=true] - Whether to include the signature. Default is `true`\n * @returns {ProtoTransaction} The protobuf-friendly JSON object.\n */\n toProtobuf(includeSignature = true) {\n const protoTx = {\n type: this.type || 2,\n chain_id: formatNumber(this.chainId || 0, 'chainId'),\n tx_ins: {\n tx_ins: this.txInputs.map((input) => ({\n previous_out_point: {\n hash: { value: getBytes(input.txhash) },\n index: input.index,\n },\n pub_key: getBytes(input.pubkey),\n })),\n },\n tx_outs: {\n tx_outs: this.txOutputs.map((output) => ({\n address: getBytes(output.address),\n denomination: output.denomination,\n })),\n },\n };\n if (this.signature && includeSignature) {\n protoTx.signature = getBytes(this.signature);\n }\n return protoTx;\n }\n /**\n * Create a Transaction from a serialized transaction or a Transaction-like object.\n *\n * @param {string | QiTransactionLike} tx - The transaction to decode.\n * @returns {QiTransaction} The decoded transaction.\n * @throws {Error} If the transaction is unsigned and defines a hash.\n */\n static from(tx) {\n if (typeof tx === 'string') {\n const decodedProtoTx = decodeProtoTransaction(getBytes(tx));\n return QiTransaction.fromProto(decodedProtoTx);\n }\n const result = new QiTransaction();\n if (tx.type != null) {\n result.type = tx.type;\n }\n if (tx.chainId != null) {\n result.chainId = tx.chainId;\n }\n if (tx.signature != null && tx.signature !== '') {\n result.signature = tx.signature;\n }\n if (tx.txInputs != null) {\n result.txInputs = tx.txInputs;\n }\n if (tx.txOutputs != null) {\n result.txOutputs = tx.txOutputs;\n }\n if (tx.hash != null) {\n assertArgument(result.isSigned(), 'unsigned transaction cannot define hash', 'tx', tx);\n }\n return result;\n }\n /**\n * Create a Transaction from a ProtoTransaction object.\n *\n * @param {ProtoTransaction} protoTx - The transaction to decode.\n * @returns {QiTransaction} The decoded transaction.\n */\n static fromProto(protoTx) {\n const tx = new QiTransaction();\n tx.type = protoTx.type;\n tx.chainId = toBigInt(protoTx.chain_id);\n if (protoTx.type == 2) {\n tx.txInputs =\n protoTx.tx_ins?.tx_ins.map((input) => ({\n txhash: hexlify(input.previous_out_point.hash.value),\n index: input.previous_out_point.index,\n pubkey: hexlify(input.pub_key),\n })) ?? [];\n tx.txOutputs =\n protoTx.tx_outs?.tx_outs.map((output) => ({\n address: hexlify(output.address),\n denomination: output.denomination,\n })) ?? [];\n }\n if (protoTx.signature) {\n tx.signature = hexlify(protoTx.signature);\n }\n return tx;\n }\n}\n//# sourceMappingURL=qi-transaction.js.map","import { keccak256, Signature } from '../crypto/index.js';\nimport { accessListify, AbstractTransaction } from './index.js';\nimport { assert, assertArgument, getBigInt, getBytes, getNumber, getZoneForAddress, hexlify, toBeArray, toBigInt, zeroPadValue, } from '../utils/index.js';\nimport { decodeProtoTransaction, encodeProtoTransaction } from '../encoding/index.js';\nimport { getAddress, recoverAddress, validateAddress, isQuaiAddress } from '../address/index.js';\nimport { formatNumber, handleNumber } from '../providers/format.js';\n/**\n * Parses a signature from an array of fields.\n *\n * @ignore\n * @param {string[]} fields - The fields to parse.\n * @returns {Signature} The parsed signature.\n */\nexport function _parseSignature(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 return Signature.from({ r, s, yParity });\n}\n/**\n * Represents a Quai transaction.\n *\n * @category Transaction\n */\nexport class QuaiTransaction extends AbstractTransaction {\n #to;\n #data;\n #nonce;\n #gasLimit;\n #gasPrice;\n #maxPriorityFeePerGas;\n #maxFeePerGas;\n #value;\n #accessList;\n from;\n /**\n * The `to` address for the transaction or `null` if the transaction is an `init` transaction.\n *\n * @type {null | string}\n */\n get to() {\n return this.#to;\n }\n set to(value) {\n if (value !== null)\n validateAddress(value);\n this.#to = value;\n }\n /**\n * The permuted hash of the transaction as specified by\n * [QIP-0010](https://github.com/quai-network/qips/blob/master/qip-0010.md).\n *\n * @type {null | string}\n * @throws {Error} If the transaction is not signed.\n */\n get hash() {\n if (this.signature == null)\n return null;\n if (!this.originZone) {\n throw new Error('Invalid Zone for from address');\n }\n if (!this.from) {\n throw new Error('Missing from address');\n }\n const isSameLedger = !this.to || isQuaiAddress(this.from) === isQuaiAddress(this.to);\n if (this.isExternal && !isSameLedger) {\n throw new Error('Cross-zone & cross-ledger transactions are not supported');\n }\n const hexString = this.serialized.startsWith('0x') ? this.serialized.substring(2) : this.serialized;\n const dataBuffer = Buffer.from(hexString, 'hex');\n const hashHex = keccak256(dataBuffer);\n const hashBuffer = Buffer.from(hashHex.substring(2), 'hex');\n const origin = this.originZone ? parseInt(this.originZone.slice(2), 16) : 0;\n hashBuffer[0] = origin;\n hashBuffer[1] &= 0x7f;\n hashBuffer[2] = origin;\n hashBuffer[3] &= 0x7f;\n return '0x' + hashBuffer.toString('hex');\n }\n /**\n * The zone of the sender address\n *\n * @type {Zone | undefined}\n */\n get originZone() {\n const zone = this.from ? getZoneForAddress(this.from) : undefined;\n return zone ?? undefined;\n }\n /**\n * The zone of the recipient address\n *\n * @type {Zone | undefined}\n */\n get destZone() {\n const zone = this.to !== null ? getZoneForAddress(this.to || '') : undefined;\n return zone ?? undefined;\n }\n /**\n * The transaction nonce.\n *\n * @type {number}\n */\n get nonce() {\n return this.#nonce;\n }\n set nonce(value) {\n this.#nonce = getNumber(value, 'value');\n }\n /**\n * The gas limit.\n *\n * @type {bigint}\n */\n get gasLimit() {\n return this.#gasLimit;\n }\n set gasLimit(value) {\n this.#gasLimit = getBigInt(value);\n }\n /**\n * The gas price.\n *\n * On legacy networks this defines the fee that will be paid. On EIP-1559 networks, this should be `null`.\n *\n * @type {null | bigint}\n */\n get gasPrice() {\n const value = this.#gasPrice;\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 networks this should be `null`.\n *\n * @type {null | bigint}\n */\n get maxPriorityFeePerGas() {\n const value = this.#maxPriorityFeePerGas;\n if (value == null) {\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 networks this should be `null`.\n *\n * @type {null | bigint}\n */\n get maxFeePerGas() {\n const value = this.#maxFeePerGas;\n if (value == null) {\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 deployment code.\n *\n * @type {string}\n */\n get data() {\n return this.#data;\n }\n set data(value) {\n this.#data = hexlify(value);\n }\n /**\n * The amount of ether to send in this transactions.\n *\n * @type {bigint}\n */\n get value() {\n return this.#value;\n }\n set value(value) {\n this.#value = getBigInt(value, 'value');\n }\n /**\n * The access list.\n *\n * An access list permits discounted (but pre-paid) access to bytecode and state variable access within contract\n * execution.\n *\n * @type {null | AccessList}\n */\n get accessList() {\n const value = this.#accessList || null;\n if (value == null) {\n return null;\n }\n return value;\n }\n set accessList(value) {\n this.#accessList = value == null ? null : accessListify(value);\n }\n /**\n * Creates a new Transaction with default values.\n *\n * @param {string} [from] - The sender address.\n */\n constructor(from) {\n super();\n this.#to = null;\n this.#nonce = 0;\n this.#gasLimit = BigInt(0);\n this.#gasPrice = null;\n this.#maxPriorityFeePerGas = null;\n this.#maxFeePerGas = null;\n this.#data = '0x';\n this.#value = BigInt(0);\n this.#accessList = null;\n this.from = from;\n }\n /**\n * Validates the explicit properties and returns a list of compatible transaction types.\n *\n * @returns {number[]} The compatible transaction types.\n */\n inferTypes() {\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 assert(this.type !== 0 && this.type !== 1, 'transaction type cannot have externalGasLimit, externalGasTip, externalGasPrice, externalData, or externalAccessList', 'BAD_DATA', { value: this });\n const types = [];\n // Explicit type\n if (this.type != null) {\n types.push(this.type);\n }\n else {\n types.push(0);\n }\n types.sort();\n return types;\n }\n /**\n * Create a copy of this transaction.\n *\n * @returns {QuaiTransaction} The cloned transaction.\n */\n clone() {\n return QuaiTransaction.from(this);\n }\n /**\n * Return a JSON-friendly object.\n *\n * @returns {QuaiTransactionLike} The 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 signature: this.signature ? this.signature.toJSON() : null,\n hash: this.hash,\n accessList: this.accessList,\n };\n }\n /**\n * Return a protobuf-friendly JSON object.\n *\n * @param {boolean} [includeSignature=true] - Whether to include the signature. Default is `true`\n * @returns {ProtoTransaction} The protobuf-friendly JSON object.\n */\n toProtobuf(includeSignature = true) {\n const protoTx = {\n type: this.type || 0,\n chain_id: formatNumber(this.chainId || 0, 'chainId'),\n nonce: this.nonce || 0,\n gas_tip_cap: formatNumber(this.maxPriorityFeePerGas || 0, 'maxPriorityFeePerGas'),\n gas_fee_cap: formatNumber(this.maxFeePerGas || 0, 'maxFeePerGas'),\n gas: Number(this.gasLimit || 0),\n to: this.to != null ? getBytes(this.to) : null,\n value: formatNumber(this.value || 0, 'value'),\n data: getBytes(this.data || '0x'),\n access_list: { access_tuples: [] },\n };\n if (this.signature && includeSignature) {\n protoTx.v = formatNumber(this.signature.yParity, 'yParity');\n protoTx.r = toBeArray(this.signature.r);\n protoTx.s = toBeArray(this.signature.s);\n }\n return protoTx;\n }\n /**\n * Create a **Transaction** from a serialized transaction or a Transaction-like object.\n *\n * @param {string | QuaiTransactionLike} tx - The transaction to decode.\n * @returns {QuaiTransaction} The decoded transaction.\n */\n static from(tx) {\n if (typeof tx === 'string') {\n const decodedProtoTx = decodeProtoTransaction(getBytes(tx));\n return QuaiTransaction.fromProto(decodedProtoTx);\n }\n const result = new QuaiTransaction(tx.from);\n if (tx.type != null) {\n result.type = tx.type;\n }\n if (tx.to != null) {\n validateAddress(tx.to);\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.maxPriorityFeePerGas != null) {\n result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas;\n }\n if (tx.maxFeePerGas != null) {\n result.maxFeePerGas = tx.maxFeePerGas;\n }\n if (tx.data != null && tx.data !== '') {\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 if (tx.hash != null) {\n assertArgument(result.isSigned(), 'unsigned transaction cannot define hash', 'tx', tx);\n }\n if (tx.from != null) {\n assertArgument(isQuaiAddress(tx.from), 'from address must be a Quai address', 'tx.from', tx.from);\n assertArgument((result.from || '').toLowerCase() === (tx.from || '').toLowerCase(), 'from mismatch', 'tx', tx);\n result.from = tx.from;\n }\n return result;\n }\n /**\n * Create a **Transaction** from a ProtoTransaction object.\n *\n * @param {ProtoTransaction} protoTx - The transaction to decode.\n * @returns {QuaiTransaction} The decoded transaction.\n */\n static fromProto(protoTx) {\n // TODO: Fix this because new tx instance requires a 'from' address\n let signature = null;\n let address = '';\n if (protoTx.v && protoTx.r && protoTx.s) {\n // check if protoTx.r is zero\n if (protoTx.r.reduce((acc, val) => (acc += val), 0) == 0) {\n throw new Error('Proto decoding only supported for signed transactions');\n }\n const signatureFields = [hexlify(protoTx.v), hexlify(protoTx.r), hexlify(protoTx.s)];\n signature = _parseSignature(signatureFields);\n const protoTxCopy = structuredClone(protoTx);\n delete protoTxCopy.v;\n delete protoTxCopy.r;\n delete protoTxCopy.s;\n delete protoTxCopy.signature;\n delete protoTxCopy.etx_sender;\n delete protoTxCopy.etx_index;\n address = recoverAddress(keccak256(encodeProtoTransaction(protoTxCopy)), signature);\n }\n const tx = new QuaiTransaction(address);\n if (signature) {\n tx.signature = signature;\n }\n if (protoTx.to !== null) {\n const toAddr = hexlify(protoTx.to);\n tx.to = getAddress(toAddr);\n }\n tx.type = protoTx.type;\n tx.chainId = toBigInt(protoTx.chain_id);\n tx.nonce = Number(protoTx.nonce);\n tx.maxPriorityFeePerGas = toBigInt(protoTx.gas_tip_cap);\n tx.maxFeePerGas = toBigInt(protoTx.gas_fee_cap);\n tx.gasLimit = toBigInt(protoTx.gas);\n tx.value = protoTx.value !== null ? toBigInt(protoTx.value) : BigInt(0);\n tx.data = hexlify(protoTx.data);\n tx.accessList = protoTx.access_list.access_tuples.map((tuple) => ({\n address: hexlify(tuple.address),\n storageKeys: tuple.storage_key.map((key) => hexlify(key)),\n }));\n return tx;\n }\n}\n//# sourceMappingURL=quai-transaction.js.map","import { defineProperties, getBigInt, getNumber, hexlify, resolveProperties, assert, assertArgument, isError, makeError, } from '../utils/index.js';\nimport { computeAddress } from '../address/index.js';\nimport { accessListify } from '../transaction/index.js';\nconst BN_0 = BigInt(0);\nimport { toShard, toZone } from '../constants/index.js';\nimport { getZoneFromNodeLocation, getZoneForAddress } from '../utils/shards.js';\n/**\n * Get the value if it is not null or undefined.\n *\n * @ignore\n * @param {undefined | null | T} value - The value to check.\n * @returns {null | T} The value if not null or undefined, otherwise null.\n */\nfunction getValue(value) {\n if (value == null) {\n return null;\n }\n return value;\n}\n/**\n * Convert a value to a JSON-friendly string.\n *\n * @ignore\n * @param {null | bigint | string} value - The value to convert.\n * @returns {null | string} The JSON-friendly string or null.\n */\nfunction toJson(value) {\n if (value == null) {\n return null;\n }\n return value.toString();\n}\n/**\n * A **FeeData** wraps all the fee-related values associated with the network.\n *\n * @category Providers\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 congestion, increasing the cost during times of heavy\n * load and lowering when less busy.\n *\n * The actual fee per gas will be the base fee for the block 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](https://eips.ethereum.org/EIPS/eip-1559))\n */\n maxFeePerGas;\n /**\n * The additional amount to pay per gas to encourage a validator to include the transaction.\n *\n * The purpose of this is to compensate the validator for the adjusted risk for including a given transaction.\n *\n * This will be `null` on legacy networks (i.e. [pre-EIP-1559](https://eips.ethereum.org/EIPS/eip-1559))\n */\n maxPriorityFeePerGas;\n /**\n * Creates a new FeeData for `gasPrice`, `maxFeePerGas` and `maxPriorityFeePerGas`.\n *\n * @param {null | bigint} [gasPrice] - The gas price.\n * @param {null | bigint} [maxFeePerGas] - The maximum fee per gas.\n * @param {null | bigint} [maxPriorityFeePerGas] - The maximum priority fee per gas.\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 * @returns {any} The 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 * Determines the address from a transaction request.\n *\n * @param {TransactionRequest} tx - The transaction request.\n * @returns {AddressLike} The address from the transaction request.\n * @throws {Error} If unable to determine the address.\n */\nexport function addressFromTransactionRequest(tx) {\n if ('from' in tx && !!tx.from) {\n return tx.from;\n }\n if ('txInputs' in tx && !!tx.txInputs) {\n return computeAddress(tx.txInputs[0].pubkey);\n }\n if ('to' in tx && !!tx.to) {\n return tx.to;\n }\n throw new Error('Unable to determine address from transaction inputs, from or to field');\n}\n/**\n * Returns a copy of `req` with all properties coerced to their strict types.\n *\n * @category Providers\n * @param {TransactionRequest} req - The transaction request to copy.\n * @returns {PreparedTransactionRequest} The prepared transaction request.\n * @throws {Error} If the request is invalid.\n */\nexport function copyRequest(req) {\n const result = {};\n // These could be addresses or Addressables\n if ('to' in req && req.to) {\n result.to = req.to;\n }\n if ('from' in req && req.from) {\n result.from = req.from;\n }\n if ('data' in req && req.data) {\n result.data = hexlify(req.data);\n }\n const bigIntKeys = 'chainId,gasLimit,gasPrice,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 ('accessList' in req && req.accessList) {\n result.accessList = accessListify(req.accessList);\n }\n if ('blockTag' in req) {\n result.blockTag = req.blockTag;\n }\n if ('customData' in req) {\n result.customData = req.customData;\n }\n if ('txInputs' in req && req.txInputs) {\n result.txInputs = req.txInputs.map((entry) => ({ ...entry }));\n }\n if ('txOutputs' in req && req.txOutputs) {\n result.txOutputs = req.txOutputs.map((entry) => ({ ...entry }));\n }\n return result;\n}\n/**\n * Represents the header of a block.\n *\n * @category Providers\n */\nexport class BlockHeader {\n baseFeePerGas;\n efficiencyScore;\n etxEligibleSlices;\n etxSetRoot;\n evmRoot;\n expansionNumber;\n extRollupRoot;\n extTransactionsRoot;\n extraData;\n gasLimit;\n gasUsed;\n hash;\n interlinkRootHash;\n manifestHash;\n number;\n parentDeltaS;\n parentEntropy;\n parentHash;\n parentUncledS;\n parentUncledSubDeltaS;\n primeTerminus;\n receiptsRoot;\n sha3Uncles;\n size;\n thresholdCount;\n transactionsRoot;\n uncledS;\n utxoRoot;\n constructor(params) {\n this.baseFeePerGas = params.baseFeePerGas;\n this.efficiencyScore = params.efficiencyScore;\n this.etxEligibleSlices = params.etxEligibleSlices;\n this.etxSetRoot = params.etxSetRoot;\n this.evmRoot = params.evmRoot;\n this.expansionNumber = params.expansionNumber;\n this.extRollupRoot = params.extRollupRoot;\n this.extTransactionsRoot = params.extTransactionsRoot;\n this.extraData = params.extraData;\n this.gasLimit = params.gasLimit;\n this.gasUsed = params.gasUsed;\n this.hash = params.hash;\n this.interlinkRootHash = params.interlinkRootHash;\n this.manifestHash = params.manifestHash;\n this.number = params.number;\n this.parentDeltaS = params.parentDeltaS;\n this.parentEntropy = params.parentEntropy;\n this.parentHash = params.parentHash;\n this.parentUncledS = params.parentUncledS;\n this.parentUncledSubDeltaS = params.parentUncledSubDeltaS;\n this.primeTerminus = params.primeTerminus;\n this.receiptsRoot = params.receiptsRoot;\n this.sha3Uncles = params.sha3Uncles;\n this.size = params.size;\n this.thresholdCount = params.thresholdCount;\n this.transactionsRoot = params.transactionsRoot;\n this.uncledS = params.uncledS;\n this.utxoRoot = params.utxoRoot;\n }\n toJSON() {\n return {\n baseFeePerGas: this.baseFeePerGas,\n efficiencyScore: this.efficiencyScore,\n etxEligibleSlices: this.etxEligibleSlices,\n etxSetRoot: this.etxSetRoot,\n evmRoot: this.evmRoot,\n expansionNumber: this.expansionNumber,\n extRollupRoot: this.extRollupRoot,\n extTransactionsRoot: this.extTransactionsRoot,\n extraData: this.extraData,\n gasLimit: this.gasLimit,\n gasUsed: this.gasUsed,\n hash: this.hash,\n interlinkRootHash: this.interlinkRootHash,\n manifestHash: this.manifestHash,\n number: this.number,\n parentDeltaS: this.parentDeltaS,\n parentEntropy: this.parentEntropy,\n parentHash: this.parentHash,\n parentUncledS: this.parentUncledS,\n parentUncledSubDeltaS: this.parentUncledSubDeltaS,\n primeTerminus: this.primeTerminus,\n receiptsRoot: this.receiptsRoot,\n sha3Uncles: this.sha3Uncles,\n size: this.size,\n thresholdCount: this.thresholdCount,\n transactionsRoot: this.transactionsRoot,\n uncledS: this.uncledS,\n utxoRoot: this.utxoRoot,\n };\n }\n}\n/**\n * Represents the header of a work object.\n *\n * @category Providers\n */\nexport class WoHeader {\n difficulty;\n headerHash;\n location;\n mixHash;\n nonce;\n number;\n parentHash;\n time;\n txHash;\n /**\n * Creates a new WoHeader instance.\n *\n * @param {WoHeaderParams} params - The parameters for the WoHeader.\n */\n constructor(params) {\n this.difficulty = params.difficulty;\n this.headerHash = params.headerHash;\n this.location = params.location;\n this.mixHash = params.mixHash;\n this.nonce = params.nonce;\n this.number = params.number;\n this.parentHash = params.parentHash;\n this.time = params.time;\n this.txHash = params.txHash;\n }\n toJSON() {\n return {\n difficulty: this.difficulty,\n headerHash: this.headerHash,\n location: this.location,\n mixHash: this.mixHash,\n nonce: this.nonce,\n number: this.number,\n parentHash: this.parentHash,\n time: this.time,\n txHash: this.txHash,\n };\n }\n}\n/**\n * A **Block** represents the data associated with a full block on Ethereum.\n *\n * @category Providers\n */\nexport class Block {\n #extTransactions;\n hash;\n header;\n interlinkHashes; // New parameter\n order;\n size;\n subManifest;\n totalEntropy;\n #transactions;\n uncles;\n woHeader; // New nested parameter structure\n /**\n * The provider connected to the block used to fetch additional details if necessary.\n */\n provider;\n /**\n * Create a new **Block** object.\n *\n * This should generally not be necessary as the unless implementing a low-level library.\n *\n * @param {BlockParams} block - The block parameters.\n * @param {Provider} provider - The provider.\n */\n constructor(block, provider) {\n this.#transactions = block.transactions.map((tx) => {\n if (typeof tx === 'string') {\n return tx;\n }\n if ('originatingTxHash' in tx) {\n return new ExternalTransactionResponse(tx, provider);\n }\n if ('from' in tx) {\n return new QuaiTransactionResponse(tx, provider);\n }\n return new QiTransactionResponse(tx, provider);\n });\n this.#extTransactions = block.extTransactions.map((tx) => {\n if (typeof tx !== 'string') {\n return new ExternalTransactionResponse(tx, provider);\n }\n return tx;\n });\n this.hash = block.hash;\n this.header = new BlockHeader(block.header);\n this.interlinkHashes = block.interlinkHashes;\n this.order = block.order;\n this.size = block.size;\n this.subManifest = block.subManifest;\n this.totalEntropy = block.totalEntropy;\n this.uncles = block.uncles;\n this.woHeader = new WoHeader(block.woHeader);\n this.provider = provider;\n }\n /**\n * Returns the list of transaction hashes, in the order they were executed within the block.\n *\n * @returns {ReadonlyArray} The list of transaction hashes.\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 list of extended transaction hashes, in the order they were executed within the block.\n *\n * @returns {ReadonlyArray} The list of extended transaction hashes.\n */\n get extTransactions() {\n return this.#extTransactions.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 were executed within the block.\n *\n * This is only available for blocks which prefetched transactions, by passing `true` to `prefetchTxs` into\n * {@link Provider.getBlock | **getBlock**}.\n *\n * @returns {TransactionResponse[]} The list of prefetched transactions.\n * @throws {Error} If the transactions were not prefetched.\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 the complete extended transactions, in the order they were executed within the block.\n *\n * This is only available for blocks which prefetched transactions, by passing `true` to `prefetchTxs` into\n * {@link Provider.getBlock | **getBlock**}.\n *\n * @returns {TransactionResponse[]} The list of prefetched extended transactions.\n * @throws {Error} If the transactions were not prefetched.\n */\n get prefetchedExtTransactions() {\n const txs = this.#extTransactions.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 * @returns {any} The JSON-friendly value.\n */\n toJSON() {\n const { hash, header, interlinkHashes, order, size, subManifest, totalEntropy, uncles, woHeader } = this;\n // Using getters to retrieve the transactions and extTransactions\n const transactions = this.transactions;\n const extTransactions = this.extTransactions;\n return {\n _type: 'Block',\n hash,\n header: header.toJSON(),\n interlinkHashes,\n order,\n size: toJson(size),\n subManifest,\n totalEntropy: toJson(totalEntropy),\n uncles,\n woHeader: woHeader.toJSON(),\n transactions,\n extTransactions, // Includes the extended transaction hashes or full transactions based on the prefetched data\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++],\n done: false,\n };\n }\n return { value: undefined, done: true };\n },\n };\n }\n /**\n * The number of transactions in this block.\n *\n * @returns {number} The number of transactions.\n */\n get length() {\n return this.#transactions.length;\n }\n /**\n * The [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) this block was\n * included at.\n *\n * @returns {null | Date} The date this block was included at, or null if the timestamp is not available.\n */\n get date() {\n const timestampHex = this.woHeader.time;\n if (!timestampHex) {\n return null;\n }\n const timestamp = parseInt(timestampHex, 16);\n return new Date(timestamp * 1000);\n }\n /**\n * Get the transaction at `index` within this block.\n *\n * @param {number | string} indexOrHash - The index or hash of the transaction.\n * @returns {Promise} A promise resolving to the transaction.\n * @throws {Error} If the transaction is not found.\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 * Get the extended transaction at `index` within this block.\n *\n * @param {number | string} indexOrHash - The index or hash of the extended transaction.\n * @returns {Promise} A promise resolving to the extended transaction.\n * @throws {Error} If the extended transaction is not found.\n */\n async getExtTransaction(indexOrHash) {\n // Find the internal value by its index or hash\n let tx = undefined;\n if (typeof indexOrHash === 'number') {\n tx = this.#extTransactions[indexOrHash];\n }\n else {\n const hash = indexOrHash.toLowerCase();\n for (const v of this.#extTransactions) {\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 throw new Error(\"External Transaction isn't prefetched\");\n }\n else {\n return tx;\n }\n }\n /**\n * If a **Block** was fetched with a request to include the transactions this will allow synchronous access to those\n * transactions.\n *\n * If the transactions were not prefetched, this will throw.\n *\n * @param {number | string} indexOrHash - The index or hash of the transaction.\n * @returns {TransactionResponse} The transaction.\n * @throws {Error} If the transaction is not found.\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 for all properties on a\n * {@link MinedBlock | **MinedBlock**}.\n *\n * @returns {boolean} True if the block has been mined.\n */\n isMined() {\n return !!this.header.hash;\n }\n /**\n * @ignore\n */\n orphanedEvent() {\n if (!this.isMined() || !this.woHeader.number) {\n throw new Error('');\n }\n return createOrphanedBlockFilter({\n hash: this.header.hash,\n number: parseInt(this.woHeader.number, 16),\n });\n }\n}\n//////////////////////\n// Log\n/**\n * A **Log** in Ethereum represents an event that has been included in a transaction using the `LOG*` opcodes, which are\n * most commonly used by Solidity's emit for announcing events.\n *\n * @category Providers\n */\nexport class Log {\n /**\n * The provider connected to the log used to fetch additional details if necessary.\n */\n provider;\n /**\n * The transaction hash of the transaction this log occurred in. Use the\n * {@link Log.getTransaction | **Log.getTransaction**} to get the\n * {@link TransactionResponse | **TransactionResponse}.\n */\n transactionHash;\n /**\n * The block hash of the block this log occurred in. Use the {@link Log.getBlock | **Log.getBlock**} to get the\n * {@link Block | **Block**}.\n */\n blockHash;\n /**\n * The block number of the block this log occurred in. It is preferred to use the {@link Block.hash | **Block.hash**}\n * when fetching the related {@link Block | **Block**}, since in the case of an orphaned block, the block at that\n * height may have changed.\n */\n blockNumber;\n /**\n * If the **Log** represents a block that was removed due to an orphaned 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 efficiently filtered using the\n * {@link Provider.getLogs | **Provider.getLogs**} method.\n */\n topics;\n /**\n * The index within the block this log occurred at. This is generally not useful to developers, but can be used with\n * the various roots 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,\n blockHash,\n blockNumber,\n data,\n index,\n removed,\n topics,\n transactionHash,\n transactionIndex,\n };\n }\n /**\n * Returns the block that this log occurred in.\n *\n * @param {Shard} shard - The shard to fetch the block from.\n * @returns {Promise} A promise resolving to the block.\n */\n async getBlock(shard) {\n const block = await this.provider.getBlock(shard, 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 * @returns {Promise} A promise resolving to the transaction.\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 log occurred in.\n *\n * @returns {Promise} A promise resolving to the transaction receipt.\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\nexport function zoneFromHash(hash) {\n return toZone(hash.slice(0, 4));\n}\n/**\n * A **TransactionReceipt** includes additional information about a transaction that is only available after it has been\n * mined.\n *\n * @category Providers\n */\nexport class TransactionReceipt {\n /**\n * The provider connected to the log used to fetch additional details 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 responsible for deploying one.\n *\n * This is non-null **only** if the `to` is empty and the `data` 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 {@link Block | **Block**} this transaction was included in.\n */\n blockHash;\n /**\n * The block number of the {@link Block | **Block**} this transaction was included in.\n */\n blockNumber;\n /**\n * The bloom filter bytes that represent all logs that occurred within this transaction. This is generally not\n * useful for most developers, 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 only be approximated, but the sender must\n * pay the gas fee for the entire gas limit. After the transaction, the difference is refunded.\n */\n gasUsed;\n /**\n * The amount of gas used by all transactions within the block for this and all transactions with a lower `index`.\n *\n * This is generally not useful for developers but can be used to validate certain aspects of execution.\n */\n cumulativeGasUsed;\n /**\n * The actual gas price used during execution.\n *\n * Due to the complexity of [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) this value can only be caluclated\n * after the transaction has been mined, snce the base fee is protocol-enforced.\n */\n gasPrice;\n /**\n * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction type.\n */\n type;\n //readonly byzantium!: boolean;\n /**\n * The status of this transaction, indicating success (i.e. `1`) or a revert (i.e. `0`).\n *\n * This is available in post-byzantium blocks, but some backends may 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 could be used to validate certain parts of\n * the receipt.\n */\n #logs;\n etxs = [];\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 const etxs = tx.etxs\n ? tx.etxs.map((etx) => {\n const safeConvert = (value, name) => {\n try {\n if (value != null) {\n return BigInt(value);\n }\n return null;\n }\n catch (error) {\n console.error(`Conversion to BigInt failed for ${name}: ${value}, error: ${error}`);\n return null;\n }\n };\n return {\n type: etx.type,\n nonce: etx.nonce,\n gasPrice: safeConvert(etx.gasPrice, 'gasPrice'),\n maxPriorityFeePerGas: safeConvert(etx.maxPriorityFeePerGas, 'maxPriorityFeePerGas'),\n maxFeePerGas: safeConvert(etx.maxFeePerGas, 'maxFeePerGas'),\n gas: safeConvert(etx.gas, 'gas'),\n value: safeConvert(etx.value, 'value'),\n input: etx.input,\n to: etx.to,\n accessList: etx.accessList,\n chainId: safeConvert(etx.chainId, 'chainId'),\n sender: etx.sender,\n hash: etx.hash,\n isCoinbase: etx.isCoinbase,\n originatingTxHash: etx.originatingTxHash,\n etxIndex: etx.etxIndex,\n };\n })\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 gasPrice,\n etxs: etxs,\n type: tx.type,\n status: tx.status,\n });\n }\n /**\n * The logs for this transaction.\n */\n get logs() {\n return this.#logs;\n }\n /**\n * Returns a JSON-compatible representation.\n */\n toJSON() {\n const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium,\n status, etxs, } = this;\n return {\n _type: 'TransactionReceipt',\n blockHash,\n blockNumber,\n contractAddress,\n cumulativeGasUsed: toJson(this.cumulativeGasUsed),\n from,\n gasPrice: toJson(this.gasPrice),\n gasUsed: toJson(this.gasUsed),\n hash,\n index,\n logs,\n logsBloom,\n status,\n to,\n etxs: etxs ?? [],\n };\n }\n /**\n * @ignore\n */\n get length() {\n return this.logs.length;\n }\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 * @param {Shard} shard - The shard to fetch the block from.\n * @returns {Promise} A promise resolving to the block.\n * @throws {Error} If the block is not found.\n */\n async getBlock(shard) {\n const block = await this.provider.getBlock(shard, 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 * @returns {Promise} A promise resolving to the transaction.\n * @throws {Error} If the transaction is not found.\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 with the `debug_` or `trace_` API enabled.\n *\n * @returns {Promise} A promise resolving to the return value of the transaction.\n * @throws {Error} If the transaction is not found.\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 * @returns {Promise} A promise resolving to the number of confirmations.\n * @throws {Error} If the block is not found.\n */\n async confirmations() {\n const zone = zoneFromHash(this.hash);\n return (await this.provider.getBlockNumber(toShard(zone))) - 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', {\n operation: 'reorderedEvent(other)',\n });\n return createReorderedTransactionFilter(this, other);\n }\n}\nexport class ExternalTransactionResponse {\n /**\n * The provider this is connected to, which will influence how its methods will resolve its async inspection\n * 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 [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy\n * transactions types.\n */\n type;\n /**\n * The receiver of this transaction.\n *\n * If `null`, then the transaction is an initcode transaction. This means the result of executing the\n * {@link ExternalTransactionResponse.data | **data** } will be deployed as a new contract on chain (assuming it does\n * not revert) and the address may be computed using [getCreateAddress](../functions/getCreateAddress).\n */\n to;\n /**\n * The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and\n * the {@link QuaiTransactionResponse.signature | **signature** } using ecrecover.\n */\n from;\n /**\n * The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender\n * are explicitly ordered.\n *\n * When sending a transaction, this must be equal to the number of transactions ever sent by\n * {@link ExternalTransactionResponse.from | **from** }.\n */\n nonce;\n /**\n * The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is\n * reverted and the sender is charged for the full amount, despite not state changes being made.\n */\n gasLimit;\n /**\n * The data.\n */\n data;\n /**\n * The value, in wei. Use [formatEther](../functions/formatEther) to format this value as ether.\n */\n value;\n /**\n * The chain ID.\n */\n chainId;\n /**\n * The signature.\n */\n signature;\n /**\n * The [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list for transaction types that support it,\n * otherwise `null`.\n */\n accessList;\n etxType;\n isCoinbase;\n originatingTxHash;\n sender;\n etxIndex;\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.chainId = tx.chainId;\n this.signature = tx.signature;\n this.accessList = tx.accessList != null ? tx.accessList : null;\n this.startBlock = -1;\n this.originatingTxHash = tx.originatingTxHash != null ? tx.originatingTxHash : null;\n this.isCoinbase = tx.isCoinbase != null ? tx.isCoinbase : null;\n this.etxType = tx.etxType != null ? tx.etxType : null;\n this.sender = tx.sender;\n this.etxIndex = tx.etxIndex;\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, etxType, isCoinbase, originatingTxHash, etxIndex, sender, } = this;\n const result = {\n _type: 'TransactionReceipt',\n accessList,\n blockNumber,\n blockHash,\n chainId: toJson(this.chainId),\n data,\n from,\n gasLimit: toJson(this.gasLimit),\n hash,\n nonce,\n signature,\n to,\n index,\n type,\n etxType,\n isCoinbase,\n originatingTxHash,\n sender,\n etxIndex,\n value: toJson(this.value),\n };\n return result;\n }\n replaceableTransaction(startBlock) {\n assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock);\n const tx = new ExternalTransactionResponse(this, this.provider);\n tx.startBlock = startBlock;\n return tx;\n }\n}\n/**\n * A **QuaiTransactionResponse** includes all properties about a Quai transaction that was sent to the network, which\n * may or may not be included in a block.\n *\n * The {@link TransactionResponse.isMined | **TransactionResponse.isMined**} can be used to check if the transaction has\n * been mined as well as type guard that the otherwise possibly `null` properties are defined.\n *\n * @category Providers\n */\nexport class QuaiTransactionResponse {\n /**\n * The provider this is connected to, which will influence how its methods will resolve its async inspection\n * 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 [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy\n * transactions types.\n */\n type;\n /**\n * The receiver of this transaction.\n *\n * If `null`, then the transaction is an initcode transaction. This means the result of executing the\n * {@link QuaiTransactionResponse.data | **data** } will be deployed as a new contract on chain (assuming it does not\n * revert) and the address may be computed using [getCreateAddress](../functions/getCreateAddress).\n */\n to;\n /**\n * The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and\n * the {@link QuaiTransactionResponse.signature | **signature** } using ecrecover.\n */\n from;\n /**\n * The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender\n * are explicitly ordered.\n *\n * When sending a transaction, this must be equal to the number of transactions ever sent by\n * {@link QuaiTransactionResponse.from | **from** }.\n */\n nonce;\n /**\n * The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is\n * reverted and the sender is charged for the full amount, despite not state changes being made.\n */\n gasLimit;\n /**\n * The maximum priority fee (per unit of gas) to allow a validator to charge the sender. This is inclusive of the\n * {@link QuaiTransactionResponse.maxFeePerGas | **maxFeePerGas** }.\n */\n maxPriorityFeePerGas;\n /**\n * The maximum fee (per unit of gas) to allow this transaction to charge the sender.\n */\n maxFeePerGas;\n /**\n * The data.\n */\n data;\n /**\n * The value, in wei. Use [formatEther](../functions/formatEther) to format this value as ether.\n */\n value;\n /**\n * The chain ID.\n */\n chainId;\n /**\n * The signature.\n */\n signature;\n /**\n * The [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list for transaction types that support it,\n * otherwise `null`.\n */\n accessList;\n etxType;\n sender;\n originatingTxHash;\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.maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? tx.maxPriorityFeePerGas : null;\n this.maxFeePerGas = tx.maxFeePerGas != null ? tx.maxFeePerGas : null;\n this.chainId = tx.chainId;\n this.signature = tx.signature;\n this.accessList = tx.accessList != null ? tx.accessList : null;\n this.startBlock = -1;\n this.etxType = tx.etxType != null ? tx.etxType : null;\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 } = this;\n const result = {\n _type: 'TransactionReceipt',\n accessList,\n blockNumber,\n blockHash,\n chainId: toJson(this.chainId),\n data,\n from,\n gasLimit: toJson(this.gasLimit),\n hash,\n maxFeePerGas: toJson(this.maxFeePerGas),\n maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas),\n nonce,\n signature,\n to,\n index,\n type,\n value: toJson(this.value),\n };\n return result;\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 * @param {Shard} shard - The shard to fetch the block from.\n * @returns {null | Promise} A promise resolving to the block.\n */\n async getBlock(shard) {\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(shard, 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 provider. This can be used if you have an unmined\n * transaction and wish to get an up-to-date populated instance.\n *\n * @returns {null | Promise} A promise resolving to the transaction, or null if not found.\n */\n async getTransaction() {\n const transaction = this.provider.getTransaction(this.hash);\n if (transaction instanceof QuaiTransactionResponse) {\n return transaction;\n }\n else {\n return null;\n }\n }\n /**\n * Resolve to the number of confirmations this transaction has.\n *\n * @returns {Promise} A promise resolving to the number of confirmations.\n * @throws {Error} If the block is not found.\n */\n async confirmations() {\n const zone = zoneFromHash(this.hash);\n if (this.blockNumber == null) {\n const { tx, blockNumber } = await resolveProperties({\n tx: this.getTransaction(),\n blockNumber: this.provider.getBlockNumber(toShard(zone)),\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(toShard(zone));\n return blockNumber - this.blockNumber + 1;\n }\n /**\n * Resolves once this transaction has been mined and has `confirms` blocks including it (default: `1`) with an\n * optional `timeout`.\n *\n * This can resolve to `null` only if `confirms` is `0` and the transaction has not been mined, otherwise this will\n * wait until enough confirmations have completed.\n *\n * @param {number} [_confirms] - The number of confirmations to wait for.\n * @param {number} [_timeout] - The number of milliseconds to wait before rejecting.\n * @returns {Promise} A promise resolving to the transaction receipt.\n * @throws {Error} If the transaction was replaced, repriced, or cancelled.\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 zone = zoneFromHash(this.hash);\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(toShard(zone)),\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(toShard(zone), 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 ('from' in tx && 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,\n reason: null,\n invocation: null,\n revert: null,\n transaction: {\n to: receipt.to,\n from: receipt.from,\n data: '', // @TODO: in v7, split out sendTransaction properties\n },\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 = () => {\n cancellers.forEach((c) => c());\n };\n // On cancel, stop scanning for replacements\n cancellers.push(() => {\n stopScanning = true;\n });\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(() => {\n clearTimeout(timer);\n });\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(() => {\n this.provider.off(this.hash, txListener);\n });\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(() => {\n this.provider.off('block', replaceListener);\n });\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 was instantiated. To get up-to-date information,\n * use {@link QuaiTransactionResponse.getTransaction | **getTransaction**}.\n *\n * This provides a Type Guard that this transaction will have non-null property values for properties that are null\n * for unmined transactions.\n *\n * @returns {QuaiMinedTransactionResponse} True if the transaction has been mined.\n * @throws {Error} If the transaction was replaced, repriced, or cancelled.\n */\n isMined() {\n return this.blockHash != null;\n }\n /**\n * Returns a filter which can be used to listen for orphan events that evict this transaction.\n *\n * @returns {OrphanFilter} The orphan filter.\n */\n removedEvent() {\n assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n return createRemovedTransactionFilter(this);\n }\n /**\n * Returns a filter which can be used to listen for orphan events that re-order this event against `other`.\n *\n * @param {TransactionResponse} [other] - The other transaction to compare against.\n * @returns {OrphanFilter} The orphan filter.\n */\n reorderedEvent(other) {\n assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n assert(!other || other.isMined(), \"unmined 'other' transaction canot be orphaned\", 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n return createReorderedTransactionFilter(this, other);\n }\n /**\n * Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the\n * transaction is replaced, which will begin scanning at `startBlock`.\n *\n * This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect\n * `startBlock` can have devastating performance consequences if used incorrectly.\n *\n * @param {number} startBlock - The block number to start scanning for replacements.\n * @returns {QuaiTransactionResponse} The replaceable transaction.\n */\n replaceableTransaction(startBlock) {\n assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock);\n const tx = new QuaiTransactionResponse(this, this.provider);\n tx.startBlock = startBlock;\n return tx;\n }\n}\n/**\n * A **QiTransactionResponse** includes all properties about a Qi transaction that was sent to the network, which may or\n * may not be included in a block.\n *\n * The {@link TransactionResponse.isMined | **TransactionResponse.isMined**} can be used to check if the transaction has\n * been mined as well as type guard that the otherwise possibly `null` properties are defined.\n *\n * @category Providers\n */\nexport class QiTransactionResponse {\n /**\n * The provider this is connected to, which will influence how its methods will resolve its async inspection\n * 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 [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy\n * transactions types.\n */\n type;\n /**\n * The chain ID.\n */\n chainId;\n /**\n * The signature.\n */\n signature;\n txInputs;\n txOutputs;\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.chainId = tx.chainId;\n this.signature = tx.signature;\n this.startBlock = -1;\n this.txInputs = tx.txInputs;\n this.txOutputs = tx.txOutputs;\n }\n /**\n * Returns a JSON-compatible representation of this transaction.\n */\n toJSON() {\n const { blockNumber, blockHash, index, hash, type, signature, txInputs, txOutputs } = this;\n const result = {\n _type: 'TransactionReceipt',\n blockNumber,\n blockHash,\n chainId: toJson(this.chainId),\n hash,\n signature,\n index,\n type,\n txInputs: JSON.parse(JSON.stringify(txInputs)),\n txOutputs: JSON.parse(JSON.stringify(txOutputs)),\n };\n return result;\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 * @param {Shard} shard - The shard to fetch the block from.\n * @returns {null | Promise} A promise resolving to the block or null if not found.\n */\n async getBlock(shard) {\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(shard, 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 provider. This can be used if you have an unmined\n * transaction and wish to get an up-to-date populated instance.\n *\n * @returns {null | Promise} A promise resolving to the transaction, or null if not found.\n * @throws {Error} If the transaction is not found.\n */\n async getTransaction() {\n const transaction = this.provider.getTransaction(this.hash);\n if (transaction instanceof QiTransactionResponse) {\n return transaction;\n }\n else {\n return null;\n }\n }\n /**\n * Resolve to the number of confirmations this transaction has.\n *\n * @returns {Promise} A promise resolving to the number of confirmations.\n */\n async confirmations() {\n const zone = zoneFromHash(this.hash);\n if (this.blockNumber == null) {\n const { tx, blockNumber } = await resolveProperties({\n tx: this.getTransaction(),\n blockNumber: this.provider.getBlockNumber(toShard(zone)),\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(toShard(zone));\n return blockNumber - this.blockNumber + 1;\n }\n /**\n * Returns `true` if this transaction has been included.\n *\n * This is effective only as of the time the TransactionResponse was instantiated. To get up-to-date information,\n * use {@link QiTransactionResponse.getTransaction | **getTransaction**}.\n *\n * This provides a Type Guard that this transaction will have non-null property values for properties that are null\n * for unmined transactions.\n *\n * @returns {QiMinedTransactionResponse} True if the transaction has been mined or false otherwise.\n */\n isMined() {\n return this.blockHash != null;\n }\n /**\n * Returns a filter which can be used to listen for orphan events that evict this transaction.\n *\n * @returns {OrphanFilter} The orphan filter.\n */\n removedEvent() {\n assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n return createRemovedTransactionFilter(this);\n }\n /**\n * Returns a filter which can be used to listen for orphan events that re-order this event against `other`.\n *\n * @param {TransactionResponse} [other] - The other transaction to compare against.\n * @returns {OrphanFilter} The orphan filter.\n */\n reorderedEvent(other) {\n assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n assert(!other || other.isMined(), \"unmined 'other' transaction canot be orphaned\", 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n return createReorderedTransactionFilter(this, other);\n }\n /**\n * Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the\n * transaction is replaced, which will begin scanning at `startBlock`.\n *\n * This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect\n * `startBlock` can have devastating performance consequences if used incorrectly.\n *\n * @param {number} startBlock - The block number to start scanning for replacements.\n * @returns {QiTransactionResponse} The replaceable transaction.\n */\n replaceableTransaction(startBlock) {\n assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock);\n const tx = new QiTransactionResponse(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 {\n orphan: 'drop-log',\n 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}\nexport function getZoneFromEventFilter(filter) {\n let zone = null;\n if (filter.nodeLocation) {\n zone = getZoneFromNodeLocation(filter.nodeLocation);\n }\n else if (filter.address) {\n let address;\n if (Array.isArray(filter.address)) {\n address = filter.address[0];\n }\n else {\n address = filter.address;\n }\n const addressZone = getZoneForAddress(address);\n if (addressZone) {\n zone = toZone(addressZone);\n }\n else {\n return null;\n }\n }\n return zone;\n}\n//# sourceMappingURL=provider.js.map","// import from provider.ts instead of index.ts to prevent circular dep\n// from quaiscanProvider\nimport { Log, QuaiTransactionResponse, TransactionReceipt } from '../providers/provider.js';\nimport { defineProperties, EventPayload } from '../utils/index.js';\n/**\n * An **EventLog** contains additional properties parsed from the {@link Log | **Log**}.\n *\n * @category Contract\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() {\n return this.fragment.name;\n }\n /**\n * The signature of the event.\n */\n get eventSignature() {\n return this.fragment.format();\n }\n}\n/**\n * An **EventLog** contains additional properties parsed from the {@link Log | **Log**}.\n *\n * @category Contract\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 {@link TransactionReceipt | **TransactionReceipt**}.\n *\n * @category Contract\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 {@link Log | **Log**} which has a matching event in the 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 {@link ContractTransactionReceipt | **ContractTransactionReceipt**}\n * when waited on.\n *\n * @category Contract\n */\nexport class ContractTransactionResponse extends QuaiTransactionResponse {\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 `confirms` blocks including it (default: `1`) with an\n * optional `timeout`.\n *\n * This can resolve to `null` only if `confirms` is `0` and the transaction has not been mined, otherwise this will\n * wait until enough confirmations have completed.\n *\n * @param {number} confirms - The number of confirmations to wait for.\n *\n * @returns {Promise} The transaction receipt, or `null` if `confirms` is `0`.\n */\n async wait(confirms) {\n const receipt = await super.wait(confirms);\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 Contract Events when the event does not match\n * any events in the ABI.\n *\n * @category Contract\n */\nexport class ContractUnknownEventPayload extends EventPayload {\n /**\n * The log with no matching events.\n */\n log;\n /**\n * @ignore\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 * @param {Shard} shard - The shard to get the block from.\n *\n * @returns {Promise} A promise resolving to the block the event occured in.\n */\n async getBlock(shard) {\n return await this.log.getBlock(shard);\n }\n /**\n * Resolves to the transaction the event occured in.\n *\n * @returns {Promise} A promise resolving 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 * @returns {Promise} A promise resolving 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 Contract Events when the event is known.\n *\n * @category Contract\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, validateAddress } from '../address/index.js';\n// import from provider.ts instead of index.ts to prevent circular dep\n// from quaiscanProvider\nimport { copyRequest, Log, } from '../providers/provider.js';\nimport { defineProperties, getBigInt, isCallException, isHexString, resolveProperties, isError, assert, assertArgument, getZoneForAddress, } from '../utils/index.js';\nimport { ContractEventPayload, ContractUnknownEventPayload, ContractTransactionResponse, EventLog, UndecodedEventLog, } from './wrappers.js';\nimport { getNodeLocationFromZone } from '../utils/shards.js';\nconst BN_0 = BigInt(0);\n/**\n * Check if the value can call transactions.\n *\n * @param {any} value - The value to check.\n * @returns {value is ContractRunnerCaller} True if the value can call transactions.\n */\nfunction canCall(value) {\n return value && typeof value.call === 'function';\n}\n/**\n * Check if the value can estimate gas.\n *\n * @param {any} value - The value to check.\n * @returns {value is ContractRunnerEstimater} True if the value can estimate gas.\n */\nfunction canEstimate(value) {\n return value && typeof value.estimateGas === 'function';\n}\n/**\n * Check if the value can send transactions.\n *\n * @param {any} value - The value to check.\n * @returns {value is ContractRunnerSender} True if the value can send transactions.\n */\nfunction canSend(value) {\n return value && typeof value.sendTransaction === 'function';\n}\n/**\n * Class representing a prepared topic filter.\n *\n * @implements {DeferredTopicFilter}\n */\nclass PreparedTopicFilter {\n #filter;\n fragment;\n /**\n * @ignore\n */\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 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)));\n }\n return resolveAddress(value);\n }\n return value;\n });\n }));\n return contract.interface.encodeFilterTopics(fragment, resolvedArgs);\n })();\n }\n /**\n * Get the topic filter.\n *\n * @returns {Promise} The topic filter.\n */\n getTopicFilter() {\n return this.#filter;\n }\n}\n/**\n * Get the runner for a specific feature.\n *\n * @param {any} value - The value to check.\n * @param {keyof ContractRunner} feature - The feature to check for.\n * @returns {null | T} The runner if available, otherwise null.\n */\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}\n/**\n * Get the provider from a contract runner.\n *\n * @param {null | ContractRunner} value - The contract runner.\n * @returns {null | Provider} The provider if available, otherwise null.\n */\nfunction getProvider(value) {\n if (value == null) {\n return null;\n }\n return value.provider || null;\n}\n/**\n * @ignore Copy overrides and validate them.\n * @param {any} arg - The argument containing overrides.\n * @param {string[]} [allowed] - The allowed override keys.\n * @returns {Promise>} The copied and validated overrides.\n * @throws {Error} If the overrides are invalid.\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(!('to' in overrides) || overrides.to == null || (allowed || []).indexOf('to') >= 0, 'cannot override to', 'overrides.to', overrides);\n assertArgument(!('data' in overrides) || overrides.data == null || (allowed || []).indexOf('data') >= 0, 'cannot override data', 'overrides.data', overrides);\n // Resolve any from\n if ('from' in overrides && overrides.from) {\n overrides.from = await overrides.from;\n }\n return overrides;\n}\n/**\n * @ignore Resolve arguments for a contract runner.\n * @param {null | ContractRunner} _runner - The contract runner.\n * @param {ReadonlyArray} inputs - The input parameter types.\n * @param {any[]} args - The arguments to resolve.\n * @returns {Promise} The resolved arguments.\n */\nexport async function resolveArgs(_runner, inputs, args) {\n // Recursively descend into args and resolve any addresses\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);\n }\n return value;\n });\n }));\n}\n/**\n * Build a wrapped fallback method for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @returns {WrappedFallback} The wrapped fallback method.\n */\nfunction buildWrappedFallback(contract) {\n /**\n * Populate a transaction with overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The populated transaction.\n * @throws {Error} If the overrides are invalid.\n */\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 validateAddress(tx.to);\n if (tx.from) {\n tx.from = await resolveAddress(tx.from);\n validateAddress(tx.from);\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 /**\n * Perform a static call with the given overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The result of the static call.\n * @throws {Error} If the call fails.\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', {\n operation: 'call',\n });\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 /**\n * Send a transaction with the given overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the transaction fails.\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', {\n operation: 'sendTransaction',\n });\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 /**\n * Estimate the gas required for a transaction with the given overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The estimated gas.\n * @throws {Error} If the gas estimation fails.\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', {\n operation: 'estimateGas',\n });\n return await runner.estimateGas(await populateTransaction(overrides));\n };\n /**\n * Send a transaction with the given overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the transaction fails.\n */\n const method = async (overrides) => {\n return await send(overrides);\n };\n defineProperties(method, {\n _contract: contract,\n estimateGas,\n populateTransaction,\n send,\n staticCall,\n });\n return method;\n}\n/**\n * Build a wrapped method for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {string} key - The method key.\n * @returns {BaseContractMethod} The wrapped method.\n */\nfunction buildWrappedMethod(contract, key) {\n /**\n * Get the function fragment for the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {FunctionFragment} The function fragment.\n * @throws {Error} If no matching fragment is found.\n */\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 /**\n * Populate a transaction with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The populated transaction.\n * @throws {Error} If the arguments are invalid.\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 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 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 await resolveProperties({\n to: contract.getAddress(),\n from: args.pop()?.from,\n data: contract.interface.encodeFunctionData(fragment, resolvedArgs),\n });\n };\n /**\n * Perform a static call with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The result of the static call.\n * @throws {Error} If the call fails.\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 /**\n * Send a transaction with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the transaction fails.\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', {\n operation: 'sendTransaction',\n });\n const pop = await populateTransaction(...args);\n if (!pop.from && 'address' in runner && typeof runner.address === 'string') {\n pop.from = await resolveAddress(runner.address);\n }\n const tx = (await runner.sendTransaction(await pop));\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 /**\n * Estimate the gas required for a transaction with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The estimated gas.\n * @throws {Error} If the gas estimation fails.\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', {\n operation: 'estimateGas',\n });\n return await runner.estimateGas(await populateTransaction(...args));\n };\n /**\n * Perform a static call and return the result with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The result of the static call.\n * @throws {Error} If the call fails.\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', {\n operation: 'call',\n });\n const tx = await populateTransaction(...args);\n if (!tx.from && 'address' in runner && typeof runner.address === 'string') {\n tx.from = await resolveAddress(runner.address);\n }\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 /**\n * Send a transaction or perform a static call based on the method arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The result of the method call.\n * @throws {Error} If the method call fails.\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,\n _key: key,\n getFragment,\n estimateGas,\n populateTransaction,\n send,\n staticCall,\n 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}\n/**\n * Build a wrapped event for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {string} key - The event key.\n * @returns {ContractEvent} The wrapped event.\n */\nfunction buildWrappedEvent(contract, key) {\n /**\n * Get the event fragment for the given arguments.\n *\n * @param {...ContractEventArgs} args - The event arguments.\n * @returns {EventFragment} The event fragment.\n * @throws {Error} If no matching fragment is found.\n */\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 /**\n * Create a prepared topic filter for the event.\n *\n * @param {...ContractMethodArgs} args - The event arguments.\n * @returns {PreparedTopicFilter} The prepared topic filter.\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,\n _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('_quaisInternal_contract');\nconst internalValues = new WeakMap();\n/**\n * Set internal values for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {Internal} values - The internal values.\n */\nfunction setInternal(contract, values) {\n internalValues.set(contract[internal], values);\n}\n/**\n * Get internal values for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @returns {Internal} The internal values.\n */\nfunction getInternal(contract) {\n return internalValues.get(contract[internal]);\n}\n/**\n * Check if a value is a deferred topic filter.\n *\n * @param {any} value - The value to check.\n * @returns {value is DeferredTopicFilter} True if the value is a deferred topic filter.\n */\nfunction isDeferred(value) {\n return (value &&\n typeof value === 'object' &&\n 'getTopicFilter' in value &&\n typeof value.getTopicFilter === 'function' &&\n value.fragment);\n}\n/**\n * Get subscription information for an event.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {ContractEventName} event - The event name.\n * @returns {Promise<{ fragment: null | EventFragment; tag: string; topics: TopicFilter }>} The subscription\n * information.\n * @throws {Error} If the event name is unknown.\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 (event && '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\n .map((t) => {\n if (t == null) {\n return 'null';\n }\n if (Array.isArray(t)) {\n return t.join('|');\n }\n return t;\n })\n .join('&');\n return { fragment, tag, topics };\n}\n/**\n * Check if a contract has a subscription for an event.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {ContractEventName} event - The event name.\n * @returns {Promise} The subscription if available, otherwise null.\n */\nasync function hasSub(contract, event) {\n const { subs } = getInternal(contract);\n return subs.get((await getSubInfo(contract, event)).tag) || null;\n}\n/**\n * Get a subscription for an event.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {string} operation - The operation name.\n * @param {ContractEventName} event - The event name.\n * @returns {Promise} The subscription.\n * @throws {Error} If the contract runner does not support subscribing.\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 // eslint-disable-next-line no-empty\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 const zone = getZoneForAddress(await resolveAddress(address));\n let starting = [];\n const start = () => {\n if (starting.length) {\n return;\n }\n starting.push(provider.on(filter, listener, zone));\n };\n const stop = async () => {\n if (starting.length == 0) {\n return;\n }\n const started = starting;\n starting = [];\n await Promise.all(started);\n provider.off(filter, listener, zone);\n };\n sub = { tag, listeners: [], start, stop };\n subs.set(tag, sub);\n }\n return sub;\n}\n/**\n * We use this to ensure one emit resolves before firing the next to ensure correct ordering (note this cannot throw and\n * just adds the notice to the event queue using setTimeout).\n */\nlet lastEmit = Promise.resolve();\n/**\n * Emit an event with the given arguments and payload function.\n *\n * @ignore\n * @param {BaseContract} contract - The contract instance.\n * @param {ContractEventName} event - The event name.\n * @param {any[]} args - The arguments to pass to the listeners.\n * @param {null | PayloadFunc} payloadFunc - The payload function.\n * @returns {Promise} Resolves to true if any listeners were called.\n */\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 // eslint-disable-next-line no-empty\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}\n/**\n * Emit an event with the given arguments and payload function.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {ContractEventName} event - The event name.\n * @param {any[]} args - The arguments to pass to the listeners.\n * @param {null | PayloadFunc} payloadFunc - The payload function.\n * @returns {Promise} Resolves to true if any listeners were called.\n */\nasync function emit(contract, event, args, payloadFunc) {\n try {\n await lastEmit;\n // eslint-disable-next-line no-empty\n }\n catch (error) { }\n const resultPromise = _emit(contract, event, args, payloadFunc);\n lastEmit = resultPromise;\n return await resultPromise;\n}\nconst passProperties = ['then'];\n/**\n * Creates a new contract connected to target with the abi and optionally connected to a runner to perform operations on\n * behalf of.\n *\n * @category Contract\n */\nexport class BaseContract {\n /**\n * The target to connect to.\n *\n * This can be an address or any [Addressable](../interfaces/Addressable), such as another contract. To get the\n * resolved address, use the `getAddress` method.\n */\n target;\n /**\n * The contract Interface.\n */\n interface;\n /**\n * The connected runner. This is generally a [**Provider**](../interfaces/Provider) or a\n * [**Signer**](../interfaces/Signer), which dictates what operations are supported.\n *\n * For example, a **Contract** connected to a [**Provider**](../interfaces/Provider) may only execute read-only\n * 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 optionally connected to a `runner` to perform\n * operations on behalf of.\n *\n * @ignore\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 const subs = new Map();\n // Resolve the target as the address\n if (typeof target === 'string') {\n addr = target;\n addrPromise = Promise.resolve(target);\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 a different `runner`.\n *\n * @param {null | ContractRunner} runner - The runner to use.\n * @returns {BaseContract} The new contract instance.\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 a different `target`.\n *\n * @param {string | Addressable} target - The target to connect to.\n * @returns {BaseContract} The new contract instance.\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 * @returns {Promise} The resolved address.\n */\n async getAddress() {\n return await getInternal(this).addrPromise;\n }\n /**\n * Return the deployed bytecode or null if no bytecode is found.\n *\n * @returns {Promise} The deployed bytecode or null.\n * @throws {Error} If the runner does not support .provider.\n */\n async getDeployedCode() {\n const provider = getProvider(this.runner);\n assert(provider, 'runner does not support .provider', 'UNSUPPORTED_OPERATION', {\n operation: 'getDeployedCode',\n });\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 resolve immediately if already deployed.\n *\n * @returns {Promise} The contract instance.\n * @throws {Error} If the contract runner does not support .provider.\n */\n async waitForDeployment() {\n // We have the deployment transaction; just use that (throws if deployment 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', {\n operation: 'waitForDeployment',\n });\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 [**ContractFactor**](../classes/ContractFactory).\n *\n * @returns The transaction used to deploy this contract or `null`.\n */\n deploymentTransaction() {\n return getInternal(this).deployTx;\n }\n /**\n * Return the function for a given name. This is useful when a contract method name conflicts with a JavaScript name\n * such as `prototype` or when using a Contract programatically.\n *\n * @param {string | FunctionFragment} key - The name of the function to return.\n * @returns The function for the given name.\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 event name conflicts with a JavaScript name\n * such as `prototype` or when using a Contract programatically.\n *\n * @param {string | EventFragment} key - The name of the event to return.\n * @returns The event for the given name.\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 // TODO: implement\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async queryTransaction(hash) {\n throw new Error('@TODO');\n }\n /**\n * Provide historic access to event data for `event` in the range `fromBlock` (default: `0`) to `toBlock` (default:\n * `\"latest\"`) inclusive.\n *\n * @param {Zone} zone - The zone to query.\n * @param {ContractEventName} event - The event to query.\n * @param {BlockTag} fromBlock - The block to start querying from.\n * @param {BlockTag} toBlock - The block to stop querying at.\n * @returns An array of event logs.\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 zone = getZoneForAddress(address);\n const filter = { address, topics, fromBlock, toBlock, nodeLocation: getNodeLocationFromZone(zone) };\n const provider = getProvider(this.runner);\n assert(provider, 'contract runner does not have a provider', 'UNSUPPORTED_OPERATION', {\n operation: 'queryFilter',\n });\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 // eslint-disable-next-line no-empty\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 * @param {ContractEventName} event - The event to listen for.\n * @param {Listener} listener - The listener to call when the event is emitted.\n * @returns This contract instance.\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 after it is fired once.\n *\n * @param {ContractEventName} event - The event to listen for.\n * @param {Listener} listener - The listener to call when the event is emitted.\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 * @param {ContractEventName} event - The event to emit.\n * @param {any[]} args - The arguments to pass to the listeners.\n * @returns `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 of listeners if unspecified.\n *\n * @param {ContractEventName} event - The event to count listeners for.\n * @returns {number} The number of listeners.\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 if unspecified.\n *\n * @param {ContractEventName} event - The event to get listeners for.\n * @returns {Listener[]} The listeners.\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 all listeners if unspecified.\n *\n * @param {ContractEventName} event - The event to remove the listener from.\n * @param {Listener} listener - The listener to remove.\n * @returns This contract instance.\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 unspecified.\n *\n * @param {ContractEventName} event - The event to remove the listeners from.\n * @returns This contract instance.\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 {@link BaseContract.on | **on**}.\n *\n * @param {ContractEventName} event - The event to listen for.\n * @param {Listener} listener - The listener to call when the event is emitted.\n */\n async addListener(event, listener) {\n return await this.on(event, listener);\n }\n /**\n * Alias for {@link BaseContract.off | **off**}.\n *\n * @param {ContractEventName} event - The event to remove the listener from.\n * @param {Listener} listener - The listener to remove.\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 * @param {Interface | InterfaceAbi} abi - The ABI to create the class from.\n * @returns The 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 * Create a new BaseContract with a specified Interface.\n *\n * @param {string} target - The target to connect to.\n * @param {Interface | InterfaceAbi} abi - The ABI to use.\n * @param {null | ContractRunner} runner - The runner to use.\n * @returns The new BaseContract.\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 {@link BaseContract | **BaseContract**} with no type guards on its methods or events.\n *\n * @category Contract\n */\nexport class Contract extends _ContractBase() {\n}\n//# sourceMappingURL=contract.js.map","/**\n * Generally the [Wallet](../classes/Wallet) and [JsonRpcSigner](../classes/JsonRpcSigner) and their sub-classes are\n * sufficent for most developers, but this is provided to fascilitate more complex Signers.\n */\nimport { resolveAddress, validateAddress } from '../address/index.js';\nimport { defineProperties, getBigInt, resolveProperties, assert, assertArgument } from '../utils/index.js';\nimport { addressFromTransactionRequest, copyRequest } from '../providers/provider.js';\nimport { getTxType } from '../utils/index.js';\nimport { QuaiTransaction } from '../transaction/index.js';\nimport { toZone } from '../constants/index.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 const pop = copyRequest(tx);\n if (pop.to != null) {\n pop.to = resolveAddress(pop.to);\n validateAddress(pop.to);\n }\n if (pop.from != null) {\n const from = pop.from;\n pop.from = await Promise.all([signer.getAddress(), resolveAddress(from)]).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 = await signer.getAddress();\n }\n validateAddress(pop.from);\n return await resolveProperties(pop);\n}\n/**\n * An **AbstractSigner** includes most of teh functionality required to get a {@link Signer | **Signer**} working as\n * expected, but requires a few Signer-specific methods be overridden.\n *\n * @category Signers\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 /**\n * @ignore\n */\n _getAddress(address) {\n return resolveAddress(address);\n }\n async zoneFromAddress(_address) {\n const address = this._getAddress(_address);\n return toZone((await address).slice(0, 4));\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 populateQuaiTransaction(tx) {\n const provider = checkProvider(this, 'populateTransaction');\n const zone = await this.zoneFromAddress(tx.from);\n const pop = (await populate(this, tx));\n if (pop.type == null) {\n pop.type = await getTxType(pop.from ?? null, pop.to ?? null);\n }\n if (pop.nonce == null) {\n pop.nonce = await this.getNonce('pending');\n }\n if (pop.type == null) {\n pop.type = getTxType(pop.from ?? null, pop.to ?? null);\n }\n if (pop.gasLimit == null) {\n if (pop.type == 0)\n pop.gasLimit = await this.estimateGas(pop);\n else {\n //Special cases for type 2 tx to bypass address out of scope in the node\n const temp = pop.to;\n pop.to = '0x0000000000000000000000000000000000000000';\n pop.gasLimit = getBigInt(2 * Number(await this.estimateGas(pop)));\n pop.to = temp;\n }\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', zone);\n }\n else {\n pop.chainId = network.chainId;\n }\n if (pop.maxFeePerGas == null || pop.maxPriorityFeePerGas == null) {\n const feeData = await provider.getFeeData(zone);\n if (pop.maxFeePerGas == null) {\n pop.maxFeePerGas = feeData.maxFeePerGas;\n }\n if (pop.maxPriorityFeePerGas == null) {\n pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas || 10n;\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 sendTransaction(tx) {\n const provider = checkProvider(this, 'sendTransaction');\n const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx));\n const pop = await this.populateQuaiTransaction(tx);\n const txObj = QuaiTransaction.from(pop);\n const sender = await this.getAddress();\n const signedTx = await this.signTransaction(txObj);\n return await provider.broadcastTransaction(zone, signedTx, sender);\n }\n}\n/**\n * A **VoidSigner** is a class deisgned to allow an address to be used in any API which accepts a Signer, but for which\n * there are no credentials available to perform any actual signing.\n *\n * This for example allow impersonating an account for the purpose of static calls or estimating gas, but does not allow\n * sending transactions.\n *\n * @category Signers\n */\nexport class VoidSigner extends AbstractSigner {\n /**\n * The signer address.\n */\n address;\n /**\n * Creates a new **VoidSigner** with `address` attached to `provider`.\n */\n constructor(address, provider) {\n super(provider);\n defineProperties(this, { address });\n }\n async getAddress() {\n return this.address;\n }\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 // TODO: `domain`, `types` and `value` are not used, remove?\n // TODO: this function only throws, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async signTransaction(tx) {\n this.#throwUnsupported('transactions', 'signTransaction');\n }\n // TODO: `domain`, `types` and `value` are not used, remove?\n // TODO: this function only throws, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async signMessage(message) {\n this.#throwUnsupported('messages', 'signMessage');\n }\n // TODO: `domain`, `types` and `value` are not used, remove?\n // TODO: this function only throws, remove?\n async signTypedData(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n domain, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n types, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n value) {\n this.#throwUnsupported('typed-data', 'signTypedData');\n }\n}\n//# sourceMappingURL=abstract-signer.js.map","import { getAddress, computeAddress, resolveAddress, validateAddress } from '../address/index.js';\nimport { hashMessage, TypedDataEncoder } from '../hash/index.js';\nimport { AbstractSigner } from '../signers/index.js';\nimport { resolveProperties, assertArgument } from '../utils/index.js';\nimport { QuaiTransaction } from '../transaction/quai-transaction.js';\nimport { keccak256 } from '../crypto/index.js';\n/**\n * The **BaseWallet** is a stream-lined implementation of a {@link AbstractSigner} that operates with a private\n * key.\n *\n * It is preferred to use the {@link Wallet} class, as it offers additional functionality and simplifies\n * loading a variety of JSON formats, Mnemonic Phrases, etc.\n *\n * This class may be of use for those attempting to implement a minimal Signer.\n *\n * @category Wallet\n */\nexport class BaseWallet extends AbstractSigner {\n /**\n * The wallet address.\n * @type {string}\n * @readonly\n */\n #address;\n /**\n * The signing key used for signing payloads.\n * @type {SigningKey}\n * @readonly\n */\n #signingKey;\n /**\n * Creates a new BaseWallet for `privateKey`, optionally connected to `provider`.\n *\n * If `provider` is not specified, only offline methods can be used.\n *\n * @param {SigningKey} privateKey - The private key for the wallet.\n * @param {null | Provider} [provider] - The provider to connect to.\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 this.#address = computeAddress(this.signingKey.publicKey);\n }\n // Store private values behind getters to reduce visibility\n /**\n * The address of this wallet.\n * @type {string}\n * @readonly\n */\n get address() {\n return this.#address;\n }\n /**\n * The {@link SigningKey | **SigningKey**} used for signing payloads.\n * @type {SigningKey}\n * @readonly\n */\n get signingKey() {\n return this.#signingKey;\n }\n /**\n * The private key for this wallet.\n * @type {string}\n * @readonly\n */\n get privateKey() {\n return this.signingKey.privateKey;\n }\n // TODO: `_zone` is not used, should it be removed?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n /**\n * Returns the address of this wallet.\n *\n * @param {string} [_zone] - The zone (optional).\n * @returns {Promise} The wallet address.\n */\n async getAddress(_zone) {\n return this.#address;\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {null | Provider} provider - The provider to connect to.\n * @returns {BaseWallet} The connected wallet.\n */\n connect(provider) {\n return new BaseWallet(this.#signingKey, provider);\n }\n /**\n * Signs a transaction.\n *\n * @param {QuaiTransactionRequest} tx - The transaction request.\n * @returns {Promise} The signed transaction.\n */\n async signTransaction(tx) {\n // Replace any Addressable with an address\n const { to, from } = await resolveProperties({\n to: tx.to ? resolveAddress(tx.to) : undefined,\n from: tx.from ? resolveAddress(tx.from) : undefined,\n });\n if (to !== undefined) {\n validateAddress(to);\n tx.to = to;\n }\n if (from !== undefined) {\n assertArgument(getAddress(from) === this.#address, 'transaction from address mismatch', 'tx.from', from);\n }\n else {\n // No `from` specified, use the wallet's address\n tx.from = this.#address;\n }\n const btx = QuaiTransaction.from(tx);\n const digest = keccak256(btx.unsignedSerialized);\n btx.signature = this.signingKey.sign(digest);\n return btx.serialized;\n }\n /**\n * Signs a message.\n *\n * @param {string | Uint8Array} message - The message to sign.\n * @returns {Promise} The signed message.\n * @async\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 * @param {string | Uint8Array} message - The message to sign.\n * @returns {string} The serialized signature.\n */\n signMessageSync(message) {\n return this.signingKey.sign(hashMessage(message)).serialized;\n }\n /**\n * Signs typed data.\n *\n * @param {TypedDataDomain} domain - The domain of the typed data.\n * @param {Record>} types - The types of the typed data.\n * @param {Record} value - The value of the typed data.\n * @returns {Promise} The signed typed data.\n * @async\n */\n async signTypedData(domain, types, value) {\n return this.signingKey.sign(TypedDataEncoder.hash(domain, types, 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 words used to encode and devoce\n * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) encoded data by mapping words to 11-bit values and vice versa.\n *\n * @category Wordlists\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, passing in the locale string of the language.\n *\n * Generally there is no need to create instances of a Wordlist, since each language-specific Wordlist creates an\n * instance and 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 method for spliting `phrase` into individual words.\n *\n * By default, `phrase` is split using any sequences of white-space as defined by regular expressions (i.e.\n * `/\\s+/`).\n *\n * @param {string} phrase - The phrase to split.\n *\n * @returns {string[]} The split words in the phrase.\n */\n split(phrase) {\n return phrase.toLowerCase().split(/\\s+/g);\n }\n /**\n * Sub-classes may override this to provider a language-specific method for joining `words` into a phrase.\n *\n * By default, `words` are joined by a single space.\n *\n * @param {string[]} words - The words to join.\n *\n * @returns {string} The joined phrase.\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 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 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 to create the necessary data.\n *\n * @category Wordlists\n */\nexport class WordlistOwl extends Wordlist {\n #data;\n #checksum;\n /**\n * Creates a new Wordlist for `locale` using the OWL `data` 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 * @ignore\n */\n get _data() {\n return this.#data;\n }\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_{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 M3AgramAlAm#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/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-PM&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryFN Noc|PutQuirySSue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+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)IdeIghtImOgAyEakEelEmEpE*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~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO\";\nconst checksum = '0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60';\nlet wordlist = null;\n/**\n * The [English wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt) for [mnemonic\n * phrases](https://en.bitcoin.it/wiki/BIP_0039).\n *\n * @category 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 {@link langEn} should suffice.\n *\n * @ignore\n */\n constructor() {\n super('en', words, checksum);\n }\n /**\n * Returns a singleton instance of a `LangEn`, creating it 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, } from '../utils/index.js';\nimport { toUtf8Bytes } from '../encoding/index.js';\nimport { LangEn } from '../wordlists/lang-en.js';\n/**\n * Returns a byte with the MSB bits set.\n *\n * @param {number} bits - The number of bits to set.\n * @returns {number} The byte with the MSB bits set.\n */\nfunction getUpperMask(bits) {\n return (((1 << bits) - 1) << (8 - bits)) & 0xff;\n}\n/**\n * Returns a byte with the LSB bits set.\n *\n * @param {number} bits - The number of bits to set.\n * @returns {number} The byte with the LSB bits set.\n */\nfunction getLowerMask(bits) {\n return ((1 << bits) - 1) & 0xff;\n}\n/**\n * Converts a mnemonic phrase to entropy.\n *\n * @param {string} mnemonic - The mnemonic phrase.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {string} The entropy.\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 const 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}\n/**\n * Converts entropy to a mnemonic phrase.\n *\n * @param {Uint8Array} entropy - The entropy.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {string} The mnemonic phrase.\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 [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) seeds and\n * convert between phrases and entropy.\n *\n * @category Wallet\n */\nexport class Mnemonic {\n /**\n * The mnemonic phrase of 12, 15, 18, 21 or 24 words.\n *\n * Use the {@link wordlist | **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 is the empty string (i.e. `\"\"`) as per the\n * 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 * @param {any} guard - The guard object.\n * @param {string} entropy - The entropy.\n * @param {string} phrase - The mnemonic phrase.\n * @param {string} [password] - The password for the mnemonic.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\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 * @returns {string} The seed.\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 wordlist is the {@link LangEn | **English wordlist**}.\n *\n * @param {string} phrase - The mnemonic phrase.\n * @param {string} [password] - The password for the mnemonic.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {Mnemonic} The new Mnemonic object.\n */\n static fromPhrase(phrase, password, wordlist) {\n // Normalize the case and space; throws if invalid\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n if (password == null) {\n password = '';\n }\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 wordlist is the [{@link LangEn | **English wordlist**}.\n *\n * @param {BytesLike} _entropy - The entropy for the mnemonic.\n * @param {string} [password] - The password for the mnemonic.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {Mnemonic} The new Mnemonic object.\n */\n static fromEntropy(_entropy, password, wordlist) {\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n if (password == null) {\n password = '';\n }\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 * @param {BytesLike} _entropy - The entropy for the mnemonic.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {string} The mnemonic phrase.\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 * @param {string} phrase - The mnemonic phrase.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {string} The entropy.\n */\n static phraseToEntropy(phrase, wordlist) {\n return mnemonicToEntropy(phrase, wordlist);\n }\n /**\n * Returns true if `phrase` is a valid [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) phrase.\n *\n * This checks all the provided words belong to the `wordlist`, that the length is valid and the checksum is\n * correct.\n *\n * @param {string} phrase - The mnemonic phrase.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {boolean} True if the phrase is valid.\n * @throws {Error} If the phrase is invalid.\n */\n static isValidMnemonic(phrase, wordlist) {\n try {\n mnemonicToEntropy(phrase, wordlist);\n return true;\n // eslint-disable-next-line no-empty\n }\n catch (error) { }\n return false;\n }\n}\n//# sourceMappingURL=mnemonic.js.map","/*! MIT License. Copyright 2015-2022 Richard Moore . See LICENSE.txt. */\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _AES_key, _AES_Kd, _AES_Ke;\n// Number of rounds by keysize\nconst numberOfRounds = { 16: 10, 24: 12, 32: 14 };\n// Round constant words\nconst rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91];\n// S-box and Inverse S-box (S is for Substitution)\nconst S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16];\nconst Si = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d];\n// Transformations for encryption\nconst T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a];\nconst T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616];\nconst T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16];\nconst T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c];\n// Transformations for decryption\nconst T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742];\nconst T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857];\nconst T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8];\nconst T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0];\n// Transformations for decryption key expansion\nconst U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3];\nconst U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697];\nconst U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46];\nconst U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d];\nfunction convertToInt32(bytes) {\n const result = [];\n for (let i = 0; i < bytes.length; i += 4) {\n result.push((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]);\n }\n return result;\n}\nexport class AES {\n get key() { return __classPrivateFieldGet(this, _AES_key, \"f\").slice(); }\n constructor(key) {\n _AES_key.set(this, void 0);\n _AES_Kd.set(this, void 0);\n _AES_Ke.set(this, void 0);\n if (!(this instanceof AES)) {\n throw Error('AES must be instanitated with `new`');\n }\n __classPrivateFieldSet(this, _AES_key, new Uint8Array(key), \"f\");\n const rounds = numberOfRounds[this.key.length];\n if (rounds == null) {\n throw new TypeError('invalid key size (must be 16, 24 or 32 bytes)');\n }\n // encryption round keys\n __classPrivateFieldSet(this, _AES_Ke, [], \"f\");\n // decryption round keys\n __classPrivateFieldSet(this, _AES_Kd, [], \"f\");\n for (let i = 0; i <= rounds; i++) {\n __classPrivateFieldGet(this, _AES_Ke, \"f\").push([0, 0, 0, 0]);\n __classPrivateFieldGet(this, _AES_Kd, \"f\").push([0, 0, 0, 0]);\n }\n const roundKeyCount = (rounds + 1) * 4;\n const KC = this.key.length / 4;\n // convert the key into ints\n const tk = convertToInt32(this.key);\n // copy values into round key arrays\n let index;\n for (let i = 0; i < KC; i++) {\n index = i >> 2;\n __classPrivateFieldGet(this, _AES_Ke, \"f\")[index][i % 4] = tk[i];\n __classPrivateFieldGet(this, _AES_Kd, \"f\")[rounds - index][i % 4] = tk[i];\n }\n // key expansion (fips-197 section 5.2)\n let rconpointer = 0;\n let t = KC, tt;\n while (t < roundKeyCount) {\n tt = tk[KC - 1];\n tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^\n (S[(tt >> 8) & 0xFF] << 16) ^\n (S[tt & 0xFF] << 8) ^\n S[(tt >> 24) & 0xFF] ^\n (rcon[rconpointer] << 24));\n rconpointer += 1;\n // key expansion (for non-256 bit)\n if (KC != 8) {\n for (let i = 1; i < KC; i++) {\n tk[i] ^= tk[i - 1];\n }\n // key expansion for 256-bit keys is \"slightly different\" (fips-197)\n }\n else {\n for (let i = 1; i < (KC / 2); i++) {\n tk[i] ^= tk[i - 1];\n }\n tt = tk[(KC / 2) - 1];\n tk[KC / 2] ^= (S[tt & 0xFF] ^\n (S[(tt >> 8) & 0xFF] << 8) ^\n (S[(tt >> 16) & 0xFF] << 16) ^\n (S[(tt >> 24) & 0xFF] << 24));\n for (let i = (KC / 2) + 1; i < KC; i++) {\n tk[i] ^= tk[i - 1];\n }\n }\n // copy values into round key arrays\n let i = 0, r, c;\n while (i < KC && t < roundKeyCount) {\n r = t >> 2;\n c = t % 4;\n __classPrivateFieldGet(this, _AES_Ke, \"f\")[r][c] = tk[i];\n __classPrivateFieldGet(this, _AES_Kd, \"f\")[rounds - r][c] = tk[i++];\n t++;\n }\n }\n // inverse-cipher-ify the decryption round key (fips-197 section 5.3)\n for (let r = 1; r < rounds; r++) {\n for (let c = 0; c < 4; c++) {\n tt = __classPrivateFieldGet(this, _AES_Kd, \"f\")[r][c];\n __classPrivateFieldGet(this, _AES_Kd, \"f\")[r][c] = (U1[(tt >> 24) & 0xFF] ^\n U2[(tt >> 16) & 0xFF] ^\n U3[(tt >> 8) & 0xFF] ^\n U4[tt & 0xFF]);\n }\n }\n }\n encrypt(plaintext) {\n if (plaintext.length != 16) {\n throw new TypeError('invalid plaintext size (must be 16 bytes)');\n }\n const rounds = __classPrivateFieldGet(this, _AES_Ke, \"f\").length - 1;\n const a = [0, 0, 0, 0];\n // convert plaintext to (ints ^ key)\n let t = convertToInt32(plaintext);\n for (let i = 0; i < 4; i++) {\n t[i] ^= __classPrivateFieldGet(this, _AES_Ke, \"f\")[0][i];\n }\n // apply round transforms\n for (let r = 1; r < rounds; r++) {\n for (let i = 0; i < 4; i++) {\n a[i] = (T1[(t[i] >> 24) & 0xff] ^\n T2[(t[(i + 1) % 4] >> 16) & 0xff] ^\n T3[(t[(i + 2) % 4] >> 8) & 0xff] ^\n T4[t[(i + 3) % 4] & 0xff] ^\n __classPrivateFieldGet(this, _AES_Ke, \"f\")[r][i]);\n }\n t = a.slice();\n }\n // the last round is special\n const result = new Uint8Array(16);\n let tt = 0;\n for (let i = 0; i < 4; i++) {\n tt = __classPrivateFieldGet(this, _AES_Ke, \"f\")[rounds][i];\n result[4 * i] = (S[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;\n result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;\n result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;\n result[4 * i + 3] = (S[t[(i + 3) % 4] & 0xff] ^ tt) & 0xff;\n }\n return result;\n }\n decrypt(ciphertext) {\n if (ciphertext.length != 16) {\n throw new TypeError('invalid ciphertext size (must be 16 bytes)');\n }\n const rounds = __classPrivateFieldGet(this, _AES_Kd, \"f\").length - 1;\n const a = [0, 0, 0, 0];\n // convert plaintext to (ints ^ key)\n let t = convertToInt32(ciphertext);\n for (let i = 0; i < 4; i++) {\n t[i] ^= __classPrivateFieldGet(this, _AES_Kd, \"f\")[0][i];\n }\n // apply round transforms\n for (let r = 1; r < rounds; r++) {\n for (let i = 0; i < 4; i++) {\n a[i] = (T5[(t[i] >> 24) & 0xff] ^\n T6[(t[(i + 3) % 4] >> 16) & 0xff] ^\n T7[(t[(i + 2) % 4] >> 8) & 0xff] ^\n T8[t[(i + 1) % 4] & 0xff] ^\n __classPrivateFieldGet(this, _AES_Kd, \"f\")[r][i]);\n }\n t = a.slice();\n }\n // the last round is special\n const result = new Uint8Array(16);\n let tt = 0;\n for (let i = 0; i < 4; i++) {\n tt = __classPrivateFieldGet(this, _AES_Kd, \"f\")[rounds][i];\n result[4 * i] = (Si[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;\n result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;\n result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;\n result[4 * i + 3] = (Si[t[(i + 1) % 4] & 0xff] ^ tt) & 0xff;\n }\n return result;\n }\n}\n_AES_key = new WeakMap(), _AES_Kd = new WeakMap(), _AES_Ke = new WeakMap();\n//# sourceMappingURL=aes.js.map","import { AES } from \"./aes.js\";\nexport class ModeOfOperation {\n constructor(name, key, cls) {\n if (cls && !(this instanceof cls)) {\n throw new Error(`${name} must be instantiated with \"new\"`);\n }\n Object.defineProperties(this, {\n aes: { enumerable: true, value: new AES(key) },\n name: { enumerable: true, value: name }\n });\n }\n}\n//# sourceMappingURL=mode.js.map","// Counter Mode\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _CTR_remaining, _CTR_remainingIndex, _CTR_counter;\nimport { ModeOfOperation } from \"./mode.js\";\nexport class CTR extends ModeOfOperation {\n constructor(key, initialValue) {\n super(\"CTR\", key, CTR);\n // Remaining bytes for the one-time pad\n _CTR_remaining.set(this, void 0);\n _CTR_remainingIndex.set(this, void 0);\n // The current counter\n _CTR_counter.set(this, void 0);\n __classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), \"f\");\n __classPrivateFieldGet(this, _CTR_counter, \"f\").fill(0);\n __classPrivateFieldSet(this, _CTR_remaining, __classPrivateFieldGet(this, _CTR_counter, \"f\"), \"f\"); // This will be discarded immediately\n __classPrivateFieldSet(this, _CTR_remainingIndex, 16, \"f\");\n if (initialValue == null) {\n initialValue = 1;\n }\n if (typeof (initialValue) === \"number\") {\n this.setCounterValue(initialValue);\n }\n else {\n this.setCounterBytes(initialValue);\n }\n }\n get counter() { return new Uint8Array(__classPrivateFieldGet(this, _CTR_counter, \"f\")); }\n setCounterValue(value) {\n if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {\n throw new TypeError(\"invalid counter initial integer value\");\n }\n for (let index = 15; index >= 0; --index) {\n __classPrivateFieldGet(this, _CTR_counter, \"f\")[index] = value % 256;\n value = Math.floor(value / 256);\n }\n }\n setCounterBytes(value) {\n if (value.length !== 16) {\n throw new TypeError(\"invalid counter initial Uint8Array value length\");\n }\n __classPrivateFieldGet(this, _CTR_counter, \"f\").set(value);\n }\n increment() {\n for (let i = 15; i >= 0; i--) {\n if (__classPrivateFieldGet(this, _CTR_counter, \"f\")[i] === 255) {\n __classPrivateFieldGet(this, _CTR_counter, \"f\")[i] = 0;\n }\n else {\n __classPrivateFieldGet(this, _CTR_counter, \"f\")[i]++;\n break;\n }\n }\n }\n encrypt(plaintext) {\n var _a, _b;\n const crypttext = new Uint8Array(plaintext);\n for (let i = 0; i < crypttext.length; i++) {\n if (__classPrivateFieldGet(this, _CTR_remainingIndex, \"f\") === 16) {\n __classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet(this, _CTR_counter, \"f\")), \"f\");\n __classPrivateFieldSet(this, _CTR_remainingIndex, 0, \"f\");\n this.increment();\n }\n crypttext[i] ^= __classPrivateFieldGet(this, _CTR_remaining, \"f\")[__classPrivateFieldSet(this, _CTR_remainingIndex, (_b = __classPrivateFieldGet(this, _CTR_remainingIndex, \"f\"), _a = _b++, _b), \"f\"), _a];\n }\n return crypttext;\n }\n decrypt(ciphertext) {\n return this.encrypt(ciphertext);\n }\n}\n_CTR_remaining = new WeakMap(), _CTR_remainingIndex = new WeakMap(), _CTR_counter = new WeakMap();\n//# sourceMappingURL=mode-ctr.js.map","/**\n * @module wallet/utils\n */\nimport { getBytesCopy, assertArgument, concat, dataSlice, getBytes, assert, } from '../utils/index.js';\nimport { computeHmac, sha256 } from '../crypto/index.js';\nimport { encodeBase58, toUtf8Bytes } from '../encoding/index.js';\n/**\n * Converts a hex string to a Uint8Array. If the string does not start with '0x', it adds it.\n * @param {string} hexString - The hex string to convert.\n * @returns {Uint8Array} The resulting byte array.\n */\nexport function looseArrayify(hexString) {\n if (typeof hexString === 'string' && !hexString.startsWith('0x')) {\n hexString = '0x' + hexString;\n }\n return getBytesCopy(hexString);\n}\n/**\n * Converts a password to a Uint8Array. If the password is a string, it converts it to UTF-8 bytes.\n * @param {string|Uint8Array} password - The password to convert.\n * @returns {Uint8Array} The resulting byte array.\n */\nexport function getPassword(password) {\n if (typeof password === 'string') {\n return toUtf8Bytes(password, 'NFKC');\n }\n return getBytesCopy(password);\n}\n/**\n * Traverses an object based on a path and returns the value at that path.\n * @param {any} object - The object to traverse.\n * @param {string} _path - The path to traverse.\n * @returns {T} The value at the specified path.\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// HDNODEWallet and UTXO Wallet util methods\n/** \"Bitcoin seed\" */\nexport const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]);\n/** Hardened bit constant */\nexport const HardenedBit = 0x80000000;\n/** Constant N used in cryptographic operations */\nexport const N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\n/** Hexadecimal characters */\nexport const Nibbles = '0123456789abcdef';\n/**\n * Pads a value with leading zeros to a specified length.\n * @param {string|number} value - The value to pad.\n * @param {number} length - The desired length.\n * @returns {string} The padded value.\n */\nexport function zpad(value, length) {\n // Determine if the value is hexadecimal\n const isHex = typeof value === 'string' && value.startsWith('0x');\n // Handle hexadecimal values\n if (isHex) {\n let hexValue = value.substring(2); // Remove the \"0x\" prefix\n while (hexValue.length < length * 2) {\n // Hexadecimal characters count double\n hexValue = '0' + hexValue;\n }\n return '0x' + hexValue;\n }\n // Handle numbers or non-hexadecimal strings\n let result = String(value);\n while (result.length < length) {\n result = '0' + result;\n }\n return result;\n}\n/**\n * Encodes a value using Base58Check encoding.\n * @param {BytesLike} _value - The value to encode.\n * @returns {string} The Base58Check encoded string.\n */\nexport function 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}\n/**\n * Serializes an index, chain code, public key, and private key into a pair of derived keys.\n * @param {number} index - The index to serialize.\n * @param {string} chainCode - The chain code.\n * @param {string} publicKey - The public key.\n * @param {null|string} privateKey - The private key.\n * @returns {{IL: Uint8Array, IR: Uint8Array}} The derived keys.\n */\nexport function 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}\n//# sourceMappingURL=utils.js.map","/**\n * The JSON Wallet formats allow a simple way to store the private keys needed in Ethereum along with related\n * information and allows for extensible forms of encryption.\n *\n * These utilities facilitate decrypting and encrypting the most common JSON Wallet formats.\n */\nimport { CTR } from 'aes-js';\nimport { getAddress, computeAddress } from '../address/index.js';\nimport { keccak256, pbkdf2, randomBytes, scrypt, scryptSync } from '../crypto/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'/994'/0'/0/0\";\n/**\n * Returns true if `json` is a valid JSON Keystore Wallet.\n *\n * @category Wallet\n * @param {string} json - The JSON data to check.\n *\n * @returns {boolean} True if the JSON data is a valid 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 // eslint-disable-next-line no-empty\n }\n catch (error) { }\n return false;\n}\n/**\n * Decrypts the given ciphertext using the provided key and data.\n *\n * @param {any} data - The data containing encryption parameters.\n * @param {Uint8Array} key - The key to use for decryption.\n * @param {Uint8Array} ciphertext - The ciphertext to decrypt.\n *\n * @returns {string} The decrypted data as a hex string.\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}\n/**\n * Retrieves the account details from the given data and key.\n *\n * @param {any} data - The data containing account information.\n * @param {string} _key - The key to use for decryption.\n *\n * @returns {KeystoreAccount} The decrypted account details.\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-quais metadata must contain an encrypted mnemonic phrase\n const version = spelunk(data, 'x-quais.version:string');\n if (version === '0.1') {\n const mnemonicKey = key.slice(32, 64);\n const mnemonicCiphertext = spelunk(data, 'x-quais.mnemonicCiphertext:data!');\n const mnemonicIv = spelunk(data, 'x-quais.mnemonicCounter:data!');\n const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv);\n account.mnemonic = {\n path: spelunk(data, 'x-quais.path:string') || defaultPath,\n locale: spelunk(data, 'x-quais.locale:string') || 'en',\n entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))),\n };\n }\n return account;\n}\n/**\n * Retrieves the key derivation function parameters from the given data.\n *\n * @param {any} data - The data containing KDF parameters.\n *\n * @returns {KdfParams} The key derivation function parameters.\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` using `password`.\n *\n * It is preferred to use the {@link decryptKeystoreJson | **async version**} instead, which allows a\n * {@link ProgressCallback | **ProgressCallback} to keep the user informed as to the decryption status.\n *\n * This method will block the event loop (freezing all UI) until decryption is complete, which can take quite some time,\n * depending on the wallet paramters and platform.\n *\n * @category Wallet\n * @param {string} json - The JSON data to decrypt.\n * @param {string | Uint8Array} _password - The password to decrypt the JSON data.\n *\n * @returns {KeystoreAccount} The decrypted account.\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}\n/**\n * Pauses execution for the specified duration.\n *\n * @param {number} duration - The duration to stall in milliseconds.\n *\n * @returns {Promise} A promise that resolves after the specified duration.\n */\nfunction stall(duration) {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve();\n }, duration);\n });\n}\n/**\n * Resolves to the decrypted JSON Keystore Wallet `json` using the `password`.\n *\n * If provided, `progress` will be called periodically during the decrpytion to provide feedback, and if the function\n * returns `false` will halt decryption.\n *\n * The `progressCallback` will **always** receive `0` before decryption begins and `1` when complete.\n *\n * @category Wallet\n * @param {string} json - The JSON data to decrypt.\n * @param {string | Uint8Array} _password - The password to decrypt the JSON data.\n * @param {ProgressCallback} [progress] - The callback to receive progress updates.\n *\n * @returns {Promise} The decrypted account.\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}\n/**\n * Retrieves the key derivation function parameters for encryption.\n *\n * @param {EncryptOptions} options - The encryption options.\n *\n * @returns {ScryptParams} The key derivation function parameters.\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}\n/**\n * Encrypts the keystore with the given key, KDF parameters, account, and options.\n *\n * @ignore\n * @param {Uint8Array} key - The key to use for encryption.\n * @param {ScryptParams} kdf - The key derivation function parameters.\n * @param {KeystoreAccount} account - The account to encrypt.\n * @param {EncryptOptions} options - The encryption options.\n *\n * @returns {any} The encrypted keystore data.\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 quais 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 : `quais/${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 '-' +\n zpad(now.getUTCMonth() + 1, 2) +\n '-' +\n zpad(now.getUTCDate(), 2) +\n 'T' +\n zpad(now.getUTCHours(), 2) +\n '-' +\n zpad(now.getUTCMinutes(), 2) +\n '-' +\n zpad(now.getUTCSeconds(), 2) +\n '.0Z';\n const gethFilename = 'UTC--' + timestamp + '--' + data.address;\n data['x-quais'] = {\n client,\n gethFilename,\n path,\n 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 `password`.\n *\n * The `options` can be used to tune the password-based key derivation function parameters, explicitly set the random\n * values used. Any provided {@link ProgressCallback | **ProgressCallback**} is ignored.\n *\n * @category Wallet\n * @param {KeystoreAccount} account - The account to encrypt.\n * @param {string | Uint8Array} password - The password to encrypt the JSON data.\n * @param {EncryptOptions} [options] - The options to use when encrypting the JSON data.\n *\n * @returns {string} The encrypted JSON data.\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 with `password`.\n *\n * The `options` can be used to tune the password-based key derivation function parameters, explicitly set the random\n * values used and provide a {@link ProgressCallback | **ProgressCallback**} to receive periodic updates on the\n * completion status..\n *\n * @category Wallet\n * @param {KeystoreAccount} account - The account to encrypt.\n * @param {string | Uint8Array} password - The password to encrypt the JSON data.\n * @param {EncryptOptions} [options] - The options to use when encrypting the JSON data.\n *\n * @returns {Promise} The encrypted JSON data.\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","import { computeHmac, randomBytes, ripemd160, SigningKey, sha256 } from '../crypto/index.js';\nimport { VoidSigner } from '../signers/index.js';\nimport { computeAddress } from '../address/index.js';\nimport { decodeBase58, encodeBase58 } from '../encoding/index.js';\nimport { concat, dataSlice, defineProperties, 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// \"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 from an HD Node using the [[link-bip-32]]\n * standard.\n *\n * An HD Node forms a hierarchical structure with each HD Node having a private key and the ability to derive child HD\n * Nodes, defined by a path indicating the index of each child.\n */\nexport class HDNodeWallet extends BaseWallet {\n /**\n * The compressed public key.\n *\n * @type {string}\n */\n publicKey;\n /**\n * The fingerprint.\n *\n * A fingerprint allows a quick way to detect parent and child nodes, but developers should be prepared to deal with\n * collisions as it is only 4 bytes.\n *\n * @type {string}\n */\n fingerprint;\n /**\n * The parent fingerprint.\n *\n * @type {string}\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 which case this will be `null`.\n *\n * @type {null | Mnemonic}\n */\n mnemonic;\n /**\n * The chaincode, which is effectively a public key used to derive children.\n *\n * @type {string}\n */\n chainCode;\n /**\n * The derivation path of this wallet.\n *\n * Since extended keys do not provide full path details, this may be `null`, if instantiated from a source that does\n * not encode it.\n *\n * @type {null | string}\n */\n path;\n /**\n * The child index of this wallet. Values over `2 ** 31` indicate the node is hardened.\n *\n * @type {number}\n */\n index;\n /**\n * The depth of this wallet, which is the number of components in its path.\n *\n * @type {number}\n */\n depth;\n /**\n * @param {any} guard\n * @param {SigningKey} signingKey\n * @param {string} parentFingerprint\n * @param {string} chainCode\n * @param {null | string} path\n * @param {number} index\n * @param {number} depth\n * @param {null | Mnemonic} mnemonic\n * @param {null | Provider} provider\n * @ignore\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,\n fingerprint,\n chainCode,\n path,\n index,\n depth,\n });\n defineProperties(this, { mnemonic });\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {null | Provider} provider\n *\n * @returns {HDNodeWallet}\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 /**\n * @returns {KeystoreAccount}\n * @ignore\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 `password`.\n *\n * If `progressCallback` is specified, it will receive periodic updates as the encryption process progresses.\n *\n * @param {Uint8Array | string} password\n * @param {ProgressCallback} [progressCallback]\n *\n * @returns {Promise}\n */\n async encrypt(password, progressCallback) {\n return await encryptKeystoreJson(this.#account(), password, { progressCallback });\n }\n /**\n * Returns a [JSON Keystore Wallet](json-wallets) encrypted with `password`.\n *\n * It is preferred to use the [async version](encrypt) instead, which allows a `ProgressCallback` to keep the user\n * informed.\n *\n * This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial\n * duration.\n *\n * @param {Uint8Array | string} password\n *\n * @returns {string}\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 reconstruct this HD Node to derive its children.\n *\n * @returns {string}\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', {\n operation: 'extendedKey',\n });\n return encodeBase58Check(concat([\n '0x0488ADE4',\n zpad(this.depth, 1),\n this.parentFingerprint,\n zpad(this.index, 4),\n this.chainCode,\n concat(['0x00', this.privateKey]),\n ]));\n }\n /**\n * Returns true if this wallet has a path, providing a Type Guard that the path is non-null.\n *\n * @returns {boolean}\n */\n hasPath() {\n return this.path != null;\n }\n /**\n * Returns a neutered HD Node, which removes the private details of an HD Node.\n *\n * A neutered node has no private key, but can be used to derive child addresses and other public data about the HD\n * Node.\n *\n * @returns {HDNodeVoidWallet}\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 * @param {Numeric} _index\n *\n * @returns {HDNodeWallet}\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 * @param {string} path\n *\n * @returns {HDNodeWallet}\n */\n derivePath(path) {\n return derivePath(this, path);\n }\n /**\n\n * @param {BytesLike} _seed\n * @param {null | Mnemonic} mnemonic\n *\n * @returns {HDNodeWallet}\n * @ignore\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 `xpriv`, returning a neutered HD Node\n * ([[HDNodeVoidWallet]]) or full HD Node ([[HDNodeWallet]]) respectively.\n *\n * @param {string} extendedKey\n *\n * @returns {HDNodeWallet | HDNodeVoidWallet}\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 * @param {string} path\n * @param {string} [password]\n * @param {Wordlist} [wordlist]\n *\n * @returns {HDNodeWallet}\n */\n static createRandom(path, password, wordlist) {\n if (password == null) {\n password = '';\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 * @param {Mnemonic} mnemonic\n * @param {string} path\n *\n * @returns {HDNodeWallet}\n */\n static fromMnemonic(mnemonic, path) {\n return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);\n }\n /**\n * Creates an HD Node from a mnemonic `phrase`.\n *\n * @param {string} phrase\n * @param {string} path\n * @param {string} [password]\n * @param {Wordlist} [wordlist]\n *\n * @returns {HDNodeWallet}\n */\n static fromPhrase(phrase, path, password, wordlist) {\n if (password == null) {\n password = '';\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 * @param {BytesLike} seed\n *\n * @returns {HDNodeWallet}\n */\n static fromSeed(seed) {\n return HDNodeWallet.#fromSeed(seed, null);\n }\n}\n/**\n * A **HDNodeVoidWallet** cannot sign, but provides access to the children nodes of a [[link-bip-32]] HD wallet\n * addresses.\n *\n * They can be created by using an extended `xpub` key to [[HDNodeWallet_fromExtendedKey]] or by\n * [neutering](HDNodeWallet-neuter) a [[HDNodeWallet]].\n */\nexport class HDNodeVoidWallet extends VoidSigner {\n /**\n * The compressed public key.\n *\n * @type {string}\n */\n publicKey;\n /**\n * The fingerprint.\n *\n * A fingerprint allows a quick way to detect parent and child nodes, but developers should be prepared to deal with\n * collisions as it is only 4 bytes.\n *\n * @type {string}\n */\n fingerprint;\n /**\n * The parent node fingerprint.\n *\n * @type {string}\n */\n parentFingerprint;\n /**\n * The chaincode, which is effectively a public key used to derive children.\n *\n * @type {string}\n */\n chainCode;\n /**\n * The derivation path of this wallet.\n *\n * Since extended keys do not provide full path details, this may be `null`, if instantiated from a source that does\n * not encode it.\n *\n * @type {null | string}\n */\n path;\n /**\n * The child index of this wallet. Values over `2 ** 31` indicate the node is hardened.\n *\n * @type {number}\n */\n index;\n /**\n * The depth of this wallet, which is the number of components in its path.\n *\n * @type {number}\n */\n depth;\n /**\n * @param {any} guard\n * @param {string} address\n * @param {string} publicKey\n * @param {string} parentFingerprint\n * @param {string} chainCode\n * @param {null | string} path\n * @param {number} index\n * @param {number} depth\n * @param {null | Provider} provider\n * @ignore\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,\n fingerprint,\n parentFingerprint,\n chainCode,\n path,\n index,\n depth,\n });\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {null | Provider} provider\n *\n * @returns {HDNodeVoidWallet}\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 reconstruct this neutered key to derive its\n * children addresses.\n *\n * @returns {string}\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 that the path is non-null.\n *\n * @returns {boolean}\n */\n hasPath() {\n return this.path != null;\n }\n /**\n * Return the child for `index`.\n *\n * @param {Numeric} _index\n *\n * @returns {HDNodeVoidWallet}\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 * @param {string} path\n *\n * @returns {HDNodeVoidWallet}\n */\n derivePath(path) {\n return derivePath(this, path);\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 some software.\n *\n * @param {Numeric} _index\n *\n * @returns {string}\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, at `index`.\n *\n * This derivation path uses the `index` component rather than the `account` component to derive sequential accounts.\n *\n * This is the pattern used by wallets like MetaMask.\n *\n * @param {Numeric} _index\n *\n * @returns {string}\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=hdnodewallet.js.map","import { HDNodeWallet } from './hdnodewallet.js';\nimport { Mnemonic } from './mnemonic.js';\nimport { LangEn } from '../wordlists/lang-en.js';\nimport { randomBytes } from '../crypto/index.js';\nimport { getZoneForAddress, assertPrivate } from '../utils/index.js';\nimport { isQiAddress } from '../address/index.js';\nimport { Zone } from '../constants/index.js';\n/**\n * Constant to represent the maximum attempt to derive an address.\n */\nconst MAX_ADDRESS_DERIVATION_ATTEMPTS = 10000000;\nexport const _guard = {};\n/**\n * Abstract class representing a Hierarchical Deterministic (HD) wallet.\n */\nclass AbstractHDWallet {\n static _version = 1;\n static _coinType;\n // Map of addresses to address info\n _addresses = new Map();\n /**\n * Root node of the HD wallet.\n */\n _root;\n provider;\n /**\n * @param {HDNodeWallet} root - The root node of the HD wallet.\n * @param {Provider} [provider] - The provider for the HD wallet.\n */\n constructor(guard, root, provider) {\n assertPrivate(guard, _guard, 'AbstractHDWallet');\n this._root = root;\n this.provider = provider;\n }\n /**\n * Returns the parent path for a given coin type.\n *\n * @param {number} coinType - The coin type.\n * @returns {string} The parent path.\n */\n static parentPath(coinType) {\n return `m/44'/${coinType}'`;\n }\n /**\n * Returns the coin type of the wallet.\n *\n * @returns {AllowedCoinType} The coin type.\n */\n coinType() {\n return this.constructor._coinType;\n }\n /**\n * Returns the extended public key of the root node of the HD wallet.\n *\n * @returns {string} The extended public key.\n */\n get xPub() {\n return this._root.extendedKey;\n }\n /**\n * Derives the next valid address node for a specified account, starting index, and zone. The method ensures the\n * derived address belongs to the correct shard and ledger, as defined by the Quai blockchain specifications.\n *\n * @param {number} account - The account number from which to derive the address node.\n * @param {number} startingIndex - The index from which to start deriving addresses.\n * @param {Zone} zone - The zone (shard) for which the address should be valid.\n * @param {boolean} [isChange=false] - Whether to derive a change address. Default is `false`\n * @returns {HDNodeWallet} - The derived HD node wallet containing a valid address for the specified zone.\n * @throws {Error} If a valid address for the specified zone cannot be derived within the allowed attempts.\n */\n deriveNextAddressNode(account, startingIndex, zone, isChange = false) {\n const changeIndex = isChange ? 1 : 0;\n const changeNode = this._root.deriveChild(account).deriveChild(changeIndex);\n let addrIndex = startingIndex;\n let addressNode;\n const isValidAddressForZone = (address) => {\n const addressZone = getZoneForAddress(address);\n if (!addressZone) {\n return false;\n }\n const isCorrectShard = addressZone === zone;\n const isCorrectLedger = this.coinType() === 969 ? isQiAddress(address) : !isQiAddress(address);\n return isCorrectShard && isCorrectLedger;\n };\n for (let attempts = 0; attempts < MAX_ADDRESS_DERIVATION_ATTEMPTS; attempts++) {\n addressNode = changeNode.deriveChild(addrIndex++);\n if (isValidAddressForZone(addressNode.address)) {\n return addressNode;\n }\n }\n throw new Error(`Failed to derive a valid address for the zone ${zone} after ${MAX_ADDRESS_DERIVATION_ATTEMPTS} attempts.`);\n }\n /**\n * Adds an address to the wallet.\n *\n * @param {number} account - The account number.\n * @param {number} addressIndex - The address index.\n * @param {boolean} [isChange=false] - Whether the address is a change address. Default is `false`\n * @returns {NeuteredAddressInfo} The added address info.\n */\n addAddress(account, addressIndex, isChange = false) {\n return this._addAddress(this._addresses, account, addressIndex, isChange);\n }\n /**\n * Helper method to add an address to the wallet address map.\n *\n * @param {Map} addressMap - The address map.\n * @param {number} account - The account number.\n * @param {number} addressIndex - The address index.\n * @param {boolean} [isChange=false] - Whether the address is a change address. Default is `false`\n * @returns {NeuteredAddressInfo} The added address info.\n * @throws {Error} If the address for the index already exists.\n */\n _addAddress(addressMap, account, addressIndex, isChange = false) {\n // check if address already exists for the index\n this._addresses.forEach((addressInfo) => {\n if (addressInfo.index === addressIndex) {\n throw new Error(`Address for index ${addressIndex} already exists`);\n }\n });\n // derive the address node and validate the zone\n const changeIndex = isChange ? 1 : 0;\n const addressNode = this._root.deriveChild(account).deriveChild(changeIndex).deriveChild(addressIndex);\n const zone = getZoneForAddress(addressNode.address);\n if (!zone) {\n throw new Error(`Failed to derive a valid address zone for the index ${addressIndex}`);\n }\n return this.createAndStoreAddressInfo(addressNode, account, zone, isChange, addressMap);\n }\n /**\n * Promise that resolves to the next address for the specified account and zone.\n *\n * @param {number} account - The index of the account for which to retrieve the next address.\n * @param {Zone} zone - The zone in which to retrieve the next address.\n * @returns {Promise} The next neutered address information.\n */\n async getNextAddress(account, zone) {\n return Promise.resolve(this._getNextAddress(account, zone, false, this._addresses));\n }\n /**\n * Synchronously retrieves the next address for the specified account and zone.\n *\n * @param {number} account - The index of the account for which to retrieve the next address.\n * @param {Zone} zone - The zone in which to retrieve the next address.\n * @returns {NeuteredAddressInfo} The next neutered address information.\n */\n getNextAddressSync(account, zone) {\n return this._getNextAddress(account, zone, false, this._addresses);\n }\n /**\n * Derives and returns the next address information for the specified account and zone.\n *\n * @param {number} accountIndex - The index of the account for which the address is being generated.\n * @param {Zone} zone - The zone in which the address is to be used.\n * @param {boolean} isChange - A flag indicating whether the address is a change address.\n * @param {Map} addressMap - A map storing the neutered address information.\n * @returns {NeuteredAddressInfo} The derived neutered address information.\n * @throws {Error} If the zone is invalid.\n */\n _getNextAddress(accountIndex, zone, isChange, addressMap) {\n this.validateZone(zone);\n const lastIndex = this.getLastAddressIndex(addressMap, zone, accountIndex, isChange);\n const addressNode = this.deriveNextAddressNode(accountIndex, lastIndex + 1, zone, isChange);\n return this.createAndStoreAddressInfo(addressNode, accountIndex, zone, isChange, addressMap);\n }\n /**\n * Gets the address info for a given address.\n *\n * @param {string} address - The address.\n * @returns {NeuteredAddressInfo | null} The address info or null if not found.\n */\n getAddressInfo(address) {\n const addressInfo = this._addresses.get(address);\n if (!addressInfo) {\n return null;\n }\n return addressInfo;\n }\n /**\n * Returns the private key for a given address. This method should be used with caution as it exposes the private\n * key to the user.\n *\n * @param {string} address - The address associated with the desired private key.\n * @returns {string} The private key.\n */\n getPrivateKey(address) {\n const hdNode = this._getHDNodeForAddress(address);\n return hdNode.privateKey;\n }\n /**\n * Gets the addresses for a given account.\n *\n * @param {number} account - The account number.\n * @returns {NeuteredAddressInfo[]} The addresses for the account.\n */\n getAddressesForAccount(account) {\n const addresses = this._addresses.values();\n return Array.from(addresses).filter((addressInfo) => addressInfo.account === account);\n }\n /**\n * Gets the addresses for a given zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {NeuteredAddressInfo[]} The addresses for the zone.\n */\n getAddressesForZone(zone) {\n this.validateZone(zone);\n const addresses = this._addresses.values();\n return Array.from(addresses).filter((addressInfo) => addressInfo.zone === zone);\n }\n /**\n * Creates an instance of the HD wallet.\n *\n * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet.\n * @param {Mnemonic} mnemonic - The mnemonic.\n * @returns {T} The created instance.\n */\n static createInstance(mnemonic) {\n const coinType = this._coinType;\n const root = HDNodeWallet.fromMnemonic(mnemonic, this.parentPath(coinType));\n return new this(_guard, root);\n }\n /**\n * Creates an HD wallet from a mnemonic.\n *\n * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet.\n * @param {Mnemonic} mnemonic - The mnemonic.\n * @returns {T} The created instance.\n */\n static fromMnemonic(mnemonic) {\n return this.createInstance(mnemonic);\n }\n /**\n * Creates a random HD wallet.\n *\n * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet.\n * @param {string} [password] - The password.\n * @param {Wordlist} [wordlist] - The wordlist.\n * @returns {T} The created instance.\n */\n static createRandom(password, wordlist) {\n if (password == null) {\n password = '';\n }\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist);\n return this.createInstance(mnemonic);\n }\n /**\n * Creates an HD wallet from a phrase.\n *\n * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet.\n * @param {string} phrase - The phrase.\n * @param {string} [password] - The password.\n * @param {Wordlist} [wordlist] - The wordlist.\n * @returns {T} The created instance.\n */\n static fromPhrase(phrase, password, wordlist) {\n if (password == null) {\n password = '';\n }\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist);\n return this.createInstance(mnemonic);\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {Provider} provider - The provider.\n */\n connect(provider) {\n this.provider = provider;\n }\n /**\n * Validates the zone.\n *\n * @param {Zone} zone - The zone.\n * @throws {Error} If the zone is invalid.\n */\n validateZone(zone) {\n if (!Object.values(Zone).includes(zone)) {\n throw new Error(`Invalid zone: ${zone}`);\n }\n }\n /**\n * Derives and returns the Hierarchical Deterministic (HD) node wallet associated with a given address.\n *\n * This method fetches the account and address information from the wallet's internal storage, derives the\n * appropriate change node based on whether the address is a change address, and further derives the final HD node\n * using the address index.\n *\n * @param {string} addr - The address for which to derive the HD node.\n * @returns {HDNodeWallet} The derived HD node wallet corresponding to the given address.\n * @throws {Error} If the given address is not known to the wallet.\n * @throws {Error} If the account associated with the address is not found.\n */\n _getHDNodeForAddress(addr) {\n const addressInfo = this._addresses.get(addr);\n if (!addressInfo) {\n throw new Error(`Address ${addr} is not known to this wallet`);\n }\n const changeIndex = addressInfo.change ? 1 : 0;\n return this._root.deriveChild(addressInfo.account).deriveChild(changeIndex).deriveChild(addressInfo.index);\n }\n /**\n * Serializes the HD wallet state into a format suitable for storage or transmission.\n *\n * @returns {SerializedHDWallet} An object representing the serialized state of the HD wallet, including version,\n * mnemonic phrase, coin type, and addresses.\n */\n serialize() {\n const addresses = Array.from(this._addresses.values());\n return {\n version: this.constructor._version,\n phrase: this._root.mnemonic.phrase,\n coinType: this.coinType(),\n addresses: addresses,\n };\n }\n /**\n * Deserializes a serialized HD wallet object and reconstructs the wallet instance. This method must be implemented\n * in the subclass.\n *\n * @param {SerializedHDWallet} _serialized - The serialized object representing the state of an HD wallet.\n * @returns {AbstractHDWallet} An instance of AbstractHDWallet.\n * @throws {Error} This method must be implemented in the subclass.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static async deserialize(_serialized) {\n throw new Error('deserialize method must be implemented in the subclass');\n }\n /**\n * Validates the version and coinType of the serialized wallet.\n *\n * @param {SerializedHDWallet} serialized - The serialized wallet data to be validated.\n * @throws {Error} If the version or coinType of the serialized wallet does not match the expected values.\n * @protected\n * @static\n */\n static validateSerializedWallet(serialized) {\n if (serialized.version !== this._version) {\n throw new Error(`Invalid version ${serialized.version} for wallet (expected ${this._version})`);\n }\n if (serialized.coinType !== this._coinType) {\n throw new Error(`Invalid coinType ${serialized.coinType} for wallet (expected ${this._coinType})`);\n }\n }\n /**\n * Imports addresses from a serialized wallet into the addresses map. Before adding the addresses, a validation is\n * performed to ensure the address, public key, and zone match the expected values.\n *\n * @param {Map} addressMap - The map where the addresses will be imported.\n * @param {NeuteredAddressInfo[]} addresses - The array of addresses to be imported, each containing account, index,\n * change, address, pubKey, and zone information.\n * @throws {Error} If there is a mismatch between the expected and actual address, public key, or zone.\n * @protected\n */\n importSerializedAddresses(addressMap, addresses) {\n for (const addressInfo of addresses) {\n const newAddressInfo = this._addAddress(addressMap, addressInfo.account, addressInfo.index, addressInfo.change);\n // validate the address info\n if (addressInfo.address !== newAddressInfo.address) {\n throw new Error(`Address mismatch: ${addressInfo.address} != ${newAddressInfo.address}`);\n }\n if (addressInfo.pubKey !== newAddressInfo.pubKey) {\n throw new Error(`Public key mismatch: ${addressInfo.pubKey} != ${newAddressInfo.pubKey}`);\n }\n if (addressInfo.zone !== newAddressInfo.zone) {\n throw new Error(`Zone mismatch: ${addressInfo.zone} != ${newAddressInfo.zone}`);\n }\n }\n }\n /**\n * Retrieves the highest address index from the given address map for a specified zone, account, and change type.\n *\n * This method filters the address map based on the provided zone, account, and change type, then determines the\n * maximum address index from the filtered addresses.\n *\n * @param {Map} addressMap - The map containing address information, where the key is\n * an address string and the value is a NeuteredAddressInfo object.\n * @param {Zone} zone - The specific zone to filter the addresses by.\n * @param {number} account - The account number to filter the addresses by.\n * @param {boolean} isChange - A boolean indicating whether to filter for change addresses (true) or receiving\n * addresses (false).\n * @returns {number} - The highest address index for the specified criteria, or -1 if no addresses match.\n * @protected\n */\n getLastAddressIndex(addressMap, zone, account, isChange) {\n const addresses = Array.from(addressMap.values()).filter((addressInfo) => addressInfo.account === account && addressInfo.zone === zone && addressInfo.change === isChange);\n return addresses.reduce((maxIndex, addressInfo) => Math.max(maxIndex, addressInfo.index), -1);\n }\n /**\n * Creates and stores address information in the address map for a specified account, zone, and change type.\n *\n * This method constructs a NeuteredAddressInfo object using the provided HDNodeWallet and other parameters, then\n * stores this information in the provided address map.\n *\n * @param {HDNodeWallet} addressNode - The HDNodeWallet object containing the address and public key information.\n * @param {number} account - The account number to associate with the address.\n * @param {Zone} zone - The specific zone to associate with the address.\n * @param {boolean} isChange - A boolean indicating whether the address is a change address (true) or a receiving\n * address (false).\n * @param {Map} addressMap - The map to store the created NeuteredAddressInfo, with the\n * address as the key.\n * @returns {NeuteredAddressInfo} - The created NeuteredAddressInfo object.\n * @protected\n */\n createAndStoreAddressInfo(addressNode, account, zone, isChange, addressMap) {\n const neuteredAddressInfo = {\n pubKey: addressNode.publicKey,\n address: addressNode.address,\n account,\n index: addressNode.index,\n change: isChange,\n zone,\n };\n addressMap.set(neuteredAddressInfo.address, neuteredAddressInfo);\n return neuteredAddressInfo;\n }\n}\nexport { AbstractHDWallet };\n//# sourceMappingURL=hdwallet.js.map","import { AbstractHDWallet, _guard } from './hdwallet.js';\nimport { HDNodeWallet } from './hdnodewallet.js';\nimport { resolveAddress } from '../address/index.js';\nimport { Mnemonic } from './mnemonic.js';\n/**\n * The Quai HD wallet is a BIP44-compliant hierarchical deterministic wallet used for managing a set of addresses in the\n * Quai ledger. This is the easiest way to manage the interaction of managing accounts and addresses on the Quai\n * network, however, if your use case requires a single address Quai address, you can use the {@link Wallet} class.\n *\n * The Quai HD wallet supports:\n *\n * - Adding accounts to the wallet heierchy\n * - Generating addresses for a specific account in any {@link Zone}\n * - Signing and sending transactions for any address in the wallet\n * - Signing and verifying EIP1193 typed data for any address in the wallet.\n * - Serializing the wallet to JSON and deserializing it back to a wallet instance.\n *\n * @category Wallet\n * @example\n *\n * ```ts\n * import { QuaiHDWallet, Zone } from 'quais';\n *\n * const wallet = new QuaiHDWallet();\n * const cyrpus1Address = await wallet.getNextAddress(0, Zone.Cyrpus1); // get the first address in the Cyrpus1 zone\n * await wallet.sendTransaction({ from: address, to: '0x...', value: 100 }); // send a transaction\n * const serializedWallet = wallet.serialize(); // serialize current (account/address) state of the wallet\n * .\n * .\n * .\n * const deserializedWallet = QuaiHDWallet.deserialize(serializedWallet); // create a new wallet instance from the serialized data\n * ```\n */\nclass QuaiHDWallet extends AbstractHDWallet {\n /**\n * The version of the wallet.\n *\n * @type {number}\n * @static\n */\n static _version = 1;\n /**\n * The coin type for the wallet.\n *\n * @type {AllowedCoinType}\n * @static\n */\n static _coinType = 994;\n /**\n * Create a QuaiHDWallet instance.\n *\n * @param {HDNodeWallet} root - The root HD node wallet.\n * @param {Provider} [provider] - The provider.\n */\n constructor(guard, root, provider) {\n super(guard, root, provider);\n }\n /**\n * Sign a transaction.\n *\n * @param {QuaiTransactionRequest} tx - The transaction request.\n * @returns {Promise} A promise that resolves to the signed transaction.\n */\n async signTransaction(tx) {\n const from = await resolveAddress(tx.from);\n const fromNode = this._getHDNodeForAddress(from);\n const signedTx = await fromNode.signTransaction(tx);\n return signedTx;\n }\n /**\n * Send a transaction.\n *\n * @param {QuaiTransactionRequest} tx - The transaction request.\n * @returns {Promise} A promise that resolves to the transaction response.\n * @throws {Error} If the provider is not set.\n */\n async sendTransaction(tx) {\n if (!this.provider) {\n throw new Error('Provider is not set');\n }\n const from = await resolveAddress(tx.from);\n const fromNode = this._getHDNodeForAddress(from);\n const fromNodeConnected = fromNode.connect(this.provider);\n return await fromNodeConnected.sendTransaction(tx);\n }\n /**\n * Sign a message.\n *\n * @param {string} address - The address.\n * @param {string | Uint8Array} message - The message to sign.\n * @returns {Promise} A promise that resolves to the signed message.\n */\n async signMessage(address, message) {\n const addrNode = this._getHDNodeForAddress(address);\n return await addrNode.signMessage(message);\n }\n /**\n * Deserializes the given serialized HD wallet data into an instance of QuaiHDWallet.\n *\n * @async\n * @param {SerializedHDWallet} serialized - The serialized wallet data to be deserialized.\n * @returns {Promise} A promise that resolves to an instance of QuaiHDWallet.\n * @throws {Error} If validation of the serialized wallet data fails or if deserialization fails.\n * @public\n * @static\n */\n static async deserialize(serialized) {\n super.validateSerializedWallet(serialized);\n // create the wallet instance\n const mnemonic = Mnemonic.fromPhrase(serialized.phrase);\n const path = this.parentPath(serialized.coinType);\n const root = HDNodeWallet.fromMnemonic(mnemonic, path);\n const wallet = new this(_guard, root);\n // import the addresses\n wallet.importSerializedAddresses(wallet._addresses, serialized.addresses);\n return wallet;\n }\n /**\n * Signs typed data using the private key associated with the given address.\n *\n * @param {string} address - The address for which the typed data is to be signed.\n * @param {TypedDataDomain} domain - The domain information of the typed data, defining the scope of the signature.\n * @param {Record} types - The types of the data to be signed, mapping each data type name\n * to its fields.\n * @param {Record} value - The actual data to be signed.\n * @returns {Promise} A promise that resolves to the signed data in string format.\n * @throws {Error} If the address does not correspond to a valid HD node or if signing fails.\n */\n async signTypedData(address, domain, types, value) {\n const addrNode = this._getHDNodeForAddress(address);\n return addrNode.signTypedData(domain, types, value);\n }\n}\nexport { QuaiHDWallet };\n//# sourceMappingURL=quai-hdwallet.js.map","import { SigningKey } from '../crypto/index.js';\nimport { assertArgument } from '../utils/index.js';\nimport { BaseWallet } from './base-wallet.js';\nimport { decryptKeystoreJson, decryptKeystoreJsonSync, encryptKeystoreJson, encryptKeystoreJsonSync, isKeystoreJson, } from './json-keystore.js';\n/**\n * A **Wallet** manages a single private key which is used to sign transactions, messages and other common payloads.\n *\n * This class is generally the main entry point for developers that wish to use a private key directly, as it can create\n * instances from a large variety of common sources, including raw private key,\n * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) mnemonics and encrypted JSON wallets.\n *\n * @category Wallet\n */\nexport class Wallet extends BaseWallet {\n /**\n * Create a new wallet for the private `key`, optionally connected to `provider`.\n *\n * @param {string | SigningKey} key - The private key.\n * @param {null | Provider} [provider] - The provider to connect to.\n */\n constructor(key, provider) {\n if (typeof key === 'string' && !key.startsWith('0x')) {\n key = '0x' + key;\n }\n const signingKey = typeof key === 'string' ? new SigningKey(key) : key;\n super(signingKey, provider);\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {null | Provider} provider - The provider to connect to.\n *\n * @returns {Wallet} The connected wallet.\n */\n connect(provider) {\n return new Wallet(this.signingKey, provider);\n }\n /**\n * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with `password`.\n *\n * If `progressCallback` is specified, it will receive periodic updates as the encryption process progresses.\n *\n * @param {Uint8Array | string} password - The password to encrypt the wallet with.\n * @param {ProgressCallback} [progressCallback] - An optional callback to keep the user informed.\n *\n * @returns {Promise} The encrypted JSON wallet.\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) encrypted with `password`.\n *\n * It is preferred to use the [async version](encrypt) instead, which allows a\n * {@link ProgressCallback | **ProgressCallback**} to keep the user informed.\n *\n * This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial\n * duration.\n *\n * @param {Uint8Array | string} password - The password to encrypt the wallet with.\n *\n * @returns {string} The encrypted JSON wallet.\n */\n encryptSync(password) {\n const account = { address: this.address, privateKey: this.privateKey };\n return encryptKeystoreJsonSync(account, password);\n }\n /**\n * Creates a wallet from a keystore account.\n *\n * @ignore\n * @param {KeystoreAccount} account - The keystore account.\n *\n * @returns {Wallet} The wallet instance.\n */\n static #fromAccount(account) {\n assertArgument(account, 'invalid JSON wallet', 'json', '[ REDACTED ]');\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` with `password`.\n *\n * If `progress` is provided, it is called periodically during decryption so that any UI can be updated.\n *\n * @param {string} json - The JSON data to decrypt.\n * @param {Uint8Array | string} password - The password to decrypt the JSON data.\n * @param {ProgressCallback} [progress] - An optional callback to keep the user informed.\n *\n * @returns {Promise} The decrypted wallet.\n */\n static async fromEncryptedJson(json, password, progress) {\n let account;\n if (isKeystoreJson(json)) {\n account = await decryptKeystoreJson(json, password, progress);\n return Wallet.#fromAccount(account);\n }\n throw new Error('invalid JSON wallet');\n }\n /**\n * Creates a **Wallet** by decrypting the `json` with `password`.\n *\n * The {@link Wallet.fromEncryptedJson | **fromEncryptedJson**} method is preferred, as this method will lock up and\n * freeze the UI during decryption, which may take some time.\n *\n * @param {string} json - The JSON data to decrypt.\n * @param {Uint8Array | string} password - The password to decrypt the JSON data.\n *\n * @returns {QuaiHDWallet | Wallet} The decrypted wallet.\n */\n static fromEncryptedJsonSync(json, password) {\n let account = null;\n if (isKeystoreJson(json)) {\n account = decryptKeystoreJsonSync(json, password);\n }\n else {\n assertArgument(false, 'invalid JSON wallet', 'json', '[ REDACTED ]');\n }\n return Wallet.#fromAccount(account);\n }\n}\n//# sourceMappingURL=wallet.js.map","/*! musig-js - MIT License (c) 2022 Brandon Black */\nconst TAGS = {\n challenge: 'BIP0340/challenge',\n keyagg_list: 'KeyAgg list',\n keyagg_coef: 'KeyAgg coefficient',\n musig_aux: 'MuSig/aux',\n musig_nonce: 'MuSig/nonce',\n musig_deterministic_nonce: 'MuSig/deterministic/nonce',\n musig_noncecoef: 'MuSig/noncecoef',\n};\nfunction compare32b(a, b) {\n if (a.length !== 32 || b.length !== 32) throw new Error('Invalid array');\n const aD = new DataView(a.buffer, a.byteOffset, a.length);\n const bD = new DataView(b.buffer, b.byteOffset, b.length);\n for (let i = 0; i < 8; i++) {\n const cmp = aD.getUint32(i * 4) - bD.getUint32(i * 4);\n if (cmp !== 0) return cmp;\n }\n return 0;\n}\nfunction compare33b(a, b) {\n if (a.length !== 33 || b.length !== 33) throw new Error('Invalid array');\n const cmp = a[0] - b[0];\n if (cmp !== 0) return cmp;\n return compare32b(a.subarray(1), b.subarray(1));\n}\nconst makeSessionId =\n typeof self === 'object' && (self.crypto || self.msCrypto)\n ? () => (self.crypto || self.msCrypto).getRandomValues(new Uint8Array(32))\n : () => require('crypto').randomBytes(32);\nconst _keyAggCache = new WeakMap();\nconst _coefCache = new WeakMap();\nconst _nonceCache = new WeakMap();\nconst _sessionCache = new WeakMap();\nexport function MuSigFactory(ecc) {\n const CPOINT_INF = new Uint8Array(33);\n const SCALAR_0 = new Uint8Array(32);\n const SCALAR_1 = new Uint8Array(32);\n SCALAR_1[31] = 1;\n const SCALAR_MINUS_1 = ecc.scalarNegate(SCALAR_1);\n function keyAggCoeff(publicKeys, publicKey) {\n let coefCache = _coefCache.get(publicKeys);\n if (coefCache === undefined) {\n coefCache = new Map();\n _coefCache.set(publicKeys, coefCache);\n }\n let coefficient = coefCache.get(publicKey);\n if (coefficient) return coefficient;\n coefficient = SCALAR_1;\n let secondPublicKey;\n let publicKeyHash;\n let keyAggCache = _keyAggCache.get(publicKeys);\n if (keyAggCache === undefined) {\n const pkIdx2 = publicKeys.findIndex((pk) => compare33b(pk, publicKeys[0]) !== 0);\n secondPublicKey = publicKeys[pkIdx2];\n publicKeyHash = ecc.taggedHash(TAGS.keyagg_list, ...publicKeys);\n keyAggCache = { publicKeyHash, secondPublicKey };\n _keyAggCache.set(publicKeys, keyAggCache);\n } else {\n ({ publicKeyHash, secondPublicKey } = keyAggCache);\n }\n if (secondPublicKey === undefined || compare33b(publicKey, secondPublicKey) !== 0)\n coefficient = ecc.taggedHash(TAGS.keyagg_coef, publicKeyHash, publicKey);\n coefCache.set(publicKey, coefficient);\n return coefficient;\n }\n function addTweak(ctx, t) {\n const tweak = 'tweak' in t ? t : { tweak: t };\n if (!ecc.isScalar(tweak.tweak))\n throw new TypeError('Expected tweak to be a valid scalar with curve order');\n let { gacc, tacc } = ctx;\n let aggPublicKey = ctx.aggPublicKey;\n if (!ecc.hasEvenY(aggPublicKey) && tweak.xOnly) {\n gacc = ecc.scalarNegate(gacc);\n tacc = ecc.scalarNegate(tacc);\n aggPublicKey = ecc.pointNegate(aggPublicKey);\n }\n aggPublicKey = ecc.pointAddTweak(aggPublicKey, tweak.tweak, false);\n if (aggPublicKey === null) throw new Error('Unexpected point at infinity during tweaking');\n tacc = ecc.scalarAdd(tweak.tweak, tacc);\n return { aggPublicKey, gacc, tacc };\n }\n function keyAgg(publicKeys, ...tweaks) {\n checkArgs({ publicKeys });\n const multipliedPublicKeys = publicKeys.map((publicKey) => {\n const coefficient = keyAggCoeff(publicKeys, publicKey);\n let multipliedPublicKey;\n if (compare32b(coefficient, SCALAR_1) === 0) {\n multipliedPublicKey = publicKey;\n } else {\n multipliedPublicKey = ecc.pointMultiplyUnsafe(publicKey, coefficient, false);\n }\n if (multipliedPublicKey === null) throw new Error('Point at infinity during aggregation');\n return multipliedPublicKey;\n });\n const aggPublicKey = multipliedPublicKeys.reduce((a, b) => {\n const next = ecc.pointAdd(a, b, false);\n if (next === null) throw new Error('Point at infinity during aggregation');\n return next;\n });\n return tweaks.reduce((ctx, tweak) => addTweak(ctx, tweak), {\n aggPublicKey,\n gacc: SCALAR_1,\n tacc: SCALAR_0,\n });\n }\n function getSessionValues(sessionKey) {\n const sessionValues = _sessionCache.get(sessionKey);\n if (!sessionValues) throw new Error('Invalid session key, please call `startSigningSession`');\n return sessionValues;\n }\n function nonceAgg(publicNonces) {\n checkArgs({ publicNonces });\n const aggNonces = [publicNonces[0].subarray(0, 33), publicNonces[0].subarray(33)];\n for (let i = 1; i < publicNonces.length; i++) {\n if (aggNonces[0] !== null)\n aggNonces[0] = ecc.pointAdd(aggNonces[0], publicNonces[i].subarray(0, 33), false);\n if (aggNonces[1] !== null)\n aggNonces[1] = ecc.pointAdd(aggNonces[1], publicNonces[i].subarray(33), false);\n }\n const aggNonce = new Uint8Array(66);\n if (aggNonces[0] !== null) aggNonce.set(ecc.pointCompress(aggNonces[0]), 0);\n if (aggNonces[1] !== null) aggNonce.set(ecc.pointCompress(aggNonces[1]), 33);\n return aggNonce;\n }\n function startSigningSessionInner(aggNonce, msg, publicKeys, ctx) {\n const pubKeyX = ecc.pointX(ctx.aggPublicKey);\n const coefficient = ecc.taggedHash(TAGS.musig_noncecoef, aggNonce, pubKeyX, msg);\n const aggNonces = [aggNonce.subarray(0, 33), aggNonce.subarray(33)];\n let r = null;\n if (compare33b(aggNonces[1], CPOINT_INF) !== 0 && compare33b(aggNonces[0], CPOINT_INF) !== 0) {\n r = ecc.pointMultiplyAndAddUnsafe(aggNonces[1], coefficient, aggNonces[0], false);\n } else if (compare33b(aggNonces[0], CPOINT_INF) !== 0) {\n r = ecc.pointCompress(aggNonces[0], false);\n } else if (compare33b(aggNonces[1], CPOINT_INF) !== 0) {\n r = ecc.pointMultiplyUnsafe(aggNonces[1], coefficient, false);\n }\n if (r === null) r = ecc.getPublicKey(SCALAR_1, false);\n if (r === null) throw new Error('Failed to get G');\n const challenge = ecc.scalarMod(ecc.taggedHash(TAGS.challenge, ecc.pointX(r), pubKeyX, msg));\n const key = { publicKey: ctx.aggPublicKey, aggNonce, msg };\n _sessionCache.set(key, { ...ctx, coefficient, challenge, finalNonce: r, publicKeys });\n return key;\n }\n function partialVerifyInner({ sig, publicKey, publicNonces, sessionKey }) {\n const { msg } = sessionKey;\n const { aggPublicKey, gacc, challenge, coefficient, finalNonce, publicKeys } =\n getSessionValues(sessionKey);\n const rePrime = ecc.pointMultiplyAndAddUnsafe(\n publicNonces[1],\n coefficient,\n publicNonces[0],\n false\n );\n if (rePrime === null) throw new Error('Unexpected public nonce at infinity');\n const re = ecc.hasEvenY(finalNonce) ? rePrime : ecc.pointNegate(rePrime);\n const a = keyAggCoeff(publicKeys, publicKey);\n const g = ecc.hasEvenY(aggPublicKey) ? gacc : ecc.scalarNegate(gacc);\n const ea = ecc.scalarMultiply(challenge, a);\n const eag = ecc.scalarMultiply(ea, g);\n const ver = ecc.pointMultiplyAndAddUnsafe(publicKey, eag, re, true);\n if (ver === null) throw new Error('Unexpected verification point at infinity');\n const sG = ecc.getPublicKey(sig, true);\n if (sG === null) throw new Error('Unexpected signature point at infinity');\n return compare33b(ver, sG) === 0;\n }\n function partialSignInner({ secretKey, publicKey, secretNonces, sessionKey }) {\n const { msg } = sessionKey;\n const { aggPublicKey, gacc, challenge, coefficient, finalNonce, publicKeys } =\n getSessionValues(sessionKey);\n const [k1, k2] = secretNonces.map((k) => (ecc.hasEvenY(finalNonce) ? k : ecc.scalarNegate(k)));\n const a = keyAggCoeff(publicKeys, publicKey);\n const g = ecc.hasEvenY(aggPublicKey) ? gacc : ecc.scalarNegate(gacc);\n const d = ecc.scalarMultiply(g, secretKey);\n const bk2 = ecc.scalarMultiply(coefficient, k2);\n const k1bk2 = ecc.scalarAdd(k1, bk2);\n const ea = ecc.scalarMultiply(challenge, a);\n const ead = ecc.scalarMultiply(ea, d);\n const sig = ecc.scalarAdd(k1bk2, ead);\n return sig;\n }\n function partialSign({ secretKey, publicNonce, sessionKey, verify = true }) {\n checkArgs({ publicNonce, secretKey });\n const secretNonce = _nonceCache.get(publicNonce);\n if (secretNonce === undefined)\n throw new Error('No secret nonce found for specified public nonce');\n _nonceCache.delete(publicNonce);\n const publicKey = ecc.getPublicKey(secretKey, true);\n if (publicKey === null) throw new Error('Invalid secret key, no corresponding public key');\n if (compare33b(publicKey, secretNonce.subarray(64)) !== 0)\n throw new Error('Secret nonce pubkey mismatch');\n const secretNonces = [secretNonce.subarray(0, 32), secretNonce.subarray(32, 64)];\n const sig = partialSignInner({\n secretKey,\n publicKey,\n secretNonces,\n sessionKey,\n });\n if (verify) {\n const publicNonces = [publicNonce.subarray(0, 33), publicNonce.subarray(33)];\n const valid = partialVerifyInner({\n sig,\n publicKey,\n publicNonces,\n sessionKey,\n });\n if (!valid) throw new Error('Partial signature failed verification');\n }\n return sig;\n }\n function deterministicSign({\n secretKey,\n aggOtherNonce,\n publicKeys,\n tweaks = [],\n msg,\n rand,\n verify = true,\n nonceOnly = false,\n }) {\n checkArgs({ rand, secretKey, aggOtherNonce });\n const publicKey = ecc.getPublicKey(secretKey, true);\n if (publicKey === null) throw new Error('Secret key has no corresponding public key');\n let secretKeyPrime;\n if (rand !== undefined) {\n secretKeyPrime = ecc.taggedHash(TAGS.musig_aux, rand);\n for (let i = 0; i < 32; i++) {\n secretKeyPrime[i] = secretKeyPrime[i] ^ secretKey[i];\n }\n } else {\n secretKeyPrime = secretKey;\n }\n const ctx = keyAgg(publicKeys, ...tweaks);\n const aggPublicKey = ecc.pointX(ctx.aggPublicKey);\n const mLength = new Uint8Array(8);\n new DataView(mLength.buffer).setBigUint64(0, BigInt(msg.length));\n const secretNonce = new Uint8Array(97);\n const publicNonce = new Uint8Array(66);\n for (let i = 0; i < 2; i++) {\n const kH = ecc.taggedHash(\n TAGS.musig_deterministic_nonce,\n ...[secretKeyPrime, aggOtherNonce, aggPublicKey, mLength, msg, Uint8Array.of(i)]\n );\n const k = ecc.scalarMod(kH);\n if (compare32b(SCALAR_0, k) === 0) throw new Error('0 secret nonce');\n const pub = ecc.getPublicKey(k, true);\n if (pub === null) throw new Error('Secret nonce has no corresponding public nonce');\n secretNonce.set(k, i * 32);\n publicNonce.set(pub, i * 33);\n }\n secretNonce.set(publicKey, 64);\n if (nonceOnly) return { publicNonce };\n _nonceCache.set(publicNonce, secretNonce);\n const aggNonce = nonceAgg([aggOtherNonce, publicNonce]);\n const sessionKey = startSigningSessionInner(aggNonce, msg, publicKeys, ctx);\n const sig = partialSign({\n secretKey,\n publicNonce,\n sessionKey,\n verify,\n });\n return { sig, sessionKey, publicNonce };\n }\n const pubKeyArgs = ['publicKey', 'publicKeys'];\n const scalarArgs = ['tweak', 'sig', 'sigs', 'tacc', 'gacc'];\n const otherArgs32b = ['xOnlyPublicKey', 'rand', 'sessionId'];\n const args32b = ['secretKey', ...scalarArgs, ...otherArgs32b];\n const pubNonceArgs = ['publicNonce', 'publicNonces', 'aggNonce', 'aggOtherNonce', 'finalNonce'];\n const otherArgs = ['aggPublicKey', 'secretNonce'];\n const argLengths = new Map();\n args32b.forEach((a) => argLengths.set(a, 32));\n pubKeyArgs.forEach((a) => argLengths.set(a, 33));\n pubNonceArgs.forEach((a) => argLengths.set(a, 66));\n argLengths.set('secretNonce', 97);\n argLengths.set('aggPublicKey', 65);\n const scalarNames = new Set();\n scalarArgs.forEach((n) => scalarNames.add(n));\n function checkArgs(args) {\n for (let [name, values] of Object.entries(args)) {\n if (values === undefined) continue;\n values = Array.isArray(values) ? values : [values];\n if (values.length === 0) throw new TypeError(`0-length ${name}s not supported`);\n for (const value of values) {\n if (argLengths.get(name) !== value.length)\n throw new TypeError(`Invalid ${name} length (${value.length})`);\n if (name === 'secretKey') {\n if (!ecc.isSecret(value)) throw new TypeError(`Invalid secretKey`);\n } else if (name === 'secretNonce') {\n for (let i = 0; i < 64; i += 32)\n if (!ecc.isSecret(value.subarray(i, i + 32)))\n throw new TypeError(`Invalid secretNonce`);\n } else if (scalarNames.has(name)) {\n for (let i = 0; i < value.length; i += 32)\n if (!ecc.isScalar(value.subarray(i, i + 32))) throw new TypeError(`Invalid ${name}`);\n }\n }\n }\n }\n return {\n getXOnlyPubkey: (ctx) => {\n if ('aggPublicKey' in ctx) return ecc.pointX(ctx.aggPublicKey);\n return ecc.pointX(getSessionValues(ctx).aggPublicKey);\n },\n getPlainPubkey: (ctx) => {\n if ('aggPublicKey' in ctx) return ecc.pointCompress(ctx.aggPublicKey);\n return ecc.pointCompress(getSessionValues(ctx).aggPublicKey);\n },\n keySort: (publicKeys) => {\n checkArgs({ publicKeys });\n return [...publicKeys].sort((a, b) => compare33b(a, b));\n },\n keyAgg,\n addTweaks: (ctx, ...tweaks) => {\n checkArgs(ctx);\n return tweaks.reduce((c, tweak) => addTweak(c, tweak), ctx);\n },\n nonceGen: ({\n sessionId = makeSessionId(),\n secretKey,\n publicKey,\n xOnlyPublicKey,\n msg,\n extraInput,\n }) => {\n if (extraInput !== undefined && extraInput.length > Math.pow(2, 32) - 1)\n throw new TypeError('extraInput is limited to 2^32-1 bytes');\n checkArgs({ sessionId, secretKey, publicKey, xOnlyPublicKey });\n let rand;\n if (secretKey !== undefined) {\n rand = ecc.taggedHash(TAGS.musig_aux, sessionId);\n for (let i = 0; i < 32; i++) {\n rand[i] = rand[i] ^ secretKey[i];\n }\n } else {\n rand = sessionId;\n }\n if (xOnlyPublicKey === undefined) xOnlyPublicKey = new Uint8Array();\n const mPrefixed = [Uint8Array.of(0)];\n if (msg !== undefined) {\n mPrefixed[0][0] = 1;\n mPrefixed.push(new Uint8Array(8));\n new DataView(mPrefixed[1].buffer).setBigUint64(0, BigInt(msg.length));\n mPrefixed.push(msg);\n }\n if (extraInput === undefined) extraInput = new Uint8Array();\n const eLength = new Uint8Array(4);\n new DataView(eLength.buffer).setUint32(0, extraInput.length);\n const secretNonce = new Uint8Array(97);\n const publicNonce = new Uint8Array(66);\n for (let i = 0; i < 2; i++) {\n const kH = ecc.taggedHash(\n TAGS.musig_nonce,\n rand,\n Uint8Array.of(publicKey.length),\n publicKey,\n Uint8Array.of(xOnlyPublicKey.length),\n xOnlyPublicKey,\n ...mPrefixed,\n eLength,\n extraInput,\n Uint8Array.of(i)\n );\n const k = ecc.scalarMod(kH);\n if (compare32b(SCALAR_0, k) === 0) throw new Error('0 secret nonce');\n const pub = ecc.getPublicKey(k, true);\n if (pub === null) throw new Error('Secret nonce has no corresponding public nonce');\n secretNonce.set(k, i * 32);\n publicNonce.set(pub, i * 33);\n }\n secretNonce.set(publicKey, 64);\n _nonceCache.set(publicNonce, secretNonce);\n return publicNonce;\n },\n addExternalNonce: (publicNonce, secretNonce) => {\n checkArgs({ publicNonce, secretNonce });\n _nonceCache.set(publicNonce, secretNonce);\n },\n deterministicNonceGen: (args) => deterministicSign({ ...args, nonceOnly: true }),\n deterministicSign,\n nonceAgg,\n startSigningSession: (aggNonce, msg, publicKeys, ...tweaks) => {\n checkArgs({ aggNonce });\n const ctx = keyAgg(publicKeys, ...tweaks);\n return startSigningSessionInner(aggNonce, msg, publicKeys, ctx);\n },\n partialSign,\n partialVerify: ({ sig, publicKey, publicNonce, sessionKey }) => {\n checkArgs({ sig, publicKey, publicNonce });\n const publicNonces = [publicNonce.subarray(0, 33), publicNonce.subarray(33)];\n const valid = partialVerifyInner({\n sig,\n publicKey,\n publicNonces,\n sessionKey,\n });\n return valid;\n },\n signAgg: (sigs, sessionKey) => {\n checkArgs({ sigs });\n const { aggPublicKey, tacc, challenge, finalNonce } = getSessionValues(sessionKey);\n let sPart = ecc.scalarMultiply(challenge, tacc);\n if (!ecc.hasEvenY(aggPublicKey)) {\n sPart = ecc.scalarNegate(sPart);\n }\n const aggS = sigs.reduce((a, b) => ecc.scalarAdd(a, b), sPart);\n const sig = new Uint8Array(64);\n sig.set(ecc.pointX(finalNonce), 0);\n sig.set(aggS, 32);\n return sig;\n },\n };\n}\n","import { AbstractHDWallet, _guard } from './hdwallet.js';\nimport { HDNodeWallet } from './hdnodewallet.js';\nimport { computeAddress } from '../address/index.js';\nimport { getBytes, hexlify } from '../utils/index.js';\nimport { QiTransaction } from '../transaction/index.js';\nimport { MuSigFactory } from '@brandonblack/musig';\nimport { schnorr } from '@noble/curves/secp256k1';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { musigCrypto } from '../crypto/index.js';\nimport { getZoneForAddress } from '../utils/index.js';\nimport { Mnemonic } from './mnemonic.js';\n/**\n * The Qi HD wallet is a BIP44-compliant hierarchical deterministic wallet used for managing a set of addresses in the\n * Qi ledger. This is wallet implementation is the primary way to interact with the Qi UTXO ledger on the Quai network.\n *\n * The Qi HD wallet supports:\n *\n * - Adding accounts to the wallet heierchy\n * - Generating addresses for a specific account in any {@link Zone}\n * - Signing and sending transactions for any address in the wallet\n * - Serializing the wallet to JSON and deserializing it back to a wallet instance.\n *\n * @category Wallet\n * @example\n *\n * ```ts\n * import { QiHDWallet, Zone } from 'quais';\n *\n * const wallet = new QiHDWallet();\n * const cyrpus1Address = await wallet.getNextAddress(0, Zone.Cyrpus1); // get the first address in the Cyrpus1 zone\n * await wallet.sendTransaction({ txInputs: [...], txOutputs: [...] }); // send a transaction\n * const serializedWallet = wallet.serialize(); // serialize current (account/address) state of the wallet\n * .\n * .\n * .\n * const deserializedWallet = QiHDWallet.deserialize(serializedWallet); // create a new wallet instance from the serialized data\n * ```\n */\nclass QiHDWallet extends AbstractHDWallet {\n /**\n * @ignore\n * @type {number}\n */\n static _version = 1;\n /**\n * @ignore\n * @type {number}\n */\n static _GAP_LIMIT = 20;\n /**\n * @ignore\n * @type {AllowedCoinType}\n */\n static _coinType = 969;\n /**\n * Map of change addresses to address info.\n *\n * @ignore\n * @type {Map}\n */\n _changeAddresses = new Map();\n /**\n * Array of gap addresses.\n *\n * @ignore\n * @type {NeuteredAddressInfo[]}\n */\n _gapChangeAddresses = [];\n /**\n * Array of gap change addresses.\n *\n * @ignore\n * @type {NeuteredAddressInfo[]}\n */\n _gapAddresses = [];\n /**\n * Array of outpoint information.\n *\n * @ignore\n * @type {OutpointInfo[]}\n */\n _outpoints = [];\n /**\n * @ignore\n * @param {HDNodeWallet} root - The root HDNodeWallet.\n * @param {Provider} [provider] - The provider (optional).\n */\n constructor(guard, root, provider) {\n super(guard, root, provider);\n }\n /**\n * Promise that resolves to the next change address for the specified account and zone.\n *\n * @param {number} account - The index of the account for which to retrieve the next change address.\n * @param {Zone} zone - The zone in which to retrieve the next change address.\n * @returns {Promise} The next change neutered address information.\n */\n async getNextChangeAddress(account, zone) {\n return Promise.resolve(this._getNextAddress(account, zone, true, this._changeAddresses));\n }\n /**\n * Synchronously retrieves the next change address for the specified account and zone.\n *\n * @param {number} account - The index of the account for which to retrieve the next change address.\n * @param {Zone} zone - The zone in which to retrieve the next change address.\n * @returns {NeuteredAddressInfo} The next change neutered address information.\n */\n getNextChangeAddressSync(account, zone) {\n return this._getNextAddress(account, zone, true, this._changeAddresses);\n }\n /**\n * Imports an array of outpoints.\n *\n * @param {OutpointInfo[]} outpoints - The outpoints to import.\n */\n importOutpoints(outpoints) {\n this.validateOutpointInfo(outpoints);\n this._outpoints.push(...outpoints);\n }\n /**\n * Gets the outpoints for the specified zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {OutpointInfo[]} The outpoints for the zone.\n */\n getOutpoints(zone) {\n this.validateZone(zone);\n return this._outpoints.filter((outpoint) => outpoint.zone === zone);\n }\n /**\n * Signs a Qi transaction and returns the serialized transaction.\n *\n * @param {QiTransactionRequest} tx - The transaction to sign.\n * @returns {Promise} The serialized transaction.\n * @throws {Error} If the UTXO transaction is invalid.\n */\n async signTransaction(tx) {\n const txobj = QiTransaction.from(tx);\n if (!txobj.txInputs || txobj.txInputs.length == 0 || !txobj.txOutputs)\n throw new Error('Invalid UTXO transaction, missing inputs or outputs');\n const hash = keccak_256(txobj.unsignedSerialized);\n let signature;\n if (txobj.txInputs.length == 1) {\n signature = this.createSchnorrSignature(txobj.txInputs[0], hash);\n }\n else {\n signature = this.createMuSigSignature(txobj, hash);\n }\n txobj.signature = signature;\n return txobj.serialized;\n }\n /**\n * Sends a Qi transaction.\n *\n * @param {QiTransactionRequest} tx - The transaction to send.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the provider is not set or if the transaction has no inputs.\n */\n async sendTransaction(tx) {\n if (!this.provider) {\n throw new Error('Provider is not set');\n }\n if (!tx.txInputs || tx.txInputs.length === 0) {\n throw new Error('Transaction has no inputs');\n }\n const input = tx.txInputs[0];\n const address = computeAddress(input.pubkey);\n const shard = getZoneForAddress(address);\n if (!shard) {\n throw new Error(`Address ${address} not found in any shard`);\n }\n // verify all inputs are from the same shard\n if (tx.txInputs.some((input) => getZoneForAddress(computeAddress(input.pubkey)) !== shard)) {\n throw new Error('All inputs must be from the same shard');\n }\n const signedTx = await this.signTransaction(tx);\n return await this.provider.broadcastTransaction(shard, signedTx);\n }\n /**\n * Returns a schnorr signature for the given message and private key.\n *\n * @ignore\n * @param {TxInput} input - The transaction input.\n * @param {Uint8Array} hash - The hash of the message.\n * @returns {string} The schnorr signature.\n */\n createSchnorrSignature(input, hash) {\n const privKey = this.getPrivateKeyForTxInput(input);\n const signature = schnorr.sign(hash, getBytes(privKey));\n return hexlify(signature);\n }\n /**\n * Returns a MuSig signature for the given message and private keys corresponding to the input addresses.\n *\n * @ignore\n * @param {QiTransaction} tx - The Qi transaction.\n * @param {Uint8Array} hash - The hash of the message.\n * @returns {string} The MuSig signature.\n */\n createMuSigSignature(tx, hash) {\n const musig = MuSigFactory(musigCrypto);\n // Collect private keys corresponding to the pubkeys found on the inputs\n const privKeysSet = new Set();\n tx.txInputs.forEach((input) => {\n const privKey = this.getPrivateKeyForTxInput(input);\n privKeysSet.add(privKey);\n });\n const privKeys = Array.from(privKeysSet);\n // Create an array of public keys corresponding to the private keys for musig aggregation\n const pubKeys = privKeys\n .map((privKey) => musigCrypto.getPublicKey(getBytes(privKey), true))\n .filter((pubKey) => pubKey !== null);\n // Generate nonces for each public key\n const nonces = pubKeys.map((pk) => musig.nonceGen({ publicKey: getBytes(pk) }));\n const aggNonce = musig.nonceAgg(nonces);\n const signingSession = musig.startSigningSession(aggNonce, hash, pubKeys);\n // Create partial signatures for each private key\n const partialSignatures = privKeys.map((sk, index) => musig.partialSign({\n secretKey: getBytes(sk || ''),\n publicNonce: nonces[index],\n sessionKey: signingSession,\n verify: true,\n }));\n // Aggregate the partial signatures into a final aggregated signature\n const finalSignature = musig.signAgg(partialSignatures, signingSession);\n return hexlify(finalSignature);\n }\n /**\n * Retrieves the private key for a given transaction input.\n *\n * This method derives the private key for a transaction input by following these steps:\n *\n * 1. Ensures the input contains a public key.\n * 2. Computes the address from the public key.\n * 3. Fetches address information associated with the computed address.\n * 4. Derives the hierarchical deterministic (HD) node corresponding to the address.\n * 5. Returns the private key of the derived HD node.\n *\n * @ignore\n * @param {TxInput} input - The transaction input containing the public key.\n * @returns {string} The private key corresponding to the transaction input.\n * @throws {Error} If the input does not contain a public key or if the address information cannot be found.\n */\n getPrivateKeyForTxInput(input) {\n if (!input.pubkey)\n throw new Error('Missing public key for input');\n const address = computeAddress(input.pubkey);\n // get address info\n const addressInfo = this.getAddressInfo(address);\n if (!addressInfo)\n throw new Error(`Address not found: ${address}`);\n // derive an HDNode for the address and get the private key\n const changeIndex = addressInfo.change ? 1 : 0;\n const addressNode = this._root\n .deriveChild(addressInfo.account)\n .deriveChild(changeIndex)\n .deriveChild(addressInfo.index);\n return addressNode.privateKey;\n }\n /**\n * Scans the specified zone for addresses with unspent outputs. Starting at index 0, it will generate new addresses\n * until the gap limit is reached for both gap and change addresses.\n *\n * @param {Zone} zone - The zone in which to scan for addresses.\n * @param {number} [account=0] - The index of the account to scan. Default is `0`\n * @returns {Promise} A promise that resolves when the scan is complete.\n * @throws {Error} If the zone is invalid.\n */\n async scan(zone, account = 0) {\n this.validateZone(zone);\n // flush the existing addresses and outpoints\n this._addresses = new Map();\n this._changeAddresses = new Map();\n this._gapAddresses = [];\n this._gapChangeAddresses = [];\n this._outpoints = [];\n await this._scan(zone, account);\n }\n /**\n * Scans the specified zone for addresses with unspent outputs. Starting at the last address index, it will generate\n * new addresses until the gap limit is reached for both gap and change addresses. If no account is specified, it\n * will scan all accounts known to the wallet.\n *\n * @param {Zone} zone - The zone in which to sync addresses.\n * @param {number} [account] - The index of the account to sync. If not specified, all accounts will be scanned.\n * @returns {Promise} A promise that resolves when the sync is complete.\n * @throws {Error} If the zone is invalid.\n */\n async sync(zone, account) {\n this.validateZone(zone);\n // if no account is specified, scan all accounts.\n if (account === undefined) {\n const addressInfos = Array.from(this._addresses.values());\n const accounts = addressInfos.reduce((unique, info) => {\n if (!unique.includes(info.account)) {\n unique.push(info.account);\n }\n return unique;\n }, []);\n for (const acc of accounts) {\n await this._scan(zone, acc);\n }\n }\n else {\n await this._scan(zone, account);\n }\n return;\n }\n /**\n * Internal method to scan the specified zone for addresses with unspent outputs. This method handles the actual\n * scanning logic, generating new addresses until the gap limit is reached for both gap and change addresses.\n *\n * @param {Zone} zone - The zone in which to scan for addresses.\n * @param {number} [account=0] - The index of the account to scan. Default is `0`\n * @returns {Promise} A promise that resolves when the scan is complete.\n * @throws {Error} If the provider is not set.\n */\n async _scan(zone, account = 0) {\n if (!this.provider)\n throw new Error('Provider not set');\n let gapAddressesCount = 0;\n let changeGapAddressesCount = 0;\n while (gapAddressesCount < QiHDWallet._GAP_LIMIT || changeGapAddressesCount < QiHDWallet._GAP_LIMIT) {\n [gapAddressesCount, changeGapAddressesCount] = await Promise.all([\n gapAddressesCount < QiHDWallet._GAP_LIMIT\n ? this.scanAddress(zone, account, false, gapAddressesCount)\n : gapAddressesCount,\n changeGapAddressesCount < QiHDWallet._GAP_LIMIT\n ? this.scanAddress(zone, account, true, changeGapAddressesCount)\n : changeGapAddressesCount,\n ]);\n }\n }\n /**\n * Scans for the next address in the specified zone and account, checking for associated outpoints, and updates the\n * address count and gap addresses accordingly.\n *\n * @param {Zone} zone - The zone in which the address is being scanned.\n * @param {number} account - The index of the account for which the address is being scanned.\n * @param {boolean} isChange - A flag indicating whether the address is a change address.\n * @param {number} addressesCount - The current count of addresses scanned.\n * @returns {Promise} A promise that resolves to the updated address count.\n * @throws {Error} If an error occurs during the address scanning or outpoints retrieval process.\n */\n async scanAddress(zone, account, isChange, addressesCount) {\n const addressMap = isChange ? this._changeAddresses : this._addresses;\n const addressInfo = this._getNextAddress(account, zone, isChange, addressMap);\n const outpoints = await this.getOutpointsByAddress(addressInfo.address);\n if (outpoints.length > 0) {\n this.importOutpoints(outpoints.map((outpoint) => ({\n outpoint,\n address: addressInfo.address,\n zone,\n account,\n })));\n addressesCount = 0;\n isChange ? (this._gapChangeAddresses = []) : (this._gapAddresses = []);\n }\n else {\n addressesCount++;\n isChange ? this._gapChangeAddresses.push(addressInfo) : this._gapAddresses.push(addressInfo);\n }\n return addressesCount;\n }\n /**\n * Queries the network node for the outpoints of the specified address.\n *\n * @ignore\n * @param {string} address - The address to query.\n * @returns {Promise} The outpoints for the address.\n * @throws {Error} If the query fails.\n */\n async getOutpointsByAddress(address) {\n try {\n const outpointsMap = await this.provider.getOutpointsByAddress(address);\n if (!outpointsMap) {\n return [];\n }\n return Object.values(outpointsMap);\n }\n catch (error) {\n throw new Error(`Failed to get outpoints for address: ${address} - error: ${error}`);\n }\n }\n /**\n * Gets the change addresses for the specified zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {NeuteredAddressInfo[]} The change addresses for the zone.\n */\n getChangeAddressesForZone(zone) {\n this.validateZone(zone);\n const changeAddresses = this._changeAddresses.values();\n return Array.from(changeAddresses).filter((addressInfo) => addressInfo.zone === zone);\n }\n /**\n * Gets the gap addresses for the specified zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {NeuteredAddressInfo[]} The gap addresses for the zone.\n */\n getGapAddressesForZone(zone) {\n this.validateZone(zone);\n const gapAddresses = this._gapAddresses.filter((addressInfo) => addressInfo.zone === zone);\n return gapAddresses;\n }\n /**\n * Gets the gap change addresses for the specified zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {NeuteredAddressInfo[]} The gap change addresses for the zone.\n */\n getGapChangeAddressesForZone(zone) {\n this.validateZone(zone);\n const gapChangeAddresses = this._gapChangeAddresses.filter((addressInfo) => addressInfo.zone === zone);\n return gapChangeAddresses;\n }\n /**\n * Signs a message using the private key associated with the given address.\n *\n * @param {string} address - The address for which the message is to be signed.\n * @param {string | Uint8Array} message - The message to be signed, either as a string or Uint8Array.\n * @returns {Promise} A promise that resolves to the signature of the message in hexadecimal string format.\n * @throws {Error} If the address does not correspond to a valid HD node or if signing fails.\n */\n async signMessage(address, message) {\n const addrNode = this._getHDNodeForAddress(address);\n const privKey = addrNode.privateKey;\n const digest = keccak_256(message);\n const signature = schnorr.sign(digest, getBytes(privKey));\n return hexlify(signature);\n }\n /**\n * Serializes the HD wallet state into a format suitable for storage or transmission.\n *\n * @returns {SerializedQiHDWallet} An object representing the serialized state of the HD wallet, including\n * outpoints, change addresses, gap addresses, and other inherited properties.\n */\n serialize() {\n const hdwalletSerialized = super.serialize();\n return {\n outpoints: this._outpoints,\n changeAddresses: Array.from(this._changeAddresses.values()),\n gapAddresses: this._gapAddresses,\n gapChangeAddresses: this._gapChangeAddresses,\n ...hdwalletSerialized,\n };\n }\n /**\n * Deserializes a serialized QiHDWallet object and reconstructs the wallet instance.\n *\n * @param {SerializedQiHDWallet} serialized - The serialized object representing the state of a QiHDWallet.\n * @returns {Promise} A promise that resolves to a reconstructed QiHDWallet instance.\n * @throws {Error} If the serialized data is invalid or if any addresses in the gap addresses or gap change\n * addresses do not exist in the wallet.\n */\n static async deserialize(serialized) {\n super.validateSerializedWallet(serialized);\n // create the wallet instance\n const mnemonic = Mnemonic.fromPhrase(serialized.phrase);\n const path = this.parentPath(serialized.coinType);\n const root = HDNodeWallet.fromMnemonic(mnemonic, path);\n const wallet = new this(_guard, root);\n // import the addresses\n wallet.importSerializedAddresses(wallet._addresses, serialized.addresses);\n // import the change addresses\n wallet.importSerializedAddresses(wallet._changeAddresses, serialized.changeAddresses);\n // import the gap addresses, verifying they already exist in the wallet\n for (const gapAddressInfo of serialized.gapAddresses) {\n const gapAddress = gapAddressInfo.address;\n if (!wallet._addresses.has(gapAddress)) {\n throw new Error(`Address ${gapAddress} not found in wallet`);\n }\n wallet._gapAddresses.push(gapAddressInfo);\n }\n // import the gap change addresses, verifying they already exist in the wallet\n for (const gapChangeAddressInfo of serialized.gapChangeAddresses) {\n const gapChangeAddress = gapChangeAddressInfo.address;\n if (!wallet._changeAddresses.has(gapChangeAddress)) {\n throw new Error(`Address ${gapChangeAddress} not found in wallet`);\n }\n wallet._gapChangeAddresses.push(gapChangeAddressInfo);\n }\n // validate the outpoints and import them\n wallet.validateOutpointInfo(serialized.outpoints);\n wallet._outpoints.push(...serialized.outpoints);\n return wallet;\n }\n /**\n * Validates an array of OutpointInfo objects. This method checks the validity of each OutpointInfo object by\n * performing the following validations:\n *\n * - Validates the zone using the `validateZone` method.\n * - Checks if the address exists in the wallet.\n * - Checks if the account (if provided) exists in the wallet.\n * - Validates the Outpoint by ensuring that `Txhash`, `Index`, and `Denomination` are not null.\n *\n * @ignore\n * @param {OutpointInfo[]} outpointInfo - An array of OutpointInfo objects to be validated.\n * @throws {Error} If any of the validations fail, an error is thrown with a descriptive message.\n */\n validateOutpointInfo(outpointInfo) {\n outpointInfo.forEach((info) => {\n // validate zone\n this.validateZone(info.zone);\n // validate address and account\n const addressInfo = this.getAddressInfo(info.address);\n if (!addressInfo) {\n throw new Error(`Address ${info.address} not found in wallet`);\n }\n if (info.account !== undefined && info.account !== addressInfo.account) {\n throw new Error(`Account ${info.account} not found for address ${info.address}`);\n }\n // validate Outpoint\n if (info.outpoint.txhash == null || info.outpoint.index == null || info.outpoint.denomination == null) {\n throw new Error(`Invalid Outpoint: ${JSON.stringify(info)} `);\n }\n });\n }\n}\nexport { QiHDWallet };\n//# sourceMappingURL=qi-hdwallet.js.map","/**\n * A **Network** encapsulates the various properties required to interact with a specific chain.\n * @category Providers\n */\nimport { getBigInt, assertArgument } from '../utils/index.js';\nconst Networks = new Map();\n/**\n * A **Network** provides access to a chain's properties and allows for plug-ins to extend functionality.\n *\n * @category Providers\n */\nexport class Network {\n #name;\n #chainId;\n /**\n * Creates a new **Network** for `name` and `chainId`.\n * @param {string} name - The network name.\n * @param {BigNumberish} chainId - The network chain ID.\n */\n constructor(name, chainId) {\n this.#name = name;\n this.#chainId = getBigInt(chainId);\n }\n /**\n * Returns a JSON-compatible representation of a Network.\n * @returns {Object} The JSON representation of the 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 might have multiple names.\n * @returns {string} The network name.\n */\n get name() {\n return this.#name;\n }\n /**\n * Sets the network name.\n * @param {string} value - The new network name.\n */\n set name(value) {\n this.#name = value;\n }\n /**\n * The network chain ID.\n * @returns {bigint} The network chain ID.\n */\n get chainId() {\n return this.#chainId;\n }\n /**\n * Sets the network chain ID.\n * @param {BigNumberish} value - The new network chain ID.\n */\n set chainId(value) {\n this.#chainId = getBigInt(value, 'chainId');\n }\n /**\n * Returns true if `other` matches this network. Any chain ID must match, and if no chain ID is present, the name\n * must match.\n *\n * This method does not currently check for additional properties, such as plug-in compatibility.\n *\n * @param {Networkish} other - The network to compare.\n * @returns {boolean} True if the networks match.\n * @ignore\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 // eslint-disable-next-line no-empty\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 // eslint-disable-next-line no-empty\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 // eslint-disable-next-line no-empty\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 * Create a copy of this Network.\n * @returns {Network} A new Network instance.\n */\n clone() {\n const clone = new Network(this.name, this.chainId);\n return clone;\n }\n /**\n * Returns a new Network for the `network` name or chainId.\n *\n * @param {Networkish} [network] - The network to get.\n * @returns {Network} The Network instance.\n * @throws {Error} If the network is invalid.\n */\n static from(network) {\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 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 return custom;\n }\n assertArgument(false, 'invalid network', 'network', network);\n }\n /**\n * Register `nameOrChainId` with a function which returns an instance of a Network representing that chain.\n *\n * @param {string | number | bigint} nameOrChainId - The name or chain ID to register.\n * @param {() => Network} networkFunc - The function to create the Network.\n * @throws {Error} If a network is already registered for `nameOrChainId`.\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//# sourceMappingURL=network.js.map","import { toZone } from '../constants/index.js';\nimport { toShard } from '../constants/shards.js';\nimport { assert, isHexString } from '../utils/index.js';\nimport { getZoneFromNodeLocation } from '../utils/shards.js';\nimport { getZoneFromEventFilter } from './provider.js';\n/**\n * Deep copies an object.\n *\n * @param {any} obj - The object to copy.\n * @returns {any} The copied object.\n */\nfunction copy(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n/**\n * Return the polling subscriber for common events.\n *\n * @category Providers\n * @param {AbstractProvider} provider - The provider to attach the subscriber to.\n * @param {ProviderEvent} event - The event to subscribe to.\n * @returns {Subscriber} The polling subscriber.\n * @throws {Error} If the event is unsupported.\n */\nexport function getPollingSubscriber(provider, event, zone) {\n if (event === 'block') {\n return new PollingBlockSubscriber(provider, zone);\n }\n if (isHexString(event, 32)) {\n return new PollingTransactionSubscriber(provider, event, zone);\n }\n assert(false, 'unsupported polling event', 'UNSUPPORTED_OPERATION', {\n operation: 'getPollingSubscriber',\n info: { event },\n });\n}\n/**\n * A **PollingBlockSubscriber** polls at a regular interval for a change in the block number.\n *\n * @category Providers\n */\nexport class PollingBlockSubscriber {\n #provider;\n #poller;\n #interval;\n #zone;\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 * @ignore\n */\n constructor(provider, zone) {\n this.#provider = provider;\n this.#zone = zone;\n this.#poller = null;\n this.#interval = 4000;\n this.#blockNumber = -2;\n }\n /**\n * The polling interval.\n *\n * @returns {number} The current polling interval.\n */\n get pollingInterval() {\n return this.#interval;\n }\n /**\n * Sets the polling interval.\n *\n * @param {number} value - The new polling interval.\n */\n set pollingInterval(value) {\n this.#interval = value;\n }\n /**\n * Polls for new blocks.\n *\n * @ignore\n * @returns {Promise} A promise that resolves when polling is complete.\n */\n async #poll() {\n try {\n const blockNumber = await this.#provider.getBlockNumber(toShard(this.#zone));\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', this.#zone, 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 }\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 /**\n * Starts the polling process.\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 /**\n * Stops the polling process.\n */\n stop() {\n if (!this.#poller) {\n return;\n }\n this.#provider._clearTimeout(this.#poller);\n this.#poller = null;\n }\n /**\n * Pauses the polling process.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused.\n */\n pause(dropWhilePaused) {\n this.stop();\n if (dropWhilePaused) {\n this.#blockNumber = -2;\n }\n }\n /**\n * Resumes the polling process.\n */\n resume() {\n this.start();\n }\n}\n/**\n * An **OnBlockSubscriber** can be sub-classed, with a {@link OnBlockSubscriber._poll | **_poll**} implementation which\n * will be called on every new block.\n *\n * @category Providers\n */\nexport class OnBlockSubscriber {\n #provider;\n #poll;\n #running;\n #zone;\n /**\n * Create a new **OnBlockSubscriber** attached to `provider`.\n *\n * @ignore\n */\n constructor(provider, zone) {\n this.#provider = provider;\n this.#zone = zone;\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 * @ignore\n * @param {number} blockNumber - The block number.\n * @param {AbstractProvider} provider - The provider.\n * @returns {Promise} A promise that resolves when the poll is complete.\n * @throws {Error} If the method is not overridden by a subclass.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _poll(blockNumber, provider) {\n throw new Error('sub-classes must override this');\n }\n /**\n * Starts the subscriber.\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, this.#zone);\n }\n /**\n * Stops the subscriber.\n */\n stop() {\n if (!this.#running) {\n return;\n }\n this.#running = false;\n this.#provider.off('block', this.#poll, this.#zone);\n }\n /**\n * Pauses the subscriber.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pause(dropWhilePaused) {\n this.stop();\n }\n /**\n * Resumes the subscriber.\n */\n resume() {\n this.start();\n }\n}\n/**\n * @ignore\n */\nexport class PollingOrphanSubscriber extends OnBlockSubscriber {\n #filter;\n /**\n * Create a new **PollingOrphanSubscriber** attached to `provider`, listening for `filter`.\n *\n * @ignore\n */\n constructor(provider, filter, zone) {\n super(provider, zone);\n this.#filter = copy(filter);\n }\n /**\n * Polls for orphaned blocks.\n *\n * @ignore\n * @param {number} blockNumber - The block number.\n * @param {AbstractProvider} provider - The provider.\n * @returns {Promise} A promise that resolves when the poll is complete.\n * @throws {Error} If the method is not implemented.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 hash for its receipt.\n *\n * @category Providers\n */\nexport class PollingTransactionSubscriber extends OnBlockSubscriber {\n #hash;\n /**\n * Create a new **PollingTransactionSubscriber** attached to `provider`, listening for `hash`.\n *\n * @ignore\n */\n constructor(provider, hash, zone) {\n super(provider, zone);\n this.#hash = hash;\n }\n /**\n * Polls for the transaction receipt.\n *\n * @ignore\n * @param {number} blockNumber - The block number.\n * @param {AbstractProvider} provider - The provider.\n * @returns {Promise} A promise that resolves when the poll is complete.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _poll(blockNumber, provider) {\n const tx = await provider.getTransactionReceipt(this.#hash);\n if (tx) {\n provider.emit(this.#hash, toZone(this.#hash.slice(0, 4)), tx);\n }\n }\n}\n/**\n * A **PollingEventSubscriber** will poll for a given filter for its logs.\n *\n * @category Providers\n */\nexport class PollingEventSubscriber {\n #provider;\n #filter;\n #poller;\n #running;\n #blockNumber;\n #zone;\n /**\n * Create a new **PollingEventSubscriber** attached to `provider`, listening for `filter`.\n *\n * @ignore\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 const zone = getZoneFromEventFilter(this.#filter);\n if (zone) {\n this.#zone = zone;\n }\n else {\n throw new Error('Unable to determine zone for event filter');\n }\n }\n /**\n * Polls for logs based on the filter.\n *\n * @ignore\n * @param {number} blockNumber - The block number.\n * @returns {Promise} A promise that resolves when the poll is complete.\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, getZoneFromNodeLocation(this.#filter.nodeLocation), 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 /**\n * Starts the subscriber.\n */\n start() {\n if (this.#running) {\n return;\n }\n this.#running = true;\n if (this.#blockNumber === -2) {\n this.#provider.getBlockNumber(toShard(this.#zone)).then((blockNumber) => {\n this.#blockNumber = blockNumber;\n });\n }\n this.#provider.on('block', this.#poller, this.#zone);\n }\n /**\n * Stops the subscriber.\n */\n stop() {\n if (!this.#running) {\n return;\n }\n this.#running = false;\n this.#provider.off('block', this.#poller, this.#zone);\n }\n /**\n * Pauses the subscriber.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused.\n */\n pause(dropWhilePaused) {\n this.stop();\n if (dropWhilePaused) {\n this.#blockNumber = -2;\n }\n }\n /**\n * Resumes the subscriber.\n */\n resume() {\n this.start();\n }\n}\n//# sourceMappingURL=subscriber-polling.js.map","/**\n * The available providers should suffice for most developers purposes, but the\n * {@link AbstractProvider | **AbstractProvider**} class has many features which enable sub-classing it for specific\n * purposes.\n */\n/**\n * Event coalescence When we register an event with an async value (e.g. address is a Signer), we need to add it\n * immediately for the Event API, but also 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 of Signer to address so we can sync respond\n * to listenerCount.\n */\nimport { computeAddress, resolveAddress, formatMixedCaseChecksumAddress } from '../address/index.js';\nimport { Shard, toShard, toZone } from '../constants/index.js';\nimport { hexlify, isHexString, getBigInt, getBytes, getNumber, makeError, assert, assertArgument, FetchRequest, toQuantity, defineProperties, EventPayload, resolveProperties, } from '../utils/index.js';\nimport { decodeProtoTransaction } from '../encoding/index.js';\nimport { formatBlock, formatLog, formatTransactionReceipt, formatTransactionResponse } from './format.js';\nimport { Network } from './network.js';\nimport { copyRequest, Block, FeeData, Log, TransactionReceipt, addressFromTransactionRequest, QuaiTransactionResponse, QiTransactionResponse, } from './provider.js';\nimport { QiTransaction, QuaiTransaction } from '../transaction/index.js';\nimport { PollingBlockSubscriber, PollingEventSubscriber, PollingOrphanSubscriber, PollingTransactionSubscriber, } from './subscriber-polling.js';\nimport { getNodeLocationFromZone, getZoneFromNodeLocation } from '../utils/shards.js';\nimport { fromShard } from '../constants/shards.js';\n/**\n * Constants\n */\nconst BN_2 = BigInt(2);\n/**\n * Check if a value is a Promise.\n *\n * @param {any} value - The value to check.\n * @returns {boolean} True if the value is a Promise, false otherwise.\n */\nfunction isPromise(value) {\n return value && typeof value.then === 'function';\n}\n/**\n * Get a tag string based on a prefix and value.\n *\n * @param {string} prefix - The prefix for the tag.\n * @param {any} value - The value to include in the tag.\n * @returns {string} The generated tag.\n */\nfunction getTag(prefix, value) {\n return (prefix +\n ':' +\n 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 any additional management, such as `\"debug\"`\n * which only requires emit in synchronous event loop triggered calls.\n *\n * @category Providers\n */\nexport class UnmanagedSubscriber {\n /**\n * The name of the event.\n */\n name;\n /**\n * Create a new UnmanagedSubscriber with `name`.\n *\n * @param {string} name - The name of the event.\n */\n constructor(name) {\n defineProperties(this, { name });\n }\n start() { }\n stop() { }\n // todo `dropWhilePaused` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pause(dropWhilePaused) { }\n resume() { }\n}\n/**\n * Create a deep copy of a value.\n *\n * @param {T} value - The value to copy.\n * @returns {T} The copied value.\n */\nfunction copy(value) {\n return JSON.parse(JSON.stringify(value));\n}\n/**\n * Remove duplicates and sort an array of strings.\n *\n * @param {string[]} items - The array of strings.\n * @returns {string[]} The concisified array.\n */\nfunction concisify(items) {\n items = Array.from(new Set(items).values());\n items.sort();\n return items;\n}\n// todo `provider` is not used, remove or re-write\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nasync function getSubscription(_event, zone) {\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 if (_event === 'debug') {\n return { type: _event, tag: _event };\n }\n switch (_event) {\n case 'block':\n case 'pending':\n if (!zone) {\n throw new Error('zone is required for block and pending events');\n }\n return { type: 'block', tag: _event, zone };\n case 'error':\n case 'finalized':\n case 'network':\n case 'safe': {\n return { type: _event, tag: _event };\n }\n }\n }\n if (isHexString(_event, 32)) {\n const hash = _event.toLowerCase();\n zone = toZone(hash.slice(0, 4));\n return { type: 'transaction', tag: getTag('tx', { hash }), hash, zone };\n }\n if (_event.orphan) {\n const event = _event;\n if (!zone) {\n const hash = event.hash ||\n event.tx.hash ||\n event.other?.hash ||\n event.log.transactionHash ||\n null;\n if (hash == null) {\n throw new Error('orphan event must specify a hash');\n }\n zone = toZone(hash.slice(0, 4));\n }\n // @todo Should lowercase and whatnot things here instead of copy...\n return { type: 'orphan', tag: getTag('orphan', event), filter: copy(event), zone };\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.nodeLocation) {\n filter.nodeLocation = event.nodeLocation;\n }\n if (event.address) {\n const addresses = [];\n const promises = [];\n const addAddress = (addr) => {\n if (isHexString(addr)) {\n addresses.push(formatMixedCaseChecksumAddress(addr));\n }\n else {\n promises.push((async () => {\n addresses.push(formatMixedCaseChecksumAddress(await resolveAddress(addr)));\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 if (!zone) {\n zone = toZone(addresses[0].slice(0, 4));\n }\n filter.address = concisify(addresses.map((a) => a.toLowerCase()));\n if (!filter.nodeLocation) {\n filter.nodeLocation = getNodeLocationFromZone(zone);\n }\n }\n else {\n if (!zone) {\n throw new Error('zone is required for event');\n }\n }\n return { filter, tag: getTag('event', filter), type: 'event', zone };\n }\n assertArgument(false, 'unknown ProviderEvent', 'event', _event);\n}\n/**\n * Get the current time in milliseconds.\n *\n * @returns {number} The current time in milliseconds.\n */\nfunction getTime() {\n return new Date().getTime();\n}\nconst defaultOptions = {\n cacheTimeout: 250,\n pollingInterval: 4000,\n usePathing: false,\n};\n/**\n * An **AbstractProvider** provides a base class for other sub-classes to implement the {@link Provider | **Provider**}\n * API by normalizing input arguments and formatting output results as well as tracking events for consistent behaviour\n * on an eventually-consistent network.\n *\n * @category Providers\n */\nexport class AbstractProvider {\n /**\n * @ignore\n */\n _urlMap;\n #connect;\n #subs;\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 #options;\n _initFailed;\n initResolvePromise;\n initRejectPromise;\n initPromise;\n /**\n * Create a new **AbstractProvider** connected to `network`, or use the various network detection capabilities to\n * discover the {@link Network | **Network**} if necessary.\n *\n * @param _network - The network to connect to, or `\"any\"` to\n * @param options - The options to configure the provider.\n */\n constructor(_network, options) {\n this._initFailed = false;\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(() => {\n this.emit('network', undefined, network, null);\n }, 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.#pausedState = null;\n this.#destroyed = false;\n this.#nextTimer = 1;\n this.#timers = new Map();\n this.#connect = [];\n this._urlMap = new Map();\n this.initResolvePromise = null;\n this.initRejectPromise = null;\n this.initPromise = new Promise((resolve, reject) => {\n this.initResolvePromise = resolve;\n this.initRejectPromise = reject;\n });\n }\n /**\n * Initialize the URL map with the provided URLs.\n *\n * @param {U} urls - The URLs to initialize the map with.\n * @returns {Promise} A promise that resolves when the map is initialized.\n */\n async initialize(urls) {\n try {\n const primeSuffix = this.#options.usePathing ? `/${fromShard(Shard.Prime, 'nickname')}` : ':9001';\n if (urls instanceof FetchRequest) {\n urls.url = urls.url.split(':')[0] + ':' + urls.url.split(':')[1] + primeSuffix;\n this._urlMap.set(Shard.Prime, urls);\n this.#connect.push(urls);\n const shards = await this.getRunningLocations();\n shards.forEach((shard) => {\n const port = 9200 + 20 * shard[0] + shard[1];\n const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);\n const shardSuffix = this.#options.usePathing ? `/${fromShard(shardEnum, 'nickname')}` : `:${port}`;\n this._urlMap.set(shardEnum, new FetchRequest(urls.url.split(':')[0] + ':' + urls.url.split(':')[1] + shardSuffix));\n });\n return;\n }\n if (Array.isArray(urls)) {\n for (const url of urls) {\n const primeUrl = url.split(':')[0] + ':' + url.split(':')[1] + primeSuffix;\n const primeConnect = new FetchRequest(primeUrl);\n this._urlMap.set(Shard.Prime, primeConnect);\n this.#connect.push(primeConnect);\n const shards = await this.getRunningLocations();\n shards.forEach((shard) => {\n const port = 9200 + 20 * shard[0] + shard[1];\n const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);\n const shardSuffix = this.#options.usePathing\n ? `/${fromShard(shardEnum, 'nickname')}`\n : `:${port}`;\n this._urlMap.set(toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`), new FetchRequest(url.split(':')[0] + ':' + url.split(':')[1] + shardSuffix));\n });\n }\n }\n if (this.initResolvePromise)\n this.initResolvePromise();\n }\n catch (error) {\n this._initFailed = true;\n console.log('Error initializing URL map:', error);\n if (this.initRejectPromise)\n this.initRejectPromise(error);\n }\n }\n /**\n * Get the list of connected FetchRequests.\n *\n * @returns {FetchRequest[]} The list of connected FetchRequests.\n */\n get connect() {\n return this.#connect;\n }\n /**\n * Get the zone from an address.\n *\n * @param {AddressLike} _address - The address to get the zone from.\n * @returns {Promise} A promise that resolves to the zone.\n */\n async zoneFromAddress(_address) {\n const address = this._getAddress(_address);\n return toZone((await address).slice(0, 4));\n }\n /**\n * Get the shard from a hash.\n *\n * @param {string} hash - The hash to get the shard from.\n * @returns {Shard} The shard.\n */\n shardFromHash(hash) {\n return toShard(hash.slice(0, 4));\n }\n /**\n * Get the zone from a hash.\n *\n * @param {string} hash - The hash to get the zone from.\n * @returns {Zone} The zone.\n */\n zoneFromHash(hash) {\n return toZone(hash.slice(0, 4));\n }\n /**\n * Get the latest Quai rate for a zone.\n *\n * @param {Zone} zone - The zone to get the rate for.\n * @param {number} [amt=1] - The amount to get the rate for. Default is `1`\n * @returns {Promise} A promise that resolves to the latest Quai rate.\n */\n async getLatestQuaiRate(zone, amt = 1) {\n const blockNumber = await this.getBlockNumber(toShard(zone));\n return this.getQuaiRateAtBlock(zone, blockNumber, amt);\n }\n /**\n * Get the Quai rate at a specific block.\n *\n * @param {Zone} zone - The zone to get the rate for.\n * @param {BlockTag} blockTag - The block tag to get the rate at.\n * @param {number} [amt=1] - The amount to get the rate for. Default is `1`\n * @returns {Promise} A promise that resolves to the Quai rate at the specified block.\n */\n async getQuaiRateAtBlock(zone, blockTag, amt = 1) {\n let resolvedBlockTag = this._getBlockTag(toShard(zone), blockTag);\n if (typeof resolvedBlockTag !== 'string') {\n resolvedBlockTag = await resolvedBlockTag;\n }\n return await this.#perform({\n method: 'getQuaiRateAtBlock',\n blockTag: resolvedBlockTag,\n amt,\n zone: zone,\n });\n }\n /**\n * Get the protocol expansion number.\n *\n * @returns {Promise} A promise that resolves to the protocol expansion number.\n */\n async getProtocolExpansionNumber() {\n return await this.#perform({\n method: 'getProtocolExpansionNumber',\n });\n }\n /**\n * Get the latest Qi rate for a zone.\n *\n * @param {Zone} zone - The zone to get the rate for.\n * @param {number} [amt=1] - The amount to get the rate for. Default is `1`\n * @returns {Promise} A promise that resolves to the latest Qi rate.\n */\n async getLatestQiRate(zone, amt = 1) {\n const blockNumber = await this.getBlockNumber(toShard(zone));\n return this.getQiRateAtBlock(zone, blockNumber, amt);\n }\n /**\n * Get the Qi rate at a specific block.\n *\n * @param {Zone} zone - The zone to get the rate for.\n * @param {BlockTag} blockTag - The block tag to get the rate at.\n * @param {number} [amt=1] - The amount to get the rate for. Default is `1`\n * @returns {Promise} A promise that resolves to the Qi rate at the specified block.\n */\n async getQiRateAtBlock(zone, blockTag, amt = 1) {\n let resolvedBlockTag = this._getBlockTag(toShard(zone), blockTag);\n if (typeof resolvedBlockTag !== 'string') {\n resolvedBlockTag = await resolvedBlockTag;\n }\n return await this.#perform({\n method: 'getQiRateAtBlock',\n blockTag: resolvedBlockTag,\n amt,\n zone: zone,\n });\n }\n /**\n * Get the polling interval.\n *\n * @returns {number} The polling interval.\n */\n get pollingInterval() {\n return this.#options.pollingInterval;\n }\n /**\n * Returns `this`, to allow an **AbstractProvider** to implement the [Contract Runner](../classes/ContractRunner)\n * interface.\n *\n * @returns {this} The provider instance.\n */\n get provider() {\n return this;\n }\n /**\n * Shares multiple identical requests made during the same 250ms.\n *\n * @ignore\n * @param {PerformActionRequest} req - The request to perform.\n * @returns {Promise} A promise that resolves to the result of the operation.\n */\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 || tag.includes('pending') || tag.includes('latest')) {\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 * Provides the opportunity for a sub-class to wrap a block before returning it, to add additional properties or an\n * alternate sub-class of {@link Block | **Block**}.\n *\n * @ignore\n * @param {BlockParams} value - The block to wrap.\n * @param {Network} network - The network the block was on.\n * @returns {Block} The wrapped block.\n */\n // @todo `network` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _wrapBlock(value, network) {\n // Handle known node by -> remove null values from the number array\n value.header.number = Array.isArray(value.header.number)\n ? value.header.number.filter((n) => n != null)\n : value.header.number;\n return new Block(formatBlock(value), this);\n }\n /**\n * Provides the opportunity for a sub-class to wrap a log before returning it, to add additional properties or an\n * alternate sub-class of {@link Log | **Log**}.\n *\n * @ignore\n * @param {LogParams} value - The log to wrap.\n * @param {Network} network - The network the log was on.\n * @returns {Log} The wrapped log.\n */\n // @todo `network` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 receipt before returning it, to add additional\n * properties or an {@link TransactionReceipt | **TransactionReceipt**}.\n *\n * @ignore\n * @param {TransactionReceiptParams} value - The transaction receipt to wrap.\n * @param {Network} network - The network the transaction was on.\n * @returns {TransactionReceipt} The wrapped transaction receipt.\n */\n // @todo `network` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _wrapTransactionReceipt(value, network) {\n const formattedReceipt = formatTransactionReceipt(value);\n return new TransactionReceipt(formattedReceipt, this);\n }\n /**\n * Provides the opportunity for a sub-class to wrap a transaction response before returning it, to add additional\n * properties or an alternate sub-class of {@link TransactionResponse | **TransactionResponse**}.\n *\n * @ignore\n * @param {TransactionResponseParams} tx - The transaction response to wrap.\n * @param {Network} network - The network the transaction was on.\n * @returns {TransactionResponse} The wrapped transaction response.\n */\n // TODO: `newtork` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _wrapTransactionResponse(tx, network) {\n if ('from' in tx) {\n return new QuaiTransactionResponse(formatTransactionResponse(tx), this);\n }\n else {\n return new QiTransactionResponse(formatTransactionResponse(tx), this);\n }\n }\n /**\n * Resolves to the Network, forcing a network detection using whatever technique the sub-class requires.\n *\n * Sub-classes **must** override this.\n *\n * @ignore\n * @param {Shard} [shard] - The shard to use for the network detection.\n * @returns {Promise} A promise resolving to the network.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 methods sanitizes and normalizes the values\n * passed into this.\n *\n * Sub-classes **must** override this.\n *\n * @ignore\n * @param {PerformActionRequest} req - The request to perform.\n * @returns {Promise} A promise resolving to the result of the operation.\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(shard) {\n const blockNumber = getNumber(await this.#perform({ method: 'getBlockNumber', shard: shard }), '%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 {@link Addressable | **Addressable**} objects and\n * returning if already an address.\n *\n * @ignore\n * @param {AddressLike} address - The address to normalize.\n * @returns {string | Promise} The normalized address.\n */\n _getAddress(address) {\n return resolveAddress(address);\n }\n /**\n * Returns or resolves to a valid block tag for `blockTag`, resolving negative values and returning if already a\n * valid block tag.\n *\n * @ignore\n * @param {Shard} [shard] - The shard to use for the block tag.\n * @param {BlockTag} [blockTag] - The block tag to normalize.\n * @returns {string | Promise} A promise that resolves to a valid block tag.\n */\n _getBlockTag(shard, 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(shard).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 {@link Addressable | **Addressable**} object and\n * returning if already a valid filter.\n *\n * @ignore\n * @param {Filter | FilterByBlockHash} filter - The filter to normalize.\n * @returns {PerformActionFilter | Promise} A promise that resolves to a valid 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, nodeLocation) => {\n let address = undefined;\n switch (_address.length) {\n case 0:\n 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 if (nodeLocation) {\n filter.nodeLocation = nodeLocation;\n }\n return filter;\n };\n // Addresses could be async (Addressables)\n const 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 const zone = getZoneFromNodeLocation(filter.nodeLocation);\n let fromBlock = undefined;\n if ('fromBlock' in filter) {\n fromBlock = this._getBlockTag(toShard(zone), filter.fromBlock);\n }\n let toBlock = undefined;\n if ('toBlock' in filter) {\n toBlock = this._getBlockTag(toShard(zone), filter.toBlock);\n }\n let nodeLocation = undefined;\n if (filter.nodeLocation) {\n nodeLocation = filter.nodeLocation;\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, nodeLocation]).then((result) => {\n return resolve(result[0], result[1], result[2], result[3]);\n });\n }\n return resolve(address, fromBlock, toBlock, nodeLocation);\n }\n /**\n * Returns or resovles to a transaction for `request`, resolving any {@link Addressable | **Addressable**} and\n * returning if already a valid transaction.\n *\n * @ignore\n * @param {PerformActionTransaction} _request - The transaction to normalize.\n * @returns {PerformActionTransaction | Promise} A promise that resolves to a valid\n * transaction.\n */\n _getTransactionRequest(_request) {\n const request = copyRequest(_request);\n const promises = [];\n ['to', 'from', 'inputs', 'outputs'].forEach((key) => {\n if (request[key] == null) {\n return;\n }\n const addr = Array.isArray(request[key])\n ? 'address' in request[key][0]\n ? request[key].map((it) => it.address)\n : request[key].map((it) => computeAddress(it.pubkey))\n : resolveAddress(request[key]);\n if (isPromise(addr)) {\n if (Array.isArray(addr)) {\n for (let i = 0; i < addr.length; i++) {\n promises.push((async function () {\n request[key][i].address = await addr[i];\n })());\n }\n }\n else {\n promises.push((async function () {\n request[key] = await addr;\n })());\n }\n }\n else {\n request[key] = addr;\n }\n });\n if (request.blockTag != null) {\n const blockTag = this._getBlockTag(toShard(request.chainId.toString()), request.blockTag);\n if (isPromise(blockTag)) {\n promises.push((async function () {\n request.blockTag = await blockTag;\n })());\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', undefined, 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', undefined, 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 _getRunningLocations(shard, now) {\n now = now ? now : false;\n return await this.#perform(shard\n ? { method: 'getRunningLocations', shard: shard, now: now }\n : { method: 'getRunningLocations', now: now });\n }\n async getRunningLocations(shard) {\n return await this._getRunningLocations(shard);\n }\n async getProtocolTrieExpansionCount(shard) {\n return await this.#perform({ method: 'getProtocolTrieExpansionCount', shard: shard });\n }\n async getFeeData(zone, txType = true) {\n const getFeeDataFunc = async () => {\n const { gasPrice, priorityFee } = await resolveProperties({\n gasPrice: (async () => {\n try {\n const value = await this.#perform({ method: 'getGasPrice', txType, zone: zone });\n return getBigInt(value, '%response');\n }\n catch (error) {\n console.log(error);\n }\n return null;\n })(),\n priorityFee: (async () => {\n try {\n const value = txType\n ? await this.#perform({ method: 'getMaxPriorityFeePerGas', zone: zone })\n : 0;\n return getBigInt(value, '%response');\n // eslint-disable-next-line no-empty\n }\n catch (error) { }\n return null;\n })(),\n });\n if (gasPrice == null) {\n throw new Error('could not determine gasPrice');\n }\n let maxFeePerGas = null;\n let maxPriorityFeePerGas = null;\n // These are the recommended EIP-1559 heuristics for fee data\n maxPriorityFeePerGas = priorityFee != null ? priorityFee : BigInt('1000000000');\n maxFeePerGas = gasPrice * BN_2 + maxPriorityFeePerGas;\n return new FeeData(gasPrice, maxFeePerGas, 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 const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx));\n return getBigInt(await this.#perform({\n method: 'estimateGas',\n transaction: tx,\n zone: zone,\n }), '%response');\n }\n // TODO: `attempt` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async #call(tx, blockTag, attempt, zone) {\n // This came in as a PerformActionTransaction, so to/from are safe; we can cast\n const transaction = copyRequest(tx);\n return hexlify(await this._perform({ method: 'call', transaction, blockTag, zone }));\n }\n // TODO: `shard` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async #checkNetwork(promise, shard) {\n const { value } = await resolveProperties({\n network: this.getNetwork(),\n value: promise,\n });\n return value;\n }\n async call(_tx) {\n const zone = await this.zoneFromAddress(addressFromTransactionRequest(_tx));\n const shard = toShard(zone);\n const { tx, blockTag } = await resolveProperties({\n tx: this._getTransactionRequest(_tx),\n blockTag: this._getBlockTag(shard, _tx.blockTag),\n });\n return await this.#checkNetwork(this.#call(tx, blockTag, -1, zone), shard);\n }\n // Account\n async #getAccountValue(request, _address, _blockTag) {\n let address = this._getAddress(_address);\n const zone = await this.zoneFromAddress(_address);\n const shard = toShard(zone);\n let blockTag = this._getBlockTag(shard, _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, zone: zone })), shard);\n }\n async getBalance(address, blockTag) {\n return getBigInt(await this.#getAccountValue({ method: 'getBalance' }, address, blockTag), '%response');\n }\n async getOutpointsByAddress(address) {\n const outpoints = await this.#getAccountValue({ method: 'getOutpointsByAddress' }, address, 'latest');\n const outpointsArray = Array.isArray(outpoints) ? outpoints : [];\n return outpointsArray.map((outpoint) => ({\n txhash: outpoint.Txhash,\n index: outpoint.Index,\n denomination: outpoint.Denomination,\n }));\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 async getPendingHeader() {\n return await this.#perform({ method: 'getPendingHeader' });\n }\n async getTxPoolContent(zone) {\n return await this.#perform({ method: 'getTxPoolContent', zone: zone });\n }\n async txPoolInspect(zone) {\n return await this.#perform({ method: 'txPoolInspect', zone: zone });\n }\n // Write\n async broadcastTransaction(zone, signedTx) {\n const type = decodeProtoTransaction(getBytes(signedTx)).type;\n const { blockNumber, hash, network } = await resolveProperties({\n blockNumber: this.getBlockNumber(toShard(zone)),\n hash: this._perform({\n method: 'broadcastTransaction',\n signedTransaction: signedTx,\n zone: zone,\n }),\n network: this.getNetwork(),\n });\n const tx = type == 2 ? QiTransaction.from(signedTx) : QuaiTransaction.from(signedTx);\n this.#validateTransactionHash(tx.hash || '', hash);\n return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber);\n }\n #validateTransactionHash(computedHash, nodehash) {\n if (computedHash !== nodehash) {\n throw new Error('Transaction hash mismatch');\n }\n }\n validateUrl(url) {\n const urlPattern = /^(https?):\\/\\/[a-zA-Z0-9.-]+(:\\d+)?$/;\n if (!urlPattern.test(url)) {\n let errorMessage = 'Invalid URL: ';\n if (!/^https?:\\/\\//.test(url)) {\n errorMessage += 'URL must start with http:// or https://. ';\n }\n if (url.endsWith('/')) {\n errorMessage += 'URL should not end with a /. ';\n }\n if (/\\/[^/]+/.test(url)) {\n errorMessage += 'URL should not contain a path, query string, or fragment. ';\n }\n throw new Error(errorMessage.trim());\n }\n }\n async #getBlock(shard, block, includeTransactions) {\n if (isHexString(block, 32)) {\n return await this.#perform({\n method: 'getBlock',\n blockHash: block,\n includeTransactions,\n shard: shard,\n });\n }\n let blockTag = this._getBlockTag(shard, block);\n if (typeof blockTag !== 'string') {\n blockTag = await blockTag;\n }\n return await this.#perform({\n method: 'getBlock',\n blockTag,\n includeTransactions,\n shard: shard,\n });\n }\n // Queries\n async getBlock(shard, block, prefetchTxs) {\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#getBlock(shard, block, !!prefetchTxs),\n });\n if (params == null) {\n return null;\n }\n return this._wrapBlock(params, network);\n }\n async getTransaction(hash) {\n const zone = toZone(this.shardFromHash(hash));\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#perform({ method: 'getTransaction', hash, zone: zone }),\n });\n if (params == null) {\n return null;\n }\n return this._wrapTransactionResponse(params, network);\n }\n async getTransactionReceipt(hash) {\n const zone = toZone(this.shardFromHash(hash));\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#perform({ method: 'getTransactionReceipt', hash, zone: zone }),\n });\n if (params == null) {\n return null;\n }\n // Some backends did not backfill the effectiveGasPrice in to 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, zone: zone });\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 zone = toZone(this.shardFromHash(hash));\n const { result } = await resolveProperties({\n network: this.getNetwork(),\n result: this.#perform({ method: 'getTransactionResult', hash, zone: zone }),\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({\n method: 'getLogs',\n filter,\n zone: getZoneFromNodeLocation(filter.nodeLocation),\n }),\n });\n return params.map((p) => this._wrapLog(p, network));\n }\n /**\n * @ignore\n */\n // TODO: unsupported, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _getProvider(chainId) {\n assert(false, 'provider cannot connect to target network', 'UNSUPPORTED_OPERATION', {\n operation: '_getProvider()',\n });\n }\n async waitForTransaction(hash, _confirms, timeout) {\n const zone = this.zoneFromHash(hash);\n const confirms = _confirms != null ? _confirms : 1;\n if (confirms === 0) {\n return this.getTransactionReceipt(hash);\n }\n // eslint-disable-next-line no-async-promise-executor\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('Error occured while waiting for transaction:', error);\n }\n this.once('block', listener, zone);\n };\n if (timeout != null) {\n timer = setTimeout(() => {\n if (timer == null) {\n return;\n }\n timer = null;\n this.off('block', listener, zone);\n reject(makeError('timeout', 'TIMEOUT', { reason: 'timeout' }));\n }, timeout);\n }\n listener(await this.getBlockNumber(toShard(zone)));\n });\n }\n // TODO: not implemented yet\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async waitForBlock(shard, blockTag) {\n assert(false, 'not implemented yet', 'NOT_IMPLEMENTED', {\n operation: 'waitForBlock',\n });\n }\n /**\n * Clear a timer created using the {@link AbstractProvider._setTimeout | **_setTimeout**} method.\n *\n * @param {number} timerId - The ID of the timer to clear.\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` (in ms). If `timeout` is unspecified, then\n * `func` will execute in the next event loop.\n *\n * {@link AbstractProvider.pause | **Pausing**} the provider will pause any associated timers.\n *\n * @ignore\n * @ignore\n * @param {() => void} _func - The function to execute.\n * @param {number} [timeout] - The time to wait before executing `func`.\n * @returns {number} The ID of the timer.\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 * @ignore\n * @param {(s: Subscriber) => void} func - The function to perform.\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 implementations.\n *\n * @ignore\n * @param {Subscription} sub - The subscription to get the subscriber for.\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, sub.zone);\n subscriber.pollingInterval = this.pollingInterval;\n return subscriber;\n }\n //! TODO: implement this for quais\n // case \"safe\": 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, sub.zone);\n case 'orphan':\n return new PollingOrphanSubscriber(this, sub.filter, sub.zone);\n }\n throw new Error(`unsupported event: ${sub.type}`);\n }\n /**\n * If a {@link Subscriber | **Subscriber**} fails and needs to replace itself, this method may be used.\n *\n * For example, this is used for providers when using the `quai_getFilterChanges` method, which can return null if\n * state filters are not supported by the backend, allowing the Subscriber to swap in a `PollingEventSubscriber`.\n *\n * @ignore\n * @param {Subscriber} oldSub - The subscriber to replace.\n * @param {Subscriber} newSub - The new subscriber.\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, zone) {\n let sub = await getSubscription(event, zone);\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] }, zone);\n }\n return this.#subs.get(sub.tag) || null;\n }\n async #getSub(event, zone) {\n const subscription = await getSubscription(event, zone);\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: [], zone: subscription.zone };\n this.#subs.set(tag, sub);\n }\n return sub;\n }\n async on(event, listener, zone) {\n const sub = await this.#getSub(event, zone);\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, zone) {\n const sub = await this.#getSub(event, zone);\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, zone, ...args) {\n const sub = await this.#hasSub(event, args, zone);\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 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 // eslint-disable-next-line no-empty\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, zone) {\n const sub = await this.#hasSub(event, [], zone);\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, zone) {\n return await this.on(event, listener, zone);\n }\n // Alias for \"off\"\n async removeListener(event, listener, zone) {\n return this.off(event, listener, zone);\n }\n /**\n * If this provider has been destroyed using the {@link AbstractProvider.destroy | **destroy**} method.\n *\n * Once destroyed, all resources are reclaimed, internal event loops and timers are cleaned up and no further\n * requests may be sent to 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 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 not make any requests to the network, but that\n * is up to sub-classes to manage.\n *\n * Setting `paused = true` is identical to calling `.pause(false)`, which will buffer any events that occur while\n * paused until the provider is unpaused.\n *\n * @returns {boolean} Whether the provider is paused.\n */\n get paused() {\n return this.#pausedState != null;\n }\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 while paused are dropped, otherwise all events\n * will be emitted once the provider is unpaused.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop events while paused.\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}\n//# sourceMappingURL=abstract-provider.js.map","import { isError } from '../utils/index.js';\nimport { PollingEventSubscriber } from './subscriber-polling.js';\nimport { getZoneFromEventFilter } from './provider.js';\n/**\n * Deep copies an object.\n *\n * @param {any} obj - The object to copy.\n * @returns {any} A deep copy of the object.\n */\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 **Filter ID**. At this point the node dedicates\n * resources to the filter, so that periodic calls to follow up on the **Filter ID** will receive any events since the\n * last call.\n *\n * @category Providers\n */\nexport class FilterIdSubscriber {\n #provider;\n #filterIdPromise;\n #poller;\n #running;\n #network;\n #hault;\n zone;\n /**\n * @ignore Creates A new **FilterIdSubscriber** which will use {@link FilterIdSubscriber._subscribe | **_subscribe**}\n * and {@link FilterIdSubscriber._emitResults | **_emitResults**} to setup the subscription and provide the event\n * to the `provider`.\n * @param {JsonRpcApiProvider} provider - The provider to use.\n */\n constructor(provider, zone) {\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 this.zone = zone;\n }\n /**\n * Sub-classes **must** override this to begin the subscription.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @returns {Promise} A promise that resolves to the subscription ID.\n * @throws {Error} If the method is not overridden.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _subscribe(provider) {\n throw new Error('subclasses must override this');\n }\n /**\n * Sub-classes **must** override this to handle the events.\n *\n * @ignore\n * @param {AbstractProvider} provider - The provider to use.\n * @param {any[]} result - The results to handle.\n * @returns {Promise} A promise that resolves when the results are handled.\n * @throws {Error} If the method is not overridden.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _emitResults(provider, result) {\n throw new Error('subclasses must override this');\n }\n /**\n * Sub-classes **must** override this to handle recovery on errors.\n *\n * @ignore\n * @param {AbstractProvider} provider - The provider to use.\n * @returns {Subscriber} The recovered subscriber.\n * @throws {Error} If the method is not overridden.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _recover(provider) {\n throw new Error('subclasses must override this');\n }\n /**\n * Polls for new events.\n *\n * @ignore\n * @param {number} blockNumber - The block number to poll from.\n * @returns {Promise} A promise that resolves when polling is complete.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 !== 'quai_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('chain changed');\n }\n if (this.#hault) {\n return;\n }\n const result = await this.#provider.send('quai_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, this.zone);\n }\n /**\n * Tears down the subscription.\n *\n * @ignore\n */\n #teardown() {\n const filterIdPromise = this.#filterIdPromise;\n if (filterIdPromise) {\n this.#filterIdPromise = null;\n filterIdPromise.then((filterId) => {\n this.#provider.send('quai_uninstallFilter', [filterId]);\n });\n }\n }\n /**\n * Starts the subscriber.\n */\n start() {\n if (this.#running) {\n return;\n }\n this.#running = true;\n this.#poll(-2);\n }\n /**\n * Stops the subscriber.\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, this.zone);\n }\n /**\n * Pauses the subscriber.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop the subscription while paused.\n */\n pause(dropWhilePaused) {\n if (dropWhilePaused) {\n this.#teardown();\n }\n this.#provider.off('block', this.#poller, this.zone);\n }\n /**\n * Resumes the subscriber.\n */\n resume() {\n this.start();\n }\n}\n/**\n * A **FilterIdSubscriber** for receiving contract events.\n *\n * @category Providers\n */\nexport class FilterIdEventSubscriber extends FilterIdSubscriber {\n #event;\n /**\n * @ignore Creates A new **FilterIdEventSubscriber** attached to `provider` listening for `filter`.\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @param {EventFilter} filter - The event filter to use.\n */\n constructor(provider, filter) {\n const zone = getZoneFromEventFilter(filter);\n if (zone == null) {\n throw new Error('Unable to determine zone for event filter');\n }\n super(provider, zone);\n this.#event = copy(filter);\n }\n /**\n * Recovers the subscriber.\n *\n * @ignore\n * @param {AbstractProvider} provider - The provider to use.\n * @returns {Subscriber} The recovered subscriber.\n */\n _recover(provider) {\n return new PollingEventSubscriber(provider, this.#event);\n }\n /**\n * Subscribes to the event filter.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @returns {Promise} A promise that resolves to the subscription ID.\n */\n async _subscribe(provider) {\n const filterId = await provider.send('quai_newFilter', [this.#event]);\n return filterId;\n }\n /**\n * Emits the results of the event filter.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @param {any[]} results - The results to emit.\n * @returns {Promise} A promise that resolves when the results are emitted.\n */\n async _emitResults(provider, results) {\n for (const result of results) {\n provider.emit(this.#event, this.zone, provider._wrapLog(result, provider._network));\n }\n }\n}\n/**\n * A **FilterIdSubscriber** for receiving pending transactions events.\n *\n * @category Providers\n */\nexport class FilterIdPendingSubscriber extends FilterIdSubscriber {\n /**\n * Subscribes to the pending transactions filter.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @returns {Promise} A promise that resolves to the subscription ID.\n */\n async _subscribe(provider) {\n return await provider.send('quai_newPendingTransactionFilter', []);\n }\n /**\n * Emits the results of the pending transactions filter.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @param {any[]} results - The results to emit.\n * @returns {Promise} A promise that resolves when the results are emitted.\n */\n async _emitResults(provider, results) {\n for (const result of results) {\n provider.emit('pending', this.zone, result);\n }\n }\n}\n//# sourceMappingURL=subscriber-filterid.js.map","/**\n * One of the most common ways to interact with the blockchain is by a node running a JSON-RPC interface which can be\n * connected to, based on the transport, using:\n *\n * - HTTP or HTTPS - {@link JsonRpcProvider | **JsonRpcProvider**}\n * - WebSocket - {@link WebSocketProvider | **WebSocketProvider**}\n * - IPC - {@link IpcSocketProvider | **IpcSocketProvider**}\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 { accessListify } from '../transaction/index.js';\nimport { getBigInt, hexlify, isHexString, toQuantity, makeError, assert, assertArgument, isError, FetchRequest, defineProperties, resolveProperties, } from '../utils/index.js';\nimport { AbstractProvider, UnmanagedSubscriber } from './abstract-provider.js';\nimport { Network } from './network.js';\nimport { FilterIdEventSubscriber, FilterIdPendingSubscriber } from './subscriber-filterid.js';\nimport { Shard, toShard, toZone } from '../constants/index.js';\nimport { TypedDataEncoder } from '../hash/index.js';\nimport { AbstractSigner } from '../signers/index.js';\nimport { toUtf8Bytes } from '../encoding/index.js';\nimport { addressFromTransactionRequest, zoneFromHash } from './provider.js';\nconst Primitive = 'bigint,boolean,function,number,string,symbol'.split(/,/g);\n/**\n * Deeply copies a value.\n *\n * @ignore\n * @param {T} value - The value to copy.\n * @returns {T} The copied value.\n */\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}\n/**\n * Stalls execution for a specified duration.\n *\n * @ignore\n * @param {number} duration - The duration to stall in milliseconds.\n * @returns {Promise} A promise that resolves after the duration.\n */\nfunction stall(duration) {\n return new Promise((resolve) => {\n setTimeout(resolve, duration);\n });\n}\nconst defaultOptions = {\n staticNetwork: null,\n batchStallTime: 10,\n batchMaxSize: 1 << 20,\n batchMaxCount: 100,\n cacheTimeout: 250,\n usePathing: false,\n};\n// @TODO: Unchecked Signers\n/**\n * A signer that uses JSON-RPC to sign transactions and messages.\n *\n * @category Providers\n */\nexport class JsonRpcSigner extends AbstractSigner {\n address;\n /**\n * Creates a new JsonRpcSigner instance.\n *\n * @param {JsonRpcApiProvider} provider - The JSON-RPC provider.\n * @param {string} address - The address of the signer.\n */\n constructor(provider, address) {\n super(provider);\n address = getAddress(address);\n defineProperties(this, { address });\n }\n /**\n * Connects the signer to a provider.\n *\n * @param {null | Provider} provider - The provider to connect to.\n * @returns {Signer} The connected signer.\n * @throws {Error} If the signer cannot be reconnected.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n connect(provider) {\n assert(false, 'cannot reconnect JsonRpcSigner', 'UNSUPPORTED_OPERATION', {\n operation: 'signer.connect',\n });\n }\n /**\n * Gets the address of the signer.\n *\n * @returns {Promise} The address of the signer.\n */\n async getAddress() {\n return this.address;\n }\n /**\n * Populates a Quai transaction.\n *\n * @ignore\n * @param {QuaiTransactionRequest} tx - The transaction request.\n * @returns {Promise} The populated transaction.\n */\n async populateQuaiTransaction(tx) {\n return (await this.populateCall(tx));\n }\n /**\n * Sends an unchecked transaction.\n *\n * @ignore\n * @param {TransactionRequest} _tx - The transaction request.\n * @returns {Promise} The transaction hash.\n */\n async sendUncheckedTransaction(_tx) {\n const tx = deepCopy(_tx);\n const promises = [];\n if ('from' in tx) {\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);\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 quai_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);\n })());\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('quai_sendTransaction', [hexTx]);\n }\n /**\n * Sends a transaction.\n *\n * @param {TransactionRequest} tx - The transaction request.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the transaction cannot be sent.\n */\n async sendTransaction(tx) {\n const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx));\n // This cannot be mined any earlier than any recent block\n const blockNumber = await this.provider.getBlockNumber(toShard(zone));\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') ||\n isError(error, 'BAD_DATA') ||\n isError(error, 'NETWORK_ERROR') ||\n 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', zoneFromHash(hash), makeError('failed to fetch transation after sending (will try again)', 'UNKNOWN_ERROR', {\n error,\n }));\n }\n // Wait another 4 seconds\n this.provider._setTimeout(() => {\n checkTx();\n }, timeouts.pop() || 4000);\n };\n checkTx();\n });\n }\n /**\n * Signs a transaction.\n *\n * @param {TransactionRequest} _tx - The transaction request.\n * @returns {Promise} The signed transaction.\n * @throws {Error} If the transaction cannot be signed.\n */\n async signTransaction(_tx) {\n const tx = deepCopy(_tx);\n // QuaiTransactionRequest\n if ('from' in tx) {\n if (tx.from) {\n const from = await resolveAddress(tx.from);\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 }\n else {\n throw new Error('No QI signing implementation in provider-jsonrpc');\n }\n const hexTx = this.provider.getRpcTransaction(tx);\n return await this.provider.send('quai_signTransaction', [hexTx]);\n }\n /**\n * Signs a message.\n *\n * @param {string | Uint8Array} _message - The message to sign.\n * @returns {Promise} The signed message.\n */\n async signMessage(_message) {\n const message = typeof _message === 'string' ? toUtf8Bytes(_message) : _message;\n return await this.provider.send('personal_sign', [hexlify(message), this.address.toLowerCase()]);\n }\n /**\n * Signs typed data.\n *\n * @param {TypedDataDomain} domain - The domain of the typed data.\n * @param {Record} types - The types of the typed data.\n * @param {Record} _value - The value of the typed data.\n * @returns {Promise} The signed typed data.\n */\n async signTypedData(domain, types, _value) {\n const value = deepCopy(_value);\n return await this.provider.send('quai_signTypedData_v4', [\n this.address.toLowerCase(),\n JSON.stringify(TypedDataEncoder.getPayload(domain, types, value)),\n ]);\n }\n /**\n * Unlocks the account.\n *\n * @param {string} password - The password to unlock the account.\n * @returns {Promise} True if the account is unlocked, false otherwise.\n */\n async unlock(password) {\n return this.provider.send('personal_unlockAccount', [this.address.toLowerCase(), password, null]);\n }\n /**\n * Signs a message using the legacy method.\n *\n * @ignore\n * @param {string | Uint8Array} _message - The message to sign.\n * @returns {Promise} The signed message.\n */\n async _legacySignMessage(_message) {\n const message = typeof _message === 'string' ? toUtf8Bytes(_message) : _message;\n return await this.provider.send('quai_sign', [this.address.toLowerCase(), hexlify(message)]);\n }\n}\n/**\n * The JsonRpcApiProvider is an abstract class and **MUST** be sub-classed.\n *\n * It provides the base for all JSON-RPC-based Provider interaction.\n *\n * Sub-classing Notes:\n *\n * - A sub-class MUST override _send\n * - A sub-class MUST call the `_start()` method once connected\n *\n * @category Providers\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 /**\n * Schedules the draining of the payload queue.\n *\n * @ignore\n */\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 payloadMap = new Map();\n const nowPayloadMap = new Map();\n for (let i = 0; i < batch.length; i++) {\n if (batch[i].now) {\n if (!nowPayloadMap.has(batch[i].shard)) {\n if (batch[i].payload != null) {\n nowPayloadMap.set(batch[i].shard, [batch[i].payload]);\n }\n }\n else {\n nowPayloadMap.get(batch[i].shard)?.push(batch[i].payload);\n }\n }\n else {\n if (!payloadMap.has(batch[i].shard)) {\n if (batch[i].payload != null) {\n payloadMap.set(batch[i].shard, [batch[i].payload]);\n }\n }\n else {\n payloadMap.get(batch[i].shard)?.push(batch[i].payload);\n }\n }\n }\n const rawResult = [];\n const processPayloads = async (key, value, now) => {\n const payload = value.length === 1 ? value[0] : value;\n const shard = key ? toShard(key) : Shard.Prime;\n const zone = shard.length < 4 ? undefined : toZone(shard);\n this.emit('debug', zone, { action: 'sendRpcPayload', payload });\n rawResult.push(await this._send(payload, shard, now));\n this.emit('debug', zone, { action: 'receiveRpcResult', payload });\n };\n await Promise.all(Array.from(nowPayloadMap)\n .map(async ([key, value]) => {\n await processPayloads(key, value, true);\n })\n .concat(Array.from(payloadMap).map(async ([key, value]) => {\n await processPayloads(key, value);\n })));\n const result = rawResult.flat();\n let lastZone;\n try {\n // Process results in batch order\n for (const { resolve, reject, payload, shard } of batch) {\n if (this.destroyed) {\n reject(makeError('provider destroyed; cancelled request', 'UNSUPPORTED_OPERATION', {\n operation: payload.method,\n }));\n continue;\n }\n if (shard) {\n lastZone = shard.length < 4 ? undefined : toZone(shard);\n }\n else {\n lastZone = undefined;\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,\n info: { payload },\n });\n this.emit('error', lastZone, error);\n reject(error);\n continue;\n }\n // The response is an error\n if ('error' in resp) {\n reject(this.getRpcError(payload, resp, shard));\n continue;\n }\n // All good; send the result\n resolve(resp.result);\n }\n }\n catch (error) {\n this.emit('debug', lastZone, { 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 /**\n * Creates a new JsonRpcApiProvider instance.\n *\n * @param {Networkish} [network] - The network to connect to.\n * @param {JsonRpcApiProviderOptions} [options] - The options for the provider.\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 * @ignore\n * @param {keyof JsonRpcApiProviderOptions} key - The option key.\n * @returns {JsonRpcApiProviderOptions[key]} The option value.\n */\n _getOption(key) {\n return this.#options[key];\n }\n /**\n * Gets the {@link Network | **Network**} this provider has committed to. On each call, the network is detected, and\n * if it has changed, the call will reject.\n *\n * @ignore\n * @returns {Network} The network.\n * @throws {Error} If the network is not available yet.\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, and should generally call `super._perform` as a\n * fallback.\n *\n * @ignore\n * @param {PerformActionRequest} req - The request to perform.\n * @returns {Promise} The result of the request.\n * @throws {Error} If the request fails.\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 !== 'getRunningLocations') {\n await this.initPromise;\n }\n if (req.method === 'call' || req.method === 'estimateGas') {\n const tx = req.transaction;\n if (tx && tx.type != null && getBigInt(tx.type)) {\n // If there are no EIP-1559 properties, it might be non-EIP-a559\n if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {\n const feeData = await this.getFeeData(req.zone);\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 const shard = 'shard' in req ? req.shard : 'zone' in req ? toShard(req.zone) : undefined;\n if (req.method === 'getRunningLocations') {\n return await this.send(request.method, request.args, shard, req.now);\n }\n else {\n return await this.send(request.method, request.args, shard);\n }\n }\n return super._perform(req);\n }\n /**\n * Sub-classes may override this; it detects the _actual_ network that we are **currently** connected to.\n *\n * Keep in mind that {@link JsonRpcApiProvider.send | **send**} may only be used once\n * {@link JsonRpcApiProvider.ready | **ready**}, otherwise the _send primitive must be used instead.\n *\n * @ignore\n * @returns {Promise} The detected network.\n * @throws {Error} If network detection fails.\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('quai_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++,\n method: 'quai_chainId',\n params: [],\n jsonrpc: '2.0',\n };\n this.emit('debug', undefined, { 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', undefined, { action: 'receiveRpcError', error });\n throw error;\n }\n this.emit('debug', undefined, { 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 {@link JsonRpcApiProvider._start | **_start**} has been called, no calls\n * will be passed to {@link JsonRpcApiProvider._send | **_send**} from {@link JsonRpcApiProvider.send | **send**} . If\n * it is overridden, then `super._start()` **MUST** be called.\n *\n * Calling it multiple times is safe and has no effect.\n *\n * @ignore\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 let retries = 0;\n const maxRetries = 5;\n while (this.#network == null && !this.destroyed && retries < maxRetries) {\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', undefined, makeError('failed to bootstrap network detection', 'NETWORK_ERROR', {\n event: 'initial-network-discovery',\n info: { error },\n }));\n await stall(1000);\n retries++;\n }\n }\n if (retries >= maxRetries) {\n throw new Error('Failed to detect network after maximum retries');\n }\n // Start dispatching requests\n this.#scheduleDrain();\n })();\n }\n /**\n * Resolves once the {@link JsonRpcApiProvider._start | **_start**} has been called. This can be used in sub-classes\n * to defer sending data until the connection has been established.\n *\n * @ignore\n * @returns {Promise} A promise that resolves once the provider is ready.\n */\n async _waitUntilReady() {\n if (this._initFailed) {\n throw new Error('Provider failed to initialize on creation. Run initialize or create a new provider.');\n }\n await this.initPromise;\n }\n /**\n * Return a Subscriber that will manage the `sub`.\n *\n * Sub-classes may override this to modify the behavior of subscription management.\n *\n * @ignore\n * @param {Subscription} sub - The subscription to manage.\n * @returns {Subscriber} The subscriber that will manage the subscription.\n */\n _getSubscriber(sub) {\n // Pending Filters aren't availble via polling\n if (sub.type === 'pending') {\n return new FilterIdPendingSubscriber(this, sub.zone);\n }\n if (sub.type === 'event') {\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 {@link JsonRpcApiProvider._start | **_start**} has been called.\n *\n * @returns {boolean} True if the provider is ready.\n */\n get ready() {\n return this.#notReady == null;\n }\n /**\n * Returns `tx` as a normalized JSON-RPC transaction request, which has all values hexlified and any numeric values\n * converted to Quantity values.\n *\n * @ignore\n * @param {TransactionRequest} tx - The transaction to normalize.\n * @returns {JsonRpcTransactionRequest} The normalized transaction.\n * @throws {Error} If the transaction is invalid.\n */\n getRpcTransaction(tx) {\n const result = {};\n if ('from' in tx || ('to' in tx && 'data' in tx)) {\n // JSON-RPC now requires numeric values to be \"quantity\" values\n [\n 'chainId',\n 'gasLimit',\n 'gasPrice',\n 'type',\n 'maxFeePerGas',\n 'maxPriorityFeePerGas',\n 'nonce',\n 'value',\n ].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 ('accessList' in tx && tx.accessList) {\n result['accessList'] = accessListify(tx.accessList);\n }\n }\n else {\n throw new Error('No Qi getRPCTransaction implementation yet');\n }\n return result;\n }\n /**\n * Returns the request method and arguments required to perform `req`.\n *\n * @ignore\n * @param {PerformActionRequest} req - The request to perform.\n * @returns {null | { method: string; args: any[] }} The method and arguments to use.\n * @throws {Error} If the request is not supported or invalid.\n */\n getRpcRequest(req) {\n switch (req.method) {\n case 'chainId':\n return { method: 'quai_chainId', args: [] };\n case 'getBlockNumber':\n return { method: 'quai_blockNumber', args: [] };\n case 'getGasPrice':\n return {\n method: 'quai_baseFee',\n args: [req.txType],\n };\n case 'getMaxPriorityFeePerGas':\n return { method: 'quai_maxPriorityFeePerGas', args: [] };\n case 'getPendingHeader':\n return { method: 'quai_getPendingHeader', args: [] };\n case 'getBalance':\n return {\n method: 'quai_getBalance',\n args: [req.address, req.blockTag],\n };\n case 'getOutpointsByAddress':\n return {\n method: 'quai_getOutpointsByAddress',\n args: [req.address],\n };\n case 'getTransactionCount':\n return {\n method: 'quai_getTransactionCount',\n args: [req.address, req.blockTag],\n };\n case 'getCode':\n return {\n method: 'quai_getCode',\n args: [req.address, req.blockTag],\n };\n case 'getStorage':\n return {\n method: 'quai_getStorageAt',\n args: [req.address, '0x' + req.position.toString(16), req.blockTag],\n };\n case 'broadcastTransaction':\n return {\n method: 'quai_sendRawTransaction',\n args: [req.signedTransaction],\n };\n case 'getBlock':\n if ('blockTag' in req) {\n return {\n method: 'quai_getBlockByNumber',\n args: [req.blockTag, !!req.includeTransactions],\n };\n }\n else if ('blockHash' in req) {\n return {\n method: 'quai_getBlockByHash',\n args: [req.blockHash, !!req.includeTransactions],\n };\n }\n break;\n case 'getTransaction':\n return {\n method: 'quai_getTransactionByHash',\n args: [req.hash],\n };\n case 'getTransactionReceipt':\n return {\n method: 'quai_getTransactionReceipt',\n args: [req.hash],\n };\n case 'call':\n return {\n method: 'quai_call',\n args: [this.getRpcTransaction(req.transaction), req.blockTag],\n };\n case 'estimateGas': {\n return {\n method: 'quai_estimateGas',\n args: [this.getRpcTransaction(req.transaction)],\n };\n }\n case 'getRunningLocations': {\n return {\n method: 'quai_listRunningChains',\n args: [],\n };\n }\n case 'getProtocolTrieExpansionCount': {\n return {\n method: 'quai_getProtocolExpansionNumber',\n args: [],\n };\n }\n case 'getProtocolExpansionNumber': {\n return {\n method: 'quai_getProtocolExpansionNumber',\n args: [],\n };\n }\n case 'getQiRateAtBlock': {\n return {\n method: 'quai_qiRateAtBlock',\n args: [req.blockTag, req.amt],\n };\n }\n case 'getQuaiRateAtBlock': {\n return {\n method: 'quai_quaiRateAtBlock',\n args: [req.blockTag, req.amt],\n };\n }\n case 'getLogs':\n return { method: 'quai_getLogs', args: [req.filter] };\n case 'getTxPoolContent':\n return { method: 'txpool_content', args: [] };\n case 'txPoolInspect':\n return { method: 'txpool_inspect', args: [] };\n }\n return null;\n }\n /**\n * Returns an quais-style Error for the given JSON-RPC error `payload`, coalescing the various strings and error\n * shapes that different nodes return, coercing them into a machine-readable standardized error.\n *\n * @ignore\n * @param {JsonRpcPayload} payload - The payload that was sent.\n * @param {JsonRpcError} _error - The error that was received.\n * @returns {Error} The coalesced error.\n */\n getRpcError(payload, _error, shard) {\n const { method } = payload;\n const { error } = _error;\n if (method === 'quai_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, shard },\n });\n }\n }\n if (method === 'quai_call' || method === 'quai_estimateGas') {\n const result = spelunkData(error);\n const e = AbiCoder.getBuiltinCallException(method === 'quai_call' ? 'call' : 'estimateGas', payload.params[0], result ? result.data : null);\n e.info = { error, payload, shard };\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 (method === 'quai_getTransactionByHash' && error.message && error.message.match(/transaction not found/i)) {\n return makeError('transaction not found', 'TRANSACTION_NOT_FOUND', { info: { payload, error, shard } });\n }\n if (typeof error.message === 'string' && error.message.match(/user denied|quais-user-denied/i)) {\n const actionMap = {\n quai_sign: 'signMessage',\n personal_sign: 'signMessage',\n quai_signTypedData_v4: 'signTypedData',\n quai_signTransaction: 'signTransaction',\n quai_sendTransaction: 'sendTransaction',\n quai_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, shard },\n });\n }\n if (method === 'quai_sendRawTransaction' || method === 'quai_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,\n info: { error, shard },\n });\n }\n if (message.match(/nonce/i) && message.match(/too low/i)) {\n return makeError('nonce has already been used', 'NONCE_EXPIRED', {\n transaction,\n info: { error, shard },\n });\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', {\n transaction,\n info: { error, shard },\n });\n }\n if (message.match(/only replay-protected/i)) {\n return makeError('legacy pre-eip-155 transactions not supported', 'UNSUPPORTED_OPERATION', {\n operation: method,\n info: { transaction, info: { error, shard } },\n });\n }\n if (message.match(/already known/i)) {\n return makeError('transaction already known', 'TRANSACTION_ALREADY_KNOWN', { info: { error, shard } });\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,\n info: { error, payload, shard },\n });\n }\n if (message.match('Provider failed to initialize on creation. Run initialize or create a new provider.')) {\n return makeError('Provider failed to initialize on creation. Run initUrlMap or create a new provider.', 'PROVIDER_FAILED_TO_INITIALIZE', {\n info: { payload, error, shard },\n });\n }\n return makeError('could not coalesce error', 'UNKNOWN_ERROR', { error, payload, shard });\n }\n /**\n * Requests the `method` with `params` via the JSON-RPC protocol over the underlying channel. This can be used to\n * call methods on the backend that do not have a high-level API within the Provider API.\n *\n * This method queues requests according to the batch constraints in the options, assigns the request a unique ID.\n *\n * **Do NOT override** this method in sub-classes; instead override {@link JsonRpcApiProvider._send | **_send**} or\n * force the options values in the call to the constructor to modify this method's behavior.\n *\n * @param {string} method - The method to call.\n * @param {any[] | Record} params - The parameters to pass to the method.\n * @param {Shard} shard - The shard to send the request to.\n * @param {boolean} now - If true, the request will be sent immediately.\n * @returns {Promise} A promise that resolves to the result of the method call.\n */\n send(method, params, shard, now) {\n const continueSend = () => {\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,\n reject,\n payload: { method, params, id, jsonrpc: '2.0' },\n shard: shard,\n now: now,\n });\n });\n // If there is not a pending drainTimer, set one\n this.#scheduleDrain();\n return promise;\n };\n // @TODO: cache chainId?? purge on switch_networks\n // We have been destroyed; no operations are supported anymore\n if (method !== 'quai_listRunningChains') {\n return this.initPromise.then(() => {\n return continueSend();\n });\n }\n else {\n return continueSend();\n }\n }\n /**\n * Returns a JsonRpcSigner for the given address.\n *\n * @param {number | string} [address] - The address or index of the account.\n * @returns {Promise} A promise that resolves to the JsonRpcSigner.\n * @throws {Error} If the account is invalid.\n */\n async getSigner(address) {\n if (address == null) {\n address = 0;\n }\n const accountsPromise = this.send('quai_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 /**\n * Returns a list of JsonRpcSigners for all accounts.\n *\n * @returns {Promise} A promise that resolves to an array of JsonRpcSigners.\n */\n async listAccounts() {\n const accounts = await this.send('quai_accounts', []);\n return accounts.map((a) => new JsonRpcSigner(this, a));\n }\n /**\n * Destroys the provider, stopping all processing and canceling all pending requests.\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', {\n operation: payload.method,\n }));\n }\n this.#payloads = [];\n // Parent clean-up\n super.destroy();\n }\n}\n/**\n * The JsonRpcProvider is one of the most common Providers, which performs all operations over HTTP (or HTTPS) requests.\n *\n * Events are processed by polling the backend for the current block number; when it advances, all block-base events are\n * then checked for updates.\n *\n * @category Providers\n */\nexport class JsonRpcProvider extends JsonRpcApiProvider {\n constructor(urls, network, options) {\n if (urls == null) {\n urls = ['http://localhost:8545'];\n }\n super(network, options);\n if (Array.isArray(urls)) {\n urls.forEach((url) => {\n this.validateUrl(url);\n });\n this.initialize(urls);\n }\n else if (typeof urls === 'string') {\n this.validateUrl(urls);\n this.initialize([urls]);\n }\n else {\n this.validateUrl(urls.url);\n this.initialize(urls.clone());\n }\n }\n _getSubscriber(sub) {\n const subscriber = super._getSubscriber(sub);\n return subscriber;\n }\n _getConnection(shard) {\n if (this._initFailed) {\n throw new Error('Provider failed to initialize on creation. Run initUrlMap or create a new provider.');\n }\n let connection;\n if (shard !== undefined) {\n connection = this._urlMap.get(shard) ?? this.connect[this.connect.length - 1].clone();\n }\n else {\n connection = this.connect[this.connect.length - 1].clone();\n }\n return new FetchRequest(connection.url);\n }\n async send(method, params, shard, now) {\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. quai_chainId) until we absolutely have to.\n await this._start();\n return await super.send(method, params, shard, now);\n }\n async _send(payload, shard) {\n // Configure a POST connection for the requested method\n const request = this._getConnection(shard);\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 // eslint-disable-next-line no-empty\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 // eslint-disable-next-line no-empty\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 { Interface } from '../abi/index.js';\nimport { concat, defineProperties, getBytes, hexlify, assert, assertArgument } from '../utils/index.js';\nimport { BaseContract, copyOverrides, resolveArgs } from './contract.js';\nimport { validateAddress } from '../address/index.js';\nimport { getZoneForAddress } from '../utils/index.js';\nimport { Wallet } from '../wallet/index.js';\nimport { randomBytes } from '../crypto/index.js';\nimport { getContractAddress, isQiAddress } from '../address/index.js';\nimport { getStatic } from '../utils/properties.js';\nimport { JsonRpcSigner } from '../providers/provider-jsonrpc.js';\n// A = Arguments to the constructor\n// I = Interface of deployed contracts\n/**\n * A **ContractFactory** is used to deploy a Contract to the blockchain.\n *\n * @category Contract\n */\nexport class ContractFactory {\n /**\n * The Contract Interface.\n */\n interface;\n /**\n * The Contract deployment bytecode. Often called the initcode.\n */\n bytecode;\n /**\n * The ContractRunner to deploy the Contract as.\n */\n runner;\n /**\n * Create a new **ContractFactory** with `abi` and `bytecode`, optionally connected to `runner`.\n *\n * The `bytecode` may be the `bytecode` property within the standard Solidity JSON output.\n */\n constructor(abi, bytecode, runner) {\n const iface = Interface.from(abi);\n // Dereference Solidity bytecode objects and allow a missing `0x`-prefix\n if (bytecode instanceof Uint8Array) {\n bytecode = hexlify(getBytes(bytecode));\n }\n else {\n if (typeof bytecode === 'object') {\n bytecode = bytecode.object;\n }\n if (!bytecode.startsWith('0x')) {\n bytecode = '0x' + bytecode;\n }\n bytecode = hexlify(getBytes(bytecode));\n }\n defineProperties(this, {\n bytecode,\n interface: iface,\n runner: runner || null,\n });\n }\n attach(target) {\n return new BaseContract(target, this.interface, this.runner);\n }\n /**\n * Resolves to the transaction to deploy the contract, passing `args` into the constructor.\n *\n * @param {ContractMethods} args - The arguments to the constructor.\n * @returns {Promise} A promise resolving to the deployment transaction.\n */\n async getDeployTransaction(...args) {\n let overrides;\n const fragment = this.interface.deploy;\n if (fragment.inputs.length + 1 === args.length) {\n overrides = await copyOverrides(args.pop());\n const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args);\n const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]);\n return Object.assign({}, overrides, { data });\n }\n if (fragment.inputs.length !== args.length) {\n throw new Error('incorrect number of arguments to constructor');\n }\n const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args);\n const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]);\n const from = args.pop()?.from || undefined;\n return Object.assign({}, from, { data });\n }\n /**\n * Resolves to the Contract deployed by passing `args` into the constructor.\n *\n * This will resovle to the Contract before it has been deployed to the network, so the\n * [baseContract.waitForDeployment](../classes/BaseContract#waitForDeployment) should be used before sending any\n * transactions to it.\n *\n * @param {ContractMethods} args - The arguments to the constructor.\n * @returns {Promise<\n * BaseContract & { deploymentTransaction(): ContractTransactionResponse } & Omit\n * >}\n * A promise resolving to the Contract.\n */\n async deploy(...args) {\n const tx = await this.getDeployTransaction(...args);\n assert(this.runner && typeof this.runner.sendTransaction === 'function', 'factory runner does not support sending transactions', 'UNSUPPORTED_OPERATION', {\n operation: 'sendTransaction',\n });\n if (this.runner instanceof Wallet || this.runner instanceof JsonRpcSigner) {\n validateAddress(this.runner.address);\n tx.from = this.runner.address;\n }\n const grindedTx = await this.grindContractAddress(tx);\n const sentTx = await this.runner.sendTransaction(grindedTx);\n const address = getStatic(this.constructor, 'getContractAddress')?.(tx);\n return new BaseContract(address, this.interface, this.runner, sentTx);\n }\n static getContractAddress(transaction) {\n return getContractAddress(transaction.from, BigInt(transaction.nonce), // Fix: Convert BigInt to bigint\n transaction.data);\n }\n async grindContractAddress(tx) {\n if (tx.nonce == null && tx.from) {\n tx.nonce = await this.runner?.provider?.getTransactionCount(tx.from);\n }\n const sender = String(tx.from);\n const toShard = getZoneForAddress(sender);\n let i = 0;\n const startingData = tx.data;\n while (i < 10000) {\n const contractAddress = getContractAddress(sender, BigInt(tx.nonce || 0), tx.data || '');\n const contractShard = getZoneForAddress(contractAddress);\n const utxo = isQiAddress(contractAddress);\n if (contractShard === toShard && !utxo) {\n return tx;\n }\n const salt = randomBytes(32);\n tx.data = hexlify(concat([String(startingData), salt]));\n i++;\n }\n return tx;\n }\n /**\n * Return a new **ContractFactory** with the same ABI and bytecode, but connected to `runner`.\n *\n * @param {ContractRunner} runner - The runner to connect to.\n * @returns {ContractFactory} A new ContractFactory.\n */\n connect(runner) {\n return new ContractFactory(this.interface, this.bytecode, runner);\n }\n /**\n * Create a new **ContractFactory** from the standard Solidity JSON output.\n *\n * @param {any} output - The Solidity JSON output.\n * @param {ContractRunner} runner - The runner to connect to.\n * @returns {ContractFactory} A new ContractFactory.\n */\n static fromSolidity(output, runner) {\n assertArgument(output != null, 'bad compiler output', 'output', output);\n if (typeof output === 'string') {\n output = JSON.parse(output);\n }\n const abi = output.abi;\n let bytecode = '';\n if (output.bytecode) {\n bytecode = output.bytecode;\n }\n else if (output.evm && output.evm.bytecode) {\n bytecode = output.evm.bytecode;\n }\n return new this(abi, bytecode, runner);\n }\n}\n//# sourceMappingURL=factory.js.map","import { assertArgument } from '../utils/index.js';\nimport { JsonRpcApiProvider } from './provider-jsonrpc.js';\n/**\n * A **BrowserProvider** is intended to wrap an injected provider which adheres to the\n * [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) standard, which most (if not all) currently do.\n *\n * @category Providers\n * @class\n * @extends JsonRpcApiProvider\n */\nexport class BrowserProvider extends JsonRpcApiProvider {\n #request;\n /**\n * Connect to the `ethereum` provider, optionally forcing the `network`.\n *\n * @class\n * @param {Eip1193Provider} ethereum - The EIP-1193 provider.\n * @param {Networkish} [network] - The network to connect to.\n */\n constructor(ethereum, network) {\n super(network, { batchMaxCount: 1 });\n this.#request = async (method, params) => {\n const payload = { method, params };\n this.emit('debug', undefined, { action: 'sendEip1193Request', payload });\n try {\n const result = await ethereum.request(payload);\n this.emit('debug', undefined, { 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', undefined, { action: 'receiveEip1193Error', error });\n throw error;\n }\n };\n }\n /**\n * Resolves to `true` if the provider manages the `address`.\n *\n * @param {number | string} address - The address to check.\n * @returns {Promise} 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('quai_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 /**\n * Sends a JSON-RPC request.\n *\n * @param {string} method - The method name.\n * @param {any[] | Record} params - The parameters for the method.\n * @returns {Promise} The result of the request.\n */\n async send(method, params) {\n await this._start();\n return await super.send(method, params);\n }\n /**\n * Sends a JSON-RPC payload.\n *\n * @ignore\n * @ignore\n * @param {JsonRpcPayload | JsonRpcPayload[]} payload - The JSON-RPC payload.\n * @returns {Promise<(JsonRpcResult | JsonRpcError)[]>} The result of the request.\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 {\n id: payload.id,\n error: { code: e.code, data: e.data, message: e.message },\n },\n ];\n }\n }\n /**\n * Gets the RPC error.\n *\n * @param {JsonRpcPayload} payload - The JSON-RPC payload.\n * @param {JsonRpcError} error - The JSON-RPC error.\n * @returns {Error} The RPC error.\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 = `quais-user-denied: ${error.error.message}`;\n break;\n case 4200:\n error.error.message = `quais-unsupported: ${error.error.message}`;\n break;\n }\n return super.getRpcError(payload, error);\n }\n /**\n * Gets the signer for the given address.\n *\n * @param {number | string} [address] - The address to get the signer for.\n * @returns {Promise} The signer for the address.\n */\n async getSigner(address) {\n if (address == null) {\n address = 0;\n }\n if (!(await this.hasSigner(address))) {\n try {\n await this.#request('quai_requestAccounts', []);\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 { UnmanagedSubscriber } from './abstract-provider.js';\nimport { assert, assertArgument, makeError } from '../utils/index.js';\nimport { JsonRpcApiProvider } from './provider-jsonrpc.js';\nimport { toShard } from '../constants/index.js';\n/**\n * A **SocketSubscriber** uses a socket transport to handle events and should use\n * {@link SocketSubscriber._emit | **_emit**} to manage the events.\n *\n * - A sub-class MUST call the `_start()` method once connected\n * - A sub-class MUST override the `_write(string)` method\n * - A sub-class MUST call `_processMessage(string)` for each message\n *\n * @category Providers\n */\nexport class SocketSubscriber {\n #provider;\n #filter;\n /**\n * The filter.\n *\n * @type {any[]}\n */\n get filter() {\n return JSON.parse(this.#filter);\n }\n #filterId;\n #paused;\n #emitPromise;\n zone;\n shard;\n /**\n * Creates a new **SocketSubscriber** attached to `provider` listening to `filter`.\n *\n * @param {SocketProvider} provider - The socket provider.\n * @param {any[]} filter - The filter.\n */\n constructor(provider, filter, zone) {\n this.#provider = provider;\n this.#filter = JSON.stringify(filter);\n this.#filterId = null;\n this.#paused = null;\n this.#emitPromise = null;\n this.zone = zone;\n this.shard = toShard(zone);\n }\n /**\n * Start the subscriber.\n */\n start() {\n this.#filterId = this.#provider.send('quai_subscribe', this.filter, this.shard).then((filterId) => {\n this.#provider._register(filterId, this);\n return filterId;\n });\n }\n /**\n * Stop the subscriber.\n */\n stop() {\n this.#filterId.then((filterId) => {\n this.#provider.send('quai_unsubscribe', [filterId], this.shard);\n });\n this.#filterId = null;\n }\n /**\n * Pause the subscriber.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop logs while paused.\n */\n pause(dropWhilePaused) {\n assert(dropWhilePaused, 'preserve logs while paused not supported by SocketSubscriber yet', 'UNSUPPORTED_OPERATION', { operation: 'pause(false)' });\n this.#paused = !!dropWhilePaused;\n }\n /**\n * Resume the subscriber.\n */\n resume() {\n this.#paused = null;\n }\n /**\n * Handle incoming messages.\n *\n * @ignore\n * @param {any} message - The message to handle.\n */\n _handleMessage(message) {\n if (this.#filterId == null) {\n return;\n }\n if (this.#paused === null) {\n let emitPromise = this.#emitPromise;\n if (emitPromise == null) {\n emitPromise = this._emit(this.#provider, message);\n }\n else {\n emitPromise = emitPromise.then(async () => {\n await this._emit(this.#provider, message);\n });\n }\n this.#emitPromise = emitPromise.then(() => {\n if (this.#emitPromise === emitPromise) {\n this.#emitPromise = null;\n }\n });\n }\n }\n /**\n * Sub-classes **must** override this to emit the events on the provider.\n *\n * @abstract\n * @param {SocketProvider} provider - The socket provider.\n * @param {any} message - The message to emit.\n * @returns {Promise}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _emit(provider, message) {\n throw new Error('sub-classes must implement this; _emit');\n }\n}\n/**\n * A **SocketBlockSubscriber** listens for `newHeads` events and emits `\"block\"` events.\n *\n * @category Providers\n */\nexport class SocketBlockSubscriber extends SocketSubscriber {\n /**\n * Creates a new **SocketBlockSubscriber**.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n */\n constructor(provider, zone) {\n super(provider, ['newHeads'], zone);\n }\n /**\n * Emit the block event.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n * @param {any} message - The message to emit.\n * @returns {Promise}\n */\n async _emit(provider, message) {\n provider.emit('block', this.zone, parseInt(message.woHeader.number));\n }\n}\n/**\n * A **SocketPendingSubscriber** listens for pending transactions and emits `\"pending\"` events.\n *\n * @category Providers\n */\nexport class SocketPendingSubscriber extends SocketSubscriber {\n /**\n * Creates a new **SocketPendingSubscriber**.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n */\n constructor(provider, zone) {\n super(provider, ['newPendingTransactions'], zone);\n }\n /**\n * Emit the pending event.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n * @param {any} message - The message to emit.\n * @returns {Promise}\n */\n async _emit(provider, message) {\n provider.emit('pending', message);\n }\n}\n/**\n * A **SocketEventSubscriber** listens for event logs.\n *\n * @category Providers\n */\nexport class SocketEventSubscriber extends SocketSubscriber {\n #logFilter;\n /**\n * The filter.\n *\n * @type {EventFilter}\n */\n get logFilter() {\n return JSON.parse(this.#logFilter);\n }\n /**\n * Creates a new **SocketEventSubscriber**.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n * @param {EventFilter} filter - The event filter.\n */\n constructor(provider, filter, zone) {\n super(provider, ['logs', filter], zone);\n this.#logFilter = JSON.stringify(filter);\n }\n /**\n * Emit the event log.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n * @param {any} message - The message to emit.\n * @returns {Promise}\n */\n async _emit(provider, message) {\n provider.emit(this.logFilter, this.zone, provider._wrapLog(message, provider._network));\n }\n}\n/**\n * A **SocketProvider** is backed by a long-lived connection over a socket, which can subscribe and receive real-time\n * messages over its communication channel.\n *\n * @category Providers\n */\nexport class SocketProvider extends JsonRpcApiProvider {\n #callbacks;\n // Maps each filterId to its subscriber\n #subs;\n // If any events come in before a subscriber has finished\n // registering, queue them\n #pending;\n /**\n * Creates a new **SocketProvider** connected to `network`.\n *\n * If unspecified, the network will be discovered.\n *\n * @param {Networkish} [network] - The network to connect to.\n * @param {JsonRpcApiProviderOptions} [_options] - The options for the provider.\n */\n constructor(network, _options) {\n // Copy the options\n const options = Object.assign({}, _options != null ? _options : {});\n // Support for batches is generally not supported for\n // connection-base providers; if this changes in the future\n // the _send should be updated to reflect this\n assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1, 'sockets-based providers do not support batches', 'options.batchMaxCount', _options);\n options.batchMaxCount = 1;\n // Socket-based Providers (generally) cannot change their network,\n // since they have a long-lived connection; but let people override\n // this if they have just cause.\n if (options.staticNetwork == null) {\n options.staticNetwork = true;\n }\n super(network, options);\n this.#callbacks = new Map();\n this.#subs = new Map();\n this.#pending = new Map();\n }\n /**\n * Get the subscriber for a given subscription.\n *\n * @ignore\n * @param {Subscription} sub - The subscription.\n * @returns {Subscriber} The subscriber.\n */\n _getSubscriber(sub) {\n switch (sub.type) {\n case 'close':\n return new UnmanagedSubscriber('close');\n case 'block':\n return new SocketBlockSubscriber(this, sub.zone);\n case 'pending':\n return new SocketPendingSubscriber(this, sub.zone);\n case 'event':\n return new SocketEventSubscriber(this, sub.filter, sub.zone);\n case 'orphan':\n // Handled auto-matically within AbstractProvider\n // when the log.removed = true\n if (sub.filter.orphan === 'drop-log') {\n return new UnmanagedSubscriber('drop-log');\n }\n }\n return super._getSubscriber(sub);\n }\n /**\n * Register a new subscriber. This is used internally by Subscribers and generally is unnecessary unless extending\n * capabilities.\n *\n * @ignore\n * @param {number | string} filterId - The filter ID.\n * @param {SocketSubscriber} subscriber - The subscriber.\n */\n _register(filterId, subscriber) {\n this.#subs.set(filterId, subscriber);\n const pending = this.#pending.get(filterId);\n if (pending) {\n for (const message of pending) {\n subscriber._handleMessage(message);\n }\n this.#pending.delete(filterId);\n }\n }\n /**\n * Send a JSON-RPC payload.\n *\n * @ignore\n * @param {JsonRpcPayload | JsonRpcPayload[]} payload - The payload to send.\n * @param {Shard} [shard] - The shard.\n * @param {boolean} [now] - Whether to send immediately.\n * @returns {Promise<(JsonRpcResult | JsonRpcError)[]>} The result or error.\n */\n async _send(payload, shard, now) {\n if (this._initFailed) {\n console.log('Provider failed to initialize on creation. Run initialize or create a new provider.');\n return [\n {\n id: Array.isArray(payload) ? payload[0].id : payload.id,\n error: {\n code: -32000,\n message: 'Provider failed to initialize on creation. Run initialize or create a new provider.',\n },\n },\n ];\n }\n // WebSocket provider doesn't accept batches\n assertArgument(!Array.isArray(payload), 'WebSocket does not support batch send', 'payload', payload);\n // @TODO: stringify payloads here and store to prevent mutations\n // Prepare a promise to respond to\n const promise = new Promise((resolve, reject) => {\n this.#callbacks.set(payload.id, { payload, resolve, reject });\n });\n // Wait until the socket is connected before writing to it\n try {\n if (!now) {\n await this._waitUntilReady();\n }\n }\n catch (error) {\n this.#callbacks.delete(payload.id);\n return [\n {\n id: Array.isArray(payload) ? payload[0].id : payload.id,\n error: {\n code: -32000,\n message: 'Provider failed to initialize on creation. Run initialize or create a new provider.',\n },\n },\n ];\n }\n // Write the request to the socket\n await this._write(JSON.stringify(payload), shard);\n return [await promise];\n }\n /**\n * Sub-classes **must** call this with messages received over their transport to be processed and dispatched.\n *\n * @ignore\n * @param {string} message - The message to process.\n */\n async _processMessage(message) {\n const result = JSON.parse(message);\n if (result && typeof result === 'object' && 'id' in result) {\n const callback = this.#callbacks.get(result.id);\n if (callback == null) {\n this.emit('error', undefined, makeError('received result for unknown id', 'UNKNOWN_ERROR', {\n reasonCode: 'UNKNOWN_ID',\n result,\n }));\n return;\n }\n this.#callbacks.delete(result.id);\n callback.resolve(result);\n }\n else if (result && result.method === 'quai_subscription') {\n const filterId = result.params.subscription;\n const subscriber = this.#subs.get(filterId);\n if (subscriber) {\n subscriber._handleMessage(result.params.result);\n }\n else {\n let pending = this.#pending.get(filterId);\n if (pending == null) {\n pending = [];\n this.#pending.set(filterId, pending);\n }\n pending.push(result.params.result);\n }\n }\n else {\n this.emit('error', undefined, makeError('received unexpected message', 'UNKNOWN_ERROR', {\n reasonCode: 'UNEXPECTED_MESSAGE',\n result,\n }));\n return;\n }\n }\n /**\n * Sub-classes **must** override this to send `message` over their transport.\n *\n * @ignore\n * @param {string} message - The message to send.\n * @param {Shard} [shard] - The shard.\n * @returns {Promise}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _write(message, shard) {\n throw new Error('sub-classes must override this');\n }\n validateUrl(url) {\n const urlPattern = /^(ws):\\/\\/[a-zA-Z0-9.-]+(:\\d+)?$/;\n if (!urlPattern.test(url)) {\n let errorMessage = 'Invalid URL: ';\n if (!/^ws:\\/\\//.test(url)) {\n errorMessage += 'URL must start with ws://. ';\n }\n if (url.endsWith('/')) {\n errorMessage += 'URL should not end with a /. ';\n }\n if (/\\/[^/]+/.test(url)) {\n errorMessage += 'URL should not contain a path, query string, or fragment. ';\n }\n throw new Error(errorMessage.trim());\n }\n }\n}\n//# sourceMappingURL=provider-socket.js.map","function getGlobal() {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('unable to locate global object');\n}\nconst _WebSocket = getGlobal().WebSocket;\nexport { _WebSocket as WebSocket };\n//# sourceMappingURL=ws-browser.js.map","import { WebSocket as _WebSocket } from './ws.js'; /*-browser*/\nimport { SocketProvider } from './provider-socket.js';\nimport { Shard, toShard } from '../constants/index.js';\nimport { fromShard } from '../constants/shards.js';\n/**\n * A JSON-RPC provider which is backed by a WebSocket.\n *\n * WebSockets are often preferred because they retain a live connection to a server, which permits more instant access\n * to events.\n *\n * However, this incurs higher server infrastructure costs, so additional resources may be required to host your own\n * WebSocket nodes and many third-party services charge additional fees for WebSocket endpoints.\n *\n * @category Providers\n * @extends SocketProvider\n */\nexport class WebSocketProvider extends SocketProvider {\n #websockets;\n /**\n * A map to track the readiness of each shard.\n *\n * @type {Map}\n */\n readyMap = new Map();\n /**\n * Get the array of WebSocketLike objects.\n *\n * @returns {WebSocketLike[]} The array of WebSocketLike objects.\n * @throws {Error} If the websocket is closed.\n */\n get websocket() {\n if (this.#websockets == null) {\n throw new Error('websocket closed');\n }\n return this.#websockets;\n }\n /**\n * Create a new WebSocketProvider.\n *\n * @param {string | string[] | WebSocketLike | WebSocketCreator} url - The URL(s) or WebSocket object or creator.\n * @param {Networkish} [network] - The network to connect to.\n * @param {JsonRpcApiProviderOptions} [options] - The options for the JSON-RPC API provider.\n */\n constructor(url, network, options) {\n super(network, options);\n this.#websockets = [];\n if (typeof url === 'string') {\n this.validateUrl(url);\n }\n else if (Array.isArray(url)) {\n url.forEach((it) => this.validateUrl(it));\n }\n else if (typeof url === 'function') {\n this.validateUrl(url().url);\n }\n else {\n this.validateUrl(url.url);\n }\n this.initialize(typeof url === 'string' ? [url] : url);\n }\n /**\n * Initialize a WebSocket connection for a shard.\n *\n * @ignore\n * @param {WebSocketLike} websocket - The WebSocket object.\n * @param {Shard} shard - The shard identifier.\n */\n initWebSocket(websocket, shard) {\n websocket.onerror = (error) => {\n console.log('WebsocketProvider error', error);\n websocket.close();\n };\n websocket.onopen = async () => {\n try {\n await this._start();\n this.resume();\n this.readyMap.set(shard, true);\n }\n catch (error) {\n console.log('failed to start WebsocketProvider', error);\n this.readyMap.set(shard, false);\n // @TODO: now what? Attempt reconnect?\n }\n };\n websocket.onmessage = (message) => {\n this._processMessage(message.data);\n };\n }\n /**\n * Wait until the shard is ready. Max wait time is ~8 seconds.\n *\n * @param {Shard} shard - The shard identifier.\n * @returns {Promise} A promise that resolves when the shard is ready.\n * @throws {Error} If the shard is not ready within the timeout period.\n */\n async waitShardReady(shard) {\n let count = 0;\n while (!this.readyMap.get(shard)) {\n await new Promise((resolve) => setTimeout(resolve, Math.pow(2, count)));\n if (count > 11) {\n throw new Error('Timeout waiting for shard to be ready');\n }\n count++;\n }\n }\n /**\n * Initialize the URL map with WebSocket connections.\n *\n * @ignore\n * @param {U} urls - The URLs or WebSocket object or creator.\n * @returns {Promise} A promise that resolves when the URL map is initialized.\n */\n async initialize(urls) {\n //clear websockets\n this.#websockets = [];\n this._urlMap.clear();\n try {\n const primeSuffix = this._getOption('usePathing') ? `/${fromShard(Shard.Prime, 'nickname')}` : ':8001';\n const createWebSocket = (baseUrl, suffix) => {\n const tempWs = new _WebSocket(`${baseUrl}${suffix}`);\n return tempWs;\n // wait 2 minutes\n };\n const initShardWebSockets = async (baseUrl) => {\n const shards = await this._getRunningLocations(Shard.Prime, true);\n await Promise.all(shards.map(async (shard) => {\n const port = 8200 + 20 * shard[0] + shard[1];\n const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);\n const shardSuffix = this._getOption('usePathing')\n ? `/${fromShard(shardEnum, 'nickname')}`\n : `:${port}`;\n const shardUrl = baseUrl.split(':').slice(0, 2).join(':');\n const websocket = createWebSocket(shardUrl, shardSuffix);\n this.initWebSocket(websocket, shardEnum);\n this.#websockets.push(websocket);\n this._urlMap.set(shardEnum, websocket);\n try {\n await this.waitShardReady(shardEnum);\n }\n catch (error) {\n console.log('failed to waitShardReady', error);\n this._initFailed = true;\n }\n }));\n };\n if (Array.isArray(urls)) {\n for (const url of urls) {\n const baseUrl = `${url.split(':')[0]}:${url.split(':')[1]}`;\n const primeWebsocket = createWebSocket(baseUrl, primeSuffix);\n this.initWebSocket(primeWebsocket, Shard.Prime);\n this.#websockets.push(primeWebsocket);\n this._urlMap.set(Shard.Prime, primeWebsocket);\n await this.waitShardReady(Shard.Prime);\n await initShardWebSockets(baseUrl);\n }\n }\n else if (typeof urls === 'function') {\n const primeWebsocket = urls();\n this.initWebSocket(primeWebsocket, Shard.Prime);\n this.#websockets.push(primeWebsocket);\n this._urlMap.set(Shard.Prime, primeWebsocket);\n await this.waitShardReady(Shard.Prime);\n const baseUrl = this.#websockets[0].url.split(':').slice(0, 2).join(':');\n await initShardWebSockets(baseUrl);\n }\n else {\n const primeWebsocket = urls;\n this.initWebSocket(primeWebsocket, Shard.Prime);\n this.#websockets.push(primeWebsocket);\n this._urlMap.set(Shard.Prime, primeWebsocket);\n await this.waitShardReady(Shard.Prime);\n const baseUrl = primeWebsocket.url.split(':').slice(0, 2).join(':');\n await initShardWebSockets(baseUrl);\n }\n if (this.initResolvePromise)\n this.initResolvePromise();\n }\n catch (error) {\n this._initFailed = true;\n console.log('failed to initialize', error);\n //clear websockets\n this.#websockets = [];\n if (this.initRejectPromise)\n this.initRejectPromise(error);\n return;\n }\n }\n /**\n * Write a message to the WebSocket.\n *\n * @ignore\n * @param {string} message - The message to send.\n * @param {Shard} [shard] - The shard identifier.\n * @returns {Promise} A promise that resolves when the message is sent.\n * @throws {Error} If the WebSocket is closed or the shard is not found.\n */\n async _write(message, shard) {\n if (this.websocket.length < 1) {\n throw new Error('Websocket closed');\n }\n if (shard && !this._urlMap.has(shard)) {\n throw new Error('Shard not found');\n }\n const websocket = shard ? this._urlMap.get(shard) : this.websocket[this.websocket.length - 1];\n if (!websocket) {\n throw new Error('Websocket is undefined');\n }\n if (shard) {\n await this.waitShardReady(shard);\n }\n websocket.send(message);\n }\n /**\n * Destroy the WebSocket connections and clean up resources.\n *\n * @returns {Promise} A promise that resolves when the WebSocket connections are closed.\n */\n async destroy() {\n this.#websockets.forEach((it) => it.close());\n this.#websockets = [];\n super.destroy();\n }\n}\n//# sourceMappingURL=provider-websocket.js.map","const Base64 = ')!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';\n/**\n * @ignore\n */\nexport function decodeBits(width, data) {\n const maxValue = (1 << width) - 1;\n const result = [];\n let accum = 0, bits = 0, flood = 0;\n for (let i = 0; i < data.length; i++) {\n // Accumulate 6 bits of data\n accum = (accum << 6) | Base64.indexOf(data[i]);\n bits += 6;\n // While we have enough for a word...\n while (bits >= width) {\n // ...read the word\n const value = accum >> (bits - width);\n accum &= (1 << (bits - width)) - 1;\n bits -= width;\n // A value of 0 indicates we exceeded maxValue, it\n // floods over into the next value\n if (value === 0) {\n flood += maxValue;\n }\n else {\n result.push(value + flood);\n flood = 0;\n }\n }\n }\n return result;\n}\n//# sourceMappingURL=bit-reader.js.map","import { assertArgument } from '../utils/index.js';\nimport { decodeBits } from './bit-reader.js';\nimport { decodeOwl } from './decode-owl.js';\n/**\n * @ignore\n */\nexport function decodeOwlA(data, accents) {\n let words = decodeOwl(data).join(',');\n // Inject the accents\n accents.split(/,/g).forEach((accent) => {\n const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);\n assertArgument(match !== null, 'internal error parsing accents', 'accents', accents);\n let posOffset = 0;\n const positions = decodeBits(parseInt(match[3]), match[4]);\n const charCode = parseInt(match[2]);\n const regex = new RegExp(`([${match[1]}])`, 'g');\n words = words.replace(regex, (all, letter) => {\n const rem = --positions[posOffset];\n if (rem === 0) {\n letter = String.fromCharCode(letter.charCodeAt(0), charCode);\n posOffset++;\n }\n return letter;\n });\n });\n return words.split(',');\n}\n//# sourceMappingURL=decode-owla.js.map","import { WordlistOwl } from './wordlist-owl.js';\nimport { decodeOwlA } from './decode-owla.js';\n/**\n * An OWL-A format Wordlist extends the OWL format to add an overlay onto an OWL format Wordlist to support diacritic\n * marks.\n *\n * This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages\n * based on latin-1 small.\n *\n * If necessary, there are tools within the `generation/` folder to create the necessary data.\n *\n * @category Wordlists\n */\nexport class WordlistOwlA extends WordlistOwl {\n #accent;\n /**\n * Creates a new Wordlist for `locale` using the OWLA `data` and `accent` data and validated against the `checksum`.\n */\n constructor(locale, data, accent, checksum) {\n super(locale, data, checksum);\n this.#accent = accent;\n }\n /**\n * The OWLA-encoded accent data.\n *\n * @ignore\n */\n get _accent() {\n return this.#accent;\n }\n /**\n * Decode all the words for the wordlist.\n *\n * @ignore\n */\n _decodeWords() {\n return decodeOwlA(this._data, this._accent);\n }\n}\n//# sourceMappingURL=wordlist-owla.js.map","import { WordlistOwlA } from './wordlist-owla.js';\nconst words = \"0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_LoAmpuAnc]ApaAr]I>Is)IvoOqueOzaUle%Up 0Cl.EgoE=EnEr#F[G +M->NeN%P_sR>Rue]SneTaU{d2Am^AnA+AseAveI,)ImaInica2B_Cc~|i'Ci`CoDigoDoF_G!He)JinJoL/ch/eg$Lg Lin/l LmoLum`Mba)M!Mi{Mo&Mpr-deNej}g-oc!Nsej}t PaPi(az.Rba%RchoR&nR.(r!S!SmosS%2AneoAt!E Ec!Ei&EmaIaIm,Ip%IsisOmoOnicaOque%U&Uz2Ad+Ar#At+BoBr*| aEl=En#Er{Es%EvaId Lebr/p/#Mb_Mpl*N-e%O%P.Pul( R$Se'Sf[zVaVi'5BleCeL^Ming}N Ra&Rm*RAu%EchaOrO%U*UjoU^2B@CaGa%G.L$Lle#N&Rm(+Rtun(z SaTo2AcaA'AsaAtisAveIe%Il=IpeIsI#OG Gu!aJaMb_Ng}^Nr((mig('St?Yo5E>ElgaEr%ENgl-$Nt Pit!R S#V,?Zg :7Lo5A]:B$C$C[DoD+nG #GrimaGu`I>M!Mi`Mp --ch-gos%NzaPizRgoRvaStimaTaTexT*U_lV Zo3AlCc~|eC#rErG~Gumb_Ja'Ngu-#NaOnOp &S~TalT[VeY,{3B!%dB+C^D!Di EnzoGaG!oMaMi)M.Mp$NceN&Ne-go)N}t!`Qui&SoS%T!aT$T+2AgaAmaAn#AveEg En Ev Or Ov!Uv@2BoC~CoCu[GicaG+MbrizM}jaTe5|aC*G J}-esPaSt+ToZ:Ce%|oD!aD_Du+Est+F@G@GoIzL{dLe%Ll/oMaMboMutN>N&Nej Ng-iquiNj N}Re(f?Rg,Ri&RmolR+nR)sRzoSaSc aSivoT T!@TizTrizXimoY^Z^ca3|aDal]D$Du]J?]J^L,/.M^i-^NsajeN)NuRca&R,gueRi#SS.TaT!To&T+Zc]3E&ElEmb+G/Lag+Lit Ll.M}-!}im}u#OpeR SaS!@S?SmoTadTo5|?aC~DaDe=HoJ LdeL!Li'M,#Mi- c-ed-j-#NoRad(d!Re'R*R+Rs(%lScaStr TivoV!V?Zo5|oD EbleE]Er)Est[G_J!L/e%L%N&Nec(alRoScu=SeoSgoSicaS=:C C~D IpeRanj(izRr SalTalTivoTu[lUseaValVeVi{d3C$Ct G Goc$G+OnRv$ToUt+V V!a3|oDoEb]E#NezNoTi&Vel5Bleza|eMin(i(m()TaTic@Va#Ve]V$5BeCaCleoD?=DoE[EveEzLoM!oTr@:Sis0EC~E[In On!T TicaUes#1Ac~A&rAlBi%CaD,EjaGa'G@Gul=I,)Ig,Il]OQues%Uga0Ad@Cu+Ez'OT[0O'Ro1EjaU=1I&Ige'0En)0O':C#D_El]Gi`GoIsJ oLabr/>Le%Li&Lm/om/p NNalNi>Nt!-ue=PaPelP?]Que)R Rcel(edR*RoRpa&RqueR[foR)S SeoS~SoS%TaT$Tr@UsaU%VoYa<3A#nCa&C!a|oDalD*G IneL L{'Le/ig+LlejoLoLuc--s N.OnOrPi'Que'R(ch(d!Rez(f?Ri>Rl(mizEgun%Em$EnsaE|!oD^Eb=Er%Es#Lg/*Lm.LpoLrNd*N%P #Pet*PoN{PaP!oSaScaSt+T 5BiB^DoE{G*I&In/e%LoMboM^Ptu[TaTi`:Ba&B!B$BleC GazG[&L/&L!oL*Lm.L.Ls/#LudLv Mb-c~Ndi-e Ng_Ni{dN}#PoQueRdin()nSt_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv!t.trim());for(let i=0;iPromise.resolve(value[k])));return results.reduce((accum,v,index)=>{accum[keys[index]]=v;return accum},{})}function getStatic(ctor,key){for(let i=0;i<32;i++){if(ctor[key]){return ctor[key]}if(!ctor.prototype||typeof ctor.prototype!=="object"){break}ctor=Object.getPrototypeOf(ctor.prototype).constructor}return null}function defineProperties(target,values,types){for(const key in values){const value=values[key];const type=types?types[key]:null;if(type){checkType(value,type,key)}Object.defineProperty(target,key,{enumerable:true,value:value,writable:false})}}function stringify(value){if(value==null){return"null"}if(Array.isArray(value)){return"[ "+value.map(stringify).join(", ")+" ]"}if(value instanceof Uint8Array){const HEX="0123456789abcdef";let result="0x";for(let i=0;i>4];result+=HEX[value[i]&15]}return result}if(typeof value==="object"&&typeof value.toJSON==="function"){return stringify(value.toJSON())}switch(typeof value){case"boolean":case"symbol":return value.toString();case"bigint":return BigInt(value).toString();case"number":return value.toString();case"string":return JSON.stringify(value);case"object":{const keys=Object.keys(value);keys.sort();return"{ "+keys.map(k=>`${stringify(k)}: ${stringify(value[k])}`).join(", ")+" }"}}return`[ COULD NOT SERIALIZE ]`}function isError(error,code){return error&&error.code===code}function isCallException(error){return isError(error,"CALL_EXCEPTION")}function makeError(message,code,info){const shortMessage=message;{const details=[];if(info){if("message"in info||"code"in info||"name"in info){throw new Error(`value will overwrite populated values: ${stringify(info)}`)}for(const key in info){if(key==="shortMessage"){continue}const value=info[key];details.push(key+"="+stringify(value))}}details.push(`code=${code}`);details.push(`version=${version}`);if(details.length){message+=" ("+details.join(", ")+")"}}let error;switch(code){case"INVALID_ARGUMENT":error=new TypeError(message);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":error=new RangeError(message);break;default:error=new Error(message)}defineProperties(error,{code:code});if(info){Object.assign(error,info)}if(error.shortMessage==null){defineProperties(error,{shortMessage:shortMessage})}return error}function assert(check,message,code,info){if(!check){throw makeError(message,code,info)}}function assertArgument(check,message,name,value){assert(check,message,"INVALID_ARGUMENT",{argument:name,value:value})}function assertArgumentCount(count,expectedCount,message){if(message==null){message=""}if(message){message=": "+message}assert(count>=expectedCount,"missing arguemnt"+message,"MISSING_ARGUMENT",{count:count,expectedCount:expectedCount});assert(count<=expectedCount,"too many arguemnts"+message,"UNEXPECTED_ARGUMENT",{count:count,expectedCount:expectedCount})}const _normalizeForms=["NFD","NFC","NFKD","NFKC"].reduce((accum,form)=>{try{if("test".normalize(form)!=="test"){throw new Error("bad")}if(form==="NFD"){const check=String.fromCharCode(233).normalize("NFD");const expected=String.fromCharCode(101,769);if(check!==expected){throw new Error("broken")}}accum.push(form)}catch(error){}return accum},[]);function assertNormalize(form){assert(_normalizeForms.indexOf(form)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:form}})}function assertPrivate(givenGuard,guard,className){if(className==null){className=""}if(givenGuard!==guard){let method=className,operation="new";if(className){method+=".";operation+=" "+className}assert(false,`private constructor; use ${method}from* methods`,"UNSUPPORTED_OPERATION",{operation:operation})}}function _getBytes(value,name,copy){if(value instanceof Uint8Array){if(copy){return new Uint8Array(value)}return value}if(typeof value==="string"&&value.match(/^0x([0-9a-f][0-9a-f])*$/i)){const result=new Uint8Array((value.length-2)/2);let offset=2;for(let i=0;i>4]+HexCharacters[v&15]}return result}function concat(datas){return"0x"+datas.map(d=>hexlify(d).substring(2)).join("")}function dataLength(data){if(isHexString(data,true)){return(data.length-2)/2}return getBytes(data).length}function dataSlice(data,start,end){const bytes=getBytes(data);if(end!=null&&end>bytes.length){assert(false,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:bytes,length:bytes.length,offset:end})}return hexlify(bytes.slice(start==null?0:start,end==null?bytes.length:end))}function stripZerosLeft(data){let bytes=hexlify(data).substring(2);while(bytes.startsWith("00")){bytes=bytes.substring(2)}return"0x"+bytes}function zeroPad(data,length,left){const bytes=getBytes(data);assert(length>=bytes.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(bytes),length:length,offset:length+1});const result=new Uint8Array(length);result.fill(0);if(left){result.set(bytes,length-bytes.length)}else{result.set(bytes,0)}return hexlify(result)}function zeroPadValue(data,length){return zeroPad(data,length,true)}function zeroPadBytes(data,length){return zeroPad(data,length,false)}class EventPayload{filter;emitter;#listener;constructor(emitter,listener,filter){this.#listener=listener;defineProperties(this,{emitter:emitter,filter:filter})}async removeListener(){if(this.#listener==null){return}await this.emitter.off(this.filter,this.#listener)}}function decodeBase64(textData){textData=atob(textData);const data=new Uint8Array(textData.length);for(let i=0;i31){throw new Error("bytes32 string must be less than 32 bytes")}return zeroPadBytes(bytes,32)}function decodeBytes32(_bytes){const data=getBytes(_bytes,"bytes");if(data.length!==32){throw new Error("invalid bytes32 - not 32 bytes long")}if(data[31]!==0){throw new Error("invalid bytes32 string - no null terminator")}let length=31;while(data[length-1]===0){length--}return toUtf8String(data.slice(0,length))}const BN_0$8=BigInt(0);const BN_1$4=BigInt(1);const maxValue=9007199254740991;function fromTwos(_value,_width){const value=getUint(_value,"value");const width=BigInt(getNumber(_width,"width"));assert(value>>width===BN_0$8,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:_value});if(value>>width-BN_1$4){const mask=(BN_1$4<=-maxValue&&value<=maxValue,"overflow",name||"value",value);return BigInt(value);case"string":try{if(value===""){throw new Error("empty string")}if(value[0]==="-"&&value[1]!=="-"){return-BigInt(value.substring(1))}return BigInt(value)}catch(e){assertArgument(false,`invalid BigNumberish string: ${e.message}`,name||"value",value)}}assertArgument(false,"invalid BigNumberish value",name||"value",value)}function bigIntAbs(value){value=getBigInt(value);if(value===-BN_0$8||value=BN_0$8,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:value});return result}const Nibbles$1="0123456789abcdef";function toBigInt(value){if(value instanceof Uint8Array){let result="0x0";for(const v of value){result+=Nibbles$1[v>>4];result+=Nibbles$1[v&15]}return BigInt(result)}return getBigInt(value)}function getNumber(value,name){switch(typeof value){case"bigint":assertArgument(value>=-maxValue&&value<=maxValue,"overflow",name||"value",value);return Number(value);case"number":assertArgument(Number.isInteger(value),"underflow",name||"value",value);assertArgument(value>=-maxValue&&value<=maxValue,"overflow",name||"value",value);return value;case"string":try{if(value===""){throw new Error("empty string")}return getNumber(BigInt(value),name)}catch(e){assertArgument(false,`invalid numeric string: ${e.message}`,name||"value",value)}}assertArgument(false,"invalid numeric value",name||"value",value)}function toNumber(value){return getNumber(toBigInt(value))}function toBeHex(_value,_width){const value=getUint(_value,"value");let result=value.toString(16);if(_width==null){if(result.length%2){result="0"+result}}else{const width=getNumber(_width,"width");assert(width*2>=result.length,`value exceeds width (${width} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:_value});while(result.lengthProtoHash.fromObject(item))}return message}toObject(){const data={};if(this.hashes!=null){data.hashes=this.hashes.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.hashes.length)writer.writeRepeatedMessage(1,this.hashes,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoHashes;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.hashes,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoHash.deserialize(reader),ProtoHash));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoHashes.deserialize(bytes)}}common.ProtoHashes=ProtoHashes;class ProtoAddress extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("value"in data&&data.value!=undefined){this.value=data.value}}}get value(){return pb_1.Message.getFieldWithDefault(this,1,new Uint8Array(0))}set value(value){pb_1.Message.setField(this,1,value)}static fromObject(data){const message=new ProtoAddress({});if(data.value!=null){message.value=data.value}return message}toObject(){const data={};if(this.value!=null){data.value=this.value}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.value.length)writer.writeBytes(1,this.value);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoAddress;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.value=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoAddress.deserialize(bytes)}}common.ProtoAddress=ProtoAddress;class ProtoNumber extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("value"in data&&data.value!=undefined){this.value=data.value}}}get value(){return pb_1.Message.getFieldWithDefault(this,1,0)}set value(value){pb_1.Message.setField(this,1,value)}static fromObject(data){const message=new ProtoNumber({});if(data.value!=null){message.value=data.value}return message}toObject(){const data={};if(this.value!=null){data.value=this.value}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.value!=0)writer.writeUint64(1,this.value);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoNumber;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.value=reader.readUint64();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoNumber.deserialize(bytes)}}common.ProtoNumber=ProtoNumber;class ProtoLocations extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("locations"in data&&data.locations!=undefined){this.locations=data.locations}}}get locations(){return pb_1.Message.getRepeatedWrapperField(this,ProtoLocation,1)}set locations(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoLocations({});if(data.locations!=null){message.locations=data.locations.map(item=>ProtoLocation.fromObject(item))}return message}toObject(){const data={};if(this.locations!=null){data.locations=this.locations.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.locations.length)writer.writeRepeatedMessage(1,this.locations,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoLocations;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.locations,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoLocation.deserialize(reader),ProtoLocation));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoLocations.deserialize(bytes)}}common.ProtoLocations=ProtoLocations})(common||(common={}));var block;(function(block){class ProtoHeader extends pb_1.Message{#one_of_decls=[[2],[3],[4],[5],[6],[7],[9],[10],[14],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1,8,11,12,13,15],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("parent_hash"in data&&data.parent_hash!=undefined){this.parent_hash=data.parent_hash}if("uncle_hash"in data&&data.uncle_hash!=undefined){this.uncle_hash=data.uncle_hash}if("coinbase"in data&&data.coinbase!=undefined){this.coinbase=data.coinbase}if("evm_root"in data&&data.evm_root!=undefined){this.evm_root=data.evm_root}if("tx_hash"in data&&data.tx_hash!=undefined){this.tx_hash=data.tx_hash}if("etx_hash"in data&&data.etx_hash!=undefined){this.etx_hash=data.etx_hash}if("etx_rollup_hash"in data&&data.etx_rollup_hash!=undefined){this.etx_rollup_hash=data.etx_rollup_hash}if("manifest_hash"in data&&data.manifest_hash!=undefined){this.manifest_hash=data.manifest_hash}if("receipt_hash"in data&&data.receipt_hash!=undefined){this.receipt_hash=data.receipt_hash}if("difficulty"in data&&data.difficulty!=undefined){this.difficulty=data.difficulty}if("parent_entropy"in data&&data.parent_entropy!=undefined){this.parent_entropy=data.parent_entropy}if("parent_delta_s"in data&&data.parent_delta_s!=undefined){this.parent_delta_s=data.parent_delta_s}if("parent_uncled_sub_delta_s"in data&&data.parent_uncled_sub_delta_s!=undefined){this.parent_uncled_sub_delta_s=data.parent_uncled_sub_delta_s}if("uncled_s"in data&&data.uncled_s!=undefined){this.uncled_s=data.uncled_s}if("number"in data&&data.number!=undefined){this.number=data.number}if("gas_limit"in data&&data.gas_limit!=undefined){this.gas_limit=data.gas_limit}if("gas_used"in data&&data.gas_used!=undefined){this.gas_used=data.gas_used}if("base_fee"in data&&data.base_fee!=undefined){this.base_fee=data.base_fee}if("location"in data&&data.location!=undefined){this.location=data.location}if("extra"in data&&data.extra!=undefined){this.extra=data.extra}if("mix_hash"in data&&data.mix_hash!=undefined){this.mix_hash=data.mix_hash}if("nonce"in data&&data.nonce!=undefined){this.nonce=data.nonce}if("utxo_root"in data&&data.utxo_root!=undefined){this.utxo_root=data.utxo_root}if("etx_set_hash"in data&&data.etx_set_hash!=undefined){this.etx_set_hash=data.etx_set_hash}if("efficiency_score"in data&&data.efficiency_score!=undefined){this.efficiency_score=data.efficiency_score}if("threshold_count"in data&&data.threshold_count!=undefined){this.threshold_count=data.threshold_count}if("expansion_number"in data&&data.expansion_number!=undefined){this.expansion_number=data.expansion_number}if("etx_eligible_slices"in data&&data.etx_eligible_slices!=undefined){this.etx_eligible_slices=data.etx_eligible_slices}if("prime_terminus"in data&&data.prime_terminus!=undefined){this.prime_terminus=data.prime_terminus}if("interlink_root_hash"in data&&data.interlink_root_hash!=undefined){this.interlink_root_hash=data.interlink_root_hash}}}get parent_hash(){return pb_1.Message.getRepeatedWrapperField(this,common.ProtoHash,1)}set parent_hash(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}get uncle_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,2)}set uncle_hash(value){pb_1.Message.setOneofWrapperField(this,2,this.#one_of_decls[0],value)}get has_uncle_hash(){return pb_1.Message.getField(this,2)!=null}get coinbase(){return pb_1.Message.getFieldWithDefault(this,3,new Uint8Array(0))}set coinbase(value){pb_1.Message.setOneofField(this,3,this.#one_of_decls[1],value)}get has_coinbase(){return pb_1.Message.getField(this,3)!=null}get evm_root(){return pb_1.Message.getWrapperField(this,common.ProtoHash,4)}set evm_root(value){pb_1.Message.setOneofWrapperField(this,4,this.#one_of_decls[2],value)}get has_evm_root(){return pb_1.Message.getField(this,4)!=null}get tx_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,5)}set tx_hash(value){pb_1.Message.setOneofWrapperField(this,5,this.#one_of_decls[3],value)}get has_tx_hash(){return pb_1.Message.getField(this,5)!=null}get etx_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,6)}set etx_hash(value){pb_1.Message.setOneofWrapperField(this,6,this.#one_of_decls[4],value)}get has_etx_hash(){return pb_1.Message.getField(this,6)!=null}get etx_rollup_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,7)}set etx_rollup_hash(value){pb_1.Message.setOneofWrapperField(this,7,this.#one_of_decls[5],value)}get has_etx_rollup_hash(){return pb_1.Message.getField(this,7)!=null}get manifest_hash(){return pb_1.Message.getRepeatedWrapperField(this,common.ProtoHash,8)}set manifest_hash(value){pb_1.Message.setRepeatedWrapperField(this,8,value)}get receipt_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,9)}set receipt_hash(value){pb_1.Message.setOneofWrapperField(this,9,this.#one_of_decls[6],value)}get has_receipt_hash(){return pb_1.Message.getField(this,9)!=null}get difficulty(){return pb_1.Message.getFieldWithDefault(this,10,new Uint8Array(0))}set difficulty(value){pb_1.Message.setOneofField(this,10,this.#one_of_decls[7],value)}get has_difficulty(){return pb_1.Message.getField(this,10)!=null}get parent_entropy(){return pb_1.Message.getFieldWithDefault(this,11,[])}set parent_entropy(value){pb_1.Message.setField(this,11,value)}get parent_delta_s(){return pb_1.Message.getFieldWithDefault(this,12,[])}set parent_delta_s(value){pb_1.Message.setField(this,12,value)}get parent_uncled_sub_delta_s(){return pb_1.Message.getFieldWithDefault(this,13,[])}set parent_uncled_sub_delta_s(value){pb_1.Message.setField(this,13,value)}get uncled_s(){return pb_1.Message.getFieldWithDefault(this,14,new Uint8Array(0))}set uncled_s(value){pb_1.Message.setOneofField(this,14,this.#one_of_decls[8],value)}get has_uncled_s(){return pb_1.Message.getField(this,14)!=null}get number(){return pb_1.Message.getFieldWithDefault(this,15,[])}set number(value){pb_1.Message.setField(this,15,value)}get gas_limit(){return pb_1.Message.getFieldWithDefault(this,16,0)}set gas_limit(value){pb_1.Message.setOneofField(this,16,this.#one_of_decls[9],value)}get has_gas_limit(){return pb_1.Message.getField(this,16)!=null}get gas_used(){return pb_1.Message.getFieldWithDefault(this,17,0)}set gas_used(value){pb_1.Message.setOneofField(this,17,this.#one_of_decls[10],value)}get has_gas_used(){return pb_1.Message.getField(this,17)!=null}get base_fee(){return pb_1.Message.getFieldWithDefault(this,18,new Uint8Array(0))}set base_fee(value){pb_1.Message.setOneofField(this,18,this.#one_of_decls[11],value)}get has_base_fee(){return pb_1.Message.getField(this,18)!=null}get location(){return pb_1.Message.getWrapperField(this,common.ProtoLocation,19)}set location(value){pb_1.Message.setOneofWrapperField(this,19,this.#one_of_decls[12],value)}get has_location(){return pb_1.Message.getField(this,19)!=null}get extra(){return pb_1.Message.getFieldWithDefault(this,20,new Uint8Array(0))}set extra(value){pb_1.Message.setOneofField(this,20,this.#one_of_decls[13],value)}get has_extra(){return pb_1.Message.getField(this,20)!=null}get mix_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,21)}set mix_hash(value){pb_1.Message.setOneofWrapperField(this,21,this.#one_of_decls[14],value)}get has_mix_hash(){return pb_1.Message.getField(this,21)!=null}get nonce(){return pb_1.Message.getFieldWithDefault(this,22,0)}set nonce(value){pb_1.Message.setOneofField(this,22,this.#one_of_decls[15],value)}get has_nonce(){return pb_1.Message.getField(this,22)!=null}get utxo_root(){return pb_1.Message.getWrapperField(this,common.ProtoHash,23)}set utxo_root(value){pb_1.Message.setOneofWrapperField(this,23,this.#one_of_decls[16],value)}get has_utxo_root(){return pb_1.Message.getField(this,23)!=null}get etx_set_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,24)}set etx_set_hash(value){pb_1.Message.setOneofWrapperField(this,24,this.#one_of_decls[17],value)}get has_etx_set_hash(){return pb_1.Message.getField(this,24)!=null}get efficiency_score(){return pb_1.Message.getFieldWithDefault(this,25,0)}set efficiency_score(value){pb_1.Message.setOneofField(this,25,this.#one_of_decls[18],value)}get has_efficiency_score(){return pb_1.Message.getField(this,25)!=null}get threshold_count(){return pb_1.Message.getFieldWithDefault(this,26,0)}set threshold_count(value){pb_1.Message.setOneofField(this,26,this.#one_of_decls[19],value)}get has_threshold_count(){return pb_1.Message.getField(this,26)!=null}get expansion_number(){return pb_1.Message.getFieldWithDefault(this,27,0)}set expansion_number(value){pb_1.Message.setOneofField(this,27,this.#one_of_decls[20],value)}get has_expansion_number(){return pb_1.Message.getField(this,27)!=null}get etx_eligible_slices(){return pb_1.Message.getWrapperField(this,common.ProtoHash,28)}set etx_eligible_slices(value){pb_1.Message.setOneofWrapperField(this,28,this.#one_of_decls[21],value)}get has_etx_eligible_slices(){return pb_1.Message.getField(this,28)!=null}get prime_terminus(){return pb_1.Message.getWrapperField(this,common.ProtoHash,29)}set prime_terminus(value){pb_1.Message.setOneofWrapperField(this,29,this.#one_of_decls[22],value)}get has_prime_terminus(){return pb_1.Message.getField(this,29)!=null}get interlink_root_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,30)}set interlink_root_hash(value){pb_1.Message.setOneofWrapperField(this,30,this.#one_of_decls[23],value)}get has_interlink_root_hash(){return pb_1.Message.getField(this,30)!=null}get _uncle_hash(){const cases={0:"none",2:"uncle_hash"};return cases[pb_1.Message.computeOneofCase(this,[2])]}get _coinbase(){const cases={0:"none",3:"coinbase"};return cases[pb_1.Message.computeOneofCase(this,[3])]}get _evm_root(){const cases={0:"none",4:"evm_root"};return cases[pb_1.Message.computeOneofCase(this,[4])]}get _tx_hash(){const cases={0:"none",5:"tx_hash"};return cases[pb_1.Message.computeOneofCase(this,[5])]}get _etx_hash(){const cases={0:"none",6:"etx_hash"};return cases[pb_1.Message.computeOneofCase(this,[6])]}get _etx_rollup_hash(){const cases={0:"none",7:"etx_rollup_hash"};return cases[pb_1.Message.computeOneofCase(this,[7])]}get _receipt_hash(){const cases={0:"none",9:"receipt_hash"};return cases[pb_1.Message.computeOneofCase(this,[9])]}get _difficulty(){const cases={0:"none",10:"difficulty"};return cases[pb_1.Message.computeOneofCase(this,[10])]}get _uncled_s(){const cases={0:"none",14:"uncled_s"};return cases[pb_1.Message.computeOneofCase(this,[14])]}get _gas_limit(){const cases={0:"none",16:"gas_limit"};return cases[pb_1.Message.computeOneofCase(this,[16])]}get _gas_used(){const cases={0:"none",17:"gas_used"};return cases[pb_1.Message.computeOneofCase(this,[17])]}get _base_fee(){const cases={0:"none",18:"base_fee"};return cases[pb_1.Message.computeOneofCase(this,[18])]}get _location(){const cases={0:"none",19:"location"};return cases[pb_1.Message.computeOneofCase(this,[19])]}get _extra(){const cases={0:"none",20:"extra"};return cases[pb_1.Message.computeOneofCase(this,[20])]}get _mix_hash(){const cases={0:"none",21:"mix_hash"};return cases[pb_1.Message.computeOneofCase(this,[21])]}get _nonce(){const cases={0:"none",22:"nonce"};return cases[pb_1.Message.computeOneofCase(this,[22])]}get _utxo_root(){const cases={0:"none",23:"utxo_root"};return cases[pb_1.Message.computeOneofCase(this,[23])]}get _etx_set_hash(){const cases={0:"none",24:"etx_set_hash"};return cases[pb_1.Message.computeOneofCase(this,[24])]}get _efficiency_score(){const cases={0:"none",25:"efficiency_score"};return cases[pb_1.Message.computeOneofCase(this,[25])]}get _threshold_count(){const cases={0:"none",26:"threshold_count"};return cases[pb_1.Message.computeOneofCase(this,[26])]}get _expansion_number(){const cases={0:"none",27:"expansion_number"};return cases[pb_1.Message.computeOneofCase(this,[27])]}get _etx_eligible_slices(){const cases={0:"none",28:"etx_eligible_slices"};return cases[pb_1.Message.computeOneofCase(this,[28])]}get _prime_terminus(){const cases={0:"none",29:"prime_terminus"};return cases[pb_1.Message.computeOneofCase(this,[29])]}get _interlink_root_hash(){const cases={0:"none",30:"interlink_root_hash"};return cases[pb_1.Message.computeOneofCase(this,[30])]}static fromObject(data){const message=new ProtoHeader({});if(data.parent_hash!=null){message.parent_hash=data.parent_hash.map(item=>common.ProtoHash.fromObject(item))}if(data.uncle_hash!=null){message.uncle_hash=common.ProtoHash.fromObject(data.uncle_hash)}if(data.coinbase!=null){message.coinbase=data.coinbase}if(data.evm_root!=null){message.evm_root=common.ProtoHash.fromObject(data.evm_root)}if(data.tx_hash!=null){message.tx_hash=common.ProtoHash.fromObject(data.tx_hash)}if(data.etx_hash!=null){message.etx_hash=common.ProtoHash.fromObject(data.etx_hash)}if(data.etx_rollup_hash!=null){message.etx_rollup_hash=common.ProtoHash.fromObject(data.etx_rollup_hash)}if(data.manifest_hash!=null){message.manifest_hash=data.manifest_hash.map(item=>common.ProtoHash.fromObject(item))}if(data.receipt_hash!=null){message.receipt_hash=common.ProtoHash.fromObject(data.receipt_hash)}if(data.difficulty!=null){message.difficulty=data.difficulty}if(data.parent_entropy!=null){message.parent_entropy=data.parent_entropy}if(data.parent_delta_s!=null){message.parent_delta_s=data.parent_delta_s}if(data.parent_uncled_sub_delta_s!=null){message.parent_uncled_sub_delta_s=data.parent_uncled_sub_delta_s}if(data.uncled_s!=null){message.uncled_s=data.uncled_s}if(data.number!=null){message.number=data.number}if(data.gas_limit!=null){message.gas_limit=data.gas_limit}if(data.gas_used!=null){message.gas_used=data.gas_used}if(data.base_fee!=null){message.base_fee=data.base_fee}if(data.location!=null){message.location=common.ProtoLocation.fromObject(data.location)}if(data.extra!=null){message.extra=data.extra}if(data.mix_hash!=null){message.mix_hash=common.ProtoHash.fromObject(data.mix_hash)}if(data.nonce!=null){message.nonce=data.nonce}if(data.utxo_root!=null){message.utxo_root=common.ProtoHash.fromObject(data.utxo_root)}if(data.etx_set_hash!=null){message.etx_set_hash=common.ProtoHash.fromObject(data.etx_set_hash)}if(data.efficiency_score!=null){message.efficiency_score=data.efficiency_score}if(data.threshold_count!=null){message.threshold_count=data.threshold_count}if(data.expansion_number!=null){message.expansion_number=data.expansion_number}if(data.etx_eligible_slices!=null){message.etx_eligible_slices=common.ProtoHash.fromObject(data.etx_eligible_slices)}if(data.prime_terminus!=null){message.prime_terminus=common.ProtoHash.fromObject(data.prime_terminus)}if(data.interlink_root_hash!=null){message.interlink_root_hash=common.ProtoHash.fromObject(data.interlink_root_hash)}return message}toObject(){const data={};if(this.parent_hash!=null){data.parent_hash=this.parent_hash.map(item=>item.toObject())}if(this.uncle_hash!=null){data.uncle_hash=this.uncle_hash.toObject()}if(this.coinbase!=null){data.coinbase=this.coinbase}if(this.evm_root!=null){data.evm_root=this.evm_root.toObject()}if(this.tx_hash!=null){data.tx_hash=this.tx_hash.toObject()}if(this.etx_hash!=null){data.etx_hash=this.etx_hash.toObject()}if(this.etx_rollup_hash!=null){data.etx_rollup_hash=this.etx_rollup_hash.toObject()}if(this.manifest_hash!=null){data.manifest_hash=this.manifest_hash.map(item=>item.toObject())}if(this.receipt_hash!=null){data.receipt_hash=this.receipt_hash.toObject()}if(this.difficulty!=null){data.difficulty=this.difficulty}if(this.parent_entropy!=null){data.parent_entropy=this.parent_entropy}if(this.parent_delta_s!=null){data.parent_delta_s=this.parent_delta_s}if(this.parent_uncled_sub_delta_s!=null){data.parent_uncled_sub_delta_s=this.parent_uncled_sub_delta_s}if(this.uncled_s!=null){data.uncled_s=this.uncled_s}if(this.number!=null){data.number=this.number}if(this.gas_limit!=null){data.gas_limit=this.gas_limit}if(this.gas_used!=null){data.gas_used=this.gas_used}if(this.base_fee!=null){data.base_fee=this.base_fee}if(this.location!=null){data.location=this.location.toObject()}if(this.extra!=null){data.extra=this.extra}if(this.mix_hash!=null){data.mix_hash=this.mix_hash.toObject()}if(this.nonce!=null){data.nonce=this.nonce}if(this.utxo_root!=null){data.utxo_root=this.utxo_root.toObject()}if(this.etx_set_hash!=null){data.etx_set_hash=this.etx_set_hash.toObject()}if(this.efficiency_score!=null){data.efficiency_score=this.efficiency_score}if(this.threshold_count!=null){data.threshold_count=this.threshold_count}if(this.expansion_number!=null){data.expansion_number=this.expansion_number}if(this.etx_eligible_slices!=null){data.etx_eligible_slices=this.etx_eligible_slices.toObject()}if(this.prime_terminus!=null){data.prime_terminus=this.prime_terminus.toObject()}if(this.interlink_root_hash!=null){data.interlink_root_hash=this.interlink_root_hash.toObject()}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.parent_hash.length)writer.writeRepeatedMessage(1,this.parent_hash,item=>item.serialize(writer));if(this.has_uncle_hash)writer.writeMessage(2,this.uncle_hash,()=>this.uncle_hash.serialize(writer));if(this.has_coinbase)writer.writeBytes(3,this.coinbase);if(this.has_evm_root)writer.writeMessage(4,this.evm_root,()=>this.evm_root.serialize(writer));if(this.has_tx_hash)writer.writeMessage(5,this.tx_hash,()=>this.tx_hash.serialize(writer));if(this.has_etx_hash)writer.writeMessage(6,this.etx_hash,()=>this.etx_hash.serialize(writer));if(this.has_etx_rollup_hash)writer.writeMessage(7,this.etx_rollup_hash,()=>this.etx_rollup_hash.serialize(writer));if(this.manifest_hash.length)writer.writeRepeatedMessage(8,this.manifest_hash,item=>item.serialize(writer));if(this.has_receipt_hash)writer.writeMessage(9,this.receipt_hash,()=>this.receipt_hash.serialize(writer));if(this.has_difficulty)writer.writeBytes(10,this.difficulty);if(this.parent_entropy.length)writer.writeRepeatedBytes(11,this.parent_entropy);if(this.parent_delta_s.length)writer.writeRepeatedBytes(12,this.parent_delta_s);if(this.parent_uncled_sub_delta_s.length)writer.writeRepeatedBytes(13,this.parent_uncled_sub_delta_s);if(this.has_uncled_s)writer.writeBytes(14,this.uncled_s);if(this.number.length)writer.writeRepeatedBytes(15,this.number);if(this.has_gas_limit)writer.writeUint64(16,this.gas_limit);if(this.has_gas_used)writer.writeUint64(17,this.gas_used);if(this.has_base_fee)writer.writeBytes(18,this.base_fee);if(this.has_location)writer.writeMessage(19,this.location,()=>this.location.serialize(writer));if(this.has_extra)writer.writeBytes(20,this.extra);if(this.has_mix_hash)writer.writeMessage(21,this.mix_hash,()=>this.mix_hash.serialize(writer));if(this.has_nonce)writer.writeUint64(22,this.nonce);if(this.has_utxo_root)writer.writeMessage(23,this.utxo_root,()=>this.utxo_root.serialize(writer));if(this.has_etx_set_hash)writer.writeMessage(24,this.etx_set_hash,()=>this.etx_set_hash.serialize(writer));if(this.has_efficiency_score)writer.writeUint64(25,this.efficiency_score);if(this.has_threshold_count)writer.writeUint64(26,this.threshold_count);if(this.has_expansion_number)writer.writeUint64(27,this.expansion_number);if(this.has_etx_eligible_slices)writer.writeMessage(28,this.etx_eligible_slices,()=>this.etx_eligible_slices.serialize(writer));if(this.has_prime_terminus)writer.writeMessage(29,this.prime_terminus,()=>this.prime_terminus.serialize(writer));if(this.has_interlink_root_hash)writer.writeMessage(30,this.interlink_root_hash,()=>this.interlink_root_hash.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoHeader;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.parent_hash,()=>pb_1.Message.addToRepeatedWrapperField(message,1,common.ProtoHash.deserialize(reader),common.ProtoHash));break;case 2:reader.readMessage(message.uncle_hash,()=>message.uncle_hash=common.ProtoHash.deserialize(reader));break;case 3:message.coinbase=reader.readBytes();break;case 4:reader.readMessage(message.evm_root,()=>message.evm_root=common.ProtoHash.deserialize(reader));break;case 5:reader.readMessage(message.tx_hash,()=>message.tx_hash=common.ProtoHash.deserialize(reader));break;case 6:reader.readMessage(message.etx_hash,()=>message.etx_hash=common.ProtoHash.deserialize(reader));break;case 7:reader.readMessage(message.etx_rollup_hash,()=>message.etx_rollup_hash=common.ProtoHash.deserialize(reader));break;case 8:reader.readMessage(message.manifest_hash,()=>pb_1.Message.addToRepeatedWrapperField(message,8,common.ProtoHash.deserialize(reader),common.ProtoHash));break;case 9:reader.readMessage(message.receipt_hash,()=>message.receipt_hash=common.ProtoHash.deserialize(reader));break;case 10:message.difficulty=reader.readBytes();break;case 11:pb_1.Message.addToRepeatedField(message,11,reader.readBytes());break;case 12:pb_1.Message.addToRepeatedField(message,12,reader.readBytes());break;case 13:pb_1.Message.addToRepeatedField(message,13,reader.readBytes());break;case 14:message.uncled_s=reader.readBytes();break;case 15:pb_1.Message.addToRepeatedField(message,15,reader.readBytes());break;case 16:message.gas_limit=reader.readUint64();break;case 17:message.gas_used=reader.readUint64();break;case 18:message.base_fee=reader.readBytes();break;case 19:reader.readMessage(message.location,()=>message.location=common.ProtoLocation.deserialize(reader));break;case 20:message.extra=reader.readBytes();break;case 21:reader.readMessage(message.mix_hash,()=>message.mix_hash=common.ProtoHash.deserialize(reader));break;case 22:message.nonce=reader.readUint64();break;case 23:reader.readMessage(message.utxo_root,()=>message.utxo_root=common.ProtoHash.deserialize(reader));break;case 24:reader.readMessage(message.etx_set_hash,()=>message.etx_set_hash=common.ProtoHash.deserialize(reader));break;case 25:message.efficiency_score=reader.readUint64();break;case 26:message.threshold_count=reader.readUint64();break;case 27:message.expansion_number=reader.readUint64();break;case 28:reader.readMessage(message.etx_eligible_slices,()=>message.etx_eligible_slices=common.ProtoHash.deserialize(reader));break;case 29:reader.readMessage(message.prime_terminus,()=>message.prime_terminus=common.ProtoHash.deserialize(reader));break;case 30:reader.readMessage(message.interlink_root_hash,()=>message.interlink_root_hash=common.ProtoHash.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoHeader.deserialize(bytes)}}block.ProtoHeader=ProtoHeader;class ProtoTransaction extends pb_1.Message{#one_of_decls=[[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("type"in data&&data.type!=undefined){this.type=data.type}if("to"in data&&data.to!=undefined){this.to=data.to}if("nonce"in data&&data.nonce!=undefined){this.nonce=data.nonce}if("value"in data&&data.value!=undefined){this.value=data.value}if("gas"in data&&data.gas!=undefined){this.gas=data.gas}if("data"in data&&data.data!=undefined){this.data=data.data}if("chain_id"in data&&data.chain_id!=undefined){this.chain_id=data.chain_id}if("gas_fee_cap"in data&&data.gas_fee_cap!=undefined){this.gas_fee_cap=data.gas_fee_cap}if("gas_tip_cap"in data&&data.gas_tip_cap!=undefined){this.gas_tip_cap=data.gas_tip_cap}if("access_list"in data&&data.access_list!=undefined){this.access_list=data.access_list}if("v"in data&&data.v!=undefined){this.v=data.v}if("r"in data&&data.r!=undefined){this.r=data.r}if("s"in data&&data.s!=undefined){this.s=data.s}if("originating_tx_hash"in data&&data.originating_tx_hash!=undefined){this.originating_tx_hash=data.originating_tx_hash}if("etx_index"in data&&data.etx_index!=undefined){this.etx_index=data.etx_index}if("tx_ins"in data&&data.tx_ins!=undefined){this.tx_ins=data.tx_ins}if("tx_outs"in data&&data.tx_outs!=undefined){this.tx_outs=data.tx_outs}if("signature"in data&&data.signature!=undefined){this.signature=data.signature}if("etx_sender"in data&&data.etx_sender!=undefined){this.etx_sender=data.etx_sender}}}get type(){return pb_1.Message.getFieldWithDefault(this,1,0)}set type(value){pb_1.Message.setOneofField(this,1,this.#one_of_decls[0],value)}get has_type(){return pb_1.Message.getField(this,1)!=null}get to(){return pb_1.Message.getFieldWithDefault(this,2,new Uint8Array(0))}set to(value){pb_1.Message.setOneofField(this,2,this.#one_of_decls[1],value)}get has_to(){return pb_1.Message.getField(this,2)!=null}get nonce(){return pb_1.Message.getFieldWithDefault(this,3,0)}set nonce(value){pb_1.Message.setOneofField(this,3,this.#one_of_decls[2],value)}get has_nonce(){return pb_1.Message.getField(this,3)!=null}get value(){return pb_1.Message.getFieldWithDefault(this,4,new Uint8Array(0))}set value(value){pb_1.Message.setOneofField(this,4,this.#one_of_decls[3],value)}get has_value(){return pb_1.Message.getField(this,4)!=null}get gas(){return pb_1.Message.getFieldWithDefault(this,5,0)}set gas(value){pb_1.Message.setOneofField(this,5,this.#one_of_decls[4],value)}get has_gas(){return pb_1.Message.getField(this,5)!=null}get data(){return pb_1.Message.getFieldWithDefault(this,6,new Uint8Array(0))}set data(value){pb_1.Message.setOneofField(this,6,this.#one_of_decls[5],value)}get has_data(){return pb_1.Message.getField(this,6)!=null}get chain_id(){return pb_1.Message.getFieldWithDefault(this,7,new Uint8Array(0))}set chain_id(value){pb_1.Message.setOneofField(this,7,this.#one_of_decls[6],value)}get has_chain_id(){return pb_1.Message.getField(this,7)!=null}get gas_fee_cap(){return pb_1.Message.getFieldWithDefault(this,8,new Uint8Array(0))}set gas_fee_cap(value){pb_1.Message.setOneofField(this,8,this.#one_of_decls[7],value)}get has_gas_fee_cap(){return pb_1.Message.getField(this,8)!=null}get gas_tip_cap(){return pb_1.Message.getFieldWithDefault(this,9,new Uint8Array(0))}set gas_tip_cap(value){pb_1.Message.setOneofField(this,9,this.#one_of_decls[8],value)}get has_gas_tip_cap(){return pb_1.Message.getField(this,9)!=null}get access_list(){return pb_1.Message.getWrapperField(this,ProtoAccessList,10)}set access_list(value){pb_1.Message.setOneofWrapperField(this,10,this.#one_of_decls[9],value)}get has_access_list(){return pb_1.Message.getField(this,10)!=null}get v(){return pb_1.Message.getFieldWithDefault(this,11,new Uint8Array(0))}set v(value){pb_1.Message.setOneofField(this,11,this.#one_of_decls[10],value)}get has_v(){return pb_1.Message.getField(this,11)!=null}get r(){return pb_1.Message.getFieldWithDefault(this,12,new Uint8Array(0))}set r(value){pb_1.Message.setOneofField(this,12,this.#one_of_decls[11],value)}get has_r(){return pb_1.Message.getField(this,12)!=null}get s(){return pb_1.Message.getFieldWithDefault(this,13,new Uint8Array(0))}set s(value){pb_1.Message.setOneofField(this,13,this.#one_of_decls[12],value)}get has_s(){return pb_1.Message.getField(this,13)!=null}get originating_tx_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,14)}set originating_tx_hash(value){pb_1.Message.setOneofWrapperField(this,14,this.#one_of_decls[13],value)}get has_originating_tx_hash(){return pb_1.Message.getField(this,14)!=null}get etx_index(){return pb_1.Message.getFieldWithDefault(this,15,0)}set etx_index(value){pb_1.Message.setOneofField(this,15,this.#one_of_decls[14],value)}get has_etx_index(){return pb_1.Message.getField(this,15)!=null}get tx_ins(){return pb_1.Message.getWrapperField(this,ProtoTxIns,16)}set tx_ins(value){pb_1.Message.setOneofWrapperField(this,16,this.#one_of_decls[15],value)}get has_tx_ins(){return pb_1.Message.getField(this,16)!=null}get tx_outs(){return pb_1.Message.getWrapperField(this,ProtoTxOuts,17)}set tx_outs(value){pb_1.Message.setOneofWrapperField(this,17,this.#one_of_decls[16],value)}get has_tx_outs(){return pb_1.Message.getField(this,17)!=null}get signature(){return pb_1.Message.getFieldWithDefault(this,18,new Uint8Array(0))}set signature(value){pb_1.Message.setOneofField(this,18,this.#one_of_decls[17],value)}get has_signature(){return pb_1.Message.getField(this,18)!=null}get etx_sender(){return pb_1.Message.getFieldWithDefault(this,19,new Uint8Array(0))}set etx_sender(value){pb_1.Message.setOneofField(this,19,this.#one_of_decls[18],value)}get has_etx_sender(){return pb_1.Message.getField(this,19)!=null}get _type(){const cases={0:"none",1:"type"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _to(){const cases={0:"none",2:"to"};return cases[pb_1.Message.computeOneofCase(this,[2])]}get _nonce(){const cases={0:"none",3:"nonce"};return cases[pb_1.Message.computeOneofCase(this,[3])]}get _value(){const cases={0:"none",4:"value"};return cases[pb_1.Message.computeOneofCase(this,[4])]}get _gas(){const cases={0:"none",5:"gas"};return cases[pb_1.Message.computeOneofCase(this,[5])]}get _data(){const cases={0:"none",6:"data"};return cases[pb_1.Message.computeOneofCase(this,[6])]}get _chain_id(){const cases={0:"none",7:"chain_id"};return cases[pb_1.Message.computeOneofCase(this,[7])]}get _gas_fee_cap(){const cases={0:"none",8:"gas_fee_cap"};return cases[pb_1.Message.computeOneofCase(this,[8])]}get _gas_tip_cap(){const cases={0:"none",9:"gas_tip_cap"};return cases[pb_1.Message.computeOneofCase(this,[9])]}get _access_list(){const cases={0:"none",10:"access_list"};return cases[pb_1.Message.computeOneofCase(this,[10])]}get _v(){const cases={0:"none",11:"v"};return cases[pb_1.Message.computeOneofCase(this,[11])]}get _r(){const cases={0:"none",12:"r"};return cases[pb_1.Message.computeOneofCase(this,[12])]}get _s(){const cases={0:"none",13:"s"};return cases[pb_1.Message.computeOneofCase(this,[13])]}get _originating_tx_hash(){const cases={0:"none",14:"originating_tx_hash"};return cases[pb_1.Message.computeOneofCase(this,[14])]}get _etx_index(){const cases={0:"none",15:"etx_index"};return cases[pb_1.Message.computeOneofCase(this,[15])]}get _tx_ins(){const cases={0:"none",16:"tx_ins"};return cases[pb_1.Message.computeOneofCase(this,[16])]}get _tx_outs(){const cases={0:"none",17:"tx_outs"};return cases[pb_1.Message.computeOneofCase(this,[17])]}get _signature(){const cases={0:"none",18:"signature"};return cases[pb_1.Message.computeOneofCase(this,[18])]}get _etx_sender(){const cases={0:"none",19:"etx_sender"};return cases[pb_1.Message.computeOneofCase(this,[19])]}static fromObject(data){const message=new ProtoTransaction({});if(data.type!=null){message.type=data.type}if(data.to!=null){message.to=data.to}if(data.nonce!=null){message.nonce=data.nonce}if(data.value!=null){message.value=data.value}if(data.gas!=null){message.gas=data.gas}if(data.data!=null){message.data=data.data}if(data.chain_id!=null){message.chain_id=data.chain_id}if(data.gas_fee_cap!=null){message.gas_fee_cap=data.gas_fee_cap}if(data.gas_tip_cap!=null){message.gas_tip_cap=data.gas_tip_cap}if(data.access_list!=null){message.access_list=ProtoAccessList.fromObject(data.access_list)}if(data.v!=null){message.v=data.v}if(data.r!=null){message.r=data.r}if(data.s!=null){message.s=data.s}if(data.originating_tx_hash!=null){message.originating_tx_hash=common.ProtoHash.fromObject(data.originating_tx_hash)}if(data.etx_index!=null){message.etx_index=data.etx_index}if(data.tx_ins!=null){message.tx_ins=ProtoTxIns.fromObject(data.tx_ins)}if(data.tx_outs!=null){message.tx_outs=ProtoTxOuts.fromObject(data.tx_outs)}if(data.signature!=null){message.signature=data.signature}if(data.etx_sender!=null){message.etx_sender=data.etx_sender}return message}toObject(){const data={};if(this.type!=null){data.type=this.type}if(this.to!=null){data.to=this.to}if(this.nonce!=null){data.nonce=this.nonce}if(this.value!=null){data.value=this.value}if(this.gas!=null){data.gas=this.gas}if(this.data!=null){data.data=this.data}if(this.chain_id!=null){data.chain_id=this.chain_id}if(this.gas_fee_cap!=null){data.gas_fee_cap=this.gas_fee_cap}if(this.gas_tip_cap!=null){data.gas_tip_cap=this.gas_tip_cap}if(this.access_list!=null){data.access_list=this.access_list.toObject()}if(this.v!=null){data.v=this.v}if(this.r!=null){data.r=this.r}if(this.s!=null){data.s=this.s}if(this.originating_tx_hash!=null){data.originating_tx_hash=this.originating_tx_hash.toObject()}if(this.etx_index!=null){data.etx_index=this.etx_index}if(this.tx_ins!=null){data.tx_ins=this.tx_ins.toObject()}if(this.tx_outs!=null){data.tx_outs=this.tx_outs.toObject()}if(this.signature!=null){data.signature=this.signature}if(this.etx_sender!=null){data.etx_sender=this.etx_sender}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_type)writer.writeUint64(1,this.type);if(this.has_to)writer.writeBytes(2,this.to);if(this.has_nonce)writer.writeUint64(3,this.nonce);if(this.has_value)writer.writeBytes(4,this.value);if(this.has_gas)writer.writeUint64(5,this.gas);if(this.has_data)writer.writeBytes(6,this.data);if(this.has_chain_id)writer.writeBytes(7,this.chain_id);if(this.has_gas_fee_cap)writer.writeBytes(8,this.gas_fee_cap);if(this.has_gas_tip_cap)writer.writeBytes(9,this.gas_tip_cap);if(this.has_access_list)writer.writeMessage(10,this.access_list,()=>this.access_list.serialize(writer));if(this.has_v)writer.writeBytes(11,this.v);if(this.has_r)writer.writeBytes(12,this.r);if(this.has_s)writer.writeBytes(13,this.s);if(this.has_originating_tx_hash)writer.writeMessage(14,this.originating_tx_hash,()=>this.originating_tx_hash.serialize(writer));if(this.has_etx_index)writer.writeUint32(15,this.etx_index);if(this.has_tx_ins)writer.writeMessage(16,this.tx_ins,()=>this.tx_ins.serialize(writer));if(this.has_tx_outs)writer.writeMessage(17,this.tx_outs,()=>this.tx_outs.serialize(writer));if(this.has_signature)writer.writeBytes(18,this.signature);if(this.has_etx_sender)writer.writeBytes(19,this.etx_sender);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoTransaction;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.type=reader.readUint64();break;case 2:message.to=reader.readBytes();break;case 3:message.nonce=reader.readUint64();break;case 4:message.value=reader.readBytes();break;case 5:message.gas=reader.readUint64();break;case 6:message.data=reader.readBytes();break;case 7:message.chain_id=reader.readBytes();break;case 8:message.gas_fee_cap=reader.readBytes();break;case 9:message.gas_tip_cap=reader.readBytes();break;case 10:reader.readMessage(message.access_list,()=>message.access_list=ProtoAccessList.deserialize(reader));break;case 11:message.v=reader.readBytes();break;case 12:message.r=reader.readBytes();break;case 13:message.s=reader.readBytes();break;case 14:reader.readMessage(message.originating_tx_hash,()=>message.originating_tx_hash=common.ProtoHash.deserialize(reader));break;case 15:message.etx_index=reader.readUint32();break;case 16:reader.readMessage(message.tx_ins,()=>message.tx_ins=ProtoTxIns.deserialize(reader));break;case 17:reader.readMessage(message.tx_outs,()=>message.tx_outs=ProtoTxOuts.deserialize(reader));break;case 18:message.signature=reader.readBytes();break;case 19:message.etx_sender=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTransaction.deserialize(bytes)}}block.ProtoTransaction=ProtoTransaction;class ProtoTransactions extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("transactions"in data&&data.transactions!=undefined){this.transactions=data.transactions}}}get transactions(){return pb_1.Message.getRepeatedWrapperField(this,ProtoTransaction,1)}set transactions(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoTransactions({});if(data.transactions!=null){message.transactions=data.transactions.map(item=>ProtoTransaction.fromObject(item))}return message}toObject(){const data={};if(this.transactions!=null){data.transactions=this.transactions.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.transactions.length)writer.writeRepeatedMessage(1,this.transactions,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoTransactions;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.transactions,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoTransaction.deserialize(reader),ProtoTransaction));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTransactions.deserialize(bytes)}}block.ProtoTransactions=ProtoTransactions;class ProtoHeaders extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("headers"in data&&data.headers!=undefined){this.headers=data.headers}}}get headers(){return pb_1.Message.getRepeatedWrapperField(this,ProtoHeader,1)}set headers(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoHeaders({});if(data.headers!=null){message.headers=data.headers.map(item=>ProtoHeader.fromObject(item))}return message}toObject(){const data={};if(this.headers!=null){data.headers=this.headers.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.headers.length)writer.writeRepeatedMessage(1,this.headers,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoHeaders;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.headers,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoHeader.deserialize(reader),ProtoHeader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoHeaders.deserialize(bytes)}}block.ProtoHeaders=ProtoHeaders;class ProtoManifest extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("manifest"in data&&data.manifest!=undefined){this.manifest=data.manifest}}}get manifest(){return pb_1.Message.getRepeatedWrapperField(this,common.ProtoHash,1)}set manifest(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoManifest({});if(data.manifest!=null){message.manifest=data.manifest.map(item=>common.ProtoHash.fromObject(item))}return message}toObject(){const data={};if(this.manifest!=null){data.manifest=this.manifest.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.manifest.length)writer.writeRepeatedMessage(1,this.manifest,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoManifest;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.manifest,()=>pb_1.Message.addToRepeatedWrapperField(message,1,common.ProtoHash.deserialize(reader),common.ProtoHash));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoManifest.deserialize(bytes)}}block.ProtoManifest=ProtoManifest;class ProtoAccessList extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("access_tuples"in data&&data.access_tuples!=undefined){this.access_tuples=data.access_tuples}}}get access_tuples(){return pb_1.Message.getRepeatedWrapperField(this,ProtoAccessTuple,1)}set access_tuples(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoAccessList({});if(data.access_tuples!=null){message.access_tuples=data.access_tuples.map(item=>ProtoAccessTuple.fromObject(item))}return message}toObject(){const data={};if(this.access_tuples!=null){data.access_tuples=this.access_tuples.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.access_tuples.length)writer.writeRepeatedMessage(1,this.access_tuples,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoAccessList;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.access_tuples,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoAccessTuple.deserialize(reader),ProtoAccessTuple));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoAccessList.deserialize(bytes)}}block.ProtoAccessList=ProtoAccessList;class ProtoWorkObjectHeader extends pb_1.Message{#one_of_decls=[[1],[2],[3],[4],[5],[6],[7],[8],[9]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("header_hash"in data&&data.header_hash!=undefined){this.header_hash=data.header_hash}if("parent_hash"in data&&data.parent_hash!=undefined){this.parent_hash=data.parent_hash}if("number"in data&&data.number!=undefined){this.number=data.number}if("difficulty"in data&&data.difficulty!=undefined){this.difficulty=data.difficulty}if("tx_hash"in data&&data.tx_hash!=undefined){this.tx_hash=data.tx_hash}if("nonce"in data&&data.nonce!=undefined){this.nonce=data.nonce}if("location"in data&&data.location!=undefined){this.location=data.location}if("mix_hash"in data&&data.mix_hash!=undefined){this.mix_hash=data.mix_hash}if("time"in data&&data.time!=undefined){this.time=data.time}}}get header_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,1)}set header_hash(value){pb_1.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_header_hash(){return pb_1.Message.getField(this,1)!=null}get parent_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,2)}set parent_hash(value){pb_1.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_parent_hash(){return pb_1.Message.getField(this,2)!=null}get number(){return pb_1.Message.getFieldWithDefault(this,3,new Uint8Array(0))}set number(value){pb_1.Message.setOneofField(this,3,this.#one_of_decls[2],value)}get has_number(){return pb_1.Message.getField(this,3)!=null}get difficulty(){return pb_1.Message.getFieldWithDefault(this,4,new Uint8Array(0))}set difficulty(value){pb_1.Message.setOneofField(this,4,this.#one_of_decls[3],value)}get has_difficulty(){return pb_1.Message.getField(this,4)!=null}get tx_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,5)}set tx_hash(value){pb_1.Message.setOneofWrapperField(this,5,this.#one_of_decls[4],value)}get has_tx_hash(){return pb_1.Message.getField(this,5)!=null}get nonce(){return pb_1.Message.getFieldWithDefault(this,6,0)}set nonce(value){pb_1.Message.setOneofField(this,6,this.#one_of_decls[5],value)}get has_nonce(){return pb_1.Message.getField(this,6)!=null}get location(){return pb_1.Message.getWrapperField(this,common.ProtoLocation,7)}set location(value){pb_1.Message.setOneofWrapperField(this,7,this.#one_of_decls[6],value)}get has_location(){return pb_1.Message.getField(this,7)!=null}get mix_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,8)}set mix_hash(value){pb_1.Message.setOneofWrapperField(this,8,this.#one_of_decls[7],value)}get has_mix_hash(){return pb_1.Message.getField(this,8)!=null}get time(){return pb_1.Message.getFieldWithDefault(this,9,0)}set time(value){pb_1.Message.setOneofField(this,9,this.#one_of_decls[8],value)}get has_time(){return pb_1.Message.getField(this,9)!=null}get _header_hash(){const cases={0:"none",1:"header_hash"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _parent_hash(){const cases={0:"none",2:"parent_hash"};return cases[pb_1.Message.computeOneofCase(this,[2])]}get _number(){const cases={0:"none",3:"number"};return cases[pb_1.Message.computeOneofCase(this,[3])]}get _difficulty(){const cases={0:"none",4:"difficulty"};return cases[pb_1.Message.computeOneofCase(this,[4])]}get _tx_hash(){const cases={0:"none",5:"tx_hash"};return cases[pb_1.Message.computeOneofCase(this,[5])]}get _nonce(){const cases={0:"none",6:"nonce"};return cases[pb_1.Message.computeOneofCase(this,[6])]}get _location(){const cases={0:"none",7:"location"};return cases[pb_1.Message.computeOneofCase(this,[7])]}get _mix_hash(){const cases={0:"none",8:"mix_hash"};return cases[pb_1.Message.computeOneofCase(this,[8])]}get _time(){const cases={0:"none",9:"time"};return cases[pb_1.Message.computeOneofCase(this,[9])]}static fromObject(data){const message=new ProtoWorkObjectHeader({});if(data.header_hash!=null){message.header_hash=common.ProtoHash.fromObject(data.header_hash)}if(data.parent_hash!=null){message.parent_hash=common.ProtoHash.fromObject(data.parent_hash)}if(data.number!=null){message.number=data.number}if(data.difficulty!=null){message.difficulty=data.difficulty}if(data.tx_hash!=null){message.tx_hash=common.ProtoHash.fromObject(data.tx_hash)}if(data.nonce!=null){message.nonce=data.nonce}if(data.location!=null){message.location=common.ProtoLocation.fromObject(data.location)}if(data.mix_hash!=null){message.mix_hash=common.ProtoHash.fromObject(data.mix_hash)}if(data.time!=null){message.time=data.time}return message}toObject(){const data={};if(this.header_hash!=null){data.header_hash=this.header_hash.toObject()}if(this.parent_hash!=null){data.parent_hash=this.parent_hash.toObject()}if(this.number!=null){data.number=this.number}if(this.difficulty!=null){data.difficulty=this.difficulty}if(this.tx_hash!=null){data.tx_hash=this.tx_hash.toObject()}if(this.nonce!=null){data.nonce=this.nonce}if(this.location!=null){data.location=this.location.toObject()}if(this.mix_hash!=null){data.mix_hash=this.mix_hash.toObject()}if(this.time!=null){data.time=this.time}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_header_hash)writer.writeMessage(1,this.header_hash,()=>this.header_hash.serialize(writer));if(this.has_parent_hash)writer.writeMessage(2,this.parent_hash,()=>this.parent_hash.serialize(writer));if(this.has_number)writer.writeBytes(3,this.number);if(this.has_difficulty)writer.writeBytes(4,this.difficulty);if(this.has_tx_hash)writer.writeMessage(5,this.tx_hash,()=>this.tx_hash.serialize(writer));if(this.has_nonce)writer.writeUint64(6,this.nonce);if(this.has_location)writer.writeMessage(7,this.location,()=>this.location.serialize(writer));if(this.has_mix_hash)writer.writeMessage(8,this.mix_hash,()=>this.mix_hash.serialize(writer));if(this.has_time)writer.writeUint64(9,this.time);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoWorkObjectHeader;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.header_hash,()=>message.header_hash=common.ProtoHash.deserialize(reader));break;case 2:reader.readMessage(message.parent_hash,()=>message.parent_hash=common.ProtoHash.deserialize(reader));break;case 3:message.number=reader.readBytes();break;case 4:message.difficulty=reader.readBytes();break;case 5:reader.readMessage(message.tx_hash,()=>message.tx_hash=common.ProtoHash.deserialize(reader));break;case 6:message.nonce=reader.readUint64();break;case 7:reader.readMessage(message.location,()=>message.location=common.ProtoLocation.deserialize(reader));break;case 8:reader.readMessage(message.mix_hash,()=>message.mix_hash=common.ProtoHash.deserialize(reader));break;case 9:message.time=reader.readUint64();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObjectHeader.deserialize(bytes)}}block.ProtoWorkObjectHeader=ProtoWorkObjectHeader;class ProtoWorkObjectHeaders extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("wo_headers"in data&&data.wo_headers!=undefined){this.wo_headers=data.wo_headers}}}get wo_headers(){return pb_1.Message.getRepeatedWrapperField(this,ProtoWorkObjectHeader,1)}set wo_headers(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoWorkObjectHeaders({});if(data.wo_headers!=null){message.wo_headers=data.wo_headers.map(item=>ProtoWorkObjectHeader.fromObject(item))}return message}toObject(){const data={};if(this.wo_headers!=null){data.wo_headers=this.wo_headers.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.wo_headers.length)writer.writeRepeatedMessage(1,this.wo_headers,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoWorkObjectHeaders;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.wo_headers,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoWorkObjectHeader.deserialize(reader),ProtoWorkObjectHeader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObjectHeaders.deserialize(bytes)}}block.ProtoWorkObjectHeaders=ProtoWorkObjectHeaders;class ProtoWorkObjectBody extends pb_1.Message{#one_of_decls=[[1],[2],[3],[4],[5],[6]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("header"in data&&data.header!=undefined){this.header=data.header}if("transactions"in data&&data.transactions!=undefined){this.transactions=data.transactions}if("uncles"in data&&data.uncles!=undefined){this.uncles=data.uncles}if("ext_transactions"in data&&data.ext_transactions!=undefined){this.ext_transactions=data.ext_transactions}if("manifest"in data&&data.manifest!=undefined){this.manifest=data.manifest}if("interlink_hashes"in data&&data.interlink_hashes!=undefined){this.interlink_hashes=data.interlink_hashes}}}get header(){return pb_1.Message.getWrapperField(this,ProtoHeader,1)}set header(value){pb_1.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_header(){return pb_1.Message.getField(this,1)!=null}get transactions(){return pb_1.Message.getWrapperField(this,ProtoTransactions,2)}set transactions(value){pb_1.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_transactions(){return pb_1.Message.getField(this,2)!=null}get uncles(){return pb_1.Message.getWrapperField(this,ProtoWorkObjectHeaders,3)}set uncles(value){pb_1.Message.setOneofWrapperField(this,3,this.#one_of_decls[2],value)}get has_uncles(){return pb_1.Message.getField(this,3)!=null}get ext_transactions(){return pb_1.Message.getWrapperField(this,ProtoTransactions,4)}set ext_transactions(value){pb_1.Message.setOneofWrapperField(this,4,this.#one_of_decls[3],value)}get has_ext_transactions(){return pb_1.Message.getField(this,4)!=null}get manifest(){return pb_1.Message.getWrapperField(this,ProtoManifest,5)}set manifest(value){pb_1.Message.setOneofWrapperField(this,5,this.#one_of_decls[4],value)}get has_manifest(){return pb_1.Message.getField(this,5)!=null}get interlink_hashes(){return pb_1.Message.getWrapperField(this,common.ProtoHashes,6)}set interlink_hashes(value){pb_1.Message.setOneofWrapperField(this,6,this.#one_of_decls[5],value)}get has_interlink_hashes(){return pb_1.Message.getField(this,6)!=null}get _header(){const cases={0:"none",1:"header"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _transactions(){const cases={0:"none",2:"transactions"};return cases[pb_1.Message.computeOneofCase(this,[2])]}get _uncles(){const cases={0:"none",3:"uncles"};return cases[pb_1.Message.computeOneofCase(this,[3])]}get _ext_transactions(){const cases={0:"none",4:"ext_transactions"};return cases[pb_1.Message.computeOneofCase(this,[4])]}get _manifest(){const cases={0:"none",5:"manifest"};return cases[pb_1.Message.computeOneofCase(this,[5])]}get _interlink_hashes(){const cases={0:"none",6:"interlink_hashes"};return cases[pb_1.Message.computeOneofCase(this,[6])]}static fromObject(data){const message=new ProtoWorkObjectBody({});if(data.header!=null){message.header=ProtoHeader.fromObject(data.header)}if(data.transactions!=null){message.transactions=ProtoTransactions.fromObject(data.transactions)}if(data.uncles!=null){message.uncles=ProtoWorkObjectHeaders.fromObject(data.uncles)}if(data.ext_transactions!=null){message.ext_transactions=ProtoTransactions.fromObject(data.ext_transactions)}if(data.manifest!=null){message.manifest=ProtoManifest.fromObject(data.manifest)}if(data.interlink_hashes!=null){message.interlink_hashes=common.ProtoHashes.fromObject(data.interlink_hashes)}return message}toObject(){const data={};if(this.header!=null){data.header=this.header.toObject()}if(this.transactions!=null){data.transactions=this.transactions.toObject()}if(this.uncles!=null){data.uncles=this.uncles.toObject()}if(this.ext_transactions!=null){data.ext_transactions=this.ext_transactions.toObject()}if(this.manifest!=null){data.manifest=this.manifest.toObject()}if(this.interlink_hashes!=null){data.interlink_hashes=this.interlink_hashes.toObject()}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_header)writer.writeMessage(1,this.header,()=>this.header.serialize(writer));if(this.has_transactions)writer.writeMessage(2,this.transactions,()=>this.transactions.serialize(writer));if(this.has_uncles)writer.writeMessage(3,this.uncles,()=>this.uncles.serialize(writer));if(this.has_ext_transactions)writer.writeMessage(4,this.ext_transactions,()=>this.ext_transactions.serialize(writer));if(this.has_manifest)writer.writeMessage(5,this.manifest,()=>this.manifest.serialize(writer));if(this.has_interlink_hashes)writer.writeMessage(6,this.interlink_hashes,()=>this.interlink_hashes.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoWorkObjectBody;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.header,()=>message.header=ProtoHeader.deserialize(reader));break;case 2:reader.readMessage(message.transactions,()=>message.transactions=ProtoTransactions.deserialize(reader));break;case 3:reader.readMessage(message.uncles,()=>message.uncles=ProtoWorkObjectHeaders.deserialize(reader));break;case 4:reader.readMessage(message.ext_transactions,()=>message.ext_transactions=ProtoTransactions.deserialize(reader));break;case 5:reader.readMessage(message.manifest,()=>message.manifest=ProtoManifest.deserialize(reader));break;case 6:reader.readMessage(message.interlink_hashes,()=>message.interlink_hashes=common.ProtoHashes.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObjectBody.deserialize(bytes)}}block.ProtoWorkObjectBody=ProtoWorkObjectBody;class ProtoWorkObject extends pb_1.Message{#one_of_decls=[[1],[2],[3]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("wo_header"in data&&data.wo_header!=undefined){this.wo_header=data.wo_header}if("wo_body"in data&&data.wo_body!=undefined){this.wo_body=data.wo_body}if("tx"in data&&data.tx!=undefined){this.tx=data.tx}}}get wo_header(){return pb_1.Message.getWrapperField(this,ProtoWorkObjectHeader,1)}set wo_header(value){pb_1.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_wo_header(){return pb_1.Message.getField(this,1)!=null}get wo_body(){return pb_1.Message.getWrapperField(this,ProtoWorkObjectBody,2)}set wo_body(value){pb_1.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_wo_body(){return pb_1.Message.getField(this,2)!=null}get tx(){return pb_1.Message.getWrapperField(this,ProtoTransaction,3)}set tx(value){pb_1.Message.setOneofWrapperField(this,3,this.#one_of_decls[2],value)}get has_tx(){return pb_1.Message.getField(this,3)!=null}get _wo_header(){const cases={0:"none",1:"wo_header"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _wo_body(){const cases={0:"none",2:"wo_body"};return cases[pb_1.Message.computeOneofCase(this,[2])]}get _tx(){const cases={0:"none",3:"tx"};return cases[pb_1.Message.computeOneofCase(this,[3])]}static fromObject(data){const message=new ProtoWorkObject({});if(data.wo_header!=null){message.wo_header=ProtoWorkObjectHeader.fromObject(data.wo_header)}if(data.wo_body!=null){message.wo_body=ProtoWorkObjectBody.fromObject(data.wo_body)}if(data.tx!=null){message.tx=ProtoTransaction.fromObject(data.tx)}return message}toObject(){const data={};if(this.wo_header!=null){data.wo_header=this.wo_header.toObject()}if(this.wo_body!=null){data.wo_body=this.wo_body.toObject()}if(this.tx!=null){data.tx=this.tx.toObject()}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_wo_header)writer.writeMessage(1,this.wo_header,()=>this.wo_header.serialize(writer));if(this.has_wo_body)writer.writeMessage(2,this.wo_body,()=>this.wo_body.serialize(writer));if(this.has_tx)writer.writeMessage(3,this.tx,()=>this.tx.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoWorkObject;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.wo_header,()=>message.wo_header=ProtoWorkObjectHeader.deserialize(reader));break;case 2:reader.readMessage(message.wo_body,()=>message.wo_body=ProtoWorkObjectBody.deserialize(reader));break;case 3:reader.readMessage(message.tx,()=>message.tx=ProtoTransaction.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObject.deserialize(bytes)}}block.ProtoWorkObject=ProtoWorkObject;class ProtoWorkObjects extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("work_objects"in data&&data.work_objects!=undefined){this.work_objects=data.work_objects}}}get work_objects(){return pb_1.Message.getRepeatedWrapperField(this,ProtoWorkObject,1)}set work_objects(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoWorkObjects({});if(data.work_objects!=null){message.work_objects=data.work_objects.map(item=>ProtoWorkObject.fromObject(item))}return message}toObject(){const data={};if(this.work_objects!=null){data.work_objects=this.work_objects.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.work_objects.length)writer.writeRepeatedMessage(1,this.work_objects,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoWorkObjects;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.work_objects,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoWorkObject.deserialize(reader),ProtoWorkObject));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObjects.deserialize(bytes)}}block.ProtoWorkObjects=ProtoWorkObjects;class ProtoAccessTuple extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[2],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("address"in data&&data.address!=undefined){this.address=data.address}if("storage_key"in data&&data.storage_key!=undefined){this.storage_key=data.storage_key}}}get address(){return pb_1.Message.getFieldWithDefault(this,1,new Uint8Array(0))}set address(value){pb_1.Message.setField(this,1,value)}get storage_key(){return pb_1.Message.getRepeatedWrapperField(this,common.ProtoHash,2)}set storage_key(value){pb_1.Message.setRepeatedWrapperField(this,2,value)}static fromObject(data){const message=new ProtoAccessTuple({});if(data.address!=null){message.address=data.address}if(data.storage_key!=null){message.storage_key=data.storage_key.map(item=>common.ProtoHash.fromObject(item))}return message}toObject(){const data={};if(this.address!=null){data.address=this.address}if(this.storage_key!=null){data.storage_key=this.storage_key.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.address.length)writer.writeBytes(1,this.address);if(this.storage_key.length)writer.writeRepeatedMessage(2,this.storage_key,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoAccessTuple;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.address=reader.readBytes();break;case 2:reader.readMessage(message.storage_key,()=>pb_1.Message.addToRepeatedWrapperField(message,2,common.ProtoHash.deserialize(reader),common.ProtoHash));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoAccessTuple.deserialize(bytes)}}block.ProtoAccessTuple=ProtoAccessTuple;class ProtoReceiptForStorage extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("post_state_or_status"in data&&data.post_state_or_status!=undefined){this.post_state_or_status=data.post_state_or_status}if("cumulative_gas_used"in data&&data.cumulative_gas_used!=undefined){this.cumulative_gas_used=data.cumulative_gas_used}if("tx_hash"in data&&data.tx_hash!=undefined){this.tx_hash=data.tx_hash}if("contract_address"in data&&data.contract_address!=undefined){this.contract_address=data.contract_address}if("logs"in data&&data.logs!=undefined){this.logs=data.logs}if("etxs"in data&&data.etxs!=undefined){this.etxs=data.etxs}if("gas_used"in data&&data.gas_used!=undefined){this.gas_used=data.gas_used}}}get post_state_or_status(){return pb_1.Message.getFieldWithDefault(this,1,new Uint8Array(0))}set post_state_or_status(value){pb_1.Message.setField(this,1,value)}get cumulative_gas_used(){return pb_1.Message.getFieldWithDefault(this,2,0)}set cumulative_gas_used(value){pb_1.Message.setField(this,2,value)}get tx_hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,3)}set tx_hash(value){pb_1.Message.setWrapperField(this,3,value)}get has_tx_hash(){return pb_1.Message.getField(this,3)!=null}get contract_address(){return pb_1.Message.getWrapperField(this,common.ProtoAddress,4)}set contract_address(value){pb_1.Message.setWrapperField(this,4,value)}get has_contract_address(){return pb_1.Message.getField(this,4)!=null}get logs(){return pb_1.Message.getWrapperField(this,ProtoLogsForStorage,5)}set logs(value){pb_1.Message.setWrapperField(this,5,value)}get has_logs(){return pb_1.Message.getField(this,5)!=null}get etxs(){return pb_1.Message.getWrapperField(this,ProtoTransactions,6)}set etxs(value){pb_1.Message.setWrapperField(this,6,value)}get has_etxs(){return pb_1.Message.getField(this,6)!=null}get gas_used(){return pb_1.Message.getFieldWithDefault(this,7,0)}set gas_used(value){pb_1.Message.setField(this,7,value)}static fromObject(data){const message=new ProtoReceiptForStorage({});if(data.post_state_or_status!=null){message.post_state_or_status=data.post_state_or_status}if(data.cumulative_gas_used!=null){message.cumulative_gas_used=data.cumulative_gas_used}if(data.tx_hash!=null){message.tx_hash=common.ProtoHash.fromObject(data.tx_hash)}if(data.contract_address!=null){message.contract_address=common.ProtoAddress.fromObject(data.contract_address)}if(data.logs!=null){message.logs=ProtoLogsForStorage.fromObject(data.logs)}if(data.etxs!=null){message.etxs=ProtoTransactions.fromObject(data.etxs)}if(data.gas_used!=null){message.gas_used=data.gas_used}return message}toObject(){const data={};if(this.post_state_or_status!=null){data.post_state_or_status=this.post_state_or_status}if(this.cumulative_gas_used!=null){data.cumulative_gas_used=this.cumulative_gas_used}if(this.tx_hash!=null){data.tx_hash=this.tx_hash.toObject()}if(this.contract_address!=null){data.contract_address=this.contract_address.toObject()}if(this.logs!=null){data.logs=this.logs.toObject()}if(this.etxs!=null){data.etxs=this.etxs.toObject()}if(this.gas_used!=null){data.gas_used=this.gas_used}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.post_state_or_status.length)writer.writeBytes(1,this.post_state_or_status);if(this.cumulative_gas_used!=0)writer.writeUint64(2,this.cumulative_gas_used);if(this.has_tx_hash)writer.writeMessage(3,this.tx_hash,()=>this.tx_hash.serialize(writer));if(this.has_contract_address)writer.writeMessage(4,this.contract_address,()=>this.contract_address.serialize(writer));if(this.has_logs)writer.writeMessage(5,this.logs,()=>this.logs.serialize(writer));if(this.has_etxs)writer.writeMessage(6,this.etxs,()=>this.etxs.serialize(writer));if(this.gas_used!=0)writer.writeUint64(7,this.gas_used);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoReceiptForStorage;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.post_state_or_status=reader.readBytes();break;case 2:message.cumulative_gas_used=reader.readUint64();break;case 3:reader.readMessage(message.tx_hash,()=>message.tx_hash=common.ProtoHash.deserialize(reader));break;case 4:reader.readMessage(message.contract_address,()=>message.contract_address=common.ProtoAddress.deserialize(reader));break;case 5:reader.readMessage(message.logs,()=>message.logs=ProtoLogsForStorage.deserialize(reader));break;case 6:reader.readMessage(message.etxs,()=>message.etxs=ProtoTransactions.deserialize(reader));break;case 7:message.gas_used=reader.readUint64();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoReceiptForStorage.deserialize(bytes)}}block.ProtoReceiptForStorage=ProtoReceiptForStorage;class ProtoReceiptsForStorage extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("receipts"in data&&data.receipts!=undefined){this.receipts=data.receipts}}}get receipts(){return pb_1.Message.getRepeatedWrapperField(this,ProtoReceiptForStorage,1)}set receipts(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoReceiptsForStorage({});if(data.receipts!=null){message.receipts=data.receipts.map(item=>ProtoReceiptForStorage.fromObject(item))}return message}toObject(){const data={};if(this.receipts!=null){data.receipts=this.receipts.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.receipts.length)writer.writeRepeatedMessage(1,this.receipts,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoReceiptsForStorage;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.receipts,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoReceiptForStorage.deserialize(reader),ProtoReceiptForStorage));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoReceiptsForStorage.deserialize(bytes)}}block.ProtoReceiptsForStorage=ProtoReceiptsForStorage;class ProtoLogForStorage extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[2],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("address"in data&&data.address!=undefined){this.address=data.address}if("topics"in data&&data.topics!=undefined){this.topics=data.topics}if("data"in data&&data.data!=undefined){this.data=data.data}}}get address(){return pb_1.Message.getWrapperField(this,common.ProtoAddress,1)}set address(value){pb_1.Message.setWrapperField(this,1,value)}get has_address(){return pb_1.Message.getField(this,1)!=null}get topics(){return pb_1.Message.getRepeatedWrapperField(this,common.ProtoHash,2)}set topics(value){pb_1.Message.setRepeatedWrapperField(this,2,value)}get data(){return pb_1.Message.getFieldWithDefault(this,3,new Uint8Array(0))}set data(value){pb_1.Message.setField(this,3,value)}static fromObject(data){const message=new ProtoLogForStorage({});if(data.address!=null){message.address=common.ProtoAddress.fromObject(data.address)}if(data.topics!=null){message.topics=data.topics.map(item=>common.ProtoHash.fromObject(item))}if(data.data!=null){message.data=data.data}return message}toObject(){const data={};if(this.address!=null){data.address=this.address.toObject()}if(this.topics!=null){data.topics=this.topics.map(item=>item.toObject())}if(this.data!=null){data.data=this.data}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_address)writer.writeMessage(1,this.address,()=>this.address.serialize(writer));if(this.topics.length)writer.writeRepeatedMessage(2,this.topics,item=>item.serialize(writer));if(this.data.length)writer.writeBytes(3,this.data);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoLogForStorage;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.address,()=>message.address=common.ProtoAddress.deserialize(reader));break;case 2:reader.readMessage(message.topics,()=>pb_1.Message.addToRepeatedWrapperField(message,2,common.ProtoHash.deserialize(reader),common.ProtoHash));break;case 3:message.data=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoLogForStorage.deserialize(bytes)}}block.ProtoLogForStorage=ProtoLogForStorage;class ProtoLogsForStorage extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("logs"in data&&data.logs!=undefined){this.logs=data.logs}}}get logs(){return pb_1.Message.getRepeatedWrapperField(this,ProtoLogForStorage,1)}set logs(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoLogsForStorage({});if(data.logs!=null){message.logs=data.logs.map(item=>ProtoLogForStorage.fromObject(item))}return message}toObject(){const data={};if(this.logs!=null){data.logs=this.logs.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.logs.length)writer.writeRepeatedMessage(1,this.logs,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoLogsForStorage;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.logs,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoLogForStorage.deserialize(reader),ProtoLogForStorage));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoLogsForStorage.deserialize(bytes)}}block.ProtoLogsForStorage=ProtoLogsForStorage;class ProtoPendingHeader extends pb_1.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("wo"in data&&data.wo!=undefined){this.wo=data.wo}if("termini"in data&&data.termini!=undefined){this.termini=data.termini}}}get wo(){return pb_1.Message.getWrapperField(this,ProtoWorkObject,1)}set wo(value){pb_1.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_wo(){return pb_1.Message.getField(this,1)!=null}get termini(){return pb_1.Message.getWrapperField(this,ProtoTermini,2)}set termini(value){pb_1.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_termini(){return pb_1.Message.getField(this,2)!=null}get _wo(){const cases={0:"none",1:"wo"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _termini(){const cases={0:"none",2:"termini"};return cases[pb_1.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoPendingHeader({});if(data.wo!=null){message.wo=ProtoWorkObject.fromObject(data.wo)}if(data.termini!=null){message.termini=ProtoTermini.fromObject(data.termini)}return message}toObject(){const data={};if(this.wo!=null){data.wo=this.wo.toObject()}if(this.termini!=null){data.termini=this.termini.toObject()}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_wo)writer.writeMessage(1,this.wo,()=>this.wo.serialize(writer));if(this.has_termini)writer.writeMessage(2,this.termini,()=>this.termini.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoPendingHeader;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.wo,()=>message.wo=ProtoWorkObject.deserialize(reader));break;case 2:reader.readMessage(message.termini,()=>message.termini=ProtoTermini.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoPendingHeader.deserialize(bytes)}}block.ProtoPendingHeader=ProtoPendingHeader;class ProtoTermini extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1,2],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("dom_termini"in data&&data.dom_termini!=undefined){this.dom_termini=data.dom_termini}if("sub_termini"in data&&data.sub_termini!=undefined){this.sub_termini=data.sub_termini}}}get dom_termini(){return pb_1.Message.getRepeatedWrapperField(this,common.ProtoHash,1)}set dom_termini(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}get sub_termini(){return pb_1.Message.getRepeatedWrapperField(this,common.ProtoHash,2)}set sub_termini(value){pb_1.Message.setRepeatedWrapperField(this,2,value)}static fromObject(data){const message=new ProtoTermini({});if(data.dom_termini!=null){message.dom_termini=data.dom_termini.map(item=>common.ProtoHash.fromObject(item))}if(data.sub_termini!=null){message.sub_termini=data.sub_termini.map(item=>common.ProtoHash.fromObject(item))}return message}toObject(){const data={};if(this.dom_termini!=null){data.dom_termini=this.dom_termini.map(item=>item.toObject())}if(this.sub_termini!=null){data.sub_termini=this.sub_termini.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.dom_termini.length)writer.writeRepeatedMessage(1,this.dom_termini,item=>item.serialize(writer));if(this.sub_termini.length)writer.writeRepeatedMessage(2,this.sub_termini,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoTermini;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.dom_termini,()=>pb_1.Message.addToRepeatedWrapperField(message,1,common.ProtoHash.deserialize(reader),common.ProtoHash));break;case 2:reader.readMessage(message.sub_termini,()=>pb_1.Message.addToRepeatedWrapperField(message,2,common.ProtoHash.deserialize(reader),common.ProtoHash));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTermini.deserialize(bytes)}}block.ProtoTermini=ProtoTermini;class ProtoEtxSet extends pb_1.Message{#one_of_decls=[[1]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("etx_hashes"in data&&data.etx_hashes!=undefined){this.etx_hashes=data.etx_hashes}}}get etx_hashes(){return pb_1.Message.getFieldWithDefault(this,1,new Uint8Array(0))}set etx_hashes(value){pb_1.Message.setOneofField(this,1,this.#one_of_decls[0],value)}get has_etx_hashes(){return pb_1.Message.getField(this,1)!=null}get _etx_hashes(){const cases={0:"none",1:"etx_hashes"};return cases[pb_1.Message.computeOneofCase(this,[1])]}static fromObject(data){const message=new ProtoEtxSet({});if(data.etx_hashes!=null){message.etx_hashes=data.etx_hashes}return message}toObject(){const data={};if(this.etx_hashes!=null){data.etx_hashes=this.etx_hashes}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_etx_hashes)writer.writeBytes(1,this.etx_hashes);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoEtxSet;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.etx_hashes=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoEtxSet.deserialize(bytes)}}block.ProtoEtxSet=ProtoEtxSet;class ProtoPendingEtxs extends pb_1.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("header"in data&&data.header!=undefined){this.header=data.header}if("etxs"in data&&data.etxs!=undefined){this.etxs=data.etxs}}}get header(){return pb_1.Message.getWrapperField(this,ProtoWorkObject,1)}set header(value){pb_1.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_header(){return pb_1.Message.getField(this,1)!=null}get etxs(){return pb_1.Message.getWrapperField(this,ProtoTransactions,2)}set etxs(value){pb_1.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_etxs(){return pb_1.Message.getField(this,2)!=null}get _header(){const cases={0:"none",1:"header"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _etxs(){const cases={0:"none",2:"etxs"};return cases[pb_1.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoPendingEtxs({});if(data.header!=null){message.header=ProtoWorkObject.fromObject(data.header)}if(data.etxs!=null){message.etxs=ProtoTransactions.fromObject(data.etxs)}return message}toObject(){const data={};if(this.header!=null){data.header=this.header.toObject()}if(this.etxs!=null){data.etxs=this.etxs.toObject()}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_header)writer.writeMessage(1,this.header,()=>this.header.serialize(writer));if(this.has_etxs)writer.writeMessage(2,this.etxs,()=>this.etxs.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoPendingEtxs;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.header,()=>message.header=ProtoWorkObject.deserialize(reader));break;case 2:reader.readMessage(message.etxs,()=>message.etxs=ProtoTransactions.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoPendingEtxs.deserialize(bytes)}}block.ProtoPendingEtxs=ProtoPendingEtxs;class ProtoPendingEtxsRollup extends pb_1.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("header"in data&&data.header!=undefined){this.header=data.header}if("etxs_rollup"in data&&data.etxs_rollup!=undefined){this.etxs_rollup=data.etxs_rollup}}}get header(){return pb_1.Message.getWrapperField(this,ProtoWorkObject,1)}set header(value){pb_1.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_header(){return pb_1.Message.getField(this,1)!=null}get etxs_rollup(){return pb_1.Message.getWrapperField(this,ProtoTransactions,2)}set etxs_rollup(value){pb_1.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_etxs_rollup(){return pb_1.Message.getField(this,2)!=null}get _header(){const cases={0:"none",1:"header"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _etxs_rollup(){const cases={0:"none",2:"etxs_rollup"};return cases[pb_1.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoPendingEtxsRollup({});if(data.header!=null){message.header=ProtoWorkObject.fromObject(data.header)}if(data.etxs_rollup!=null){message.etxs_rollup=ProtoTransactions.fromObject(data.etxs_rollup)}return message}toObject(){const data={};if(this.header!=null){data.header=this.header.toObject()}if(this.etxs_rollup!=null){data.etxs_rollup=this.etxs_rollup.toObject()}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_header)writer.writeMessage(1,this.header,()=>this.header.serialize(writer));if(this.has_etxs_rollup)writer.writeMessage(2,this.etxs_rollup,()=>this.etxs_rollup.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoPendingEtxsRollup;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.header,()=>message.header=ProtoWorkObject.deserialize(reader));break;case 2:reader.readMessage(message.etxs_rollup,()=>message.etxs_rollup=ProtoTransactions.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoPendingEtxsRollup.deserialize(bytes)}}block.ProtoPendingEtxsRollup=ProtoPendingEtxsRollup;class ProtoTxIns extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("tx_ins"in data&&data.tx_ins!=undefined){this.tx_ins=data.tx_ins}}}get tx_ins(){return pb_1.Message.getRepeatedWrapperField(this,ProtoTxIn,1)}set tx_ins(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoTxIns({});if(data.tx_ins!=null){message.tx_ins=data.tx_ins.map(item=>ProtoTxIn.fromObject(item))}return message}toObject(){const data={};if(this.tx_ins!=null){data.tx_ins=this.tx_ins.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.tx_ins.length)writer.writeRepeatedMessage(1,this.tx_ins,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoTxIns;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.tx_ins,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoTxIn.deserialize(reader),ProtoTxIn));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTxIns.deserialize(bytes)}}block.ProtoTxIns=ProtoTxIns;class ProtoTxOuts extends pb_1.Message{#one_of_decls=[];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("tx_outs"in data&&data.tx_outs!=undefined){this.tx_outs=data.tx_outs}}}get tx_outs(){return pb_1.Message.getRepeatedWrapperField(this,ProtoTxOut,1)}set tx_outs(value){pb_1.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoTxOuts({});if(data.tx_outs!=null){message.tx_outs=data.tx_outs.map(item=>ProtoTxOut.fromObject(item))}return message}toObject(){const data={};if(this.tx_outs!=null){data.tx_outs=this.tx_outs.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.tx_outs.length)writer.writeRepeatedMessage(1,this.tx_outs,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoTxOuts;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.tx_outs,()=>pb_1.Message.addToRepeatedWrapperField(message,1,ProtoTxOut.deserialize(reader),ProtoTxOut));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTxOuts.deserialize(bytes)}}block.ProtoTxOuts=ProtoTxOuts;class ProtoTxIn extends pb_1.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("previous_out_point"in data&&data.previous_out_point!=undefined){this.previous_out_point=data.previous_out_point}if("pub_key"in data&&data.pub_key!=undefined){this.pub_key=data.pub_key}}}get previous_out_point(){return pb_1.Message.getWrapperField(this,ProtoOutPoint,1)}set previous_out_point(value){pb_1.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_previous_out_point(){return pb_1.Message.getField(this,1)!=null}get pub_key(){return pb_1.Message.getFieldWithDefault(this,2,new Uint8Array(0))}set pub_key(value){pb_1.Message.setOneofField(this,2,this.#one_of_decls[1],value)}get has_pub_key(){return pb_1.Message.getField(this,2)!=null}get _previous_out_point(){const cases={0:"none",1:"previous_out_point"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _pub_key(){const cases={0:"none",2:"pub_key"};return cases[pb_1.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoTxIn({});if(data.previous_out_point!=null){message.previous_out_point=ProtoOutPoint.fromObject(data.previous_out_point)}if(data.pub_key!=null){message.pub_key=data.pub_key}return message}toObject(){const data={};if(this.previous_out_point!=null){data.previous_out_point=this.previous_out_point.toObject()}if(this.pub_key!=null){data.pub_key=this.pub_key}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_previous_out_point)writer.writeMessage(1,this.previous_out_point,()=>this.previous_out_point.serialize(writer));if(this.has_pub_key)writer.writeBytes(2,this.pub_key);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoTxIn;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.previous_out_point,()=>message.previous_out_point=ProtoOutPoint.deserialize(reader));break;case 2:message.pub_key=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTxIn.deserialize(bytes)}}block.ProtoTxIn=ProtoTxIn;class ProtoOutPoint extends pb_1.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("hash"in data&&data.hash!=undefined){this.hash=data.hash}if("index"in data&&data.index!=undefined){this.index=data.index}}}get hash(){return pb_1.Message.getWrapperField(this,common.ProtoHash,1)}set hash(value){pb_1.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_hash(){return pb_1.Message.getField(this,1)!=null}get index(){return pb_1.Message.getFieldWithDefault(this,2,0)}set index(value){pb_1.Message.setOneofField(this,2,this.#one_of_decls[1],value)}get has_index(){return pb_1.Message.getField(this,2)!=null}get _hash(){const cases={0:"none",1:"hash"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _index(){const cases={0:"none",2:"index"};return cases[pb_1.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoOutPoint({});if(data.hash!=null){message.hash=common.ProtoHash.fromObject(data.hash)}if(data.index!=null){message.index=data.index}return message}toObject(){const data={};if(this.hash!=null){data.hash=this.hash.toObject()}if(this.index!=null){data.index=this.index}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_hash)writer.writeMessage(1,this.hash,()=>this.hash.serialize(writer));if(this.has_index)writer.writeUint32(2,this.index);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoOutPoint;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.hash,()=>message.hash=common.ProtoHash.deserialize(reader));break;case 2:message.index=reader.readUint32();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoOutPoint.deserialize(bytes)}}block.ProtoOutPoint=ProtoOutPoint;class ProtoTxOut extends pb_1.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("denomination"in data&&data.denomination!=undefined){this.denomination=data.denomination}if("address"in data&&data.address!=undefined){this.address=data.address}}}get denomination(){return pb_1.Message.getFieldWithDefault(this,1,0)}set denomination(value){pb_1.Message.setOneofField(this,1,this.#one_of_decls[0],value)}get has_denomination(){return pb_1.Message.getField(this,1)!=null}get address(){return pb_1.Message.getFieldWithDefault(this,2,new Uint8Array(0))}set address(value){pb_1.Message.setOneofField(this,2,this.#one_of_decls[1],value)}get has_address(){return pb_1.Message.getField(this,2)!=null}get _denomination(){const cases={0:"none",1:"denomination"};return cases[pb_1.Message.computeOneofCase(this,[1])]}get _address(){const cases={0:"none",2:"address"};return cases[pb_1.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoTxOut({});if(data.denomination!=null){message.denomination=data.denomination}if(data.address!=null){message.address=data.address}return message}toObject(){const data={};if(this.denomination!=null){data.denomination=this.denomination}if(this.address!=null){data.address=this.address}return data}serialize(w){const writer=w||new pb_1.BinaryWriter;if(this.has_denomination)writer.writeUint32(1,this.denomination);if(this.has_address)writer.writeBytes(2,this.address);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1.BinaryReader?bytes:new pb_1.BinaryReader(bytes),message=new ProtoTxOut;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.denomination=reader.readUint32();break;case 2:message.address=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTxOut.deserialize(bytes)}}block.ProtoTxOut=ProtoTxOut})(block||(block={}));function encodeProtoTransaction(protoTx){const tx=block.ProtoTransaction.fromObject(protoTx);return hexlify(tx.serialize())}function decodeProtoTransaction(bytes){const tx=block.ProtoTransaction.deserialize(bytes);const result=tx.toObject();if(result.to?.length==0){result.to=null}return result}function errorFunc(reason,offset,bytes,output,badCodepoint){assertArgument(false,`invalid codepoint at offset ${offset}; ${reason}`,"bytes",bytes)}function ignoreFunc(reason,offset,bytes,output,badCodepoint){if(reason==="BAD_PREFIX"||reason==="UNEXPECTED_CONTINUE"){let i=0;for(let o=offset+1;o>6!==2){break}i++}return i}if(reason==="OVERRUN"){return bytes.length-offset-1}return 0}function replaceFunc(reason,offset,bytes,output,badCodepoint){if(reason==="OVERLONG"){assertArgument(typeof badCodepoint==="number","invalid bad code point for replacement","badCodepoint",badCodepoint);output.push(badCodepoint);return 0}output.push(65533);return ignoreFunc(reason,offset,bytes)}const Utf8ErrorFuncs=Object.freeze({error:errorFunc,ignore:ignoreFunc,replace:replaceFunc});function getUtf8CodePoints(_bytes,onError){if(onError==null){onError=Utf8ErrorFuncs.error}const bytes=getBytes(_bytes,"bytes");const result=[];let i=0;while(i>7===0){result.push(c);continue}let extraLength=null;let overlongMask=null;if((c&224)===192){extraLength=1;overlongMask=127}else if((c&240)===224){extraLength=2;overlongMask=2047}else if((c&248)===240){extraLength=3;overlongMask=65535}else{if((c&192)===128){i+=onError("UNEXPECTED_CONTINUE",i-1,bytes,result)}else{i+=onError("BAD_PREFIX",i-1,bytes,result)}continue}if(i-1+extraLength>=bytes.length){i+=onError("OVERRUN",i-1,bytes,result);continue}let res=c&(1<<8-extraLength-1)-1;for(let j=0;j1114111){i+=onError("OUT_OF_RANGE",i-1-extraLength,bytes,result,res);continue}if(res>=55296&&res<=57343){i+=onError("UTF16_SURROGATE",i-1-extraLength,bytes,result,res);continue}if(res<=overlongMask){i+=onError("OVERLONG",i-1-extraLength,bytes,result,res);continue}result.push(res)}return result}function toUtf8Bytes(str,form){if(form!=null){assertNormalize(form);str=str.normalize(form)}const result=[];for(let i=0;i>6|192);result.push(c&63|128)}else if((c&64512)==55296){i++;const c2=str.charCodeAt(i);assertArgument(i>18|240);result.push(pair>>12&63|128);result.push(pair>>6&63|128);result.push(pair&63|128)}else{result.push(c>>12|224);result.push(c>>6&63|128);result.push(c&63|128)}}return new Uint8Array(result)}function _toUtf8String(codePoints){return codePoints.map(codePoint=>{if(codePoint<=65535){return String.fromCharCode(codePoint)}codePoint-=65536;return String.fromCharCode((codePoint>>10&1023)+55296,(codePoint&1023)+56320)}).join("")}function toUtf8String(bytes,onError){return _toUtf8String(getUtf8CodePoints(bytes,onError))}function toUtf8CodePoints(str,form){return getUtf8CodePoints(toUtf8Bytes(str,form))}function createGetUrl(options){async function getUrl(req,_signal){const protocol=req.url.split(":")[0].toLowerCase();assert(protocol==="http"||protocol==="https",`unsupported protocol ${protocol}`,"UNSUPPORTED_OPERATION",{info:{protocol:protocol},operation:"request"});assert(protocol==="https"||!req.credentials||req.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let signal=undefined;if(_signal){const controller=new AbortController;signal=controller.signal;_signal.addListener(()=>{controller.abort()})}const init={method:req.method,headers:new Headers(Array.from(req)),body:req.body||undefined,signal:signal};const resp=await fetch(req.url,init);const headers={};resp.headers.forEach((value,key)=>{headers[key.toLowerCase()]=value});const respBody=await resp.arrayBuffer();const body=respBody==null?null:new Uint8Array(respBody);return{statusCode:resp.status,statusMessage:resp.statusText,headers:headers,body:body}}return getUrl}const MAX_ATTEMPTS=12;const SLOT_INTERVAL=250;let defaultGetUrlFunc=createGetUrl();const reData=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i");const reIpfs=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let locked$5=false;async function dataGatewayFunc(url,signal){try{const match=url.match(reData);if(!match){throw new Error("invalid data")}return new FetchResponse(200,"OK",{"content-type":match[1]||"text/plain"},match[2]?decodeBase64(match[3]):unpercent(match[3]))}catch(error){return new FetchResponse(599,"BAD REQUEST (invalid data: URI)",{},null,new FetchRequest(url))}}function getIpfsGatewayFunc(baseUrl){async function gatewayIpfs(url,signal){try{const match=url.match(reIpfs);if(!match){throw new Error("invalid link")}return new FetchRequest(`${baseUrl}${match[2]}`)}catch(error){return new FetchResponse(599,"BAD REQUEST (invalid IPFS URI)",{},null,new FetchRequest(url))}}return gatewayIpfs}const Gateways={data:dataGatewayFunc,ipfs:getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/")};const fetchSignals=new WeakMap;class FetchCancelSignal{#listeners;#cancelled;constructor(request){this.#listeners=[];this.#cancelled=false;fetchSignals.set(request,()=>{if(this.#cancelled){return}this.#cancelled=true;for(const listener of this.#listeners){setTimeout(()=>{listener()},0)}this.#listeners=[]})}addListener(listener){assert(!this.#cancelled,"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"});this.#listeners.push(listener)}get cancelled(){return this.#cancelled}checkSignal(){assert(!this.cancelled,"cancelled","CANCELLED",{})}}function checkSignal(signal){if(signal==null){throw new Error("missing signal; should not happen")}signal.checkSignal();return signal}class FetchRequest{#allowInsecure;#gzip;#headers;#method;#timeout;#url;#body;#bodyType;#creds;#preflight;#process;#retry;#signal;#throttle;#getUrlFunc;get url(){return this.#url}set url(url){this.#url=String(url)}get body(){if(this.#body==null){return null}return new Uint8Array(this.#body)}set body(body){if(body==null){this.#body=undefined;this.#bodyType=undefined}else if(typeof body==="string"){this.#body=toUtf8Bytes(body);this.#bodyType="text/plain"}else if(body instanceof Uint8Array){this.#body=body;this.#bodyType="application/octet-stream"}else if(typeof body==="object"){this.#body=toUtf8Bytes(JSON.stringify(body));this.#bodyType="application/json"}else{throw new Error("invalid body")}}hasBody(){return this.#body!=null}get method(){if(this.#method){return this.#method}if(this.hasBody()){return"POST"}return"GET"}set method(method){if(method==null){method=""}this.#method=String(method).toUpperCase()}get headers(){const headers=Object.assign({},this.#headers);if(this.#creds){headers["authorization"]=`Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`}if(this.allowGzip){headers["accept-encoding"]="gzip"}if(headers["content-type"]==null&&this.#bodyType){headers["content-type"]=this.#bodyType}if(this.body){headers["content-length"]=String(this.body.length)}return headers}getHeader(key){return this.headers[key.toLowerCase()]}setHeader(key,value){this.#headers[String(key).toLowerCase()]=String(value)}clearHeaders(){this.#headers={}}[Symbol.iterator](){const headers=this.headers;const keys=Object.keys(headers);let index=0;return{next:()=>{if(index=0,"timeout must be non-zero","timeout",timeout);this.#timeout=timeout}get preflightFunc(){return this.#preflight||null}set preflightFunc(preflight){this.#preflight=preflight}get processFunc(){return this.#process||null}set processFunc(process){this.#process=process}get retryFunc(){return this.#retry||null}set retryFunc(retry){this.#retry=retry}get getUrlFunc(){return this.#getUrlFunc||defaultGetUrlFunc}set getUrlFunc(value){this.#getUrlFunc=value}constructor(url){this.#url=String(url);this.#allowInsecure=false;this.#gzip=true;this.#headers={};this.#method="";this.#timeout=3e5;this.#throttle={slotInterval:SLOT_INTERVAL,maxAttempts:MAX_ATTEMPTS};this.#getUrlFunc=null}toString(){return``}setThrottleParams(params){if(params.slotInterval!=null){this.#throttle.slotInterval=params.slotInterval}if(params.maxAttempts!=null){this.#throttle.maxAttempts=params.maxAttempts}}async#send(attempt,expires,delay,_request,_response){if(attempt>=this.#throttle.maxAttempts){return _response.makeServerError("exceeded maximum retry limit")}assert(getTime$1()<=expires,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:_request});if(delay>0){await wait(delay)}let req=this.clone();const scheme=(req.url.split(":")[0]||"").toLowerCase();if(scheme in Gateways){const result=await Gateways[scheme](req.url,checkSignal(_request.#signal));if(result instanceof FetchResponse){let response=result;if(this.processFunc){checkSignal(_request.#signal);try{response=await this.processFunc(req,response)}catch(error){if(error.throttle==null||typeof error.stall!=="number"){response.makeServerError("error in post-processing function",error).assertOk()}}}return response}req=result}if(this.preflightFunc){req=await this.preflightFunc(req)}const resp=await this.getUrlFunc(req,checkSignal(_request.#signal));let response=new FetchResponse(resp.statusCode,resp.statusMessage,resp.headers,resp.body,_request);if(response.statusCode===301||response.statusCode===302){try{const location=response.headers.location||"";return req.redirect(location).#send(attempt+1,expires,0,_request,response)}catch(error){}return response}else if(response.statusCode===429){if(this.retryFunc==null||await this.retryFunc(req,response,attempt)){const retryAfter=response.headers["retry-after"];let delay=this.#throttle.slotInterval*Math.trunc(Math.random()*Math.pow(2,attempt));if(typeof retryAfter==="string"&&retryAfter.match(/^[1-9][0-9]*$/)){delay=parseInt(retryAfter)}return req.clone().#send(attempt+1,expires,delay,_request,response)}}if(this.processFunc){checkSignal(_request.#signal);try{response=await this.processFunc(req,response)}catch(error){if(error.throttle==null||typeof error.stall!=="number"){response.makeServerError("error in post-processing function",error).assertOk()}let delay=this.#throttle.slotInterval*Math.trunc(Math.random()*Math.pow(2,attempt));if(error.stall>=0){delay=error.stall}return req.clone().#send(attempt+1,expires,delay,_request,response)}}return response}send(){assert(this.#signal==null,"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"});this.#signal=new FetchCancelSignal(this);return this.#send(0,getTime$1()+this.timeout,0,this,new FetchResponse(0,"",{},null,this))}cancel(){assert(this.#signal!=null,"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const signal=fetchSignals.get(this);if(!signal){throw new Error("missing signal; should not happen")}signal()}redirect(location){const current=this.url.split(":")[0].toLowerCase();const target=location.split(":")[0].toLowerCase();assert(this.method==="GET"&&(current!=="https"||target!=="http")&&location.match(/^https?:/),`unsupported redirect`,"UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`});const req=new FetchRequest(location);req.method="GET";req.allowGzip=this.allowGzip;req.timeout=this.timeout;req.#headers=Object.assign({},this.#headers);if(this.#body){req.#body=new Uint8Array(this.#body)}req.#bodyType=this.#bodyType;return req}clone(){const clone=new FetchRequest(this.url);clone.#method=this.#method;if(this.#body){clone.#body=this.#body}clone.#bodyType=this.#bodyType;clone.#headers=Object.assign({},this.#headers);clone.#creds=this.#creds;if(this.allowGzip){clone.allowGzip=true}clone.timeout=this.timeout;if(this.allowInsecureAuthentication){clone.allowInsecureAuthentication=true}clone.#preflight=this.#preflight;clone.#process=this.#process;clone.#retry=this.#retry;clone.#getUrlFunc=this.#getUrlFunc;return clone}static lockConfig(){locked$5=true}static getGateway(scheme){return Gateways[scheme.toLowerCase()]||null}static registerGateway(scheme,func){scheme=scheme.toLowerCase();if(scheme==="http"||scheme==="https"){throw new Error(`cannot intercept ${scheme}; use registerGetUrl`)}if(locked$5){throw new Error("gateways locked")}Gateways[scheme]=func}static registerGetUrl(getUrl){if(locked$5){throw new Error("gateways locked")}defaultGetUrlFunc=getUrl}static createGetUrlFunc(options){return createGetUrl()}static createDataGateway(){return dataGatewayFunc}static createIpfsGatewayFunc(baseUrl){return getIpfsGatewayFunc(baseUrl)}}class FetchResponse{#statusCode;#statusMessage;#headers;#body;#request;#error;toString(){return``}get statusCode(){return this.#statusCode}get statusMessage(){return this.#statusMessage}get headers(){return Object.assign({},this.#headers)}get body(){return this.#body==null?null:new Uint8Array(this.#body)}get bodyText(){try{return this.#body==null?"":toUtf8String(this.#body)}catch(error){assert(false,"response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch(error){assert(false,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const headers=this.headers;const keys=Object.keys(headers);let index=0;return{next:()=>{if(index{accum[k.toLowerCase()]=String(headers[k]);return accum},{});this.#body=body==null?null:new Uint8Array(body);this.#request=request||null;this.#error={message:""}}makeServerError(message,error){let statusMessage;if(!message){message=`${this.statusCode} ${this.statusMessage}`;statusMessage=`CLIENT ESCALATED SERVER ERROR (${message})`}else{statusMessage=`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`}const response=new FetchResponse(599,statusMessage,this.headers,this.body,this.#request||undefined);response.#error={message:message,error:error};return response}throwThrottleError(message,stall){if(stall==null){stall=-1}else{assertArgument(Number.isInteger(stall)&&stall>=0,"invalid stall timeout","stall",stall)}const error=new Error(message||"throttling requests");defineProperties(error,{stall:stall,throttle:true});throw error}getHeader(key){return this.headers[key.toLowerCase()]}hasBody(){return this.#body!=null}get request(){return this.#request}ok(){return this.#error.message===""&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok()){return}let{message,error}=this.#error;if(message===""){message=`server response ${this.statusCode} ${this.statusMessage}`}assert(false,message,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:error})}}function getTime$1(){return(new Date).getTime()}function unpercent(value){return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi,(all,code)=>{return String.fromCharCode(parseInt(code,16))}))}function wait(delay){return new Promise(resolve=>setTimeout(resolve,delay))}const BN_N1=BigInt(-1);const BN_0$6=BigInt(0);const BN_1$3=BigInt(1);const BN_5=BigInt(5);const _guard$7={};let Zeros="0000";while(Zeros.length<80){Zeros+=Zeros}function getTens(decimals){let result=Zeros;while(result.length=-limit&&valBN_0$6){val=fromTwos(mask(val,width),width)}else{val=-fromTwos(mask(-val,width),width)}}else{const limit=BN_1$3<=0&&val{if(v[key]==null){return defaultValue}assertArgument(typeof v[key]===type,"invalid fixed format ("+key+" not "+type+")","format."+key,v[key]);return v[key]};signed=check("signed","boolean",signed);width=check("width","number",width);decimals=check("decimals","number",decimals)}assertArgument(width%8===0,"invalid FixedNumber width (not byte aligned)","format.width",width);assertArgument(decimals<=80,"invalid FixedNumber decimals (too large)","format.decimals",decimals);const name=(signed?"":"u")+"fixed"+String(width)+"x"+String(decimals);return{signed:signed,width:width,decimals:decimals,name:name}}function toString(val,decimals){let negative="";if(val0){b*=getTens(delta)}else if(delta<0){a*=getTens(-delta)}if(ab){return 1}return 0}eq(other){return this.cmp(other)===0}lt(other){return this.cmp(other)<0}lte(other){return this.cmp(other)<=0}gt(other){return this.cmp(other)>0}gte(other){return this.cmp(other)>=0}floor(){let val=this.#val;if(this.#valBN_0$6){val+=this.#tens-BN_1$3}val=this.#val/this.#tens*this.#tens;return this.#checkValue(val,"ceiling")}round(decimals){if(decimals==null){decimals=0}if(decimals>=this.decimals){return this}const delta=this.decimals-decimals;const bump=BN_5*getTens(delta-1);let value=this.value+bump;const tens=getTens(delta);value=value/tens*tens;checkValue(value,this.#format,"round");return new FixedNumber(_guard$7,value,this.#format)}isZero(){return this.#val===BN_0$6}isNegative(){return this.#val0){const tens=getTens(delta);assert(value%tens===BN_0$6,"value loses precision for format","NUMERIC_FAULT",{operation:"fromValue",fault:"underflow",value:_value});value/=tens}else if(delta<0){value*=getTens(-delta)}checkValue(value,format,"fromValue");return new FixedNumber(_guard$7,value,format)}static fromString(_value,_format){const match=_value.match(/^(-?)([0-9]*)\.?([0-9]*)$/);assertArgument(match&&match[2].length+match[3].length>0,"invalid FixedNumber string value","value",_value);const format=getFormat(_format);const whole=match[2]||"0";let decimal=match[3]||"";while(decimal.length=0,"invalid unit","unit",unit);decimals=3*index}else if(unit!=null){decimals=getNumber(unit,"unit")}return FixedNumber.fromValue(value,decimals,{decimals:decimals,width:512}).toString()}function parseUnits(value,unit){assertArgument(typeof value==="string","value must be a string","value",value);let decimals=18;if(typeof unit==="string"){const index=names.indexOf(unit);assertArgument(index>=0,"invalid unit","unit",unit);decimals=3*index}else if(unit!=null){decimals=getNumber(unit,"unit")}return FixedNumber.fromString(value,{decimals:decimals,width:512}).value}function formatQuai(wei){return formatUnits(wei,18)}function parseQuai(ether){return parseUnits(ether,18)}function uuidV4(randomBytes){const bytes=getBytes(randomBytes,"randomBytes");bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;const value=hexlify(bytes);return[value.substring(2,10),value.substring(10,14),value.substring(14,18),value.substring(18,22),value.substring(22,34)].join("-")}var Zone;(function(Zone){Zone["Cyprus1"]="0x00";Zone["Cyprus2"]="0x01";Zone["Cyprus3"]="0x02";Zone["Paxos1"]="0x10";Zone["Paxos2"]="0x11";Zone["Paxos3"]="0x12";Zone["Hydra1"]="0x20";Zone["Hydra2"]="0x21";Zone["Hydra3"]="0x22"})(Zone||(Zone={}));var Ledger;(function(Ledger){Ledger[Ledger["Quai"]=0]="Quai";Ledger[Ledger["Qi"]=1]="Qi"})(Ledger||(Ledger={}));function zoneFromBytes(zone){switch(zone){case"0x00":return Zone.Cyprus1;case"0x01":return Zone.Cyprus2;case"0x02":return Zone.Cyprus3;case"0x10":return Zone.Paxos1;case"0x11":return Zone.Paxos2;case"0x12":return Zone.Paxos3;case"0x20":return Zone.Hydra1;case"0x21":return Zone.Hydra2;case"0x22":return Zone.Hydra3;default:throw new Error(`Invalid zone: ${zone}`)}}const ZoneData=[{name:"Cyprus One",nickname:"cyprus1",shard:"zone-0-0",context:2,byte:"0x00"},{name:"Cyprus Two",nickname:"cyprus2",shard:"zone-0-1",context:2,byte:"0x01"},{name:"Cyprus Three",nickname:"cyprus3",shard:"zone-0-2",context:2,byte:"0x02"},{name:"Paxos One",nickname:"paxos1",shard:"zone-1-0",context:2,byte:"0x10"},{name:"Paxos Two",nickname:"paxos2",shard:"zone-1-1",context:2,byte:"0x11"},{name:"Paxos Three",nickname:"paxos3",shard:"zone-1-2",context:2,byte:"0x12"},{name:"Hydra One",nickname:"hydra1",shard:"zone-2-0",context:2,byte:"0x20"},{name:"Hydra Two",nickname:"hydra2",shard:"zone-2-1",context:2,byte:"0x21"},{name:"Hydra Three",nickname:"hydra3",shard:"zone-2-2",context:2,byte:"0x22"}];function toZone(shard){return zoneFromBytes(ZoneData.find(it=>it.name==shard||it.byte==shard||it.nickname==shard||it.shard==shard)?.byte||"")}function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bytes(b,...lengths){if(!(b instanceof Uint8Array))throw new Error("Expected Uint8Array");if(lengths.length>0&&!lengths.includes(b.length))throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`)}function hash(hash){if(typeof hash!=="function"||typeof hash.create!=="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number(hash.outputLen);number(hash.blockLen)}function exists(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function output(out,instance){bytes(out);const min=instance.outputLen;if(out.lengtha instanceof Uint8Array;const u32=arr=>new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4));const createView=arr=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);const rotr=(word,shift)=>word<<32-shift|word>>>shift;const isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");const nextTick=async()=>{};async function asyncLoop(iters,tick,cb){let ts=Date.now();for(let i=0;i=0&&diffsum+a.length,0));let pad=0;arrays.forEach(a=>{if(!u8a$1(a))throw new Error("Uint8Array expected");r.set(a,pad);pad+=a.length});return r}class Hash{clone(){return this._cloneInto()}}const toStr={}.toString;function checkOpts(defaults,opts){if(opts!==undefined&&toStr.call(opts)!=="[object Object]")throw new Error("Options should be object or undefined");const merged=Object.assign(defaults,opts);return merged}function wrapConstructor(hashCons){const hashC=msg=>hashCons().update(toBytes(msg)).digest();const tmp=hashCons();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashCons();return hashC}function randomBytes$2(bytesLength=32){if(crypto$1&&typeof crypto$1.getRandomValues==="function"){return crypto$1.getRandomValues(new Uint8Array(bytesLength))}throw new Error("crypto.getRandomValues must be defined")}class HMAC extends Hash{constructor(hash$1,_key){super();this.finished=false;this.destroyed=false;hash(hash$1);const key=toBytes(_key);this.iHash=hash$1.create();if(typeof this.iHash.update!=="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen;this.outputLen=this.iHash.outputLen;const blockLen=this.blockLen;const pad=new Uint8Array(blockLen);pad.set(key.length>blockLen?hash$1.create().update(key).digest():key);for(let i=0;inew HMAC(hash,key).update(message).digest();hmac.create=(hash,key)=>new HMAC(hash,key);function pbkdf2Init(hash$1,_password,_salt,_opts){hash(hash$1);const opts=checkOpts({dkLen:32,asyncTick:10},_opts);const{c,dkLen,asyncTick}=opts;number(c);number(dkLen);number(asyncTick);if(c<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const password=toBytes(_password);const salt=toBytes(_salt);const DK=new Uint8Array(dkLen);const PRF=hmac.create(hash$1,password);const PRFSalt=PRF._cloneInto().update(salt);return{c:c,dkLen:dkLen,asyncTick:asyncTick,DK:DK,PRF:PRF,PRFSalt:PRFSalt}}function pbkdf2Output(PRF,PRFSalt,DK,prfW,u){PRF.destroy();PRFSalt.destroy();if(prfW)prfW.destroy();u.fill(0);return DK}function pbkdf2$1(hash,password,salt,opts){const{c,dkLen,DK,PRF,PRFSalt}=pbkdf2Init(hash,password,salt,opts);let prfW;const arr=new Uint8Array(4);const view=createView(arr);const u=new Uint8Array(PRF.outputLen);for(let ti=1,pos=0;pos>_32n&_u32_max);const wl=Number(value&_u32_max);const h=isLE?4:0;const l=isLE?0:4;view.setUint32(byteOffset+h,wh,isLE);view.setUint32(byteOffset+l,wl,isLE)}class SHA2 extends Hash{constructor(blockLen,outputLen,padOffset,isLE){super();this.blockLen=blockLen;this.outputLen=outputLen;this.padOffset=padOffset;this.isLE=isLE;this.finished=false;this.length=0;this.pos=0;this.destroyed=false;this.buffer=new Uint8Array(blockLen);this.view=createView(this.buffer)}update(data){exists(this);const{view,buffer,blockLen}=this;data=toBytes(data);const len=data.length;for(let pos=0;posblockLen-pos){this.process(view,0);pos=0}for(let i=pos;istate.length)throw new Error("_sha2: outputLen bigger than state");for(let i=0;ia&b^~a&c;const Maj=(a,b,c)=>a&b^a&c^b&c;const SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);const IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);const SHA256_W=new Uint32Array(64);class SHA256 extends SHA2{constructor(){super(64,32,8,false);this.A=IV[0]|0;this.B=IV[1]|0;this.C=IV[2]|0;this.D=IV[3]|0;this.E=IV[4]|0;this.F=IV[5]|0;this.G=IV[6]|0;this.H=IV[7]|0}get(){const{A,B,C,D,E,F,G,H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=A|0;this.B=B|0;this.C=C|0;this.D=D|0;this.E=E|0;this.F=F|0;this.G=G|0;this.H=H|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,false);for(let i=16;i<64;i++){const W15=SHA256_W[i-15];const W2=SHA256_W[i-2];const s0=rotr(W15,7)^rotr(W15,18)^W15>>>3;const s1=rotr(W2,17)^rotr(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A,B,C,D,E,F,G,H}=this;for(let i=0;i<64;i++){const sigma1=rotr(E,6)^rotr(E,11)^rotr(E,25);const T1=H+sigma1+Chi(E,F,G)+SHA256_K[i]+SHA256_W[i]|0;const sigma0=rotr(A,2)^rotr(A,13)^rotr(A,22);const T2=sigma0+Maj(A,B,C)|0;H=G;G=F;F=E;E=D+T1|0;D=C;C=B;B=A;A=T1+T2|0}A=A+this.A|0;B=B+this.B|0;C=C+this.C|0;D=D+this.D|0;E=E+this.E|0;F=F+this.F|0;G=G+this.G|0;H=H+this.H|0;this.set(A,B,C,D,E,F,G,H)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0);this.buffer.fill(0)}}const sha256$1=wrapConstructor(()=>new SHA256);const U32_MASK64=BigInt(2**32-1);const _32n=BigInt(32);function fromBig(n,le=false){if(le)return{h:Number(n&U32_MASK64),l:Number(n>>_32n&U32_MASK64)};return{h:Number(n>>_32n&U32_MASK64)|0,l:Number(n&U32_MASK64)|0}}function split(lst,le=false){let Ah=new Uint32Array(lst.length);let Al=new Uint32Array(lst.length);for(let i=0;iBigInt(h>>>0)<<_32n|BigInt(l>>>0);const shrSH=(h,_l,s)=>h>>>s;const shrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrSH=(h,l,s)=>h>>>s|l<<32-s;const rotrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrBH=(h,l,s)=>h<<64-s|l>>>s-32;const rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;const rotr32H=(_h,l)=>l;const rotr32L=(h,_l)=>h;const rotlSH=(h,l,s)=>h<>>32-s;const rotlSL=(h,l,s)=>l<>>32-s;const rotlBH=(h,l,s)=>l<>>64-s;const rotlBL=(h,l,s)=>h<>>64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:l|0}}const add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0);const add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0;const add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0);const add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0;const add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0);const add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0;const u64={fromBig:fromBig,split:split,toBig:toBig,shrSH:shrSH,shrSL:shrSL,rotrSH:rotrSH,rotrSL:rotrSL,rotrBH:rotrBH,rotrBL:rotrBL,rotr32H:rotr32H,rotr32L:rotr32L,rotlSH:rotlSH,rotlSL:rotlSL,rotlBH:rotlBH,rotlBL:rotlBL,add:add,add3L:add3L,add3H:add3H,add4L:add4L,add4H:add4H,add5H:add5H,add5L:add5L};const[SHA512_Kh,SHA512_Kl]=(()=>u64.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))))();const SHA512_W_H=new Uint32Array(80);const SHA512_W_L=new Uint32Array(80);class SHA512 extends SHA2{constructor(){super(128,64,16,false);this.Ah=1779033703|0;this.Al=4089235720|0;this.Bh=3144134277|0;this.Bl=2227873595|0;this.Ch=1013904242|0;this.Cl=4271175723|0;this.Dh=2773480762|0;this.Dl=1595750129|0;this.Eh=1359893119|0;this.El=2917565137|0;this.Fh=2600822924|0;this.Fl=725511199|0;this.Gh=528734635|0;this.Gl=4215389547|0;this.Hh=1541459225|0;this.Hl=327033209|0}get(){const{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0;this.Al=Al|0;this.Bh=Bh|0;this.Bl=Bl|0;this.Ch=Ch|0;this.Cl=Cl|0;this.Dh=Dh|0;this.Dl=Dl|0;this.Eh=Eh|0;this.El=El|0;this.Fh=Fh|0;this.Fl=Fl|0;this.Gh=Gh|0;this.Gl=Gl|0;this.Hh=Hh|0;this.Hl=Hl|0}process(view,offset){for(let i=0;i<16;i++,offset+=4){SHA512_W_H[i]=view.getUint32(offset);SHA512_W_L[i]=view.getUint32(offset+=4)}for(let i=16;i<80;i++){const W15h=SHA512_W_H[i-15]|0;const W15l=SHA512_W_L[i-15]|0;const s0h=u64.rotrSH(W15h,W15l,1)^u64.rotrSH(W15h,W15l,8)^u64.shrSH(W15h,W15l,7);const s0l=u64.rotrSL(W15h,W15l,1)^u64.rotrSL(W15h,W15l,8)^u64.shrSL(W15h,W15l,7);const W2h=SHA512_W_H[i-2]|0;const W2l=SHA512_W_L[i-2]|0;const s1h=u64.rotrSH(W2h,W2l,19)^u64.rotrBH(W2h,W2l,61)^u64.shrSH(W2h,W2l,6);const s1l=u64.rotrSL(W2h,W2l,19)^u64.rotrBL(W2h,W2l,61)^u64.shrSL(W2h,W2l,6);const SUMl=u64.add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]);const SUMh=u64.add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=SUMh|0;SHA512_W_L[i]=SUMl|0}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){const sigma1h=u64.rotrSH(Eh,El,14)^u64.rotrSH(Eh,El,18)^u64.rotrBH(Eh,El,41);const sigma1l=u64.rotrSL(Eh,El,14)^u64.rotrSL(Eh,El,18)^u64.rotrBL(Eh,El,41);const CHIh=Eh&Fh^~Eh&Gh;const CHIl=El&Fl^~El&Gl;const T1ll=u64.add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]);const T1h=u64.add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]);const T1l=T1ll|0;const sigma0h=u64.rotrSH(Ah,Al,28)^u64.rotrBH(Ah,Al,34)^u64.rotrBH(Ah,Al,39);const sigma0l=u64.rotrSL(Ah,Al,28)^u64.rotrBL(Ah,Al,34)^u64.rotrBL(Ah,Al,39);const MAJh=Ah&Bh^Ah&Ch^Bh&Ch;const MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0;Hl=Gl|0;Gh=Fh|0;Gl=Fl|0;Fh=Eh|0;Fl=El|0;({h:Eh,l:El}=u64.add(Dh|0,Dl|0,T1h|0,T1l|0));Dh=Ch|0;Dl=Cl|0;Ch=Bh|0;Cl=Bl|0;Bh=Ah|0;Bl=Al|0;const All=u64.add3L(T1l,sigma0l,MAJl);Ah=u64.add3H(All,T1h,sigma0h,MAJh);Al=All|0}({h:Ah,l:Al}=u64.add(this.Ah|0,this.Al|0,Ah|0,Al|0));({h:Bh,l:Bl}=u64.add(this.Bh|0,this.Bl|0,Bh|0,Bl|0));({h:Ch,l:Cl}=u64.add(this.Ch|0,this.Cl|0,Ch|0,Cl|0));({h:Dh,l:Dl}=u64.add(this.Dh|0,this.Dl|0,Dh|0,Dl|0));({h:Eh,l:El}=u64.add(this.Eh|0,this.El|0,Eh|0,El|0));({h:Fh,l:Fl}=u64.add(this.Fh|0,this.Fl|0,Fh|0,Fl|0));({h:Gh,l:Gl}=u64.add(this.Gh|0,this.Gl|0,Gh|0,Gl|0));({h:Hh,l:Hl}=u64.add(this.Hh|0,this.Hl|0,Hh|0,Hl|0));this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){SHA512_W_H.fill(0);SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0);this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha512$1=wrapConstructor(()=>new SHA512);function getGlobal$1(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")}const anyGlobal=getGlobal$1();const crypto=anyGlobal.crypto||anyGlobal.msCrypto;function createHash(algo){switch(algo){case"sha256":return sha256$1.create();case"sha512":return sha512$1.create()}assertArgument(false,"invalid hashing algorithm name","algorithm",algo)}function createHmac(_algo,key){const algo={sha256:sha256$1,sha512:sha512$1}[_algo];assertArgument(algo!=null,"invalid hmac algorithm","algorithm",_algo);return hmac.create(algo,key)}function pbkdf2Sync(password,salt,iterations,keylen,_algo){const algo={sha256:sha256$1,sha512:sha512$1}[_algo];assertArgument(algo!=null,"invalid pbkdf2 algorithm","algorithm",_algo);return pbkdf2$1(algo,password,salt,{c:iterations,dkLen:keylen})}function randomBytes$1(length){assert(crypto!=null,"platform does not support secure random numbers","UNSUPPORTED_OPERATION",{operation:"randomBytes"});assertArgument(Number.isInteger(length)&&length>0&&length<=1024,"invalid length","length",length);const result=new Uint8Array(length);crypto.getRandomValues(result);return result}let locked$4=false;const _computeHmac=function(algorithm,key,data){return createHmac(algorithm,key).update(data).digest()};let __computeHmac=_computeHmac;function computeHmac(algorithm,_key,_data){const key=getBytes(_key,"key");const data=getBytes(_data,"data");return hexlify(__computeHmac(algorithm,key,data))}computeHmac._=_computeHmac;computeHmac.lock=function(){locked$4=true};computeHmac.register=function(func){if(locked$4){throw new Error("computeHmac is locked")}__computeHmac=func};Object.freeze(computeHmac);const[SHA3_PI,SHA3_ROTL,_SHA3_IOTA]=[[],[],[]];const _0n$6=BigInt(0);const _1n$6=BigInt(1);const _2n$4=BigInt(2);const _7n$1=BigInt(7);const _256n=BigInt(256);const _0x71n=BigInt(113);for(let round=0,R=_1n$6,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5];SHA3_PI.push(2*(5*y+x));SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n$6;for(let j=0;j<7;j++){R=(R<<_1n$6^(R>>_7n$1)*_0x71n)%_256n;if(R&_2n$4)t^=_1n$6<<(_1n$6<s>32?rotlBH(h,l,s):rotlSH(h,l,s);const rotlL=(h,l,s)=>s>32?rotlBL(h,l,s):rotlSL(h,l,s);function keccakP(s,rounds=24){const B=new Uint32Array(5*2);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){const idx1=(x+8)%10;const idx0=(x+2)%10;const B0=B[idx0];const B1=B[idx0+1];const Th=rotlH(B0,B1,1)^B[idx1];const Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10){s[x+y]^=Th;s[x+y+1]^=Tl}}let curH=s[2];let curL=s[3];for(let t=0;t<24;t++){const shift=SHA3_ROTL[t];const Th=rotlH(curH,curL,shift);const Tl=rotlL(curH,curL,shift);const PI=SHA3_PI[t];curH=s[PI];curL=s[PI+1];s[PI]=Th;s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round];s[1]^=SHA3_IOTA_L[round]}B.fill(0)}class Keccak extends Hash{constructor(blockLen,suffix,outputLen,enableXOF=false,rounds=24){super();this.blockLen=blockLen;this.suffix=suffix;this.outputLen=outputLen;this.enableXOF=enableXOF;this.rounds=rounds;this.pos=0;this.posOut=0;this.finished=false;this.destroyed=false;number(outputLen);if(0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200);this.state32=u32(this.state)}keccak(){keccakP(this.state32,this.rounds);this.posOut=0;this.pos=0}update(data){exists(this);const{blockLen,state}=this;data=toBytes(data);const len=data.length;for(let pos=0;pos=blockLen)this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos);this.posOut+=take;pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){number(bytes);return this.xofInto(new Uint8Array(bytes))}digestInto(out){output(out,this);if(this.finished)throw new Error("digest() was already called");this.writeInto(out);this.destroy();return out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true;this.state.fill(0)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds));to.state32.set(this.state32);to.pos=this.pos;to.posOut=this.posOut;to.finished=this.finished;to.rounds=rounds;to.suffix=suffix;to.outputLen=outputLen;to.enableXOF=enableXOF;to.destroyed=this.destroyed;return to}}const gen=(suffix,blockLen,outputLen)=>wrapConstructor(()=>new Keccak(blockLen,suffix,outputLen));const keccak_256=gen(1,136,256/8);let locked$3=false;const _keccak256=function(data){return keccak_256(data)};let __keccak256=_keccak256;function keccak256(_data){const data=getBytes(_data,"data");return hexlify(__keccak256(data))}keccak256._=_keccak256;keccak256.lock=function(){locked$3=true};keccak256.register=function(func){if(locked$3){throw new TypeError("keccak256 is locked")}__keccak256=func};Object.freeze(keccak256);const Rho=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]);const Id=Uint8Array.from({length:16},(_,i)=>i);const Pi=Id.map(i=>(9*i+5)%16);let idxL=[Id];let idxR=[Pi];for(let i=0;i<4;i++)for(let j of[idxL,idxR])j.push(j[i].map(k=>Rho[k]));const shifts=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(i=>new Uint8Array(i));const shiftsL=idxL.map((idx,i)=>idx.map(j=>shifts[i][j]));const shiftsR=idxR.map((idx,i)=>idx.map(j=>shifts[i][j]));const Kl=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]);const Kr=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);const rotl$1=(word,shift)=>word<>>32-shift;function f(group,x,y,z){if(group===0)return x^y^z;else if(group===1)return x&y|~x&z;else if(group===2)return(x|~y)^z;else if(group===3)return x&z|y&~z;else return x^(y|~z)}const BUF=new Uint32Array(16);class RIPEMD160 extends SHA2{constructor(){super(64,20,8,true);this.h0=1732584193|0;this.h1=4023233417|0;this.h2=2562383102|0;this.h3=271733878|0;this.h4=3285377520|0}get(){const{h0,h1,h2,h3,h4}=this;return[h0,h1,h2,h3,h4]}set(h0,h1,h2,h3,h4){this.h0=h0|0;this.h1=h1|0;this.h2=h2|0;this.h3=h3|0;this.h4=h4|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)BUF[i]=view.getUint32(offset,true);let al=this.h0|0,ar=al,bl=this.h1|0,br=bl,cl=this.h2|0,cr=cl,dl=this.h3|0,dr=dl,el=this.h4|0,er=el;for(let group=0;group<5;group++){const rGroup=4-group;const hbl=Kl[group],hbr=Kr[group];const rl=idxL[group],rr=idxR[group];const sl=shiftsL[group],sr=shiftsR[group];for(let i=0;i<16;i++){const tl=rotl$1(al+f(group,bl,cl,dl)+BUF[rl[i]]+hbl,sl[i])+el|0;al=el,el=dl,dl=rotl$1(cl,10)|0,cl=bl,bl=tl}for(let i=0;i<16;i++){const tr=rotl$1(ar+f(rGroup,br,cr,dr)+BUF[rr[i]]+hbr,sr[i])+er|0;ar=er,er=dr,dr=rotl$1(cr,10)|0,cr=br,br=tr}}this.set(this.h1+cl+dr|0,this.h2+dl+er|0,this.h3+el+ar|0,this.h4+al+br|0,this.h0+bl+cr|0)}roundClean(){BUF.fill(0)}destroy(){this.destroyed=true;this.buffer.fill(0);this.set(0,0,0,0,0)}}const ripemd160$1=wrapConstructor(()=>new RIPEMD160);let locked$2=false;const _ripemd160=function(data){return ripemd160$1(data)};let __ripemd160=_ripemd160;function ripemd160(_data){const data=getBytes(_data,"data");return hexlify(__ripemd160(data))}ripemd160._=_ripemd160;ripemd160.lock=function(){locked$2=true};ripemd160.register=function(func){if(locked$2){throw new TypeError("ripemd160 is locked")}__ripemd160=func};Object.freeze(ripemd160);let locked$1=false;const _pbkdf2=function(password,salt,iterations,keylen,algo){return pbkdf2Sync(password,salt,iterations,keylen,algo)};let __pbkdf2=_pbkdf2;function pbkdf2(_password,_salt,iterations,keylen,algo){const password=getBytes(_password,"password");const salt=getBytes(_salt,"salt");return hexlify(__pbkdf2(password,salt,iterations,keylen,algo))}pbkdf2._=_pbkdf2;pbkdf2.lock=function(){locked$1=true};pbkdf2.register=function(func){if(locked$1){throw new Error("pbkdf2 is locked")}__pbkdf2=func};Object.freeze(pbkdf2);let locked=false;const _randomBytes=function(length){return new Uint8Array(randomBytes$1(length))};let __randomBytes=_randomBytes;function randomBytes(length){return __randomBytes(length)}randomBytes._=_randomBytes;randomBytes.lock=function(){locked=true};randomBytes.register=function(func){if(locked){throw new Error("randomBytes is locked")}__randomBytes=func};Object.freeze(randomBytes);const rotl=(a,b)=>a<>>32-b;function XorAndSalsa(prev,pi,input,ii,out,oi){let y00=prev[pi++]^input[ii++],y01=prev[pi++]^input[ii++];let y02=prev[pi++]^input[ii++],y03=prev[pi++]^input[ii++];let y04=prev[pi++]^input[ii++],y05=prev[pi++]^input[ii++];let y06=prev[pi++]^input[ii++],y07=prev[pi++]^input[ii++];let y08=prev[pi++]^input[ii++],y09=prev[pi++]^input[ii++];let y10=prev[pi++]^input[ii++],y11=prev[pi++]^input[ii++];let y12=prev[pi++]^input[ii++],y13=prev[pi++]^input[ii++];let y14=prev[pi++]^input[ii++],y15=prev[pi++]^input[ii++];let x00=y00,x01=y01,x02=y02,x03=y03,x04=y04,x05=y05,x06=y06,x07=y07,x08=y08,x09=y09,x10=y10,x11=y11,x12=y12,x13=y13,x14=y14,x15=y15;for(let i=0;i<8;i+=2){x04^=rotl(x00+x12|0,7);x08^=rotl(x04+x00|0,9);x12^=rotl(x08+x04|0,13);x00^=rotl(x12+x08|0,18);x09^=rotl(x05+x01|0,7);x13^=rotl(x09+x05|0,9);x01^=rotl(x13+x09|0,13);x05^=rotl(x01+x13|0,18);x14^=rotl(x10+x06|0,7);x02^=rotl(x14+x10|0,9);x06^=rotl(x02+x14|0,13);x10^=rotl(x06+x02|0,18);x03^=rotl(x15+x11|0,7);x07^=rotl(x03+x15|0,9);x11^=rotl(x07+x03|0,13);x15^=rotl(x11+x07|0,18);x01^=rotl(x00+x03|0,7);x02^=rotl(x01+x00|0,9);x03^=rotl(x02+x01|0,13);x00^=rotl(x03+x02|0,18);x06^=rotl(x05+x04|0,7);x07^=rotl(x06+x05|0,9);x04^=rotl(x07+x06|0,13);x05^=rotl(x04+x07|0,18);x11^=rotl(x10+x09|0,7);x08^=rotl(x11+x10|0,9);x09^=rotl(x08+x11|0,13);x10^=rotl(x09+x08|0,18);x12^=rotl(x15+x14|0,7);x13^=rotl(x12+x15|0,9);x14^=rotl(x13+x12|0,13);x15^=rotl(x14+x13|0,18)}out[oi++]=y00+x00|0;out[oi++]=y01+x01|0;out[oi++]=y02+x02|0;out[oi++]=y03+x03|0;out[oi++]=y04+x04|0;out[oi++]=y05+x05|0;out[oi++]=y06+x06|0;out[oi++]=y07+x07|0;out[oi++]=y08+x08|0;out[oi++]=y09+x09|0;out[oi++]=y10+x10|0;out[oi++]=y11+x11|0;out[oi++]=y12+x12|0;out[oi++]=y13+x13|0;out[oi++]=y14+x14|0;out[oi++]=y15+x15|0}function BlockMix(input,ii,out,oi,r){let head=oi+0;let tail=oi+16*r;for(let i=0;i<16;i++)out[tail+i]=input[ii+(2*r-1)*16+i];for(let i=0;i0)tail+=16;XorAndSalsa(out,head,input,ii+=16,out,tail)}}function scryptInit(password,salt,_opts){const opts=checkOpts({dkLen:32,asyncTick:10,maxmem:1024**3+1024},_opts);const{N,r,p,dkLen,asyncTick,maxmem,onProgress}=opts;number(N);number(r);number(p);number(dkLen);number(asyncTick);number(maxmem);if(onProgress!==undefined&&typeof onProgress!=="function")throw new Error("progressCb should be function");const blockSize=128*r;const blockSize32=blockSize/4;if(N<=1||(N&N-1)!==0||N>=2**(blockSize/8)||N>2**32){throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32")}if(p<0||p>(2**32-1)*32/blockSize){throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)")}if(dkLen<0||dkLen>(2**32-1)*32){throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32")}const memUsed=blockSize*(N+p);if(memUsed>maxmem){throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`)}const B=pbkdf2$1(sha256$1,password,salt,{c:1,dkLen:blockSize*p});const B32=u32(B);const V=u32(new Uint8Array(blockSize*N));const tmp=u32(new Uint8Array(blockSize));let blockMixCb=()=>{};if(onProgress){const totalBlockMix=2*N*p;const callbackPer=Math.max(Math.floor(totalBlockMix/1e4),1);let blockMixCnt=0;blockMixCb=()=>{blockMixCnt++;if(onProgress&&(!(blockMixCnt%callbackPer)||blockMixCnt===totalBlockMix))onProgress(blockMixCnt/totalBlockMix)}}return{N:N,r:r,p:p,dkLen:dkLen,blockSize32:blockSize32,V:V,B32:B32,B:B,tmp:tmp,blockMixCb:blockMixCb,asyncTick:asyncTick}}function scryptOutput(password,dkLen,B,V,tmp){const res=pbkdf2$1(sha256$1,password,B,{c:1,dkLen:dkLen});B.fill(0);V.fill(0);tmp.fill(0);return res}function scrypt$1(password,salt,opts){const{N,r,p,dkLen,blockSize32,V,B32,B,tmp,blockMixCb}=scryptInit(password,salt,opts);for(let pi=0;pi{BlockMix(V,pos,V,pos+=blockSize32,r);blockMixCb()});BlockMix(V,(N-1)*blockSize32,B32,Pi,r);blockMixCb();await asyncLoop(N,asyncTick,()=>{const j=B32[Pi+blockSize32-16]%N;for(let k=0;ka instanceof Uint8Array;const hexes=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));function bytesToHex(bytes){if(!u8a(bytes))throw new Error("Uint8Array expected");let hex="";for(let i=0;isum+a.length,0));let pad=0;arrays.forEach(a=>{if(!u8a(a))throw new Error("Uint8Array expected");r.set(a,pad);pad+=a.length});return r}function equalBytes(b1,b2){if(b1.length!==b2.length)return false;for(let i=0;i_0n$5;n>>=_1n$5,len+=1);return len}function bitGet(n,pos){return n>>BigInt(pos)&_1n$5}const bitSet=(n,pos,value)=>{return n|(value?_1n$5:_0n$5)<(_2n$3<new Uint8Array(data);const u8fr=arr=>Uint8Array.from(arr);function createHmacDrbg(hashLen,qByteLen,hmacFn){if(typeof hashLen!=="number"||hashLen<2)throw new Error("hashLen must be a number");if(typeof qByteLen!=="number"||qByteLen<2)throw new Error("qByteLen must be a number");if(typeof hmacFn!=="function")throw new Error("hmacFn must be a function");let v=u8n(hashLen);let k=u8n(hashLen);let i=0;const reset=()=>{v.fill(1);k.fill(0);i=0};const h=(...b)=>hmacFn(k,v,...b);const reseed=(seed=u8n())=>{k=h(u8fr([0]),seed);v=h();if(seed.length===0)return;k=h(u8fr([1]),seed);v=h()};const gen=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let len=0;const out=[];while(len{reset();reseed(seed);let res=undefined;while(!(res=pred(gen())))reseed();reset();return res};return genUntil}const validatorFns={bigint:val=>typeof val==="bigint",function:val=>typeof val==="function",boolean:val=>typeof val==="boolean",string:val=>typeof val==="string",stringOrUint8Array:val=>typeof val==="string"||val instanceof Uint8Array,isSafeInteger:val=>Number.isSafeInteger(val),array:val=>Array.isArray(val),field:(val,object)=>object.Fp.isValid(val),hash:val=>typeof val==="function"&&Number.isSafeInteger(val.outputLen)};function validateObject(object,validators,optValidators={}){const checkField=(fieldName,type,isOptional)=>{const checkVal=validatorFns[type];if(typeof checkVal!=="function")throw new Error(`Invalid validator "${type}", expected function`);const val=object[fieldName];if(isOptional&&val===undefined)return;if(!checkVal(val,object)){throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`)}};for(const[fieldName,type]of Object.entries(validators))checkField(fieldName,type,false);for(const[fieldName,type]of Object.entries(optValidators))checkField(fieldName,type,true);return object}var ut=Object.freeze({__proto__:null,bitGet:bitGet,bitLen:bitLen,bitMask:bitMask,bitSet:bitSet,bytesToHex:bytesToHex,bytesToNumberBE:bytesToNumberBE,bytesToNumberLE:bytesToNumberLE,concatBytes:concatBytes,createHmacDrbg:createHmacDrbg,ensureBytes:ensureBytes,equalBytes:equalBytes,hexToBytes:hexToBytes,hexToNumber:hexToNumber,numberToBytesBE:numberToBytesBE,numberToBytesLE:numberToBytesLE,numberToHexUnpadded:numberToHexUnpadded,numberToVarBytesBE:numberToVarBytesBE,utf8ToBytes:utf8ToBytes,validateObject:validateObject});const _0n$4=BigInt(0),_1n$4=BigInt(1),_2n$2=BigInt(2),_3n$2=BigInt(3);const _4n=BigInt(4),_5n$1=BigInt(5),_8n=BigInt(8);BigInt(9);BigInt(16);function mod(a,b){const result=a%b;return result>=_0n$4?result:b+result}function pow(num,power,modulo){if(modulo<=_0n$4||power<_0n$4)throw new Error("Expected power/modulo > 0");if(modulo===_1n$4)return _0n$4;let res=_1n$4;while(power>_0n$4){if(power&_1n$4)res=res*num%modulo;num=num*num%modulo;power>>=_1n$4}return res}function pow2(x,power,modulo){let res=x;while(power-- >_0n$4){res*=res;res%=modulo}return res}function invert(number,modulo){if(number===_0n$4||modulo<=_0n$4){throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`)}let a=mod(number,modulo);let b=modulo;let x=_0n$4,u=_1n$4;while(a!==_0n$4){const q=b/a;const r=b%a;const m=x-u*q;b=a,a=r,x=u,u=m}const gcd=b;if(gcd!==_1n$4)throw new Error("invert: does not exist");return mod(x,modulo)}function tonelliShanks(P){const legendreC=(P-_1n$4)/_2n$2;let Q,S,Z;for(Q=P-_1n$4,S=0;Q%_2n$2===_0n$4;Q/=_2n$2,S++);for(Z=_2n$2;Z{map[val]="function";return map},initial);return validateObject(field,opts)}function FpPow(f,num,power){if(power<_0n$4)throw new Error("Expected power > 0");if(power===_0n$4)return f.ONE;if(power===_1n$4)return num;let p=f.ONE;let d=num;while(power>_0n$4){if(power&_1n$4)p=f.mul(p,d);d=f.sqr(d);power>>=_1n$4}return p}function FpInvertBatch(f,nums){const tmp=new Array(nums.length);const lastMultiplied=nums.reduce((acc,num,i)=>{if(f.is0(num))return acc;tmp[i]=acc;return f.mul(acc,num)},f.ONE);const inverted=f.inv(lastMultiplied);nums.reduceRight((acc,num,i)=>{if(f.is0(num))return acc;tmp[i]=f.mul(acc,tmp[i]);return f.mul(acc,num)},inverted);return tmp}function nLength(n,nBitLength){const _nBitLength=nBitLength!==undefined?nBitLength:n.toString(2).length;const nByteLength=Math.ceil(_nBitLength/8);return{nBitLength:_nBitLength,nByteLength:nByteLength}}function Field(ORDER,bitLen,isLE=false,redef={}){if(ORDER<=_0n$4)throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);const{nBitLength:BITS,nByteLength:BYTES}=nLength(ORDER,bitLen);if(BYTES>2048)throw new Error("Field lengths over 2048 bytes are not supported");const sqrtP=FpSqrt(ORDER);const f=Object.freeze({ORDER:ORDER,BITS:BITS,BYTES:BYTES,MASK:bitMask(BITS),ZERO:_0n$4,ONE:_1n$4,create:num=>mod(num,ORDER),isValid:num=>{if(typeof num!=="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);return _0n$4<=num&&numnum===_0n$4,isOdd:num=>(num&_1n$4)===_1n$4,neg:num=>mod(-num,ORDER),eql:(lhs,rhs)=>lhs===rhs,sqr:num=>mod(num*num,ORDER),add:(lhs,rhs)=>mod(lhs+rhs,ORDER),sub:(lhs,rhs)=>mod(lhs-rhs,ORDER),mul:(lhs,rhs)=>mod(lhs*rhs,ORDER),pow:(num,power)=>FpPow(f,num,power),div:(lhs,rhs)=>mod(lhs*invert(rhs,ORDER),ORDER),sqrN:num=>num*num,addN:(lhs,rhs)=>lhs+rhs,subN:(lhs,rhs)=>lhs-rhs,mulN:(lhs,rhs)=>lhs*rhs,inv:num=>invert(num,ORDER),sqrt:redef.sqrt||(n=>sqrtP(f,n)),invertBatch:lst=>FpInvertBatch(f,lst),cmov:(a,b,c)=>c?b:a,toBytes:num=>isLE?numberToBytesLE(num,BYTES):numberToBytesBE(num,BYTES),fromBytes:bytes=>{if(bytes.length!==BYTES)throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);return isLE?bytesToNumberLE(bytes):bytesToNumberBE(bytes)}});return Object.freeze(f)}function getFieldBytesLength(fieldOrder){if(typeof fieldOrder!=="bigint")throw new Error("field order must be bigint");const bitLength=fieldOrder.toString(2).length;return Math.ceil(bitLength/8)}function getMinHashLength(fieldOrder){const length=getFieldBytesLength(fieldOrder);return length+Math.ceil(length/2)}function mapHashToField(key,fieldOrder,isLE=false){const len=key.length;const fieldLen=getFieldBytesLength(fieldOrder);const minLen=getMinHashLength(fieldOrder);if(len<16||len1024)throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);const num=isLE?bytesToNumberBE(key):bytesToNumberLE(key);const reduced=mod(num,fieldOrder-_1n$4)+_1n$4;return isLE?numberToBytesLE(reduced,fieldLen):numberToBytesBE(reduced,fieldLen)}const _0n$3=BigInt(0);const _1n$3=BigInt(1);function wNAF(c,bits){const constTimeNegate=(condition,item)=>{const neg=item.negate();return condition?neg:item};const opts=W=>{const windows=Math.ceil(bits/W)+1;const windowSize=2**(W-1);return{windows:windows,windowSize:windowSize}};return{constTimeNegate:constTimeNegate,unsafeLadder(elm,n){let p=c.ZERO;let d=elm;while(n>_0n$3){if(n&_1n$3)p=p.add(d);d=d.double();n>>=_1n$3}return p},precomputeWindow(elm,W){const{windows,windowSize}=opts(W);const points=[];let p=elm;let base=p;for(let window=0;window>=shiftBy;if(wbits>windowSize){wbits-=maxNumber;n+=_1n$3}const offset1=offset;const offset2=offset+Math.abs(wbits)-1;const cond1=window%2!==0;const cond2=wbits<0;if(wbits===0){f=f.add(constTimeNegate(cond1,precomputes[offset1]))}else{p=p.add(constTimeNegate(cond2,precomputes[offset2]))}}return{p:p,f:f}},wNAFCached(P,precomputesMap,n,transform){const W=P._WINDOW_SIZE||1;let comp=precomputesMap.get(P);if(!comp){comp=this.precomputeWindow(P,W);if(W!==1){precomputesMap.set(P,transform(comp))}}return this.wNAF(W,comp,n)}}}function validateBasic(curve){validateField(curve.Fp);validateObject(curve,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"});return Object.freeze({...nLength(curve.n,curve.nBitLength),...curve,...{p:curve.Fp.ORDER}})}function validatePointOpts(curve){const opts=validateBasic(curve);validateObject(opts,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo,Fp,a}=opts;if(endo){if(!Fp.eql(a,Fp.ZERO)){throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0")}if(typeof endo!=="object"||typeof endo.beta!=="bigint"||typeof endo.splitScalar!=="function"){throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}}return Object.freeze({...opts})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut;const DER={Err:class DERErr extends Error{constructor(m=""){super(m)}},_parseInt(data){const{Err:E}=DER;if(data.length<2||data[0]!==2)throw new E("Invalid signature integer tag");const len=data[1];const res=data.subarray(2,len+2);if(!len||res.length!==len)throw new E("Invalid signature integer: wrong length");if(res[0]&128)throw new E("Invalid signature integer: negative");if(res[0]===0&&!(res[1]&128))throw new E("Invalid signature integer: unnecessary leading zero");return{d:b2n(res),l:data.subarray(len+2)}},toSig(hex){const{Err:E}=DER;const data=typeof hex==="string"?h2b(hex):hex;if(!(data instanceof Uint8Array))throw new Error("ui8a expected");let l=data.length;if(l<2||data[0]!=48)throw new E("Invalid signature tag");if(data[1]!==l-2)throw new E("Invalid signature: incorrect length");const{d:r,l:sBytes}=DER._parseInt(data.subarray(2));const{d:s,l:rBytesLeft}=DER._parseInt(sBytes);if(rBytesLeft.length)throw new E("Invalid signature: left bytes after parsing");return{r:r,s:s}},hexFromSig(sig){const slice=s=>Number.parseInt(s[0],16)&8?"00"+s:s;const h=num=>{const hex=num.toString(16);return hex.length&1?`0${hex}`:hex};const s=slice(h(sig.s));const r=slice(h(sig.r));const shl=s.length/2;const rhl=r.length/2;const sl=h(shl);const rl=h(rhl);return`30${h(rhl+shl+4)}02${rl}${r}02${sl}${s}`}};const _0n$2=BigInt(0),_1n$2=BigInt(1);BigInt(2);const _3n$1=BigInt(3);BigInt(4);function weierstrassPoints(opts){const CURVE=validatePointOpts(opts);const{Fp}=CURVE;const toBytes=CURVE.toBytes||((_c,point,_isCompressed)=>{const a=point.toAffine();return concatBytes(Uint8Array.from([4]),Fp.toBytes(a.x),Fp.toBytes(a.y))});const fromBytes=CURVE.fromBytes||(bytes=>{const tail=bytes.subarray(1);const x=Fp.fromBytes(tail.subarray(0,Fp.BYTES));const y=Fp.fromBytes(tail.subarray(Fp.BYTES,2*Fp.BYTES));return{x:x,y:y}});function weierstrassEquation(x){const{a,b}=CURVE;const x2=Fp.sqr(x);const x3=Fp.mul(x2,x);return Fp.add(Fp.add(x3,Fp.mul(x,a)),b)}if(!Fp.eql(Fp.sqr(CURVE.Gy),weierstrassEquation(CURVE.Gx)))throw new Error("bad generator point: equation left != right");function isWithinCurveOrder(num){return typeof num==="bigint"&&_0n$2Fp.eql(i,Fp.ZERO);if(is0(x)&&is0(y))return Point.ZERO;return new Point(x,y,Fp.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(points){const toInv=Fp.invertBatch(points.map(p=>p.pz));return points.map((p,i)=>p.toAffine(toInv[i])).map(Point.fromAffine)}static fromHex(hex){const P=Point.fromAffine(fromBytes(ensureBytes("pointHex",hex)));P.assertValidity();return P}static fromPrivateKey(privateKey){return Point.BASE.multiply(normPrivateKeyToScalar(privateKey))}_setWindowSize(windowSize){this._WINDOW_SIZE=windowSize;pointPrecomputes.delete(this)}assertValidity(){if(this.is0()){if(CURVE.allowInfinityPoint&&!Fp.is0(this.py))return;throw new Error("bad point: ZERO")}const{x,y}=this.toAffine();if(!Fp.isValid(x)||!Fp.isValid(y))throw new Error("bad point: x or y not FE");const left=Fp.sqr(y);const right=weierstrassEquation(x);if(!Fp.eql(left,right))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y}=this.toAffine();if(Fp.isOdd)return!Fp.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(other){assertPrjPoint(other);const{px:X1,py:Y1,pz:Z1}=this;const{px:X2,py:Y2,pz:Z2}=other;const U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1));const U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point(this.px,Fp.neg(this.py),this.pz)}double(){const{a,b}=CURVE;const b3=Fp.mul(b,_3n$1);const{px:X1,py:Y1,pz:Z1}=this;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;let t0=Fp.mul(X1,X1);let t1=Fp.mul(Y1,Y1);let t2=Fp.mul(Z1,Z1);let t3=Fp.mul(X1,Y1);t3=Fp.add(t3,t3);Z3=Fp.mul(X1,Z1);Z3=Fp.add(Z3,Z3);X3=Fp.mul(a,Z3);Y3=Fp.mul(b3,t2);Y3=Fp.add(X3,Y3);X3=Fp.sub(t1,Y3);Y3=Fp.add(t1,Y3);Y3=Fp.mul(X3,Y3);X3=Fp.mul(t3,X3);Z3=Fp.mul(b3,Z3);t2=Fp.mul(a,t2);t3=Fp.sub(t0,t2);t3=Fp.mul(a,t3);t3=Fp.add(t3,Z3);Z3=Fp.add(t0,t0);t0=Fp.add(Z3,t0);t0=Fp.add(t0,t2);t0=Fp.mul(t0,t3);Y3=Fp.add(Y3,t0);t2=Fp.mul(Y1,Z1);t2=Fp.add(t2,t2);t0=Fp.mul(t2,t3);X3=Fp.sub(X3,t0);Z3=Fp.mul(t2,t1);Z3=Fp.add(Z3,Z3);Z3=Fp.add(Z3,Z3);return new Point(X3,Y3,Z3)}add(other){assertPrjPoint(other);const{px:X1,py:Y1,pz:Z1}=this;const{px:X2,py:Y2,pz:Z2}=other;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;const a=CURVE.a;const b3=Fp.mul(CURVE.b,_3n$1);let t0=Fp.mul(X1,X2);let t1=Fp.mul(Y1,Y2);let t2=Fp.mul(Z1,Z2);let t3=Fp.add(X1,Y1);let t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4);t4=Fp.add(t0,t1);t3=Fp.sub(t3,t4);t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);t4=Fp.mul(t4,t5);t5=Fp.add(t0,t2);t4=Fp.sub(t4,t5);t5=Fp.add(Y1,Z1);X3=Fp.add(Y2,Z2);t5=Fp.mul(t5,X3);X3=Fp.add(t1,t2);t5=Fp.sub(t5,X3);Z3=Fp.mul(a,t4);X3=Fp.mul(b3,t2);Z3=Fp.add(X3,Z3);X3=Fp.sub(t1,Z3);Z3=Fp.add(t1,Z3);Y3=Fp.mul(X3,Z3);t1=Fp.add(t0,t0);t1=Fp.add(t1,t0);t2=Fp.mul(a,t2);t4=Fp.mul(b3,t4);t1=Fp.add(t1,t2);t2=Fp.sub(t0,t2);t2=Fp.mul(a,t2);t4=Fp.add(t4,t2);t0=Fp.mul(t1,t4);Y3=Fp.add(Y3,t0);t0=Fp.mul(t5,t4);X3=Fp.mul(t3,X3);X3=Fp.sub(X3,t0);t0=Fp.mul(t3,t1);Z3=Fp.mul(t5,Z3);Z3=Fp.add(Z3,t0);return new Point(X3,Y3,Z3)}subtract(other){return this.add(other.negate())}is0(){return this.equals(Point.ZERO)}wNAF(n){return wnaf.wNAFCached(this,pointPrecomputes,n,comp=>{const toInv=Fp.invertBatch(comp.map(p=>p.pz));return comp.map((p,i)=>p.toAffine(toInv[i])).map(Point.fromAffine)})}multiplyUnsafe(n){const I=Point.ZERO;if(n===_0n$2)return I;assertGE(n);if(n===_1n$2)return this;const{endo}=CURVE;if(!endo)return wnaf.unsafeLadder(this,n);let{k1neg,k1,k2neg,k2}=endo.splitScalar(n);let k1p=I;let k2p=I;let d=this;while(k1>_0n$2||k2>_0n$2){if(k1&_1n$2)k1p=k1p.add(d);if(k2&_1n$2)k2p=k2p.add(d);d=d.double();k1>>=_1n$2;k2>>=_1n$2}if(k1neg)k1p=k1p.negate();if(k2neg)k2p=k2p.negate();k2p=new Point(Fp.mul(k2p.px,endo.beta),k2p.py,k2p.pz);return k1p.add(k2p)}multiply(scalar){assertGE(scalar);let n=scalar;let point,fake;const{endo}=CURVE;if(endo){const{k1neg,k1,k2neg,k2}=endo.splitScalar(n);let{p:k1p,f:f1p}=this.wNAF(k1);let{p:k2p,f:f2p}=this.wNAF(k2);k1p=wnaf.constTimeNegate(k1neg,k1p);k2p=wnaf.constTimeNegate(k2neg,k2p);k2p=new Point(Fp.mul(k2p.px,endo.beta),k2p.py,k2p.pz);point=k1p.add(k2p);fake=f1p.add(f2p)}else{const{p,f}=this.wNAF(n);point=p;fake=f}return Point.normalizeZ([point,fake])[0]}multiplyAndAddUnsafe(Q,a,b){const G=Point.BASE;const mul=(P,a)=>a===_0n$2||a===_1n$2||!P.equals(G)?P.multiplyUnsafe(a):P.multiply(a);const sum=mul(this,a).add(mul(Q,b));return sum.is0()?undefined:sum}toAffine(iz){const{px:x,py:y,pz:z}=this;const is0=this.is0();if(iz==null)iz=is0?Fp.ONE:Fp.inv(z);const ax=Fp.mul(x,iz);const ay=Fp.mul(y,iz);const zz=Fp.mul(z,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw new Error("invZ was invalid");return{x:ax,y:ay}}isTorsionFree(){const{h:cofactor,isTorsionFree}=CURVE;if(cofactor===_1n$2)return true;if(isTorsionFree)return isTorsionFree(Point,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:cofactor,clearCofactor}=CURVE;if(cofactor===_1n$2)return this;if(clearCofactor)return clearCofactor(Point,this);return this.multiplyUnsafe(CURVE.h)}toRawBytes(isCompressed=true){this.assertValidity();return toBytes(Point,this,isCompressed)}toHex(isCompressed=true){return bytesToHex(this.toRawBytes(isCompressed))}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy,Fp.ONE);Point.ZERO=new Point(Fp.ZERO,Fp.ONE,Fp.ZERO);const _bits=CURVE.nBitLength;const wnaf=wNAF(Point,CURVE.endo?Math.ceil(_bits/2):_bits);return{CURVE:CURVE,ProjectivePoint:Point,normPrivateKeyToScalar:normPrivateKeyToScalar,weierstrassEquation:weierstrassEquation,isWithinCurveOrder:isWithinCurveOrder}}function validateOpts(curve){const opts=validateBasic(curve);validateObject(opts,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"});return Object.freeze({lowS:true,...opts})}function weierstrass(curveDef){const CURVE=validateOpts(curveDef);const{Fp,n:CURVE_ORDER}=CURVE;const compressedLen=Fp.BYTES+1;const uncompressedLen=2*Fp.BYTES+1;function isValidFieldElement(num){return _0n$2bytesToHex(numberToBytesBE(num,CURVE.nByteLength));function isBiggerThanHalfOrder(number){const HALF=CURVE_ORDER>>_1n$2;return number>HALF}function normalizeS(s){return isBiggerThanHalfOrder(s)?modN(-s):s}const slcNum=(b,from,to)=>bytesToNumberBE(b.slice(from,to));class Signature{constructor(r,s,recovery){this.r=r;this.s=s;this.recovery=recovery;this.assertValidity()}static fromCompact(hex){const l=CURVE.nByteLength;hex=ensureBytes("compactSignature",hex,l*2);return new Signature(slcNum(hex,0,l),slcNum(hex,l,2*l))}static fromDER(hex){const{r,s}=DER.toSig(ensureBytes("DER",hex));return new Signature(r,s)}assertValidity(){if(!isWithinCurveOrder(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!isWithinCurveOrder(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(recovery){return new Signature(this.r,this.s,recovery)}recoverPublicKey(msgHash){const{r,s,recovery:rec}=this;const h=bits2int_modN(ensureBytes("msgHash",msgHash));if(rec==null||![0,1,2,3].includes(rec))throw new Error("recovery id invalid");const radj=rec===2||rec===3?r+CURVE.n:r;if(radj>=Fp.ORDER)throw new Error("recovery id 2 or 3 invalid");const prefix=(rec&1)===0?"02":"03";const R=Point.fromHex(prefix+numToNByteStr(radj));const ir=invN(radj);const u1=modN(-h*ir);const u2=modN(s*ir);const Q=Point.BASE.multiplyAndAddUnsafe(R,u1,u2);if(!Q)throw new Error("point at infinify");Q.assertValidity();return Q}hasHighS(){return isBiggerThanHalfOrder(this.s)}normalizeS(){return this.hasHighS()?new Signature(this.r,modN(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numToNByteStr(this.r)+numToNByteStr(this.s)}}const utils={isValidPrivateKey(privateKey){try{normPrivateKeyToScalar(privateKey);return true}catch(error){return false}},normPrivateKeyToScalar:normPrivateKeyToScalar,randomPrivateKey:()=>{const length=getMinHashLength(CURVE.n);return mapHashToField(CURVE.randomBytes(length),CURVE.n)},precompute(windowSize=8,point=Point.BASE){point._setWindowSize(windowSize);point.multiply(BigInt(3));return point}};function getPublicKey(privateKey,isCompressed=true){return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed)}function isProbPub(item){const arr=item instanceof Uint8Array;const str=typeof item==="string";const len=(arr||str)&&item.length;if(arr)return len===compressedLen||len===uncompressedLen;if(str)return len===2*compressedLen||len===2*uncompressedLen;if(item instanceof Point)return true;return false}function getSharedSecret(privateA,publicB,isCompressed=true){if(isProbPub(privateA))throw new Error("first arg must be private key");if(!isProbPub(publicB))throw new Error("second arg must be public key");const b=Point.fromHex(publicB);return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed)}const bits2int=CURVE.bits2int||function(bytes){const num=bytesToNumberBE(bytes);const delta=bytes.length*8-CURVE.nBitLength;return delta>0?num>>BigInt(delta):num};const bits2int_modN=CURVE.bits2int_modN||function(bytes){return modN(bits2int(bytes))};const ORDER_MASK=bitMask(CURVE.nBitLength);function int2octets(num){if(typeof num!=="bigint")throw new Error("bigint expected");if(!(_0n$2<=num&&numk in opts))throw new Error("sign() legacy options not supported");const{hash,randomBytes}=CURVE;let{lowS,prehash,extraEntropy:ent}=opts;if(lowS==null)lowS=true;msgHash=ensureBytes("msgHash",msgHash);if(prehash)msgHash=ensureBytes("prehashed msgHash",hash(msgHash));const h1int=bits2int_modN(msgHash);const d=normPrivateKeyToScalar(privateKey);const seedArgs=[int2octets(d),int2octets(h1int)];if(ent!=null){const e=ent===true?randomBytes(Fp.BYTES):ent;seedArgs.push(ensureBytes("extraEntropy",e))}const seed=concatBytes(...seedArgs);const m=h1int;function k2sig(kBytes){const k=bits2int(kBytes);if(!isWithinCurveOrder(k))return;const ik=invN(k);const q=Point.BASE.multiply(k).toAffine();const r=modN(q.x);if(r===_0n$2)return;const s=modN(ik*modN(m+r*d));if(s===_0n$2)return;let recovery=(q.x===r?0:2)|Number(q.y&_1n$2);let normS=s;if(lowS&&isBiggerThanHalfOrder(s)){normS=normalizeS(s);recovery^=1}return new Signature(r,normS,recovery)}return{seed:seed,k2sig:k2sig}}const defaultSigOpts={lowS:CURVE.lowS,prehash:false};const defaultVerOpts={lowS:CURVE.lowS,prehash:false};function sign(msgHash,privKey,opts=defaultSigOpts){const{seed,k2sig}=prepSig(msgHash,privKey,opts);const C=CURVE;const drbg=createHmacDrbg(C.hash.outputLen,C.nByteLength,C.hmac);return drbg(seed,k2sig)}Point.BASE._setWindowSize(8);function verify(signature,msgHash,publicKey,opts=defaultVerOpts){const sg=signature;msgHash=ensureBytes("msgHash",msgHash);publicKey=ensureBytes("publicKey",publicKey);if("strict"in opts)throw new Error("options.strict was renamed to lowS");const{lowS,prehash}=opts;let _sig=undefined;let P;try{if(typeof sg==="string"||sg instanceof Uint8Array){try{_sig=Signature.fromDER(sg)}catch(derError){if(!(derError instanceof DER.Err))throw derError;_sig=Signature.fromCompact(sg)}}else if(typeof sg==="object"&&typeof sg.r==="bigint"&&typeof sg.s==="bigint"){const{r,s}=sg;_sig=new Signature(r,s)}else{throw new Error("PARSE")}P=Point.fromHex(publicKey)}catch(error){if(error.message==="PARSE")throw new Error(`signature must be Signature instance, Uint8Array or hex string`);return false}if(lowS&&_sig.hasHighS())return false;if(prehash)msgHash=CURVE.hash(msgHash);const{r,s}=_sig;const h=bits2int_modN(msgHash);const is=invN(s);const u1=modN(h*is);const u2=modN(r*is);const R=Point.BASE.multiplyAndAddUnsafe(P,u1,u2)?.toAffine();if(!R)return false;const v=modN(R.x);return v===r}return{CURVE:CURVE,getPublicKey:getPublicKey,getSharedSecret:getSharedSecret,sign:sign,verify:verify,ProjectivePoint:Point,Signature:Signature,utils:utils}}function getHash(hash){return{hash:hash,hmac:(key,...msgs)=>hmac(hash,key,concatBytes$1(...msgs)),randomBytes:randomBytes$2}}function createCurve(curveDef,defHash){const create=hash=>weierstrass({...curveDef,...getHash(hash)});return Object.freeze({...create(defHash),create:create})}const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");const secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const _1n$1=BigInt(1);const _2n$1=BigInt(2);const divNearest=(a,b)=>(a+b/_2n$1)/b;function sqrtMod(y){const P=secp256k1P;const _3n=BigInt(3),_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22);const _23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88);const b2=y*y*y%P;const b3=b2*b2*y%P;const b6=pow2(b3,_3n,P)*b3%P;const b9=pow2(b6,_3n,P)*b3%P;const b11=pow2(b9,_2n$1,P)*b2%P;const b22=pow2(b11,_11n,P)*b11%P;const b44=pow2(b22,_22n,P)*b22%P;const b88=pow2(b44,_44n,P)*b44%P;const b176=pow2(b88,_88n,P)*b88%P;const b220=pow2(b176,_44n,P)*b44%P;const b223=pow2(b220,_3n,P)*b3%P;const t1=pow2(b223,_23n,P)*b22%P;const t2=pow2(t1,_6n,P)*b2%P;const root=pow2(t2,_2n$1,P);if(!Fp.eql(Fp.sqr(root),y))throw new Error("Cannot find square root");return root}const Fp=Field(secp256k1P,undefined,undefined,{sqrt:sqrtMod});const secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp:Fp,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:true,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:k=>{const n=secp256k1N;const a1=BigInt("0x3086d221a7d46bcde86c90e49284eb15");const b1=-_1n$1*BigInt("0xe4437ed6010e88286f547fa90abfe4c3");const a2=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");const b2=a1;const POW_2_128=BigInt("0x100000000000000000000000000000000");const c1=divNearest(b2*k,n);const c2=divNearest(-b1*k,n);let k1=mod(k-c1*a1-c2*a2,n);let k2=mod(-c1*b1-c2*b2,n);const k1neg=k1>POW_2_128;const k2neg=k2>POW_2_128;if(k1neg)k1=n-k1;if(k2neg)k2=n-k2;if(k1>POW_2_128||k2>POW_2_128){throw new Error("splitScalar: Endomorphism failed, k="+k)}return{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}}}},sha256$1);const _0n$1=BigInt(0);const fe=x=>typeof x==="bigint"&&_0n$1typeof x==="bigint"&&_0n$1c.charCodeAt(0)));tagP=concatBytes(tagH,tagH);TAGGED_HASH_PREFIXES[tag]=tagP}return sha256$1(concatBytes(tagP,...messages))}const pointToBytes=point=>point.toRawBytes(true).slice(1);const numTo32b=n=>numberToBytesBE(n,32);const modP=x=>mod(x,secp256k1P);const modN=x=>mod(x,secp256k1N);const Point=secp256k1.ProjectivePoint;const GmulAdd=(Q,a,b)=>Point.BASE.multiplyAndAddUnsafe(Q,a,b);function schnorrGetExtPubKey(priv){let d_=secp256k1.utils.normPrivateKeyToScalar(priv);let p=Point.fromPrivateKey(d_);const scalar=p.hasEvenY()?d_:modN(-d_);return{scalar:scalar,bytes:pointToBytes(p)}}function lift_x(x){if(!fe(x))throw new Error("bad x: need 0 < x < p");const xx=modP(x*x);const c=modP(xx*x+BigInt(7));let y=sqrtMod(c);if(y%_2n$1!==_0n$1)y=modP(-y);const p=new Point(x,y,_1n$1);p.assertValidity();return p}function challenge(...args){return modN(bytesToNumberBE(taggedHash$1("BIP0340/challenge",...args)))}function schnorrGetPublicKey(privateKey){return schnorrGetExtPubKey(privateKey).bytes}function schnorrSign(message,privateKey,auxRand=randomBytes$2(32)){const m=ensureBytes("message",message);const{bytes:px,scalar:d}=schnorrGetExtPubKey(privateKey);const a=ensureBytes("auxRand",auxRand,32);const t=numTo32b(d^bytesToNumberBE(taggedHash$1("BIP0340/aux",a)));const rand=taggedHash$1("BIP0340/nonce",t,px,m);const k_=modN(bytesToNumberBE(rand));if(k_===_0n$1)throw new Error("sign failed: k is zero");const{bytes:rx,scalar:k}=schnorrGetExtPubKey(k_);const e=challenge(rx,px,m);const sig=new Uint8Array(64);sig.set(rx,0);sig.set(numTo32b(modN(k+e*d)),32);if(!schnorrVerify(sig,m,px))throw new Error("sign: Invalid signature produced");return sig}function schnorrVerify(signature,message,publicKey){const sig=ensureBytes("signature",signature,64);const m=ensureBytes("message",message);const pub=ensureBytes("publicKey",publicKey,32);try{const P=lift_x(bytesToNumberBE(pub));const r=bytesToNumberBE(sig.subarray(0,32));if(!fe(r))return false;const s=bytesToNumberBE(sig.subarray(32,64));if(!ge(s))return false;const e=challenge(numTo32b(r),pointToBytes(P),m);const R=GmulAdd(P,s,modN(-e));if(!R||!R.hasEvenY()||R.toAffine().x!==r)return false;return true}catch(error){return false}}const schnorr=(()=>({getPublicKey:schnorrGetPublicKey,sign:schnorrSign,verify:schnorrVerify,utils:{randomPrivateKey:secp256k1.utils.randomPrivateKey,lift_x:lift_x,pointToBytes:pointToBytes,numberToBytesBE:numberToBytesBE,bytesToNumberBE:bytesToNumberBE,taggedHash:taggedHash$1,mod:mod}}))();const ZeroAddress="0x0000000000000000000000000000000000000000";const ZeroHash="0x0000000000000000000000000000000000000000000000000000000000000000";const N$1=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const WeiPerEther=BigInt("1000000000000000000");const MaxUint256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const MinInt256=BigInt("0x8000000000000000000000000000000000000000000000000000000000000000")*BigInt(-1);const MaxInt256=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const quaisymbol="Ξ";const MessagePrefix="Quai Signed Message:\n";const EthMessagePrefix="Ethereum Signed Message:\n";var Shard;(function(Shard){Shard["Cyprus"]="0x0";Shard["Cyprus1"]="0x00";Shard["Cyprus2"]="0x01";Shard["Cyprus3"]="0x02";Shard["Paxos"]="0x1";Shard["Paxos1"]="0x10";Shard["Paxos2"]="0x11";Shard["Paxos3"]="0x12";Shard["Hydra"]="0x2";Shard["Hydra1"]="0x20";Shard["Hydra2"]="0x21";Shard["Hydra3"]="0x22";Shard["Prime"]="0x"})(Shard||(Shard={}));function shardFromBytes(shard){switch(shard){case"0x":return Shard.Prime;case"0x0":return Shard.Cyprus;case"0x1":return Shard.Paxos;case"0x2":return Shard.Hydra;case"0x00":return Shard.Cyprus1;case"0x01":return Shard.Cyprus2;case"0x02":return Shard.Cyprus3;case"0x10":return Shard.Paxos1;case"0x11":return Shard.Paxos2;case"0x12":return Shard.Paxos3;case"0x20":return Shard.Hydra1;case"0x21":return Shard.Hydra2;case"0x22":return Shard.Hydra3;default:throw new Error("Invalid shard")}}const ShardData=[...ZoneData,{name:"Cyprus",nickname:"cyprus",shard:"region-0",context:2,byte:"0x0"},{name:"Paxos",nickname:"paxos",shard:"region-1",context:2,byte:"0x1"},{name:"Hydra",nickname:"hydra",shard:"region-2",context:2,byte:"0x2"},{name:"Prime",nickname:"prime",shard:"prime",context:2,byte:"0x"}];function toShard(shard){return shardFromBytes(ShardData.find(it=>it.name==shard||it.byte==shard||it.nickname==shard||it.shard==shard)?.byte||"")}function fromShard(shard,key){return ShardData.find(it=>it.byte==shard)?.[key]||""}const BN_0$5=BigInt(0);const BN_1$2=BigInt(1);const BN_2$1=BigInt(2);const BN_27=BigInt(27);const BN_28=BigInt(28);const BN_35=BigInt(35);const _guard$6={};function toUint256(value){return zeroPadValue(toBeArray(value),32)}class Signature{#r;#s;#v;#networkV;get r(){return this.#r}set r(value){assertArgument(dataLength(value)===32,"invalid r","value",value);this.#r=hexlify(value)}get s(){return this.#s}set s(_value){assertArgument(dataLength(_value)===32,"invalid s","value",_value);const value=hexlify(_value);assertArgument(parseInt(value.substring(0,3))<8,"non-canonical s","value",value);this.#s=value}get v(){return this.#v}set v(value){const v=getNumber(value,"value");assertArgument(v===27||v===28,"invalid v","v",value);this.#v=v}get networkV(){return this.#networkV}get legacyChainId(){const v=this.networkV;if(v==null){return null}return Signature.getChainId(v)}get yParity(){return this.v===27?0:1}get yParityAndS(){const yParityAndS=getBytes(this.s);if(this.yParity){yParityAndS[0]|=128}return hexlify(yParityAndS)}get compactSerialized(){return concat([this.r,this.yParityAndS])}get serialized(){return concat([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(guard,r,s,v){assertPrivate(guard,_guard$6,"Signature");this.#r=r;this.#s=s;this.#v=v;this.#networkV=null}[Symbol.for("nodejs.util.inspect.custom")](){return`Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`}clone(){const clone=new Signature(_guard$6,this.r,this.s,this.v);if(this.networkV){clone.#networkV=this.networkV}return clone}toJSON(){const networkV=this.networkV;return{_type:"signature",networkV:networkV!=null?networkV.toString():null,r:this.r,s:this.s,v:this.v}}static getChainId(v){const bv=getBigInt(v,"v");if(bv==BN_27||bv==BN_28){return BN_0$5}assertArgument(bv>=BN_35,"invalid EIP-155 v","v",v);return(bv-BN_35)/BN_2$1}static getChainIdV(chainId,v){return getBigInt(chainId)*BN_2$1+BigInt(35+v-27)}static getNormalizedV(v){const bv=getBigInt(v);if(bv===BN_0$5||bv===BN_27){return 27}if(bv===BN_1$2||bv===BN_28){return 28}assertArgument(bv>=BN_35,"invalid v","v",v);return bv&BN_1$2?27:28}static from(sig){function assertError(check,message){assertArgument(check,message,"signature",sig)}if(sig==null){return new Signature(_guard$6,ZeroHash,ZeroHash,27)}if(typeof sig==="string"){const bytes=getBytes(sig,"signature");if(bytes.length===64){const r=hexlify(bytes.slice(0,32));const s=bytes.slice(32,64);const v=s[0]&128?28:27;s[0]&=127;return new Signature(_guard$6,r,hexlify(s),v)}if(bytes.length===65){const r=hexlify(bytes.slice(0,32));const s=bytes.slice(32,64);assertError((s[0]&128)===0,"non-canonical s");const v=Signature.getNormalizedV(bytes[64]);return new Signature(_guard$6,r,hexlify(s),v)}assertError(false,"invalid raw signature length")}if(sig instanceof Signature){return sig.clone()}const _r=sig.r;assertError(_r!=null,"missing r");const r=toUint256(_r);const s=function(s,yParityAndS){if(s!=null){return toUint256(s)}if(yParityAndS!=null){assertError(isHexString(yParityAndS,32),"invalid yParityAndS");const bytes=getBytes(yParityAndS);bytes[0]&=127;return hexlify(bytes)}assertError(false,"missing s")}(sig.s,sig.yParityAndS);assertError((getBytes(s)[0]&128)==0,"non-canonical s");const{networkV,v}=function(_v,yParityAndS,yParity){if(_v!=null){const v=getBigInt(_v);return{networkV:v>=BN_35?v:undefined,v:Signature.getNormalizedV(v)}}if(yParityAndS!=null){assertError(isHexString(yParityAndS,32),"invalid yParityAndS");return{v:getBytes(yParityAndS)[0]&128?28:27}}if(yParity!=null){switch(yParity){case 0:return{v:27};case 1:return{v:28}}assertError(false,"invalid yParity")}assertError(false,"missing v")}(sig.v,sig.yParityAndS,sig.yParity);const result=new Signature(_guard$6,r,s,v);if(networkV){result.#networkV=networkV}assertError(!("yParity"in sig&&sig.yParity!==result.yParity),"yParity mismatch");assertError(!("yParityAndS"in sig&&sig.yParityAndS!==result.yParityAndS),"yParityAndS mismatch");return result}}class SigningKey{#privateKey;constructor(privateKey){assertArgument(dataLength(privateKey)===32,"invalid private key","privateKey","[REDACTED]");this.#privateKey=hexlify(privateKey)}get privateKey(){return this.#privateKey}get publicKey(){return SigningKey.computePublicKey(this.#privateKey)}get compressedPublicKey(){return SigningKey.computePublicKey(this.#privateKey,true)}sign(digest){assertArgument(dataLength(digest)===32,"invalid digest length","digest",digest);const sig=secp256k1.sign(getBytesCopy(digest),getBytesCopy(this.#privateKey),{lowS:true});return Signature.from({r:toBeHex("0x"+sig.r.toString(16),32),s:toBeHex("0x"+sig.s.toString(16),32),v:sig.recovery?28:27})}computeSharedSecret(other){const pubKey=SigningKey.computePublicKey(other);return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey),getBytes(pubKey),false))}static computePublicKey(key,compressed){let bytes=getBytes(key,"key");if(bytes.length===32){const pubKey=secp256k1.getPublicKey(bytes,!!compressed);return hexlify(pubKey)}if(bytes.length===64){const pub=new Uint8Array(65);pub[0]=4;pub.set(bytes,1);bytes=pub}const point=secp256k1.ProjectivePoint.fromHex(bytes);return hexlify(point.toRawBytes(compressed))}static recoverPublicKey(digest,signature){assertArgument(dataLength(digest)===32,"invalid digest length","digest",digest);const sig=Signature.from(signature);let secpSig=secp256k1.Signature.fromCompact(getBytesCopy(concat([sig.r,sig.s])));secpSig=secpSig.addRecoveryBit(sig.yParity);const pubKey=secpSig.recoverPublicKey(getBytesCopy(digest));assertArgument(pubKey!=null,"invalid signautre for digest","signature",signature);return"0x"+pubKey.toHex(false)}static addPoints(p0,p1,compressed){const pub0=secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p0).substring(2));const pub1=secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p1).substring(2));return"0x"+pub0.add(pub1).toHex(!!compressed)}}const _0n=BigInt(0);const _1n=BigInt(1);const _2n=BigInt(2);const _3n=BigInt(3);const _5n=BigInt(5);const _7n=BigInt(7);const _64n=BigInt(64);const _64mask=BigInt("0xFFFFFFFFFFFFFFFF");const CURVE={b:BigInt(7),P:BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),n:BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141")};function read32b(bytes){if(bytes.length!==32)throw new Error(`Expected 32-bytes, not ${bytes.length}`);const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.length);let b=view.getBigUint64(0);for(let offs=8;offs=0;offs-=8){view.setBigUint64(offs,num&_64mask);num>>=_64n}return dest}function readScalar(bytes){const a=read32b(bytes);if(a>=CURVE.n)throw new Error("Expected value mod n");return a}function readSecret(bytes){const a=readScalar(bytes);if(a===0n)throw new Error("Expected non-zero");return a}function secp256k1Right(x){const x2=x*x%CURVE.P;const x3=x2*x%CURVE.P;return(x3+CURVE.b)%CURVE.P}function jacobiSymbol(a){if(a===_0n)return 0;let p=CURVE.P;let sign=1;for(;;){let and3;for(and3=a&_3n;and3===_0n;a>>=_2n,and3=a&_3n);if(and3===_2n){a>>=_1n;const pand7=p&_7n;if(pand7===_3n||pand7===_5n)sign=-sign}if(a===_1n)break;if((_3n&a)===_3n&&(_3n&p)===_3n)sign=-sign;[a,p]=[p%a,a]}return sign>0?1:-1}function isPoint(p){if(p.length<33)return false;const t=p[0];if(p.length===33){return(t===2||t===3)&&isXOnlyPoint(p.subarray(1))}if(t!==4||p.length!==65)return false;const x=read32b(p.subarray(1,33));if(x===_0n)return false;if(x>=CURVE.P)return false;const y=read32b(p.subarray(33));if(y===_0n)return false;if(y>=CURVE.P)return false;const left=y*y%CURVE.P;const right=secp256k1Right(x);return left===right}function isXOnlyPoint(p){if(p.length!==32)return false;const x=read32b(p);if(x===_0n)return false;if(x>=CURVE.P)return false;const y2=secp256k1Right(x);return jacobiSymbol(y2)===1}function scalarAdd(a,b){const aN=readScalar(a);const bN=readScalar(b);const sum=(aN+bN)%CURVE.n;return write32b(sum)}function scalarMultiply(a,b){const aN=readScalar(a);const bN=readScalar(b);const product=aN*bN%CURVE.n;return write32b(product)}function scalarNegate(a){const aN=readScalar(a);const negated=aN===_0n?_0n:CURVE.n-aN;return write32b(negated)}function scalarMod(a){const aN=read32b(a);const remainder=aN%CURVE.n;return write32b(remainder)}function isScalar(t){try{readScalar(t);return true}catch{return false}}function isSecret(s){try{readSecret(s);return true}catch{return false}}function pointNegate(p){const even=hasEvenY(p);const negated=Uint8Array.from(p);if(p.length===33){negated[0]=even?3:2}else if(p.length===65){const y=read32b(p.subarray(33));if(y>=CURVE.P)throw new Error("Expected Y coordinate mod P");const minusY=y===_0n?_0n:CURVE.P-y;write32b(minusY,negated.subarray(33))}return negated}function pointX(p){if(p.length===32)return p;hasEvenY(p);return p.slice(1,33)}function hasEvenY(p){if(p.length===33){if(p[0]===2)return true;else if(p[0]===3)return false;else throw new Error("Wrong first byte to be a point")}if(p.length===65){if(p[0]!==4)throw new Error("Wrong first byte to be point");return p[64]%2===0}throw new Error("Wrong length to be a point")}function pointMultiplyUnsafe(p,a,compress){try{const product=secp256k1.ProjectivePoint.fromHex(p).multiplyAndAddUnsafe(secp256k1.ProjectivePoint.ZERO,BigInt(`0x${Buffer.from(a).toString("hex")}`),BigInt(1));if(!product)return null;return product.toRawBytes(compress)}catch{return null}}function pointMultiplyAndAddUnsafe(p1,a,p2,compress){try{const p2p=secp256k1.ProjectivePoint.fromHex(p2);const p=secp256k1.ProjectivePoint.fromHex(p1).multiplyAndAddUnsafe(p2p,BigInt(`0x${Buffer.from(a).toString("hex")}`),BigInt(1));if(!p)return null;return p.toRawBytes(compress)}catch{return null}}function pointAdd(a,b,compress){try{return secp256k1.ProjectivePoint.fromHex(a).add(secp256k1.ProjectivePoint.fromHex(b)).toRawBytes(compress)}catch{return null}}function pointAddTweak(p,tweak,compress){try{const P=secp256k1.ProjectivePoint.fromHex(p);const t=readSecret(tweak);const Q=secp256k1.ProjectivePoint.BASE.multiplyAndAddUnsafe(P,t,1n);if(!Q)throw new Error("Tweaked point at infinity");return Q.toRawBytes(compress)}catch{return null}}function pointCompress(p,compress=true){return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(compress)}function liftX(p){try{return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(false)}catch{return null}}function getPublicKey(s,compress){try{return secp256k1.getPublicKey(s,compress)}catch{return null}}function taggedHash(tag,...messages){return schnorr.utils.taggedHash(tag,...messages)}function sha256Hash(...messages){const h=sha256$1.create();for(const message of messages)h.update(message);return h.digest()}const musigCrypto={read32b:read32b,write32b:write32b,readScalar:readScalar,readSecret:readSecret,secp256k1Right:secp256k1Right,jacobiSymbol:jacobiSymbol,isPoint:isPoint,isXOnlyPoint:isXOnlyPoint,scalarAdd:scalarAdd,scalarMultiply:scalarMultiply,scalarNegate:scalarNegate,scalarMod:scalarMod,isScalar:isScalar,isSecret:isSecret,pointNegate:pointNegate,pointX:pointX,hasEvenY:hasEvenY,pointMultiplyUnsafe:pointMultiplyUnsafe,pointMultiplyAndAddUnsafe:pointMultiplyAndAddUnsafe,pointAdd:pointAdd,pointAddTweak:pointAddTweak,pointCompress:pointCompress,liftX:liftX,getPublicKey:getPublicKey,taggedHash:taggedHash,sha256:sha256Hash};function lock(){computeHmac.lock();keccak256.lock();pbkdf2.lock();randomBytes.lock();ripemd160.lock();scrypt.lock();scryptSync.lock();sha256.lock();sha512.lock();randomBytes.lock()}function formatMixedCaseChecksumAddress(address){address=address.toLowerCase();const chars=address.substring(2).split("");const expanded=new Uint8Array(40);for(let i=0;i<40;i++){expanded[i]=chars[i].charCodeAt(0)}const hashed=getBytes(keccak256(expanded));for(let i=0;i<40;i+=2){if(hashed[i>>1]>>4>=8){chars[i]=chars[i].toUpperCase()}if((hashed[i>>1]&15)>=8){chars[i+1]=chars[i+1].toUpperCase()}}return"0x"+chars.join("")}function getAddress(address){assertArgument(typeof address==="string","invalid address","address",address);if(address.match(/^(0x)?[0-9a-fA-F]{40}$/)){if(!address.startsWith("0x")){address="0x"+address}const result=formatMixedCaseChecksumAddress(address);assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||result===address,"invalid address checksum","address",address);return result}assertArgument(false,"invalid address string format","address",address)}function getContractAddress(from,nonce,data){const nonceBytes=zeroPadValue(toBeHex(toBigInt(nonce)),8);return getAddress(dataSlice(keccak256(concat([getAddress(from),nonceBytes,stripZerosLeft(data)])),12))}function computeAddress(key){let pubkey;if(typeof key==="string"){pubkey=SigningKey.computePublicKey(key,false)}else{pubkey=key.publicKey}return getAddress(keccak256("0x"+pubkey.substring(4)).substring(26))}function recoverAddress(digest,signature){return computeAddress(SigningKey.recoverPublicKey(digest,signature))}function isAddressable(value){return value&&typeof value.getAddress==="function"}function isAddress(value){try{getAddress(value);return true}catch(error){}return false}async function checkAddress(target,promise){const result=await promise;if(result==null||result==="0x0000000000000000000000000000000000000000"){assertArgument(false,"invalid AddressLike value; did not resolve to a value address","target",target)}return result}function resolveAddress(target){if(typeof target==="string"){if(target.match(/^0x[0-9a-f]{40}$/i)){return target}}else if(isAddressable(target)){return checkAddress(target,target.getAddress())}else if(target&&typeof target.then==="function"){return checkAddress(target,target)}assertArgument(false,"unsupported addressable value","target",target)}function validateAddress(address){assertArgument(typeof address==="string","address must be string","address",address);assertArgument(Boolean(address.match(/^(0x)?[0-9a-fA-F]{40}$/)),"invalid address string format","address",address);assertArgument(formatMixedCaseChecksumAddress(address)===address,"invalid address checksum","address",address)}function isQiAddress(address){const secondByte=address.substring(4,6);const binaryString=parseInt(secondByte,16).toString(2).padStart(8,"0");const isUTXO=binaryString[0]==="1";return isUTXO}function isQuaiAddress(address){return!isQiAddress(address)}function getZoneForAddress(address){try{return toZone(address.slice(0,4))}catch(error){return null}}function getAddressDetails(address){const isQiLedger=(parseInt(address.substring(4,5),16)&1)===Ledger.Qi;return{zone:toZone(address.substring(0,4)),ledger:isQiLedger?Ledger.Qi:Ledger.Quai}}function getTxType(from,to){if(from===null||to===null)return 0;const senderAddressIsQi=isQiAddress(from);const recipientAddressIsQi=isQiAddress(to);switch(true){case senderAddressIsQi&&recipientAddressIsQi:return 2;case senderAddressIsQi&&!recipientAddressIsQi:return 1;default:return 0}}function getNodeLocationFromZone(zone){const zoneId=zone.slice(2);if(zoneId.length>2){throw new Error(`Invalid zone: ${zone}`)}else if(zoneId.length===0){return[]}return zoneId.split("").map(Number)}function getZoneFromNodeLocation(location){if(location.length>2){throw new Error("Invalid location")}return toZone(`0x${location.join("")}`)}const WordSize=32;const Padding=new Uint8Array(WordSize);const passProperties$1=["then"];const _guard$5={};function throwError(name,error){const wrapped=new Error(`deferred error during ABI decoding triggered accessing ${name}`);wrapped.error=error;throw wrapped}class Result extends Array{#names;constructor(...args){const guard=args[0];let items=args[1];let names=(args[2]||[]).slice();let wrap=true;if(guard!==_guard$5){items=args;names=[];wrap=false}super(items.length);items.forEach((item,index)=>{this[index]=item});const nameCounts=names.reduce((accum,name)=>{if(typeof name==="string"){accum.set(name,(accum.get(name)||0)+1)}return accum},new Map);this.#names=Object.freeze(items.map((item,index)=>{const name=names[index];if(name!=null&&nameCounts.get(name)===1){return name}return null}));if(!wrap){return}Object.freeze(this);return new Proxy(this,{get:(target,prop,receiver)=>{if(typeof prop==="string"){if(prop.match(/^[0-9]+$/)){const index=getNumber(prop,"%index");if(index<0||index>=this.length){throw new RangeError("out of result range")}const item=target[index];if(item instanceof Error){throwError(`index ${index}`,item)}return item}if(passProperties$1.indexOf(prop)>=0){return Reflect.get(target,prop,receiver)}const value=target[prop];if(value instanceof Function){return function(...args){return value.apply(this===receiver?target:this,args)}}else if(!(prop in target)){return target.getValue.apply(this===receiver?target:this,[prop])}}return Reflect.get(target,prop,receiver)}})}toArray(){const result=[];this.forEach((item,index)=>{if(item instanceof Error){throwError(`index ${index}`,item)}result.push(item)});return result}toObject(){return this.#names.reduce((accum,name,index)=>{assert(name!=null,"value at index ${ index } unnamed","UNSUPPORTED_OPERATION",{operation:"toObject()"});if(!(name in accum)){accum[name]=this.getValue(name)}return accum},{})}slice(start,end){if(start==null){start=0}if(start<0){start+=this.length;if(start<0){start=0}}if(end==null){end=this.length}if(end<0){end+=this.length;if(end<0){end=0}}if(end>this.length){end=this.length}const result=[],names=[];for(let i=start;i{this.#data[offset]=getValue$1(value)}}}class Reader{allowLoose;#data;#offset;#bytesRead;#parent;#maxInflation;constructor(data,allowLoose,maxInflation){defineProperties(this,{allowLoose:!!allowLoose});this.#data=getBytesCopy(data);this.#bytesRead=0;this.#parent=null;this.#maxInflation=maxInflation!=null?maxInflation:1024;this.#offset=0}get data(){return hexlify(this.#data)}get dataLength(){return this.#data.length}get consumed(){return this.#offset}get bytes(){return new Uint8Array(this.#data)}#incrementBytesRead(count){if(this.#parent){return this.#parent.#incrementBytesRead(count)}this.#bytesRead+=count;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",{buffer:getBytesCopy(this.#data),offset:this.#offset,length:count,info:{bytesRead:this.#bytesRead,dataLength:this.dataLength}})}#peekBytes(offset,length,loose){let alignedLength=Math.ceil(length/WordSize)*WordSize;if(this.#offset+alignedLength>this.#data.length){if(this.allowLoose&&loose&&this.#offset+length<=this.#data.length){alignedLength=length}else{assert(false,"data out-of-bounds","BUFFER_OVERRUN",{buffer:getBytesCopy(this.#data),length:this.#data.length,offset:this.#offset+alignedLength})}}return this.#data.slice(this.#offset,this.#offset+alignedLength)}subReader(offset){const reader=new Reader(this.#data.slice(this.#offset+offset),this.allowLoose,this.#maxInflation);reader.#parent=this;return reader}readBytes(length,loose){const bytes=this.#peekBytes(0,length,!!loose);this.#incrementBytesRead(length);this.#offset+=bytes.length;return bytes.slice(0,length)}readValue(){return toBigInt(this.readBytes(WordSize))}readIndex(){return toNumber(this.readBytes(WordSize))}}function getCreateAddress(tx){const from=getAddress(tx.from);const nonce=getBigInt(tx.nonce,"tx.nonce");const nonceBytes=bigEndianNonce(nonce);const fromBytes=getBytes(from);const codeBytes=tx.data?getBytes(tx.data):new Uint8Array;const concatenated=new Uint8Array([...fromBytes,...nonceBytes,...codeBytes]);const hash=keccak256(concatenated);return getAddress(dataSlice(hash,12))}function getCreate2Address(_from,_salt,_initCodeHash){const from=getAddress(_from);const salt=getBytes(_salt,"salt");const initCodeHash=getBytes(_initCodeHash,"initCodeHash");assertArgument(salt.length===32,"salt must be 32 bytes","salt",_salt);assertArgument(initCodeHash.length===32,"initCodeHash must be 32 bytes","initCodeHash",_initCodeHash);return getAddress(dataSlice(keccak256(concat(["0xff",from,salt,initCodeHash])),12))}function bigEndianNonce(nonce){const buffer=new ArrayBuffer(8);const view=new DataView(buffer);view.setBigUint64(0,nonce,false);return new Uint8Array(buffer)}const _guard$4={};function n(value,width){let signed=false;if(width<0){signed=true;width*=-1}return new Typed(_guard$4,`${signed?"":"u"}int${width}`,value,{signed:signed,width:width})}function b(value,size){return new Typed(_guard$4,`bytes${size?size:""}`,value,{size:size})}const _typedSymbol=Symbol.for("_quais_typed");class Typed{type;value;#options;_typedSymbol;constructor(guard,type,value,options){if(options==null){options=null}assertPrivate(_guard$4,guard,"Typed");defineProperties(this,{_typedSymbol:_typedSymbol,type:type,value:value});this.#options=options;this.format()}format(){if(this.type==="array"){throw new Error("")}else if(this.type==="dynamicArray"){throw new Error("")}else if(this.type==="tuple"){return`tuple(${this.value.map(v=>v.format()).join(",")})`}return this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple"){throw TypeError("not a tuple")}return this.#options}get arrayLength(){if(this.type!=="array"){throw TypeError("not an array")}if(this.#options===true){return-1}if(this.#options===false){return this.value.length}return null}static from(type,value){return new Typed(_guard$4,type,value)}static uint8(v){return n(v,8)}static uint16(v){return n(v,16)}static uint24(v){return n(v,24)}static uint32(v){return n(v,32)}static uint40(v){return n(v,40)}static uint48(v){return n(v,48)}static uint56(v){return n(v,56)}static uint64(v){return n(v,64)}static uint72(v){return n(v,72)}static uint80(v){return n(v,80)}static uint88(v){return n(v,88)}static uint96(v){return n(v,96)}static uint104(v){return n(v,104)}static uint112(v){return n(v,112)}static uint120(v){return n(v,120)}static uint128(v){return n(v,128)}static uint136(v){return n(v,136)}static uint144(v){return n(v,144)}static uint152(v){return n(v,152)}static uint160(v){return n(v,160)}static uint168(v){return n(v,168)}static uint176(v){return n(v,176)}static uint184(v){return n(v,184)}static uint192(v){return n(v,192)}static uint200(v){return n(v,200)}static uint208(v){return n(v,208)}static uint216(v){return n(v,216)}static uint224(v){return n(v,224)}static uint232(v){return n(v,232)}static uint240(v){return n(v,240)}static uint248(v){return n(v,248)}static uint256(v){return n(v,256)}static uint(v){return n(v,256)}static int8(v){return n(v,-8)}static int16(v){return n(v,-16)}static int24(v){return n(v,-24)}static int32(v){return n(v,-32)}static int40(v){return n(v,-40)}static int48(v){return n(v,-48)}static int56(v){return n(v,-56)}static int64(v){return n(v,-64)}static int72(v){return n(v,-72)}static int80(v){return n(v,-80)}static int88(v){return n(v,-88)}static int96(v){return n(v,-96)}static int104(v){return n(v,-104)}static int112(v){return n(v,-112)}static int120(v){return n(v,-120)}static int128(v){return n(v,-128)}static int136(v){return n(v,-136)}static int144(v){return n(v,-144)}static int152(v){return n(v,-152)}static int160(v){return n(v,-160)}static int168(v){return n(v,-168)}static int176(v){return n(v,-176)}static int184(v){return n(v,-184)}static int192(v){return n(v,-192)}static int200(v){return n(v,-200)}static int208(v){return n(v,-208)}static int216(v){return n(v,-216)}static int224(v){return n(v,-224)}static int232(v){return n(v,-232)}static int240(v){return n(v,-240)}static int248(v){return n(v,-248)}static int256(v){return n(v,-256)}static int(v){return n(v,-256)}static bytes1(v){return b(v,1)}static bytes2(v){return b(v,2)}static bytes3(v){return b(v,3)}static bytes4(v){return b(v,4)}static bytes5(v){return b(v,5)}static bytes6(v){return b(v,6)}static bytes7(v){return b(v,7)}static bytes8(v){return b(v,8)}static bytes9(v){return b(v,9)}static bytes10(v){return b(v,10)}static bytes11(v){return b(v,11)}static bytes12(v){return b(v,12)}static bytes13(v){return b(v,13)}static bytes14(v){return b(v,14)}static bytes15(v){return b(v,15)}static bytes16(v){return b(v,16)}static bytes17(v){return b(v,17)}static bytes18(v){return b(v,18)}static bytes19(v){return b(v,19)}static bytes20(v){return b(v,20)}static bytes21(v){return b(v,21)}static bytes22(v){return b(v,22)}static bytes23(v){return b(v,23)}static bytes24(v){return b(v,24)}static bytes25(v){return b(v,25)}static bytes26(v){return b(v,26)}static bytes27(v){return b(v,27)}static bytes28(v){return b(v,28)}static bytes29(v){return b(v,29)}static bytes30(v){return b(v,30)}static bytes31(v){return b(v,31)}static bytes32(v){return b(v,32)}static address(v){return new Typed(_guard$4,"address",v)}static bool(v){return new Typed(_guard$4,"bool",!!v)}static bytes(v){return new Typed(_guard$4,"bytes",v)}static string(v){return new Typed(_guard$4,"string",v)}static array(v,dynamic){throw new Error("not implemented yet")}static tuple(v,name){throw new Error("not implemented yet")}static overrides(v){return new Typed(_guard$4,"overrides",Object.assign({},v))}static isTyped(value){return value&&typeof value==="object"&&"_typedSymbol"in value&&value._typedSymbol===_typedSymbol}static dereference(value,type){if(Typed.isTyped(value)){if(value.type!==type){throw new Error(`invalid type: expected ${type}, got ${value.type}`)}return value.value}return value}}class AddressCoder extends Coder{constructor(localName){super("address","address",localName,false)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(writer,_value){let value=Typed.dereference(_value,"string");try{value=getAddress(value)}catch(error){return this._throwError(error.message,_value)}return writer.writeValue(value)}decode(reader){return getAddress(toBeHex(reader.readValue(),20))}}class AnonymousCoder extends Coder{coder;constructor(coder){super(coder.name,coder.type,"_",coder.dynamic);this.coder=coder}defaultValue(){return this.coder.defaultValue()}encode(writer,value){return this.coder.encode(writer,value)}decode(reader){return this.coder.decode(reader)}}function pack(writer,coders,values){let arrayValues=[];if(Array.isArray(values)){arrayValues=values}else if(values&&typeof values==="object"){let unique={};arrayValues=coders.map(coder=>{const name=coder.localName;assert(name,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:coder},value:values});assert(!unique[name],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:coder},value:values});unique[name]=true;return values[name]})}else{assertArgument(false,"invalid tuple value","tuple",values)}assertArgument(coders.length===arrayValues.length,"types/value length mismatch","tuple",values);let staticWriter=new Writer;let dynamicWriter=new Writer;let updateFuncs=[];coders.forEach((coder,index)=>{let value=arrayValues[index];if(coder.dynamic){let dynamicOffset=dynamicWriter.length;coder.encode(dynamicWriter,value);let updateFunc=staticWriter.writeUpdatableValue();updateFuncs.push(baseOffset=>{updateFunc(baseOffset+dynamicOffset)})}else{coder.encode(staticWriter,value)}});updateFuncs.forEach(func=>{func(staticWriter.length)});let length=writer.appendWriter(staticWriter);length+=writer.appendWriter(dynamicWriter);return length}function unpack(reader,coders){let values=[];let keys=[];let baseReader=reader.subReader(0);coders.forEach(coder=>{let value=null;if(coder.dynamic){let offset=reader.readIndex();let offsetReader=baseReader.subReader(offset);try{value=coder.decode(offsetReader)}catch(error){if(isError(error,"BUFFER_OVERRUN")){throw error}value=error;value.baseType=coder.name;value.name=coder.localName;value.type=coder.type}}else{try{value=coder.decode(reader)}catch(error){if(isError(error,"BUFFER_OVERRUN")){throw error}value=error;value.baseType=coder.name;value.name=coder.localName;value.type=coder.type}}if(value==undefined){throw new Error("investigate")}values.push(value);keys.push(coder.localName||null)});return Result.fromItems(values,keys)}class ArrayCoder extends Coder{coder;length;constructor(coder,length,localName){const type=coder.type+"["+(length>=0?length:"")+"]";const dynamic=length===-1||coder.dynamic;super("array",type,localName,dynamic);defineProperties(this,{coder:coder,length:length})}defaultValue(){const defaultChild=this.coder.defaultValue();const result=[];for(let i=0;ibounds||value<-(bounds+BN_1$1)){this._throwError("value out-of-bounds",_value)}value=toTwos(value,8*WordSize)}else if(valuemask(maxUintValue,this.size*8)){this._throwError("value out-of-bounds",_value)}return writer.writeValue(value)}decode(reader){let value=mask(reader.readValue(),this.size*8);if(this.signed){value=fromTwos(value,this.size*8)}return value}}class StringCoder extends DynamicBytesCoder{constructor(localName){super("string",localName)}defaultValue(){return""}encode(writer,_value){return super.encode(writer,toUtf8Bytes(Typed.dereference(_value,"string")))}decode(reader){return toUtf8String(super.decode(reader))}}class TupleCoder extends Coder{coders;constructor(coders,localName){let dynamic=false;const types=[];coders.forEach(coder=>{if(coder.dynamic){dynamic=true}types.push(coder.type)});const type="tuple("+types.join(",")+")";super("tuple",type,localName,dynamic);defineProperties(this,{coders:Object.freeze(coders.slice())})}defaultValue(){const values=[];this.coders.forEach(coder=>{values.push(coder.defaultValue())});const uniqueNames=this.coders.reduce((accum,coder)=>{const name=coder.localName;if(name){if(!accum[name]){accum[name]=0}accum[name]++}return accum},{});this.coders.forEach((coder,index)=>{let name=coder.localName;if(!name||uniqueNames[name]!==1){return}if(name==="length"){name="_length"}if(values[name]!=null){return}values[name]=values[index]});return Object.freeze(values)}encode(writer,_value){const value=Typed.dereference(_value,"tuple");return pack(writer,this.coders,value)}decode(reader){return unpack(reader,this.coders)}}function id(value){return keccak256(toUtf8Bytes(value))}function hashMessage(message){if(typeof message==="string"){message=toUtf8Bytes(message)}return keccak256(concat([toUtf8Bytes(MessagePrefix),toUtf8Bytes(String(message.length)),message]))}function verifyMessage(message,sig){const digest=hashMessage(message);return recoverAddress(digest,sig)}function ethHashMessage(message){if(typeof message==="string"){message=toUtf8Bytes(message)}return keccak256(concat([toUtf8Bytes(EthMessagePrefix),toUtf8Bytes(String(message.length)),message]))}function ethVerifyMessage(message,sig){const digest=ethHashMessage(message);return recoverAddress(digest,sig)}const regexBytes=new RegExp("^bytes([0-9]+)$");const regexNumber=new RegExp("^(u?int)([0-9]*)$");const regexArray=new RegExp("^(.*)\\[([0-9]*)\\]$");function _pack(type,value,isArray){switch(type){case"address":if(isArray){return getBytes(zeroPadValue(value,32))}return getBytes(getAddress(value));case"string":return toUtf8Bytes(value);case"bytes":return getBytes(value);case"bool":value=value?"0x01":"0x00";if(isArray){return getBytes(zeroPadValue(value,32))}return getBytes(value)}let match=type.match(regexNumber);if(match){const signed=match[1]==="int";let size=parseInt(match[2]||"256");assertArgument((!match[2]||match[2]===String(size))&&size%8===0&&size!==0&&size<=256,"invalid number type","type",type);if(isArray){size=256}if(signed){value=toTwos(value,size)}return getBytes(zeroPadValue(toBeArray(value),size/8))}match=type.match(regexBytes);if(match){const size=parseInt(match[1]);assertArgument(String(size)===match[1]&&size!==0&&size<=32,"invalid bytes type","type",type);assertArgument(dataLength(value)===size,`invalid value for ${type}`,"value",value);if(isArray){return getBytes(zeroPadBytes(value,32))}return value}match=type.match(regexArray);if(match&&Array.isArray(value)){const baseType=match[1];const count=parseInt(match[2]||String(value.length));assertArgument(count===value.length,`invalid array length for ${type}`,"value",value);const result=[];value.forEach(function(value){result.push(_pack(baseType,value,true))});return getBytes(concat(result))}assertArgument(false,"invalid type","type",type)}function solidityPacked(types,values){assertArgument(types.length===values.length,"wrong number of values; expected ${ types.length }","values",values);const tight=[];types.forEach(function(type,index){tight.push(_pack(type,values[index]))});return hexlify(concat(tight))}function solidityPackedKeccak256(types,values){return keccak256(solidityPacked(types,values))}function solidityPackedSha256(types,values){return sha256(solidityPacked(types,values))}const padding=new Uint8Array(32);padding.fill(0);const BN__1=BigInt(-1);const BN_0$3=BigInt(0);const BN_1=BigInt(1);const BN_MAX_UINT256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function hexPadRight(value){const bytes=getBytes(value);const padOffset=bytes.length%32;if(padOffset){return concat([bytes,padding.slice(padOffset)])}return hexlify(bytes)}const hexTrue=toBeHex(BN_1,32);const hexFalse=toBeHex(BN_0$3,32);const domainFieldTypes={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"};const domainFieldNames=["name","version","chainId","verifyingContract","salt"];function checkString(key){return function(value){assertArgument(typeof value==="string",`invalid domain value for ${JSON.stringify(key)}`,`domain.${key}`,value);return value}}const domainChecks={name:checkString("name"),version:checkString("version"),chainId:function(_value){const value=getBigInt(_value,"domain.chainId");assertArgument(value>=0,"invalid chain ID","domain.chainId",_value);if(Number.isSafeInteger(value)){return Number(value)}return toQuantity(value)},verifyingContract:function(value){try{return getAddress(value)}catch(error){}assertArgument(false,`invalid domain value "verifyingContract"`,"domain.verifyingContract",value)},salt:function(value){const bytes=getBytes(value,"domain.salt");assertArgument(bytes.length===32,`invalid domain value "salt"`,"domain.salt",value);return hexlify(bytes)}};function getBaseEncoder(type){{const match=type.match(/^(u?)int(\d*)$/);if(match){const signed=match[1]==="";const width=parseInt(match[2]||"256");assertArgument(width%8===0&&width!==0&&width<=256&&(match[2]==null||match[2]===String(width)),"invalid numeric width","type",type);const boundsUpper=mask(BN_MAX_UINT256,signed?width-1:width);const boundsLower=signed?(boundsUpper+BN_1)*BN__1:BN_0$3;return function(_value){const value=getBigInt(_value,"value");assertArgument(value>=boundsLower&&value<=boundsUpper,`value out-of-bounds for ${type}`,"value",value);return toBeHex(signed?toTwos(value,256):value,32)}}}{const match=type.match(/^bytes(\d+)$/);if(match){const width=parseInt(match[1]);assertArgument(width!==0&&width<=32&&match[1]===String(width),"invalid bytes width","type",type);return function(value){const bytes=getBytes(value);assertArgument(bytes.length===width,`invalid length for ${type}`,"value",value);return hexPadRight(value)}}}switch(type){case"address":return function(value){return zeroPadValue(getAddress(value),32)};case"bool":return function(value){return!value?hexFalse:hexTrue};case"bytes":return function(value){return keccak256(value)};case"string":return function(value){return id(value)}}return null}function encodeType(name,fields){return`${name}(${fields.map(({name,type})=>type+" "+name).join(",")})`}class TypedDataEncoder{primaryType;#types;get types(){return JSON.parse(this.#types)}#fullTypes;#encoderCache;constructor(types){this.#types=JSON.stringify(types);this.#fullTypes=new Map;this.#encoderCache=new Map;const links=new Map;const parents=new Map;const subtypes=new Map;Object.keys(types).forEach(type=>{links.set(type,new Set);parents.set(type,[]);subtypes.set(type,new Set)});for(const name in types){const uniqueNames=new Set;for(const field of types[name]){assertArgument(!uniqueNames.has(field.name),`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`,"types",types);uniqueNames.add(field.name);const baseType=field.type.match(/^([^\x5b]*)(\x5b|$)/)[1]||null;assertArgument(baseType!==name,`circular type reference to ${JSON.stringify(baseType)}`,"types",types);const encoder=getBaseEncoder(baseType);if(encoder){continue}assertArgument(parents.has(baseType),`unknown type ${JSON.stringify(baseType)}`,"types",types);parents.get(baseType).push(name);links.get(name).add(baseType)}}const primaryTypes=Array.from(parents.keys()).filter(n=>parents.get(n).length===0);assertArgument(primaryTypes.length!==0,"missing primary type","types",types);assertArgument(primaryTypes.length===1,`ambiguous primary types or unused types: ${primaryTypes.map(t=>JSON.stringify(t)).join(", ")}`,"types",types);defineProperties(this,{primaryType:primaryTypes[0]});function checkCircular(type,found){assertArgument(!found.has(type),`circular type reference to ${JSON.stringify(type)}`,"types",types);found.add(type);for(const child of links.get(type)){if(!parents.has(child)){continue}checkCircular(child,found);for(const subtype of found){subtypes.get(subtype).add(child)}}found.delete(type)}checkCircular(this.primaryType,new Set);for(const[name,set]of subtypes){const st=Array.from(set);st.sort();this.#fullTypes.set(name,encodeType(name,types[name])+st.map(t=>encodeType(t,types[t])).join(""))}}getEncoder(type){let encoder=this.#encoderCache.get(type);if(!encoder){encoder=this.#getEncoder(type);this.#encoderCache.set(type,encoder)}return encoder}#getEncoder(type){{const encoder=getBaseEncoder(type);if(encoder){return encoder}}const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){const subtype=match[1];const subEncoder=this.getEncoder(subtype);return value=>{assertArgument(!match[3]||parseInt(match[3])===value.length,`array length mismatch; expected length ${parseInt(match[3])}`,"value",value);let result=value.map(subEncoder);if(this.#fullTypes.has(subtype)){result=result.map(keccak256)}return keccak256(concat(result))}}const fields=this.types[type];if(fields){const encodedType=id(this.#fullTypes.get(type));return value=>{const values=fields.map(({name,type})=>{const result=this.getEncoder(type)(value[name]);if(this.#fullTypes.has(type)){return keccak256(result)}return result});values.unshift(encodedType);return concat(values)}}assertArgument(false,`unknown type: ${type}`,"type",type)}encodeType(name){const result=this.#fullTypes.get(name);assertArgument(result,`unknown type: ${JSON.stringify(name)}`,"name",name);return result}encodeData(type,value){return this.getEncoder(type)(value)}hashStruct(name,value){return keccak256(this.encodeData(name,value))}encode(value){return this.encodeData(this.primaryType,value)}hash(value){return this.hashStruct(this.primaryType,value)}_visit(type,value,callback){{const encoder=getBaseEncoder(type);if(encoder){return callback(type,value)}}const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){assertArgument(!match[3]||parseInt(match[3])===value.length,`array length mismatch; expected length ${parseInt(match[3])}`,"value",value);return value.map(v=>this._visit(match[1],v,callback))}const fields=this.types[type];if(fields){return fields.reduce((accum,{name,type})=>{accum[name]=this._visit(type,value[name],callback);return accum},{})}assertArgument(false,`unknown type: ${type}`,"type",type)}visit(value,callback){return this._visit(this.primaryType,value,callback)}static from(types){return new TypedDataEncoder(types)}static getPrimaryType(types){return TypedDataEncoder.from(types).primaryType}static hashStruct(name,types,value){return TypedDataEncoder.from(types).hashStruct(name,value)}static hashDomain(domain){const domainFields=[];for(const name in domain){if(domain[name]==null){continue}const type=domainFieldTypes[name];assertArgument(type,`invalid typed-data domain key: ${JSON.stringify(name)}`,"domain",domain);domainFields.push({name:name,type:type})}domainFields.sort((a,b)=>{return domainFieldNames.indexOf(a.name)-domainFieldNames.indexOf(b.name)});return TypedDataEncoder.hashStruct("EIP712Domain",{EIP712Domain:domainFields},domain)}static encode(domain,types,value){return concat(["0x1901",TypedDataEncoder.hashDomain(domain),TypedDataEncoder.from(types).hash(value)])}static hash(domain,types,value){return keccak256(TypedDataEncoder.encode(domain,types,value))}static getPayload(domain,types,value){TypedDataEncoder.hashDomain(domain);const domainValues={};const domainTypes=[];domainFieldNames.forEach(name=>{const value=domain[name];if(value==null){return}domainValues[name]=domainChecks[name](value);domainTypes.push({name:name,type:domainFieldTypes[name]})});const encoder=TypedDataEncoder.from(types);const typesWithDomain=Object.assign({},types);assertArgument(typesWithDomain.EIP712Domain==null,"types must not contain EIP712Domain type","types.EIP712Domain",types);typesWithDomain.EIP712Domain=domainTypes;encoder.encode(value);return{types:typesWithDomain,domain:domainValues,primaryType:encoder.primaryType,message:encoder.visit(value,(type,value)=>{if(type.match(/^bytes(\d*)/)){return hexlify(getBytes(value))}if(type.match(/^u?int/)){return getBigInt(value).toString()}switch(type){case"address":return value.toLowerCase();case"bool":return!!value;case"string":assertArgument(typeof value==="string","invalid string","value",value);return value}assertArgument(false,"unsupported type","type",type)})}}}function verifyTypedData(domain,types,value,signature){return recoverAddress(TypedDataEncoder.hash(domain,types,value),signature)}function setify(items){const result=new Set;items.forEach(k=>result.add(k));return Object.freeze(result)}const _kwVisibDeploy="external public payable";const KwVisibDeploy=setify(_kwVisibDeploy.split(" "));const _kwVisib="constant external internal payable private public pure view";const KwVisib=setify(_kwVisib.split(" "));const _kwTypes="constructor error event fallback function receive struct";const KwTypes=setify(_kwTypes.split(" "));const _kwModifiers="calldata memory storage payable indexed";const KwModifiers=setify(_kwModifiers.split(" "));const _kwOther="tuple returns";const _keywords=[_kwTypes,_kwModifiers,_kwOther,_kwVisib].join(" ");const Keywords=setify(_keywords.split(" "));const SimpleTokens={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"};const regexWhitespacePrefix=new RegExp("^(\\s*)");const regexNumberPrefix=new RegExp("^([0-9]+)");const regexIdPrefix=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)");const regexId=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$");const regexType=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class TokenString{#offset;#tokens;get offset(){return this.#offset}get length(){return this.#tokens.length-this.#offset}constructor(tokens){this.#offset=0;this.#tokens=tokens.slice()}clone(){return new TokenString(this.#tokens)}reset(){this.#offset=0}#subTokenString(from=0,to=0){return new TokenString(this.#tokens.slice(from,to).map(t=>{return Object.freeze(Object.assign({},t,{match:t.match-from,linkBack:t.linkBack-from,linkNext:t.linkNext-from}))}))}popKeyword(allowed){const top=this.peek();if(top.type!=="KEYWORD"||!allowed.has(top.text)){throw new Error(`expected keyword ${top.text}`)}return this.pop().text}popType(type){if(this.peek().type!==type){throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`)}return this.pop().text}popParen(){const top=this.peek();if(top.type!=="OPEN_PAREN"){throw new Error("bad start")}const result=this.#subTokenString(this.#offset+1,top.match+1);this.#offset=top.match+1;return result}popParams(){const top=this.peek();if(top.type!=="OPEN_PAREN"){throw new Error("bad start")}const result=[];while(this.#offset=this.#tokens.length){throw new Error("out-of-bounds")}return this.#tokens[this.#offset]}peekKeyword(allowed){const top=this.peekType("KEYWORD");return top!=null&&allowed.has(top)?top:null}peekType(type){if(this.length===0){return null}const top=this.peek();return top.type===type?top.text:null}pop(){const result=this.peek();this.#offset++;return result}toString(){const tokens=[];for(let i=this.#offset;i`}}function lex(text){const tokens=[];const throwError=message=>{const token=offset0&&tokens[tokens.length-1].type==="NUMBER"){const value=tokens.pop().text;suffix=value+suffix;tokens[tokens.length-1].value=getNumber(value)}if(tokens.length===0||tokens[tokens.length-1].type!=="BRACKET"){throw new Error("missing opening bracket")}tokens[tokens.length-1].text+=suffix}continue}match=cur.match(regexIdPrefix);if(match){token.text=match[1];offset+=token.text.length;if(Keywords.has(token.text)){token.type="KEYWORD";continue}if(token.text.match(regexType)){token.type="TYPE";continue}token.type="ID";continue}match=cur.match(regexNumberPrefix);if(match){token.text=match[1];token.type="NUMBER";offset+=token.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`)}return new TokenString(tokens.map(t=>Object.freeze(t)))}function allowSingle(set,allowed){const included=[];for(const key in allowed.keys()){if(set.has(key)){included.push(key)}}if(included.length>1){throw new Error(`conflicting types: ${included.join(", ")}`)}}function consumeName(type,tokens){if(tokens.peekKeyword(KwTypes)){const keyword=tokens.pop().text;if(keyword!==type){throw new Error(`expected ${type}, got ${keyword}`)}}return tokens.popType("ID")}function consumeKeywords(tokens,allowed){const keywords=new Set;while(true){const keyword=tokens.peekType("KEYWORD");if(keyword==null||allowed&&!allowed.has(keyword)){break}tokens.pop();if(keywords.has(keyword)){throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`)}keywords.add(keyword)}return Object.freeze(keywords)}function consumeMutability(tokens){const modifiers=consumeKeywords(tokens,KwVisib);allowSingle(modifiers,setify("constant payable nonpayable".split(" ")));allowSingle(modifiers,setify("pure view payable nonpayable".split(" ")));if(modifiers.has("view")){return"view"}if(modifiers.has("pure")){return"pure"}if(modifiers.has("payable")){return"payable"}if(modifiers.has("nonpayable")){return"nonpayable"}if(modifiers.has("constant")){return"view"}return"nonpayable"}function consumeParams(tokens,allowIndexed){return tokens.popParams().map(t=>ParamType.from(t,allowIndexed))}function consumeGas(tokens){if(tokens.peekType("AT")){tokens.pop();if(tokens.peekType("NUMBER")){return getBigInt(tokens.pop().text)}throw new Error("invalid gas")}return null}function consumeEoi(tokens){if(tokens.length){throw new Error(`unexpected tokens: ${tokens.toString()}`)}}const regexArrayType=new RegExp(/^(.*)\[([0-9]*)\]$/);function verifyBasicType(type){const match=type.match(regexType);assertArgument(match,"invalid type","type",type);if(type==="uint"){return"uint256"}if(type==="int"){return"int256"}if(match[2]){const length=parseInt(match[2]);assertArgument(length!==0&&length<=32,"invalid bytes length","type",type)}else if(match[3]){const size=parseInt(match[3]);assertArgument(size!==0&&size<=256&&size%8===0,"invalid numeric width","type",type)}return type}const _guard$3={};const internal$1=Symbol.for("_quais_internal");const ParamTypeInternal="_ParamTypeInternal";const ErrorFragmentInternal="_ErrorInternal";const EventFragmentInternal="_EventInternal";const ConstructorFragmentInternal="_ConstructorInternal";const FallbackFragmentInternal="_FallbackInternal";const FunctionFragmentInternal="_FunctionInternal";const StructFragmentInternal="_StructInternal";class ParamType{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(guard,name,type,baseType,indexed,components,arrayLength,arrayChildren){assertPrivate(guard,_guard$3,"ParamType");Object.defineProperty(this,internal$1,{value:ParamTypeInternal});if(components){components=Object.freeze(components.slice())}if(baseType==="array"){if(arrayLength==null||arrayChildren==null){throw new Error("")}}else if(arrayLength!=null||arrayChildren!=null){throw new Error("")}if(baseType==="tuple"){if(components==null){throw new Error("")}}else if(components!=null){throw new Error("")}defineProperties(this,{name:name,type:type,baseType:baseType,indexed:indexed,components:components,arrayLength:arrayLength,arrayChildren:arrayChildren})}format(format){if(format==null){format="sighash"}if(format==="json"){const name=this.name||"";if(this.isArray()){const result=JSON.parse(this.arrayChildren.format("json"));result.name=name;result.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`;return JSON.stringify(result)}const result={type:this.baseType==="tuple"?"tuple":this.type,name:name};if(typeof this.indexed==="boolean"){result.indexed=this.indexed}if(this.isTuple()){result.components=this.components.map(c=>JSON.parse(c.format(format)))}return JSON.stringify(result)}let result="";if(this.isArray()){result+=this.arrayChildren.format(format);result+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`}else{if(this.isTuple()){result+="("+this.components.map(comp=>comp.format(format)).join(format==="full"?", ":",")+")"}else{result+=this.type}}if(format!=="sighash"){if(this.indexed===true){result+=" indexed"}if(format==="full"&&this.name){result+=" "+this.name}}return result}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(value,process){if(this.isArray()){if(!Array.isArray(value)){throw new Error("invalid array value")}if(this.arrayLength!==-1&&value.length!==this.arrayLength){throw new Error("array is wrong length")}const _this=this;return value.map(v=>_this.arrayChildren.walk(v,process))}if(this.isTuple()){if(!Array.isArray(value)){throw new Error("invalid tuple value")}if(value.length!==this.components.length){throw new Error("array is wrong length")}const _this=this;return value.map((v,i)=>_this.components[i].walk(v,process))}return process(this.type,value)}#walkAsync(promises,value,process,setValue){if(this.isArray()){if(!Array.isArray(value)){throw new Error("invalid array value")}if(this.arrayLength!==-1&&value.length!==this.arrayLength){throw new Error("array is wrong length")}const childType=this.arrayChildren;const result=value.slice();result.forEach((value,index)=>{childType.#walkAsync(promises,value,process,value=>{result[index]=value})});setValue(result);return}if(this.isTuple()){const components=this.components;let result;if(Array.isArray(value)){result=value.slice()}else{if(value==null||typeof value!=="object"){throw new Error("invalid tuple value")}result=components.map(param=>{if(!param.name){throw new Error("cannot use object value with unnamed components")}if(!(param.name in value)){throw new Error(`missing value for component ${param.name}`)}return value[param.name]})}if(result.length!==this.components.length){throw new Error("array is wrong length")}result.forEach((value,index)=>{components[index].#walkAsync(promises,value,process,value=>{result[index]=value})});setValue(result);return}const result=process(this.type,value);if(result.then){promises.push(async function(){setValue(await result)}())}else{setValue(result)}}async walkAsync(value,process){const promises=[];const result=[value];this.#walkAsync(promises,value,process,value=>{result[0]=value});if(promises.length){await Promise.all(promises)}return result[0]}static from(obj,allowIndexed){if(ParamType.isParamType(obj)){return obj}if(typeof obj==="string"){try{return ParamType.from(lex(obj),allowIndexed)}catch(error){assertArgument(false,"invalid param type","obj",obj)}}else if(obj instanceof TokenString){let type="",baseType="";let comps=null;if(consumeKeywords(obj,setify(["tuple"])).has("tuple")||obj.peekType("OPEN_PAREN")){baseType="tuple";comps=obj.popParams().map(t=>ParamType.from(t));type=`tuple(${comps.map(c=>c.format()).join(",")})`}else{type=verifyBasicType(obj.popType("TYPE"));baseType=type}let arrayChildren=null;let arrayLength=null;while(obj.length&&obj.peekType("BRACKET")){const bracket=obj.pop();arrayChildren=new ParamType(_guard$3,"",type,baseType,null,comps,arrayLength,arrayChildren);arrayLength=bracket.value;type+=bracket.text;baseType="array";comps=null}let indexed=null;const keywords=consumeKeywords(obj,KwModifiers);if(keywords.has("indexed")){if(!allowIndexed){throw new Error("")}indexed=true}const name=obj.peekType("ID")?obj.pop().text:"";if(obj.length){throw new Error("leftover tokens")}return new ParamType(_guard$3,name,type,baseType,indexed,comps,arrayLength,arrayChildren)}const name=obj.name;assertArgument(!name||typeof name==="string"&&name.match(regexId),"invalid name","obj.name",name);let indexed=obj.indexed;if(indexed!=null){assertArgument(allowIndexed,"parameter cannot be indexed","obj.indexed",obj.indexed);indexed=!!indexed}let type=obj.type;const arrayMatch=type.match(regexArrayType);if(arrayMatch){const arrayLength=parseInt(arrayMatch[2]||"-1");const arrayChildren=ParamType.from({type:arrayMatch[1],components:obj.components});return new ParamType(_guard$3,name||"",type,"array",indexed,null,arrayLength,arrayChildren)}if(type==="tuple"||type.startsWith("tuple(")||type.startsWith("(")){const comps=obj.components!=null?obj.components.map(c=>ParamType.from(c)):null;const tuple=new ParamType(_guard$3,name||"",type,"tuple",indexed,comps,null,null);return tuple}type=verifyBasicType(obj.type);return new ParamType(_guard$3,name||"",type,type,indexed,null,null,null)}static isParamType(value){return value&&value[internal$1]===ParamTypeInternal}}class Fragment{type;inputs;constructor(guard,type,inputs){assertPrivate(guard,_guard$3,"Fragment");inputs=Object.freeze(inputs.slice());defineProperties(this,{type:type,inputs:inputs})}static from(obj){if(typeof obj==="string"){try{Fragment.from(JSON.parse(obj))}catch(e){}return Fragment.from(lex(obj))}if(obj instanceof TokenString){const type=obj.peekKeyword(KwTypes);switch(type){case"constructor":return ConstructorFragment.from(obj);case"error":return ErrorFragment.from(obj);case"event":return EventFragment.from(obj);case"fallback":case"receive":return FallbackFragment.from(obj);case"function":return FunctionFragment.from(obj);case"struct":return StructFragment.from(obj)}}else if(typeof obj==="object"){switch(obj.type){case"constructor":return ConstructorFragment.from(obj);case"error":return ErrorFragment.from(obj);case"event":return EventFragment.from(obj);case"fallback":case"receive":return FallbackFragment.from(obj);case"function":return FunctionFragment.from(obj);case"struct":return StructFragment.from(obj)}assert(false,`unsupported type: ${obj.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}assertArgument(false,"unsupported frgament object","obj",obj)}static isConstructor(value){return ConstructorFragment.isFragment(value)}static isError(value){return ErrorFragment.isFragment(value)}static isEvent(value){return EventFragment.isFragment(value)}static isFunction(value){return FunctionFragment.isFragment(value)}static isStruct(value){return StructFragment.isFragment(value)}}class NamedFragment extends Fragment{name;constructor(guard,type,name,inputs){super(guard,type,inputs);assertArgument(typeof name==="string"&&name.match(regexId),"invalid identifier","name",name);inputs=Object.freeze(inputs.slice());defineProperties(this,{name:name})}}function joinParams(format,params){return"("+params.map(p=>p.format(format)).join(format==="full"?", ":",")+")"}class ErrorFragment extends NamedFragment{constructor(guard,name,inputs){super(guard,"error",name,inputs);Object.defineProperty(this,internal$1,{value:ErrorFragmentInternal})}get selector(){return id(this.format("sighash")).substring(0,10)}format(format){if(format==null){format="sighash"}if(format==="json"){return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(input=>JSON.parse(input.format(format)))})}const result=[];if(format!=="sighash"){result.push("error")}result.push(this.name+joinParams(format,this.inputs));return result.join(" ")}static from(obj){if(ErrorFragment.isFragment(obj)){return obj}if(typeof obj==="string"){return ErrorFragment.from(lex(obj))}else if(obj instanceof TokenString){const name=consumeName("error",obj);const inputs=consumeParams(obj);consumeEoi(obj);return new ErrorFragment(_guard$3,name,inputs)}return new ErrorFragment(_guard$3,obj.name,obj.inputs?obj.inputs.map(ParamType.from):[])}static isFragment(value){return value&&value[internal$1]===ErrorFragmentInternal}}class EventFragment extends NamedFragment{anonymous;constructor(guard,name,inputs,anonymous){super(guard,"event",name,inputs);Object.defineProperty(this,internal$1,{value:EventFragmentInternal});defineProperties(this,{anonymous:anonymous})}get topicHash(){return id(this.format("sighash"))}format(format){if(format==null){format="sighash"}if(format==="json"){return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(i=>JSON.parse(i.format(format)))})}const result=[];if(format!=="sighash"){result.push("event")}result.push(this.name+joinParams(format,this.inputs));if(format!=="sighash"&&this.anonymous){result.push("anonymous")}return result.join(" ")}static getTopicHash(name,params){params=(params||[]).map(p=>ParamType.from(p));const fragment=new EventFragment(_guard$3,name,params,false);return fragment.topicHash}static from(obj){if(EventFragment.isFragment(obj)){return obj}if(typeof obj==="string"){try{return EventFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid event fragment","obj",obj)}}else if(obj instanceof TokenString){const name=consumeName("event",obj);const inputs=consumeParams(obj,true);const anonymous=!!consumeKeywords(obj,setify(["anonymous"])).has("anonymous");consumeEoi(obj);return new EventFragment(_guard$3,name,inputs,anonymous)}return new EventFragment(_guard$3,obj.name,obj.inputs?obj.inputs.map(p=>ParamType.from(p,true)):[],!!obj.anonymous)}static isFragment(value){return value&&value[internal$1]===EventFragmentInternal}}class ConstructorFragment extends Fragment{payable;gas;constructor(guard,type,inputs,payable,gas){super(guard,type,inputs);Object.defineProperty(this,internal$1,{value:ConstructorFragmentInternal});defineProperties(this,{payable:payable,gas:gas})}format(format){assert(format!=null&&format!=="sighash","cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"});if(format==="json"){return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:undefined,inputs:this.inputs.map(i=>JSON.parse(i.format(format)))})}const result=[`constructor${joinParams(format,this.inputs)}`];if(this.payable){result.push("payable")}if(this.gas!=null){result.push(`@${this.gas.toString()}`)}return result.join(" ")}static from(obj){if(ConstructorFragment.isFragment(obj)){return obj}if(typeof obj==="string"){try{return ConstructorFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid constuctor fragment","obj",obj)}}else if(obj instanceof TokenString){consumeKeywords(obj,setify(["constructor"]));const inputs=consumeParams(obj);const payable=!!consumeKeywords(obj,KwVisibDeploy).has("payable");const gas=consumeGas(obj);consumeEoi(obj);return new ConstructorFragment(_guard$3,"constructor",inputs,payable,gas)}return new ConstructorFragment(_guard$3,"constructor",obj.inputs?obj.inputs.map(ParamType.from):[],!!obj.payable,obj.gas!=null?obj.gas:null)}static isFragment(value){return value&&value[internal$1]===ConstructorFragmentInternal}}class FallbackFragment extends Fragment{payable;constructor(guard,inputs,payable){super(guard,"fallback",inputs);Object.defineProperty(this,internal$1,{value:FallbackFragmentInternal});defineProperties(this,{payable:payable})}format(format){const type=this.inputs.length===0?"receive":"fallback";if(format==="json"){const stateMutability=this.payable?"payable":"nonpayable";return JSON.stringify({type:type,stateMutability:stateMutability})}return`${type}()${this.payable?" payable":""}`}static from(obj){if(FallbackFragment.isFragment(obj)){return obj}if(typeof obj==="string"){try{return FallbackFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid fallback fragment","obj",obj)}}else if(obj instanceof TokenString){const errorObj=obj.toString();const topIsValid=obj.peekKeyword(setify(["fallback","receive"]));assertArgument(topIsValid,"type must be fallback or receive","obj",errorObj);const type=obj.popKeyword(setify(["fallback","receive"]));if(type==="receive"){const inputs=consumeParams(obj);assertArgument(inputs.length===0,`receive cannot have arguments`,"obj.inputs",inputs);consumeKeywords(obj,setify(["payable"]));consumeEoi(obj);return new FallbackFragment(_guard$3,[],true)}let inputs=consumeParams(obj);if(inputs.length){assertArgument(inputs.length===1&&inputs[0].type==="bytes","invalid fallback inputs","obj.inputs",inputs.map(i=>i.format("minimal")).join(", "))}else{inputs=[ParamType.from("bytes")]}const mutability=consumeMutability(obj);assertArgument(mutability==="nonpayable"||mutability==="payable","fallback cannot be constants","obj.stateMutability",mutability);if(consumeKeywords(obj,setify(["returns"])).has("returns")){const outputs=consumeParams(obj);assertArgument(outputs.length===1&&outputs[0].type==="bytes","invalid fallback outputs","obj.outputs",outputs.map(i=>i.format("minimal")).join(", "))}consumeEoi(obj);return new FallbackFragment(_guard$3,inputs,mutability==="payable")}if(obj.type==="receive"){return new FallbackFragment(_guard$3,[],true)}if(obj.type==="fallback"){const inputs=[ParamType.from("bytes")];const payable=obj.stateMutability==="payable";return new FallbackFragment(_guard$3,inputs,payable)}assertArgument(false,"invalid fallback description","obj",obj)}static isFragment(value){return value&&value[internal$1]===FallbackFragmentInternal}}class FunctionFragment extends NamedFragment{constant;outputs;stateMutability;payable;gas;constructor(guard,name,stateMutability,inputs,outputs,gas){super(guard,"function",name,inputs);Object.defineProperty(this,internal$1,{value:FunctionFragmentInternal});outputs=Object.freeze(outputs.slice());const constant=stateMutability==="view"||stateMutability==="pure";const payable=stateMutability==="payable";defineProperties(this,{constant:constant,gas:gas,outputs:outputs,payable:payable,stateMutability:stateMutability})}get selector(){return id(this.format("sighash")).substring(0,10)}format(format){if(format==null){format="sighash"}if(format==="json"){return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:undefined,payable:this.payable,gas:this.gas!=null?this.gas:undefined,inputs:this.inputs.map(i=>JSON.parse(i.format(format))),outputs:this.outputs.map(o=>JSON.parse(o.format(format)))})}const result=[];if(format!=="sighash"){result.push("function")}result.push(this.name+joinParams(format,this.inputs));if(format!=="sighash"){if(this.stateMutability!=="nonpayable"){result.push(this.stateMutability)}if(this.outputs&&this.outputs.length){result.push("returns");result.push(joinParams(format,this.outputs))}if(this.gas!=null){result.push(`@${this.gas.toString()}`)}}return result.join(" ")}static getSelector(name,params){params=(params||[]).map(p=>ParamType.from(p));const fragment=new FunctionFragment(_guard$3,name,"view",params,[],null);return fragment.selector}static from(obj){if(FunctionFragment.isFragment(obj)){return obj}if(typeof obj==="string"){try{return FunctionFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid function fragment","obj",obj)}}else if(obj instanceof TokenString){const name=consumeName("function",obj);const inputs=consumeParams(obj);const mutability=consumeMutability(obj);let outputs=[];if(consumeKeywords(obj,setify(["returns"])).has("returns")){outputs=consumeParams(obj)}const gas=consumeGas(obj);consumeEoi(obj);return new FunctionFragment(_guard$3,name,mutability,inputs,outputs,gas)}let stateMutability=obj.stateMutability;if(stateMutability==null){stateMutability="payable";if(typeof obj.constant==="boolean"){stateMutability="view";if(!obj.constant){stateMutability="payable";if(typeof obj.payable==="boolean"&&!obj.payable){stateMutability="nonpayable"}}}else if(typeof obj.payable==="boolean"&&!obj.payable){stateMutability="nonpayable"}}return new FunctionFragment(_guard$3,obj.name,stateMutability,obj.inputs?obj.inputs.map(ParamType.from):[],obj.outputs?obj.outputs.map(ParamType.from):[],obj.gas!=null?obj.gas:null)}static isFragment(value){return value&&value[internal$1]===FunctionFragmentInternal}}class StructFragment extends NamedFragment{constructor(guard,name,inputs){super(guard,"struct",name,inputs);Object.defineProperty(this,internal$1,{value:StructFragmentInternal})}format(){throw new Error("@TODO")}static from(obj){if(typeof obj==="string"){try{return StructFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid struct fragment","obj",obj)}}else if(obj instanceof TokenString){const name=consumeName("struct",obj);const inputs=consumeParams(obj);consumeEoi(obj);return new StructFragment(_guard$3,name,inputs)}return new StructFragment(_guard$3,obj.name,obj.inputs?obj.inputs.map(ParamType.from):[])}static isFragment(value){return value&&value[internal$1]===StructFragmentInternal}}const PanicReasons$1=new Map;PanicReasons$1.set(0,"GENERIC_PANIC");PanicReasons$1.set(1,"ASSERT_FALSE");PanicReasons$1.set(17,"OVERFLOW");PanicReasons$1.set(18,"DIVIDE_BY_ZERO");PanicReasons$1.set(33,"ENUM_RANGE_ERROR");PanicReasons$1.set(34,"BAD_STORAGE_DATA");PanicReasons$1.set(49,"STACK_UNDERFLOW");PanicReasons$1.set(50,"ARRAY_RANGE_ERROR");PanicReasons$1.set(65,"OUT_OF_MEMORY");PanicReasons$1.set(81,"UNINITIALIZED_FUNCTION_CALL");const paramTypeBytes=new RegExp(/^bytes([0-9]*)$/);const paramTypeNumber=new RegExp(/^(u?int)([0-9]*)$/);let defaultCoder=null;let defaultMaxInflation=1024;function getBuiltinCallException(action,tx,data,abiCoder){let message="missing revert data";let reason=null;const invocation=null;let revert=null;if(data){message="execution reverted";const bytes=getBytes(data);data=hexlify(data);if(bytes.length===0){message+=" (no data present; likely require(false) occurred";reason="require(false)"}else if(bytes.length%32!==4){message+=" (could not decode reason; invalid data length)"}else if(hexlify(bytes.slice(0,4))==="0x08c379a0"){try{reason=abiCoder.decode(["string"],bytes.slice(4))[0];revert={signature:"Error(string)",name:"Error",args:[reason]};message+=`: ${JSON.stringify(reason)}`}catch(error){message+=" (could not decode reason; invalid string data)"}}else if(hexlify(bytes.slice(0,4))==="0x4e487b71"){try{const code=Number(abiCoder.decode(["uint256"],bytes.slice(4))[0]);revert={signature:"Panic(uint256)",name:"Panic",args:[code]};reason=`Panic due to ${PanicReasons$1.get(code)||"UNKNOWN"}(${code})`;message+=`: ${reason}`}catch(error){message+=" (could not decode panic code)"}}else{message+=" (unknown custom error)"}}const transaction={to:tx.to?getAddress(tx.to):null,data:tx.data||"0x"};if(tx.from){transaction.from=getAddress(tx.from)}return makeError(message,"CALL_EXCEPTION",{action:action,data:data,reason:reason,transaction:transaction,invocation:invocation,revert:revert})}class AbiCoder{#getCoder(param){if(param.isArray()){return new ArrayCoder(this.#getCoder(param.arrayChildren),param.arrayLength,param.name)}if(param.isTuple()){return new TupleCoder(param.components.map(c=>this.#getCoder(c)),param.name)}switch(param.baseType){case"address":return new AddressCoder(param.name);case"bool":return new BooleanCoder(param.name);case"string":return new StringCoder(param.name);case"bytes":return new BytesCoder(param.name);case"":return new NullCoder(param.name)}let match=param.type.match(paramTypeNumber);if(match){const size=parseInt(match[2]||"256");assertArgument(size!==0&&size<=256&&size%8===0,"invalid "+match[1]+" bit length","param",param);return new NumberCoder(size/8,match[1]==="int",param.name)}match=param.type.match(paramTypeBytes);if(match){const size=parseInt(match[1]);assertArgument(size!==0&&size<=32,"invalid bytes length","param",param);return new FixedBytesCoder(size,param.name)}assertArgument(false,"invalid type","type",param.type)}getDefaultValue(types){const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");return coder.defaultValue()}encode(types,values){assertArgumentCount(values.length,types.length,"types/values length mismatch");const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");const writer=new Writer;coder.encode(writer,values);return writer.data}decode(types,data,loose){const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");return coder.decode(new Reader(data,loose,defaultMaxInflation))}static _setDefaultMaxInflation(value){assertArgument(typeof value==="number"&&Number.isInteger(value),"invalid defaultMaxInflation factor","value",value);defaultMaxInflation=value}static defaultAbiCoder(){if(defaultCoder==null){defaultCoder=new AbiCoder}return defaultCoder}static getBuiltinCallException(action,tx,data){return getBuiltinCallException(action,tx,data,AbiCoder.defaultAbiCoder())}}class LogDescription{fragment;name;signature;topic;args;constructor(fragment,topic,args){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,signature:signature,topic:topic,args:args})}}class TransactionDescription{fragment;name;args;signature;selector;value;constructor(fragment,selector,args,value){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,args:args,signature:signature,selector:selector,value:value})}}class ErrorDescription{fragment;name;args;signature;selector;constructor(fragment,selector,args){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,args:args,signature:signature,selector:selector})}}class Indexed{hash;_isIndexed;static isIndexed(value){return!!(value&&value._isIndexed)}constructor(hash){defineProperties(this,{hash:hash,_isIndexed:true})}}const PanicReasons={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"};const BuiltinErrors={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:message=>{return`reverted with reason string ${JSON.stringify(message)}`}},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:code=>{let reason="unknown panic code";if(code>=0&&code<=255&&PanicReasons[code.toString()]){reason=PanicReasons[code.toString()]}return`reverted with panic code 0x${code.toString(16)} (${reason})`}}};class Interface{fragments;deploy;fallback;receive;#errors;#events;#functions;#abiCoder;constructor(fragments){let abi=[];if(typeof fragments==="string"){abi=JSON.parse(fragments)}else{abi=fragments}this.#functions=new Map;this.#errors=new Map;this.#events=new Map;const frags=[];for(const a of abi){try{frags.push(Fragment.from(a))}catch(error){console.log("Error parsing ABI fragment",error)}}defineProperties(this,{fragments:Object.freeze(frags)});let fallback=null;let receive=false;this.#abiCoder=this.getAbiCoder();this.fragments.forEach((fragment,index)=>{let bucket;switch(fragment.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}defineProperties(this,{deploy:fragment});return;case"fallback":if(fragment.inputs.length===0){receive=true}else{assertArgument(!fallback||fragment.payable!==fallback.payable,"conflicting fallback fragments",`fragments[${index}]`,fragment);fallback=fragment;receive=fallback.payable}return;case"function":bucket=this.#functions;break;case"event":bucket=this.#events;break;case"error":bucket=this.#errors;break;default:return}const signature=fragment.format();if(bucket.has(signature)){return}bucket.set(signature,fragment)});if(!this.deploy){defineProperties(this,{deploy:ConstructorFragment.from("constructor()")})}defineProperties(this,{fallback:fallback,receive:receive})}format(minimal){const format=minimal?"minimal":"full";const abi=this.fragments.map(f=>f.format(format));return abi}formatJson(){const abi=this.fragments.map(f=>f.format("json"));return JSON.stringify(abi.map(j=>JSON.parse(j)))}getAbiCoder(){return AbiCoder.defaultAbiCoder()}#getFunction(key,values,forceUnique){if(isHexString(key)){const selector=key.toLowerCase();for(const fragment of this.#functions.values()){if(selector===fragment.selector){return fragment}}return null}if(key.indexOf("(")===-1){const matching=[];for(const[name,fragment]of this.#functions){if(name.split("(")[0]===key){matching.push(fragment)}}if(values){const lastValue=values.length>0?values[values.length-1]:null;let valueLength=values.length;let allowOptions=true;if(Typed.isTyped(lastValue)&&lastValue.type==="overrides"){allowOptions=false;valueLength--}for(let i=matching.length-1;i>=0;i--){const inputs=matching[i].inputs.length;if(inputs!==valueLength&&(!allowOptions||inputs!==valueLength-1)){matching.splice(i,1)}}for(let i=matching.length-1;i>=0;i--){const inputs=matching[i].inputs;for(let j=0;j=inputs.length){if(values[j].type==="overrides"){continue}matching.splice(i,1);break}if(values[j].type!==inputs[j].baseType){matching.splice(i,1);break}}}}if(matching.length===1&&values&&values.length!==matching[0].inputs.length){const lastArg=values[values.length-1];if(lastArg==null||Array.isArray(lastArg)||typeof lastArg!=="object"){matching.splice(0,1)}}if(matching.length===0){return null}if(matching.length>1&&forceUnique){const matchStr=matching.map(m=>JSON.stringify(m.format())).join(", ");assertArgument(false,`ambiguous function description (i.e. matches ${matchStr})`,"key",key)}return matching[0]}const result=this.#functions.get(FunctionFragment.from(key).format());if(result){return result}return null}getFunctionName(key){const fragment=this.#getFunction(key,null,false);assertArgument(fragment,"no matching function","key",key);return fragment.name}hasFunction(key){return!!this.#getFunction(key,null,false)}getFunction(key,values){return this.#getFunction(key,values||null,true)}forEachFunction(callback){const names=Array.from(this.#functions.keys());names.sort((a,b)=>a.localeCompare(b));for(let i=0;i=0;i--){if(matching[i].inputs.length=0;i--){const inputs=matching[i].inputs;for(let j=0;j1&&forceUnique){const matchStr=matching.map(m=>JSON.stringify(m.format())).join(", ");assertArgument(false,`ambiguous event description (i.e. matches ${matchStr})`,"key",key)}return matching[0]}const result=this.#events.get(EventFragment.from(key).format());if(result){return result}return null}getEventName(key){const fragment=this.#getEvent(key,null,false);assertArgument(fragment,"no matching event","key",key);return fragment.name}hasEvent(key){return!!this.#getEvent(key,null,false)}getEvent(key,values){return this.#getEvent(key,values||null,true)}forEachEvent(callback){const names=Array.from(this.#events.keys());names.sort((a,b)=>a.localeCompare(b));for(let i=0;i1){const matchStr=matching.map(m=>JSON.stringify(m.format())).join(", ");assertArgument(false,`ambiguous error description (i.e. ${matchStr})`,"name",key)}return matching[0]}key=ErrorFragment.from(key).format();if(key==="Error(string)"){return ErrorFragment.from("error Error(string)")}if(key==="Panic(uint256)"){return ErrorFragment.from("error Panic(uint256)")}const result=this.#errors.get(key);if(result){return result}return null}forEachError(callback){const names=Array.from(this.#errors.keys());names.sort((a,b)=>a.localeCompare(b));for(let i=0;i{if(param.type==="string"){return id(value)}else if(param.type==="bytes"){return keccak256(hexlify(value))}if(param.type==="bool"&&typeof value==="boolean"){value=value?"0x01":"0x00"}else if(param.type.match(/^u?int/)){value=toBeHex(value)}else if(param.type.match(/^bytes/)){value=zeroPadBytes(value,32)}else if(param.type==="address"){this.#abiCoder.encode(["address"],[value])}return zeroPadValue(hexlify(value),32)};values.forEach((value,index)=>{const param=fragment.inputs[index];if(!param.indexed){assertArgument(value==null,"cannot filter non-indexed parameters; must be null","contract."+param.name,value);return}if(value==null){topics.push(null)}else if(param.baseType==="array"||param.baseType==="tuple"){assertArgument(false,"filtering with tuples or arrays not supported","contract."+param.name,value)}else if(Array.isArray(value)){topics.push(value.map(value=>encodeTopic(param,value)))}else{topics.push(encodeTopic(param,value))}});while(topics.length&&topics[topics.length-1]===null){topics.pop()}return topics}encodeEventLog(fragment,values){if(typeof fragment==="string"){const f=this.getEvent(fragment);assertArgument(f,"unknown event","eventFragment",fragment);fragment=f}const topics=[];const dataTypes=[];const dataValues=[];if(!fragment.anonymous){topics.push(fragment.topicHash)}assertArgument(values.length===fragment.inputs.length,"event arguments/values mismatch","values",values);fragment.inputs.forEach((param,index)=>{const value=values[index];if(param.indexed){if(param.type==="string"){topics.push(id(value))}else if(param.type==="bytes"){topics.push(keccak256(value))}else if(param.baseType==="tuple"||param.baseType==="array"){throw new Error("not implemented")}else{topics.push(this.#abiCoder.encode([param.type],[value]))}}else{dataTypes.push(param);dataValues.push(value)}});return{data:this.#abiCoder.encode(dataTypes,dataValues),topics:topics}}decodeEventLog(fragment,data,topics){if(typeof fragment==="string"){const f=this.getEvent(fragment);assertArgument(f,"unknown event","eventFragment",fragment);fragment=f}if(topics!=null&&!fragment.anonymous){const eventTopic=fragment.topicHash;assertArgument(isHexString(topics[0],32)&&topics[0].toLowerCase()===eventTopic,"fragment/topic mismatch","topics[0]",topics[0]);topics=topics.slice(1)}const indexed=[];const nonIndexed=[];const dynamic=[];fragment.inputs.forEach((param,index)=>{if(param.indexed){if(param.type==="string"||param.type==="bytes"||param.baseType==="tuple"||param.baseType==="array"){indexed.push(ParamType.from({type:"bytes32",name:param.name}));dynamic.push(true)}else{indexed.push(param);dynamic.push(false)}}else{nonIndexed.push(param);dynamic.push(false)}});const resultIndexed=topics!=null?this.#abiCoder.decode(indexed,concat(topics)):null;const resultNonIndexed=this.#abiCoder.decode(nonIndexed,data,true);const values=[];const keys=[];let nonIndexedIndex=0,indexedIndex=0;fragment.inputs.forEach((param,index)=>{let value=null;if(param.indexed){if(resultIndexed==null){value=new Indexed(null)}else if(dynamic[index]){value=new Indexed(resultIndexed[indexedIndex++])}else{try{value=resultIndexed[indexedIndex++]}catch(error){value=error}}}else{try{value=resultNonIndexed[nonIndexedIndex++]}catch(error){value=error}}values.push(value);keys.push(param.name||null)});return Result.fromItems(values,keys)}parseTransaction(tx){const data=getBytes(tx.data,"tx.data");const value=getBigInt(tx.value!=null?tx.value:0,"tx.value");const fragment=this.getFunction(hexlify(data.slice(0,4)));if(!fragment){return null}const args=this.#abiCoder.decode(fragment.inputs,data.slice(4));return new TransactionDescription(fragment,fragment.selector,args,value)}parseCallResult(data){throw new Error("@TODO")}parseLog(log){const fragment=this.getEvent(log.topics[0]);if(!fragment||fragment.anonymous){return null}return new LogDescription(fragment,fragment.topicHash,this.decodeEventLog(fragment,log.data,log.topics))}parseError(data){const hexData=hexlify(data);const fragment=this.getError(dataSlice(hexData,0,4));if(!fragment){return null}const args=this.#abiCoder.decode(fragment.inputs,dataSlice(hexData,4));return new ErrorDescription(fragment,fragment.selector,args)}static from(value){if(value instanceof Interface){return value}if(typeof value==="string"){return new Interface(JSON.parse(value))}if(typeof value.format==="function"){return new Interface(value.format("json"))}return new Interface(value)}}function accessSetify(addr,storageKeys){validateAddress(addr);return{address:getAddress(addr),storageKeys:storageKeys.map((storageKey,index)=>{assertArgument(isHexString(storageKey,32),"invalid slot",`storageKeys[${index}]`,storageKey);return storageKey.toLowerCase()})}}function accessListify(value){if(Array.isArray(value)){return value.map((set,index)=>{if(Array.isArray(set)){assertArgument(set.length===2,"invalid slot set",`value[${index}]`,set);return accessSetify(set[0],set[1])}assertArgument(set!=null&&typeof set==="object","invalid address-slot set","value",value);return accessSetify(set.address,set.storageKeys)})}assertArgument(value!=null&&typeof value==="object","invalid access list","value",value);const result=Object.keys(value).map(addr=>{const storageKeys=value[addr].reduce((accum,storageKey)=>{accum[storageKey]=true;return accum},{});return accessSetify(addr,Object.keys(storageKeys).sort())});result.sort((a,b)=>a.address.localeCompare(b.address));return result}class AbstractTransaction{_type;_signature;_chainId;get type(){return this._type}set type(value){switch(value){case null:this._type=null;break;case 0:case"standard":this._type=0;break;case 2:case"utxo":this._type=2;break;default:assertArgument(false,"unsupported transaction type","type",value)}}get typeName(){switch(this.type){case 0:return"standard";case 1:return"external";case 2:return"utxo"}return null}get chainId(){return this._chainId}set chainId(value){this._chainId=getBigInt(value)}get signature(){return this._signature||null}set signature(value){if(typeof value==="string"){this._signature=value}else{this._signature=value==null?null:Signature.from(value)}}constructor(){this._type=null;this._chainId=BigInt(0);this._signature=null}get digest(){return keccak256(this.unsignedSerialized)}isSigned(){return this.signature!=null}get serialized(){assert(this.signature!=null,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});return encodeProtoTransaction(this.toProtobuf(true))}get unsignedSerialized(){return encodeProtoTransaction(this.toProtobuf(false))}inferType(){return this.inferTypes().pop()}get isExternal(){return this.destZone!==undefined&&this.originZone!==this.destZone}}const denominations=[BigInt(1),BigInt(5),BigInt(10),BigInt(50),BigInt(100),BigInt(250),BigInt(500),BigInt(1e3),BigInt(5e3),BigInt(1e4),BigInt(2e4),BigInt(5e4),BigInt(1e5),BigInt(1e6),BigInt(1e7),BigInt(1e8),BigInt(1e9)];function isValidDenomination(denomination){return denominations.includes(denomination)}function handleBigInt(value,param){if(value==="0x"){return BigInt(0)}return getBigInt(value,param)}function denominate(value){if(value<=BigInt(0)){throw new Error("Value must be greater than 0")}const result=[];let remainingValue=value;for(let i=denominations.length-1;i>=0;i--){const denomination=denominations[i];while(remainingValue>=denomination){result.push(denomination);remainingValue-=denomination}}if(remainingValue>0){throw new Error("Unable to match the value with available denominations")}return result}class UTXO{#txhash;#index;#address;#denomination;get txhash(){return this.#txhash}set txhash(value){this.#txhash=value}get index(){return this.#index}set index(value){this.#index=value}get address(){return this.#address||""}set address(value){validateAddress(value);this.#address=value}get denomination(){return this.#denomination}set denomination(value){if(value==null){this.#denomination=null;return}const denominationBigInt=handleBigInt(value.toString(),"denomination");if(!isValidDenomination(denominationBigInt)){throw new Error("Invalid denomination value")}this.#denomination=denominationBigInt}constructor(){this.#txhash=null;this.#index=null;this.#address=null;this.#denomination=null}toJSON(){return{txhash:this.txhash,index:this.index,address:this.address,denomination:this.denomination}}static from(utxo){if(utxo===null){return new UTXO}const result=utxo instanceof UTXO?utxo:new UTXO;if(utxo.txhash!=null){result.txhash=utxo.txhash}if(utxo.index!=null){result.index=utxo.index}if(utxo.address!=null&&utxo.address!==""){result.address=utxo.address}if(utxo.denomination!=null){result.denomination=utxo.denomination}return result}}class AbstractCoinSelector{#availableUXTOs;#spendOutputs;#changeOutputs;get availableUXTOs(){return this.#availableUXTOs}set availableUXTOs(value){this.#availableUXTOs=value.map(val=>{const utxo=UTXO.from(val);this._validateUTXO(utxo);return utxo})}get spendOutputs(){return this.#spendOutputs}set spendOutputs(value){this.#spendOutputs=value.map(utxo=>UTXO.from(utxo))}get changeOutputs(){return this.#changeOutputs}set changeOutputs(value){this.#changeOutputs=value.map(utxo=>UTXO.from(utxo))}constructor(availableUXTOs=[]){this.#availableUXTOs=availableUXTOs.map(val=>{const utxo=UTXO.from(val);this._validateUTXO(utxo);return utxo});this.#spendOutputs=[];this.#changeOutputs=[]}_validateUTXO(utxo){if(utxo.address==null){throw new Error("UTXO address is required")}if(utxo.denomination==null){throw new Error("UTXO denomination is required")}}}class FewestCoinSelector extends AbstractCoinSelector{performSelection(target){this.validateTarget(target);this.validateUTXOs();const sortedUTXOs=this.sortUTXOsByDenomination(this.availableUXTOs,"desc");let totalValue=BigInt(0);let selectedUTXOs=[];const UTXOsEqualOrGreaterThanTarget=sortedUTXOs.filter(utxo=>utxo.denomination&&utxo.denomination>=target.value);if(UTXOsEqualOrGreaterThanTarget.length>0){const optimalUTXO=UTXOsEqualOrGreaterThanTarget.reduce((minDenominationUTXO,currentUTXO)=>{if(!currentUTXO.denomination)return minDenominationUTXO;return currentUTXO.denomination0&&totalValue{if(!utxo.denomination)return closest;const absThisDiff=bigIntAbs(target.value-(totalValue+utxo.denomination));const currentClosestDiff=closest&&closest.denomination?bigIntAbs(target.value-(totalValue+closest.denomination)):BigInt(Infinity);return absThisDiffutxo.denomination===nextOptimalUTXO.denomination&&utxo.address===nextOptimalUTXO.address);sortedUTXOs.splice(index,1)}}if(totalValue=target.value){runningTotal-=utxo.denomination;lastRemovableIndex=i}else{break}}}if(lastRemovableIndex>=0){totalValue-=selectedUTXOs[lastRemovableIndex].denomination;selectedUTXOs.splice(lastRemovableIndex,1)}const spendDenominations=denominate(target.value);this.spendOutputs=spendDenominations.map(denomination=>{const utxo=new UTXO;utxo.denomination=denomination;utxo.address=target.address;return utxo});const change=totalValue-target.value;if(change>BigInt(0)){const changeDenominations=denominate(change);this.changeOutputs=changeDenominations.map(denomination=>{const utxo=new UTXO;utxo.denomination=denomination;return utxo})}else{this.changeOutputs=[]}return{inputs:selectedUTXOs,spendOutputs:this.spendOutputs,changeOutputs:this.changeOutputs}}sortUTXOsByDenomination(utxos,direction){if(direction==="asc"){return[...utxos].sort((a,b)=>{const diff=(a.denomination??BigInt(0))-(b.denomination??BigInt(0));return diff>0?1:diff<0?-1:0})}return[...utxos].sort((a,b)=>{const diff=(b.denomination??BigInt(0))-(a.denomination??BigInt(0));return diff>0?1:diff<0?-1:0})}validateTarget(target){if(target.value<=BigInt(0)){throw new Error("Target amount must be greater than 0")}}validateUTXOs(){if(this.availableUXTOs.length===0){throw new Error("No UTXOs available")}}}const BN_0$2=BigInt(0);function allowNull(format,nullValue){return function(value){if(value==null){return nullValue}return format(value)}}function arrayOf(format){return array=>{if(!Array.isArray(array)){throw new Error("not an array")}return array.map(i=>format(i))}}function object(format,altNames){return value=>{const result={};for(const key in format){let srcKey=key;if(altNames&&key in altNames&&!(srcKey in value)){for(const altKey of altNames[key]){if(altKey in value){srcKey=altKey;break}}}try{const nv=format[key](value[srcKey]);if(nv!==undefined){result[key]=nv}}catch(error){const message=error instanceof Error?error.message:"not-an-error";assert(false,`invalid value for value.${key} (${message})`,"BAD_DATA",{value:value})}}return result}}function formatBoolean(value){switch(value){case true:case"true":return true;case false:case"false":return false}assertArgument(false,`invalid boolean; ${JSON.stringify(value)}`,"value",value)}function formatData(value){assertArgument(isHexString(value),"invalid data","value",value);return value}function formatHash(value){assertArgument(isHexString(value,32),"invalid hash","value",value);return value}function handleNumber(_value,param){if(_value==="0x"){return 0}return getNumber(_value,param)}function formatNumber(_value,name){const value=getBigInt(_value,"value");const result=toBeArray(value);assertArgument(result.length<=32,`value too large`,`tx.${name}`,value);return result}const _formatLog=object({address:getAddress,blockHash:formatHash,blockNumber:getNumber,data:formatData,index:getNumber,removed:allowNull(formatBoolean,false),topics:arrayOf(formatHash),transactionHash:formatHash,transactionIndex:getNumber},{index:["logIndex"]});function formatLog(value){return _formatLog(value)}const _formatHeader=object({baseFeePerGas:getBigInt,efficiencyScore:getBigInt,etxEligibleSlices:formatHash,etxSetRoot:formatHash,evmRoot:formatHash,expansionNumber:getNumber,extRollupRoot:formatHash,extTransactionsRoot:formatHash,extraData:formatData,gasLimit:getBigInt,gasUsed:getBigInt,hash:formatHash,interlinkRootHash:formatHash,manifestHash:arrayOf(formatHash),number:arrayOf(getNumber),parentDeltaS:arrayOf(getBigInt),parentEntropy:arrayOf(getBigInt),parentHash:arrayOf(formatHash),parentUncledS:arrayOf(allowNull(getBigInt)),parentUncledSubDeltaS:arrayOf(getBigInt),primeTerminus:formatHash,receiptsRoot:formatHash,sha3Uncles:formatHash,size:getBigInt,thresholdCount:getBigInt,transactionsRoot:formatHash,uncledS:getBigInt,utxoRoot:formatHash});const _formatUncle=object({coinbase:allowNull(getAddress),difficulty:getBigInt,headerHash:formatHash,location:formatData,mixHash:formatHash,nonce:formatData,number:getNumber,parentHash:formatHash,primeTerminusNumber:getNumber,time:getBigInt,txHash:formatHash,workShare:formatBoolean});const _formatWoHeader=object({coinbase:getAddress,difficulty:getNumber,headerHash:formatHash,location:formatData,mixHash:formatHash,nonce:formatData,number:getNumber,parentHash:formatHash,primeTerminusNumber:getNumber,time:formatData,txHash:formatHash});const _formatBlock=object({extTransactions:arrayOf(tx=>{if(typeof tx==="string"){return formatHash(tx)}return formatExternalTransactionResponse(tx)}),hash:formatHash,header:_formatHeader,interlinkHashes:arrayOf(formatHash),order:getNumber,size:getBigInt,subManifest:arrayOf(formatData),totalEntropy:getBigInt,transactions:arrayOf(tx=>{if(typeof tx==="string"){return formatHash(tx)}return formatTransactionResponse(tx)}),uncles:allowNull(arrayOf(_formatUncle),[]),woHeader:_formatWoHeader});function formatBlock(value){const result=_formatBlock(value);result.transactions=value.transactions.map(tx=>{if(typeof tx==="string"){return tx}if("originatingTxHash"in tx){return formatExternalTransactionResponse(tx)}return formatTransactionResponse(tx)});result.extTransactions=value.extTransactions.map(tx=>{if(typeof tx==="string"){return tx}return formatExternalTransactionResponse(tx)});return result}const _formatReceiptLog=object({transactionIndex:getNumber,blockNumber:getNumber,transactionHash:formatHash,address:getAddress,topics:arrayOf(formatHash),data:formatData,index:getNumber,blockHash:formatHash},{index:["logIndex"]});function formatReceiptLog(value){return _formatReceiptLog(value)}const _formatEtx=object({type:allowNull(getNumber,0),nonce:allowNull(getNumber),gasPrice:allowNull(getBigInt),maxPriorityFeePerGas:allowNull(getBigInt),maxFeePerGas:allowNull(getBigInt),gas:allowNull(getBigInt),value:allowNull(getBigInt,BN_0$2),input:allowNull(formatData),to:allowNull(getAddress,null),accessList:allowNull(accessListify,null),isCoinbase:allowNull(getNumber,0),sender:getAddress,originatingTxHash:formatHash,etxIndex:getNumber,chainId:allowNull(getBigInt,null),hash:formatHash},{from:["sender"]});function formatEtx(value){return _formatEtx(value)}const _formatTransactionReceipt=object({to:allowNull(getAddress,null),from:allowNull(getAddress,null),contractAddress:allowNull(getAddress,null),index:getNumber,gasUsed:getBigInt,logsBloom:allowNull(formatData),blockHash:formatHash,hash:formatHash,logs:arrayOf(formatReceiptLog),blockNumber:getNumber,cumulativeGasUsed:getBigInt,effectiveGasPrice:allowNull(getBigInt),status:allowNull(getNumber),type:allowNull(getNumber,0),etxs:value=>value===null?[]:arrayOf(formatEtx)(value)},{hash:["transactionHash"],index:["transactionIndex"]});function formatTransactionReceipt(value){const result=_formatTransactionReceipt(value);return result}function formatExternalTransactionResponse(value){const result=object({hash:formatHash,type:value=>{if(value==="0x"||value==null){return 0}return parseInt(value,16)},accessList:allowNull(accessListify,null),blockHash:allowNull(formatHash,null),blockNumber:allowNull(value=>value?parseInt(value,16):null,null),index:allowNull(value=>value?BigInt(value):null,null),from:allowNull(getAddress,null),sender:allowNull(getAddress,null),maxPriorityFeePerGas:allowNull(value=>value?BigInt(value):null),maxFeePerGas:allowNull(value=>value?BigInt(value):null),gasLimit:allowNull(value=>value?BigInt(value):null,null),to:allowNull(getAddress,null),value:allowNull(value=>value?BigInt(value):null,null),nonce:allowNull(value=>value?parseInt(value,10):null,null),creates:allowNull(getAddress,null),chainId:allowNull(value=>value?BigInt(value):null,null),isCoinbase:allowNull(value=>value?parseInt(value,10):null,null),originatingTxHash:allowNull(formatHash,null),etxIndex:allowNull(value=>value?parseInt(value,10):null,null),etxType:allowNull(value=>value,null),data:value=>value},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(value);if(result.blockHash&&getBigInt(result.blockHash)===BN_0$2){result.blockHash=null}return result}function formatTransactionResponse(value){const transactionType=parseInt(value.type,16);let result;if(transactionType===0||transactionType===1){result=object({hash:formatHash,type:value=>{if(value==="0x"||value==null){return 0}return parseInt(value,16)},accessList:allowNull(accessListify,null),blockHash:allowNull(formatHash,null),blockNumber:allowNull(value=>value?parseInt(value,16):null,null),index:allowNull(value=>value?BigInt(value):null,null),from:allowNull(getAddress,null),sender:allowNull(getAddress,null),maxPriorityFeePerGas:allowNull(value=>value?BigInt(value):null),maxFeePerGas:allowNull(value=>value?BigInt(value):null),gasLimit:allowNull(value=>value?BigInt(value):null,null),to:allowNull(getAddress,null),value:allowNull(value=>value?BigInt(value):null,null),nonce:allowNull(value=>value?parseInt(value,10):null,null),creates:allowNull(getAddress,null),chainId:allowNull(value=>value?BigInt(value):null,null),etxType:allowNull(value=>value,null),data:value=>value},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(value);if((value.type===0||value.type===2)&&value.accessList==null){result.accessList=[]}if(value.signature){result.signature=Signature.from(value.signature);if(result.chainId==null){const chainId=result.signature.legacyChainId;if(chainId!=null){result.chainId=chainId}}}if(result.blockHash&&getBigInt(result.blockHash)===BN_0$2){result.blockHash=null}}else if(transactionType===2){result=object({hash:formatHash,type:value=>{if(value==="0x"||value==null){return 0}return parseInt(value,16)},blockHash:allowNull(formatHash,null),blockNumber:allowNull(value=>value?parseInt(value,16):null,null),index:allowNull(value=>value?BigInt(value):null,null),chainId:allowNull(value=>value?BigInt(value):null,null),signature:value=>value,txInputs:allowNull(value=>value.map(_formatTxInput),null),txOutputs:allowNull(value=>value.map(_formatTxOutput),null)},{index:["transactionIndex"],signature:["utxoSignature"],txInputs:["inputs"],txOutputs:["outputs"]})(value)}else{throw new Error("Unknown transaction type")}return result}const _formatTxInput=object({txhash:formatTxHash,index:formatIndex,pubkey:hexlify},{txhash:["PreviousOutPoint","TxHash"],index:["PreviousOutPoint","Index"],pubkey:["PubKey"]});function extractTxHash(value){if(value&&value.TxHash){return value.TxHash}throw new Error("Invalid PreviousOutPoint")}function formatTxHash(value){return formatHash(extractTxHash(value))}function extractIndex(value){if(value&&value.Index!==undefined){return value.Index}throw new Error("Invalid PreviousOutPoint")}function formatIndex(value){return getNumber(extractIndex(value))}const _formatTxOutput=object({address:addr=>hexlify(getAddress(addr)),denomination:getNumber});class QiTransaction extends AbstractTransaction{#txInputs;#txOutputs;get txInputs(){return(this.#txInputs??[]).map(entry=>({...entry}))}set txInputs(value){if(!Array.isArray(value)){throw new Error("txInputs must be an array")}this.#txInputs=value.map(entry=>({...entry}))}get txOutputs(){return(this.#txOutputs??[]).map(output=>({...output}))}set txOutputs(value){if(!Array.isArray(value)){throw new Error("txOutputs must be an array")}this.#txOutputs=value.map(output=>({...output}))}get hash(){if(this.signature==null){return null}if(this.txInputs.length<1||this.txOutputs.length<1){throw new Error("Transaction must have at least one input and one output")}const senderAddr=computeAddress(this.txInputs[0].pubkey||"");if(!this.destZone||!this.originZone){throw new Error(`Invalid zones: origin ${this.originZone} -> destination ${this.destZone} (address: ${senderAddr})`)}const isSameLedger=isQiAddress(senderAddr)===isQiAddress(hexlify(this.txOutputs[0].address)||"");if(this.isExternal&&!isSameLedger){throw new Error("Cross-zone & cross-ledger transactions are not supported")}const hexString=this.serialized.startsWith("0x")?this.serialized.substring(2):this.serialized;const dataBuffer=Buffer.from(hexString,"hex");const hashHex=keccak256(dataBuffer);const hashBuffer=Buffer.from(hashHex.substring(2),"hex");const origin=this.originZone?parseInt(this.originZone.slice(2),16):0;hashBuffer[0]=origin;hashBuffer[1]|=128;hashBuffer[2]=origin;hashBuffer[3]|=128;return"0x"+hashBuffer.toString("hex")}get originZone(){const senderAddr=computeAddress(this.txInputs[0].pubkey||"");const zone=getZoneForAddress(senderAddr);return zone??undefined}get destZone(){const zone=getZoneForAddress(this.txOutputs[0].address);return zone??undefined}constructor(){super();this.#txInputs=[];this.#txOutputs=[]}inferTypes(){const types=[];if(this.type!=null){types.push(this.type)}else{types.push(2)}types.sort();return types}clone(){return QiTransaction.from(this)}toJSON(){const s=v=>{if(v==null){return null}return v.toString()};return{type:this.type,chainId:s(this.chainId),signature:this.signature?this.signature:null,hash:this.hash,txInputs:this.txInputs,txOutputs:this.txOutputs}}toProtobuf(includeSignature=true){const protoTx={type:this.type||2,chain_id:formatNumber(this.chainId||0,"chainId"),tx_ins:{tx_ins:this.txInputs.map(input=>({previous_out_point:{hash:{value:getBytes(input.txhash)},index:input.index},pub_key:getBytes(input.pubkey)}))},tx_outs:{tx_outs:this.txOutputs.map(output=>({address:getBytes(output.address),denomination:output.denomination}))}};if(this.signature&&includeSignature){protoTx.signature=getBytes(this.signature)}return protoTx}static from(tx){if(typeof tx==="string"){const decodedProtoTx=decodeProtoTransaction(getBytes(tx));return QiTransaction.fromProto(decodedProtoTx)}const result=new QiTransaction;if(tx.type!=null){result.type=tx.type}if(tx.chainId!=null){result.chainId=tx.chainId}if(tx.signature!=null&&tx.signature!==""){result.signature=tx.signature}if(tx.txInputs!=null){result.txInputs=tx.txInputs}if(tx.txOutputs!=null){result.txOutputs=tx.txOutputs}if(tx.hash!=null){assertArgument(result.isSigned(),"unsigned transaction cannot define hash","tx",tx)}return result}static fromProto(protoTx){const tx=new QiTransaction;tx.type=protoTx.type;tx.chainId=toBigInt(protoTx.chain_id);if(protoTx.type==2){tx.txInputs=protoTx.tx_ins?.tx_ins.map(input=>({txhash:hexlify(input.previous_out_point.hash.value),index:input.previous_out_point.index,pubkey:hexlify(input.pub_key)}))??[];tx.txOutputs=protoTx.tx_outs?.tx_outs.map(output=>({address:hexlify(output.address),denomination:output.denomination}))??[]}if(protoTx.signature){tx.signature=hexlify(protoTx.signature)}return tx}}function _parseSignature(fields){let yParity;try{yParity=handleNumber(fields[0],"yParity");if(yParity!==0&&yParity!==1){throw new Error("bad yParity")}}catch(error){assertArgument(false,"invalid yParity","yParity",fields[0])}const r=zeroPadValue(fields[1],32);const s=zeroPadValue(fields[2],32);return Signature.from({r:r,s:s,yParity:yParity})}class QuaiTransaction extends AbstractTransaction{#to;#data;#nonce;#gasLimit;#gasPrice;#maxPriorityFeePerGas;#maxFeePerGas;#value;#accessList;from;get to(){return this.#to}set to(value){if(value!==null)validateAddress(value);this.#to=value}get hash(){if(this.signature==null)return null;if(!this.originZone){throw new Error("Invalid Zone for from address")}if(!this.from){throw new Error("Missing from address")}const isSameLedger=!this.to||isQuaiAddress(this.from)===isQuaiAddress(this.to);if(this.isExternal&&!isSameLedger){throw new Error("Cross-zone & cross-ledger transactions are not supported")}const hexString=this.serialized.startsWith("0x")?this.serialized.substring(2):this.serialized;const dataBuffer=Buffer.from(hexString,"hex");const hashHex=keccak256(dataBuffer);const hashBuffer=Buffer.from(hashHex.substring(2),"hex");const origin=this.originZone?parseInt(this.originZone.slice(2),16):0;hashBuffer[0]=origin;hashBuffer[1]&=127;hashBuffer[2]=origin;hashBuffer[3]&=127;return"0x"+hashBuffer.toString("hex")}get originZone(){const zone=this.from?getZoneForAddress(this.from):undefined;return zone??undefined}get destZone(){const zone=this.to!==null?getZoneForAddress(this.to||""):undefined;return zone??undefined}get nonce(){return this.#nonce}set nonce(value){this.#nonce=getNumber(value,"value")}get gasLimit(){return this.#gasLimit}set gasLimit(value){this.#gasLimit=getBigInt(value)}get gasPrice(){const value=this.#gasPrice;return value}set gasPrice(value){this.#gasPrice=value==null?null:getBigInt(value,"gasPrice")}get maxPriorityFeePerGas(){const value=this.#maxPriorityFeePerGas;if(value==null){return null}return value}set maxPriorityFeePerGas(value){this.#maxPriorityFeePerGas=value==null?null:getBigInt(value,"maxPriorityFeePerGas")}get maxFeePerGas(){const value=this.#maxFeePerGas;if(value==null){return null}return value}set maxFeePerGas(value){this.#maxFeePerGas=value==null?null:getBigInt(value,"maxFeePerGas")}get data(){return this.#data}set data(value){this.#data=hexlify(value)}get value(){return this.#value}set value(value){this.#value=getBigInt(value,"value")}get accessList(){const value=this.#accessList||null;if(value==null){return null}return value}set accessList(value){this.#accessList=value==null?null:accessListify(value)}constructor(from){super();this.#to=null;this.#nonce=0;this.#gasLimit=BigInt(0);this.#gasPrice=null;this.#maxPriorityFeePerGas=null;this.#maxFeePerGas=null;this.#data="0x";this.#value=BigInt(0);this.#accessList=null;this.from=from}inferTypes(){if(this.maxFeePerGas!=null&&this.maxPriorityFeePerGas!=null){assert(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this})}assert(this.type!==0&&this.type!==1,"transaction type cannot have externalGasLimit, externalGasTip, externalGasPrice, externalData, or externalAccessList","BAD_DATA",{value:this});const types=[];if(this.type!=null){types.push(this.type)}else{types.push(0)}types.sort();return types}clone(){return QuaiTransaction.from(this)}toJSON(){const s=v=>{if(v==null){return null}return v.toString()};return{type:this.type,to:this.to,from:this.from,data:this.data,nonce:this.nonce,gasLimit:s(this.gasLimit),gasPrice:s(this.gasPrice),maxPriorityFeePerGas:s(this.maxPriorityFeePerGas),maxFeePerGas:s(this.maxFeePerGas),value:s(this.value),chainId:s(this.chainId),signature:this.signature?this.signature.toJSON():null,hash:this.hash,accessList:this.accessList}}toProtobuf(includeSignature=true){const protoTx={type:this.type||0,chain_id:formatNumber(this.chainId||0,"chainId"),nonce:this.nonce||0,gas_tip_cap:formatNumber(this.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),gas_fee_cap:formatNumber(this.maxFeePerGas||0,"maxFeePerGas"),gas:Number(this.gasLimit||0),to:this.to!=null?getBytes(this.to):null,value:formatNumber(this.value||0,"value"),data:getBytes(this.data||"0x"),access_list:{access_tuples:[]}};if(this.signature&&includeSignature){protoTx.v=formatNumber(this.signature.yParity,"yParity");protoTx.r=toBeArray(this.signature.r);protoTx.s=toBeArray(this.signature.s)}return protoTx}static from(tx){if(typeof tx==="string"){const decodedProtoTx=decodeProtoTransaction(getBytes(tx));return QuaiTransaction.fromProto(decodedProtoTx)}const result=new QuaiTransaction(tx.from);if(tx.type!=null){result.type=tx.type}if(tx.to!=null){validateAddress(tx.to);result.to=tx.to}if(tx.nonce!=null){result.nonce=tx.nonce}if(tx.gasLimit!=null){result.gasLimit=tx.gasLimit}if(tx.maxPriorityFeePerGas!=null){result.maxPriorityFeePerGas=tx.maxPriorityFeePerGas}if(tx.maxFeePerGas!=null){result.maxFeePerGas=tx.maxFeePerGas}if(tx.data!=null&&tx.data!==""){result.data=tx.data}if(tx.value!=null){result.value=tx.value}if(tx.chainId!=null){result.chainId=tx.chainId}if(tx.signature!=null){result.signature=Signature.from(tx.signature)}if(tx.accessList!=null){result.accessList=tx.accessList}if(tx.hash!=null){assertArgument(result.isSigned(),"unsigned transaction cannot define hash","tx",tx)}if(tx.from!=null){assertArgument(isQuaiAddress(tx.from),"from address must be a Quai address","tx.from",tx.from);assertArgument((result.from||"").toLowerCase()===(tx.from||"").toLowerCase(),"from mismatch","tx",tx);result.from=tx.from}return result}static fromProto(protoTx){let signature=null;let address="";if(protoTx.v&&protoTx.r&&protoTx.s){if(protoTx.r.reduce((acc,val)=>acc+=val,0)==0){throw new Error("Proto decoding only supported for signed transactions")}const signatureFields=[hexlify(protoTx.v),hexlify(protoTx.r),hexlify(protoTx.s)];signature=_parseSignature(signatureFields);const protoTxCopy=structuredClone(protoTx);delete protoTxCopy.v;delete protoTxCopy.r;delete protoTxCopy.s;delete protoTxCopy.signature;delete protoTxCopy.etx_sender;delete protoTxCopy.etx_index;address=recoverAddress(keccak256(encodeProtoTransaction(protoTxCopy)),signature)}const tx=new QuaiTransaction(address);if(signature){tx.signature=signature}if(protoTx.to!==null){const toAddr=hexlify(protoTx.to);tx.to=getAddress(toAddr)}tx.type=protoTx.type;tx.chainId=toBigInt(protoTx.chain_id);tx.nonce=Number(protoTx.nonce);tx.maxPriorityFeePerGas=toBigInt(protoTx.gas_tip_cap);tx.maxFeePerGas=toBigInt(protoTx.gas_fee_cap);tx.gasLimit=toBigInt(protoTx.gas);tx.value=protoTx.value!==null?toBigInt(protoTx.value):BigInt(0);tx.data=hexlify(protoTx.data);tx.accessList=protoTx.access_list.access_tuples.map(tuple=>({address:hexlify(tuple.address),storageKeys:tuple.storage_key.map(key=>hexlify(key))}));return tx}}const BN_0$1=BigInt(0);function getValue(value){if(value==null){return null}return value}function toJson(value){if(value==null){return null}return value.toString()}class FeeData{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(gasPrice,maxFeePerGas,maxPriorityFeePerGas){defineProperties(this,{gasPrice:getValue(gasPrice),maxFeePerGas:getValue(maxFeePerGas),maxPriorityFeePerGas:getValue(maxPriorityFeePerGas)})}toJSON(){const{gasPrice,maxFeePerGas,maxPriorityFeePerGas}=this;return{_type:"FeeData",gasPrice:toJson(gasPrice),maxFeePerGas:toJson(maxFeePerGas),maxPriorityFeePerGas:toJson(maxPriorityFeePerGas)}}}function addressFromTransactionRequest(tx){if("from"in tx&&!!tx.from){return tx.from}if("txInputs"in tx&&!!tx.txInputs){return computeAddress(tx.txInputs[0].pubkey)}if("to"in tx&&!!tx.to){return tx.to}throw new Error("Unable to determine address from transaction inputs, from or to field")}function copyRequest(req){const result={};if("to"in req&&req.to){result.to=req.to}if("from"in req&&req.from){result.from=req.from}if("data"in req&&req.data){result.data=hexlify(req.data)}const bigIntKeys="chainId,gasLimit,gasPrice,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const key of bigIntKeys){if(!(key in req)||req[key]==null){continue}result[key]=getBigInt(req[key],`request.${key}`)}const numberKeys="type,nonce".split(/,/);for(const key of numberKeys){if(!(key in req)||req[key]==null){continue}result[key]=getNumber(req[key],`request.${key}`)}if("accessList"in req&&req.accessList){result.accessList=accessListify(req.accessList)}if("blockTag"in req){result.blockTag=req.blockTag}if("customData"in req){result.customData=req.customData}if("txInputs"in req&&req.txInputs){result.txInputs=req.txInputs.map(entry=>({...entry}))}if("txOutputs"in req&&req.txOutputs){result.txOutputs=req.txOutputs.map(entry=>({...entry}))}return result}class BlockHeader{baseFeePerGas;efficiencyScore;etxEligibleSlices;etxSetRoot;evmRoot;expansionNumber;extRollupRoot;extTransactionsRoot;extraData;gasLimit;gasUsed;hash;interlinkRootHash;manifestHash;number;parentDeltaS;parentEntropy;parentHash;parentUncledS;parentUncledSubDeltaS;primeTerminus;receiptsRoot;sha3Uncles;size;thresholdCount;transactionsRoot;uncledS;utxoRoot;constructor(params){this.baseFeePerGas=params.baseFeePerGas;this.efficiencyScore=params.efficiencyScore;this.etxEligibleSlices=params.etxEligibleSlices;this.etxSetRoot=params.etxSetRoot;this.evmRoot=params.evmRoot;this.expansionNumber=params.expansionNumber;this.extRollupRoot=params.extRollupRoot;this.extTransactionsRoot=params.extTransactionsRoot;this.extraData=params.extraData;this.gasLimit=params.gasLimit;this.gasUsed=params.gasUsed;this.hash=params.hash;this.interlinkRootHash=params.interlinkRootHash;this.manifestHash=params.manifestHash;this.number=params.number;this.parentDeltaS=params.parentDeltaS;this.parentEntropy=params.parentEntropy;this.parentHash=params.parentHash;this.parentUncledS=params.parentUncledS;this.parentUncledSubDeltaS=params.parentUncledSubDeltaS;this.primeTerminus=params.primeTerminus;this.receiptsRoot=params.receiptsRoot;this.sha3Uncles=params.sha3Uncles;this.size=params.size;this.thresholdCount=params.thresholdCount;this.transactionsRoot=params.transactionsRoot;this.uncledS=params.uncledS;this.utxoRoot=params.utxoRoot}toJSON(){return{baseFeePerGas:this.baseFeePerGas,efficiencyScore:this.efficiencyScore,etxEligibleSlices:this.etxEligibleSlices,etxSetRoot:this.etxSetRoot,evmRoot:this.evmRoot,expansionNumber:this.expansionNumber,extRollupRoot:this.extRollupRoot,extTransactionsRoot:this.extTransactionsRoot,extraData:this.extraData,gasLimit:this.gasLimit,gasUsed:this.gasUsed,hash:this.hash,interlinkRootHash:this.interlinkRootHash,manifestHash:this.manifestHash,number:this.number,parentDeltaS:this.parentDeltaS,parentEntropy:this.parentEntropy,parentHash:this.parentHash,parentUncledS:this.parentUncledS,parentUncledSubDeltaS:this.parentUncledSubDeltaS,primeTerminus:this.primeTerminus,receiptsRoot:this.receiptsRoot,sha3Uncles:this.sha3Uncles,size:this.size,thresholdCount:this.thresholdCount,transactionsRoot:this.transactionsRoot,uncledS:this.uncledS,utxoRoot:this.utxoRoot}}}class WoHeader{difficulty;headerHash;location;mixHash;nonce;number;parentHash;time;txHash;constructor(params){this.difficulty=params.difficulty;this.headerHash=params.headerHash;this.location=params.location;this.mixHash=params.mixHash;this.nonce=params.nonce;this.number=params.number;this.parentHash=params.parentHash;this.time=params.time;this.txHash=params.txHash}toJSON(){return{difficulty:this.difficulty,headerHash:this.headerHash,location:this.location,mixHash:this.mixHash,nonce:this.nonce,number:this.number,parentHash:this.parentHash,time:this.time,txHash:this.txHash}}}class Block{#extTransactions;hash;header;interlinkHashes;order;size;subManifest;totalEntropy;#transactions;uncles;woHeader;provider;constructor(block,provider){this.#transactions=block.transactions.map(tx=>{if(typeof tx==="string"){return tx}if("originatingTxHash"in tx){return new ExternalTransactionResponse(tx,provider)}if("from"in tx){return new QuaiTransactionResponse(tx,provider)}return new QiTransactionResponse(tx,provider)});this.#extTransactions=block.extTransactions.map(tx=>{if(typeof tx!=="string"){return new ExternalTransactionResponse(tx,provider)}return tx});this.hash=block.hash;this.header=new BlockHeader(block.header);this.interlinkHashes=block.interlinkHashes;this.order=block.order;this.size=block.size;this.subManifest=block.subManifest;this.totalEntropy=block.totalEntropy;this.uncles=block.uncles;this.woHeader=new WoHeader(block.woHeader);this.provider=provider}get transactions(){return this.#transactions.map(tx=>{if(typeof tx==="string"){return tx}return tx.hash})}get extTransactions(){return this.#extTransactions.map(tx=>{if(typeof tx==="string"){return tx}return tx.hash})}get prefetchedTransactions(){const txs=this.#transactions.slice();if(txs.length===0){return[]}assert(typeof txs[0]==="object","transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"});return txs}get prefetchedExtTransactions(){const txs=this.#extTransactions.slice();if(txs.length===0){return[]}assert(typeof txs[0]==="object","transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"});return txs}toJSON(){const{hash,header,interlinkHashes,order,size,subManifest,totalEntropy,uncles,woHeader}=this;const transactions=this.transactions;const extTransactions=this.extTransactions;return{_type:"Block",hash:hash,header:header.toJSON(),interlinkHashes:interlinkHashes,order:order,size:toJson(size),subManifest:subManifest,totalEntropy:toJson(totalEntropy),uncles:uncles,woHeader:woHeader.toJSON(),transactions:transactions,extTransactions:extTransactions}}[Symbol.iterator](){let index=0;const txs=this.transactions;return{next:()=>{if(index{return new Log(log,provider)}));let gasPrice=BN_0$1;if(tx.effectiveGasPrice!=null){gasPrice=tx.effectiveGasPrice}else if(tx.gasPrice!=null){gasPrice=tx.gasPrice}const etxs=tx.etxs?tx.etxs.map(etx=>{const safeConvert=(value,name)=>{try{if(value!=null){return BigInt(value)}return null}catch(error){console.error(`Conversion to BigInt failed for ${name}: ${value}, error: ${error}`);return null}};return{type:etx.type,nonce:etx.nonce,gasPrice:safeConvert(etx.gasPrice,"gasPrice"),maxPriorityFeePerGas:safeConvert(etx.maxPriorityFeePerGas,"maxPriorityFeePerGas"),maxFeePerGas:safeConvert(etx.maxFeePerGas,"maxFeePerGas"),gas:safeConvert(etx.gas,"gas"),value:safeConvert(etx.value,"value"),input:etx.input,to:etx.to,accessList:etx.accessList,chainId:safeConvert(etx.chainId,"chainId"),sender:etx.sender,hash:etx.hash,isCoinbase:etx.isCoinbase,originatingTxHash:etx.originatingTxHash,etxIndex:etx.etxIndex}}):[];defineProperties(this,{provider:provider,to:tx.to,from:tx.from,contractAddress:tx.contractAddress,hash:tx.hash,index:tx.index,blockHash:tx.blockHash,blockNumber:tx.blockNumber,logsBloom:tx.logsBloom,gasUsed:tx.gasUsed,cumulativeGasUsed:tx.cumulativeGasUsed,gasPrice:gasPrice,etxs:etxs,type:tx.type,status:tx.status})}get logs(){return this.#logs}toJSON(){const{to,from,contractAddress,hash,index,blockHash,blockNumber,logsBloom,logs,status,etxs}=this;return{_type:"TransactionReceipt",blockHash:blockHash,blockNumber:blockNumber,contractAddress:contractAddress,cumulativeGasUsed:toJson(this.cumulativeGasUsed),from:from,gasPrice:toJson(this.gasPrice),gasUsed:toJson(this.gasUsed),hash:hash,index:index,logs:logs,logsBloom:logsBloom,status:status,to:to,etxs:etxs??[]}}get length(){return this.logs.length}[Symbol.iterator](){let index=0;return{next:()=>{if(index=0,"invalid startBlock","startBlock",startBlock);const tx=new ExternalTransactionResponse(this,this.provider);tx.startBlock=startBlock;return tx}}class QuaiTransactionResponse{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;maxPriorityFeePerGas;maxFeePerGas;data;value;chainId;signature;accessList;etxType;sender;originatingTxHash;startBlock;constructor(tx,provider){this.provider=provider;this.blockNumber=tx.blockNumber!=null?tx.blockNumber:null;this.blockHash=tx.blockHash!=null?tx.blockHash:null;this.hash=tx.hash;this.index=tx.index;this.type=tx.type;this.from=tx.from;this.to=tx.to||null;this.gasLimit=tx.gasLimit;this.nonce=tx.nonce;this.data=tx.data;this.value=tx.value;this.maxPriorityFeePerGas=tx.maxPriorityFeePerGas!=null?tx.maxPriorityFeePerGas:null;this.maxFeePerGas=tx.maxFeePerGas!=null?tx.maxFeePerGas:null;this.chainId=tx.chainId;this.signature=tx.signature;this.accessList=tx.accessList!=null?tx.accessList:null;this.startBlock=-1;this.etxType=tx.etxType!=null?tx.etxType:null}toJSON(){const{blockNumber,blockHash,index,hash,type,to,from,nonce,data,signature,accessList}=this;const result={_type:"TransactionReceipt",accessList:accessList,blockNumber:blockNumber,blockHash:blockHash,chainId:toJson(this.chainId),data:data,from:from,gasLimit:toJson(this.gasLimit),hash:hash,maxFeePerGas:toJson(this.maxFeePerGas),maxPriorityFeePerGas:toJson(this.maxPriorityFeePerGas),nonce:nonce,signature:signature,to:to,index:index,type:type,value:toJson(this.value)};return result}async getBlock(shard){let blockNumber=this.blockNumber;if(blockNumber==null){const tx=await this.getTransaction();if(tx){blockNumber=tx.blockNumber}}if(blockNumber==null){return null}const block=this.provider.getBlock(shard,blockNumber);if(block==null){throw new Error("TODO")}return block}async getTransaction(){const transaction=this.provider.getTransaction(this.hash);if(transaction instanceof QuaiTransactionResponse){return transaction}else{return null}}async confirmations(){const zone=zoneFromHash(this.hash);if(this.blockNumber==null){const{tx,blockNumber}=await resolveProperties({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber(toShard(zone))});if(tx==null||tx.blockNumber==null){return 0}return blockNumber-tx.blockNumber+1}const blockNumber=await this.provider.getBlockNumber(toShard(zone));return blockNumber-this.blockNumber+1}async wait(_confirms,_timeout){const confirms=_confirms==null?1:_confirms;const timeout=_timeout==null?0:_timeout;let startBlock=this.startBlock;let nextScan=-1;let stopScanning=startBlock===-1?true:false;const zone=zoneFromHash(this.hash);const checkReplacement=async()=>{if(stopScanning){return null}const{blockNumber,nonce}=await resolveProperties({blockNumber:this.provider.getBlockNumber(toShard(zone)),nonce:this.provider.getTransactionCount(this.from)});if(nonce{if(receipt==null||receipt.status!==0){return receipt}assert(false,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:receipt.to,from:receipt.from,data:""},receipt:receipt})};const receipt=await this.provider.getTransactionReceipt(this.hash);if(confirms===0){return checkReceipt(receipt)}if(receipt){if(await receipt.confirmations()>=confirms){return checkReceipt(receipt)}}else{await checkReplacement();if(confirms===0){return null}}const waiter=new Promise((resolve,reject)=>{const cancellers=[];const cancel=()=>{cancellers.forEach(c=>c())};cancellers.push(()=>{stopScanning=true});if(timeout>0){const timer=setTimeout(()=>{cancel();reject(makeError("wait for transaction timeout","TIMEOUT"))},timeout);cancellers.push(()=>{clearTimeout(timer)})}const txListener=async receipt=>{if(await receipt.confirmations()>=confirms){cancel();try{resolve(checkReceipt(receipt))}catch(error){reject(error)}}};cancellers.push(()=>{this.provider.off(this.hash,txListener)});this.provider.on(this.hash,txListener);if(startBlock>=0){const replaceListener=async()=>{try{await checkReplacement()}catch(error){if(isError(error,"TRANSACTION_REPLACED")){cancel();reject(error);return}}if(!stopScanning){this.provider.once("block",replaceListener)}};cancellers.push(()=>{this.provider.off("block",replaceListener)});this.provider.once("block",replaceListener)}});return await waiter}isMined(){return this.blockHash!=null}removedEvent(){assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});return createRemovedTransactionFilter(this)}reorderedEvent(other){assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});assert(!other||other.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});return createReorderedTransactionFilter(this,other)}replaceableTransaction(startBlock){assertArgument(Number.isInteger(startBlock)&&startBlock>=0,"invalid startBlock","startBlock",startBlock);const tx=new QuaiTransactionResponse(this,this.provider);tx.startBlock=startBlock;return tx}}class QiTransactionResponse{provider;blockNumber;blockHash;index;hash;type;chainId;signature;txInputs;txOutputs;startBlock;constructor(tx,provider){this.provider=provider;this.blockNumber=tx.blockNumber!=null?tx.blockNumber:null;this.blockHash=tx.blockHash!=null?tx.blockHash:null;this.hash=tx.hash;this.index=tx.index;this.type=tx.type;this.chainId=tx.chainId;this.signature=tx.signature;this.startBlock=-1;this.txInputs=tx.txInputs;this.txOutputs=tx.txOutputs}toJSON(){const{blockNumber,blockHash,index,hash,type,signature,txInputs,txOutputs}=this;const result={_type:"TransactionReceipt",blockNumber:blockNumber,blockHash:blockHash,chainId:toJson(this.chainId),hash:hash,signature:signature,index:index,type:type,txInputs:JSON.parse(JSON.stringify(txInputs)),txOutputs:JSON.parse(JSON.stringify(txOutputs))};return result}async getBlock(shard){let blockNumber=this.blockNumber;if(blockNumber==null){const tx=await this.getTransaction();if(tx){blockNumber=tx.blockNumber}}if(blockNumber==null){return null}const block=this.provider.getBlock(shard,blockNumber);if(block==null){throw new Error("TODO")}return block}async getTransaction(){const transaction=this.provider.getTransaction(this.hash);if(transaction instanceof QiTransactionResponse){return transaction}else{return null}}async confirmations(){const zone=zoneFromHash(this.hash);if(this.blockNumber==null){const{tx,blockNumber}=await resolveProperties({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber(toShard(zone))});if(tx==null||tx.blockNumber==null){return 0}return blockNumber-tx.blockNumber+1}const blockNumber=await this.provider.getBlockNumber(toShard(zone));return blockNumber-this.blockNumber+1}isMined(){return this.blockHash!=null}removedEvent(){assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});return createRemovedTransactionFilter(this)}reorderedEvent(other){assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});assert(!other||other.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});return createReorderedTransactionFilter(this,other)}replaceableTransaction(startBlock){assertArgument(Number.isInteger(startBlock)&&startBlock>=0,"invalid startBlock","startBlock",startBlock);const tx=new QiTransactionResponse(this,this.provider);tx.startBlock=startBlock;return tx}}function createOrphanedBlockFilter(block){return{orphan:"drop-block",hash:block.hash,number:block.number}}function createReorderedTransactionFilter(tx,other){return{orphan:"reorder-transaction",tx:tx,other:other}}function createRemovedTransactionFilter(tx){return{orphan:"drop-transaction",tx:tx}}function createRemovedLogFilter(log){return{orphan:"drop-log",log:{transactionHash:log.transactionHash,blockHash:log.blockHash,blockNumber:log.blockNumber,address:log.address,data:log.data,topics:Object.freeze(log.topics.slice()),index:log.index}}}function getZoneFromEventFilter(filter){let zone=null;if(filter.nodeLocation){zone=getZoneFromNodeLocation(filter.nodeLocation)}else if(filter.address){let address;if(Array.isArray(filter.address)){address=filter.address[0]}else{address=filter.address}const addressZone=getZoneForAddress(address);if(addressZone){zone=toZone(addressZone)}else{return null}}return zone}class EventLog extends Log{interface;fragment;args;constructor(log,iface,fragment){super(log,log.provider);const args=iface.decodeEventLog(fragment,log.data,log.topics);defineProperties(this,{args:args,fragment:fragment,interface:iface})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class UndecodedEventLog extends Log{error;constructor(log,error){super(log,log.provider);defineProperties(this,{error:error})}}class ContractTransactionReceipt extends TransactionReceipt{#iface;constructor(iface,provider,tx){super(tx,provider);this.#iface=iface}get logs(){return super.logs.map(log=>{const fragment=log.topics.length?this.#iface.getEvent(log.topics[0]):null;if(fragment){try{return new EventLog(log,this.#iface,fragment)}catch(error){return new UndecodedEventLog(log,error)}}return log})}}class ContractTransactionResponse extends QuaiTransactionResponse{#iface;constructor(iface,provider,tx){super(tx,provider);this.#iface=iface}async wait(confirms){const receipt=await super.wait(confirms);if(receipt==null){return null}return new ContractTransactionReceipt(this.#iface,this.provider,receipt)}}class ContractUnknownEventPayload extends EventPayload{log;constructor(contract,listener,filter,log){super(contract,listener,filter);defineProperties(this,{log:log})}async getBlock(shard){return await this.log.getBlock(shard)}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class ContractEventPayload extends ContractUnknownEventPayload{constructor(contract,listener,filter,fragment,_log){super(contract,listener,filter,new EventLog(_log,contract.interface,fragment));const args=contract.interface.decodeEventLog(fragment,this.log.data,this.log.topics);defineProperties(this,{args:args,fragment:fragment})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const BN_0=BigInt(0);function canCall(value){return value&&typeof value.call==="function"}function canEstimate(value){return value&&typeof value.estimateGas==="function"}function canSend(value){return value&&typeof value.sendTransaction==="function"}class PreparedTopicFilter{#filter;fragment;constructor(contract,fragment,args){defineProperties(this,{fragment:fragment});if(fragment.inputs.length{const arg=args[index];if(arg==null){return null}return param.walkAsync(args[index],(type,value)=>{if(type==="address"){if(Array.isArray(value)){return Promise.all(value.map(v=>resolveAddress(v)))}return resolveAddress(value)}return value})}));return contract.interface.encodeFilterTopics(fragment,resolvedArgs)}()}getTopicFilter(){return this.#filter}}function getRunner(value,feature){if(value==null){return null}if(typeof value[feature]==="function"){return value}if(value.provider&&typeof value.provider[feature]==="function"){return value.provider}return null}function getProvider(value){if(value==null){return null}return value.provider||null}async function copyOverrides(arg,allowed){const _overrides=Typed.dereference(arg,"overrides");assertArgument(typeof _overrides==="object","invalid overrides parameter","overrides",arg);const overrides=copyRequest(_overrides);assertArgument(!("to"in overrides)||overrides.to==null||(allowed||[]).indexOf("to")>=0,"cannot override to","overrides.to",overrides);assertArgument(!("data"in overrides)||overrides.data==null||(allowed||[]).indexOf("data")>=0,"cannot override data","overrides.data",overrides);if("from"in overrides&&overrides.from){overrides.from=await overrides.from}return overrides}async function resolveArgs(_runner,inputs,args){return await Promise.all(inputs.map((param,index)=>{return param.walkAsync(args[index],(type,value)=>{value=Typed.dereference(value,type);if(type==="address"){return resolveAddress(value)}return value})}))}function buildWrappedFallback(contract){const populateTransaction=async function(overrides){const tx=await copyOverrides(overrides,["data"]);tx.to=await contract.getAddress();validateAddress(tx.to);if(tx.from){tx.from=await resolveAddress(tx.from);validateAddress(tx.from)}const iface=contract.interface;const noValue=getBigInt(tx.value||BN_0,"overrides.value")===BN_0;const noData=(tx.data||"0x")==="0x";if(iface.fallback&&!iface.fallback.payable&&iface.receive&&!noData&&!noValue){assertArgument(false,"cannot send data to receive or send value to non-payable fallback","overrides",overrides)}assertArgument(iface.fallback||noData,"cannot send data to receive-only contract","overrides.data",tx.data);const payable=iface.receive||iface.fallback&&iface.fallback.payable;assertArgument(payable||noValue,"cannot send value to non-payable fallback","overrides.value",tx.value);assertArgument(iface.fallback||noData,"cannot send data to receive-only contract","overrides.data",tx.data);return tx};const staticCall=async function(overrides){const runner=getRunner(contract.runner,"call");assert(canCall(runner),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const tx=await populateTransaction(overrides);try{return await runner.call(tx)}catch(error){if(isCallException(error)&&error.data){throw contract.interface.makeError(error.data,tx)}throw error}};const send=async function(overrides){const runner=contract.runner;assert(canSend(runner),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const tx=await runner.sendTransaction(await populateTransaction(overrides));const provider=getProvider(contract.runner);return new ContractTransactionResponse(contract.interface,provider,tx)};const estimateGas=async function(overrides){const runner=getRunner(contract.runner,"estimateGas");assert(canEstimate(runner),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"});return await runner.estimateGas(await populateTransaction(overrides))};const method=async overrides=>{return await send(overrides)};defineProperties(method,{_contract:contract,estimateGas:estimateGas,populateTransaction:populateTransaction,send:send,staticCall:staticCall});return method}function buildWrappedMethod(contract,key){const getFragment=function(...args){const fragment=contract.interface.getFunction(key,args);assert(fragment,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:key,args:args}});return fragment};const populateTransaction=async function(...args){const fragment=getFragment(...args);let overrides;if(fragment.inputs.length+1===args.length){overrides=await copyOverrides(args.pop());const resolvedArgs=await resolveArgs(contract.runner,fragment.inputs,args);return Object.assign({},overrides,await resolveProperties({to:contract.getAddress(),data:contract.interface.encodeFunctionData(fragment,resolvedArgs)}))}if(fragment.inputs.length!==args.length){throw new Error("internal error: fragment inputs doesn't match arguments; should not happen")}const resolvedArgs=await resolveArgs(contract.runner,fragment.inputs,args);return await resolveProperties({to:contract.getAddress(),from:args.pop()?.from,data:contract.interface.encodeFunctionData(fragment,resolvedArgs)})};const staticCall=async function(...args){const result=await staticCallResult(...args);if(result.length===1){return result[0]}return result};const send=async function(...args){const runner=contract.runner;assert(canSend(runner),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const pop=await populateTransaction(...args);if(!pop.from&&"address"in runner&&typeof runner.address==="string"){pop.from=await resolveAddress(runner.address)}const tx=await runner.sendTransaction(await pop);const provider=getProvider(contract.runner);return new ContractTransactionResponse(contract.interface,provider,tx)};const estimateGas=async function(...args){const runner=getRunner(contract.runner,"estimateGas");assert(canEstimate(runner),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"});return await runner.estimateGas(await populateTransaction(...args))};const staticCallResult=async function(...args){const runner=getRunner(contract.runner,"call");assert(canCall(runner),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const tx=await populateTransaction(...args);if(!tx.from&&"address"in runner&&typeof runner.address==="string"){tx.from=await resolveAddress(runner.address)}let result="0x";try{result=await runner.call(tx)}catch(error){if(isCallException(error)&&error.data){throw contract.interface.makeError(error.data,tx)}throw error}const fragment=getFragment(...args);return contract.interface.decodeFunctionResult(fragment,result)};const method=async(...args)=>{const fragment=getFragment(...args);if(fragment.constant){return await staticCall(...args)}return await send(...args)};defineProperties(method,{name:contract.interface.getFunctionName(key),_contract:contract,_key:key,getFragment:getFragment,estimateGas:estimateGas,populateTransaction:populateTransaction,send:send,staticCall:staticCall,staticCallResult:staticCallResult});Object.defineProperty(method,"fragment",{configurable:false,enumerable:true,get:()=>{const fragment=contract.interface.getFunction(key);assert(fragment,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:key}});return fragment}});return method}function buildWrappedEvent(contract,key){const getFragment=function(...args){const fragment=contract.interface.getEvent(key,args);assert(fragment,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:key,args:args}});return fragment};const method=function(...args){return new PreparedTopicFilter(contract,getFragment(...args),args)};defineProperties(method,{name:contract.interface.getEventName(key),_contract:contract,_key:key,getFragment:getFragment});Object.defineProperty(method,"fragment",{configurable:false,enumerable:true,get:()=>{const fragment=contract.interface.getEvent(key);assert(fragment,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:key}});return fragment}});return method}const internal=Symbol.for("_quaisInternal_contract");const internalValues=new WeakMap;function setInternal(contract,values){internalValues.set(contract[internal],values)}function getInternal(contract){return internalValues.get(contract[internal])}function isDeferred(value){return value&&typeof value==="object"&&"getTopicFilter"in value&&typeof value.getTopicFilter==="function"&&value.fragment}async function getSubInfo(contract,event){let topics;let fragment=null;if(Array.isArray(event)){const topicHashify=function(name){if(isHexString(name,32)){return name}const fragment=contract.interface.getEvent(name);assertArgument(fragment,"unknown fragment","name",name);return fragment.topicHash};topics=event.map(e=>{if(e==null){return null}if(Array.isArray(e)){return e.map(topicHashify)}return topicHashify(e)})}else if(event==="*"){topics=[null]}else if(typeof event==="string"){if(isHexString(event,32)){topics=[event]}else{fragment=contract.interface.getEvent(event);assertArgument(fragment,"unknown fragment","event",event);topics=[fragment.topicHash]}}else if(isDeferred(event)){topics=await event.getTopicFilter()}else if(event&&"fragment"in event){fragment=event.fragment;topics=[fragment.topicHash]}else{assertArgument(false,"unknown event name","event",event)}topics=topics.map(t=>{if(t==null){return null}if(Array.isArray(t)){const items=Array.from(new Set(t.map(t=>t.toLowerCase())).values());if(items.length===1){return items[0]}items.sort();return items}return t.toLowerCase()});const tag=topics.map(t=>{if(t==null){return"null"}if(Array.isArray(t)){return t.join("|")}return t}).join("&");return{fragment:fragment,tag:tag,topics:topics}}async function hasSub(contract,event){const{subs}=getInternal(contract);return subs.get((await getSubInfo(contract,event)).tag)||null}async function getSub(contract,operation,event){const provider=getProvider(contract.runner);assert(provider,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:operation});const{fragment,tag,topics}=await getSubInfo(contract,event);const{addr,subs}=getInternal(contract);let sub=subs.get(tag);if(!sub){const address=addr?addr:contract;const filter={address:address,topics:topics};const listener=log=>{let foundFragment=fragment;if(foundFragment==null){try{foundFragment=contract.interface.getEvent(log.topics[0])}catch(error){}}if(foundFragment){const _foundFragment=foundFragment;const args=fragment?contract.interface.decodeEventLog(fragment,log.data,log.topics):[];emit(contract,event,args,listener=>{return new ContractEventPayload(contract,listener,event,_foundFragment,log)})}else{emit(contract,event,[],listener=>{return new ContractUnknownEventPayload(contract,listener,event,log)})}};const zone=getZoneForAddress(await resolveAddress(address));let starting=[];const start=()=>{if(starting.length){return}starting.push(provider.on(filter,listener,zone))};const stop=async()=>{if(starting.length==0){return}const started=starting;starting=[];await Promise.all(started);provider.off(filter,listener,zone)};sub={tag:tag,listeners:[],start:start,stop:stop};subs.set(tag,sub)}return sub}let lastEmit=Promise.resolve();async function _emit(contract,event,args,payloadFunc){await lastEmit;const sub=await hasSub(contract,event);if(!sub){return false}const count=sub.listeners.length;sub.listeners=sub.listeners.filter(({listener,once})=>{const passArgs=Array.from(args);if(payloadFunc){passArgs.push(payloadFunc(once?null:listener))}try{listener.call(contract,...passArgs)}catch(error){}return!once});if(sub.listeners.length===0){sub.stop();getInternal(contract).subs.delete(sub.tag)}return count>0}async function emit(contract,event,args,payloadFunc){try{await lastEmit}catch(error){}const resultPromise=_emit(contract,event,args,payloadFunc);lastEmit=resultPromise;return await resultPromise}const passProperties=["then"];class BaseContract{target;interface;runner;filters;[internal];fallback;constructor(target,abi,runner,_deployTx){assertArgument(typeof target==="string"||isAddressable(target),"invalid value for Contract target","target",target);if(runner==null){runner=null}const iface=Interface.from(abi);defineProperties(this,{target:target,runner:runner,interface:iface});Object.defineProperty(this,internal,{value:{}});let addrPromise;let addr=null;let deployTx=null;if(_deployTx){const provider=getProvider(runner);deployTx=new ContractTransactionResponse(this.interface,provider,_deployTx)}const subs=new Map;if(typeof target==="string"){addr=target;addrPromise=Promise.resolve(target)}else{addrPromise=target.getAddress().then(addr=>{if(addr==null){throw new Error("TODO")}getInternal(this).addr=addr;return addr})}setInternal(this,{addrPromise:addrPromise,addr:addr,deployTx:deployTx,subs:subs});const filters=new Proxy({},{get:(target,prop,receiver)=>{if(typeof prop==="symbol"||passProperties.indexOf(prop)>=0){return Reflect.get(target,prop,receiver)}try{return this.getEvent(prop)}catch(error){if(!isError(error,"INVALID_ARGUMENT")||error.argument!=="key"){throw error}}return undefined},has:(target,prop)=>{if(passProperties.indexOf(prop)>=0){return Reflect.has(target,prop)}return Reflect.has(target,prop)||this.interface.hasEvent(String(prop))}});defineProperties(this,{filters:filters});defineProperties(this,{fallback:iface.receive||iface.fallback?buildWrappedFallback(this):null});return new Proxy(this,{get:(target,prop,receiver)=>{if(typeof prop==="symbol"||prop in target||passProperties.indexOf(prop)>=0){return Reflect.get(target,prop,receiver)}try{return target.getFunction(prop)}catch(error){if(!isError(error,"INVALID_ARGUMENT")||error.argument!=="key"){throw error}}return undefined},has:(target,prop)=>{if(typeof prop==="symbol"||prop in target||passProperties.indexOf(prop)>=0){return Reflect.has(target,prop)}return target.interface.hasFunction(prop)}})}connect(runner){return new BaseContract(this.target,this.interface,runner)}attach(target){return new BaseContract(target,this.interface,this.runner)}async getAddress(){return await getInternal(this).addrPromise}async getDeployedCode(){const provider=getProvider(this.runner);assert(provider,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const code=await provider.getCode(await this.getAddress());if(code==="0x"){return null}return code}async waitForDeployment(){const deployTx=this.deploymentTransaction();if(deployTx){await deployTx.wait();return this}const code=await this.getDeployedCode();if(code!=null){return this}const provider=getProvider(this.runner);assert(provider!=null,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"});return new Promise((resolve,reject)=>{const checkCode=async()=>{try{const code=await this.getDeployedCode();if(code!=null){return resolve(this)}provider.once("block",checkCode)}catch(error){reject(error)}};checkCode()})}deploymentTransaction(){return getInternal(this).deployTx}getFunction(key){if(typeof key!=="string"){key=key.format()}const func=buildWrappedMethod(this,key);return func}getEvent(key){if(typeof key!=="string"){key=key.format()}return buildWrappedEvent(this,key)}async queryTransaction(hash){throw new Error("@TODO")}async queryFilter(event,fromBlock,toBlock){if(fromBlock==null){fromBlock=0}if(toBlock==null){toBlock="latest"}const{addr,addrPromise}=getInternal(this);const address=addr?addr:await addrPromise;const{fragment,topics}=await getSubInfo(this,event);const zone=getZoneForAddress(address);const filter={address:address,topics:topics,fromBlock:fromBlock,toBlock:toBlock,nodeLocation:getNodeLocationFromZone(zone)};const provider=getProvider(this.runner);assert(provider,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"});return(await provider.getLogs(filter)).map(log=>{let foundFragment=fragment;if(foundFragment==null){try{foundFragment=this.interface.getEvent(log.topics[0])}catch(error){}}if(foundFragment){try{return new EventLog(log,this.interface,foundFragment)}catch(error){return new UndecodedEventLog(log,error)}}return new Log(log,provider)})}async on(event,listener){const sub=await getSub(this,"on",event);sub.listeners.push({listener:listener,once:false});sub.start();return this}async once(event,listener){const sub=await getSub(this,"once",event);sub.listeners.push({listener:listener,once:true});sub.start();return this}async emit(event,...args){return await emit(this,event,args,null)}async listenerCount(event){if(event){const sub=await hasSub(this,event);if(!sub){return 0}return sub.listeners.length}const{subs}=getInternal(this);let total=0;for(const{listeners}of subs.values()){total+=listeners.length}return total}async listeners(event){if(event){const sub=await hasSub(this,event);if(!sub){return[]}return sub.listeners.map(({listener})=>listener)}const{subs}=getInternal(this);let result=[];for(const{listeners}of subs.values()){result=result.concat(listeners.map(({listener})=>listener))}return result}async off(event,listener){const sub=await hasSub(this,event);if(!sub){return this}if(listener){const index=sub.listeners.map(({listener})=>listener).indexOf(listener);if(index>=0){sub.listeners.splice(index,1)}}if(listener==null||sub.listeners.length===0){sub.stop();getInternal(this).subs.delete(sub.tag)}return this}async removeAllListeners(event){if(event){const sub=await hasSub(this,event);if(!sub){return this}sub.stop();getInternal(this).subs.delete(sub.tag)}else{const{subs}=getInternal(this);for(const{tag,stop}of subs.values()){stop();subs.delete(tag)}}return this}async addListener(event,listener){return await this.on(event,listener)}async removeListener(event,listener){return await this.off(event,listener)}static buildClass(abi){class CustomContract extends BaseContract{constructor(address,runner=null){super(address,abi,runner)}}return CustomContract}static from(target,abi,runner){if(runner==null){runner=null}const contract=new this(target,abi,runner);return contract}}function _ContractBase(){return BaseContract}class Contract extends _ContractBase(){}function checkProvider(signer,operation){if(signer.provider){return signer.provider}assert(false,"missing provider","UNSUPPORTED_OPERATION",{operation:operation})}async function populate(signer,tx){const pop=copyRequest(tx);if(pop.to!=null){pop.to=resolveAddress(pop.to);validateAddress(pop.to)}if(pop.from!=null){const from=pop.from;pop.from=await Promise.all([signer.getAddress(),resolveAddress(from)]).then(([address,from])=>{assertArgument(address.toLowerCase()===from.toLowerCase(),"transaction from mismatch","tx.from",from);return address})}else{pop.from=await signer.getAddress()}validateAddress(pop.from);return await resolveProperties(pop)}class AbstractSigner{provider;constructor(provider){defineProperties(this,{provider:provider||null})}_getAddress(address){return resolveAddress(address)}async zoneFromAddress(_address){const address=this._getAddress(_address);return toZone((await address).slice(0,4))}async getNonce(blockTag){return checkProvider(this,"getTransactionCount").getTransactionCount(await this.getAddress(),blockTag)}async populateCall(tx){const pop=await populate(this,tx);return pop}async populateQuaiTransaction(tx){const provider=checkProvider(this,"populateTransaction");const zone=await this.zoneFromAddress(tx.from);const pop=await populate(this,tx);if(pop.type==null){pop.type=await getTxType(pop.from??null,pop.to??null)}if(pop.nonce==null){pop.nonce=await this.getNonce("pending")}if(pop.type==null){pop.type=getTxType(pop.from??null,pop.to??null)}if(pop.gasLimit==null){if(pop.type==0)pop.gasLimit=await this.estimateGas(pop);else{const temp=pop.to;pop.to="0x0000000000000000000000000000000000000000";pop.gasLimit=getBigInt(2*Number(await this.estimateGas(pop)));pop.to=temp}}const network=await this.provider.getNetwork();if(pop.chainId!=null){const chainId=getBigInt(pop.chainId);assertArgument(chainId===network.chainId,"transaction chainId mismatch","tx.chainId",zone)}else{pop.chainId=network.chainId}if(pop.maxFeePerGas==null||pop.maxPriorityFeePerGas==null){const feeData=await provider.getFeeData(zone);if(pop.maxFeePerGas==null){pop.maxFeePerGas=feeData.maxFeePerGas}if(pop.maxPriorityFeePerGas==null){pop.maxPriorityFeePerGas=feeData.maxPriorityFeePerGas||10n}}return await resolveProperties(pop)}async estimateGas(tx){return checkProvider(this,"estimateGas").estimateGas(await this.populateCall(tx))}async call(tx){return checkProvider(this,"call").call(await this.populateCall(tx))}async sendTransaction(tx){const provider=checkProvider(this,"sendTransaction");const zone=await this.zoneFromAddress(addressFromTransactionRequest(tx));const pop=await this.populateQuaiTransaction(tx);const txObj=QuaiTransaction.from(pop);const sender=await this.getAddress();const signedTx=await this.signTransaction(txObj);return await provider.broadcastTransaction(zone,signedTx,sender)}}class VoidSigner extends AbstractSigner{address;constructor(address,provider){super(provider);defineProperties(this,{address:address})}async getAddress(){return this.address}connect(provider){return new VoidSigner(this.address,provider)}#throwUnsupported(suffix,operation){assert(false,`VoidSigner cannot sign ${suffix}`,"UNSUPPORTED_OPERATION",{operation:operation})}async signTransaction(tx){this.#throwUnsupported("transactions","signTransaction")}async signMessage(message){this.#throwUnsupported("messages","signMessage")}async signTypedData(domain,types,value){this.#throwUnsupported("typed-data","signTypedData")}}class BaseWallet extends AbstractSigner{#address;#signingKey;constructor(privateKey,provider){super(provider);assertArgument(privateKey&&typeof privateKey.sign==="function","invalid private key","privateKey","[ REDACTED ]");this.#signingKey=privateKey;this.#address=computeAddress(this.signingKey.publicKey)}get address(){return this.#address}get signingKey(){return this.#signingKey}get privateKey(){return this.signingKey.privateKey}async getAddress(_zone){return this.#address}connect(provider){return new BaseWallet(this.#signingKey,provider)}async signTransaction(tx){const{to,from}=await resolveProperties({to:tx.to?resolveAddress(tx.to):undefined,from:tx.from?resolveAddress(tx.from):undefined});if(to!==undefined){validateAddress(to);tx.to=to}if(from!==undefined){assertArgument(getAddress(from)===this.#address,"transaction from address mismatch","tx.from",from)}else{tx.from=this.#address}const btx=QuaiTransaction.from(tx);const digest=keccak256(btx.unsignedSerialized);btx.signature=this.signingKey.sign(digest);return btx.serialized}async signMessage(message){return this.signMessageSync(message)}signMessageSync(message){return this.signingKey.sign(hashMessage(message)).serialized}async signTypedData(domain,types,value){return this.signingKey.sign(TypedDataEncoder.hash(domain,types,value)).serialized}}const subsChrs=" !#$%&'()*+,-./<=>?@[]^_`{|}~";const Word=/^[a-z]*$/i;function unfold(words,sep){let initial=97;return words.reduce((accum,word)=>{if(word===sep){initial++}else if(word.match(Word)){accum.push(String.fromCharCode(initial)+word)}else{initial=97;accum.push(word)}return accum},[])}function decode(data,subs){for(let i=subsChrs.length-1;i>=0;i--){data=data.split(subsChrs[i]).join(subs.substring(2*i,2*i+2))}const clumps=[];const leftover=data.replace(/(:|([0-9])|([A-Z][a-z]*))/g,(all,item,semi,word)=>{if(semi){for(let i=parseInt(semi);i>=0;i--){clumps.push(";")}}else{clumps.push(item.toLowerCase())}return""});if(leftover){throw new Error(`leftovers: ${JSON.stringify(leftover)}`)}return unfold(unfold(clumps,";"),":")}function decodeOwl(data){assertArgument(data[0]==="0","unsupported auwl data","data",data);return decode(data.substring(1+2*subsChrs.length),data.substring(1,1+2*subsChrs.length))}class Wordlist{locale;constructor(locale){defineProperties(this,{locale:locale})}split(phrase){return phrase.toLowerCase().split(/\s+/g)}join(words){return words.join(" ")}}class WordlistOwl extends Wordlist{#data;#checksum;constructor(locale,data,checksum){super(locale);this.#data=data;this.#checksum=checksum;this.#words=null}get _data(){return this.#data}_decodeWords(){return decodeOwl(this.#data)}#words;#loadWords(){if(this.#words==null){const words=this._decodeWords();const checksum=id(words.join("\n")+"\n");if(checksum!==this.#checksum){throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`)}this.#words=words}return this.#words}getWord(index){const words=this.#loadWords();assertArgument(index>=0&&index=12&&words.length<=24,"invalid mnemonic length","mnemonic","[ REDACTED ]");const entropy=new Uint8Array(Math.ceil(11*words.length/8));let offset=0;for(let i=0;i=0,`invalid mnemonic word at index ${i}`,"mnemonic","[ REDACTED ]");for(let bit=0;bit<11;bit++){if(index&1<<10-bit){entropy[offset>>3]|=1<<7-offset%8}offset++}}const entropyBits=32*words.length/3;const checksumBits=words.length/3;const checksumMask=getUpperMask(checksumBits);const checksum=getBytes(sha256(entropy.slice(0,entropyBits/8)))[0]&checksumMask;assertArgument(checksum===(entropy[entropy.length-1]&checksumMask),"invalid mnemonic checksum","mnemonic","[ REDACTED ]");return hexlify(entropy.slice(0,entropyBits/8))}function entropyToMnemonic(entropy,wordlist){assertArgument(entropy.length%4===0&&entropy.length>=16&&entropy.length<=32,"invalid entropy size","entropy","[ REDACTED ]");if(wordlist==null){wordlist=LangEn.wordlist()}const indices=[0];let remainingBits=11;for(let i=0;i8){indices[indices.length-1]<<=8;indices[indices.length-1]|=entropy[i];remainingBits-=8}else{indices[indices.length-1]<<=remainingBits;indices[indices.length-1]|=entropy[i]>>8-remainingBits;indices.push(entropy[i]&getLowerMask(8-remainingBits));remainingBits+=3}}const checksumBits=entropy.length/4;const checksum=parseInt(sha256(entropy).substring(2,4),16)&getUpperMask(checksumBits);indices[indices.length-1]<<=checksumBits;indices[indices.length-1]|=checksum>>8-checksumBits;return wordlist.join(indices.map(index=>wordlist.getWord(index)))}const _guard$2={};class Mnemonic{phrase;password;wordlist;entropy;constructor(guard,entropy,phrase,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}assertPrivate(guard,_guard$2,"Mnemonic");defineProperties(this,{phrase:phrase,password:password,wordlist:wordlist,entropy:entropy})}computeSeed(){const salt=toUtf8Bytes("mnemonic"+this.password,"NFKD");return pbkdf2(toUtf8Bytes(this.phrase,"NFKD"),salt,2048,64,"sha512")}static fromPhrase(phrase,password,wordlist){if(wordlist==null){wordlist=LangEn.wordlist()}if(password==null){password=""}const entropy=mnemonicToEntropy(phrase,wordlist);phrase=entropyToMnemonic(getBytes(entropy),wordlist);return new Mnemonic(_guard$2,entropy,phrase,password,wordlist)}static fromEntropy(_entropy,password,wordlist){if(wordlist==null){wordlist=LangEn.wordlist()}if(password==null){password=""}const entropy=getBytes(_entropy,"entropy");const phrase=entropyToMnemonic(entropy,wordlist);return new Mnemonic(_guard$2,hexlify(entropy),phrase,password,wordlist)}static entropyToPhrase(_entropy,wordlist){const entropy=getBytes(_entropy,"entropy");return entropyToMnemonic(entropy,wordlist)}static phraseToEntropy(phrase,wordlist){return mnemonicToEntropy(phrase,wordlist)}static isValidMnemonic(phrase,wordlist){try{mnemonicToEntropy(phrase,wordlist);return true}catch(error){}return false}}var __classPrivateFieldGet$1=__$G&&__$G.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var __classPrivateFieldSet$1=__$G&&__$G.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var _AES_key,_AES_Kd,_AES_Ke;const numberOfRounds={16:10,24:12,32:14};const rcon=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145];const S=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22];const Si=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125];const T1=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986];const T2=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766];const T3=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126];const T4=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436];const T5=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890];const T6=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935];const T7=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600];const T8=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480];const U1=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795];const U2=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855];const U3=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150];const U4=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function convertToInt32(bytes){const result=[];for(let i=0;i>2;__classPrivateFieldGet$1(this,_AES_Ke,"f")[index][i%4]=tk[i];__classPrivateFieldGet$1(this,_AES_Kd,"f")[rounds-index][i%4]=tk[i]}let rconpointer=0;let t=KC,tt;while(t>16&255]<<24^S[tt>>8&255]<<16^S[tt&255]<<8^S[tt>>24&255]^rcon[rconpointer]<<24;rconpointer+=1;if(KC!=8){for(let i=1;i>8&255]<<8^S[tt>>16&255]<<16^S[tt>>24&255]<<24;for(let i=KC/2+1;i>2;c=t%4;__classPrivateFieldGet$1(this,_AES_Ke,"f")[r][c]=tk[i];__classPrivateFieldGet$1(this,_AES_Kd,"f")[rounds-r][c]=tk[i++];t++}}for(let r=1;r>24&255]^U2[tt>>16&255]^U3[tt>>8&255]^U4[tt&255]}}}encrypt(plaintext){if(plaintext.length!=16){throw new TypeError("invalid plaintext size (must be 16 bytes)")}const rounds=__classPrivateFieldGet$1(this,_AES_Ke,"f").length-1;const a=[0,0,0,0];let t=convertToInt32(plaintext);for(let i=0;i<4;i++){t[i]^=__classPrivateFieldGet$1(this,_AES_Ke,"f")[0][i]}for(let r=1;r>24&255]^T2[t[(i+1)%4]>>16&255]^T3[t[(i+2)%4]>>8&255]^T4[t[(i+3)%4]&255]^__classPrivateFieldGet$1(this,_AES_Ke,"f")[r][i]}t=a.slice()}const result=new Uint8Array(16);let tt=0;for(let i=0;i<4;i++){tt=__classPrivateFieldGet$1(this,_AES_Ke,"f")[rounds][i];result[4*i]=(S[t[i]>>24&255]^tt>>24)&255;result[4*i+1]=(S[t[(i+1)%4]>>16&255]^tt>>16)&255;result[4*i+2]=(S[t[(i+2)%4]>>8&255]^tt>>8)&255;result[4*i+3]=(S[t[(i+3)%4]&255]^tt)&255}return result}decrypt(ciphertext){if(ciphertext.length!=16){throw new TypeError("invalid ciphertext size (must be 16 bytes)")}const rounds=__classPrivateFieldGet$1(this,_AES_Kd,"f").length-1;const a=[0,0,0,0];let t=convertToInt32(ciphertext);for(let i=0;i<4;i++){t[i]^=__classPrivateFieldGet$1(this,_AES_Kd,"f")[0][i]}for(let r=1;r>24&255]^T6[t[(i+3)%4]>>16&255]^T7[t[(i+2)%4]>>8&255]^T8[t[(i+1)%4]&255]^__classPrivateFieldGet$1(this,_AES_Kd,"f")[r][i]}t=a.slice()}const result=new Uint8Array(16);let tt=0;for(let i=0;i<4;i++){tt=__classPrivateFieldGet$1(this,_AES_Kd,"f")[rounds][i];result[4*i]=(Si[t[i]>>24&255]^tt>>24)&255;result[4*i+1]=(Si[t[(i+3)%4]>>16&255]^tt>>16)&255;result[4*i+2]=(Si[t[(i+2)%4]>>8&255]^tt>>8)&255;result[4*i+3]=(Si[t[(i+1)%4]&255]^tt)&255}return result}}_AES_key=new WeakMap,_AES_Kd=new WeakMap,_AES_Ke=new WeakMap;class ModeOfOperation{constructor(name,key,cls){if(cls&&!(this instanceof cls)){throw new Error(`${name} must be instantiated with "new"`)}Object.defineProperties(this,{aes:{enumerable:true,value:new AES(key)},name:{enumerable:true,value:name}})}}var __classPrivateFieldSet=__$G&&__$G.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var __classPrivateFieldGet=__$G&&__$G.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _CTR_remaining,_CTR_remainingIndex,_CTR_counter;class CTR extends ModeOfOperation{constructor(key,initialValue){super("CTR",key,CTR);_CTR_remaining.set(this,void 0);_CTR_remainingIndex.set(this,void 0);_CTR_counter.set(this,void 0);__classPrivateFieldSet(this,_CTR_counter,new Uint8Array(16),"f");__classPrivateFieldGet(this,_CTR_counter,"f").fill(0);__classPrivateFieldSet(this,_CTR_remaining,__classPrivateFieldGet(this,_CTR_counter,"f"),"f");__classPrivateFieldSet(this,_CTR_remainingIndex,16,"f");if(initialValue==null){initialValue=1}if(typeof initialValue==="number"){this.setCounterValue(initialValue)}else{this.setCounterBytes(initialValue)}}get counter(){return new Uint8Array(__classPrivateFieldGet(this,_CTR_counter,"f"))}setCounterValue(value){if(!Number.isInteger(value)||value<0||value>Number.MAX_SAFE_INTEGER){throw new TypeError("invalid counter initial integer value")}for(let index=15;index>=0;--index){__classPrivateFieldGet(this,_CTR_counter,"f")[index]=value%256;value=Math.floor(value/256)}}setCounterBytes(value){if(value.length!==16){throw new TypeError("invalid counter initial Uint8Array value length")}__classPrivateFieldGet(this,_CTR_counter,"f").set(value)}increment(){for(let i=15;i>=0;i--){if(__classPrivateFieldGet(this,_CTR_counter,"f")[i]===255){__classPrivateFieldGet(this,_CTR_counter,"f")[i]=0}else{__classPrivateFieldGet(this,_CTR_counter,"f")[i]++;break}}}encrypt(plaintext){var _a,_b;const crypttext=new Uint8Array(plaintext);for(let i=0;i0&&(N&N-1)===0,"invalid kdf.N","kdf.N",N);assertArgument(r>0&&p>0,"invalid kdf","kdf",kdf);const dkLen=spelunk(data,"crypto.kdfparams.dklen:int!");assertArgument(dkLen===32,"invalid kdf.dklen","kdf.dflen",dkLen);return{name:"scrypt",salt:salt,N:N,r:r,p:p,dkLen:64}}else if(kdf.toLowerCase()==="pbkdf2"){const salt=spelunk(data,"crypto.kdfparams.salt:data!");const prf=spelunk(data,"crypto.kdfparams.prf:string!");const algorithm=prf.split("-").pop();assertArgument(algorithm==="sha256"||algorithm==="sha512","invalid kdf.pdf","kdf.pdf",prf);const count=spelunk(data,"crypto.kdfparams.c:int!");const dkLen=spelunk(data,"crypto.kdfparams.dklen:int!");assertArgument(dkLen===32,"invalid kdf.dklen","kdf.dklen",dkLen);return{name:"pbkdf2",salt:salt,count:count,dkLen:dkLen,algorithm:algorithm}}}assertArgument(false,"unsupported key-derivation function","kdf",kdf)}function decryptKeystoreJsonSync(json,_password){const data=JSON.parse(json);const password=getPassword(_password);const params=getDecryptKdfParams(data);if(params.name==="pbkdf2"){const{salt,count,dkLen,algorithm}=params;const key=pbkdf2(password,salt,count,dkLen,algorithm);return getAccount(data,key)}assert(params.name==="scrypt","cannot be reached","UNKNOWN_ERROR",{params:params});const{salt,N,r,p,dkLen}=params;const key=scryptSync(password,salt,N,r,p,dkLen);return getAccount(data,key)}function stall$1(duration){return new Promise(resolve=>{setTimeout(()=>{resolve()},duration)})}async function decryptKeystoreJson(json,_password,progress){const data=JSON.parse(json);const password=getPassword(_password);const params=getDecryptKdfParams(data);if(params.name==="pbkdf2"){if(progress){progress(0);await stall$1(0)}const{salt,count,dkLen,algorithm}=params;const key=pbkdf2(password,salt,count,dkLen,algorithm);if(progress){progress(1);await stall$1(0)}return getAccount(data,key)}assert(params.name==="scrypt","cannot be reached","UNKNOWN_ERROR",{params:params});const{salt,N,r,p,dkLen}=params;const key=await scrypt(password,salt,N,r,p,dkLen,progress);return getAccount(data,key)}function getEncryptKdfParams(options){const salt=options.salt!=null?getBytes(options.salt,"options.salt"):randomBytes(32);let N=1<<17,r=8,p=1;if(options.scrypt){if(options.scrypt.N){N=options.scrypt.N}if(options.scrypt.r){r=options.scrypt.r}if(options.scrypt.p){p=options.scrypt.p}}assertArgument(typeof N==="number"&&N>0&&Number.isSafeInteger(N)&&(BigInt(N)&BigInt(N-1))===BigInt(0),"invalid scrypt N parameter","options.N",N);assertArgument(typeof r==="number"&&r>0&&Number.isSafeInteger(r),"invalid scrypt r parameter","options.r",r);assertArgument(typeof p==="number"&&p>0&&Number.isSafeInteger(p),"invalid scrypt p parameter","options.p",p);return{name:"scrypt",dkLen:32,salt:salt,N:N,r:r,p:p}}function _encryptKeystore(key,kdf,account,options){const privateKey=getBytes(account.privateKey,"privateKey");const iv=options.iv!=null?getBytes(options.iv,"options.iv"):randomBytes(16);assertArgument(iv.length===16,"invalid options.iv length","options.iv",options.iv);const uuidRandom=options.uuid!=null?getBytes(options.uuid,"options.uuid"):randomBytes(16);assertArgument(uuidRandom.length===16,"invalid options.uuid length","options.uuid",options.iv);const derivedKey=key.slice(0,16);const macPrefix=key.slice(16,32);const aesCtr=new CTR(derivedKey,iv);const ciphertext=getBytes(aesCtr.encrypt(privateKey));const mac=keccak256(concat([macPrefix,ciphertext]));const data={address:account.address.substring(2).toLowerCase(),id:uuidV4(uuidRandom),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:hexlify(iv).substring(2)},ciphertext:hexlify(ciphertext).substring(2),kdf:"scrypt",kdfparams:{salt:hexlify(kdf.salt).substring(2),n:kdf.N,dklen:32,p:kdf.p,r:kdf.r},mac:mac.substring(2)}};if(account.mnemonic){const client=options.client!=null?options.client:`quais/${version}`;const path=account.mnemonic.path||defaultPath;const locale=account.mnemonic.locale||"en";const mnemonicKey=key.slice(32,64);const entropy=getBytes(account.mnemonic.entropy,"account.mnemonic.entropy");const mnemonicIv=randomBytes(16);const mnemonicAesCtr=new CTR(mnemonicKey,mnemonicIv);const mnemonicCiphertext=getBytes(mnemonicAesCtr.encrypt(entropy));const now=new Date;const timestamp=now.getUTCFullYear()+"-"+zpad$1(now.getUTCMonth()+1,2)+"-"+zpad$1(now.getUTCDate(),2)+"T"+zpad$1(now.getUTCHours(),2)+"-"+zpad$1(now.getUTCMinutes(),2)+"-"+zpad$1(now.getUTCSeconds(),2)+".0Z";const gethFilename="UTC--"+timestamp+"--"+data.address;data["x-quais"]={client:client,gethFilename:gethFilename,path:path,locale:locale,mnemonicCounter:hexlify(mnemonicIv).substring(2),mnemonicCiphertext:hexlify(mnemonicCiphertext).substring(2),version:"0.1"}}return JSON.stringify(data)}function encryptKeystoreJsonSync(account,password,options){if(options==null){options={}}const passwordBytes=getPassword(password);const kdf=getEncryptKdfParams(options);const key=scryptSync(passwordBytes,kdf.salt,kdf.N,kdf.r,kdf.p,64);return _encryptKeystore(getBytes(key),kdf,account,options)}async function encryptKeystoreJson(account,password,options){if(options==null){options={}}const passwordBytes=getPassword(password);const kdf=getEncryptKdfParams(options);const key=await scrypt(passwordBytes,kdf.salt,kdf.N,kdf.r,kdf.p,64,options.progressCallback);return _encryptKeystore(getBytes(key),kdf,account,options)}const MasterSecret=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]);const HardenedBit=2147483648;const N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const Nibbles="0123456789abcdef";function zpad(value,length){let result="";while(value){result=Nibbles[value%16]+result;value=Math.trunc(value/16)}while(result.length=0;i-=8){data[33+(i>>3)]=index>>24-i&255}const I=getBytes(computeHmac("sha512",chainCode,data));return{IL:I.slice(0,32),IR:I.slice(32)}}function derivePath(node,path){const components=path.split("/");assertArgument(components.length>0,"invalid path","path",path);if(components[0]==="m"){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);components.shift()}let result=node;for(let i=0;i=16&&seed.length<=64,"invalid seed","seed","[REDACTED]");const I=getBytes(computeHmac("sha512",MasterSecret,seed));const signingKey=new SigningKey(hexlify(I.slice(0,32)));return new HDNodeWallet(_guard$1,signingKey,"0x00000000",hexlify(I.slice(32)),"m",0,0,mnemonic,null)}static fromExtendedKey(extendedKey){const bytes=toBeArray(decodeBase58(extendedKey));assertArgument(bytes.length===82||encodeBase58Check(bytes.slice(0,78))===extendedKey,"invalid extended key","extendedKey","[ REDACTED ]");const depth=bytes[4];const parentFingerprint=hexlify(bytes.slice(5,9));const index=parseInt(hexlify(bytes.slice(9,13)).substring(2),16);const chainCode=hexlify(bytes.slice(13,45));const key=bytes.slice(45,78);switch(hexlify(bytes.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const publicKey=hexlify(key);return new HDNodeVoidWallet(_guard$1,computeAddress(publicKey),publicKey,parentFingerprint,chainCode,null,index,depth,null)}case"0x0488ade4":case"0x04358394 ":if(key[0]!==0){break}return new HDNodeWallet(_guard$1,new SigningKey(key.slice(1)),parentFingerprint,chainCode,null,index,depth,null,null)}assertArgument(false,"invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(path,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}const mnemonic=Mnemonic.fromEntropy(randomBytes(16),password,wordlist);return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromMnemonic(mnemonic,path){return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromPhrase(phrase,path,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}const mnemonic=Mnemonic.fromPhrase(phrase,password,wordlist);return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromSeed(seed){return HDNodeWallet.#fromSeed(seed,null)}}class HDNodeVoidWallet extends VoidSigner{publicKey;fingerprint;parentFingerprint;chainCode;path;index;depth;constructor(guard,address,publicKey,parentFingerprint,chainCode,path,index,depth,provider){super(address,provider);assertPrivate(guard,_guard$1,"HDNodeVoidWallet");defineProperties(this,{publicKey:publicKey});const fingerprint=dataSlice(ripemd160(sha256(publicKey)),0,4);defineProperties(this,{publicKey:publicKey,fingerprint:fingerprint,parentFingerprint:parentFingerprint,chainCode:chainCode,path:path,index:index,depth:depth})}connect(provider){return new HDNodeVoidWallet(_guard$1,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,provider)}get extendedKey(){assert(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"});return encodeBase58Check(concat(["0x0488B21E",zpad(this.depth,1),this.parentFingerprint,zpad(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return this.path!=null}deriveChild(_index){const index=getNumber(_index,"index");assertArgument(index<=4294967295,"invalid index","index",index);let path=this.path;if(path){path+="/"+(index&~HardenedBit);if(index&HardenedBit){path+="'"}}const{IR,IL}=ser_I(index,this.chainCode,this.publicKey,null);const Ki=SigningKey.addPoints(IL,this.publicKey,true);const address=computeAddress(Ki);return new HDNodeVoidWallet(_guard$1,address,Ki,this.fingerprint,hexlify(IR),path,index,this.depth+1,this.provider)}derivePath(path){return derivePath(this,path)}}const MAX_ADDRESS_DERIVATION_ATTEMPTS=1e7;const _guard={};class AbstractHDWallet{static _version=1;static _coinType;_addresses=new Map;_root;provider;constructor(guard,root,provider){assertPrivate(guard,_guard,"AbstractHDWallet");this._root=root;this.provider=provider}static parentPath(coinType){return`m/44'/${coinType}'`}coinType(){return this.constructor._coinType}get xPub(){return this._root.extendedKey}deriveNextAddressNode(account,startingIndex,zone,isChange=false){const changeIndex=isChange?1:0;const changeNode=this._root.deriveChild(account).deriveChild(changeIndex);let addrIndex=startingIndex;let addressNode;const isValidAddressForZone=address=>{const addressZone=getZoneForAddress(address);if(!addressZone){return false}const isCorrectShard=addressZone===zone;const isCorrectLedger=this.coinType()===969?isQiAddress(address):!isQiAddress(address);return isCorrectShard&&isCorrectLedger};for(let attempts=0;attempts{if(addressInfo.index===addressIndex){throw new Error(`Address for index ${addressIndex} already exists`)}});const changeIndex=isChange?1:0;const addressNode=this._root.deriveChild(account).deriveChild(changeIndex).deriveChild(addressIndex);const zone=getZoneForAddress(addressNode.address);if(!zone){throw new Error(`Failed to derive a valid address zone for the index ${addressIndex}`)}return this.createAndStoreAddressInfo(addressNode,account,zone,isChange,addressMap)}async getNextAddress(account,zone){return Promise.resolve(this._getNextAddress(account,zone,false,this._addresses))}getNextAddressSync(account,zone){return this._getNextAddress(account,zone,false,this._addresses)}_getNextAddress(accountIndex,zone,isChange,addressMap){this.validateZone(zone);const lastIndex=this.getLastAddressIndex(addressMap,zone,accountIndex,isChange);const addressNode=this.deriveNextAddressNode(accountIndex,lastIndex+1,zone,isChange);return this.createAndStoreAddressInfo(addressNode,accountIndex,zone,isChange,addressMap)}getAddressInfo(address){const addressInfo=this._addresses.get(address);if(!addressInfo){return null}return addressInfo}getPrivateKey(address){const hdNode=this._getHDNodeForAddress(address);return hdNode.privateKey}getAddressesForAccount(account){const addresses=this._addresses.values();return Array.from(addresses).filter(addressInfo=>addressInfo.account===account)}getAddressesForZone(zone){this.validateZone(zone);const addresses=this._addresses.values();return Array.from(addresses).filter(addressInfo=>addressInfo.zone===zone)}static createInstance(mnemonic){const coinType=this._coinType;const root=HDNodeWallet.fromMnemonic(mnemonic,this.parentPath(coinType));return new this(_guard,root)}static fromMnemonic(mnemonic){return this.createInstance(mnemonic)}static createRandom(password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}const mnemonic=Mnemonic.fromEntropy(randomBytes(16),password,wordlist);return this.createInstance(mnemonic)}static fromPhrase(phrase,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}const mnemonic=Mnemonic.fromPhrase(phrase,password,wordlist);return this.createInstance(mnemonic)}connect(provider){this.provider=provider}validateZone(zone){if(!Object.values(Zone).includes(zone)){throw new Error(`Invalid zone: ${zone}`)}}_getHDNodeForAddress(addr){const addressInfo=this._addresses.get(addr);if(!addressInfo){throw new Error(`Address ${addr} is not known to this wallet`)}const changeIndex=addressInfo.change?1:0;return this._root.deriveChild(addressInfo.account).deriveChild(changeIndex).deriveChild(addressInfo.index)}serialize(){const addresses=Array.from(this._addresses.values());return{version:this.constructor._version,phrase:this._root.mnemonic.phrase,coinType:this.coinType(),addresses:addresses}}static async deserialize(_serialized){throw new Error("deserialize method must be implemented in the subclass")}static validateSerializedWallet(serialized){if(serialized.version!==this._version){throw new Error(`Invalid version ${serialized.version} for wallet (expected ${this._version})`)}if(serialized.coinType!==this._coinType){throw new Error(`Invalid coinType ${serialized.coinType} for wallet (expected ${this._coinType})`)}}importSerializedAddresses(addressMap,addresses){for(const addressInfo of addresses){const newAddressInfo=this._addAddress(addressMap,addressInfo.account,addressInfo.index,addressInfo.change);if(addressInfo.address!==newAddressInfo.address){throw new Error(`Address mismatch: ${addressInfo.address} != ${newAddressInfo.address}`)}if(addressInfo.pubKey!==newAddressInfo.pubKey){throw new Error(`Public key mismatch: ${addressInfo.pubKey} != ${newAddressInfo.pubKey}`)}if(addressInfo.zone!==newAddressInfo.zone){throw new Error(`Zone mismatch: ${addressInfo.zone} != ${newAddressInfo.zone}`)}}}getLastAddressIndex(addressMap,zone,account,isChange){const addresses=Array.from(addressMap.values()).filter(addressInfo=>addressInfo.account===account&&addressInfo.zone===zone&&addressInfo.change===isChange);return addresses.reduce((maxIndex,addressInfo)=>Math.max(maxIndex,addressInfo.index),-1)}createAndStoreAddressInfo(addressNode,account,zone,isChange,addressMap){const neuteredAddressInfo={pubKey:addressNode.publicKey,address:addressNode.address,account:account,index:addressNode.index,change:isChange,zone:zone};addressMap.set(neuteredAddressInfo.address,neuteredAddressInfo);return neuteredAddressInfo}}class QuaiHDWallet extends AbstractHDWallet{static _version=1;static _coinType=994;constructor(guard,root,provider){super(guard,root,provider)}async signTransaction(tx){const from=await resolveAddress(tx.from);const fromNode=this._getHDNodeForAddress(from);const signedTx=await fromNode.signTransaction(tx);return signedTx}async sendTransaction(tx){if(!this.provider){throw new Error("Provider is not set")}const from=await resolveAddress(tx.from);const fromNode=this._getHDNodeForAddress(from);const fromNodeConnected=fromNode.connect(this.provider);return await fromNodeConnected.sendTransaction(tx)}async signMessage(address,message){const addrNode=this._getHDNodeForAddress(address);return await addrNode.signMessage(message)}static async deserialize(serialized){super.validateSerializedWallet(serialized);const mnemonic=Mnemonic.fromPhrase(serialized.phrase);const path=this.parentPath(serialized.coinType);const root=HDNodeWallet.fromMnemonic(mnemonic,path);const wallet=new this(_guard,root);wallet.importSerializedAddresses(wallet._addresses,serialized.addresses);return wallet}async signTypedData(address,domain,types,value){const addrNode=this._getHDNodeForAddress(address);return addrNode.signTypedData(domain,types,value)}}class Wallet extends BaseWallet{constructor(key,provider){if(typeof key==="string"&&!key.startsWith("0x")){key="0x"+key}const signingKey=typeof key==="string"?new SigningKey(key):key;super(signingKey,provider)}connect(provider){return new Wallet(this.signingKey,provider)}async encrypt(password,progressCallback){const account={address:this.address,privateKey:this.privateKey};return await encryptKeystoreJson(account,password,{progressCallback:progressCallback})}encryptSync(password){const account={address:this.address,privateKey:this.privateKey};return encryptKeystoreJsonSync(account,password)}static#fromAccount(account){assertArgument(account,"invalid JSON wallet","json","[ REDACTED ]");const wallet=new Wallet(account.privateKey);assertArgument(wallet.address===account.address,"address/privateKey mismatch","json","[ REDACTED ]");return wallet}static async fromEncryptedJson(json,password,progress){let account;if(isKeystoreJson(json)){account=await decryptKeystoreJson(json,password,progress);return Wallet.#fromAccount(account)}throw new Error("invalid JSON wallet")}static fromEncryptedJsonSync(json,password){let account=null;if(isKeystoreJson(json)){account=decryptKeystoreJsonSync(json,password)}else{assertArgument(false,"invalid JSON wallet","json","[ REDACTED ]")}return Wallet.#fromAccount(account)}}const TAGS={challenge:"BIP0340/challenge",keyagg_list:"KeyAgg list",keyagg_coef:"KeyAgg coefficient",musig_aux:"MuSig/aux",musig_nonce:"MuSig/nonce",musig_deterministic_nonce:"MuSig/deterministic/nonce",musig_noncecoef:"MuSig/noncecoef"};function compare32b(a,b){if(a.length!==32||b.length!==32)throw new Error("Invalid array");const aD=new DataView(a.buffer,a.byteOffset,a.length);const bD=new DataView(b.buffer,b.byteOffset,b.length);for(let i=0;i<8;i++){const cmp=aD.getUint32(i*4)-bD.getUint32(i*4);if(cmp!==0)return cmp}return 0}function compare33b(a,b){if(a.length!==33||b.length!==33)throw new Error("Invalid array");const cmp=a[0]-b[0];if(cmp!==0)return cmp;return compare32b(a.subarray(1),b.subarray(1))}const makeSessionId=typeof self==="object"&&(self.crypto||self.msCrypto)?()=>(self.crypto||self.msCrypto).getRandomValues(new Uint8Array(32)):()=>require("crypto").randomBytes(32);const _keyAggCache=new WeakMap;const _coefCache=new WeakMap;const _nonceCache=new WeakMap;const _sessionCache=new WeakMap;function MuSigFactory(ecc){const CPOINT_INF=new Uint8Array(33);const SCALAR_0=new Uint8Array(32);const SCALAR_1=new Uint8Array(32);SCALAR_1[31]=1;ecc.scalarNegate(SCALAR_1);function keyAggCoeff(publicKeys,publicKey){let coefCache=_coefCache.get(publicKeys);if(coefCache===undefined){coefCache=new Map;_coefCache.set(publicKeys,coefCache)}let coefficient=coefCache.get(publicKey);if(coefficient)return coefficient;coefficient=SCALAR_1;let secondPublicKey;let publicKeyHash;let keyAggCache=_keyAggCache.get(publicKeys);if(keyAggCache===undefined){const pkIdx2=publicKeys.findIndex(pk=>compare33b(pk,publicKeys[0])!==0);secondPublicKey=publicKeys[pkIdx2];publicKeyHash=ecc.taggedHash(TAGS.keyagg_list,...publicKeys);keyAggCache={publicKeyHash:publicKeyHash,secondPublicKey:secondPublicKey};_keyAggCache.set(publicKeys,keyAggCache)}else{({publicKeyHash,secondPublicKey}=keyAggCache)}if(secondPublicKey===undefined||compare33b(publicKey,secondPublicKey)!==0)coefficient=ecc.taggedHash(TAGS.keyagg_coef,publicKeyHash,publicKey);coefCache.set(publicKey,coefficient);return coefficient}function addTweak(ctx,t){const tweak="tweak"in t?t:{tweak:t};if(!ecc.isScalar(tweak.tweak))throw new TypeError("Expected tweak to be a valid scalar with curve order");let{gacc,tacc}=ctx;let aggPublicKey=ctx.aggPublicKey;if(!ecc.hasEvenY(aggPublicKey)&&tweak.xOnly){gacc=ecc.scalarNegate(gacc);tacc=ecc.scalarNegate(tacc);aggPublicKey=ecc.pointNegate(aggPublicKey)}aggPublicKey=ecc.pointAddTweak(aggPublicKey,tweak.tweak,false);if(aggPublicKey===null)throw new Error("Unexpected point at infinity during tweaking");tacc=ecc.scalarAdd(tweak.tweak,tacc);return{aggPublicKey:aggPublicKey,gacc:gacc,tacc:tacc}}function keyAgg(publicKeys,...tweaks){checkArgs({publicKeys:publicKeys});const multipliedPublicKeys=publicKeys.map(publicKey=>{const coefficient=keyAggCoeff(publicKeys,publicKey);let multipliedPublicKey;if(compare32b(coefficient,SCALAR_1)===0){multipliedPublicKey=publicKey}else{multipliedPublicKey=ecc.pointMultiplyUnsafe(publicKey,coefficient,false)}if(multipliedPublicKey===null)throw new Error("Point at infinity during aggregation");return multipliedPublicKey});const aggPublicKey=multipliedPublicKeys.reduce((a,b)=>{const next=ecc.pointAdd(a,b,false);if(next===null)throw new Error("Point at infinity during aggregation");return next});return tweaks.reduce((ctx,tweak)=>addTweak(ctx,tweak),{aggPublicKey:aggPublicKey,gacc:SCALAR_1,tacc:SCALAR_0})}function getSessionValues(sessionKey){const sessionValues=_sessionCache.get(sessionKey);if(!sessionValues)throw new Error("Invalid session key, please call `startSigningSession`");return sessionValues}function nonceAgg(publicNonces){checkArgs({publicNonces:publicNonces});const aggNonces=[publicNonces[0].subarray(0,33),publicNonces[0].subarray(33)];for(let i=1;iecc.hasEvenY(finalNonce)?k:ecc.scalarNegate(k));const a=keyAggCoeff(publicKeys,publicKey);const g=ecc.hasEvenY(aggPublicKey)?gacc:ecc.scalarNegate(gacc);const d=ecc.scalarMultiply(g,secretKey);const bk2=ecc.scalarMultiply(coefficient,k2);const k1bk2=ecc.scalarAdd(k1,bk2);const ea=ecc.scalarMultiply(challenge,a);const ead=ecc.scalarMultiply(ea,d);const sig=ecc.scalarAdd(k1bk2,ead);return sig}function partialSign({secretKey,publicNonce,sessionKey,verify=true}){checkArgs({publicNonce:publicNonce,secretKey:secretKey});const secretNonce=_nonceCache.get(publicNonce);if(secretNonce===undefined)throw new Error("No secret nonce found for specified public nonce");_nonceCache.delete(publicNonce);const publicKey=ecc.getPublicKey(secretKey,true);if(publicKey===null)throw new Error("Invalid secret key, no corresponding public key");if(compare33b(publicKey,secretNonce.subarray(64))!==0)throw new Error("Secret nonce pubkey mismatch");const secretNonces=[secretNonce.subarray(0,32),secretNonce.subarray(32,64)];const sig=partialSignInner({secretKey:secretKey,publicKey:publicKey,secretNonces:secretNonces,sessionKey:sessionKey});if(verify){const publicNonces=[publicNonce.subarray(0,33),publicNonce.subarray(33)];const valid=partialVerifyInner({sig:sig,publicKey:publicKey,publicNonces:publicNonces,sessionKey:sessionKey});if(!valid)throw new Error("Partial signature failed verification")}return sig}function deterministicSign({secretKey,aggOtherNonce,publicKeys,tweaks=[],msg,rand,verify=true,nonceOnly=false}){checkArgs({rand:rand,secretKey:secretKey,aggOtherNonce:aggOtherNonce});const publicKey=ecc.getPublicKey(secretKey,true);if(publicKey===null)throw new Error("Secret key has no corresponding public key");let secretKeyPrime;if(rand!==undefined){secretKeyPrime=ecc.taggedHash(TAGS.musig_aux,rand);for(let i=0;i<32;i++){secretKeyPrime[i]=secretKeyPrime[i]^secretKey[i]}}else{secretKeyPrime=secretKey}const ctx=keyAgg(publicKeys,...tweaks);const aggPublicKey=ecc.pointX(ctx.aggPublicKey);const mLength=new Uint8Array(8);new DataView(mLength.buffer).setBigUint64(0,BigInt(msg.length));const secretNonce=new Uint8Array(97);const publicNonce=new Uint8Array(66);for(let i=0;i<2;i++){const kH=ecc.taggedHash(TAGS.musig_deterministic_nonce,...[secretKeyPrime,aggOtherNonce,aggPublicKey,mLength,msg,Uint8Array.of(i)]);const k=ecc.scalarMod(kH);if(compare32b(SCALAR_0,k)===0)throw new Error("0 secret nonce");const pub=ecc.getPublicKey(k,true);if(pub===null)throw new Error("Secret nonce has no corresponding public nonce");secretNonce.set(k,i*32);publicNonce.set(pub,i*33)}secretNonce.set(publicKey,64);if(nonceOnly)return{publicNonce:publicNonce};_nonceCache.set(publicNonce,secretNonce);const aggNonce=nonceAgg([aggOtherNonce,publicNonce]);const sessionKey=startSigningSessionInner(aggNonce,msg,publicKeys,ctx);const sig=partialSign({secretKey:secretKey,publicNonce:publicNonce,sessionKey:sessionKey,verify:verify});return{sig:sig,sessionKey:sessionKey,publicNonce:publicNonce}}const pubKeyArgs=["publicKey","publicKeys"];const scalarArgs=["tweak","sig","sigs","tacc","gacc"];const otherArgs32b=["xOnlyPublicKey","rand","sessionId"];const args32b=["secretKey",...scalarArgs,...otherArgs32b];const pubNonceArgs=["publicNonce","publicNonces","aggNonce","aggOtherNonce","finalNonce"];const argLengths=new Map;args32b.forEach(a=>argLengths.set(a,32));pubKeyArgs.forEach(a=>argLengths.set(a,33));pubNonceArgs.forEach(a=>argLengths.set(a,66));argLengths.set("secretNonce",97);argLengths.set("aggPublicKey",65);const scalarNames=new Set;scalarArgs.forEach(n=>scalarNames.add(n));function checkArgs(args){for(let[name,values]of Object.entries(args)){if(values===undefined)continue;values=Array.isArray(values)?values:[values];if(values.length===0)throw new TypeError(`0-length ${name}s not supported`);for(const value of values){if(argLengths.get(name)!==value.length)throw new TypeError(`Invalid ${name} length (${value.length})`);if(name==="secretKey"){if(!ecc.isSecret(value))throw new TypeError(`Invalid secretKey`)}else if(name==="secretNonce"){for(let i=0;i<64;i+=32)if(!ecc.isSecret(value.subarray(i,i+32)))throw new TypeError(`Invalid secretNonce`)}else if(scalarNames.has(name)){for(let i=0;i{if("aggPublicKey"in ctx)return ecc.pointX(ctx.aggPublicKey);return ecc.pointX(getSessionValues(ctx).aggPublicKey)},getPlainPubkey:ctx=>{if("aggPublicKey"in ctx)return ecc.pointCompress(ctx.aggPublicKey);return ecc.pointCompress(getSessionValues(ctx).aggPublicKey)},keySort:publicKeys=>{checkArgs({publicKeys:publicKeys});return[...publicKeys].sort((a,b)=>compare33b(a,b))},keyAgg:keyAgg,addTweaks:(ctx,...tweaks)=>{checkArgs(ctx);return tweaks.reduce((c,tweak)=>addTweak(c,tweak),ctx)},nonceGen:({sessionId=makeSessionId(),secretKey,publicKey,xOnlyPublicKey,msg,extraInput})=>{if(extraInput!==undefined&&extraInput.length>Math.pow(2,32)-1)throw new TypeError("extraInput is limited to 2^32-1 bytes");checkArgs({sessionId:sessionId,secretKey:secretKey,publicKey:publicKey,xOnlyPublicKey:xOnlyPublicKey});let rand;if(secretKey!==undefined){rand=ecc.taggedHash(TAGS.musig_aux,sessionId);for(let i=0;i<32;i++){rand[i]=rand[i]^secretKey[i]}}else{rand=sessionId}if(xOnlyPublicKey===undefined)xOnlyPublicKey=new Uint8Array;const mPrefixed=[Uint8Array.of(0)];if(msg!==undefined){mPrefixed[0][0]=1;mPrefixed.push(new Uint8Array(8));new DataView(mPrefixed[1].buffer).setBigUint64(0,BigInt(msg.length));mPrefixed.push(msg)}if(extraInput===undefined)extraInput=new Uint8Array;const eLength=new Uint8Array(4);new DataView(eLength.buffer).setUint32(0,extraInput.length);const secretNonce=new Uint8Array(97);const publicNonce=new Uint8Array(66);for(let i=0;i<2;i++){const kH=ecc.taggedHash(TAGS.musig_nonce,rand,Uint8Array.of(publicKey.length),publicKey,Uint8Array.of(xOnlyPublicKey.length),xOnlyPublicKey,...mPrefixed,eLength,extraInput,Uint8Array.of(i));const k=ecc.scalarMod(kH);if(compare32b(SCALAR_0,k)===0)throw new Error("0 secret nonce");const pub=ecc.getPublicKey(k,true);if(pub===null)throw new Error("Secret nonce has no corresponding public nonce");secretNonce.set(k,i*32);publicNonce.set(pub,i*33)}secretNonce.set(publicKey,64);_nonceCache.set(publicNonce,secretNonce);return publicNonce},addExternalNonce:(publicNonce,secretNonce)=>{checkArgs({publicNonce:publicNonce,secretNonce:secretNonce});_nonceCache.set(publicNonce,secretNonce)},deterministicNonceGen:args=>deterministicSign({...args,nonceOnly:true}),deterministicSign:deterministicSign,nonceAgg:nonceAgg,startSigningSession:(aggNonce,msg,publicKeys,...tweaks)=>{checkArgs({aggNonce:aggNonce});const ctx=keyAgg(publicKeys,...tweaks);return startSigningSessionInner(aggNonce,msg,publicKeys,ctx)},partialSign:partialSign,partialVerify:({sig,publicKey,publicNonce,sessionKey})=>{checkArgs({sig:sig,publicKey:publicKey,publicNonce:publicNonce});const publicNonces=[publicNonce.subarray(0,33),publicNonce.subarray(33)];const valid=partialVerifyInner({sig:sig,publicKey:publicKey,publicNonces:publicNonces,sessionKey:sessionKey});return valid},signAgg:(sigs,sessionKey)=>{checkArgs({sigs:sigs});const{aggPublicKey,tacc,challenge,finalNonce}=getSessionValues(sessionKey);let sPart=ecc.scalarMultiply(challenge,tacc);if(!ecc.hasEvenY(aggPublicKey)){sPart=ecc.scalarNegate(sPart)}const aggS=sigs.reduce((a,b)=>ecc.scalarAdd(a,b),sPart);const sig=new Uint8Array(64);sig.set(ecc.pointX(finalNonce),0);sig.set(aggS,32);return sig}}}class QiHDWallet extends AbstractHDWallet{static _version=1;static _GAP_LIMIT=20;static _coinType=969;_changeAddresses=new Map;_gapChangeAddresses=[];_gapAddresses=[];_outpoints=[];constructor(guard,root,provider){super(guard,root,provider)}async getNextChangeAddress(account,zone){return Promise.resolve(this._getNextAddress(account,zone,true,this._changeAddresses))}getNextChangeAddressSync(account,zone){return this._getNextAddress(account,zone,true,this._changeAddresses)}importOutpoints(outpoints){this.validateOutpointInfo(outpoints);this._outpoints.push(...outpoints)}getOutpoints(zone){this.validateZone(zone);return this._outpoints.filter(outpoint=>outpoint.zone===zone)}async signTransaction(tx){const txobj=QiTransaction.from(tx);if(!txobj.txInputs||txobj.txInputs.length==0||!txobj.txOutputs)throw new Error("Invalid UTXO transaction, missing inputs or outputs");const hash=keccak_256(txobj.unsignedSerialized);let signature;if(txobj.txInputs.length==1){signature=this.createSchnorrSignature(txobj.txInputs[0],hash)}else{signature=this.createMuSigSignature(txobj,hash)}txobj.signature=signature;return txobj.serialized}async sendTransaction(tx){if(!this.provider){throw new Error("Provider is not set")}if(!tx.txInputs||tx.txInputs.length===0){throw new Error("Transaction has no inputs")}const input=tx.txInputs[0];const address=computeAddress(input.pubkey);const shard=getZoneForAddress(address);if(!shard){throw new Error(`Address ${address} not found in any shard`)}if(tx.txInputs.some(input=>getZoneForAddress(computeAddress(input.pubkey))!==shard)){throw new Error("All inputs must be from the same shard")}const signedTx=await this.signTransaction(tx);return await this.provider.broadcastTransaction(shard,signedTx)}createSchnorrSignature(input,hash){const privKey=this.getPrivateKeyForTxInput(input);const signature=schnorr.sign(hash,getBytes(privKey));return hexlify(signature)}createMuSigSignature(tx,hash){const musig=MuSigFactory(musigCrypto);const privKeysSet=new Set;tx.txInputs.forEach(input=>{const privKey=this.getPrivateKeyForTxInput(input);privKeysSet.add(privKey)});const privKeys=Array.from(privKeysSet);const pubKeys=privKeys.map(privKey=>musigCrypto.getPublicKey(getBytes(privKey),true)).filter(pubKey=>pubKey!==null);const nonces=pubKeys.map(pk=>musig.nonceGen({publicKey:getBytes(pk)}));const aggNonce=musig.nonceAgg(nonces);const signingSession=musig.startSigningSession(aggNonce,hash,pubKeys);const partialSignatures=privKeys.map((sk,index)=>musig.partialSign({secretKey:getBytes(sk||""),publicNonce:nonces[index],sessionKey:signingSession,verify:true}));const finalSignature=musig.signAgg(partialSignatures,signingSession);return hexlify(finalSignature)}getPrivateKeyForTxInput(input){if(!input.pubkey)throw new Error("Missing public key for input");const address=computeAddress(input.pubkey);const addressInfo=this.getAddressInfo(address);if(!addressInfo)throw new Error(`Address not found: ${address}`);const changeIndex=addressInfo.change?1:0;const addressNode=this._root.deriveChild(addressInfo.account).deriveChild(changeIndex).deriveChild(addressInfo.index);return addressNode.privateKey}async scan(zone,account=0){this.validateZone(zone);this._addresses=new Map;this._changeAddresses=new Map;this._gapAddresses=[];this._gapChangeAddresses=[];this._outpoints=[];await this._scan(zone,account)}async sync(zone,account){this.validateZone(zone);if(account===undefined){const addressInfos=Array.from(this._addresses.values());const accounts=addressInfos.reduce((unique,info)=>{if(!unique.includes(info.account)){unique.push(info.account)}return unique},[]);for(const acc of accounts){await this._scan(zone,acc)}}else{await this._scan(zone,account)}return}async _scan(zone,account=0){if(!this.provider)throw new Error("Provider not set");let gapAddressesCount=0;let changeGapAddressesCount=0;while(gapAddressesCount0){this.importOutpoints(outpoints.map(outpoint=>({outpoint:outpoint,address:addressInfo.address,zone:zone,account:account})));addressesCount=0;isChange?this._gapChangeAddresses=[]:this._gapAddresses=[]}else{addressesCount++;isChange?this._gapChangeAddresses.push(addressInfo):this._gapAddresses.push(addressInfo)}return addressesCount}async getOutpointsByAddress(address){try{const outpointsMap=await this.provider.getOutpointsByAddress(address);if(!outpointsMap){return[]}return Object.values(outpointsMap)}catch(error){throw new Error(`Failed to get outpoints for address: ${address} - error: ${error}`)}}getChangeAddressesForZone(zone){this.validateZone(zone);const changeAddresses=this._changeAddresses.values();return Array.from(changeAddresses).filter(addressInfo=>addressInfo.zone===zone)}getGapAddressesForZone(zone){this.validateZone(zone);const gapAddresses=this._gapAddresses.filter(addressInfo=>addressInfo.zone===zone);return gapAddresses}getGapChangeAddressesForZone(zone){this.validateZone(zone);const gapChangeAddresses=this._gapChangeAddresses.filter(addressInfo=>addressInfo.zone===zone);return gapChangeAddresses}async signMessage(address,message){const addrNode=this._getHDNodeForAddress(address);const privKey=addrNode.privateKey;const digest=keccak_256(message);const signature=schnorr.sign(digest,getBytes(privKey));return hexlify(signature)}serialize(){const hdwalletSerialized=super.serialize();return{outpoints:this._outpoints,changeAddresses:Array.from(this._changeAddresses.values()),gapAddresses:this._gapAddresses,gapChangeAddresses:this._gapChangeAddresses,...hdwalletSerialized}}static async deserialize(serialized){super.validateSerializedWallet(serialized);const mnemonic=Mnemonic.fromPhrase(serialized.phrase);const path=this.parentPath(serialized.coinType);const root=HDNodeWallet.fromMnemonic(mnemonic,path);const wallet=new this(_guard,root);wallet.importSerializedAddresses(wallet._addresses,serialized.addresses);wallet.importSerializedAddresses(wallet._changeAddresses,serialized.changeAddresses);for(const gapAddressInfo of serialized.gapAddresses){const gapAddress=gapAddressInfo.address;if(!wallet._addresses.has(gapAddress)){throw new Error(`Address ${gapAddress} not found in wallet`)}wallet._gapAddresses.push(gapAddressInfo)}for(const gapChangeAddressInfo of serialized.gapChangeAddresses){const gapChangeAddress=gapChangeAddressInfo.address;if(!wallet._changeAddresses.has(gapChangeAddress)){throw new Error(`Address ${gapChangeAddress} not found in wallet`)}wallet._gapChangeAddresses.push(gapChangeAddressInfo)}wallet.validateOutpointInfo(serialized.outpoints);wallet._outpoints.push(...serialized.outpoints);return wallet}validateOutpointInfo(outpointInfo){outpointInfo.forEach(info=>{this.validateZone(info.zone);const addressInfo=this.getAddressInfo(info.address);if(!addressInfo){throw new Error(`Address ${info.address} not found in wallet`)}if(info.account!==undefined&&info.account!==addressInfo.account){throw new Error(`Account ${info.account} not found for address ${info.address}`)}if(info.outpoint.txhash==null||info.outpoint.index==null||info.outpoint.denomination==null){throw new Error(`Invalid Outpoint: ${JSON.stringify(info)} `)}})}}const Networks=new Map;class Network{#name;#chainId;constructor(name,chainId){this.#name=name;this.#chainId=getBigInt(chainId)}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return this.#name}set name(value){this.#name=value}get chainId(){return this.#chainId}set chainId(value){this.#chainId=getBigInt(value,"chainId")}matches(other){if(other==null){return false}if(typeof other==="string"){try{return this.chainId===getBigInt(other)}catch(error){}return this.name===other}if(typeof other==="number"||typeof other==="bigint"){try{return this.chainId===getBigInt(other)}catch(error){}return false}if(typeof other==="object"){if(other.chainId!=null){try{return this.chainId===getBigInt(other.chainId)}catch(error){}return false}if(other.name!=null){return this.name===other.name}return false}return false}clone(){const clone=new Network(this.name,this.chainId);return clone}static from(network){if(network==null){return Network.from("mainnet")}if(typeof network==="number"){network=BigInt(network)}if(typeof network==="string"||typeof network==="bigint"){const networkFunc=Networks.get(network);if(networkFunc){return networkFunc()}if(typeof network==="bigint"){return new Network("unknown",network)}assertArgument(false,"unknown network","network",network)}if(typeof network.clone==="function"){const clone=network.clone();return clone}if(typeof network==="object"){assertArgument(typeof network.name==="string"&&typeof network.chainId==="number","invalid network object name or chainId","network",network);const custom=new Network(network.name,network.chainId);return custom}assertArgument(false,"invalid network","network",network)}static register(nameOrChainId,networkFunc){if(typeof nameOrChainId==="number"){nameOrChainId=BigInt(nameOrChainId)}const existing=Networks.get(nameOrChainId);if(existing){assertArgument(false,`conflicting network for ${JSON.stringify(existing.name)}`,"nameOrChainId",nameOrChainId)}Networks.set(nameOrChainId,networkFunc)}}function copy$2(obj){return JSON.parse(JSON.stringify(obj))}class PollingBlockSubscriber{#provider;#poller;#interval;#zone;#blockNumber;constructor(provider,zone){this.#provider=provider;this.#zone=zone;this.#poller=null;this.#interval=4e3;this.#blockNumber=-2}get pollingInterval(){return this.#interval}set pollingInterval(value){this.#interval=value}async#poll(){try{const blockNumber=await this.#provider.getBlockNumber(toShard(this.#zone));if(this.#blockNumber===-2){this.#blockNumber=blockNumber;return}if(blockNumber!==this.#blockNumber){for(let b=this.#blockNumber+1;b<=blockNumber;b++){if(this.#poller==null){return}await this.#provider.emit("block",this.#zone,b)}this.#blockNumber=blockNumber}}catch(error){}if(this.#poller==null){return}this.#poller=this.#provider._setTimeout(this.#poll.bind(this),this.#interval)}start(){if(this.#poller){return}this.#poller=this.#provider._setTimeout(this.#poll.bind(this),this.#interval);this.#poll()}stop(){if(!this.#poller){return}this.#provider._clearTimeout(this.#poller);this.#poller=null}pause(dropWhilePaused){this.stop();if(dropWhilePaused){this.#blockNumber=-2}}resume(){this.start()}}class OnBlockSubscriber{#provider;#poll;#running;#zone;constructor(provider,zone){this.#provider=provider;this.#zone=zone;this.#running=false;this.#poll=blockNumber=>{this._poll(blockNumber,this.#provider)}}async _poll(blockNumber,provider){throw new Error("sub-classes must override this")}start(){if(this.#running){return}this.#running=true;this.#poll(-2);this.#provider.on("block",this.#poll,this.#zone)}stop(){if(!this.#running){return}this.#running=false;this.#provider.off("block",this.#poll,this.#zone)}pause(dropWhilePaused){this.stop()}resume(){this.start()}}class PollingOrphanSubscriber extends OnBlockSubscriber{#filter;constructor(provider,filter,zone){super(provider,zone);this.#filter=copy$2(filter)}async _poll(blockNumber,provider){throw new Error("@TODO")}}class PollingTransactionSubscriber extends OnBlockSubscriber{#hash;constructor(provider,hash,zone){super(provider,zone);this.#hash=hash}async _poll(blockNumber,provider){const tx=await provider.getTransactionReceipt(this.#hash);if(tx){provider.emit(this.#hash,toZone(this.#hash.slice(0,4)),tx)}}}class PollingEventSubscriber{#provider;#filter;#poller;#running;#blockNumber;#zone;constructor(provider,filter){this.#provider=provider;this.#filter=copy$2(filter);this.#poller=this.#poll.bind(this);this.#running=false;this.#blockNumber=-2;const zone=getZoneFromEventFilter(this.#filter);if(zone){this.#zone=zone}else{throw new Error("Unable to determine zone for event filter")}}async#poll(blockNumber){if(this.#blockNumber===-2){return}const filter=copy$2(this.#filter);filter.fromBlock=this.#blockNumber+1;filter.toBlock=blockNumber;const logs=await this.#provider.getLogs(filter);if(logs.length===0){if(this.#blockNumber{this.#blockNumber=blockNumber})}this.#provider.on("block",this.#poller,this.#zone)}stop(){if(!this.#running){return}this.#running=false;this.#provider.off("block",this.#poller,this.#zone)}pause(dropWhilePaused){this.stop();if(dropWhilePaused){this.#blockNumber=-2}}resume(){this.start()}}const BN_2=BigInt(2);function isPromise(value){return value&&typeof value.then==="function"}function getTag(prefix,value){return prefix+":"+JSON.stringify(value,(k,v)=>{if(v==null){return"null"}if(typeof v==="bigint"){return`bigint:${v.toString()}`}if(typeof v==="string"){return v.toLowerCase()}if(typeof v==="object"&&!Array.isArray(v)){const keys=Object.keys(v);keys.sort();return keys.reduce((accum,key)=>{accum[key]=v[key];return accum},{})}return v})}class UnmanagedSubscriber{name;constructor(name){defineProperties(this,{name:name})}start(){}stop(){}pause(dropWhilePaused){}resume(){}}function copy$1(value){return JSON.parse(JSON.stringify(value))}function concisify(items){items=Array.from(new Set(items).values());items.sort();return items}async function getSubscription(_event,zone){if(_event==null){throw new Error("invalid event")}if(Array.isArray(_event)){_event={topics:_event}}if(typeof _event==="string"){if(_event==="debug"){return{type:_event,tag:_event}}switch(_event){case"block":case"pending":if(!zone){throw new Error("zone is required for block and pending events")}return{type:"block",tag:_event,zone:zone};case"error":case"finalized":case"network":case"safe":{return{type:_event,tag:_event}}}}if(isHexString(_event,32)){const hash=_event.toLowerCase();zone=toZone(hash.slice(0,4));return{type:"transaction",tag:getTag("tx",{hash:hash}),hash:hash,zone:zone}}if(_event.orphan){const event=_event;if(!zone){const hash=event.hash||event.tx.hash||event.other?.hash||event.log.transactionHash||null;if(hash==null){throw new Error("orphan event must specify a hash")}zone=toZone(hash.slice(0,4))}return{type:"orphan",tag:getTag("orphan",event),filter:copy$1(event),zone:zone}}if(_event.address||_event.topics){const event=_event;const filter={topics:(event.topics||[]).map(t=>{if(t==null){return null}if(Array.isArray(t)){return concisify(t.map(t=>t.toLowerCase()))}return t.toLowerCase()})};if(event.nodeLocation){filter.nodeLocation=event.nodeLocation}if(event.address){const addresses=[];const promises=[];const addAddress=addr=>{if(isHexString(addr)){addresses.push(formatMixedCaseChecksumAddress(addr))}else{promises.push((async()=>{addresses.push(formatMixedCaseChecksumAddress(await resolveAddress(addr)))})())}};if(Array.isArray(event.address)){event.address.forEach(addAddress)}else{addAddress(event.address)}if(promises.length){await Promise.all(promises)}if(!zone){zone=toZone(addresses[0].slice(0,4))}filter.address=concisify(addresses.map(a=>a.toLowerCase()));if(!filter.nodeLocation){filter.nodeLocation=getNodeLocationFromZone(zone)}}else{if(!zone){throw new Error("zone is required for event")}}return{filter:filter,tag:getTag("event",filter),type:"event",zone:zone}}assertArgument(false,"unknown ProviderEvent","event",_event)}function getTime(){return(new Date).getTime()}const defaultOptions$1={cacheTimeout:250,pollingInterval:4e3,usePathing:false};class AbstractProvider{_urlMap;#connect;#subs;#pausedState;#destroyed;#networkPromise;#anyNetwork;#performCache;#lastBlockNumber;#nextTimer;#timers;#options;_initFailed;initResolvePromise;initRejectPromise;initPromise;constructor(_network,options){this._initFailed=false;this.#options=Object.assign({},defaultOptions$1,options||{});if(_network==="any"){this.#anyNetwork=true;this.#networkPromise=null}else if(_network){const network=Network.from(_network);this.#anyNetwork=false;this.#networkPromise=Promise.resolve(network);setTimeout(()=>{this.emit("network",undefined,network,null)},0)}else{this.#anyNetwork=false;this.#networkPromise=null}this.#lastBlockNumber=-1;this.#performCache=new Map;this.#subs=new Map;this.#pausedState=null;this.#destroyed=false;this.#nextTimer=1;this.#timers=new Map;this.#connect=[];this._urlMap=new Map;this.initResolvePromise=null;this.initRejectPromise=null;this.initPromise=new Promise((resolve,reject)=>{this.initResolvePromise=resolve;this.initRejectPromise=reject})}async initialize(urls){try{const primeSuffix=this.#options.usePathing?`/${fromShard(Shard.Prime,"nickname")}`:":9001";if(urls instanceof FetchRequest){urls.url=urls.url.split(":")[0]+":"+urls.url.split(":")[1]+primeSuffix;this._urlMap.set(Shard.Prime,urls);this.#connect.push(urls);const shards=await this.getRunningLocations();shards.forEach(shard=>{const port=9200+20*shard[0]+shard[1];const shardEnum=toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);const shardSuffix=this.#options.usePathing?`/${fromShard(shardEnum,"nickname")}`:`:${port}`;this._urlMap.set(shardEnum,new FetchRequest(urls.url.split(":")[0]+":"+urls.url.split(":")[1]+shardSuffix))});return}if(Array.isArray(urls)){for(const url of urls){const primeUrl=url.split(":")[0]+":"+url.split(":")[1]+primeSuffix;const primeConnect=new FetchRequest(primeUrl);this._urlMap.set(Shard.Prime,primeConnect);this.#connect.push(primeConnect);const shards=await this.getRunningLocations();shards.forEach(shard=>{const port=9200+20*shard[0]+shard[1];const shardEnum=toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);const shardSuffix=this.#options.usePathing?`/${fromShard(shardEnum,"nickname")}`:`:${port}`;this._urlMap.set(toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`),new FetchRequest(url.split(":")[0]+":"+url.split(":")[1]+shardSuffix))})}}if(this.initResolvePromise)this.initResolvePromise()}catch(error){this._initFailed=true;console.log("Error initializing URL map:",error);if(this.initRejectPromise)this.initRejectPromise(error)}}get connect(){return this.#connect}async zoneFromAddress(_address){const address=this._getAddress(_address);return toZone((await address).slice(0,4))}shardFromHash(hash){return toShard(hash.slice(0,4))}zoneFromHash(hash){return toZone(hash.slice(0,4))}async getLatestQuaiRate(zone,amt=1){const blockNumber=await this.getBlockNumber(toShard(zone));return this.getQuaiRateAtBlock(zone,blockNumber,amt)}async getQuaiRateAtBlock(zone,blockTag,amt=1){let resolvedBlockTag=this._getBlockTag(toShard(zone),blockTag);if(typeof resolvedBlockTag!=="string"){resolvedBlockTag=await resolvedBlockTag}return await this.#perform({method:"getQuaiRateAtBlock",blockTag:resolvedBlockTag,amt:amt,zone:zone})}async getProtocolExpansionNumber(){return await this.#perform({method:"getProtocolExpansionNumber"})}async getLatestQiRate(zone,amt=1){const blockNumber=await this.getBlockNumber(toShard(zone));return this.getQiRateAtBlock(zone,blockNumber,amt)}async getQiRateAtBlock(zone,blockTag,amt=1){let resolvedBlockTag=this._getBlockTag(toShard(zone),blockTag);if(typeof resolvedBlockTag!=="string"){resolvedBlockTag=await resolvedBlockTag}return await this.#perform({method:"getQiRateAtBlock",blockTag:resolvedBlockTag,amt:amt,zone:zone})}get pollingInterval(){return this.#options.pollingInterval}get provider(){return this}async#perform(req){const timeout=this.#options.cacheTimeout;if(timeout<0){return await this._perform(req)}const tag=getTag(req.method,req);let perform=this.#performCache.get(tag);if(!perform||tag.includes("pending")||tag.includes("latest")){perform=this._perform(req);this.#performCache.set(tag,perform);setTimeout(()=>{if(this.#performCache.get(tag)===perform){this.#performCache.delete(tag)}},timeout)}return await perform}_wrapBlock(value,network){value.header.number=Array.isArray(value.header.number)?value.header.number.filter(n=>n!=null):value.header.number;return new Block(formatBlock(value),this)}_wrapLog(value,network){return new Log(formatLog(value),this)}_wrapTransactionReceipt(value,network){const formattedReceipt=formatTransactionReceipt(value);return new TransactionReceipt(formattedReceipt,this)}_wrapTransactionResponse(tx,network){if("from"in tx){return new QuaiTransactionResponse(formatTransactionResponse(tx),this)}else{return new QiTransactionResponse(formatTransactionResponse(tx),this)}}_detectNetwork(){assert(false,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(req){assert(false,`unsupported method: ${req.method}`,"UNSUPPORTED_OPERATION",{operation:req.method,info:req})}async getBlockNumber(shard){const blockNumber=getNumber(await this.#perform({method:"getBlockNumber",shard:shard}),"%response");if(this.#lastBlockNumber>=0){this.#lastBlockNumber=blockNumber}return blockNumber}_getAddress(address){return resolveAddress(address)}_getBlockTag(shard,blockTag){if(blockTag==null){return"latest"}switch(blockTag){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return blockTag}if(isHexString(blockTag)){if(isHexString(blockTag,32)){return blockTag}return toQuantity(blockTag)}if(typeof blockTag==="bigint"){blockTag=getNumber(blockTag,"blockTag")}if(typeof blockTag==="number"){if(blockTag>=0){return toQuantity(blockTag)}if(this.#lastBlockNumber>=0){return toQuantity(this.#lastBlockNumber+blockTag)}return this.getBlockNumber(shard).then(b=>toQuantity(b+blockTag))}assertArgument(false,"invalid blockTag","blockTag",blockTag)}_getFilter(filter){const topics=(filter.topics||[]).map(t=>{if(t==null){return null}if(Array.isArray(t)){return concisify(t.map(t=>t.toLowerCase()))}return t.toLowerCase()});const blockHash="blockHash"in filter?filter.blockHash:undefined;const resolve=(_address,fromBlock,toBlock,nodeLocation)=>{let address=undefined;switch(_address.length){case 0:break;case 1:address=_address[0];break;default:_address.sort();address=_address}if(blockHash){if(fromBlock!=null||toBlock!=null){throw new Error("invalid filter")}}const filter={};if(address){filter.address=address}if(topics.length){filter.topics=topics}if(fromBlock){filter.fromBlock=fromBlock}if(toBlock){filter.toBlock=toBlock}if(blockHash){filter.blockHash=blockHash}if(nodeLocation){filter.nodeLocation=nodeLocation}return filter};const address=[];if(filter.address){if(Array.isArray(filter.address)){for(const addr of filter.address){address.push(this._getAddress(addr))}}else{address.push(this._getAddress(filter.address))}}const zone=getZoneFromNodeLocation(filter.nodeLocation);let fromBlock=undefined;if("fromBlock"in filter){fromBlock=this._getBlockTag(toShard(zone),filter.fromBlock)}let toBlock=undefined;if("toBlock"in filter){toBlock=this._getBlockTag(toShard(zone),filter.toBlock)}let nodeLocation=undefined;if(filter.nodeLocation){nodeLocation=filter.nodeLocation}if(address.filter(a=>typeof a!=="string").length||fromBlock!=null&&typeof fromBlock!=="string"||toBlock!=null&&typeof toBlock!=="string"){return Promise.all([Promise.all(address),fromBlock,toBlock,nodeLocation]).then(result=>{return resolve(result[0],result[1],result[2],result[3])})}return resolve(address,fromBlock,toBlock,nodeLocation)}_getTransactionRequest(_request){const request=copyRequest(_request);const promises=[];["to","from","inputs","outputs"].forEach(key=>{if(request[key]==null){return}const addr=Array.isArray(request[key])?"address"in request[key][0]?request[key].map(it=>it.address):request[key].map(it=>computeAddress(it.pubkey)):resolveAddress(request[key]);if(isPromise(addr)){if(Array.isArray(addr)){for(let i=0;i{try{const network=await this._detectNetwork();this.emit("network",undefined,network,null);return network}catch(error){if(this.#networkPromise===detectNetwork){this.#networkPromise=null}throw error}})();this.#networkPromise=detectNetwork;return(await detectNetwork).clone()}const networkPromise=this.#networkPromise;const[expected,actual]=await Promise.all([networkPromise,this._detectNetwork()]);if(expected.chainId!==actual.chainId){if(this.#anyNetwork){this.emit("network",undefined,actual,expected);if(this.#networkPromise===networkPromise){this.#networkPromise=Promise.resolve(actual)}}else{assert(false,`network changed: ${expected.chainId} => ${actual.chainId} `,"NETWORK_ERROR",{event:"changed"})}}return expected.clone()}async _getRunningLocations(shard,now){now=now?now:false;return await this.#perform(shard?{method:"getRunningLocations",shard:shard,now:now}:{method:"getRunningLocations",now:now})}async getRunningLocations(shard){return await this._getRunningLocations(shard)}async getProtocolTrieExpansionCount(shard){return await this.#perform({method:"getProtocolTrieExpansionCount",shard:shard})}async getFeeData(zone,txType=true){const getFeeDataFunc=async()=>{const{gasPrice,priorityFee}=await resolveProperties({gasPrice:(async()=>{try{const value=await this.#perform({method:"getGasPrice",txType:txType,zone:zone});return getBigInt(value,"%response")}catch(error){console.log(error)}return null})(),priorityFee:(async()=>{try{const value=txType?await this.#perform({method:"getMaxPriorityFeePerGas",zone:zone}):0;return getBigInt(value,"%response")}catch(error){}return null})()});if(gasPrice==null){throw new Error("could not determine gasPrice")}let maxFeePerGas=null;let maxPriorityFeePerGas=null;maxPriorityFeePerGas=priorityFee!=null?priorityFee:BigInt("1000000000");maxFeePerGas=gasPrice*BN_2+maxPriorityFeePerGas;return new FeeData(gasPrice,maxFeePerGas,maxPriorityFeePerGas)};return await getFeeDataFunc()}async estimateGas(_tx){let tx=this._getTransactionRequest(_tx);if(isPromise(tx)){tx=await tx}const zone=await this.zoneFromAddress(addressFromTransactionRequest(tx));return getBigInt(await this.#perform({method:"estimateGas",transaction:tx,zone:zone}),"%response")}async#call(tx,blockTag,attempt,zone){const transaction=copyRequest(tx);return hexlify(await this._perform({method:"call",transaction:transaction,blockTag:blockTag,zone:zone}))}async#checkNetwork(promise,shard){const{value}=await resolveProperties({network:this.getNetwork(),value:promise});return value}async call(_tx){const zone=await this.zoneFromAddress(addressFromTransactionRequest(_tx));const shard=toShard(zone);const{tx,blockTag}=await resolveProperties({tx:this._getTransactionRequest(_tx),blockTag:this._getBlockTag(shard,_tx.blockTag)});return await this.#checkNetwork(this.#call(tx,blockTag,-1,zone),shard)}async#getAccountValue(request,_address,_blockTag){let address=this._getAddress(_address);const zone=await this.zoneFromAddress(_address);const shard=toShard(zone);let blockTag=this._getBlockTag(shard,_blockTag);if(typeof address!=="string"||typeof blockTag!=="string"){[address,blockTag]=await Promise.all([address,blockTag])}return await this.#checkNetwork(this.#perform(Object.assign(request,{address:address,blockTag:blockTag,zone:zone})),shard)}async getBalance(address,blockTag){return getBigInt(await this.#getAccountValue({method:"getBalance"},address,blockTag),"%response")}async getOutpointsByAddress(address){const outpoints=await this.#getAccountValue({method:"getOutpointsByAddress"},address,"latest");const outpointsArray=Array.isArray(outpoints)?outpoints:[];return outpointsArray.map(outpoint=>({txhash:outpoint.Txhash,index:outpoint.Index,denomination:outpoint.Denomination}))}async getTransactionCount(address,blockTag){return getNumber(await this.#getAccountValue({method:"getTransactionCount"},address,blockTag),"%response")}async getCode(address,blockTag){return hexlify(await this.#getAccountValue({method:"getCode"},address,blockTag))}async getStorage(address,_position,blockTag){const position=getBigInt(_position,"position");return hexlify(await this.#getAccountValue({method:"getStorage",position:position},address,blockTag))}async getPendingHeader(){return await this.#perform({method:"getPendingHeader"})}async getTxPoolContent(zone){return await this.#perform({method:"getTxPoolContent",zone:zone})}async txPoolInspect(zone){return await this.#perform({method:"txPoolInspect",zone:zone})}async broadcastTransaction(zone,signedTx){const type=decodeProtoTransaction(getBytes(signedTx)).type;const{blockNumber,hash,network}=await resolveProperties({blockNumber:this.getBlockNumber(toShard(zone)),hash:this._perform({method:"broadcastTransaction",signedTransaction:signedTx,zone:zone}),network:this.getNetwork()});const tx=type==2?QiTransaction.from(signedTx):QuaiTransaction.from(signedTx);this.#validateTransactionHash(tx.hash||"",hash);return this._wrapTransactionResponse(tx,network).replaceableTransaction(blockNumber)}#validateTransactionHash(computedHash,nodehash){if(computedHash!==nodehash){throw new Error("Transaction hash mismatch")}}validateUrl(url){const urlPattern=/^(https?):\/\/[a-zA-Z0-9.-]+(:\d+)?$/;if(!urlPattern.test(url)){let errorMessage="Invalid URL: ";if(!/^https?:\/\//.test(url)){errorMessage+="URL must start with http:// or https://. "}if(url.endsWith("/")){errorMessage+="URL should not end with a /. "}if(/\/[^/]+/.test(url)){errorMessage+="URL should not contain a path, query string, or fragment. "}throw new Error(errorMessage.trim())}}async#getBlock(shard,block,includeTransactions){if(isHexString(block,32)){return await this.#perform({method:"getBlock",blockHash:block,includeTransactions:includeTransactions,shard:shard})}let blockTag=this._getBlockTag(shard,block);if(typeof blockTag!=="string"){blockTag=await blockTag}return await this.#perform({method:"getBlock",blockTag:blockTag,includeTransactions:includeTransactions,shard:shard})}async getBlock(shard,block,prefetchTxs){const{network,params}=await resolveProperties({network:this.getNetwork(),params:this.#getBlock(shard,block,!!prefetchTxs)});if(params==null){return null}return this._wrapBlock(params,network)}async getTransaction(hash){const zone=toZone(this.shardFromHash(hash));const{network,params}=await resolveProperties({network:this.getNetwork(),params:this.#perform({method:"getTransaction",hash:hash,zone:zone})});if(params==null){return null}return this._wrapTransactionResponse(params,network)}async getTransactionReceipt(hash){const zone=toZone(this.shardFromHash(hash));const{network,params}=await resolveProperties({network:this.getNetwork(),params:this.#perform({method:"getTransactionReceipt",hash:hash,zone:zone})});if(params==null){return null}if(params.gasPrice==null&¶ms.effectiveGasPrice==null){const tx=await this.#perform({method:"getTransaction",hash:hash,zone:zone});if(tx==null){throw new Error("report this; could not find tx or effectiveGasPrice")}params.effectiveGasPrice=tx.gasPrice}return this._wrapTransactionReceipt(params,network)}async getTransactionResult(hash){const zone=toZone(this.shardFromHash(hash));const{result}=await resolveProperties({network:this.getNetwork(),result:this.#perform({method:"getTransactionResult",hash:hash,zone:zone})});if(result==null){return null}return hexlify(result)}async getLogs(_filter){let filter=this._getFilter(_filter);if(isPromise(filter)){filter=await filter}const{network,params}=await resolveProperties({network:this.getNetwork(),params:this.#perform({method:"getLogs",filter:filter,zone:getZoneFromNodeLocation(filter.nodeLocation)})});return params.map(p=>this._wrapLog(p,network))}_getProvider(chainId){assert(false,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async waitForTransaction(hash,_confirms,timeout){const zone=this.zoneFromHash(hash);const confirms=_confirms!=null?_confirms:1;if(confirms===0){return this.getTransactionReceipt(hash)}return new Promise(async(resolve,reject)=>{let timer=null;const listener=async blockNumber=>{try{const receipt=await this.getTransactionReceipt(hash);if(receipt!=null){if(blockNumber-receipt.blockNumber+1>=confirms){resolve(receipt);if(timer){clearTimeout(timer);timer=null}return}}}catch(error){console.log("Error occured while waiting for transaction:",error)}this.once("block",listener,zone)};if(timeout!=null){timer=setTimeout(()=>{if(timer==null){return}timer=null;this.off("block",listener,zone);reject(makeError("timeout","TIMEOUT",{reason:"timeout"}))},timeout)}listener(await this.getBlockNumber(toShard(zone)))})}async waitForBlock(shard,blockTag){assert(false,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(timerId){const timer=this.#timers.get(timerId);if(!timer){return}if(timer.timer){clearTimeout(timer.timer)}this.#timers.delete(timerId)}_setTimeout(_func,timeout){if(timeout==null){timeout=0}const timerId=this.#nextTimer++;const func=()=>{this.#timers.delete(timerId);_func()};if(this.paused){this.#timers.set(timerId,{timer:null,func:func,time:timeout})}else{const timer=setTimeout(func,timeout);this.#timers.set(timerId,{timer:timer,func:func,time:getTime()})}return timerId}_forEachSubscriber(func){for(const sub of this.#subs.values()){func(sub.subscriber)}}_getSubscriber(sub){switch(sub.type){case"debug":case"error":case"network":return new UnmanagedSubscriber(sub.type);case"block":{const subscriber=new PollingBlockSubscriber(this,sub.zone);subscriber.pollingInterval=this.pollingInterval;return subscriber}case"event":return new PollingEventSubscriber(this,sub.filter);case"transaction":return new PollingTransactionSubscriber(this,sub.hash,sub.zone);case"orphan":return new PollingOrphanSubscriber(this,sub.filter,sub.zone)}throw new Error(`unsupported event: ${sub.type}`)}_recoverSubscriber(oldSub,newSub){for(const sub of this.#subs.values()){if(sub.subscriber===oldSub){if(sub.started){sub.subscriber.stop()}sub.subscriber=newSub;if(sub.started){newSub.start()}if(this.#pausedState!=null){newSub.pause(this.#pausedState)}break}}}async#hasSub(event,emitArgs,zone){let sub=await getSubscription(event,zone);if(sub.type==="event"&&emitArgs&&emitArgs.length>0&&emitArgs[0].removed===true){sub=await getSubscription({orphan:"drop-log",log:emitArgs[0]},zone)}return this.#subs.get(sub.tag)||null}async#getSub(event,zone){const subscription=await getSubscription(event,zone);const tag=subscription.tag;let sub=this.#subs.get(tag);if(!sub){const subscriber=this._getSubscriber(subscription);const addressableMap=new WeakMap;const nameMap=new Map;sub={subscriber:subscriber,tag:tag,addressableMap:addressableMap,nameMap:nameMap,started:false,listeners:[],zone:subscription.zone};this.#subs.set(tag,sub)}return sub}async on(event,listener,zone){const sub=await this.#getSub(event,zone);sub.listeners.push({listener:listener,once:false});if(!sub.started){sub.subscriber.start();sub.started=true;if(this.#pausedState!=null){sub.subscriber.pause(this.#pausedState)}}return this}async once(event,listener,zone){const sub=await this.#getSub(event,zone);sub.listeners.push({listener:listener,once:true});if(!sub.started){sub.subscriber.start();sub.started=true;if(this.#pausedState!=null){sub.subscriber.pause(this.#pausedState)}}return this}async emit(event,zone,...args){const sub=await this.#hasSub(event,args,zone);if(!sub||sub.listeners.length===0){return false}const count=sub.listeners.length;sub.listeners=sub.listeners.filter(({listener,once})=>{const payload=new EventPayload(this,once?null:listener,event);try{listener.call(this,...args,payload)}catch(error){}return!once});if(sub.listeners.length===0){if(sub.started){sub.subscriber.stop()}this.#subs.delete(sub.tag)}return count>0}async listenerCount(event){if(event){const sub=await this.#hasSub(event);if(!sub){return 0}return sub.listeners.length}let total=0;for(const{listeners}of this.#subs.values()){total+=listeners.length}return total}async listeners(event){if(event){const sub=await this.#hasSub(event);if(!sub){return[]}return sub.listeners.map(({listener})=>listener)}let result=[];for(const{listeners}of this.#subs.values()){result=result.concat(listeners.map(({listener})=>listener))}return result}async off(event,listener,zone){const sub=await this.#hasSub(event,[],zone);if(!sub){return this}if(listener){const index=sub.listeners.map(({listener})=>listener).indexOf(listener);if(index>=0){sub.listeners.splice(index,1)}}if(!listener||sub.listeners.length===0){if(sub.started){sub.subscriber.stop()}this.#subs.delete(sub.tag)}return this}async removeAllListeners(event){if(event){const{tag,started,subscriber}=await this.#getSub(event);if(started){subscriber.stop()}this.#subs.delete(tag)}else{for(const[tag,{started,subscriber}]of this.#subs){if(started){subscriber.stop()}this.#subs.delete(tag)}}return this}async addListener(event,listener,zone){return await this.on(event,listener,zone)}async removeListener(event,listener,zone){return this.off(event,listener,zone)}get destroyed(){return this.#destroyed}destroy(){this.removeAllListeners();for(const timerId of this.#timers.keys()){this._clearTimeout(timerId)}this.#destroyed=true}get paused(){return this.#pausedState!=null}set paused(pause){if(!!pause===this.paused){return}if(this.paused){this.resume()}else{this.pause(false)}}pause(dropWhilePaused){this.#lastBlockNumber=-1;if(this.#pausedState!=null){if(this.#pausedState==!!dropWhilePaused){return}assert(false,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber(s=>s.pause(dropWhilePaused));this.#pausedState=!!dropWhilePaused;for(const timer of this.#timers.values()){if(timer.timer){clearTimeout(timer.timer)}timer.time=getTime()-timer.time}}resume(){if(this.#pausedState==null){return}this._forEachSubscriber(s=>s.resume());this.#pausedState=null;for(const timer of this.#timers.values()){let timeout=timer.time;if(timeout<0){timeout=0}timer.time=getTime();setTimeout(timer.func,timeout)}}}function copy(obj){return JSON.parse(JSON.stringify(obj))}class FilterIdSubscriber{#provider;#filterIdPromise;#poller;#running;#network;#hault;zone;constructor(provider,zone){this.#provider=provider;this.#filterIdPromise=null;this.#poller=this.#poll.bind(this);this.#running=false;this.#network=null;this.#hault=false;this.zone=zone}_subscribe(provider){throw new Error("subclasses must override this")}_emitResults(provider,result){throw new Error("subclasses must override this")}_recover(provider){throw new Error("subclasses must override this")}async#poll(blockNumber){try{if(this.#filterIdPromise==null){this.#filterIdPromise=this._subscribe(this.#provider)}let filterId=null;try{filterId=await this.#filterIdPromise}catch(error){if(!isError(error,"UNSUPPORTED_OPERATION")||error.operation!=="quai_newFilter"){throw error}}if(filterId==null){this.#filterIdPromise=null;this.#provider._recoverSubscriber(this,this._recover(this.#provider));return}const network=await this.#provider.getNetwork();if(!this.#network){this.#network=network}if(this.#network.chainId!==network.chainId){throw new Error("chain changed")}if(this.#hault){return}const result=await this.#provider.send("quai_getFilterChanges",[filterId]);await this._emitResults(this.#provider,result)}catch(error){console.log("@TODO",error)}this.#provider.once("block",this.#poller,this.zone)}#teardown(){const filterIdPromise=this.#filterIdPromise;if(filterIdPromise){this.#filterIdPromise=null;filterIdPromise.then(filterId=>{this.#provider.send("quai_uninstallFilter",[filterId])})}}start(){if(this.#running){return}this.#running=true;this.#poll(-2)}stop(){if(!this.#running){return}this.#running=false;this.#hault=true;this.#teardown();this.#provider.off("block",this.#poller,this.zone)}pause(dropWhilePaused){if(dropWhilePaused){this.#teardown()}this.#provider.off("block",this.#poller,this.zone)}resume(){this.start()}}class FilterIdEventSubscriber extends FilterIdSubscriber{#event;constructor(provider,filter){const zone=getZoneFromEventFilter(filter);if(zone==null){throw new Error("Unable to determine zone for event filter")}super(provider,zone);this.#event=copy(filter)}_recover(provider){return new PollingEventSubscriber(provider,this.#event)}async _subscribe(provider){const filterId=await provider.send("quai_newFilter",[this.#event]);return filterId}async _emitResults(provider,results){for(const result of results){provider.emit(this.#event,this.zone,provider._wrapLog(result,provider._network))}}}class FilterIdPendingSubscriber extends FilterIdSubscriber{async _subscribe(provider){return await provider.send("quai_newPendingTransactionFilter",[])}async _emitResults(provider,results){for(const result of results){provider.emit("pending",this.zone,result)}}}const Primitive="bigint,boolean,function,number,string,symbol".split(/,/g);function deepCopy(value){if(value==null||Primitive.indexOf(typeof value)>=0){return value}if(typeof value.getAddress==="function"){return value}if(Array.isArray(value)){return value.map(deepCopy)}if(typeof value==="object"){return Object.keys(value).reduce((accum,key)=>{accum[key]=value[key];return accum},{})}throw new Error(`should not happen: ${value} (${typeof value})`)}function stall(duration){return new Promise(resolve=>{setTimeout(resolve,duration)})}const defaultOptions={staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,usePathing:false};class JsonRpcSigner extends AbstractSigner{address;constructor(provider,address){super(provider);address=getAddress(address);defineProperties(this,{address:address})}connect(provider){assert(false,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateQuaiTransaction(tx){return await this.populateCall(tx)}async sendUncheckedTransaction(_tx){const tx=deepCopy(_tx);const promises=[];if("from"in tx){if(tx.from){const _from=tx.from;promises.push((async()=>{const from=await resolveAddress(_from);assertArgument(from!=null&&from.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",_tx);tx.from=from})())}else{tx.from=this.address}if(tx.gasLimit==null){promises.push((async()=>{tx.gasLimit=await this.provider.estimateGas({...tx,from:this.address})})())}if(tx.to!=null){const _to=tx.to;promises.push((async()=>{tx.to=await resolveAddress(_to)})())}}if(promises.length){await Promise.all(promises)}const hexTx=this.provider.getRpcTransaction(tx);return this.provider.send("quai_sendTransaction",[hexTx])}async sendTransaction(tx){const zone=await this.zoneFromAddress(addressFromTransactionRequest(tx));const blockNumber=await this.provider.getBlockNumber(toShard(zone));const hash=await this.sendUncheckedTransaction(tx);return await new Promise((resolve,reject)=>{const timeouts=[1e3,100];let invalids=0;const checkTx=async()=>{try{const tx=await this.provider.getTransaction(hash);if(tx!=null){resolve(tx.replaceableTransaction(blockNumber));return}}catch(error){if(isError(error,"CANCELLED")||isError(error,"BAD_DATA")||isError(error,"NETWORK_ERROR")||isError(error,"UNSUPPORTED_OPERATION")){if(error.info==null){error.info={}}error.info.sendTransactionHash=hash;reject(error);return}if(isError(error,"INVALID_ARGUMENT")){invalids++;if(error.info==null){error.info={}}error.info.sendTransactionHash=hash;if(invalids>10){reject(error);return}}this.provider.emit("error",zoneFromHash(hash),makeError("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:error}))}this.provider._setTimeout(()=>{checkTx()},timeouts.pop()||4e3)};checkTx()})}async signTransaction(_tx){const tx=deepCopy(_tx);if("from"in tx){if(tx.from){const from=await resolveAddress(tx.from);assertArgument(from!=null&&from.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",_tx);tx.from=from}else{tx.from=this.address}}else{throw new Error("No QI signing implementation in provider-jsonrpc")}const hexTx=this.provider.getRpcTransaction(tx);return await this.provider.send("quai_signTransaction",[hexTx])}async signMessage(_message){const message=typeof _message==="string"?toUtf8Bytes(_message):_message;return await this.provider.send("personal_sign",[hexlify(message),this.address.toLowerCase()])}async signTypedData(domain,types,_value){const value=deepCopy(_value);return await this.provider.send("quai_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(TypedDataEncoder.getPayload(domain,types,value))])}async unlock(password){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),password,null])}async _legacySignMessage(_message){const message=typeof _message==="string"?toUtf8Bytes(_message):_message;return await this.provider.send("quai_sign",[this.address.toLowerCase(),hexlify(message)])}}class JsonRpcApiProvider extends AbstractProvider{#options;#nextId;#payloads;#drainTimer;#notReady;#network;#pendingDetectNetwork;#scheduleDrain(){if(this.#drainTimer){return}const stallTime=this._getOption("batchMaxCount")===1?0:this._getOption("batchStallTime");this.#drainTimer=setTimeout(()=>{this.#drainTimer=null;const payloads=this.#payloads;this.#payloads=[];while(payloads.length){const batch=[payloads.shift()];while(payloads.length){if(batch.length===this.#options.batchMaxCount){break}batch.push(payloads.shift());const bytes=JSON.stringify(batch.map(p=>p.payload));if(bytes.length>this.#options.batchMaxSize){payloads.unshift(batch.pop());break}}(async()=>{const payloadMap=new Map;const nowPayloadMap=new Map;for(let i=0;i{const payload=value.length===1?value[0]:value;const shard=key?toShard(key):Shard.Prime;const zone=shard.length<4?undefined:toZone(shard);this.emit("debug",zone,{action:"sendRpcPayload",payload:payload});rawResult.push(await this._send(payload,shard,now));this.emit("debug",zone,{action:"receiveRpcResult",payload:payload})};await Promise.all(Array.from(nowPayloadMap).map(async([key,value])=>{await processPayloads(key,value,true)}).concat(Array.from(payloadMap).map(async([key,value])=>{await processPayloads(key,value)})));const result=rawResult.flat();let lastZone;try{for(const{resolve,reject,payload,shard}of batch){if(this.destroyed){reject(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:payload.method}));continue}if(shard){lastZone=shard.length<4?undefined:toZone(shard)}else{lastZone=undefined}const resp=result.filter(r=>r.id===payload.id)[0];if(resp==null){const error=makeError("missing response for request","BAD_DATA",{value:result,info:{payload:payload}});this.emit("error",lastZone,error);reject(error);continue}if("error"in resp){reject(this.getRpcError(payload,resp,shard));continue}resolve(resp.result)}}catch(error){this.emit("debug",lastZone,{action:"receiveRpcError",error:error});for(const{reject}of batch){reject(error)}}})()}},stallTime)}constructor(network,options){super(network,options);this.#nextId=1;this.#options=Object.assign({},defaultOptions,options||{});this.#payloads=[];this.#drainTimer=null;this.#network=null;this.#pendingDetectNetwork=null;{let resolve=null;const promise=new Promise(_resolve=>{resolve=_resolve});this.#notReady={promise:promise,resolve:resolve}}const staticNetwork=this._getOption("staticNetwork");if(typeof staticNetwork==="boolean"){assertArgument(!staticNetwork||network!=="any","staticNetwork cannot be used on special network 'any'","options",options);if(staticNetwork&&network!=null){this.#network=Network.from(network)}}else if(staticNetwork){assertArgument(network==null||staticNetwork.matches(network),"staticNetwork MUST match network object","options",options);this.#network=staticNetwork}}_getOption(key){return this.#options[key]}get _network(){assert(this.#network,"network is not available yet","NETWORK_ERROR");return this.#network}async _perform(req){if(req.method!=="getRunningLocations"){await this.initPromise}if(req.method==="call"||req.method==="estimateGas"){const tx=req.transaction;if(tx&&tx.type!=null&&getBigInt(tx.type)){if(tx.maxFeePerGas==null&&tx.maxPriorityFeePerGas==null){const feeData=await this.getFeeData(req.zone);if(feeData.maxFeePerGas==null&&feeData.maxPriorityFeePerGas==null){req=Object.assign({},req,{transaction:Object.assign({},tx,{type:undefined})})}}}}const request=this.getRpcRequest(req);if(request!=null){const shard="shard"in req?req.shard:"zone"in req?toShard(req.zone):undefined;if(req.method==="getRunningLocations"){return await this.send(request.method,request.args,shard,req.now)}else{return await this.send(request.method,request.args,shard)}}return super._perform(req)}async _detectNetwork(){const network=this._getOption("staticNetwork");if(network){if(network===true){if(this.#network){return this.#network}}else{return network}}if(this.#pendingDetectNetwork){return await this.#pendingDetectNetwork}if(this.ready){this.#pendingDetectNetwork=(async()=>{try{const result=Network.from(getBigInt(await this.send("quai_chainId",[])));this.#pendingDetectNetwork=null;return result}catch(error){this.#pendingDetectNetwork=null;throw error}})();return await this.#pendingDetectNetwork}this.#pendingDetectNetwork=(async()=>{const payload={id:this.#nextId++,method:"quai_chainId",params:[],jsonrpc:"2.0"};this.emit("debug",undefined,{action:"sendRpcPayload",payload:payload});let result;try{result=(await this._send(payload))[0];this.#pendingDetectNetwork=null}catch(error){this.#pendingDetectNetwork=null;this.emit("debug",undefined,{action:"receiveRpcError",error:error});throw error}this.emit("debug",undefined,{action:"receiveRpcResult",result:result});if("result"in result){return Network.from(getBigInt(result.result))}throw this.getRpcError(payload,result)})();return await this.#pendingDetectNetwork}_start(){if(this.#notReady==null||this.#notReady.resolve==null){return}this.#notReady.resolve();this.#notReady=null;(async()=>{let retries=0;const maxRetries=5;while(this.#network==null&&!this.destroyed&&retries=maxRetries){throw new Error("Failed to detect network after maximum retries")}this.#scheduleDrain()})()}async _waitUntilReady(){if(this._initFailed){throw new Error("Provider failed to initialize on creation. Run initialize or create a new provider.")}await this.initPromise}_getSubscriber(sub){if(sub.type==="pending"){return new FilterIdPendingSubscriber(this,sub.zone)}if(sub.type==="event"){return new FilterIdEventSubscriber(this,sub.filter)}if(sub.type==="orphan"&&sub.filter.orphan==="drop-log"){return new UnmanagedSubscriber("orphan")}return super._getSubscriber(sub)}get ready(){return this.#notReady==null}getRpcTransaction(tx){const result={};if("from"in tx||"to"in tx&&"data"in tx){["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach(key=>{if(tx[key]==null){return}let dstKey=key;if(key==="gasLimit"){dstKey="gas"}result[dstKey]=toQuantity(getBigInt(tx[key],`tx.${key}`))});["from","to","data"].forEach(key=>{if(tx[key]==null){return}result[key]=hexlify(tx[key])});if("accessList"in tx&&tx.accessList){result["accessList"]=accessListify(tx.accessList)}}else{throw new Error("No Qi getRPCTransaction implementation yet")}return result}getRpcRequest(req){switch(req.method){case"chainId":return{method:"quai_chainId",args:[]};case"getBlockNumber":return{method:"quai_blockNumber",args:[]};case"getGasPrice":return{method:"quai_baseFee",args:[req.txType]};case"getMaxPriorityFeePerGas":return{method:"quai_maxPriorityFeePerGas",args:[]};case"getPendingHeader":return{method:"quai_getPendingHeader",args:[]};case"getBalance":return{method:"quai_getBalance",args:[req.address,req.blockTag]};case"getOutpointsByAddress":return{method:"quai_getOutpointsByAddress",args:[req.address]};case"getTransactionCount":return{method:"quai_getTransactionCount",args:[req.address,req.blockTag]};case"getCode":return{method:"quai_getCode",args:[req.address,req.blockTag]};case"getStorage":return{method:"quai_getStorageAt",args:[req.address,"0x"+req.position.toString(16),req.blockTag]};case"broadcastTransaction":return{method:"quai_sendRawTransaction",args:[req.signedTransaction]};case"getBlock":if("blockTag"in req){return{method:"quai_getBlockByNumber",args:[req.blockTag,!!req.includeTransactions]}}else if("blockHash"in req){return{method:"quai_getBlockByHash",args:[req.blockHash,!!req.includeTransactions]}}break;case"getTransaction":return{method:"quai_getTransactionByHash",args:[req.hash]};case"getTransactionReceipt":return{method:"quai_getTransactionReceipt",args:[req.hash]};case"call":return{method:"quai_call",args:[this.getRpcTransaction(req.transaction),req.blockTag]};case"estimateGas":{return{method:"quai_estimateGas",args:[this.getRpcTransaction(req.transaction)]}}case"getRunningLocations":{return{method:"quai_listRunningChains",args:[]}}case"getProtocolTrieExpansionCount":{return{method:"quai_getProtocolExpansionNumber",args:[]}}case"getProtocolExpansionNumber":{return{method:"quai_getProtocolExpansionNumber",args:[]}}case"getQiRateAtBlock":{return{method:"quai_qiRateAtBlock",args:[req.blockTag,req.amt]}}case"getQuaiRateAtBlock":{return{method:"quai_quaiRateAtBlock",args:[req.blockTag,req.amt]}}case"getLogs":return{method:"quai_getLogs",args:[req.filter]};case"getTxPoolContent":return{method:"txpool_content",args:[]};case"txPoolInspect":return{method:"txpool_inspect",args:[]}}return null}getRpcError(payload,_error,shard){const{method}=payload;const{error}=_error;if(method==="quai_estimateGas"&&error.message){const msg=error.message;if(!msg.match(/revert/i)&&msg.match(/insufficient funds/i)){return makeError("insufficient funds","INSUFFICIENT_FUNDS",{transaction:payload.params[0],info:{payload:payload,error:error,shard:shard}})}}if(method==="quai_call"||method==="quai_estimateGas"){const result=spelunkData(error);const e=AbiCoder.getBuiltinCallException(method==="quai_call"?"call":"estimateGas",payload.params[0],result?result.data:null);e.info={error:error,payload:payload,shard:shard};return e}const message=JSON.stringify(spelunkMessage(error));if(method==="quai_getTransactionByHash"&&error.message&&error.message.match(/transaction not found/i)){return makeError("transaction not found","TRANSACTION_NOT_FOUND",{info:{payload:payload,error:error,shard:shard}})}if(typeof error.message==="string"&&error.message.match(/user denied|quais-user-denied/i)){const actionMap={quai_sign:"signMessage",personal_sign:"signMessage",quai_signTypedData_v4:"signTypedData",quai_signTransaction:"signTransaction",quai_sendTransaction:"sendTransaction",quai_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"};return makeError(`user rejected action`,"ACTION_REJECTED",{action:actionMap[method]||"unknown",reason:"rejected",info:{payload:payload,error:error,shard:shard}})}if(method==="quai_sendRawTransaction"||method==="quai_sendTransaction"){const transaction=payload.params[0];if(message.match(/insufficient funds|base fee exceeds gas limit/i)){return makeError("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:transaction,info:{error:error,shard:shard}})}if(message.match(/nonce/i)&&message.match(/too low/i)){return makeError("nonce has already been used","NONCE_EXPIRED",{transaction:transaction,info:{error:error,shard:shard}})}if(message.match(/replacement transaction/i)&&message.match(/underpriced/i)){return makeError("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:transaction,info:{error:error,shard:shard}})}if(message.match(/only replay-protected/i)){return makeError("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:method,info:{transaction:transaction,info:{error:error,shard:shard}}})}if(message.match(/already known/i)){return makeError("transaction already known","TRANSACTION_ALREADY_KNOWN",{info:{error:error,shard:shard}})}}let unsupported=!!message.match(/the method .* does not exist/i);if(!unsupported){if(error&&error.details&&error.details.startsWith("Unauthorized method:")){unsupported=true}}if(unsupported){return makeError("unsupported operation","UNSUPPORTED_OPERATION",{operation:payload.method,info:{error:error,payload:payload,shard:shard}})}if(message.match("Provider failed to initialize on creation. Run initialize or create a new provider.")){return makeError("Provider failed to initialize on creation. Run initUrlMap or create a new provider.","PROVIDER_FAILED_TO_INITIALIZE",{info:{payload:payload,error:error,shard:shard}})}return makeError("could not coalesce error","UNKNOWN_ERROR",{error:error,payload:payload,shard:shard})}send(method,params,shard,now){const continueSend=()=>{if(this.destroyed){return Promise.reject(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:method}))}const id=this.#nextId++;const promise=new Promise((resolve,reject)=>{this.#payloads.push({resolve:resolve,reject:reject,payload:{method:method,params:params,id:id,jsonrpc:"2.0"},shard:shard,now:now})});this.#scheduleDrain();return promise};if(method!=="quai_listRunningChains"){return this.initPromise.then(()=>{return continueSend()})}else{return continueSend()}}async getSigner(address){if(address==null){address=0}const accountsPromise=this.send("quai_accounts",[]);if(typeof address==="number"){const accounts=await accountsPromise;if(address>=accounts.length){throw new Error("no such account")}return new JsonRpcSigner(this,accounts[address])}const{accounts}=await resolveProperties({network:this.getNetwork(),accounts:accountsPromise});address=getAddress(address);for(const account of accounts){if(getAddress(account)===address){return new JsonRpcSigner(this,address)}}throw new Error("invalid account")}async listAccounts(){const accounts=await this.send("quai_accounts",[]);return accounts.map(a=>new JsonRpcSigner(this,a))}destroy(){if(this.#drainTimer){clearTimeout(this.#drainTimer);this.#drainTimer=null}for(const{payload,reject}of this.#payloads){reject(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:payload.method}))}this.#payloads=[];super.destroy()}}class JsonRpcProvider extends JsonRpcApiProvider{constructor(urls,network,options){if(urls==null){urls=["http://localhost:8545"]}super(network,options);if(Array.isArray(urls)){urls.forEach(url=>{this.validateUrl(url)});this.initialize(urls)}else if(typeof urls==="string"){this.validateUrl(urls);this.initialize([urls])}else{this.validateUrl(urls.url);this.initialize(urls.clone())}}_getSubscriber(sub){const subscriber=super._getSubscriber(sub);return subscriber}_getConnection(shard){if(this._initFailed){throw new Error("Provider failed to initialize on creation. Run initUrlMap or create a new provider.")}let connection;if(shard!==undefined){connection=this._urlMap.get(shard)??this.connect[this.connect.length-1].clone()}else{connection=this.connect[this.connect.length-1].clone()}return new FetchRequest(connection.url)}async send(method,params,shard,now){await this._start();return await super.send(method,params,shard,now)}async _send(payload,shard){const request=this._getConnection(shard);request.body=JSON.stringify(payload);request.setHeader("content-type","application/json");const response=await request.send();response.assertOk();let resp=response.bodyJson;if(!Array.isArray(resp)){resp=[resp]}return resp}}function spelunkData(value){if(value==null){return null}if(typeof value.message==="string"&&value.message.match(/revert/i)&&isHexString(value.data)){return{message:value.message,data:value.data}}if(typeof value==="object"){for(const key in value){const result=spelunkData(value[key]);if(result){return result}}return null}if(typeof value==="string"){try{return spelunkData(JSON.parse(value))}catch(error){}}return null}function _spelunkMessage(value,result){if(value==null){return}if(typeof value.message==="string"){result.push(value.message)}if(typeof value==="object"){for(const key in value){_spelunkMessage(value[key],result)}}if(typeof value==="string"){try{return _spelunkMessage(JSON.parse(value),result)}catch(error){}}}function spelunkMessage(value){const result=[];_spelunkMessage(value,result);return result}class ContractFactory{interface;bytecode;runner;constructor(abi,bytecode,runner){const iface=Interface.from(abi);if(bytecode instanceof Uint8Array){bytecode=hexlify(getBytes(bytecode))}else{if(typeof bytecode==="object"){bytecode=bytecode.object}if(!bytecode.startsWith("0x")){bytecode="0x"+bytecode}bytecode=hexlify(getBytes(bytecode))}defineProperties(this,{bytecode:bytecode,interface:iface,runner:runner||null})}attach(target){return new BaseContract(target,this.interface,this.runner)}async getDeployTransaction(...args){let overrides;const fragment=this.interface.deploy;if(fragment.inputs.length+1===args.length){overrides=await copyOverrides(args.pop());const resolvedArgs=await resolveArgs(this.runner,fragment.inputs,args);const data=concat([this.bytecode,this.interface.encodeDeploy(resolvedArgs)]);return Object.assign({},overrides,{data:data})}if(fragment.inputs.length!==args.length){throw new Error("incorrect number of arguments to constructor")}const resolvedArgs=await resolveArgs(this.runner,fragment.inputs,args);const data=concat([this.bytecode,this.interface.encodeDeploy(resolvedArgs)]);const from=args.pop()?.from||undefined;return Object.assign({},from,{data:data})}async deploy(...args){const tx=await this.getDeployTransaction(...args);assert(this.runner&&typeof this.runner.sendTransaction==="function","factory runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});if(this.runner instanceof Wallet||this.runner instanceof JsonRpcSigner){validateAddress(this.runner.address);tx.from=this.runner.address}const grindedTx=await this.grindContractAddress(tx);const sentTx=await this.runner.sendTransaction(grindedTx);const address=getStatic(this.constructor,"getContractAddress")?.(tx);return new BaseContract(address,this.interface,this.runner,sentTx)}static getContractAddress(transaction){return getContractAddress(transaction.from,BigInt(transaction.nonce),transaction.data)}async grindContractAddress(tx){if(tx.nonce==null&&tx.from){tx.nonce=await this.runner?.provider?.getTransactionCount(tx.from)}const sender=String(tx.from);const toShard=getZoneForAddress(sender);let i=0;const startingData=tx.data;while(i<1e4){const contractAddress=getContractAddress(sender,BigInt(tx.nonce||0),tx.data||"");const contractShard=getZoneForAddress(contractAddress);const utxo=isQiAddress(contractAddress);if(contractShard===toShard&&!utxo){return tx}const salt=randomBytes(32);tx.data=hexlify(concat([String(startingData),salt]));i++}return tx}connect(runner){return new ContractFactory(this.interface,this.bytecode,runner)}static fromSolidity(output,runner){assertArgument(output!=null,"bad compiler output","output",output);if(typeof output==="string"){output=JSON.parse(output)}const abi=output.abi;let bytecode="";if(output.bytecode){bytecode=output.bytecode}else if(output.evm&&output.evm.bytecode){bytecode=output.evm.bytecode}return new this(abi,bytecode,runner)}}class BrowserProvider extends JsonRpcApiProvider{#request;constructor(ethereum,network){super(network,{batchMaxCount:1});this.#request=async(method,params)=>{const payload={method:method,params:params};this.emit("debug",undefined,{action:"sendEip1193Request",payload:payload});try{const result=await ethereum.request(payload);this.emit("debug",undefined,{action:"receiveEip1193Result",result:result});return result}catch(e){const error=new Error(e.message);error.code=e.code;error.data=e.data;error.payload=payload;this.emit("debug",undefined,{action:"receiveEip1193Error",error:error});throw error}}}async hasSigner(address){if(address==null){address=0}const accounts=await this.send("quai_accounts",[]);if(typeof address==="number"){return accounts.length>address}address=address.toLowerCase();return accounts.filter(a=>a.toLowerCase()===address).length!==0}async send(method,params){await this._start();return await super.send(method,params)}async _send(payload){assertArgument(!Array.isArray(payload),"EIP-1193 does not support batch request","payload",payload);try{const result=await this.#request(payload.method,payload.params||[]);return[{id:payload.id,result:result}]}catch(e){return[{id:payload.id,error:{code:e.code,data:e.data,message:e.message}}]}}getRpcError(payload,error){error=JSON.parse(JSON.stringify(error));switch(error.error.code||-1){case 4001:error.error.message=`quais-user-denied: ${error.error.message}`;break;case 4200:error.error.message=`quais-unsupported: ${error.error.message}`;break}return super.getRpcError(payload,error)}async getSigner(address){if(address==null){address=0}if(!await this.hasSigner(address)){try{await this.#request("quai_requestAccounts",[])}catch(error){const payload=error.payload;throw this.getRpcError(payload,{id:payload.id,error:error})}}return await super.getSigner(address)}}class SocketSubscriber{#provider;#filter;get filter(){return JSON.parse(this.#filter)}#filterId;#paused;#emitPromise;zone;shard;constructor(provider,filter,zone){this.#provider=provider;this.#filter=JSON.stringify(filter);this.#filterId=null;this.#paused=null;this.#emitPromise=null;this.zone=zone;this.shard=toShard(zone)}start(){this.#filterId=this.#provider.send("quai_subscribe",this.filter,this.shard).then(filterId=>{this.#provider._register(filterId,this);return filterId})}stop(){this.#filterId.then(filterId=>{this.#provider.send("quai_unsubscribe",[filterId],this.shard)});this.#filterId=null}pause(dropWhilePaused){assert(dropWhilePaused,"preserve logs while paused not supported by SocketSubscriber yet","UNSUPPORTED_OPERATION",{operation:"pause(false)"});this.#paused=!!dropWhilePaused}resume(){this.#paused=null}_handleMessage(message){if(this.#filterId==null){return}if(this.#paused===null){let emitPromise=this.#emitPromise;if(emitPromise==null){emitPromise=this._emit(this.#provider,message)}else{emitPromise=emitPromise.then(async()=>{await this._emit(this.#provider,message)})}this.#emitPromise=emitPromise.then(()=>{if(this.#emitPromise===emitPromise){this.#emitPromise=null}})}}async _emit(provider,message){throw new Error("sub-classes must implement this; _emit")}}class SocketBlockSubscriber extends SocketSubscriber{constructor(provider,zone){super(provider,["newHeads"],zone)}async _emit(provider,message){provider.emit("block",this.zone,parseInt(message.woHeader.number))}}class SocketPendingSubscriber extends SocketSubscriber{constructor(provider,zone){super(provider,["newPendingTransactions"],zone)}async _emit(provider,message){provider.emit("pending",message)}}class SocketEventSubscriber extends SocketSubscriber{#logFilter;get logFilter(){return JSON.parse(this.#logFilter)}constructor(provider,filter,zone){super(provider,["logs",filter],zone);this.#logFilter=JSON.stringify(filter)}async _emit(provider,message){provider.emit(this.logFilter,this.zone,provider._wrapLog(message,provider._network))}}class SocketProvider extends JsonRpcApiProvider{#callbacks;#subs;#pending;constructor(network,_options){const options=Object.assign({},_options!=null?_options:{});assertArgument(options.batchMaxCount==null||options.batchMaxCount===1,"sockets-based providers do not support batches","options.batchMaxCount",_options);options.batchMaxCount=1;if(options.staticNetwork==null){options.staticNetwork=true}super(network,options);this.#callbacks=new Map;this.#subs=new Map;this.#pending=new Map}_getSubscriber(sub){switch(sub.type){case"close":return new UnmanagedSubscriber("close");case"block":return new SocketBlockSubscriber(this,sub.zone);case"pending":return new SocketPendingSubscriber(this,sub.zone);case"event":return new SocketEventSubscriber(this,sub.filter,sub.zone);case"orphan":if(sub.filter.orphan==="drop-log"){return new UnmanagedSubscriber("drop-log")}}return super._getSubscriber(sub)}_register(filterId,subscriber){this.#subs.set(filterId,subscriber);const pending=this.#pending.get(filterId);if(pending){for(const message of pending){subscriber._handleMessage(message)}this.#pending.delete(filterId)}}async _send(payload,shard,now){if(this._initFailed){console.log("Provider failed to initialize on creation. Run initialize or create a new provider.");return[{id:Array.isArray(payload)?payload[0].id:payload.id,error:{code:-32e3,message:"Provider failed to initialize on creation. Run initialize or create a new provider."}}]}assertArgument(!Array.isArray(payload),"WebSocket does not support batch send","payload",payload);const promise=new Promise((resolve,reject)=>{this.#callbacks.set(payload.id,{payload:payload,resolve:resolve,reject:reject})});try{if(!now){await this._waitUntilReady()}}catch(error){this.#callbacks.delete(payload.id);return[{id:Array.isArray(payload)?payload[0].id:payload.id,error:{code:-32e3,message:"Provider failed to initialize on creation. Run initialize or create a new provider."}}]}await this._write(JSON.stringify(payload),shard);return[await promise]}async _processMessage(message){const result=JSON.parse(message);if(result&&typeof result==="object"&&"id"in result){const callback=this.#callbacks.get(result.id);if(callback==null){this.emit("error",undefined,makeError("received result for unknown id","UNKNOWN_ERROR",{reasonCode:"UNKNOWN_ID",result:result}));return}this.#callbacks.delete(result.id);callback.resolve(result)}else if(result&&result.method==="quai_subscription"){const filterId=result.params.subscription;const subscriber=this.#subs.get(filterId);if(subscriber){subscriber._handleMessage(result.params.result)}else{let pending=this.#pending.get(filterId);if(pending==null){pending=[];this.#pending.set(filterId,pending)}pending.push(result.params.result)}}else{this.emit("error",undefined,makeError("received unexpected message","UNKNOWN_ERROR",{reasonCode:"UNEXPECTED_MESSAGE",result:result}));return}}async _write(message,shard){throw new Error("sub-classes must override this")}validateUrl(url){const urlPattern=/^(ws):\/\/[a-zA-Z0-9.-]+(:\d+)?$/;if(!urlPattern.test(url)){let errorMessage="Invalid URL: ";if(!/^ws:\/\//.test(url)){errorMessage+="URL must start with ws://. "}if(url.endsWith("/")){errorMessage+="URL should not end with a /. "}if(/\/[^/]+/.test(url)){errorMessage+="URL should not contain a path, query string, or fragment. "}throw new Error(errorMessage.trim())}}}function getGlobal(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")}const _WebSocket=getGlobal().WebSocket;class WebSocketProvider extends SocketProvider{#websockets;readyMap=new Map;get websocket(){if(this.#websockets==null){throw new Error("websocket closed")}return this.#websockets}constructor(url,network,options){super(network,options);this.#websockets=[];if(typeof url==="string"){this.validateUrl(url)}else if(Array.isArray(url)){url.forEach(it=>this.validateUrl(it))}else if(typeof url==="function"){this.validateUrl(url().url)}else{this.validateUrl(url.url)}this.initialize(typeof url==="string"?[url]:url)}initWebSocket(websocket,shard){websocket.onerror=error=>{console.log("WebsocketProvider error",error);websocket.close()};websocket.onopen=async()=>{try{await this._start();this.resume();this.readyMap.set(shard,true)}catch(error){console.log("failed to start WebsocketProvider",error);this.readyMap.set(shard,false)}};websocket.onmessage=message=>{this._processMessage(message.data)}}async waitShardReady(shard){let count=0;while(!this.readyMap.get(shard)){await new Promise(resolve=>setTimeout(resolve,Math.pow(2,count)));if(count>11){throw new Error("Timeout waiting for shard to be ready")}count++}}async initialize(urls){this.#websockets=[];this._urlMap.clear();try{const primeSuffix=this._getOption("usePathing")?`/${fromShard(Shard.Prime,"nickname")}`:":8001";const createWebSocket=(baseUrl,suffix)=>{const tempWs=new _WebSocket(`${baseUrl}${suffix}`);return tempWs};const initShardWebSockets=async baseUrl=>{const shards=await this._getRunningLocations(Shard.Prime,true);await Promise.all(shards.map(async shard=>{const port=8200+20*shard[0]+shard[1];const shardEnum=toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);const shardSuffix=this._getOption("usePathing")?`/${fromShard(shardEnum,"nickname")}`:`:${port}`;const shardUrl=baseUrl.split(":").slice(0,2).join(":");const websocket=createWebSocket(shardUrl,shardSuffix);this.initWebSocket(websocket,shardEnum);this.#websockets.push(websocket);this._urlMap.set(shardEnum,websocket);try{await this.waitShardReady(shardEnum)}catch(error){console.log("failed to waitShardReady",error);this._initFailed=true}}))};if(Array.isArray(urls)){for(const url of urls){const baseUrl=`${url.split(":")[0]}:${url.split(":")[1]}`;const primeWebsocket=createWebSocket(baseUrl,primeSuffix);this.initWebSocket(primeWebsocket,Shard.Prime);this.#websockets.push(primeWebsocket);this._urlMap.set(Shard.Prime,primeWebsocket);await this.waitShardReady(Shard.Prime);await initShardWebSockets(baseUrl)}}else if(typeof urls==="function"){const primeWebsocket=urls();this.initWebSocket(primeWebsocket,Shard.Prime);this.#websockets.push(primeWebsocket);this._urlMap.set(Shard.Prime,primeWebsocket);await this.waitShardReady(Shard.Prime);const baseUrl=this.#websockets[0].url.split(":").slice(0,2).join(":");await initShardWebSockets(baseUrl)}else{const primeWebsocket=urls;this.initWebSocket(primeWebsocket,Shard.Prime);this.#websockets.push(primeWebsocket);this._urlMap.set(Shard.Prime,primeWebsocket);await this.waitShardReady(Shard.Prime);const baseUrl=primeWebsocket.url.split(":").slice(0,2).join(":");await initShardWebSockets(baseUrl)}if(this.initResolvePromise)this.initResolvePromise()}catch(error){this._initFailed=true;console.log("failed to initialize",error);this.#websockets=[];if(this.initRejectPromise)this.initRejectPromise(error);return}}async _write(message,shard){if(this.websocket.length<1){throw new Error("Websocket closed")}if(shard&&!this._urlMap.has(shard)){throw new Error("Shard not found")}const websocket=shard?this._urlMap.get(shard):this.websocket[this.websocket.length-1];if(!websocket){throw new Error("Websocket is undefined")}if(shard){await this.waitShardReady(shard)}websocket.send(message)}async destroy(){this.#websockets.forEach(it=>it.close());this.#websockets=[];super.destroy()}}const Base64=")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";function decodeBits(width,data){const maxValue=(1<=width){const value=accum>>bits-width;accum&=(1<{const match=accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);assertArgument(match!==null,"internal error parsing accents","accents",accents);let posOffset=0;const positions=decodeBits(parseInt(match[3]),match[4]);const charCode=parseInt(match[2]);const regex=new RegExp(`([${match[1]}])`,"g");words=words.replace(regex,(all,letter)=>{const rem=--positions[posOffset];if(rem===0){letter=String.fromCharCode(letter.charCodeAt(0),charCode);posOffset++}return letter})});return words.split(",")}class WordlistOwlA extends WordlistOwl{#accent;constructor(locale,data,accent,checksum){super(locale,data,checksum);this.#accent=accent}get _accent(){return this.#accent}_decodeWords(){return decodeOwlA(this._data,this._accent)}}const words="0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_LoAmpuAnc]ApaAr]I>Is)IvoOqueOzaUle%Up 0Cl.EgoE=EnEr#F[G +M->NeN%P_sR>Rue]SneTaU{d2Am^AnA+AseAveI,)ImaInica2B_Cc~|i'Ci`CoDigoDoF_G!He)JinJoL/ch/eg$Lg Lin/l LmoLum`Mba)M!Mi{Mo&Mpr-deNej}g-oc!Nsej}t PaPi(az.Rba%RchoR&nR.(r!S!SmosS%2AneoAt!E Ec!Ei&EmaIaIm,Ip%IsisOmoOnicaOque%U&Uz2Ad+Ar#At+BoBr*| aEl=En#Er{Es%EvaId Lebr/p/#Mb_Mpl*N-e%O%P.Pul( R$Se'Sf[zVaVi'5BleCeL^Ming}N Ra&Rm*RAu%EchaOrO%U*UjoU^2B@CaGa%G.L$Lle#N&Rm(+Rtun(z SaTo2AcaA'AsaAtisAveIe%Il=IpeIsI#OG Gu!aJaMb_Ng}^Nr((mig('St?Yo5E>ElgaEr%ENgl-$Nt Pit!R S#V,?Zg :7Lo5A]:B$C$C[DoD+nG #GrimaGu`I>M!Mi`Mp --ch-gos%NzaPizRgoRvaStimaTaTexT*U_lV Zo3AlCc~|eC#rErG~Gumb_Ja'Ngu-#NaOnOp &S~TalT[VeY,{3B!%dB+C^D!Di EnzoGaG!oMaMi)M.Mp$NceN&Ne-go)N}t!`Qui&SoS%T!aT$T+2AgaAmaAn#AveEg En Ev Or Ov!Uv@2BoC~CoCu[GicaG+MbrizM}jaTe5|aC*G J}-esPaSt+ToZ:Ce%|oD!aD_Du+Est+F@G@GoIzL{dLe%Ll/oMaMboMutN>N&Nej Ng-iquiNj N}Re(f?Rg,Ri&RmolR+nR)sRzoSaSc aSivoT T!@TizTrizXimoY^Z^ca3|aDal]D$Du]J?]J^L,/.M^i-^NsajeN)NuRca&R,gueRi#SS.TaT!To&T+Zc]3E&ElEmb+G/Lag+Lit Ll.M}-!}im}u#OpeR SaS!@S?SmoTadTo5|?aC~DaDe=HoJ LdeL!Li'M,#Mi- c-ed-j-#NoRad(d!Re'R*R+Rs(%lScaStr TivoV!V?Zo5|oD EbleE]Er)Est[G_J!L/e%L%N&Nec(alRoScu=SeoSgoSicaS=:C C~D IpeRanj(izRr SalTalTivoTu[lUseaValVeVi{d3C$Ct G Goc$G+OnRv$ToUt+V V!a3|oDoEb]E#NezNoTi&Vel5Bleza|eMin(i(m()TaTic@Va#Ve]V$5BeCaCleoD?=DoE[EveEzLoM!oTr@:Sis0EC~E[In On!T TicaUes#1Ac~A&rAlBi%CaD,EjaGa'G@Gul=I,)Ig,Il]OQues%Uga0Ad@Cu+Ez'OT[0O'Ro1EjaU=1I&Ige'0En)0O':C#D_El]Gi`GoIsJ oLabr/>Le%Li&Lm/om/p NNalNi>Nt!-ue=PaPelP?]Que)R Rcel(edR*RoRpa&RqueR[foR)S SeoS~SoS%TaT$Tr@UsaU%VoYa<3A#nCa&C!a|oDalD*G IneL L{'Le/ig+LlejoLoLuc--s N.OnOrPi'Que'R(ch(d!Rez(f?Ri>Rl(mizEgun%Em$EnsaE|!oD^Eb=Er%Es#Lg/*Lm.LpoLrNd*N%P #Pet*PoN{PaP!oSaScaSt+T 5BiB^DoE{G*I&In/e%LoMboM^Ptu[TaTi`:Ba&B!B$BleC GazG[&L/&L!oL*Lm.L.Ls/#LudLv Mb-c~Ndi-e Ng_Ni{dN}#PoQueRdin()nSt_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv! t.trim()); - for (let i = 0; i < types.length; i++) { - switch (type) { - case 'any': - return; - case 'bigint': - case 'boolean': - case 'number': - case 'string': - if (typeof value === type) { - return; - } - } - } - const error = new Error(`invalid value for type ${type}`); - error.code = 'INVALID_ARGUMENT'; - error.argument = `value.${name}`; - error.value = value; - throw error; - } - /** - * Resolves to a new object that is a copy of `value`, but with all values resolved. - * - * @category Utils - * @param {Object} value - The object to resolve. - * - * @returns {Promise} The resolved object. - */ - async function resolveProperties(value) { - const keys = Object.keys(value); - const results = await Promise.all(keys.map((k) => Promise.resolve(value[k]))); - return results.reduce((accum, v, index) => { - accum[keys[index]] = v; - return accum; - }, {}); - } - // Crawl up the constructor chain to find a static method - function getStatic(ctor, key) { - for (let i = 0; i < 32; i++) { - if (ctor[key]) { - return ctor[key]; - } - if (!ctor.prototype || typeof ctor.prototype !== 'object') { - break; - } - ctor = Object.getPrototypeOf(ctor.prototype).constructor; - } - return null; - } - /** - * Assigns the `values` to `target` as read-only values. - * - * It `types` is specified, the values are checked. - * - * @category Utils - * @param {Object} target - The target object to assign to. - * @param {Object} values - The values to assign. - * @param {Object} types - The types to check. - */ - function defineProperties(target, values, types) { - for (const key in values) { - const value = values[key]; - const type = types ? types[key] : null; - if (type) { - checkType(value, type, key); - } - Object.defineProperty(target, key, { enumerable: true, value, writable: false }); - } - } - - /** - * All errors in quais include properties to ensure they are both human-readable (i.e. `.message`) and machine-readable - * (i.e. `.code`). - * - * The {@link isError | **isError**} function can be used to check the error `code` and provide a type guard for the - * properties present on that error interface. - */ - function stringify(value) { - if (value == null) { - return 'null'; - } - if (Array.isArray(value)) { - return '[ ' + value.map(stringify).join(', ') + ' ]'; - } - if (value instanceof Uint8Array) { - const HEX = '0123456789abcdef'; - let result = '0x'; - for (let i = 0; i < value.length; i++) { - result += HEX[value[i] >> 4]; - result += HEX[value[i] & 0xf]; - } - return result; - } - if (typeof value === 'object' && typeof value.toJSON === 'function') { - return stringify(value.toJSON()); - } - switch (typeof value) { - case 'boolean': - case 'symbol': - return value.toString(); - case 'bigint': - return BigInt(value).toString(); - case 'number': - return value.toString(); - case 'string': - return JSON.stringify(value); - case 'object': { - const keys = Object.keys(value); - keys.sort(); - return '{ ' + keys.map((k) => `${stringify(k)}: ${stringify(value[k])}`).join(', ') + ' }'; - } - } - return `[ COULD NOT SERIALIZE ]`; - } - /** - * Returns true if the `error` matches an error thrown by quais that matches the error `code`. - * - * In TypeScript environments, this can be used to check that `error` matches an quaisError type, which means the - * expected properties will be set. - * - * @category Utils - * @example - * - * ```ts - * try { - * // code.... - * } catch (e) { - * if (isError(e, 'CALL_EXCEPTION')) { - * // The Type Guard has validated this object - * console.log(e.data); - * } - * } - * ``` - * - * @see [ErrorCodes](api:ErrorCode) - */ - function isError(error, code) { - return error && error.code === code; - } - /** - * Returns true if `error` is a {@link CallExceptionError | **CallExceptionError**}. - * - * @category Utils - */ - function isCallException(error) { - return isError(error, 'CALL_EXCEPTION'); - } - /** - * Returns a new Error configured to the format quais emits errors, with the `message`, {@link ErrorCode | **ErrorCode**} - * `code` and additional properties for the corresponding quaisError. - * - * Each error in quais includes the version of quais, a machine-readable {@link ErrorCode | **ErrorCode**}, and depending - * on `code`, additional required properties. The error message will also include the `message`, quais version, `code` - * and all additional properties, serialized. - * - * @category Utils - * @param {string} message - The error message. - * @param {ErrorCode} code - The error code. - * @param {ErrorInfo} [info] - Additional properties for the error. - * @returns {T} The new error. - */ - function makeError(message, code, info) { - const shortMessage = message; - { - const details = []; - if (info) { - if ('message' in info || 'code' in info || 'name' in info) { - throw new Error(`value will overwrite populated values: ${stringify(info)}`); - } - for (const key in info) { - if (key === 'shortMessage') { - continue; - } - const value = info[key]; - details.push(key + '=' + stringify(value)); - } - } - details.push(`code=${code}`); - details.push(`version=${version}`); - if (details.length) { - message += ' (' + details.join(', ') + ')'; - } - } - let error; - switch (code) { - case 'INVALID_ARGUMENT': - error = new TypeError(message); - break; - case 'NUMERIC_FAULT': - case 'BUFFER_OVERRUN': - error = new RangeError(message); - break; - default: - error = new Error(message); - } - defineProperties(error, { code }); - if (info) { - Object.assign(error, info); - } - if (error.shortMessage == null) { - defineProperties(error, { shortMessage }); - } - return error; - } - /** - * Throws an quaisError with `message`, `code` and additional error `info` when `check` is falsish.. - * - * @category Utils - * @param {unknown} check - The value to check. - * @param {string} message - The error message. - * @param {ErrorCode} code - The error code. - * @param {ErrorInfo} [info] - Additional properties for the error. - * @throws {T} Throws the error if `check` is falsish. - */ - function assert(check, message, code, info) { - if (!check) { - throw makeError(message, code, info); - } - } - /** - * A simple helper to simply ensuring provided arguments match expected constraints, throwing if not. - * - * In TypeScript environments, the `check` has been asserted true, so any further code does not need additional - * compile-time checks. - * - * @category Utils - * @param {unknown} check - The value to check. - * @param {string} message - The error message. - * @param {string} name - The name of the argument. - * @param {unknown} value - The value of the argument. - * @throws {InvalidArgumentError} Throws if `check` is falsish. - */ - function assertArgument(check, message, name, value) { - assert(check, message, 'INVALID_ARGUMENT', { argument: name, value: value }); - } - function assertArgumentCount(count, expectedCount, message) { - if (message == null) { - message = ''; - } - if (message) { - message = ': ' + message; - } - assert(count >= expectedCount, 'missing arguemnt' + message, 'MISSING_ARGUMENT', { - count: count, - expectedCount: expectedCount, - }); - assert(count <= expectedCount, 'too many arguemnts' + message, 'UNEXPECTED_ARGUMENT', { - count: count, - expectedCount: expectedCount, - }); - } - const _normalizeForms = ['NFD', 'NFC', 'NFKD', 'NFKC'].reduce((accum, form) => { - try { - // General test for normalize - /* c8 ignore start */ - if ('test'.normalize(form) !== 'test') { - throw new Error('bad'); - } - /* c8 ignore stop */ - if (form === 'NFD') { - const check = String.fromCharCode(0xe9).normalize('NFD'); - const expected = String.fromCharCode(0x65, 0x0301); - /* c8 ignore start */ - if (check !== expected) { - throw new Error('broken'); - } - /* c8 ignore stop */ - } - accum.push(form); - // eslint-disable-next-line no-empty - } - catch (error) { } - return accum; - }, []); - /** - * Throws if the normalization `form` is not supported. - * - * @category Utils - * @param {string} form - The normalization form. - * @throws {UnsupportedOperationError} Throws if the form is not supported. - */ - function assertNormalize(form) { - assert(_normalizeForms.indexOf(form) >= 0, 'platform missing String.prototype.normalize', 'UNSUPPORTED_OPERATION', { - operation: 'String.prototype.normalize', - info: { form }, - }); - } - /** - * Many classes use file-scoped values to guard the constructor, making it effectively private. This facilitates that - * pattern by ensuring the `givenGuard` matches the file-scoped `guard`, throwing if not, indicating the `className%% if - * provided. - * - * @category Utils - * @param {any} givenGuard - The guard provided to the constructor. - * @param {any} guard - The file-scoped guard. - * @param {string} [className] - The class name. - * @throws {UnsupportedOperationError} Throws if the guards do not match. - */ - function assertPrivate(givenGuard, guard, className) { - if (className == null) { - className = ''; - } - if (givenGuard !== guard) { - let method = className, operation = 'new'; - if (className) { - method += '.'; - operation += ' ' + className; - } - assert(false, `private constructor; use ${method}from* methods`, 'UNSUPPORTED_OPERATION', { - operation, - }); - } - } - - /** - * Some data helpers. - */ - /** - * Converts a BytesLike value to a Uint8Array. - * - * @ignore - * @category Utils - * @param {BytesLike} value - The value to convert. - * @param {string} [name] - The name of the value for error context. - * @param {boolean} [copy] - Whether to create a copy of the value. - * - * @returns {Uint8Array} The converted Uint8Array. - * @throws {Error} If the value is not a valid BytesLike. - */ - function _getBytes(value, name, copy) { - if (value instanceof Uint8Array) { - if (copy) { - return new Uint8Array(value); - } - return value; - } - if (typeof value === 'string' && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) { - const result = new Uint8Array((value.length - 2) / 2); - let offset = 2; - for (let i = 0; i < result.length; i++) { - result[i] = parseInt(value.substring(offset, offset + 2), 16); - offset += 2; - } - return result; - } - assertArgument(false, 'invalid BytesLike value', name || 'value', value); - } - /** - * Get a typed Uint8Array for `value`. If already a Uint8Array the original `value` is returned; if a copy is required - * use {@link getBytesCopy | **getBytesCopy**}. - * - * @category Utils - * @param {BytesLike} value - The value to convert to a Uint8Array. - * @param {string} [name] - The name of the value for error context. - * - * @returns {Uint8Array} The typed Uint8Array. - */ - function getBytes(value, name) { - return _getBytes(value, name, false); - } - /** - * Get a typed Uint8Array for `value`, creating a copy if necessary to prevent any modifications of the returned value - * from being reflected elsewhere. - * - * @category Utils - * @param {BytesLike} value - The value to convert to a Uint8Array. - * @param {string} [name] - The name of the value for error context. - * - * @returns {Uint8Array} The typed Uint8Array. - */ - function getBytesCopy(value, name) { - return _getBytes(value, name, true); - } - /** - * Returns true if `value` is a valid {@link HexString | **HexString**}. - * - * If `length` is `true` or a number, it also checks that `value` is a valid {@link DataHexString | **DataHexString**} of - * `length` (if a number) bytes of data (e.g. `0x1234` is 2 bytes). - * - * @category Utils - * @param {any} value - The value to check. - * @param {number | boolean} [length] - The expected length of the data. - * - * @returns {boolean} True if the value is a valid {@link HexString | **HexString**}. - */ - function isHexString(value, length) { - if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { - return false; - } - if (typeof length === 'number' && value.length !== 2 + 2 * length) { - return false; - } - if (length === true && value.length % 2 !== 0) { - return false; - } - return true; - } - /** - * Returns true if `value` is a valid representation of arbitrary data (i.e. a valid - * {@link DataHexString | **DataHexString**} or a Uint8Array). - * - * @category Utils - * @param {any} value - The value to check. - * - * @returns {boolean} True if the value is a valid {@link DataHexString | **DataHexString**}. - */ - function isBytesLike(value) { - return isHexString(value, true) || value instanceof Uint8Array; - } - const HexCharacters = '0123456789abcdef'; - /** - * Returns a {@link DataHexString | **DataHexString**} representation of `data`. - * - * @category Utils - * @param {BytesLike} data - The data to convert to a hex string. - * - * @returns {string} The hex string. - */ - function hexlify(data) { - const bytes = getBytes(data); - let result = '0x'; - for (let i = 0; i < bytes.length; i++) { - const v = bytes[i]; - result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; - } - return result; - } - /** - * Returns a {@link DataHexString | **DataHexString** } by concatenating all values within `data`. - * - * @category Utils - * @param {ReadonlyArray} datas - The data to concatenate. - * - * @returns {string} The concatenated data. - */ - function concat(datas) { - return '0x' + datas.map((d) => hexlify(d).substring(2)).join(''); - } - /** - * Returns the length of `data`, in bytes. - * - * @category Utils - * @param {BytesLike} data - The data to get the length of. - * - * @returns {number} The length of the data. - */ - function dataLength(data) { - if (isHexString(data, true)) { - return (data.length - 2) / 2; - } - return getBytes(data).length; - } - /** - * Returns a {@link DataHexString | **DataHexString** } by slicing `data` from the `start` offset to the `end` offset. - * - * By default `start` is 0 and `end` is the length of `data`. - * - * @category Utils - * @param {BytesLike} data - The data to slice. - * @param {number} [start] - The start offset. - * @param {number} [end] - The end offset. - * - * @returns {string} The sliced data. - * @throws {Error} If the end offset is beyond the data bounds. - */ - function dataSlice(data, start, end) { - const bytes = getBytes(data); - if (end != null && end > bytes.length) { - assert(false, 'cannot slice beyond data bounds', 'BUFFER_OVERRUN', { - buffer: bytes, - length: bytes.length, - offset: end, - }); - } - return hexlify(bytes.slice(start == null ? 0 : start, end == null ? bytes.length : end)); - } - /** - * Return the {@link DataHexString | **DataHexString**} result by stripping all **leading** zero bytes from `data`. - * - * @category Utils - * @param {BytesLike} data - The data to strip. - * - * @returns {string} The stripped data. - */ - function stripZerosLeft(data) { - let bytes = hexlify(data).substring(2); - while (bytes.startsWith('00')) { - bytes = bytes.substring(2); - } - return '0x' + bytes; - } - /** - * Pads the data to the specified length. - * - * @ignore - * @category Utils - * @param {BytesLike} data - The data to pad. - * @param {number} length - The length to pad to. - * @param {boolean} left - Whether to pad on the left. - * - * @returns {string} The padded data. - * @throws {Error} If the padding exceeds data length. - */ - function zeroPad(data, length, left) { - const bytes = getBytes(data); - assert(length >= bytes.length, 'padding exceeds data length', 'BUFFER_OVERRUN', { - buffer: new Uint8Array(bytes), - length: length, - offset: length + 1, - }); - const result = new Uint8Array(length); - result.fill(0); - if (left) { - result.set(bytes, length - bytes.length); - } - else { - result.set(bytes, 0); - } - return hexlify(result); - } - /** - * Return the {@link DataHexString | **DataHexString**} of `data` padded on the **left** to `length` bytes. - * - * If `data` already exceeds `length`, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown. - * - * This pads data the same as **values** are in Solidity (e.g. `uint128`). - * - * @category Utils - * @param {BytesLike} data - The data to pad. - * @param {number} length - The length to pad to. - * - * @returns {string} The padded data. - */ - function zeroPadValue(data, length) { - return zeroPad(data, length, true); - } - /** - * Return the {@link DataHexString | **DataHexString**} of `data` padded on the **right** to `length` bytes. - * - * If `data` already exceeds %%length%%, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown. - * - * This pads data the same as **bytes** are in Solidity (e.g. `bytes16`). - * - * @category Utils - * @param {BytesLike} data - The data to pad. - * @param {number} length - The length to pad to. - * - * @returns {string} The padded data. - */ - function zeroPadBytes(data, length) { - return zeroPad(data, length, false); - } - - /** - * When an {@link EventEmitterable | **EventEmitterable**} triggers a Listener, the callback always ahas one additional - * argument passed, which is an **EventPayload**. - * - * @category Utils - */ - class EventPayload { - /** - * The event filter. - */ - filter; - /** - * The **EventEmitterable**. - */ - emitter; - #listener; - /** - * Create a new **EventPayload** for `emitter` with the `listener` and for `filter`. - */ - constructor(emitter, listener, filter) { - this.#listener = listener; - defineProperties(this, { emitter, filter }); - } - /** - * Unregister the triggered listener for future events. - */ - async removeListener() { - if (this.#listener == null) { - return; - } - await this.emitter.off(this.filter, this.#listener); - } - } - - function decodeBase64(textData) { - textData = atob(textData); - const data = new Uint8Array(textData.length); - for (let i = 0; i < textData.length; i++) { - data[i] = textData.charCodeAt(i); - } - return getBytes(data); - } - function encodeBase64(_data) { - const data = getBytes(_data); - let textData = ''; - for (let i = 0; i < data.length; i++) { - textData += String.fromCharCode(data[i]); - } - return btoa(textData); - } - - /** - * Provides utility functions for encoding and decoding strings in the Bytes32 format. - * - * @category Application Binary Interface - */ - /** - * Encodes a string as a Bytes32 string. This is used to encode ABI data. - * - * @category Encoding - * @param {string} text - The string to encode. - * - * @returns {string} The Bytes32-encoded string. - * @throws {Error} If the string is too long to fit in a Bytes32 format. - */ - function encodeBytes32(text) { - // Get the bytes - const bytes = toUtf8Bytes(text); - // Check we have room for null-termination - if (bytes.length > 31) { - throw new Error('bytes32 string must be less than 32 bytes'); - } - // Zero-pad (implicitly null-terminates) - return zeroPadBytes(bytes, 32); - } - /** - * Decodes a Bytes32-encoded string into a regular string. This is used to decode ABI-encoded data. - * - * @category Encoding - * @param {BytesLike} _bytes - The Bytes32-encoded data. - * - * @returns {string} The decoded string. - * @throws {Error} If the input is not exactly 32 bytes long or lacks a null terminator. - */ - function decodeBytes32(_bytes) { - const data = getBytes(_bytes, 'bytes'); - // Must be 32 bytes with a null-termination - if (data.length !== 32) { - throw new Error('invalid bytes32 - not 32 bytes long'); - } - if (data[31] !== 0) { - throw new Error('invalid bytes32 string - no null terminator'); - } - // Find the null termination - let length = 31; - while (data[length - 1] === 0) { - length--; - } - // Determine the string value - return toUtf8String(data.slice(0, length)); - } - - /** - * Some mathematic operations. - */ - const BN_0$8 = BigInt(0); - const BN_1$4 = BigInt(1); - //const BN_Max256 = (BN_1 << BigInt(256)) - BN_1; - // IEEE 754 support 53-bits of mantissa - const maxValue = 0x1fffffffffffff; - /** - * Convert `value` from a twos-compliment representation of `width` bits to its value. - * - * If the highest bit is `1`, the result will be negative. - * - * @category Utils - * @param {BigNumberish} _value - The value to convert. - * @param {Numeric} _width - The width of the value in bits. - * @returns {bigint} The value. - * @throws {Error} If the value is too large for the width. - */ - function fromTwos(_value, _width) { - const value = getUint(_value, 'value'); - const width = BigInt(getNumber(_width, 'width')); - assert(value >> width === BN_0$8, 'overflow', 'NUMERIC_FAULT', { - operation: 'fromTwos', - fault: 'overflow', - value: _value, - }); - // Top bit set; treat as a negative value - if (value >> (width - BN_1$4)) { - const mask = (BN_1$4 << width) - BN_1$4; - return -((~value & mask) + BN_1$4); - } - return value; - } - /** - * Convert `value` to a twos-compliment representation of `width` bits. - * - * The result will always be positive. - * - * @category Utils - * @param {BigNumberish} _value - The value to convert. - * @param {Numeric} _width - The width of the value in bits. - * @returns {bigint} The value. - * @throws {Error} If the value is too large for the width. - */ - function toTwos(_value, _width) { - let value = getBigInt(_value, 'value'); - const width = BigInt(getNumber(_width, 'width')); - const limit = BN_1$4 << (width - BN_1$4); - if (value < BN_0$8) { - value = -value; - assert(value <= limit, 'too low', 'NUMERIC_FAULT', { - operation: 'toTwos', - fault: 'overflow', - value: _value, - }); - const mask = (BN_1$4 << width) - BN_1$4; - return (~value & mask) + BN_1$4; - } - else { - assert(value < limit, 'too high', 'NUMERIC_FAULT', { - operation: 'toTwos', - fault: 'overflow', - value: _value, - }); - } - return value; - } - /** - * Mask `value` with a bitmask of `bits` ones. - * - * @category Utils - * @param {BigNumberish} _value - The value to mask. - * @param {Numeric} _bits - The number of bits to mask. - * @returns {bigint} The masked value. - */ - function mask(_value, _bits) { - const value = getUint(_value, 'value'); - const bits = BigInt(getNumber(_bits, 'bits')); - return value & ((BN_1$4 << bits) - BN_1$4); - } - /** - * Gets a BigInt from `value`. If it is an invalid value for a BigInt, then an ArgumentError will be thrown for `name`. - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @param {string} name - The name of the value. - * @returns {bigint} The value. - */ - function getBigInt(value, name) { - switch (typeof value) { - case 'bigint': - return value; - case 'number': - assertArgument(Number.isInteger(value), 'underflow', name || 'value', value); - assertArgument(value >= -maxValue && value <= maxValue, 'overflow', name || 'value', value); - return BigInt(value); - case 'string': - try { - if (value === '') { - throw new Error('empty string'); - } - if (value[0] === '-' && value[1] !== '-') { - return -BigInt(value.substring(1)); - } - return BigInt(value); - } - catch (e) { - assertArgument(false, `invalid BigNumberish string: ${e.message}`, name || 'value', value); - } - } - assertArgument(false, 'invalid BigNumberish value', name || 'value', value); - } - /** - * Returns absolute value of bigint `value`. - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @returns {bigint} The absolute value. - */ - function bigIntAbs(value) { - value = getBigInt(value); - // if value is negative (including -0), return -value, else return value - if (value === -BN_0$8 || value < BN_0$8) { - return -value; - } - return value; - } - /** - * Returns `value` as a bigint, validating it is valid as a bigint value and that it is positive. - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @param {string} name - The name of the value. - * @returns {bigint} The value. - * @throws {Error} If the value is negative. - */ - function getUint(value, name) { - const result = getBigInt(value, name); - assert(result >= BN_0$8, 'unsigned value cannot be negative', 'NUMERIC_FAULT', { - fault: 'overflow', - operation: 'getUint', - value, - }); - return result; - } - const Nibbles$1 = '0123456789abcdef'; - /** - * Converts `value` to a BigInt. If `value` is a Uint8Array, it is treated as Big Endian data. - * - * @category Utils - * @param {BigNumberish | Uint8Array} value - The value to convert. - * @returns {bigint} The value. - */ - function toBigInt(value) { - if (value instanceof Uint8Array) { - let result = '0x0'; - for (const v of value) { - result += Nibbles$1[v >> 4]; - result += Nibbles$1[v & 0x0f]; - } - return BigInt(result); - } - return getBigInt(value); - } - /** - * Gets a number from `value`. If it is an invalid value for a number, then an ArgumentError will be thrown for `name`. - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @param {string} name - The name of the value. - * @returns {number} The value. - * @throws {Error} If the value is invalid. - * @throws {Error} If the value is too large. - */ - function getNumber(value, name) { - switch (typeof value) { - case 'bigint': - assertArgument(value >= -maxValue && value <= maxValue, 'overflow', name || 'value', value); - return Number(value); - case 'number': - assertArgument(Number.isInteger(value), 'underflow', name || 'value', value); - assertArgument(value >= -maxValue && value <= maxValue, 'overflow', name || 'value', value); - return value; - case 'string': - try { - if (value === '') { - throw new Error('empty string'); - } - return getNumber(BigInt(value), name); - } - catch (e) { - assertArgument(false, `invalid numeric string: ${e.message}`, name || 'value', value); - } - } - assertArgument(false, 'invalid numeric value', name || 'value', value); - } - /** - * Converts `value` to a number. If `value` is a Uint8Array, it is treated as Big Endian data. Throws if the value is - * not safe. - * - * @category Utils - * @param {BigNumberish | Uint8Array} value - The value to convert. - * @returns {number} The value. - * @throws {Error} If the value is not safe to convert to a number. - */ - function toNumber(value) { - return getNumber(toBigInt(value)); - } - /** - * Converts `value` to a Big Endian hexstring, optionally padded to `width` bytes. - * - * @category Utils - * @param {BigNumberish} _value - The value to convert. - * @param {Numeric} _width - The width of the value in bytes. - * @returns {string} The hexstring. - * @throws {Error} If the value exceeds the width. - */ - function toBeHex(_value, _width) { - const value = getUint(_value, 'value'); - let result = value.toString(16); - if (_width == null) { - // Ensure the value is of even length - if (result.length % 2) { - result = '0' + result; - } - } - else { - const width = getNumber(_width, 'width'); - assert(width * 2 >= result.length, `value exceeds width (${width} bytes)`, 'NUMERIC_FAULT', { - operation: 'toBeHex', - fault: 'overflow', - value: _value, - }); - // Pad the value to the required width - while (result.length < width * 2) { - result = '0' + result; - } - } - return '0x' + result; - } - /** - * Converts `value` to a Big Endian Uint8Array. - * - * @category Utils - * @param {BigNumberish} _value - The value to convert. - * @returns {Uint8Array} The value. - */ - function toBeArray(_value) { - const value = getUint(_value, 'value'); - if (value === BN_0$8) { - return new Uint8Array([]); - } - let hex = value.toString(16); - if (hex.length % 2) { - hex = '0' + hex; - } - const result = new Uint8Array(hex.length / 2); - for (let i = 0; i < result.length; i++) { - const offset = i * 2; - result[i] = parseInt(hex.substring(offset, offset + 2), 16); - } - return result; - } - /** - * Returns a `HexString` for `value` safe to use as a Quantity. - * - * A Quantity does not have and leading 0 values unless the value is the literal value `0x0`. This is most commonly used - * for JSSON-RPC numeric values. - * - * @category Utils - * @param {BigNumberish | Uint8Array} value - The value to convert. - * @returns {string} The quantity. - */ - function toQuantity(value) { - let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2); - while (result.startsWith('0')) { - result = result.substring(1); - } - if (result === '') { - result = '0'; - } - return '0x' + result; - } - - /** - * The [Base58 Encoding](https://en.bitcoinwiki.org/wiki/Base58) scheme allows a **numeric** value to be encoded as a - * compact string using a radix of 58 using only alpha-numeric characters. Confusingly similar characters are omitted - * (i.e. `"l0O"`). - * - * Note that Base58 encodes a **numeric** value, not arbitrary bytes, since any zero-bytes on the left would get - * removed. To mitigate this issue most schemes that use Base58 choose specific high-order values to ensure non-zero - * prefixes. - */ - const Alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; - let Lookup = null; - function getAlpha(letter) { - if (Lookup == null) { - Lookup = {}; - for (let i = 0; i < Alphabet.length; i++) { - Lookup[Alphabet[i]] = BigInt(i); - } - } - const result = Lookup[letter]; - assertArgument(result != null, `invalid base58 value`, 'letter', letter); - return result; - } - const BN_0$7 = BigInt(0); - const BN_58 = BigInt(58); - /** - * Encode `value` as a Base58-encoded string. - * - * @category Encoding - * @param {BytesLike} _value - The value to encode. - * - * @returns {string} The Base58-encoded string. - */ - function encodeBase58(_value) { - const bytes = getBytes(_value); - let value = toBigInt(bytes); - let result = ''; - while (value) { - result = Alphabet[Number(value % BN_58)] + result; - value /= BN_58; - } - // Account for leading padding zeros - for (let i = 0; i < bytes.length; i++) { - if (bytes[i]) { - break; - } - result = Alphabet[0] + result; - } - return result; - } - /** - * Decode the Base58-encoded `value`. - * - * @category Encoding - * @param {string} value - The Base58-encoded value. - * - * @returns {bigint} The decoded value. - */ - function decodeBase58(value) { - let result = BN_0$7; - for (let i = 0; i < value.length; i++) { - result *= BN_58; - result += getAlpha(value[i]); - } - return result; - } - - /** - * Generated by the protoc-gen-ts. DO NOT EDIT! - * compiler version: 4.25.3 - * source: proto_common.proto - * git: https://github.com/thesayyn/protoc-gen-ts */ - var common; - (function (common) { - class ProtoLocation extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - } - } - get value() { - return pb_1__namespace.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set value(value) { - pb_1__namespace.Message.setField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoLocation({}); - if (data.value != null) { - message.value = data.value; - } - return message; - } - toObject() { - const data = {}; - if (this.value != null) { - data.value = this.value; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.value.length) - writer.writeBytes(1, this.value); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoLocation(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.value = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoLocation.deserialize(bytes); - } - } - common.ProtoLocation = ProtoLocation; - class ProtoHash extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - } - } - get value() { - return pb_1__namespace.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set value(value) { - pb_1__namespace.Message.setField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoHash({}); - if (data.value != null) { - message.value = data.value; - } - return message; - } - toObject() { - const data = {}; - if (this.value != null) { - data.value = this.value; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.value.length) - writer.writeBytes(1, this.value); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoHash(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.value = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoHash.deserialize(bytes); - } - } - common.ProtoHash = ProtoHash; - class ProtoHashes extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("hashes" in data && data.hashes != undefined) { - this.hashes = data.hashes; - } - } - } - get hashes() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoHash, 1); - } - set hashes(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoHashes({}); - if (data.hashes != null) { - message.hashes = data.hashes.map(item => ProtoHash.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.hashes != null) { - data.hashes = this.hashes.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.hashes.length) - writer.writeRepeatedMessage(1, this.hashes, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoHashes(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.hashes, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoHash.deserialize(reader), ProtoHash)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoHashes.deserialize(bytes); - } - } - common.ProtoHashes = ProtoHashes; - class ProtoAddress extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - } - } - get value() { - return pb_1__namespace.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set value(value) { - pb_1__namespace.Message.setField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoAddress({}); - if (data.value != null) { - message.value = data.value; - } - return message; - } - toObject() { - const data = {}; - if (this.value != null) { - data.value = this.value; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.value.length) - writer.writeBytes(1, this.value); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoAddress(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.value = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoAddress.deserialize(bytes); - } - } - common.ProtoAddress = ProtoAddress; - class ProtoNumber extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - } - } - get value() { - return pb_1__namespace.Message.getFieldWithDefault(this, 1, 0); - } - set value(value) { - pb_1__namespace.Message.setField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoNumber({}); - if (data.value != null) { - message.value = data.value; - } - return message; - } - toObject() { - const data = {}; - if (this.value != null) { - data.value = this.value; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.value != 0) - writer.writeUint64(1, this.value); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoNumber(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.value = reader.readUint64(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoNumber.deserialize(bytes); - } - } - common.ProtoNumber = ProtoNumber; - class ProtoLocations extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("locations" in data && data.locations != undefined) { - this.locations = data.locations; - } - } - } - get locations() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoLocation, 1); - } - set locations(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoLocations({}); - if (data.locations != null) { - message.locations = data.locations.map(item => ProtoLocation.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.locations != null) { - data.locations = this.locations.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.locations.length) - writer.writeRepeatedMessage(1, this.locations, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoLocations(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.locations, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoLocation.deserialize(reader), ProtoLocation)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoLocations.deserialize(bytes); - } - } - common.ProtoLocations = ProtoLocations; - })(common || (common = {})); - - /** - * Generated by the protoc-gen-ts. DO NOT EDIT! - * compiler version: 4.25.3 - * source: proto_block.proto - * git: https://github.com/thesayyn/protoc-gen-ts */ - var block; - (function (block) { - class ProtoHeader extends pb_1__namespace.Message { - #one_of_decls = [[2], [3], [4], [5], [6], [7], [9], [10], [14], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1, 8, 11, 12, 13, 15], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("parent_hash" in data && data.parent_hash != undefined) { - this.parent_hash = data.parent_hash; - } - if ("uncle_hash" in data && data.uncle_hash != undefined) { - this.uncle_hash = data.uncle_hash; - } - if ("coinbase" in data && data.coinbase != undefined) { - this.coinbase = data.coinbase; - } - if ("evm_root" in data && data.evm_root != undefined) { - this.evm_root = data.evm_root; - } - if ("tx_hash" in data && data.tx_hash != undefined) { - this.tx_hash = data.tx_hash; - } - if ("etx_hash" in data && data.etx_hash != undefined) { - this.etx_hash = data.etx_hash; - } - if ("etx_rollup_hash" in data && data.etx_rollup_hash != undefined) { - this.etx_rollup_hash = data.etx_rollup_hash; - } - if ("manifest_hash" in data && data.manifest_hash != undefined) { - this.manifest_hash = data.manifest_hash; - } - if ("receipt_hash" in data && data.receipt_hash != undefined) { - this.receipt_hash = data.receipt_hash; - } - if ("difficulty" in data && data.difficulty != undefined) { - this.difficulty = data.difficulty; - } - if ("parent_entropy" in data && data.parent_entropy != undefined) { - this.parent_entropy = data.parent_entropy; - } - if ("parent_delta_s" in data && data.parent_delta_s != undefined) { - this.parent_delta_s = data.parent_delta_s; - } - if ("parent_uncled_sub_delta_s" in data && data.parent_uncled_sub_delta_s != undefined) { - this.parent_uncled_sub_delta_s = data.parent_uncled_sub_delta_s; - } - if ("uncled_s" in data && data.uncled_s != undefined) { - this.uncled_s = data.uncled_s; - } - if ("number" in data && data.number != undefined) { - this.number = data.number; - } - if ("gas_limit" in data && data.gas_limit != undefined) { - this.gas_limit = data.gas_limit; - } - if ("gas_used" in data && data.gas_used != undefined) { - this.gas_used = data.gas_used; - } - if ("base_fee" in data && data.base_fee != undefined) { - this.base_fee = data.base_fee; - } - if ("location" in data && data.location != undefined) { - this.location = data.location; - } - if ("extra" in data && data.extra != undefined) { - this.extra = data.extra; - } - if ("mix_hash" in data && data.mix_hash != undefined) { - this.mix_hash = data.mix_hash; - } - if ("nonce" in data && data.nonce != undefined) { - this.nonce = data.nonce; - } - if ("utxo_root" in data && data.utxo_root != undefined) { - this.utxo_root = data.utxo_root; - } - if ("etx_set_hash" in data && data.etx_set_hash != undefined) { - this.etx_set_hash = data.etx_set_hash; - } - if ("efficiency_score" in data && data.efficiency_score != undefined) { - this.efficiency_score = data.efficiency_score; - } - if ("threshold_count" in data && data.threshold_count != undefined) { - this.threshold_count = data.threshold_count; - } - if ("expansion_number" in data && data.expansion_number != undefined) { - this.expansion_number = data.expansion_number; - } - if ("etx_eligible_slices" in data && data.etx_eligible_slices != undefined) { - this.etx_eligible_slices = data.etx_eligible_slices; - } - if ("prime_terminus" in data && data.prime_terminus != undefined) { - this.prime_terminus = data.prime_terminus; - } - if ("interlink_root_hash" in data && data.interlink_root_hash != undefined) { - this.interlink_root_hash = data.interlink_root_hash; - } - } - } - get parent_hash() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, common.ProtoHash, 1); - } - set parent_hash(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - get uncle_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 2); - } - set uncle_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 2, this.#one_of_decls[0], value); - } - get has_uncle_hash() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get coinbase() { - return pb_1__namespace.Message.getFieldWithDefault(this, 3, new Uint8Array(0)); - } - set coinbase(value) { - pb_1__namespace.Message.setOneofField(this, 3, this.#one_of_decls[1], value); - } - get has_coinbase() { - return pb_1__namespace.Message.getField(this, 3) != null; - } - get evm_root() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 4); - } - set evm_root(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 4, this.#one_of_decls[2], value); - } - get has_evm_root() { - return pb_1__namespace.Message.getField(this, 4) != null; - } - get tx_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 5); - } - set tx_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 5, this.#one_of_decls[3], value); - } - get has_tx_hash() { - return pb_1__namespace.Message.getField(this, 5) != null; - } - get etx_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 6); - } - set etx_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 6, this.#one_of_decls[4], value); - } - get has_etx_hash() { - return pb_1__namespace.Message.getField(this, 6) != null; - } - get etx_rollup_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 7); - } - set etx_rollup_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 7, this.#one_of_decls[5], value); - } - get has_etx_rollup_hash() { - return pb_1__namespace.Message.getField(this, 7) != null; - } - get manifest_hash() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, common.ProtoHash, 8); - } - set manifest_hash(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 8, value); - } - get receipt_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 9); - } - set receipt_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 9, this.#one_of_decls[6], value); - } - get has_receipt_hash() { - return pb_1__namespace.Message.getField(this, 9) != null; - } - get difficulty() { - return pb_1__namespace.Message.getFieldWithDefault(this, 10, new Uint8Array(0)); - } - set difficulty(value) { - pb_1__namespace.Message.setOneofField(this, 10, this.#one_of_decls[7], value); - } - get has_difficulty() { - return pb_1__namespace.Message.getField(this, 10) != null; - } - get parent_entropy() { - return pb_1__namespace.Message.getFieldWithDefault(this, 11, []); - } - set parent_entropy(value) { - pb_1__namespace.Message.setField(this, 11, value); - } - get parent_delta_s() { - return pb_1__namespace.Message.getFieldWithDefault(this, 12, []); - } - set parent_delta_s(value) { - pb_1__namespace.Message.setField(this, 12, value); - } - get parent_uncled_sub_delta_s() { - return pb_1__namespace.Message.getFieldWithDefault(this, 13, []); - } - set parent_uncled_sub_delta_s(value) { - pb_1__namespace.Message.setField(this, 13, value); - } - get uncled_s() { - return pb_1__namespace.Message.getFieldWithDefault(this, 14, new Uint8Array(0)); - } - set uncled_s(value) { - pb_1__namespace.Message.setOneofField(this, 14, this.#one_of_decls[8], value); - } - get has_uncled_s() { - return pb_1__namespace.Message.getField(this, 14) != null; - } - get number() { - return pb_1__namespace.Message.getFieldWithDefault(this, 15, []); - } - set number(value) { - pb_1__namespace.Message.setField(this, 15, value); - } - get gas_limit() { - return pb_1__namespace.Message.getFieldWithDefault(this, 16, 0); - } - set gas_limit(value) { - pb_1__namespace.Message.setOneofField(this, 16, this.#one_of_decls[9], value); - } - get has_gas_limit() { - return pb_1__namespace.Message.getField(this, 16) != null; - } - get gas_used() { - return pb_1__namespace.Message.getFieldWithDefault(this, 17, 0); - } - set gas_used(value) { - pb_1__namespace.Message.setOneofField(this, 17, this.#one_of_decls[10], value); - } - get has_gas_used() { - return pb_1__namespace.Message.getField(this, 17) != null; - } - get base_fee() { - return pb_1__namespace.Message.getFieldWithDefault(this, 18, new Uint8Array(0)); - } - set base_fee(value) { - pb_1__namespace.Message.setOneofField(this, 18, this.#one_of_decls[11], value); - } - get has_base_fee() { - return pb_1__namespace.Message.getField(this, 18) != null; - } - get location() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoLocation, 19); - } - set location(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 19, this.#one_of_decls[12], value); - } - get has_location() { - return pb_1__namespace.Message.getField(this, 19) != null; - } - get extra() { - return pb_1__namespace.Message.getFieldWithDefault(this, 20, new Uint8Array(0)); - } - set extra(value) { - pb_1__namespace.Message.setOneofField(this, 20, this.#one_of_decls[13], value); - } - get has_extra() { - return pb_1__namespace.Message.getField(this, 20) != null; - } - get mix_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 21); - } - set mix_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 21, this.#one_of_decls[14], value); - } - get has_mix_hash() { - return pb_1__namespace.Message.getField(this, 21) != null; - } - get nonce() { - return pb_1__namespace.Message.getFieldWithDefault(this, 22, 0); - } - set nonce(value) { - pb_1__namespace.Message.setOneofField(this, 22, this.#one_of_decls[15], value); - } - get has_nonce() { - return pb_1__namespace.Message.getField(this, 22) != null; - } - get utxo_root() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 23); - } - set utxo_root(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 23, this.#one_of_decls[16], value); - } - get has_utxo_root() { - return pb_1__namespace.Message.getField(this, 23) != null; - } - get etx_set_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 24); - } - set etx_set_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 24, this.#one_of_decls[17], value); - } - get has_etx_set_hash() { - return pb_1__namespace.Message.getField(this, 24) != null; - } - get efficiency_score() { - return pb_1__namespace.Message.getFieldWithDefault(this, 25, 0); - } - set efficiency_score(value) { - pb_1__namespace.Message.setOneofField(this, 25, this.#one_of_decls[18], value); - } - get has_efficiency_score() { - return pb_1__namespace.Message.getField(this, 25) != null; - } - get threshold_count() { - return pb_1__namespace.Message.getFieldWithDefault(this, 26, 0); - } - set threshold_count(value) { - pb_1__namespace.Message.setOneofField(this, 26, this.#one_of_decls[19], value); - } - get has_threshold_count() { - return pb_1__namespace.Message.getField(this, 26) != null; - } - get expansion_number() { - return pb_1__namespace.Message.getFieldWithDefault(this, 27, 0); - } - set expansion_number(value) { - pb_1__namespace.Message.setOneofField(this, 27, this.#one_of_decls[20], value); - } - get has_expansion_number() { - return pb_1__namespace.Message.getField(this, 27) != null; - } - get etx_eligible_slices() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 28); - } - set etx_eligible_slices(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 28, this.#one_of_decls[21], value); - } - get has_etx_eligible_slices() { - return pb_1__namespace.Message.getField(this, 28) != null; - } - get prime_terminus() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 29); - } - set prime_terminus(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 29, this.#one_of_decls[22], value); - } - get has_prime_terminus() { - return pb_1__namespace.Message.getField(this, 29) != null; - } - get interlink_root_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 30); - } - set interlink_root_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 30, this.#one_of_decls[23], value); - } - get has_interlink_root_hash() { - return pb_1__namespace.Message.getField(this, 30) != null; - } - get _uncle_hash() { - const cases = { - 0: "none", - 2: "uncle_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - get _coinbase() { - const cases = { - 0: "none", - 3: "coinbase" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [3])]; - } - get _evm_root() { - const cases = { - 0: "none", - 4: "evm_root" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [4])]; - } - get _tx_hash() { - const cases = { - 0: "none", - 5: "tx_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [5])]; - } - get _etx_hash() { - const cases = { - 0: "none", - 6: "etx_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [6])]; - } - get _etx_rollup_hash() { - const cases = { - 0: "none", - 7: "etx_rollup_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [7])]; - } - get _receipt_hash() { - const cases = { - 0: "none", - 9: "receipt_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [9])]; - } - get _difficulty() { - const cases = { - 0: "none", - 10: "difficulty" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [10])]; - } - get _uncled_s() { - const cases = { - 0: "none", - 14: "uncled_s" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [14])]; - } - get _gas_limit() { - const cases = { - 0: "none", - 16: "gas_limit" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [16])]; - } - get _gas_used() { - const cases = { - 0: "none", - 17: "gas_used" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [17])]; - } - get _base_fee() { - const cases = { - 0: "none", - 18: "base_fee" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [18])]; - } - get _location() { - const cases = { - 0: "none", - 19: "location" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [19])]; - } - get _extra() { - const cases = { - 0: "none", - 20: "extra" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [20])]; - } - get _mix_hash() { - const cases = { - 0: "none", - 21: "mix_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [21])]; - } - get _nonce() { - const cases = { - 0: "none", - 22: "nonce" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [22])]; - } - get _utxo_root() { - const cases = { - 0: "none", - 23: "utxo_root" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [23])]; - } - get _etx_set_hash() { - const cases = { - 0: "none", - 24: "etx_set_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [24])]; - } - get _efficiency_score() { - const cases = { - 0: "none", - 25: "efficiency_score" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [25])]; - } - get _threshold_count() { - const cases = { - 0: "none", - 26: "threshold_count" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [26])]; - } - get _expansion_number() { - const cases = { - 0: "none", - 27: "expansion_number" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [27])]; - } - get _etx_eligible_slices() { - const cases = { - 0: "none", - 28: "etx_eligible_slices" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [28])]; - } - get _prime_terminus() { - const cases = { - 0: "none", - 29: "prime_terminus" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [29])]; - } - get _interlink_root_hash() { - const cases = { - 0: "none", - 30: "interlink_root_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [30])]; - } - static fromObject(data) { - const message = new ProtoHeader({}); - if (data.parent_hash != null) { - message.parent_hash = data.parent_hash.map(item => common.ProtoHash.fromObject(item)); - } - if (data.uncle_hash != null) { - message.uncle_hash = common.ProtoHash.fromObject(data.uncle_hash); - } - if (data.coinbase != null) { - message.coinbase = data.coinbase; - } - if (data.evm_root != null) { - message.evm_root = common.ProtoHash.fromObject(data.evm_root); - } - if (data.tx_hash != null) { - message.tx_hash = common.ProtoHash.fromObject(data.tx_hash); - } - if (data.etx_hash != null) { - message.etx_hash = common.ProtoHash.fromObject(data.etx_hash); - } - if (data.etx_rollup_hash != null) { - message.etx_rollup_hash = common.ProtoHash.fromObject(data.etx_rollup_hash); - } - if (data.manifest_hash != null) { - message.manifest_hash = data.manifest_hash.map(item => common.ProtoHash.fromObject(item)); - } - if (data.receipt_hash != null) { - message.receipt_hash = common.ProtoHash.fromObject(data.receipt_hash); - } - if (data.difficulty != null) { - message.difficulty = data.difficulty; - } - if (data.parent_entropy != null) { - message.parent_entropy = data.parent_entropy; - } - if (data.parent_delta_s != null) { - message.parent_delta_s = data.parent_delta_s; - } - if (data.parent_uncled_sub_delta_s != null) { - message.parent_uncled_sub_delta_s = data.parent_uncled_sub_delta_s; - } - if (data.uncled_s != null) { - message.uncled_s = data.uncled_s; - } - if (data.number != null) { - message.number = data.number; - } - if (data.gas_limit != null) { - message.gas_limit = data.gas_limit; - } - if (data.gas_used != null) { - message.gas_used = data.gas_used; - } - if (data.base_fee != null) { - message.base_fee = data.base_fee; - } - if (data.location != null) { - message.location = common.ProtoLocation.fromObject(data.location); - } - if (data.extra != null) { - message.extra = data.extra; - } - if (data.mix_hash != null) { - message.mix_hash = common.ProtoHash.fromObject(data.mix_hash); - } - if (data.nonce != null) { - message.nonce = data.nonce; - } - if (data.utxo_root != null) { - message.utxo_root = common.ProtoHash.fromObject(data.utxo_root); - } - if (data.etx_set_hash != null) { - message.etx_set_hash = common.ProtoHash.fromObject(data.etx_set_hash); - } - if (data.efficiency_score != null) { - message.efficiency_score = data.efficiency_score; - } - if (data.threshold_count != null) { - message.threshold_count = data.threshold_count; - } - if (data.expansion_number != null) { - message.expansion_number = data.expansion_number; - } - if (data.etx_eligible_slices != null) { - message.etx_eligible_slices = common.ProtoHash.fromObject(data.etx_eligible_slices); - } - if (data.prime_terminus != null) { - message.prime_terminus = common.ProtoHash.fromObject(data.prime_terminus); - } - if (data.interlink_root_hash != null) { - message.interlink_root_hash = common.ProtoHash.fromObject(data.interlink_root_hash); - } - return message; - } - toObject() { - const data = {}; - if (this.parent_hash != null) { - data.parent_hash = this.parent_hash.map((item) => item.toObject()); - } - if (this.uncle_hash != null) { - data.uncle_hash = this.uncle_hash.toObject(); - } - if (this.coinbase != null) { - data.coinbase = this.coinbase; - } - if (this.evm_root != null) { - data.evm_root = this.evm_root.toObject(); - } - if (this.tx_hash != null) { - data.tx_hash = this.tx_hash.toObject(); - } - if (this.etx_hash != null) { - data.etx_hash = this.etx_hash.toObject(); - } - if (this.etx_rollup_hash != null) { - data.etx_rollup_hash = this.etx_rollup_hash.toObject(); - } - if (this.manifest_hash != null) { - data.manifest_hash = this.manifest_hash.map((item) => item.toObject()); - } - if (this.receipt_hash != null) { - data.receipt_hash = this.receipt_hash.toObject(); - } - if (this.difficulty != null) { - data.difficulty = this.difficulty; - } - if (this.parent_entropy != null) { - data.parent_entropy = this.parent_entropy; - } - if (this.parent_delta_s != null) { - data.parent_delta_s = this.parent_delta_s; - } - if (this.parent_uncled_sub_delta_s != null) { - data.parent_uncled_sub_delta_s = this.parent_uncled_sub_delta_s; - } - if (this.uncled_s != null) { - data.uncled_s = this.uncled_s; - } - if (this.number != null) { - data.number = this.number; - } - if (this.gas_limit != null) { - data.gas_limit = this.gas_limit; - } - if (this.gas_used != null) { - data.gas_used = this.gas_used; - } - if (this.base_fee != null) { - data.base_fee = this.base_fee; - } - if (this.location != null) { - data.location = this.location.toObject(); - } - if (this.extra != null) { - data.extra = this.extra; - } - if (this.mix_hash != null) { - data.mix_hash = this.mix_hash.toObject(); - } - if (this.nonce != null) { - data.nonce = this.nonce; - } - if (this.utxo_root != null) { - data.utxo_root = this.utxo_root.toObject(); - } - if (this.etx_set_hash != null) { - data.etx_set_hash = this.etx_set_hash.toObject(); - } - if (this.efficiency_score != null) { - data.efficiency_score = this.efficiency_score; - } - if (this.threshold_count != null) { - data.threshold_count = this.threshold_count; - } - if (this.expansion_number != null) { - data.expansion_number = this.expansion_number; - } - if (this.etx_eligible_slices != null) { - data.etx_eligible_slices = this.etx_eligible_slices.toObject(); - } - if (this.prime_terminus != null) { - data.prime_terminus = this.prime_terminus.toObject(); - } - if (this.interlink_root_hash != null) { - data.interlink_root_hash = this.interlink_root_hash.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.parent_hash.length) - writer.writeRepeatedMessage(1, this.parent_hash, (item) => item.serialize(writer)); - if (this.has_uncle_hash) - writer.writeMessage(2, this.uncle_hash, () => this.uncle_hash.serialize(writer)); - if (this.has_coinbase) - writer.writeBytes(3, this.coinbase); - if (this.has_evm_root) - writer.writeMessage(4, this.evm_root, () => this.evm_root.serialize(writer)); - if (this.has_tx_hash) - writer.writeMessage(5, this.tx_hash, () => this.tx_hash.serialize(writer)); - if (this.has_etx_hash) - writer.writeMessage(6, this.etx_hash, () => this.etx_hash.serialize(writer)); - if (this.has_etx_rollup_hash) - writer.writeMessage(7, this.etx_rollup_hash, () => this.etx_rollup_hash.serialize(writer)); - if (this.manifest_hash.length) - writer.writeRepeatedMessage(8, this.manifest_hash, (item) => item.serialize(writer)); - if (this.has_receipt_hash) - writer.writeMessage(9, this.receipt_hash, () => this.receipt_hash.serialize(writer)); - if (this.has_difficulty) - writer.writeBytes(10, this.difficulty); - if (this.parent_entropy.length) - writer.writeRepeatedBytes(11, this.parent_entropy); - if (this.parent_delta_s.length) - writer.writeRepeatedBytes(12, this.parent_delta_s); - if (this.parent_uncled_sub_delta_s.length) - writer.writeRepeatedBytes(13, this.parent_uncled_sub_delta_s); - if (this.has_uncled_s) - writer.writeBytes(14, this.uncled_s); - if (this.number.length) - writer.writeRepeatedBytes(15, this.number); - if (this.has_gas_limit) - writer.writeUint64(16, this.gas_limit); - if (this.has_gas_used) - writer.writeUint64(17, this.gas_used); - if (this.has_base_fee) - writer.writeBytes(18, this.base_fee); - if (this.has_location) - writer.writeMessage(19, this.location, () => this.location.serialize(writer)); - if (this.has_extra) - writer.writeBytes(20, this.extra); - if (this.has_mix_hash) - writer.writeMessage(21, this.mix_hash, () => this.mix_hash.serialize(writer)); - if (this.has_nonce) - writer.writeUint64(22, this.nonce); - if (this.has_utxo_root) - writer.writeMessage(23, this.utxo_root, () => this.utxo_root.serialize(writer)); - if (this.has_etx_set_hash) - writer.writeMessage(24, this.etx_set_hash, () => this.etx_set_hash.serialize(writer)); - if (this.has_efficiency_score) - writer.writeUint64(25, this.efficiency_score); - if (this.has_threshold_count) - writer.writeUint64(26, this.threshold_count); - if (this.has_expansion_number) - writer.writeUint64(27, this.expansion_number); - if (this.has_etx_eligible_slices) - writer.writeMessage(28, this.etx_eligible_slices, () => this.etx_eligible_slices.serialize(writer)); - if (this.has_prime_terminus) - writer.writeMessage(29, this.prime_terminus, () => this.prime_terminus.serialize(writer)); - if (this.has_interlink_root_hash) - writer.writeMessage(30, this.interlink_root_hash, () => this.interlink_root_hash.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoHeader(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.parent_hash, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - case 2: - reader.readMessage(message.uncle_hash, () => message.uncle_hash = common.ProtoHash.deserialize(reader)); - break; - case 3: - message.coinbase = reader.readBytes(); - break; - case 4: - reader.readMessage(message.evm_root, () => message.evm_root = common.ProtoHash.deserialize(reader)); - break; - case 5: - reader.readMessage(message.tx_hash, () => message.tx_hash = common.ProtoHash.deserialize(reader)); - break; - case 6: - reader.readMessage(message.etx_hash, () => message.etx_hash = common.ProtoHash.deserialize(reader)); - break; - case 7: - reader.readMessage(message.etx_rollup_hash, () => message.etx_rollup_hash = common.ProtoHash.deserialize(reader)); - break; - case 8: - reader.readMessage(message.manifest_hash, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 8, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - case 9: - reader.readMessage(message.receipt_hash, () => message.receipt_hash = common.ProtoHash.deserialize(reader)); - break; - case 10: - message.difficulty = reader.readBytes(); - break; - case 11: - pb_1__namespace.Message.addToRepeatedField(message, 11, reader.readBytes()); - break; - case 12: - pb_1__namespace.Message.addToRepeatedField(message, 12, reader.readBytes()); - break; - case 13: - pb_1__namespace.Message.addToRepeatedField(message, 13, reader.readBytes()); - break; - case 14: - message.uncled_s = reader.readBytes(); - break; - case 15: - pb_1__namespace.Message.addToRepeatedField(message, 15, reader.readBytes()); - break; - case 16: - message.gas_limit = reader.readUint64(); - break; - case 17: - message.gas_used = reader.readUint64(); - break; - case 18: - message.base_fee = reader.readBytes(); - break; - case 19: - reader.readMessage(message.location, () => message.location = common.ProtoLocation.deserialize(reader)); - break; - case 20: - message.extra = reader.readBytes(); - break; - case 21: - reader.readMessage(message.mix_hash, () => message.mix_hash = common.ProtoHash.deserialize(reader)); - break; - case 22: - message.nonce = reader.readUint64(); - break; - case 23: - reader.readMessage(message.utxo_root, () => message.utxo_root = common.ProtoHash.deserialize(reader)); - break; - case 24: - reader.readMessage(message.etx_set_hash, () => message.etx_set_hash = common.ProtoHash.deserialize(reader)); - break; - case 25: - message.efficiency_score = reader.readUint64(); - break; - case 26: - message.threshold_count = reader.readUint64(); - break; - case 27: - message.expansion_number = reader.readUint64(); - break; - case 28: - reader.readMessage(message.etx_eligible_slices, () => message.etx_eligible_slices = common.ProtoHash.deserialize(reader)); - break; - case 29: - reader.readMessage(message.prime_terminus, () => message.prime_terminus = common.ProtoHash.deserialize(reader)); - break; - case 30: - reader.readMessage(message.interlink_root_hash, () => message.interlink_root_hash = common.ProtoHash.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoHeader.deserialize(bytes); - } - } - block.ProtoHeader = ProtoHeader; - class ProtoTransaction extends pb_1__namespace.Message { - #one_of_decls = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("type" in data && data.type != undefined) { - this.type = data.type; - } - if ("to" in data && data.to != undefined) { - this.to = data.to; - } - if ("nonce" in data && data.nonce != undefined) { - this.nonce = data.nonce; - } - if ("value" in data && data.value != undefined) { - this.value = data.value; - } - if ("gas" in data && data.gas != undefined) { - this.gas = data.gas; - } - if ("data" in data && data.data != undefined) { - this.data = data.data; - } - if ("chain_id" in data && data.chain_id != undefined) { - this.chain_id = data.chain_id; - } - if ("gas_fee_cap" in data && data.gas_fee_cap != undefined) { - this.gas_fee_cap = data.gas_fee_cap; - } - if ("gas_tip_cap" in data && data.gas_tip_cap != undefined) { - this.gas_tip_cap = data.gas_tip_cap; - } - if ("access_list" in data && data.access_list != undefined) { - this.access_list = data.access_list; - } - if ("v" in data && data.v != undefined) { - this.v = data.v; - } - if ("r" in data && data.r != undefined) { - this.r = data.r; - } - if ("s" in data && data.s != undefined) { - this.s = data.s; - } - if ("originating_tx_hash" in data && data.originating_tx_hash != undefined) { - this.originating_tx_hash = data.originating_tx_hash; - } - if ("etx_index" in data && data.etx_index != undefined) { - this.etx_index = data.etx_index; - } - if ("tx_ins" in data && data.tx_ins != undefined) { - this.tx_ins = data.tx_ins; - } - if ("tx_outs" in data && data.tx_outs != undefined) { - this.tx_outs = data.tx_outs; - } - if ("signature" in data && data.signature != undefined) { - this.signature = data.signature; - } - if ("etx_sender" in data && data.etx_sender != undefined) { - this.etx_sender = data.etx_sender; - } - } - } - get type() { - return pb_1__namespace.Message.getFieldWithDefault(this, 1, 0); - } - set type(value) { - pb_1__namespace.Message.setOneofField(this, 1, this.#one_of_decls[0], value); - } - get has_type() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get to() { - return pb_1__namespace.Message.getFieldWithDefault(this, 2, new Uint8Array(0)); - } - set to(value) { - pb_1__namespace.Message.setOneofField(this, 2, this.#one_of_decls[1], value); - } - get has_to() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get nonce() { - return pb_1__namespace.Message.getFieldWithDefault(this, 3, 0); - } - set nonce(value) { - pb_1__namespace.Message.setOneofField(this, 3, this.#one_of_decls[2], value); - } - get has_nonce() { - return pb_1__namespace.Message.getField(this, 3) != null; - } - get value() { - return pb_1__namespace.Message.getFieldWithDefault(this, 4, new Uint8Array(0)); - } - set value(value) { - pb_1__namespace.Message.setOneofField(this, 4, this.#one_of_decls[3], value); - } - get has_value() { - return pb_1__namespace.Message.getField(this, 4) != null; - } - get gas() { - return pb_1__namespace.Message.getFieldWithDefault(this, 5, 0); - } - set gas(value) { - pb_1__namespace.Message.setOneofField(this, 5, this.#one_of_decls[4], value); - } - get has_gas() { - return pb_1__namespace.Message.getField(this, 5) != null; - } - get data() { - return pb_1__namespace.Message.getFieldWithDefault(this, 6, new Uint8Array(0)); - } - set data(value) { - pb_1__namespace.Message.setOneofField(this, 6, this.#one_of_decls[5], value); - } - get has_data() { - return pb_1__namespace.Message.getField(this, 6) != null; - } - get chain_id() { - return pb_1__namespace.Message.getFieldWithDefault(this, 7, new Uint8Array(0)); - } - set chain_id(value) { - pb_1__namespace.Message.setOneofField(this, 7, this.#one_of_decls[6], value); - } - get has_chain_id() { - return pb_1__namespace.Message.getField(this, 7) != null; - } - get gas_fee_cap() { - return pb_1__namespace.Message.getFieldWithDefault(this, 8, new Uint8Array(0)); - } - set gas_fee_cap(value) { - pb_1__namespace.Message.setOneofField(this, 8, this.#one_of_decls[7], value); - } - get has_gas_fee_cap() { - return pb_1__namespace.Message.getField(this, 8) != null; - } - get gas_tip_cap() { - return pb_1__namespace.Message.getFieldWithDefault(this, 9, new Uint8Array(0)); - } - set gas_tip_cap(value) { - pb_1__namespace.Message.setOneofField(this, 9, this.#one_of_decls[8], value); - } - get has_gas_tip_cap() { - return pb_1__namespace.Message.getField(this, 9) != null; - } - get access_list() { - return pb_1__namespace.Message.getWrapperField(this, ProtoAccessList, 10); - } - set access_list(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 10, this.#one_of_decls[9], value); - } - get has_access_list() { - return pb_1__namespace.Message.getField(this, 10) != null; - } - get v() { - return pb_1__namespace.Message.getFieldWithDefault(this, 11, new Uint8Array(0)); - } - set v(value) { - pb_1__namespace.Message.setOneofField(this, 11, this.#one_of_decls[10], value); - } - get has_v() { - return pb_1__namespace.Message.getField(this, 11) != null; - } - get r() { - return pb_1__namespace.Message.getFieldWithDefault(this, 12, new Uint8Array(0)); - } - set r(value) { - pb_1__namespace.Message.setOneofField(this, 12, this.#one_of_decls[11], value); - } - get has_r() { - return pb_1__namespace.Message.getField(this, 12) != null; - } - get s() { - return pb_1__namespace.Message.getFieldWithDefault(this, 13, new Uint8Array(0)); - } - set s(value) { - pb_1__namespace.Message.setOneofField(this, 13, this.#one_of_decls[12], value); - } - get has_s() { - return pb_1__namespace.Message.getField(this, 13) != null; - } - get originating_tx_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 14); - } - set originating_tx_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 14, this.#one_of_decls[13], value); - } - get has_originating_tx_hash() { - return pb_1__namespace.Message.getField(this, 14) != null; - } - get etx_index() { - return pb_1__namespace.Message.getFieldWithDefault(this, 15, 0); - } - set etx_index(value) { - pb_1__namespace.Message.setOneofField(this, 15, this.#one_of_decls[14], value); - } - get has_etx_index() { - return pb_1__namespace.Message.getField(this, 15) != null; - } - get tx_ins() { - return pb_1__namespace.Message.getWrapperField(this, ProtoTxIns, 16); - } - set tx_ins(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 16, this.#one_of_decls[15], value); - } - get has_tx_ins() { - return pb_1__namespace.Message.getField(this, 16) != null; - } - get tx_outs() { - return pb_1__namespace.Message.getWrapperField(this, ProtoTxOuts, 17); - } - set tx_outs(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 17, this.#one_of_decls[16], value); - } - get has_tx_outs() { - return pb_1__namespace.Message.getField(this, 17) != null; - } - get signature() { - return pb_1__namespace.Message.getFieldWithDefault(this, 18, new Uint8Array(0)); - } - set signature(value) { - pb_1__namespace.Message.setOneofField(this, 18, this.#one_of_decls[17], value); - } - get has_signature() { - return pb_1__namespace.Message.getField(this, 18) != null; - } - get etx_sender() { - return pb_1__namespace.Message.getFieldWithDefault(this, 19, new Uint8Array(0)); - } - set etx_sender(value) { - pb_1__namespace.Message.setOneofField(this, 19, this.#one_of_decls[18], value); - } - get has_etx_sender() { - return pb_1__namespace.Message.getField(this, 19) != null; - } - get _type() { - const cases = { - 0: "none", - 1: "type" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _to() { - const cases = { - 0: "none", - 2: "to" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - get _nonce() { - const cases = { - 0: "none", - 3: "nonce" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [3])]; - } - get _value() { - const cases = { - 0: "none", - 4: "value" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [4])]; - } - get _gas() { - const cases = { - 0: "none", - 5: "gas" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [5])]; - } - get _data() { - const cases = { - 0: "none", - 6: "data" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [6])]; - } - get _chain_id() { - const cases = { - 0: "none", - 7: "chain_id" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [7])]; - } - get _gas_fee_cap() { - const cases = { - 0: "none", - 8: "gas_fee_cap" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [8])]; - } - get _gas_tip_cap() { - const cases = { - 0: "none", - 9: "gas_tip_cap" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [9])]; - } - get _access_list() { - const cases = { - 0: "none", - 10: "access_list" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [10])]; - } - get _v() { - const cases = { - 0: "none", - 11: "v" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [11])]; - } - get _r() { - const cases = { - 0: "none", - 12: "r" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [12])]; - } - get _s() { - const cases = { - 0: "none", - 13: "s" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [13])]; - } - get _originating_tx_hash() { - const cases = { - 0: "none", - 14: "originating_tx_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [14])]; - } - get _etx_index() { - const cases = { - 0: "none", - 15: "etx_index" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [15])]; - } - get _tx_ins() { - const cases = { - 0: "none", - 16: "tx_ins" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [16])]; - } - get _tx_outs() { - const cases = { - 0: "none", - 17: "tx_outs" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [17])]; - } - get _signature() { - const cases = { - 0: "none", - 18: "signature" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [18])]; - } - get _etx_sender() { - const cases = { - 0: "none", - 19: "etx_sender" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [19])]; - } - static fromObject(data) { - const message = new ProtoTransaction({}); - if (data.type != null) { - message.type = data.type; - } - if (data.to != null) { - message.to = data.to; - } - if (data.nonce != null) { - message.nonce = data.nonce; - } - if (data.value != null) { - message.value = data.value; - } - if (data.gas != null) { - message.gas = data.gas; - } - if (data.data != null) { - message.data = data.data; - } - if (data.chain_id != null) { - message.chain_id = data.chain_id; - } - if (data.gas_fee_cap != null) { - message.gas_fee_cap = data.gas_fee_cap; - } - if (data.gas_tip_cap != null) { - message.gas_tip_cap = data.gas_tip_cap; - } - if (data.access_list != null) { - message.access_list = ProtoAccessList.fromObject(data.access_list); - } - if (data.v != null) { - message.v = data.v; - } - if (data.r != null) { - message.r = data.r; - } - if (data.s != null) { - message.s = data.s; - } - if (data.originating_tx_hash != null) { - message.originating_tx_hash = common.ProtoHash.fromObject(data.originating_tx_hash); - } - if (data.etx_index != null) { - message.etx_index = data.etx_index; - } - if (data.tx_ins != null) { - message.tx_ins = ProtoTxIns.fromObject(data.tx_ins); - } - if (data.tx_outs != null) { - message.tx_outs = ProtoTxOuts.fromObject(data.tx_outs); - } - if (data.signature != null) { - message.signature = data.signature; - } - if (data.etx_sender != null) { - message.etx_sender = data.etx_sender; - } - return message; - } - toObject() { - const data = {}; - if (this.type != null) { - data.type = this.type; - } - if (this.to != null) { - data.to = this.to; - } - if (this.nonce != null) { - data.nonce = this.nonce; - } - if (this.value != null) { - data.value = this.value; - } - if (this.gas != null) { - data.gas = this.gas; - } - if (this.data != null) { - data.data = this.data; - } - if (this.chain_id != null) { - data.chain_id = this.chain_id; - } - if (this.gas_fee_cap != null) { - data.gas_fee_cap = this.gas_fee_cap; - } - if (this.gas_tip_cap != null) { - data.gas_tip_cap = this.gas_tip_cap; - } - if (this.access_list != null) { - data.access_list = this.access_list.toObject(); - } - if (this.v != null) { - data.v = this.v; - } - if (this.r != null) { - data.r = this.r; - } - if (this.s != null) { - data.s = this.s; - } - if (this.originating_tx_hash != null) { - data.originating_tx_hash = this.originating_tx_hash.toObject(); - } - if (this.etx_index != null) { - data.etx_index = this.etx_index; - } - if (this.tx_ins != null) { - data.tx_ins = this.tx_ins.toObject(); - } - if (this.tx_outs != null) { - data.tx_outs = this.tx_outs.toObject(); - } - if (this.signature != null) { - data.signature = this.signature; - } - if (this.etx_sender != null) { - data.etx_sender = this.etx_sender; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_type) - writer.writeUint64(1, this.type); - if (this.has_to) - writer.writeBytes(2, this.to); - if (this.has_nonce) - writer.writeUint64(3, this.nonce); - if (this.has_value) - writer.writeBytes(4, this.value); - if (this.has_gas) - writer.writeUint64(5, this.gas); - if (this.has_data) - writer.writeBytes(6, this.data); - if (this.has_chain_id) - writer.writeBytes(7, this.chain_id); - if (this.has_gas_fee_cap) - writer.writeBytes(8, this.gas_fee_cap); - if (this.has_gas_tip_cap) - writer.writeBytes(9, this.gas_tip_cap); - if (this.has_access_list) - writer.writeMessage(10, this.access_list, () => this.access_list.serialize(writer)); - if (this.has_v) - writer.writeBytes(11, this.v); - if (this.has_r) - writer.writeBytes(12, this.r); - if (this.has_s) - writer.writeBytes(13, this.s); - if (this.has_originating_tx_hash) - writer.writeMessage(14, this.originating_tx_hash, () => this.originating_tx_hash.serialize(writer)); - if (this.has_etx_index) - writer.writeUint32(15, this.etx_index); - if (this.has_tx_ins) - writer.writeMessage(16, this.tx_ins, () => this.tx_ins.serialize(writer)); - if (this.has_tx_outs) - writer.writeMessage(17, this.tx_outs, () => this.tx_outs.serialize(writer)); - if (this.has_signature) - writer.writeBytes(18, this.signature); - if (this.has_etx_sender) - writer.writeBytes(19, this.etx_sender); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoTransaction(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.type = reader.readUint64(); - break; - case 2: - message.to = reader.readBytes(); - break; - case 3: - message.nonce = reader.readUint64(); - break; - case 4: - message.value = reader.readBytes(); - break; - case 5: - message.gas = reader.readUint64(); - break; - case 6: - message.data = reader.readBytes(); - break; - case 7: - message.chain_id = reader.readBytes(); - break; - case 8: - message.gas_fee_cap = reader.readBytes(); - break; - case 9: - message.gas_tip_cap = reader.readBytes(); - break; - case 10: - reader.readMessage(message.access_list, () => message.access_list = ProtoAccessList.deserialize(reader)); - break; - case 11: - message.v = reader.readBytes(); - break; - case 12: - message.r = reader.readBytes(); - break; - case 13: - message.s = reader.readBytes(); - break; - case 14: - reader.readMessage(message.originating_tx_hash, () => message.originating_tx_hash = common.ProtoHash.deserialize(reader)); - break; - case 15: - message.etx_index = reader.readUint32(); - break; - case 16: - reader.readMessage(message.tx_ins, () => message.tx_ins = ProtoTxIns.deserialize(reader)); - break; - case 17: - reader.readMessage(message.tx_outs, () => message.tx_outs = ProtoTxOuts.deserialize(reader)); - break; - case 18: - message.signature = reader.readBytes(); - break; - case 19: - message.etx_sender = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTransaction.deserialize(bytes); - } - } - block.ProtoTransaction = ProtoTransaction; - class ProtoTransactions extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("transactions" in data && data.transactions != undefined) { - this.transactions = data.transactions; - } - } - } - get transactions() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoTransaction, 1); - } - set transactions(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoTransactions({}); - if (data.transactions != null) { - message.transactions = data.transactions.map(item => ProtoTransaction.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.transactions != null) { - data.transactions = this.transactions.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.transactions.length) - writer.writeRepeatedMessage(1, this.transactions, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoTransactions(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.transactions, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoTransaction.deserialize(reader), ProtoTransaction)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTransactions.deserialize(bytes); - } - } - block.ProtoTransactions = ProtoTransactions; - class ProtoHeaders extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("headers" in data && data.headers != undefined) { - this.headers = data.headers; - } - } - } - get headers() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoHeader, 1); - } - set headers(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoHeaders({}); - if (data.headers != null) { - message.headers = data.headers.map(item => ProtoHeader.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.headers != null) { - data.headers = this.headers.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.headers.length) - writer.writeRepeatedMessage(1, this.headers, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoHeaders(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.headers, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoHeader.deserialize(reader), ProtoHeader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoHeaders.deserialize(bytes); - } - } - block.ProtoHeaders = ProtoHeaders; - class ProtoManifest extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("manifest" in data && data.manifest != undefined) { - this.manifest = data.manifest; - } - } - } - get manifest() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, common.ProtoHash, 1); - } - set manifest(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoManifest({}); - if (data.manifest != null) { - message.manifest = data.manifest.map(item => common.ProtoHash.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.manifest != null) { - data.manifest = this.manifest.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.manifest.length) - writer.writeRepeatedMessage(1, this.manifest, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoManifest(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.manifest, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoManifest.deserialize(bytes); - } - } - block.ProtoManifest = ProtoManifest; - class ProtoAccessList extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("access_tuples" in data && data.access_tuples != undefined) { - this.access_tuples = data.access_tuples; - } - } - } - get access_tuples() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoAccessTuple, 1); - } - set access_tuples(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoAccessList({}); - if (data.access_tuples != null) { - message.access_tuples = data.access_tuples.map(item => ProtoAccessTuple.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.access_tuples != null) { - data.access_tuples = this.access_tuples.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.access_tuples.length) - writer.writeRepeatedMessage(1, this.access_tuples, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoAccessList(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.access_tuples, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoAccessTuple.deserialize(reader), ProtoAccessTuple)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoAccessList.deserialize(bytes); - } - } - block.ProtoAccessList = ProtoAccessList; - class ProtoWorkObjectHeader extends pb_1__namespace.Message { - #one_of_decls = [[1], [2], [3], [4], [5], [6], [7], [8], [9]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("header_hash" in data && data.header_hash != undefined) { - this.header_hash = data.header_hash; - } - if ("parent_hash" in data && data.parent_hash != undefined) { - this.parent_hash = data.parent_hash; - } - if ("number" in data && data.number != undefined) { - this.number = data.number; - } - if ("difficulty" in data && data.difficulty != undefined) { - this.difficulty = data.difficulty; - } - if ("tx_hash" in data && data.tx_hash != undefined) { - this.tx_hash = data.tx_hash; - } - if ("nonce" in data && data.nonce != undefined) { - this.nonce = data.nonce; - } - if ("location" in data && data.location != undefined) { - this.location = data.location; - } - if ("mix_hash" in data && data.mix_hash != undefined) { - this.mix_hash = data.mix_hash; - } - if ("time" in data && data.time != undefined) { - this.time = data.time; - } - } - } - get header_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 1); - } - set header_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_header_hash() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get parent_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 2); - } - set parent_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_parent_hash() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get number() { - return pb_1__namespace.Message.getFieldWithDefault(this, 3, new Uint8Array(0)); - } - set number(value) { - pb_1__namespace.Message.setOneofField(this, 3, this.#one_of_decls[2], value); - } - get has_number() { - return pb_1__namespace.Message.getField(this, 3) != null; - } - get difficulty() { - return pb_1__namespace.Message.getFieldWithDefault(this, 4, new Uint8Array(0)); - } - set difficulty(value) { - pb_1__namespace.Message.setOneofField(this, 4, this.#one_of_decls[3], value); - } - get has_difficulty() { - return pb_1__namespace.Message.getField(this, 4) != null; - } - get tx_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 5); - } - set tx_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 5, this.#one_of_decls[4], value); - } - get has_tx_hash() { - return pb_1__namespace.Message.getField(this, 5) != null; - } - get nonce() { - return pb_1__namespace.Message.getFieldWithDefault(this, 6, 0); - } - set nonce(value) { - pb_1__namespace.Message.setOneofField(this, 6, this.#one_of_decls[5], value); - } - get has_nonce() { - return pb_1__namespace.Message.getField(this, 6) != null; - } - get location() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoLocation, 7); - } - set location(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 7, this.#one_of_decls[6], value); - } - get has_location() { - return pb_1__namespace.Message.getField(this, 7) != null; - } - get mix_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 8); - } - set mix_hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 8, this.#one_of_decls[7], value); - } - get has_mix_hash() { - return pb_1__namespace.Message.getField(this, 8) != null; - } - get time() { - return pb_1__namespace.Message.getFieldWithDefault(this, 9, 0); - } - set time(value) { - pb_1__namespace.Message.setOneofField(this, 9, this.#one_of_decls[8], value); - } - get has_time() { - return pb_1__namespace.Message.getField(this, 9) != null; - } - get _header_hash() { - const cases = { - 0: "none", - 1: "header_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _parent_hash() { - const cases = { - 0: "none", - 2: "parent_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - get _number() { - const cases = { - 0: "none", - 3: "number" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [3])]; - } - get _difficulty() { - const cases = { - 0: "none", - 4: "difficulty" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [4])]; - } - get _tx_hash() { - const cases = { - 0: "none", - 5: "tx_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [5])]; - } - get _nonce() { - const cases = { - 0: "none", - 6: "nonce" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [6])]; - } - get _location() { - const cases = { - 0: "none", - 7: "location" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [7])]; - } - get _mix_hash() { - const cases = { - 0: "none", - 8: "mix_hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [8])]; - } - get _time() { - const cases = { - 0: "none", - 9: "time" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [9])]; - } - static fromObject(data) { - const message = new ProtoWorkObjectHeader({}); - if (data.header_hash != null) { - message.header_hash = common.ProtoHash.fromObject(data.header_hash); - } - if (data.parent_hash != null) { - message.parent_hash = common.ProtoHash.fromObject(data.parent_hash); - } - if (data.number != null) { - message.number = data.number; - } - if (data.difficulty != null) { - message.difficulty = data.difficulty; - } - if (data.tx_hash != null) { - message.tx_hash = common.ProtoHash.fromObject(data.tx_hash); - } - if (data.nonce != null) { - message.nonce = data.nonce; - } - if (data.location != null) { - message.location = common.ProtoLocation.fromObject(data.location); - } - if (data.mix_hash != null) { - message.mix_hash = common.ProtoHash.fromObject(data.mix_hash); - } - if (data.time != null) { - message.time = data.time; - } - return message; - } - toObject() { - const data = {}; - if (this.header_hash != null) { - data.header_hash = this.header_hash.toObject(); - } - if (this.parent_hash != null) { - data.parent_hash = this.parent_hash.toObject(); - } - if (this.number != null) { - data.number = this.number; - } - if (this.difficulty != null) { - data.difficulty = this.difficulty; - } - if (this.tx_hash != null) { - data.tx_hash = this.tx_hash.toObject(); - } - if (this.nonce != null) { - data.nonce = this.nonce; - } - if (this.location != null) { - data.location = this.location.toObject(); - } - if (this.mix_hash != null) { - data.mix_hash = this.mix_hash.toObject(); - } - if (this.time != null) { - data.time = this.time; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_header_hash) - writer.writeMessage(1, this.header_hash, () => this.header_hash.serialize(writer)); - if (this.has_parent_hash) - writer.writeMessage(2, this.parent_hash, () => this.parent_hash.serialize(writer)); - if (this.has_number) - writer.writeBytes(3, this.number); - if (this.has_difficulty) - writer.writeBytes(4, this.difficulty); - if (this.has_tx_hash) - writer.writeMessage(5, this.tx_hash, () => this.tx_hash.serialize(writer)); - if (this.has_nonce) - writer.writeUint64(6, this.nonce); - if (this.has_location) - writer.writeMessage(7, this.location, () => this.location.serialize(writer)); - if (this.has_mix_hash) - writer.writeMessage(8, this.mix_hash, () => this.mix_hash.serialize(writer)); - if (this.has_time) - writer.writeUint64(9, this.time); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoWorkObjectHeader(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.header_hash, () => message.header_hash = common.ProtoHash.deserialize(reader)); - break; - case 2: - reader.readMessage(message.parent_hash, () => message.parent_hash = common.ProtoHash.deserialize(reader)); - break; - case 3: - message.number = reader.readBytes(); - break; - case 4: - message.difficulty = reader.readBytes(); - break; - case 5: - reader.readMessage(message.tx_hash, () => message.tx_hash = common.ProtoHash.deserialize(reader)); - break; - case 6: - message.nonce = reader.readUint64(); - break; - case 7: - reader.readMessage(message.location, () => message.location = common.ProtoLocation.deserialize(reader)); - break; - case 8: - reader.readMessage(message.mix_hash, () => message.mix_hash = common.ProtoHash.deserialize(reader)); - break; - case 9: - message.time = reader.readUint64(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObjectHeader.deserialize(bytes); - } - } - block.ProtoWorkObjectHeader = ProtoWorkObjectHeader; - class ProtoWorkObjectHeaders extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("wo_headers" in data && data.wo_headers != undefined) { - this.wo_headers = data.wo_headers; - } - } - } - get wo_headers() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoWorkObjectHeader, 1); - } - set wo_headers(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoWorkObjectHeaders({}); - if (data.wo_headers != null) { - message.wo_headers = data.wo_headers.map(item => ProtoWorkObjectHeader.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.wo_headers != null) { - data.wo_headers = this.wo_headers.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.wo_headers.length) - writer.writeRepeatedMessage(1, this.wo_headers, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoWorkObjectHeaders(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.wo_headers, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoWorkObjectHeader.deserialize(reader), ProtoWorkObjectHeader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObjectHeaders.deserialize(bytes); - } - } - block.ProtoWorkObjectHeaders = ProtoWorkObjectHeaders; - class ProtoWorkObjectBody extends pb_1__namespace.Message { - #one_of_decls = [[1], [2], [3], [4], [5], [6]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("header" in data && data.header != undefined) { - this.header = data.header; - } - if ("transactions" in data && data.transactions != undefined) { - this.transactions = data.transactions; - } - if ("uncles" in data && data.uncles != undefined) { - this.uncles = data.uncles; - } - if ("ext_transactions" in data && data.ext_transactions != undefined) { - this.ext_transactions = data.ext_transactions; - } - if ("manifest" in data && data.manifest != undefined) { - this.manifest = data.manifest; - } - if ("interlink_hashes" in data && data.interlink_hashes != undefined) { - this.interlink_hashes = data.interlink_hashes; - } - } - } - get header() { - return pb_1__namespace.Message.getWrapperField(this, ProtoHeader, 1); - } - set header(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_header() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get transactions() { - return pb_1__namespace.Message.getWrapperField(this, ProtoTransactions, 2); - } - set transactions(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_transactions() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get uncles() { - return pb_1__namespace.Message.getWrapperField(this, ProtoWorkObjectHeaders, 3); - } - set uncles(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 3, this.#one_of_decls[2], value); - } - get has_uncles() { - return pb_1__namespace.Message.getField(this, 3) != null; - } - get ext_transactions() { - return pb_1__namespace.Message.getWrapperField(this, ProtoTransactions, 4); - } - set ext_transactions(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 4, this.#one_of_decls[3], value); - } - get has_ext_transactions() { - return pb_1__namespace.Message.getField(this, 4) != null; - } - get manifest() { - return pb_1__namespace.Message.getWrapperField(this, ProtoManifest, 5); - } - set manifest(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 5, this.#one_of_decls[4], value); - } - get has_manifest() { - return pb_1__namespace.Message.getField(this, 5) != null; - } - get interlink_hashes() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHashes, 6); - } - set interlink_hashes(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 6, this.#one_of_decls[5], value); - } - get has_interlink_hashes() { - return pb_1__namespace.Message.getField(this, 6) != null; - } - get _header() { - const cases = { - 0: "none", - 1: "header" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _transactions() { - const cases = { - 0: "none", - 2: "transactions" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - get _uncles() { - const cases = { - 0: "none", - 3: "uncles" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [3])]; - } - get _ext_transactions() { - const cases = { - 0: "none", - 4: "ext_transactions" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [4])]; - } - get _manifest() { - const cases = { - 0: "none", - 5: "manifest" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [5])]; - } - get _interlink_hashes() { - const cases = { - 0: "none", - 6: "interlink_hashes" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [6])]; - } - static fromObject(data) { - const message = new ProtoWorkObjectBody({}); - if (data.header != null) { - message.header = ProtoHeader.fromObject(data.header); - } - if (data.transactions != null) { - message.transactions = ProtoTransactions.fromObject(data.transactions); - } - if (data.uncles != null) { - message.uncles = ProtoWorkObjectHeaders.fromObject(data.uncles); - } - if (data.ext_transactions != null) { - message.ext_transactions = ProtoTransactions.fromObject(data.ext_transactions); - } - if (data.manifest != null) { - message.manifest = ProtoManifest.fromObject(data.manifest); - } - if (data.interlink_hashes != null) { - message.interlink_hashes = common.ProtoHashes.fromObject(data.interlink_hashes); - } - return message; - } - toObject() { - const data = {}; - if (this.header != null) { - data.header = this.header.toObject(); - } - if (this.transactions != null) { - data.transactions = this.transactions.toObject(); - } - if (this.uncles != null) { - data.uncles = this.uncles.toObject(); - } - if (this.ext_transactions != null) { - data.ext_transactions = this.ext_transactions.toObject(); - } - if (this.manifest != null) { - data.manifest = this.manifest.toObject(); - } - if (this.interlink_hashes != null) { - data.interlink_hashes = this.interlink_hashes.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_header) - writer.writeMessage(1, this.header, () => this.header.serialize(writer)); - if (this.has_transactions) - writer.writeMessage(2, this.transactions, () => this.transactions.serialize(writer)); - if (this.has_uncles) - writer.writeMessage(3, this.uncles, () => this.uncles.serialize(writer)); - if (this.has_ext_transactions) - writer.writeMessage(4, this.ext_transactions, () => this.ext_transactions.serialize(writer)); - if (this.has_manifest) - writer.writeMessage(5, this.manifest, () => this.manifest.serialize(writer)); - if (this.has_interlink_hashes) - writer.writeMessage(6, this.interlink_hashes, () => this.interlink_hashes.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoWorkObjectBody(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.header, () => message.header = ProtoHeader.deserialize(reader)); - break; - case 2: - reader.readMessage(message.transactions, () => message.transactions = ProtoTransactions.deserialize(reader)); - break; - case 3: - reader.readMessage(message.uncles, () => message.uncles = ProtoWorkObjectHeaders.deserialize(reader)); - break; - case 4: - reader.readMessage(message.ext_transactions, () => message.ext_transactions = ProtoTransactions.deserialize(reader)); - break; - case 5: - reader.readMessage(message.manifest, () => message.manifest = ProtoManifest.deserialize(reader)); - break; - case 6: - reader.readMessage(message.interlink_hashes, () => message.interlink_hashes = common.ProtoHashes.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObjectBody.deserialize(bytes); - } - } - block.ProtoWorkObjectBody = ProtoWorkObjectBody; - class ProtoWorkObject extends pb_1__namespace.Message { - #one_of_decls = [[1], [2], [3]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("wo_header" in data && data.wo_header != undefined) { - this.wo_header = data.wo_header; - } - if ("wo_body" in data && data.wo_body != undefined) { - this.wo_body = data.wo_body; - } - if ("tx" in data && data.tx != undefined) { - this.tx = data.tx; - } - } - } - get wo_header() { - return pb_1__namespace.Message.getWrapperField(this, ProtoWorkObjectHeader, 1); - } - set wo_header(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_wo_header() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get wo_body() { - return pb_1__namespace.Message.getWrapperField(this, ProtoWorkObjectBody, 2); - } - set wo_body(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_wo_body() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get tx() { - return pb_1__namespace.Message.getWrapperField(this, ProtoTransaction, 3); - } - set tx(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 3, this.#one_of_decls[2], value); - } - get has_tx() { - return pb_1__namespace.Message.getField(this, 3) != null; - } - get _wo_header() { - const cases = { - 0: "none", - 1: "wo_header" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _wo_body() { - const cases = { - 0: "none", - 2: "wo_body" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - get _tx() { - const cases = { - 0: "none", - 3: "tx" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [3])]; - } - static fromObject(data) { - const message = new ProtoWorkObject({}); - if (data.wo_header != null) { - message.wo_header = ProtoWorkObjectHeader.fromObject(data.wo_header); - } - if (data.wo_body != null) { - message.wo_body = ProtoWorkObjectBody.fromObject(data.wo_body); - } - if (data.tx != null) { - message.tx = ProtoTransaction.fromObject(data.tx); - } - return message; - } - toObject() { - const data = {}; - if (this.wo_header != null) { - data.wo_header = this.wo_header.toObject(); - } - if (this.wo_body != null) { - data.wo_body = this.wo_body.toObject(); - } - if (this.tx != null) { - data.tx = this.tx.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_wo_header) - writer.writeMessage(1, this.wo_header, () => this.wo_header.serialize(writer)); - if (this.has_wo_body) - writer.writeMessage(2, this.wo_body, () => this.wo_body.serialize(writer)); - if (this.has_tx) - writer.writeMessage(3, this.tx, () => this.tx.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoWorkObject(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.wo_header, () => message.wo_header = ProtoWorkObjectHeader.deserialize(reader)); - break; - case 2: - reader.readMessage(message.wo_body, () => message.wo_body = ProtoWorkObjectBody.deserialize(reader)); - break; - case 3: - reader.readMessage(message.tx, () => message.tx = ProtoTransaction.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObject.deserialize(bytes); - } - } - block.ProtoWorkObject = ProtoWorkObject; - class ProtoWorkObjects extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("work_objects" in data && data.work_objects != undefined) { - this.work_objects = data.work_objects; - } - } - } - get work_objects() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoWorkObject, 1); - } - set work_objects(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoWorkObjects({}); - if (data.work_objects != null) { - message.work_objects = data.work_objects.map(item => ProtoWorkObject.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.work_objects != null) { - data.work_objects = this.work_objects.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.work_objects.length) - writer.writeRepeatedMessage(1, this.work_objects, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoWorkObjects(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.work_objects, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoWorkObject.deserialize(reader), ProtoWorkObject)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoWorkObjects.deserialize(bytes); - } - } - block.ProtoWorkObjects = ProtoWorkObjects; - class ProtoAccessTuple extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("address" in data && data.address != undefined) { - this.address = data.address; - } - if ("storage_key" in data && data.storage_key != undefined) { - this.storage_key = data.storage_key; - } - } - } - get address() { - return pb_1__namespace.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set address(value) { - pb_1__namespace.Message.setField(this, 1, value); - } - get storage_key() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, common.ProtoHash, 2); - } - set storage_key(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 2, value); - } - static fromObject(data) { - const message = new ProtoAccessTuple({}); - if (data.address != null) { - message.address = data.address; - } - if (data.storage_key != null) { - message.storage_key = data.storage_key.map(item => common.ProtoHash.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.address != null) { - data.address = this.address; - } - if (this.storage_key != null) { - data.storage_key = this.storage_key.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.address.length) - writer.writeBytes(1, this.address); - if (this.storage_key.length) - writer.writeRepeatedMessage(2, this.storage_key, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoAccessTuple(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.address = reader.readBytes(); - break; - case 2: - reader.readMessage(message.storage_key, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 2, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoAccessTuple.deserialize(bytes); - } - } - block.ProtoAccessTuple = ProtoAccessTuple; - class ProtoReceiptForStorage extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("post_state_or_status" in data && data.post_state_or_status != undefined) { - this.post_state_or_status = data.post_state_or_status; - } - if ("cumulative_gas_used" in data && data.cumulative_gas_used != undefined) { - this.cumulative_gas_used = data.cumulative_gas_used; - } - if ("tx_hash" in data && data.tx_hash != undefined) { - this.tx_hash = data.tx_hash; - } - if ("contract_address" in data && data.contract_address != undefined) { - this.contract_address = data.contract_address; - } - if ("logs" in data && data.logs != undefined) { - this.logs = data.logs; - } - if ("etxs" in data && data.etxs != undefined) { - this.etxs = data.etxs; - } - if ("gas_used" in data && data.gas_used != undefined) { - this.gas_used = data.gas_used; - } - } - } - get post_state_or_status() { - return pb_1__namespace.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set post_state_or_status(value) { - pb_1__namespace.Message.setField(this, 1, value); - } - get cumulative_gas_used() { - return pb_1__namespace.Message.getFieldWithDefault(this, 2, 0); - } - set cumulative_gas_used(value) { - pb_1__namespace.Message.setField(this, 2, value); - } - get tx_hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 3); - } - set tx_hash(value) { - pb_1__namespace.Message.setWrapperField(this, 3, value); - } - get has_tx_hash() { - return pb_1__namespace.Message.getField(this, 3) != null; - } - get contract_address() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoAddress, 4); - } - set contract_address(value) { - pb_1__namespace.Message.setWrapperField(this, 4, value); - } - get has_contract_address() { - return pb_1__namespace.Message.getField(this, 4) != null; - } - get logs() { - return pb_1__namespace.Message.getWrapperField(this, ProtoLogsForStorage, 5); - } - set logs(value) { - pb_1__namespace.Message.setWrapperField(this, 5, value); - } - get has_logs() { - return pb_1__namespace.Message.getField(this, 5) != null; - } - get etxs() { - return pb_1__namespace.Message.getWrapperField(this, ProtoTransactions, 6); - } - set etxs(value) { - pb_1__namespace.Message.setWrapperField(this, 6, value); - } - get has_etxs() { - return pb_1__namespace.Message.getField(this, 6) != null; - } - get gas_used() { - return pb_1__namespace.Message.getFieldWithDefault(this, 7, 0); - } - set gas_used(value) { - pb_1__namespace.Message.setField(this, 7, value); - } - static fromObject(data) { - const message = new ProtoReceiptForStorage({}); - if (data.post_state_or_status != null) { - message.post_state_or_status = data.post_state_or_status; - } - if (data.cumulative_gas_used != null) { - message.cumulative_gas_used = data.cumulative_gas_used; - } - if (data.tx_hash != null) { - message.tx_hash = common.ProtoHash.fromObject(data.tx_hash); - } - if (data.contract_address != null) { - message.contract_address = common.ProtoAddress.fromObject(data.contract_address); - } - if (data.logs != null) { - message.logs = ProtoLogsForStorage.fromObject(data.logs); - } - if (data.etxs != null) { - message.etxs = ProtoTransactions.fromObject(data.etxs); - } - if (data.gas_used != null) { - message.gas_used = data.gas_used; - } - return message; - } - toObject() { - const data = {}; - if (this.post_state_or_status != null) { - data.post_state_or_status = this.post_state_or_status; - } - if (this.cumulative_gas_used != null) { - data.cumulative_gas_used = this.cumulative_gas_used; - } - if (this.tx_hash != null) { - data.tx_hash = this.tx_hash.toObject(); - } - if (this.contract_address != null) { - data.contract_address = this.contract_address.toObject(); - } - if (this.logs != null) { - data.logs = this.logs.toObject(); - } - if (this.etxs != null) { - data.etxs = this.etxs.toObject(); - } - if (this.gas_used != null) { - data.gas_used = this.gas_used; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.post_state_or_status.length) - writer.writeBytes(1, this.post_state_or_status); - if (this.cumulative_gas_used != 0) - writer.writeUint64(2, this.cumulative_gas_used); - if (this.has_tx_hash) - writer.writeMessage(3, this.tx_hash, () => this.tx_hash.serialize(writer)); - if (this.has_contract_address) - writer.writeMessage(4, this.contract_address, () => this.contract_address.serialize(writer)); - if (this.has_logs) - writer.writeMessage(5, this.logs, () => this.logs.serialize(writer)); - if (this.has_etxs) - writer.writeMessage(6, this.etxs, () => this.etxs.serialize(writer)); - if (this.gas_used != 0) - writer.writeUint64(7, this.gas_used); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoReceiptForStorage(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.post_state_or_status = reader.readBytes(); - break; - case 2: - message.cumulative_gas_used = reader.readUint64(); - break; - case 3: - reader.readMessage(message.tx_hash, () => message.tx_hash = common.ProtoHash.deserialize(reader)); - break; - case 4: - reader.readMessage(message.contract_address, () => message.contract_address = common.ProtoAddress.deserialize(reader)); - break; - case 5: - reader.readMessage(message.logs, () => message.logs = ProtoLogsForStorage.deserialize(reader)); - break; - case 6: - reader.readMessage(message.etxs, () => message.etxs = ProtoTransactions.deserialize(reader)); - break; - case 7: - message.gas_used = reader.readUint64(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoReceiptForStorage.deserialize(bytes); - } - } - block.ProtoReceiptForStorage = ProtoReceiptForStorage; - class ProtoReceiptsForStorage extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("receipts" in data && data.receipts != undefined) { - this.receipts = data.receipts; - } - } - } - get receipts() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoReceiptForStorage, 1); - } - set receipts(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoReceiptsForStorage({}); - if (data.receipts != null) { - message.receipts = data.receipts.map(item => ProtoReceiptForStorage.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.receipts != null) { - data.receipts = this.receipts.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.receipts.length) - writer.writeRepeatedMessage(1, this.receipts, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoReceiptsForStorage(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.receipts, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoReceiptForStorage.deserialize(reader), ProtoReceiptForStorage)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoReceiptsForStorage.deserialize(bytes); - } - } - block.ProtoReceiptsForStorage = ProtoReceiptsForStorage; - class ProtoLogForStorage extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("address" in data && data.address != undefined) { - this.address = data.address; - } - if ("topics" in data && data.topics != undefined) { - this.topics = data.topics; - } - if ("data" in data && data.data != undefined) { - this.data = data.data; - } - } - } - get address() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoAddress, 1); - } - set address(value) { - pb_1__namespace.Message.setWrapperField(this, 1, value); - } - get has_address() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get topics() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, common.ProtoHash, 2); - } - set topics(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 2, value); - } - get data() { - return pb_1__namespace.Message.getFieldWithDefault(this, 3, new Uint8Array(0)); - } - set data(value) { - pb_1__namespace.Message.setField(this, 3, value); - } - static fromObject(data) { - const message = new ProtoLogForStorage({}); - if (data.address != null) { - message.address = common.ProtoAddress.fromObject(data.address); - } - if (data.topics != null) { - message.topics = data.topics.map(item => common.ProtoHash.fromObject(item)); - } - if (data.data != null) { - message.data = data.data; - } - return message; - } - toObject() { - const data = {}; - if (this.address != null) { - data.address = this.address.toObject(); - } - if (this.topics != null) { - data.topics = this.topics.map((item) => item.toObject()); - } - if (this.data != null) { - data.data = this.data; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_address) - writer.writeMessage(1, this.address, () => this.address.serialize(writer)); - if (this.topics.length) - writer.writeRepeatedMessage(2, this.topics, (item) => item.serialize(writer)); - if (this.data.length) - writer.writeBytes(3, this.data); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoLogForStorage(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.address, () => message.address = common.ProtoAddress.deserialize(reader)); - break; - case 2: - reader.readMessage(message.topics, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 2, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - case 3: - message.data = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoLogForStorage.deserialize(bytes); - } - } - block.ProtoLogForStorage = ProtoLogForStorage; - class ProtoLogsForStorage extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("logs" in data && data.logs != undefined) { - this.logs = data.logs; - } - } - } - get logs() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoLogForStorage, 1); - } - set logs(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoLogsForStorage({}); - if (data.logs != null) { - message.logs = data.logs.map(item => ProtoLogForStorage.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.logs != null) { - data.logs = this.logs.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.logs.length) - writer.writeRepeatedMessage(1, this.logs, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoLogsForStorage(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.logs, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoLogForStorage.deserialize(reader), ProtoLogForStorage)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoLogsForStorage.deserialize(bytes); - } - } - block.ProtoLogsForStorage = ProtoLogsForStorage; - class ProtoPendingHeader extends pb_1__namespace.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("wo" in data && data.wo != undefined) { - this.wo = data.wo; - } - if ("termini" in data && data.termini != undefined) { - this.termini = data.termini; - } - } - } - get wo() { - return pb_1__namespace.Message.getWrapperField(this, ProtoWorkObject, 1); - } - set wo(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_wo() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get termini() { - return pb_1__namespace.Message.getWrapperField(this, ProtoTermini, 2); - } - set termini(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_termini() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get _wo() { - const cases = { - 0: "none", - 1: "wo" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _termini() { - const cases = { - 0: "none", - 2: "termini" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoPendingHeader({}); - if (data.wo != null) { - message.wo = ProtoWorkObject.fromObject(data.wo); - } - if (data.termini != null) { - message.termini = ProtoTermini.fromObject(data.termini); - } - return message; - } - toObject() { - const data = {}; - if (this.wo != null) { - data.wo = this.wo.toObject(); - } - if (this.termini != null) { - data.termini = this.termini.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_wo) - writer.writeMessage(1, this.wo, () => this.wo.serialize(writer)); - if (this.has_termini) - writer.writeMessage(2, this.termini, () => this.termini.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoPendingHeader(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.wo, () => message.wo = ProtoWorkObject.deserialize(reader)); - break; - case 2: - reader.readMessage(message.termini, () => message.termini = ProtoTermini.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoPendingHeader.deserialize(bytes); - } - } - block.ProtoPendingHeader = ProtoPendingHeader; - class ProtoTermini extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1, 2], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("dom_termini" in data && data.dom_termini != undefined) { - this.dom_termini = data.dom_termini; - } - if ("sub_termini" in data && data.sub_termini != undefined) { - this.sub_termini = data.sub_termini; - } - } - } - get dom_termini() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, common.ProtoHash, 1); - } - set dom_termini(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - get sub_termini() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, common.ProtoHash, 2); - } - set sub_termini(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 2, value); - } - static fromObject(data) { - const message = new ProtoTermini({}); - if (data.dom_termini != null) { - message.dom_termini = data.dom_termini.map(item => common.ProtoHash.fromObject(item)); - } - if (data.sub_termini != null) { - message.sub_termini = data.sub_termini.map(item => common.ProtoHash.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.dom_termini != null) { - data.dom_termini = this.dom_termini.map((item) => item.toObject()); - } - if (this.sub_termini != null) { - data.sub_termini = this.sub_termini.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.dom_termini.length) - writer.writeRepeatedMessage(1, this.dom_termini, (item) => item.serialize(writer)); - if (this.sub_termini.length) - writer.writeRepeatedMessage(2, this.sub_termini, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoTermini(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.dom_termini, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - case 2: - reader.readMessage(message.sub_termini, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 2, common.ProtoHash.deserialize(reader), common.ProtoHash)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTermini.deserialize(bytes); - } - } - block.ProtoTermini = ProtoTermini; - class ProtoEtxSet extends pb_1__namespace.Message { - #one_of_decls = [[1]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("etx_hashes" in data && data.etx_hashes != undefined) { - this.etx_hashes = data.etx_hashes; - } - } - } - get etx_hashes() { - return pb_1__namespace.Message.getFieldWithDefault(this, 1, new Uint8Array(0)); - } - set etx_hashes(value) { - pb_1__namespace.Message.setOneofField(this, 1, this.#one_of_decls[0], value); - } - get has_etx_hashes() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get _etx_hashes() { - const cases = { - 0: "none", - 1: "etx_hashes" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - static fromObject(data) { - const message = new ProtoEtxSet({}); - if (data.etx_hashes != null) { - message.etx_hashes = data.etx_hashes; - } - return message; - } - toObject() { - const data = {}; - if (this.etx_hashes != null) { - data.etx_hashes = this.etx_hashes; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_etx_hashes) - writer.writeBytes(1, this.etx_hashes); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoEtxSet(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.etx_hashes = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoEtxSet.deserialize(bytes); - } - } - block.ProtoEtxSet = ProtoEtxSet; - class ProtoPendingEtxs extends pb_1__namespace.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("header" in data && data.header != undefined) { - this.header = data.header; - } - if ("etxs" in data && data.etxs != undefined) { - this.etxs = data.etxs; - } - } - } - get header() { - return pb_1__namespace.Message.getWrapperField(this, ProtoWorkObject, 1); - } - set header(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_header() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get etxs() { - return pb_1__namespace.Message.getWrapperField(this, ProtoTransactions, 2); - } - set etxs(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_etxs() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get _header() { - const cases = { - 0: "none", - 1: "header" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _etxs() { - const cases = { - 0: "none", - 2: "etxs" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoPendingEtxs({}); - if (data.header != null) { - message.header = ProtoWorkObject.fromObject(data.header); - } - if (data.etxs != null) { - message.etxs = ProtoTransactions.fromObject(data.etxs); - } - return message; - } - toObject() { - const data = {}; - if (this.header != null) { - data.header = this.header.toObject(); - } - if (this.etxs != null) { - data.etxs = this.etxs.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_header) - writer.writeMessage(1, this.header, () => this.header.serialize(writer)); - if (this.has_etxs) - writer.writeMessage(2, this.etxs, () => this.etxs.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoPendingEtxs(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.header, () => message.header = ProtoWorkObject.deserialize(reader)); - break; - case 2: - reader.readMessage(message.etxs, () => message.etxs = ProtoTransactions.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoPendingEtxs.deserialize(bytes); - } - } - block.ProtoPendingEtxs = ProtoPendingEtxs; - class ProtoPendingEtxsRollup extends pb_1__namespace.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("header" in data && data.header != undefined) { - this.header = data.header; - } - if ("etxs_rollup" in data && data.etxs_rollup != undefined) { - this.etxs_rollup = data.etxs_rollup; - } - } - } - get header() { - return pb_1__namespace.Message.getWrapperField(this, ProtoWorkObject, 1); - } - set header(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_header() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get etxs_rollup() { - return pb_1__namespace.Message.getWrapperField(this, ProtoTransactions, 2); - } - set etxs_rollup(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value); - } - get has_etxs_rollup() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get _header() { - const cases = { - 0: "none", - 1: "header" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _etxs_rollup() { - const cases = { - 0: "none", - 2: "etxs_rollup" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoPendingEtxsRollup({}); - if (data.header != null) { - message.header = ProtoWorkObject.fromObject(data.header); - } - if (data.etxs_rollup != null) { - message.etxs_rollup = ProtoTransactions.fromObject(data.etxs_rollup); - } - return message; - } - toObject() { - const data = {}; - if (this.header != null) { - data.header = this.header.toObject(); - } - if (this.etxs_rollup != null) { - data.etxs_rollup = this.etxs_rollup.toObject(); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_header) - writer.writeMessage(1, this.header, () => this.header.serialize(writer)); - if (this.has_etxs_rollup) - writer.writeMessage(2, this.etxs_rollup, () => this.etxs_rollup.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoPendingEtxsRollup(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.header, () => message.header = ProtoWorkObject.deserialize(reader)); - break; - case 2: - reader.readMessage(message.etxs_rollup, () => message.etxs_rollup = ProtoTransactions.deserialize(reader)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoPendingEtxsRollup.deserialize(bytes); - } - } - block.ProtoPendingEtxsRollup = ProtoPendingEtxsRollup; - class ProtoTxIns extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("tx_ins" in data && data.tx_ins != undefined) { - this.tx_ins = data.tx_ins; - } - } - } - get tx_ins() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoTxIn, 1); - } - set tx_ins(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoTxIns({}); - if (data.tx_ins != null) { - message.tx_ins = data.tx_ins.map(item => ProtoTxIn.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.tx_ins != null) { - data.tx_ins = this.tx_ins.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.tx_ins.length) - writer.writeRepeatedMessage(1, this.tx_ins, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoTxIns(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.tx_ins, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoTxIn.deserialize(reader), ProtoTxIn)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTxIns.deserialize(bytes); - } - } - block.ProtoTxIns = ProtoTxIns; - class ProtoTxOuts extends pb_1__namespace.Message { - #one_of_decls = []; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("tx_outs" in data && data.tx_outs != undefined) { - this.tx_outs = data.tx_outs; - } - } - } - get tx_outs() { - return pb_1__namespace.Message.getRepeatedWrapperField(this, ProtoTxOut, 1); - } - set tx_outs(value) { - pb_1__namespace.Message.setRepeatedWrapperField(this, 1, value); - } - static fromObject(data) { - const message = new ProtoTxOuts({}); - if (data.tx_outs != null) { - message.tx_outs = data.tx_outs.map(item => ProtoTxOut.fromObject(item)); - } - return message; - } - toObject() { - const data = {}; - if (this.tx_outs != null) { - data.tx_outs = this.tx_outs.map((item) => item.toObject()); - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.tx_outs.length) - writer.writeRepeatedMessage(1, this.tx_outs, (item) => item.serialize(writer)); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoTxOuts(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.tx_outs, () => pb_1__namespace.Message.addToRepeatedWrapperField(message, 1, ProtoTxOut.deserialize(reader), ProtoTxOut)); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTxOuts.deserialize(bytes); - } - } - block.ProtoTxOuts = ProtoTxOuts; - class ProtoTxIn extends pb_1__namespace.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("previous_out_point" in data && data.previous_out_point != undefined) { - this.previous_out_point = data.previous_out_point; - } - if ("pub_key" in data && data.pub_key != undefined) { - this.pub_key = data.pub_key; - } - } - } - get previous_out_point() { - return pb_1__namespace.Message.getWrapperField(this, ProtoOutPoint, 1); - } - set previous_out_point(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_previous_out_point() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get pub_key() { - return pb_1__namespace.Message.getFieldWithDefault(this, 2, new Uint8Array(0)); - } - set pub_key(value) { - pb_1__namespace.Message.setOneofField(this, 2, this.#one_of_decls[1], value); - } - get has_pub_key() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get _previous_out_point() { - const cases = { - 0: "none", - 1: "previous_out_point" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _pub_key() { - const cases = { - 0: "none", - 2: "pub_key" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoTxIn({}); - if (data.previous_out_point != null) { - message.previous_out_point = ProtoOutPoint.fromObject(data.previous_out_point); - } - if (data.pub_key != null) { - message.pub_key = data.pub_key; - } - return message; - } - toObject() { - const data = {}; - if (this.previous_out_point != null) { - data.previous_out_point = this.previous_out_point.toObject(); - } - if (this.pub_key != null) { - data.pub_key = this.pub_key; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_previous_out_point) - writer.writeMessage(1, this.previous_out_point, () => this.previous_out_point.serialize(writer)); - if (this.has_pub_key) - writer.writeBytes(2, this.pub_key); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoTxIn(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.previous_out_point, () => message.previous_out_point = ProtoOutPoint.deserialize(reader)); - break; - case 2: - message.pub_key = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTxIn.deserialize(bytes); - } - } - block.ProtoTxIn = ProtoTxIn; - class ProtoOutPoint extends pb_1__namespace.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("hash" in data && data.hash != undefined) { - this.hash = data.hash; - } - if ("index" in data && data.index != undefined) { - this.index = data.index; - } - } - } - get hash() { - return pb_1__namespace.Message.getWrapperField(this, common.ProtoHash, 1); - } - set hash(value) { - pb_1__namespace.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value); - } - get has_hash() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get index() { - return pb_1__namespace.Message.getFieldWithDefault(this, 2, 0); - } - set index(value) { - pb_1__namespace.Message.setOneofField(this, 2, this.#one_of_decls[1], value); - } - get has_index() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get _hash() { - const cases = { - 0: "none", - 1: "hash" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _index() { - const cases = { - 0: "none", - 2: "index" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoOutPoint({}); - if (data.hash != null) { - message.hash = common.ProtoHash.fromObject(data.hash); - } - if (data.index != null) { - message.index = data.index; - } - return message; - } - toObject() { - const data = {}; - if (this.hash != null) { - data.hash = this.hash.toObject(); - } - if (this.index != null) { - data.index = this.index; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_hash) - writer.writeMessage(1, this.hash, () => this.hash.serialize(writer)); - if (this.has_index) - writer.writeUint32(2, this.index); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoOutPoint(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - reader.readMessage(message.hash, () => message.hash = common.ProtoHash.deserialize(reader)); - break; - case 2: - message.index = reader.readUint32(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoOutPoint.deserialize(bytes); - } - } - block.ProtoOutPoint = ProtoOutPoint; - class ProtoTxOut extends pb_1__namespace.Message { - #one_of_decls = [[1], [2]]; - constructor(data) { - super(); - pb_1__namespace.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls); - if (!Array.isArray(data) && typeof data == "object") { - if ("denomination" in data && data.denomination != undefined) { - this.denomination = data.denomination; - } - if ("address" in data && data.address != undefined) { - this.address = data.address; - } - } - } - get denomination() { - return pb_1__namespace.Message.getFieldWithDefault(this, 1, 0); - } - set denomination(value) { - pb_1__namespace.Message.setOneofField(this, 1, this.#one_of_decls[0], value); - } - get has_denomination() { - return pb_1__namespace.Message.getField(this, 1) != null; - } - get address() { - return pb_1__namespace.Message.getFieldWithDefault(this, 2, new Uint8Array(0)); - } - set address(value) { - pb_1__namespace.Message.setOneofField(this, 2, this.#one_of_decls[1], value); - } - get has_address() { - return pb_1__namespace.Message.getField(this, 2) != null; - } - get _denomination() { - const cases = { - 0: "none", - 1: "denomination" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [1])]; - } - get _address() { - const cases = { - 0: "none", - 2: "address" - }; - return cases[pb_1__namespace.Message.computeOneofCase(this, [2])]; - } - static fromObject(data) { - const message = new ProtoTxOut({}); - if (data.denomination != null) { - message.denomination = data.denomination; - } - if (data.address != null) { - message.address = data.address; - } - return message; - } - toObject() { - const data = {}; - if (this.denomination != null) { - data.denomination = this.denomination; - } - if (this.address != null) { - data.address = this.address; - } - return data; - } - serialize(w) { - const writer = w || new pb_1__namespace.BinaryWriter(); - if (this.has_denomination) - writer.writeUint32(1, this.denomination); - if (this.has_address) - writer.writeBytes(2, this.address); - if (!w) - return writer.getResultBuffer(); - } - static deserialize(bytes) { - const reader = bytes instanceof pb_1__namespace.BinaryReader ? bytes : new pb_1__namespace.BinaryReader(bytes), message = new ProtoTxOut(); - while (reader.nextField()) { - if (reader.isEndGroup()) - break; - switch (reader.getFieldNumber()) { - case 1: - message.denomination = reader.readUint32(); - break; - case 2: - message.address = reader.readBytes(); - break; - default: reader.skipField(); - } - } - return message; - } - serializeBinary() { - return this.serialize(); - } - static deserializeBinary(bytes) { - return ProtoTxOut.deserialize(bytes); - } - } - block.ProtoTxOut = ProtoTxOut; - })(block || (block = {})); - - /** - * @category Encoding - * @param {ProtoTransaction} protoTx - The signed constructed transaction - * @returns {string} - The Protobuf encoded transaction - */ - function encodeProtoTransaction(protoTx) { - const tx = block.ProtoTransaction.fromObject(protoTx); - return hexlify(tx.serialize()); - } - - /** - * @category Encoding - * @param {Uint8Array} bytes - The Protobuf encoded transaction - * @returns {ProtoTransaction} - The decoded transaction - */ - function decodeProtoTransaction(bytes) { - const tx = block.ProtoTransaction.deserialize(bytes); - const result = tx.toObject(); - if (result.to?.length == 0) { - result.to = null; - } - return result; - } - - /** - * Using strings in Ethereum (or any security-basd system) requires additional care. These utilities attempt to mitigate - * some of the safety issues as well as provide the ability to recover and analyse strings. - * - * @subsection api/utils:Strings and UTF-8 [about-strings] - */ - // `output` and `badCodepoint` are passed to calls below, but not used in the function - function errorFunc(reason, offset, bytes, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - output, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - badCodepoint) { - assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, 'bytes', bytes); - } - // `output` and `badCodepoint` are passed to calls below, but not used in the function - function ignoreFunc(reason, offset, bytes, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - output, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - badCodepoint) { - // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes - if (reason === 'BAD_PREFIX' || reason === 'UNEXPECTED_CONTINUE') { - let i = 0; - for (let o = offset + 1; o < bytes.length; o++) { - if (bytes[o] >> 6 !== 0x02) { - break; - } - i++; - } - return i; - } - // This byte runs us past the end of the string, so just jump to the end - // (but the first byte was read already read and therefore skipped) - if (reason === 'OVERRUN') { - return bytes.length - offset - 1; - } - // Nothing to skip - return 0; - } - function replaceFunc(reason, offset, bytes, output, badCodepoint) { - // Overlong representations are otherwise "valid" code points; just non-deistingtished - if (reason === 'OVERLONG') { - assertArgument(typeof badCodepoint === 'number', 'invalid bad code point for replacement', 'badCodepoint', badCodepoint); - output.push(badCodepoint); - return 0; - } - // Put the replacement character into the output - output.push(0xfffd); - // Otherwise, process as if ignoring errors - return ignoreFunc(reason, offset, bytes); - } - /** - * A handful of popular, built-in UTF-8 error handling strategies. - * - * **`"error"`** - throws on ANY illegal UTF-8 sequence or non-canonical (overlong) codepoints (this is the default) - * - * **`"ignore"`** - silently drops any illegal UTF-8 sequence and accepts non-canonical (overlong) codepoints - * - * **`"replace"`** - replace any illegal UTF-8 sequence with the UTF-8 replacement character (i.e. `"\\ufffd"`) and - * accepts non-canonical (overlong) codepoints - * - * @category Encoding - * @returns Record<"error" | "ignore" | "replace", Utf8ErrorFunc> - */ - const Utf8ErrorFuncs = Object.freeze({ - error: errorFunc, - ignore: ignoreFunc, - replace: replaceFunc, - }); - // http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 - function getUtf8CodePoints(_bytes, onError) { - if (onError == null) { - onError = Utf8ErrorFuncs.error; - } - const bytes = getBytes(_bytes, 'bytes'); - const result = []; - let i = 0; - // Invalid bytes are ignored - while (i < bytes.length) { - const c = bytes[i++]; - // 0xxx xxxx - if (c >> 7 === 0) { - result.push(c); - continue; - } - // Multibyte; how many bytes left for this character? - let extraLength = null; - let overlongMask = null; - // 110x xxxx 10xx xxxx - if ((c & 0xe0) === 0xc0) { - extraLength = 1; - overlongMask = 0x7f; - // 1110 xxxx 10xx xxxx 10xx xxxx - } - else if ((c & 0xf0) === 0xe0) { - extraLength = 2; - overlongMask = 0x7ff; - // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx - } - else if ((c & 0xf8) === 0xf0) { - extraLength = 3; - overlongMask = 0xffff; - } - else { - if ((c & 0xc0) === 0x80) { - i += onError('UNEXPECTED_CONTINUE', i - 1, bytes, result); - } - else { - i += onError('BAD_PREFIX', i - 1, bytes, result); - } - continue; - } - // Do we have enough bytes in our data? - if (i - 1 + extraLength >= bytes.length) { - i += onError('OVERRUN', i - 1, bytes, result); - continue; - } - // Remove the length prefix from the char - let res = c & ((1 << (8 - extraLength - 1)) - 1); - for (let j = 0; j < extraLength; j++) { - const nextChar = bytes[i]; - // Invalid continuation byte - if ((nextChar & 0xc0) != 0x80) { - i += onError('MISSING_CONTINUE', i, bytes, result); - res = null; - break; - } - res = (res << 6) | (nextChar & 0x3f); - i++; - } - // See above loop for invalid continuation byte - if (res === null) { - continue; - } - // Maximum code point - if (res > 0x10ffff) { - i += onError('OUT_OF_RANGE', i - 1 - extraLength, bytes, result, res); - continue; - } - // Reserved for UTF-16 surrogate halves - if (res >= 0xd800 && res <= 0xdfff) { - i += onError('UTF16_SURROGATE', i - 1 - extraLength, bytes, result, res); - continue; - } - // Check for overlong sequences (more bytes than needed) - if (res <= overlongMask) { - i += onError('OVERLONG', i - 1 - extraLength, bytes, result, res); - continue; - } - result.push(res); - } - return result; - } - // http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array - /** - * Returns the UTF-8 byte representation of `str`. - * - * If `form` is specified, the string is normalized. - * - * @category Encoding - * @param {string} str - The string to convert. - * @param {UnicodeNormalizationForm} [form] - The normalization form to use. - * - * @returns {Uint8Array} The UTF-8 byte representation. - * @throws {Error} If the UTF-8 conversion fails. - */ - function toUtf8Bytes(str, form) { - if (form != null) { - assertNormalize(form); - str = str.normalize(form); - } - const result = []; - for (let i = 0; i < str.length; i++) { - const c = str.charCodeAt(i); - if (c < 0x80) { - result.push(c); - } - else if (c < 0x800) { - result.push((c >> 6) | 0xc0); - result.push((c & 0x3f) | 0x80); - } - else if ((c & 0xfc00) == 0xd800) { - i++; - const c2 = str.charCodeAt(i); - assertArgument(i < str.length && (c2 & 0xfc00) === 0xdc00, 'invalid surrogate pair', 'str', str); - // Surrogate Pair - const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); - result.push((pair >> 18) | 0xf0); - result.push(((pair >> 12) & 0x3f) | 0x80); - result.push(((pair >> 6) & 0x3f) | 0x80); - result.push((pair & 0x3f) | 0x80); - } - else { - result.push((c >> 12) | 0xe0); - result.push(((c >> 6) & 0x3f) | 0x80); - result.push((c & 0x3f) | 0x80); - } - } - return new Uint8Array(result); - } - /** - * @ignore - */ - function _toUtf8String(codePoints) { - return codePoints - .map((codePoint) => { - if (codePoint <= 0xffff) { - return String.fromCharCode(codePoint); - } - codePoint -= 0x10000; - return String.fromCharCode(((codePoint >> 10) & 0x3ff) + 0xd800, (codePoint & 0x3ff) + 0xdc00); - }) - .join(''); - } - /** - * Returns the string represented by the UTF-8 data `bytes`. - * - * When `onError` function is specified, it is called on UTF-8 errors allowing recovery using the - * {@link Utf8ErrorFunc | **Utf8ErrorFunc**} API. (default: [error](Utf8ErrorFuncs)) - * - * @category Encoding - * @param {BytesLike} bytes - The UTF-8 data to convert. - * @param {Utf8ErrorFunc} [onError] - The error handling function. - * - * @returns {string} The string. - */ - function toUtf8String(bytes, onError) { - return _toUtf8String(getUtf8CodePoints(bytes, onError)); - } - /** - * Returns the UTF-8 code-points for `str`. - * - * If `form` is specified, the string is normalized. - * - * @category Encoding - * @param {string} str - The string to convert. - * @param {UnicodeNormalizationForm} [form] - The normalization form to use. - * - * @returns {number[]} The UTF-8 code-points. - */ - function toUtf8CodePoints(str, form) { - return getUtf8CodePoints(toUtf8Bytes(str, form)); - } - - // @TODO: timeout is completely ignored; start a Promise.any with a reject? - // TODO: `options` is not used; remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - function createGetUrl(options) { - async function getUrl(req, _signal) { - const protocol = req.url.split(':')[0].toLowerCase(); - assert(protocol === 'http' || protocol === 'https', `unsupported protocol ${protocol}`, 'UNSUPPORTED_OPERATION', { - info: { protocol }, - operation: 'request', - }); - assert(protocol === 'https' || !req.credentials || req.allowInsecureAuthentication, 'insecure authorized connections unsupported', 'UNSUPPORTED_OPERATION', { - operation: 'request', - }); - let signal = undefined; - if (_signal) { - const controller = new AbortController(); - signal = controller.signal; - _signal.addListener(() => { - controller.abort(); - }); - } - const init = { - method: req.method, - headers: new Headers(Array.from(req)), - body: req.body || undefined, - signal, - }; - const resp = await fetch(req.url, init); - const headers = {}; - resp.headers.forEach((value, key) => { - headers[key.toLowerCase()] = value; - }); - const respBody = await resp.arrayBuffer(); - const body = respBody == null ? null : new Uint8Array(respBody); - return { - statusCode: resp.status, - statusMessage: resp.statusText, - headers, - body, - }; - } - return getUrl; - } - - /** - * Fetching content from the web is environment-specific, so quais provides an abstraction that each environment can - * implement to provide this service. - * - * On [Node.js](https://nodejs.org/), the `http` and `https` libs are used to create a request object, register event - * listeners and process data and populate the {@link FetchResponse | **FetchResponse**}. - * - * In a browser, the [DOM fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) is used, and the resulting - * `Promise` is waited on to retrieve the payload. - * - * The {@link FetchRequest | **FetchRequest**} is responsible for handling many common situations, such as redirects, - * server throttling, authentication, etc. - * - * It also handles common gateways, such as IPFS and data URIs. - */ - const MAX_ATTEMPTS = 12; - const SLOT_INTERVAL = 250; - // The global FetchGetUrlFunc implementation. - let defaultGetUrlFunc = createGetUrl(); - const reData = new RegExp('^data:([^;:]*)?(;base64)?,(.*)$', 'i'); - const reIpfs = new RegExp('^ipfs://(ipfs/)?(.*)$', 'i'); - // If locked, new Gateways cannot be added - let locked$5 = false; - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs - // TODO: `signal` is not used; remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async function dataGatewayFunc(url, signal) { - try { - const match = url.match(reData); - if (!match) { - throw new Error('invalid data'); - } - return new FetchResponse(200, 'OK', { - 'content-type': match[1] || 'text/plain', - }, match[2] ? decodeBase64(match[3]) : unpercent(match[3])); - } - catch (error) { - return new FetchResponse(599, 'BAD REQUEST (invalid data: URI)', {}, null, new FetchRequest(url)); - } - } - /** - * Returns a {@link FetchGatewayFunc | **FetchGatewayFunc**} for fetching content from a standard IPFS gateway hosted at - * `baseUrl`. - * - * @category Utils - * @param {string} baseUrl - The base URL of the IPFS gateway. - * @returns {FetchGatewayFunc} The gateway function. - */ - function getIpfsGatewayFunc(baseUrl) { - // TODO: `signal` is not used; remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async function gatewayIpfs(url, signal) { - try { - const match = url.match(reIpfs); - if (!match) { - throw new Error('invalid link'); - } - return new FetchRequest(`${baseUrl}${match[2]}`); - } - catch (error) { - return new FetchResponse(599, 'BAD REQUEST (invalid IPFS URI)', {}, null, new FetchRequest(url)); - } - } - return gatewayIpfs; - } - const Gateways = { - data: dataGatewayFunc, - ipfs: getIpfsGatewayFunc('https://gateway.ipfs.io/ipfs/'), - }; - const fetchSignals = new WeakMap(); - /** - * @ignore - */ - class FetchCancelSignal { - #listeners; - #cancelled; - constructor(request) { - this.#listeners = []; - this.#cancelled = false; - fetchSignals.set(request, () => { - if (this.#cancelled) { - return; - } - this.#cancelled = true; - for (const listener of this.#listeners) { - setTimeout(() => { - listener(); - }, 0); - } - this.#listeners = []; - }); - } - addListener(listener) { - assert(!this.#cancelled, 'singal already cancelled', 'UNSUPPORTED_OPERATION', { - operation: 'fetchCancelSignal.addCancelListener', - }); - this.#listeners.push(listener); - } - get cancelled() { - return this.#cancelled; - } - checkSignal() { - assert(!this.cancelled, 'cancelled', 'CANCELLED', {}); - } - } - // Check the signal, throwing if it is cancelled - function checkSignal(signal) { - if (signal == null) { - throw new Error('missing signal; should not happen'); - } - signal.checkSignal(); - return signal; - } - /** - * Represents a request for a resource using a URI. - * - * By default, the supported schemes are `HTTP`, `HTTPS`, `data:`, and `IPFS:`. - * - * Additional schemes can be added globally using {@link registerGateway | **registerGateway**}. - * - * @category Utils - * @example - * - * ```ts - * req = new FetchRequest('https://www.ricmoo.com'); - * resp = await req.send(); - * resp.body.length; - * ``` - */ - class FetchRequest { - #allowInsecure; - #gzip; - #headers; - #method; - #timeout; - #url; - #body; - #bodyType; - #creds; - // Hooks - #preflight; - #process; - #retry; - #signal; - #throttle; - #getUrlFunc; - /** - * The fetch URL to request. - */ - get url() { - return this.#url; - } - set url(url) { - this.#url = String(url); - } - /** - * The fetch body, if any, to send as the request body. (default: null) - * - * When setting a body, the intrinsic `Content-Type` is automatically set and will be used if **not overridden** by - * setting a custom header. - * - * If `body` is null, the body is cleared (along with the intrinsic `Content-Type`). - * - * If `body` is a string, the intrinsic `Content-Type` is set to `text/plain`. - * - * If `body` is a Uint8Array, the intrinsic `Content-Type` is set to `application/octet-stream`. - * - * If `body` is any other object, the intrinsic `Content-Type` is set to `application/json`. - */ - get body() { - if (this.#body == null) { - return null; - } - return new Uint8Array(this.#body); - } - set body(body) { - if (body == null) { - this.#body = undefined; - this.#bodyType = undefined; - } - else if (typeof body === 'string') { - this.#body = toUtf8Bytes(body); - this.#bodyType = 'text/plain'; - } - else if (body instanceof Uint8Array) { - this.#body = body; - this.#bodyType = 'application/octet-stream'; - } - else if (typeof body === 'object') { - this.#body = toUtf8Bytes(JSON.stringify(body)); - this.#bodyType = 'application/json'; - } - else { - throw new Error('invalid body'); - } - } - /** - * Returns true if the request has a body. - */ - hasBody() { - return this.#body != null; - } - /** - * The HTTP method to use when requesting the URI. If no method has been explicitly set, then `GET` is used if the - * body is null and `POST` otherwise. - */ - get method() { - if (this.#method) { - return this.#method; - } - if (this.hasBody()) { - return 'POST'; - } - return 'GET'; - } - set method(method) { - if (method == null) { - method = ''; - } - this.#method = String(method).toUpperCase(); - } - /** - * The headers that will be used when requesting the URI. All keys are lower-case. - * - * This object is a copy, so any changes will **NOT** be reflected in the `FetchRequest`. - * - * To set a header entry, use the `setHeader` method. - */ - get headers() { - const headers = Object.assign({}, this.#headers); - if (this.#creds) { - headers['authorization'] = `Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`; - } - if (this.allowGzip) { - headers['accept-encoding'] = 'gzip'; - } - if (headers['content-type'] == null && this.#bodyType) { - headers['content-type'] = this.#bodyType; - } - if (this.body) { - headers['content-length'] = String(this.body.length); - } - return headers; - } - /** - * Get the header for `key`, ignoring case. - * - * @param {string} key - The header key to retrieve. - * @returns {string} The header value. - */ - getHeader(key) { - return this.headers[key.toLowerCase()]; - } - /** - * Set the header for `key` to `value`. All values are coerced to a string. - * - * @param {string} key - The header key to set. - * @param {string | number} value - The header value to set. - */ - setHeader(key, value) { - this.#headers[String(key).toLowerCase()] = String(value); - } - /** - * Clear all headers, resetting all intrinsic headers. - */ - clearHeaders() { - this.#headers = {}; - } - [Symbol.iterator]() { - const headers = this.headers; - const keys = Object.keys(headers); - let index = 0; - return { - next: () => { - if (index < keys.length) { - const key = keys[index++]; - return { - value: [key, headers[key]], - done: false, - }; - } - return { value: undefined, done: true }; - }, - }; - } - /** - * The value that will be sent for the `Authorization` header. - * - * To set the credentials, use the `setCredentials` method. - */ - get credentials() { - return this.#creds || null; - } - /** - * Sets an `Authorization` for `username` with `password`. - * - * @param {string} username - The username to use for basic authentication. - * @param {string} password - The password to use for basic authentication. - * @throws {Error} If the `username` contains a colon. - */ - setCredentials(username, password) { - assertArgument(!username.match(/:/), 'invalid basic authentication username', 'username', '[REDACTED]'); - this.#creds = `${username}:${password}`; - } - /** - * Enable and request gzip-encoded responses. The response will automatically be decompressed. (default: true) - */ - get allowGzip() { - return this.#gzip; - } - set allowGzip(value) { - this.#gzip = !!value; - } - /** - * Allow `Authentication` credentials to be sent over insecure channels. (default: false) - */ - get allowInsecureAuthentication() { - return !!this.#allowInsecure; - } - set allowInsecureAuthentication(value) { - this.#allowInsecure = !!value; - } - /** - * The timeout (in milliseconds) to wait for a complete response. (default: 5 minutes) - */ - get timeout() { - return this.#timeout; - } - set timeout(timeout) { - assertArgument(timeout >= 0, 'timeout must be non-zero', 'timeout', timeout); - this.#timeout = timeout; - } - /** - * This function is called prior to each request, for example during a redirection or retry in case of server - * throttling. - * - * This offers an opportunity to populate headers or update content before sending a request. - */ - get preflightFunc() { - return this.#preflight || null; - } - set preflightFunc(preflight) { - this.#preflight = preflight; - } - /** - * This function is called after each response, offering an opportunity to provide client-level throttling or - * updating response data. - * - * Any error thrown in this causes the `send()` to throw. - * - * To schedule a retry attempt (assuming the maximum retry limit has not been reached), use - * {@link FetchResponse.throwThrottleError | **FetchResponse.throwThrottleError**}. - */ - get processFunc() { - return this.#process || null; - } - set processFunc(process) { - this.#process = process; - } - /** - * This function is called on each retry attempt. - */ - get retryFunc() { - return this.#retry || null; - } - set retryFunc(retry) { - this.#retry = retry; - } - /** - * This function is called to fetch content from HTTP and HTTPS URLs and is platform specific (e.g. nodejs vs - * browsers). - * - * This is by default the currently registered global getUrl function, which can be changed using - * {@link registerGetUrl | **registerGetUrl**}. If this has been set, setting is to `null` will cause this - * FetchRequest (and any future clones) to revert back to using the currently registered global getUrl function. - * - * Setting this is generally not necessary, but may be useful for developers that wish to intercept requests or to - * configurege a proxy or other agent. - */ - get getUrlFunc() { - return this.#getUrlFunc || defaultGetUrlFunc; - } - set getUrlFunc(value) { - this.#getUrlFunc = value; - } - /** - * Create a new FetchRequest instance with default values. - * - * Once created, each property may be set before issuing a `.send()` to make the request. - */ - constructor(url) { - this.#url = String(url); - this.#allowInsecure = false; - this.#gzip = true; - this.#headers = {}; - this.#method = ''; - this.#timeout = 300000; - this.#throttle = { - slotInterval: SLOT_INTERVAL, - maxAttempts: MAX_ATTEMPTS, - }; - this.#getUrlFunc = null; - } - toString() { - return ``; - } - /** - * Update the throttle parameters used to determine maximum attempts and exponential-backoff properties. - * - * @param {FetchThrottleParams} params - The throttle parameters to set. - * @throws {Error} If the `slotInterval` is not a positive integer. - */ - setThrottleParams(params) { - if (params.slotInterval != null) { - this.#throttle.slotInterval = params.slotInterval; - } - if (params.maxAttempts != null) { - this.#throttle.maxAttempts = params.maxAttempts; - } - } - async #send(attempt, expires, delay, _request, _response) { - if (attempt >= this.#throttle.maxAttempts) { - return _response.makeServerError('exceeded maximum retry limit'); - } - assert(getTime$1() <= expires, 'timeout', 'TIMEOUT', { - operation: 'request.send', - reason: 'timeout', - request: _request, - }); - if (delay > 0) { - await wait(delay); - } - let req = this.clone(); - const scheme = (req.url.split(':')[0] || '').toLowerCase(); - // Process any Gateways - if (scheme in Gateways) { - const result = await Gateways[scheme](req.url, checkSignal(_request.#signal)); - if (result instanceof FetchResponse) { - let response = result; - if (this.processFunc) { - checkSignal(_request.#signal); - try { - response = await this.processFunc(req, response); - } - catch (error) { - // Something went wrong during processing; throw a 5xx server error - if (error.throttle == null || typeof error.stall !== 'number') { - response.makeServerError('error in post-processing function', error).assertOk(); - } - // Ignore throttling - } - } - return response; - } - req = result; - } - // We have a preflight function; update the request - if (this.preflightFunc) { - req = await this.preflightFunc(req); - } - const resp = await this.getUrlFunc(req, checkSignal(_request.#signal)); - let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request); - if (response.statusCode === 301 || response.statusCode === 302) { - // Redirect - try { - const location = response.headers.location || ''; - return req.redirect(location).#send(attempt + 1, expires, 0, _request, response); - // eslint-disable-next-line no-empty - } - catch (error) { } - // Things won't get any better on another attempt; abort - return response; - } - else if (response.statusCode === 429) { - // Throttle - if (this.retryFunc == null || (await this.retryFunc(req, response, attempt))) { - const retryAfter = response.headers['retry-after']; - let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); - if (typeof retryAfter === 'string' && retryAfter.match(/^[1-9][0-9]*$/)) { - delay = parseInt(retryAfter); - } - return req.clone().#send(attempt + 1, expires, delay, _request, response); - } - } - if (this.processFunc) { - checkSignal(_request.#signal); - try { - response = await this.processFunc(req, response); - } - catch (error) { - // Something went wrong during processing; throw a 5xx server error - if (error.throttle == null || typeof error.stall !== 'number') { - response.makeServerError('error in post-processing function', error).assertOk(); - } - // Throttle - let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); - if (error.stall >= 0) { - delay = error.stall; - } - return req.clone().#send(attempt + 1, expires, delay, _request, response); - } - } - return response; - } - /** - * Resolves to the response by sending the request. - */ - send() { - assert(this.#signal == null, 'request already sent', 'UNSUPPORTED_OPERATION', { - operation: 'fetchRequest.send', - }); - this.#signal = new FetchCancelSignal(this); - return this.#send(0, getTime$1() + this.timeout, 0, this, new FetchResponse(0, '', {}, null, this)); - } - /** - * Cancels the inflight response, causing a `CANCELLED` error to be rejected from the - * {@link FetchRequest.send | **send**}. - */ - cancel() { - assert(this.#signal != null, 'request has not been sent', 'UNSUPPORTED_OPERATION', { - operation: 'fetchRequest.cancel', - }); - const signal = fetchSignals.get(this); - if (!signal) { - throw new Error('missing signal; should not happen'); - } - signal(); - } - /** - * Returns a new {@link FetchRequest | **FetchRequest**} that represents the redirection to `location`. - * - * @param {string} location - The location to redirect to. - * @returns {FetchRequest} The new request. - */ - redirect(location) { - // Redirection; for now we only support absolute locations - const current = this.url.split(':')[0].toLowerCase(); - const target = location.split(':')[0].toLowerCase(); - // Don't allow redirecting: - // - non-GET requests - // - downgrading the security (e.g. https => http) - // - to non-HTTP (or non-HTTPS) protocols [this could be relaxed?] - assert(this.method === 'GET' && (current !== 'https' || target !== 'http') && location.match(/^https?:/), `unsupported redirect`, 'UNSUPPORTED_OPERATION', { - operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`, - }); - // Create a copy of this request, with a new URL - const req = new FetchRequest(location); - req.method = 'GET'; - req.allowGzip = this.allowGzip; - req.timeout = this.timeout; - req.#headers = Object.assign({}, this.#headers); - if (this.#body) { - req.#body = new Uint8Array(this.#body); - } - req.#bodyType = this.#bodyType; - return req; - } - /** - * Create a new copy of this request. - * - * @returns {FetchRequest} The new request. - */ - clone() { - const clone = new FetchRequest(this.url); - // Preserve "default method" (i.e. null) - clone.#method = this.#method; - // Preserve "default body" with type, copying the Uint8Array is present - if (this.#body) { - clone.#body = this.#body; - } - clone.#bodyType = this.#bodyType; - // Preserve "default headers" - clone.#headers = Object.assign({}, this.#headers); - // Credentials is readonly, so we copy internally - clone.#creds = this.#creds; - if (this.allowGzip) { - clone.allowGzip = true; - } - clone.timeout = this.timeout; - if (this.allowInsecureAuthentication) { - clone.allowInsecureAuthentication = true; - } - clone.#preflight = this.#preflight; - clone.#process = this.#process; - clone.#retry = this.#retry; - clone.#getUrlFunc = this.#getUrlFunc; - return clone; - } - /** - * Locks all static configuration for gateways and FetchGetUrlFunc registration. - */ - static lockConfig() { - locked$5 = true; - } - /** - * Get the current Gateway function for `scheme`. - * - * @param {string} scheme - The scheme to get the gateway for. - * @returns {FetchGatewayFunc | null} The gateway function, or null if not found. - */ - static getGateway(scheme) { - return Gateways[scheme.toLowerCase()] || null; - } - /** - * Use the `func` when fetching URIs using `scheme`. - * - * This method affects all requests globally. - * - * If {@link FetchRequest.lockConfig | **lockConfig**} has been called, no change is made and this throws. - * - * @param {string} scheme - The scheme to register the gateway for. - * @param {FetchGatewayFunc} func - The gateway function to use. - * @throws {Error} If the scheme is `http` or `https`. - */ - static registerGateway(scheme, func) { - scheme = scheme.toLowerCase(); - if (scheme === 'http' || scheme === 'https') { - throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); - } - if (locked$5) { - throw new Error('gateways locked'); - } - Gateways[scheme] = func; - } - /** - * Use `getUrl` when fetching URIs over HTTP and HTTPS requests. - * - * This method affects all requests globally. - * - * If {@link FetchRequest.lockConfig | **lockConfig**} has been called, no change is made and this throws. - * - * @param {FetchGetUrlFunc} getUrl - The function to use for fetching HTTP and HTTPS URIs. - * @throws {Error} If the gateways are locked. - */ - static registerGetUrl(getUrl) { - if (locked$5) { - throw new Error('gateways locked'); - } - defaultGetUrlFunc = getUrl; - } - /** - * Creates a getUrl function that fetches content from HTTP and HTTPS URLs. - * - * The available `options` are dependent on the platform implementation of the default getUrl function. - * - * This is not generally something that is needed, but is useful when trying to customize simple behaviour when - * fetching HTTP content. - * - * @param {Record} [options] - The options to use when creating the getUrl function. - * @returns {FetchGetUrlFunc} The getUrl function. - * @throws {Error} If the gateways are locked. - */ - static createGetUrlFunc(options) { - return createGetUrl(); - } - /** - * Creates a function that can "fetch" data URIs. - * - * Note that this is automatically done internally to support data URIs, so it is not necessary to register it. - * - * This is not generally something that is needed, but may be useful in a wrapper to perfom custom data URI - * functionality. - * - * @returns {FetchGatewayFunc} The gateway function. - */ - static createDataGateway() { - return dataGatewayFunc; - } - /** - * Creates a function that will fetch IPFS (unvalidated) from a custom gateway baseUrl. - * - * The default IPFS gateway used internally is `"https:/\/gateway.ipfs.io/ipfs/"`. - * - * @param {string} baseUrl - The base URL of the IPFS gateway. - * @returns {FetchGatewayFunc} The gateway function. - */ - static createIpfsGatewayFunc(baseUrl) { - return getIpfsGatewayFunc(baseUrl); - } - } - /** - * The response for a FetchRequest. - * - * @category Utils - */ - class FetchResponse { - #statusCode; - #statusMessage; - #headers; - #body; - #request; - #error; - toString() { - return ``; - } - /** - * The response status code. - */ - get statusCode() { - return this.#statusCode; - } - /** - * The response status message. - */ - get statusMessage() { - return this.#statusMessage; - } - /** - * The response headers. All keys are lower-case. - */ - get headers() { - return Object.assign({}, this.#headers); - } - /** - * The response body, or `null` if there was no body. - */ - get body() { - return this.#body == null ? null : new Uint8Array(this.#body); - } - /** - * The response body as a UTF-8 encoded string, or the empty string (i.e. `""`) if there was no body. - * - * An error is thrown if the body is invalid UTF-8 data. - */ - get bodyText() { - try { - return this.#body == null ? '' : toUtf8String(this.#body); - } - catch (error) { - assert(false, 'response body is not valid UTF-8 data', 'UNSUPPORTED_OPERATION', { - operation: 'bodyText', - info: { response: this }, - }); - } - } - /** - * The response body, decoded as JSON. - * - * An error is thrown if the body is invalid JSON-encoded data or if there was no body. - */ - get bodyJson() { - try { - return JSON.parse(this.bodyText); - } - catch (error) { - assert(false, 'response body is not valid JSON', 'UNSUPPORTED_OPERATION', { - operation: 'bodyJson', - info: { response: this }, - }); - } - } - [Symbol.iterator]() { - const headers = this.headers; - const keys = Object.keys(headers); - let index = 0; - return { - next: () => { - if (index < keys.length) { - const key = keys[index++]; - return { - value: [key, headers[key]], - done: false, - }; - } - return { value: undefined, done: true }; - }, - }; - } - constructor(statusCode, statusMessage, headers, body, request) { - this.#statusCode = statusCode; - this.#statusMessage = statusMessage; - this.#headers = Object.keys(headers).reduce((accum, k) => { - accum[k.toLowerCase()] = String(headers[k]); - return accum; - }, {}); - this.#body = body == null ? null : new Uint8Array(body); - this.#request = request || null; - this.#error = { message: '' }; - } - /** - * Return a Response with matching headers and body, but with an error status code (i.e. 599) and `message` with an - * optional `error`. - * - * @param {string} [message] - The error message to use. - * @param {Error} [error] - The error to use. - * @returns {FetchResponse} The error response. - */ - makeServerError(message, error) { - let statusMessage; - if (!message) { - message = `${this.statusCode} ${this.statusMessage}`; - statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; - } - else { - statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; - } - const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined); - response.#error = { message, error }; - return response; - } - /** - * If called within a [request.processFunc](FetchRequest-processFunc) call, causes the request to retry as if - * throttled for `stall` milliseconds. - * - * @param {string} [message] - The error message to use. - * @param {number} [stall] - The number of milliseconds to stall before retrying. - * @throws {Error} If `stall` is not a non-negative integer. - */ - throwThrottleError(message, stall) { - if (stall == null) { - stall = -1; - } - else { - assertArgument(Number.isInteger(stall) && stall >= 0, 'invalid stall timeout', 'stall', stall); - } - const error = new Error(message || 'throttling requests'); - defineProperties(error, { stall, throttle: true }); - throw error; - } - /** - * Get the header value for `key`, ignoring case. - * - * @param {string} key - The header key to retrieve. - * @returns {string} The header value. - */ - getHeader(key) { - return this.headers[key.toLowerCase()]; - } - /** - * Returns true if the response has a body. - * - * @returns {boolean} True if the response has a body. - * @throws {Error} If the body is invalid UTF-8 data. - */ - hasBody() { - return this.#body != null; - } - /** - * The request made for this response. - */ - get request() { - return this.#request; - } - /** - * Returns true if this response was a success statusCode. - */ - ok() { - return this.#error.message === '' && this.statusCode >= 200 && this.statusCode < 300; - } - /** - * Throws a `SERVER_ERROR` if this response is not ok. - * - * @throws {Error} If the response is not ok. - */ - assertOk() { - if (this.ok()) { - return; - } - // eslint-disable-next-line prefer-const - let { message, error } = this.#error; - if (message === '') { - message = `server response ${this.statusCode} ${this.statusMessage}`; - } - assert(false, message, 'SERVER_ERROR', { - request: this.request || 'unknown request', - response: this, - error, - }); - } - } - function getTime$1() { - return new Date().getTime(); - } - function unpercent(value) { - return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => { - return String.fromCharCode(parseInt(code, 16)); - })); - } - function wait(delay) { - return new Promise((resolve) => setTimeout(resolve, delay)); - } - - /** - * The **FixedNumber** class permits using values with decimal places, using fixed-pont math. - * - * Fixed-point math is still based on integers under-the-hood, but uses an internal offset to store fractional - * components below, and each operation corrects for this after each operation. - */ - const BN_N1 = BigInt(-1); - const BN_0$6 = BigInt(0); - const BN_1$3 = BigInt(1); - const BN_5 = BigInt(5); - const _guard$7 = {}; - // Constant to pull zeros from for multipliers - let Zeros = '0000'; - while (Zeros.length < 80) { - Zeros += Zeros; - } - // Returns a string "1" followed by decimal "0"s - function getTens(decimals) { - let result = Zeros; - while (result.length < decimals) { - result += result; - } - return BigInt('1' + result.substring(0, decimals)); - } - function checkValue(val, format, safeOp) { - const width = BigInt(format.width); - if (format.signed) { - const limit = BN_1$3 << (width - BN_1$3); - assert(safeOp == null || (val >= -limit && val < limit), 'overflow', 'NUMERIC_FAULT', { - operation: safeOp, - fault: 'overflow', - value: val, - }); - if (val > BN_0$6) { - val = fromTwos(mask(val, width), width); - } - else { - val = -fromTwos(mask(-val, width), width); - } - } - else { - const limit = BN_1$3 << width; - assert(safeOp == null || (val >= 0 && val < limit), 'overflow', 'NUMERIC_FAULT', { - operation: safeOp, - fault: 'overflow', - value: val, - }); - val = ((val % limit) + limit) % limit & (limit - BN_1$3); - } - return val; - } - function getFormat(value) { - if (typeof value === 'number') { - value = `fixed128x${value}`; - } - let signed = true; - let width = 128; - let decimals = 18; - if (typeof value === 'string') { - // Parse the format string - if (value === 'fixed') ; - else if (value === 'ufixed') { - signed = false; - } - else { - const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); - assertArgument(match, 'invalid fixed format', 'format', value); - signed = match[1] !== 'u'; - width = parseInt(match[2]); - decimals = parseInt(match[3]); - } - } - else if (value) { - // Extract the values from the object - const v = value; - const check = (key, type, defaultValue) => { - if (v[key] == null) { - return defaultValue; - } - assertArgument(typeof v[key] === type, 'invalid fixed format (' + key + ' not ' + type + ')', 'format.' + key, v[key]); - return v[key]; - }; - signed = check('signed', 'boolean', signed); - width = check('width', 'number', width); - decimals = check('decimals', 'number', decimals); - } - assertArgument(width % 8 === 0, 'invalid FixedNumber width (not byte aligned)', 'format.width', width); - assertArgument(decimals <= 80, 'invalid FixedNumber decimals (too large)', 'format.decimals', decimals); - const name = (signed ? '' : 'u') + 'fixed' + String(width) + 'x' + String(decimals); - return { signed, width, decimals, name }; - } - function toString(val, decimals) { - let negative = ''; - if (val < BN_0$6) { - negative = '-'; - val *= BN_N1; - } - let str = val.toString(); - // No decimal point for whole values - if (decimals === 0) { - return negative + str; - } - // Pad out to the whole component (including a whole digit) - while (str.length <= decimals) { - str = Zeros + str; - } - // Insert the decimal point - const index = str.length - decimals; - str = str.substring(0, index) + '.' + str.substring(index); - // Trim the whole component (leaving at least one 0) - while (str[0] === '0' && str[1] !== '.') { - str = str.substring(1); - } - // Trim the decimal component (leaving at least one 0) - while (str[str.length - 1] === '0' && str[str.length - 2] !== '.') { - str = str.substring(0, str.length - 1); - } - return negative + str; - } - /** - * A FixedNumber represents a value over its {@link FixedFormat | **FixedFormat**} arithmetic field. - * - * A FixedNumber can be used to perform math, losslessly, on values which have decmial places. - * - * A FixedNumber has a fixed bit-width to store values in, and stores all values internally by multiplying the value by - * 10 raised to the power of `decimals`. - * - * If operations are performed that cause a value to grow too high (close to positive infinity) or too low (close to - * negative infinity), the value is said to overflow. - * - * For example, an 8-bit signed value, with 0 decimals may only be within the range `-128` to `127`; so `-128 - 1` will - * overflow and become `127`. Likewise, `127 + 1` will overflow and become `-127`. - * - * Many operation have a normal and unsafe variant. The normal variant will throw a - * [NumericFaultError](../interfaces/NumericFaultError) on any overflow, while the unsafe variant will silently allow - * overflow, corrupting its value value. - * - * If operations are performed that cause a value to become too small (close to zero), the value loses precison and is - * said to underflow. - * - * For example, an value with 1 decimal place may store a number as small as `0.1`, but the value of `0.1 / 2` is - * `0.05`, which cannot fit into 1 decimal place, so underflow occurs which means precision is lost and the value - * becomes `0`. - * - * Some operations have a normal and signalling variant. The normal variant will silently ignore underflow, while the - * signalling variant will thow a [NumericFaultError](../interfaces/NumericFaultError) on underflow. - * - * @category Utils - */ - class FixedNumber { - /** - * The specific fixed-point arithmetic field for this value. - */ - format; - #format; - // The actual value (accounting for decimals) - #val; - // A base-10 value to multiple values by to maintain the magnitude - #tens; - /** - * This is a property so console.log shows a human-meaningful value. - * - * @ignore - */ - _value; - // Use this when changing this file to get some typing info, - // but then switch to any to mask the internal type - // constructor(guard: any, value: bigint, format: _FixedFormat) { - /** - * @ignore - */ - constructor(guard, value, format) { - assertPrivate(guard, _guard$7, 'FixedNumber'); - this.#val = value; - this.#format = format; - const _value = toString(value, format.decimals); - defineProperties(this, { format: format.name, _value }); - this.#tens = getTens(format.decimals); - } - /** - * If true, negative values are permitted, otherwise only positive values and zero are allowed. - */ - get signed() { - return this.#format.signed; - } - /** - * The number of bits available to store the value. - */ - get width() { - return this.#format.width; - } - /** - * The number of decimal places in the fixed-point arithment field. - */ - get decimals() { - return this.#format.decimals; - } - /** - * The value as an integer, based on the smallest unit the {@link FixedNumber.decimals | **decimals**} allow. - */ - get value() { - return this.#val; - } - #checkFormat(other) { - assertArgument(this.format === other.format, 'incompatible format; use fixedNumber.toFormat', 'other', other); - } - #checkValue(val, safeOp) { - val = checkValue(val, this.#format, safeOp); - return new FixedNumber(_guard$7, val, this.#format); - } - #add(o, safeOp) { - this.#checkFormat(o); - return this.#checkValue(this.#val + o.#val, safeOp); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` added to `other`, ignoring overflow. - * - * @param {FixedNumber} other - The value to add to `this`. - * @returns {FixedNumber} The result of the addition. - */ - addUnsafe(other) { - return this.#add(other); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` added to `other`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to add to `this`. - * @returns {FixedNumber} The result of the addition. - */ - add(other) { - return this.#add(other, 'add'); - } - #sub(o, safeOp) { - this.#checkFormat(o); - return this.#checkValue(this.#val - o.#val, safeOp); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `other` subtracted from `this`, ignoring - * overflow. - * - * @param {FixedNumber} other - The value to subtract from `this`. - * @returns {FixedNumber} The result of the subtraction. - */ - subUnsafe(other) { - return this.#sub(other); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `other` subtracted from `this`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to subtract from `this`. - * @returns {FixedNumber} The result of the subtraction. - */ - sub(other) { - return this.#sub(other, 'sub'); - } - #mul(o, safeOp) { - this.#checkFormat(o); - return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`, ignoring - * overflow and underflow (precision loss). - * - * @param {FixedNumber} other - The value to multiply `this` by. - * @returns {FixedNumber} The result of the multiplication. - */ - mulUnsafe(other) { - return this.#mul(other); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to multiply `this` by. - * @returns {FixedNumber} The result of the multiplication. - */ - mul(other) { - return this.#mul(other, 'mul'); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs or if underflow (precision - * loss) occurs. - * - * @param {FixedNumber} other - The value to multiply `this` by. - * @returns {FixedNumber} The result of the multiplication. - * @throws {NumericFaultError} Thrown if overflow or underflow occurs. - * @throws {NumericFaultError} Thrown if division by 0 occurs. - */ - mulSignal(other) { - this.#checkFormat(other); - const value = this.#val * other.#val; - assert(value % this.#tens === BN_0$6, 'precision lost during signalling mul', 'NUMERIC_FAULT', { - operation: 'mulSignal', - fault: 'underflow', - value: this, - }); - return this.#checkValue(value / this.#tens, 'mulSignal'); - } - #div(o, safeOp) { - assert(o.#val !== BN_0$6, 'division by zero', 'NUMERIC_FAULT', { - operation: 'div', - fault: 'divide-by-zero', - value: this, - }); - this.#checkFormat(o); - return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`, ignoring - * underflow (precision loss). A [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to divide `this` by. - * @returns {FixedNumber} The result of the division. - */ - divUnsafe(other) { - return this.#div(other); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`, ignoring - * underflow (precision loss). A [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs. - * - * @param {FixedNumber} other - The value to divide `this` by. - * @returns {FixedNumber} The result of the division. - */ - div(other) { - return this.#div(other, 'div'); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`. A - * [NumericFaultError](../interfaces/NumericFaultError) is thrown if underflow (precision loss) occurs. - * - * @param {FixedNumber} other - The value to divide `this` by. - * @returns {FixedNumber} The result of the division. - * @throws {NumericFaultError} Thrown if underflow occurs. - */ - divSignal(other) { - assert(other.#val !== BN_0$6, 'division by zero', 'NUMERIC_FAULT', { - operation: 'div', - fault: 'divide-by-zero', - value: this, - }); - this.#checkFormat(other); - const value = this.#val * this.#tens; - assert(value % other.#val === BN_0$6, 'precision lost during signalling div', 'NUMERIC_FAULT', { - operation: 'divSignal', - fault: 'underflow', - value: this, - }); - return this.#checkValue(value / other.#val, 'divSignal'); - } - /** - * Returns a comparison result between `this` and `other`. - * - * This is suitable for use in sorting, where `-1` implies `this` is smaller, `1` implies `this` is larger and `0` - * implies both are equal. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {number} The comparison result. - */ - cmp(other) { - let a = this.value, b = other.value; - // Coerce a and b to the same magnitude - const delta = this.decimals - other.decimals; - if (delta > 0) { - b *= getTens(delta); - } - else if (delta < 0) { - a *= getTens(-delta); - } - // Comnpare - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; - } - /** - * Returns true if `other` is equal to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is equal to `this`. - */ - eq(other) { - return this.cmp(other) === 0; - } - /** - * Returns true if `other` is less than to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is less than to `this`. - */ - lt(other) { - return this.cmp(other) < 0; - } - /** - * Returns true if `other` is less than or equal to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is less than or equal to `this`. - */ - lte(other) { - return this.cmp(other) <= 0; - } - /** - * Returns true if `other` is greater than to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is greater than to `this`. - */ - gt(other) { - return this.cmp(other) > 0; - } - /** - * Returns true if `other` is greater than or equal to `this`. - * - * @param {FixedNumber} other - The value to compare to `this`. - * @returns {boolean} True if `other` is greater than or equal to `this`. - */ - gte(other) { - return this.cmp(other) >= 0; - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} which is the largest **integer** that is less than or equal to - * `this`. - * - * The decimal component of the result will always be `0`. - * - * @returns {FixedNumber} The floored value. - */ - floor() { - let val = this.#val; - if (this.#val < BN_0$6) { - val -= this.#tens - BN_1$3; - } - val = (this.#val / this.#tens) * this.#tens; - return this.#checkValue(val, 'floor'); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} which is the smallest **integer** that is greater than or - * equal to `this`. - * - * The decimal component of the result will always be `0`. - * - * @returns {FixedNumber} The ceiling value. - */ - ceiling() { - let val = this.#val; - if (this.#val > BN_0$6) { - val += this.#tens - BN_1$3; - } - val = (this.#val / this.#tens) * this.#tens; - return this.#checkValue(val, 'ceiling'); - } - /** - * Returns a new {@link FixedNumber | **FixedNumber**} with the decimal component rounded up on ties at `decimals` - * places. - * - * @param {number} [decimals] - The number of decimal places to round to. - * @returns {FixedNumber} The rounded value. - */ - round(decimals) { - if (decimals == null) { - decimals = 0; - } - // Not enough precision to not already be rounded - if (decimals >= this.decimals) { - return this; - } - const delta = this.decimals - decimals; - const bump = BN_5 * getTens(delta - 1); - let value = this.value + bump; - const tens = getTens(delta); - value = (value / tens) * tens; - checkValue(value, this.#format, 'round'); - return new FixedNumber(_guard$7, value, this.#format); - } - /** - * Returns true if `this` is equal to `0`. - * - * @returns {boolean} True if `this` is equal to `0`. - */ - isZero() { - return this.#val === BN_0$6; - } - /** - * Returns true if `this` is less than `0`. - * - * @returns {boolean} True if `this` is less than `0`. - */ - isNegative() { - return this.#val < BN_0$6; - } - /** - * Returns the string representation of `this`. - * - * @returns {string} The string representation. - */ - toString() { - return this._value; - } - /** - * Returns a float approximation. - * - * Due to IEEE 754 precission (or lack thereof), this function can only return an approximation and most values will - * contain rounding errors. - * - * @returns {number} The float approximation. - */ - toUnsafeFloat() { - return parseFloat(this.toString()); - } - /** - * Return a new {@link FixedNumber | **FixedNumber**} with the same value but has had its field set to `format`. - * - * This will throw if the value cannot fit into `format`. - * - * @param {FixedFormat} format - The new format for the value. - */ - toFormat(format) { - return FixedNumber.fromString(this.toString(), format); - } - /** - * Creates a new {@link FixedNumber | **FixedNumber**} for `value` divided by `decimal` places with `format`. - * - * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` (once adjusted for `decimals`) - * cannot fit in `format`, either due to overflow or underflow (precision loss). - * - * @param {BigNumberish} _value - The value to create a FixedNumber for. - * @param {Numeric} [_decimals] - The number of decimal places in `value`. - * @param {FixedFormat} [_format] - The format for the FixedNumber. - * @returns {FixedNumber} The FixedNumber for `value`. - */ - static fromValue(_value, _decimals, _format) { - const decimals = _decimals == null ? 0 : getNumber(_decimals); - const format = getFormat(_format); - let value = getBigInt(_value, 'value'); - const delta = decimals - format.decimals; - if (delta > 0) { - const tens = getTens(delta); - assert(value % tens === BN_0$6, 'value loses precision for format', 'NUMERIC_FAULT', { - operation: 'fromValue', - fault: 'underflow', - value: _value, - }); - value /= tens; - } - else if (delta < 0) { - value *= getTens(-delta); - } - checkValue(value, format, 'fromValue'); - return new FixedNumber(_guard$7, value, format); - } - /** - * Creates a new {@link FixedNumber | **FixedNumber**} for `value` with `format`. - * - * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` cannot fit in `format`, either - * due to overflow or underflow (precision loss). - * - * @param {BigNumberish} _value - The value to create a FixedNumber for. - * @param {FixedFormat} [_format] - The format for the FixedNumber. - * @returns {FixedNumber} The FixedNumber for `value`. - */ - static fromString(_value, _format) { - const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/); - assertArgument(match && match[2].length + match[3].length > 0, 'invalid FixedNumber string value', 'value', _value); - const format = getFormat(_format); - const whole = match[2] || '0'; - let decimal = match[3] || ''; - // Pad out the decimals - while (decimal.length < format.decimals) { - decimal += Zeros; - } - // Check precision is safe - assert(decimal.substring(format.decimals).match(/^0*$/), 'too many decimals for format', 'NUMERIC_FAULT', { - operation: 'fromString', - fault: 'underflow', - value: _value, - }); - // Remove extra padding - decimal = decimal.substring(0, format.decimals); - const value = BigInt(match[1] + whole + decimal); - checkValue(value, format, 'fromString'); - return new FixedNumber(_guard$7, value, format); - } - /** - * Creates a new {@link FixedNumber | **FixedNumber**} with the big-endian representation `value` with `format`. - * - * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` cannot fit in `format` due to - * overflow. - * - * @param {BytesLike} _value - The big-endian representation of the value. - * @param {FixedFormat} [_format] - The format for the FixedNumber. - * @returns {FixedNumber} The FixedNumber for `value`. - */ - static fromBytes(_value, _format) { - let value = toBigInt(getBytes(_value, 'value')); - const format = getFormat(_format); - if (format.signed) { - value = fromTwos(value, format.width); - } - checkValue(value, format, 'fromBytes'); - return new FixedNumber(_guard$7, value, format); - } - } - - /** - * Most interactions with Ethereum requires integer values, which use the smallest magnitude unit. - * - * For example, imagine dealing with dollars and cents. Since dollars are divisible, non-integer values are possible, - * such as `$10.77`. By using the smallest indivisible unit (i.e. cents), the value can be kept as the integer `1077`. - * - * When receiving decimal input from the user (as a decimal string), the value should be converted to an integer and - * when showing a user a value, the integer value should be converted to a decimal string. - * - * This creates a clear distinction, between values to be used by code (integers) and values used for display logic to - * users (decimals). - * - * The native unit in Ethereum, ether is divisible to 18 decimal places, where each individual unit is called a wei. - */ - const names = ['wei', 'kwei', 'mwei', 'gwei', 'szabo', 'finney', 'ether']; - /** - * Converts `value` into a decimal string, assuming `unit` decimal places. The `unit` may be the number of decimal - * places or the name of a unit (e.g. `"gwei"` for 9 decimal places). - * - * @category Utils - * @param {BigNumberish} value - The value to convert. - * @param {string | Numeric} [unit=18] - The unit to convert to. Default is `18` - * @returns {string} The converted value. - * @throws {Error} If the unit is invalid. - */ - function formatUnits(value, unit) { - let decimals = 18; - if (typeof unit === 'string') { - const index = names.indexOf(unit); - assertArgument(index >= 0, 'invalid unit', 'unit', unit); - decimals = 3 * index; - } - else if (unit != null) { - decimals = getNumber(unit, 'unit'); - } - return FixedNumber.fromValue(value, decimals, { decimals, width: 512 }).toString(); - } - /** - * Converts the decimal string `value` to a BigInt, assuming `unit` decimal places. The `unit` may the number of decimal - * places or the name of a unit (e.g. `"gwei"` for 9 decimal places). - * - * @category Utils - * @param {string} value - The value to convert. - * @param {string | Numeric} [unit=18] - The unit to convert from. Default is `18` - * @returns {bigint} The converted value. - * @throws {Error} If the unit is invalid. - * @throws {Error} If the value is not a string. - */ - function parseUnits(value, unit) { - assertArgument(typeof value === 'string', 'value must be a string', 'value', value); - let decimals = 18; - if (typeof unit === 'string') { - const index = names.indexOf(unit); - assertArgument(index >= 0, 'invalid unit', 'unit', unit); - decimals = 3 * index; - } - else if (unit != null) { - decimals = getNumber(unit, 'unit'); - } - return FixedNumber.fromString(value, { decimals, width: 512 }).value; - } - /** - * Converts `value` into a decimal string sing 18 decimal places. - * - * @category Utils - * @param {BigNumberish} wei - The value to convert. - * @returns {string} The converted value. - */ - function formatQuai(wei) { - return formatUnits(wei, 18); - } - /** - * Converts the decimal string `quai` to a BigInt, using 18 decimal places. - * - * @category Utils - * @param {string} ether - The value to convert. - * @returns {bigint} The converted value. - */ - function parseQuai(ether) { - return parseUnits(ether, 18); - } - - /** - * Explain UUID and link to RFC here. - */ - /** - * Returns the version 4 [UUID](https://www.ietf.org/rfc/rfc4122.txt) for the `randomBytes`. - * - * @category Utils - * @param {BytesLike} randomBytes - The random bytes to use. - * - * @returns {string} The UUID. - */ - function uuidV4(randomBytes) { - const bytes = getBytes(randomBytes, 'randomBytes'); - // Section: 4.1.3: - // - time_hi_and_version[12:16] = 0b0100 - bytes[6] = (bytes[6] & 0x0f) | 0x40; - // Section 4.4 - // - clock_seq_hi_and_reserved[6] = 0b0 - // - clock_seq_hi_and_reserved[7] = 0b1 - bytes[8] = (bytes[8] & 0x3f) | 0x80; - const value = hexlify(bytes); - return [ - value.substring(2, 10), - value.substring(10, 14), - value.substring(14, 18), - value.substring(18, 22), - value.substring(22, 34), - ].join('-'); - } - - /** - * A zone is the lowest level shard within the Quai network hierarchy. Zones are the only shards in the network that - * accept user transactions. The value is a hexadecimal string representing the encoded value of the zone. Read more - * [here](https://github.com/quai-network/qips/blob/master/qip-0002.md). - * - * @category Constants - */ - exports.Zone = void 0; - (function (Zone) { - Zone["Cyprus1"] = "0x00"; - Zone["Cyprus2"] = "0x01"; - Zone["Cyprus3"] = "0x02"; - Zone["Paxos1"] = "0x10"; - Zone["Paxos2"] = "0x11"; - Zone["Paxos3"] = "0x12"; - Zone["Hydra1"] = "0x20"; - Zone["Hydra2"] = "0x21"; - Zone["Hydra3"] = "0x22"; - })(exports.Zone || (exports.Zone = {})); - exports.Ledger = void 0; - (function (Ledger) { - Ledger[Ledger["Quai"] = 0] = "Quai"; - Ledger[Ledger["Qi"] = 1] = "Qi"; - })(exports.Ledger || (exports.Ledger = {})); - function zoneFromBytes(zone) { - switch (zone) { - case '0x00': - return exports.Zone.Cyprus1; - case '0x01': - return exports.Zone.Cyprus2; - case '0x02': - return exports.Zone.Cyprus3; - case '0x10': - return exports.Zone.Paxos1; - case '0x11': - return exports.Zone.Paxos2; - case '0x12': - return exports.Zone.Paxos3; - case '0x20': - return exports.Zone.Hydra1; - case '0x21': - return exports.Zone.Hydra2; - case '0x22': - return exports.Zone.Hydra3; - default: - throw new Error(`Invalid zone: ${zone}`); - } - } - const ZoneData = [ - { - name: 'Cyprus One', - nickname: 'cyprus1', - shard: 'zone-0-0', - context: 2, - byte: '0x00', //0000 0000 region-0 zone-0 - }, - { - name: 'Cyprus Two', - nickname: 'cyprus2', - shard: 'zone-0-1', - context: 2, - byte: '0x01', // 0000 0001 region-0 zone-1 - }, - { - name: 'Cyprus Three', - nickname: 'cyprus3', - shard: 'zone-0-2', - context: 2, - byte: '0x02', // 0000 0010 region-0 zone-2 - }, - { - name: 'Paxos One', - nickname: 'paxos1', - shard: 'zone-1-0', - context: 2, - byte: '0x10', // 0001 0000 region-1 zone-0 - }, - { - name: 'Paxos Two', - nickname: 'paxos2', - shard: 'zone-1-1', - context: 2, - byte: '0x11', // 0001 0001 region-1 zone-1 - }, - { - name: 'Paxos Three', - nickname: 'paxos3', - shard: 'zone-1-2', - context: 2, - byte: '0x12', // 0001 0010 region-1 zone-2 - }, - { - name: 'Hydra One', - nickname: 'hydra1', - shard: 'zone-2-0', - context: 2, - byte: '0x20', // 0010 0000 region-2 zone-0 - }, - { - name: 'Hydra Two', - nickname: 'hydra2', - shard: 'zone-2-1', - context: 2, - byte: '0x21', // 0010 0001 region-2 zone-1 - }, - { - name: 'Hydra Three', - nickname: 'hydra3', - shard: 'zone-2-2', - context: 2, - byte: '0x22', // 0010 0010 region-2 zone-2 - }, - ]; - function toZone(shard) { - return zoneFromBytes(ZoneData.find((it) => it.name == shard || it.byte == shard || it.nickname == shard || it.shard == shard) - ?.byte || ''); - } - - function number(n) { - if (!Number.isSafeInteger(n) || n < 0) - throw new Error(`Wrong positive integer: ${n}`); - } - function bytes(b, ...lengths) { - if (!(b instanceof Uint8Array)) - throw new Error('Expected Uint8Array'); - if (lengths.length > 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); - } - function hash(hash) { - if (typeof hash !== 'function' || typeof hash.create !== 'function') - throw new Error('Hash should be wrapped by utils.wrapConstructor'); - number(hash.outputLen); - number(hash.blockLen); - } - function exists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error('Hash instance has been destroyed'); - if (checkFinished && instance.finished) - throw new Error('Hash#digest() has already been called'); - } - function output(out, instance) { - bytes(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); - } - } - - const crypto$1 = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined; - - /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. - // node.js versions earlier than v19 don't declare it in global scope. - // For node.js, package.json#exports field mapping rewrites import - // from `crypto` to `cryptoNode`, which imports native module. - // Makes the utils un-importable in browsers without a bundler. - // Once node.js 18 is deprecated, we can just drop the import. - const u8a$1 = (a) => a instanceof Uint8Array; - const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); - // Cast array to view - const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength); - // The rotate right (circular right shift) operation for uint32 - const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift); - // big-endian hardware is rare. Just in case someone still decides to run hashes: - // early-throw an error because we don't support BE yet. - const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; - if (!isLE) - throw new Error('Non little-endian hardware is not supported'); - // There is no setImmediate in browser and setTimeout is slow. - // call of async fn will return Promise, which will be fullfiled only on - // next scheduler queue processing step and this is exactly what we need. - const nextTick = async () => { }; - // Returns control to thread each 'tick' ms to avoid blocking - async function asyncLoop(iters, tick, cb) { - let ts = Date.now(); - for (let i = 0; i < iters; i++) { - cb(i); - // Date.now() is not monotonic, so in case if clock goes backwards we return return control too - const diff = Date.now() - ts; - if (diff >= 0 && diff < tick) - continue; - await nextTick(); - ts += diff; - } - } - /** - * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) - */ - function utf8ToBytes$1(str) { - if (typeof str !== 'string') - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 - } - /** - * Normalizes (non-hex) string or Uint8Array to Uint8Array. - * Warning: when Uint8Array is passed, it would NOT get copied. - * Keep in mind for future mutable operations. - */ - function toBytes(data) { - if (typeof data === 'string') - data = utf8ToBytes$1(data); - if (!u8a$1(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; - } - /** - * Copies several Uint8Arrays into one. - */ - function concatBytes$1(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; // walk through each item, ensure they have proper type - arrays.forEach((a) => { - if (!u8a$1(a)) - throw new Error('Uint8Array expected'); - r.set(a, pad); - pad += a.length; - }); - return r; - } - // For runtime check if class implements interface - class Hash { - // Safe version that clones internal state - clone() { - return this._cloneInto(); - } - } - const toStr = {}.toString; - function checkOpts(defaults, opts) { - if (opts !== undefined && toStr.call(opts) !== '[object Object]') - throw new Error('Options should be object or undefined'); - const merged = Object.assign(defaults, opts); - return merged; - } - function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; - } - /** - * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS. - */ - function randomBytes$2(bytesLength = 32) { - if (crypto$1 && typeof crypto$1.getRandomValues === 'function') { - return crypto$1.getRandomValues(new Uint8Array(bytesLength)); - } - throw new Error('crypto.getRandomValues must be defined'); - } - - // HMAC (RFC 2104) - class HMAC extends Hash { - constructor(hash$1, _key) { - super(); - this.finished = false; - this.destroyed = false; - hash(hash$1); - const key = toBytes(_key); - this.iHash = hash$1.create(); - if (typeof this.iHash.update !== 'function') - throw new Error('Expected instance of class which extends utils.Hash'); - this.blockLen = this.iHash.blockLen; - this.outputLen = this.iHash.outputLen; - const blockLen = this.blockLen; - const pad = new Uint8Array(blockLen); - // blockLen can be bigger than outputLen - pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key); - for (let i = 0; i < pad.length; i++) - pad[i] ^= 0x36; - this.iHash.update(pad); - // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone - this.oHash = hash$1.create(); - // Undo internal XOR && apply outer XOR - for (let i = 0; i < pad.length; i++) - pad[i] ^= 0x36 ^ 0x5c; - this.oHash.update(pad); - pad.fill(0); - } - update(buf) { - exists(this); - this.iHash.update(buf); - return this; - } - digestInto(out) { - exists(this); - bytes(out, this.outputLen); - this.finished = true; - this.iHash.digestInto(out); - this.oHash.update(out); - this.oHash.digestInto(out); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.oHash.outputLen); - this.digestInto(out); - return out; - } - _cloneInto(to) { - // Create new instance without calling constructor since key already in state and we don't know it. - to || (to = Object.create(Object.getPrototypeOf(this), {})); - const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; - to = to; - to.finished = finished; - to.destroyed = destroyed; - to.blockLen = blockLen; - to.outputLen = outputLen; - to.oHash = oHash._cloneInto(to.oHash); - to.iHash = iHash._cloneInto(to.iHash); - return to; - } - destroy() { - this.destroyed = true; - this.oHash.destroy(); - this.iHash.destroy(); - } - } - /** - * HMAC: RFC2104 message authentication code. - * @param hash - function that would be used e.g. sha256 - * @param key - message key - * @param message - message data - */ - const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest(); - hmac.create = (hash, key) => new HMAC(hash, key); - - // Common prologue and epilogue for sync/async functions - function pbkdf2Init(hash$1, _password, _salt, _opts) { - hash(hash$1); - const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); - const { c, dkLen, asyncTick } = opts; - number(c); - number(dkLen); - number(asyncTick); - if (c < 1) - throw new Error('PBKDF2: iterations (c) should be >= 1'); - const password = toBytes(_password); - const salt = toBytes(_salt); - // DK = PBKDF2(PRF, Password, Salt, c, dkLen); - const DK = new Uint8Array(dkLen); - // U1 = PRF(Password, Salt + INT_32_BE(i)) - const PRF = hmac.create(hash$1, password); - const PRFSalt = PRF._cloneInto().update(salt); - return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; - } - function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { - PRF.destroy(); - PRFSalt.destroy(); - if (prfW) - prfW.destroy(); - u.fill(0); - return DK; - } - /** - * PBKDF2-HMAC: RFC 2898 key derivation function - * @param hash - hash function that would be used e.g. sha256 - * @param password - password from which a derived key is generated - * @param salt - cryptographic salt - * @param opts - {c, dkLen} where c is work factor and dkLen is output message size - */ - function pbkdf2$1(hash, password, salt, opts) { - const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); - let prfW; // Working copy - const arr = new Uint8Array(4); - const view = createView(arr); - const u = new Uint8Array(PRF.outputLen); - // DK = T1 + T2 + ⋯ + Tdklen/hlen - for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { - // Ti = F(Password, Salt, c, i) - const Ti = DK.subarray(pos, pos + PRF.outputLen); - view.setInt32(0, ti, false); - // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc - // U1 = PRF(Password, Salt + INT_32_BE(i)) - (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); - Ti.set(u.subarray(0, Ti.length)); - for (let ui = 1; ui < c; ui++) { - // Uc = PRF(Password, Uc−1) - PRF._cloneInto(prfW).update(u).digestInto(u); - for (let i = 0; i < Ti.length; i++) - Ti[i] ^= u[i]; - } - } - return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); - } - - // Polyfill for Safari 14 - function setBigUint64(view, byteOffset, value, isLE) { - if (typeof view.setBigUint64 === 'function') - return view.setBigUint64(byteOffset, value, isLE); - const _32n = BigInt(32); - const _u32_max = BigInt(0xffffffff); - const wh = Number((value >> _32n) & _u32_max); - const wl = Number(value & _u32_max); - const h = isLE ? 4 : 0; - const l = isLE ? 0 : 4; - view.setUint32(byteOffset + h, wh, isLE); - view.setUint32(byteOffset + l, wl, isLE); - } - // Base SHA2 class (RFC 6234) - class SHA2 extends Hash { - constructor(blockLen, outputLen, padOffset, isLE) { - super(); - this.blockLen = blockLen; - this.outputLen = outputLen; - this.padOffset = padOffset; - this.isLE = isLE; - this.finished = false; - this.length = 0; - this.pos = 0; - this.destroyed = false; - this.buffer = new Uint8Array(blockLen); - this.view = createView(this.buffer); - } - update(data) { - exists(this); - const { view, buffer, blockLen } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len;) { - const take = Math.min(blockLen - this.pos, len - pos); - // Fast path: we have at least one block in input, cast it to view and process - if (take === blockLen) { - const dataView = createView(data); - for (; blockLen <= len - pos; pos += blockLen) - this.process(dataView, pos); - continue; - } - buffer.set(data.subarray(pos, pos + take), this.pos); - this.pos += take; - pos += take; - if (this.pos === blockLen) { - this.process(view, 0); - this.pos = 0; - } - } - this.length += data.length; - this.roundClean(); - return this; - } - digestInto(out) { - exists(this); - output(out, this); - this.finished = true; - // Padding - // We can avoid allocation of buffer for padding completely if it - // was previously not allocated here. But it won't change performance. - const { buffer, view, blockLen, isLE } = this; - let { pos } = this; - // append the bit '1' to the message - buffer[pos++] = 0b10000000; - this.buffer.subarray(pos).fill(0); - // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again - if (this.padOffset > blockLen - pos) { - this.process(view, 0); - pos = 0; - } - // Pad until full block byte with zeros - for (let i = pos; i < blockLen; i++) - buffer[i] = 0; - // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that - // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen. - // So we just write lowest 64 bits of that value. - setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); - this.process(view, 0); - const oview = createView(out); - const len = this.outputLen; - // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT - if (len % 4) - throw new Error('_sha2: outputLen should be aligned to 32bit'); - const outLen = len / 4; - const state = this.get(); - if (outLen > state.length) - throw new Error('_sha2: outputLen bigger than state'); - for (let i = 0; i < outLen; i++) - oview.setUint32(4 * i, state[i], isLE); - } - digest() { - const { buffer, outputLen } = this; - this.digestInto(buffer); - const res = buffer.slice(0, outputLen); - this.destroy(); - return res; - } - _cloneInto(to) { - to || (to = new this.constructor()); - to.set(...this.get()); - const { blockLen, buffer, length, finished, destroyed, pos } = this; - to.length = length; - to.pos = pos; - to.finished = finished; - to.destroyed = destroyed; - if (length % blockLen) - to.buffer.set(buffer); - return to; - } - } - - // SHA2-256 need to try 2^128 hashes to execute birthday attack. - // BTC network is doing 2^67 hashes/sec as per early 2023. - // Choice: a ? b : c - const Chi = (a, b, c) => (a & b) ^ (~a & c); - // Majority function, true if any two inpust is true - const Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c); - // Round constants: - // first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) - // prettier-ignore - const SHA256_K = /* @__PURE__ */ new Uint32Array([ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 - ]); - // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): - // prettier-ignore - const IV = /* @__PURE__ */ new Uint32Array([ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]); - // Temporary buffer, not used to store anything between runs - // Named this way because it matches specification. - const SHA256_W = /* @__PURE__ */ new Uint32Array(64); - class SHA256 extends SHA2 { - constructor() { - super(64, 32, 8, false); - // We cannot use array here since array allows indexing by variable - // which means optimizer/compiler cannot use registers. - this.A = IV[0] | 0; - this.B = IV[1] | 0; - this.C = IV[2] | 0; - this.D = IV[3] | 0; - this.E = IV[4] | 0; - this.F = IV[5] | 0; - this.G = IV[6] | 0; - this.H = IV[7] | 0; - } - get() { - const { A, B, C, D, E, F, G, H } = this; - return [A, B, C, D, E, F, G, H]; - } - // prettier-ignore - set(A, B, C, D, E, F, G, H) { - this.A = A | 0; - this.B = B | 0; - this.C = C | 0; - this.D = D | 0; - this.E = E | 0; - this.F = F | 0; - this.G = G | 0; - this.H = H | 0; - } - process(view, offset) { - // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array - for (let i = 0; i < 16; i++, offset += 4) - SHA256_W[i] = view.getUint32(offset, false); - for (let i = 16; i < 64; i++) { - const W15 = SHA256_W[i - 15]; - const W2 = SHA256_W[i - 2]; - const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); - const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); - SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; - } - // Compression function main loop, 64 rounds - let { A, B, C, D, E, F, G, H } = this; - for (let i = 0; i < 64; i++) { - const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); - const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; - const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); - const T2 = (sigma0 + Maj(A, B, C)) | 0; - H = G; - G = F; - F = E; - E = (D + T1) | 0; - D = C; - C = B; - B = A; - A = (T1 + T2) | 0; - } - // Add the compressed chunk to the current hash value - A = (A + this.A) | 0; - B = (B + this.B) | 0; - C = (C + this.C) | 0; - D = (D + this.D) | 0; - E = (E + this.E) | 0; - F = (F + this.F) | 0; - G = (G + this.G) | 0; - H = (H + this.H) | 0; - this.set(A, B, C, D, E, F, G, H); - } - roundClean() { - SHA256_W.fill(0); - } - destroy() { - this.set(0, 0, 0, 0, 0, 0, 0, 0); - this.buffer.fill(0); - } - } - /** - * SHA2-256 hash function - * @param message - data that would be hashed - */ - const sha256$1 = /* @__PURE__ */ wrapConstructor(() => new SHA256()); - - const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); - const _32n = /* @__PURE__ */ BigInt(32); - // We are not using BigUint64Array, because they are extremely slow as per 2022 - function fromBig(n, le = false) { - if (le) - return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; - return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; - } - function split(lst, le = false) { - let Ah = new Uint32Array(lst.length); - let Al = new Uint32Array(lst.length); - for (let i = 0; i < lst.length; i++) { - const { h, l } = fromBig(lst[i], le); - [Ah[i], Al[i]] = [h, l]; - } - return [Ah, Al]; - } - const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); - // for Shift in [0, 32) - const shrSH = (h, _l, s) => h >>> s; - const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); - // Right rotate for Shift in [1, 32) - const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); - const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); - // Right rotate for Shift in (32, 64), NOTE: 32 is special case. - const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); - const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); - // Right rotate for shift===32 (just swaps l&h) - const rotr32H = (_h, l) => l; - const rotr32L = (h, _l) => h; - // Left rotate for Shift in [1, 32) - const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); - const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); - // Left rotate for Shift in (32, 64), NOTE: 32 is special case. - const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); - const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); - // JS uses 32-bit signed integers for bitwise operations which means we cannot - // simple take carry out of low bit sum by shift, we need to use division. - function add(Ah, Al, Bh, Bl) { - const l = (Al >>> 0) + (Bl >>> 0); - return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; - } - // Addition with more than 2 elements - const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); - const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; - const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); - const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; - const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); - const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; - // prettier-ignore - const u64 = { - fromBig, split, toBig, - shrSH, shrSL, - rotrSH, rotrSL, rotrBH, rotrBL, - rotr32H, rotr32L, - rotlSH, rotlSL, rotlBH, rotlBL, - add, add3L, add3H, add4L, add4H, add5H, add5L, - }; - - // Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409): - // prettier-ignore - const [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([ - '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', - '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', - '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', - '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', - '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', - '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', - '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', - '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', - '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', - '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', - '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', - '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', - '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', - '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', - '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', - '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', - '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', - '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', - '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', - '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' - ].map(n => BigInt(n))))(); - // Temporary buffer, not used to store anything between runs - const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); - const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); - class SHA512 extends SHA2 { - constructor() { - super(128, 64, 16, false); - // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers. - // Also looks cleaner and easier to verify with spec. - // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19): - // h -- high 32 bits, l -- low 32 bits - this.Ah = 0x6a09e667 | 0; - this.Al = 0xf3bcc908 | 0; - this.Bh = 0xbb67ae85 | 0; - this.Bl = 0x84caa73b | 0; - this.Ch = 0x3c6ef372 | 0; - this.Cl = 0xfe94f82b | 0; - this.Dh = 0xa54ff53a | 0; - this.Dl = 0x5f1d36f1 | 0; - this.Eh = 0x510e527f | 0; - this.El = 0xade682d1 | 0; - this.Fh = 0x9b05688c | 0; - this.Fl = 0x2b3e6c1f | 0; - this.Gh = 0x1f83d9ab | 0; - this.Gl = 0xfb41bd6b | 0; - this.Hh = 0x5be0cd19 | 0; - this.Hl = 0x137e2179 | 0; - } - // prettier-ignore - get() { - const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; - } - // prettier-ignore - set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { - this.Ah = Ah | 0; - this.Al = Al | 0; - this.Bh = Bh | 0; - this.Bl = Bl | 0; - this.Ch = Ch | 0; - this.Cl = Cl | 0; - this.Dh = Dh | 0; - this.Dl = Dl | 0; - this.Eh = Eh | 0; - this.El = El | 0; - this.Fh = Fh | 0; - this.Fl = Fl | 0; - this.Gh = Gh | 0; - this.Gl = Gl | 0; - this.Hh = Hh | 0; - this.Hl = Hl | 0; - } - process(view, offset) { - // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array - for (let i = 0; i < 16; i++, offset += 4) { - SHA512_W_H[i] = view.getUint32(offset); - SHA512_W_L[i] = view.getUint32((offset += 4)); - } - for (let i = 16; i < 80; i++) { - // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) - const W15h = SHA512_W_H[i - 15] | 0; - const W15l = SHA512_W_L[i - 15] | 0; - const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); - const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); - // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) - const W2h = SHA512_W_H[i - 2] | 0; - const W2l = SHA512_W_L[i - 2] | 0; - const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); - const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); - // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16]; - const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); - const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); - SHA512_W_H[i] = SUMh | 0; - SHA512_W_L[i] = SUMl | 0; - } - let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; - // Compression function main loop, 80 rounds - for (let i = 0; i < 80; i++) { - // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) - const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); - const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); - //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; - const CHIh = (Eh & Fh) ^ (~Eh & Gh); - const CHIl = (El & Fl) ^ (~El & Gl); - // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] - // prettier-ignore - const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); - const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); - const T1l = T1ll | 0; - // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) - const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); - const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); - const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); - const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); - Hh = Gh | 0; - Hl = Gl | 0; - Gh = Fh | 0; - Gl = Fl | 0; - Fh = Eh | 0; - Fl = El | 0; - ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); - Dh = Ch | 0; - Dl = Cl | 0; - Ch = Bh | 0; - Cl = Bl | 0; - Bh = Ah | 0; - Bl = Al | 0; - const All = u64.add3L(T1l, sigma0l, MAJl); - Ah = u64.add3H(All, T1h, sigma0h, MAJh); - Al = All | 0; - } - // Add the compressed chunk to the current hash value - ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); - ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); - ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); - ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); - ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); - ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); - ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); - ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); - this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); - } - roundClean() { - SHA512_W_H.fill(0); - SHA512_W_L.fill(0); - } - destroy() { - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); - } - } - const sha512$1 = /* @__PURE__ */ wrapConstructor(() => new SHA512()); - - /* Browser Crypto Shims */ - function getGlobal$1() { - if (typeof self !== 'undefined') { - return self; - } - if (typeof window !== 'undefined') { - return window; - } - if (typeof global !== 'undefined') { - return global; - } - throw new Error('unable to locate global object'); - } - const anyGlobal = getGlobal$1(); - const crypto = anyGlobal.crypto || anyGlobal.msCrypto; - function createHash(algo) { - switch (algo) { - case 'sha256': - return sha256$1.create(); - case 'sha512': - return sha512$1.create(); - } - assertArgument(false, 'invalid hashing algorithm name', 'algorithm', algo); - } - function createHmac(_algo, key) { - const algo = { sha256: sha256$1, sha512: sha512$1 }[_algo]; - assertArgument(algo != null, 'invalid hmac algorithm', 'algorithm', _algo); - return hmac.create(algo, key); - } - function pbkdf2Sync(password, salt, iterations, keylen, _algo) { - const algo = { sha256: sha256$1, sha512: sha512$1 }[_algo]; - assertArgument(algo != null, 'invalid pbkdf2 algorithm', 'algorithm', _algo); - return pbkdf2$1(algo, password, salt, { c: iterations, dkLen: keylen }); - } - function randomBytes$1(length) { - assert(crypto != null, 'platform does not support secure random numbers', 'UNSUPPORTED_OPERATION', { - operation: 'randomBytes', - }); - assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, 'invalid length', 'length', length); - const result = new Uint8Array(length); - crypto.getRandomValues(result); - return result; - } - - /** - * An **HMAC** enables verification that a given key was used to authenticate a payload. - * - * @see {@link https://en.wikipedia.org/wiki/HMAC | HMAC - Wikipedia} - */ - let locked$4 = false; - const _computeHmac = function (algorithm, key, data) { - return createHmac(algorithm, key).update(data).digest(); - }; - let __computeHmac = _computeHmac; - /** - * Return the HMAC for `data` using the `key` key with the underlying `algo` used for compression. - * - * @category Crypto - * @example - * - * ```js - * key = id('some-secret'); - * - * // Compute the HMAC - * computeHmac('sha256', key, '0x1337'); - * - * // To compute the HMAC of UTF-8 data, the data must be - * // converted to UTF-8 bytes - * computeHmac('sha256', key, toUtf8Bytes('Hello World')); - * ``` - * - * @param {'sha256' | 'sha512'} algorithm - The algorithm to use for compression. - * @param {BytesLike} _key - The key to use for the HMAC. - * @param {BytesLike} _data - The data to authenticate. - * @returns {string} The HMAC of the data. - */ - function computeHmac(algorithm, _key, _data) { - const key = getBytes(_key, 'key'); - const data = getBytes(_data, 'data'); - return hexlify(__computeHmac(algorithm, key, data)); - } - computeHmac._ = _computeHmac; - computeHmac.lock = function () { - locked$4 = true; - }; - computeHmac.register = function (func) { - if (locked$4) { - throw new Error('computeHmac is locked'); - } - __computeHmac = func; - }; - Object.freeze(computeHmac); - - // SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. - // It's called a sponge function. - // Various per round constants calculations - const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; - const _0n$6 = /* @__PURE__ */ BigInt(0); - const _1n$6 = /* @__PURE__ */ BigInt(1); - const _2n$4 = /* @__PURE__ */ BigInt(2); - const _7n$1 = /* @__PURE__ */ BigInt(7); - const _256n = /* @__PURE__ */ BigInt(256); - const _0x71n = /* @__PURE__ */ BigInt(0x71); - for (let round = 0, R = _1n$6, x = 1, y = 0; round < 24; round++) { - // Pi - [x, y] = [y, (2 * x + 3 * y) % 5]; - SHA3_PI.push(2 * (5 * y + x)); - // Rotational - SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); - // Iota - let t = _0n$6; - for (let j = 0; j < 7; j++) { - R = ((R << _1n$6) ^ ((R >> _7n$1) * _0x71n)) % _256n; - if (R & _2n$4) - t ^= _1n$6 << ((_1n$6 << /* @__PURE__ */ BigInt(j)) - _1n$6); - } - _SHA3_IOTA.push(t); - } - const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); - // Left rotation (without 0, 32, 64) - const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); - const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); - // Same as keccakf1600, but allows to skip some rounds - function keccakP(s, rounds = 24) { - const B = new Uint32Array(5 * 2); - // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) - for (let round = 24 - rounds; round < 24; round++) { - // Theta θ - for (let x = 0; x < 10; x++) - B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; - for (let x = 0; x < 10; x += 2) { - const idx1 = (x + 8) % 10; - const idx0 = (x + 2) % 10; - const B0 = B[idx0]; - const B1 = B[idx0 + 1]; - const Th = rotlH(B0, B1, 1) ^ B[idx1]; - const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; - for (let y = 0; y < 50; y += 10) { - s[x + y] ^= Th; - s[x + y + 1] ^= Tl; - } - } - // Rho (ρ) and Pi (π) - let curH = s[2]; - let curL = s[3]; - for (let t = 0; t < 24; t++) { - const shift = SHA3_ROTL[t]; - const Th = rotlH(curH, curL, shift); - const Tl = rotlL(curH, curL, shift); - const PI = SHA3_PI[t]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = Th; - s[PI + 1] = Tl; - } - // Chi (χ) - for (let y = 0; y < 50; y += 10) { - for (let x = 0; x < 10; x++) - B[x] = s[y + x]; - for (let x = 0; x < 10; x++) - s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; - } - // Iota (ι) - s[0] ^= SHA3_IOTA_H[round]; - s[1] ^= SHA3_IOTA_L[round]; - } - B.fill(0); - } - class Keccak extends Hash { - // NOTE: we accept arguments in bytes instead of bits here. - constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { - super(); - this.blockLen = blockLen; - this.suffix = suffix; - this.outputLen = outputLen; - this.enableXOF = enableXOF; - this.rounds = rounds; - this.pos = 0; - this.posOut = 0; - this.finished = false; - this.destroyed = false; - // Can be passed from user as dkLen - number(outputLen); - // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes - if (0 >= this.blockLen || this.blockLen >= 200) - throw new Error('Sha3 supports only keccak-f1600 function'); - this.state = new Uint8Array(200); - this.state32 = u32(this.state); - } - keccak() { - keccakP(this.state32, this.rounds); - this.posOut = 0; - this.pos = 0; - } - update(data) { - exists(this); - const { blockLen, state } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len;) { - const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0; i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); - } - return this; - } - finish() { - if (this.finished) - return; - this.finished = true; - const { state, suffix, pos, blockLen } = this; - // Do the padding - state[pos] ^= suffix; - if ((suffix & 0x80) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 0x80; - this.keccak(); - } - writeInto(out) { - exists(this, false); - bytes(out); - this.finish(); - const bufferOut = this.state; - const { blockLen } = this; - for (let pos = 0, len = out.length; pos < len;) { - if (this.posOut >= blockLen) - this.keccak(); - const take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; - } - return out; - } - xofInto(out) { - // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF - if (!this.enableXOF) - throw new Error('XOF is not possible for this instance'); - return this.writeInto(out); - } - xof(bytes) { - number(bytes); - return this.xofInto(new Uint8Array(bytes)); - } - digestInto(out) { - output(out, this); - if (this.finished) - throw new Error('digest() was already called'); - this.writeInto(out); - this.destroy(); - return out; - } - digest() { - return this.digestInto(new Uint8Array(this.outputLen)); - } - destroy() { - this.destroyed = true; - this.state.fill(0); - } - _cloneInto(to) { - const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); - to.state32.set(this.state32); - to.pos = this.pos; - to.posOut = this.posOut; - to.finished = this.finished; - to.rounds = rounds; - // Suffix can change in cSHAKE - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.destroyed = this.destroyed; - return to; - } - } - const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); - /** - * keccak-256 hash function. Different from SHA3-256. - * @param message - that would be hashed - */ - const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); - - /** - * Cryptographic hashing functions - */ - let locked$3 = false; - const _keccak256 = function (data) { - return keccak_256(data); - }; - let __keccak256 = _keccak256; - /** - * Compute the cryptographic KECCAK256 hash of `data`. - * - * The `data` **must** be a data representation, to compute the hash of UTF-8 data use the [**id**}(../functions/id) - * function. - * - * @category Crypto - * @example - * - * ```ts - * keccak256('0x'); - * - * keccak256('0x1337'); - * - * keccak256(new Uint8Array([0x13, 0x37])); - * - * // Strings are assumed to be DataHexString, otherwise it will - * // throw. To hash UTF-8 data, see the note above. - * keccak256('Hello World'); - * ``` - * - * @param {BytesLike} _data - The data to hash. - * @returns DataHexstring - * @returns {string} The hash of the data. - */ - function keccak256(_data) { - const data = getBytes(_data, 'data'); - return hexlify(__keccak256(data)); - } - keccak256._ = _keccak256; - keccak256.lock = function () { - locked$3 = true; - }; - keccak256.register = function (func) { - if (locked$3) { - throw new TypeError('keccak256 is locked'); - } - __keccak256 = func; - }; - Object.freeze(keccak256); - - // https://homes.esat.kuleuven.be/~bosselae/ripemd160.html - // https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf - const Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]); - const Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i); - const Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16); - let idxL = [Id]; - let idxR = [Pi]; - for (let i = 0; i < 4; i++) - for (let j of [idxL, idxR]) - j.push(j[i].map((k) => Rho[k])); - const shifts = /* @__PURE__ */ [ - [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], - [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], - [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], - [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], - [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], - ].map((i) => new Uint8Array(i)); - const shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j])); - const shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j])); - const Kl = /* @__PURE__ */ new Uint32Array([ - 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, - ]); - const Kr = /* @__PURE__ */ new Uint32Array([ - 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, - ]); - // The rotate left (circular left shift) operation for uint32 - const rotl$1 = (word, shift) => (word << shift) | (word >>> (32 - shift)); - // It's called f() in spec. - function f(group, x, y, z) { - if (group === 0) - return x ^ y ^ z; - else if (group === 1) - return (x & y) | (~x & z); - else if (group === 2) - return (x | ~y) ^ z; - else if (group === 3) - return (x & z) | (y & ~z); - else - return x ^ (y | ~z); - } - // Temporary buffer, not used to store anything between runs - const BUF = /* @__PURE__ */ new Uint32Array(16); - class RIPEMD160 extends SHA2 { - constructor() { - super(64, 20, 8, true); - this.h0 = 0x67452301 | 0; - this.h1 = 0xefcdab89 | 0; - this.h2 = 0x98badcfe | 0; - this.h3 = 0x10325476 | 0; - this.h4 = 0xc3d2e1f0 | 0; - } - get() { - const { h0, h1, h2, h3, h4 } = this; - return [h0, h1, h2, h3, h4]; - } - set(h0, h1, h2, h3, h4) { - this.h0 = h0 | 0; - this.h1 = h1 | 0; - this.h2 = h2 | 0; - this.h3 = h3 | 0; - this.h4 = h4 | 0; - } - process(view, offset) { - for (let i = 0; i < 16; i++, offset += 4) - BUF[i] = view.getUint32(offset, true); - // prettier-ignore - let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; - // Instead of iterating 0 to 80, we split it into 5 groups - // And use the groups in constants, functions, etc. Much simpler - for (let group = 0; group < 5; group++) { - const rGroup = 4 - group; - const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore - const rl = idxL[group], rr = idxR[group]; // prettier-ignore - const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore - for (let i = 0; i < 16; i++) { - const tl = (rotl$1(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0; - al = el, el = dl, dl = rotl$1(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore - } - // 2 loops are 10% faster - for (let i = 0; i < 16; i++) { - const tr = (rotl$1(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0; - ar = er, er = dr, dr = rotl$1(cr, 10) | 0, cr = br, br = tr; // prettier-ignore - } - } - // Add the compressed chunk to the current hash value - this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); - } - roundClean() { - BUF.fill(0); - } - destroy() { - this.destroyed = true; - this.buffer.fill(0); - this.set(0, 0, 0, 0, 0); - } - } - /** - * RIPEMD-160 - a hash function from 1990s. - * @param message - msg that would be hashed - */ - const ripemd160$1 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160()); - - let locked$2 = false; - const _ripemd160 = function (data) { - return ripemd160$1(data); - }; - let __ripemd160 = _ripemd160; - /** - * Compute the cryptographic RIPEMD-160 hash of `data`. - * - * @category Crypto - * @example - * - * ```ts - * ripemd160('0x'); - * - * ripemd160('0x1337'); - * - * ripemd160(new Uint8Array([0x13, 0x37])); - * ``` - * - * @param {BytesLike} _data - The data to hash. - * @returns DataHexstring - * @returns {string} The hash of the data. - */ - function ripemd160(_data) { - const data = getBytes(_data, 'data'); - return hexlify(__ripemd160(data)); - } - ripemd160._ = _ripemd160; - ripemd160.lock = function () { - locked$2 = true; - }; - ripemd160.register = function (func) { - if (locked$2) { - throw new TypeError('ripemd160 is locked'); - } - __ripemd160 = func; - }; - Object.freeze(ripemd160); - - /** - * A **Password-Based Key-Derivation Function** is designed to create a sequence of bytes suitible as a **key** from a - * human-rememberable password. - */ - let locked$1 = false; - const _pbkdf2 = function (password, salt, iterations, keylen, algo) { - return pbkdf2Sync(password, salt, iterations, keylen, algo); - }; - let __pbkdf2 = _pbkdf2; - /** - * Return the [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) for `keylen` bytes for `password` using the `salt` and - * using `iterations` of `algo`. - * - * This PBKDF is outdated and should not be used in new projects, but is required to decrypt older files. - * - * @category Crypto - * @example - * - * ```ts - * // The password must be converted to bytes, and it is generally - * // best practices to ensure the string has been normalized. Many - * // formats explicitly indicate the normalization form to use. - * password = 'hello'; - * passwordBytes = toUtf8Bytes(password, 'NFKC'); - * - * salt = id('some-salt'); - * - * // Compute the PBKDF2 - * pbkdf2(passwordBytes, salt, 1024, 16, 'sha256'); - * ``` - * - * @param {BytesLike} _password - The password to use. - * @param {BytesLike} _salt - The salt to use. - * @param {number} iterations - The number of iterations to use. - * @param {number} keylen - The length of the key to generate. - * @param {'sha256' | 'sha512'} algo - The algorithm to use. - * @returns {string} The key derived from the password. - */ - function pbkdf2(_password, _salt, iterations, keylen, algo) { - const password = getBytes(_password, 'password'); - const salt = getBytes(_salt, 'salt'); - return hexlify(__pbkdf2(password, salt, iterations, keylen, algo)); - } - pbkdf2._ = _pbkdf2; - pbkdf2.lock = function () { - locked$1 = true; - }; - pbkdf2.register = function (func) { - if (locked$1) { - throw new Error('pbkdf2 is locked'); - } - __pbkdf2 = func; - }; - Object.freeze(pbkdf2); - - /** - * A **Cryptographically Secure Random Value** is one that has been generated with additional care take to prevent - * side-channels from allowing others to detect it and prevent others from through coincidence generate the same - * values. - */ - let locked = false; - const _randomBytes = function (length) { - return new Uint8Array(randomBytes$1(length)); - }; - let __randomBytes = _randomBytes; - /** - * Return `length` bytes of cryptographically secure random data. - * - * @category Crypto - * @example - * - * ```ts - * randomBytes(8); - * ``` - * - * @param {number} length - The number of bytes to generate. - * @returns {Uint8Array} The random bytes. - */ - function randomBytes(length) { - return __randomBytes(length); - } - randomBytes._ = _randomBytes; - randomBytes.lock = function () { - locked = true; - }; - randomBytes.register = function (func) { - if (locked) { - throw new Error('randomBytes is locked'); - } - __randomBytes = func; - }; - Object.freeze(randomBytes); - - // RFC 7914 Scrypt KDF - // Left rotate for uint32 - const rotl = (a, b) => (a << b) | (a >>> (32 - b)); - // The main Scrypt loop: uses Salsa extensively. - // Six versions of the function were tried, this is the fastest one. - // prettier-ignore - function XorAndSalsa(prev, pi, input, ii, out, oi) { - // Based on https://cr.yp.to/salsa20.html - // Xor blocks - let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; - let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; - let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; - let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; - let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; - let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; - let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; - let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; - // Save state to temporary variables (salsa) - let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; - // Main loop (salsa) - for (let i = 0; i < 8; i += 2) { - x04 ^= rotl(x00 + x12 | 0, 7); - x08 ^= rotl(x04 + x00 | 0, 9); - x12 ^= rotl(x08 + x04 | 0, 13); - x00 ^= rotl(x12 + x08 | 0, 18); - x09 ^= rotl(x05 + x01 | 0, 7); - x13 ^= rotl(x09 + x05 | 0, 9); - x01 ^= rotl(x13 + x09 | 0, 13); - x05 ^= rotl(x01 + x13 | 0, 18); - x14 ^= rotl(x10 + x06 | 0, 7); - x02 ^= rotl(x14 + x10 | 0, 9); - x06 ^= rotl(x02 + x14 | 0, 13); - x10 ^= rotl(x06 + x02 | 0, 18); - x03 ^= rotl(x15 + x11 | 0, 7); - x07 ^= rotl(x03 + x15 | 0, 9); - x11 ^= rotl(x07 + x03 | 0, 13); - x15 ^= rotl(x11 + x07 | 0, 18); - x01 ^= rotl(x00 + x03 | 0, 7); - x02 ^= rotl(x01 + x00 | 0, 9); - x03 ^= rotl(x02 + x01 | 0, 13); - x00 ^= rotl(x03 + x02 | 0, 18); - x06 ^= rotl(x05 + x04 | 0, 7); - x07 ^= rotl(x06 + x05 | 0, 9); - x04 ^= rotl(x07 + x06 | 0, 13); - x05 ^= rotl(x04 + x07 | 0, 18); - x11 ^= rotl(x10 + x09 | 0, 7); - x08 ^= rotl(x11 + x10 | 0, 9); - x09 ^= rotl(x08 + x11 | 0, 13); - x10 ^= rotl(x09 + x08 | 0, 18); - x12 ^= rotl(x15 + x14 | 0, 7); - x13 ^= rotl(x12 + x15 | 0, 9); - x14 ^= rotl(x13 + x12 | 0, 13); - x15 ^= rotl(x14 + x13 | 0, 18); - } - // Write output (salsa) - out[oi++] = (y00 + x00) | 0; - out[oi++] = (y01 + x01) | 0; - out[oi++] = (y02 + x02) | 0; - out[oi++] = (y03 + x03) | 0; - out[oi++] = (y04 + x04) | 0; - out[oi++] = (y05 + x05) | 0; - out[oi++] = (y06 + x06) | 0; - out[oi++] = (y07 + x07) | 0; - out[oi++] = (y08 + x08) | 0; - out[oi++] = (y09 + x09) | 0; - out[oi++] = (y10 + x10) | 0; - out[oi++] = (y11 + x11) | 0; - out[oi++] = (y12 + x12) | 0; - out[oi++] = (y13 + x13) | 0; - out[oi++] = (y14 + x14) | 0; - out[oi++] = (y15 + x15) | 0; - } - function BlockMix(input, ii, out, oi, r) { - // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks) - let head = oi + 0; - let tail = oi + 16 * r; - for (let i = 0; i < 16; i++) - out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] - for (let i = 0; i < r; i++, head += 16, ii += 16) { - // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1 - XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) - if (i > 0) - tail += 16; // First iteration overwrites tmp value in tail - XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) - } - } - // Common prologue and epilogue for sync/async functions - function scryptInit(password, salt, _opts) { - // Maxmem - 1GB+1KB by default - const opts = checkOpts({ - dkLen: 32, - asyncTick: 10, - maxmem: 1024 ** 3 + 1024, - }, _opts); - const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; - number(N); - number(r); - number(p); - number(dkLen); - number(asyncTick); - number(maxmem); - if (onProgress !== undefined && typeof onProgress !== 'function') - throw new Error('progressCb should be function'); - const blockSize = 128 * r; - const blockSize32 = blockSize / 4; - if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { - // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function - // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future. - throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'); - } - if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) { - throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'); - } - if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { - throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'); - } - const memUsed = blockSize * (N + p); - if (memUsed > maxmem) { - throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); - } - // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) - // Since it has only one iteration there is no reason to use async variant - const B = pbkdf2$1(sha256$1, password, salt, { c: 1, dkLen: blockSize * p }); - const B32 = u32(B); - // Re-used between parallel iterations. Array(iterations) of B - const V = u32(new Uint8Array(blockSize * N)); - const tmp = u32(new Uint8Array(blockSize)); - let blockMixCb = () => { }; - if (onProgress) { - const totalBlockMix = 2 * N * p; - // Invoke callback if progress changes from 10.01 to 10.02 - // Allows to draw smooth progress bar on up to 8K screen - const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); - let blockMixCnt = 0; - blockMixCb = () => { - blockMixCnt++; - if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) - onProgress(blockMixCnt / totalBlockMix); - }; - } - return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; - } - function scryptOutput(password, dkLen, B, V, tmp) { - const res = pbkdf2$1(sha256$1, password, B, { c: 1, dkLen }); - B.fill(0); - V.fill(0); - tmp.fill(0); - return res; - } - /** - * Scrypt KDF from RFC 7914. - * @param password - pass - * @param salt - salt - * @param opts - parameters - * - `N` is cpu/mem work factor (power of 2 e.g. 2**18) - * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance - * - `p` is parallelization factor (1 is common) - * - `dkLen` is output key length in bytes e.g. 32. - * - `asyncTick` - (default: 10) max time in ms for which async function can block execution - * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt - * - `onProgress` - callback function that would be executed for progress report - * @returns Derived key - */ - function scrypt$1(password, salt, opts) { - const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); - for (let pi = 0; pi < p; pi++) { - const Pi = blockSize32 * pi; - for (let i = 0; i < blockSize32; i++) - V[i] = B32[Pi + i]; // V[0] = B[i] - for (let i = 0, pos = 0; i < N - 1; i++) { - BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); - blockMixCb(); - } - BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element - blockMixCb(); - for (let i = 0; i < N; i++) { - // First u32 of the last 64-byte block (u32 is LE) - const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations - for (let k = 0; k < blockSize32; k++) - tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] - BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) - blockMixCb(); - } - } - return scryptOutput(password, dkLen, B, V, tmp); - } - /** - * Scrypt KDF from RFC 7914. - */ - async function scryptAsync(password, salt, opts) { - const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); - for (let pi = 0; pi < p; pi++) { - const Pi = blockSize32 * pi; - for (let i = 0; i < blockSize32; i++) - V[i] = B32[Pi + i]; // V[0] = B[i] - let pos = 0; - await asyncLoop(N - 1, asyncTick, () => { - BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); - blockMixCb(); - }); - BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element - blockMixCb(); - await asyncLoop(N, asyncTick, () => { - // First u32 of the last 64-byte block (u32 is LE) - const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations - for (let k = 0; k < blockSize32; k++) - tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j] - BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) - blockMixCb(); - }); - } - return scryptOutput(password, dkLen, B, V, tmp); - } - - let lockedSync = false, lockedAsync = false; - const _scryptAsync = async function (passwd, salt, N, r, p, dkLen, onProgress) { - return await scryptAsync(passwd, salt, { N, r, p, dkLen, onProgress }); - }; - const _scryptSync = function (passwd, salt, N, r, p, dkLen) { - return scrypt$1(passwd, salt, { N, r, p, dkLen }); - }; - let __scryptAsync = _scryptAsync; - let __scryptSync = _scryptSync; - /** - * The [scrypt PBKDF](https://en.wikipedia.org/wiki/Scrypt) uses a memory and cpu hard method of derivation to increase - * the resource cost to brute-force a password for a given key. - * - * This means this algorithm is intentionally slow, and can be tuned to become slower. As computation and memory speed - * improve over time, increasing the difficulty maintains the cost of an attacker. - * - * For example, if a target time of 5 seconds is used, a legitimate user which knows their password requires only 5 - * seconds to unlock their account. A 6 character password has 68 billion possibilities, which would require an attacker - * to invest over 10,000 years of CPU time. This is of course a crude example (as password generally aren't random), but - * demonstrates to value of imposing large costs to decryption. - * - * For this reason, if building a UI which involved decrypting or encrypting datsa using scrypt, it is recommended to - * use a [**ProgressCallback**](../types-aliases/ProgressCallback) (as event short periods can seem lik an eternity if - * the UI freezes). Including the phrase //"decrypting"// in the UI can also help, assuring the user their waiting is - * for a good reason. - * - * @category Crypto - * @example - * - * ```ts - * // The password must be converted to bytes, and it is generally - * // best practices to ensure the string has been normalized. Many - * // formats explicitly indicate the normalization form to use. - * password = 'hello'; - * passwordBytes = toUtf8Bytes(password, 'NFKC'); - * - * salt = id('some-salt'); - * - * // Compute the scrypt - * scrypt(passwordBytes, salt, 1024, 8, 1, 16); - * ``` - * - * @param {BytesLike} _passwd - The password to use. - * @param {BytesLike} _salt - The salt to use. - * @param {number} N - The CPU/memory cost parameter. - * @param {number} r - The block size parameter. - * @param {number} p - The parallelization parameter. - * @param {number} dkLen - The length of the key to generate. - * @param {ProgressCallback} [progress] - A callback to update the progress. - * @returns {Promise} The key derived from the password. - */ - async function scrypt(_passwd, _salt, N, r, p, dkLen, progress) { - const passwd = getBytes(_passwd, 'passwd'); - const salt = getBytes(_salt, 'salt'); - return hexlify(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress)); - } - scrypt._ = _scryptAsync; - scrypt.lock = function () { - lockedAsync = true; - }; - scrypt.register = function (func) { - if (lockedAsync) { - throw new Error('scrypt is locked'); - } - __scryptAsync = func; - }; - Object.freeze(scrypt); - /** - * Provides a synchronous variant of {@link scrypt | **scrypt**}. - * - * This will completely lock up and freeze the UI in a browser and will prevent any event loop from progressing. For - * this reason, it is preferred to use the [async variant](scrypt). - * - * @category Crypto - * @example - * - * ```ts - * // The password must be converted to bytes, and it is generally - * // best practices to ensure the string has been normalized. Many - * // formats explicitly indicate the normalization form to use. - * password = 'hello'; - * passwordBytes = toUtf8Bytes(password, 'NFKC'); - * - * salt = id('some-salt'); - * - * // Compute the scrypt - * scryptSync(passwordBytes, salt, 1024, 8, 1, 16); - * ``` - * - * @param {BytesLike} _passwd - The password to use. - * @param {BytesLike} _salt - The salt to use. - * @param {number} N - The CPU/memory cost parameter. - * @param {number} r - The block size parameter. - * @param {number} p - The parallelization parameter. - * @param {number} dkLen - The length of the key to generate. - * @returns {string} The key derived from the password. - */ - function scryptSync(_passwd, _salt, N, r, p, dkLen) { - const passwd = getBytes(_passwd, 'passwd'); - const salt = getBytes(_salt, 'salt'); - return hexlify(__scryptSync(passwd, salt, N, r, p, dkLen)); - } - scryptSync._ = _scryptSync; - scryptSync.lock = function () { - lockedSync = true; - }; - scryptSync.register = function (func) { - if (lockedSync) { - throw new Error('scryptSync is locked'); - } - __scryptSync = func; - }; - Object.freeze(scryptSync); - - const _sha256 = function (data) { - return createHash('sha256').update(data).digest(); - }; - const _sha512 = function (data) { - return createHash('sha512').update(data).digest(); - }; - let __sha256 = _sha256; - let __sha512 = _sha512; - let locked256 = false, locked512 = false; - /** - * Compute the cryptographic SHA2-256 hash of `data`. - * - * @category Crypto - * @example - * - * ```ts - * sha256('0x'); - * - * sha256('0x1337'); - * - * sha256(new Uint8Array([0x13, 0x37])); - * ``` - * - * @param {BytesLike} _data - The data to hash. - * @returns {string} The hash of the data. - */ - function sha256(_data) { - const data = getBytes(_data, 'data'); - return hexlify(__sha256(data)); - } - sha256._ = _sha256; - sha256.lock = function () { - locked256 = true; - }; - sha256.register = function (func) { - if (locked256) { - throw new Error('sha256 is locked'); - } - __sha256 = func; - }; - Object.freeze(sha256); - /** - * Compute the cryptographic SHA2-512 hash of `data`. - * - * @category Crypto - * @example - * - * ```ts - * sha512('0x'); - * - * sha512('0x1337'); - * - * sha512(new Uint8Array([0x13, 0x37])); - * ``` - * - * @param {BytesLike} _data - The data to hash. - * @returns {string} The hash of the data. - */ - function sha512(_data) { - const data = getBytes(_data, 'data'); - return hexlify(__sha512(data)); - } - sha512._ = _sha512; - sha512.lock = function () { - locked512 = true; - }; - sha512.register = function (func) { - if (locked512) { - throw new Error('sha512 is locked'); - } - __sha512 = func; - }; - Object.freeze(sha256); - - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - // 100 lines of code in the file are duplicated from noble-hashes (utils). - // This is OK: `abstract` directory does not use noble-hashes. - // User may opt-in into using different hashing library. This way, noble-hashes - // won't be included into their bundle. - const _0n$5 = BigInt(0); - const _1n$5 = BigInt(1); - const _2n$3 = BigInt(2); - const u8a = (a) => a instanceof Uint8Array; - const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); - /** - * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123' - */ - function bytesToHex(bytes) { - if (!u8a(bytes)) - throw new Error('Uint8Array expected'); - // pre-caching improves the speed 6x - let hex = ''; - for (let i = 0; i < bytes.length; i++) { - hex += hexes[bytes[i]]; - } - return hex; - } - function numberToHexUnpadded(num) { - const hex = num.toString(16); - return hex.length & 1 ? `0${hex}` : hex; - } - function hexToNumber(hex) { - if (typeof hex !== 'string') - throw new Error('hex string expected, got ' + typeof hex); - // Big Endian - return BigInt(hex === '' ? '0' : `0x${hex}`); - } - /** - * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) - */ - function hexToBytes(hex) { - if (typeof hex !== 'string') - throw new Error('hex string expected, got ' + typeof hex); - const len = hex.length; - if (len % 2) - throw new Error('padded hex string expected, got unpadded hex of length ' + len); - const array = new Uint8Array(len / 2); - for (let i = 0; i < array.length; i++) { - const j = i * 2; - const hexByte = hex.slice(j, j + 2); - const byte = Number.parseInt(hexByte, 16); - if (Number.isNaN(byte) || byte < 0) - throw new Error('Invalid byte sequence'); - array[i] = byte; - } - return array; - } - // BE: Big Endian, LE: Little Endian - function bytesToNumberBE(bytes) { - return hexToNumber(bytesToHex(bytes)); - } - function bytesToNumberLE(bytes) { - if (!u8a(bytes)) - throw new Error('Uint8Array expected'); - return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); - } - function numberToBytesBE(n, len) { - return hexToBytes(n.toString(16).padStart(len * 2, '0')); - } - function numberToBytesLE(n, len) { - return numberToBytesBE(n, len).reverse(); - } - // Unpadded, rarely used - function numberToVarBytesBE(n) { - return hexToBytes(numberToHexUnpadded(n)); - } - /** - * Takes hex string or Uint8Array, converts to Uint8Array. - * Validates output length. - * Will throw error for other types. - * @param title descriptive title for an error e.g. 'private key' - * @param hex hex string or Uint8Array - * @param expectedLength optional, will compare to result array's length - * @returns - */ - function ensureBytes(title, hex, expectedLength) { - let res; - if (typeof hex === 'string') { - try { - res = hexToBytes(hex); - } - catch (e) { - throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); - } - } - else if (u8a(hex)) { - // Uint8Array.from() instead of hash.slice() because node.js Buffer - // is instance of Uint8Array, and its slice() creates **mutable** copy - res = Uint8Array.from(hex); - } - else { - throw new Error(`${title} must be hex string or Uint8Array`); - } - const len = res.length; - if (typeof expectedLength === 'number' && len !== expectedLength) - throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); - return res; - } - /** - * Copies several Uint8Arrays into one. - */ - function concatBytes(...arrays) { - const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0)); - let pad = 0; // walk through each item, ensure they have proper type - arrays.forEach((a) => { - if (!u8a(a)) - throw new Error('Uint8Array expected'); - r.set(a, pad); - pad += a.length; - }); - return r; - } - function equalBytes(b1, b2) { - // We don't care about timing attacks here - if (b1.length !== b2.length) - return false; - for (let i = 0; i < b1.length; i++) - if (b1[i] !== b2[i]) - return false; - return true; - } - /** - * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) - */ - function utf8ToBytes(str) { - if (typeof str !== 'string') - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 - } - // Bit operations - /** - * Calculates amount of bits in a bigint. - * Same as `n.toString(2).length` - */ - function bitLen(n) { - let len; - for (len = 0; n > _0n$5; n >>= _1n$5, len += 1) - ; - return len; - } - /** - * Gets single bit at position. - * NOTE: first bit position is 0 (same as arrays) - * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` - */ - function bitGet(n, pos) { - return (n >> BigInt(pos)) & _1n$5; - } - /** - * Sets single bit at position. - */ - const bitSet = (n, pos, value) => { - return n | ((value ? _1n$5 : _0n$5) << BigInt(pos)); - }; - /** - * Calculate mask for N bits. Not using ** operator with bigints because of old engines. - * Same as BigInt(`0b${Array(i).fill('1').join('')}`) - */ - const bitMask = (n) => (_2n$3 << BigInt(n - 1)) - _1n$5; - // DRBG - const u8n = (data) => new Uint8Array(data); // creates Uint8Array - const u8fr = (arr) => Uint8Array.from(arr); // another shortcut - /** - * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. - * @returns function that will call DRBG until 2nd arg returns something meaningful - * @example - * const drbg = createHmacDRBG(32, 32, hmac); - * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined - */ - function createHmacDrbg(hashLen, qByteLen, hmacFn) { - if (typeof hashLen !== 'number' || hashLen < 2) - throw new Error('hashLen must be a number'); - if (typeof qByteLen !== 'number' || qByteLen < 2) - throw new Error('qByteLen must be a number'); - if (typeof hmacFn !== 'function') - throw new Error('hmacFn must be a function'); - // Step B, Step C: set hashLen to 8*ceil(hlen/8) - let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs. - let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same - let i = 0; // Iterations counter, will throw when over 1000 - const reset = () => { - v.fill(1); - k.fill(0); - i = 0; - }; - const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values) - const reseed = (seed = u8n()) => { - // HMAC-DRBG reseed() function. Steps D-G - k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed) - v = h(); // v = hmac(k || v) - if (seed.length === 0) - return; - k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed) - v = h(); // v = hmac(k || v) - }; - const gen = () => { - // HMAC-DRBG generate() function - if (i++ >= 1000) - throw new Error('drbg: tried 1000 values'); - let len = 0; - const out = []; - while (len < qByteLen) { - v = h(); - const sl = v.slice(); - out.push(sl); - len += v.length; - } - return concatBytes(...out); - }; - const genUntil = (seed, pred) => { - reset(); - reseed(seed); // Steps D-G - let res = undefined; // Step H: grind until k is in [1..n-1] - while (!(res = pred(gen()))) - reseed(); - reset(); - return res; - }; - return genUntil; - } - // Validating curves and fields - const validatorFns = { - bigint: (val) => typeof val === 'bigint', - function: (val) => typeof val === 'function', - boolean: (val) => typeof val === 'boolean', - string: (val) => typeof val === 'string', - stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array, - isSafeInteger: (val) => Number.isSafeInteger(val), - array: (val) => Array.isArray(val), - field: (val, object) => object.Fp.isValid(val), - hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen), - }; - // type Record = { [P in K]: T; } - function validateObject(object, validators, optValidators = {}) { - const checkField = (fieldName, type, isOptional) => { - const checkVal = validatorFns[type]; - if (typeof checkVal !== 'function') - throw new Error(`Invalid validator "${type}", expected function`); - const val = object[fieldName]; - if (isOptional && val === undefined) - return; - if (!checkVal(val, object)) { - throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); - } - }; - for (const [fieldName, type] of Object.entries(validators)) - checkField(fieldName, type, false); - for (const [fieldName, type] of Object.entries(optValidators)) - checkField(fieldName, type, true); - return object; - } - // validate type tests - // const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 }; - // const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok! - // // Should fail type-check - // const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' }); - // const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' }); - // const z3 = validateObject(o, { test: 'boolean', z: 'bug' }); - // const z4 = validateObject(o, { a: 'boolean', z: 'bug' }); - - var ut = /*#__PURE__*/Object.freeze({ - __proto__: null, - bitGet: bitGet, - bitLen: bitLen, - bitMask: bitMask, - bitSet: bitSet, - bytesToHex: bytesToHex, - bytesToNumberBE: bytesToNumberBE, - bytesToNumberLE: bytesToNumberLE, - concatBytes: concatBytes, - createHmacDrbg: createHmacDrbg, - ensureBytes: ensureBytes, - equalBytes: equalBytes, - hexToBytes: hexToBytes, - hexToNumber: hexToNumber, - numberToBytesBE: numberToBytesBE, - numberToBytesLE: numberToBytesLE, - numberToHexUnpadded: numberToHexUnpadded, - numberToVarBytesBE: numberToVarBytesBE, - utf8ToBytes: utf8ToBytes, - validateObject: validateObject - }); - - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - // Utilities for modular arithmetics and finite fields - // prettier-ignore - const _0n$4 = BigInt(0), _1n$4 = BigInt(1), _2n$2 = BigInt(2), _3n$2 = BigInt(3); - // prettier-ignore - const _4n = BigInt(4), _5n$1 = BigInt(5), _8n = BigInt(8); - // prettier-ignore - BigInt(9); BigInt(16); - // Calculates a modulo b - function mod(a, b) { - const result = a % b; - return result >= _0n$4 ? result : b + result; - } - /** - * Efficiently raise num to power and do modular division. - * Unsafe in some contexts: uses ladder, so can expose bigint bits. - * @example - * pow(2n, 6n, 11n) // 64n % 11n == 9n - */ - // TODO: use field version && remove - function pow(num, power, modulo) { - if (modulo <= _0n$4 || power < _0n$4) - throw new Error('Expected power/modulo > 0'); - if (modulo === _1n$4) - return _0n$4; - let res = _1n$4; - while (power > _0n$4) { - if (power & _1n$4) - res = (res * num) % modulo; - num = (num * num) % modulo; - power >>= _1n$4; - } - return res; - } - // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4) - function pow2(x, power, modulo) { - let res = x; - while (power-- > _0n$4) { - res *= res; - res %= modulo; - } - return res; - } - // Inverses number over modulo - function invert(number, modulo) { - if (number === _0n$4 || modulo <= _0n$4) { - throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); - } - // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/ - // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. - let a = mod(number, modulo); - let b = modulo; - // prettier-ignore - let x = _0n$4, u = _1n$4; - while (a !== _0n$4) { - // JIT applies optimization if those two lines follow each other - const q = b / a; - const r = b % a; - const m = x - u * q; - // prettier-ignore - b = a, a = r, x = u, u = m; - } - const gcd = b; - if (gcd !== _1n$4) - throw new Error('invert: does not exist'); - return mod(x, modulo); - } - /** - * Tonelli-Shanks square root search algorithm. - * 1. https://eprint.iacr.org/2012/685.pdf (page 12) - * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks - * Will start an infinite loop if field order P is not prime. - * @param P field order - * @returns function that takes field Fp (created from P) and number n - */ - function tonelliShanks(P) { - // Legendre constant: used to calculate Legendre symbol (a | p), - // which denotes the value of a^((p-1)/2) (mod p). - // (a | p) ≡ 1 if a is a square (mod p) - // (a | p) ≡ -1 if a is not a square (mod p) - // (a | p) ≡ 0 if a ≡ 0 (mod p) - const legendreC = (P - _1n$4) / _2n$2; - let Q, S, Z; - // Step 1: By factoring out powers of 2 from p - 1, - // find q and s such that p - 1 = q*(2^s) with q odd - for (Q = P - _1n$4, S = 0; Q % _2n$2 === _0n$4; Q /= _2n$2, S++) - ; - // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq - for (Z = _2n$2; Z < P && pow(Z, legendreC, P) !== P - _1n$4; Z++) - ; - // Fast-path - if (S === 1) { - const p1div4 = (P + _1n$4) / _4n; - return function tonelliFast(Fp, n) { - const root = Fp.pow(n, p1div4); - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error('Cannot find square root'); - return root; - }; - } - // Slow-path - const Q1div2 = (Q + _1n$4) / _2n$2; - return function tonelliSlow(Fp, n) { - // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1 - if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) - throw new Error('Cannot find square root'); - let r = S; - // TODO: will fail at Fp2/etc - let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b - let x = Fp.pow(n, Q1div2); // first guess at the square root - let b = Fp.pow(n, Q); // first guess at the fudge factor - while (!Fp.eql(b, Fp.ONE)) { - if (Fp.eql(b, Fp.ZERO)) - return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0) - // Find m such b^(2^m)==1 - let m = 1; - for (let t2 = Fp.sqr(b); m < r; m++) { - if (Fp.eql(t2, Fp.ONE)) - break; - t2 = Fp.sqr(t2); // t2 *= t2 - } - // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow - const ge = Fp.pow(g, _1n$4 << BigInt(r - m - 1)); // ge = 2^(r-m-1) - g = Fp.sqr(ge); // g = ge * ge - x = Fp.mul(x, ge); // x *= ge - b = Fp.mul(b, g); // b *= g - r = m; - } - return x; - }; - } - function FpSqrt(P) { - // NOTE: different algorithms can give different roots, it is up to user to decide which one they want. - // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve). - // P ≡ 3 (mod 4) - // √n = n^((P+1)/4) - if (P % _4n === _3n$2) { - // Not all roots possible! - // const ORDER = - // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn; - // const NUM = 72057594037927816n; - const p1div4 = (P + _1n$4) / _4n; - return function sqrt3mod4(Fp, n) { - const root = Fp.pow(n, p1div4); - // Throw if root**2 != n - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error('Cannot find square root'); - return root; - }; - } - // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10) - if (P % _8n === _5n$1) { - const c1 = (P - _5n$1) / _8n; - return function sqrt5mod8(Fp, n) { - const n2 = Fp.mul(n, _2n$2); - const v = Fp.pow(n2, c1); - const nv = Fp.mul(n, v); - const i = Fp.mul(Fp.mul(nv, _2n$2), v); - const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); - if (!Fp.eql(Fp.sqr(root), n)) - throw new Error('Cannot find square root'); - return root; - }; - } - // Other cases: Tonelli-Shanks algorithm - return tonelliShanks(P); - } - // prettier-ignore - const FIELD_FIELDS = [ - 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', - 'eql', 'add', 'sub', 'mul', 'pow', 'div', - 'addN', 'subN', 'mulN', 'sqrN' - ]; - function validateField(field) { - const initial = { - ORDER: 'bigint', - MASK: 'bigint', - BYTES: 'isSafeInteger', - BITS: 'isSafeInteger', - }; - const opts = FIELD_FIELDS.reduce((map, val) => { - map[val] = 'function'; - return map; - }, initial); - return validateObject(field, opts); - } - // Generic field functions - /** - * Same as `pow` but for Fp: non-constant-time. - * Unsafe in some contexts: uses ladder, so can expose bigint bits. - */ - function FpPow(f, num, power) { - // Should have same speed as pow for bigints - // TODO: benchmark! - if (power < _0n$4) - throw new Error('Expected power > 0'); - if (power === _0n$4) - return f.ONE; - if (power === _1n$4) - return num; - let p = f.ONE; - let d = num; - while (power > _0n$4) { - if (power & _1n$4) - p = f.mul(p, d); - d = f.sqr(d); - power >>= _1n$4; - } - return p; - } - /** - * Efficiently invert an array of Field elements. - * `inv(0)` will return `undefined` here: make sure to throw an error. - */ - function FpInvertBatch(f, nums) { - const tmp = new Array(nums.length); - // Walk from first to last, multiply them by each other MOD p - const lastMultiplied = nums.reduce((acc, num, i) => { - if (f.is0(num)) - return acc; - tmp[i] = acc; - return f.mul(acc, num); - }, f.ONE); - // Invert last element - const inverted = f.inv(lastMultiplied); - // Walk from last to first, multiply them by inverted each other MOD p - nums.reduceRight((acc, num, i) => { - if (f.is0(num)) - return acc; - tmp[i] = f.mul(acc, tmp[i]); - return f.mul(acc, num); - }, inverted); - return tmp; - } - // CURVE.n lengths - function nLength(n, nBitLength) { - // Bit size, byte size of CURVE.n - const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; - const nByteLength = Math.ceil(_nBitLength / 8); - return { nBitLength: _nBitLength, nByteLength }; - } - /** - * Initializes a finite field over prime. **Non-primes are not supported.** - * Do not init in loop: slow. Very fragile: always run a benchmark on a change. - * Major performance optimizations: - * * a) denormalized operations like mulN instead of mul - * * b) same object shape: never add or remove keys - * * c) Object.freeze - * @param ORDER prime positive bigint - * @param bitLen how many bits the field consumes - * @param isLE (def: false) if encoding / decoding should be in little-endian - * @param redef optional faster redefinitions of sqrt and other methods - */ - function Field(ORDER, bitLen, isLE = false, redef = {}) { - if (ORDER <= _0n$4) - throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); - const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); - if (BYTES > 2048) - throw new Error('Field lengths over 2048 bytes are not supported'); - const sqrtP = FpSqrt(ORDER); - const f = Object.freeze({ - ORDER, - BITS, - BYTES, - MASK: bitMask(BITS), - ZERO: _0n$4, - ONE: _1n$4, - create: (num) => mod(num, ORDER), - isValid: (num) => { - if (typeof num !== 'bigint') - throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); - return _0n$4 <= num && num < ORDER; // 0 is valid element, but it's not invertible - }, - is0: (num) => num === _0n$4, - isOdd: (num) => (num & _1n$4) === _1n$4, - neg: (num) => mod(-num, ORDER), - eql: (lhs, rhs) => lhs === rhs, - sqr: (num) => mod(num * num, ORDER), - add: (lhs, rhs) => mod(lhs + rhs, ORDER), - sub: (lhs, rhs) => mod(lhs - rhs, ORDER), - mul: (lhs, rhs) => mod(lhs * rhs, ORDER), - pow: (num, power) => FpPow(f, num, power), - div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER), - // Same as above, but doesn't normalize - sqrN: (num) => num * num, - addN: (lhs, rhs) => lhs + rhs, - subN: (lhs, rhs) => lhs - rhs, - mulN: (lhs, rhs) => lhs * rhs, - inv: (num) => invert(num, ORDER), - sqrt: redef.sqrt || ((n) => sqrtP(f, n)), - invertBatch: (lst) => FpInvertBatch(f, lst), - // TODO: do we really need constant cmov? - // We don't have const-time bigints anyway, so probably will be not very useful - cmov: (a, b, c) => (c ? b : a), - toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)), - fromBytes: (bytes) => { - if (bytes.length !== BYTES) - throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); - return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); - }, - }); - return Object.freeze(f); - } - /** - * Returns total number of bytes consumed by the field element. - * For example, 32 bytes for usual 256-bit weierstrass curve. - * @param fieldOrder number of field elements, usually CURVE.n - * @returns byte length of field - */ - function getFieldBytesLength(fieldOrder) { - if (typeof fieldOrder !== 'bigint') - throw new Error('field order must be bigint'); - const bitLength = fieldOrder.toString(2).length; - return Math.ceil(bitLength / 8); - } - /** - * Returns minimal amount of bytes that can be safely reduced - * by field order. - * Should be 2^-128 for 128-bit curve such as P256. - * @param fieldOrder number of field elements, usually CURVE.n - * @returns byte length of target hash - */ - function getMinHashLength(fieldOrder) { - const length = getFieldBytesLength(fieldOrder); - return length + Math.ceil(length / 2); - } - /** - * "Constant-time" private key generation utility. - * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF - * and convert them into private scalar, with the modulo bias being negligible. - * Needs at least 48 bytes of input for 32-byte private key. - * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/ - * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final - * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5 - * @param hash hash output from SHA3 or a similar function - * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n) - * @param isLE interpret hash bytes as LE num - * @returns valid private scalar - */ - function mapHashToField(key, fieldOrder, isLE = false) { - const len = key.length; - const fieldLen = getFieldBytesLength(fieldOrder); - const minLen = getMinHashLength(fieldOrder); - // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings. - if (len < 16 || len < minLen || len > 1024) - throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); - const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); - // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 - const reduced = mod(num, fieldOrder - _1n$4) + _1n$4; - return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); - } - - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - // Abelian group utilities - const _0n$3 = BigInt(0); - const _1n$3 = BigInt(1); - // Elliptic curve multiplication of Point by scalar. Fragile. - // Scalars should always be less than curve order: this should be checked inside of a curve itself. - // Creates precomputation tables for fast multiplication: - // - private scalar is split by fixed size windows of W bits - // - every window point is collected from window's table & added to accumulator - // - since windows are different, same point inside tables won't be accessed more than once per calc - // - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) - // - +1 window is neccessary for wNAF - // - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication - // TODO: Research returning 2d JS array of windows, instead of a single window. This would allow - // windows to be in different memory locations - function wNAF(c, bits) { - const constTimeNegate = (condition, item) => { - const neg = item.negate(); - return condition ? neg : item; - }; - const opts = (W) => { - const windows = Math.ceil(bits / W) + 1; // +1, because - const windowSize = 2 ** (W - 1); // -1 because we skip zero - return { windows, windowSize }; - }; - return { - constTimeNegate, - // non-const time multiplication ladder - unsafeLadder(elm, n) { - let p = c.ZERO; - let d = elm; - while (n > _0n$3) { - if (n & _1n$3) - p = p.add(d); - d = d.double(); - n >>= _1n$3; - } - return p; - }, - /** - * Creates a wNAF precomputation window. Used for caching. - * Default window size is set by `utils.precompute()` and is equal to 8. - * Number of precomputed points depends on the curve size: - * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: - * - 𝑊 is the window size - * - 𝑛 is the bitlength of the curve order. - * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. - * @returns precomputed point tables flattened to a single array - */ - precomputeWindow(elm, W) { - const { windows, windowSize } = opts(W); - const points = []; - let p = elm; - let base = p; - for (let window = 0; window < windows; window++) { - base = p; - points.push(base); - // =1, because we skip zero - for (let i = 1; i < windowSize; i++) { - base = base.add(p); - points.push(base); - } - p = base.double(); - } - return points; - }, - /** - * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. - * @param W window size - * @param precomputes precomputed tables - * @param n scalar (we don't check here, but should be less than curve order) - * @returns real and fake (for const-time) points - */ - wNAF(W, precomputes, n) { - // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise - // But need to carefully remove other checks before wNAF. ORDER == bits here - const { windows, windowSize } = opts(W); - let p = c.ZERO; - let f = c.BASE; - const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc. - const maxNumber = 2 ** W; - const shiftBy = BigInt(W); - for (let window = 0; window < windows; window++) { - const offset = window * windowSize; - // Extract W bits. - let wbits = Number(n & mask); - // Shift number by W bits. - n >>= shiftBy; - // If the bits are bigger than max size, we'll split those. - // +224 => 256 - 32 - if (wbits > windowSize) { - wbits -= maxNumber; - n += _1n$3; - } - // This code was first written with assumption that 'f' and 'p' will never be infinity point: - // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, - // there is negate now: it is possible that negated element from low value - // would be the same as high element, which will create carry into next window. - // It's not obvious how this can fail, but still worth investigating later. - // Check if we're onto Zero point. - // Add random point inside current window to f. - const offset1 = offset; - const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero - const cond1 = window % 2 !== 0; - const cond2 = wbits < 0; - if (wbits === 0) { - // The most important part for const-time getPublicKey - f = f.add(constTimeNegate(cond1, precomputes[offset1])); - } - else { - p = p.add(constTimeNegate(cond2, precomputes[offset2])); - } - } - // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ() - // Even if the variable is still unused, there are some checks which will - // throw an exception, so compiler needs to prove they won't happen, which is hard. - // At this point there is a way to F be infinity-point even if p is not, - // which makes it less const-time: around 1 bigint multiply. - return { p, f }; - }, - wNAFCached(P, precomputesMap, n, transform) { - // @ts-ignore - const W = P._WINDOW_SIZE || 1; - // Calculate precomputes on a first run, reuse them after - let comp = precomputesMap.get(P); - if (!comp) { - comp = this.precomputeWindow(P, W); - if (W !== 1) { - precomputesMap.set(P, transform(comp)); - } - } - return this.wNAF(W, comp, n); - }, - }; - } - function validateBasic(curve) { - validateField(curve.Fp); - validateObject(curve, { - n: 'bigint', - h: 'bigint', - Gx: 'field', - Gy: 'field', - }, { - nBitLength: 'isSafeInteger', - nByteLength: 'isSafeInteger', - }); - // Set defaults - return Object.freeze({ - ...nLength(curve.n, curve.nBitLength), - ...curve, - ...{ p: curve.Fp.ORDER }, - }); - } - - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - // Short Weierstrass curve. The formula is: y² = x³ + ax + b - function validatePointOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - a: 'field', - b: 'field', - }, { - allowedPrivateKeyLengths: 'array', - wrapPrivateKey: 'boolean', - isTorsionFree: 'function', - clearCofactor: 'function', - allowInfinityPoint: 'boolean', - fromBytes: 'function', - toBytes: 'function', - }); - const { endo, Fp, a } = opts; - if (endo) { - if (!Fp.eql(a, Fp.ZERO)) { - throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0'); - } - if (typeof endo !== 'object' || - typeof endo.beta !== 'bigint' || - typeof endo.splitScalar !== 'function') { - throw new Error('Expected endomorphism with beta: bigint and splitScalar: function'); - } - } - return Object.freeze({ ...opts }); - } - // ASN.1 DER encoding utilities - const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; - const DER = { - // asn.1 DER encoding utils - Err: class DERErr extends Error { - constructor(m = '') { - super(m); - } - }, - _parseInt(data) { - const { Err: E } = DER; - if (data.length < 2 || data[0] !== 0x02) - throw new E('Invalid signature integer tag'); - const len = data[1]; - const res = data.subarray(2, len + 2); - if (!len || res.length !== len) - throw new E('Invalid signature integer: wrong length'); - // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, - // since we always use positive integers here. It must always be empty: - // - add zero byte if exists - // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) - if (res[0] & 0b10000000) - throw new E('Invalid signature integer: negative'); - if (res[0] === 0x00 && !(res[1] & 0b10000000)) - throw new E('Invalid signature integer: unnecessary leading zero'); - return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left - }, - toSig(hex) { - // parse DER signature - const { Err: E } = DER; - const data = typeof hex === 'string' ? h2b(hex) : hex; - if (!(data instanceof Uint8Array)) - throw new Error('ui8a expected'); - let l = data.length; - if (l < 2 || data[0] != 0x30) - throw new E('Invalid signature tag'); - if (data[1] !== l - 2) - throw new E('Invalid signature: incorrect length'); - const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); - const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); - if (rBytesLeft.length) - throw new E('Invalid signature: left bytes after parsing'); - return { r, s }; - }, - hexFromSig(sig) { - // Add leading zero if first byte has negative bit enabled. More details in '_parseInt' - const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s); - const h = (num) => { - const hex = num.toString(16); - return hex.length & 1 ? `0${hex}` : hex; - }; - const s = slice(h(sig.s)); - const r = slice(h(sig.r)); - const shl = s.length / 2; - const rhl = r.length / 2; - const sl = h(shl); - const rl = h(rhl); - return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; - }, - }; - // Be friendly to bad ECMAScript parsers by not using bigint literals - // prettier-ignore - const _0n$2 = BigInt(0), _1n$2 = BigInt(1); BigInt(2); const _3n$1 = BigInt(3); BigInt(4); - function weierstrassPoints(opts) { - const CURVE = validatePointOpts(opts); - const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ - const toBytes = CURVE.toBytes || - ((_c, point, _isCompressed) => { - const a = point.toAffine(); - return concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y)); - }); - const fromBytes = CURVE.fromBytes || - ((bytes) => { - // const head = bytes[0]; - const tail = bytes.subarray(1); - // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported'); - const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); - const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); - return { x, y }; - }); - /** - * y² = x³ + ax + b: Short weierstrass curve formula - * @returns y² - */ - function weierstrassEquation(x) { - const { a, b } = CURVE; - const x2 = Fp.sqr(x); // x * x - const x3 = Fp.mul(x2, x); // x2 * x - return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b - } - // Validate whether the passed curve params are valid. - // We check if curve equation works for generator point. - // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381. - // ProjectivePoint class has not been initialized yet. - if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) - throw new Error('bad generator point: equation left != right'); - // Valid group elements reside in range 1..n-1 - function isWithinCurveOrder(num) { - return typeof num === 'bigint' && _0n$2 < num && num < CURVE.n; - } - function assertGE(num) { - if (!isWithinCurveOrder(num)) - throw new Error('Expected valid bigint: 0 < bigint < curve.n'); - } - // Validates if priv key is valid and converts it to bigint. - // Supports options allowedPrivateKeyLengths and wrapPrivateKey. - function normPrivateKeyToScalar(key) { - const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; - if (lengths && typeof key !== 'bigint') { - if (key instanceof Uint8Array) - key = bytesToHex(key); - // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes - if (typeof key !== 'string' || !lengths.includes(key.length)) - throw new Error('Invalid key'); - key = key.padStart(nByteLength * 2, '0'); - } - let num; - try { - num = - typeof key === 'bigint' - ? key - : bytesToNumberBE(ensureBytes('private key', key, nByteLength)); - } - catch (error) { - throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); - } - if (wrapPrivateKey) - num = mod(num, n); // disabled by default, enabled for BLS - assertGE(num); // num in range [1..N-1] - return num; - } - const pointPrecomputes = new Map(); - function assertPrjPoint(other) { - if (!(other instanceof Point)) - throw new Error('ProjectivePoint expected'); - } - /** - * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z) - * Default Point works in 2d / affine coordinates: (x, y) - * We're doing calculations in projective, because its operations don't require costly inversion. - */ - class Point { - constructor(px, py, pz) { - this.px = px; - this.py = py; - this.pz = pz; - if (px == null || !Fp.isValid(px)) - throw new Error('x required'); - if (py == null || !Fp.isValid(py)) - throw new Error('y required'); - if (pz == null || !Fp.isValid(pz)) - throw new Error('z required'); - } - // Does not validate if the point is on-curve. - // Use fromHex instead, or call assertValidity() later. - static fromAffine(p) { - const { x, y } = p || {}; - if (!p || !Fp.isValid(x) || !Fp.isValid(y)) - throw new Error('invalid affine point'); - if (p instanceof Point) - throw new Error('projective point not allowed'); - const is0 = (i) => Fp.eql(i, Fp.ZERO); - // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0) - if (is0(x) && is0(y)) - return Point.ZERO; - return new Point(x, y, Fp.ONE); - } - get x() { - return this.toAffine().x; - } - get y() { - return this.toAffine().y; - } - /** - * Takes a bunch of Projective Points but executes only one - * inversion on all of them. Inversion is very slow operation, - * so this improves performance massively. - * Optimization: converts a list of projective points to a list of identical points with Z=1. - */ - static normalizeZ(points) { - const toInv = Fp.invertBatch(points.map((p) => p.pz)); - return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); - } - /** - * Converts hash string or Uint8Array to Point. - * @param hex short/long ECDSA hex - */ - static fromHex(hex) { - const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex))); - P.assertValidity(); - return P; - } - // Multiplies generator point by privateKey. - static fromPrivateKey(privateKey) { - return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); - } - // "Private method", don't use it directly - _setWindowSize(windowSize) { - this._WINDOW_SIZE = windowSize; - pointPrecomputes.delete(this); - } - // A point on curve is valid if it conforms to equation. - assertValidity() { - if (this.is0()) { - // (0, 1, 0) aka ZERO is invalid in most contexts. - // In BLS, ZERO can be serialized, so we allow it. - // (0, 0, 0) is wrong representation of ZERO and is always invalid. - if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) - return; - throw new Error('bad point: ZERO'); - } - // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` - const { x, y } = this.toAffine(); - // Check if x, y are valid field elements - if (!Fp.isValid(x) || !Fp.isValid(y)) - throw new Error('bad point: x or y not FE'); - const left = Fp.sqr(y); // y² - const right = weierstrassEquation(x); // x³ + ax + b - if (!Fp.eql(left, right)) - throw new Error('bad point: equation left != right'); - if (!this.isTorsionFree()) - throw new Error('bad point: not in prime-order subgroup'); - } - hasEvenY() { - const { y } = this.toAffine(); - if (Fp.isOdd) - return !Fp.isOdd(y); - throw new Error("Field doesn't support isOdd"); - } - /** - * Compare one point to another. - */ - equals(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); - const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); - return U1 && U2; - } - /** - * Flips point to one corresponding to (x, -y) in Affine coordinates. - */ - negate() { - return new Point(this.px, Fp.neg(this.py), this.pz); - } - // Renes-Costello-Batina exception-free doubling formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 3 - // Cost: 8M + 3S + 3*a + 2*b3 + 15add. - double() { - const { a, b } = CURVE; - const b3 = Fp.mul(b, _3n$1); - const { px: X1, py: Y1, pz: Z1 } = this; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore - let t0 = Fp.mul(X1, X1); // step 1 - let t1 = Fp.mul(Y1, Y1); - let t2 = Fp.mul(Z1, Z1); - let t3 = Fp.mul(X1, Y1); - t3 = Fp.add(t3, t3); // step 5 - Z3 = Fp.mul(X1, Z1); - Z3 = Fp.add(Z3, Z3); - X3 = Fp.mul(a, Z3); - Y3 = Fp.mul(b3, t2); - Y3 = Fp.add(X3, Y3); // step 10 - X3 = Fp.sub(t1, Y3); - Y3 = Fp.add(t1, Y3); - Y3 = Fp.mul(X3, Y3); - X3 = Fp.mul(t3, X3); - Z3 = Fp.mul(b3, Z3); // step 15 - t2 = Fp.mul(a, t2); - t3 = Fp.sub(t0, t2); - t3 = Fp.mul(a, t3); - t3 = Fp.add(t3, Z3); - Z3 = Fp.add(t0, t0); // step 20 - t0 = Fp.add(Z3, t0); - t0 = Fp.add(t0, t2); - t0 = Fp.mul(t0, t3); - Y3 = Fp.add(Y3, t0); - t2 = Fp.mul(Y1, Z1); // step 25 - t2 = Fp.add(t2, t2); - t0 = Fp.mul(t2, t3); - X3 = Fp.sub(X3, t0); - Z3 = Fp.mul(t2, t1); - Z3 = Fp.add(Z3, Z3); // step 30 - Z3 = Fp.add(Z3, Z3); - return new Point(X3, Y3, Z3); - } - // Renes-Costello-Batina exception-free addition formula. - // There is 30% faster Jacobian formula, but it is not complete. - // https://eprint.iacr.org/2015/1060, algorithm 1 - // Cost: 12M + 0S + 3*a + 3*b3 + 23add. - add(other) { - assertPrjPoint(other); - const { px: X1, py: Y1, pz: Z1 } = this; - const { px: X2, py: Y2, pz: Z2 } = other; - let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore - const a = CURVE.a; - const b3 = Fp.mul(CURVE.b, _3n$1); - let t0 = Fp.mul(X1, X2); // step 1 - let t1 = Fp.mul(Y1, Y2); - let t2 = Fp.mul(Z1, Z2); - let t3 = Fp.add(X1, Y1); - let t4 = Fp.add(X2, Y2); // step 5 - t3 = Fp.mul(t3, t4); - t4 = Fp.add(t0, t1); - t3 = Fp.sub(t3, t4); - t4 = Fp.add(X1, Z1); - let t5 = Fp.add(X2, Z2); // step 10 - t4 = Fp.mul(t4, t5); - t5 = Fp.add(t0, t2); - t4 = Fp.sub(t4, t5); - t5 = Fp.add(Y1, Z1); - X3 = Fp.add(Y2, Z2); // step 15 - t5 = Fp.mul(t5, X3); - X3 = Fp.add(t1, t2); - t5 = Fp.sub(t5, X3); - Z3 = Fp.mul(a, t4); - X3 = Fp.mul(b3, t2); // step 20 - Z3 = Fp.add(X3, Z3); - X3 = Fp.sub(t1, Z3); - Z3 = Fp.add(t1, Z3); - Y3 = Fp.mul(X3, Z3); - t1 = Fp.add(t0, t0); // step 25 - t1 = Fp.add(t1, t0); - t2 = Fp.mul(a, t2); - t4 = Fp.mul(b3, t4); - t1 = Fp.add(t1, t2); - t2 = Fp.sub(t0, t2); // step 30 - t2 = Fp.mul(a, t2); - t4 = Fp.add(t4, t2); - t0 = Fp.mul(t1, t4); - Y3 = Fp.add(Y3, t0); - t0 = Fp.mul(t5, t4); // step 35 - X3 = Fp.mul(t3, X3); - X3 = Fp.sub(X3, t0); - t0 = Fp.mul(t3, t1); - Z3 = Fp.mul(t5, Z3); - Z3 = Fp.add(Z3, t0); // step 40 - return new Point(X3, Y3, Z3); - } - subtract(other) { - return this.add(other.negate()); - } - is0() { - return this.equals(Point.ZERO); - } - wNAF(n) { - return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => { - const toInv = Fp.invertBatch(comp.map((p) => p.pz)); - return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine); - }); - } - /** - * Non-constant-time multiplication. Uses double-and-add algorithm. - * It's faster, but should only be used when you don't care about - * an exposed private key e.g. sig verification, which works over *public* keys. - */ - multiplyUnsafe(n) { - const I = Point.ZERO; - if (n === _0n$2) - return I; - assertGE(n); // Will throw on 0 - if (n === _1n$2) - return this; - const { endo } = CURVE; - if (!endo) - return wnaf.unsafeLadder(this, n); - // Apply endomorphism - let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let k1p = I; - let k2p = I; - let d = this; - while (k1 > _0n$2 || k2 > _0n$2) { - if (k1 & _1n$2) - k1p = k1p.add(d); - if (k2 & _1n$2) - k2p = k2p.add(d); - d = d.double(); - k1 >>= _1n$2; - k2 >>= _1n$2; - } - if (k1neg) - k1p = k1p.negate(); - if (k2neg) - k2p = k2p.negate(); - k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - return k1p.add(k2p); - } - /** - * Constant time multiplication. - * Uses wNAF method. Windowed method may be 10% faster, - * but takes 2x longer to generate and consumes 2x memory. - * Uses precomputes when available. - * Uses endomorphism for Koblitz curves. - * @param scalar by which the point would be multiplied - * @returns New point - */ - multiply(scalar) { - assertGE(scalar); - let n = scalar; - let point, fake; // Fake point is used to const-time mult - const { endo } = CURVE; - if (endo) { - const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); - let { p: k1p, f: f1p } = this.wNAF(k1); - let { p: k2p, f: f2p } = this.wNAF(k2); - k1p = wnaf.constTimeNegate(k1neg, k1p); - k2p = wnaf.constTimeNegate(k2neg, k2p); - k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); - point = k1p.add(k2p); - fake = f1p.add(f2p); - } - else { - const { p, f } = this.wNAF(n); - point = p; - fake = f; - } - // Normalize `z` for both points, but return only real one - return Point.normalizeZ([point, fake])[0]; - } - /** - * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly. - * Not using Strauss-Shamir trick: precomputation tables are faster. - * The trick could be useful if both P and Q are not G (not in our case). - * @returns non-zero affine point - */ - multiplyAndAddUnsafe(Q, a, b) { - const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes - const mul = (P, a // Select faster multiply() method - ) => (a === _0n$2 || a === _1n$2 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a)); - const sum = mul(this, a).add(mul(Q, b)); - return sum.is0() ? undefined : sum; - } - // Converts Projective point to affine (x, y) coordinates. - // Can accept precomputed Z^-1 - for example, from invertBatch. - // (x, y, z) ∋ (x=x/z, y=y/z) - toAffine(iz) { - const { px: x, py: y, pz: z } = this; - const is0 = this.is0(); - // If invZ was 0, we return zero point. However we still want to execute - // all operations, so we replace invZ with a random number, 1. - if (iz == null) - iz = is0 ? Fp.ONE : Fp.inv(z); - const ax = Fp.mul(x, iz); - const ay = Fp.mul(y, iz); - const zz = Fp.mul(z, iz); - if (is0) - return { x: Fp.ZERO, y: Fp.ZERO }; - if (!Fp.eql(zz, Fp.ONE)) - throw new Error('invZ was invalid'); - return { x: ax, y: ay }; - } - isTorsionFree() { - const { h: cofactor, isTorsionFree } = CURVE; - if (cofactor === _1n$2) - return true; // No subgroups, always torsion-free - if (isTorsionFree) - return isTorsionFree(Point, this); - throw new Error('isTorsionFree() has not been declared for the elliptic curve'); - } - clearCofactor() { - const { h: cofactor, clearCofactor } = CURVE; - if (cofactor === _1n$2) - return this; // Fast-path - if (clearCofactor) - return clearCofactor(Point, this); - return this.multiplyUnsafe(CURVE.h); - } - toRawBytes(isCompressed = true) { - this.assertValidity(); - return toBytes(Point, this, isCompressed); - } - toHex(isCompressed = true) { - return bytesToHex(this.toRawBytes(isCompressed)); - } - } - Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); - Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); - const _bits = CURVE.nBitLength; - const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); - // Validate if generator point is on curve - return { - CURVE, - ProjectivePoint: Point, - normPrivateKeyToScalar, - weierstrassEquation, - isWithinCurveOrder, - }; - } - function validateOpts(curve) { - const opts = validateBasic(curve); - validateObject(opts, { - hash: 'hash', - hmac: 'function', - randomBytes: 'function', - }, { - bits2int: 'function', - bits2int_modN: 'function', - lowS: 'boolean', - }); - return Object.freeze({ lowS: true, ...opts }); - } - function weierstrass(curveDef) { - const CURVE = validateOpts(curveDef); - const { Fp, n: CURVE_ORDER } = CURVE; - const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32 - const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32 - function isValidFieldElement(num) { - return _0n$2 < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE - } - function modN(a) { - return mod(a, CURVE_ORDER); - } - function invN(a) { - return invert(a, CURVE_ORDER); - } - const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({ - ...CURVE, - toBytes(_c, point, isCompressed) { - const a = point.toAffine(); - const x = Fp.toBytes(a.x); - const cat = concatBytes; - if (isCompressed) { - return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x); - } - else { - return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y)); - } - }, - fromBytes(bytes) { - const len = bytes.length; - const head = bytes[0]; - const tail = bytes.subarray(1); - // this.assertValidity() is done inside of fromHex - if (len === compressedLen && (head === 0x02 || head === 0x03)) { - const x = bytesToNumberBE(tail); - if (!isValidFieldElement(x)) - throw new Error('Point is not on curve'); - const y2 = weierstrassEquation(x); // y² = x³ + ax + b - let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 - const isYOdd = (y & _1n$2) === _1n$2; - // ECDSA - const isHeadOdd = (head & 1) === 1; - if (isHeadOdd !== isYOdd) - y = Fp.neg(y); - return { x, y }; - } - else if (len === uncompressedLen && head === 0x04) { - const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); - const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); - return { x, y }; - } - else { - throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); - } - }, - }); - const numToNByteStr = (num) => bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); - function isBiggerThanHalfOrder(number) { - const HALF = CURVE_ORDER >> _1n$2; - return number > HALF; - } - function normalizeS(s) { - return isBiggerThanHalfOrder(s) ? modN(-s) : s; - } - // slice bytes num - const slcNum = (b, from, to) => bytesToNumberBE(b.slice(from, to)); - /** - * ECDSA signature with its (r, s) properties. Supports DER & compact representations. - */ - class Signature { - constructor(r, s, recovery) { - this.r = r; - this.s = s; - this.recovery = recovery; - this.assertValidity(); - } - // pair (bytes of r, bytes of s) - static fromCompact(hex) { - const l = CURVE.nByteLength; - hex = ensureBytes('compactSignature', hex, l * 2); - return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); - } - // DER encoded ECDSA signature - // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script - static fromDER(hex) { - const { r, s } = DER.toSig(ensureBytes('DER', hex)); - return new Signature(r, s); - } - assertValidity() { - // can use assertGE here - if (!isWithinCurveOrder(this.r)) - throw new Error('r must be 0 < r < CURVE.n'); - if (!isWithinCurveOrder(this.s)) - throw new Error('s must be 0 < s < CURVE.n'); - } - addRecoveryBit(recovery) { - return new Signature(this.r, this.s, recovery); - } - recoverPublicKey(msgHash) { - const { r, s, recovery: rec } = this; - const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash - if (rec == null || ![0, 1, 2, 3].includes(rec)) - throw new Error('recovery id invalid'); - const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; - if (radj >= Fp.ORDER) - throw new Error('recovery id 2 or 3 invalid'); - const prefix = (rec & 1) === 0 ? '02' : '03'; - const R = Point.fromHex(prefix + numToNByteStr(radj)); - const ir = invN(radj); // r^-1 - const u1 = modN(-h * ir); // -hr^-1 - const u2 = modN(s * ir); // sr^-1 - const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1) - if (!Q) - throw new Error('point at infinify'); // unsafe is fine: no priv data leaked - Q.assertValidity(); - return Q; - } - // Signatures should be low-s, to prevent malleability. - hasHighS() { - return isBiggerThanHalfOrder(this.s); - } - normalizeS() { - return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; - } - // DER-encoded - toDERRawBytes() { - return hexToBytes(this.toDERHex()); - } - toDERHex() { - return DER.hexFromSig({ r: this.r, s: this.s }); - } - // padded bytes of r, then padded bytes of s - toCompactRawBytes() { - return hexToBytes(this.toCompactHex()); - } - toCompactHex() { - return numToNByteStr(this.r) + numToNByteStr(this.s); - } - } - const utils = { - isValidPrivateKey(privateKey) { - try { - normPrivateKeyToScalar(privateKey); - return true; - } - catch (error) { - return false; - } - }, - normPrivateKeyToScalar: normPrivateKeyToScalar, - /** - * Produces cryptographically secure private key from random of size - * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. - */ - randomPrivateKey: () => { - const length = getMinHashLength(CURVE.n); - return mapHashToField(CURVE.randomBytes(length), CURVE.n); - }, - /** - * Creates precompute table for an arbitrary EC point. Makes point "cached". - * Allows to massively speed-up `point.multiply(scalar)`. - * @returns cached point - * @example - * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey)); - * fast.multiply(privKey); // much faster ECDH now - */ - precompute(windowSize = 8, point = Point.BASE) { - point._setWindowSize(windowSize); - point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here - return point; - }, - }; - /** - * Computes public key for a private key. Checks for validity of the private key. - * @param privateKey private key - * @param isCompressed whether to return compact (default), or full key - * @returns Public key, full when isCompressed=false; short when isCompressed=true - */ - function getPublicKey(privateKey, isCompressed = true) { - return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); - } - /** - * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. - */ - function isProbPub(item) { - const arr = item instanceof Uint8Array; - const str = typeof item === 'string'; - const len = (arr || str) && item.length; - if (arr) - return len === compressedLen || len === uncompressedLen; - if (str) - return len === 2 * compressedLen || len === 2 * uncompressedLen; - if (item instanceof Point) - return true; - return false; - } - /** - * ECDH (Elliptic Curve Diffie Hellman). - * Computes shared public key from private key and public key. - * Checks: 1) private key validity 2) shared key is on-curve. - * Does NOT hash the result. - * @param privateA private key - * @param publicB different public key - * @param isCompressed whether to return compact (default), or full key - * @returns shared public key - */ - function getSharedSecret(privateA, publicB, isCompressed = true) { - if (isProbPub(privateA)) - throw new Error('first arg must be private key'); - if (!isProbPub(publicB)) - throw new Error('second arg must be public key'); - const b = Point.fromHex(publicB); // check for being on-curve - return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); - } - // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. - // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. - // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. - // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors - const bits2int = CURVE.bits2int || - function (bytes) { - // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) - // for some cases, since bytes.length * 8 is not actual bitLength. - const num = bytesToNumberBE(bytes); // check for == u8 done here - const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits - return delta > 0 ? num >> BigInt(delta) : num; - }; - const bits2int_modN = CURVE.bits2int_modN || - function (bytes) { - return modN(bits2int(bytes)); // can't use bytesToNumberBE here - }; - // NOTE: pads output with zero as per spec - const ORDER_MASK = bitMask(CURVE.nBitLength); - /** - * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. - */ - function int2octets(num) { - if (typeof num !== 'bigint') - throw new Error('bigint expected'); - if (!(_0n$2 <= num && num < ORDER_MASK)) - throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); - // works with order, can have different size than numToField! - return numberToBytesBE(num, CURVE.nByteLength); - } - // Steps A, D of RFC6979 3.2 - // Creates RFC6979 seed; converts msg/privKey to numbers. - // Used only in sign, not in verify. - // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521. - // Also it can be bigger for P224 + SHA256 - function prepSig(msgHash, privateKey, opts = defaultSigOpts) { - if (['recovered', 'canonical'].some((k) => k in opts)) - throw new Error('sign() legacy options not supported'); - const { hash, randomBytes } = CURVE; - let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default - if (lowS == null) - lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash - msgHash = ensureBytes('msgHash', msgHash); - if (prehash) - msgHash = ensureBytes('prehashed msgHash', hash(msgHash)); - // We can't later call bits2octets, since nested bits2int is broken for curves - // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call. - // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) - const h1int = bits2int_modN(msgHash); - const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint - const seedArgs = [int2octets(d), int2octets(h1int)]; - // extraEntropy. RFC6979 3.6: additional k' (optional). - if (ent != null) { - // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') - const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is - seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes - } - const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2 - const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash! - // Converts signature params into point w r/s, checks result for validity. - function k2sig(kBytes) { - // RFC 6979 Section 3.2, step 3: k = bits2int(T) - const k = bits2int(kBytes); // Cannot use fields methods, since it is group element - if (!isWithinCurveOrder(k)) - return; // Important: all mod() calls here must be done over N - const ik = invN(k); // k^-1 mod n - const q = Point.BASE.multiply(k).toAffine(); // q = Gk - const r = modN(q.x); // r = q.x mod n - if (r === _0n$2) - return; - // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to - // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: - // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT - const s = modN(ik * modN(m + r * d)); // Not using blinding here - if (s === _0n$2) - return; - let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$2); // recovery bit (2 or 3, when q.x > n) - let normS = s; - if (lowS && isBiggerThanHalfOrder(s)) { - normS = normalizeS(s); // if lowS was passed, ensure s is always - recovery ^= 1; // // in the bottom half of N - } - return new Signature(r, normS, recovery); // use normS, not s - } - return { seed, k2sig }; - } - const defaultSigOpts = { lowS: CURVE.lowS, prehash: false }; - const defaultVerOpts = { lowS: CURVE.lowS, prehash: false }; - /** - * Signs message hash with a private key. - * ``` - * sign(m, d, k) where - * (x, y) = G × k - * r = x mod n - * s = (m + dr)/k mod n - * ``` - * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`. - * @param privKey private key - * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg. - * @returns signature with recovery param - */ - function sign(msgHash, privKey, opts = defaultSigOpts) { - const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2. - const C = CURVE; - const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); - return drbg(seed, k2sig); // Steps B, C, D, E, F, G - } - // Enable precomputes. Slows down first publicKey computation by 20ms. - Point.BASE._setWindowSize(8); - // utils.precompute(8, ProjectivePoint.BASE) - /** - * Verifies a signature against message hash and public key. - * Rejects lowS signatures by default: to override, - * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: - * - * ``` - * verify(r, s, h, P) where - * U1 = hs^-1 mod n - * U2 = rs^-1 mod n - * R = U1⋅G - U2⋅P - * mod(R.x, n) == r - * ``` - */ - function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { - const sg = signature; - msgHash = ensureBytes('msgHash', msgHash); - publicKey = ensureBytes('publicKey', publicKey); - if ('strict' in opts) - throw new Error('options.strict was renamed to lowS'); - const { lowS, prehash } = opts; - let _sig = undefined; - let P; - try { - if (typeof sg === 'string' || sg instanceof Uint8Array) { - // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length). - // Since DER can also be 2*nByteLength bytes, we check for it first. - try { - _sig = Signature.fromDER(sg); - } - catch (derError) { - if (!(derError instanceof DER.Err)) - throw derError; - _sig = Signature.fromCompact(sg); - } - } - else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') { - const { r, s } = sg; - _sig = new Signature(r, s); - } - else { - throw new Error('PARSE'); - } - P = Point.fromHex(publicKey); - } - catch (error) { - if (error.message === 'PARSE') - throw new Error(`signature must be Signature instance, Uint8Array or hex string`); - return false; - } - if (lowS && _sig.hasHighS()) - return false; - if (prehash) - msgHash = CURVE.hash(msgHash); - const { r, s } = _sig; - const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element - const is = invN(s); // s^-1 - const u1 = modN(h * is); // u1 = hs^-1 mod n - const u2 = modN(r * is); // u2 = rs^-1 mod n - const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P - if (!R) - return false; - const v = modN(R.x); - return v === r; - } - return { - CURVE, - getPublicKey, - getSharedSecret, - sign, - verify, - ProjectivePoint: Point, - Signature, - utils, - }; - } - - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - // connects noble-curves to noble-hashes - function getHash(hash) { - return { - hash, - hmac: (key, ...msgs) => hmac(hash, key, concatBytes$1(...msgs)), - randomBytes: randomBytes$2, - }; - } - function createCurve(curveDef, defHash) { - const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) }); - return Object.freeze({ ...create(defHash), create }); - } - - /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ - const secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'); - const secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); - const _1n$1 = BigInt(1); - const _2n$1 = BigInt(2); - const divNearest = (a, b) => (a + b / _2n$1) / b; - /** - * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. - * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] - */ - function sqrtMod(y) { - const P = secp256k1P; - // prettier-ignore - const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); - // prettier-ignore - const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); - const b2 = (y * y * y) % P; // x^3, 11 - const b3 = (b2 * b2 * y) % P; // x^7 - const b6 = (pow2(b3, _3n, P) * b3) % P; - const b9 = (pow2(b6, _3n, P) * b3) % P; - const b11 = (pow2(b9, _2n$1, P) * b2) % P; - const b22 = (pow2(b11, _11n, P) * b11) % P; - const b44 = (pow2(b22, _22n, P) * b22) % P; - const b88 = (pow2(b44, _44n, P) * b44) % P; - const b176 = (pow2(b88, _88n, P) * b88) % P; - const b220 = (pow2(b176, _44n, P) * b44) % P; - const b223 = (pow2(b220, _3n, P) * b3) % P; - const t1 = (pow2(b223, _23n, P) * b22) % P; - const t2 = (pow2(t1, _6n, P) * b2) % P; - const root = pow2(t2, _2n$1, P); - if (!Fp.eql(Fp.sqr(root), y)) - throw new Error('Cannot find square root'); - return root; - } - const Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod }); - const secp256k1 = createCurve({ - a: BigInt(0), - b: BigInt(7), - Fp, - n: secp256k1N, - // Base point (x, y) aka generator point - Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'), - Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'), - h: BigInt(1), - lowS: true, - /** - * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism. - * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. - * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. - * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 - */ - endo: { - beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), - splitScalar: (k) => { - const n = secp256k1N; - const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15'); - const b1 = -_1n$1 * BigInt('0xe4437ed6010e88286f547fa90abfe4c3'); - const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'); - const b2 = a1; - const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16) - const c1 = divNearest(b2 * k, n); - const c2 = divNearest(-b1 * k, n); - let k1 = mod(k - c1 * a1 - c2 * a2, n); - let k2 = mod(-c1 * b1 - c2 * b2, n); - const k1neg = k1 > POW_2_128; - const k2neg = k2 > POW_2_128; - if (k1neg) - k1 = n - k1; - if (k2neg) - k2 = n - k2; - if (k1 > POW_2_128 || k2 > POW_2_128) { - throw new Error('splitScalar: Endomorphism failed, k=' + k); - } - return { k1neg, k1, k2neg, k2 }; - }, - }, - }, sha256$1); - // Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. - // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki - const _0n$1 = BigInt(0); - const fe = (x) => typeof x === 'bigint' && _0n$1 < x && x < secp256k1P; - const ge = (x) => typeof x === 'bigint' && _0n$1 < x && x < secp256k1N; - /** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ - const TAGGED_HASH_PREFIXES = {}; - function taggedHash$1(tag, ...messages) { - let tagP = TAGGED_HASH_PREFIXES[tag]; - if (tagP === undefined) { - const tagH = sha256$1(Uint8Array.from(tag, (c) => c.charCodeAt(0))); - tagP = concatBytes(tagH, tagH); - TAGGED_HASH_PREFIXES[tag] = tagP; - } - return sha256$1(concatBytes(tagP, ...messages)); - } - // ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 - const pointToBytes = (point) => point.toRawBytes(true).slice(1); - const numTo32b = (n) => numberToBytesBE(n, 32); - const modP = (x) => mod(x, secp256k1P); - const modN = (x) => mod(x, secp256k1N); - const Point = secp256k1.ProjectivePoint; - const GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b); - // Calculate point, scalar and bytes - function schnorrGetExtPubKey(priv) { - let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey - let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside - const scalar = p.hasEvenY() ? d_ : modN(-d_); - return { scalar: scalar, bytes: pointToBytes(p) }; - } - /** - * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. - * @returns valid point checked for being on-curve - */ - function lift_x(x) { - if (!fe(x)) - throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p. - const xx = modP(x * x); - const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. - let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p. - if (y % _2n$1 !== _0n$1) - y = modP(-y); // Return the unique point P such that x(P) = x and - const p = new Point(x, y, _1n$1); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. - p.assertValidity(); - return p; - } - /** - * Create tagged hash, convert it to bigint, reduce modulo-n. - */ - function challenge(...args) { - return modN(bytesToNumberBE(taggedHash$1('BIP0340/challenge', ...args))); - } - /** - * Schnorr public key is just `x` coordinate of Point as per BIP340. - */ - function schnorrGetPublicKey(privateKey) { - return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) - } - /** - * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. - * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous. - */ - function schnorrSign(message, privateKey, auxRand = randomBytes$2(32)) { - const m = ensureBytes('message', message); - const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder - const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array - const t = numTo32b(d ^ bytesToNumberBE(taggedHash$1('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a) - const rand = taggedHash$1('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) - const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n - if (k_ === _0n$1) - throw new Error('sign failed: k is zero'); // Fail if k' = 0. - const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G. - const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. - const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). - sig.set(rx, 0); - sig.set(numTo32b(modN(k + e * d)), 32); - // If Verify(bytes(P), m, sig) (see below) returns failure, abort - if (!schnorrVerify(sig, m, px)) - throw new Error('sign: Invalid signature produced'); - return sig; - } - /** - * Verifies Schnorr signature. - * Will swallow errors & return false except for initial type validation of arguments. - */ - function schnorrVerify(signature, message, publicKey) { - const sig = ensureBytes('signature', signature, 64); - const m = ensureBytes('message', message); - const pub = ensureBytes('publicKey', publicKey, 32); - try { - const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails - const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. - if (!fe(r)) - return false; - const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. - if (!ge(s)) - return false; - const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n - const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P - if (!R || !R.hasEvenY() || R.toAffine().x !== r) - return false; // -eP == (n-e)P - return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. - } - catch (error) { - return false; - } - } - const schnorr = /* @__PURE__ */ (() => ({ - getPublicKey: schnorrGetPublicKey, - sign: schnorrSign, - verify: schnorrVerify, - utils: { - randomPrivateKey: secp256k1.utils.randomPrivateKey, - lift_x, - pointToBytes, - numberToBytesBE, - bytesToNumberBE, - taggedHash: taggedHash$1, - mod, - }, - }))(); - - /** - * A constant for the zero address. - * - * (**i.e.** `"0x0000000000000000000000000000000000000000"`) - * - * @category Constants - */ - const ZeroAddress = '0x0000000000000000000000000000000000000000'; - - /** - * A constant for the zero hash. - * - * (**i.e.** `"0x0000000000000000000000000000000000000000000000000000000000000000"`) - * - * @category Constants - */ - const ZeroHash = '0x0000000000000000000000000000000000000000000000000000000000000000'; - - /** - * A constant for the order N for the secp256k1 curve. - * - * (**i.e.** `0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n`) - * - * @category Constants - */ - const N$1 = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); - /** - * A constant for the number of wei in a single ether. - * - * (**i.e.** `1000000000000000000n`) - * - * @category Constants - */ - const WeiPerEther = BigInt('1000000000000000000'); - /** - * A constant for the maximum value for a `uint256`. - * - * (**i.e.** `0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn`) - * - * @category Constants - */ - const MaxUint256 = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); - /** - * A constant for the minimum value for an `int256`. - * - * (**i.e.** `-8000000000000000000000000000000000000000000000000000000000000000n`) - * - * @category Constants - */ - const MinInt256 = BigInt('0x8000000000000000000000000000000000000000000000000000000000000000') * BigInt(-1); - /** - * A constant for the maximum value for an `int256`. - * - * (**i.e.** `0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn`) - * - * @category Constants - */ - const MaxInt256 = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); - - // NFKC (composed) // (decomposed) - /** - * A constant for the ether symbol (normalized using NFKC). - * - * (**i.e.** `"\\u039e"`) - * - * @category Constants - */ - const quaisymbol = '\u039e'; // "\uD835\uDF63"; - /** - * A constant for the Quai Network equivalent of the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal message - * prefix. - * - * (**i.e.** `"\\x19Quai Signed Message:\\n"`) - * - * @category Constants - */ - const MessagePrefix = '\x19Quai Signed Message:\n'; - /** - * A constant for the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal message prefix. - * - * (**i.e.** `"\\x19Ethereum Signed Message:\\n"`) - * - * @category Constants - */ - const EthMessagePrefix = '\x19Ethereum Signed Message:\n'; - - /** - * A shard represents a chain within the Quai network hierarchy. A shard refer to the Prime chain, a region under the - * Prime chain, or a Zone within a region. The value is a hexadecimal string representing the encoded value of the - * shard. Read more [here](https://github.com/quai-network/qips/blob/master/qip-0002.md). - * - * @category Constants - */ - exports.Shard = void 0; - (function (Shard) { - Shard["Cyprus"] = "0x0"; - Shard["Cyprus1"] = "0x00"; - Shard["Cyprus2"] = "0x01"; - Shard["Cyprus3"] = "0x02"; - Shard["Paxos"] = "0x1"; - Shard["Paxos1"] = "0x10"; - Shard["Paxos2"] = "0x11"; - Shard["Paxos3"] = "0x12"; - Shard["Hydra"] = "0x2"; - Shard["Hydra1"] = "0x20"; - Shard["Hydra2"] = "0x21"; - Shard["Hydra3"] = "0x22"; - Shard["Prime"] = "0x"; - })(exports.Shard || (exports.Shard = {})); - function shardFromBytes(shard) { - switch (shard) { - case '0x': - return exports.Shard.Prime; - case '0x0': - return exports.Shard.Cyprus; - case '0x1': - return exports.Shard.Paxos; - case '0x2': - return exports.Shard.Hydra; - case '0x00': - return exports.Shard.Cyprus1; - case '0x01': - return exports.Shard.Cyprus2; - case '0x02': - return exports.Shard.Cyprus3; - case '0x10': - return exports.Shard.Paxos1; - case '0x11': - return exports.Shard.Paxos2; - case '0x12': - return exports.Shard.Paxos3; - case '0x20': - return exports.Shard.Hydra1; - case '0x21': - return exports.Shard.Hydra2; - case '0x22': - return exports.Shard.Hydra3; - default: - throw new Error('Invalid shard'); - } - } - /** - * Constant data that defines each shard within the network. - * - * @category Constants - */ - const ShardData = [ - ...ZoneData, - { - name: 'Cyprus', - nickname: 'cyprus', - shard: 'region-0', - context: 2, - byte: '0x0', - }, - { - name: 'Paxos', - nickname: 'paxos', - shard: 'region-1', - context: 2, - byte: '0x1', - }, - { - name: 'Hydra', - nickname: 'hydra', - shard: 'region-2', - context: 2, - byte: '0x2', - }, - { - name: 'Prime', - nickname: 'prime', - shard: 'prime', - context: 2, - byte: '0x', - }, - ]; - function toShard(shard) { - return shardFromBytes(ShardData.find((it) => it.name == shard || it.byte == shard || it.nickname == shard || it.shard == shard) - ?.byte || ''); - } - function fromShard(shard, key) { - return ShardData.find((it) => it.byte == shard)?.[key] || ''; - } - - // Constants - const BN_0$5 = BigInt(0); - const BN_1$2 = BigInt(1); - const BN_2$1 = BigInt(2); - const BN_27 = BigInt(27); - const BN_28 = BigInt(28); - const BN_35 = BigInt(35); - const _guard$6 = {}; - function toUint256(value) { - return zeroPadValue(toBeArray(value), 32); - } - /** - * A Signature @TODO - * - * @category Crypto - */ - class Signature { - #r; - #s; - #v; - #networkV; - /** - * The `r` value for a signautre. - * - * This represents the `x` coordinate of a "reference" or challenge point, from which the `y` can be computed. - */ - get r() { - return this.#r; - } - set r(value) { - assertArgument(dataLength(value) === 32, 'invalid r', 'value', value); - this.#r = hexlify(value); - } - /** - * The `s` value for a signature. - */ - get s() { - return this.#s; - } - set s(_value) { - assertArgument(dataLength(_value) === 32, 'invalid s', 'value', _value); - const value = hexlify(_value); - assertArgument(parseInt(value.substring(0, 3)) < 8, 'non-canonical s', 'value', value); - this.#s = value; - } - /** - * The `v` value for a signature. - * - * Since a given `x` value for `r` has two possible values for its correspondin `y`, the `v` indicates which of the - * two `y` values to use. - * - * It is normalized to the values `27` or `28` for legacy purposes. - */ - get v() { - return this.#v; - } - set v(value) { - const v = getNumber(value, 'value'); - assertArgument(v === 27 || v === 28, 'invalid v', 'v', value); - this.#v = v; - } - /** - * The EIP-155 `v` for legacy transactions. For non-legacy transactions, this value is `null`. - */ - get networkV() { - return this.#networkV; - } - /** - * The chain ID for EIP-155 legacy transactions. For non-legacy transactions, this value is `null`. - */ - get legacyChainId() { - const v = this.networkV; - if (v == null) { - return null; - } - return Signature.getChainId(v); - } - /** - * The `yParity` for the signature. - * - * See `v` for more details on how this value is used. - */ - get yParity() { - return this.v === 27 ? 0 : 1; - } - /** - * The [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098) compact representation of the `yParity` and `s` compacted - * into a single `bytes32`. - */ - get yParityAndS() { - // The EIP-2098 compact representation - const yParityAndS = getBytes(this.s); - if (this.yParity) { - yParityAndS[0] |= 0x80; - } - return hexlify(yParityAndS); - } - /** - * The [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098) compact representation. - */ - get compactSerialized() { - return concat([this.r, this.yParityAndS]); - } - /** - * The serialized representation. - */ - get serialized() { - return concat([this.r, this.s, this.yParity ? '0x1c' : '0x1b']); - } - /** - * @ignore - */ - constructor(guard, r, s, v) { - assertPrivate(guard, _guard$6, 'Signature'); - this.#r = r; - this.#s = s; - this.#v = v; - this.#networkV = null; - } - [Symbol.for('nodejs.util.inspect.custom')]() { - return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`; - } - /** - * Returns a new identical {@link Signature | **Signature**}. - */ - clone() { - const clone = new Signature(_guard$6, this.r, this.s, this.v); - if (this.networkV) { - clone.#networkV = this.networkV; - } - return clone; - } - /** - * Returns a representation that is compatible with `JSON.stringify`. - */ - toJSON() { - const networkV = this.networkV; - return { - _type: 'signature', - networkV: networkV != null ? networkV.toString() : null, - r: this.r, - s: this.s, - v: this.v, - }; - } - /** - * Compute the chain ID from the `v` in a legacy EIP-155 transactions. - * - * @example - * - * ```ts - * Signature.getChainId(45); - * - * Signature.getChainId(46); - * ``` - * - * @param {BigNumberish} v - The `v` value from the signature. - * @returns {bigint} The chain ID. - */ - static getChainId(v) { - const bv = getBigInt(v, 'v'); - // The v is not an EIP-155 v, so it is the unspecified chain ID - if (bv == BN_27 || bv == BN_28) { - return BN_0$5; - } - // Bad value for an EIP-155 v - assertArgument(bv >= BN_35, 'invalid EIP-155 v', 'v', v); - return (bv - BN_35) / BN_2$1; - } - /** - * Compute the `v` for a chain ID for a legacy EIP-155 transactions. - * - * Legacy transactions which use [EIP-155](https://eips.ethereum.org/EIPS/eip-155) hijack the `v` property to - * include the chain ID. - * - * @example - * - * ```ts - * Signature.getChainIdV(5, 27); - * - * Signature.getChainIdV(5, 28); - * ``` - * - * @param {BigNumberish} chainId - The chain ID. - * @param {27 | 28} v - The `v` value. - * @returns {bigint} The `v` value. - */ - static getChainIdV(chainId, v) { - return getBigInt(chainId) * BN_2$1 + BigInt(35 + v - 27); - } - /** - * Compute the normalized legacy transaction `v` from a `yParirty`, a legacy transaction `v` or a legacy - * [EIP-155](https://eips.ethereum.org/EIPS/eip-155) transaction. - * - * @example - * - * ```ts - * // The values 0 and 1 imply v is actually yParity - * Signature.getNormalizedV(0); - * - * // Legacy non-EIP-1559 transaction (i.e. 27 or 28) - * Signature.getNormalizedV(27); - * - * // Legacy EIP-155 transaction (i.e. >= 35) - * Signature.getNormalizedV(46); - * - * // Invalid values throw - * Signature.getNormalizedV(5); - * ``` - * - * @param {BigNumberish} v - The `v` value. - * @returns {27 | 28} The normalized `v` value. - * @throws {Error} Thrown if the `v` is invalid. - */ - static getNormalizedV(v) { - const bv = getBigInt(v); - if (bv === BN_0$5 || bv === BN_27) { - return 27; - } - if (bv === BN_1$2 || bv === BN_28) { - return 28; - } - assertArgument(bv >= BN_35, 'invalid v', 'v', v); - // Otherwise, EIP-155 v means odd is 27 and even is 28 - return bv & BN_1$2 ? 27 : 28; - } - /** - * Creates a new {@link Signature | **Signature**}. - * - * If no `sig` is provided, a new {@link Signature | **Signature**} is created with default values. - * - * If `sig` is a string, it is parsed. - * - * @param {SignatureLike} [sig] - The signature to create. - * @returns {Signature} The new signature. - */ - static from(sig) { - function assertError(check, message) { - assertArgument(check, message, 'signature', sig); - } - if (sig == null) { - return new Signature(_guard$6, ZeroHash, ZeroHash, 27); - } - if (typeof sig === 'string') { - const bytes = getBytes(sig, 'signature'); - if (bytes.length === 64) { - const r = hexlify(bytes.slice(0, 32)); - const s = bytes.slice(32, 64); - const v = s[0] & 0x80 ? 28 : 27; - s[0] &= 0x7f; - return new Signature(_guard$6, r, hexlify(s), v); - } - if (bytes.length === 65) { - const r = hexlify(bytes.slice(0, 32)); - const s = bytes.slice(32, 64); - assertError((s[0] & 0x80) === 0, 'non-canonical s'); - const v = Signature.getNormalizedV(bytes[64]); - return new Signature(_guard$6, r, hexlify(s), v); - } - assertError(false, 'invalid raw signature length'); - } - if (sig instanceof Signature) { - return sig.clone(); - } - // Get r - const _r = sig.r; - assertError(_r != null, 'missing r'); - const r = toUint256(_r); - // Get s; by any means necessary (we check consistency below) - const s = (function (s, yParityAndS) { - if (s != null) { - return toUint256(s); - } - if (yParityAndS != null) { - assertError(isHexString(yParityAndS, 32), 'invalid yParityAndS'); - const bytes = getBytes(yParityAndS); - bytes[0] &= 0x7f; - return hexlify(bytes); - } - assertError(false, 'missing s'); - })(sig.s, sig.yParityAndS); - assertError((getBytes(s)[0] & 0x80) == 0, 'non-canonical s'); - // Get v; by any means necessary (we check consistency below) - const { networkV, v } = (function (_v, yParityAndS, yParity) { - if (_v != null) { - const v = getBigInt(_v); - return { - networkV: v >= BN_35 ? v : undefined, - v: Signature.getNormalizedV(v), - }; - } - if (yParityAndS != null) { - assertError(isHexString(yParityAndS, 32), 'invalid yParityAndS'); - return { v: getBytes(yParityAndS)[0] & 0x80 ? 28 : 27 }; - } - if (yParity != null) { - switch (yParity) { - case 0: - return { v: 27 }; - case 1: - return { v: 28 }; - } - assertError(false, 'invalid yParity'); - } - assertError(false, 'missing v'); - })(sig.v, sig.yParityAndS, sig.yParity); - const result = new Signature(_guard$6, r, s, v); - if (networkV) { - result.#networkV = networkV; - } - // If multiple of v, yParity, yParityAndS we given, check they match - assertError(!('yParity' in sig && sig.yParity !== result.yParity), 'yParity mismatch'); - assertError(!('yParityAndS' in sig && sig.yParityAndS !== result.yParityAndS), 'yParityAndS mismatch'); - return result; - } - } - - /** - * Add details about signing here. - */ - /** - * A **SigningKey** provides high-level access to the elliptic curve cryptography (ECC) operations and key management. - * - * @category Crypto - */ - class SigningKey { - #privateKey; - /** - * Creates a new **SigningKey** for `privateKey`. - */ - constructor(privateKey) { - assertArgument(dataLength(privateKey) === 32, 'invalid private key', 'privateKey', '[REDACTED]'); - this.#privateKey = hexlify(privateKey); - } - /** - * The private key. - */ - get privateKey() { - return this.#privateKey; - } - /** - * The uncompressed public key. - * - * This will always begin with the prefix `0x04` and be 132 characters long (the `0x` prefix and 130 hexadecimal - * nibbles). - */ - get publicKey() { - return SigningKey.computePublicKey(this.#privateKey); - } - /** - * The compressed public key. - * - * This will always begin with either the prefix `0x02` or `0x03` and be 68 characters long (the `0x` prefix and 33 - * hexadecimal nibbles) - */ - get compressedPublicKey() { - return SigningKey.computePublicKey(this.#privateKey, true); - } - /** - * Return the signature of the signed `digest`. - * - * @param {BytesLike} digest - The data to sign. - * @returns {Signature} The signature of the data. - * @throws {Error} If the digest is not 32 bytes long. - */ - sign(digest) { - assertArgument(dataLength(digest) === 32, 'invalid digest length', 'digest', digest); - const sig = secp256k1.sign(getBytesCopy(digest), getBytesCopy(this.#privateKey), { - lowS: true, - }); - return Signature.from({ - r: toBeHex('0x' + sig.r.toString(16), 32), - s: toBeHex('0x' + sig.s.toString(16), 32), - v: sig.recovery ? 0x1c : 0x1b, - }); - } - /** - * Returns the [ECDH](https://en.wikipedia.org/wiki/Elliptic-curve_Diffie-Hellman) shared secret between this - * private key and the `other` key. - * - * The `other` key may be any type of key, a raw public key, a compressed/uncompressed pubic key or aprivate key. - * - * Best practice is usually to use a cryptographic hash on the returned value before using it as a symetric secret. - * - * @example - * - * ```ts - * sign1 = new SigningKey(id('some-secret-1')); - * sign2 = new SigningKey(id('some-secret-2')); - * - * // Notice that privA.computeSharedSecret(pubB)... - * sign1.computeSharedSecret(sign2.publicKey); - * - * // ...is equal to privB.computeSharedSecret(pubA). - * sign2.computeSharedSecret(sign1.publicKey); - * ``` - * - * @param {BytesLike} other - The other key to compute the shared secret with. - * @returns {string} The shared secret. - */ - computeSharedSecret(other) { - const pubKey = SigningKey.computePublicKey(other); - return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey), getBytes(pubKey), false)); - } - /** - * Compute the public key for `key`, optionally `compressed`. - * - * The `key` may be any type of key, a raw public key, a compressed/uncompressed public key or private key. - * - * @example - * - * ```ts - * sign = new SigningKey(id('some-secret')); - * - * // Compute the uncompressed public key for a private key - * SigningKey.computePublicKey(sign.privateKey); - * - * // Compute the compressed public key for a private key - * SigningKey.computePublicKey(sign.privateKey, true); - * - * // Compute the uncompressed public key - * SigningKey.computePublicKey(sign.publicKey, false); - * - * // Compute the Compressed a public key - * SigningKey.computePublicKey(sign.publicKey, true); - * ``` - * - * @param {BytesLike} key - The key to compute the public key for. - * @param {boolean} [compressed] - Whether to return the compressed public key. - * @returns {string} The public key. - */ - static computePublicKey(key, compressed) { - let bytes = getBytes(key, 'key'); - // private key - if (bytes.length === 32) { - const pubKey = secp256k1.getPublicKey(bytes, !!compressed); - return hexlify(pubKey); - } - // raw public key; use uncompressed key with 0x04 prefix - if (bytes.length === 64) { - const pub = new Uint8Array(65); - pub[0] = 0x04; - pub.set(bytes, 1); - bytes = pub; - } - const point = secp256k1.ProjectivePoint.fromHex(bytes); - return hexlify(point.toRawBytes(compressed)); - } - /** - * Returns the public key for the private key which produced the `signature` for the given `digest`. - * - * @example - * - * ```ts - * key = new SigningKey(id('some-secret')); - * digest = id('hello world'); - * sig = key.sign(digest); - * - * // Notice the signer public key... - * key.publicKey; - * - * // ...is equal to the recovered public key - * SigningKey.recoverPublicKey(digest, sig); - * ``` - * - * @param {BytesLike} digest - The data that was signed. - * @param {SignatureLike} signature - The signature of the data. - * @returns {string} The public key. - */ - static recoverPublicKey(digest, signature) { - assertArgument(dataLength(digest) === 32, 'invalid digest length', 'digest', digest); - const sig = Signature.from(signature); - let secpSig = secp256k1.Signature.fromCompact(getBytesCopy(concat([sig.r, sig.s]))); - secpSig = secpSig.addRecoveryBit(sig.yParity); - const pubKey = secpSig.recoverPublicKey(getBytesCopy(digest)); - assertArgument(pubKey != null, 'invalid signautre for digest', 'signature', signature); - return '0x' + pubKey.toHex(false); - } - /** - * Returns the point resulting from adding the ellipic curve points `p0` and `p1`. - * - * This is not a common function most developers should require, but can be useful for certain privacy-specific - * techniques. - * - * For example, it is used by [**QuaiHDWallet**](../classes/QuaiHDWallet) to compute child addresses from parent - * public keys and chain codes. - * - * @param {BytesLike} p0 - The first point to add. - * @param {BytesLike} p1 - The second point to add. - * @param {boolean} [compressed] - Whether to return the compressed public key. - * @returns {string} The sum of the points. - */ - static addPoints(p0, p1, compressed) { - const pub0 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p0).substring(2)); - const pub1 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p1).substring(2)); - return '0x' + pub0.add(pub1).toHex(!!compressed); - } - } - - // BigInt / Uint8Array versions of Crypto functions that do not require point - // math. If your JS interpreter has BigInt, you can use all of these. If not, - // you'll need to either shim it in or override more of these functions. - // Idea from noble-secp256k1, be nice to bad JS parsers - const _0n = BigInt(0); - const _1n = BigInt(1); - const _2n = BigInt(2); - const _3n = BigInt(3); - const _5n = BigInt(5); - const _7n = BigInt(7); - const _64n = BigInt(64); - const _64mask = BigInt('0xFFFFFFFFFFFFFFFF'); - const CURVE = { - b: BigInt(7), - P: BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'), - n: BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141'), - }; - // Big Endian - function read32b(bytes) { - if (bytes.length !== 32) - throw new Error(`Expected 32-bytes, not ${bytes.length}`); - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length); - let b = view.getBigUint64(0); - for (let offs = 8; offs < bytes.length; offs += 8) { - b <<= _64n; - b += view.getBigUint64(offs); - } - return b; - } - function write32b(num, dest = new Uint8Array(32)) { - // All input values are modulo P or n, so no bounds checking needed - const view = new DataView(dest.buffer, dest.byteOffset, dest.length); - for (let offs = 24; offs >= 0; offs -= 8) { - view.setBigUint64(offs, num & _64mask); - num >>= _64n; - } - return dest; - } - function readScalar(bytes) { - const a = read32b(bytes); - if (a >= CURVE.n) - throw new Error('Expected value mod n'); - return a; - } - function readSecret(bytes) { - const a = readScalar(bytes); - if (a === 0n) - throw new Error('Expected non-zero'); - return a; - } - // The short Weierstrass form curve equation simplifes to y^2 = x^3 + 7. - function secp256k1Right(x) { - const x2 = (x * x) % CURVE.P; - const x3 = (x2 * x) % CURVE.P; - return (x3 + CURVE.b) % CURVE.P; - } - // For prime P, the Jacobi Symbol of 'a' is 1 if and only if 'a' is a quadratic - // residue mod P, ie. there exists a value 'x' for whom x^2 = a. - function jacobiSymbol(a) { - if (a === _0n) - return 0; // Vanishingly improbable - let p = CURVE.P; - let sign = 1; - // This algorithm is fairly heavily optimized, so don't simplify it w/o benchmarking - for (;;) { - let and3; - // Handle runs of zeros efficiently w/o flipping sign each time - for (and3 = a & _3n; and3 === _0n; a >>= _2n, and3 = a & _3n) - ; - // If there's one more zero, shift it off and flip the sign - if (and3 === _2n) { - a >>= _1n; - const pand7 = p & _7n; - if (pand7 === _3n || pand7 === _5n) - sign = -sign; - } - if (a === _1n) - break; - if ((_3n & a) === _3n && (_3n & p) === _3n) - sign = -sign; - [a, p] = [p % a, a]; - } - return sign > 0 ? 1 : -1; - } - function isPoint(p) { - if (p.length < 33) - return false; - const t = p[0]; - if (p.length === 33) { - return (t === 0x02 || t === 0x03) && isXOnlyPoint(p.subarray(1)); - } - if (t !== 0x04 || p.length !== 65) - return false; - const x = read32b(p.subarray(1, 33)); - if (x === _0n) - return false; - if (x >= CURVE.P) - return false; - const y = read32b(p.subarray(33)); - if (y === _0n) - return false; - if (y >= CURVE.P) - return false; - const left = (y * y) % CURVE.P; - const right = secp256k1Right(x); - return left === right; - } - function isXOnlyPoint(p) { - if (p.length !== 32) - return false; - const x = read32b(p); - if (x === _0n) - return false; - if (x >= CURVE.P) - return false; - const y2 = secp256k1Right(x); - return jacobiSymbol(y2) === 1; // If sqrt(y^2) exists, x is on the curve. - } - function scalarAdd(a, b) { - const aN = readScalar(a); - const bN = readScalar(b); - const sum = (aN + bN) % CURVE.n; - return write32b(sum); - } - function scalarMultiply(a, b) { - const aN = readScalar(a); - const bN = readScalar(b); - const product = (aN * bN) % CURVE.n; - return write32b(product); - } - function scalarNegate(a) { - const aN = readScalar(a); - const negated = aN === _0n ? _0n : CURVE.n - aN; - return write32b(negated); - } - function scalarMod(a) { - const aN = read32b(a); - const remainder = aN % CURVE.n; - return write32b(remainder); - } - function isScalar(t) { - try { - readScalar(t); - return true; - } - catch { - return false; - } - } - function isSecret(s) { - try { - readSecret(s); - return true; - } - catch { - return false; - } - } - function pointNegate(p) { - // hasEvenY does basic structure check, so start there - const even = hasEvenY(p); - // `from` because node.Buffer.slice doesn't copy but looks like a Uint8Array - const negated = Uint8Array.from(p); - if (p.length === 33) { - negated[0] = even ? 3 : 2; - } - else if (p.length === 65) { - const y = read32b(p.subarray(33)); - if (y >= CURVE.P) - throw new Error('Expected Y coordinate mod P'); - const minusY = y === _0n ? _0n : CURVE.P - y; - write32b(minusY, negated.subarray(33)); - } - return negated; - } - function pointX(p) { - if (p.length === 32) - return p; - hasEvenY(p); // hasEvenY throws if not well structured - return p.slice(1, 33); - } - function hasEvenY(p) { - if (p.length === 33) { - if (p[0] === 2) - return true; - else if (p[0] === 3) - return false; - else - throw new Error('Wrong first byte to be a point'); - } - if (p.length === 65) { - if (p[0] !== 4) - throw new Error('Wrong first byte to be point'); - return p[64] % 2 === 0; - } - throw new Error('Wrong length to be a point'); - } - function pointMultiplyUnsafe(p, a, compress) { - try { - const product = secp256k1.ProjectivePoint.fromHex(p).multiplyAndAddUnsafe(secp256k1.ProjectivePoint.ZERO, BigInt(`0x${Buffer.from(a).toString('hex')}`), BigInt(1)); - if (!product) - return null; - return product.toRawBytes(compress); - } - catch { - return null; - } - } - function pointMultiplyAndAddUnsafe(p1, a, p2, compress) { - try { - const p2p = secp256k1.ProjectivePoint.fromHex(p2); - const p = secp256k1.ProjectivePoint.fromHex(p1).multiplyAndAddUnsafe(p2p, BigInt(`0x${Buffer.from(a).toString('hex')}`), BigInt(1)); - if (!p) - return null; - return p.toRawBytes(compress); - } - catch { - return null; - } - } - function pointAdd(a, b, compress) { - try { - return secp256k1.ProjectivePoint.fromHex(a).add(secp256k1.ProjectivePoint.fromHex(b)).toRawBytes(compress); - } - catch { - return null; - } - } - function pointAddTweak(p, tweak, compress) { - try { - const P = secp256k1.ProjectivePoint.fromHex(p); - const t = readSecret(tweak); - const Q = secp256k1.ProjectivePoint.BASE.multiplyAndAddUnsafe(P, t, 1n); - if (!Q) - throw new Error('Tweaked point at infinity'); - return Q.toRawBytes(compress); - } - catch { - return null; - } - } - function pointCompress(p, compress = true) { - return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(compress); - } - function liftX(p) { - try { - return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(false); - } - catch { - return null; - } - } - function getPublicKey(s, compress) { - try { - return secp256k1.getPublicKey(s, compress); - } - catch { - return null; - } - } - function taggedHash(tag, ...messages) { - return schnorr.utils.taggedHash(tag, ...messages); - } - function sha256Hash(...messages) { - const h = sha256$1.create(); - for (const message of messages) - h.update(message); - return h.digest(); - } - const musigCrypto = { - read32b, - write32b, - readScalar, - readSecret, - secp256k1Right, - jacobiSymbol, - isPoint, - isXOnlyPoint, - scalarAdd, - scalarMultiply, - scalarNegate, - scalarMod, - isScalar, - isSecret, - pointNegate, - pointX, - hasEvenY, - pointMultiplyUnsafe, - pointMultiplyAndAddUnsafe, - pointAdd, - pointAddTweak, - pointCompress, - liftX, - getPublicKey, - taggedHash, - sha256: sha256Hash, - }; - - /** - * A fundamental building block of Ethereum is the underlying cryptographic primitives. - */ - /** - * Once called, prevents any future change to the underlying cryptographic primitives using the `.register` feature for - * hooks. - * - * @category Crypto - */ - function lock() { - computeHmac.lock(); - keccak256.lock(); - pbkdf2.lock(); - randomBytes.lock(); - ripemd160.lock(); - scrypt.lock(); - scryptSync.lock(); - sha256.lock(); - sha512.lock(); - randomBytes.lock(); - } - - function formatMixedCaseChecksumAddress(address) { - address = address.toLowerCase(); - const chars = address.substring(2).split(''); - const expanded = new Uint8Array(40); - for (let i = 0; i < 40; i++) { - expanded[i] = chars[i].charCodeAt(0); - } - const hashed = getBytes(keccak256(expanded)); - for (let i = 0; i < 40; i += 2) { - if (hashed[i >> 1] >> 4 >= 8) { - chars[i] = chars[i].toUpperCase(); - } - if ((hashed[i >> 1] & 0x0f) >= 8) { - chars[i + 1] = chars[i + 1].toUpperCase(); - } - } - return '0x' + chars.join(''); - } - /** - * Returns a normalized and checksumed address for `address`. This accepts non-checksum addressesa and checksum - * addresses. - * - * The checksum in Quai uses the capitalization (upper-case vs lower-case) of the characters within an address to encode - * its checksum, which offers, on average, a checksum of 15-bits. - * - * If `address` contains both upper-case and lower-case, it is assumed to already be a checksum address and its checksum - * is validated, and if the address fails its expected checksum an error is thrown. - * - * If you wish the checksum of `address` to be ignore, it should be converted to lower-case (i.e. `.toLowercase()`) - * before being passed in. This should be a very rare situation though, that you wish to bypass the safeguards in place - * to protect against an address that has been incorrectly copied from another source. - * - * @category Address - * @example - * - * ```js - * // Adds the checksum (via upper-casing specific letters) - * getAddress('0x8ba1f109551bd432803012645ac136ddd64dba72'); - * - * // Throws an error if an address contains mixed case, - * // but the checksum fails - * getAddress('0x8Ba1f109551bD432803012645Ac136ddd64DBA72'); - * ``` - */ - function getAddress(address) { - assertArgument(typeof address === 'string', 'invalid address', 'address', address); - if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { - // Missing the 0x prefix - if (!address.startsWith('0x')) { - address = '0x' + address; - } - const result = formatMixedCaseChecksumAddress(address); - // If original address is mix cased and recomputed version doesn't - // match the original this could indicate a potential typo or mispaste. - assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, 'invalid address checksum', 'address', address); - return result; - } - assertArgument(false, 'invalid address string format', 'address', address); - } - function getContractAddress(from, nonce, data) { - const nonceBytes = zeroPadValue(toBeHex(toBigInt(nonce)), 8); - return getAddress(dataSlice(keccak256(concat([getAddress(from), nonceBytes, stripZerosLeft(data)])), 12)); - } - /** - * Returns the address for the `key`. - * - * The key may be any standard form of public key or a private key. - * - * @category Address - * @param {string | SigningKey} key - The key to compute the address for. - * @returns {string} The address. - */ - function computeAddress(key) { - let pubkey; - if (typeof key === 'string') { - pubkey = SigningKey.computePublicKey(key, false); - } - else { - pubkey = key.publicKey; - } - return getAddress(keccak256('0x' + pubkey.substring(4)).substring(26)); - } - /** - * Returns the recovered address for the private key that was used to sign `digest` that resulted in `signature`. - * - * @category Address - * @param {BytesLike} digest - The digest of the message. - * @param {SignatureLike} signature - The signature. - * @returns {string} The address. - */ - function recoverAddress(digest, signature) { - return computeAddress(SigningKey.recoverPublicKey(digest, signature)); - } - - /** - * Returns true if `value` is an object which implements the [**Addressable**](../interfaces/Addressable) interface. - * - * @category Address - * @example - * - * ```js - * // Wallets and AbstractSigner sub-classes - * isAddressable(Wallet.createRandom()); - * - * // Contracts - * contract = new Contract('0x643aA0A61eADCC9Cc202D1915D942d35D005400C', [], provider); - * isAddressable(contract); - * ``` - * - * @param {any} value - The value to check. - * @returns {boolean} True if the value is an Addressable. - */ - function isAddressable(value) { - return value && typeof value.getAddress === 'function'; - } - /** - * Returns true if `value` is a valid address. - * - * @category Address - * @example - * - * ```js - * // Valid address - * isAddress('0x8ba1f109551bD432803012645Ac136ddd64DBA72'); - * - * // Invalid checksum - * isAddress('0x8Ba1f109551bD432803012645Ac136ddd64DBa72'); - * ``` - * - * @param {any} value - The value to check. - * @returns {boolean} True if the value is a valid address. - */ - function isAddress(value) { - try { - getAddress(value); - return true; - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; - } - async function checkAddress(target, promise) { - const result = await promise; - if (result == null || result === '0x0000000000000000000000000000000000000000') { - assertArgument(false, 'invalid AddressLike value; did not resolve to a value address', 'target', target); - } - return result; - } - /** - * Resolves to an address for the `target`, which may be any supported address type, an - * [**Addressable**](../interfaces/Addressable) or a Promise which resolves to an address. - * - * @category Address - * @example - * - * ```js - * addr = '0x6B175474E89094C44Da98b954EedeAC495271d0F'; - * - * // Addresses are return synchronously - * resolveAddress(addr, provider); - * - * // Address promises are resolved asynchronously - * resolveAddress(Promise.resolve(addr)); - * - * // Addressable objects are resolved asynchronously - * contract = new Contract(addr, []); - * resolveAddress(contract, provider); - * ``` - * - * @param {AddressLike} target - The target to resolve to an address. - * @returns {string | Promise} The resolved address. - */ - function resolveAddress(target) { - if (typeof target === 'string') { - if (target.match(/^0x[0-9a-f]{40}$/i)) { - return target; - } - } - else if (isAddressable(target)) { - return checkAddress(target, target.getAddress()); - } - else if (target && typeof target.then === 'function') { - return checkAddress(target, target); - } - assertArgument(false, 'unsupported addressable value', 'target', target); - } - /** - * Checks if the address is a valid mixed case checksummed address. - * - * @category Address - * @param address - The address to validate. - * @returns True if the address is a valid mixed case checksummed address. - */ - function validateAddress(address) { - assertArgument(typeof address === 'string', 'address must be string', 'address', address); - assertArgument(Boolean(address.match(/^(0x)?[0-9a-fA-F]{40}$/)), 'invalid address string format', 'address', address); - assertArgument(formatMixedCaseChecksumAddress(address) === address, 'invalid address checksum', 'address', address); - } - /** - * Checks whether a given address is in the Qi ledger scope by checking the 9th bit of the address. - * - * @category Address - * @param {string} address - The address to check - * @returns {boolean} True if the address is in the Qi ledger scope, false otherwise. - */ - function isQiAddress(address) { - const secondByte = address.substring(4, 6); - const binaryString = parseInt(secondByte, 16).toString(2).padStart(8, '0'); - const isUTXO = binaryString[0] === '1'; - return isUTXO; - } - /** - * Checks whether a given address is in the Quai ledger scope by checking the 9th bit of the address. - * - * @category Address - * @param {string} address - The address to check - * @returns {boolean} True if the address is in the Quai ledger scope, false otherwise. - */ - function isQuaiAddress(address) { - return !isQiAddress(address); - } - - /** - * Retrieves the shard information for a given address based on its byte prefix. The function parses the address to - * extract its byte prefix, then filters the ShardData to find a matching shard entry. If no matching shard is found, it - * returns null. - * - * @category Utils - * @param {string} address - The blockchain address to be analyzed. The address should start with "0x" followed by the - * hexadecimal representation. - * @returns {Object | null} An object containing the shard information, or null if no - */ - function getZoneForAddress(address) { - try { - return toZone(address.slice(0, 4)); - } - catch (error) { - return null; - } - } - /** - * Extracts both zone and UTXO information from a given blockchain address. This function first determines the address's - * zone by its byte prefix, then checks the 9th bit of the address to ascertain if it's a UTXO or non-UTXO address. - * - * @category Utils - * @param {string} address - The blockchain address to be analyzed, expected to start with "0x" followed by its - * hexadecimal representation. - * @returns {Object | null} An object containing the zone and UTXO information, or null if no address is found. - */ - function getAddressDetails(address) { - const isQiLedger = (parseInt(address.substring(4, 5), 16) & 0x1) === exports.Ledger.Qi; - return { zone: toZone(address.substring(0, 4)), ledger: isQiLedger ? exports.Ledger.Qi : exports.Ledger.Quai }; - } - /** - * Determines the transaction type based on the sender and recipient addresses. The function checks if both addresses - * are UTXO addresses, in which case it returns 2. If only the sender address is a UTXO address, it returns 1. - * Otherwise, it returns 0. - * - * @category Utils - * @param {string | null} from - The sender address. If null, the function returns 0. - * @param {string | null} to - The recipient address. If null, the function returns 0. - * @returns {number} The transaction type based on the addresses. - */ - function getTxType(from, to) { - if (from === null || to === null) - return 0; - const senderAddressIsQi = isQiAddress(from); - const recipientAddressIsQi = isQiAddress(to); - switch (true) { - case senderAddressIsQi && recipientAddressIsQi: - return 2; - case senderAddressIsQi && !recipientAddressIsQi: - return 1; - default: - return 0; - } - } - /** - * Location of a chain within the Quai hierarchy - * - * Prime = [] region[0] = [0] zone[1,2] = [1, 2] - * - * @param shard - The shard to get the location for - * @returns The location of the chain within the Quai hierarchy - */ - function getNodeLocationFromZone(zone) { - const zoneId = zone.slice(2); - if (zoneId.length > 2) { - throw new Error(`Invalid zone: ${zone}`); - } - else if (zoneId.length === 0) { - return []; - } - return zoneId.split('').map(Number); - } - function getZoneFromNodeLocation(location) { - if (location.length > 2) { - throw new Error('Invalid location'); - } - return toZone(`0x${location.join('')}`); - } - - /** - * @ignore - */ - const WordSize = 32; - const Padding = new Uint8Array(WordSize); - // Properties used to immediate pass through to the underlying object - // - `then` is used to detect if an object is a Promise for await - const passProperties$1 = ['then']; - const _guard$5 = {}; - function throwError(name, error) { - const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`); - wrapped.error = error; - throw wrapped; - } - /** - * A {@link Result | **Result**} is a sub-class of Array, which allows accessing any of its values either positionally by - * its index or, if keys are provided by its name. - * - * @category Application Binary Interface - */ - class Result extends Array { - #names; - /** - * @ignore - */ - constructor(...args) { - // To properly sub-class Array so the other built-in - // functions work, the constructor has to behave fairly - // well. So, in the event we are created via fromItems() - // we build the read-only Result object we want, but on - // any other input, we use the default constructor - // constructor(guard: any, items: Array, keys?: Array); - const guard = args[0]; - let items = args[1]; - let names = (args[2] || []).slice(); - let wrap = true; - if (guard !== _guard$5) { - items = args; - names = []; - wrap = false; - } - // Can't just pass in ...items since an array of length 1 - // is a special case in the super. - super(items.length); - items.forEach((item, index) => { - this[index] = item; - }); - // Find all unique keys - const nameCounts = names.reduce((accum, name) => { - if (typeof name === 'string') { - accum.set(name, (accum.get(name) || 0) + 1); - } - return accum; - }, new Map()); - // Remove any key thats not unique - this.#names = Object.freeze(items.map((item, index) => { - const name = names[index]; - if (name != null && nameCounts.get(name) === 1) { - return name; - } - return null; - })); - if (!wrap) { - return; - } - // A wrapped Result is immutable - Object.freeze(this); - // Proxy indices and names so we can trap deferred errors - return new Proxy(this, { - get: (target, prop, receiver) => { - if (typeof prop === 'string') { - // Index accessor - if (prop.match(/^[0-9]+$/)) { - const index = getNumber(prop, '%index'); - if (index < 0 || index >= this.length) { - throw new RangeError('out of result range'); - } - const item = target[index]; - if (item instanceof Error) { - throwError(`index ${index}`, item); - } - return item; - } - // Pass important checks (like `then` for Promise) through - if (passProperties$1.indexOf(prop) >= 0) { - return Reflect.get(target, prop, receiver); - } - const value = target[prop]; - if (value instanceof Function) { - // Make sure functions work with private variables - // See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy#no_private_property_forwarding - return function (...args) { - return value.apply(this === receiver ? target : this, args); - }; - } - else if (!(prop in target)) { - // Possible name accessor - return target.getValue.apply(this === receiver ? target : this, [prop]); - } - } - return Reflect.get(target, prop, receiver); - }, - }); - } - /** - * Returns the Result as a normal Array. - * - * This will throw if there are any outstanding deferred errors. - */ - toArray() { - const result = []; - this.forEach((item, index) => { - if (item instanceof Error) { - throwError(`index ${index}`, item); - } - result.push(item); - }); - return result; - } - /** - * Returns the Result as an Object with each name-value pair. - * - * This will throw if any value is unnamed, or if there are any outstanding deferred errors. - */ - toObject() { - return this.#names.reduce( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - (accum, name, index) => { - assert(name != null, 'value at index ${ index } unnamed', 'UNSUPPORTED_OPERATION', { - operation: 'toObject()', - }); - // Add values for names that don't conflict - if (!(name in accum)) { - accum[name] = this.getValue(name); - } - return accum; - }, {}); - } - /** - * @ignore - */ - slice(start, end) { - if (start == null) { - start = 0; - } - if (start < 0) { - start += this.length; - if (start < 0) { - start = 0; - } - } - if (end == null) { - end = this.length; - } - if (end < 0) { - end += this.length; - if (end < 0) { - end = 0; - } - } - if (end > this.length) { - end = this.length; - } - const result = [], names = []; - for (let i = start; i < end; i++) { - result.push(this[i]); - names.push(this.#names[i]); - } - return new Result(_guard$5, result, names); - } - /** - * @ignore - */ - filter(callback, thisArg) { - const result = [], names = []; - for (let i = 0; i < this.length; i++) { - const item = this[i]; - if (item instanceof Error) { - throwError(`index ${i}`, item); - } - if (callback.call(thisArg, item, i, this)) { - result.push(item); - names.push(this.#names[i]); - } - } - return new Result(_guard$5, result, names); - } - /** - * @ignore - */ - // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint - map(callback, thisArg) { - const result = []; - for (let i = 0; i < this.length; i++) { - const item = this[i]; - if (item instanceof Error) { - throwError(`index ${i}`, item); - } - result.push(callback.call(thisArg, item, i, this)); - } - return result; - } - /** - * Returns the value for `name`. - * - * Since it is possible to have a key whose name conflicts with a method on a {@link Result | **Result**} or its - * superclass Array, or any JavaScript keyword, this ensures all named values are still accessible by name. - * - * @param {string} name - The name of the value to retrieve. - * - * @returns The value for `name`. - */ - getValue(name) { - const index = this.#names.indexOf(name); - if (index === -1) { - return undefined; - } - const value = this[index]; - if (value instanceof Error) { - throwError(`property ${JSON.stringify(name)}`, value.error); - } - return value; - } - /** - * Creates a new {@link Result | **Result**} for `items` with each entry also accessible by its corresponding name in - * `keys`. - * - * @param {any[]} items - The items to include in the Result. - * @param {(null | string)[]} [keys] - The names for each item in `items`. - * - * @returns The new Result. - */ - static fromItems(items, keys) { - return new Result(_guard$5, items, keys); - } - } - /** - * Returns all errors found in a {@link Result | **Result**}. - * - * Since certain errors encountered when creating a {@link Result | **Result**} do not impact the ability to continue - * parsing data, they are deferred until they are actually accessed. Hence a faulty string in an Event that is never - * used does not impact the program flow. - * - * However, sometimes it may be useful to access, identify or validate correctness of a {@link Result | **Result**}. - * - * @category Application Binary Interface - * @param {Result} result - The Result to check for errors. - * - * @returns An array of objects with the path to the error and the error itself. - */ - function checkResultErrors(result) { - // Find the first error (if any) - const errors = []; - const checkErrors = function (path, object) { - if (!Array.isArray(object)) { - return; - } - for (const key in object) { - const childPath = path.slice(); - childPath.push(key); - try { - checkErrors(childPath, object[key]); - } - catch (error) { - errors.push({ path: childPath, error: error }); - } - } - }; - checkErrors([], result); - return errors; - } - function getValue$1(value) { - let bytes = toBeArray(value); - assert(bytes.length <= WordSize, 'value out-of-bounds', 'BUFFER_OVERRUN', { - buffer: bytes, - length: WordSize, - offset: bytes.length, - }); - if (bytes.length !== WordSize) { - bytes = getBytesCopy(concat([Padding.slice(bytes.length % WordSize), bytes])); - } - return bytes; - } - /** - * @ignore - */ - class Coder { - // The coder name: - // - address, uint256, tuple, array, etc. - name; - // The fully expanded type, including composite types: - // - address, uint256, tuple(address,bytes), uint256[3][4][], etc. - type; - // The localName bound in the signature, in this example it is "baz": - // - tuple(address foo, uint bar) baz - localName; - // Whether this type is dynamic: - // - Dynamic: bytes, string, address[], tuple(boolean[]), etc. - // - Not Dynamic: address, uint256, boolean[3], tuple(address, uint8) - dynamic; - constructor(name, type, localName, dynamic) { - defineProperties(this, { name, type, localName, dynamic }, { - name: 'string', - type: 'string', - localName: 'string', - dynamic: 'boolean', - }); - } - _throwError(message, value) { - assertArgument(false, message, this.localName, value); - } - } - /** - * @ignore - */ - class Writer { - // An array of WordSize lengthed objects to concatenation - #data; - #dataLength; - constructor() { - this.#data = []; - this.#dataLength = 0; - } - get data() { - return concat(this.#data); - } - get length() { - return this.#dataLength; - } - #writeData(data) { - this.#data.push(data); - this.#dataLength += data.length; - return data.length; - } - appendWriter(writer) { - return this.#writeData(getBytesCopy(writer.data)); - } - // Arrayish item; pad on the right to *nearest* WordSize - writeBytes(value) { - let bytes = getBytesCopy(value); - const paddingOffset = bytes.length % WordSize; - if (paddingOffset) { - bytes = getBytesCopy(concat([bytes, Padding.slice(paddingOffset)])); - } - return this.#writeData(bytes); - } - // Numeric item; pad on the left *to* WordSize - writeValue(value) { - return this.#writeData(getValue$1(value)); - } - // Inserts a numeric place-holder, returning a callback that can - // be used to asjust the value later - writeUpdatableValue() { - const offset = this.#data.length; - this.#data.push(Padding); - this.#dataLength += WordSize; - return (value) => { - this.#data[offset] = getValue$1(value); - }; - } - } - /** - * @ignore - */ - class Reader { - // Allows incomplete unpadded data to be read; otherwise an error - // is raised if attempting to overrun the buffer. This is required - // to deal with an old Solidity bug, in which event data for - // external (not public thoguh) was tightly packed. - allowLoose; - #data; - #offset; - #bytesRead; - #parent; - #maxInflation; - constructor(data, allowLoose, maxInflation) { - defineProperties(this, { allowLoose: !!allowLoose }); - this.#data = getBytesCopy(data); - this.#bytesRead = 0; - this.#parent = null; - this.#maxInflation = maxInflation != null ? maxInflation : 1024; - this.#offset = 0; - } - get data() { - return hexlify(this.#data); - } - get dataLength() { - return this.#data.length; - } - get consumed() { - return this.#offset; - } - get bytes() { - return new Uint8Array(this.#data); - } - #incrementBytesRead(count) { - if (this.#parent) { - return this.#parent.#incrementBytesRead(count); - } - this.#bytesRead += count; - // Check for excessive inflation (see: #4537) - assert(this.#maxInflation < 1 || this.#bytesRead <= this.#maxInflation * this.dataLength, - // eslint-disable-next-line no-useless-escape - `compressed ABI data exceeds inflation ratio of ${this.#maxInflation} ( see: https:/\/github.com/ethers-io/ethers.js/issues/4537 )`, 'BUFFER_OVERRUN', { - buffer: getBytesCopy(this.#data), - offset: this.#offset, - length: count, - info: { - bytesRead: this.#bytesRead, - dataLength: this.dataLength, - }, - }); - } - #peekBytes(offset, length, loose) { - let alignedLength = Math.ceil(length / WordSize) * WordSize; - if (this.#offset + alignedLength > this.#data.length) { - if (this.allowLoose && loose && this.#offset + length <= this.#data.length) { - alignedLength = length; - } - else { - assert(false, 'data out-of-bounds', 'BUFFER_OVERRUN', { - buffer: getBytesCopy(this.#data), - length: this.#data.length, - offset: this.#offset + alignedLength, - }); - } - } - return this.#data.slice(this.#offset, this.#offset + alignedLength); - } - // Create a sub-reader with the same underlying data, but offset - subReader(offset) { - const reader = new Reader(this.#data.slice(this.#offset + offset), this.allowLoose, this.#maxInflation); - reader.#parent = this; - return reader; - } - // Read bytes - readBytes(length, loose) { - const bytes = this.#peekBytes(0, length, !!loose); - this.#incrementBytesRead(length); - this.#offset += bytes.length; - // @TODO: Make sure the length..end bytes are all 0? - return bytes.slice(0, length); - } - // Read a numeric values - readValue() { - return toBigInt(this.readBytes(WordSize)); - } - readIndex() { - return toNumber(this.readBytes(WordSize)); - } - } - - // http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed - /** - * Returns the address that would result from a `CREATE` for `tx`. - * - * This can be used to compute the address a contract will be deployed to by an EOA when sending a deployment - * transaction (i.e. when the `to` address is `null`). - * - * This can also be used to compute the address a contract will be deployed to by a contract, by using the contract's - * address as the `to` and the contract's nonce. - * - * @category Address - * @example - * - * ```js - * from = '0x8ba1f109551bD432803012645Ac136ddd64DBA72'; - * nonce = 5; - * - * getCreateAddress({ from, nonce }); - * ``` - * - * @param {object} tx - The transaction object. - * @param {string} tx.from - The address of the sender. - * @param {BigNumberish} tx.nonce - The nonce of the sender. - * @param {string} [tx.data] - The data of the transaction. - */ - function getCreateAddress(tx) { - const from = getAddress(tx.from); - const nonce = getBigInt(tx.nonce, 'tx.nonce'); - const nonceBytes = bigEndianNonce(nonce); - const fromBytes = getBytes(from); - const codeBytes = tx.data ? getBytes(tx.data) : new Uint8Array(); - const concatenated = new Uint8Array([...fromBytes, ...nonceBytes, ...codeBytes]); - const hash = keccak256(concatenated); - return getAddress(dataSlice(hash, 12)); - } - /** - * Returns the address that would result from a `CREATE2` operation with the given `from`, `salt` and `initCodeHash`. - * - * To compute the `initCodeHash` from a contract's init code, use the [**keccak256**](../functions/keccak256) function. - * - * For a quick overview and example of `CREATE2`, see [Wisps: The Magical World of - * Create2](https://blog.ricmoo.com/wisps-the-magical-world-of-create2-5c2177027604). - * - * @category Address - * @example - * - * ```js - * // The address of the contract - * from = '0x8ba1f109551bD432803012645Ac136ddd64DBA72'; - * - * // The salt - * salt = id('HelloWorld'); - * - * // The hash of the initCode - * initCode = '0x6394198df16000526103ff60206004601c335afa6040516060f3'; - * initCodeHash = keccak256(initCode); - * - * getCreate2Address(from, salt, initCodeHash); - * ``` - * - * @param {string} _from - The address of the sender. - * @param {BytesLike} _salt - The salt value. - * @param {BytesLike} _initCodeHash - The hash of the init code. - * @returns {string} The computed address. - * @throws {Error} If the salt is not exactly 32 bytes long. - * @throws {Error} If the initCodeHash is not exactly 32 bytes long. - */ - function getCreate2Address(_from, _salt, _initCodeHash) { - const from = getAddress(_from); - const salt = getBytes(_salt, 'salt'); - const initCodeHash = getBytes(_initCodeHash, 'initCodeHash'); - assertArgument(salt.length === 32, 'salt must be 32 bytes', 'salt', _salt); - assertArgument(initCodeHash.length === 32, 'initCodeHash must be 32 bytes', 'initCodeHash', _initCodeHash); - return getAddress(dataSlice(keccak256(concat(['0xff', from, salt, initCodeHash])), 12)); - } - // Helper function to convert a BigInt nonce to a big-endian byte array - function bigEndianNonce(nonce) { - const buffer = new ArrayBuffer(8); - const view = new DataView(buffer); - view.setBigUint64(0, nonce, false); - return new Uint8Array(buffer); - } - - /** - * A Typed object allows a value to have its type explicitly specified. - * - * For example, in Solidity, the value `45` could represent a `uint8` or a `uint256`. The value `0x1234` could represent - * a `bytes2` or `bytes`. - * - * Since JavaScript has no meaningful way to explicitly inform any APIs which what the type is, this allows transparent - * interoperation with Soldity. - * - * @category Application Binary Interface - */ - const _guard$4 = {}; - function n(value, width) { - let signed = false; - if (width < 0) { - signed = true; - width *= -1; - } - // @TODO: Check range is valid for value - return new Typed(_guard$4, `${signed ? '' : 'u'}int${width}`, value, { signed, width }); - } - function b(value, size) { - // @TODO: Check range is valid for value - return new Typed(_guard$4, `bytes${size ? size : ''}`, value, { size }); - } - const _typedSymbol = Symbol.for('_quais_typed'); - /** - * The **Typed** class to wrap values providing explicit type information. - * - * @category Application Binary Interface - */ - class Typed { - /** - * The type, as a Solidity-compatible type. - */ - type; - /** - * The actual value. - */ - value; - #options; - /** - * @ignore - */ - _typedSymbol; - /** - * @ignore - */ - constructor(guard, type, value, options) { - if (options == null) { - options = null; - } - assertPrivate(_guard$4, guard, 'Typed'); - defineProperties(this, { _typedSymbol, type, value }); - this.#options = options; - // Check the value is valid - this.format(); - } - /** - * Format the type as a Human-Readable type. - * - * @returns The human-readable type for the provided type. - * @throws If the type is array or dynamic array. - */ - format() { - if (this.type === 'array') { - throw new Error(''); - } - else if (this.type === 'dynamicArray') { - throw new Error(''); - } - else if (this.type === 'tuple') { - return `tuple(${this.value.map((v) => v.format()).join(',')})`; - } - return this.type; - } - /** - * The default value returned by this type. - * - * @returns The default value for this type. - */ - defaultValue() { - return 0; - } - /** - * The minimum value for numeric types. - * - * @returns The minimum value for the provided numeric type. - */ - minValue() { - return 0; - } - /** - * The maximum value for numeric types. - * - * @returns The maximum value for the provided numeric type. - */ - maxValue() { - return 0; - } - /** - * Returns whether this is a {@link TypedBigInt | **TypedBigInt**}. If true, a type guard is provided. - * - * @returns `true` if this is a big integer. - */ - isBigInt() { - return !!this.type.match(/^u?int[0-9]+$/); - } - /** - * Returns whether this is a {@link TypedData | **TypedData**}. If true, a type guard is provided. - * - * @returns {boolean} `true` if this is a number. - */ - isData() { - return this.type.startsWith('bytes'); - } - /** - * Return whether this is a {@link TypedString | **TypedString**}. If true, a type guard is provided. - * - * @returns {boolean} `true` if this is a string. - */ - isString() { - return this.type === 'string'; - } - /** - * Returns the tuple name. - * - * @returns {boolean} The tuple name if this is a tuple. - * @throws If this is not a tuple. - */ - get tupleName() { - if (this.type !== 'tuple') { - throw TypeError('not a tuple'); - } - return this.#options; - } - /** - * Returns the length of a typed array. - * - * @returns {number} The length of the array type or `-1` if it is dynamic. - * @throws If this is not an array. - */ - get arrayLength() { - if (this.type !== 'array') { - throw TypeError('not an array'); - } - if (this.#options === true) { - return -1; - } - if (this.#options === false) { - return this.value.length; - } - return null; - } - /** - * Returns a new **Typed** of `type` with the `value`. - * - * @param {string} type - The type to use. - * @param {any} value - The value to use. - */ - static from(type, value) { - return new Typed(_guard$4, type, value); - } - /** - * Return a new `uint8` type for v. - * - * @param {BigNumberish} v - The value to convert to a `uint8`. - * - * @returns {uint8} A new `uint8` type for `v`. - */ - static uint8(v) { - return n(v, 8); - } - /** - * Return a new `uint16` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint16`. - * - * @returns A new `uint16` type for `v`. - */ - static uint16(v) { - return n(v, 16); - } - /** - * Return a new `uint24` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint24`. - * - * @returns A new `uint24` type for `v`. - */ - static uint24(v) { - return n(v, 24); - } - /** - * Return a new `uint32` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint32`. - * - * @returns A new `uint32` type for `v`. - */ - static uint32(v) { - return n(v, 32); - } - /** - * Return a new `uint40` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint40`. - * - * @returns A new `uint40` type for `v`. - */ - static uint40(v) { - return n(v, 40); - } - /** - * Return a new `uint48` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint48`. - * - * @returns A new `uint48` type for `v`. - */ - static uint48(v) { - return n(v, 48); - } - /** - * Return a new `uint56` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint56`. - * - * @returns A new `uint56` type for `v`. - */ - static uint56(v) { - return n(v, 56); - } - /** - * Return a new `uint64` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint64`. - * - * @returns A new `uint64` type for `v`. - */ - static uint64(v) { - return n(v, 64); - } - /** - * Return a new `uint72` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint72`. - * - * @returns A new `uint72` type for `v`. - */ - static uint72(v) { - return n(v, 72); - } - /** - * Return a new `uint80` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint80`. - * - * @returns A new `uint80` type for `v`. - */ - static uint80(v) { - return n(v, 80); - } - /** - * Return a new `uint88` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint88`. - * - * @returns A new `uint88` type for `v`. - */ - static uint88(v) { - return n(v, 88); - } - /** - * Return a new `uint96` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint96`. - * - * @returns A new `uint96` type for `v`. - */ - static uint96(v) { - return n(v, 96); - } - /** - * Return a new `uint104` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint104`. - * - * @returns A new `uint104` type for `v`. - */ - static uint104(v) { - return n(v, 104); - } - /** - * Return a new `uint112` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint112`. - * - * @returns A new `uint112` type for `v`. - */ - static uint112(v) { - return n(v, 112); - } - /** - * Return a new `uint120` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint120`. - * - * @returns A new `uint120` type for `v`. - */ - static uint120(v) { - return n(v, 120); - } - /** - * Return a new `uint128` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint128`. - * - * @returns A new `uint128` type for `v`. - */ - static uint128(v) { - return n(v, 128); - } - /** - * Return a new `uint136` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint136`. - * - * @returns A new `uint136` type for `v`. - */ - static uint136(v) { - return n(v, 136); - } - /** - * Return a new `uint144` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint144`. - * - * @returns A new `uint144` type for `v`. - */ - static uint144(v) { - return n(v, 144); - } - /** - * Return a new `uint152` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint152`. - * - * @returns A new `uint152` type for `v`. - */ - static uint152(v) { - return n(v, 152); - } - /** - * Return a new `uint160` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint160`. - * - * @returns A new `uint160` type for `v`. - */ - static uint160(v) { - return n(v, 160); - } - /** - * Return a new `uint168` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint168`. - * - * @returns A new `uint168` type for `v`. - */ - static uint168(v) { - return n(v, 168); - } - /** - * Return a new `uint176` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint176`. - * - * @returns A new `uint176` type for `v`. - */ - static uint176(v) { - return n(v, 176); - } - /** - * Return a new `uint184` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint184`. - * - * @returns A new `uint184` type for `v`. - */ - static uint184(v) { - return n(v, 184); - } - /** - * Return a new `uint192` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint192`. - * - * @returns A new `uint192` type for `v`. - */ - static uint192(v) { - return n(v, 192); - } - /** - * Return a new `uint200` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint200`. - * - * @returns A new `uint200` type for `v`. - */ - static uint200(v) { - return n(v, 200); - } - /** - * Return a new `uint208` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint208`. - * - * @returns A new `uint208` type for `v`. - */ - static uint208(v) { - return n(v, 208); - } - /** - * Return a new `uint216` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint216`. - * - * @returns A new `uint216` type for `v`. - */ - static uint216(v) { - return n(v, 216); - } - /** - * Return a new `uint224` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint224`. - * - * @returns A new `uint224` type for `v`. - */ - static uint224(v) { - return n(v, 224); - } - /** - * Return a new `uint232` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint232`. - * - * @returns A new `uint232` type for `v`. - */ - static uint232(v) { - return n(v, 232); - } - /** - * Return a new `uint240` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint240`. - * - * @returns A new `uint240` type for `v`. - */ - static uint240(v) { - return n(v, 240); - } - /** - * Return a new `uint248` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint248`. - * - * @returns A new `uint248` type for `v`. - */ - static uint248(v) { - return n(v, 248); - } - /** - * Return a new `uint256` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint256`. - * - * @returns A new `uint256` type for `v`. - */ - static uint256(v) { - return n(v, 256); - } - /** - * Return a new `uint256` type for `v`. - * - * @param {BigNumberish} v - The value to convert to a `uint256`. - * - * @returns A new `uint256` type for `v`. - */ - static uint(v) { - return n(v, 256); - } - /** - * Return a new `int8` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int8`. - * - * @returns A new `int8` type for `v`. - */ - static int8(v) { - return n(v, -8); - } - /** - * Return a new `int16` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int16`. - * - * @returns A new `int16` type for `v`. - */ - static int16(v) { - return n(v, -16); - } - /** - * Return a new `int24` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int24`. - * - * @returns A new `int24` type for `v`. - */ - static int24(v) { - return n(v, -24); - } - /** - * Return a new `int32` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int32`. - * - * @returns A new `int32` type for `v`. - */ - static int32(v) { - return n(v, -32); - } - /** - * Return a new `int40` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int40`. - * - * @returns A new `int40` type for `v`. - */ - static int40(v) { - return n(v, -40); - } - /** - * Return a new `int48` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int48`. - * - * @returns A new `int48` type for `v`. - */ - static int48(v) { - return n(v, -48); - } - /** - * Return a new `int56` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int56`. - * - * @returns A new `int56` type for `v`. - */ - static int56(v) { - return n(v, -56); - } - /** - * Return a new `int64` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int64`. - * - * @returns A new `int64` type for `v`. - */ - static int64(v) { - return n(v, -64); - } - /** - * Return a new `int72` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int72`. - * - * @returns A new `int72` type for `v`. - */ - static int72(v) { - return n(v, -72); - } - /** - * Return a new `int80` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int80`. - * - * @returns A new `int80` type for `v`. - */ - static int80(v) { - return n(v, -80); - } - /** - * Return a new `int88` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int88`. - * - * @returns A new `int88` type for `v`. - */ - static int88(v) { - return n(v, -88); - } - /** - * Return a new `int96` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int96`. - * - * @returns A new `int96` type for `v`. - */ - static int96(v) { - return n(v, -96); - } - /** - * Return a new `int104` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int104`. - * - * @returns A new `int104` type for `v`. - */ - static int104(v) { - return n(v, -104); - } - /** - * Return a new `int112` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int112`. - * - * @returns A new `int112` type for `v`. - */ - static int112(v) { - return n(v, -112); - } - /** - * Return a new `int120` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int120`. - * - * @returns A new `int120` type for `v`. - */ - static int120(v) { - return n(v, -120); - } - /** - * Return a new `int128` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int128`. - * - * @returns A new `int128` type for `v`. - */ - static int128(v) { - return n(v, -128); - } - /** - * Return a new `int136` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int136`. - * - * @returns A new `int136` type for `v`. - */ - static int136(v) { - return n(v, -136); - } - /** - * Return a new `int144` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int144`. - * - * @returns A new `int144` type for `v`. - */ - static int144(v) { - return n(v, -144); - } - /** - * Return a new `int152` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int152`. - * - * @returns A new `int152` type for `v`. - */ - static int152(v) { - return n(v, -152); - } - /** - * Return a new `int160` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int160`. - * - * @returns A new `int160` type for `v`. - */ - static int160(v) { - return n(v, -160); - } - /** - * Return a new `int168` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int168`. - * - * @returns A new `int168` type for `v`. - */ - static int168(v) { - return n(v, -168); - } - /** - * Return a new `int176` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int176`. - * - * @returns A new `int176` type for `v`. - */ - static int176(v) { - return n(v, -176); - } - /** - * Return a new `int184` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int184`. - * - * @returns A new `int184` type for `v`. - */ - static int184(v) { - return n(v, -184); - } - /** - * Return a new `int192` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int192`. - * - * @returns A new `int192` type for `v`. - */ - static int192(v) { - return n(v, -192); - } - /** - * Return a new `int200` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int200`. - * - * @returns A new `int200` type for `v`. - */ - static int200(v) { - return n(v, -200); - } - /** - * Return a new `int208` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int208`. - * - * @returns A new `int208` type for `v`. - */ - static int208(v) { - return n(v, -208); - } - /** - * Return a new `int216` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int216`. - * - * @returns A new `int216` type for `v`. - */ - static int216(v) { - return n(v, -216); - } - /** - * Return a new `int224` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int224`. - * - * @returns A new `int224` type for `v`. - */ - static int224(v) { - return n(v, -224); - } - /** - * Return a new `int232` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int232`. - * - * @returns A new `int232` type for `v`. - */ - static int232(v) { - return n(v, -232); - } - /** - * Return a new `int240` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int240`. - * - * @returns A new `int240` type for `v`. - */ - static int240(v) { - return n(v, -240); - } - /** - * Return a new `int248` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int248`. - * - * @returns A new `int248` type for `v`. - */ - static int248(v) { - return n(v, -248); - } - /** - * Return a new `int256` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int256`. - * - * @returns A new `int256` type for `v`. - */ - static int256(v) { - return n(v, -256); - } - /** - * Return a new `int256` type for `v`. - * - * @param {BigNumberish} v - The value to convert to an `int256`. - * - * @returns A new `int256` type for `v`. - */ - static int(v) { - return n(v, -256); - } - /** - * Return a new `bytes1` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes1`. - * - * @returns A new `bytes1` type for `v`. - */ - static bytes1(v) { - return b(v, 1); - } - /** - * Return a new `bytes2` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes2`. - * - * @returns A new `bytes2` type for `v`. - */ - static bytes2(v) { - return b(v, 2); - } - /** - * Return a new `bytes3` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes3`. - * - * @returns A new `bytes3` type for `v`. - */ - static bytes3(v) { - return b(v, 3); - } - /** - * Return a new `bytes4` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes4`. - * - * @returns A new `bytes4` type for `v`. - */ - static bytes4(v) { - return b(v, 4); - } - /** - * Return a new `bytes5` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes5`. - * - * @returns A new `bytes5` type for `v`. - */ - static bytes5(v) { - return b(v, 5); - } - /** - * Return a new `bytes6` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes6`. - * - * @returns A new `bytes6` type for `v`. - */ - static bytes6(v) { - return b(v, 6); - } - /** - * Return a new `bytes7` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes7`. - * - * @returns A new `bytes7` type for `v`. - */ - static bytes7(v) { - return b(v, 7); - } - /** - * Return a new `bytes8` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes8`. - * - * @returns A new `bytes8` type for `v`. - */ - static bytes8(v) { - return b(v, 8); - } - /** - * Return a new `bytes9` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes9`. - * - * @returns A new `bytes9` type for `v`. - */ - static bytes9(v) { - return b(v, 9); - } - /** - * Return a new `bytes10` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes10`. - * - * @returns A new `bytes10` type for `v`. - */ - static bytes10(v) { - return b(v, 10); - } - /** - * Return a new `bytes11` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes11`. - * - * @returns A new `bytes11` type for `v`. - */ - static bytes11(v) { - return b(v, 11); - } - /** - * Return a new `bytes12` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes12`. - * - * @returns A new `bytes12` type for `v`. - */ - static bytes12(v) { - return b(v, 12); - } - /** - * Return a new `bytes13` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes13`. - * - * @returns A new `bytes13` type for `v`. - */ - static bytes13(v) { - return b(v, 13); - } - /** - * Return a new `bytes14` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes14`. - * - * @returns A new `bytes14` type for `v`. - */ - static bytes14(v) { - return b(v, 14); - } - /** - * Return a new `bytes15` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes15`. - * - * @returns A new `bytes15` type for `v`. - */ - static bytes15(v) { - return b(v, 15); - } - /** - * Return a new `bytes16` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes16`. - * - * @returns A new `bytes16` type for `v`. - */ - static bytes16(v) { - return b(v, 16); - } - /** - * Return a new `bytes17` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes17`. - * - * @returns A new `bytes17` type for `v`. - */ - static bytes17(v) { - return b(v, 17); - } - /** - * Return a new `bytes18` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes18`. - * - * @returns A new `bytes18` type for `v`. - */ - static bytes18(v) { - return b(v, 18); - } - /** - * Return a new `bytes19` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes19`. - * - * @returns A new `bytes19` type for `v`. - */ - static bytes19(v) { - return b(v, 19); - } - /** - * Return a new `bytes20` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes20`. - * - * @returns A new `bytes20` type for `v`. - */ - static bytes20(v) { - return b(v, 20); - } - /** - * Return a new `bytes21` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes21`. - * - * @returns A new `bytes21` type for `v`. - */ - static bytes21(v) { - return b(v, 21); - } - /** - * Return a new `bytes22` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes22`. - * - * @returns A new `bytes22` type for `v`. - */ - static bytes22(v) { - return b(v, 22); - } - /** - * Return a new `bytes23` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes23`. - * - * @returns A new `bytes23` type for `v`. - */ - static bytes23(v) { - return b(v, 23); - } - /** - * Return a new `bytes24` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes24`. - * - * @returns A new `bytes24` type for `v`. - */ - static bytes24(v) { - return b(v, 24); - } - /** - * Return a new `bytes25` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes25`. - * - * @returns A new `bytes25` type for `v`. - */ - static bytes25(v) { - return b(v, 25); - } - /** - * Return a new `bytes26` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes26`. - * - * @returns A new `bytes26` type for `v`. - */ - static bytes26(v) { - return b(v, 26); - } - /** - * Return a new `bytes27` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes27`. - * - * @returns A new `bytes27` type for `v`. - */ - static bytes27(v) { - return b(v, 27); - } - /** - * Return a new `bytes28` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes28`. - * - * @returns A new `bytes28` type for `v`. - */ - static bytes28(v) { - return b(v, 28); - } - /** - * Return a new `bytes29` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes29`. - * - * @returns A new `bytes29` type for `v`. - */ - static bytes29(v) { - return b(v, 29); - } - /** - * Return a new `bytes30` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes30`. - * - * @returns A new `bytes30` type for `v`. - */ - static bytes30(v) { - return b(v, 30); - } - /** - * Return a new `bytes31` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes31`. - * - * @returns A new `bytes31` type for `v`. - */ - static bytes31(v) { - return b(v, 31); - } - /** - * Return a new `bytes32` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes32`. - * - * @returns A new `bytes32` type for `v`. - */ - static bytes32(v) { - return b(v, 32); - } - /** - * Return a new `address` type for `v`. - * - * @param {BytesLike} v - The value to convert to an `address`. - * - * @returns A new `address` type for `v`. - */ - static address(v) { - return new Typed(_guard$4, 'address', v); - } - /** - * Return a new `bool` type for `v`. - * - * @param {any} v - The value to convert to a `bool`. - * - * @returns A new `bool` type for `v`. - */ - static bool(v) { - return new Typed(_guard$4, 'bool', !!v); - } - /** - * Return a new `bytes` type for `v`. - * - * @param {BytesLike} v - The value to convert to a `bytes`. - * - * @returns A new `bytes` type for `v`. - */ - static bytes(v) { - return new Typed(_guard$4, 'bytes', v); - } - /** - * Return a new `string` type for `v`. - * - * @param {string} v - The value to convert to a `string`. - * - * @returns A new `string` type for `v`. - */ - static string(v) { - return new Typed(_guard$4, 'string', v); - } - /** - * Return a new `array` type for v, allowing dynamic length. - * - * @param {(any | Typed)[]} v - The value to convert to an `array`. - * @param {null | boolean} dynamic - Whether the array is dynamic. - * - * @returns A new `array` type for `v`. - */ - static array(v, dynamic) { - throw new Error('not implemented yet'); - } - /** - * Return a new `tuple` type for v, with the optional name. - * - * @param {(any | Typed)[]} v - The value to convert to a `tuple`. - * @param {string} name - The name of the tuple. - * - * @returns A new `tuple` type for `v`. - */ - static tuple(v, name) { - throw new Error('not implemented yet'); - } - /** - * Return a new `overrides` type with the provided properties. - * - * @param {Record} v - A record containing the properties to be included in the `overrides` type. - * - * @returns A new `overrides` type with the given properties. - */ - static overrides(v) { - return new Typed(_guard$4, 'overrides', Object.assign({}, v)); - } - /** - * Returns true only if `value` is a {@link Typed | **Typed**} instance. - * - * @param {any} value - The value to check. - * - * @returns {boolean} True if `value` is a {@link Typed | **Typed**} instance. - */ - static isTyped(value) { - return value && typeof value === 'object' && '_typedSymbol' in value && value._typedSymbol === _typedSymbol; - } - /** - * If the value is a {@link Typed | **Typed**} instance, validates the underlying value and returns it, otherwise - * returns value directly. - * - * This is useful for functions that with to accept either a {@link Typed | **Typed**} object or values. - * - * @param {Typed | T} value - The value to dereference. - * @param {string} type - The dereferenced value. - */ - static dereference(value, type) { - if (Typed.isTyped(value)) { - if (value.type !== type) { - throw new Error(`invalid type: expected ${type}, got ${value.type}`); - } - return value.value; - } - return value; - } - } - - /** - * @ignore - */ - class AddressCoder extends Coder { - constructor(localName) { - super("address", "address", localName, false); - } - defaultValue() { - return "0x0000000000000000000000000000000000000000"; - } - encode(writer, _value) { - let value = Typed.dereference(_value, "string"); - try { - value = getAddress(value); - } - catch (error) { - return this._throwError(error.message, _value); - } - return writer.writeValue(value); - } - decode(reader) { - return getAddress(toBeHex(reader.readValue(), 20)); - } - } - - /** - * Clones the functionality of an existing Coder, but without a localName - * - * @ignore - */ - class AnonymousCoder extends Coder { - coder; - constructor(coder) { - super(coder.name, coder.type, "_", coder.dynamic); - this.coder = coder; - } - defaultValue() { - return this.coder.defaultValue(); - } - encode(writer, value) { - return this.coder.encode(writer, value); - } - decode(reader) { - return this.coder.decode(reader); - } - } - - /** - * @ignore - */ - function pack(writer, coders, values) { - let arrayValues = []; - if (Array.isArray(values)) { - arrayValues = values; - } - else if (values && typeof (values) === "object") { - let unique = {}; - arrayValues = coders.map((coder) => { - const name = coder.localName; - assert(name, "cannot encode object for signature with missing names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); - assert(!unique[name], "cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { argument: "values", info: { coder }, value: values }); - unique[name] = true; - return values[name]; - }); - } - else { - assertArgument(false, "invalid tuple value", "tuple", values); - } - assertArgument(coders.length === arrayValues.length, "types/value length mismatch", "tuple", values); - let staticWriter = new Writer(); - let dynamicWriter = new Writer(); - let updateFuncs = []; - coders.forEach((coder, index) => { - let value = arrayValues[index]; - if (coder.dynamic) { - // Get current dynamic offset (for the future pointer) - let dynamicOffset = dynamicWriter.length; - // Encode the dynamic value into the dynamicWriter - coder.encode(dynamicWriter, value); - // Prepare to populate the correct offset once we are done - let updateFunc = staticWriter.writeUpdatableValue(); - updateFuncs.push((baseOffset) => { - updateFunc(baseOffset + dynamicOffset); - }); - } - else { - coder.encode(staticWriter, value); - } - }); - // Backfill all the dynamic offsets, now that we know the static length - updateFuncs.forEach((func) => { func(staticWriter.length); }); - let length = writer.appendWriter(staticWriter); - length += writer.appendWriter(dynamicWriter); - return length; - } - /** - * @ignore - */ - function unpack(reader, coders) { - let values = []; - let keys = []; - // A reader anchored to this base - let baseReader = reader.subReader(0); - coders.forEach((coder) => { - let value = null; - if (coder.dynamic) { - let offset = reader.readIndex(); - let offsetReader = baseReader.subReader(offset); - try { - value = coder.decode(offsetReader); - } - catch (error) { - // Cannot recover from this - if (isError(error, "BUFFER_OVERRUN")) { - throw error; - } - value = error; - value.baseType = coder.name; - value.name = coder.localName; - value.type = coder.type; - } - } - else { - try { - value = coder.decode(reader); - } - catch (error) { - // Cannot recover from this - if (isError(error, "BUFFER_OVERRUN")) { - throw error; - } - value = error; - value.baseType = coder.name; - value.name = coder.localName; - value.type = coder.type; - } - } - if (value == undefined) { - throw new Error("investigate"); - } - values.push(value); - keys.push(coder.localName || null); - }); - return Result.fromItems(values, keys); - } - /** - * @ignore - */ - class ArrayCoder extends Coder { - coder; - length; - constructor(coder, length, localName) { - const type = (coder.type + "[" + (length >= 0 ? length : "") + "]"); - const dynamic = (length === -1 || coder.dynamic); - super("array", type, localName, dynamic); - defineProperties(this, { coder, length }); - } - defaultValue() { - // Verifies the child coder is valid (even if the array is dynamic or 0-length) - const defaultChild = this.coder.defaultValue(); - const result = []; - for (let i = 0; i < this.length; i++) { - result.push(defaultChild); - } - return result; - } - encode(writer, _value) { - const value = Typed.dereference(_value, "array"); - if (!Array.isArray(value)) { - this._throwError("expected array value", value); - } - let count = this.length; - if (count === -1) { - count = value.length; - writer.writeValue(value.length); - } - assertArgumentCount(value.length, count, "coder array" + (this.localName ? (" " + this.localName) : "")); - let coders = []; - for (let i = 0; i < value.length; i++) { - coders.push(this.coder); - } - return pack(writer, coders, value); - } - decode(reader) { - let count = this.length; - if (count === -1) { - count = reader.readIndex(); - // Check that there is *roughly* enough data to ensure - // stray random data is not being read as a length. Each - // slot requires at least 32 bytes for their value (or 32 - // bytes as a link to the data). This could use a much - // tighter bound, but we are erroring on the side of safety. - assert(count * WordSize <= reader.dataLength, "insufficient data length", "BUFFER_OVERRUN", { buffer: reader.bytes, offset: count * WordSize, length: reader.dataLength }); - } - let coders = []; - for (let i = 0; i < count; i++) { - coders.push(new AnonymousCoder(this.coder)); - } - return unpack(reader, coders); - } - } - - /** - * @ignore - */ - class BooleanCoder extends Coder { - constructor(localName) { - super("bool", "bool", localName, false); - } - defaultValue() { - return false; - } - encode(writer, _value) { - const value = Typed.dereference(_value, "bool"); - return writer.writeValue(value ? 1 : 0); - } - decode(reader) { - return !!reader.readValue(); - } - } - - /** - * @ignore - */ - class DynamicBytesCoder extends Coder { - constructor(type, localName) { - super(type, type, localName, true); - } - defaultValue() { - return "0x"; - } - encode(writer, value) { - value = getBytesCopy(value); - let length = writer.writeValue(value.length); - length += writer.writeBytes(value); - return length; - } - decode(reader) { - return reader.readBytes(reader.readIndex(), true); - } - } - /** - * @ignore - */ - class BytesCoder extends DynamicBytesCoder { - constructor(localName) { - super("bytes", localName); - } - decode(reader) { - return hexlify(super.decode(reader)); - } - } - - /** - * @ignore - */ - class FixedBytesCoder extends Coder { - size; - constructor(size, localName) { - let name = "bytes" + String(size); - super(name, name, localName, false); - defineProperties(this, { size }, { size: "number" }); - } - defaultValue() { - return ("0x0000000000000000000000000000000000000000000000000000000000000000").substring(0, 2 + this.size * 2); - } - encode(writer, _value) { - let data = getBytesCopy(Typed.dereference(_value, this.type)); - if (data.length !== this.size) { - this._throwError("incorrect data length", _value); - } - return writer.writeBytes(data); - } - decode(reader) { - return hexlify(reader.readBytes(this.size)); - } - } - - const Empty = new Uint8Array([]); - /** - * @ignore - */ - class NullCoder extends Coder { - constructor(localName) { - super("null", "", localName, false); - } - defaultValue() { - return null; - } - encode(writer, value) { - if (value != null) { - this._throwError("not null", value); - } - return writer.writeBytes(Empty); - } - decode(reader) { - reader.readBytes(0); - return null; - } - } - - const BN_0$4 = BigInt(0); - const BN_1$1 = BigInt(1); - const BN_MAX_UINT256$1 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); - /** - * @ignore - */ - class NumberCoder extends Coder { - size; - signed; - constructor(size, signed, localName) { - const name = ((signed ? "int" : "uint") + (size * 8)); - super(name, name, localName, false); - defineProperties(this, { size, signed }, { size: "number", signed: "boolean" }); - } - defaultValue() { - return 0; - } - encode(writer, _value) { - let value = getBigInt(Typed.dereference(_value, this.type)); - // Check bounds are safe for encoding - let maxUintValue = mask(BN_MAX_UINT256$1, WordSize * 8); - if (this.signed) { - let bounds = mask(maxUintValue, (this.size * 8) - 1); - if (value > bounds || value < -(bounds + BN_1$1)) { - this._throwError("value out-of-bounds", _value); - } - value = toTwos(value, 8 * WordSize); - } - else if (value < BN_0$4 || value > mask(maxUintValue, this.size * 8)) { - this._throwError("value out-of-bounds", _value); - } - return writer.writeValue(value); - } - decode(reader) { - let value = mask(reader.readValue(), this.size * 8); - if (this.signed) { - value = fromTwos(value, this.size * 8); - } - return value; - } - } - - /** - * @ignore - */ - class StringCoder extends DynamicBytesCoder { - constructor(localName) { - super("string", localName); - } - defaultValue() { - return ""; - } - encode(writer, _value) { - return super.encode(writer, toUtf8Bytes(Typed.dereference(_value, "string"))); - } - decode(reader) { - return toUtf8String(super.decode(reader)); - } - } - - /** - * @ignore - */ - class TupleCoder extends Coder { - coders; - constructor(coders, localName) { - let dynamic = false; - const types = []; - coders.forEach((coder) => { - if (coder.dynamic) { - dynamic = true; - } - types.push(coder.type); - }); - const type = ("tuple(" + types.join(",") + ")"); - super("tuple", type, localName, dynamic); - defineProperties(this, { coders: Object.freeze(coders.slice()) }); - } - defaultValue() { - const values = []; - this.coders.forEach((coder) => { - values.push(coder.defaultValue()); - }); - // We only output named properties for uniquely named coders - const uniqueNames = this.coders.reduce((accum, coder) => { - const name = coder.localName; - if (name) { - if (!accum[name]) { - accum[name] = 0; - } - accum[name]++; - } - return accum; - }, {}); - // Add named values - this.coders.forEach((coder, index) => { - let name = coder.localName; - if (!name || uniqueNames[name] !== 1) { - return; - } - if (name === "length") { - name = "_length"; - } - if (values[name] != null) { - return; - } - values[name] = values[index]; - }); - return Object.freeze(values); - } - encode(writer, _value) { - const value = Typed.dereference(_value, "tuple"); - return pack(writer, this.coders, value); - } - decode(reader) { - return unpack(reader, this.coders); - } - } - - /** - * A simple hashing function which operates on UTF-8 strings to compute an 32-byte identifier. - * - * This simply computes the {@link toUtf8Bytes | **UTF-8 bytes**} and computes the {@link keccak256 | **keccak256**}. - * - * @category Hash - * @example - * - * ```ts - * id('hello world'); - * ``` - * - * @param {string} value - The string to hash. - * @returns {string} The 32-byte identifier. - */ - function id(value) { - return keccak256(toUtf8Bytes(value)); - } - - /** - * Computes the Quai Network equivalent of the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal-sign message - * digest to sign. - * - * This prefixes the message with {@link MessagePrefix | **MessagePrefix**} and the decimal length of `message` and - * computes the {@link keccak256 | **keccak256**} digest. - * - * If `message` is a string, it is converted to its UTF-8 bytes first. To compute the digest of a - * [**DataHexString**](../types-aliases/DataHex), it must be converted to [**bytes**](../functions/getBytes). - * - * @category Hash - * @example - * - * ```ts - * hashMessage('Hello World'); - * - * // Hashes the SIX (6) string characters, i.e. - * // [ "0", "x", "4", "2", "4", "3" ] - * hashMessage('0x4243'); - * - * // Hashes the TWO (2) bytes [ 0x42, 0x43 ]... - * hashMessage(getBytes('0x4243')); - * - * // ...which is equal to using data - * hashMessage(new Uint8Array([0x42, 0x43])); - * ``` - * - * @param {Uint8Array | string} message - The message to hash. - * @returns {string} The message digest. - */ - function hashMessage(message) { - if (typeof message === 'string') { - message = toUtf8Bytes(message); - } - return keccak256(concat([toUtf8Bytes(MessagePrefix), toUtf8Bytes(String(message.length)), message])); - } - /** - * Return the address of the private key that produced the signature `sig` during signing for `message`. - * - * @category Hash - * @param {Uint8Array | string} message - The message that was signed. - * @param {SignatureLike} sig - The signature to verify. - * @returns {string} The address of the signer. - */ - function verifyMessage(message, sig) { - const digest = hashMessage(message); - return recoverAddress(digest, sig); - } - /** - * Computes the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal-sign message digest to sign. - * - * This prefixes the message with {@link EthMessagePrefix | **EthMessagePrefix**} and the decimal length of `message` and - * computes the {@link keccak256 | **keccak256**} digest. - * - * If `message` is a string, it is converted to its UTF-8 bytes first. To compute the digest of a - * [**DataHexString**](../types-aliases/DataHex), it must be converted to [**bytes**](../functions/getBytes). - * - * This is the same as `hashMessage` except it uses `EthMessagePrefix` instead of `MessagePrefix` and is available for - * broader compatibility with EVM signing practices. - * - * @category Hash - * @param message - * @returns - */ - function ethHashMessage(message) { - if (typeof message === 'string') { - message = toUtf8Bytes(message); - } - return keccak256(concat([toUtf8Bytes(EthMessagePrefix), toUtf8Bytes(String(message.length)), message])); - } - /** - * Return the address of the private key that produced the signature `sig` during signing for `message`. - * - * This is the same as `verifyMessage` except it uses `EthMessagePrefix` instead of `MessagePrefix` and is available for - * broader compatibility with EVM signing practices. - * - * @category Hash - * @param message - The message that was signed. - * @param sig - The signature to verify. - * @returns {string} The address of the signer. - */ - function ethVerifyMessage(message, sig) { - const digest = ethHashMessage(message); - return recoverAddress(digest, sig); - } - - const regexBytes = new RegExp('^bytes([0-9]+)$'); - const regexNumber = new RegExp('^(u?int)([0-9]*)$'); - const regexArray = new RegExp('^(.*)\\[([0-9]*)\\]$'); - function _pack(type, value, isArray) { - switch (type) { - case 'address': - if (isArray) { - return getBytes(zeroPadValue(value, 32)); - } - return getBytes(getAddress(value)); - case 'string': - return toUtf8Bytes(value); - case 'bytes': - return getBytes(value); - case 'bool': - value = value ? '0x01' : '0x00'; - if (isArray) { - return getBytes(zeroPadValue(value, 32)); - } - return getBytes(value); - } - let match = type.match(regexNumber); - if (match) { - const signed = match[1] === 'int'; - let size = parseInt(match[2] || '256'); - assertArgument((!match[2] || match[2] === String(size)) && size % 8 === 0 && size !== 0 && size <= 256, 'invalid number type', 'type', type); - if (isArray) { - size = 256; - } - if (signed) { - value = toTwos(value, size); - } - return getBytes(zeroPadValue(toBeArray(value), size / 8)); - } - match = type.match(regexBytes); - if (match) { - const size = parseInt(match[1]); - assertArgument(String(size) === match[1] && size !== 0 && size <= 32, 'invalid bytes type', 'type', type); - assertArgument(dataLength(value) === size, `invalid value for ${type}`, 'value', value); - if (isArray) { - return getBytes(zeroPadBytes(value, 32)); - } - return value; - } - match = type.match(regexArray); - if (match && Array.isArray(value)) { - const baseType = match[1]; - const count = parseInt(match[2] || String(value.length)); - assertArgument(count === value.length, `invalid array length for ${type}`, 'value', value); - const result = []; - value.forEach(function (value) { - result.push(_pack(baseType, value, true)); - }); - return getBytes(concat(result)); - } - assertArgument(false, 'invalid type', 'type', type); - } - // @TODO: Array Enum - /** - * Computes the [Non-Standard Packed - * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) representation of `values` - * respectively to their `types`. - * - * @category Hash - * @example - * - * ```ts - * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72'; - * solidityPacked(['address', 'uint'], [addr, 45]); - * ``` - * - * @param {string[]} types - The types of the values. - * @param {ReadonlyArray} values - The values to pack. - * @returns {string} The packed values. - */ - function solidityPacked(types, values) { - assertArgument(types.length === values.length, 'wrong number of values; expected ${ types.length }', 'values', values); - const tight = []; - types.forEach(function (type, index) { - tight.push(_pack(type, values[index])); - }); - return hexlify(concat(tight)); - } - /** - * Computes the [Non-Standard Packed - * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) - * [**keccak256**](../functions/keccak256) hash of `values` respectively to their `types`. - * - * @category Hash - * @example - * - * ```ts - * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72'; - * solidityPackedKeccak256(['address', 'uint'], [addr, 45]); - * ``` - * - * @param {ReadonlyArray} types - The types of the values. - * @param {ReadonlyArray} values - The values to hash. - * @returns {string} The hash of the packed values. - */ - function solidityPackedKeccak256(types, values) { - return keccak256(solidityPacked(types, values)); - } - /** - * Computes the [Non-Standard Packed - * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) [sha256](../functions/sha256) - * hash of `values` respectively to their `types`. - * - * @category Hash - * @example - * - * ```ts - * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72'; - * solidityPackedSha256(['address', 'uint'], [addr, 45]); - * ``` - * - * @param {ReadonlyArray} types - The types of the values. - * @param {ReadonlyArray} values - The values to hash. - * @returns {string} The hash of the packed values. - */ - function solidityPackedSha256(types, values) { - return sha256(solidityPacked(types, values)); - } - - //import { TypedDataDomain, TypedDataField } from "@quaisproject/providerabstract-signer"; - const padding = new Uint8Array(32); - padding.fill(0); - const BN__1 = BigInt(-1); - const BN_0$3 = BigInt(0); - const BN_1 = BigInt(1); - const BN_MAX_UINT256 = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); - function hexPadRight(value) { - const bytes = getBytes(value); - const padOffset = bytes.length % 32; - if (padOffset) { - return concat([bytes, padding.slice(padOffset)]); - } - return hexlify(bytes); - } - const hexTrue = toBeHex(BN_1, 32); - const hexFalse = toBeHex(BN_0$3, 32); - const domainFieldTypes = { - name: 'string', - version: 'string', - chainId: 'uint256', - verifyingContract: 'address', - salt: 'bytes32', - }; - const domainFieldNames = ['name', 'version', 'chainId', 'verifyingContract', 'salt']; - function checkString(key) { - return function (value) { - assertArgument(typeof value === 'string', `invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); - return value; - }; - } - const domainChecks = { - name: checkString('name'), - version: checkString('version'), - chainId: function (_value) { - const value = getBigInt(_value, 'domain.chainId'); - assertArgument(value >= 0, 'invalid chain ID', 'domain.chainId', _value); - if (Number.isSafeInteger(value)) { - return Number(value); - } - return toQuantity(value); - }, - verifyingContract: function (value) { - try { - return getAddress(value); - // eslint-disable-next-line no-empty - } - catch (error) { } - assertArgument(false, `invalid domain value "verifyingContract"`, 'domain.verifyingContract', value); - }, - salt: function (value) { - const bytes = getBytes(value, 'domain.salt'); - assertArgument(bytes.length === 32, `invalid domain value "salt"`, 'domain.salt', value); - return hexlify(bytes); - }, - }; - function getBaseEncoder(type) { - // intXX and uintXX - { - const match = type.match(/^(u?)int(\d*)$/); - if (match) { - const signed = match[1] === ''; - const width = parseInt(match[2] || '256'); - assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && (match[2] == null || match[2] === String(width)), 'invalid numeric width', 'type', type); - const boundsUpper = mask(BN_MAX_UINT256, signed ? width - 1 : width); - const boundsLower = signed ? (boundsUpper + BN_1) * BN__1 : BN_0$3; - return function (_value) { - const value = getBigInt(_value, 'value'); - assertArgument(value >= boundsLower && value <= boundsUpper, `value out-of-bounds for ${type}`, 'value', value); - return toBeHex(signed ? toTwos(value, 256) : value, 32); - }; - } - } - // bytesXX - { - const match = type.match(/^bytes(\d+)$/); - if (match) { - const width = parseInt(match[1]); - assertArgument(width !== 0 && width <= 32 && match[1] === String(width), 'invalid bytes width', 'type', type); - return function (value) { - const bytes = getBytes(value); - assertArgument(bytes.length === width, `invalid length for ${type}`, 'value', value); - return hexPadRight(value); - }; - } - } - switch (type) { - case 'address': - return function (value) { - return zeroPadValue(getAddress(value), 32); - }; - case 'bool': - return function (value) { - return !value ? hexFalse : hexTrue; - }; - case 'bytes': - return function (value) { - return keccak256(value); - }; - case 'string': - return function (value) { - return id(value); - }; - } - return null; - } - function encodeType(name, fields) { - return `${name}(${fields.map(({ name, type }) => type + ' ' + name).join(',')})`; - } - /** - * A **TypedDataEncode** prepares and encodes [EIP-712](https://eips.ethereum.org/EIPS/eip-712) payloads for signed - * typed data. - * - * This is useful for those that wish to compute various components of a typed data hash, primary types, or - * sub-components, but generally the higher level [`Signer.signTypedData`](../classes/Signer#signTypedData) is more - * useful. - * - * @category Hash - */ - class TypedDataEncoder { - /** - * The primary type for the structured {@link types | **types**}. - * - * This is derived automatically from the {@link types | **types**}, since no recursion is possible, once the DAG for - * the types is consturcted internally, the primary type must be the only remaining type with no parent nodes. - */ - primaryType; - #types; - /** - * The types. - */ - get types() { - return JSON.parse(this.#types); - } - #fullTypes; - #encoderCache; - /** - * Create a new **TypedDataEncoder** for `types`. - * - * This performs all necessary checking that types are valid and do not violate the - * [EIP-712](https://eips.ethereum.org/EIPS/eip-712) structural constraints as well as computes the - * {@link primaryType | **primaryType**}. - */ - constructor(types) { - this.#types = JSON.stringify(types); - this.#fullTypes = new Map(); - this.#encoderCache = new Map(); - // Link struct types to their direct child structs - const links = new Map(); - // Link structs to structs which contain them as a child - const parents = new Map(); - // Link all subtypes within a given struct - const subtypes = new Map(); - Object.keys(types).forEach((type) => { - links.set(type, new Set()); - parents.set(type, []); - subtypes.set(type, new Set()); - }); - for (const name in types) { - const uniqueNames = new Set(); - for (const field of types[name]) { - // Check each field has a unique name - assertArgument(!uniqueNames.has(field.name), `duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, 'types', types); - uniqueNames.add(field.name); - // Get the base type (drop any array specifiers) - const baseType = field.type.match(/^([^\x5b]*)(\x5b|$)/)[1] || null; - assertArgument(baseType !== name, `circular type reference to ${JSON.stringify(baseType)}`, 'types', types); - // Is this a base encoding type? - const encoder = getBaseEncoder(baseType); - if (encoder) { - continue; - } - assertArgument(parents.has(baseType), `unknown type ${JSON.stringify(baseType)}`, 'types', types); - // Add linkage - parents.get(baseType).push(name); - links.get(name).add(baseType); - } - } - // Deduce the primary type - const primaryTypes = Array.from(parents.keys()).filter((n) => parents.get(n).length === 0); - assertArgument(primaryTypes.length !== 0, 'missing primary type', 'types', types); - assertArgument(primaryTypes.length === 1, `ambiguous primary types or unused types: ${primaryTypes.map((t) => JSON.stringify(t)).join(', ')}`, 'types', types); - defineProperties(this, { primaryType: primaryTypes[0] }); - // Check for circular type references - function checkCircular(type, found) { - assertArgument(!found.has(type), `circular type reference to ${JSON.stringify(type)}`, 'types', types); - found.add(type); - for (const child of links.get(type)) { - if (!parents.has(child)) { - continue; - } - // Recursively check children - checkCircular(child, found); - // Mark all ancestors as having this decendant - for (const subtype of found) { - subtypes.get(subtype).add(child); - } - } - found.delete(type); - } - checkCircular(this.primaryType, new Set()); - // Compute each fully describe type - for (const [name, set] of subtypes) { - const st = Array.from(set); - st.sort(); - this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t) => encodeType(t, types[t])).join('')); - } - } - /** - * Returnthe encoder for the specific `type`. - * - * @param {string} type - The type to get the encoder for. - * - * @returns {(value: any) => string} The encoder for the type. - */ - getEncoder(type) { - let encoder = this.#encoderCache.get(type); - if (!encoder) { - encoder = this.#getEncoder(type); - this.#encoderCache.set(type, encoder); - } - return encoder; - } - #getEncoder(type) { - // Basic encoder type (address, bool, uint256, etc) - { - const encoder = getBaseEncoder(type); - if (encoder) { - return encoder; - } - } - // Array - const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); - if (match) { - const subtype = match[1]; - const subEncoder = this.getEncoder(subtype); - return (value) => { - assertArgument(!match[3] || parseInt(match[3]) === value.length, `array length mismatch; expected length ${parseInt(match[3])}`, 'value', value); - let result = value.map(subEncoder); - if (this.#fullTypes.has(subtype)) { - result = result.map(keccak256); - } - return keccak256(concat(result)); - }; - } - // Struct - const fields = this.types[type]; - if (fields) { - const encodedType = id(this.#fullTypes.get(type)); - return (value) => { - const values = fields.map(({ name, type }) => { - const result = this.getEncoder(type)(value[name]); - if (this.#fullTypes.has(type)) { - return keccak256(result); - } - return result; - }); - values.unshift(encodedType); - return concat(values); - }; - } - assertArgument(false, `unknown type: ${type}`, 'type', type); - } - /** - * Return the full type for `name`. - * - * @param {string} name - The name to get the full type for. - * - * @returns {string} The full type. - */ - encodeType(name) { - const result = this.#fullTypes.get(name); - assertArgument(result, `unknown type: ${JSON.stringify(name)}`, 'name', name); - return result; - } - /** - * Return the encoded `value` for the `type`. - * - * @param {string} type - The type to encode the value for. - * @param {any} value - The value to encode. - * - * @returns {string} The encoded value. - */ - encodeData(type, value) { - return this.getEncoder(type)(value); - } - /** - * Returns the hash of `value` for the type of `name`. - * - * @param {string} name - The name of the type. - * @param {Record} value - The value to hash. - * - * @returns {string} The hash of the value. - */ - hashStruct(name, value) { - return keccak256(this.encodeData(name, value)); - } - /** - * Return the fulled encoded `value` for the {@link types | **types**}. - * - * @param {Record} value - The value to encode. - * - * @returns {string} The encoded value. - */ - encode(value) { - return this.encodeData(this.primaryType, value); - } - /** - * Return the hash of the fully encoded `value` for the {@link types | **types**}. - * - * @param {Record} value - The value to hash. - * - * @returns {string} The hash of the value. - */ - hash(value) { - return this.hashStruct(this.primaryType, value); - } - /** - * @ignore - */ - _visit(type, value, callback) { - // Basic encoder type (address, bool, uint256, etc) - { - const encoder = getBaseEncoder(type); - if (encoder) { - return callback(type, value); - } - } - // Array - const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); - if (match) { - assertArgument(!match[3] || parseInt(match[3]) === value.length, `array length mismatch; expected length ${parseInt(match[3])}`, 'value', value); - return value.map((v) => this._visit(match[1], v, callback)); - } - // Struct - const fields = this.types[type]; - if (fields) { - return fields.reduce((accum, { name, type }) => { - accum[name] = this._visit(type, value[name], callback); - return accum; - }, {}); - } - assertArgument(false, `unknown type: ${type}`, 'type', type); - } - /** - * Call `calback` for each value in `value`, passing the type and component within `value`. - * - * This is useful for replacing addresses or other transformation that may be desired on each component, based on - * its type. - * - * @param {Record} value - The value to visit. - * @param {(type: string, data: any) => any} callback - The callback to call for each value. - * - * @returns {any} The result of the callback. - */ - visit(value, callback) { - return this._visit(this.primaryType, value, callback); - } - /** - * Create a new **TypedDataEncoder** for `types`. - * - * @param {Record} types - The types to encode. - * - * @returns {TypedDataEncoder} The encoder for the types. - * @throws {Error} If the types are invalid. - */ - static from(types) { - return new TypedDataEncoder(types); - } - /** - * Return the primary type for `types`. - * - * @param {Record} types - The types to get the primary type for. - * - * @returns {string} The primary type. - * @throws {Error} If the types are invalid. - */ - static getPrimaryType(types) { - return TypedDataEncoder.from(types).primaryType; - } - /** - * Return the hashed struct for `value` using `types` and `name`. - * - * @param {string} name - The name of the type. - * @param {Record} types - The types to hash. - * @param {Record} value - The value to hash. - * - * @returns {string} The hash of the value. - */ - static hashStruct(name, types, value) { - return TypedDataEncoder.from(types).hashStruct(name, value); - } - /** - * Return the domain hash for `domain`. - * - * @param {TypedDataDomain} domain - The domain to hash. - * - * @returns {string} The hash of the domain. - * @throws {Error} If the domain is invalid. - */ - static hashDomain(domain) { - const domainFields = []; - for (const name in domain) { - if (domain[name] == null) { - continue; - } - const type = domainFieldTypes[name]; - assertArgument(type, `invalid typed-data domain key: ${JSON.stringify(name)}`, 'domain', domain); - domainFields.push({ name, type }); - } - domainFields.sort((a, b) => { - return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); - }); - return TypedDataEncoder.hashStruct('EIP712Domain', { EIP712Domain: domainFields }, domain); - } - /** - * Return the fully encoded [EIP-712](https://eips.ethereum.org/EIPS/eip-712) `value` for `types` with `domain`. - * - * @param {TypedDataDomain} domain - The domain to use. - * @param {Record} types - The types to encode. - * @param {Record} value - The value to encode. - * - * @returns {string} The encoded value. - */ - static encode(domain, types, value) { - return concat(['0x1901', TypedDataEncoder.hashDomain(domain), TypedDataEncoder.from(types).hash(value)]); - } - /** - * Return the hash of the fully encoded [EIP-712](https://eips.ethereum.org/EIPS/eip-712) `value` for `types` with - * `domain`. - * - * @param {TypedDataDomain} domain - The domain to use. - * @param {Record} types - The types to hash. - * @param {Record} value - The value to hash. - * - * @returns {string} The hash of the value. - */ - static hash(domain, types, value) { - return keccak256(TypedDataEncoder.encode(domain, types, value)); - } - /** - * Returns the JSON-encoded payload expected by nodes which implement the JSON-RPC - * [EIP-712](https://eips.ethereum.org/EIPS/eip-712) method. - * - * @param {TypedDataDomain} domain - The domain to use. - * @param {Record} types - The types to encode. - * @param {Record} value - The value to encode. - * - * @returns {any} The JSON-encoded payload. - */ - static getPayload(domain, types, value) { - // Validate the domain fields - TypedDataEncoder.hashDomain(domain); - // Derive the EIP712Domain Struct reference type - const domainValues = {}; - const domainTypes = []; - domainFieldNames.forEach((name) => { - const value = domain[name]; - if (value == null) { - return; - } - domainValues[name] = domainChecks[name](value); - domainTypes.push({ name, type: domainFieldTypes[name] }); - }); - const encoder = TypedDataEncoder.from(types); - const typesWithDomain = Object.assign({}, types); - assertArgument(typesWithDomain.EIP712Domain == null, 'types must not contain EIP712Domain type', 'types.EIP712Domain', types); - typesWithDomain.EIP712Domain = domainTypes; - // Validate the data structures and types - encoder.encode(value); - return { - types: typesWithDomain, - domain: domainValues, - primaryType: encoder.primaryType, - message: encoder.visit(value, (type, value) => { - // bytes - if (type.match(/^bytes(\d*)/)) { - return hexlify(getBytes(value)); - } - // uint or int - if (type.match(/^u?int/)) { - return getBigInt(value).toString(); - } - switch (type) { - case 'address': - return value.toLowerCase(); - case 'bool': - return !!value; - case 'string': - assertArgument(typeof value === 'string', 'invalid string', 'value', value); - return value; - } - assertArgument(false, 'unsupported type', 'type', type); - }), - }; - } - } - /** - * Compute the address used to sign the typed data for the `signature`. - * - * @category Hash - * @param {TypedDataDomain} domain - The domain of the typed data. - * @param {Record} types - The types of the typed data. - * @param {Record} value - The value of the typed data. - * @param {SignatureLike} signature - The signature to verify. - * - * @returns {string} The address that signed the typed data. - */ - function verifyTypedData(domain, types, value, signature) { - return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature); - } - - /** - * A fragment is a single item from an ABI, which may represent any of: - * - * - {@link FunctionFragment | Functions} - * - {@link EventFragment | Events} - * - {@link ConstructorFragment | Constructors} - * - Custom {@link ErrorFragment | Errors} - * - {@link FallbackFragment | Fallback or Recieve} functions - * - * @category Application Binary Interface - */ - // [ "a", "b" ] => { "a": 1, "b": 1 } - function setify(items) { - const result = new Set(); - items.forEach((k) => result.add(k)); - return Object.freeze(result); - } - const _kwVisibDeploy = 'external public payable'; - const KwVisibDeploy = setify(_kwVisibDeploy.split(' ')); - // Visibility Keywords - const _kwVisib = 'constant external internal payable private public pure view'; - const KwVisib = setify(_kwVisib.split(' ')); - const _kwTypes = 'constructor error event fallback function receive struct'; - const KwTypes = setify(_kwTypes.split(' ')); - const _kwModifiers = 'calldata memory storage payable indexed'; - const KwModifiers = setify(_kwModifiers.split(' ')); - const _kwOther = 'tuple returns'; - // All Keywords - const _keywords = [_kwTypes, _kwModifiers, _kwOther, _kwVisib].join(' '); - const Keywords = setify(_keywords.split(' ')); - // Single character tokens - const SimpleTokens = { - '(': 'OPEN_PAREN', - ')': 'CLOSE_PAREN', - '[': 'OPEN_BRACKET', - ']': 'CLOSE_BRACKET', - ',': 'COMMA', - '@': 'AT', - }; - // Parser regexes to consume the next token - const regexWhitespacePrefix = new RegExp('^(\\s*)'); - const regexNumberPrefix = new RegExp('^([0-9]+)'); - const regexIdPrefix = new RegExp('^([a-zA-Z$_][a-zA-Z0-9$_]*)'); - // Parser regexs to check validity - const regexId = new RegExp('^([a-zA-Z$_][a-zA-Z0-9$_]*)$'); - const regexType = new RegExp('^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$'); - /** - * Represents a parsed list of tokens. - * - * @category Application Binary Interface - */ - class TokenString { - #offset; - #tokens; - get offset() { - return this.#offset; - } - get length() { - return this.#tokens.length - this.#offset; - } - constructor(tokens) { - this.#offset = 0; - this.#tokens = tokens.slice(); - } - /** - * Returns a clone of the current token string. - * - * @returns {TokenString} A cloned TokenString object. - */ - clone() { - return new TokenString(this.#tokens); - } - reset() { - this.#offset = 0; - } - /** - * @ignore - */ - #subTokenString(from = 0, to = 0) { - return new TokenString(this.#tokens.slice(from, to).map((t) => { - return Object.freeze(Object.assign({}, t, { - match: t.match - from, - linkBack: t.linkBack - from, - linkNext: t.linkNext - from, - })); - })); - } - // Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens - popKeyword(allowed) { - const top = this.peek(); - if (top.type !== 'KEYWORD' || !allowed.has(top.text)) { - throw new Error(`expected keyword ${top.text}`); - } - return this.pop().text; - } - // Pops and returns the value of the next token if it is `type`; throws if out of tokens - popType(type) { - if (this.peek().type !== type) { - throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`); - } - return this.pop().text; - } - // Pops and returns a "(" TOKENS ")" - popParen() { - const top = this.peek(); - if (top.type !== 'OPEN_PAREN') { - throw new Error('bad start'); - } - const result = this.#subTokenString(this.#offset + 1, top.match + 1); - this.#offset = top.match + 1; - return result; - } - // Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")" - popParams() { - const top = this.peek(); - if (top.type !== 'OPEN_PAREN') { - throw new Error('bad start'); - } - const result = []; - while (this.#offset < top.match - 1) { - const link = this.peek().linkNext; - result.push(this.#subTokenString(this.#offset + 1, link)); - this.#offset = link; - } - this.#offset = top.match + 1; - return result; - } - // Returns the top Token, throwing if out of tokens - peek() { - if (this.#offset >= this.#tokens.length) { - throw new Error('out-of-bounds'); - } - return this.#tokens[this.#offset]; - } - // Returns the next value, if it is a keyword in `allowed` - peekKeyword(allowed) { - const top = this.peekType('KEYWORD'); - return top != null && allowed.has(top) ? top : null; - } - // Returns the value of the next token if it is `type` - peekType(type) { - if (this.length === 0) { - return null; - } - const top = this.peek(); - return top.type === type ? top.text : null; - } - // Returns the next token; throws if out of tokens - pop() { - const result = this.peek(); - this.#offset++; - return result; - } - toString() { - const tokens = []; - for (let i = this.#offset; i < this.#tokens.length; i++) { - const token = this.#tokens[i]; - tokens.push(`${token.type}:${token.text}`); - } - return ``; - } - } - function lex(text) { - const tokens = []; - const throwError = (message) => { - const token = offset < text.length ? JSON.stringify(text[offset]) : '$EOI'; - throw new Error(`invalid token ${token} at ${offset}: ${message}`); - }; - const brackets = []; - const commas = []; - let offset = 0; - while (offset < text.length) { - // Strip off any leading whitespace - let cur = text.substring(offset); - let match = cur.match(regexWhitespacePrefix); - if (match) { - offset += match[1].length; - cur = text.substring(offset); - } - const token = { - depth: brackets.length, - linkBack: -1, - linkNext: -1, - match: -1, - type: '', - text: '', - offset, - value: -1, - }; - tokens.push(token); - const type = SimpleTokens[cur[0]] || ''; - if (type) { - token.type = type; - token.text = cur[0]; - offset++; - if (type === 'OPEN_PAREN') { - brackets.push(tokens.length - 1); - commas.push(tokens.length - 1); - } - else if (type == 'CLOSE_PAREN') { - if (brackets.length === 0) { - throwError('no matching open bracket'); - } - token.match = brackets.pop(); - tokens[token.match].match = tokens.length - 1; - token.depth--; - token.linkBack = commas.pop(); - tokens[token.linkBack].linkNext = tokens.length - 1; - } - else if (type === 'COMMA') { - token.linkBack = commas.pop(); - tokens[token.linkBack].linkNext = tokens.length - 1; - commas.push(tokens.length - 1); - } - else if (type === 'OPEN_BRACKET') { - token.type = 'BRACKET'; - } - else if (type === 'CLOSE_BRACKET') { - // Remove the CLOSE_BRACKET - let suffix = tokens.pop().text; - if (tokens.length > 0 && tokens[tokens.length - 1].type === 'NUMBER') { - const value = tokens.pop().text; - suffix = value + suffix; - tokens[tokens.length - 1].value = getNumber(value); - } - if (tokens.length === 0 || tokens[tokens.length - 1].type !== 'BRACKET') { - throw new Error('missing opening bracket'); - } - tokens[tokens.length - 1].text += suffix; - } - continue; - } - match = cur.match(regexIdPrefix); - if (match) { - token.text = match[1]; - offset += token.text.length; - if (Keywords.has(token.text)) { - token.type = 'KEYWORD'; - continue; - } - if (token.text.match(regexType)) { - token.type = 'TYPE'; - continue; - } - token.type = 'ID'; - continue; - } - match = cur.match(regexNumberPrefix); - if (match) { - token.text = match[1]; - token.type = 'NUMBER'; - offset += token.text.length; - continue; - } - throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`); - } - return new TokenString(tokens.map((t) => Object.freeze(t))); - } - // Check only one of `allowed` is in `set` - function allowSingle(set, allowed) { - const included = []; - for (const key in allowed.keys()) { - if (set.has(key)) { - included.push(key); - } - } - if (included.length > 1) { - throw new Error(`conflicting types: ${included.join(', ')}`); - } - } - // Functions to process a Solidity Signature TokenString from left-to-right for... - // ...the name with an optional type, returning the name - function consumeName(type, tokens) { - if (tokens.peekKeyword(KwTypes)) { - const keyword = tokens.pop().text; - if (keyword !== type) { - throw new Error(`expected ${type}, got ${keyword}`); - } - } - return tokens.popType('ID'); - } - // ...all keywords matching allowed, returning the keywords - function consumeKeywords(tokens, allowed) { - const keywords = new Set(); - // eslint-disable-next-line no-constant-condition - while (true) { - const keyword = tokens.peekType('KEYWORD'); - if (keyword == null || (allowed && !allowed.has(keyword))) { - break; - } - tokens.pop(); - if (keywords.has(keyword)) { - throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`); - } - keywords.add(keyword); - } - return Object.freeze(keywords); - } - // ...all visibility keywords, returning the coalesced mutability - function consumeMutability(tokens) { - const modifiers = consumeKeywords(tokens, KwVisib); - // Detect conflicting modifiers - allowSingle(modifiers, setify('constant payable nonpayable'.split(' '))); - allowSingle(modifiers, setify('pure view payable nonpayable'.split(' '))); - // Process mutability states - if (modifiers.has('view')) { - return 'view'; - } - if (modifiers.has('pure')) { - return 'pure'; - } - if (modifiers.has('payable')) { - return 'payable'; - } - if (modifiers.has('nonpayable')) { - return 'nonpayable'; - } - // Process legacy `constant` last - if (modifiers.has('constant')) { - return 'view'; - } - return 'nonpayable'; - } - // ...a parameter list, returning the ParamType list - function consumeParams(tokens, allowIndexed) { - return tokens.popParams().map((t) => ParamType.from(t, allowIndexed)); - } - // ...a gas limit, returning a BigNumber or null if none - function consumeGas(tokens) { - if (tokens.peekType('AT')) { - tokens.pop(); - if (tokens.peekType('NUMBER')) { - return getBigInt(tokens.pop().text); - } - throw new Error('invalid gas'); - } - return null; - } - function consumeEoi(tokens) { - if (tokens.length) { - throw new Error(`unexpected tokens: ${tokens.toString()}`); - } - } - const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/); - function verifyBasicType(type) { - const match = type.match(regexType); - assertArgument(match, 'invalid type', 'type', type); - if (type === 'uint') { - return 'uint256'; - } - if (type === 'int') { - return 'int256'; - } - if (match[2]) { - // bytesXX - const length = parseInt(match[2]); - assertArgument(length !== 0 && length <= 32, 'invalid bytes length', 'type', type); - } - else if (match[3]) { - // intXX or uintXX - const size = parseInt(match[3]); - assertArgument(size !== 0 && size <= 256 && size % 8 === 0, 'invalid numeric width', 'type', type); - } - return type; - } - // Make the Fragment constructors effectively private - const _guard$3 = {}; - const internal$1 = Symbol.for('_quais_internal'); - const ParamTypeInternal = '_ParamTypeInternal'; - const ErrorFragmentInternal = '_ErrorInternal'; - const EventFragmentInternal = '_EventInternal'; - const ConstructorFragmentInternal = '_ConstructorInternal'; - const FallbackFragmentInternal = '_FallbackInternal'; - const FunctionFragmentInternal = '_FunctionInternal'; - const StructFragmentInternal = '_StructInternal'; - /** - * Each input and output of a {@link Fragment | **Fragment**} is an Array of {@link ParamType | **ParamType**}. - * - * @category Application Binary Interface - */ - class ParamType { - /** - * The local name of the parameter (or `""` if unbound) - */ - name; - /** - * The fully qualified type (e.g. `"address"`, `"tuple(address)"`, `"uint256[3][]"`) - */ - type; - /** - * The base type (e.g. `"address"`, `"tuple"`, `"array"`) - */ - baseType; - /** - * True if the parameters is indexed. - * - * For non-indexable types this is `null`. - */ - indexed; - /** - * The components for the tuple. - * - * For non-tuple types this is `null`. - */ - components; - /** - * The array length, or `-1` for dynamic-lengthed arrays. - * - * For non-array types this is `null`. - */ - arrayLength; - /** - * The type of each child in the array. - * - * For non-array types this is `null`. - */ - arrayChildren; - /** - * @ignore - */ - constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren) { - assertPrivate(guard, _guard$3, 'ParamType'); - Object.defineProperty(this, internal$1, { value: ParamTypeInternal }); - if (components) { - components = Object.freeze(components.slice()); - } - if (baseType === 'array') { - if (arrayLength == null || arrayChildren == null) { - throw new Error(''); - } - } - else if (arrayLength != null || arrayChildren != null) { - throw new Error(''); - } - if (baseType === 'tuple') { - if (components == null) { - throw new Error(''); - } - } - else if (components != null) { - throw new Error(''); - } - defineProperties(this, { - name, - type, - baseType, - indexed, - components, - arrayLength, - arrayChildren, - }); - } - /** - * Return a string representation of this type. - * - * For example, - * - * `sighash" => "(uint256,address)"` - * - * `"minimal" => "tuple(uint256,address) indexed"` - * - * `"full" => "tuple(uint256 foo, address bar) indexed baz"` - * - * @returns {string} The formatted type. - */ - format(format) { - if (format == null) { - format = 'sighash'; - } - if (format === 'json') { - const name = this.name || ''; - if (this.isArray()) { - const result = JSON.parse(this.arrayChildren.format('json')); - result.name = name; - result.type += `[${this.arrayLength < 0 ? '' : String(this.arrayLength)}]`; - return JSON.stringify(result); - } - const result = { - type: this.baseType === 'tuple' ? 'tuple' : this.type, - name, - }; - if (typeof this.indexed === 'boolean') { - result.indexed = this.indexed; - } - if (this.isTuple()) { - result.components = this.components.map((c) => JSON.parse(c.format(format))); - } - return JSON.stringify(result); - } - let result = ''; - // Array - if (this.isArray()) { - result += this.arrayChildren.format(format); - result += `[${this.arrayLength < 0 ? '' : String(this.arrayLength)}]`; - } - else { - if (this.isTuple()) { - result += - '(' + this.components.map((comp) => comp.format(format)).join(format === 'full' ? ', ' : ',') + ')'; - } - else { - result += this.type; - } - } - if (format !== 'sighash') { - if (this.indexed === true) { - result += ' indexed'; - } - if (format === 'full' && this.name) { - result += ' ' + this.name; - } - } - return result; - } - /** - * This provides a type guard ensuring that {@link arrayChildren | **arrayChildren**} and - * {@link arrayLength | **arrayLength**} are non-null. - * - * @returns {boolean} True if this is an Array type. - */ - isArray() { - return this.baseType === 'array'; - } - /** - * This provides a type guard ensuring that {@link components | **components**} is non-null. - * - * @returns {boolean} True if this is a Tuple type. - */ - isTuple() { - return this.baseType === 'tuple'; - } - /** - * This provides a type guard ensuring that {@link indexed | **indexed**} is non-null. - * - * @returns {boolean} True if this is an Indexable type. - */ - isIndexable() { - return this.indexed != null; - } - /** - * Walks the **ParamType** with `value`, calling `process` on each type, destructing the `value` recursively. - */ - walk(value, process) { - if (this.isArray()) { - if (!Array.isArray(value)) { - throw new Error('invalid array value'); - } - if (this.arrayLength !== -1 && value.length !== this.arrayLength) { - throw new Error('array is wrong length'); - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - const _this = this; - return value.map((v) => _this.arrayChildren.walk(v, process)); - } - if (this.isTuple()) { - if (!Array.isArray(value)) { - throw new Error('invalid tuple value'); - } - if (value.length !== this.components.length) { - throw new Error('array is wrong length'); - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - const _this = this; - return value.map((v, i) => _this.components[i].walk(v, process)); - } - return process(this.type, value); - } - /** - * @ignore - */ - #walkAsync(promises, value, process, setValue) { - if (this.isArray()) { - if (!Array.isArray(value)) { - throw new Error('invalid array value'); - } - if (this.arrayLength !== -1 && value.length !== this.arrayLength) { - throw new Error('array is wrong length'); - } - const childType = this.arrayChildren; - const result = value.slice(); - result.forEach((value, index) => { - childType.#walkAsync(promises, value, process, (value) => { - result[index] = value; - }); - }); - setValue(result); - return; - } - if (this.isTuple()) { - const components = this.components; - // Convert the object into an array - let result; - if (Array.isArray(value)) { - result = value.slice(); - } - else { - if (value == null || typeof value !== 'object') { - throw new Error('invalid tuple value'); - } - result = components.map((param) => { - if (!param.name) { - throw new Error('cannot use object value with unnamed components'); - } - if (!(param.name in value)) { - throw new Error(`missing value for component ${param.name}`); - } - return value[param.name]; - }); - } - if (result.length !== this.components.length) { - throw new Error('array is wrong length'); - } - result.forEach((value, index) => { - components[index].#walkAsync(promises, value, process, (value) => { - result[index] = value; - }); - }); - setValue(result); - return; - } - const result = process(this.type, value); - if (result.then) { - promises.push((async function () { - setValue(await result); - })()); - } - else { - setValue(result); - } - } - /** - * Walks the **ParamType** with `value`, asynchronously calling `process` on each type, destructing the `value` - * recursively. - * - * This can be used to resolve ENS naes by walking and resolving each `"address"` type. - */ - async walkAsync(value, process) { - const promises = []; - const result = [value]; - this.#walkAsync(promises, value, process, (value) => { - result[0] = value; - }); - if (promises.length) { - await Promise.all(promises); - } - return result[0]; - } - /** - * Creates a new **ParamType** for `obj`. - * - * If `allowIndexed` then the `indexed` keyword is permitted, otherwise the `indexed` keyword will throw an error. - */ - static from(obj, allowIndexed) { - if (ParamType.isParamType(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return ParamType.from(lex(obj), allowIndexed); - } - catch (error) { - assertArgument(false, 'invalid param type', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - let type = '', baseType = ''; - let comps = null; - if (consumeKeywords(obj, setify(['tuple'])).has('tuple') || obj.peekType('OPEN_PAREN')) { - // Tuple - baseType = 'tuple'; - comps = obj.popParams().map((t) => ParamType.from(t)); - type = `tuple(${comps.map((c) => c.format()).join(',')})`; - } - else { - // Normal - type = verifyBasicType(obj.popType('TYPE')); - baseType = type; - } - // Check for Array - let arrayChildren = null; - let arrayLength = null; - while (obj.length && obj.peekType('BRACKET')) { - const bracket = obj.pop(); //arrays[i]; - arrayChildren = new ParamType(_guard$3, '', type, baseType, null, comps, arrayLength, arrayChildren); - arrayLength = bracket.value; - type += bracket.text; - baseType = 'array'; - comps = null; - } - let indexed = null; - const keywords = consumeKeywords(obj, KwModifiers); - if (keywords.has('indexed')) { - if (!allowIndexed) { - throw new Error(''); - } - indexed = true; - } - const name = obj.peekType('ID') ? obj.pop().text : ''; - if (obj.length) { - throw new Error('leftover tokens'); - } - return new ParamType(_guard$3, name, type, baseType, indexed, comps, arrayLength, arrayChildren); - } - const name = obj.name; - assertArgument(!name || (typeof name === 'string' && name.match(regexId)), 'invalid name', 'obj.name', name); - let indexed = obj.indexed; - if (indexed != null) { - assertArgument(allowIndexed, 'parameter cannot be indexed', 'obj.indexed', obj.indexed); - indexed = !!indexed; - } - let type = obj.type; - const arrayMatch = type.match(regexArrayType); - if (arrayMatch) { - const arrayLength = parseInt(arrayMatch[2] || '-1'); - const arrayChildren = ParamType.from({ - type: arrayMatch[1], - components: obj.components, - }); - return new ParamType(_guard$3, name || '', type, 'array', indexed, null, arrayLength, arrayChildren); - } - if (type === 'tuple' || type.startsWith('tuple(' /* fix: ) */) || type.startsWith('(' /* fix: ) */)) { - const comps = obj.components != null ? obj.components.map((c) => ParamType.from(c)) : null; - const tuple = new ParamType(_guard$3, name || '', type, 'tuple', indexed, comps, null, null); - // @TODO: use lexer to validate and normalize type - return tuple; - } - type = verifyBasicType(obj.type); - return new ParamType(_guard$3, name || '', type, type, indexed, null, null, null); - } - /** - * Returns true if `value` is a **ParamType**. - */ - static isParamType(value) { - return value && value[internal$1] === ParamTypeInternal; - } - } - /** - * An abstract class to represent An individual fragment from a parse ABI. - * - * @category Application Binary Interface - */ - class Fragment { - /** - * The type of the fragment. - */ - type; - /** - * The inputs for the fragment. - */ - inputs; - /** - * @ignore - */ - constructor(guard, type, inputs) { - assertPrivate(guard, _guard$3, 'Fragment'); - inputs = Object.freeze(inputs.slice()); - defineProperties(this, { type, inputs }); - } - /** - * Creates a new **Fragment** for `obj`, wich can be any supported ABI frgament type. - */ - static from(obj) { - if (typeof obj === 'string') { - // Try parsing JSON... - try { - Fragment.from(JSON.parse(obj)); - // eslint-disable-next-line no-empty - } - catch (e) { } - // ...otherwise, use the human-readable lexer - return Fragment.from(lex(obj)); - } - if (obj instanceof TokenString) { - // Human-readable ABI (already lexed) - const type = obj.peekKeyword(KwTypes); - switch (type) { - case 'constructor': - return ConstructorFragment.from(obj); - case 'error': - return ErrorFragment.from(obj); - case 'event': - return EventFragment.from(obj); - case 'fallback': - case 'receive': - return FallbackFragment.from(obj); - case 'function': - return FunctionFragment.from(obj); - case 'struct': - return StructFragment.from(obj); - } - } - else if (typeof obj === 'object') { - // JSON ABI - switch (obj.type) { - case 'constructor': - return ConstructorFragment.from(obj); - case 'error': - return ErrorFragment.from(obj); - case 'event': - return EventFragment.from(obj); - case 'fallback': - case 'receive': - return FallbackFragment.from(obj); - case 'function': - return FunctionFragment.from(obj); - case 'struct': - return StructFragment.from(obj); - } - assert(false, `unsupported type: ${obj.type}`, 'UNSUPPORTED_OPERATION', { - operation: 'Fragment.from', - }); - } - assertArgument(false, 'unsupported frgament object', 'obj', obj); - } - /** - * Returns true if `value` is a {@link ConstructorFragment | **ConstructorFragment**}. - */ - static isConstructor(value) { - return ConstructorFragment.isFragment(value); - } - /** - * Returns true if `value` is an {@link ErrorFragment | **ErrorFragment**}. - */ - static isError(value) { - return ErrorFragment.isFragment(value); - } - /** - * Returns true if `value` is an {@link EventFragment | **EventFragment**}. - */ - static isEvent(value) { - return EventFragment.isFragment(value); - } - /** - * Returns true if `value` is a {@link FunctionFragment | **FunctionFragment**}. - */ - static isFunction(value) { - return FunctionFragment.isFragment(value); - } - /** - * Returns true if `value` is a {@link StructFragment | **StructFragment**}. - */ - static isStruct(value) { - return StructFragment.isFragment(value); - } - } - /** - * An abstract class to represent An individual fragment which has a name from a parse ABI. - * - * @category Application Binary Interface - */ - class NamedFragment extends Fragment { - /** - * The name of the fragment. - */ - name; - /** - * @ignore - */ - constructor(guard, type, name, inputs) { - super(guard, type, inputs); - assertArgument(typeof name === 'string' && name.match(regexId), 'invalid identifier', 'name', name); - inputs = Object.freeze(inputs.slice()); - defineProperties(this, { name }); - } - } - function joinParams(format, params) { - return '(' + params.map((p) => p.format(format)).join(format === 'full' ? ', ' : ',') + ')'; - } - /** - * A Fragment which represents a _Custom Error_. - * - * @category Application Binary Interface - */ - class ErrorFragment extends NamedFragment { - /** - * @ignore - */ - constructor(guard, name, inputs) { - super(guard, 'error', name, inputs); - Object.defineProperty(this, internal$1, { value: ErrorFragmentInternal }); - } - /** - * The Custom Error selector. - */ - get selector() { - return id(this.format('sighash')).substring(0, 10); - } - /** - * Returns a string representation of this fragment as `format`. - */ - format(format) { - if (format == null) { - format = 'sighash'; - } - if (format === 'json') { - return JSON.stringify({ - type: 'error', - name: this.name, - inputs: this.inputs.map((input) => JSON.parse(input.format(format))), - }); - } - const result = []; - if (format !== 'sighash') { - result.push('error'); - } - result.push(this.name + joinParams(format, this.inputs)); - return result.join(' '); - } - /** - * Returns a new **ErrorFragment** for `obj`. - */ - static from(obj) { - if (ErrorFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - return ErrorFragment.from(lex(obj)); - } - else if (obj instanceof TokenString) { - const name = consumeName('error', obj); - const inputs = consumeParams(obj); - consumeEoi(obj); - return new ErrorFragment(_guard$3, name, inputs); - } - return new ErrorFragment(_guard$3, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); - } - /** - * Returns `true` and provides a type guard if `value` is an **ErrorFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === ErrorFragmentInternal; - } - } - /** - * A Fragment which represents an Event. - * - * @category Application Binary Interface - */ - class EventFragment extends NamedFragment { - /** - * Whether this event is anonymous. - */ - anonymous; - /** - * @ignore - */ - constructor(guard, name, inputs, anonymous) { - super(guard, 'event', name, inputs); - Object.defineProperty(this, internal$1, { value: EventFragmentInternal }); - defineProperties(this, { anonymous }); - } - /** - * The Event topic hash. - */ - get topicHash() { - return id(this.format('sighash')); - } - /** - * Returns a string representation of this event as `format`. - */ - format(format) { - if (format == null) { - format = 'sighash'; - } - if (format === 'json') { - return JSON.stringify({ - type: 'event', - anonymous: this.anonymous, - name: this.name, - inputs: this.inputs.map((i) => JSON.parse(i.format(format))), - }); - } - const result = []; - if (format !== 'sighash') { - result.push('event'); - } - result.push(this.name + joinParams(format, this.inputs)); - if (format !== 'sighash' && this.anonymous) { - result.push('anonymous'); - } - return result.join(' '); - } - /** - * Return the topic hash for an event with `name` and `params`. - */ - static getTopicHash(name, params) { - params = (params || []).map((p) => ParamType.from(p)); - const fragment = new EventFragment(_guard$3, name, params, false); - return fragment.topicHash; - } - /** - * Returns a new **EventFragment** for `obj`. - */ - static from(obj) { - if (EventFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return EventFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid event fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - const name = consumeName('event', obj); - const inputs = consumeParams(obj, true); - const anonymous = !!consumeKeywords(obj, setify(['anonymous'])).has('anonymous'); - consumeEoi(obj); - return new EventFragment(_guard$3, name, inputs, anonymous); - } - return new EventFragment(_guard$3, obj.name, obj.inputs ? obj.inputs.map((p) => ParamType.from(p, true)) : [], !!obj.anonymous); - } - /** - * Returns `true` and provides a type guard if `value` is an **EventFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === EventFragmentInternal; - } - } - /** - * A Fragment which represents a constructor. - * - * @category Application Binary Interface - */ - class ConstructorFragment extends Fragment { - /** - * Whether the constructor can receive an endowment. - */ - payable; - /** - * The recommended gas limit for deployment or `null`. - */ - gas; - /** - * @ignore - */ - constructor(guard, type, inputs, payable, gas) { - super(guard, type, inputs); - Object.defineProperty(this, internal$1, { value: ConstructorFragmentInternal }); - defineProperties(this, { payable, gas }); - } - /** - * Returns a string representation of this constructor as `format`. - */ - format(format) { - assert(format != null && format !== 'sighash', 'cannot format a constructor for sighash', 'UNSUPPORTED_OPERATION', { operation: 'format(sighash)' }); - if (format === 'json') { - return JSON.stringify({ - type: 'constructor', - stateMutability: this.payable ? 'payable' : 'undefined', - payable: this.payable, - gas: this.gas != null ? this.gas : undefined, - inputs: this.inputs.map((i) => JSON.parse(i.format(format))), - }); - } - const result = [`constructor${joinParams(format, this.inputs)}`]; - if (this.payable) { - result.push('payable'); - } - if (this.gas != null) { - result.push(`@${this.gas.toString()}`); - } - return result.join(' '); - } - /** - * Returns a new **ConstructorFragment** for `obj`. - */ - static from(obj) { - if (ConstructorFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return ConstructorFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid constuctor fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - consumeKeywords(obj, setify(['constructor'])); - const inputs = consumeParams(obj); - const payable = !!consumeKeywords(obj, KwVisibDeploy).has('payable'); - const gas = consumeGas(obj); - consumeEoi(obj); - return new ConstructorFragment(_guard$3, 'constructor', inputs, payable, gas); - } - return new ConstructorFragment(_guard$3, 'constructor', obj.inputs ? obj.inputs.map(ParamType.from) : [], !!obj.payable, obj.gas != null ? obj.gas : null); - } - /** - * Returns `true` and provides a type guard if `value` is a **ConstructorFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === ConstructorFragmentInternal; - } - } - /** - * A Fragment which represents a method. - * - * @category Application Binary Interface - */ - class FallbackFragment extends Fragment { - /** - * If the function can be sent value during invocation. - */ - payable; - constructor(guard, inputs, payable) { - super(guard, 'fallback', inputs); - Object.defineProperty(this, internal$1, { value: FallbackFragmentInternal }); - defineProperties(this, { payable }); - } - /** - * Returns a string representation of this fallback as `format`. - */ - format(format) { - const type = this.inputs.length === 0 ? 'receive' : 'fallback'; - if (format === 'json') { - const stateMutability = this.payable ? 'payable' : 'nonpayable'; - return JSON.stringify({ type, stateMutability }); - } - return `${type}()${this.payable ? ' payable' : ''}`; - } - /** - * Returns a new **FallbackFragment** for `obj`. - */ - static from(obj) { - if (FallbackFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return FallbackFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid fallback fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - const errorObj = obj.toString(); - const topIsValid = obj.peekKeyword(setify(['fallback', 'receive'])); - assertArgument(topIsValid, 'type must be fallback or receive', 'obj', errorObj); - const type = obj.popKeyword(setify(['fallback', 'receive'])); - // receive() - if (type === 'receive') { - const inputs = consumeParams(obj); - assertArgument(inputs.length === 0, `receive cannot have arguments`, 'obj.inputs', inputs); - consumeKeywords(obj, setify(['payable'])); - consumeEoi(obj); - return new FallbackFragment(_guard$3, [], true); - } - // fallback() [payable] - // fallback(bytes) [payable] returns (bytes) - let inputs = consumeParams(obj); - if (inputs.length) { - assertArgument(inputs.length === 1 && inputs[0].type === 'bytes', 'invalid fallback inputs', 'obj.inputs', inputs.map((i) => i.format('minimal')).join(', ')); - } - else { - inputs = [ParamType.from('bytes')]; - } - const mutability = consumeMutability(obj); - assertArgument(mutability === 'nonpayable' || mutability === 'payable', 'fallback cannot be constants', 'obj.stateMutability', mutability); - if (consumeKeywords(obj, setify(['returns'])).has('returns')) { - const outputs = consumeParams(obj); - assertArgument(outputs.length === 1 && outputs[0].type === 'bytes', 'invalid fallback outputs', 'obj.outputs', outputs.map((i) => i.format('minimal')).join(', ')); - } - consumeEoi(obj); - return new FallbackFragment(_guard$3, inputs, mutability === 'payable'); - } - if (obj.type === 'receive') { - return new FallbackFragment(_guard$3, [], true); - } - if (obj.type === 'fallback') { - const inputs = [ParamType.from('bytes')]; - const payable = obj.stateMutability === 'payable'; - return new FallbackFragment(_guard$3, inputs, payable); - } - assertArgument(false, 'invalid fallback description', 'obj', obj); - } - /** - * Returns `true` and provides a type guard if `value` is a **FallbackFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === FallbackFragmentInternal; - } - } - /** - * A Fragment which represents a method. - * - * @category Application Binary Interface - */ - class FunctionFragment extends NamedFragment { - /** - * If the function is constant (e.g. `pure` or `view` functions). - */ - constant; - /** - * The returned types for the result of calling this function. - */ - outputs; - /** - * The state mutability (e.g. `payable`, `nonpayable`, `view` or `pure`) - */ - stateMutability; - /** - * If the function can be sent value during invocation. - */ - payable; - /** - * The recommended gas limit to send when calling this function. - */ - gas; - /** - * @ignore - */ - constructor(guard, name, stateMutability, inputs, outputs, gas) { - super(guard, 'function', name, inputs); - Object.defineProperty(this, internal$1, { value: FunctionFragmentInternal }); - outputs = Object.freeze(outputs.slice()); - const constant = stateMutability === 'view' || stateMutability === 'pure'; - const payable = stateMutability === 'payable'; - defineProperties(this, { constant, gas, outputs, payable, stateMutability }); - } - /** - * The Function selector. - */ - get selector() { - return id(this.format('sighash')).substring(0, 10); - } - /** - * Returns a string representation of this function as `format`. - */ - format(format) { - if (format == null) { - format = 'sighash'; - } - if (format === 'json') { - return JSON.stringify({ - type: 'function', - name: this.name, - constant: this.constant, - stateMutability: this.stateMutability !== 'nonpayable' ? this.stateMutability : undefined, - payable: this.payable, - gas: this.gas != null ? this.gas : undefined, - inputs: this.inputs.map((i) => JSON.parse(i.format(format))), - outputs: this.outputs.map((o) => JSON.parse(o.format(format))), - }); - } - const result = []; - if (format !== 'sighash') { - result.push('function'); - } - result.push(this.name + joinParams(format, this.inputs)); - if (format !== 'sighash') { - if (this.stateMutability !== 'nonpayable') { - result.push(this.stateMutability); - } - if (this.outputs && this.outputs.length) { - result.push('returns'); - result.push(joinParams(format, this.outputs)); - } - if (this.gas != null) { - result.push(`@${this.gas.toString()}`); - } - } - return result.join(' '); - } - /** - * Return the selector for a function with `name` and `params`. - */ - static getSelector(name, params) { - params = (params || []).map((p) => ParamType.from(p)); - const fragment = new FunctionFragment(_guard$3, name, 'view', params, [], null); - return fragment.selector; - } - /** - * Returns a new **FunctionFragment** for `obj`. - */ - static from(obj) { - if (FunctionFragment.isFragment(obj)) { - return obj; - } - if (typeof obj === 'string') { - try { - return FunctionFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid function fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - const name = consumeName('function', obj); - const inputs = consumeParams(obj); - const mutability = consumeMutability(obj); - let outputs = []; - if (consumeKeywords(obj, setify(['returns'])).has('returns')) { - outputs = consumeParams(obj); - } - const gas = consumeGas(obj); - consumeEoi(obj); - return new FunctionFragment(_guard$3, name, mutability, inputs, outputs, gas); - } - let stateMutability = obj.stateMutability; - // Use legacy Solidity ABI logic if stateMutability is missing - if (stateMutability == null) { - stateMutability = 'payable'; - if (typeof obj.constant === 'boolean') { - stateMutability = 'view'; - if (!obj.constant) { - stateMutability = 'payable'; - if (typeof obj.payable === 'boolean' && !obj.payable) { - stateMutability = 'nonpayable'; - } - } - } - else if (typeof obj.payable === 'boolean' && !obj.payable) { - stateMutability = 'nonpayable'; - } - } - // @TODO: verifyState for stateMutability (e.g. throw if - // payable: false but stateMutability is "nonpayable") - return new FunctionFragment(_guard$3, obj.name, stateMutability, obj.inputs ? obj.inputs.map(ParamType.from) : [], obj.outputs ? obj.outputs.map(ParamType.from) : [], obj.gas != null ? obj.gas : null); - } - /** - * Returns `true` and provides a type guard if `value` is a **FunctionFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === FunctionFragmentInternal; - } - } - /** - * A Fragment which represents a structure. - * - * @category Application Binary Interface - */ - class StructFragment extends NamedFragment { - /** - * @ignore - */ - constructor(guard, name, inputs) { - super(guard, 'struct', name, inputs); - Object.defineProperty(this, internal$1, { value: StructFragmentInternal }); - } - /** - * Returns a string representation of this struct as `format`. - */ - format() { - throw new Error('@TODO'); - } - /** - * Returns a new **StructFragment** for `obj`. - */ - static from(obj) { - if (typeof obj === 'string') { - try { - return StructFragment.from(lex(obj)); - } - catch (error) { - assertArgument(false, 'invalid struct fragment', 'obj', obj); - } - } - else if (obj instanceof TokenString) { - const name = consumeName('struct', obj); - const inputs = consumeParams(obj); - consumeEoi(obj); - return new StructFragment(_guard$3, name, inputs); - } - return new StructFragment(_guard$3, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); - } - // @TODO: fix this return type - /** - * Returns `true` and provides a type guard if `value` is a **StructFragment**. - */ - static isFragment(value) { - return value && value[internal$1] === StructFragmentInternal; - } - } - - /** - * When sending values to or receiving values from a [Contract](../classes/Contract), the data is generally encoded - * using the [ABI - * Specification](https://docs.soliditylang.org/en/v0.8.19/abi-spec.html#formal-specification-of-the-encoding). - * - * The AbiCoder provides a utility to encode values to ABI data and decode values from ABI data. - * - * Most of the time, developers should favor the [Contract](../classes/Contract) class, which further abstracts the - * finer details of ABI data. - * - * @category Application Binary Interface - */ - // https://docs.soliditylang.org/en/v0.8.17/control-structures.html - const PanicReasons$1 = new Map(); - PanicReasons$1.set(0x00, 'GENERIC_PANIC'); - PanicReasons$1.set(0x01, 'ASSERT_FALSE'); - PanicReasons$1.set(0x11, 'OVERFLOW'); - PanicReasons$1.set(0x12, 'DIVIDE_BY_ZERO'); - PanicReasons$1.set(0x21, 'ENUM_RANGE_ERROR'); - PanicReasons$1.set(0x22, 'BAD_STORAGE_DATA'); - PanicReasons$1.set(0x31, 'STACK_UNDERFLOW'); - PanicReasons$1.set(0x32, 'ARRAY_RANGE_ERROR'); - PanicReasons$1.set(0x41, 'OUT_OF_MEMORY'); - PanicReasons$1.set(0x51, 'UNINITIALIZED_FUNCTION_CALL'); - const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); - const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); - let defaultCoder = null; - let defaultMaxInflation = 1024; - function getBuiltinCallException(action, tx, data, abiCoder) { - let message = 'missing revert data'; - let reason = null; - const invocation = null; - let revert = null; - if (data) { - message = 'execution reverted'; - const bytes = getBytes(data); - data = hexlify(data); - if (bytes.length === 0) { - message += ' (no data present; likely require(false) occurred'; - reason = 'require(false)'; - } - else if (bytes.length % 32 !== 4) { - message += ' (could not decode reason; invalid data length)'; - } - else if (hexlify(bytes.slice(0, 4)) === '0x08c379a0') { - // Error(string) - try { - reason = abiCoder.decode(['string'], bytes.slice(4))[0]; - revert = { - signature: 'Error(string)', - name: 'Error', - args: [reason], - }; - message += `: ${JSON.stringify(reason)}`; - } - catch (error) { - message += ' (could not decode reason; invalid string data)'; - } - } - else if (hexlify(bytes.slice(0, 4)) === '0x4e487b71') { - // Panic(uint256) - try { - const code = Number(abiCoder.decode(['uint256'], bytes.slice(4))[0]); - revert = { - signature: 'Panic(uint256)', - name: 'Panic', - args: [code], - }; - reason = `Panic due to ${PanicReasons$1.get(code) || 'UNKNOWN'}(${code})`; - message += `: ${reason}`; - } - catch (error) { - message += ' (could not decode panic code)'; - } - } - else { - message += ' (unknown custom error)'; - } - } - const transaction = { - to: tx.to ? getAddress(tx.to) : null, - data: tx.data || '0x', - }; - if (tx.from) { - transaction.from = getAddress(tx.from); - } - return makeError(message, 'CALL_EXCEPTION', { - action, - data, - reason, - transaction, - invocation, - revert, - }); - } - /** - * The **AbiCoder** is a low-level class responsible for encoding JavaScript values into binary data and decoding binary - * data into JavaScript values. - * - * @category Application Binary Interface - */ - class AbiCoder { - #getCoder(param) { - if (param.isArray()) { - return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name); - } - if (param.isTuple()) { - return new TupleCoder(param.components.map((c) => this.#getCoder(c)), param.name); - } - switch (param.baseType) { - case 'address': - return new AddressCoder(param.name); - case 'bool': - return new BooleanCoder(param.name); - case 'string': - return new StringCoder(param.name); - case 'bytes': - return new BytesCoder(param.name); - case '': - return new NullCoder(param.name); - } - // u?int[0-9]* - let match = param.type.match(paramTypeNumber); - if (match) { - const size = parseInt(match[2] || '256'); - assertArgument(size !== 0 && size <= 256 && size % 8 === 0, 'invalid ' + match[1] + ' bit length', 'param', param); - return new NumberCoder(size / 8, match[1] === 'int', param.name); - } - // bytes[0-9]+ - match = param.type.match(paramTypeBytes); - if (match) { - const size = parseInt(match[1]); - assertArgument(size !== 0 && size <= 32, 'invalid bytes length', 'param', param); - return new FixedBytesCoder(size, param.name); - } - assertArgument(false, 'invalid type', 'type', param.type); - } - /** - * Get the default values for the given types. For example, a `uint` is by default `0` and `bool` is by default - * `false`. - * - * @param {(string | ParamType)[]} types - Array of parameter types to get default values for. - * @returns {Result} The default values corresponding to the given types. - */ - getDefaultValue(types) { - const coders = types.map((type) => this.#getCoder(ParamType.from(type))); - const coder = new TupleCoder(coders, '_'); - return coder.defaultValue(); - } - /** - * Encode the values as the specified types into ABI data. - * - * @param {(string | ParamType)[]} types - Array of parameter types. - * @param {any[]} values - Array of values to encode. - * @returns {string} The encoded data in hexadecimal format. - */ - encode(types, values) { - assertArgumentCount(values.length, types.length, 'types/values length mismatch'); - const coders = types.map((type) => this.#getCoder(ParamType.from(type))); - const coder = new TupleCoder(coders, '_'); - const writer = new Writer(); - coder.encode(writer, values); - return writer.data; - } - /** - * Decode the ABI data as the types into values. - * - * If loose decoding is enabled, then strict padding is not enforced. Some older versions of Solidity incorrectly - * padded event data emitted from `external` functions. - * - * @param {(string | ParamType)[]} types - Array of parameter types. - * @param {BytesLike} data - The ABI data to decode. - * @param {boolean} [loose=false] - Enable loose decoding. Default is `false` - * @returns {Result} The decoded values. - */ - decode(types, data, loose) { - const coders = types.map((type) => this.#getCoder(ParamType.from(type))); - const coder = new TupleCoder(coders, '_'); - return coder.decode(new Reader(data, loose, defaultMaxInflation)); - } - /** - * Set the default maximum inflation factor. - * - * @ignore - * @param {number} value - The new inflation factor. - */ - static _setDefaultMaxInflation(value) { - assertArgument(typeof value === 'number' && Number.isInteger(value), 'invalid defaultMaxInflation factor', 'value', value); - defaultMaxInflation = value; - } - /** - * Returns the shared singleton instance of a default {@link AbiCoder | **AbiCoder**}. - * - * On the first call, the instance is created internally. - * - * @returns {AbiCoder} The default ABI coder instance. - */ - static defaultAbiCoder() { - if (defaultCoder == null) { - defaultCoder = new AbiCoder(); - } - return defaultCoder; - } - /** - * Returns a quais-compatible {@link CallExceptionError | **CallExceptionError**} for the given result data. - * - * @param {CallExceptionAction} action - The action that triggered the exception. - * @param {Object} tx - The transaction information. - * @param {BytesLike | null} data - The data associated with the call exception. - * @returns {CallExceptionError} The corresponding call exception error. - */ - static getBuiltinCallException(action, tx, data) { - return getBuiltinCallException(action, tx, data, AbiCoder.defaultAbiCoder()); - } - } - - /** - * The Interface class is a low-level class that accepts an ABI and provides all the necessary functionality to encode - * and decode paramaters to and results from methods, events and errors. - * - * It also provides several convenience methods to automatically search and find matching transactions and events to - * parse them. - * - * @category Application Binary Interface - */ - /** - * When using the {@link Interface.parseLog | **Interface.parseLog**} to automatically match a Log to its event for - * parsing, a **LogDescription** is returned. - * - * @category Application Binary Interface - */ - class LogDescription { - /** - * The matching fragment for the `topic0`. - */ - fragment; - /** - * The name of the Event. - */ - name; - /** - * The full Event signature. - */ - signature; - /** - * The topic hash for the Event. - */ - topic; - /** - * The arguments passed into the Event with `emit`. - */ - args; - /** - * @ignore - */ - constructor(fragment, topic, args) { - const name = fragment.name, signature = fragment.format(); - defineProperties(this, { - fragment, - name, - signature, - topic, - args, - }); - } - } - /** - * When using the {@link Interface.parseTransaction | **Interface.parseTransaction**} to automatically match a - * transaction data to its function for parsing, a **TransactionDescription** is returned. - * - * @category Application Binary Interface - */ - class TransactionDescription { - /** - * The matching fragment from the transaction `data`. - */ - fragment; - /** - * The name of the Function from the transaction `data`. - */ - name; - /** - * The arguments passed to the Function from the transaction `data`. - */ - args; - /** - * The full Function signature from the transaction `data`. - */ - signature; - /** - * The selector for the Function from the transaction `data`. - */ - selector; - /** - * The `value` (in wei) from the transaction. - */ - value; - /** - * @ignore - */ - constructor(fragment, selector, args, value) { - const name = fragment.name, signature = fragment.format(); - defineProperties(this, { - fragment, - name, - args, - signature, - selector, - value, - }); - } - } - /** - * When using the {@link Interface.parseError | **Interface.parseError**} to automatically match an error for a call - * result for parsing, an **ErrorDescription** is returned. - * - * @category Application Binary Interface - */ - class ErrorDescription { - /** - * The matching fragment. - */ - fragment; - /** - * The name of the Error. - */ - name; - /** - * The arguments passed to the Error with `revert`. - */ - args; - /** - * The full Error signature. - */ - signature; - /** - * The selector for the Error. - */ - selector; - /** - * @ignore - */ - constructor(fragment, selector, args) { - const name = fragment.name, signature = fragment.format(); - defineProperties(this, { - fragment, - name, - args, - signature, - selector, - }); - } - } - /** - * An **Indexed** is used as a value when a value that does not fit within a topic (i.e. not a fixed-length, 32-byte - * type). It is the `keccak256` of the value, and used for types such as arrays, tuples, bytes and strings. - * - * @category Application Binary Interface - */ - class Indexed { - /** - * The `keccak256` of the value logged. - */ - hash; - /** - * @ignore - */ - _isIndexed; - /** - * Check if a value is an **Indexed** This provides a Type Guard for property access. - * - * @param value - The value to check. - * - * @returns `true` if the value is an **Indexed**. - */ - static isIndexed(value) { - return !!(value && value._isIndexed); - } - /** - * @ignore - */ - constructor(hash) { - defineProperties(this, { hash, _isIndexed: true }); - } - } - // https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require - const PanicReasons = { - '0': 'generic panic', - '1': 'assert(false)', - '17': 'arithmetic overflow', - '18': 'division or modulo by zero', - '33': 'enum overflow', - '34': 'invalid encoded storage byte array accessed', - '49': 'out-of-bounds array access; popping on an empty array', - '50': 'out-of-bounds access of an array or bytesN', - '65': 'out of memory', - '81': 'uninitialized function', - }; - const BuiltinErrors = { - '0x08c379a0': { - signature: 'Error(string)', - name: 'Error', - inputs: ['string'], - reason: (message) => { - return `reverted with reason string ${JSON.stringify(message)}`; - }, - }, - '0x4e487b71': { - signature: 'Panic(uint256)', - name: 'Panic', - inputs: ['uint256'], - reason: (code) => { - let reason = 'unknown panic code'; - if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) { - reason = PanicReasons[code.toString()]; - } - return `reverted with panic code 0x${code.toString(16)} (${reason})`; - }, - }, - }; - /** - * An Interface abstracts many of the low-level details for encoding and decoding the data on the blockchain. - * - * An ABI provides information on how to encode data to send to a Contract, how to decode the results and events and how - * to interpret revert errors. - * - * The ABI can be specified by {@link InterfaceAbi | any supported format}. - * - * @category Application Binary Interface - */ - class Interface { - /** - * All the Contract ABI members (i.e. methods, events, errors, etc). - */ - fragments; - /** - * The Contract constructor. - */ - deploy; - /** - * The Fallback method, if any. - */ - fallback; - /** - * If receiving ether is supported. - */ - receive; - #errors; - #events; - #functions; - // #structs: Map; - #abiCoder; - /** - * Create a new Interface for the fragments. - * - * @param {InterfaceAbi} fragments - The ABI fragments. - */ - constructor(fragments) { - let abi = []; - if (typeof fragments === 'string') { - abi = JSON.parse(fragments); - } - else { - abi = fragments; - } - this.#functions = new Map(); - this.#errors = new Map(); - this.#events = new Map(); - const frags = []; - for (const a of abi) { - try { - frags.push(Fragment.from(a)); - } - catch (error) { - console.log('Error parsing ABI fragment', error); - } - } - defineProperties(this, { - fragments: Object.freeze(frags), - }); - let fallback = null; - let receive = false; - this.#abiCoder = this.getAbiCoder(); - // Add all fragments by their signature - this.fragments.forEach((fragment, index) => { - let bucket; - switch (fragment.type) { - case 'constructor': - if (this.deploy) { - console.log('duplicate definition - constructor'); - return; - } - defineProperties(this, { deploy: fragment }); - return; - case 'fallback': - if (fragment.inputs.length === 0) { - receive = true; - } - else { - assertArgument(!fallback || fragment.payable !== fallback.payable, 'conflicting fallback fragments', `fragments[${index}]`, fragment); - fallback = fragment; - receive = fallback.payable; - } - return; - case 'function': - bucket = this.#functions; - break; - case 'event': - bucket = this.#events; - break; - case 'error': - bucket = this.#errors; - break; - default: - return; - } - // Two identical entries; ignore it - const signature = fragment.format(); - if (bucket.has(signature)) { - return; - } - bucket.set(signature, fragment); - }); - // If we do not have a constructor add a default - if (!this.deploy) { - defineProperties(this, { - deploy: ConstructorFragment.from('constructor()'), - }); - } - defineProperties(this, { fallback, receive }); - } - /** - * Returns the entire Human-Readable ABI, as an array of signatures, optionally as `minimal` strings, which removes - * parameter names and unneceesary spaces. - */ - format(minimal) { - const format = minimal ? 'minimal' : 'full'; - const abi = this.fragments.map((f) => f.format(format)); - return abi; - } - /** - * Return the JSON-encoded ABI. This is the format Solidiy returns. - */ - formatJson() { - const abi = this.fragments.map((f) => f.format('json')); - // We need to re-bundle the JSON fragments a bit - return JSON.stringify(abi.map((j) => JSON.parse(j))); - } - /** - * The ABI coder that will be used to encode and decode binary data. - */ - getAbiCoder() { - return AbiCoder.defaultAbiCoder(); - } - // Find a function definition by any means necessary (unless it is ambiguous) - #getFunction(key, values, forceUnique) { - // Selector - if (isHexString(key)) { - const selector = key.toLowerCase(); - for (const fragment of this.#functions.values()) { - if (selector === fragment.selector) { - return fragment; - } - } - return null; - } - // It is a bare name, look up the function (will return null if ambiguous) - if (key.indexOf('(') === -1) { - const matching = []; - for (const [name, fragment] of this.#functions) { - if (name.split('(' /* fix:) */)[0] === key) { - matching.push(fragment); - } - } - if (values) { - const lastValue = values.length > 0 ? values[values.length - 1] : null; - let valueLength = values.length; - let allowOptions = true; - if (Typed.isTyped(lastValue) && lastValue.type === 'overrides') { - allowOptions = false; - valueLength--; - } - // Remove all matches that don't have a compatible length. The args - // may contain an overrides, so the match may have n or n - 1 parameters - for (let i = matching.length - 1; i >= 0; i--) { - const inputs = matching[i].inputs.length; - if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) { - matching.splice(i, 1); - } - } - // Remove all matches that don't match the Typed signature - for (let i = matching.length - 1; i >= 0; i--) { - const inputs = matching[i].inputs; - for (let j = 0; j < values.length; j++) { - // Not a typed value - if (!Typed.isTyped(values[j])) { - continue; - } - // We are past the inputs - if (j >= inputs.length) { - if (values[j].type === 'overrides') { - continue; - } - matching.splice(i, 1); - break; - } - // Make sure the value type matches the input type - if (values[j].type !== inputs[j].baseType) { - matching.splice(i, 1); - break; - } - } - } - } - // We found a single matching signature with an overrides, but the - // last value is something that cannot possibly be an options - if (matching.length === 1 && values && values.length !== matching[0].inputs.length) { - const lastArg = values[values.length - 1]; - if (lastArg == null || Array.isArray(lastArg) || typeof lastArg !== 'object') { - matching.splice(0, 1); - } - } - if (matching.length === 0) { - return null; - } - if (matching.length > 1 && forceUnique) { - const matchStr = matching.map((m) => JSON.stringify(m.format())).join(', '); - assertArgument(false, `ambiguous function description (i.e. matches ${matchStr})`, 'key', key); - } - return matching[0]; - } - // Normalize the signature and lookup the function - const result = this.#functions.get(FunctionFragment.from(key).format()); - if (result) { - return result; - } - return null; - } - /** - * Get the function name for `key`, which may be a function selector, function name or function signature that - * belongs to the ABI. - */ - getFunctionName(key) { - const fragment = this.#getFunction(key, null, false); - assertArgument(fragment, 'no matching function', 'key', key); - return fragment.name; - } - /** - * Returns true if `key` (a function selector, function name or function signature) is present in the ABI. - * - * In the case of a function name, the name may be ambiguous, so accessing the - * {@link FunctionFragment | **FunctionFragment**} may require refinement. - */ - hasFunction(key) { - return !!this.#getFunction(key, null, false); - } - /** - * Get the {@link FunctionFragment | **FunctionFragment**} for `key`, which may be a function selector, function name - * or function signature that belongs to the ABI. - * - * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple functions match by - * name. - * - * If the `key` and `values` do not refine to a single function in the ABI, this will throw. - */ - getFunction(key, values) { - return this.#getFunction(key, values || null, true); - } - /** - * Iterate over all functions, calling `callback`, sorted by their name. - */ - forEachFunction(callback) { - const names = Array.from(this.#functions.keys()); - names.sort((a, b) => a.localeCompare(b)); - for (let i = 0; i < names.length; i++) { - const name = names[i]; - callback(this.#functions.get(name), i); - } - } - // Find an event definition by any means necessary (unless it is ambiguous) - #getEvent(key, values, forceUnique) { - // EventTopic - if (isHexString(key)) { - const eventTopic = key.toLowerCase(); - for (const fragment of this.#events.values()) { - if (eventTopic === fragment.topicHash) { - return fragment; - } - } - return null; - } - // It is a bare name, look up the function (will return null if ambiguous) - if (key.indexOf('(') === -1) { - const matching = []; - for (const [name, fragment] of this.#events) { - if (name.split('(' /* fix:) */)[0] === key) { - matching.push(fragment); - } - } - if (values) { - // Remove all matches that don't have a compatible length. - for (let i = matching.length - 1; i >= 0; i--) { - if (matching[i].inputs.length < values.length) { - matching.splice(i, 1); - } - } - // Remove all matches that don't match the Typed signature - for (let i = matching.length - 1; i >= 0; i--) { - const inputs = matching[i].inputs; - for (let j = 0; j < values.length; j++) { - // Not a typed value - if (!Typed.isTyped(values[j])) { - continue; - } - // Make sure the value type matches the input type - if (values[j].type !== inputs[j].baseType) { - matching.splice(i, 1); - break; - } - } - } - } - if (matching.length === 0) { - return null; - } - if (matching.length > 1 && forceUnique) { - const matchStr = matching.map((m) => JSON.stringify(m.format())).join(', '); - assertArgument(false, `ambiguous event description (i.e. matches ${matchStr})`, 'key', key); - } - return matching[0]; - } - // Normalize the signature and lookup the function - const result = this.#events.get(EventFragment.from(key).format()); - if (result) { - return result; - } - return null; - } - /** - * Get the event name for `key`, which may be a topic hash, event name or event signature that belongs to the ABI. - */ - getEventName(key) { - const fragment = this.#getEvent(key, null, false); - assertArgument(fragment, 'no matching event', 'key', key); - return fragment.name; - } - /** - * Returns true if `key` (an event topic hash, event name or event signature) is present in the ABI. - * - * In the case of an event name, the name may be ambiguous, so accessing the - * {@link EventFragment | **EventFragment**} may require refinement. - */ - hasEvent(key) { - return !!this.#getEvent(key, null, false); - } - /** - * Get the {@link EventFragment | **EventFragment**} for `key`, which may be a topic hash, event name or event - * signature that belongs to the ABI. - * - * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple events match by name. - * - * If the `key` and `values` do not refine to a single event in the ABI, this will throw. - */ - getEvent(key, values) { - return this.#getEvent(key, values || null, true); - } - /** - * Iterate over all events, calling `callback`, sorted by their name. - */ - forEachEvent(callback) { - const names = Array.from(this.#events.keys()); - names.sort((a, b) => a.localeCompare(b)); - for (let i = 0; i < names.length; i++) { - const name = names[i]; - callback(this.#events.get(name), i); - } - } - /** - * Get the {@link ErrorFragment | **ErroFragment**} for `key`, which may be an error selector, error name or error - * signature that belongs to the ABI. - * - * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple errors match by name. - * - * If the `key` and `values` do not refine to a single error in the ABI, this will throw. - */ - // TODO: `values` is not used, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - getError(key, values) { - if (isHexString(key)) { - const selector = key.toLowerCase(); - if (BuiltinErrors[selector]) { - return ErrorFragment.from(BuiltinErrors[selector].signature); - } - for (const fragment of this.#errors.values()) { - if (selector === fragment.selector) { - return fragment; - } - } - return null; - } - // It is a bare name, look up the function (will return null if ambiguous) - if (key.indexOf('(') === -1) { - const matching = []; - for (const [name, fragment] of this.#errors) { - if (name.split('(' /* fix:) */)[0] === key) { - matching.push(fragment); - } - } - if (matching.length === 0) { - if (key === 'Error') { - return ErrorFragment.from('error Error(string)'); - } - if (key === 'Panic') { - return ErrorFragment.from('error Panic(uint256)'); - } - return null; - } - else if (matching.length > 1) { - const matchStr = matching.map((m) => JSON.stringify(m.format())).join(', '); - assertArgument(false, `ambiguous error description (i.e. ${matchStr})`, 'name', key); - } - return matching[0]; - } - // Normalize the signature and lookup the function - key = ErrorFragment.from(key).format(); - if (key === 'Error(string)') { - return ErrorFragment.from('error Error(string)'); - } - if (key === 'Panic(uint256)') { - return ErrorFragment.from('error Panic(uint256)'); - } - const result = this.#errors.get(key); - if (result) { - return result; - } - return null; - } - /** - * Iterate over all errors, calling `callback`, sorted by their name. - */ - forEachError(callback) { - const names = Array.from(this.#errors.keys()); - names.sort((a, b) => a.localeCompare(b)); - for (let i = 0; i < names.length; i++) { - const name = names[i]; - callback(this.#errors.get(name), i); - } - } - /** - * @ignore - */ - _decodeParams(params, data) { - return this.#abiCoder.decode(params, data); - } - /** - * @ignore - */ - _encodeParams(params, values) { - return this.#abiCoder.encode(params, values); - } - /** - * Encodes a `tx.data` object for deploying the Contract with the `values` as the constructor arguments. - */ - encodeDeploy(values) { - return this._encodeParams(this.deploy.inputs, values || []); - } - /** - * Decodes the result `data` (e.g. from an `quai_call`) for the specified error (see {@link getError | **getError**} - * for valid values for `key`). - * - * Most developers should prefer the {@link parseCallResult | **parseCallResult**} method instead, which will - * automatically detect a `CALL_EXCEPTION` and throw the corresponding error. - */ - decodeErrorResult(fragment, data) { - if (typeof fragment === 'string') { - const f = this.getError(fragment); - assertArgument(f, 'unknown error', 'fragment', fragment); - fragment = f; - } - assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match error ${fragment.name}.`, 'data', data); - return this._decodeParams(fragment.inputs, dataSlice(data, 4)); - } - /** - * Encodes the transaction revert data for a call result that reverted from the the Contract with the sepcified - * `error` (see {@link getError | **getError**} for valid values for `fragment`) with the `values`. - * - * This is generally not used by most developers, unless trying to mock a result from a Contract. - */ - encodeErrorResult(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getError(fragment); - assertArgument(f, 'unknown error', 'fragment', fragment); - fragment = f; - } - return concat([fragment.selector, this._encodeParams(fragment.inputs, values || [])]); - } - /** - * Decodes the `data` from a transaction `tx.data` for the function specified (see - * {@link getFunction | **getFunction**} for valid values for `fragment`). - * - * Most developers should prefer the {@link parseTransaction | **parseTransaction**} method instead, which will - * automatically detect the fragment. - */ - decodeFunctionData(fragment, data) { - if (typeof fragment === 'string') { - const f = this.getFunction(fragment); - assertArgument(f, 'unknown function', 'fragment', fragment); - fragment = f; - } - assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match function ${fragment.name}.`, 'data', data); - return this._decodeParams(fragment.inputs, dataSlice(data, 4)); - } - /** - * Encodes the `tx.data` for a transaction that calls the function specified (see - * {@link getFunction | **getFunction**} for valid values for `fragment`) with the `values`. - */ - encodeFunctionData(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getFunction(fragment); - assertArgument(f, 'unknown function', 'fragment', fragment); - fragment = f; - } - return concat([fragment.selector, this._encodeParams(fragment.inputs, values || [])]); - } - /** - * Decodes the result `data` (e.g. from an `quai_call`) for the specified function (see - * {@link getFunction | **getFunction**} for valid values for `key`). - * - * Most developers should prefer the {@link parseCallResult | **parseCallResult**} method instead, which will - * automatically detect a `CALL_EXCEPTION` and throw the corresponding error. - */ - decodeFunctionResult(fragment, data) { - if (typeof fragment === 'string') { - const f = this.getFunction(fragment); - assertArgument(f, 'unknown function', 'fragment', fragment); - fragment = f; - } - let message = 'invalid length for result data'; - const bytes = getBytesCopy(data); - if (bytes.length % 32 === 0) { - try { - return this.#abiCoder.decode(fragment.outputs, bytes); - } - catch (error) { - message = 'could not decode result data'; - } - } - // Call returned data with no error, but the data is junk - assert(false, message, 'BAD_DATA', { - value: hexlify(bytes), - info: { method: fragment.name, signature: fragment.format() }, - }); - } - makeError(_data, tx) { - const data = getBytes(_data, 'data'); - const error = AbiCoder.getBuiltinCallException('call', tx, data); - // Not a built-in error; try finding a custom error - const customPrefix = 'execution reverted (unknown custom error)'; - if (error.message.startsWith(customPrefix)) { - const selector = hexlify(data.slice(0, 4)); - const ef = this.getError(selector); - if (ef) { - try { - const args = this.#abiCoder.decode(ef.inputs, data.slice(4)); - error.revert = { - name: ef.name, - signature: ef.format(), - args, - }; - error.reason = error.revert.signature; - error.message = `execution reverted: ${error.reason}`; - } - catch (e) { - error.message = `execution reverted (coult not decode custom error)`; - } - } - } - // Add the invocation, if available - const parsed = this.parseTransaction(tx); - if (parsed) { - error.invocation = { - method: parsed.name, - signature: parsed.signature, - args: parsed.args, - }; - } - return error; - } - /** - * Encodes the result data (e.g. from an `quai_call`) for the specified function (see - * {@link getFunction | **getFunction**} for valid values for `fragment`) with `values`. - * - * This is generally not used by most developers, unless trying to mock a result from a Contract. - */ - encodeFunctionResult(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getFunction(fragment); - assertArgument(f, 'unknown function', 'fragment', fragment); - fragment = f; - } - return hexlify(this.#abiCoder.encode(fragment.outputs, values || [])); - } - // Create the filter for the event with search criteria (e.g. for quai_filterLog) - encodeFilterTopics(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getEvent(fragment); - assertArgument(f, 'unknown event', 'eventFragment', fragment); - fragment = f; - } - assert(values.length <= fragment.inputs.length, `too many arguments for ${fragment.format()}`, 'UNEXPECTED_ARGUMENT', { count: values.length, expectedCount: fragment.inputs.length }); - const topics = []; - if (!fragment.anonymous) { - topics.push(fragment.topicHash); - } - // @TODO: Use the coders for this; to properly support tuples, etc. - const encodeTopic = (param, value) => { - if (param.type === 'string') { - return id(value); - } - else if (param.type === 'bytes') { - return keccak256(hexlify(value)); - } - if (param.type === 'bool' && typeof value === 'boolean') { - value = value ? '0x01' : '0x00'; - } - else if (param.type.match(/^u?int/)) { - value = toBeHex(value); // @TODO: Should this toTwos?? - } - else if (param.type.match(/^bytes/)) { - value = zeroPadBytes(value, 32); - } - else if (param.type === 'address') { - // Check addresses are valid - this.#abiCoder.encode(['address'], [value]); - } - return zeroPadValue(hexlify(value), 32); - }; - values.forEach((value, index) => { - const param = fragment.inputs[index]; - if (!param.indexed) { - assertArgument(value == null, 'cannot filter non-indexed parameters; must be null', 'contract.' + param.name, value); - return; - } - if (value == null) { - topics.push(null); - } - else if (param.baseType === 'array' || param.baseType === 'tuple') { - assertArgument(false, 'filtering with tuples or arrays not supported', 'contract.' + param.name, value); - } - else if (Array.isArray(value)) { - topics.push(value.map((value) => encodeTopic(param, value))); - } - else { - topics.push(encodeTopic(param, value)); - } - }); - // Trim off trailing nulls - while (topics.length && topics[topics.length - 1] === null) { - topics.pop(); - } - return topics; - } - encodeEventLog(fragment, values) { - if (typeof fragment === 'string') { - const f = this.getEvent(fragment); - assertArgument(f, 'unknown event', 'eventFragment', fragment); - fragment = f; - } - const topics = []; - const dataTypes = []; - const dataValues = []; - if (!fragment.anonymous) { - topics.push(fragment.topicHash); - } - assertArgument(values.length === fragment.inputs.length, 'event arguments/values mismatch', 'values', values); - fragment.inputs.forEach((param, index) => { - const value = values[index]; - if (param.indexed) { - if (param.type === 'string') { - topics.push(id(value)); - } - else if (param.type === 'bytes') { - topics.push(keccak256(value)); - } - else if (param.baseType === 'tuple' || param.baseType === 'array') { - // @TODO - throw new Error('not implemented'); - } - else { - topics.push(this.#abiCoder.encode([param.type], [value])); - } - } - else { - dataTypes.push(param); - dataValues.push(value); - } - }); - return { - data: this.#abiCoder.encode(dataTypes, dataValues), - topics: topics, - }; - } - // Decode a filter for the event and the search criteria - decodeEventLog(fragment, data, topics) { - if (typeof fragment === 'string') { - const f = this.getEvent(fragment); - assertArgument(f, 'unknown event', 'eventFragment', fragment); - fragment = f; - } - if (topics != null && !fragment.anonymous) { - const eventTopic = fragment.topicHash; - assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic, 'fragment/topic mismatch', 'topics[0]', topics[0]); - topics = topics.slice(1); - } - const indexed = []; - const nonIndexed = []; - const dynamic = []; - // TODO: `index` is not used, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - fragment.inputs.forEach((param, index) => { - if (param.indexed) { - if (param.type === 'string' || - param.type === 'bytes' || - param.baseType === 'tuple' || - param.baseType === 'array') { - indexed.push(ParamType.from({ type: 'bytes32', name: param.name })); - dynamic.push(true); - } - else { - indexed.push(param); - dynamic.push(false); - } - } - else { - nonIndexed.push(param); - dynamic.push(false); - } - }); - const resultIndexed = topics != null ? this.#abiCoder.decode(indexed, concat(topics)) : null; - const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true); - //const result: (Array & { [ key: string ]: any }) = [ ]; - const values = []; - const keys = []; - let nonIndexedIndex = 0, indexedIndex = 0; - fragment.inputs.forEach((param, index) => { - let value = null; - if (param.indexed) { - if (resultIndexed == null) { - value = new Indexed(null); - } - else if (dynamic[index]) { - value = new Indexed(resultIndexed[indexedIndex++]); - } - else { - try { - value = resultIndexed[indexedIndex++]; - } - catch (error) { - value = error; - } - } - } - else { - try { - value = resultNonIndexed[nonIndexedIndex++]; - } - catch (error) { - value = error; - } - } - values.push(value); - keys.push(param.name || null); - }); - return Result.fromItems(values, keys); - } - /** - * Parses a transaction, finding the matching function and extracts the parameter values along with other useful - * function details. - * - * If the matching function cannot be found, return null. - */ - parseTransaction(tx) { - const data = getBytes(tx.data, 'tx.data'); - const value = getBigInt(tx.value != null ? tx.value : 0, 'tx.value'); - const fragment = this.getFunction(hexlify(data.slice(0, 4))); - if (!fragment) { - return null; - } - const args = this.#abiCoder.decode(fragment.inputs, data.slice(4)); - return new TransactionDescription(fragment, fragment.selector, args, value); - } - // TODO: not implemented - // eslint-disable-next-line @typescript-eslint/no-unused-vars - parseCallResult(data) { - throw new Error('@TODO'); - } - /** - * Parses a receipt log, finding the matching event and extracts the parameter values along with other useful event - * details. - * - * If the matching event cannot be found, returns null. - */ - parseLog(log) { - const fragment = this.getEvent(log.topics[0]); - if (!fragment || fragment.anonymous) { - return null; - } - // @TODO: If anonymous, and the only method, and the input count matches, should we parse? - // Probably not, because just because it is the only event in the ABI does - // not mean we have the full ABI; maybe just a fragment? - return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics)); - } - /** - * Parses a revert data, finding the matching error and extracts the parameter values along with other useful error - * details. - * - * If the matching error cannot be found, returns null. - */ - parseError(data) { - const hexData = hexlify(data); - const fragment = this.getError(dataSlice(hexData, 0, 4)); - if (!fragment) { - return null; - } - const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4)); - return new ErrorDescription(fragment, fragment.selector, args); - } - /** - * Creates a new {@link Interface | **Interface**} from the ABI `value`. - * - * The `value` may be provided as an existing {@link Interface | **Interface**} object, a JSON-encoded ABI or any - * Human-Readable ABI format. - */ - static from(value) { - // Already an Interface, which is immutable - if (value instanceof Interface) { - return value; - } - // JSON - if (typeof value === 'string') { - return new Interface(JSON.parse(value)); - } - // Maybe an interface from an older version, or from a symlinked copy - if (typeof value.format === 'function') { - return new Interface(value.format('json')); - } - // Array of fragments - return new Interface(value); - } - } - - /** - * Converts an address and storage keys into an access set. - * - * @param {string} addr - The address to validate and convert. - * @param {Array} storageKeys - The storage keys to validate and convert. - * @returns {{ address: string; storageKeys: Array }} The access set. - */ - function accessSetify(addr, storageKeys) { - validateAddress(addr); - return { - address: getAddress(addr), - storageKeys: storageKeys.map((storageKey, index) => { - assertArgument(isHexString(storageKey, 32), 'invalid slot', `storageKeys[${index}]`, storageKey); - return storageKey.toLowerCase(); - }), - }; - } - /** - * Returns an {@link AccessList | **AccessList**} from any quasi-supported access-list structure. - * - * @category Transaction - * @param {AccessListish} value - The value to convert to an access list. - * @returns {AccessList} The access list. - * @throws {Error} If the value is not a valid access list. - */ - function accessListify(value) { - if (Array.isArray(value)) { - return value.map((set, index) => { - if (Array.isArray(set)) { - assertArgument(set.length === 2, 'invalid slot set', `value[${index}]`, set); - return accessSetify(set[0], set[1]); - } - assertArgument(set != null && typeof set === 'object', 'invalid address-slot set', 'value', value); - return accessSetify(set.address, set.storageKeys); - }); - } - assertArgument(value != null && typeof value === 'object', 'invalid access list', 'value', value); - const result = Object.keys(value).map((addr) => { - const storageKeys = value[addr].reduce((accum, storageKey) => { - accum[storageKey] = true; - return accum; - }, {}); - return accessSetify(addr, Object.keys(storageKeys).sort()); - }); - result.sort((a, b) => a.address.localeCompare(b.address)); - return result; - } - - /** - * An **AbstractTransaction** describes the common operations to be executed on Quai and Qi ledgers by an Externally - * Owned Account (EOA). This class must be subclassed by concrete implementations of transactions on each ledger. - */ - class AbstractTransaction { - _type; - _signature; - _chainId; - /** - * The transaction type. - * - * If null, the type will be automatically inferred based on explicit properties. - */ - get type() { - return this._type; - } - set type(value) { - switch (value) { - case null: - this._type = null; - break; - case 0: - case 'standard': - this._type = 0; - break; - case 2: - case 'utxo': - this._type = 2; - break; - default: - assertArgument(false, 'unsupported transaction type', 'type', value); - } - } - /** - * The name of the transaction type. - */ - get typeName() { - switch (this.type) { - case 0: - return 'standard'; - case 1: - return 'external'; - case 2: - return 'utxo'; - } - return null; - } - /** - * The chain ID this transaction is valid on. - */ - get chainId() { - return this._chainId; - } - set chainId(value) { - this._chainId = getBigInt(value); - } - /** - * If signed, the signature for this transaction. - */ - get signature() { - return (this._signature || null); - } - set signature(value) { - if (typeof value === 'string') { - this._signature = value; - } - else { - this._signature = (value == null ? null : Signature.from(value)); - } - } - /** - * Creates a new Transaction with default values. - */ - constructor() { - this._type = null; - this._chainId = BigInt(0); - this._signature = null; - } - /** - * The pre-image hash of this transaction. - * - * This is the digest that a [Signer](../interfaces/Signer) must sign to authorize this transaction. - */ - get digest() { - return keccak256(this.unsignedSerialized); - } - /** - * Returns true if signed. - * - * This provides a Type Guard that properties requiring a signed transaction are non-null. - * - * @returns {boolean} Indicates if the transaction is signed. - */ - isSigned() { - return this.signature != null; - } - /** - * The serialized transaction. - * - * This throws if the transaction is unsigned. For the pre-image, use - * {@link AbstractTransaction.unsignedSerialized | **unsignedSerialized** }. - */ - get serialized() { - assert(this.signature != null, 'cannot serialize unsigned transaction; maybe you meant .unsignedSerialized', 'UNSUPPORTED_OPERATION', { operation: '.serialized' }); - return encodeProtoTransaction(this.toProtobuf(true)); - } - /** - * The transaction pre-image. - * - * The hash of this is the digest which needs to be signed to authorize this transaction. - */ - get unsignedSerialized() { - return encodeProtoTransaction(this.toProtobuf(false)); - } - /** - * Return the most "likely" type; currently the highest supported transaction type. - * - * @returns {number} The inferred transaction type. - */ - inferType() { - return this.inferTypes().pop(); - } - /** - * Check if the transaction is external. - * - * @returns {boolean} True if the transaction is external. - */ - get isExternal() { - return this.destZone !== undefined && this.originZone !== this.destZone; - } - } - - /** - * List of supported Qi denominations. - * - * @category Transaction - */ - const denominations = [ - BigInt(1), - BigInt(5), - BigInt(10), - BigInt(50), - BigInt(100), - BigInt(250), - BigInt(500), - BigInt(1000), - BigInt(5000), - BigInt(10000), - BigInt(20000), - BigInt(50000), - BigInt(100000), - BigInt(1000000), - BigInt(10000000), - BigInt(100000000), - BigInt(1000000000), // 1000000 Qi - ]; - /** - * Checks if the provided denomination is valid. - * - * @category Transaction - * @param {bigint} denomination - The denomination to check. - * @returns {boolean} True if the denomination is valid, false otherwise. - */ - function isValidDenomination(denomination) { - return denominations.includes(denomination); - } - /** - * Handles conversion of string to bigint, specifically for transaction parameters. - * - * @ignore - * @category Transaction - * @param {string} value - The value to convert. - * @param {string} param - The parameter name. - * @returns {bigint} The converted value. - */ - function handleBigInt(value, param) { - if (value === '0x') { - return BigInt(0); - } - return getBigInt(value, param); - } - /** - * Given a value, returns an array of supported denominations that sum to the value. - * - * @category Transaction - * @param {bigint} value - The value to denominate. - * @returns {bigint[]} An array of denominations that sum to the value. - * @throws {Error} If the value is less than or equal to 0 or cannot be matched with available denominations. - */ - function denominate(value) { - if (value <= BigInt(0)) { - throw new Error('Value must be greater than 0'); - } - const result = []; - let remainingValue = value; - // Iterate through denominations in descending order - for (let i = denominations.length - 1; i >= 0; i--) { - const denomination = denominations[i]; - // Add the denomination to the result array as many times as possible - while (remainingValue >= denomination) { - result.push(denomination); - remainingValue -= denomination; - } - } - if (remainingValue > 0) { - throw new Error('Unable to match the value with available denominations'); - } - return result; - } - /** - * Represents a UTXO (Unspent Transaction Output). - * - * @category Transaction - * @implements {UTXOLike} - */ - class UTXO { - #txhash; - #index; - #address; - #denomination; - /** - * Gets the transaction hash. - * - * @returns {null | string} The transaction hash. - */ - get txhash() { - return this.#txhash; - } - /** - * Sets the transaction hash. - * - * @param {null | string} value - The transaction hash. - */ - set txhash(value) { - this.#txhash = value; - } - /** - * Gets the index. - * - * @returns {null | number} The index. - */ - get index() { - return this.#index; - } - /** - * Sets the index. - * - * @param {null | number} value - The index. - */ - set index(value) { - this.#index = value; - } - /** - * Gets the address. - * - * @returns {string} The address. - */ - get address() { - return this.#address || ''; - } - /** - * Sets the address. - * - * @param {string} value - The address. - * @throws {Error} If the address is invalid. - */ - set address(value) { - validateAddress(value); - this.#address = value; - } - /** - * Gets the denomination. - * - * @returns {null | bigint} The denomination. - */ - get denomination() { - return this.#denomination; - } - /** - * Sets the denomination. - * - * @param {null | BigNumberish} value - The denomination. - * @throws {Error} If the denomination value is invalid. - */ - set denomination(value) { - if (value == null) { - this.#denomination = null; - return; - } - const denominationBigInt = handleBigInt(value.toString(), 'denomination'); - if (!isValidDenomination(denominationBigInt)) { - throw new Error('Invalid denomination value'); - } - this.#denomination = denominationBigInt; - } - /** - * Constructs a new UTXO instance with null properties. - */ - constructor() { - this.#txhash = null; - this.#index = null; - this.#address = null; - this.#denomination = null; - } - /** - * Converts the UTXO instance to a JSON object. - * - * @returns {any} A JSON representation of the UTXO instance. - */ - toJSON() { - return { - txhash: this.txhash, - index: this.index, - address: this.address, - denomination: this.denomination, - }; - } - /** - * Creates a UTXO instance from a UTXOLike object. - * - * @param {UTXOLike} utxo - The UTXOLike object to convert. - * @returns {UTXO} The UTXO instance. - */ - static from(utxo) { - if (utxo === null) { - return new UTXO(); - } - const result = utxo instanceof UTXO ? utxo : new UTXO(); - if (utxo.txhash != null) { - result.txhash = utxo.txhash; - } - if (utxo.index != null) { - result.index = utxo.index; - } - if (utxo.address != null && utxo.address !== '') { - result.address = utxo.address; - } - if (utxo.denomination != null) { - result.denomination = utxo.denomination; - } - return result; - } - } - - /** - * An **AbstractCoinSelector** provides a base class for other sub-classes to implement the functionality for selecting - * UTXOs for a spend and to properly handle spend and change outputs. - * - * This class is abstract and should not be used directly. Sub-classes should implement the - * {@link AbstractCoinSelector#performSelection | **performSelection**} method to provide the actual coin selection - * logic. - * - * @category Transaction - * @abstract - */ - class AbstractCoinSelector { - #availableUXTOs; - #spendOutputs; - #changeOutputs; - /** - * Gets the available UTXOs. - * @returns {UTXO[]} The available UTXOs. - */ - get availableUXTOs() { - return this.#availableUXTOs; - } - /** - * Sets the available UTXOs. - * @param {UTXOLike[]} value - The UTXOs to set. - */ - set availableUXTOs(value) { - this.#availableUXTOs = value.map((val) => { - const utxo = UTXO.from(val); - this._validateUTXO(utxo); - return utxo; - }); - } - /** - * Gets the spend outputs. - * @returns {UTXO[]} The spend outputs. - */ - get spendOutputs() { - return this.#spendOutputs; - } - /** - * Sets the spend outputs. - * @param {UTXOLike[]} value - The spend outputs to set. - */ - set spendOutputs(value) { - this.#spendOutputs = value.map((utxo) => UTXO.from(utxo)); - } - /** - * Gets the change outputs. - * @returns {UTXO[]} The change outputs. - */ - get changeOutputs() { - return this.#changeOutputs; - } - /** - * Sets the change outputs. - * @param {UTXOLike[]} value - The change outputs to set. - */ - set changeOutputs(value) { - this.#changeOutputs = value.map((utxo) => UTXO.from(utxo)); - } - /** - * Constructs a new AbstractCoinSelector instance with an empty UTXO array. - * @param {UTXOEntry[]} [availableUXTOs=[]] - The initial available UTXOs. - */ - constructor(availableUXTOs = []) { - this.#availableUXTOs = availableUXTOs.map((val) => { - const utxo = UTXO.from(val); - this._validateUTXO(utxo); - return utxo; - }); - this.#spendOutputs = []; - this.#changeOutputs = []; - } - /** - * Validates the provided UTXO instance. In order to be valid for coin selection, the UTXO must have a valid address - * and denomination. - * - * @param {UTXO} utxo - The UTXO to validate. - * @throws {Error} If the UTXO is invalid. - * @protected - */ - _validateUTXO(utxo) { - if (utxo.address == null) { - throw new Error('UTXO address is required'); - } - if (utxo.denomination == null) { - throw new Error('UTXO denomination is required'); - } - } - } - - /** - * The FewestCoinSelector class provides a coin selection algorithm that selects the fewest UTXOs required to meet the - * target amount. This algorithm is useful for minimizing the size of the transaction and the fees associated with it. - * - * This class is a sub-class of {@link AbstractCoinSelector | **AbstractCoinSelector** } and implements the - * {@link AbstractCoinSelector.performSelection | **performSelection** } method to provide the actual coin selection - * logic. - * - * @category Transaction - */ - class FewestCoinSelector extends AbstractCoinSelector { - /** - * The largest first coin selection algorithm. - * - * This algorithm selects the largest UTXOs first, and continues to select UTXOs until the target amount is reached. - * If the total value of the selected UTXOs is greater than the target amount, the remaining value is returned as a - * change output. - * - * @param {SpendTarget} target - The target amount to spend. - * - * @returns {SelectedCoinsResult} The selected UTXOs and change outputs. - */ - performSelection(target) { - this.validateTarget(target); - this.validateUTXOs(); - const sortedUTXOs = this.sortUTXOsByDenomination(this.availableUXTOs, 'desc'); - let totalValue = BigInt(0); - let selectedUTXOs = []; - // Get UTXOs that meets or exceeds the target value - const UTXOsEqualOrGreaterThanTarget = sortedUTXOs.filter((utxo) => utxo.denomination && utxo.denomination >= target.value); - if (UTXOsEqualOrGreaterThanTarget.length > 0) { - // Find the smallest UTXO that meets or exceeds the target value - const optimalUTXO = UTXOsEqualOrGreaterThanTarget.reduce((minDenominationUTXO, currentUTXO) => { - if (!currentUTXO.denomination) - return minDenominationUTXO; - return currentUTXO.denomination < minDenominationUTXO.denomination ? currentUTXO : minDenominationUTXO; - }, UTXOsEqualOrGreaterThanTarget[0]); // Initialize with the first UTXO in the list - selectedUTXOs.push(optimalUTXO); - totalValue += optimalUTXO.denomination; - } - else { - // If no single UTXO meets or exceeds the target, aggregate smaller denominations - // until the target is met/exceeded or there are no more UTXOs to aggregate - while (sortedUTXOs.length > 0 && totalValue < target.value) { - const nextOptimalUTXO = sortedUTXOs.reduce((closest, utxo) => { - if (!utxo.denomination) - return closest; - // Prioritize UTXOs that bring totalValue closer to target.value - const absThisDiff = bigIntAbs(target.value - (totalValue + utxo.denomination)); - const currentClosestDiff = closest && closest.denomination - ? bigIntAbs(target.value - (totalValue + closest.denomination)) - : BigInt(Infinity); - return absThisDiff < currentClosestDiff ? utxo : closest; - }, sortedUTXOs[0]); - // Add the selected UTXO to the selection and update totalValue - selectedUTXOs.push(nextOptimalUTXO); - totalValue += nextOptimalUTXO.denomination; - // Remove the selected UTXO from the list of available UTXOs - const index = sortedUTXOs.findIndex((utxo) => utxo.denomination === nextOptimalUTXO.denomination && utxo.address === nextOptimalUTXO.address); - sortedUTXOs.splice(index, 1); - } - } - // Check if the selected UTXOs meet or exceed the target amount - if (totalValue < target.value) { - throw new Error('Insufficient funds'); - } - // Check if any denominations can be removed from the input set and it still remain valid - selectedUTXOs = this.sortUTXOsByDenomination(selectedUTXOs, 'asc'); - let runningTotal = totalValue; - let lastRemovableIndex = -1; // Index of the last UTXO that can be removed - // Iterate through selectedUTXOs to find the last removable UTXO - for (let i = 0; i < selectedUTXOs.length; i++) { - const utxo = selectedUTXOs[i]; - if (utxo.denomination) { - if (runningTotal - utxo.denomination >= target.value) { - runningTotal -= utxo.denomination; - lastRemovableIndex = i; - } - else { - // Once a UTXO makes the total less than target.value, stop the loop - break; - } - } - } - if (lastRemovableIndex >= 0) { - totalValue -= selectedUTXOs[lastRemovableIndex].denomination; - selectedUTXOs.splice(lastRemovableIndex, 1); - } - // Break down the total spend into properly denominatated UTXOs - const spendDenominations = denominate(target.value); - this.spendOutputs = spendDenominations.map((denomination) => { - const utxo = new UTXO(); - utxo.denomination = denomination; - utxo.address = target.address; - return utxo; - }); - // Calculate change to be returned - const change = totalValue - target.value; - // If there's change, break it down into properly denominatated UTXOs - if (change > BigInt(0)) { - const changeDenominations = denominate(change); - this.changeOutputs = changeDenominations.map((denomination) => { - const utxo = new UTXO(); - utxo.denomination = denomination; - // We do not have access to change addresses here so leave it null - return utxo; - }); - } - else { - this.changeOutputs = []; - } - return { - inputs: selectedUTXOs, - spendOutputs: this.spendOutputs, - changeOutputs: this.changeOutputs, - }; - } - /** - * Sorts UTXOs by their denomination. - * - * @param {UTXO[]} utxos - The UTXOs to sort. - * @param {'asc' | 'desc'} direction - The direction to sort ('asc' for ascending, 'desc' for descending). - * @returns {UTXO[]} The sorted UTXOs. - */ - sortUTXOsByDenomination(utxos, direction) { - if (direction === 'asc') { - return [...utxos].sort((a, b) => { - const diff = (a.denomination ?? BigInt(0)) - (b.denomination ?? BigInt(0)); - return diff > 0 ? 1 : diff < 0 ? -1 : 0; - }); - } - return [...utxos].sort((a, b) => { - const diff = (b.denomination ?? BigInt(0)) - (a.denomination ?? BigInt(0)); - return diff > 0 ? 1 : diff < 0 ? -1 : 0; - }); - } - /** - * Validates the target amount. - * - * @param {SpendTarget} target - The target amount to validate. - * @throws Will throw an error if the target amount is less than or equal to 0. - */ - validateTarget(target) { - if (target.value <= BigInt(0)) { - throw new Error('Target amount must be greater than 0'); - } - } - /** - * Validates the available UTXOs. - * - * @throws Will throw an error if there are no available UTXOs. - */ - validateUTXOs() { - if (this.availableUXTOs.length === 0) { - throw new Error('No UTXOs available'); - } - } - } - - /** - * @ignore - */ - const BN_0$2 = BigInt(0); - function allowNull(format, nullValue) { - return function (value) { - if (value == null) { - return nullValue; - } - return format(value); - }; - } - function arrayOf(format) { - return (array) => { - if (!Array.isArray(array)) { - throw new Error('not an array'); - } - return array.map((i) => format(i)); - }; - } - // Requires an object which matches a fleet of other formatters - // Any FormatFunc may return `undefined` to have the value omitted - // from the result object. Calls preserve `this`. - function object(format, altNames) { - return (value) => { - const result = {}; - for (const key in format) { - let srcKey = key; - if (altNames && key in altNames && !(srcKey in value)) { - for (const altKey of altNames[key]) { - if (altKey in value) { - srcKey = altKey; - break; - } - } - } - try { - const nv = format[key](value[srcKey]); - if (nv !== undefined) { - result[key] = nv; - } - } - catch (error) { - const message = error instanceof Error ? error.message : 'not-an-error'; - assert(false, `invalid value for value.${key} (${message})`, 'BAD_DATA', { value }); - } - } - return result; - }; - } - function formatBoolean(value) { - switch (value) { - case true: - case 'true': - return true; - case false: - case 'false': - return false; - } - assertArgument(false, `invalid boolean; ${JSON.stringify(value)}`, 'value', value); - } - function formatData(value) { - assertArgument(isHexString(value), 'invalid data', 'value', value); - return value; - } - function formatHash(value) { - assertArgument(isHexString(value, 32), 'invalid hash', 'value', value); - return value; - } - function handleNumber(_value, param) { - if (_value === '0x') { - return 0; - } - return getNumber(_value, param); - } - function formatNumber(_value, name) { - const value = getBigInt(_value, 'value'); - const result = toBeArray(value); - assertArgument(result.length <= 32, `value too large`, `tx.${name}`, value); - return result; - } - const _formatLog = object({ - address: getAddress, - blockHash: formatHash, - blockNumber: getNumber, - data: formatData, - index: getNumber, - removed: allowNull(formatBoolean, false), - topics: arrayOf(formatHash), - transactionHash: formatHash, - transactionIndex: getNumber, - }, { - index: ['logIndex'], - }); - function formatLog(value) { - return _formatLog(value); - } - const _formatHeader = object({ - baseFeePerGas: getBigInt, - efficiencyScore: getBigInt, - etxEligibleSlices: formatHash, - etxSetRoot: formatHash, - evmRoot: formatHash, - expansionNumber: getNumber, - extRollupRoot: formatHash, - extTransactionsRoot: formatHash, - extraData: formatData, - gasLimit: getBigInt, - gasUsed: getBigInt, - hash: formatHash, - interlinkRootHash: formatHash, - manifestHash: arrayOf(formatHash), - number: arrayOf(getNumber), - parentDeltaS: arrayOf(getBigInt), - parentEntropy: arrayOf(getBigInt), - parentHash: arrayOf(formatHash), - parentUncledS: arrayOf(allowNull(getBigInt)), - parentUncledSubDeltaS: arrayOf(getBigInt), - primeTerminus: formatHash, - receiptsRoot: formatHash, - sha3Uncles: formatHash, - size: getBigInt, - thresholdCount: getBigInt, - transactionsRoot: formatHash, - uncledS: getBigInt, - utxoRoot: formatHash, - }); - const _formatUncle = object({ - coinbase: allowNull(getAddress), - difficulty: getBigInt, - headerHash: formatHash, - location: formatData, - mixHash: formatHash, - nonce: formatData, - number: getNumber, - parentHash: formatHash, - primeTerminusNumber: getNumber, - time: getBigInt, - txHash: formatHash, - workShare: formatBoolean, - }); - const _formatWoHeader = object({ - coinbase: getAddress, - difficulty: getNumber, - headerHash: formatHash, - location: formatData, - mixHash: formatHash, - nonce: formatData, - number: getNumber, - parentHash: formatHash, - primeTerminusNumber: getNumber, - time: formatData, - txHash: formatHash, - }); - const _formatBlock = object({ - extTransactions: arrayOf((tx) => { - if (typeof tx === 'string') { - return formatHash(tx); - } - return formatExternalTransactionResponse(tx); - }), - hash: formatHash, - header: _formatHeader, - interlinkHashes: arrayOf(formatHash), - order: getNumber, - size: getBigInt, - subManifest: arrayOf(formatData), - totalEntropy: getBigInt, - transactions: arrayOf((tx) => { - if (typeof tx === 'string') { - return formatHash(tx); - } - return formatTransactionResponse(tx); - }), - uncles: allowNull(arrayOf(_formatUncle), []), - woHeader: _formatWoHeader, - }); - function formatBlock(value) { - const result = _formatBlock(value); - result.transactions = value.transactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - if ('originatingTxHash' in tx) { - return formatExternalTransactionResponse(tx); - } - return formatTransactionResponse(tx); - }); - result.extTransactions = value.extTransactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - return formatExternalTransactionResponse(tx); - }); - return result; - } - const _formatReceiptLog = object({ - transactionIndex: getNumber, - blockNumber: getNumber, - transactionHash: formatHash, - address: getAddress, - topics: arrayOf(formatHash), - data: formatData, - index: getNumber, - blockHash: formatHash, - }, { - index: ['logIndex'], - }); - function formatReceiptLog(value) { - return _formatReceiptLog(value); - } - const _formatEtx = object({ - type: allowNull(getNumber, 0), - nonce: allowNull(getNumber), - gasPrice: allowNull(getBigInt), - maxPriorityFeePerGas: allowNull(getBigInt), - maxFeePerGas: allowNull(getBigInt), - gas: allowNull(getBigInt), - value: allowNull(getBigInt, BN_0$2), - input: allowNull(formatData), - to: allowNull(getAddress, null), - accessList: allowNull(accessListify, null), - isCoinbase: allowNull(getNumber, 0), - sender: getAddress, - originatingTxHash: formatHash, - etxIndex: getNumber, - chainId: allowNull(getBigInt, null), - hash: formatHash, - }, { - from: ['sender'], - }); - function formatEtx(value) { - return _formatEtx(value); - } - const _formatTransactionReceipt = object({ - to: allowNull(getAddress, null), - from: allowNull(getAddress, null), - contractAddress: allowNull(getAddress, null), - index: getNumber, - gasUsed: getBigInt, - logsBloom: allowNull(formatData), - blockHash: formatHash, - hash: formatHash, - logs: arrayOf(formatReceiptLog), - blockNumber: getNumber, - cumulativeGasUsed: getBigInt, - effectiveGasPrice: allowNull(getBigInt), - status: allowNull(getNumber), - type: allowNull(getNumber, 0), - etxs: (value) => (value === null ? [] : arrayOf(formatEtx)(value)), - }, { - hash: ['transactionHash'], - index: ['transactionIndex'], - }); - function formatTransactionReceipt(value) { - const result = _formatTransactionReceipt(value); - return result; - } - function formatExternalTransactionResponse(value) { - const result = object({ - hash: formatHash, - type: (value) => { - if (value === '0x' || value == null) { - return 0; - } - return parseInt(value, 16); - }, - accessList: allowNull(accessListify, null), - blockHash: allowNull(formatHash, null), - blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null), - index: allowNull((value) => (value ? BigInt(value) : null), null), - from: allowNull(getAddress, null), - sender: allowNull(getAddress, null), - maxPriorityFeePerGas: allowNull((value) => (value ? BigInt(value) : null)), - maxFeePerGas: allowNull((value) => (value ? BigInt(value) : null)), - gasLimit: allowNull((value) => (value ? BigInt(value) : null), null), - to: allowNull(getAddress, null), - value: allowNull((value) => (value ? BigInt(value) : null), null), - nonce: allowNull((value) => (value ? parseInt(value, 10) : null), null), - creates: allowNull(getAddress, null), - chainId: allowNull((value) => (value ? BigInt(value) : null), null), - isCoinbase: allowNull((value) => (value ? parseInt(value, 10) : null), null), - originatingTxHash: allowNull(formatHash, null), - etxIndex: allowNull((value) => (value ? parseInt(value, 10) : null), null), - etxType: allowNull((value) => value, null), - data: (value) => value, - }, { - data: ['input'], - gasLimit: ['gas'], - index: ['transactionIndex'], - })(value); - // 0x0000... should actually be null - if (result.blockHash && getBigInt(result.blockHash) === BN_0$2) { - result.blockHash = null; - } - return result; - } - function formatTransactionResponse(value) { - // Determine if it is a Quai or Qi transaction based on the type - const transactionType = parseInt(value.type, 16); - let result; - if (transactionType === 0x0 || transactionType === 0x1) { - // QuaiTransactionResponseParams - result = object({ - hash: formatHash, - type: (value) => { - if (value === '0x' || value == null) { - return 0; - } - return parseInt(value, 16); - }, - accessList: allowNull(accessListify, null), - blockHash: allowNull(formatHash, null), - blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null), - index: allowNull((value) => (value ? BigInt(value) : null), null), - from: allowNull(getAddress, null), - sender: allowNull(getAddress, null), - maxPriorityFeePerGas: allowNull((value) => (value ? BigInt(value) : null)), - maxFeePerGas: allowNull((value) => (value ? BigInt(value) : null)), - gasLimit: allowNull((value) => (value ? BigInt(value) : null), null), - to: allowNull(getAddress, null), - value: allowNull((value) => (value ? BigInt(value) : null), null), - nonce: allowNull((value) => (value ? parseInt(value, 10) : null), null), - creates: allowNull(getAddress, null), - chainId: allowNull((value) => (value ? BigInt(value) : null), null), - etxType: allowNull((value) => value, null), - data: (value) => value, - }, { - data: ['input'], - gasLimit: ['gas'], - index: ['transactionIndex'], - })(value); - // Add an access list to supported transaction types - if ((value.type === 0 || value.type === 2) && value.accessList == null) { - result.accessList = []; - } - // Compute the signature - if (value.signature) { - result.signature = Signature.from(value.signature); - // Some backends omit ChainId on legacy transactions, but we can compute it - if (result.chainId == null) { - const chainId = result.signature.legacyChainId; - if (chainId != null) { - result.chainId = chainId; - } - } - } - // 0x0000... should actually be null - if (result.blockHash && getBigInt(result.blockHash) === BN_0$2) { - result.blockHash = null; - } - } - else if (transactionType === 0x2) { - // QiTransactionResponseParams - result = object({ - hash: formatHash, - type: (value) => { - if (value === '0x' || value == null) { - return 0; - } - return parseInt(value, 16); - }, - blockHash: allowNull(formatHash, null), - blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null), - index: allowNull((value) => (value ? BigInt(value) : null), null), - chainId: allowNull((value) => (value ? BigInt(value) : null), null), - signature: (value) => value, - txInputs: allowNull((value) => value.map(_formatTxInput), null), - txOutputs: allowNull((value) => value.map(_formatTxOutput), null), - }, { - index: ['transactionIndex'], - signature: ['utxoSignature'], - txInputs: ['inputs'], - txOutputs: ['outputs'], - })(value); - } - else { - throw new Error('Unknown transaction type'); - } - return result; - } - const _formatTxInput = object({ - txhash: formatTxHash, - index: formatIndex, - pubkey: hexlify, - }, { - txhash: ['PreviousOutPoint', 'TxHash'], - index: ['PreviousOutPoint', 'Index'], - pubkey: ['PubKey'], - }); - function extractTxHash(value) { - if (value && value.TxHash) { - return value.TxHash; - } - throw new Error('Invalid PreviousOutPoint'); - } - function formatTxHash(value) { - return formatHash(extractTxHash(value)); - } - function extractIndex(value) { - if (value && value.Index !== undefined) { - return value.Index; - } - throw new Error('Invalid PreviousOutPoint'); - } - function formatIndex(value) { - return getNumber(extractIndex(value)); - } - const _formatTxOutput = object({ - address: (addr) => hexlify(getAddress(addr)), - denomination: getNumber, - }); - - /** - * Class representing a QiTransaction. - * - * @category Transaction - * @extends {AbstractTransaction} - * @implements {QiTransactionLike} - */ - class QiTransaction extends AbstractTransaction { - #txInputs; - #txOutputs; - /** - * Get transaction inputs. - * - * @returns {TxInput[]} The transaction inputs. - */ - get txInputs() { - return (this.#txInputs ?? []).map((entry) => ({ ...entry })); - } - /** - * Set transaction inputs. - * - * @param {TxInput[] | null} value - The transaction inputs. - * @throws {Error} If the value is not an array. - */ - set txInputs(value) { - if (!Array.isArray(value)) { - throw new Error('txInputs must be an array'); - } - this.#txInputs = value.map((entry) => ({ ...entry })); - } - /** - * Get transaction outputs. - * - * @returns {TxOutput[]} The transaction outputs. - */ - get txOutputs() { - return (this.#txOutputs ?? []).map((output) => ({ ...output })); - } - /** - * Set transaction outputs. - * - * @param {TxOutput[] | null} value - The transaction outputs. - * @throws {Error} If the value is not an array. - */ - set txOutputs(value) { - if (!Array.isArray(value)) { - throw new Error('txOutputs must be an array'); - } - this.#txOutputs = value.map((output) => ({ ...output })); - } - /** - * Get the permuted hash of the transaction as specified by QIP-0010. - * - * @returns {string | null} The transaction hash. - * @throws {Error} If the transaction has no inputs or outputs, or if cross-zone & cross-ledger transactions are not - * supported. - * @see {@link [QIP0010](https://github.com/quai-network/qips/blob/master/qip-0010.md)} - */ - get hash() { - if (this.signature == null) { - return null; - } - if (this.txInputs.length < 1 || this.txOutputs.length < 1) { - throw new Error('Transaction must have at least one input and one output'); - } - const senderAddr = computeAddress(this.txInputs[0].pubkey || ''); - if (!this.destZone || !this.originZone) { - throw new Error(`Invalid zones: origin ${this.originZone} -> destination ${this.destZone} (address: ${senderAddr})`); - } - const isSameLedger = isQiAddress(senderAddr) === isQiAddress(hexlify(this.txOutputs[0].address) || ''); - if (this.isExternal && !isSameLedger) { - throw new Error('Cross-zone & cross-ledger transactions are not supported'); - } - const hexString = this.serialized.startsWith('0x') ? this.serialized.substring(2) : this.serialized; - const dataBuffer = Buffer.from(hexString, 'hex'); - const hashHex = keccak256(dataBuffer); - const hashBuffer = Buffer.from(hashHex.substring(2), 'hex'); - const origin = this.originZone ? parseInt(this.originZone.slice(2), 16) : 0; - hashBuffer[0] = origin; - hashBuffer[1] |= 0x80; - hashBuffer[2] = origin; - hashBuffer[3] |= 0x80; - return '0x' + hashBuffer.toString('hex'); - } - /** - * Get the zone of the sender address. - * - * @returns {Zone | undefined} The origin zone. - */ - get originZone() { - const senderAddr = computeAddress(this.txInputs[0].pubkey || ''); - const zone = getZoneForAddress(senderAddr); - return zone ?? undefined; - } - /** - * Get the zone of the recipient address. - * - * @returns {Zone | undefined} The destination zone. - */ - get destZone() { - const zone = getZoneForAddress(this.txOutputs[0].address); - return zone ?? undefined; - } - /** - * Creates a new Transaction with default values. - */ - constructor() { - super(); - this.#txInputs = []; - this.#txOutputs = []; - } - /** - * Validates the explicit properties and returns a list of compatible transaction types. - * - * @returns {number[]} The compatible transaction types. - */ - inferTypes() { - const types = []; - // Explicit type - if (this.type != null) { - types.push(this.type); - } - else { - types.push(2); - } - types.sort(); - return types; - } - /** - * Create a copy of this transaction. - * - * @returns {QiTransaction} The cloned transaction. - */ - clone() { - return QiTransaction.from(this); - } - /** - * Return a JSON-friendly object. - * - * @returns {QiTransactionLike} The JSON-friendly object. - */ - toJSON() { - const s = (v) => { - if (v == null) { - return null; - } - return v.toString(); - }; - return { - type: this.type, - chainId: s(this.chainId), - signature: this.signature ? this.signature : null, - hash: this.hash, - txInputs: this.txInputs, - txOutputs: this.txOutputs, - }; - } - /** - * Return a protobuf-friendly JSON object. - * - * @param {boolean} [includeSignature=true] - Whether to include the signature. Default is `true` - * @returns {ProtoTransaction} The protobuf-friendly JSON object. - */ - toProtobuf(includeSignature = true) { - const protoTx = { - type: this.type || 2, - chain_id: formatNumber(this.chainId || 0, 'chainId'), - tx_ins: { - tx_ins: this.txInputs.map((input) => ({ - previous_out_point: { - hash: { value: getBytes(input.txhash) }, - index: input.index, - }, - pub_key: getBytes(input.pubkey), - })), - }, - tx_outs: { - tx_outs: this.txOutputs.map((output) => ({ - address: getBytes(output.address), - denomination: output.denomination, - })), - }, - }; - if (this.signature && includeSignature) { - protoTx.signature = getBytes(this.signature); - } - return protoTx; - } - /** - * Create a Transaction from a serialized transaction or a Transaction-like object. - * - * @param {string | QiTransactionLike} tx - The transaction to decode. - * @returns {QiTransaction} The decoded transaction. - * @throws {Error} If the transaction is unsigned and defines a hash. - */ - static from(tx) { - if (typeof tx === 'string') { - const decodedProtoTx = decodeProtoTransaction(getBytes(tx)); - return QiTransaction.fromProto(decodedProtoTx); - } - const result = new QiTransaction(); - if (tx.type != null) { - result.type = tx.type; - } - if (tx.chainId != null) { - result.chainId = tx.chainId; - } - if (tx.signature != null && tx.signature !== '') { - result.signature = tx.signature; - } - if (tx.txInputs != null) { - result.txInputs = tx.txInputs; - } - if (tx.txOutputs != null) { - result.txOutputs = tx.txOutputs; - } - if (tx.hash != null) { - assertArgument(result.isSigned(), 'unsigned transaction cannot define hash', 'tx', tx); - } - return result; - } - /** - * Create a Transaction from a ProtoTransaction object. - * - * @param {ProtoTransaction} protoTx - The transaction to decode. - * @returns {QiTransaction} The decoded transaction. - */ - static fromProto(protoTx) { - const tx = new QiTransaction(); - tx.type = protoTx.type; - tx.chainId = toBigInt(protoTx.chain_id); - if (protoTx.type == 2) { - tx.txInputs = - protoTx.tx_ins?.tx_ins.map((input) => ({ - txhash: hexlify(input.previous_out_point.hash.value), - index: input.previous_out_point.index, - pubkey: hexlify(input.pub_key), - })) ?? []; - tx.txOutputs = - protoTx.tx_outs?.tx_outs.map((output) => ({ - address: hexlify(output.address), - denomination: output.denomination, - })) ?? []; - } - if (protoTx.signature) { - tx.signature = hexlify(protoTx.signature); - } - return tx; - } - } - - /** - * Parses a signature from an array of fields. - * - * @ignore - * @param {string[]} fields - The fields to parse. - * @returns {Signature} The parsed signature. - */ - function _parseSignature(fields) { - let yParity; - try { - yParity = handleNumber(fields[0], 'yParity'); - if (yParity !== 0 && yParity !== 1) { - throw new Error('bad yParity'); - } - } - catch (error) { - assertArgument(false, 'invalid yParity', 'yParity', fields[0]); - } - const r = zeroPadValue(fields[1], 32); - const s = zeroPadValue(fields[2], 32); - return Signature.from({ r, s, yParity }); - } - /** - * Represents a Quai transaction. - * - * @category Transaction - */ - class QuaiTransaction extends AbstractTransaction { - #to; - #data; - #nonce; - #gasLimit; - #gasPrice; - #maxPriorityFeePerGas; - #maxFeePerGas; - #value; - #accessList; - from; - /** - * The `to` address for the transaction or `null` if the transaction is an `init` transaction. - * - * @type {null | string} - */ - get to() { - return this.#to; - } - set to(value) { - if (value !== null) - validateAddress(value); - this.#to = value; - } - /** - * The permuted hash of the transaction as specified by - * [QIP-0010](https://github.com/quai-network/qips/blob/master/qip-0010.md). - * - * @type {null | string} - * @throws {Error} If the transaction is not signed. - */ - get hash() { - if (this.signature == null) - return null; - if (!this.originZone) { - throw new Error('Invalid Zone for from address'); - } - if (!this.from) { - throw new Error('Missing from address'); - } - const isSameLedger = !this.to || isQuaiAddress(this.from) === isQuaiAddress(this.to); - if (this.isExternal && !isSameLedger) { - throw new Error('Cross-zone & cross-ledger transactions are not supported'); - } - const hexString = this.serialized.startsWith('0x') ? this.serialized.substring(2) : this.serialized; - const dataBuffer = Buffer.from(hexString, 'hex'); - const hashHex = keccak256(dataBuffer); - const hashBuffer = Buffer.from(hashHex.substring(2), 'hex'); - const origin = this.originZone ? parseInt(this.originZone.slice(2), 16) : 0; - hashBuffer[0] = origin; - hashBuffer[1] &= 0x7f; - hashBuffer[2] = origin; - hashBuffer[3] &= 0x7f; - return '0x' + hashBuffer.toString('hex'); - } - /** - * The zone of the sender address - * - * @type {Zone | undefined} - */ - get originZone() { - const zone = this.from ? getZoneForAddress(this.from) : undefined; - return zone ?? undefined; - } - /** - * The zone of the recipient address - * - * @type {Zone | undefined} - */ - get destZone() { - const zone = this.to !== null ? getZoneForAddress(this.to || '') : undefined; - return zone ?? undefined; - } - /** - * The transaction nonce. - * - * @type {number} - */ - get nonce() { - return this.#nonce; - } - set nonce(value) { - this.#nonce = getNumber(value, 'value'); - } - /** - * The gas limit. - * - * @type {bigint} - */ - get gasLimit() { - return this.#gasLimit; - } - set gasLimit(value) { - this.#gasLimit = getBigInt(value); - } - /** - * The gas price. - * - * On legacy networks this defines the fee that will be paid. On EIP-1559 networks, this should be `null`. - * - * @type {null | bigint} - */ - get gasPrice() { - const value = this.#gasPrice; - return value; - } - set gasPrice(value) { - this.#gasPrice = value == null ? null : getBigInt(value, 'gasPrice'); - } - /** - * The maximum priority fee per unit of gas to pay. On legacy networks this should be `null`. - * - * @type {null | bigint} - */ - get maxPriorityFeePerGas() { - const value = this.#maxPriorityFeePerGas; - if (value == null) { - return null; - } - return value; - } - set maxPriorityFeePerGas(value) { - this.#maxPriorityFeePerGas = value == null ? null : getBigInt(value, 'maxPriorityFeePerGas'); - } - /** - * The maximum total fee per unit of gas to pay. On legacy networks this should be `null`. - * - * @type {null | bigint} - */ - get maxFeePerGas() { - const value = this.#maxFeePerGas; - if (value == null) { - return null; - } - return value; - } - set maxFeePerGas(value) { - this.#maxFeePerGas = value == null ? null : getBigInt(value, 'maxFeePerGas'); - } - /** - * The transaction data. For `init` transactions this is the deployment code. - * - * @type {string} - */ - get data() { - return this.#data; - } - set data(value) { - this.#data = hexlify(value); - } - /** - * The amount of ether to send in this transactions. - * - * @type {bigint} - */ - get value() { - return this.#value; - } - set value(value) { - this.#value = getBigInt(value, 'value'); - } - /** - * The access list. - * - * An access list permits discounted (but pre-paid) access to bytecode and state variable access within contract - * execution. - * - * @type {null | AccessList} - */ - get accessList() { - const value = this.#accessList || null; - if (value == null) { - return null; - } - return value; - } - set accessList(value) { - this.#accessList = value == null ? null : accessListify(value); - } - /** - * Creates a new Transaction with default values. - * - * @param {string} [from] - The sender address. - */ - constructor(from) { - super(); - this.#to = null; - this.#nonce = 0; - this.#gasLimit = BigInt(0); - this.#gasPrice = null; - this.#maxPriorityFeePerGas = null; - this.#maxFeePerGas = null; - this.#data = '0x'; - this.#value = BigInt(0); - this.#accessList = null; - this.from = from; - } - /** - * Validates the explicit properties and returns a list of compatible transaction types. - * - * @returns {number[]} The compatible transaction types. - */ - inferTypes() { - if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) { - assert(this.maxFeePerGas >= this.maxPriorityFeePerGas, 'priorityFee cannot be more than maxFee', 'BAD_DATA', { value: this }); - } - assert(this.type !== 0 && this.type !== 1, 'transaction type cannot have externalGasLimit, externalGasTip, externalGasPrice, externalData, or externalAccessList', 'BAD_DATA', { value: this }); - const types = []; - // Explicit type - if (this.type != null) { - types.push(this.type); - } - else { - types.push(0); - } - types.sort(); - return types; - } - /** - * Create a copy of this transaction. - * - * @returns {QuaiTransaction} The cloned transaction. - */ - clone() { - return QuaiTransaction.from(this); - } - /** - * Return a JSON-friendly object. - * - * @returns {QuaiTransactionLike} The JSON-friendly object. - */ - toJSON() { - const s = (v) => { - if (v == null) { - return null; - } - return v.toString(); - }; - return { - type: this.type, - to: this.to, - from: this.from, - data: this.data, - nonce: this.nonce, - gasLimit: s(this.gasLimit), - gasPrice: s(this.gasPrice), - maxPriorityFeePerGas: s(this.maxPriorityFeePerGas), - maxFeePerGas: s(this.maxFeePerGas), - value: s(this.value), - chainId: s(this.chainId), - signature: this.signature ? this.signature.toJSON() : null, - hash: this.hash, - accessList: this.accessList, - }; - } - /** - * Return a protobuf-friendly JSON object. - * - * @param {boolean} [includeSignature=true] - Whether to include the signature. Default is `true` - * @returns {ProtoTransaction} The protobuf-friendly JSON object. - */ - toProtobuf(includeSignature = true) { - const protoTx = { - type: this.type || 0, - chain_id: formatNumber(this.chainId || 0, 'chainId'), - nonce: this.nonce || 0, - gas_tip_cap: formatNumber(this.maxPriorityFeePerGas || 0, 'maxPriorityFeePerGas'), - gas_fee_cap: formatNumber(this.maxFeePerGas || 0, 'maxFeePerGas'), - gas: Number(this.gasLimit || 0), - to: this.to != null ? getBytes(this.to) : null, - value: formatNumber(this.value || 0, 'value'), - data: getBytes(this.data || '0x'), - access_list: { access_tuples: [] }, - }; - if (this.signature && includeSignature) { - protoTx.v = formatNumber(this.signature.yParity, 'yParity'); - protoTx.r = toBeArray(this.signature.r); - protoTx.s = toBeArray(this.signature.s); - } - return protoTx; - } - /** - * Create a **Transaction** from a serialized transaction or a Transaction-like object. - * - * @param {string | QuaiTransactionLike} tx - The transaction to decode. - * @returns {QuaiTransaction} The decoded transaction. - */ - static from(tx) { - if (typeof tx === 'string') { - const decodedProtoTx = decodeProtoTransaction(getBytes(tx)); - return QuaiTransaction.fromProto(decodedProtoTx); - } - const result = new QuaiTransaction(tx.from); - if (tx.type != null) { - result.type = tx.type; - } - if (tx.to != null) { - validateAddress(tx.to); - result.to = tx.to; - } - if (tx.nonce != null) { - result.nonce = tx.nonce; - } - if (tx.gasLimit != null) { - result.gasLimit = tx.gasLimit; - } - if (tx.maxPriorityFeePerGas != null) { - result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas; - } - if (tx.maxFeePerGas != null) { - result.maxFeePerGas = tx.maxFeePerGas; - } - if (tx.data != null && tx.data !== '') { - result.data = tx.data; - } - if (tx.value != null) { - result.value = tx.value; - } - if (tx.chainId != null) { - result.chainId = tx.chainId; - } - if (tx.signature != null) { - result.signature = Signature.from(tx.signature); - } - if (tx.accessList != null) { - result.accessList = tx.accessList; - } - if (tx.hash != null) { - assertArgument(result.isSigned(), 'unsigned transaction cannot define hash', 'tx', tx); - } - if (tx.from != null) { - assertArgument(isQuaiAddress(tx.from), 'from address must be a Quai address', 'tx.from', tx.from); - assertArgument((result.from || '').toLowerCase() === (tx.from || '').toLowerCase(), 'from mismatch', 'tx', tx); - result.from = tx.from; - } - return result; - } - /** - * Create a **Transaction** from a ProtoTransaction object. - * - * @param {ProtoTransaction} protoTx - The transaction to decode. - * @returns {QuaiTransaction} The decoded transaction. - */ - static fromProto(protoTx) { - // TODO: Fix this because new tx instance requires a 'from' address - let signature = null; - let address = ''; - if (protoTx.v && protoTx.r && protoTx.s) { - // check if protoTx.r is zero - if (protoTx.r.reduce((acc, val) => (acc += val), 0) == 0) { - throw new Error('Proto decoding only supported for signed transactions'); - } - const signatureFields = [hexlify(protoTx.v), hexlify(protoTx.r), hexlify(protoTx.s)]; - signature = _parseSignature(signatureFields); - const protoTxCopy = structuredClone(protoTx); - delete protoTxCopy.v; - delete protoTxCopy.r; - delete protoTxCopy.s; - delete protoTxCopy.signature; - delete protoTxCopy.etx_sender; - delete protoTxCopy.etx_index; - address = recoverAddress(keccak256(encodeProtoTransaction(protoTxCopy)), signature); - } - const tx = new QuaiTransaction(address); - if (signature) { - tx.signature = signature; - } - if (protoTx.to !== null) { - const toAddr = hexlify(protoTx.to); - tx.to = getAddress(toAddr); - } - tx.type = protoTx.type; - tx.chainId = toBigInt(protoTx.chain_id); - tx.nonce = Number(protoTx.nonce); - tx.maxPriorityFeePerGas = toBigInt(protoTx.gas_tip_cap); - tx.maxFeePerGas = toBigInt(protoTx.gas_fee_cap); - tx.gasLimit = toBigInt(protoTx.gas); - tx.value = protoTx.value !== null ? toBigInt(protoTx.value) : BigInt(0); - tx.data = hexlify(protoTx.data); - tx.accessList = protoTx.access_list.access_tuples.map((tuple) => ({ - address: hexlify(tuple.address), - storageKeys: tuple.storage_key.map((key) => hexlify(key)), - })); - return tx; - } - } - - const BN_0$1 = BigInt(0); - /** - * Get the value if it is not null or undefined. - * - * @ignore - * @param {undefined | null | T} value - The value to check. - * @returns {null | T} The value if not null or undefined, otherwise null. - */ - function getValue(value) { - if (value == null) { - return null; - } - return value; - } - /** - * Convert a value to a JSON-friendly string. - * - * @ignore - * @param {null | bigint | string} value - The value to convert. - * @returns {null | string} The JSON-friendly string or null. - */ - function toJson(value) { - if (value == null) { - return null; - } - return value.toString(); - } - /** - * A **FeeData** wraps all the fee-related values associated with the network. - * - * @category Providers - */ - class FeeData { - /** - * The gas price for legacy networks. - */ - gasPrice; - /** - * The maximum fee to pay per gas. - * - * The base fee per gas is defined by the network and based on congestion, increasing the cost during times of heavy - * load and lowering when less busy. - * - * The actual fee per gas will be the base fee for the block and the priority fee, up to the max fee per gas. - * - * This will be `null` on legacy networks (i.e. [pre-EIP-1559](https://eips.ethereum.org/EIPS/eip-1559)) - */ - maxFeePerGas; - /** - * The additional amount to pay per gas to encourage a validator to include the transaction. - * - * The purpose of this is to compensate the validator for the adjusted risk for including a given transaction. - * - * This will be `null` on legacy networks (i.e. [pre-EIP-1559](https://eips.ethereum.org/EIPS/eip-1559)) - */ - maxPriorityFeePerGas; - /** - * Creates a new FeeData for `gasPrice`, `maxFeePerGas` and `maxPriorityFeePerGas`. - * - * @param {null | bigint} [gasPrice] - The gas price. - * @param {null | bigint} [maxFeePerGas] - The maximum fee per gas. - * @param {null | bigint} [maxPriorityFeePerGas] - The maximum priority fee per gas. - */ - constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas) { - defineProperties(this, { - gasPrice: getValue(gasPrice), - maxFeePerGas: getValue(maxFeePerGas), - maxPriorityFeePerGas: getValue(maxPriorityFeePerGas), - }); - } - /** - * Returns a JSON-friendly value. - * - * @returns {any} The JSON-friendly value. - */ - toJSON() { - const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; - return { - _type: 'FeeData', - gasPrice: toJson(gasPrice), - maxFeePerGas: toJson(maxFeePerGas), - maxPriorityFeePerGas: toJson(maxPriorityFeePerGas), - }; - } - } - /** - * Determines the address from a transaction request. - * - * @param {TransactionRequest} tx - The transaction request. - * @returns {AddressLike} The address from the transaction request. - * @throws {Error} If unable to determine the address. - */ - function addressFromTransactionRequest(tx) { - if ('from' in tx && !!tx.from) { - return tx.from; - } - if ('txInputs' in tx && !!tx.txInputs) { - return computeAddress(tx.txInputs[0].pubkey); - } - if ('to' in tx && !!tx.to) { - return tx.to; - } - throw new Error('Unable to determine address from transaction inputs, from or to field'); - } - /** - * Returns a copy of `req` with all properties coerced to their strict types. - * - * @category Providers - * @param {TransactionRequest} req - The transaction request to copy. - * @returns {PreparedTransactionRequest} The prepared transaction request. - * @throws {Error} If the request is invalid. - */ - function copyRequest(req) { - const result = {}; - // These could be addresses or Addressables - if ('to' in req && req.to) { - result.to = req.to; - } - if ('from' in req && req.from) { - result.from = req.from; - } - if ('data' in req && req.data) { - result.data = hexlify(req.data); - } - const bigIntKeys = 'chainId,gasLimit,gasPrice,maxFeePerGas,maxPriorityFeePerGas,value'.split(/,/); - for (const key of bigIntKeys) { - if (!(key in req) || req[key] == null) { - continue; - } - result[key] = getBigInt(req[key], `request.${key}`); - } - const numberKeys = 'type,nonce'.split(/,/); - for (const key of numberKeys) { - if (!(key in req) || req[key] == null) { - continue; - } - result[key] = getNumber(req[key], `request.${key}`); - } - if ('accessList' in req && req.accessList) { - result.accessList = accessListify(req.accessList); - } - if ('blockTag' in req) { - result.blockTag = req.blockTag; - } - if ('customData' in req) { - result.customData = req.customData; - } - if ('txInputs' in req && req.txInputs) { - result.txInputs = req.txInputs.map((entry) => ({ ...entry })); - } - if ('txOutputs' in req && req.txOutputs) { - result.txOutputs = req.txOutputs.map((entry) => ({ ...entry })); - } - return result; - } - /** - * Represents the header of a block. - * - * @category Providers - */ - class BlockHeader { - baseFeePerGas; - efficiencyScore; - etxEligibleSlices; - etxSetRoot; - evmRoot; - expansionNumber; - extRollupRoot; - extTransactionsRoot; - extraData; - gasLimit; - gasUsed; - hash; - interlinkRootHash; - manifestHash; - number; - parentDeltaS; - parentEntropy; - parentHash; - parentUncledS; - parentUncledSubDeltaS; - primeTerminus; - receiptsRoot; - sha3Uncles; - size; - thresholdCount; - transactionsRoot; - uncledS; - utxoRoot; - constructor(params) { - this.baseFeePerGas = params.baseFeePerGas; - this.efficiencyScore = params.efficiencyScore; - this.etxEligibleSlices = params.etxEligibleSlices; - this.etxSetRoot = params.etxSetRoot; - this.evmRoot = params.evmRoot; - this.expansionNumber = params.expansionNumber; - this.extRollupRoot = params.extRollupRoot; - this.extTransactionsRoot = params.extTransactionsRoot; - this.extraData = params.extraData; - this.gasLimit = params.gasLimit; - this.gasUsed = params.gasUsed; - this.hash = params.hash; - this.interlinkRootHash = params.interlinkRootHash; - this.manifestHash = params.manifestHash; - this.number = params.number; - this.parentDeltaS = params.parentDeltaS; - this.parentEntropy = params.parentEntropy; - this.parentHash = params.parentHash; - this.parentUncledS = params.parentUncledS; - this.parentUncledSubDeltaS = params.parentUncledSubDeltaS; - this.primeTerminus = params.primeTerminus; - this.receiptsRoot = params.receiptsRoot; - this.sha3Uncles = params.sha3Uncles; - this.size = params.size; - this.thresholdCount = params.thresholdCount; - this.transactionsRoot = params.transactionsRoot; - this.uncledS = params.uncledS; - this.utxoRoot = params.utxoRoot; - } - toJSON() { - return { - baseFeePerGas: this.baseFeePerGas, - efficiencyScore: this.efficiencyScore, - etxEligibleSlices: this.etxEligibleSlices, - etxSetRoot: this.etxSetRoot, - evmRoot: this.evmRoot, - expansionNumber: this.expansionNumber, - extRollupRoot: this.extRollupRoot, - extTransactionsRoot: this.extTransactionsRoot, - extraData: this.extraData, - gasLimit: this.gasLimit, - gasUsed: this.gasUsed, - hash: this.hash, - interlinkRootHash: this.interlinkRootHash, - manifestHash: this.manifestHash, - number: this.number, - parentDeltaS: this.parentDeltaS, - parentEntropy: this.parentEntropy, - parentHash: this.parentHash, - parentUncledS: this.parentUncledS, - parentUncledSubDeltaS: this.parentUncledSubDeltaS, - primeTerminus: this.primeTerminus, - receiptsRoot: this.receiptsRoot, - sha3Uncles: this.sha3Uncles, - size: this.size, - thresholdCount: this.thresholdCount, - transactionsRoot: this.transactionsRoot, - uncledS: this.uncledS, - utxoRoot: this.utxoRoot, - }; - } - } - /** - * Represents the header of a work object. - * - * @category Providers - */ - class WoHeader { - difficulty; - headerHash; - location; - mixHash; - nonce; - number; - parentHash; - time; - txHash; - /** - * Creates a new WoHeader instance. - * - * @param {WoHeaderParams} params - The parameters for the WoHeader. - */ - constructor(params) { - this.difficulty = params.difficulty; - this.headerHash = params.headerHash; - this.location = params.location; - this.mixHash = params.mixHash; - this.nonce = params.nonce; - this.number = params.number; - this.parentHash = params.parentHash; - this.time = params.time; - this.txHash = params.txHash; - } - toJSON() { - return { - difficulty: this.difficulty, - headerHash: this.headerHash, - location: this.location, - mixHash: this.mixHash, - nonce: this.nonce, - number: this.number, - parentHash: this.parentHash, - time: this.time, - txHash: this.txHash, - }; - } - } - /** - * A **Block** represents the data associated with a full block on Ethereum. - * - * @category Providers - */ - class Block { - #extTransactions; - hash; - header; - interlinkHashes; // New parameter - order; - size; - subManifest; - totalEntropy; - #transactions; - uncles; - woHeader; // New nested parameter structure - /** - * The provider connected to the block used to fetch additional details if necessary. - */ - provider; - /** - * Create a new **Block** object. - * - * This should generally not be necessary as the unless implementing a low-level library. - * - * @param {BlockParams} block - The block parameters. - * @param {Provider} provider - The provider. - */ - constructor(block, provider) { - this.#transactions = block.transactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - if ('originatingTxHash' in tx) { - return new ExternalTransactionResponse(tx, provider); - } - if ('from' in tx) { - return new QuaiTransactionResponse(tx, provider); - } - return new QiTransactionResponse(tx, provider); - }); - this.#extTransactions = block.extTransactions.map((tx) => { - if (typeof tx !== 'string') { - return new ExternalTransactionResponse(tx, provider); - } - return tx; - }); - this.hash = block.hash; - this.header = new BlockHeader(block.header); - this.interlinkHashes = block.interlinkHashes; - this.order = block.order; - this.size = block.size; - this.subManifest = block.subManifest; - this.totalEntropy = block.totalEntropy; - this.uncles = block.uncles; - this.woHeader = new WoHeader(block.woHeader); - this.provider = provider; - } - /** - * Returns the list of transaction hashes, in the order they were executed within the block. - * - * @returns {ReadonlyArray} The list of transaction hashes. - */ - get transactions() { - return this.#transactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - return tx.hash; - }); - } - /** - * Returns the list of extended transaction hashes, in the order they were executed within the block. - * - * @returns {ReadonlyArray} The list of extended transaction hashes. - */ - get extTransactions() { - return this.#extTransactions.map((tx) => { - if (typeof tx === 'string') { - return tx; - } - return tx.hash; - }); - } - /** - * Returns the complete transactions, in the order they were executed within the block. - * - * This is only available for blocks which prefetched transactions, by passing `true` to `prefetchTxs` into - * {@link Provider.getBlock | **getBlock**}. - * - * @returns {TransactionResponse[]} The list of prefetched transactions. - * @throws {Error} If the transactions were not prefetched. - */ - get prefetchedTransactions() { - const txs = this.#transactions.slice(); - // Doesn't matter... - if (txs.length === 0) { - return []; - } - // Make sure we prefetched the transactions - assert(typeof txs[0] === 'object', 'transactions were not prefetched with block request', 'UNSUPPORTED_OPERATION', { - operation: 'transactionResponses()', - }); - return txs; - } - /** - * Returns the complete extended transactions, in the order they were executed within the block. - * - * This is only available for blocks which prefetched transactions, by passing `true` to `prefetchTxs` into - * {@link Provider.getBlock | **getBlock**}. - * - * @returns {TransactionResponse[]} The list of prefetched extended transactions. - * @throws {Error} If the transactions were not prefetched. - */ - get prefetchedExtTransactions() { - const txs = this.#extTransactions.slice(); - // Doesn't matter... - if (txs.length === 0) { - return []; - } - // Make sure we prefetched the transactions - assert(typeof txs[0] === 'object', 'transactions were not prefetched with block request', 'UNSUPPORTED_OPERATION', { - operation: 'transactionResponses()', - }); - return txs; - } - /** - * Returns a JSON-friendly value. - * - * @returns {any} The JSON-friendly value. - */ - toJSON() { - const { hash, header, interlinkHashes, order, size, subManifest, totalEntropy, uncles, woHeader } = this; - // Using getters to retrieve the transactions and extTransactions - const transactions = this.transactions; - const extTransactions = this.extTransactions; - return { - _type: 'Block', - hash, - header: header.toJSON(), - interlinkHashes, - order, - size: toJson(size), - subManifest, - totalEntropy: toJson(totalEntropy), - uncles, - woHeader: woHeader.toJSON(), - transactions, - extTransactions, // Includes the extended transaction hashes or full transactions based on the prefetched data - }; - } - [Symbol.iterator]() { - let index = 0; - const txs = this.transactions; - return { - next: () => { - if (index < this.length) { - return { - value: txs[index++], - done: false, - }; - } - return { value: undefined, done: true }; - }, - }; - } - /** - * The number of transactions in this block. - * - * @returns {number} The number of transactions. - */ - get length() { - return this.#transactions.length; - } - /** - * The [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) this block was - * included at. - * - * @returns {null | Date} The date this block was included at, or null if the timestamp is not available. - */ - get date() { - const timestampHex = this.woHeader.time; - if (!timestampHex) { - return null; - } - const timestamp = parseInt(timestampHex, 16); - return new Date(timestamp * 1000); - } - /** - * Get the transaction at `index` within this block. - * - * @param {number | string} indexOrHash - The index or hash of the transaction. - * @returns {Promise} A promise resolving to the transaction. - * @throws {Error} If the transaction is not found. - */ - async getTransaction(indexOrHash) { - // Find the internal value by its index or hash - let tx = undefined; - if (typeof indexOrHash === 'number') { - tx = this.#transactions[indexOrHash]; - } - else { - const hash = indexOrHash.toLowerCase(); - for (const v of this.#transactions) { - if (typeof v === 'string') { - if (v !== hash) { - continue; - } - tx = v; - break; - } - else { - if (v.hash === hash) { - continue; - } - tx = v; - break; - } - } - } - if (tx == null) { - throw new Error('no such tx'); - } - if (typeof tx === 'string') { - return await this.provider.getTransaction(tx); - } - else { - return tx; - } - } - /** - * Get the extended transaction at `index` within this block. - * - * @param {number | string} indexOrHash - The index or hash of the extended transaction. - * @returns {Promise} A promise resolving to the extended transaction. - * @throws {Error} If the extended transaction is not found. - */ - async getExtTransaction(indexOrHash) { - // Find the internal value by its index or hash - let tx = undefined; - if (typeof indexOrHash === 'number') { - tx = this.#extTransactions[indexOrHash]; - } - else { - const hash = indexOrHash.toLowerCase(); - for (const v of this.#extTransactions) { - if (typeof v === 'string') { - if (v !== hash) { - continue; - } - tx = v; - break; - } - else { - if (v.hash === hash) { - continue; - } - tx = v; - break; - } - } - } - if (tx == null) { - throw new Error('no such tx'); - } - if (typeof tx === 'string') { - throw new Error("External Transaction isn't prefetched"); - } - else { - return tx; - } - } - /** - * If a **Block** was fetched with a request to include the transactions this will allow synchronous access to those - * transactions. - * - * If the transactions were not prefetched, this will throw. - * - * @param {number | string} indexOrHash - The index or hash of the transaction. - * @returns {TransactionResponse} The transaction. - * @throws {Error} If the transaction is not found. - */ - getPrefetchedTransaction(indexOrHash) { - const txs = this.prefetchedTransactions; - if (typeof indexOrHash === 'number') { - return txs[indexOrHash]; - } - indexOrHash = indexOrHash.toLowerCase(); - for (const tx of txs) { - if (tx.hash === indexOrHash) { - return tx; - } - } - assertArgument(false, 'no matching transaction', 'indexOrHash', indexOrHash); - } - /** - * Returns true if this block been mined. This provides a type guard for all properties on a - * {@link MinedBlock | **MinedBlock**}. - * - * @returns {boolean} True if the block has been mined. - */ - isMined() { - return !!this.header.hash; - } - /** - * @ignore - */ - orphanedEvent() { - if (!this.isMined() || !this.woHeader.number) { - throw new Error(''); - } - return createOrphanedBlockFilter({ - hash: this.header.hash, - number: parseInt(this.woHeader.number, 16), - }); - } - } - ////////////////////// - // Log - /** - * A **Log** in Ethereum represents an event that has been included in a transaction using the `LOG*` opcodes, which are - * most commonly used by Solidity's emit for announcing events. - * - * @category Providers - */ - class Log { - /** - * The provider connected to the log used to fetch additional details if necessary. - */ - provider; - /** - * The transaction hash of the transaction this log occurred in. Use the - * {@link Log.getTransaction | **Log.getTransaction**} to get the - * {@link TransactionResponse | **TransactionResponse}. - */ - transactionHash; - /** - * The block hash of the block this log occurred in. Use the {@link Log.getBlock | **Log.getBlock**} to get the - * {@link Block | **Block**}. - */ - blockHash; - /** - * The block number of the block this log occurred in. It is preferred to use the {@link Block.hash | **Block.hash**} - * when fetching the related {@link Block | **Block**}, since in the case of an orphaned block, the block at that - * height may have changed. - */ - blockNumber; - /** - * If the **Log** represents a block that was removed due to an orphaned block, this will be true. - * - * This can only happen within an orphan event listener. - */ - removed; - /** - * The address of the contract that emitted this log. - */ - address; - /** - * The data included in this log when it was emitted. - */ - data; - /** - * The indexed topics included in this log when it was emitted. - * - * All topics are included in the bloom filters, so they can be efficiently filtered using the - * {@link Provider.getLogs | **Provider.getLogs**} method. - */ - topics; - /** - * The index within the block this log occurred at. This is generally not useful to developers, but can be used with - * the various roots to proof inclusion within a block. - */ - index; - /** - * The index within the transaction of this log. - */ - transactionIndex; - /** - * @ignore - */ - constructor(log, provider) { - this.provider = provider; - const topics = Object.freeze(log.topics.slice()); - defineProperties(this, { - transactionHash: log.transactionHash, - blockHash: log.blockHash, - blockNumber: log.blockNumber, - removed: log.removed, - address: log.address, - data: log.data, - topics, - index: log.index, - transactionIndex: log.transactionIndex, - }); - } - /** - * Returns a JSON-compatible object. - */ - toJSON() { - const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this; - return { - _type: 'log', - address, - blockHash, - blockNumber, - data, - index, - removed, - topics, - transactionHash, - transactionIndex, - }; - } - /** - * Returns the block that this log occurred in. - * - * @param {Shard} shard - The shard to fetch the block from. - * @returns {Promise} A promise resolving to the block. - */ - async getBlock(shard) { - const block = await this.provider.getBlock(shard, this.blockHash); - assert(!!block, 'failed to find transaction', 'UNKNOWN_ERROR', {}); - return block; - } - /** - * Returns the transaction that this log occurred in. - * - * @returns {Promise} A promise resolving to the transaction. - */ - async getTransaction() { - const tx = await this.provider.getTransaction(this.transactionHash); - assert(!!tx, 'failed to find transaction', 'UNKNOWN_ERROR', {}); - return tx; - } - /** - * Returns the transaction receipt fot the transaction that this log occurred in. - * - * @returns {Promise} A promise resolving to the transaction receipt. - */ - async getTransactionReceipt() { - const receipt = await this.provider.getTransactionReceipt(this.transactionHash); - assert(!!receipt, 'failed to find transaction receipt', 'UNKNOWN_ERROR', {}); - return receipt; - } - /** - * @ignore - */ - removedEvent() { - return createRemovedLogFilter(this); - } - } - ////////////////////// - // Transaction Receipt - function zoneFromHash(hash) { - return toZone(hash.slice(0, 4)); - } - /** - * A **TransactionReceipt** includes additional information about a transaction that is only available after it has been - * mined. - * - * @category Providers - */ - class TransactionReceipt { - /** - * The provider connected to the log used to fetch additional details if necessary. - */ - provider; - /** - * The address the transaction was sent to. - */ - to; - /** - * The sender of the transaction. - */ - from; - /** - * The address of the contract if the transaction was directly responsible for deploying one. - * - * This is non-null **only** if the `to` is empty and the `data` was successfully executed as initcode. - */ - contractAddress; - /** - * The transaction hash. - */ - hash; - /** - * The index of this transaction within the block transactions. - */ - index; - /** - * The block hash of the {@link Block | **Block**} this transaction was included in. - */ - blockHash; - /** - * The block number of the {@link Block | **Block**} this transaction was included in. - */ - blockNumber; - /** - * The bloom filter bytes that represent all logs that occurred within this transaction. This is generally not - * useful for most developers, but can be used to validate the included logs. - */ - logsBloom; - /** - * The actual amount of gas used by this transaction. - * - * When creating a transaction, the amount of gas that will be used can only be approximated, but the sender must - * pay the gas fee for the entire gas limit. After the transaction, the difference is refunded. - */ - gasUsed; - /** - * The amount of gas used by all transactions within the block for this and all transactions with a lower `index`. - * - * This is generally not useful for developers but can be used to validate certain aspects of execution. - */ - cumulativeGasUsed; - /** - * The actual gas price used during execution. - * - * Due to the complexity of [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) this value can only be caluclated - * after the transaction has been mined, snce the base fee is protocol-enforced. - */ - gasPrice; - /** - * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction type. - */ - type; - //readonly byzantium!: boolean; - /** - * The status of this transaction, indicating success (i.e. `1`) or a revert (i.e. `0`). - * - * This is available in post-byzantium blocks, but some backends may backfill this value. - */ - status; - /** - * The root hash of this transaction. - * - * This is no present and was only included in pre-byzantium blocks, but could be used to validate certain parts of - * the receipt. - */ - #logs; - etxs = []; - /** - * @ignore - */ - constructor(tx, provider) { - this.#logs = Object.freeze(tx.logs.map((log) => { - return new Log(log, provider); - })); - let gasPrice = BN_0$1; - if (tx.effectiveGasPrice != null) { - gasPrice = tx.effectiveGasPrice; - } - else if (tx.gasPrice != null) { - gasPrice = tx.gasPrice; - } - const etxs = tx.etxs - ? tx.etxs.map((etx) => { - const safeConvert = (value, name) => { - try { - if (value != null) { - return BigInt(value); - } - return null; - } - catch (error) { - console.error(`Conversion to BigInt failed for ${name}: ${value}, error: ${error}`); - return null; - } - }; - return { - type: etx.type, - nonce: etx.nonce, - gasPrice: safeConvert(etx.gasPrice, 'gasPrice'), - maxPriorityFeePerGas: safeConvert(etx.maxPriorityFeePerGas, 'maxPriorityFeePerGas'), - maxFeePerGas: safeConvert(etx.maxFeePerGas, 'maxFeePerGas'), - gas: safeConvert(etx.gas, 'gas'), - value: safeConvert(etx.value, 'value'), - input: etx.input, - to: etx.to, - accessList: etx.accessList, - chainId: safeConvert(etx.chainId, 'chainId'), - sender: etx.sender, - hash: etx.hash, - isCoinbase: etx.isCoinbase, - originatingTxHash: etx.originatingTxHash, - etxIndex: etx.etxIndex, - }; - }) - : []; - defineProperties(this, { - provider, - to: tx.to, - from: tx.from, - contractAddress: tx.contractAddress, - hash: tx.hash, - index: tx.index, - blockHash: tx.blockHash, - blockNumber: tx.blockNumber, - logsBloom: tx.logsBloom, - gasUsed: tx.gasUsed, - cumulativeGasUsed: tx.cumulativeGasUsed, - gasPrice, - etxs: etxs, - type: tx.type, - status: tx.status, - }); - } - /** - * The logs for this transaction. - */ - get logs() { - return this.#logs; - } - /** - * Returns a JSON-compatible representation. - */ - toJSON() { - const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium, - status, etxs, } = this; - return { - _type: 'TransactionReceipt', - blockHash, - blockNumber, - contractAddress, - cumulativeGasUsed: toJson(this.cumulativeGasUsed), - from, - gasPrice: toJson(this.gasPrice), - gasUsed: toJson(this.gasUsed), - hash, - index, - logs, - logsBloom, - status, - to, - etxs: etxs ?? [], - }; - } - /** - * @ignore - */ - get length() { - return this.logs.length; - } - [Symbol.iterator]() { - let index = 0; - return { - next: () => { - if (index < this.length) { - return { value: this.logs[index++], done: false }; - } - return { value: undefined, done: true }; - }, - }; - } - /** - * The total fee for this transaction, in wei. - */ - get fee() { - return this.gasUsed * this.gasPrice; - } - /** - * Resolves to the block this transaction occurred in. - * - * @param {Shard} shard - The shard to fetch the block from. - * @returns {Promise} A promise resolving to the block. - * @throws {Error} If the block is not found. - */ - async getBlock(shard) { - const block = await this.provider.getBlock(shard, this.blockHash); - if (block == null) { - throw new Error('TODO'); - } - return block; - } - /** - * Resolves to the transaction this transaction occurred in. - * - * @returns {Promise} A promise resolving to the transaction. - * @throws {Error} If the transaction is not found. - */ - async getTransaction() { - const tx = await this.provider.getTransaction(this.hash); - if (tx == null) { - throw new Error('TODO'); - } - return tx; - } - /** - * Resolves to the return value of the execution of this transaction. - * - * Support for this feature is limited, as it requires an archive node with the `debug_` or `trace_` API enabled. - * - * @returns {Promise} A promise resolving to the return value of the transaction. - * @throws {Error} If the transaction is not found. - */ - async getResult() { - return await this.provider.getTransactionResult(this.hash); - } - /** - * Resolves to the number of confirmations this transaction has. - * - * @returns {Promise} A promise resolving to the number of confirmations. - * @throws {Error} If the block is not found. - */ - async confirmations() { - const zone = zoneFromHash(this.hash); - return (await this.provider.getBlockNumber(toShard(zone))) - this.blockNumber + 1; - } - /** - * @ignore - */ - removedEvent() { - return createRemovedTransactionFilter(this); - } - /** - * @ignore - */ - reorderedEvent(other) { - assert(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", 'UNSUPPORTED_OPERATION', { - operation: 'reorderedEvent(other)', - }); - return createReorderedTransactionFilter(this, other); - } - } - class ExternalTransactionResponse { - /** - * The provider this is connected to, which will influence how its methods will resolve its async inspection - * methods. - */ - provider; - /** - * The block number of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockNumber; - /** - * The blockHash of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockHash; - /** - * The index within the block that this transaction resides at. - */ - index; - /** - * The transaction hash. - */ - hash; - /** - * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy - * transactions types. - */ - type; - /** - * The receiver of this transaction. - * - * If `null`, then the transaction is an initcode transaction. This means the result of executing the - * {@link ExternalTransactionResponse.data | **data** } will be deployed as a new contract on chain (assuming it does - * not revert) and the address may be computed using [getCreateAddress](../functions/getCreateAddress). - */ - to; - /** - * The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and - * the {@link QuaiTransactionResponse.signature | **signature** } using ecrecover. - */ - from; - /** - * The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender - * are explicitly ordered. - * - * When sending a transaction, this must be equal to the number of transactions ever sent by - * {@link ExternalTransactionResponse.from | **from** }. - */ - nonce; - /** - * The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is - * reverted and the sender is charged for the full amount, despite not state changes being made. - */ - gasLimit; - /** - * The data. - */ - data; - /** - * The value, in wei. Use [formatEther](../functions/formatEther) to format this value as ether. - */ - value; - /** - * The chain ID. - */ - chainId; - /** - * The signature. - */ - signature; - /** - * The [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list for transaction types that support it, - * otherwise `null`. - */ - accessList; - etxType; - isCoinbase; - originatingTxHash; - sender; - etxIndex; - startBlock; - /** - * @ignore - */ - constructor(tx, provider) { - this.provider = provider; - this.blockNumber = tx.blockNumber != null ? tx.blockNumber : null; - this.blockHash = tx.blockHash != null ? tx.blockHash : null; - this.hash = tx.hash; - this.index = tx.index; - this.type = tx.type; - this.from = tx.from; - this.to = tx.to || null; - this.gasLimit = tx.gasLimit; - this.nonce = tx.nonce; - this.data = tx.data; - this.value = tx.value; - this.chainId = tx.chainId; - this.signature = tx.signature; - this.accessList = tx.accessList != null ? tx.accessList : null; - this.startBlock = -1; - this.originatingTxHash = tx.originatingTxHash != null ? tx.originatingTxHash : null; - this.isCoinbase = tx.isCoinbase != null ? tx.isCoinbase : null; - this.etxType = tx.etxType != null ? tx.etxType : null; - this.sender = tx.sender; - this.etxIndex = tx.etxIndex; - } - /** - * Returns a JSON-compatible representation of this transaction. - */ - toJSON() { - const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, etxType, isCoinbase, originatingTxHash, etxIndex, sender, } = this; - const result = { - _type: 'TransactionReceipt', - accessList, - blockNumber, - blockHash, - chainId: toJson(this.chainId), - data, - from, - gasLimit: toJson(this.gasLimit), - hash, - nonce, - signature, - to, - index, - type, - etxType, - isCoinbase, - originatingTxHash, - sender, - etxIndex, - value: toJson(this.value), - }; - return result; - } - replaceableTransaction(startBlock) { - assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock); - const tx = new ExternalTransactionResponse(this, this.provider); - tx.startBlock = startBlock; - return tx; - } - } - /** - * A **QuaiTransactionResponse** includes all properties about a Quai transaction that was sent to the network, which - * may or may not be included in a block. - * - * The {@link TransactionResponse.isMined | **TransactionResponse.isMined**} can be used to check if the transaction has - * been mined as well as type guard that the otherwise possibly `null` properties are defined. - * - * @category Providers - */ - class QuaiTransactionResponse { - /** - * The provider this is connected to, which will influence how its methods will resolve its async inspection - * methods. - */ - provider; - /** - * The block number of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockNumber; - /** - * The blockHash of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockHash; - /** - * The index within the block that this transaction resides at. - */ - index; - /** - * The transaction hash. - */ - hash; - /** - * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy - * transactions types. - */ - type; - /** - * The receiver of this transaction. - * - * If `null`, then the transaction is an initcode transaction. This means the result of executing the - * {@link QuaiTransactionResponse.data | **data** } will be deployed as a new contract on chain (assuming it does not - * revert) and the address may be computed using [getCreateAddress](../functions/getCreateAddress). - */ - to; - /** - * The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and - * the {@link QuaiTransactionResponse.signature | **signature** } using ecrecover. - */ - from; - /** - * The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender - * are explicitly ordered. - * - * When sending a transaction, this must be equal to the number of transactions ever sent by - * {@link QuaiTransactionResponse.from | **from** }. - */ - nonce; - /** - * The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is - * reverted and the sender is charged for the full amount, despite not state changes being made. - */ - gasLimit; - /** - * The maximum priority fee (per unit of gas) to allow a validator to charge the sender. This is inclusive of the - * {@link QuaiTransactionResponse.maxFeePerGas | **maxFeePerGas** }. - */ - maxPriorityFeePerGas; - /** - * The maximum fee (per unit of gas) to allow this transaction to charge the sender. - */ - maxFeePerGas; - /** - * The data. - */ - data; - /** - * The value, in wei. Use [formatEther](../functions/formatEther) to format this value as ether. - */ - value; - /** - * The chain ID. - */ - chainId; - /** - * The signature. - */ - signature; - /** - * The [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list for transaction types that support it, - * otherwise `null`. - */ - accessList; - etxType; - sender; - originatingTxHash; - startBlock; - /** - * @ignore - */ - constructor(tx, provider) { - this.provider = provider; - this.blockNumber = tx.blockNumber != null ? tx.blockNumber : null; - this.blockHash = tx.blockHash != null ? tx.blockHash : null; - this.hash = tx.hash; - this.index = tx.index; - this.type = tx.type; - this.from = tx.from; - this.to = tx.to || null; - this.gasLimit = tx.gasLimit; - this.nonce = tx.nonce; - this.data = tx.data; - this.value = tx.value; - this.maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? tx.maxPriorityFeePerGas : null; - this.maxFeePerGas = tx.maxFeePerGas != null ? tx.maxFeePerGas : null; - this.chainId = tx.chainId; - this.signature = tx.signature; - this.accessList = tx.accessList != null ? tx.accessList : null; - this.startBlock = -1; - this.etxType = tx.etxType != null ? tx.etxType : null; - } - /** - * Returns a JSON-compatible representation of this transaction. - */ - toJSON() { - const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList } = this; - const result = { - _type: 'TransactionReceipt', - accessList, - blockNumber, - blockHash, - chainId: toJson(this.chainId), - data, - from, - gasLimit: toJson(this.gasLimit), - hash, - maxFeePerGas: toJson(this.maxFeePerGas), - maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), - nonce, - signature, - to, - index, - type, - value: toJson(this.value), - }; - return result; - } - /** - * Resolves to the Block that this transaction was included in. - * - * This will return null if the transaction has not been included yet. - * - * @param {Shard} shard - The shard to fetch the block from. - * @returns {null | Promise} A promise resolving to the block. - */ - async getBlock(shard) { - let blockNumber = this.blockNumber; - if (blockNumber == null) { - const tx = await this.getTransaction(); - if (tx) { - blockNumber = tx.blockNumber; - } - } - if (blockNumber == null) { - return null; - } - const block = this.provider.getBlock(shard, blockNumber); - if (block == null) { - throw new Error('TODO'); - } - return block; - } - /** - * Resolves to this transaction being re-requested from the provider. This can be used if you have an unmined - * transaction and wish to get an up-to-date populated instance. - * - * @returns {null | Promise} A promise resolving to the transaction, or null if not found. - */ - async getTransaction() { - const transaction = this.provider.getTransaction(this.hash); - if (transaction instanceof QuaiTransactionResponse) { - return transaction; - } - else { - return null; - } - } - /** - * Resolve to the number of confirmations this transaction has. - * - * @returns {Promise} A promise resolving to the number of confirmations. - * @throws {Error} If the block is not found. - */ - async confirmations() { - const zone = zoneFromHash(this.hash); - if (this.blockNumber == null) { - const { tx, blockNumber } = await resolveProperties({ - tx: this.getTransaction(), - blockNumber: this.provider.getBlockNumber(toShard(zone)), - }); - // Not mined yet... - if (tx == null || tx.blockNumber == null) { - return 0; - } - return blockNumber - tx.blockNumber + 1; - } - const blockNumber = await this.provider.getBlockNumber(toShard(zone)); - return blockNumber - this.blockNumber + 1; - } - /** - * Resolves once this transaction has been mined and has `confirms` blocks including it (default: `1`) with an - * optional `timeout`. - * - * This can resolve to `null` only if `confirms` is `0` and the transaction has not been mined, otherwise this will - * wait until enough confirmations have completed. - * - * @param {number} [_confirms] - The number of confirmations to wait for. - * @param {number} [_timeout] - The number of milliseconds to wait before rejecting. - * @returns {Promise} A promise resolving to the transaction receipt. - * @throws {Error} If the transaction was replaced, repriced, or cancelled. - */ - async wait(_confirms, _timeout) { - const confirms = _confirms == null ? 1 : _confirms; - const timeout = _timeout == null ? 0 : _timeout; - let startBlock = this.startBlock; - let nextScan = -1; - let stopScanning = startBlock === -1 ? true : false; - const zone = zoneFromHash(this.hash); - const checkReplacement = async () => { - // Get the current transaction count for this sender - if (stopScanning) { - return null; - } - const { blockNumber, nonce } = await resolveProperties({ - blockNumber: this.provider.getBlockNumber(toShard(zone)), - nonce: this.provider.getTransactionCount(this.from), - }); - // No transaction or our nonce has not been mined yet; but we - // can start scanning later when we do start - if (nonce < this.nonce) { - startBlock = blockNumber; - return; - } - // We were mined; no replacement - if (stopScanning) { - return null; - } - const mined = await this.getTransaction(); - if (mined && mined.blockNumber != null) { - return; - } - // We were replaced; start scanning for that transaction - // Starting to scan; look back a few extra blocks for safety - if (nextScan === -1) { - nextScan = startBlock - 3; - if (nextScan < this.startBlock) { - nextScan = this.startBlock; - } - } - while (nextScan <= blockNumber) { - // Get the next block to scan - if (stopScanning) { - return null; - } - const block = await this.provider.getBlock(toShard(zone), nextScan, true); - // This should not happen; but we'll try again shortly - if (block == null) { - return; - } - // We were mined; no replacement - for (const hash of block) { - if (hash === this.hash) { - return; - } - } - // Search for the transaction that replaced us - for (let i = 0; i < block.length; i++) { - const tx = await block.getTransaction(i); - if ('from' in tx && tx.from === this.from && tx.nonce === this.nonce) { - // Get the receipt - if (stopScanning) { - return null; - } - const receipt = await this.provider.getTransactionReceipt(tx.hash); - // This should not happen; but we'll try again shortly - if (receipt == null) { - return; - } - // We will retry this on the next block (this case could be optimized) - if (blockNumber - receipt.blockNumber + 1 < confirms) { - return; - } - // The reason we were replaced - let reason = 'replaced'; - if (tx.data === this.data && tx.to === this.to && tx.value === this.value) { - reason = 'repriced'; - } - else if (tx.data === '0x' && tx.from === tx.to && tx.value === BN_0$1) { - reason = 'cancelled'; - } - assert(false, 'transaction was replaced', 'TRANSACTION_REPLACED', { - cancelled: reason === 'replaced' || reason === 'cancelled', - reason, - replacement: tx.replaceableTransaction(startBlock), - hash: tx.hash, - receipt, - }); - } - } - nextScan++; - } - return; - }; - const checkReceipt = (receipt) => { - if (receipt == null || receipt.status !== 0) { - return receipt; - } - assert(false, 'transaction execution reverted', 'CALL_EXCEPTION', { - action: 'sendTransaction', - data: null, - reason: null, - invocation: null, - revert: null, - transaction: { - to: receipt.to, - from: receipt.from, - data: '', // @TODO: in v7, split out sendTransaction properties - }, - receipt, - }); - }; - const receipt = await this.provider.getTransactionReceipt(this.hash); - if (confirms === 0) { - return checkReceipt(receipt); - } - if (receipt) { - if ((await receipt.confirmations()) >= confirms) { - return checkReceipt(receipt); - } - } - else { - // Check for a replacement; throws if a replacement was found - await checkReplacement(); - // Allow null only when the confirms is 0 - if (confirms === 0) { - return null; - } - } - const waiter = new Promise((resolve, reject) => { - // List of things to cancel when we have a result (one way or the other) - const cancellers = []; - const cancel = () => { - cancellers.forEach((c) => c()); - }; - // On cancel, stop scanning for replacements - cancellers.push(() => { - stopScanning = true; - }); - // Set up any timeout requested - if (timeout > 0) { - const timer = setTimeout(() => { - cancel(); - reject(makeError('wait for transaction timeout', 'TIMEOUT')); - }, timeout); - cancellers.push(() => { - clearTimeout(timer); - }); - } - const txListener = async (receipt) => { - // Done; return it! - if ((await receipt.confirmations()) >= confirms) { - cancel(); - try { - resolve(checkReceipt(receipt)); - } - catch (error) { - reject(error); - } - } - }; - cancellers.push(() => { - this.provider.off(this.hash, txListener); - }); - this.provider.on(this.hash, txListener); - // We support replacement detection; start checking - if (startBlock >= 0) { - const replaceListener = async () => { - try { - // Check for a replacement; this throws only if one is found - await checkReplacement(); - } - catch (error) { - // We were replaced (with enough confirms); re-throw the error - if (isError(error, 'TRANSACTION_REPLACED')) { - cancel(); - reject(error); - return; - } - } - // Rescheudle a check on the next block - if (!stopScanning) { - this.provider.once('block', replaceListener); - } - }; - cancellers.push(() => { - this.provider.off('block', replaceListener); - }); - this.provider.once('block', replaceListener); - } - }); - return await waiter; - } - /** - * Returns `true` if this transaction has been included. - * - * This is effective only as of the time the TransactionResponse was instantiated. To get up-to-date information, - * use {@link QuaiTransactionResponse.getTransaction | **getTransaction**}. - * - * This provides a Type Guard that this transaction will have non-null property values for properties that are null - * for unmined transactions. - * - * @returns {QuaiMinedTransactionResponse} True if the transaction has been mined. - * @throws {Error} If the transaction was replaced, repriced, or cancelled. - */ - isMined() { - return this.blockHash != null; - } - /** - * Returns a filter which can be used to listen for orphan events that evict this transaction. - * - * @returns {OrphanFilter} The orphan filter. - */ - removedEvent() { - assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - return createRemovedTransactionFilter(this); - } - /** - * Returns a filter which can be used to listen for orphan events that re-order this event against `other`. - * - * @param {TransactionResponse} [other] - The other transaction to compare against. - * @returns {OrphanFilter} The orphan filter. - */ - reorderedEvent(other) { - assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - return createReorderedTransactionFilter(this, other); - } - /** - * Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the - * transaction is replaced, which will begin scanning at `startBlock`. - * - * This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect - * `startBlock` can have devastating performance consequences if used incorrectly. - * - * @param {number} startBlock - The block number to start scanning for replacements. - * @returns {QuaiTransactionResponse} The replaceable transaction. - */ - replaceableTransaction(startBlock) { - assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock); - const tx = new QuaiTransactionResponse(this, this.provider); - tx.startBlock = startBlock; - return tx; - } - } - /** - * A **QiTransactionResponse** includes all properties about a Qi transaction that was sent to the network, which may or - * may not be included in a block. - * - * The {@link TransactionResponse.isMined | **TransactionResponse.isMined**} can be used to check if the transaction has - * been mined as well as type guard that the otherwise possibly `null` properties are defined. - * - * @category Providers - */ - class QiTransactionResponse { - /** - * The provider this is connected to, which will influence how its methods will resolve its async inspection - * methods. - */ - provider; - /** - * The block number of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockNumber; - /** - * The blockHash of the block that this transaction was included in. - * - * This is `null` for pending transactions. - */ - blockHash; - /** - * The index within the block that this transaction resides at. - */ - index; - /** - * The transaction hash. - */ - hash; - /** - * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy - * transactions types. - */ - type; - /** - * The chain ID. - */ - chainId; - /** - * The signature. - */ - signature; - txInputs; - txOutputs; - startBlock; - /** - * @ignore - */ - constructor(tx, provider) { - this.provider = provider; - this.blockNumber = tx.blockNumber != null ? tx.blockNumber : null; - this.blockHash = tx.blockHash != null ? tx.blockHash : null; - this.hash = tx.hash; - this.index = tx.index; - this.type = tx.type; - this.chainId = tx.chainId; - this.signature = tx.signature; - this.startBlock = -1; - this.txInputs = tx.txInputs; - this.txOutputs = tx.txOutputs; - } - /** - * Returns a JSON-compatible representation of this transaction. - */ - toJSON() { - const { blockNumber, blockHash, index, hash, type, signature, txInputs, txOutputs } = this; - const result = { - _type: 'TransactionReceipt', - blockNumber, - blockHash, - chainId: toJson(this.chainId), - hash, - signature, - index, - type, - txInputs: JSON.parse(JSON.stringify(txInputs)), - txOutputs: JSON.parse(JSON.stringify(txOutputs)), - }; - return result; - } - /** - * Resolves to the Block that this transaction was included in. - * - * This will return null if the transaction has not been included yet. - * - * @param {Shard} shard - The shard to fetch the block from. - * @returns {null | Promise} A promise resolving to the block or null if not found. - */ - async getBlock(shard) { - let blockNumber = this.blockNumber; - if (blockNumber == null) { - const tx = await this.getTransaction(); - if (tx) { - blockNumber = tx.blockNumber; - } - } - if (blockNumber == null) { - return null; - } - const block = this.provider.getBlock(shard, blockNumber); - if (block == null) { - throw new Error('TODO'); - } - return block; - } - /** - * Resolves to this transaction being re-requested from the provider. This can be used if you have an unmined - * transaction and wish to get an up-to-date populated instance. - * - * @returns {null | Promise} A promise resolving to the transaction, or null if not found. - * @throws {Error} If the transaction is not found. - */ - async getTransaction() { - const transaction = this.provider.getTransaction(this.hash); - if (transaction instanceof QiTransactionResponse) { - return transaction; - } - else { - return null; - } - } - /** - * Resolve to the number of confirmations this transaction has. - * - * @returns {Promise} A promise resolving to the number of confirmations. - */ - async confirmations() { - const zone = zoneFromHash(this.hash); - if (this.blockNumber == null) { - const { tx, blockNumber } = await resolveProperties({ - tx: this.getTransaction(), - blockNumber: this.provider.getBlockNumber(toShard(zone)), - }); - // Not mined yet... - if (tx == null || tx.blockNumber == null) { - return 0; - } - return blockNumber - tx.blockNumber + 1; - } - const blockNumber = await this.provider.getBlockNumber(toShard(zone)); - return blockNumber - this.blockNumber + 1; - } - /** - * Returns `true` if this transaction has been included. - * - * This is effective only as of the time the TransactionResponse was instantiated. To get up-to-date information, - * use {@link QiTransactionResponse.getTransaction | **getTransaction**}. - * - * This provides a Type Guard that this transaction will have non-null property values for properties that are null - * for unmined transactions. - * - * @returns {QiMinedTransactionResponse} True if the transaction has been mined or false otherwise. - */ - isMined() { - return this.blockHash != null; - } - /** - * Returns a filter which can be used to listen for orphan events that evict this transaction. - * - * @returns {OrphanFilter} The orphan filter. - */ - removedEvent() { - assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - return createRemovedTransactionFilter(this); - } - /** - * Returns a filter which can be used to listen for orphan events that re-order this event against `other`. - * - * @param {TransactionResponse} [other] - The other transaction to compare against. - * @returns {OrphanFilter} The orphan filter. - */ - reorderedEvent(other) { - assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - assert(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", 'UNSUPPORTED_OPERATION', { - operation: 'removeEvent()', - }); - return createReorderedTransactionFilter(this, other); - } - /** - * Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the - * transaction is replaced, which will begin scanning at `startBlock`. - * - * This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect - * `startBlock` can have devastating performance consequences if used incorrectly. - * - * @param {number} startBlock - The block number to start scanning for replacements. - * @returns {QiTransactionResponse} The replaceable transaction. - */ - replaceableTransaction(startBlock) { - assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock); - const tx = new QiTransactionResponse(this, this.provider); - tx.startBlock = startBlock; - return tx; - } - } - function createOrphanedBlockFilter(block) { - return { orphan: 'drop-block', hash: block.hash, number: block.number }; - } - function createReorderedTransactionFilter(tx, other) { - return { orphan: 'reorder-transaction', tx, other }; - } - function createRemovedTransactionFilter(tx) { - return { orphan: 'drop-transaction', tx }; - } - function createRemovedLogFilter(log) { - return { - orphan: 'drop-log', - log: { - transactionHash: log.transactionHash, - blockHash: log.blockHash, - blockNumber: log.blockNumber, - address: log.address, - data: log.data, - topics: Object.freeze(log.topics.slice()), - index: log.index, - }, - }; - } - function getZoneFromEventFilter(filter) { - let zone = null; - if (filter.nodeLocation) { - zone = getZoneFromNodeLocation(filter.nodeLocation); - } - else if (filter.address) { - let address; - if (Array.isArray(filter.address)) { - address = filter.address[0]; - } - else { - address = filter.address; - } - const addressZone = getZoneForAddress(address); - if (addressZone) { - zone = toZone(addressZone); - } - else { - return null; - } - } - return zone; - } - - // import from provider.ts instead of index.ts to prevent circular dep - // from quaiscanProvider - /** - * An **EventLog** contains additional properties parsed from the {@link Log | **Log**}. - * - * @category Contract - */ - class EventLog extends Log { - /** - * The Contract Interface. - */ - interface; - /** - * The matching event. - */ - fragment; - /** - * The parsed arguments passed to the event by `emit`. - */ - args; - /** - * @ignore - */ - constructor(log, iface, fragment) { - super(log, log.provider); - const args = iface.decodeEventLog(fragment, log.data, log.topics); - defineProperties(this, { args, fragment, interface: iface }); - } - /** - * The name of the event. - */ - get eventName() { - return this.fragment.name; - } - /** - * The signature of the event. - */ - get eventSignature() { - return this.fragment.format(); - } - } - /** - * An **EventLog** contains additional properties parsed from the {@link Log | **Log**}. - * - * @category Contract - */ - class UndecodedEventLog extends Log { - /** - * The error encounted when trying to decode the log. - */ - error; - /** - * @ignore - */ - constructor(log, error) { - super(log, log.provider); - defineProperties(this, { error }); - } - } - /** - * A **ContractTransactionReceipt** includes the parsed logs from a {@link TransactionReceipt | **TransactionReceipt**}. - * - * @category Contract - */ - class ContractTransactionReceipt extends TransactionReceipt { - #iface; - /** - * @ignore - */ - constructor(iface, provider, tx) { - super(tx, provider); - this.#iface = iface; - } - /** - * The parsed logs for any {@link Log | **Log**} which has a matching event in the Contract ABI. - */ - get logs() { - return super.logs.map((log) => { - const fragment = log.topics.length ? this.#iface.getEvent(log.topics[0]) : null; - if (fragment) { - try { - return new EventLog(log, this.#iface, fragment); - } - catch (error) { - return new UndecodedEventLog(log, error); - } - } - return log; - }); - } - } - /** - * A **ContractTransactionResponse** will return a {@link ContractTransactionReceipt | **ContractTransactionReceipt**} - * when waited on. - * - * @category Contract - */ - class ContractTransactionResponse extends QuaiTransactionResponse { - #iface; - /** - * @ignore - */ - constructor(iface, provider, tx) { - super(tx, provider); - this.#iface = iface; - } - /** - * Resolves once this transaction has been mined and has `confirms` blocks including it (default: `1`) with an - * optional `timeout`. - * - * This can resolve to `null` only if `confirms` is `0` and the transaction has not been mined, otherwise this will - * wait until enough confirmations have completed. - * - * @param {number} confirms - The number of confirmations to wait for. - * - * @returns {Promise} The transaction receipt, or `null` if `confirms` is `0`. - */ - async wait(confirms) { - const receipt = await super.wait(confirms); - if (receipt == null) { - return null; - } - return new ContractTransactionReceipt(this.#iface, this.provider, receipt); - } - } - /** - * A **ContractUnknownEventPayload** is included as the last parameter to Contract Events when the event does not match - * any events in the ABI. - * - * @category Contract - */ - class ContractUnknownEventPayload extends EventPayload { - /** - * The log with no matching events. - */ - log; - /** - * @ignore - */ - constructor(contract, listener, filter, log) { - super(contract, listener, filter); - defineProperties(this, { log }); - } - /** - * Resolves to the block the event occured in. - * - * @param {Shard} shard - The shard to get the block from. - * - * @returns {Promise} A promise resolving to the block the event occured in. - */ - async getBlock(shard) { - return await this.log.getBlock(shard); - } - /** - * Resolves to the transaction the event occured in. - * - * @returns {Promise} A promise resolving to the transaction the event occured in. - */ - async getTransaction() { - return await this.log.getTransaction(); - } - /** - * Resolves to the transaction receipt the event occured in. - * - * @returns {Promise} A promise resolving to the transaction receipt the event occured in. - */ - async getTransactionReceipt() { - return await this.log.getTransactionReceipt(); - } - } - /** - * A **ContractEventPayload** is included as the last parameter to Contract Events when the event is known. - * - * @category Contract - */ - class ContractEventPayload extends ContractUnknownEventPayload { - /** - * @ignore - */ - constructor(contract, listener, filter, fragment, _log) { - super(contract, listener, filter, new EventLog(_log, contract.interface, fragment)); - const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics); - defineProperties(this, { args, fragment }); - } - /** - * The event name. - */ - get eventName() { - return this.fragment.name; - } - /** - * The event signature. - */ - get eventSignature() { - return this.fragment.format(); - } - } - - const BN_0 = BigInt(0); - /** - * Check if the value can call transactions. - * - * @param {any} value - The value to check. - * @returns {value is ContractRunnerCaller} True if the value can call transactions. - */ - function canCall(value) { - return value && typeof value.call === 'function'; - } - /** - * Check if the value can estimate gas. - * - * @param {any} value - The value to check. - * @returns {value is ContractRunnerEstimater} True if the value can estimate gas. - */ - function canEstimate(value) { - return value && typeof value.estimateGas === 'function'; - } - /** - * Check if the value can send transactions. - * - * @param {any} value - The value to check. - * @returns {value is ContractRunnerSender} True if the value can send transactions. - */ - function canSend(value) { - return value && typeof value.sendTransaction === 'function'; - } - /** - * Class representing a prepared topic filter. - * - * @implements {DeferredTopicFilter} - */ - class PreparedTopicFilter { - #filter; - fragment; - /** - * @ignore - */ - constructor(contract, fragment, args) { - defineProperties(this, { fragment }); - if (fragment.inputs.length < args.length) { - throw new Error('too many arguments'); - } - this.#filter = (async function () { - const resolvedArgs = await Promise.all(fragment.inputs.map((param, index) => { - const arg = args[index]; - if (arg == null) { - return null; - } - return param.walkAsync(args[index], (type, value) => { - if (type === 'address') { - if (Array.isArray(value)) { - return Promise.all(value.map((v) => resolveAddress(v))); - } - return resolveAddress(value); - } - return value; - }); - })); - return contract.interface.encodeFilterTopics(fragment, resolvedArgs); - })(); - } - /** - * Get the topic filter. - * - * @returns {Promise} The topic filter. - */ - getTopicFilter() { - return this.#filter; - } - } - /** - * Get the runner for a specific feature. - * - * @param {any} value - The value to check. - * @param {keyof ContractRunner} feature - The feature to check for. - * @returns {null | T} The runner if available, otherwise null. - */ - function getRunner(value, feature) { - if (value == null) { - return null; - } - if (typeof value[feature] === 'function') { - return value; - } - if (value.provider && typeof value.provider[feature] === 'function') { - return value.provider; - } - return null; - } - /** - * Get the provider from a contract runner. - * - * @param {null | ContractRunner} value - The contract runner. - * @returns {null | Provider} The provider if available, otherwise null. - */ - function getProvider(value) { - if (value == null) { - return null; - } - return value.provider || null; - } - /** - * @ignore Copy overrides and validate them. - * @param {any} arg - The argument containing overrides. - * @param {string[]} [allowed] - The allowed override keys. - * @returns {Promise>} The copied and validated overrides. - * @throws {Error} If the overrides are invalid. - */ - async function copyOverrides(arg, allowed) { - // Make sure the overrides passed in are a valid overrides object - const _overrides = Typed.dereference(arg, 'overrides'); - assertArgument(typeof _overrides === 'object', 'invalid overrides parameter', 'overrides', arg); - // Create a shallow copy (we'll deep-ify anything needed during normalizing) - const overrides = copyRequest(_overrides); - assertArgument(!('to' in overrides) || overrides.to == null || (allowed || []).indexOf('to') >= 0, 'cannot override to', 'overrides.to', overrides); - assertArgument(!('data' in overrides) || overrides.data == null || (allowed || []).indexOf('data') >= 0, 'cannot override data', 'overrides.data', overrides); - // Resolve any from - if ('from' in overrides && overrides.from) { - overrides.from = await overrides.from; - } - return overrides; - } - /** - * @ignore Resolve arguments for a contract runner. - * @param {null | ContractRunner} _runner - The contract runner. - * @param {ReadonlyArray} inputs - The input parameter types. - * @param {any[]} args - The arguments to resolve. - * @returns {Promise} The resolved arguments. - */ - async function resolveArgs(_runner, inputs, args) { - // Recursively descend into args and resolve any addresses - return await Promise.all(inputs.map((param, index) => { - return param.walkAsync(args[index], (type, value) => { - value = Typed.dereference(value, type); - if (type === 'address') { - return resolveAddress(value); - } - return value; - }); - })); - } - /** - * Build a wrapped fallback method for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @returns {WrappedFallback} The wrapped fallback method. - */ - function buildWrappedFallback(contract) { - /** - * Populate a transaction with overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The populated transaction. - * @throws {Error} If the overrides are invalid. - */ - const populateTransaction = async function (overrides) { - // If an overrides was passed in, copy it and normalize the values - const tx = await copyOverrides(overrides, ['data']); - tx.to = await contract.getAddress(); - validateAddress(tx.to); - if (tx.from) { - tx.from = await resolveAddress(tx.from); - validateAddress(tx.from); - } - const iface = contract.interface; - const noValue = getBigInt(tx.value || BN_0, 'overrides.value') === BN_0; - const noData = (tx.data || '0x') === '0x'; - if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) { - assertArgument(false, 'cannot send data to receive or send value to non-payable fallback', 'overrides', overrides); - } - assertArgument(iface.fallback || noData, 'cannot send data to receive-only contract', 'overrides.data', tx.data); - // Only allow payable contracts to set non-zero value - const payable = iface.receive || (iface.fallback && iface.fallback.payable); - assertArgument(payable || noValue, 'cannot send value to non-payable fallback', 'overrides.value', tx.value); - // Only allow fallback contracts to set non-empty data - assertArgument(iface.fallback || noData, 'cannot send data to receive-only contract', 'overrides.data', tx.data); - return tx; - }; - /** - * Perform a static call with the given overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The result of the static call. - * @throws {Error} If the call fails. - */ - const staticCall = async function (overrides) { - const runner = getRunner(contract.runner, 'call'); - assert(canCall(runner), 'contract runner does not support calling', 'UNSUPPORTED_OPERATION', { - operation: 'call', - }); - const tx = await populateTransaction(overrides); - try { - return await runner.call(tx); - } - catch (error) { - if (isCallException(error) && error.data) { - throw contract.interface.makeError(error.data, tx); - } - throw error; - } - }; - /** - * Send a transaction with the given overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The transaction response. - * @throws {Error} If the transaction fails. - */ - const send = async function (overrides) { - const runner = contract.runner; - assert(canSend(runner), 'contract runner does not support sending transactions', 'UNSUPPORTED_OPERATION', { - operation: 'sendTransaction', - }); - const tx = (await runner.sendTransaction(await populateTransaction(overrides))); - const provider = getProvider(contract.runner); - // @TODO: the provider can be null; make a custom dummy provider that will throw a - // meaningful error - return new ContractTransactionResponse(contract.interface, provider, tx); - }; - /** - * Estimate the gas required for a transaction with the given overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The estimated gas. - * @throws {Error} If the gas estimation fails. - */ - const estimateGas = async function (overrides) { - const runner = getRunner(contract.runner, 'estimateGas'); - assert(canEstimate(runner), 'contract runner does not support gas estimation', 'UNSUPPORTED_OPERATION', { - operation: 'estimateGas', - }); - return await runner.estimateGas(await populateTransaction(overrides)); - }; - /** - * Send a transaction with the given overrides. - * - * @param {Omit} [overrides] - The transaction overrides. - * @returns {Promise} The transaction response. - * @throws {Error} If the transaction fails. - */ - const method = async (overrides) => { - return await send(overrides); - }; - defineProperties(method, { - _contract: contract, - estimateGas, - populateTransaction, - send, - staticCall, - }); - return method; - } - /** - * Build a wrapped method for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @param {string} key - The method key. - * @returns {BaseContractMethod} The wrapped method. - */ - function buildWrappedMethod(contract, key) { - /** - * Get the function fragment for the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {FunctionFragment} The function fragment. - * @throws {Error} If no matching fragment is found. - */ - const getFragment = function (...args) { - const fragment = contract.interface.getFunction(key, args); - assert(fragment, 'no matching fragment', 'UNSUPPORTED_OPERATION', { - operation: 'fragment', - info: { key, args }, - }); - return fragment; - }; - /** - * Populate a transaction with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The populated transaction. - * @throws {Error} If the arguments are invalid. - */ - const populateTransaction = async function (...args) { - const fragment = getFragment(...args); - // If an overrides was passed in, copy it and normalize the values - let overrides; - if (fragment.inputs.length + 1 === args.length) { - overrides = await copyOverrides(args.pop()); - const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); - return Object.assign({}, overrides, await resolveProperties({ - to: contract.getAddress(), - data: contract.interface.encodeFunctionData(fragment, resolvedArgs), - })); - } - if (fragment.inputs.length !== args.length) { - throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); - } - const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); - return await resolveProperties({ - to: contract.getAddress(), - from: args.pop()?.from, - data: contract.interface.encodeFunctionData(fragment, resolvedArgs), - }); - }; - /** - * Perform a static call with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The result of the static call. - * @throws {Error} If the call fails. - */ - const staticCall = async function (...args) { - const result = await staticCallResult(...args); - if (result.length === 1) { - return result[0]; - } - return result; - }; - /** - * Send a transaction with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The transaction response. - * @throws {Error} If the transaction fails. - */ - const send = async function (...args) { - const runner = contract.runner; - assert(canSend(runner), 'contract runner does not support sending transactions', 'UNSUPPORTED_OPERATION', { - operation: 'sendTransaction', - }); - const pop = await populateTransaction(...args); - if (!pop.from && 'address' in runner && typeof runner.address === 'string') { - pop.from = await resolveAddress(runner.address); - } - const tx = (await runner.sendTransaction(await pop)); - const provider = getProvider(contract.runner); - // @TODO: the provider can be null; make a custom dummy provider that will throw a - // meaningful error - return new ContractTransactionResponse(contract.interface, provider, tx); - }; - /** - * Estimate the gas required for a transaction with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The estimated gas. - * @throws {Error} If the gas estimation fails. - */ - const estimateGas = async function (...args) { - const runner = getRunner(contract.runner, 'estimateGas'); - assert(canEstimate(runner), 'contract runner does not support gas estimation', 'UNSUPPORTED_OPERATION', { - operation: 'estimateGas', - }); - return await runner.estimateGas(await populateTransaction(...args)); - }; - /** - * Perform a static call and return the result with the given arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The result of the static call. - * @throws {Error} If the call fails. - */ - const staticCallResult = async function (...args) { - const runner = getRunner(contract.runner, 'call'); - assert(canCall(runner), 'contract runner does not support calling', 'UNSUPPORTED_OPERATION', { - operation: 'call', - }); - const tx = await populateTransaction(...args); - if (!tx.from && 'address' in runner && typeof runner.address === 'string') { - tx.from = await resolveAddress(runner.address); - } - let result = '0x'; - try { - result = await runner.call(tx); - } - catch (error) { - if (isCallException(error) && error.data) { - throw contract.interface.makeError(error.data, tx); - } - throw error; - } - const fragment = getFragment(...args); - return contract.interface.decodeFunctionResult(fragment, result); - }; - /** - * Send a transaction or perform a static call based on the method arguments. - * - * @param {...ContractMethodArgs} args - The method arguments. - * @returns {Promise} The result of the method call. - * @throws {Error} If the method call fails. - */ - const method = async (...args) => { - const fragment = getFragment(...args); - if (fragment.constant) { - return await staticCall(...args); - } - return await send(...args); - }; - defineProperties(method, { - name: contract.interface.getFunctionName(key), - _contract: contract, - _key: key, - getFragment, - estimateGas, - populateTransaction, - send, - staticCall, - staticCallResult, - }); - // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) - Object.defineProperty(method, 'fragment', { - configurable: false, - enumerable: true, - get: () => { - const fragment = contract.interface.getFunction(key); - assert(fragment, 'no matching fragment', 'UNSUPPORTED_OPERATION', { - operation: 'fragment', - info: { key }, - }); - return fragment; - }, - }); - return method; - } - /** - * Build a wrapped event for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @param {string} key - The event key. - * @returns {ContractEvent} The wrapped event. - */ - function buildWrappedEvent(contract, key) { - /** - * Get the event fragment for the given arguments. - * - * @param {...ContractEventArgs} args - The event arguments. - * @returns {EventFragment} The event fragment. - * @throws {Error} If no matching fragment is found. - */ - const getFragment = function (...args) { - const fragment = contract.interface.getEvent(key, args); - assert(fragment, 'no matching fragment', 'UNSUPPORTED_OPERATION', { - operation: 'fragment', - info: { key, args }, - }); - return fragment; - }; - /** - * Create a prepared topic filter for the event. - * - * @param {...ContractMethodArgs} args - The event arguments. - * @returns {PreparedTopicFilter} The prepared topic filter. - */ - const method = function (...args) { - return new PreparedTopicFilter(contract, getFragment(...args), args); - }; - defineProperties(method, { - name: contract.interface.getEventName(key), - _contract: contract, - _key: key, - getFragment, - }); - // Only works on non-ambiguous keys (refined fragment is always non-ambiguous) - Object.defineProperty(method, 'fragment', { - configurable: false, - enumerable: true, - get: () => { - const fragment = contract.interface.getEvent(key); - assert(fragment, 'no matching fragment', 'UNSUPPORTED_OPERATION', { - operation: 'fragment', - info: { key }, - }); - return fragment; - }, - }); - return method; - } - // The combination of TypeScrype, Private Fields and Proxies makes - // the world go boom; so we hide variables with some trickery keeping - // a symbol attached to each BaseContract which its sub-class (even - // via a Proxy) can reach and use to look up its internal values. - const internal = Symbol.for('_quaisInternal_contract'); - const internalValues = new WeakMap(); - /** - * Set internal values for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @param {Internal} values - The internal values. - */ - function setInternal(contract, values) { - internalValues.set(contract[internal], values); - } - /** - * Get internal values for a contract. - * - * @param {BaseContract} contract - The contract instance. - * @returns {Internal} The internal values. - */ - function getInternal(contract) { - return internalValues.get(contract[internal]); - } - /** - * Check if a value is a deferred topic filter. - * - * @param {any} value - The value to check. - * @returns {value is DeferredTopicFilter} True if the value is a deferred topic filter. - */ - function isDeferred(value) { - return (value && - typeof value === 'object' && - 'getTopicFilter' in value && - typeof value.getTopicFilter === 'function' && - value.fragment); - } - /** - * Get subscription information for an event. - * - * @param {BaseContract} contract - The contract instance. - * @param {ContractEventName} event - The event name. - * @returns {Promise<{ fragment: null | EventFragment; tag: string; topics: TopicFilter }>} The subscription - * information. - * @throws {Error} If the event name is unknown. - */ - async function getSubInfo(contract, event) { - let topics; - let fragment = null; - // Convert named events to topicHash and get the fragment for - // events which need deconstructing. - if (Array.isArray(event)) { - const topicHashify = function (name) { - if (isHexString(name, 32)) { - return name; - } - const fragment = contract.interface.getEvent(name); - assertArgument(fragment, 'unknown fragment', 'name', name); - return fragment.topicHash; - }; - // Array of Topics and Names; e.g. `[ "0x1234...89ab", "Transfer(address)" ]` - topics = event.map((e) => { - if (e == null) { - return null; - } - if (Array.isArray(e)) { - return e.map(topicHashify); - } - return topicHashify(e); - }); - } - else if (event === '*') { - topics = [null]; - } - else if (typeof event === 'string') { - if (isHexString(event, 32)) { - // Topic Hash - topics = [event]; - } - else { - // Name or Signature; e.g. `"Transfer", `"Transfer(address)"` - fragment = contract.interface.getEvent(event); - assertArgument(fragment, 'unknown fragment', 'event', event); - topics = [fragment.topicHash]; - } - } - else if (isDeferred(event)) { - // Deferred Topic Filter; e.g. `contract.filter.Transfer(from)` - topics = await event.getTopicFilter(); - } - else if (event && 'fragment' in event) { - // ContractEvent; e.g. `contract.filter.Transfer` - fragment = event.fragment; - topics = [fragment.topicHash]; - } - else { - assertArgument(false, 'unknown event name', 'event', event); - } - // Normalize topics and sort TopicSets - topics = topics.map((t) => { - if (t == null) { - return null; - } - if (Array.isArray(t)) { - const items = Array.from(new Set(t.map((t) => t.toLowerCase())).values()); - if (items.length === 1) { - return items[0]; - } - items.sort(); - return items; - } - return t.toLowerCase(); - }); - const tag = topics - .map((t) => { - if (t == null) { - return 'null'; - } - if (Array.isArray(t)) { - return t.join('|'); - } - return t; - }) - .join('&'); - return { fragment, tag, topics }; - } - /** - * Check if a contract has a subscription for an event. - * - * @param {BaseContract} contract - The contract instance. - * @param {ContractEventName} event - The event name. - * @returns {Promise} The subscription if available, otherwise null. - */ - async function hasSub(contract, event) { - const { subs } = getInternal(contract); - return subs.get((await getSubInfo(contract, event)).tag) || null; - } - /** - * Get a subscription for an event. - * - * @param {BaseContract} contract - The contract instance. - * @param {string} operation - The operation name. - * @param {ContractEventName} event - The event name. - * @returns {Promise} The subscription. - * @throws {Error} If the contract runner does not support subscribing. - */ - async function getSub(contract, operation, event) { - // Make sure our runner can actually subscribe to events - const provider = getProvider(contract.runner); - assert(provider, 'contract runner does not support subscribing', 'UNSUPPORTED_OPERATION', { operation }); - const { fragment, tag, topics } = await getSubInfo(contract, event); - const { addr, subs } = getInternal(contract); - let sub = subs.get(tag); - if (!sub) { - const address = addr ? addr : contract; - const filter = { address, topics }; - const listener = (log) => { - let foundFragment = fragment; - if (foundFragment == null) { - try { - foundFragment = contract.interface.getEvent(log.topics[0]); - // eslint-disable-next-line no-empty - } - catch (error) { } - } - // If fragment is null, we do not deconstruct the args to emit - if (foundFragment) { - const _foundFragment = foundFragment; - const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : []; - emit(contract, event, args, (listener) => { - return new ContractEventPayload(contract, listener, event, _foundFragment, log); - }); - } - else { - emit(contract, event, [], (listener) => { - return new ContractUnknownEventPayload(contract, listener, event, log); - }); - } - }; - const zone = getZoneForAddress(await resolveAddress(address)); - let starting = []; - const start = () => { - if (starting.length) { - return; - } - starting.push(provider.on(filter, listener, zone)); - }; - const stop = async () => { - if (starting.length == 0) { - return; - } - const started = starting; - starting = []; - await Promise.all(started); - provider.off(filter, listener, zone); - }; - sub = { tag, listeners: [], start, stop }; - subs.set(tag, sub); - } - return sub; - } - /** - * We use this to ensure one emit resolves before firing the next to ensure correct ordering (note this cannot throw and - * just adds the notice to the event queue using setTimeout). - */ - let lastEmit = Promise.resolve(); - /** - * Emit an event with the given arguments and payload function. - * - * @ignore - * @param {BaseContract} contract - The contract instance. - * @param {ContractEventName} event - The event name. - * @param {any[]} args - The arguments to pass to the listeners. - * @param {null | PayloadFunc} payloadFunc - The payload function. - * @returns {Promise} Resolves to true if any listeners were called. - */ - async function _emit(contract, event, args, payloadFunc) { - await lastEmit; - const sub = await hasSub(contract, event); - if (!sub) { - return false; - } - const count = sub.listeners.length; - sub.listeners = sub.listeners.filter(({ listener, once }) => { - const passArgs = Array.from(args); - if (payloadFunc) { - passArgs.push(payloadFunc(once ? null : listener)); - } - try { - listener.call(contract, ...passArgs); - // eslint-disable-next-line no-empty - } - catch (error) { } - return !once; - }); - if (sub.listeners.length === 0) { - sub.stop(); - getInternal(contract).subs.delete(sub.tag); - } - return count > 0; - } - /** - * Emit an event with the given arguments and payload function. - * - * @param {BaseContract} contract - The contract instance. - * @param {ContractEventName} event - The event name. - * @param {any[]} args - The arguments to pass to the listeners. - * @param {null | PayloadFunc} payloadFunc - The payload function. - * @returns {Promise} Resolves to true if any listeners were called. - */ - async function emit(contract, event, args, payloadFunc) { - try { - await lastEmit; - // eslint-disable-next-line no-empty - } - catch (error) { } - const resultPromise = _emit(contract, event, args, payloadFunc); - lastEmit = resultPromise; - return await resultPromise; - } - const passProperties = ['then']; - /** - * Creates a new contract connected to target with the abi and optionally connected to a runner to perform operations on - * behalf of. - * - * @category Contract - */ - class BaseContract { - /** - * The target to connect to. - * - * This can be an address or any [Addressable](../interfaces/Addressable), such as another contract. To get the - * resolved address, use the `getAddress` method. - */ - target; - /** - * The contract Interface. - */ - interface; - /** - * The connected runner. This is generally a [**Provider**](../interfaces/Provider) or a - * [**Signer**](../interfaces/Signer), which dictates what operations are supported. - * - * For example, a **Contract** connected to a [**Provider**](../interfaces/Provider) may only execute read-only - * operations. - */ - runner; - /** - * All the Events available on this contract. - */ - filters; - /** - * @ignore - */ - [internal]; - /** - * The fallback or receive function if any. - */ - fallback; - /** - * Creates a new contract connected to `target` with the `abi` and optionally connected to a `runner` to perform - * operations on behalf of. - * - * @ignore - */ - constructor(target, abi, runner, _deployTx) { - assertArgument(typeof target === 'string' || isAddressable(target), 'invalid value for Contract target', 'target', target); - if (runner == null) { - runner = null; - } - const iface = Interface.from(abi); - defineProperties(this, { target, runner, interface: iface }); - Object.defineProperty(this, internal, { value: {} }); - let addrPromise; - let addr = null; - let deployTx = null; - if (_deployTx) { - const provider = getProvider(runner); - // @TODO: the provider can be null; make a custom dummy provider that will throw a - // meaningful error - deployTx = new ContractTransactionResponse(this.interface, provider, _deployTx); - } - const subs = new Map(); - // Resolve the target as the address - if (typeof target === 'string') { - addr = target; - addrPromise = Promise.resolve(target); - } - else { - addrPromise = target.getAddress().then((addr) => { - if (addr == null) { - throw new Error('TODO'); - } - getInternal(this).addr = addr; - return addr; - }); - } - // Set our private values - setInternal(this, { addrPromise, addr, deployTx, subs }); - // Add the event filters - const filters = new Proxy({}, { - get: (target, prop, receiver) => { - // Pass important checks (like `then` for Promise) through - if (typeof prop === 'symbol' || passProperties.indexOf(prop) >= 0) { - return Reflect.get(target, prop, receiver); - } - try { - return this.getEvent(prop); - } - catch (error) { - if (!isError(error, 'INVALID_ARGUMENT') || error.argument !== 'key') { - throw error; - } - } - return undefined; - }, - has: (target, prop) => { - // Pass important checks (like `then` for Promise) through - if (passProperties.indexOf(prop) >= 0) { - return Reflect.has(target, prop); - } - return Reflect.has(target, prop) || this.interface.hasEvent(String(prop)); - }, - }); - defineProperties(this, { filters }); - defineProperties(this, { - fallback: iface.receive || iface.fallback ? buildWrappedFallback(this) : null, - }); - // Return a Proxy that will respond to functions - return new Proxy(this, { - get: (target, prop, receiver) => { - if (typeof prop === 'symbol' || prop in target || passProperties.indexOf(prop) >= 0) { - return Reflect.get(target, prop, receiver); - } - // Undefined properties should return undefined - try { - return target.getFunction(prop); - } - catch (error) { - if (!isError(error, 'INVALID_ARGUMENT') || error.argument !== 'key') { - throw error; - } - } - return undefined; - }, - has: (target, prop) => { - if (typeof prop === 'symbol' || prop in target || passProperties.indexOf(prop) >= 0) { - return Reflect.has(target, prop); - } - return target.interface.hasFunction(prop); - }, - }); - } - /** - * Return a new Contract instance with the same target and ABI, but a different `runner`. - * - * @param {null | ContractRunner} runner - The runner to use. - * @returns {BaseContract} The new contract instance. - */ - connect(runner) { - return new BaseContract(this.target, this.interface, runner); - } - /** - * Return a new Contract instance with the same ABI and runner, but a different `target`. - * - * @param {string | Addressable} target - The target to connect to. - * @returns {BaseContract} The new contract instance. - */ - attach(target) { - return new BaseContract(target, this.interface, this.runner); - } - /** - * Return the resolved address of this Contract. - * - * @returns {Promise} The resolved address. - */ - async getAddress() { - return await getInternal(this).addrPromise; - } - /** - * Return the deployed bytecode or null if no bytecode is found. - * - * @returns {Promise} The deployed bytecode or null. - * @throws {Error} If the runner does not support .provider. - */ - async getDeployedCode() { - const provider = getProvider(this.runner); - assert(provider, 'runner does not support .provider', 'UNSUPPORTED_OPERATION', { - operation: 'getDeployedCode', - }); - const code = await provider.getCode(await this.getAddress()); - if (code === '0x') { - return null; - } - return code; - } - /** - * Resolve to this Contract once the bytecode has been deployed, or resolve immediately if already deployed. - * - * @returns {Promise} The contract instance. - * @throws {Error} If the contract runner does not support .provider. - */ - async waitForDeployment() { - // We have the deployment transaction; just use that (throws if deployment fails) - const deployTx = this.deploymentTransaction(); - if (deployTx) { - await deployTx.wait(); - return this; - } - // Check for code - const code = await this.getDeployedCode(); - if (code != null) { - return this; - } - // Make sure we can subscribe to a provider event - const provider = getProvider(this.runner); - assert(provider != null, 'contract runner does not support .provider', 'UNSUPPORTED_OPERATION', { - operation: 'waitForDeployment', - }); - return new Promise((resolve, reject) => { - const checkCode = async () => { - try { - const code = await this.getDeployedCode(); - if (code != null) { - return resolve(this); - } - provider.once('block', checkCode); - } - catch (error) { - reject(error); - } - }; - checkCode(); - }); - } - /** - * Return the transaction used to deploy this contract. - * - * This is only available if this instance was returned from a [**ContractFactor**](../classes/ContractFactory). - * - * @returns The transaction used to deploy this contract or `null`. - */ - deploymentTransaction() { - return getInternal(this).deployTx; - } - /** - * Return the function for a given name. This is useful when a contract method name conflicts with a JavaScript name - * such as `prototype` or when using a Contract programatically. - * - * @param {string | FunctionFragment} key - The name of the function to return. - * @returns The function for the given name. - */ - getFunction(key) { - if (typeof key !== 'string') { - key = key.format(); - } - const func = buildWrappedMethod(this, key); - return func; - } - /** - * Return the event for a given name. This is useful when a contract event name conflicts with a JavaScript name - * such as `prototype` or when using a Contract programatically. - * - * @param {string | EventFragment} key - The name of the event to return. - * @returns The event for the given name. - */ - getEvent(key) { - if (typeof key !== 'string') { - key = key.format(); - } - return buildWrappedEvent(this, key); - } - /** - * @ignore - */ - // TODO: implement - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async queryTransaction(hash) { - throw new Error('@TODO'); - } - /** - * Provide historic access to event data for `event` in the range `fromBlock` (default: `0`) to `toBlock` (default: - * `"latest"`) inclusive. - * - * @param {Zone} zone - The zone to query. - * @param {ContractEventName} event - The event to query. - * @param {BlockTag} fromBlock - The block to start querying from. - * @param {BlockTag} toBlock - The block to stop querying at. - * @returns An array of event logs. - */ - async queryFilter(event, fromBlock, toBlock) { - if (fromBlock == null) { - fromBlock = 0; - } - if (toBlock == null) { - toBlock = 'latest'; - } - const { addr, addrPromise } = getInternal(this); - const address = addr ? addr : await addrPromise; - const { fragment, topics } = await getSubInfo(this, event); - const zone = getZoneForAddress(address); - const filter = { address, topics, fromBlock, toBlock, nodeLocation: getNodeLocationFromZone(zone) }; - const provider = getProvider(this.runner); - assert(provider, 'contract runner does not have a provider', 'UNSUPPORTED_OPERATION', { - operation: 'queryFilter', - }); - return (await provider.getLogs(filter)).map((log) => { - let foundFragment = fragment; - if (foundFragment == null) { - try { - foundFragment = this.interface.getEvent(log.topics[0]); - // eslint-disable-next-line no-empty - } - catch (error) { } - } - if (foundFragment) { - try { - return new EventLog(log, this.interface, foundFragment); - } - catch (error) { - return new UndecodedEventLog(log, error); - } - } - return new Log(log, provider); - }); - } - /** - * Add an event `listener` for the `event`. - * - * @param {ContractEventName} event - The event to listen for. - * @param {Listener} listener - The listener to call when the event is emitted. - * @returns This contract instance. - */ - async on(event, listener) { - const sub = await getSub(this, 'on', event); - sub.listeners.push({ listener, once: false }); - sub.start(); - return this; - } - /** - * Add an event `listener` for the `event`, but remove the listener after it is fired once. - * - * @param {ContractEventName} event - The event to listen for. - * @param {Listener} listener - The listener to call when the event is emitted. - */ - async once(event, listener) { - const sub = await getSub(this, 'once', event); - sub.listeners.push({ listener, once: true }); - sub.start(); - return this; - } - /** - * Emit an `event` calling all listeners with `args`. - * - * Resolves to `true` if any listeners were called. - * - * @param {ContractEventName} event - The event to emit. - * @param {any[]} args - The arguments to pass to the listeners. - * @returns `true` if any listeners were called. - */ - async emit(event, ...args) { - return await emit(this, event, args, null); - } - /** - * Resolves to the number of listeners of `event` or the total number of listeners if unspecified. - * - * @param {ContractEventName} event - The event to count listeners for. - * @returns {number} The number of listeners. - */ - async listenerCount(event) { - if (event) { - const sub = await hasSub(this, event); - if (!sub) { - return 0; - } - return sub.listeners.length; - } - const { subs } = getInternal(this); - let total = 0; - for (const { listeners } of subs.values()) { - total += listeners.length; - } - return total; - } - /** - * Resolves to the listeners subscribed to `event` or all listeners if unspecified. - * - * @param {ContractEventName} event - The event to get listeners for. - * @returns {Listener[]} The listeners. - */ - async listeners(event) { - if (event) { - const sub = await hasSub(this, event); - if (!sub) { - return []; - } - return sub.listeners.map(({ listener }) => listener); - } - const { subs } = getInternal(this); - let result = []; - for (const { listeners } of subs.values()) { - result = result.concat(listeners.map(({ listener }) => listener)); - } - return result; - } - /** - * Remove the `listener` from the listeners for `event` or remove all listeners if unspecified. - * - * @param {ContractEventName} event - The event to remove the listener from. - * @param {Listener} listener - The listener to remove. - * @returns This contract instance. - */ - async off(event, listener) { - const sub = await hasSub(this, event); - if (!sub) { - return this; - } - if (listener) { - const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); - if (index >= 0) { - sub.listeners.splice(index, 1); - } - } - if (listener == null || sub.listeners.length === 0) { - sub.stop(); - getInternal(this).subs.delete(sub.tag); - } - return this; - } - /** - * Remove all the listeners for `event` or remove all listeners if unspecified. - * - * @param {ContractEventName} event - The event to remove the listeners from. - * @returns This contract instance. - */ - async removeAllListeners(event) { - if (event) { - const sub = await hasSub(this, event); - if (!sub) { - return this; - } - sub.stop(); - getInternal(this).subs.delete(sub.tag); - } - else { - const { subs } = getInternal(this); - for (const { tag, stop } of subs.values()) { - stop(); - subs.delete(tag); - } - } - return this; - } - /** - * Alias for {@link BaseContract.on | **on**}. - * - * @param {ContractEventName} event - The event to listen for. - * @param {Listener} listener - The listener to call when the event is emitted. - */ - async addListener(event, listener) { - return await this.on(event, listener); - } - /** - * Alias for {@link BaseContract.off | **off**}. - * - * @param {ContractEventName} event - The event to remove the listener from. - * @param {Listener} listener - The listener to remove. - */ - async removeListener(event, listener) { - return await this.off(event, listener); - } - /** - * Create a new Class for the `abi`. - * - * @param {Interface | InterfaceAbi} abi - The ABI to create the class from. - * @returns The new Class for the ABI. - */ - static buildClass(abi) { - class CustomContract extends BaseContract { - constructor(address, runner = null) { - super(address, abi, runner); - } - } - return CustomContract; - } - /** - * Create a new BaseContract with a specified Interface. - * - * @param {string} target - The target to connect to. - * @param {Interface | InterfaceAbi} abi - The ABI to use. - * @param {null | ContractRunner} runner - The runner to use. - * @returns The new BaseContract. - */ - static from(target, abi, runner) { - if (runner == null) { - runner = null; - } - const contract = new this(target, abi, runner); - return contract; - } - } - function _ContractBase() { - return BaseContract; - } - /** - * A {@link BaseContract | **BaseContract**} with no type guards on its methods or events. - * - * @category Contract - */ - class Contract extends _ContractBase() { - } - - /** - * Generally the [Wallet](../classes/Wallet) and [JsonRpcSigner](../classes/JsonRpcSigner) and their sub-classes are - * sufficent for most developers, but this is provided to fascilitate more complex Signers. - */ - function checkProvider(signer, operation) { - if (signer.provider) { - return signer.provider; - } - assert(false, 'missing provider', 'UNSUPPORTED_OPERATION', { operation }); - } - async function populate(signer, tx) { - const pop = copyRequest(tx); - if (pop.to != null) { - pop.to = resolveAddress(pop.to); - validateAddress(pop.to); - } - if (pop.from != null) { - const from = pop.from; - pop.from = await Promise.all([signer.getAddress(), resolveAddress(from)]).then(([address, from]) => { - assertArgument(address.toLowerCase() === from.toLowerCase(), 'transaction from mismatch', 'tx.from', from); - return address; - }); - } - else { - pop.from = await signer.getAddress(); - } - validateAddress(pop.from); - return await resolveProperties(pop); - } - /** - * An **AbstractSigner** includes most of teh functionality required to get a {@link Signer | **Signer**} working as - * expected, but requires a few Signer-specific methods be overridden. - * - * @category Signers - */ - class AbstractSigner { - /** - * The provider this signer is connected to. - */ - provider; - /** - * Creates a new Signer connected to `provider`. - */ - constructor(provider) { - defineProperties(this, { provider: provider || null }); - } - /** - * @ignore - */ - _getAddress(address) { - return resolveAddress(address); - } - async zoneFromAddress(_address) { - const address = this._getAddress(_address); - return toZone((await address).slice(0, 4)); - } - async getNonce(blockTag) { - return checkProvider(this, 'getTransactionCount').getTransactionCount(await this.getAddress(), blockTag); - } - async populateCall(tx) { - const pop = await populate(this, tx); - return pop; - } - async populateQuaiTransaction(tx) { - const provider = checkProvider(this, 'populateTransaction'); - const zone = await this.zoneFromAddress(tx.from); - const pop = (await populate(this, tx)); - if (pop.type == null) { - pop.type = await getTxType(pop.from ?? null, pop.to ?? null); - } - if (pop.nonce == null) { - pop.nonce = await this.getNonce('pending'); - } - if (pop.type == null) { - pop.type = getTxType(pop.from ?? null, pop.to ?? null); - } - if (pop.gasLimit == null) { - if (pop.type == 0) - pop.gasLimit = await this.estimateGas(pop); - else { - //Special cases for type 2 tx to bypass address out of scope in the node - const temp = pop.to; - pop.to = '0x0000000000000000000000000000000000000000'; - pop.gasLimit = getBigInt(2 * Number(await this.estimateGas(pop))); - pop.to = temp; - } - } - // Populate the chain ID - const network = await this.provider.getNetwork(); - if (pop.chainId != null) { - const chainId = getBigInt(pop.chainId); - assertArgument(chainId === network.chainId, 'transaction chainId mismatch', 'tx.chainId', zone); - } - else { - pop.chainId = network.chainId; - } - if (pop.maxFeePerGas == null || pop.maxPriorityFeePerGas == null) { - const feeData = await provider.getFeeData(zone); - if (pop.maxFeePerGas == null) { - pop.maxFeePerGas = feeData.maxFeePerGas; - } - if (pop.maxPriorityFeePerGas == null) { - pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas || 10n; - } - } - //@TOOD: Don't await all over the place; save them up for - // the end for better batching - return await resolveProperties(pop); - } - async estimateGas(tx) { - return checkProvider(this, 'estimateGas').estimateGas(await this.populateCall(tx)); - } - async call(tx) { - return checkProvider(this, 'call').call(await this.populateCall(tx)); - } - async sendTransaction(tx) { - const provider = checkProvider(this, 'sendTransaction'); - const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx)); - const pop = await this.populateQuaiTransaction(tx); - const txObj = QuaiTransaction.from(pop); - const sender = await this.getAddress(); - const signedTx = await this.signTransaction(txObj); - return await provider.broadcastTransaction(zone, signedTx, sender); - } - } - /** - * A **VoidSigner** is a class deisgned to allow an address to be used in any API which accepts a Signer, but for which - * there are no credentials available to perform any actual signing. - * - * This for example allow impersonating an account for the purpose of static calls or estimating gas, but does not allow - * sending transactions. - * - * @category Signers - */ - class VoidSigner extends AbstractSigner { - /** - * The signer address. - */ - address; - /** - * Creates a new **VoidSigner** with `address` attached to `provider`. - */ - constructor(address, provider) { - super(provider); - defineProperties(this, { address }); - } - async getAddress() { - return this.address; - } - connect(provider) { - return new VoidSigner(this.address, provider); - } - #throwUnsupported(suffix, operation) { - assert(false, `VoidSigner cannot sign ${suffix}`, 'UNSUPPORTED_OPERATION', { operation }); - } - // TODO: `domain`, `types` and `value` are not used, remove? - // TODO: this function only throws, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async signTransaction(tx) { - this.#throwUnsupported('transactions', 'signTransaction'); - } - // TODO: `domain`, `types` and `value` are not used, remove? - // TODO: this function only throws, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async signMessage(message) { - this.#throwUnsupported('messages', 'signMessage'); - } - // TODO: `domain`, `types` and `value` are not used, remove? - // TODO: this function only throws, remove? - async signTypedData( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - domain, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - types, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - value) { - this.#throwUnsupported('typed-data', 'signTypedData'); - } - } - - /** - * The **BaseWallet** is a stream-lined implementation of a {@link AbstractSigner} that operates with a private - * key. - * - * It is preferred to use the {@link Wallet} class, as it offers additional functionality and simplifies - * loading a variety of JSON formats, Mnemonic Phrases, etc. - * - * This class may be of use for those attempting to implement a minimal Signer. - * - * @category Wallet - */ - class BaseWallet extends AbstractSigner { - /** - * The wallet address. - * @type {string} - * @readonly - */ - #address; - /** - * The signing key used for signing payloads. - * @type {SigningKey} - * @readonly - */ - #signingKey; - /** - * Creates a new BaseWallet for `privateKey`, optionally connected to `provider`. - * - * If `provider` is not specified, only offline methods can be used. - * - * @param {SigningKey} privateKey - The private key for the wallet. - * @param {null | Provider} [provider] - The provider to connect to. - */ - constructor(privateKey, provider) { - super(provider); - assertArgument(privateKey && typeof privateKey.sign === 'function', 'invalid private key', 'privateKey', '[ REDACTED ]'); - this.#signingKey = privateKey; - this.#address = computeAddress(this.signingKey.publicKey); - } - // Store private values behind getters to reduce visibility - /** - * The address of this wallet. - * @type {string} - * @readonly - */ - get address() { - return this.#address; - } - /** - * The {@link SigningKey | **SigningKey**} used for signing payloads. - * @type {SigningKey} - * @readonly - */ - get signingKey() { - return this.#signingKey; - } - /** - * The private key for this wallet. - * @type {string} - * @readonly - */ - get privateKey() { - return this.signingKey.privateKey; - } - // TODO: `_zone` is not used, should it be removed? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - /** - * Returns the address of this wallet. - * - * @param {string} [_zone] - The zone (optional). - * @returns {Promise} The wallet address. - */ - async getAddress(_zone) { - return this.#address; - } - /** - * Connects the wallet to a provider. - * - * @param {null | Provider} provider - The provider to connect to. - * @returns {BaseWallet} The connected wallet. - */ - connect(provider) { - return new BaseWallet(this.#signingKey, provider); - } - /** - * Signs a transaction. - * - * @param {QuaiTransactionRequest} tx - The transaction request. - * @returns {Promise} The signed transaction. - */ - async signTransaction(tx) { - // Replace any Addressable with an address - const { to, from } = await resolveProperties({ - to: tx.to ? resolveAddress(tx.to) : undefined, - from: tx.from ? resolveAddress(tx.from) : undefined, - }); - if (to !== undefined) { - validateAddress(to); - tx.to = to; - } - if (from !== undefined) { - assertArgument(getAddress(from) === this.#address, 'transaction from address mismatch', 'tx.from', from); - } - else { - // No `from` specified, use the wallet's address - tx.from = this.#address; - } - const btx = QuaiTransaction.from(tx); - const digest = keccak256(btx.unsignedSerialized); - btx.signature = this.signingKey.sign(digest); - return btx.serialized; - } - /** - * Signs a message. - * - * @param {string | Uint8Array} message - The message to sign. - * @returns {Promise} The signed message. - * @async - */ - async signMessage(message) { - return this.signMessageSync(message); - } - // @TODO: Add a secialized signTx and signTyped sync that enforces - // all parameters are known? - /** - * Returns the signature for `message` signed with this wallet. - * - * @param {string | Uint8Array} message - The message to sign. - * @returns {string} The serialized signature. - */ - signMessageSync(message) { - return this.signingKey.sign(hashMessage(message)).serialized; - } - /** - * Signs typed data. - * - * @param {TypedDataDomain} domain - The domain of the typed data. - * @param {Record>} types - The types of the typed data. - * @param {Record} value - The value of the typed data. - * @returns {Promise} The signed typed data. - * @async - */ - async signTypedData(domain, types, value) { - return this.signingKey.sign(TypedDataEncoder.hash(domain, types, value)).serialized; - } - } - - const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; - const Word = /^[a-z]*$/i; - function unfold(words, sep) { - let initial = 97; - return words.reduce((accum, word) => { - if (word === sep) { - initial++; - } - else if (word.match(Word)) { - accum.push(String.fromCharCode(initial) + word); - } - else { - initial = 97; - accum.push(word); - } - return accum; - }, []); - } - /** - * @ignore - */ - function decode(data, subs) { - // Replace all the substitutions with their expanded form - for (let i = subsChrs.length - 1; i >= 0; i--) { - data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); - } - // Get all tle clumps; each suffix, first-increment and second-increment - const clumps = []; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => { - if (semi) { - for (let i = parseInt(semi); i >= 0; i--) { - clumps.push(';'); - } - } - else { - clumps.push(item.toLowerCase()); - } - return ''; - }); - /* c8 ignore start */ - if (leftover) { - throw new Error(`leftovers: ${JSON.stringify(leftover)}`); - } - /* c8 ignore stop */ - return unfold(unfold(clumps, ';'), ':'); - } - /** - * @ignore - */ - function decodeOwl(data) { - assertArgument(data[0] === '0', 'unsupported auwl data', 'data', data); - return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); - } - - /** - * A Wordlist represents a collection of language-specific words used to encode and devoce - * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) encoded data by mapping words to 11-bit values and vice versa. - * - * @category Wordlists - */ - class Wordlist { - locale; - /** - * Creates a new Wordlist instance. - * - * Sub-classes MUST call this if they provide their own constructor, passing in the locale string of the language. - * - * Generally there is no need to create instances of a Wordlist, since each language-specific Wordlist creates an - * instance and there is no state kept internally, so they are safe to share. - */ - constructor(locale) { - defineProperties(this, { locale }); - } - /** - * Sub-classes may override this to provide a language-specific method for spliting `phrase` into individual words. - * - * By default, `phrase` is split using any sequences of white-space as defined by regular expressions (i.e. - * `/\s+/`). - * - * @param {string} phrase - The phrase to split. - * - * @returns {string[]} The split words in the phrase. - */ - split(phrase) { - return phrase.toLowerCase().split(/\s+/g); - } - /** - * Sub-classes may override this to provider a language-specific method for joining `words` into a phrase. - * - * By default, `words` are joined by a single space. - * - * @param {string[]} words - The words to join. - * - * @returns {string} The joined phrase. - */ - join(words) { - return words.join(' '); - } - } - - // Use the encode-latin.js script to create the necessary - // data files to be consumed by this class - /** - * An OWL format Wordlist is an encoding method that exploits the general locality of alphabetically sorted words to - * achieve a simple but effective means of compression. - * - * This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages - * based on ASCII-7 small. - * - * If necessary, there are tools within the `generation/` folder to create the necessary data. - * - * @category Wordlists - */ - class WordlistOwl extends Wordlist { - #data; - #checksum; - /** - * Creates a new Wordlist for `locale` using the OWL `data` and validated against the `checksum`. - */ - constructor(locale, data, checksum) { - super(locale); - this.#data = data; - this.#checksum = checksum; - this.#words = null; - } - /** - * The OWL-encoded data. - * - * @ignore - */ - get _data() { - return this.#data; - } - /** - * Decode all the words for the wordlist. - */ - _decodeWords() { - return decodeOwl(this.#data); - } - #words; - #loadWords() { - if (this.#words == null) { - const words = this._decodeWords(); - // Verify the computed list matches the official list - const checksum = id(words.join('\n') + '\n'); - /* c8 ignore start */ - if (checksum !== this.#checksum) { - throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); - } - /* c8 ignore stop */ - this.#words = words; - } - return this.#words; - } - getWord(index) { - const words = this.#loadWords(); - assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, 'index', index); - return words[index]; - } - getWordIndex(word) { - return this.#loadWords().indexOf(word); - } - } - - const words$1 = "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_{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 M3AgramAlAm#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/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-PM&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryFN Noc|PutQuirySSue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+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)IdeIghtImOgAyEakEelEmEpE*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~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO"; - const checksum$1 = '0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60'; - let wordlist$1 = null; - /** - * The [English wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt) for [mnemonic - * phrases](https://en.bitcoin.it/wiki/BIP_0039). - * - * @category Wordlists - */ - class LangEn extends WordlistOwl { - /** - * Creates a new instance of the English language Wordlist. - * - * This should be unnecessary most of the time as the exported {@link langEn} should suffice. - * - * @ignore - */ - constructor() { - super('en', words$1, checksum$1); - } - /** - * Returns a singleton instance of a `LangEn`, creating it if this is the first time being called. - */ - static wordlist() { - if (wordlist$1 == null) { - wordlist$1 = new LangEn(); - } - return wordlist$1; - } - } - - /** - * Returns a byte with the MSB bits set. - * - * @param {number} bits - The number of bits to set. - * @returns {number} The byte with the MSB bits set. - */ - function getUpperMask(bits) { - return (((1 << bits) - 1) << (8 - bits)) & 0xff; - } - /** - * Returns a byte with the LSB bits set. - * - * @param {number} bits - The number of bits to set. - * @returns {number} The byte with the LSB bits set. - */ - function getLowerMask(bits) { - return ((1 << bits) - 1) & 0xff; - } - /** - * Converts a mnemonic phrase to entropy. - * - * @param {string} mnemonic - The mnemonic phrase. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {string} The entropy. - */ - function mnemonicToEntropy(mnemonic, wordlist) { - assertNormalize('NFKD'); - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const words = wordlist.split(mnemonic); - assertArgument(words.length % 3 === 0 && words.length >= 12 && words.length <= 24, 'invalid mnemonic length', 'mnemonic', '[ REDACTED ]'); - const entropy = new Uint8Array(Math.ceil((11 * words.length) / 8)); - let offset = 0; - for (let i = 0; i < words.length; i++) { - const index = wordlist.getWordIndex(words[i].normalize('NFKD')); - assertArgument(index >= 0, `invalid mnemonic word at index ${i}`, 'mnemonic', '[ REDACTED ]'); - for (let bit = 0; bit < 11; bit++) { - if (index & (1 << (10 - bit))) { - entropy[offset >> 3] |= 1 << (7 - (offset % 8)); - } - offset++; - } - } - const entropyBits = (32 * words.length) / 3; - const checksumBits = words.length / 3; - const checksumMask = getUpperMask(checksumBits); - const checksum = getBytes(sha256(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; - assertArgument(checksum === (entropy[entropy.length - 1] & checksumMask), 'invalid mnemonic checksum', 'mnemonic', '[ REDACTED ]'); - return hexlify(entropy.slice(0, entropyBits / 8)); - } - /** - * Converts entropy to a mnemonic phrase. - * - * @param {Uint8Array} entropy - The entropy. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {string} The mnemonic phrase. - */ - function entropyToMnemonic(entropy, wordlist) { - assertArgument(entropy.length % 4 === 0 && entropy.length >= 16 && entropy.length <= 32, 'invalid entropy size', 'entropy', '[ REDACTED ]'); - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const indices = [0]; - let remainingBits = 11; - for (let i = 0; i < entropy.length; i++) { - // Consume the whole byte (with still more to go) - if (remainingBits > 8) { - indices[indices.length - 1] <<= 8; - indices[indices.length - 1] |= entropy[i]; - remainingBits -= 8; - // This byte will complete an 11-bit index - } - else { - indices[indices.length - 1] <<= remainingBits; - indices[indices.length - 1] |= entropy[i] >> (8 - remainingBits); - // Start the next word - indices.push(entropy[i] & getLowerMask(8 - remainingBits)); - remainingBits += 3; - } - } - // Compute the checksum bits - const checksumBits = entropy.length / 4; - const checksum = parseInt(sha256(entropy).substring(2, 4), 16) & getUpperMask(checksumBits); - // Shift the checksum into the word indices - indices[indices.length - 1] <<= checksumBits; - indices[indices.length - 1] |= checksum >> (8 - checksumBits); - return wordlist.join(indices.map((index) => wordlist.getWord(index))); - } - const _guard$2 = {}; - /** - * A **Mnemonic** wraps all properties required to compute [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) seeds and - * convert between phrases and entropy. - * - * @category Wallet - */ - class Mnemonic { - /** - * The mnemonic phrase of 12, 15, 18, 21 or 24 words. - * - * Use the {@link wordlist | **wordlist**} `split` method to get the individual words. - */ - phrase; - /** - * The password used for this mnemonic. If no password is used this is the empty string (i.e. `""`) as per the - * specification. - */ - password; - /** - * The wordlist for this mnemonic. - */ - wordlist; - /** - * The underlying entropy which the mnemonic encodes. - */ - entropy; - /** - * @param {any} guard - The guard object. - * @param {string} entropy - The entropy. - * @param {string} phrase - The mnemonic phrase. - * @param {string} [password] - The password for the mnemonic. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - */ - constructor(guard, entropy, phrase, password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - assertPrivate(guard, _guard$2, 'Mnemonic'); - defineProperties(this, { phrase, password, wordlist, entropy }); - } - /** - * Returns the seed for the mnemonic. - * - * @returns {string} The seed. - */ - computeSeed() { - const salt = toUtf8Bytes('mnemonic' + this.password, 'NFKD'); - return pbkdf2(toUtf8Bytes(this.phrase, 'NFKD'), salt, 2048, 64, 'sha512'); - } - /** - * Creates a new Mnemonic for the `phrase`. - * - * The default `password` is the empty string and the default wordlist is the {@link LangEn | **English wordlist**}. - * - * @param {string} phrase - The mnemonic phrase. - * @param {string} [password] - The password for the mnemonic. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {Mnemonic} The new Mnemonic object. - */ - static fromPhrase(phrase, password, wordlist) { - // Normalize the case and space; throws if invalid - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - if (password == null) { - password = ''; - } - const entropy = mnemonicToEntropy(phrase, wordlist); - phrase = entropyToMnemonic(getBytes(entropy), wordlist); - return new Mnemonic(_guard$2, entropy, phrase, password, wordlist); - } - /** - * Create a new **Mnemonic** from the `entropy`. - * - * The default `password` is the empty string and the default wordlist is the [{@link LangEn | **English wordlist**}. - * - * @param {BytesLike} _entropy - The entropy for the mnemonic. - * @param {string} [password] - The password for the mnemonic. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {Mnemonic} The new Mnemonic object. - */ - static fromEntropy(_entropy, password, wordlist) { - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - if (password == null) { - password = ''; - } - const entropy = getBytes(_entropy, 'entropy'); - const phrase = entropyToMnemonic(entropy, wordlist); - return new Mnemonic(_guard$2, hexlify(entropy), phrase, password, wordlist); - } - /** - * Returns the phrase for `mnemonic`. - * - * @param {BytesLike} _entropy - The entropy for the mnemonic. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {string} The mnemonic phrase. - */ - static entropyToPhrase(_entropy, wordlist) { - const entropy = getBytes(_entropy, 'entropy'); - return entropyToMnemonic(entropy, wordlist); - } - /** - * Returns the entropy for `phrase`. - * - * @param {string} phrase - The mnemonic phrase. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {string} The entropy. - */ - static phraseToEntropy(phrase, wordlist) { - return mnemonicToEntropy(phrase, wordlist); - } - /** - * Returns true if `phrase` is a valid [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) phrase. - * - * This checks all the provided words belong to the `wordlist`, that the length is valid and the checksum is - * correct. - * - * @param {string} phrase - The mnemonic phrase. - * @param {Wordlist} [wordlist] - The wordlist for the mnemonic. - * @returns {boolean} True if the phrase is valid. - * @throws {Error} If the phrase is invalid. - */ - static isValidMnemonic(phrase, wordlist) { - try { - mnemonicToEntropy(phrase, wordlist); - return true; - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; - } - } - - /*! MIT License. Copyright 2015-2022 Richard Moore . See LICENSE.txt. */ - var __classPrivateFieldGet$1 = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - var __classPrivateFieldSet$1 = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; - }; - var _AES_key, _AES_Kd, _AES_Ke; - // Number of rounds by keysize - const numberOfRounds = { 16: 10, 24: 12, 32: 14 }; - // Round constant words - const rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91]; - // S-box and Inverse S-box (S is for Substitution) - const S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]; - const Si = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d]; - // Transformations for encryption - const T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a]; - const T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616]; - const T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16]; - const T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c]; - // Transformations for decryption - const T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742]; - const T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857]; - const T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8]; - const T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0]; - // Transformations for decryption key expansion - const U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3]; - const U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697]; - const U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46]; - const U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d]; - function convertToInt32(bytes) { - const result = []; - for (let i = 0; i < bytes.length; i += 4) { - result.push((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]); - } - return result; - } - class AES { - get key() { return __classPrivateFieldGet$1(this, _AES_key, "f").slice(); } - constructor(key) { - _AES_key.set(this, void 0); - _AES_Kd.set(this, void 0); - _AES_Ke.set(this, void 0); - if (!(this instanceof AES)) { - throw Error('AES must be instanitated with `new`'); - } - __classPrivateFieldSet$1(this, _AES_key, new Uint8Array(key), "f"); - const rounds = numberOfRounds[this.key.length]; - if (rounds == null) { - throw new TypeError('invalid key size (must be 16, 24 or 32 bytes)'); - } - // encryption round keys - __classPrivateFieldSet$1(this, _AES_Ke, [], "f"); - // decryption round keys - __classPrivateFieldSet$1(this, _AES_Kd, [], "f"); - for (let i = 0; i <= rounds; i++) { - __classPrivateFieldGet$1(this, _AES_Ke, "f").push([0, 0, 0, 0]); - __classPrivateFieldGet$1(this, _AES_Kd, "f").push([0, 0, 0, 0]); - } - const roundKeyCount = (rounds + 1) * 4; - const KC = this.key.length / 4; - // convert the key into ints - const tk = convertToInt32(this.key); - // copy values into round key arrays - let index; - for (let i = 0; i < KC; i++) { - index = i >> 2; - __classPrivateFieldGet$1(this, _AES_Ke, "f")[index][i % 4] = tk[i]; - __classPrivateFieldGet$1(this, _AES_Kd, "f")[rounds - index][i % 4] = tk[i]; - } - // key expansion (fips-197 section 5.2) - let rconpointer = 0; - let t = KC, tt; - while (t < roundKeyCount) { - tt = tk[KC - 1]; - tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^ - (S[(tt >> 8) & 0xFF] << 16) ^ - (S[tt & 0xFF] << 8) ^ - S[(tt >> 24) & 0xFF] ^ - (rcon[rconpointer] << 24)); - rconpointer += 1; - // key expansion (for non-256 bit) - if (KC != 8) { - for (let i = 1; i < KC; i++) { - tk[i] ^= tk[i - 1]; - } - // key expansion for 256-bit keys is "slightly different" (fips-197) - } - else { - for (let i = 1; i < (KC / 2); i++) { - tk[i] ^= tk[i - 1]; - } - tt = tk[(KC / 2) - 1]; - tk[KC / 2] ^= (S[tt & 0xFF] ^ - (S[(tt >> 8) & 0xFF] << 8) ^ - (S[(tt >> 16) & 0xFF] << 16) ^ - (S[(tt >> 24) & 0xFF] << 24)); - for (let i = (KC / 2) + 1; i < KC; i++) { - tk[i] ^= tk[i - 1]; - } - } - // copy values into round key arrays - let i = 0, r, c; - while (i < KC && t < roundKeyCount) { - r = t >> 2; - c = t % 4; - __classPrivateFieldGet$1(this, _AES_Ke, "f")[r][c] = tk[i]; - __classPrivateFieldGet$1(this, _AES_Kd, "f")[rounds - r][c] = tk[i++]; - t++; - } - } - // inverse-cipher-ify the decryption round key (fips-197 section 5.3) - for (let r = 1; r < rounds; r++) { - for (let c = 0; c < 4; c++) { - tt = __classPrivateFieldGet$1(this, _AES_Kd, "f")[r][c]; - __classPrivateFieldGet$1(this, _AES_Kd, "f")[r][c] = (U1[(tt >> 24) & 0xFF] ^ - U2[(tt >> 16) & 0xFF] ^ - U3[(tt >> 8) & 0xFF] ^ - U4[tt & 0xFF]); - } - } - } - encrypt(plaintext) { - if (plaintext.length != 16) { - throw new TypeError('invalid plaintext size (must be 16 bytes)'); - } - const rounds = __classPrivateFieldGet$1(this, _AES_Ke, "f").length - 1; - const a = [0, 0, 0, 0]; - // convert plaintext to (ints ^ key) - let t = convertToInt32(plaintext); - for (let i = 0; i < 4; i++) { - t[i] ^= __classPrivateFieldGet$1(this, _AES_Ke, "f")[0][i]; - } - // apply round transforms - for (let r = 1; r < rounds; r++) { - for (let i = 0; i < 4; i++) { - a[i] = (T1[(t[i] >> 24) & 0xff] ^ - T2[(t[(i + 1) % 4] >> 16) & 0xff] ^ - T3[(t[(i + 2) % 4] >> 8) & 0xff] ^ - T4[t[(i + 3) % 4] & 0xff] ^ - __classPrivateFieldGet$1(this, _AES_Ke, "f")[r][i]); - } - t = a.slice(); - } - // the last round is special - const result = new Uint8Array(16); - let tt = 0; - for (let i = 0; i < 4; i++) { - tt = __classPrivateFieldGet$1(this, _AES_Ke, "f")[rounds][i]; - result[4 * i] = (S[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; - result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; - result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; - result[4 * i + 3] = (S[t[(i + 3) % 4] & 0xff] ^ tt) & 0xff; - } - return result; - } - decrypt(ciphertext) { - if (ciphertext.length != 16) { - throw new TypeError('invalid ciphertext size (must be 16 bytes)'); - } - const rounds = __classPrivateFieldGet$1(this, _AES_Kd, "f").length - 1; - const a = [0, 0, 0, 0]; - // convert plaintext to (ints ^ key) - let t = convertToInt32(ciphertext); - for (let i = 0; i < 4; i++) { - t[i] ^= __classPrivateFieldGet$1(this, _AES_Kd, "f")[0][i]; - } - // apply round transforms - for (let r = 1; r < rounds; r++) { - for (let i = 0; i < 4; i++) { - a[i] = (T5[(t[i] >> 24) & 0xff] ^ - T6[(t[(i + 3) % 4] >> 16) & 0xff] ^ - T7[(t[(i + 2) % 4] >> 8) & 0xff] ^ - T8[t[(i + 1) % 4] & 0xff] ^ - __classPrivateFieldGet$1(this, _AES_Kd, "f")[r][i]); - } - t = a.slice(); - } - // the last round is special - const result = new Uint8Array(16); - let tt = 0; - for (let i = 0; i < 4; i++) { - tt = __classPrivateFieldGet$1(this, _AES_Kd, "f")[rounds][i]; - result[4 * i] = (Si[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff; - result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff; - result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff; - result[4 * i + 3] = (Si[t[(i + 1) % 4] & 0xff] ^ tt) & 0xff; - } - return result; - } - } - _AES_key = new WeakMap(), _AES_Kd = new WeakMap(), _AES_Ke = new WeakMap(); - - class ModeOfOperation { - constructor(name, key, cls) { - if (cls && !(this instanceof cls)) { - throw new Error(`${name} must be instantiated with "new"`); - } - Object.defineProperties(this, { - aes: { enumerable: true, value: new AES(key) }, - name: { enumerable: true, value: name } - }); - } - } - - // Counter Mode - var __classPrivateFieldSet = (__$G && __$G.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; - }; - var __classPrivateFieldGet = (__$G && __$G.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); - }; - var _CTR_remaining, _CTR_remainingIndex, _CTR_counter; - class CTR extends ModeOfOperation { - constructor(key, initialValue) { - super("CTR", key, CTR); - // Remaining bytes for the one-time pad - _CTR_remaining.set(this, void 0); - _CTR_remainingIndex.set(this, void 0); - // The current counter - _CTR_counter.set(this, void 0); - __classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), "f"); - __classPrivateFieldGet(this, _CTR_counter, "f").fill(0); - __classPrivateFieldSet(this, _CTR_remaining, __classPrivateFieldGet(this, _CTR_counter, "f"), "f"); // This will be discarded immediately - __classPrivateFieldSet(this, _CTR_remainingIndex, 16, "f"); - if (initialValue == null) { - initialValue = 1; - } - if (typeof (initialValue) === "number") { - this.setCounterValue(initialValue); - } - else { - this.setCounterBytes(initialValue); - } - } - get counter() { return new Uint8Array(__classPrivateFieldGet(this, _CTR_counter, "f")); } - setCounterValue(value) { - if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) { - throw new TypeError("invalid counter initial integer value"); - } - for (let index = 15; index >= 0; --index) { - __classPrivateFieldGet(this, _CTR_counter, "f")[index] = value % 256; - value = Math.floor(value / 256); - } - } - setCounterBytes(value) { - if (value.length !== 16) { - throw new TypeError("invalid counter initial Uint8Array value length"); - } - __classPrivateFieldGet(this, _CTR_counter, "f").set(value); - } - increment() { - for (let i = 15; i >= 0; i--) { - if (__classPrivateFieldGet(this, _CTR_counter, "f")[i] === 255) { - __classPrivateFieldGet(this, _CTR_counter, "f")[i] = 0; - } - else { - __classPrivateFieldGet(this, _CTR_counter, "f")[i]++; - break; - } - } - } - encrypt(plaintext) { - var _a, _b; - const crypttext = new Uint8Array(plaintext); - for (let i = 0; i < crypttext.length; i++) { - if (__classPrivateFieldGet(this, _CTR_remainingIndex, "f") === 16) { - __classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet(this, _CTR_counter, "f")), "f"); - __classPrivateFieldSet(this, _CTR_remainingIndex, 0, "f"); - this.increment(); - } - crypttext[i] ^= __classPrivateFieldGet(this, _CTR_remaining, "f")[__classPrivateFieldSet(this, _CTR_remainingIndex, (_b = __classPrivateFieldGet(this, _CTR_remainingIndex, "f"), _a = _b++, _b), "f"), _a]; - } - return crypttext; - } - decrypt(ciphertext) { - return this.encrypt(ciphertext); - } - } - _CTR_remaining = new WeakMap(), _CTR_remainingIndex = new WeakMap(), _CTR_counter = new WeakMap(); - - /** - * @module wallet/utils - */ - /** - * Converts a hex string to a Uint8Array. If the string does not start with '0x', it adds it. - * @param {string} hexString - The hex string to convert. - * @returns {Uint8Array} The resulting byte array. - */ - function looseArrayify(hexString) { - if (typeof hexString === 'string' && !hexString.startsWith('0x')) { - hexString = '0x' + hexString; - } - return getBytesCopy(hexString); - } - /** - * Converts a password to a Uint8Array. If the password is a string, it converts it to UTF-8 bytes. - * @param {string|Uint8Array} password - The password to convert. - * @returns {Uint8Array} The resulting byte array. - */ - function getPassword(password) { - if (typeof password === 'string') { - return toUtf8Bytes(password, 'NFKC'); - } - return getBytesCopy(password); - } - /** - * Traverses an object based on a path and returns the value at that path. - * @param {any} object - The object to traverse. - * @param {string} _path - The path to traverse. - * @returns {T} The value at the specified path. - */ - function spelunk(object, _path) { - const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i); - assertArgument(match != null, 'invalid path', 'path', _path); - const path = match[1]; - const type = match[3]; - const reqd = match[4] === '!'; - let cur = object; - for (const comp of path.toLowerCase().split('.')) { - // Search for a child object with a case-insensitive matching key - if (Array.isArray(cur)) { - if (!comp.match(/^[0-9]+$/)) { - break; - } - cur = cur[parseInt(comp)]; - } - else if (typeof cur === 'object') { - let found = null; - for (const key in cur) { - if (key.toLowerCase() === comp) { - found = cur[key]; - break; - } - } - cur = found; - } - else { - cur = null; - } - if (cur == null) { - break; - } - } - assertArgument(!reqd || cur != null, 'missing required value', 'path', path); - if (type && cur != null) { - if (type === 'int') { - if (typeof cur === 'string' && cur.match(/^-?[0-9]+$/)) { - return parseInt(cur); - } - else if (Number.isSafeInteger(cur)) { - return cur; - } - } - if (type === 'number') { - if (typeof cur === 'string' && cur.match(/^-?[0-9.]*$/)) { - return parseFloat(cur); - } - } - if (type === 'data') { - if (typeof cur === 'string') { - return looseArrayify(cur); - } - } - if (type === 'array' && Array.isArray(cur)) { - return cur; - } - if (type === typeof cur) { - return cur; - } - assertArgument(false, `wrong type found for ${type} `, 'path', path); - } - return cur; - } - /** Constant N used in cryptographic operations */ - BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); - /** - * Pads a value with leading zeros to a specified length. - * @param {string|number} value - The value to pad. - * @param {number} length - The desired length. - * @returns {string} The padded value. - */ - function zpad$1(value, length) { - // Determine if the value is hexadecimal - const isHex = typeof value === 'string' && value.startsWith('0x'); - // Handle hexadecimal values - if (isHex) { - let hexValue = value.substring(2); // Remove the "0x" prefix - while (hexValue.length < length * 2) { - // Hexadecimal characters count double - hexValue = '0' + hexValue; - } - return '0x' + hexValue; - } - // Handle numbers or non-hexadecimal strings - let result = String(value); - while (result.length < length) { - result = '0' + result; - } - return result; - } - - /** - * The JSON Wallet formats allow a simple way to store the private keys needed in Ethereum along with related - * information and allows for extensible forms of encryption. - * - * These utilities facilitate decrypting and encrypting the most common JSON Wallet formats. - */ - const defaultPath = "m/44'/994'/0'/0/0"; - /** - * Returns true if `json` is a valid JSON Keystore Wallet. - * - * @category Wallet - * @param {string} json - The JSON data to check. - * - * @returns {boolean} True if the JSON data is a valid Keystore Wallet. - */ - function isKeystoreJson(json) { - try { - const data = JSON.parse(json); - const version = data.version != null ? parseInt(data.version) : 0; - if (version === 3) { - return true; - } - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; - } - /** - * Decrypts the given ciphertext using the provided key and data. - * - * @param {any} data - The data containing encryption parameters. - * @param {Uint8Array} key - The key to use for decryption. - * @param {Uint8Array} ciphertext - The ciphertext to decrypt. - * - * @returns {string} The decrypted data as a hex string. - */ - function decrypt(data, key, ciphertext) { - const cipher = spelunk(data, 'crypto.cipher:string'); - if (cipher === 'aes-128-ctr') { - const iv = spelunk(data, 'crypto.cipherparams.iv:data!'); - const aesCtr = new CTR(key, iv); - return hexlify(aesCtr.decrypt(ciphertext)); - } - assert(false, 'unsupported cipher', 'UNSUPPORTED_OPERATION', { - operation: 'decrypt', - }); - } - /** - * Retrieves the account details from the given data and key. - * - * @param {any} data - The data containing account information. - * @param {string} _key - The key to use for decryption. - * - * @returns {KeystoreAccount} The decrypted account details. - */ - function getAccount(data, _key) { - const key = getBytes(_key); - const ciphertext = spelunk(data, 'crypto.ciphertext:data!'); - const computedMAC = hexlify(keccak256(concat([key.slice(16, 32), ciphertext]))).substring(2); - assertArgument(computedMAC === spelunk(data, 'crypto.mac:string!').toLowerCase(), 'incorrect password', 'password', '[ REDACTED ]'); - const privateKey = decrypt(data, key.slice(0, 16), ciphertext); - const address = computeAddress(privateKey); - if (data.address) { - let check = data.address.toLowerCase(); - if (!check.startsWith('0x')) { - check = '0x' + check; - } - assertArgument(getAddress(check) === address, 'keystore address/privateKey mismatch', 'address', data.address); - } - const account = { address, privateKey }; - // Version 0.1 x-quais metadata must contain an encrypted mnemonic phrase - const version = spelunk(data, 'x-quais.version:string'); - if (version === '0.1') { - const mnemonicKey = key.slice(32, 64); - const mnemonicCiphertext = spelunk(data, 'x-quais.mnemonicCiphertext:data!'); - const mnemonicIv = spelunk(data, 'x-quais.mnemonicCounter:data!'); - const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); - account.mnemonic = { - path: spelunk(data, 'x-quais.path:string') || defaultPath, - locale: spelunk(data, 'x-quais.locale:string') || 'en', - entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))), - }; - } - return account; - } - /** - * Retrieves the key derivation function parameters from the given data. - * - * @param {any} data - The data containing KDF parameters. - * - * @returns {KdfParams} The key derivation function parameters. - */ - function getDecryptKdfParams(data) { - const kdf = spelunk(data, 'crypto.kdf:string'); - if (kdf && typeof kdf === 'string') { - if (kdf.toLowerCase() === 'scrypt') { - const salt = spelunk(data, 'crypto.kdfparams.salt:data!'); - const N = spelunk(data, 'crypto.kdfparams.n:int!'); - const r = spelunk(data, 'crypto.kdfparams.r:int!'); - const p = spelunk(data, 'crypto.kdfparams.p:int!'); - // Make sure N is a power of 2 - assertArgument(N > 0 && (N & (N - 1)) === 0, 'invalid kdf.N', 'kdf.N', N); - assertArgument(r > 0 && p > 0, 'invalid kdf', 'kdf', kdf); - const dkLen = spelunk(data, 'crypto.kdfparams.dklen:int!'); - assertArgument(dkLen === 32, 'invalid kdf.dklen', 'kdf.dflen', dkLen); - return { name: 'scrypt', salt, N, r, p, dkLen: 64 }; - } - else if (kdf.toLowerCase() === 'pbkdf2') { - const salt = spelunk(data, 'crypto.kdfparams.salt:data!'); - const prf = spelunk(data, 'crypto.kdfparams.prf:string!'); - const algorithm = prf.split('-').pop(); - assertArgument(algorithm === 'sha256' || algorithm === 'sha512', 'invalid kdf.pdf', 'kdf.pdf', prf); - const count = spelunk(data, 'crypto.kdfparams.c:int!'); - const dkLen = spelunk(data, 'crypto.kdfparams.dklen:int!'); - assertArgument(dkLen === 32, 'invalid kdf.dklen', 'kdf.dklen', dkLen); - return { name: 'pbkdf2', salt, count, dkLen, algorithm }; - } - } - assertArgument(false, 'unsupported key-derivation function', 'kdf', kdf); - } - /** - * Returns the account details for the JSON Keystore Wallet `json` using `password`. - * - * It is preferred to use the {@link decryptKeystoreJson | **async version**} instead, which allows a - * {@link ProgressCallback | **ProgressCallback} to keep the user informed as to the decryption status. - * - * This method will block the event loop (freezing all UI) until decryption is complete, which can take quite some time, - * depending on the wallet paramters and platform. - * - * @category Wallet - * @param {string} json - The JSON data to decrypt. - * @param {string | Uint8Array} _password - The password to decrypt the JSON data. - * - * @returns {KeystoreAccount} The decrypted account. - */ - function decryptKeystoreJsonSync(json, _password) { - const data = JSON.parse(json); - const password = getPassword(_password); - const params = getDecryptKdfParams(data); - if (params.name === 'pbkdf2') { - const { salt, count, dkLen, algorithm } = params; - const key = pbkdf2(password, salt, count, dkLen, algorithm); - return getAccount(data, key); - } - assert(params.name === 'scrypt', 'cannot be reached', 'UNKNOWN_ERROR', { params }); - const { salt, N, r, p, dkLen } = params; - const key = scryptSync(password, salt, N, r, p, dkLen); - return getAccount(data, key); - } - /** - * Pauses execution for the specified duration. - * - * @param {number} duration - The duration to stall in milliseconds. - * - * @returns {Promise} A promise that resolves after the specified duration. - */ - function stall$1(duration) { - return new Promise((resolve) => { - setTimeout(() => { - resolve(); - }, duration); - }); - } - /** - * Resolves to the decrypted JSON Keystore Wallet `json` using the `password`. - * - * If provided, `progress` will be called periodically during the decrpytion to provide feedback, and if the function - * returns `false` will halt decryption. - * - * The `progressCallback` will **always** receive `0` before decryption begins and `1` when complete. - * - * @category Wallet - * @param {string} json - The JSON data to decrypt. - * @param {string | Uint8Array} _password - The password to decrypt the JSON data. - * @param {ProgressCallback} [progress] - The callback to receive progress updates. - * - * @returns {Promise} The decrypted account. - */ - async function decryptKeystoreJson(json, _password, progress) { - const data = JSON.parse(json); - const password = getPassword(_password); - const params = getDecryptKdfParams(data); - if (params.name === 'pbkdf2') { - if (progress) { - progress(0); - await stall$1(0); - } - const { salt, count, dkLen, algorithm } = params; - const key = pbkdf2(password, salt, count, dkLen, algorithm); - if (progress) { - progress(1); - await stall$1(0); - } - return getAccount(data, key); - } - assert(params.name === 'scrypt', 'cannot be reached', 'UNKNOWN_ERROR', { params }); - const { salt, N, r, p, dkLen } = params; - const key = await scrypt(password, salt, N, r, p, dkLen, progress); - return getAccount(data, key); - } - /** - * Retrieves the key derivation function parameters for encryption. - * - * @param {EncryptOptions} options - The encryption options. - * - * @returns {ScryptParams} The key derivation function parameters. - */ - function getEncryptKdfParams(options) { - // Check/generate the salt - const salt = options.salt != null ? getBytes(options.salt, 'options.salt') : randomBytes(32); - // Override the scrypt password-based key derivation function parameters - let N = 1 << 17, r = 8, p = 1; - if (options.scrypt) { - if (options.scrypt.N) { - N = options.scrypt.N; - } - if (options.scrypt.r) { - r = options.scrypt.r; - } - if (options.scrypt.p) { - p = options.scrypt.p; - } - } - assertArgument(typeof N === 'number' && N > 0 && Number.isSafeInteger(N) && (BigInt(N) & BigInt(N - 1)) === BigInt(0), 'invalid scrypt N parameter', 'options.N', N); - assertArgument(typeof r === 'number' && r > 0 && Number.isSafeInteger(r), 'invalid scrypt r parameter', 'options.r', r); - assertArgument(typeof p === 'number' && p > 0 && Number.isSafeInteger(p), 'invalid scrypt p parameter', 'options.p', p); - return { name: 'scrypt', dkLen: 32, salt, N, r, p }; - } - /** - * Encrypts the keystore with the given key, KDF parameters, account, and options. - * - * @ignore - * @param {Uint8Array} key - The key to use for encryption. - * @param {ScryptParams} kdf - The key derivation function parameters. - * @param {KeystoreAccount} account - The account to encrypt. - * @param {EncryptOptions} options - The encryption options. - * - * @returns {any} The encrypted keystore data. - */ - function _encryptKeystore(key, kdf, account, options) { - const privateKey = getBytes(account.privateKey, 'privateKey'); - // Override initialization vector - const iv = options.iv != null ? getBytes(options.iv, 'options.iv') : randomBytes(16); - assertArgument(iv.length === 16, 'invalid options.iv length', 'options.iv', options.iv); - // Override the uuid - const uuidRandom = options.uuid != null ? getBytes(options.uuid, 'options.uuid') : randomBytes(16); - assertArgument(uuidRandom.length === 16, 'invalid options.uuid length', 'options.uuid', options.iv); - // This will be used to encrypt the wallet (as per Web3 secret storage) - // - 32 bytes As normal for the Web3 secret storage (derivedKey, macPrefix) - // - 32 bytes AES key to encrypt mnemonic with (required here to be quais Wallet) - const derivedKey = key.slice(0, 16); - const macPrefix = key.slice(16, 32); - // Encrypt the private key - const aesCtr = new CTR(derivedKey, iv); - const ciphertext = getBytes(aesCtr.encrypt(privateKey)); - // Compute the message authentication code, used to check the password - const mac = keccak256(concat([macPrefix, ciphertext])); - // See: https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition - const data = { - address: account.address.substring(2).toLowerCase(), - id: uuidV4(uuidRandom), - version: 3, - Crypto: { - cipher: 'aes-128-ctr', - cipherparams: { - iv: hexlify(iv).substring(2), - }, - ciphertext: hexlify(ciphertext).substring(2), - kdf: 'scrypt', - kdfparams: { - salt: hexlify(kdf.salt).substring(2), - n: kdf.N, - dklen: 32, - p: kdf.p, - r: kdf.r, - }, - mac: mac.substring(2), - }, - }; - // If we have a mnemonic, encrypt it into the JSON wallet - if (account.mnemonic) { - const client = options.client != null ? options.client : `quais/${version}`; - const path = account.mnemonic.path || defaultPath; - const locale = account.mnemonic.locale || 'en'; - const mnemonicKey = key.slice(32, 64); - const entropy = getBytes(account.mnemonic.entropy, 'account.mnemonic.entropy'); - const mnemonicIv = randomBytes(16); - const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); - const mnemonicCiphertext = getBytes(mnemonicAesCtr.encrypt(entropy)); - const now = new Date(); - const timestamp = now.getUTCFullYear() + - '-' + - zpad$1(now.getUTCMonth() + 1, 2) + - '-' + - zpad$1(now.getUTCDate(), 2) + - 'T' + - zpad$1(now.getUTCHours(), 2) + - '-' + - zpad$1(now.getUTCMinutes(), 2) + - '-' + - zpad$1(now.getUTCSeconds(), 2) + - '.0Z'; - const gethFilename = 'UTC--' + timestamp + '--' + data.address; - data['x-quais'] = { - client, - gethFilename, - path, - locale, - mnemonicCounter: hexlify(mnemonicIv).substring(2), - mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2), - version: '0.1', - }; - } - return JSON.stringify(data); - } - /** - * Return the JSON Keystore Wallet for `account` encrypted with `password`. - * - * The `options` can be used to tune the password-based key derivation function parameters, explicitly set the random - * values used. Any provided {@link ProgressCallback | **ProgressCallback**} is ignored. - * - * @category Wallet - * @param {KeystoreAccount} account - The account to encrypt. - * @param {string | Uint8Array} password - The password to encrypt the JSON data. - * @param {EncryptOptions} [options] - The options to use when encrypting the JSON data. - * - * @returns {string} The encrypted JSON data. - */ - function encryptKeystoreJsonSync(account, password, options) { - if (options == null) { - options = {}; - } - const passwordBytes = getPassword(password); - const kdf = getEncryptKdfParams(options); - const key = scryptSync(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64); - return _encryptKeystore(getBytes(key), kdf, account, options); - } - /** - * Resolved to the JSON Keystore Wallet for `account` encrypted with `password`. - * - * The `options` can be used to tune the password-based key derivation function parameters, explicitly set the random - * values used and provide a {@link ProgressCallback | **ProgressCallback**} to receive periodic updates on the - * completion status.. - * - * @category Wallet - * @param {KeystoreAccount} account - The account to encrypt. - * @param {string | Uint8Array} password - The password to encrypt the JSON data. - * @param {EncryptOptions} [options] - The options to use when encrypting the JSON data. - * - * @returns {Promise} The encrypted JSON data. - */ - async function encryptKeystoreJson(account, password, options) { - if (options == null) { - options = {}; - } - const passwordBytes = getPassword(password); - const kdf = getEncryptKdfParams(options); - const key = await scrypt(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64, options.progressCallback); - return _encryptKeystore(getBytes(key), kdf, account, options); - } - - // "Bitcoin seed" - const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]); - const HardenedBit = 0x80000000; - const N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'); - const Nibbles = '0123456789abcdef'; - function zpad(value, length) { - let result = ''; - while (value) { - result = Nibbles[value % 16] + result; - value = Math.trunc(value / 16); - } - while (result.length < length * 2) { - result = '0' + result; - } - return '0x' + result; - } - function encodeBase58Check(_value) { - const value = getBytes(_value); - const check = dataSlice(sha256(sha256(value)), 0, 4); - const bytes = concat([value, check]); - return encodeBase58(bytes); - } - const _guard$1 = {}; - function ser_I(index, chainCode, publicKey, privateKey) { - const data = new Uint8Array(37); - if (index & HardenedBit) { - assert(privateKey != null, 'cannot derive child of neutered node', 'UNSUPPORTED_OPERATION', { - operation: 'deriveChild', - }); - // Data = 0x00 || ser_256(k_par) - data.set(getBytes(privateKey), 1); - } - else { - // Data = ser_p(point(k_par)) - data.set(getBytes(publicKey)); - } - // Data += ser_32(i) - for (let i = 24; i >= 0; i -= 8) { - data[33 + (i >> 3)] = (index >> (24 - i)) & 0xff; - } - const I = getBytes(computeHmac('sha512', chainCode, data)); - return { IL: I.slice(0, 32), IR: I.slice(32) }; - } - function derivePath(node, path) { - const components = path.split('/'); - assertArgument(components.length > 0, 'invalid path', 'path', path); - if (components[0] === 'm') { - 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); - components.shift(); - } - let result = node; - for (let i = 0; i < components.length; i++) { - const component = components[i]; - if (component.match(/^[0-9]+'$/)) { - const index = parseInt(component.substring(0, component.length - 1)); - assertArgument(index < HardenedBit, 'invalid path index', `path[${i}]`, component); - result = result.deriveChild(HardenedBit + index); - } - else if (component.match(/^[0-9]+$/)) { - const index = parseInt(component); - assertArgument(index < HardenedBit, 'invalid path index', `path[${i}]`, component); - result = result.deriveChild(index); - } - else { - assertArgument(false, 'invalid path component', `path[${i}]`, component); - } - } - return result; - } - /** - * An **HDNodeWallet** is a [[Signer]] backed by the private key derived from an HD Node using the [[link-bip-32]] - * standard. - * - * An HD Node forms a hierarchical structure with each HD Node having a private key and the ability to derive child HD - * Nodes, defined by a path indicating the index of each child. - */ - class HDNodeWallet extends BaseWallet { - /** - * The compressed public key. - * - * @type {string} - */ - publicKey; - /** - * The fingerprint. - * - * A fingerprint allows a quick way to detect parent and child nodes, but developers should be prepared to deal with - * collisions as it is only 4 bytes. - * - * @type {string} - */ - fingerprint; - /** - * The parent fingerprint. - * - * @type {string} - */ - parentFingerprint; - /** - * The mnemonic used to create this HD Node, if available. - * - * Sources such as extended keys do not encode the mnemonic, in which case this will be `null`. - * - * @type {null | Mnemonic} - */ - mnemonic; - /** - * The chaincode, which is effectively a public key used to derive children. - * - * @type {string} - */ - chainCode; - /** - * The derivation path of this wallet. - * - * Since extended keys do not provide full path details, this may be `null`, if instantiated from a source that does - * not encode it. - * - * @type {null | string} - */ - path; - /** - * The child index of this wallet. Values over `2 ** 31` indicate the node is hardened. - * - * @type {number} - */ - index; - /** - * The depth of this wallet, which is the number of components in its path. - * - * @type {number} - */ - depth; - /** - * @param {any} guard - * @param {SigningKey} signingKey - * @param {string} parentFingerprint - * @param {string} chainCode - * @param {null | string} path - * @param {number} index - * @param {number} depth - * @param {null | Mnemonic} mnemonic - * @param {null | Provider} provider - * @ignore - */ - constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider) { - super(signingKey, provider); - assertPrivate(guard, _guard$1, 'HDNodeWallet'); - defineProperties(this, { publicKey: signingKey.compressedPublicKey }); - const fingerprint = dataSlice(ripemd160(sha256(this.publicKey)), 0, 4); - defineProperties(this, { - parentFingerprint, - fingerprint, - chainCode, - path, - index, - depth, - }); - defineProperties(this, { mnemonic }); - } - /** - * Connects the wallet to a provider. - * - * @param {null | Provider} provider - * - * @returns {HDNodeWallet} - */ - connect(provider) { - return new HDNodeWallet(_guard$1, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider); - } - /** - * @returns {KeystoreAccount} - * @ignore - */ - #account() { - const account = { address: this.address, privateKey: this.privateKey }; - const m = this.mnemonic; - if (this.path && m && m.wordlist.locale === 'en' && m.password === '') { - account.mnemonic = { - path: this.path, - locale: 'en', - entropy: m.entropy, - }; - } - return account; - } - /** - * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with `password`. - * - * If `progressCallback` is specified, it will receive periodic updates as the encryption process progresses. - * - * @param {Uint8Array | string} password - * @param {ProgressCallback} [progressCallback] - * - * @returns {Promise} - */ - async encrypt(password, progressCallback) { - return await encryptKeystoreJson(this.#account(), password, { progressCallback }); - } - /** - * Returns a [JSON Keystore Wallet](json-wallets) encrypted with `password`. - * - * It is preferred to use the [async version](encrypt) instead, which allows a `ProgressCallback` to keep the user - * informed. - * - * This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial - * duration. - * - * @param {Uint8Array | string} password - * - * @returns {string} - */ - encryptSync(password) { - return encryptKeystoreJsonSync(this.#account(), password); - } - /** - * The extended key. - * - * This key will begin with the prefix `xpriv` and can be used to reconstruct this HD Node to derive its children. - * - * @returns {string} - */ - get extendedKey() { - // We only support the mainnet values for now, but if anyone needs - // testnet values, let me know. I believe current sentiment is that - // we should always use mainnet, and use BIP-44 to derive the network - // - Mainnet: public=0x0488B21E, private=0x0488ADE4 - // - Testnet: public=0x043587CF, private=0x04358394 - assert(this.depth < 256, 'Depth too deep', 'UNSUPPORTED_OPERATION', { - operation: 'extendedKey', - }); - return encodeBase58Check(concat([ - '0x0488ADE4', - zpad(this.depth, 1), - this.parentFingerprint, - zpad(this.index, 4), - this.chainCode, - concat(['0x00', this.privateKey]), - ])); - } - /** - * Returns true if this wallet has a path, providing a Type Guard that the path is non-null. - * - * @returns {boolean} - */ - hasPath() { - return this.path != null; - } - /** - * Returns a neutered HD Node, which removes the private details of an HD Node. - * - * A neutered node has no private key, but can be used to derive child addresses and other public data about the HD - * Node. - * - * @returns {HDNodeVoidWallet} - */ - neuter() { - return new HDNodeVoidWallet(_guard$1, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider); - } - /** - * Return the child for `index`. - * - * @param {Numeric} _index - * - * @returns {HDNodeWallet} - */ - deriveChild(_index) { - const index = getNumber(_index, 'index'); - assertArgument(index <= 0xffffffff, 'invalid index', 'index', index); - // Base path - let path = this.path; - if (path) { - path += '/' + (index & ~HardenedBit); - if (index & HardenedBit) { - path += "'"; - } - } - const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey); - const ki = new SigningKey(toBeHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32)); - return new HDNodeWallet(_guard$1, ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.mnemonic, this.provider); - } - /** - * Return the HDNode for `path` from this node. - * - * @param {string} path - * - * @returns {HDNodeWallet} - */ - derivePath(path) { - return derivePath(this, path); - } - /** - - * @param {BytesLike} _seed - * @param {null | Mnemonic} mnemonic - * - * @returns {HDNodeWallet} - * @ignore - */ - static #fromSeed(_seed, mnemonic) { - assertArgument(isBytesLike(_seed), 'invalid seed', 'seed', '[REDACTED]'); - const seed = getBytes(_seed, 'seed'); - assertArgument(seed.length >= 16 && seed.length <= 64, 'invalid seed', 'seed', '[REDACTED]'); - const I = getBytes(computeHmac('sha512', MasterSecret, seed)); - const signingKey = new SigningKey(hexlify(I.slice(0, 32))); - return new HDNodeWallet(_guard$1, signingKey, '0x00000000', hexlify(I.slice(32)), 'm', 0, 0, mnemonic, null); - } - /** - * Creates a new HD Node from `extendedKey`. - * - * If the `extendedKey` will either have a prefix or `xpub` or `xpriv`, returning a neutered HD Node - * ([[HDNodeVoidWallet]]) or full HD Node ([[HDNodeWallet]]) respectively. - * - * @param {string} extendedKey - * - * @returns {HDNodeWallet | HDNodeVoidWallet} - */ - static fromExtendedKey(extendedKey) { - const bytes = toBeArray(decodeBase58(extendedKey)); // @TODO: redact - assertArgument(bytes.length === 82 || encodeBase58Check(bytes.slice(0, 78)) === extendedKey, 'invalid extended key', 'extendedKey', '[ REDACTED ]'); - const depth = bytes[4]; - const parentFingerprint = hexlify(bytes.slice(5, 9)); - const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16); - const chainCode = hexlify(bytes.slice(13, 45)); - const key = bytes.slice(45, 78); - switch (hexlify(bytes.slice(0, 4))) { - // Public Key - case '0x0488b21e': - case '0x043587cf': { - const publicKey = hexlify(key); - return new HDNodeVoidWallet(_guard$1, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null); - } - // Private Key - case '0x0488ade4': - case '0x04358394 ': - if (key[0] !== 0) { - break; - } - return new HDNodeWallet(_guard$1, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null); - } - assertArgument(false, 'invalid extended key prefix', 'extendedKey', '[ REDACTED ]'); - } - /** - * Creates a new random HDNode. - * - * @param {string} path - * @param {string} [password] - * @param {Wordlist} [wordlist] - * - * @returns {HDNodeWallet} - */ - static createRandom(path, password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist); - return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); - } - /** - * Create an HD Node from `mnemonic`. - * - * @param {Mnemonic} mnemonic - * @param {string} path - * - * @returns {HDNodeWallet} - */ - static fromMnemonic(mnemonic, path) { - return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); - } - /** - * Creates an HD Node from a mnemonic `phrase`. - * - * @param {string} phrase - * @param {string} path - * @param {string} [password] - * @param {Wordlist} [wordlist] - * - * @returns {HDNodeWallet} - */ - static fromPhrase(phrase, path, password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist); - return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); - } - /** - * Creates an HD Node from a `seed`. - * - * @param {BytesLike} seed - * - * @returns {HDNodeWallet} - */ - static fromSeed(seed) { - return HDNodeWallet.#fromSeed(seed, null); - } - } - /** - * A **HDNodeVoidWallet** cannot sign, but provides access to the children nodes of a [[link-bip-32]] HD wallet - * addresses. - * - * They can be created by using an extended `xpub` key to [[HDNodeWallet_fromExtendedKey]] or by - * [neutering](HDNodeWallet-neuter) a [[HDNodeWallet]]. - */ - class HDNodeVoidWallet extends VoidSigner { - /** - * The compressed public key. - * - * @type {string} - */ - publicKey; - /** - * The fingerprint. - * - * A fingerprint allows a quick way to detect parent and child nodes, but developers should be prepared to deal with - * collisions as it is only 4 bytes. - * - * @type {string} - */ - fingerprint; - /** - * The parent node fingerprint. - * - * @type {string} - */ - parentFingerprint; - /** - * The chaincode, which is effectively a public key used to derive children. - * - * @type {string} - */ - chainCode; - /** - * The derivation path of this wallet. - * - * Since extended keys do not provide full path details, this may be `null`, if instantiated from a source that does - * not encode it. - * - * @type {null | string} - */ - path; - /** - * The child index of this wallet. Values over `2 ** 31` indicate the node is hardened. - * - * @type {number} - */ - index; - /** - * The depth of this wallet, which is the number of components in its path. - * - * @type {number} - */ - depth; - /** - * @param {any} guard - * @param {string} address - * @param {string} publicKey - * @param {string} parentFingerprint - * @param {string} chainCode - * @param {null | string} path - * @param {number} index - * @param {number} depth - * @param {null | Provider} provider - * @ignore - */ - constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider) { - super(address, provider); - assertPrivate(guard, _guard$1, 'HDNodeVoidWallet'); - defineProperties(this, { publicKey }); - const fingerprint = dataSlice(ripemd160(sha256(publicKey)), 0, 4); - defineProperties(this, { - publicKey, - fingerprint, - parentFingerprint, - chainCode, - path, - index, - depth, - }); - } - /** - * Connects the wallet to a provider. - * - * @param {null | Provider} provider - * - * @returns {HDNodeVoidWallet} - */ - connect(provider) { - return new HDNodeVoidWallet(_guard$1, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider); - } - /** - * The extended key. - * - * This key will begin with the prefix `xpub` and can be used to reconstruct this neutered key to derive its - * children addresses. - * - * @returns {string} - */ - get extendedKey() { - // We only support the mainnet values for now, but if anyone needs - // testnet values, let me know. I believe current sentiment is that - // we should always use mainnet, and use BIP-44 to derive the network - // - Mainnet: public=0x0488B21E, private=0x0488ADE4 - // - Testnet: public=0x043587CF, private=0x04358394 - assert(this.depth < 256, 'Depth too deep', 'UNSUPPORTED_OPERATION', { operation: 'extendedKey' }); - return encodeBase58Check(concat([ - '0x0488B21E', - zpad(this.depth, 1), - this.parentFingerprint, - zpad(this.index, 4), - this.chainCode, - this.publicKey, - ])); - } - /** - * Returns true if this wallet has a path, providing a Type Guard that the path is non-null. - * - * @returns {boolean} - */ - hasPath() { - return this.path != null; - } - /** - * Return the child for `index`. - * - * @param {Numeric} _index - * - * @returns {HDNodeVoidWallet} - */ - deriveChild(_index) { - const index = getNumber(_index, 'index'); - assertArgument(index <= 0xffffffff, 'invalid index', 'index', index); - // Base path - let path = this.path; - if (path) { - path += '/' + (index & ~HardenedBit); - if (index & HardenedBit) { - path += "'"; - } - } - const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null); - const Ki = SigningKey.addPoints(IL, this.publicKey, true); - const address = computeAddress(Ki); - return new HDNodeVoidWallet(_guard$1, address, Ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.provider); - } - /** - * Return the signer for `path` from this node. - * - * @param {string} path - * - * @returns {HDNodeVoidWallet} - */ - derivePath(path) { - return derivePath(this, path); - } - } - - /** - * Constant to represent the maximum attempt to derive an address. - */ - const MAX_ADDRESS_DERIVATION_ATTEMPTS = 10000000; - const _guard = {}; - /** - * Abstract class representing a Hierarchical Deterministic (HD) wallet. - */ - class AbstractHDWallet { - static _version = 1; - static _coinType; - // Map of addresses to address info - _addresses = new Map(); - /** - * Root node of the HD wallet. - */ - _root; - provider; - /** - * @param {HDNodeWallet} root - The root node of the HD wallet. - * @param {Provider} [provider] - The provider for the HD wallet. - */ - constructor(guard, root, provider) { - assertPrivate(guard, _guard, 'AbstractHDWallet'); - this._root = root; - this.provider = provider; - } - /** - * Returns the parent path for a given coin type. - * - * @param {number} coinType - The coin type. - * @returns {string} The parent path. - */ - static parentPath(coinType) { - return `m/44'/${coinType}'`; - } - /** - * Returns the coin type of the wallet. - * - * @returns {AllowedCoinType} The coin type. - */ - coinType() { - return this.constructor._coinType; - } - /** - * Returns the extended public key of the root node of the HD wallet. - * - * @returns {string} The extended public key. - */ - get xPub() { - return this._root.extendedKey; - } - /** - * Derives the next valid address node for a specified account, starting index, and zone. The method ensures the - * derived address belongs to the correct shard and ledger, as defined by the Quai blockchain specifications. - * - * @param {number} account - The account number from which to derive the address node. - * @param {number} startingIndex - The index from which to start deriving addresses. - * @param {Zone} zone - The zone (shard) for which the address should be valid. - * @param {boolean} [isChange=false] - Whether to derive a change address. Default is `false` - * @returns {HDNodeWallet} - The derived HD node wallet containing a valid address for the specified zone. - * @throws {Error} If a valid address for the specified zone cannot be derived within the allowed attempts. - */ - deriveNextAddressNode(account, startingIndex, zone, isChange = false) { - const changeIndex = isChange ? 1 : 0; - const changeNode = this._root.deriveChild(account).deriveChild(changeIndex); - let addrIndex = startingIndex; - let addressNode; - const isValidAddressForZone = (address) => { - const addressZone = getZoneForAddress(address); - if (!addressZone) { - return false; - } - const isCorrectShard = addressZone === zone; - const isCorrectLedger = this.coinType() === 969 ? isQiAddress(address) : !isQiAddress(address); - return isCorrectShard && isCorrectLedger; - }; - for (let attempts = 0; attempts < MAX_ADDRESS_DERIVATION_ATTEMPTS; attempts++) { - addressNode = changeNode.deriveChild(addrIndex++); - if (isValidAddressForZone(addressNode.address)) { - return addressNode; - } - } - throw new Error(`Failed to derive a valid address for the zone ${zone} after ${MAX_ADDRESS_DERIVATION_ATTEMPTS} attempts.`); - } - /** - * Adds an address to the wallet. - * - * @param {number} account - The account number. - * @param {number} addressIndex - The address index. - * @param {boolean} [isChange=false] - Whether the address is a change address. Default is `false` - * @returns {NeuteredAddressInfo} The added address info. - */ - addAddress(account, addressIndex, isChange = false) { - return this._addAddress(this._addresses, account, addressIndex, isChange); - } - /** - * Helper method to add an address to the wallet address map. - * - * @param {Map} addressMap - The address map. - * @param {number} account - The account number. - * @param {number} addressIndex - The address index. - * @param {boolean} [isChange=false] - Whether the address is a change address. Default is `false` - * @returns {NeuteredAddressInfo} The added address info. - * @throws {Error} If the address for the index already exists. - */ - _addAddress(addressMap, account, addressIndex, isChange = false) { - // check if address already exists for the index - this._addresses.forEach((addressInfo) => { - if (addressInfo.index === addressIndex) { - throw new Error(`Address for index ${addressIndex} already exists`); - } - }); - // derive the address node and validate the zone - const changeIndex = isChange ? 1 : 0; - const addressNode = this._root.deriveChild(account).deriveChild(changeIndex).deriveChild(addressIndex); - const zone = getZoneForAddress(addressNode.address); - if (!zone) { - throw new Error(`Failed to derive a valid address zone for the index ${addressIndex}`); - } - return this.createAndStoreAddressInfo(addressNode, account, zone, isChange, addressMap); - } - /** - * Promise that resolves to the next address for the specified account and zone. - * - * @param {number} account - The index of the account for which to retrieve the next address. - * @param {Zone} zone - The zone in which to retrieve the next address. - * @returns {Promise} The next neutered address information. - */ - async getNextAddress(account, zone) { - return Promise.resolve(this._getNextAddress(account, zone, false, this._addresses)); - } - /** - * Synchronously retrieves the next address for the specified account and zone. - * - * @param {number} account - The index of the account for which to retrieve the next address. - * @param {Zone} zone - The zone in which to retrieve the next address. - * @returns {NeuteredAddressInfo} The next neutered address information. - */ - getNextAddressSync(account, zone) { - return this._getNextAddress(account, zone, false, this._addresses); - } - /** - * Derives and returns the next address information for the specified account and zone. - * - * @param {number} accountIndex - The index of the account for which the address is being generated. - * @param {Zone} zone - The zone in which the address is to be used. - * @param {boolean} isChange - A flag indicating whether the address is a change address. - * @param {Map} addressMap - A map storing the neutered address information. - * @returns {NeuteredAddressInfo} The derived neutered address information. - * @throws {Error} If the zone is invalid. - */ - _getNextAddress(accountIndex, zone, isChange, addressMap) { - this.validateZone(zone); - const lastIndex = this.getLastAddressIndex(addressMap, zone, accountIndex, isChange); - const addressNode = this.deriveNextAddressNode(accountIndex, lastIndex + 1, zone, isChange); - return this.createAndStoreAddressInfo(addressNode, accountIndex, zone, isChange, addressMap); - } - /** - * Gets the address info for a given address. - * - * @param {string} address - The address. - * @returns {NeuteredAddressInfo | null} The address info or null if not found. - */ - getAddressInfo(address) { - const addressInfo = this._addresses.get(address); - if (!addressInfo) { - return null; - } - return addressInfo; - } - /** - * Returns the private key for a given address. This method should be used with caution as it exposes the private - * key to the user. - * - * @param {string} address - The address associated with the desired private key. - * @returns {string} The private key. - */ - getPrivateKey(address) { - const hdNode = this._getHDNodeForAddress(address); - return hdNode.privateKey; - } - /** - * Gets the addresses for a given account. - * - * @param {number} account - The account number. - * @returns {NeuteredAddressInfo[]} The addresses for the account. - */ - getAddressesForAccount(account) { - const addresses = this._addresses.values(); - return Array.from(addresses).filter((addressInfo) => addressInfo.account === account); - } - /** - * Gets the addresses for a given zone. - * - * @param {Zone} zone - The zone. - * @returns {NeuteredAddressInfo[]} The addresses for the zone. - */ - getAddressesForZone(zone) { - this.validateZone(zone); - const addresses = this._addresses.values(); - return Array.from(addresses).filter((addressInfo) => addressInfo.zone === zone); - } - /** - * Creates an instance of the HD wallet. - * - * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet. - * @param {Mnemonic} mnemonic - The mnemonic. - * @returns {T} The created instance. - */ - static createInstance(mnemonic) { - const coinType = this._coinType; - const root = HDNodeWallet.fromMnemonic(mnemonic, this.parentPath(coinType)); - return new this(_guard, root); - } - /** - * Creates an HD wallet from a mnemonic. - * - * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet. - * @param {Mnemonic} mnemonic - The mnemonic. - * @returns {T} The created instance. - */ - static fromMnemonic(mnemonic) { - return this.createInstance(mnemonic); - } - /** - * Creates a random HD wallet. - * - * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet. - * @param {string} [password] - The password. - * @param {Wordlist} [wordlist] - The wordlist. - * @returns {T} The created instance. - */ - static createRandom(password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist); - return this.createInstance(mnemonic); - } - /** - * Creates an HD wallet from a phrase. - * - * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet. - * @param {string} phrase - The phrase. - * @param {string} [password] - The password. - * @param {Wordlist} [wordlist] - The wordlist. - * @returns {T} The created instance. - */ - static fromPhrase(phrase, password, wordlist) { - if (password == null) { - password = ''; - } - if (wordlist == null) { - wordlist = LangEn.wordlist(); - } - const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist); - return this.createInstance(mnemonic); - } - /** - * Connects the wallet to a provider. - * - * @param {Provider} provider - The provider. - */ - connect(provider) { - this.provider = provider; - } - /** - * Validates the zone. - * - * @param {Zone} zone - The zone. - * @throws {Error} If the zone is invalid. - */ - validateZone(zone) { - if (!Object.values(exports.Zone).includes(zone)) { - throw new Error(`Invalid zone: ${zone}`); - } - } - /** - * Derives and returns the Hierarchical Deterministic (HD) node wallet associated with a given address. - * - * This method fetches the account and address information from the wallet's internal storage, derives the - * appropriate change node based on whether the address is a change address, and further derives the final HD node - * using the address index. - * - * @param {string} addr - The address for which to derive the HD node. - * @returns {HDNodeWallet} The derived HD node wallet corresponding to the given address. - * @throws {Error} If the given address is not known to the wallet. - * @throws {Error} If the account associated with the address is not found. - */ - _getHDNodeForAddress(addr) { - const addressInfo = this._addresses.get(addr); - if (!addressInfo) { - throw new Error(`Address ${addr} is not known to this wallet`); - } - const changeIndex = addressInfo.change ? 1 : 0; - return this._root.deriveChild(addressInfo.account).deriveChild(changeIndex).deriveChild(addressInfo.index); - } - /** - * Serializes the HD wallet state into a format suitable for storage or transmission. - * - * @returns {SerializedHDWallet} An object representing the serialized state of the HD wallet, including version, - * mnemonic phrase, coin type, and addresses. - */ - serialize() { - const addresses = Array.from(this._addresses.values()); - return { - version: this.constructor._version, - phrase: this._root.mnemonic.phrase, - coinType: this.coinType(), - addresses: addresses, - }; - } - /** - * Deserializes a serialized HD wallet object and reconstructs the wallet instance. This method must be implemented - * in the subclass. - * - * @param {SerializedHDWallet} _serialized - The serialized object representing the state of an HD wallet. - * @returns {AbstractHDWallet} An instance of AbstractHDWallet. - * @throws {Error} This method must be implemented in the subclass. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - static async deserialize(_serialized) { - throw new Error('deserialize method must be implemented in the subclass'); - } - /** - * Validates the version and coinType of the serialized wallet. - * - * @param {SerializedHDWallet} serialized - The serialized wallet data to be validated. - * @throws {Error} If the version or coinType of the serialized wallet does not match the expected values. - * @protected - * @static - */ - static validateSerializedWallet(serialized) { - if (serialized.version !== this._version) { - throw new Error(`Invalid version ${serialized.version} for wallet (expected ${this._version})`); - } - if (serialized.coinType !== this._coinType) { - throw new Error(`Invalid coinType ${serialized.coinType} for wallet (expected ${this._coinType})`); - } - } - /** - * Imports addresses from a serialized wallet into the addresses map. Before adding the addresses, a validation is - * performed to ensure the address, public key, and zone match the expected values. - * - * @param {Map} addressMap - The map where the addresses will be imported. - * @param {NeuteredAddressInfo[]} addresses - The array of addresses to be imported, each containing account, index, - * change, address, pubKey, and zone information. - * @throws {Error} If there is a mismatch between the expected and actual address, public key, or zone. - * @protected - */ - importSerializedAddresses(addressMap, addresses) { - for (const addressInfo of addresses) { - const newAddressInfo = this._addAddress(addressMap, addressInfo.account, addressInfo.index, addressInfo.change); - // validate the address info - if (addressInfo.address !== newAddressInfo.address) { - throw new Error(`Address mismatch: ${addressInfo.address} != ${newAddressInfo.address}`); - } - if (addressInfo.pubKey !== newAddressInfo.pubKey) { - throw new Error(`Public key mismatch: ${addressInfo.pubKey} != ${newAddressInfo.pubKey}`); - } - if (addressInfo.zone !== newAddressInfo.zone) { - throw new Error(`Zone mismatch: ${addressInfo.zone} != ${newAddressInfo.zone}`); - } - } - } - /** - * Retrieves the highest address index from the given address map for a specified zone, account, and change type. - * - * This method filters the address map based on the provided zone, account, and change type, then determines the - * maximum address index from the filtered addresses. - * - * @param {Map} addressMap - The map containing address information, where the key is - * an address string and the value is a NeuteredAddressInfo object. - * @param {Zone} zone - The specific zone to filter the addresses by. - * @param {number} account - The account number to filter the addresses by. - * @param {boolean} isChange - A boolean indicating whether to filter for change addresses (true) or receiving - * addresses (false). - * @returns {number} - The highest address index for the specified criteria, or -1 if no addresses match. - * @protected - */ - getLastAddressIndex(addressMap, zone, account, isChange) { - const addresses = Array.from(addressMap.values()).filter((addressInfo) => addressInfo.account === account && addressInfo.zone === zone && addressInfo.change === isChange); - return addresses.reduce((maxIndex, addressInfo) => Math.max(maxIndex, addressInfo.index), -1); - } - /** - * Creates and stores address information in the address map for a specified account, zone, and change type. - * - * This method constructs a NeuteredAddressInfo object using the provided HDNodeWallet and other parameters, then - * stores this information in the provided address map. - * - * @param {HDNodeWallet} addressNode - The HDNodeWallet object containing the address and public key information. - * @param {number} account - The account number to associate with the address. - * @param {Zone} zone - The specific zone to associate with the address. - * @param {boolean} isChange - A boolean indicating whether the address is a change address (true) or a receiving - * address (false). - * @param {Map} addressMap - The map to store the created NeuteredAddressInfo, with the - * address as the key. - * @returns {NeuteredAddressInfo} - The created NeuteredAddressInfo object. - * @protected - */ - createAndStoreAddressInfo(addressNode, account, zone, isChange, addressMap) { - const neuteredAddressInfo = { - pubKey: addressNode.publicKey, - address: addressNode.address, - account, - index: addressNode.index, - change: isChange, - zone, - }; - addressMap.set(neuteredAddressInfo.address, neuteredAddressInfo); - return neuteredAddressInfo; - } - } - - /** - * The Quai HD wallet is a BIP44-compliant hierarchical deterministic wallet used for managing a set of addresses in the - * Quai ledger. This is the easiest way to manage the interaction of managing accounts and addresses on the Quai - * network, however, if your use case requires a single address Quai address, you can use the {@link Wallet} class. - * - * The Quai HD wallet supports: - * - * - Adding accounts to the wallet heierchy - * - Generating addresses for a specific account in any {@link Zone} - * - Signing and sending transactions for any address in the wallet - * - Signing and verifying EIP1193 typed data for any address in the wallet. - * - Serializing the wallet to JSON and deserializing it back to a wallet instance. - * - * @category Wallet - * @example - * - * ```ts - * import { QuaiHDWallet, Zone } from 'quais'; - * - * const wallet = new QuaiHDWallet(); - * const cyrpus1Address = await wallet.getNextAddress(0, Zone.Cyrpus1); // get the first address in the Cyrpus1 zone - * await wallet.sendTransaction({ from: address, to: '0x...', value: 100 }); // send a transaction - * const serializedWallet = wallet.serialize(); // serialize current (account/address) state of the wallet - * . - * . - * . - * const deserializedWallet = QuaiHDWallet.deserialize(serializedWallet); // create a new wallet instance from the serialized data - * ``` - */ - class QuaiHDWallet extends AbstractHDWallet { - /** - * The version of the wallet. - * - * @type {number} - * @static - */ - static _version = 1; - /** - * The coin type for the wallet. - * - * @type {AllowedCoinType} - * @static - */ - static _coinType = 994; - /** - * Create a QuaiHDWallet instance. - * - * @param {HDNodeWallet} root - The root HD node wallet. - * @param {Provider} [provider] - The provider. - */ - constructor(guard, root, provider) { - super(guard, root, provider); - } - /** - * Sign a transaction. - * - * @param {QuaiTransactionRequest} tx - The transaction request. - * @returns {Promise} A promise that resolves to the signed transaction. - */ - async signTransaction(tx) { - const from = await resolveAddress(tx.from); - const fromNode = this._getHDNodeForAddress(from); - const signedTx = await fromNode.signTransaction(tx); - return signedTx; - } - /** - * Send a transaction. - * - * @param {QuaiTransactionRequest} tx - The transaction request. - * @returns {Promise} A promise that resolves to the transaction response. - * @throws {Error} If the provider is not set. - */ - async sendTransaction(tx) { - if (!this.provider) { - throw new Error('Provider is not set'); - } - const from = await resolveAddress(tx.from); - const fromNode = this._getHDNodeForAddress(from); - const fromNodeConnected = fromNode.connect(this.provider); - return await fromNodeConnected.sendTransaction(tx); - } - /** - * Sign a message. - * - * @param {string} address - The address. - * @param {string | Uint8Array} message - The message to sign. - * @returns {Promise} A promise that resolves to the signed message. - */ - async signMessage(address, message) { - const addrNode = this._getHDNodeForAddress(address); - return await addrNode.signMessage(message); - } - /** - * Deserializes the given serialized HD wallet data into an instance of QuaiHDWallet. - * - * @async - * @param {SerializedHDWallet} serialized - The serialized wallet data to be deserialized. - * @returns {Promise} A promise that resolves to an instance of QuaiHDWallet. - * @throws {Error} If validation of the serialized wallet data fails or if deserialization fails. - * @public - * @static - */ - static async deserialize(serialized) { - super.validateSerializedWallet(serialized); - // create the wallet instance - const mnemonic = Mnemonic.fromPhrase(serialized.phrase); - const path = this.parentPath(serialized.coinType); - const root = HDNodeWallet.fromMnemonic(mnemonic, path); - const wallet = new this(_guard, root); - // import the addresses - wallet.importSerializedAddresses(wallet._addresses, serialized.addresses); - return wallet; - } - /** - * Signs typed data using the private key associated with the given address. - * - * @param {string} address - The address for which the typed data is to be signed. - * @param {TypedDataDomain} domain - The domain information of the typed data, defining the scope of the signature. - * @param {Record} types - The types of the data to be signed, mapping each data type name - * to its fields. - * @param {Record} value - The actual data to be signed. - * @returns {Promise} A promise that resolves to the signed data in string format. - * @throws {Error} If the address does not correspond to a valid HD node or if signing fails. - */ - async signTypedData(address, domain, types, value) { - const addrNode = this._getHDNodeForAddress(address); - return addrNode.signTypedData(domain, types, value); - } - } - - /** - * A **Wallet** manages a single private key which is used to sign transactions, messages and other common payloads. - * - * This class is generally the main entry point for developers that wish to use a private key directly, as it can create - * instances from a large variety of common sources, including raw private key, - * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) mnemonics and encrypted JSON wallets. - * - * @category Wallet - */ - class Wallet extends BaseWallet { - /** - * Create a new wallet for the private `key`, optionally connected to `provider`. - * - * @param {string | SigningKey} key - The private key. - * @param {null | Provider} [provider] - The provider to connect to. - */ - constructor(key, provider) { - if (typeof key === 'string' && !key.startsWith('0x')) { - key = '0x' + key; - } - const signingKey = typeof key === 'string' ? new SigningKey(key) : key; - super(signingKey, provider); - } - /** - * Connects the wallet to a provider. - * - * @param {null | Provider} provider - The provider to connect to. - * - * @returns {Wallet} The connected wallet. - */ - connect(provider) { - return new Wallet(this.signingKey, provider); - } - /** - * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with `password`. - * - * If `progressCallback` is specified, it will receive periodic updates as the encryption process progresses. - * - * @param {Uint8Array | string} password - The password to encrypt the wallet with. - * @param {ProgressCallback} [progressCallback] - An optional callback to keep the user informed. - * - * @returns {Promise} The encrypted JSON wallet. - */ - async encrypt(password, progressCallback) { - const account = { address: this.address, privateKey: this.privateKey }; - return await encryptKeystoreJson(account, password, { progressCallback }); - } - /** - * Returns a [JSON Keystore Wallet](json-wallets) encrypted with `password`. - * - * It is preferred to use the [async version](encrypt) instead, which allows a - * {@link ProgressCallback | **ProgressCallback**} to keep the user informed. - * - * This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial - * duration. - * - * @param {Uint8Array | string} password - The password to encrypt the wallet with. - * - * @returns {string} The encrypted JSON wallet. - */ - encryptSync(password) { - const account = { address: this.address, privateKey: this.privateKey }; - return encryptKeystoreJsonSync(account, password); - } - /** - * Creates a wallet from a keystore account. - * - * @ignore - * @param {KeystoreAccount} account - The keystore account. - * - * @returns {Wallet} The wallet instance. - */ - static #fromAccount(account) { - assertArgument(account, 'invalid JSON wallet', 'json', '[ REDACTED ]'); - const wallet = new Wallet(account.privateKey); - assertArgument(wallet.address === account.address, 'address/privateKey mismatch', 'json', '[ REDACTED ]'); - return wallet; - } - /** - * Creates (asynchronously) a **Wallet** by decrypting the `json` with `password`. - * - * If `progress` is provided, it is called periodically during decryption so that any UI can be updated. - * - * @param {string} json - The JSON data to decrypt. - * @param {Uint8Array | string} password - The password to decrypt the JSON data. - * @param {ProgressCallback} [progress] - An optional callback to keep the user informed. - * - * @returns {Promise} The decrypted wallet. - */ - static async fromEncryptedJson(json, password, progress) { - let account; - if (isKeystoreJson(json)) { - account = await decryptKeystoreJson(json, password, progress); - return Wallet.#fromAccount(account); - } - throw new Error('invalid JSON wallet'); - } - /** - * Creates a **Wallet** by decrypting the `json` with `password`. - * - * The {@link Wallet.fromEncryptedJson | **fromEncryptedJson**} method is preferred, as this method will lock up and - * freeze the UI during decryption, which may take some time. - * - * @param {string} json - The JSON data to decrypt. - * @param {Uint8Array | string} password - The password to decrypt the JSON data. - * - * @returns {QuaiHDWallet | Wallet} The decrypted wallet. - */ - static fromEncryptedJsonSync(json, password) { - let account = null; - if (isKeystoreJson(json)) { - account = decryptKeystoreJsonSync(json, password); - } - else { - assertArgument(false, 'invalid JSON wallet', 'json', '[ REDACTED ]'); - } - return Wallet.#fromAccount(account); - } - } - - /*! musig-js - MIT License (c) 2022 Brandon Black */ - const TAGS = { - challenge: 'BIP0340/challenge', - keyagg_list: 'KeyAgg list', - keyagg_coef: 'KeyAgg coefficient', - musig_aux: 'MuSig/aux', - musig_nonce: 'MuSig/nonce', - musig_deterministic_nonce: 'MuSig/deterministic/nonce', - musig_noncecoef: 'MuSig/noncecoef', - }; - function compare32b(a, b) { - if (a.length !== 32 || b.length !== 32) throw new Error('Invalid array'); - const aD = new DataView(a.buffer, a.byteOffset, a.length); - const bD = new DataView(b.buffer, b.byteOffset, b.length); - for (let i = 0; i < 8; i++) { - const cmp = aD.getUint32(i * 4) - bD.getUint32(i * 4); - if (cmp !== 0) return cmp; - } - return 0; - } - function compare33b(a, b) { - if (a.length !== 33 || b.length !== 33) throw new Error('Invalid array'); - const cmp = a[0] - b[0]; - if (cmp !== 0) return cmp; - return compare32b(a.subarray(1), b.subarray(1)); - } - const makeSessionId = - typeof self === 'object' && (self.crypto || self.msCrypto) - ? () => (self.crypto || self.msCrypto).getRandomValues(new Uint8Array(32)) - : () => require('crypto').randomBytes(32); - const _keyAggCache = new WeakMap(); - const _coefCache = new WeakMap(); - const _nonceCache = new WeakMap(); - const _sessionCache = new WeakMap(); - function MuSigFactory(ecc) { - const CPOINT_INF = new Uint8Array(33); - const SCALAR_0 = new Uint8Array(32); - const SCALAR_1 = new Uint8Array(32); - SCALAR_1[31] = 1; - ecc.scalarNegate(SCALAR_1); - function keyAggCoeff(publicKeys, publicKey) { - let coefCache = _coefCache.get(publicKeys); - if (coefCache === undefined) { - coefCache = new Map(); - _coefCache.set(publicKeys, coefCache); - } - let coefficient = coefCache.get(publicKey); - if (coefficient) return coefficient; - coefficient = SCALAR_1; - let secondPublicKey; - let publicKeyHash; - let keyAggCache = _keyAggCache.get(publicKeys); - if (keyAggCache === undefined) { - const pkIdx2 = publicKeys.findIndex((pk) => compare33b(pk, publicKeys[0]) !== 0); - secondPublicKey = publicKeys[pkIdx2]; - publicKeyHash = ecc.taggedHash(TAGS.keyagg_list, ...publicKeys); - keyAggCache = { publicKeyHash, secondPublicKey }; - _keyAggCache.set(publicKeys, keyAggCache); - } else { - ({ publicKeyHash, secondPublicKey } = keyAggCache); - } - if (secondPublicKey === undefined || compare33b(publicKey, secondPublicKey) !== 0) - coefficient = ecc.taggedHash(TAGS.keyagg_coef, publicKeyHash, publicKey); - coefCache.set(publicKey, coefficient); - return coefficient; - } - function addTweak(ctx, t) { - const tweak = 'tweak' in t ? t : { tweak: t }; - if (!ecc.isScalar(tweak.tweak)) - throw new TypeError('Expected tweak to be a valid scalar with curve order'); - let { gacc, tacc } = ctx; - let aggPublicKey = ctx.aggPublicKey; - if (!ecc.hasEvenY(aggPublicKey) && tweak.xOnly) { - gacc = ecc.scalarNegate(gacc); - tacc = ecc.scalarNegate(tacc); - aggPublicKey = ecc.pointNegate(aggPublicKey); - } - aggPublicKey = ecc.pointAddTweak(aggPublicKey, tweak.tweak, false); - if (aggPublicKey === null) throw new Error('Unexpected point at infinity during tweaking'); - tacc = ecc.scalarAdd(tweak.tweak, tacc); - return { aggPublicKey, gacc, tacc }; - } - function keyAgg(publicKeys, ...tweaks) { - checkArgs({ publicKeys }); - const multipliedPublicKeys = publicKeys.map((publicKey) => { - const coefficient = keyAggCoeff(publicKeys, publicKey); - let multipliedPublicKey; - if (compare32b(coefficient, SCALAR_1) === 0) { - multipliedPublicKey = publicKey; - } else { - multipliedPublicKey = ecc.pointMultiplyUnsafe(publicKey, coefficient, false); - } - if (multipliedPublicKey === null) throw new Error('Point at infinity during aggregation'); - return multipliedPublicKey; - }); - const aggPublicKey = multipliedPublicKeys.reduce((a, b) => { - const next = ecc.pointAdd(a, b, false); - if (next === null) throw new Error('Point at infinity during aggregation'); - return next; - }); - return tweaks.reduce((ctx, tweak) => addTweak(ctx, tweak), { - aggPublicKey, - gacc: SCALAR_1, - tacc: SCALAR_0, - }); - } - function getSessionValues(sessionKey) { - const sessionValues = _sessionCache.get(sessionKey); - if (!sessionValues) throw new Error('Invalid session key, please call `startSigningSession`'); - return sessionValues; - } - function nonceAgg(publicNonces) { - checkArgs({ publicNonces }); - const aggNonces = [publicNonces[0].subarray(0, 33), publicNonces[0].subarray(33)]; - for (let i = 1; i < publicNonces.length; i++) { - if (aggNonces[0] !== null) - aggNonces[0] = ecc.pointAdd(aggNonces[0], publicNonces[i].subarray(0, 33), false); - if (aggNonces[1] !== null) - aggNonces[1] = ecc.pointAdd(aggNonces[1], publicNonces[i].subarray(33), false); - } - const aggNonce = new Uint8Array(66); - if (aggNonces[0] !== null) aggNonce.set(ecc.pointCompress(aggNonces[0]), 0); - if (aggNonces[1] !== null) aggNonce.set(ecc.pointCompress(aggNonces[1]), 33); - return aggNonce; - } - function startSigningSessionInner(aggNonce, msg, publicKeys, ctx) { - const pubKeyX = ecc.pointX(ctx.aggPublicKey); - const coefficient = ecc.taggedHash(TAGS.musig_noncecoef, aggNonce, pubKeyX, msg); - const aggNonces = [aggNonce.subarray(0, 33), aggNonce.subarray(33)]; - let r = null; - if (compare33b(aggNonces[1], CPOINT_INF) !== 0 && compare33b(aggNonces[0], CPOINT_INF) !== 0) { - r = ecc.pointMultiplyAndAddUnsafe(aggNonces[1], coefficient, aggNonces[0], false); - } else if (compare33b(aggNonces[0], CPOINT_INF) !== 0) { - r = ecc.pointCompress(aggNonces[0], false); - } else if (compare33b(aggNonces[1], CPOINT_INF) !== 0) { - r = ecc.pointMultiplyUnsafe(aggNonces[1], coefficient, false); - } - if (r === null) r = ecc.getPublicKey(SCALAR_1, false); - if (r === null) throw new Error('Failed to get G'); - const challenge = ecc.scalarMod(ecc.taggedHash(TAGS.challenge, ecc.pointX(r), pubKeyX, msg)); - const key = { publicKey: ctx.aggPublicKey, aggNonce, msg }; - _sessionCache.set(key, { ...ctx, coefficient, challenge, finalNonce: r, publicKeys }); - return key; - } - function partialVerifyInner({ sig, publicKey, publicNonces, sessionKey }) { - const { aggPublicKey, gacc, challenge, coefficient, finalNonce, publicKeys } = - getSessionValues(sessionKey); - const rePrime = ecc.pointMultiplyAndAddUnsafe( - publicNonces[1], - coefficient, - publicNonces[0], - false - ); - if (rePrime === null) throw new Error('Unexpected public nonce at infinity'); - const re = ecc.hasEvenY(finalNonce) ? rePrime : ecc.pointNegate(rePrime); - const a = keyAggCoeff(publicKeys, publicKey); - const g = ecc.hasEvenY(aggPublicKey) ? gacc : ecc.scalarNegate(gacc); - const ea = ecc.scalarMultiply(challenge, a); - const eag = ecc.scalarMultiply(ea, g); - const ver = ecc.pointMultiplyAndAddUnsafe(publicKey, eag, re, true); - if (ver === null) throw new Error('Unexpected verification point at infinity'); - const sG = ecc.getPublicKey(sig, true); - if (sG === null) throw new Error('Unexpected signature point at infinity'); - return compare33b(ver, sG) === 0; - } - function partialSignInner({ secretKey, publicKey, secretNonces, sessionKey }) { - const { aggPublicKey, gacc, challenge, coefficient, finalNonce, publicKeys } = - getSessionValues(sessionKey); - const [k1, k2] = secretNonces.map((k) => (ecc.hasEvenY(finalNonce) ? k : ecc.scalarNegate(k))); - const a = keyAggCoeff(publicKeys, publicKey); - const g = ecc.hasEvenY(aggPublicKey) ? gacc : ecc.scalarNegate(gacc); - const d = ecc.scalarMultiply(g, secretKey); - const bk2 = ecc.scalarMultiply(coefficient, k2); - const k1bk2 = ecc.scalarAdd(k1, bk2); - const ea = ecc.scalarMultiply(challenge, a); - const ead = ecc.scalarMultiply(ea, d); - const sig = ecc.scalarAdd(k1bk2, ead); - return sig; - } - function partialSign({ secretKey, publicNonce, sessionKey, verify = true }) { - checkArgs({ publicNonce, secretKey }); - const secretNonce = _nonceCache.get(publicNonce); - if (secretNonce === undefined) - throw new Error('No secret nonce found for specified public nonce'); - _nonceCache.delete(publicNonce); - const publicKey = ecc.getPublicKey(secretKey, true); - if (publicKey === null) throw new Error('Invalid secret key, no corresponding public key'); - if (compare33b(publicKey, secretNonce.subarray(64)) !== 0) - throw new Error('Secret nonce pubkey mismatch'); - const secretNonces = [secretNonce.subarray(0, 32), secretNonce.subarray(32, 64)]; - const sig = partialSignInner({ - secretKey, - publicKey, - secretNonces, - sessionKey, - }); - if (verify) { - const publicNonces = [publicNonce.subarray(0, 33), publicNonce.subarray(33)]; - const valid = partialVerifyInner({ - sig, - publicKey, - publicNonces, - sessionKey, - }); - if (!valid) throw new Error('Partial signature failed verification'); - } - return sig; - } - function deterministicSign({ - secretKey, - aggOtherNonce, - publicKeys, - tweaks = [], - msg, - rand, - verify = true, - nonceOnly = false, - }) { - checkArgs({ rand, secretKey, aggOtherNonce }); - const publicKey = ecc.getPublicKey(secretKey, true); - if (publicKey === null) throw new Error('Secret key has no corresponding public key'); - let secretKeyPrime; - if (rand !== undefined) { - secretKeyPrime = ecc.taggedHash(TAGS.musig_aux, rand); - for (let i = 0; i < 32; i++) { - secretKeyPrime[i] = secretKeyPrime[i] ^ secretKey[i]; - } - } else { - secretKeyPrime = secretKey; - } - const ctx = keyAgg(publicKeys, ...tweaks); - const aggPublicKey = ecc.pointX(ctx.aggPublicKey); - const mLength = new Uint8Array(8); - new DataView(mLength.buffer).setBigUint64(0, BigInt(msg.length)); - const secretNonce = new Uint8Array(97); - const publicNonce = new Uint8Array(66); - for (let i = 0; i < 2; i++) { - const kH = ecc.taggedHash( - TAGS.musig_deterministic_nonce, - ...[secretKeyPrime, aggOtherNonce, aggPublicKey, mLength, msg, Uint8Array.of(i)] - ); - const k = ecc.scalarMod(kH); - if (compare32b(SCALAR_0, k) === 0) throw new Error('0 secret nonce'); - const pub = ecc.getPublicKey(k, true); - if (pub === null) throw new Error('Secret nonce has no corresponding public nonce'); - secretNonce.set(k, i * 32); - publicNonce.set(pub, i * 33); - } - secretNonce.set(publicKey, 64); - if (nonceOnly) return { publicNonce }; - _nonceCache.set(publicNonce, secretNonce); - const aggNonce = nonceAgg([aggOtherNonce, publicNonce]); - const sessionKey = startSigningSessionInner(aggNonce, msg, publicKeys, ctx); - const sig = partialSign({ - secretKey, - publicNonce, - sessionKey, - verify, - }); - return { sig, sessionKey, publicNonce }; - } - const pubKeyArgs = ['publicKey', 'publicKeys']; - const scalarArgs = ['tweak', 'sig', 'sigs', 'tacc', 'gacc']; - const otherArgs32b = ['xOnlyPublicKey', 'rand', 'sessionId']; - const args32b = ['secretKey', ...scalarArgs, ...otherArgs32b]; - const pubNonceArgs = ['publicNonce', 'publicNonces', 'aggNonce', 'aggOtherNonce', 'finalNonce']; - const argLengths = new Map(); - args32b.forEach((a) => argLengths.set(a, 32)); - pubKeyArgs.forEach((a) => argLengths.set(a, 33)); - pubNonceArgs.forEach((a) => argLengths.set(a, 66)); - argLengths.set('secretNonce', 97); - argLengths.set('aggPublicKey', 65); - const scalarNames = new Set(); - scalarArgs.forEach((n) => scalarNames.add(n)); - function checkArgs(args) { - for (let [name, values] of Object.entries(args)) { - if (values === undefined) continue; - values = Array.isArray(values) ? values : [values]; - if (values.length === 0) throw new TypeError(`0-length ${name}s not supported`); - for (const value of values) { - if (argLengths.get(name) !== value.length) - throw new TypeError(`Invalid ${name} length (${value.length})`); - if (name === 'secretKey') { - if (!ecc.isSecret(value)) throw new TypeError(`Invalid secretKey`); - } else if (name === 'secretNonce') { - for (let i = 0; i < 64; i += 32) - if (!ecc.isSecret(value.subarray(i, i + 32))) - throw new TypeError(`Invalid secretNonce`); - } else if (scalarNames.has(name)) { - for (let i = 0; i < value.length; i += 32) - if (!ecc.isScalar(value.subarray(i, i + 32))) throw new TypeError(`Invalid ${name}`); - } - } - } - } - return { - getXOnlyPubkey: (ctx) => { - if ('aggPublicKey' in ctx) return ecc.pointX(ctx.aggPublicKey); - return ecc.pointX(getSessionValues(ctx).aggPublicKey); - }, - getPlainPubkey: (ctx) => { - if ('aggPublicKey' in ctx) return ecc.pointCompress(ctx.aggPublicKey); - return ecc.pointCompress(getSessionValues(ctx).aggPublicKey); - }, - keySort: (publicKeys) => { - checkArgs({ publicKeys }); - return [...publicKeys].sort((a, b) => compare33b(a, b)); - }, - keyAgg, - addTweaks: (ctx, ...tweaks) => { - checkArgs(ctx); - return tweaks.reduce((c, tweak) => addTweak(c, tweak), ctx); - }, - nonceGen: ({ - sessionId = makeSessionId(), - secretKey, - publicKey, - xOnlyPublicKey, - msg, - extraInput, - }) => { - if (extraInput !== undefined && extraInput.length > Math.pow(2, 32) - 1) - throw new TypeError('extraInput is limited to 2^32-1 bytes'); - checkArgs({ sessionId, secretKey, publicKey, xOnlyPublicKey }); - let rand; - if (secretKey !== undefined) { - rand = ecc.taggedHash(TAGS.musig_aux, sessionId); - for (let i = 0; i < 32; i++) { - rand[i] = rand[i] ^ secretKey[i]; - } - } else { - rand = sessionId; - } - if (xOnlyPublicKey === undefined) xOnlyPublicKey = new Uint8Array(); - const mPrefixed = [Uint8Array.of(0)]; - if (msg !== undefined) { - mPrefixed[0][0] = 1; - mPrefixed.push(new Uint8Array(8)); - new DataView(mPrefixed[1].buffer).setBigUint64(0, BigInt(msg.length)); - mPrefixed.push(msg); - } - if (extraInput === undefined) extraInput = new Uint8Array(); - const eLength = new Uint8Array(4); - new DataView(eLength.buffer).setUint32(0, extraInput.length); - const secretNonce = new Uint8Array(97); - const publicNonce = new Uint8Array(66); - for (let i = 0; i < 2; i++) { - const kH = ecc.taggedHash( - TAGS.musig_nonce, - rand, - Uint8Array.of(publicKey.length), - publicKey, - Uint8Array.of(xOnlyPublicKey.length), - xOnlyPublicKey, - ...mPrefixed, - eLength, - extraInput, - Uint8Array.of(i) - ); - const k = ecc.scalarMod(kH); - if (compare32b(SCALAR_0, k) === 0) throw new Error('0 secret nonce'); - const pub = ecc.getPublicKey(k, true); - if (pub === null) throw new Error('Secret nonce has no corresponding public nonce'); - secretNonce.set(k, i * 32); - publicNonce.set(pub, i * 33); - } - secretNonce.set(publicKey, 64); - _nonceCache.set(publicNonce, secretNonce); - return publicNonce; - }, - addExternalNonce: (publicNonce, secretNonce) => { - checkArgs({ publicNonce, secretNonce }); - _nonceCache.set(publicNonce, secretNonce); - }, - deterministicNonceGen: (args) => deterministicSign({ ...args, nonceOnly: true }), - deterministicSign, - nonceAgg, - startSigningSession: (aggNonce, msg, publicKeys, ...tweaks) => { - checkArgs({ aggNonce }); - const ctx = keyAgg(publicKeys, ...tweaks); - return startSigningSessionInner(aggNonce, msg, publicKeys, ctx); - }, - partialSign, - partialVerify: ({ sig, publicKey, publicNonce, sessionKey }) => { - checkArgs({ sig, publicKey, publicNonce }); - const publicNonces = [publicNonce.subarray(0, 33), publicNonce.subarray(33)]; - const valid = partialVerifyInner({ - sig, - publicKey, - publicNonces, - sessionKey, - }); - return valid; - }, - signAgg: (sigs, sessionKey) => { - checkArgs({ sigs }); - const { aggPublicKey, tacc, challenge, finalNonce } = getSessionValues(sessionKey); - let sPart = ecc.scalarMultiply(challenge, tacc); - if (!ecc.hasEvenY(aggPublicKey)) { - sPart = ecc.scalarNegate(sPart); - } - const aggS = sigs.reduce((a, b) => ecc.scalarAdd(a, b), sPart); - const sig = new Uint8Array(64); - sig.set(ecc.pointX(finalNonce), 0); - sig.set(aggS, 32); - return sig; - }, - }; - } - - /** - * The Qi HD wallet is a BIP44-compliant hierarchical deterministic wallet used for managing a set of addresses in the - * Qi ledger. This is wallet implementation is the primary way to interact with the Qi UTXO ledger on the Quai network. - * - * The Qi HD wallet supports: - * - * - Adding accounts to the wallet heierchy - * - Generating addresses for a specific account in any {@link Zone} - * - Signing and sending transactions for any address in the wallet - * - Serializing the wallet to JSON and deserializing it back to a wallet instance. - * - * @category Wallet - * @example - * - * ```ts - * import { QiHDWallet, Zone } from 'quais'; - * - * const wallet = new QiHDWallet(); - * const cyrpus1Address = await wallet.getNextAddress(0, Zone.Cyrpus1); // get the first address in the Cyrpus1 zone - * await wallet.sendTransaction({ txInputs: [...], txOutputs: [...] }); // send a transaction - * const serializedWallet = wallet.serialize(); // serialize current (account/address) state of the wallet - * . - * . - * . - * const deserializedWallet = QiHDWallet.deserialize(serializedWallet); // create a new wallet instance from the serialized data - * ``` - */ - class QiHDWallet extends AbstractHDWallet { - /** - * @ignore - * @type {number} - */ - static _version = 1; - /** - * @ignore - * @type {number} - */ - static _GAP_LIMIT = 20; - /** - * @ignore - * @type {AllowedCoinType} - */ - static _coinType = 969; - /** - * Map of change addresses to address info. - * - * @ignore - * @type {Map} - */ - _changeAddresses = new Map(); - /** - * Array of gap addresses. - * - * @ignore - * @type {NeuteredAddressInfo[]} - */ - _gapChangeAddresses = []; - /** - * Array of gap change addresses. - * - * @ignore - * @type {NeuteredAddressInfo[]} - */ - _gapAddresses = []; - /** - * Array of outpoint information. - * - * @ignore - * @type {OutpointInfo[]} - */ - _outpoints = []; - /** - * @ignore - * @param {HDNodeWallet} root - The root HDNodeWallet. - * @param {Provider} [provider] - The provider (optional). - */ - constructor(guard, root, provider) { - super(guard, root, provider); - } - /** - * Promise that resolves to the next change address for the specified account and zone. - * - * @param {number} account - The index of the account for which to retrieve the next change address. - * @param {Zone} zone - The zone in which to retrieve the next change address. - * @returns {Promise} The next change neutered address information. - */ - async getNextChangeAddress(account, zone) { - return Promise.resolve(this._getNextAddress(account, zone, true, this._changeAddresses)); - } - /** - * Synchronously retrieves the next change address for the specified account and zone. - * - * @param {number} account - The index of the account for which to retrieve the next change address. - * @param {Zone} zone - The zone in which to retrieve the next change address. - * @returns {NeuteredAddressInfo} The next change neutered address information. - */ - getNextChangeAddressSync(account, zone) { - return this._getNextAddress(account, zone, true, this._changeAddresses); - } - /** - * Imports an array of outpoints. - * - * @param {OutpointInfo[]} outpoints - The outpoints to import. - */ - importOutpoints(outpoints) { - this.validateOutpointInfo(outpoints); - this._outpoints.push(...outpoints); - } - /** - * Gets the outpoints for the specified zone. - * - * @param {Zone} zone - The zone. - * @returns {OutpointInfo[]} The outpoints for the zone. - */ - getOutpoints(zone) { - this.validateZone(zone); - return this._outpoints.filter((outpoint) => outpoint.zone === zone); - } - /** - * Signs a Qi transaction and returns the serialized transaction. - * - * @param {QiTransactionRequest} tx - The transaction to sign. - * @returns {Promise} The serialized transaction. - * @throws {Error} If the UTXO transaction is invalid. - */ - async signTransaction(tx) { - const txobj = QiTransaction.from(tx); - if (!txobj.txInputs || txobj.txInputs.length == 0 || !txobj.txOutputs) - throw new Error('Invalid UTXO transaction, missing inputs or outputs'); - const hash = keccak_256(txobj.unsignedSerialized); - let signature; - if (txobj.txInputs.length == 1) { - signature = this.createSchnorrSignature(txobj.txInputs[0], hash); - } - else { - signature = this.createMuSigSignature(txobj, hash); - } - txobj.signature = signature; - return txobj.serialized; - } - /** - * Sends a Qi transaction. - * - * @param {QiTransactionRequest} tx - The transaction to send. - * @returns {Promise} The transaction response. - * @throws {Error} If the provider is not set or if the transaction has no inputs. - */ - async sendTransaction(tx) { - if (!this.provider) { - throw new Error('Provider is not set'); - } - if (!tx.txInputs || tx.txInputs.length === 0) { - throw new Error('Transaction has no inputs'); - } - const input = tx.txInputs[0]; - const address = computeAddress(input.pubkey); - const shard = getZoneForAddress(address); - if (!shard) { - throw new Error(`Address ${address} not found in any shard`); - } - // verify all inputs are from the same shard - if (tx.txInputs.some((input) => getZoneForAddress(computeAddress(input.pubkey)) !== shard)) { - throw new Error('All inputs must be from the same shard'); - } - const signedTx = await this.signTransaction(tx); - return await this.provider.broadcastTransaction(shard, signedTx); - } - /** - * Returns a schnorr signature for the given message and private key. - * - * @ignore - * @param {TxInput} input - The transaction input. - * @param {Uint8Array} hash - The hash of the message. - * @returns {string} The schnorr signature. - */ - createSchnorrSignature(input, hash) { - const privKey = this.getPrivateKeyForTxInput(input); - const signature = schnorr.sign(hash, getBytes(privKey)); - return hexlify(signature); - } - /** - * Returns a MuSig signature for the given message and private keys corresponding to the input addresses. - * - * @ignore - * @param {QiTransaction} tx - The Qi transaction. - * @param {Uint8Array} hash - The hash of the message. - * @returns {string} The MuSig signature. - */ - createMuSigSignature(tx, hash) { - const musig = MuSigFactory(musigCrypto); - // Collect private keys corresponding to the pubkeys found on the inputs - const privKeysSet = new Set(); - tx.txInputs.forEach((input) => { - const privKey = this.getPrivateKeyForTxInput(input); - privKeysSet.add(privKey); - }); - const privKeys = Array.from(privKeysSet); - // Create an array of public keys corresponding to the private keys for musig aggregation - const pubKeys = privKeys - .map((privKey) => musigCrypto.getPublicKey(getBytes(privKey), true)) - .filter((pubKey) => pubKey !== null); - // Generate nonces for each public key - const nonces = pubKeys.map((pk) => musig.nonceGen({ publicKey: getBytes(pk) })); - const aggNonce = musig.nonceAgg(nonces); - const signingSession = musig.startSigningSession(aggNonce, hash, pubKeys); - // Create partial signatures for each private key - const partialSignatures = privKeys.map((sk, index) => musig.partialSign({ - secretKey: getBytes(sk || ''), - publicNonce: nonces[index], - sessionKey: signingSession, - verify: true, - })); - // Aggregate the partial signatures into a final aggregated signature - const finalSignature = musig.signAgg(partialSignatures, signingSession); - return hexlify(finalSignature); - } - /** - * Retrieves the private key for a given transaction input. - * - * This method derives the private key for a transaction input by following these steps: - * - * 1. Ensures the input contains a public key. - * 2. Computes the address from the public key. - * 3. Fetches address information associated with the computed address. - * 4. Derives the hierarchical deterministic (HD) node corresponding to the address. - * 5. Returns the private key of the derived HD node. - * - * @ignore - * @param {TxInput} input - The transaction input containing the public key. - * @returns {string} The private key corresponding to the transaction input. - * @throws {Error} If the input does not contain a public key or if the address information cannot be found. - */ - getPrivateKeyForTxInput(input) { - if (!input.pubkey) - throw new Error('Missing public key for input'); - const address = computeAddress(input.pubkey); - // get address info - const addressInfo = this.getAddressInfo(address); - if (!addressInfo) - throw new Error(`Address not found: ${address}`); - // derive an HDNode for the address and get the private key - const changeIndex = addressInfo.change ? 1 : 0; - const addressNode = this._root - .deriveChild(addressInfo.account) - .deriveChild(changeIndex) - .deriveChild(addressInfo.index); - return addressNode.privateKey; - } - /** - * Scans the specified zone for addresses with unspent outputs. Starting at index 0, it will generate new addresses - * until the gap limit is reached for both gap and change addresses. - * - * @param {Zone} zone - The zone in which to scan for addresses. - * @param {number} [account=0] - The index of the account to scan. Default is `0` - * @returns {Promise} A promise that resolves when the scan is complete. - * @throws {Error} If the zone is invalid. - */ - async scan(zone, account = 0) { - this.validateZone(zone); - // flush the existing addresses and outpoints - this._addresses = new Map(); - this._changeAddresses = new Map(); - this._gapAddresses = []; - this._gapChangeAddresses = []; - this._outpoints = []; - await this._scan(zone, account); - } - /** - * Scans the specified zone for addresses with unspent outputs. Starting at the last address index, it will generate - * new addresses until the gap limit is reached for both gap and change addresses. If no account is specified, it - * will scan all accounts known to the wallet. - * - * @param {Zone} zone - The zone in which to sync addresses. - * @param {number} [account] - The index of the account to sync. If not specified, all accounts will be scanned. - * @returns {Promise} A promise that resolves when the sync is complete. - * @throws {Error} If the zone is invalid. - */ - async sync(zone, account) { - this.validateZone(zone); - // if no account is specified, scan all accounts. - if (account === undefined) { - const addressInfos = Array.from(this._addresses.values()); - const accounts = addressInfos.reduce((unique, info) => { - if (!unique.includes(info.account)) { - unique.push(info.account); - } - return unique; - }, []); - for (const acc of accounts) { - await this._scan(zone, acc); - } - } - else { - await this._scan(zone, account); - } - return; - } - /** - * Internal method to scan the specified zone for addresses with unspent outputs. This method handles the actual - * scanning logic, generating new addresses until the gap limit is reached for both gap and change addresses. - * - * @param {Zone} zone - The zone in which to scan for addresses. - * @param {number} [account=0] - The index of the account to scan. Default is `0` - * @returns {Promise} A promise that resolves when the scan is complete. - * @throws {Error} If the provider is not set. - */ - async _scan(zone, account = 0) { - if (!this.provider) - throw new Error('Provider not set'); - let gapAddressesCount = 0; - let changeGapAddressesCount = 0; - while (gapAddressesCount < QiHDWallet._GAP_LIMIT || changeGapAddressesCount < QiHDWallet._GAP_LIMIT) { - [gapAddressesCount, changeGapAddressesCount] = await Promise.all([ - gapAddressesCount < QiHDWallet._GAP_LIMIT - ? this.scanAddress(zone, account, false, gapAddressesCount) - : gapAddressesCount, - changeGapAddressesCount < QiHDWallet._GAP_LIMIT - ? this.scanAddress(zone, account, true, changeGapAddressesCount) - : changeGapAddressesCount, - ]); - } - } - /** - * Scans for the next address in the specified zone and account, checking for associated outpoints, and updates the - * address count and gap addresses accordingly. - * - * @param {Zone} zone - The zone in which the address is being scanned. - * @param {number} account - The index of the account for which the address is being scanned. - * @param {boolean} isChange - A flag indicating whether the address is a change address. - * @param {number} addressesCount - The current count of addresses scanned. - * @returns {Promise} A promise that resolves to the updated address count. - * @throws {Error} If an error occurs during the address scanning or outpoints retrieval process. - */ - async scanAddress(zone, account, isChange, addressesCount) { - const addressMap = isChange ? this._changeAddresses : this._addresses; - const addressInfo = this._getNextAddress(account, zone, isChange, addressMap); - const outpoints = await this.getOutpointsByAddress(addressInfo.address); - if (outpoints.length > 0) { - this.importOutpoints(outpoints.map((outpoint) => ({ - outpoint, - address: addressInfo.address, - zone, - account, - }))); - addressesCount = 0; - isChange ? (this._gapChangeAddresses = []) : (this._gapAddresses = []); - } - else { - addressesCount++; - isChange ? this._gapChangeAddresses.push(addressInfo) : this._gapAddresses.push(addressInfo); - } - return addressesCount; - } - /** - * Queries the network node for the outpoints of the specified address. - * - * @ignore - * @param {string} address - The address to query. - * @returns {Promise} The outpoints for the address. - * @throws {Error} If the query fails. - */ - async getOutpointsByAddress(address) { - try { - const outpointsMap = await this.provider.getOutpointsByAddress(address); - if (!outpointsMap) { - return []; - } - return Object.values(outpointsMap); - } - catch (error) { - throw new Error(`Failed to get outpoints for address: ${address} - error: ${error}`); - } - } - /** - * Gets the change addresses for the specified zone. - * - * @param {Zone} zone - The zone. - * @returns {NeuteredAddressInfo[]} The change addresses for the zone. - */ - getChangeAddressesForZone(zone) { - this.validateZone(zone); - const changeAddresses = this._changeAddresses.values(); - return Array.from(changeAddresses).filter((addressInfo) => addressInfo.zone === zone); - } - /** - * Gets the gap addresses for the specified zone. - * - * @param {Zone} zone - The zone. - * @returns {NeuteredAddressInfo[]} The gap addresses for the zone. - */ - getGapAddressesForZone(zone) { - this.validateZone(zone); - const gapAddresses = this._gapAddresses.filter((addressInfo) => addressInfo.zone === zone); - return gapAddresses; - } - /** - * Gets the gap change addresses for the specified zone. - * - * @param {Zone} zone - The zone. - * @returns {NeuteredAddressInfo[]} The gap change addresses for the zone. - */ - getGapChangeAddressesForZone(zone) { - this.validateZone(zone); - const gapChangeAddresses = this._gapChangeAddresses.filter((addressInfo) => addressInfo.zone === zone); - return gapChangeAddresses; - } - /** - * Signs a message using the private key associated with the given address. - * - * @param {string} address - The address for which the message is to be signed. - * @param {string | Uint8Array} message - The message to be signed, either as a string or Uint8Array. - * @returns {Promise} A promise that resolves to the signature of the message in hexadecimal string format. - * @throws {Error} If the address does not correspond to a valid HD node or if signing fails. - */ - async signMessage(address, message) { - const addrNode = this._getHDNodeForAddress(address); - const privKey = addrNode.privateKey; - const digest = keccak_256(message); - const signature = schnorr.sign(digest, getBytes(privKey)); - return hexlify(signature); - } - /** - * Serializes the HD wallet state into a format suitable for storage or transmission. - * - * @returns {SerializedQiHDWallet} An object representing the serialized state of the HD wallet, including - * outpoints, change addresses, gap addresses, and other inherited properties. - */ - serialize() { - const hdwalletSerialized = super.serialize(); - return { - outpoints: this._outpoints, - changeAddresses: Array.from(this._changeAddresses.values()), - gapAddresses: this._gapAddresses, - gapChangeAddresses: this._gapChangeAddresses, - ...hdwalletSerialized, - }; - } - /** - * Deserializes a serialized QiHDWallet object and reconstructs the wallet instance. - * - * @param {SerializedQiHDWallet} serialized - The serialized object representing the state of a QiHDWallet. - * @returns {Promise} A promise that resolves to a reconstructed QiHDWallet instance. - * @throws {Error} If the serialized data is invalid or if any addresses in the gap addresses or gap change - * addresses do not exist in the wallet. - */ - static async deserialize(serialized) { - super.validateSerializedWallet(serialized); - // create the wallet instance - const mnemonic = Mnemonic.fromPhrase(serialized.phrase); - const path = this.parentPath(serialized.coinType); - const root = HDNodeWallet.fromMnemonic(mnemonic, path); - const wallet = new this(_guard, root); - // import the addresses - wallet.importSerializedAddresses(wallet._addresses, serialized.addresses); - // import the change addresses - wallet.importSerializedAddresses(wallet._changeAddresses, serialized.changeAddresses); - // import the gap addresses, verifying they already exist in the wallet - for (const gapAddressInfo of serialized.gapAddresses) { - const gapAddress = gapAddressInfo.address; - if (!wallet._addresses.has(gapAddress)) { - throw new Error(`Address ${gapAddress} not found in wallet`); - } - wallet._gapAddresses.push(gapAddressInfo); - } - // import the gap change addresses, verifying they already exist in the wallet - for (const gapChangeAddressInfo of serialized.gapChangeAddresses) { - const gapChangeAddress = gapChangeAddressInfo.address; - if (!wallet._changeAddresses.has(gapChangeAddress)) { - throw new Error(`Address ${gapChangeAddress} not found in wallet`); - } - wallet._gapChangeAddresses.push(gapChangeAddressInfo); - } - // validate the outpoints and import them - wallet.validateOutpointInfo(serialized.outpoints); - wallet._outpoints.push(...serialized.outpoints); - return wallet; - } - /** - * Validates an array of OutpointInfo objects. This method checks the validity of each OutpointInfo object by - * performing the following validations: - * - * - Validates the zone using the `validateZone` method. - * - Checks if the address exists in the wallet. - * - Checks if the account (if provided) exists in the wallet. - * - Validates the Outpoint by ensuring that `Txhash`, `Index`, and `Denomination` are not null. - * - * @ignore - * @param {OutpointInfo[]} outpointInfo - An array of OutpointInfo objects to be validated. - * @throws {Error} If any of the validations fail, an error is thrown with a descriptive message. - */ - validateOutpointInfo(outpointInfo) { - outpointInfo.forEach((info) => { - // validate zone - this.validateZone(info.zone); - // validate address and account - const addressInfo = this.getAddressInfo(info.address); - if (!addressInfo) { - throw new Error(`Address ${info.address} not found in wallet`); - } - if (info.account !== undefined && info.account !== addressInfo.account) { - throw new Error(`Account ${info.account} not found for address ${info.address}`); - } - // validate Outpoint - if (info.outpoint.txhash == null || info.outpoint.index == null || info.outpoint.denomination == null) { - throw new Error(`Invalid Outpoint: ${JSON.stringify(info)} `); - } - }); - } - } - - /** - * A **Network** encapsulates the various properties required to interact with a specific chain. - * @category Providers - */ - const Networks = new Map(); - /** - * A **Network** provides access to a chain's properties and allows for plug-ins to extend functionality. - * - * @category Providers - */ - class Network { - #name; - #chainId; - /** - * Creates a new **Network** for `name` and `chainId`. - * @param {string} name - The network name. - * @param {BigNumberish} chainId - The network chain ID. - */ - constructor(name, chainId) { - this.#name = name; - this.#chainId = getBigInt(chainId); - } - /** - * Returns a JSON-compatible representation of a Network. - * @returns {Object} The JSON representation of the network. - */ - toJSON() { - return { name: this.name, chainId: String(this.chainId) }; - } - /** - * The network common name. - * - * This is the canonical name, as networks might have multiple names. - * @returns {string} The network name. - */ - get name() { - return this.#name; - } - /** - * Sets the network name. - * @param {string} value - The new network name. - */ - set name(value) { - this.#name = value; - } - /** - * The network chain ID. - * @returns {bigint} The network chain ID. - */ - get chainId() { - return this.#chainId; - } - /** - * Sets the network chain ID. - * @param {BigNumberish} value - The new network chain ID. - */ - set chainId(value) { - this.#chainId = getBigInt(value, 'chainId'); - } - /** - * Returns true if `other` matches this network. Any chain ID must match, and if no chain ID is present, the name - * must match. - * - * This method does not currently check for additional properties, such as plug-in compatibility. - * - * @param {Networkish} other - The network to compare. - * @returns {boolean} True if the networks match. - * @ignore - */ - matches(other) { - if (other == null) { - return false; - } - if (typeof other === 'string') { - try { - return this.chainId === getBigInt(other); - // eslint-disable-next-line no-empty - } - catch (error) { } - return this.name === other; - } - if (typeof other === 'number' || typeof other === 'bigint') { - try { - return this.chainId === getBigInt(other); - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; - } - if (typeof other === 'object') { - if (other.chainId != null) { - try { - return this.chainId === getBigInt(other.chainId); - // eslint-disable-next-line no-empty - } - catch (error) { } - return false; - } - if (other.name != null) { - return this.name === other.name; - } - return false; - } - return false; - } - /** - * Create a copy of this Network. - * @returns {Network} A new Network instance. - */ - clone() { - const clone = new Network(this.name, this.chainId); - return clone; - } - /** - * Returns a new Network for the `network` name or chainId. - * - * @param {Networkish} [network] - The network to get. - * @returns {Network} The Network instance. - * @throws {Error} If the network is invalid. - */ - static from(network) { - // Default network - if (network == null) { - return Network.from('mainnet'); - } - // Canonical name or chain ID - if (typeof network === 'number') { - network = BigInt(network); - } - if (typeof network === 'string' || typeof network === 'bigint') { - const networkFunc = Networks.get(network); - if (networkFunc) { - return networkFunc(); - } - if (typeof network === 'bigint') { - return new Network('unknown', network); - } - assertArgument(false, 'unknown network', 'network', network); - } - // Clonable with network-like abilities - if (typeof network.clone === 'function') { - const clone = network.clone(); - return clone; - } - // Networkish - if (typeof network === 'object') { - assertArgument(typeof network.name === 'string' && typeof network.chainId === 'number', 'invalid network object name or chainId', 'network', network); - const custom = new Network(network.name, network.chainId); - return custom; - } - assertArgument(false, 'invalid network', 'network', network); - } - /** - * Register `nameOrChainId` with a function which returns an instance of a Network representing that chain. - * - * @param {string | number | bigint} nameOrChainId - The name or chain ID to register. - * @param {() => Network} networkFunc - The function to create the Network. - * @throws {Error} If a network is already registered for `nameOrChainId`. - */ - static register(nameOrChainId, networkFunc) { - if (typeof nameOrChainId === 'number') { - nameOrChainId = BigInt(nameOrChainId); - } - const existing = Networks.get(nameOrChainId); - if (existing) { - assertArgument(false, `conflicting network for ${JSON.stringify(existing.name)}`, 'nameOrChainId', nameOrChainId); - } - Networks.set(nameOrChainId, networkFunc); - } - } - - /** - * Deep copies an object. - * - * @param {any} obj - The object to copy. - * @returns {any} The copied object. - */ - function copy$2(obj) { - return JSON.parse(JSON.stringify(obj)); - } - /** - * A **PollingBlockSubscriber** polls at a regular interval for a change in the block number. - * - * @category Providers - */ - class PollingBlockSubscriber { - #provider; - #poller; - #interval; - #zone; - // The most recent block we have scanned for events. The value -2 - // indicates we still need to fetch an initial block number - #blockNumber; - /** - * Create a new **PollingBlockSubscriber** attached to `provider`. - * - * @ignore - */ - constructor(provider, zone) { - this.#provider = provider; - this.#zone = zone; - this.#poller = null; - this.#interval = 4000; - this.#blockNumber = -2; - } - /** - * The polling interval. - * - * @returns {number} The current polling interval. - */ - get pollingInterval() { - return this.#interval; - } - /** - * Sets the polling interval. - * - * @param {number} value - The new polling interval. - */ - set pollingInterval(value) { - this.#interval = value; - } - /** - * Polls for new blocks. - * - * @ignore - * @returns {Promise} A promise that resolves when polling is complete. - */ - async #poll() { - try { - const blockNumber = await this.#provider.getBlockNumber(toShard(this.#zone)); - // Bootstrap poll to setup our initial block number - if (this.#blockNumber === -2) { - this.#blockNumber = blockNumber; - return; - } - // @TODO: Put a cap on the maximum number of events per loop? - if (blockNumber !== this.#blockNumber) { - for (let b = this.#blockNumber + 1; b <= blockNumber; b++) { - // We have been stopped - if (this.#poller == null) { - return; - } - await this.#provider.emit('block', this.#zone, b); - } - this.#blockNumber = blockNumber; - } - } - catch (error) { - // @TODO: Minor bump, add an "error" event to let subscribers - // know things went awry. - } - // We have been stopped - if (this.#poller == null) { - return; - } - this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); - } - /** - * Starts the polling process. - */ - start() { - if (this.#poller) { - return; - } - this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); - this.#poll(); - } - /** - * Stops the polling process. - */ - stop() { - if (!this.#poller) { - return; - } - this.#provider._clearTimeout(this.#poller); - this.#poller = null; - } - /** - * Pauses the polling process. - * - * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused. - */ - pause(dropWhilePaused) { - this.stop(); - if (dropWhilePaused) { - this.#blockNumber = -2; - } - } - /** - * Resumes the polling process. - */ - resume() { - this.start(); - } - } - /** - * An **OnBlockSubscriber** can be sub-classed, with a {@link OnBlockSubscriber._poll | **_poll**} implementation which - * will be called on every new block. - * - * @category Providers - */ - class OnBlockSubscriber { - #provider; - #poll; - #running; - #zone; - /** - * Create a new **OnBlockSubscriber** attached to `provider`. - * - * @ignore - */ - constructor(provider, zone) { - this.#provider = provider; - this.#zone = zone; - this.#running = false; - this.#poll = (blockNumber) => { - this._poll(blockNumber, this.#provider); - }; - } - /** - * Called on every new block. - * - * @ignore - * @param {number} blockNumber - The block number. - * @param {AbstractProvider} provider - The provider. - * @returns {Promise} A promise that resolves when the poll is complete. - * @throws {Error} If the method is not overridden by a subclass. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _poll(blockNumber, provider) { - throw new Error('sub-classes must override this'); - } - /** - * Starts the subscriber. - */ - start() { - if (this.#running) { - return; - } - this.#running = true; - this.#poll(-2); - this.#provider.on('block', this.#poll, this.#zone); - } - /** - * Stops the subscriber. - */ - stop() { - if (!this.#running) { - return; - } - this.#running = false; - this.#provider.off('block', this.#poll, this.#zone); - } - /** - * Pauses the subscriber. - * - * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - pause(dropWhilePaused) { - this.stop(); - } - /** - * Resumes the subscriber. - */ - resume() { - this.start(); - } - } - /** - * @ignore - */ - class PollingOrphanSubscriber extends OnBlockSubscriber { - #filter; - /** - * Create a new **PollingOrphanSubscriber** attached to `provider`, listening for `filter`. - * - * @ignore - */ - constructor(provider, filter, zone) { - super(provider, zone); - this.#filter = copy$2(filter); - } - /** - * Polls for orphaned blocks. - * - * @ignore - * @param {number} blockNumber - The block number. - * @param {AbstractProvider} provider - The provider. - * @returns {Promise} A promise that resolves when the poll is complete. - * @throws {Error} If the method is not implemented. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _poll(blockNumber, provider) { - throw new Error('@TODO'); - } - } - /** - * A **PollingTransactionSubscriber** will poll for a given transaction hash for its receipt. - * - * @category Providers - */ - class PollingTransactionSubscriber extends OnBlockSubscriber { - #hash; - /** - * Create a new **PollingTransactionSubscriber** attached to `provider`, listening for `hash`. - * - * @ignore - */ - constructor(provider, hash, zone) { - super(provider, zone); - this.#hash = hash; - } - /** - * Polls for the transaction receipt. - * - * @ignore - * @param {number} blockNumber - The block number. - * @param {AbstractProvider} provider - The provider. - * @returns {Promise} A promise that resolves when the poll is complete. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _poll(blockNumber, provider) { - const tx = await provider.getTransactionReceipt(this.#hash); - if (tx) { - provider.emit(this.#hash, toZone(this.#hash.slice(0, 4)), tx); - } - } - } - /** - * A **PollingEventSubscriber** will poll for a given filter for its logs. - * - * @category Providers - */ - class PollingEventSubscriber { - #provider; - #filter; - #poller; - #running; - #blockNumber; - #zone; - /** - * Create a new **PollingEventSubscriber** attached to `provider`, listening for `filter`. - * - * @ignore - */ - constructor(provider, filter) { - this.#provider = provider; - this.#filter = copy$2(filter); - this.#poller = this.#poll.bind(this); - this.#running = false; - this.#blockNumber = -2; - const zone = getZoneFromEventFilter(this.#filter); - if (zone) { - this.#zone = zone; - } - else { - throw new Error('Unable to determine zone for event filter'); - } - } - /** - * Polls for logs based on the filter. - * - * @ignore - * @param {number} blockNumber - The block number. - * @returns {Promise} A promise that resolves when the poll is complete. - */ - async #poll(blockNumber) { - // The initial block hasn't been determined yet - if (this.#blockNumber === -2) { - return; - } - const filter = copy$2(this.#filter); - filter.fromBlock = this.#blockNumber + 1; - filter.toBlock = blockNumber; - const logs = await this.#provider.getLogs(filter); - // No logs could just mean the node has not indexed them yet, - // so we keep a sliding window of 60 blocks to keep scanning - if (logs.length === 0) { - if (this.#blockNumber < blockNumber - 60) { - this.#blockNumber = blockNumber - 60; - } - return; - } - for (const log of logs) { - this.#provider.emit(this.#filter, getZoneFromNodeLocation(this.#filter.nodeLocation), log); - // Only advance the block number when logs were found to - // account for networks (like BNB and Polygon) which may - // sacrifice event consistency for block event speed - this.#blockNumber = log.blockNumber; - } - } - /** - * Starts the subscriber. - */ - start() { - if (this.#running) { - return; - } - this.#running = true; - if (this.#blockNumber === -2) { - this.#provider.getBlockNumber(toShard(this.#zone)).then((blockNumber) => { - this.#blockNumber = blockNumber; - }); - } - this.#provider.on('block', this.#poller, this.#zone); - } - /** - * Stops the subscriber. - */ - stop() { - if (!this.#running) { - return; - } - this.#running = false; - this.#provider.off('block', this.#poller, this.#zone); - } - /** - * Pauses the subscriber. - * - * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused. - */ - pause(dropWhilePaused) { - this.stop(); - if (dropWhilePaused) { - this.#blockNumber = -2; - } - } - /** - * Resumes the subscriber. - */ - resume() { - this.start(); - } - } - - /** - * The available providers should suffice for most developers purposes, but the - * {@link AbstractProvider | **AbstractProvider**} class has many features which enable sub-classing it for specific - * purposes. - */ - /** - * Event coalescence When we register an event with an async value (e.g. address is a Signer), we need to add it - * immediately for the Event API, but also need time to resolve the address. Upon resolving the address, we need to - * migrate the listener to the static event. We also need to maintain a map of Signer to address so we can sync respond - * to listenerCount. - */ - /** - * Constants - */ - const BN_2 = BigInt(2); - /** - * Check if a value is a Promise. - * - * @param {any} value - The value to check. - * @returns {boolean} True if the value is a Promise, false otherwise. - */ - function isPromise(value) { - return value && typeof value.then === 'function'; - } - /** - * Get a tag string based on a prefix and value. - * - * @param {string} prefix - The prefix for the tag. - * @param {any} value - The value to include in the tag. - * @returns {string} The generated tag. - */ - function getTag(prefix, value) { - return (prefix + - ':' + - JSON.stringify(value, (k, v) => { - if (v == null) { - return 'null'; - } - if (typeof v === 'bigint') { - return `bigint:${v.toString()}`; - } - if (typeof v === 'string') { - return v.toLowerCase(); - } - // Sort object keys - if (typeof v === 'object' && !Array.isArray(v)) { - const keys = Object.keys(v); - keys.sort(); - return keys.reduce((accum, key) => { - accum[key] = v[key]; - return accum; - }, {}); - } - return v; - })); - } - /** - * An **UnmanagedSubscriber** is useful for events which do not require any additional management, such as `"debug"` - * which only requires emit in synchronous event loop triggered calls. - * - * @category Providers - */ - class UnmanagedSubscriber { - /** - * The name of the event. - */ - name; - /** - * Create a new UnmanagedSubscriber with `name`. - * - * @param {string} name - The name of the event. - */ - constructor(name) { - defineProperties(this, { name }); - } - start() { } - stop() { } - // todo `dropWhilePaused` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - pause(dropWhilePaused) { } - resume() { } - } - /** - * Create a deep copy of a value. - * - * @param {T} value - The value to copy. - * @returns {T} The copied value. - */ - function copy$1(value) { - return JSON.parse(JSON.stringify(value)); - } - /** - * Remove duplicates and sort an array of strings. - * - * @param {string[]} items - The array of strings. - * @returns {string[]} The concisified array. - */ - function concisify(items) { - items = Array.from(new Set(items).values()); - items.sort(); - return items; - } - // todo `provider` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async function getSubscription(_event, zone) { - if (_event == null) { - throw new Error('invalid event'); - } - // Normalize topic array info an EventFilter - if (Array.isArray(_event)) { - _event = { topics: _event }; - } - if (typeof _event === 'string') { - if (_event === 'debug') { - return { type: _event, tag: _event }; - } - switch (_event) { - case 'block': - case 'pending': - if (!zone) { - throw new Error('zone is required for block and pending events'); - } - return { type: 'block', tag: _event, zone }; - case 'error': - case 'finalized': - case 'network': - case 'safe': { - return { type: _event, tag: _event }; - } - } - } - if (isHexString(_event, 32)) { - const hash = _event.toLowerCase(); - zone = toZone(hash.slice(0, 4)); - return { type: 'transaction', tag: getTag('tx', { hash }), hash, zone }; - } - if (_event.orphan) { - const event = _event; - if (!zone) { - const hash = event.hash || - event.tx.hash || - event.other?.hash || - event.log.transactionHash || - null; - if (hash == null) { - throw new Error('orphan event must specify a hash'); - } - zone = toZone(hash.slice(0, 4)); - } - // @todo Should lowercase and whatnot things here instead of copy... - return { type: 'orphan', tag: getTag('orphan', event), filter: copy$1(event), zone }; - } - if (_event.address || _event.topics) { - const event = _event; - const filter = { - topics: (event.topics || []).map((t) => { - if (t == null) { - return null; - } - if (Array.isArray(t)) { - return concisify(t.map((t) => t.toLowerCase())); - } - return t.toLowerCase(); - }), - }; - if (event.nodeLocation) { - filter.nodeLocation = event.nodeLocation; - } - if (event.address) { - const addresses = []; - const promises = []; - const addAddress = (addr) => { - if (isHexString(addr)) { - addresses.push(formatMixedCaseChecksumAddress(addr)); - } - else { - promises.push((async () => { - addresses.push(formatMixedCaseChecksumAddress(await resolveAddress(addr))); - })()); - } - }; - if (Array.isArray(event.address)) { - event.address.forEach(addAddress); - } - else { - addAddress(event.address); - } - if (promises.length) { - await Promise.all(promises); - } - if (!zone) { - zone = toZone(addresses[0].slice(0, 4)); - } - filter.address = concisify(addresses.map((a) => a.toLowerCase())); - if (!filter.nodeLocation) { - filter.nodeLocation = getNodeLocationFromZone(zone); - } - } - else { - if (!zone) { - throw new Error('zone is required for event'); - } - } - return { filter, tag: getTag('event', filter), type: 'event', zone }; - } - assertArgument(false, 'unknown ProviderEvent', 'event', _event); - } - /** - * Get the current time in milliseconds. - * - * @returns {number} The current time in milliseconds. - */ - function getTime() { - return new Date().getTime(); - } - const defaultOptions$1 = { - cacheTimeout: 250, - pollingInterval: 4000, - usePathing: false, - }; - /** - * An **AbstractProvider** provides a base class for other sub-classes to implement the {@link Provider | **Provider**} - * API by normalizing input arguments and formatting output results as well as tracking events for consistent behaviour - * on an eventually-consistent network. - * - * @category Providers - */ - class AbstractProvider { - /** - * @ignore - */ - _urlMap; - #connect; - #subs; - // null=unpaused, true=paused+dropWhilePaused, false=paused - #pausedState; - #destroyed; - #networkPromise; - #anyNetwork; - #performCache; - // The most recent block number if running an event or -1 if no "block" event - #lastBlockNumber; - #nextTimer; - #timers; - #options; - _initFailed; - initResolvePromise; - initRejectPromise; - initPromise; - /** - * Create a new **AbstractProvider** connected to `network`, or use the various network detection capabilities to - * discover the {@link Network | **Network**} if necessary. - * - * @param _network - The network to connect to, or `"any"` to - * @param options - The options to configure the provider. - */ - constructor(_network, options) { - this._initFailed = false; - this.#options = Object.assign({}, defaultOptions$1, options || {}); - if (_network === 'any') { - this.#anyNetwork = true; - this.#networkPromise = null; - } - else if (_network) { - const network = Network.from(_network); - this.#anyNetwork = false; - this.#networkPromise = Promise.resolve(network); - setTimeout(() => { - this.emit('network', undefined, network, null); - }, 0); - } - else { - this.#anyNetwork = false; - this.#networkPromise = null; - } - this.#lastBlockNumber = -1; - this.#performCache = new Map(); - this.#subs = new Map(); - this.#pausedState = null; - this.#destroyed = false; - this.#nextTimer = 1; - this.#timers = new Map(); - this.#connect = []; - this._urlMap = new Map(); - this.initResolvePromise = null; - this.initRejectPromise = null; - this.initPromise = new Promise((resolve, reject) => { - this.initResolvePromise = resolve; - this.initRejectPromise = reject; - }); - } - /** - * Initialize the URL map with the provided URLs. - * - * @param {U} urls - The URLs to initialize the map with. - * @returns {Promise} A promise that resolves when the map is initialized. - */ - async initialize(urls) { - try { - const primeSuffix = this.#options.usePathing ? `/${fromShard(exports.Shard.Prime, 'nickname')}` : ':9001'; - if (urls instanceof FetchRequest) { - urls.url = urls.url.split(':')[0] + ':' + urls.url.split(':')[1] + primeSuffix; - this._urlMap.set(exports.Shard.Prime, urls); - this.#connect.push(urls); - const shards = await this.getRunningLocations(); - shards.forEach((shard) => { - const port = 9200 + 20 * shard[0] + shard[1]; - const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`); - const shardSuffix = this.#options.usePathing ? `/${fromShard(shardEnum, 'nickname')}` : `:${port}`; - this._urlMap.set(shardEnum, new FetchRequest(urls.url.split(':')[0] + ':' + urls.url.split(':')[1] + shardSuffix)); - }); - return; - } - if (Array.isArray(urls)) { - for (const url of urls) { - const primeUrl = url.split(':')[0] + ':' + url.split(':')[1] + primeSuffix; - const primeConnect = new FetchRequest(primeUrl); - this._urlMap.set(exports.Shard.Prime, primeConnect); - this.#connect.push(primeConnect); - const shards = await this.getRunningLocations(); - shards.forEach((shard) => { - const port = 9200 + 20 * shard[0] + shard[1]; - const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`); - const shardSuffix = this.#options.usePathing - ? `/${fromShard(shardEnum, 'nickname')}` - : `:${port}`; - this._urlMap.set(toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`), new FetchRequest(url.split(':')[0] + ':' + url.split(':')[1] + shardSuffix)); - }); - } - } - if (this.initResolvePromise) - this.initResolvePromise(); - } - catch (error) { - this._initFailed = true; - console.log('Error initializing URL map:', error); - if (this.initRejectPromise) - this.initRejectPromise(error); - } - } - /** - * Get the list of connected FetchRequests. - * - * @returns {FetchRequest[]} The list of connected FetchRequests. - */ - get connect() { - return this.#connect; - } - /** - * Get the zone from an address. - * - * @param {AddressLike} _address - The address to get the zone from. - * @returns {Promise} A promise that resolves to the zone. - */ - async zoneFromAddress(_address) { - const address = this._getAddress(_address); - return toZone((await address).slice(0, 4)); - } - /** - * Get the shard from a hash. - * - * @param {string} hash - The hash to get the shard from. - * @returns {Shard} The shard. - */ - shardFromHash(hash) { - return toShard(hash.slice(0, 4)); - } - /** - * Get the zone from a hash. - * - * @param {string} hash - The hash to get the zone from. - * @returns {Zone} The zone. - */ - zoneFromHash(hash) { - return toZone(hash.slice(0, 4)); - } - /** - * Get the latest Quai rate for a zone. - * - * @param {Zone} zone - The zone to get the rate for. - * @param {number} [amt=1] - The amount to get the rate for. Default is `1` - * @returns {Promise} A promise that resolves to the latest Quai rate. - */ - async getLatestQuaiRate(zone, amt = 1) { - const blockNumber = await this.getBlockNumber(toShard(zone)); - return this.getQuaiRateAtBlock(zone, blockNumber, amt); - } - /** - * Get the Quai rate at a specific block. - * - * @param {Zone} zone - The zone to get the rate for. - * @param {BlockTag} blockTag - The block tag to get the rate at. - * @param {number} [amt=1] - The amount to get the rate for. Default is `1` - * @returns {Promise} A promise that resolves to the Quai rate at the specified block. - */ - async getQuaiRateAtBlock(zone, blockTag, amt = 1) { - let resolvedBlockTag = this._getBlockTag(toShard(zone), blockTag); - if (typeof resolvedBlockTag !== 'string') { - resolvedBlockTag = await resolvedBlockTag; - } - return await this.#perform({ - method: 'getQuaiRateAtBlock', - blockTag: resolvedBlockTag, - amt, - zone: zone, - }); - } - /** - * Get the protocol expansion number. - * - * @returns {Promise} A promise that resolves to the protocol expansion number. - */ - async getProtocolExpansionNumber() { - return await this.#perform({ - method: 'getProtocolExpansionNumber', - }); - } - /** - * Get the latest Qi rate for a zone. - * - * @param {Zone} zone - The zone to get the rate for. - * @param {number} [amt=1] - The amount to get the rate for. Default is `1` - * @returns {Promise} A promise that resolves to the latest Qi rate. - */ - async getLatestQiRate(zone, amt = 1) { - const blockNumber = await this.getBlockNumber(toShard(zone)); - return this.getQiRateAtBlock(zone, blockNumber, amt); - } - /** - * Get the Qi rate at a specific block. - * - * @param {Zone} zone - The zone to get the rate for. - * @param {BlockTag} blockTag - The block tag to get the rate at. - * @param {number} [amt=1] - The amount to get the rate for. Default is `1` - * @returns {Promise} A promise that resolves to the Qi rate at the specified block. - */ - async getQiRateAtBlock(zone, blockTag, amt = 1) { - let resolvedBlockTag = this._getBlockTag(toShard(zone), blockTag); - if (typeof resolvedBlockTag !== 'string') { - resolvedBlockTag = await resolvedBlockTag; - } - return await this.#perform({ - method: 'getQiRateAtBlock', - blockTag: resolvedBlockTag, - amt, - zone: zone, - }); - } - /** - * Get the polling interval. - * - * @returns {number} The polling interval. - */ - get pollingInterval() { - return this.#options.pollingInterval; - } - /** - * Returns `this`, to allow an **AbstractProvider** to implement the [Contract Runner](../classes/ContractRunner) - * interface. - * - * @returns {this} The provider instance. - */ - get provider() { - return this; - } - /** - * Shares multiple identical requests made during the same 250ms. - * - * @ignore - * @param {PerformActionRequest} req - The request to perform. - * @returns {Promise} A promise that resolves to the result of the operation. - */ - async #perform(req) { - const timeout = this.#options.cacheTimeout; - // Caching disabled - if (timeout < 0) { - return await this._perform(req); - } - // Create a tag - const tag = getTag(req.method, req); - let perform = this.#performCache.get(tag); - if (!perform || tag.includes('pending') || tag.includes('latest')) { - perform = this._perform(req); - this.#performCache.set(tag, perform); - setTimeout(() => { - if (this.#performCache.get(tag) === perform) { - this.#performCache.delete(tag); - } - }, timeout); - } - return await perform; - } - /** - * Provides the opportunity for a sub-class to wrap a block before returning it, to add additional properties or an - * alternate sub-class of {@link Block | **Block**}. - * - * @ignore - * @param {BlockParams} value - The block to wrap. - * @param {Network} network - The network the block was on. - * @returns {Block} The wrapped block. - */ - // @todo `network` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _wrapBlock(value, network) { - // Handle known node by -> remove null values from the number array - value.header.number = Array.isArray(value.header.number) - ? value.header.number.filter((n) => n != null) - : value.header.number; - return new Block(formatBlock(value), this); - } - /** - * Provides the opportunity for a sub-class to wrap a log before returning it, to add additional properties or an - * alternate sub-class of {@link Log | **Log**}. - * - * @ignore - * @param {LogParams} value - The log to wrap. - * @param {Network} network - The network the log was on. - * @returns {Log} The wrapped log. - */ - // @todo `network` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _wrapLog(value, network) { - return new Log(formatLog(value), this); - } - /** - * Provides the opportunity for a sub-class to wrap a transaction receipt before returning it, to add additional - * properties or an {@link TransactionReceipt | **TransactionReceipt**}. - * - * @ignore - * @param {TransactionReceiptParams} value - The transaction receipt to wrap. - * @param {Network} network - The network the transaction was on. - * @returns {TransactionReceipt} The wrapped transaction receipt. - */ - // @todo `network` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _wrapTransactionReceipt(value, network) { - const formattedReceipt = formatTransactionReceipt(value); - return new TransactionReceipt(formattedReceipt, this); - } - /** - * Provides the opportunity for a sub-class to wrap a transaction response before returning it, to add additional - * properties or an alternate sub-class of {@link TransactionResponse | **TransactionResponse**}. - * - * @ignore - * @param {TransactionResponseParams} tx - The transaction response to wrap. - * @param {Network} network - The network the transaction was on. - * @returns {TransactionResponse} The wrapped transaction response. - */ - // TODO: `newtork` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _wrapTransactionResponse(tx, network) { - if ('from' in tx) { - return new QuaiTransactionResponse(formatTransactionResponse(tx), this); - } - else { - return new QiTransactionResponse(formatTransactionResponse(tx), this); - } - } - /** - * Resolves to the Network, forcing a network detection using whatever technique the sub-class requires. - * - * Sub-classes **must** override this. - * - * @ignore - * @param {Shard} [shard] - The shard to use for the network detection. - * @returns {Promise} A promise resolving to the network. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _detectNetwork() { - assert(false, 'sub-classes must implement this', 'UNSUPPORTED_OPERATION', { - operation: '_detectNetwork', - }); - } - /** - * Sub-classes should use this to perform all built-in operations. All methods sanitizes and normalizes the values - * passed into this. - * - * Sub-classes **must** override this. - * - * @ignore - * @param {PerformActionRequest} req - The request to perform. - * @returns {Promise} A promise resolving to the result of the operation. - */ - async _perform(req) { - assert(false, `unsupported method: ${req.method}`, 'UNSUPPORTED_OPERATION', { - operation: req.method, - info: req, - }); - } - // State - async getBlockNumber(shard) { - const blockNumber = getNumber(await this.#perform({ method: 'getBlockNumber', shard: shard }), '%response'); - if (this.#lastBlockNumber >= 0) { - this.#lastBlockNumber = blockNumber; - } - return blockNumber; - } - /** - * Returns or resolves to the address for `address`, resolving {@link Addressable | **Addressable**} objects and - * returning if already an address. - * - * @ignore - * @param {AddressLike} address - The address to normalize. - * @returns {string | Promise} The normalized address. - */ - _getAddress(address) { - return resolveAddress(address); - } - /** - * Returns or resolves to a valid block tag for `blockTag`, resolving negative values and returning if already a - * valid block tag. - * - * @ignore - * @param {Shard} [shard] - The shard to use for the block tag. - * @param {BlockTag} [blockTag] - The block tag to normalize. - * @returns {string | Promise} A promise that resolves to a valid block tag. - */ - _getBlockTag(shard, blockTag) { - if (blockTag == null) { - return 'latest'; - } - switch (blockTag) { - case 'earliest': - return '0x0'; - case 'finalized': - case 'latest': - case 'pending': - case 'safe': - return blockTag; - } - if (isHexString(blockTag)) { - if (isHexString(blockTag, 32)) { - return blockTag; - } - return toQuantity(blockTag); - } - if (typeof blockTag === 'bigint') { - blockTag = getNumber(blockTag, 'blockTag'); - } - if (typeof blockTag === 'number') { - if (blockTag >= 0) { - return toQuantity(blockTag); - } - if (this.#lastBlockNumber >= 0) { - return toQuantity(this.#lastBlockNumber + blockTag); - } - return this.getBlockNumber(shard).then((b) => toQuantity(b + blockTag)); - } - assertArgument(false, 'invalid blockTag', 'blockTag', blockTag); - } - /** - * Returns or resolves to a filter for `filter`, resolving any {@link Addressable | **Addressable**} object and - * returning if already a valid filter. - * - * @ignore - * @param {Filter | FilterByBlockHash} filter - The filter to normalize. - * @returns {PerformActionFilter | Promise} A promise that resolves to a valid filter. - */ - _getFilter(filter) { - // Create a canonical representation of the topics - const topics = (filter.topics || []).map((t) => { - if (t == null) { - return null; - } - if (Array.isArray(t)) { - return concisify(t.map((t) => t.toLowerCase())); - } - return t.toLowerCase(); - }); - const blockHash = 'blockHash' in filter ? filter.blockHash : undefined; - const resolve = (_address, fromBlock, toBlock, nodeLocation) => { - let address = undefined; - switch (_address.length) { - case 0: - break; - case 1: - address = _address[0]; - break; - default: - _address.sort(); - address = _address; - } - if (blockHash) { - if (fromBlock != null || toBlock != null) { - throw new Error('invalid filter'); - } - } - const filter = {}; - if (address) { - filter.address = address; - } - if (topics.length) { - filter.topics = topics; - } - if (fromBlock) { - filter.fromBlock = fromBlock; - } - if (toBlock) { - filter.toBlock = toBlock; - } - if (blockHash) { - filter.blockHash = blockHash; - } - if (nodeLocation) { - filter.nodeLocation = nodeLocation; - } - return filter; - }; - // Addresses could be async (Addressables) - const address = []; - if (filter.address) { - if (Array.isArray(filter.address)) { - for (const addr of filter.address) { - address.push(this._getAddress(addr)); - } - } - else { - address.push(this._getAddress(filter.address)); - } - } - const zone = getZoneFromNodeLocation(filter.nodeLocation); - let fromBlock = undefined; - if ('fromBlock' in filter) { - fromBlock = this._getBlockTag(toShard(zone), filter.fromBlock); - } - let toBlock = undefined; - if ('toBlock' in filter) { - toBlock = this._getBlockTag(toShard(zone), filter.toBlock); - } - let nodeLocation = undefined; - if (filter.nodeLocation) { - nodeLocation = filter.nodeLocation; - } - if (address.filter((a) => typeof a !== 'string').length || - (fromBlock != null && typeof fromBlock !== 'string') || - (toBlock != null && typeof toBlock !== 'string')) { - return Promise.all([Promise.all(address), fromBlock, toBlock, nodeLocation]).then((result) => { - return resolve(result[0], result[1], result[2], result[3]); - }); - } - return resolve(address, fromBlock, toBlock, nodeLocation); - } - /** - * Returns or resovles to a transaction for `request`, resolving any {@link Addressable | **Addressable**} and - * returning if already a valid transaction. - * - * @ignore - * @param {PerformActionTransaction} _request - The transaction to normalize. - * @returns {PerformActionTransaction | Promise} A promise that resolves to a valid - * transaction. - */ - _getTransactionRequest(_request) { - const request = copyRequest(_request); - const promises = []; - ['to', 'from', 'inputs', 'outputs'].forEach((key) => { - if (request[key] == null) { - return; - } - const addr = Array.isArray(request[key]) - ? 'address' in request[key][0] - ? request[key].map((it) => it.address) - : request[key].map((it) => computeAddress(it.pubkey)) - : resolveAddress(request[key]); - if (isPromise(addr)) { - if (Array.isArray(addr)) { - for (let i = 0; i < addr.length; i++) { - promises.push((async function () { - request[key][i].address = await addr[i]; - })()); - } - } - else { - promises.push((async function () { - request[key] = await addr; - })()); - } - } - else { - request[key] = addr; - } - }); - if (request.blockTag != null) { - const blockTag = this._getBlockTag(toShard(request.chainId.toString()), request.blockTag); - if (isPromise(blockTag)) { - promises.push((async function () { - request.blockTag = await blockTag; - })()); - } - else { - request.blockTag = blockTag; - } - } - if (promises.length) { - return (async function () { - await Promise.all(promises); - return request; - })(); - } - return request; - } - async getNetwork() { - // No explicit network was set and this is our first time - if (this.#networkPromise == null) { - // Detect the current network (shared with all calls) - const detectNetwork = (async () => { - try { - const network = await this._detectNetwork(); - this.emit('network', undefined, network, null); - return network; - } - catch (error) { - if (this.#networkPromise === detectNetwork) { - this.#networkPromise = null; - } - throw error; - } - })(); - this.#networkPromise = detectNetwork; - return (await detectNetwork).clone(); - } - const networkPromise = this.#networkPromise; - const [expected, actual] = await Promise.all([ - networkPromise, - this._detectNetwork(), // The actual connected network - ]); - if (expected.chainId !== actual.chainId) { - if (this.#anyNetwork) { - // The "any" network can change, so notify listeners - this.emit('network', undefined, actual, expected); - // Update the network if something else hasn't already changed it - if (this.#networkPromise === networkPromise) { - this.#networkPromise = Promise.resolve(actual); - } - } - else { - // Otherwise, we do not allow changes to the underlying network - assert(false, `network changed: ${expected.chainId} => ${actual.chainId} `, 'NETWORK_ERROR', { - event: 'changed', - }); - } - } - return expected.clone(); - } - async _getRunningLocations(shard, now) { - now = now ? now : false; - return await this.#perform(shard - ? { method: 'getRunningLocations', shard: shard, now: now } - : { method: 'getRunningLocations', now: now }); - } - async getRunningLocations(shard) { - return await this._getRunningLocations(shard); - } - async getProtocolTrieExpansionCount(shard) { - return await this.#perform({ method: 'getProtocolTrieExpansionCount', shard: shard }); - } - async getFeeData(zone, txType = true) { - const getFeeDataFunc = async () => { - const { gasPrice, priorityFee } = await resolveProperties({ - gasPrice: (async () => { - try { - const value = await this.#perform({ method: 'getGasPrice', txType, zone: zone }); - return getBigInt(value, '%response'); - } - catch (error) { - console.log(error); - } - return null; - })(), - priorityFee: (async () => { - try { - const value = txType - ? await this.#perform({ method: 'getMaxPriorityFeePerGas', zone: zone }) - : 0; - return getBigInt(value, '%response'); - // eslint-disable-next-line no-empty - } - catch (error) { } - return null; - })(), - }); - if (gasPrice == null) { - throw new Error('could not determine gasPrice'); - } - let maxFeePerGas = null; - let maxPriorityFeePerGas = null; - // These are the recommended EIP-1559 heuristics for fee data - maxPriorityFeePerGas = priorityFee != null ? priorityFee : BigInt('1000000000'); - maxFeePerGas = gasPrice * BN_2 + maxPriorityFeePerGas; - return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); - }; - return await getFeeDataFunc(); - } - async estimateGas(_tx) { - let tx = this._getTransactionRequest(_tx); - if (isPromise(tx)) { - tx = await tx; - } - const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx)); - return getBigInt(await this.#perform({ - method: 'estimateGas', - transaction: tx, - zone: zone, - }), '%response'); - } - // TODO: `attempt` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async #call(tx, blockTag, attempt, zone) { - // This came in as a PerformActionTransaction, so to/from are safe; we can cast - const transaction = copyRequest(tx); - return hexlify(await this._perform({ method: 'call', transaction, blockTag, zone })); - } - // TODO: `shard` is not used, remove or re-write - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async #checkNetwork(promise, shard) { - const { value } = await resolveProperties({ - network: this.getNetwork(), - value: promise, - }); - return value; - } - async call(_tx) { - const zone = await this.zoneFromAddress(addressFromTransactionRequest(_tx)); - const shard = toShard(zone); - const { tx, blockTag } = await resolveProperties({ - tx: this._getTransactionRequest(_tx), - blockTag: this._getBlockTag(shard, _tx.blockTag), - }); - return await this.#checkNetwork(this.#call(tx, blockTag, -1, zone), shard); - } - // Account - async #getAccountValue(request, _address, _blockTag) { - let address = this._getAddress(_address); - const zone = await this.zoneFromAddress(_address); - const shard = toShard(zone); - let blockTag = this._getBlockTag(shard, _blockTag); - if (typeof address !== 'string' || typeof blockTag !== 'string') { - [address, blockTag] = await Promise.all([address, blockTag]); - } - return await this.#checkNetwork(this.#perform(Object.assign(request, { address, blockTag, zone: zone })), shard); - } - async getBalance(address, blockTag) { - return getBigInt(await this.#getAccountValue({ method: 'getBalance' }, address, blockTag), '%response'); - } - async getOutpointsByAddress(address) { - const outpoints = await this.#getAccountValue({ method: 'getOutpointsByAddress' }, address, 'latest'); - const outpointsArray = Array.isArray(outpoints) ? outpoints : []; - return outpointsArray.map((outpoint) => ({ - txhash: outpoint.Txhash, - index: outpoint.Index, - denomination: outpoint.Denomination, - })); - } - async getTransactionCount(address, blockTag) { - return getNumber(await this.#getAccountValue({ method: 'getTransactionCount' }, address, blockTag), '%response'); - } - async getCode(address, blockTag) { - return hexlify(await this.#getAccountValue({ method: 'getCode' }, address, blockTag)); - } - async getStorage(address, _position, blockTag) { - const position = getBigInt(_position, 'position'); - return hexlify(await this.#getAccountValue({ method: 'getStorage', position }, address, blockTag)); - } - async getPendingHeader() { - return await this.#perform({ method: 'getPendingHeader' }); - } - async getTxPoolContent(zone) { - return await this.#perform({ method: 'getTxPoolContent', zone: zone }); - } - async txPoolInspect(zone) { - return await this.#perform({ method: 'txPoolInspect', zone: zone }); - } - // Write - async broadcastTransaction(zone, signedTx) { - const type = decodeProtoTransaction(getBytes(signedTx)).type; - const { blockNumber, hash, network } = await resolveProperties({ - blockNumber: this.getBlockNumber(toShard(zone)), - hash: this._perform({ - method: 'broadcastTransaction', - signedTransaction: signedTx, - zone: zone, - }), - network: this.getNetwork(), - }); - const tx = type == 2 ? QiTransaction.from(signedTx) : QuaiTransaction.from(signedTx); - this.#validateTransactionHash(tx.hash || '', hash); - return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber); - } - #validateTransactionHash(computedHash, nodehash) { - if (computedHash !== nodehash) { - throw new Error('Transaction hash mismatch'); - } - } - validateUrl(url) { - const urlPattern = /^(https?):\/\/[a-zA-Z0-9.-]+(:\d+)?$/; - if (!urlPattern.test(url)) { - let errorMessage = 'Invalid URL: '; - if (!/^https?:\/\//.test(url)) { - errorMessage += 'URL must start with http:// or https://. '; - } - if (url.endsWith('/')) { - errorMessage += 'URL should not end with a /. '; - } - if (/\/[^/]+/.test(url)) { - errorMessage += 'URL should not contain a path, query string, or fragment. '; - } - throw new Error(errorMessage.trim()); - } - } - async #getBlock(shard, block, includeTransactions) { - if (isHexString(block, 32)) { - return await this.#perform({ - method: 'getBlock', - blockHash: block, - includeTransactions, - shard: shard, - }); - } - let blockTag = this._getBlockTag(shard, block); - if (typeof blockTag !== 'string') { - blockTag = await blockTag; - } - return await this.#perform({ - method: 'getBlock', - blockTag, - includeTransactions, - shard: shard, - }); - } - // Queries - async getBlock(shard, block, prefetchTxs) { - const { network, params } = await resolveProperties({ - network: this.getNetwork(), - params: this.#getBlock(shard, block, !!prefetchTxs), - }); - if (params == null) { - return null; - } - return this._wrapBlock(params, network); - } - async getTransaction(hash) { - const zone = toZone(this.shardFromHash(hash)); - const { network, params } = await resolveProperties({ - network: this.getNetwork(), - params: this.#perform({ method: 'getTransaction', hash, zone: zone }), - }); - if (params == null) { - return null; - } - return this._wrapTransactionResponse(params, network); - } - async getTransactionReceipt(hash) { - const zone = toZone(this.shardFromHash(hash)); - const { network, params } = await resolveProperties({ - network: this.getNetwork(), - params: this.#perform({ method: 'getTransactionReceipt', hash, zone: zone }), - }); - if (params == null) { - return null; - } - // Some backends did not backfill the effectiveGasPrice in to old transactions - // in the receipt, so we look it up manually and inject it. - if (params.gasPrice == null && params.effectiveGasPrice == null) { - const tx = await this.#perform({ method: 'getTransaction', hash, zone: zone }); - if (tx == null) { - throw new Error('report this; could not find tx or effectiveGasPrice'); - } - params.effectiveGasPrice = tx.gasPrice; - } - return this._wrapTransactionReceipt(params, network); - } - async getTransactionResult(hash) { - const zone = toZone(this.shardFromHash(hash)); - const { result } = await resolveProperties({ - network: this.getNetwork(), - result: this.#perform({ method: 'getTransactionResult', hash, zone: zone }), - }); - if (result == null) { - return null; - } - return hexlify(result); - } - // Bloom-filter Queries - async getLogs(_filter) { - let filter = this._getFilter(_filter); - if (isPromise(filter)) { - filter = await filter; - } - const { network, params } = await resolveProperties({ - network: this.getNetwork(), - params: this.#perform({ - method: 'getLogs', - filter, - zone: getZoneFromNodeLocation(filter.nodeLocation), - }), - }); - return params.map((p) => this._wrapLog(p, network)); - } - /** - * @ignore - */ - // TODO: unsupported, remove? - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _getProvider(chainId) { - assert(false, 'provider cannot connect to target network', 'UNSUPPORTED_OPERATION', { - operation: '_getProvider()', - }); - } - async waitForTransaction(hash, _confirms, timeout) { - const zone = this.zoneFromHash(hash); - const confirms = _confirms != null ? _confirms : 1; - if (confirms === 0) { - return this.getTransactionReceipt(hash); - } - // eslint-disable-next-line no-async-promise-executor - return new Promise(async (resolve, reject) => { - let timer = null; - const listener = async (blockNumber) => { - try { - const receipt = await this.getTransactionReceipt(hash); - if (receipt != null) { - if (blockNumber - receipt.blockNumber + 1 >= confirms) { - resolve(receipt); - //this.off("block", listener); - if (timer) { - clearTimeout(timer); - timer = null; - } - return; - } - } - } - catch (error) { - console.log('Error occured while waiting for transaction:', error); - } - this.once('block', listener, zone); - }; - if (timeout != null) { - timer = setTimeout(() => { - if (timer == null) { - return; - } - timer = null; - this.off('block', listener, zone); - reject(makeError('timeout', 'TIMEOUT', { reason: 'timeout' })); - }, timeout); - } - listener(await this.getBlockNumber(toShard(zone))); - }); - } - // TODO: not implemented yet - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async waitForBlock(shard, blockTag) { - assert(false, 'not implemented yet', 'NOT_IMPLEMENTED', { - operation: 'waitForBlock', - }); - } - /** - * Clear a timer created using the {@link AbstractProvider._setTimeout | **_setTimeout**} method. - * - * @param {number} timerId - The ID of the timer to clear. - */ - _clearTimeout(timerId) { - const timer = this.#timers.get(timerId); - if (!timer) { - return; - } - if (timer.timer) { - clearTimeout(timer.timer); - } - this.#timers.delete(timerId); - } - /** - * Create a timer that will execute `func` after at least `timeout` (in ms). If `timeout` is unspecified, then - * `func` will execute in the next event loop. - * - * {@link AbstractProvider.pause | **Pausing**} the provider will pause any associated timers. - * - * @ignore - * @ignore - * @param {() => void} _func - The function to execute. - * @param {number} [timeout] - The time to wait before executing `func`. - * @returns {number} The ID of the timer. - */ - _setTimeout(_func, timeout) { - if (timeout == null) { - timeout = 0; - } - const timerId = this.#nextTimer++; - const func = () => { - this.#timers.delete(timerId); - _func(); - }; - if (this.paused) { - this.#timers.set(timerId, { timer: null, func, time: timeout }); - } - else { - const timer = setTimeout(func, timeout); - this.#timers.set(timerId, { timer, func, time: getTime() }); - } - return timerId; - } - /** - * Perform `func` on each subscriber. - * - * @ignore - * @param {(s: Subscriber) => void} func - The function to perform. - */ - _forEachSubscriber(func) { - for (const sub of this.#subs.values()) { - func(sub.subscriber); - } - } - /** - * Sub-classes may override this to customize subscription implementations. - * - * @ignore - * @param {Subscription} sub - The subscription to get the subscriber for. - */ - _getSubscriber(sub) { - switch (sub.type) { - case 'debug': - case 'error': - case 'network': - return new UnmanagedSubscriber(sub.type); - case 'block': { - const subscriber = new PollingBlockSubscriber(this, sub.zone); - subscriber.pollingInterval = this.pollingInterval; - return subscriber; - } - //! TODO: implement this for quais - // case "safe": case "finalized": - // return new PollingBlockTagSubscriber(this, sub.type); - case 'event': - return new PollingEventSubscriber(this, sub.filter); - case 'transaction': - return new PollingTransactionSubscriber(this, sub.hash, sub.zone); - case 'orphan': - return new PollingOrphanSubscriber(this, sub.filter, sub.zone); - } - throw new Error(`unsupported event: ${sub.type}`); - } - /** - * If a {@link Subscriber | **Subscriber**} fails and needs to replace itself, this method may be used. - * - * For example, this is used for providers when using the `quai_getFilterChanges` method, which can return null if - * state filters are not supported by the backend, allowing the Subscriber to swap in a `PollingEventSubscriber`. - * - * @ignore - * @param {Subscriber} oldSub - The subscriber to replace. - * @param {Subscriber} newSub - The new subscriber. - */ - _recoverSubscriber(oldSub, newSub) { - for (const sub of this.#subs.values()) { - if (sub.subscriber === oldSub) { - if (sub.started) { - sub.subscriber.stop(); - } - sub.subscriber = newSub; - if (sub.started) { - newSub.start(); - } - if (this.#pausedState != null) { - newSub.pause(this.#pausedState); - } - break; - } - } - } - async #hasSub(event, emitArgs, zone) { - let sub = await getSubscription(event, zone); - // This is a log that is removing an existing log; we actually want - // to emit an orphan event for the removed log - if (sub.type === 'event' && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) { - sub = await getSubscription({ orphan: 'drop-log', log: emitArgs[0] }, zone); - } - return this.#subs.get(sub.tag) || null; - } - async #getSub(event, zone) { - const subscription = await getSubscription(event, zone); - // Prevent tampering with our tag in any subclass' _getSubscriber - const tag = subscription.tag; - let sub = this.#subs.get(tag); - if (!sub) { - const subscriber = this._getSubscriber(subscription); - const addressableMap = new WeakMap(); - const nameMap = new Map(); - sub = { subscriber, tag, addressableMap, nameMap, started: false, listeners: [], zone: subscription.zone }; - this.#subs.set(tag, sub); - } - return sub; - } - async on(event, listener, zone) { - const sub = await this.#getSub(event, zone); - sub.listeners.push({ listener, once: false }); - if (!sub.started) { - sub.subscriber.start(); - sub.started = true; - if (this.#pausedState != null) { - sub.subscriber.pause(this.#pausedState); - } - } - return this; - } - async once(event, listener, zone) { - const sub = await this.#getSub(event, zone); - sub.listeners.push({ listener, once: true }); - if (!sub.started) { - sub.subscriber.start(); - sub.started = true; - if (this.#pausedState != null) { - sub.subscriber.pause(this.#pausedState); - } - } - return this; - } - async emit(event, zone, ...args) { - const sub = await this.#hasSub(event, args, zone); - // If there is not subscription or if a recent emit removed - // the last of them (which also deleted the sub) do nothing - if (!sub || sub.listeners.length === 0) { - return false; - } - const count = sub.listeners.length; - sub.listeners = sub.listeners.filter(({ listener, once }) => { - const payload = new EventPayload(this, once ? null : listener, event); - try { - listener.call(this, ...args, payload); - // eslint-disable-next-line no-empty - } - catch (error) { } - return !once; - }); - if (sub.listeners.length === 0) { - if (sub.started) { - sub.subscriber.stop(); - } - this.#subs.delete(sub.tag); - } - return count > 0; - } - async listenerCount(event) { - if (event) { - const sub = await this.#hasSub(event); - if (!sub) { - return 0; - } - return sub.listeners.length; - } - let total = 0; - for (const { listeners } of this.#subs.values()) { - total += listeners.length; - } - return total; - } - async listeners(event) { - if (event) { - const sub = await this.#hasSub(event); - if (!sub) { - return []; - } - return sub.listeners.map(({ listener }) => listener); - } - let result = []; - for (const { listeners } of this.#subs.values()) { - result = result.concat(listeners.map(({ listener }) => listener)); - } - return result; - } - async off(event, listener, zone) { - const sub = await this.#hasSub(event, [], zone); - if (!sub) { - return this; - } - if (listener) { - const index = sub.listeners.map(({ listener }) => listener).indexOf(listener); - if (index >= 0) { - sub.listeners.splice(index, 1); - } - } - if (!listener || sub.listeners.length === 0) { - if (sub.started) { - sub.subscriber.stop(); - } - this.#subs.delete(sub.tag); - } - return this; - } - async removeAllListeners(event) { - if (event) { - const { tag, started, subscriber } = await this.#getSub(event); - if (started) { - subscriber.stop(); - } - this.#subs.delete(tag); - } - else { - for (const [tag, { started, subscriber }] of this.#subs) { - if (started) { - subscriber.stop(); - } - this.#subs.delete(tag); - } - } - return this; - } - // Alias for "on" - async addListener(event, listener, zone) { - return await this.on(event, listener, zone); - } - // Alias for "off" - async removeListener(event, listener, zone) { - return this.off(event, listener, zone); - } - /** - * If this provider has been destroyed using the {@link AbstractProvider.destroy | **destroy**} method. - * - * Once destroyed, all resources are reclaimed, internal event loops and timers are cleaned up and no further - * requests may be sent to the provider. - */ - get destroyed() { - return this.#destroyed; - } - /** - * Sub-classes may use this to shutdown any sockets or release their resources and reject any pending requests. - * - * Sub-classes **must** call `super.destroy()`. - */ - destroy() { - // Stop all listeners - this.removeAllListeners(); - // Shut down all tiemrs - for (const timerId of this.#timers.keys()) { - this._clearTimeout(timerId); - } - this.#destroyed = true; - } - /** - * Whether the provider is currently paused. - * - * A paused provider will not emit any events, and generally should not make any requests to the network, but that - * is up to sub-classes to manage. - * - * Setting `paused = true` is identical to calling `.pause(false)`, which will buffer any events that occur while - * paused until the provider is unpaused. - * - * @returns {boolean} Whether the provider is paused. - */ - get paused() { - return this.#pausedState != null; - } - set paused(pause) { - if (!!pause === this.paused) { - return; - } - if (this.paused) { - this.resume(); - } - else { - this.pause(false); - } - } - /** - * Pause the provider. If `dropWhilePaused`, any events that occur while paused are dropped, otherwise all events - * will be emitted once the provider is unpaused. - * - * @param {boolean} [dropWhilePaused] - Whether to drop events while paused. - */ - pause(dropWhilePaused) { - this.#lastBlockNumber = -1; - if (this.#pausedState != null) { - if (this.#pausedState == !!dropWhilePaused) { - return; - } - assert(false, 'cannot change pause type; resume first', 'UNSUPPORTED_OPERATION', { - operation: 'pause', - }); - } - this._forEachSubscriber((s) => s.pause(dropWhilePaused)); - this.#pausedState = !!dropWhilePaused; - for (const timer of this.#timers.values()) { - // Clear the timer - if (timer.timer) { - clearTimeout(timer.timer); - } - // Remaining time needed for when we become unpaused - timer.time = getTime() - timer.time; - } - } - /** - * Resume the provider. - */ - resume() { - if (this.#pausedState == null) { - return; - } - this._forEachSubscriber((s) => s.resume()); - this.#pausedState = null; - for (const timer of this.#timers.values()) { - // Remaining time when we were paused - let timeout = timer.time; - if (timeout < 0) { - timeout = 0; - } - // Start time (in cause paused, so we con compute remaininf time) - timer.time = getTime(); - // Start the timer - setTimeout(timer.func, timeout); - } - } - } - - /** - * Deep copies an object. - * - * @param {any} obj - The object to copy. - * @returns {any} A deep copy of the object. - */ - function copy(obj) { - return JSON.parse(JSON.stringify(obj)); - } - /** - * Some backends support subscribing to events using a Filter ID. - * - * When subscribing with this technique, the node issues a unique **Filter ID**. At this point the node dedicates - * resources to the filter, so that periodic calls to follow up on the **Filter ID** will receive any events since the - * last call. - * - * @category Providers - */ - class FilterIdSubscriber { - #provider; - #filterIdPromise; - #poller; - #running; - #network; - #hault; - zone; - /** - * @ignore Creates A new **FilterIdSubscriber** which will use {@link FilterIdSubscriber._subscribe | **_subscribe**} - * and {@link FilterIdSubscriber._emitResults | **_emitResults**} to setup the subscription and provide the event - * to the `provider`. - * @param {JsonRpcApiProvider} provider - The provider to use. - */ - constructor(provider, zone) { - this.#provider = provider; - this.#filterIdPromise = null; - this.#poller = this.#poll.bind(this); - this.#running = false; - this.#network = null; - this.#hault = false; - this.zone = zone; - } - /** - * Sub-classes **must** override this to begin the subscription. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @returns {Promise} A promise that resolves to the subscription ID. - * @throws {Error} If the method is not overridden. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _subscribe(provider) { - throw new Error('subclasses must override this'); - } - /** - * Sub-classes **must** override this to handle the events. - * - * @ignore - * @param {AbstractProvider} provider - The provider to use. - * @param {any[]} result - The results to handle. - * @returns {Promise} A promise that resolves when the results are handled. - * @throws {Error} If the method is not overridden. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _emitResults(provider, result) { - throw new Error('subclasses must override this'); - } - /** - * Sub-classes **must** override this to handle recovery on errors. - * - * @ignore - * @param {AbstractProvider} provider - The provider to use. - * @returns {Subscriber} The recovered subscriber. - * @throws {Error} If the method is not overridden. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _recover(provider) { - throw new Error('subclasses must override this'); - } - /** - * Polls for new events. - * - * @ignore - * @param {number} blockNumber - The block number to poll from. - * @returns {Promise} A promise that resolves when polling is complete. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async #poll(blockNumber) { - try { - // Subscribe if necessary - if (this.#filterIdPromise == null) { - this.#filterIdPromise = this._subscribe(this.#provider); - } - // Get the Filter ID - let filterId = null; - try { - filterId = await this.#filterIdPromise; - } - catch (error) { - if (!isError(error, 'UNSUPPORTED_OPERATION') || error.operation !== 'quai_newFilter') { - throw error; - } - } - // The backend does not support Filter ID; downgrade to - // polling - if (filterId == null) { - this.#filterIdPromise = null; - this.#provider._recoverSubscriber(this, this._recover(this.#provider)); - return; - } - const network = await this.#provider.getNetwork(); - if (!this.#network) { - this.#network = network; - } - if (this.#network.chainId !== network.chainId) { - throw new Error('chain changed'); - } - if (this.#hault) { - return; - } - const result = await this.#provider.send('quai_getFilterChanges', [filterId]); - await this._emitResults(this.#provider, result); - } - catch (error) { - console.log('@TODO', error); - } - this.#provider.once('block', this.#poller, this.zone); - } - /** - * Tears down the subscription. - * - * @ignore - */ - #teardown() { - const filterIdPromise = this.#filterIdPromise; - if (filterIdPromise) { - this.#filterIdPromise = null; - filterIdPromise.then((filterId) => { - this.#provider.send('quai_uninstallFilter', [filterId]); - }); - } - } - /** - * Starts the subscriber. - */ - start() { - if (this.#running) { - return; - } - this.#running = true; - this.#poll(-2); - } - /** - * Stops the subscriber. - */ - stop() { - if (!this.#running) { - return; - } - this.#running = false; - this.#hault = true; - this.#teardown(); - this.#provider.off('block', this.#poller, this.zone); - } - /** - * Pauses the subscriber. - * - * @param {boolean} [dropWhilePaused] - Whether to drop the subscription while paused. - */ - pause(dropWhilePaused) { - if (dropWhilePaused) { - this.#teardown(); - } - this.#provider.off('block', this.#poller, this.zone); - } - /** - * Resumes the subscriber. - */ - resume() { - this.start(); - } - } - /** - * A **FilterIdSubscriber** for receiving contract events. - * - * @category Providers - */ - class FilterIdEventSubscriber extends FilterIdSubscriber { - #event; - /** - * @ignore Creates A new **FilterIdEventSubscriber** attached to `provider` listening for `filter`. - * @param {JsonRpcApiProvider} provider - The provider to use. - * @param {EventFilter} filter - The event filter to use. - */ - constructor(provider, filter) { - const zone = getZoneFromEventFilter(filter); - if (zone == null) { - throw new Error('Unable to determine zone for event filter'); - } - super(provider, zone); - this.#event = copy(filter); - } - /** - * Recovers the subscriber. - * - * @ignore - * @param {AbstractProvider} provider - The provider to use. - * @returns {Subscriber} The recovered subscriber. - */ - _recover(provider) { - return new PollingEventSubscriber(provider, this.#event); - } - /** - * Subscribes to the event filter. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @returns {Promise} A promise that resolves to the subscription ID. - */ - async _subscribe(provider) { - const filterId = await provider.send('quai_newFilter', [this.#event]); - return filterId; - } - /** - * Emits the results of the event filter. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @param {any[]} results - The results to emit. - * @returns {Promise} A promise that resolves when the results are emitted. - */ - async _emitResults(provider, results) { - for (const result of results) { - provider.emit(this.#event, this.zone, provider._wrapLog(result, provider._network)); - } - } - } - /** - * A **FilterIdSubscriber** for receiving pending transactions events. - * - * @category Providers - */ - class FilterIdPendingSubscriber extends FilterIdSubscriber { - /** - * Subscribes to the pending transactions filter. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @returns {Promise} A promise that resolves to the subscription ID. - */ - async _subscribe(provider) { - return await provider.send('quai_newPendingTransactionFilter', []); - } - /** - * Emits the results of the pending transactions filter. - * - * @ignore - * @param {JsonRpcApiProvider} provider - The provider to use. - * @param {any[]} results - The results to emit. - * @returns {Promise} A promise that resolves when the results are emitted. - */ - async _emitResults(provider, results) { - for (const result of results) { - provider.emit('pending', this.zone, result); - } - } - } - - /** - * One of the most common ways to interact with the blockchain is by a node running a JSON-RPC interface which can be - * connected to, based on the transport, using: - * - * - HTTP or HTTPS - {@link JsonRpcProvider | **JsonRpcProvider**} - * - WebSocket - {@link WebSocketProvider | **WebSocketProvider**} - * - IPC - {@link IpcSocketProvider | **IpcSocketProvider**} - */ - // @TODO: - // - Add the batching API - // 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 - const Primitive = 'bigint,boolean,function,number,string,symbol'.split(/,/g); - /** - * Deeply copies a value. - * - * @ignore - * @param {T} value - The value to copy. - * @returns {T} The copied value. - */ - function deepCopy(value) { - if (value == null || Primitive.indexOf(typeof value) >= 0) { - return value; - } - // Keep any Addressable - if (typeof value.getAddress === 'function') { - return value; - } - if (Array.isArray(value)) { - return value.map(deepCopy); - } - if (typeof value === 'object') { - return Object.keys(value).reduce((accum, key) => { - accum[key] = value[key]; - return accum; - }, {}); - } - throw new Error(`should not happen: ${value} (${typeof value})`); - } - /** - * Stalls execution for a specified duration. - * - * @ignore - * @param {number} duration - The duration to stall in milliseconds. - * @returns {Promise} A promise that resolves after the duration. - */ - function stall(duration) { - return new Promise((resolve) => { - setTimeout(resolve, duration); - }); - } - const defaultOptions = { - staticNetwork: null, - batchStallTime: 10, - batchMaxSize: 1 << 20, - batchMaxCount: 100, - cacheTimeout: 250, - usePathing: false, - }; - // @TODO: Unchecked Signers - /** - * A signer that uses JSON-RPC to sign transactions and messages. - * - * @category Providers - */ - class JsonRpcSigner extends AbstractSigner { - address; - /** - * Creates a new JsonRpcSigner instance. - * - * @param {JsonRpcApiProvider} provider - The JSON-RPC provider. - * @param {string} address - The address of the signer. - */ - constructor(provider, address) { - super(provider); - address = getAddress(address); - defineProperties(this, { address }); - } - /** - * Connects the signer to a provider. - * - * @param {null | Provider} provider - The provider to connect to. - * @returns {Signer} The connected signer. - * @throws {Error} If the signer cannot be reconnected. - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - connect(provider) { - assert(false, 'cannot reconnect JsonRpcSigner', 'UNSUPPORTED_OPERATION', { - operation: 'signer.connect', - }); - } - /** - * Gets the address of the signer. - * - * @returns {Promise} The address of the signer. - */ - async getAddress() { - return this.address; - } - /** - * Populates a Quai transaction. - * - * @ignore - * @param {QuaiTransactionRequest} tx - The transaction request. - * @returns {Promise} The populated transaction. - */ - async populateQuaiTransaction(tx) { - return (await this.populateCall(tx)); - } - /** - * Sends an unchecked transaction. - * - * @ignore - * @param {TransactionRequest} _tx - The transaction request. - * @returns {Promise} The transaction hash. - */ - async sendUncheckedTransaction(_tx) { - const tx = deepCopy(_tx); - const promises = []; - if ('from' in tx) { - // Make sure the from matches the sender - if (tx.from) { - const _from = tx.from; - promises.push((async () => { - const from = await resolveAddress(_from); - assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), 'from address mismatch', 'transaction', _tx); - tx.from = from; - })()); - } - else { - tx.from = this.address; - } - // The JSON-RPC for quai_sendTransaction uses 90000 gas; if the user - // wishes to use this, it is easy to specify explicitly, otherwise - // we look it up for them. - if (tx.gasLimit == null) { - promises.push((async () => { - tx.gasLimit = await this.provider.estimateGas({ ...tx, from: this.address }); - })()); - } - // The address may be an ENS name or Addressable - if (tx.to != null) { - const _to = tx.to; - promises.push((async () => { - tx.to = await resolveAddress(_to); - })()); - } - } - // Wait until all of our properties are filled in - if (promises.length) { - await Promise.all(promises); - } - const hexTx = this.provider.getRpcTransaction(tx); - return this.provider.send('quai_sendTransaction', [hexTx]); - } - /** - * Sends a transaction. - * - * @param {TransactionRequest} tx - The transaction request. - * @returns {Promise} The transaction response. - * @throws {Error} If the transaction cannot be sent. - */ - async sendTransaction(tx) { - const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx)); - // This cannot be mined any earlier than any recent block - const blockNumber = await this.provider.getBlockNumber(toShard(zone)); - // Send the transaction - const hash = await this.sendUncheckedTransaction(tx); - // Unfortunately, JSON-RPC only provides and opaque transaction hash - // for a response, and we need the actual transaction, so we poll - // for it; it should show up very quickly - return await new Promise((resolve, reject) => { - const timeouts = [1000, 100]; - let invalids = 0; - const checkTx = async () => { - try { - // Try getting the transaction - const tx = await this.provider.getTransaction(hash); - if (tx != null) { - resolve(tx.replaceableTransaction(blockNumber)); - return; - } - } - catch (error) { - // If we were cancelled: stop polling. - // If the data is bad: the node returns bad transactions - // If the network changed: calling again will also fail - // If unsupported: likely destroyed - if (isError(error, 'CANCELLED') || - isError(error, 'BAD_DATA') || - isError(error, 'NETWORK_ERROR') || - isError(error, 'UNSUPPORTED_OPERATION')) { - if (error.info == null) { - error.info = {}; - } - error.info.sendTransactionHash = hash; - reject(error); - return; - } - // Stop-gap for misbehaving backends; see #4513 - if (isError(error, 'INVALID_ARGUMENT')) { - invalids++; - if (error.info == null) { - error.info = {}; - } - error.info.sendTransactionHash = hash; - if (invalids > 10) { - reject(error); - return; - } - } - // Notify anyone that cares; but we will try again, since - // it is likely an intermittent service error - this.provider.emit('error', zoneFromHash(hash), makeError('failed to fetch transation after sending (will try again)', 'UNKNOWN_ERROR', { - error, - })); - } - // Wait another 4 seconds - this.provider._setTimeout(() => { - checkTx(); - }, timeouts.pop() || 4000); - }; - checkTx(); - }); - } - /** - * Signs a transaction. - * - * @param {TransactionRequest} _tx - The transaction request. - * @returns {Promise} The signed transaction. - * @throws {Error} If the transaction cannot be signed. - */ - async signTransaction(_tx) { - const tx = deepCopy(_tx); - // QuaiTransactionRequest - if ('from' in tx) { - if (tx.from) { - const from = await resolveAddress(tx.from); - assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), 'from address mismatch', 'transaction', _tx); - tx.from = from; - } - else { - tx.from = this.address; - } - } - else { - throw new Error('No QI signing implementation in provider-jsonrpc'); - } - const hexTx = this.provider.getRpcTransaction(tx); - return await this.provider.send('quai_signTransaction', [hexTx]); - } - /** - * Signs a message. - * - * @param {string | Uint8Array} _message - The message to sign. - * @returns {Promise} The signed message. - */ - async signMessage(_message) { - const message = typeof _message === 'string' ? toUtf8Bytes(_message) : _message; - return await this.provider.send('personal_sign', [hexlify(message), this.address.toLowerCase()]); - } - /** - * Signs typed data. - * - * @param {TypedDataDomain} domain - The domain of the typed data. - * @param {Record} types - The types of the typed data. - * @param {Record} _value - The value of the typed data. - * @returns {Promise} The signed typed data. - */ - async signTypedData(domain, types, _value) { - const value = deepCopy(_value); - return await this.provider.send('quai_signTypedData_v4', [ - this.address.toLowerCase(), - JSON.stringify(TypedDataEncoder.getPayload(domain, types, value)), - ]); - } - /** - * Unlocks the account. - * - * @param {string} password - The password to unlock the account. - * @returns {Promise} True if the account is unlocked, false otherwise. - */ - async unlock(password) { - return this.provider.send('personal_unlockAccount', [this.address.toLowerCase(), password, null]); - } - /** - * Signs a message using the legacy method. - * - * @ignore - * @param {string | Uint8Array} _message - The message to sign. - * @returns {Promise} The signed message. - */ - async _legacySignMessage(_message) { - const message = typeof _message === 'string' ? toUtf8Bytes(_message) : _message; - return await this.provider.send('quai_sign', [this.address.toLowerCase(), hexlify(message)]); - } - } - /** - * The JsonRpcApiProvider is an abstract class and **MUST** be sub-classed. - * - * It provides the base for all JSON-RPC-based Provider interaction. - * - * Sub-classing Notes: - * - * - A sub-class MUST override _send - * - A sub-class MUST call the `_start()` method once connected - * - * @category Providers - */ - class JsonRpcApiProvider extends AbstractProvider { - #options; - // The next ID to use for the JSON-RPC ID field - #nextId; - // Payloads are queued and triggered in batches using the drainTimer - #payloads; - #drainTimer; - #notReady; - #network; - #pendingDetectNetwork; - /** - * Schedules the draining of the payload queue. - * - * @ignore - */ - #scheduleDrain() { - if (this.#drainTimer) { - return; - } - // If we aren't using batching, no harm in sending it immediately - const stallTime = this._getOption('batchMaxCount') === 1 ? 0 : this._getOption('batchStallTime'); - this.#drainTimer = setTimeout(() => { - this.#drainTimer = null; - const payloads = this.#payloads; - this.#payloads = []; - while (payloads.length) { - // Create payload batches that satisfy our batch constraints - const batch = [payloads.shift()]; - while (payloads.length) { - if (batch.length === this.#options.batchMaxCount) { - break; - } - batch.push(payloads.shift()); - const bytes = JSON.stringify(batch.map((p) => p.payload)); - if (bytes.length > this.#options.batchMaxSize) { - payloads.unshift(batch.pop()); - break; - } - } - // Process the result to each payload - (async () => { - const payloadMap = new Map(); - const nowPayloadMap = new Map(); - for (let i = 0; i < batch.length; i++) { - if (batch[i].now) { - if (!nowPayloadMap.has(batch[i].shard)) { - if (batch[i].payload != null) { - nowPayloadMap.set(batch[i].shard, [batch[i].payload]); - } - } - else { - nowPayloadMap.get(batch[i].shard)?.push(batch[i].payload); - } - } - else { - if (!payloadMap.has(batch[i].shard)) { - if (batch[i].payload != null) { - payloadMap.set(batch[i].shard, [batch[i].payload]); - } - } - else { - payloadMap.get(batch[i].shard)?.push(batch[i].payload); - } - } - } - const rawResult = []; - const processPayloads = async (key, value, now) => { - const payload = value.length === 1 ? value[0] : value; - const shard = key ? toShard(key) : exports.Shard.Prime; - const zone = shard.length < 4 ? undefined : toZone(shard); - this.emit('debug', zone, { action: 'sendRpcPayload', payload }); - rawResult.push(await this._send(payload, shard, now)); - this.emit('debug', zone, { action: 'receiveRpcResult', payload }); - }; - await Promise.all(Array.from(nowPayloadMap) - .map(async ([key, value]) => { - await processPayloads(key, value, true); - }) - .concat(Array.from(payloadMap).map(async ([key, value]) => { - await processPayloads(key, value); - }))); - const result = rawResult.flat(); - let lastZone; - try { - // Process results in batch order - for (const { resolve, reject, payload, shard } of batch) { - if (this.destroyed) { - reject(makeError('provider destroyed; cancelled request', 'UNSUPPORTED_OPERATION', { - operation: payload.method, - })); - continue; - } - if (shard) { - lastZone = shard.length < 4 ? undefined : toZone(shard); - } - else { - lastZone = undefined; - } - // Find the matching result - const resp = result.filter((r) => r.id === payload.id)[0]; - // No result; the node failed us in unexpected ways - if (resp == null) { - const error = makeError('missing response for request', 'BAD_DATA', { - value: result, - info: { payload }, - }); - this.emit('error', lastZone, error); - reject(error); - continue; - } - // The response is an error - if ('error' in resp) { - reject(this.getRpcError(payload, resp, shard)); - continue; - } - // All good; send the result - resolve(resp.result); - } - } - catch (error) { - this.emit('debug', lastZone, { action: 'receiveRpcError', error }); - for (const { reject } of batch) { - // @TODO: augment the error with the payload - reject(error); - } - } - })(); - } - }, stallTime); - } - /** - * Creates a new JsonRpcApiProvider instance. - * - * @param {Networkish} [network] - The network to connect to. - * @param {JsonRpcApiProviderOptions} [options] - The options for the provider. - */ - constructor(network, options) { - super(network, options); - this.#nextId = 1; - this.#options = Object.assign({}, defaultOptions, options || {}); - this.#payloads = []; - this.#drainTimer = null; - this.#network = null; - this.#pendingDetectNetwork = null; - { - let resolve = null; - const promise = new Promise((_resolve) => { - resolve = _resolve; - }); - this.#notReady = { promise, resolve }; - } - const staticNetwork = this._getOption('staticNetwork'); - if (typeof staticNetwork === 'boolean') { - assertArgument(!staticNetwork || network !== 'any', "staticNetwork cannot be used on special network 'any'", 'options', options); - if (staticNetwork && network != null) { - this.#network = Network.from(network); - } - } - else if (staticNetwork) { - // Make sure any static network is compatbile with the provided netwrok - assertArgument(network == null || staticNetwork.matches(network), 'staticNetwork MUST match network object', 'options', options); - this.#network = staticNetwork; - } - } - /** - * Returns the value associated with the option `key`. - * - * Sub-classes can use this to inquire about configuration options. - * - * @ignore - * @param {keyof JsonRpcApiProviderOptions} key - The option key. - * @returns {JsonRpcApiProviderOptions[key]} The option value. - */ - _getOption(key) { - return this.#options[key]; - } - /** - * Gets the {@link Network | **Network**} this provider has committed to. On each call, the network is detected, and - * if it has changed, the call will reject. - * - * @ignore - * @returns {Network} The network. - * @throws {Error} If the network is not available yet. - */ - get _network() { - assert(this.#network, 'network is not available yet', 'NETWORK_ERROR'); - return this.#network; - } - /** - * Resolves to the non-normalized value by performing `req`. - * - * Sub-classes may override this to modify behavior of actions, and should generally call `super._perform` as a - * fallback. - * - * @ignore - * @param {PerformActionRequest} req - The request to perform. - * @returns {Promise} The result of the request. - * @throws {Error} If the request fails. - */ - async _perform(req) { - // Legacy networks do not like the type field being passed along (which - // is fair), so we delete type if it is 0 and a non-EIP-1559 network - if (req.method !== 'getRunningLocations') { - await this.initPromise; - } - if (req.method === 'call' || req.method === 'estimateGas') { - const tx = req.transaction; - if (tx && tx.type != null && getBigInt(tx.type)) { - // If there are no EIP-1559 properties, it might be non-EIP-a559 - if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { - const feeData = await this.getFeeData(req.zone); - if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { - // Network doesn't know about EIP-1559 (and hence type) - req = Object.assign({}, req, { - transaction: Object.assign({}, tx, { type: undefined }), - }); - } - } - } - } - const request = this.getRpcRequest(req); - if (request != null) { - const shard = 'shard' in req ? req.shard : 'zone' in req ? toShard(req.zone) : undefined; - if (req.method === 'getRunningLocations') { - return await this.send(request.method, request.args, shard, req.now); - } - else { - return await this.send(request.method, request.args, shard); - } - } - return super._perform(req); - } - /** - * Sub-classes may override this; it detects the _actual_ network that we are **currently** connected to. - * - * Keep in mind that {@link JsonRpcApiProvider.send | **send**} may only be used once - * {@link JsonRpcApiProvider.ready | **ready**}, otherwise the _send primitive must be used instead. - * - * @ignore - * @returns {Promise} The detected network. - * @throws {Error} If network detection fails. - */ - async _detectNetwork() { - const network = this._getOption('staticNetwork'); - if (network) { - if (network === true) { - if (this.#network) { - return this.#network; - } - } - else { - return network; - } - } - if (this.#pendingDetectNetwork) { - return await this.#pendingDetectNetwork; - } - // If we are ready, use `send`, which enabled requests to be batched - if (this.ready) { - this.#pendingDetectNetwork = (async () => { - try { - const result = Network.from(getBigInt(await this.send('quai_chainId', []))); - this.#pendingDetectNetwork = null; - return result; - } - catch (error) { - this.#pendingDetectNetwork = null; - throw error; - } - })(); - return await this.#pendingDetectNetwork; - } - // We are not ready yet; use the primitive _send - this.#pendingDetectNetwork = (async () => { - const payload = { - id: this.#nextId++, - method: 'quai_chainId', - params: [], - jsonrpc: '2.0', - }; - this.emit('debug', undefined, { action: 'sendRpcPayload', payload }); - let result; - try { - result = (await this._send(payload))[0]; - this.#pendingDetectNetwork = null; - } - catch (error) { - this.#pendingDetectNetwork = null; - this.emit('debug', undefined, { action: 'receiveRpcError', error }); - throw error; - } - this.emit('debug', undefined, { action: 'receiveRpcResult', result }); - if ('result' in result) { - return Network.from(getBigInt(result.result)); - } - throw this.getRpcError(payload, result); - })(); - return await this.#pendingDetectNetwork; - } - /** - * Sub-classes **MUST** call this. Until {@link JsonRpcApiProvider._start | **_start**} has been called, no calls - * will be passed to {@link JsonRpcApiProvider._send | **_send**} from {@link JsonRpcApiProvider.send | **send**} . If - * it is overridden, then `super._start()` **MUST** be called. - * - * Calling it multiple times is safe and has no effect. - * - * @ignore - */ - _start() { - if (this.#notReady == null || this.#notReady.resolve == null) { - return; - } - this.#notReady.resolve(); - this.#notReady = null; - (async () => { - let retries = 0; - const maxRetries = 5; - while (this.#network == null && !this.destroyed && retries < maxRetries) { - try { - this.#network = await this._detectNetwork(); - } - catch (error) { - if (this.destroyed) { - break; - } - 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)'); - this.emit('error', undefined, makeError('failed to bootstrap network detection', 'NETWORK_ERROR', { - event: 'initial-network-discovery', - info: { error }, - })); - await stall(1000); - retries++; - } - } - if (retries >= maxRetries) { - throw new Error('Failed to detect network after maximum retries'); - } - // Start dispatching requests - this.#scheduleDrain(); - })(); - } - /** - * Resolves once the {@link JsonRpcApiProvider._start | **_start**} has been called. This can be used in sub-classes - * to defer sending data until the connection has been established. - * - * @ignore - * @returns {Promise} A promise that resolves once the provider is ready. - */ - async _waitUntilReady() { - if (this._initFailed) { - throw new Error('Provider failed to initialize on creation. Run initialize or create a new provider.'); - } - await this.initPromise; - } - /** - * Return a Subscriber that will manage the `sub`. - * - * Sub-classes may override this to modify the behavior of subscription management. - * - * @ignore - * @param {Subscription} sub - The subscription to manage. - * @returns {Subscriber} The subscriber that will manage the subscription. - */ - _getSubscriber(sub) { - // Pending Filters aren't availble via polling - if (sub.type === 'pending') { - return new FilterIdPendingSubscriber(this, sub.zone); - } - if (sub.type === 'event') { - return new FilterIdEventSubscriber(this, sub.filter); - } - // Orphaned Logs are handled automatically, by the filter, since - // logs with removed are emitted by it - if (sub.type === 'orphan' && sub.filter.orphan === 'drop-log') { - return new UnmanagedSubscriber('orphan'); - } - return super._getSubscriber(sub); - } - /** - * Returns true only if the {@link JsonRpcApiProvider._start | **_start**} has been called. - * - * @returns {boolean} True if the provider is ready. - */ - get ready() { - return this.#notReady == null; - } - /** - * Returns `tx` as a normalized JSON-RPC transaction request, which has all values hexlified and any numeric values - * converted to Quantity values. - * - * @ignore - * @param {TransactionRequest} tx - The transaction to normalize. - * @returns {JsonRpcTransactionRequest} The normalized transaction. - * @throws {Error} If the transaction is invalid. - */ - getRpcTransaction(tx) { - const result = {}; - if ('from' in tx || ('to' in tx && 'data' in tx)) { - // JSON-RPC now requires numeric values to be "quantity" values - [ - 'chainId', - 'gasLimit', - 'gasPrice', - 'type', - 'maxFeePerGas', - 'maxPriorityFeePerGas', - 'nonce', - 'value', - ].forEach((key) => { - if (tx[key] == null) { - return; - } - let dstKey = key; - if (key === 'gasLimit') { - dstKey = 'gas'; - } - result[dstKey] = toQuantity(getBigInt(tx[key], `tx.${key}`)); - }); - // Make sure addresses and data are lowercase - ['from', 'to', 'data'].forEach((key) => { - if (tx[key] == null) { - return; - } - result[key] = hexlify(tx[key]); - }); - // Normalize the access list object - if ('accessList' in tx && tx.accessList) { - result['accessList'] = accessListify(tx.accessList); - } - } - else { - throw new Error('No Qi getRPCTransaction implementation yet'); - } - return result; - } - /** - * Returns the request method and arguments required to perform `req`. - * - * @ignore - * @param {PerformActionRequest} req - The request to perform. - * @returns {null | { method: string; args: any[] }} The method and arguments to use. - * @throws {Error} If the request is not supported or invalid. - */ - getRpcRequest(req) { - switch (req.method) { - case 'chainId': - return { method: 'quai_chainId', args: [] }; - case 'getBlockNumber': - return { method: 'quai_blockNumber', args: [] }; - case 'getGasPrice': - return { - method: 'quai_baseFee', - args: [req.txType], - }; - case 'getMaxPriorityFeePerGas': - return { method: 'quai_maxPriorityFeePerGas', args: [] }; - case 'getPendingHeader': - return { method: 'quai_getPendingHeader', args: [] }; - case 'getBalance': - return { - method: 'quai_getBalance', - args: [req.address, req.blockTag], - }; - case 'getOutpointsByAddress': - return { - method: 'quai_getOutpointsByAddress', - args: [req.address], - }; - case 'getTransactionCount': - return { - method: 'quai_getTransactionCount', - args: [req.address, req.blockTag], - }; - case 'getCode': - return { - method: 'quai_getCode', - args: [req.address, req.blockTag], - }; - case 'getStorage': - return { - method: 'quai_getStorageAt', - args: [req.address, '0x' + req.position.toString(16), req.blockTag], - }; - case 'broadcastTransaction': - return { - method: 'quai_sendRawTransaction', - args: [req.signedTransaction], - }; - case 'getBlock': - if ('blockTag' in req) { - return { - method: 'quai_getBlockByNumber', - args: [req.blockTag, !!req.includeTransactions], - }; - } - else if ('blockHash' in req) { - return { - method: 'quai_getBlockByHash', - args: [req.blockHash, !!req.includeTransactions], - }; - } - break; - case 'getTransaction': - return { - method: 'quai_getTransactionByHash', - args: [req.hash], - }; - case 'getTransactionReceipt': - return { - method: 'quai_getTransactionReceipt', - args: [req.hash], - }; - case 'call': - return { - method: 'quai_call', - args: [this.getRpcTransaction(req.transaction), req.blockTag], - }; - case 'estimateGas': { - return { - method: 'quai_estimateGas', - args: [this.getRpcTransaction(req.transaction)], - }; - } - case 'getRunningLocations': { - return { - method: 'quai_listRunningChains', - args: [], - }; - } - case 'getProtocolTrieExpansionCount': { - return { - method: 'quai_getProtocolExpansionNumber', - args: [], - }; - } - case 'getProtocolExpansionNumber': { - return { - method: 'quai_getProtocolExpansionNumber', - args: [], - }; - } - case 'getQiRateAtBlock': { - return { - method: 'quai_qiRateAtBlock', - args: [req.blockTag, req.amt], - }; - } - case 'getQuaiRateAtBlock': { - return { - method: 'quai_quaiRateAtBlock', - args: [req.blockTag, req.amt], - }; - } - case 'getLogs': - return { method: 'quai_getLogs', args: [req.filter] }; - case 'getTxPoolContent': - return { method: 'txpool_content', args: [] }; - case 'txPoolInspect': - return { method: 'txpool_inspect', args: [] }; - } - return null; - } - /** - * Returns an quais-style Error for the given JSON-RPC error `payload`, coalescing the various strings and error - * shapes that different nodes return, coercing them into a machine-readable standardized error. - * - * @ignore - * @param {JsonRpcPayload} payload - The payload that was sent. - * @param {JsonRpcError} _error - The error that was received. - * @returns {Error} The coalesced error. - */ - getRpcError(payload, _error, shard) { - const { method } = payload; - const { error } = _error; - if (method === 'quai_estimateGas' && error.message) { - const msg = error.message; - if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) { - return makeError('insufficient funds', 'INSUFFICIENT_FUNDS', { - transaction: payload.params[0], - info: { payload, error, shard }, - }); - } - } - if (method === 'quai_call' || method === 'quai_estimateGas') { - const result = spelunkData(error); - const e = AbiCoder.getBuiltinCallException(method === 'quai_call' ? 'call' : 'estimateGas', payload.params[0], result ? result.data : null); - e.info = { error, payload, shard }; - return e; - } - // Only estimateGas and call can return arbitrary contract-defined text, so now we - // we can process text safely. - const message = JSON.stringify(spelunkMessage(error)); - if (method === 'quai_getTransactionByHash' && error.message && error.message.match(/transaction not found/i)) { - return makeError('transaction not found', 'TRANSACTION_NOT_FOUND', { info: { payload, error, shard } }); - } - if (typeof error.message === 'string' && error.message.match(/user denied|quais-user-denied/i)) { - const actionMap = { - quai_sign: 'signMessage', - personal_sign: 'signMessage', - quai_signTypedData_v4: 'signTypedData', - quai_signTransaction: 'signTransaction', - quai_sendTransaction: 'sendTransaction', - quai_requestAccounts: 'requestAccess', - wallet_requestAccounts: 'requestAccess', - }; - return makeError(`user rejected action`, 'ACTION_REJECTED', { - action: actionMap[method] || 'unknown', - reason: 'rejected', - info: { payload, error, shard }, - }); - } - if (method === 'quai_sendRawTransaction' || method === 'quai_sendTransaction') { - const transaction = payload.params[0]; - if (message.match(/insufficient funds|base fee exceeds gas limit/i)) { - return makeError('insufficient funds for intrinsic transaction cost', 'INSUFFICIENT_FUNDS', { - transaction, - info: { error, shard }, - }); - } - if (message.match(/nonce/i) && message.match(/too low/i)) { - return makeError('nonce has already been used', 'NONCE_EXPIRED', { - transaction, - info: { error, shard }, - }); - } - // "replacement transaction underpriced" - if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) { - return makeError('replacement fee too low', 'REPLACEMENT_UNDERPRICED', { - transaction, - info: { error, shard }, - }); - } - if (message.match(/only replay-protected/i)) { - return makeError('legacy pre-eip-155 transactions not supported', 'UNSUPPORTED_OPERATION', { - operation: method, - info: { transaction, info: { error, shard } }, - }); - } - if (message.match(/already known/i)) { - return makeError('transaction already known', 'TRANSACTION_ALREADY_KNOWN', { info: { error, shard } }); - } - } - let unsupported = !!message.match(/the method .* does not exist/i); - if (!unsupported) { - if (error && error.details && error.details.startsWith('Unauthorized method:')) { - unsupported = true; - } - } - if (unsupported) { - return makeError('unsupported operation', 'UNSUPPORTED_OPERATION', { - operation: payload.method, - info: { error, payload, shard }, - }); - } - if (message.match('Provider failed to initialize on creation. Run initialize or create a new provider.')) { - return makeError('Provider failed to initialize on creation. Run initUrlMap or create a new provider.', 'PROVIDER_FAILED_TO_INITIALIZE', { - info: { payload, error, shard }, - }); - } - return makeError('could not coalesce error', 'UNKNOWN_ERROR', { error, payload, shard }); - } - /** - * Requests the `method` with `params` via the JSON-RPC protocol over the underlying channel. This can be used to - * call methods on the backend that do not have a high-level API within the Provider API. - * - * This method queues requests according to the batch constraints in the options, assigns the request a unique ID. - * - * **Do NOT override** this method in sub-classes; instead override {@link JsonRpcApiProvider._send | **_send**} or - * force the options values in the call to the constructor to modify this method's behavior. - * - * @param {string} method - The method to call. - * @param {any[] | Record} params - The parameters to pass to the method. - * @param {Shard} shard - The shard to send the request to. - * @param {boolean} now - If true, the request will be sent immediately. - * @returns {Promise} A promise that resolves to the result of the method call. - */ - send(method, params, shard, now) { - const continueSend = () => { - if (this.destroyed) { - return Promise.reject(makeError('provider destroyed; cancelled request', 'UNSUPPORTED_OPERATION', { operation: method })); - } - const id = this.#nextId++; - const promise = new Promise((resolve, reject) => { - this.#payloads.push({ - resolve, - reject, - payload: { method, params, id, jsonrpc: '2.0' }, - shard: shard, - now: now, - }); - }); - // If there is not a pending drainTimer, set one - this.#scheduleDrain(); - return promise; - }; - // @TODO: cache chainId?? purge on switch_networks - // We have been destroyed; no operations are supported anymore - if (method !== 'quai_listRunningChains') { - return this.initPromise.then(() => { - return continueSend(); - }); - } - else { - return continueSend(); - } - } - /** - * Returns a JsonRpcSigner for the given address. - * - * @param {number | string} [address] - The address or index of the account. - * @returns {Promise} A promise that resolves to the JsonRpcSigner. - * @throws {Error} If the account is invalid. - */ - async getSigner(address) { - if (address == null) { - address = 0; - } - const accountsPromise = this.send('quai_accounts', []); - // Account index - if (typeof address === 'number') { - const accounts = await accountsPromise; - if (address >= accounts.length) { - throw new Error('no such account'); - } - return new JsonRpcSigner(this, accounts[address]); - } - const { accounts } = await resolveProperties({ - network: this.getNetwork(), - accounts: accountsPromise, - }); - // Account address - address = getAddress(address); - for (const account of accounts) { - if (getAddress(account) === address) { - return new JsonRpcSigner(this, address); - } - } - throw new Error('invalid account'); - } - /** - * Returns a list of JsonRpcSigners for all accounts. - * - * @returns {Promise} A promise that resolves to an array of JsonRpcSigners. - */ - async listAccounts() { - const accounts = await this.send('quai_accounts', []); - return accounts.map((a) => new JsonRpcSigner(this, a)); - } - /** - * Destroys the provider, stopping all processing and canceling all pending requests. - */ - destroy() { - // Stop processing requests - if (this.#drainTimer) { - clearTimeout(this.#drainTimer); - this.#drainTimer = null; - } - // Cancel all pending requests - for (const { payload, reject } of this.#payloads) { - reject(makeError('provider destroyed; cancelled request', 'UNSUPPORTED_OPERATION', { - operation: payload.method, - })); - } - this.#payloads = []; - // Parent clean-up - super.destroy(); - } - } - /** - * The JsonRpcProvider is one of the most common Providers, which performs all operations over HTTP (or HTTPS) requests. - * - * Events are processed by polling the backend for the current block number; when it advances, all block-base events are - * then checked for updates. - * - * @category Providers - */ - class JsonRpcProvider extends JsonRpcApiProvider { - constructor(urls, network, options) { - if (urls == null) { - urls = ['http://localhost:8545']; - } - super(network, options); - if (Array.isArray(urls)) { - urls.forEach((url) => { - this.validateUrl(url); - }); - this.initialize(urls); - } - else if (typeof urls === 'string') { - this.validateUrl(urls); - this.initialize([urls]); - } - else { - this.validateUrl(urls.url); - this.initialize(urls.clone()); - } - } - _getSubscriber(sub) { - const subscriber = super._getSubscriber(sub); - return subscriber; - } - _getConnection(shard) { - if (this._initFailed) { - throw new Error('Provider failed to initialize on creation. Run initUrlMap or create a new provider.'); - } - let connection; - if (shard !== undefined) { - connection = this._urlMap.get(shard) ?? this.connect[this.connect.length - 1].clone(); - } - else { - connection = this.connect[this.connect.length - 1].clone(); - } - return new FetchRequest(connection.url); - } - async send(method, params, shard, now) { - // All requests are over HTTP, so we can just start handling requests - // We do this here rather than the constructor so that we don't send any - // requests to the network (i.e. quai_chainId) until we absolutely have to. - await this._start(); - return await super.send(method, params, shard, now); - } - async _send(payload, shard) { - // Configure a POST connection for the requested method - const request = this._getConnection(shard); - request.body = JSON.stringify(payload); - request.setHeader('content-type', 'application/json'); - const response = await request.send(); - response.assertOk(); - let resp = response.bodyJson; - if (!Array.isArray(resp)) { - resp = [resp]; - } - return resp; - } - } - function spelunkData(value) { - if (value == null) { - return null; - } - // These *are* the droids we're looking for. - if (typeof value.message === 'string' && value.message.match(/revert/i) && isHexString(value.data)) { - return { message: value.message, data: value.data }; - } - // Spelunk further... - if (typeof value === 'object') { - for (const key in value) { - const result = spelunkData(value[key]); - if (result) { - return result; - } - } - return null; - } - // Might be a JSON string we can further descend... - if (typeof value === 'string') { - try { - return spelunkData(JSON.parse(value)); - // eslint-disable-next-line no-empty - } - catch (error) { } - } - return null; - } - function _spelunkMessage(value, result) { - if (value == null) { - return; - } - // These *are* the droids we're looking for. - if (typeof value.message === 'string') { - result.push(value.message); - } - // Spelunk further... - if (typeof value === 'object') { - for (const key in value) { - _spelunkMessage(value[key], result); - } - } - // Might be a JSON string we can further descend... - if (typeof value === 'string') { - try { - return _spelunkMessage(JSON.parse(value), result); - // eslint-disable-next-line no-empty - } - catch (error) { } - } - } - function spelunkMessage(value) { - const result = []; - _spelunkMessage(value, result); - return result; - } - - // A = Arguments to the constructor - // I = Interface of deployed contracts - /** - * A **ContractFactory** is used to deploy a Contract to the blockchain. - * - * @category Contract - */ - class ContractFactory { - /** - * The Contract Interface. - */ - interface; - /** - * The Contract deployment bytecode. Often called the initcode. - */ - bytecode; - /** - * The ContractRunner to deploy the Contract as. - */ - runner; - /** - * Create a new **ContractFactory** with `abi` and `bytecode`, optionally connected to `runner`. - * - * The `bytecode` may be the `bytecode` property within the standard Solidity JSON output. - */ - constructor(abi, bytecode, runner) { - const iface = Interface.from(abi); - // Dereference Solidity bytecode objects and allow a missing `0x`-prefix - if (bytecode instanceof Uint8Array) { - bytecode = hexlify(getBytes(bytecode)); - } - else { - if (typeof bytecode === 'object') { - bytecode = bytecode.object; - } - if (!bytecode.startsWith('0x')) { - bytecode = '0x' + bytecode; - } - bytecode = hexlify(getBytes(bytecode)); - } - defineProperties(this, { - bytecode, - interface: iface, - runner: runner || null, - }); - } - attach(target) { - return new BaseContract(target, this.interface, this.runner); - } - /** - * Resolves to the transaction to deploy the contract, passing `args` into the constructor. - * - * @param {ContractMethods} args - The arguments to the constructor. - * @returns {Promise} A promise resolving to the deployment transaction. - */ - async getDeployTransaction(...args) { - let overrides; - const fragment = this.interface.deploy; - if (fragment.inputs.length + 1 === args.length) { - overrides = await copyOverrides(args.pop()); - const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); - const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); - return Object.assign({}, overrides, { data }); - } - if (fragment.inputs.length !== args.length) { - throw new Error('incorrect number of arguments to constructor'); - } - const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); - const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]); - const from = args.pop()?.from || undefined; - return Object.assign({}, from, { data }); - } - /** - * Resolves to the Contract deployed by passing `args` into the constructor. - * - * This will resovle to the Contract before it has been deployed to the network, so the - * [baseContract.waitForDeployment](../classes/BaseContract#waitForDeployment) should be used before sending any - * transactions to it. - * - * @param {ContractMethods} args - The arguments to the constructor. - * @returns {Promise< - * BaseContract & { deploymentTransaction(): ContractTransactionResponse } & Omit - * >} - * A promise resolving to the Contract. - */ - async deploy(...args) { - const tx = await this.getDeployTransaction(...args); - assert(this.runner && typeof this.runner.sendTransaction === 'function', 'factory runner does not support sending transactions', 'UNSUPPORTED_OPERATION', { - operation: 'sendTransaction', - }); - if (this.runner instanceof Wallet || this.runner instanceof JsonRpcSigner) { - validateAddress(this.runner.address); - tx.from = this.runner.address; - } - const grindedTx = await this.grindContractAddress(tx); - const sentTx = await this.runner.sendTransaction(grindedTx); - const address = getStatic(this.constructor, 'getContractAddress')?.(tx); - return new BaseContract(address, this.interface, this.runner, sentTx); - } - static getContractAddress(transaction) { - return getContractAddress(transaction.from, BigInt(transaction.nonce), // Fix: Convert BigInt to bigint - transaction.data); - } - async grindContractAddress(tx) { - if (tx.nonce == null && tx.from) { - tx.nonce = await this.runner?.provider?.getTransactionCount(tx.from); - } - const sender = String(tx.from); - const toShard = getZoneForAddress(sender); - let i = 0; - const startingData = tx.data; - while (i < 10000) { - const contractAddress = getContractAddress(sender, BigInt(tx.nonce || 0), tx.data || ''); - const contractShard = getZoneForAddress(contractAddress); - const utxo = isQiAddress(contractAddress); - if (contractShard === toShard && !utxo) { - return tx; - } - const salt = randomBytes(32); - tx.data = hexlify(concat([String(startingData), salt])); - i++; - } - return tx; - } - /** - * Return a new **ContractFactory** with the same ABI and bytecode, but connected to `runner`. - * - * @param {ContractRunner} runner - The runner to connect to. - * @returns {ContractFactory} A new ContractFactory. - */ - connect(runner) { - return new ContractFactory(this.interface, this.bytecode, runner); - } - /** - * Create a new **ContractFactory** from the standard Solidity JSON output. - * - * @param {any} output - The Solidity JSON output. - * @param {ContractRunner} runner - The runner to connect to. - * @returns {ContractFactory} A new ContractFactory. - */ - static fromSolidity(output, runner) { - assertArgument(output != null, 'bad compiler output', 'output', output); - if (typeof output === 'string') { - output = JSON.parse(output); - } - const abi = output.abi; - let bytecode = ''; - if (output.bytecode) { - bytecode = output.bytecode; - } - else if (output.evm && output.evm.bytecode) { - bytecode = output.evm.bytecode; - } - return new this(abi, bytecode, runner); - } - } - - /** - * A **BrowserProvider** is intended to wrap an injected provider which adheres to the - * [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) standard, which most (if not all) currently do. - * - * @category Providers - * @class - * @extends JsonRpcApiProvider - */ - class BrowserProvider extends JsonRpcApiProvider { - #request; - /** - * Connect to the `ethereum` provider, optionally forcing the `network`. - * - * @class - * @param {Eip1193Provider} ethereum - The EIP-1193 provider. - * @param {Networkish} [network] - The network to connect to. - */ - constructor(ethereum, network) { - super(network, { batchMaxCount: 1 }); - this.#request = async (method, params) => { - const payload = { method, params }; - this.emit('debug', undefined, { action: 'sendEip1193Request', payload }); - try { - const result = await ethereum.request(payload); - this.emit('debug', undefined, { action: 'receiveEip1193Result', result }); - return result; - } - catch (e) { - const error = new Error(e.message); - error.code = e.code; - error.data = e.data; - error.payload = payload; - this.emit('debug', undefined, { action: 'receiveEip1193Error', error }); - throw error; - } - }; - } - /** - * Resolves to `true` if the provider manages the `address`. - * - * @param {number | string} address - The address to check. - * @returns {Promise} Resolves to `true` if the provider manages the `address`. - */ - async hasSigner(address) { - if (address == null) { - address = 0; - } - const accounts = await this.send('quai_accounts', []); - if (typeof address === 'number') { - return accounts.length > address; - } - address = address.toLowerCase(); - return accounts.filter((a) => a.toLowerCase() === address).length !== 0; - } - /** - * Sends a JSON-RPC request. - * - * @param {string} method - The method name. - * @param {any[] | Record} params - The parameters for the method. - * @returns {Promise} The result of the request. - */ - async send(method, params) { - await this._start(); - return await super.send(method, params); - } - /** - * Sends a JSON-RPC payload. - * - * @ignore - * @ignore - * @param {JsonRpcPayload | JsonRpcPayload[]} payload - The JSON-RPC payload. - * @returns {Promise<(JsonRpcResult | JsonRpcError)[]>} The result of the request. - */ - async _send(payload) { - assertArgument(!Array.isArray(payload), 'EIP-1193 does not support batch request', 'payload', payload); - try { - const result = await this.#request(payload.method, payload.params || []); - return [{ id: payload.id, result }]; - } - catch (e) { - return [ - { - id: payload.id, - error: { code: e.code, data: e.data, message: e.message }, - }, - ]; - } - } - /** - * Gets the RPC error. - * - * @param {JsonRpcPayload} payload - The JSON-RPC payload. - * @param {JsonRpcError} error - The JSON-RPC error. - * @returns {Error} The RPC error. - */ - getRpcError(payload, error) { - error = JSON.parse(JSON.stringify(error)); - // EIP-1193 gives us some machine-readable error codes, so rewrite - // them into - switch (error.error.code || -1) { - case 4001: - error.error.message = `quais-user-denied: ${error.error.message}`; - break; - case 4200: - error.error.message = `quais-unsupported: ${error.error.message}`; - break; - } - return super.getRpcError(payload, error); - } - /** - * Gets the signer for the given address. - * - * @param {number | string} [address] - The address to get the signer for. - * @returns {Promise} The signer for the address. - */ - async getSigner(address) { - if (address == null) { - address = 0; - } - if (!(await this.hasSigner(address))) { - try { - await this.#request('quai_requestAccounts', []); - } - catch (error) { - const payload = error.payload; - throw this.getRpcError(payload, { id: payload.id, error }); - } - } - return await super.getSigner(address); - } - } - - /** - * A **SocketSubscriber** uses a socket transport to handle events and should use - * {@link SocketSubscriber._emit | **_emit**} to manage the events. - * - * - A sub-class MUST call the `_start()` method once connected - * - A sub-class MUST override the `_write(string)` method - * - A sub-class MUST call `_processMessage(string)` for each message - * - * @category Providers - */ - class SocketSubscriber { - #provider; - #filter; - /** - * The filter. - * - * @type {any[]} - */ - get filter() { - return JSON.parse(this.#filter); - } - #filterId; - #paused; - #emitPromise; - zone; - shard; - /** - * Creates a new **SocketSubscriber** attached to `provider` listening to `filter`. - * - * @param {SocketProvider} provider - The socket provider. - * @param {any[]} filter - The filter. - */ - constructor(provider, filter, zone) { - this.#provider = provider; - this.#filter = JSON.stringify(filter); - this.#filterId = null; - this.#paused = null; - this.#emitPromise = null; - this.zone = zone; - this.shard = toShard(zone); - } - /** - * Start the subscriber. - */ - start() { - this.#filterId = this.#provider.send('quai_subscribe', this.filter, this.shard).then((filterId) => { - this.#provider._register(filterId, this); - return filterId; - }); - } - /** - * Stop the subscriber. - */ - stop() { - this.#filterId.then((filterId) => { - this.#provider.send('quai_unsubscribe', [filterId], this.shard); - }); - this.#filterId = null; - } - /** - * Pause the subscriber. - * - * @param {boolean} [dropWhilePaused] - Whether to drop logs while paused. - */ - pause(dropWhilePaused) { - assert(dropWhilePaused, 'preserve logs while paused not supported by SocketSubscriber yet', 'UNSUPPORTED_OPERATION', { operation: 'pause(false)' }); - this.#paused = !!dropWhilePaused; - } - /** - * Resume the subscriber. - */ - resume() { - this.#paused = null; - } - /** - * Handle incoming messages. - * - * @ignore - * @param {any} message - The message to handle. - */ - _handleMessage(message) { - if (this.#filterId == null) { - return; - } - if (this.#paused === null) { - let emitPromise = this.#emitPromise; - if (emitPromise == null) { - emitPromise = this._emit(this.#provider, message); - } - else { - emitPromise = emitPromise.then(async () => { - await this._emit(this.#provider, message); - }); - } - this.#emitPromise = emitPromise.then(() => { - if (this.#emitPromise === emitPromise) { - this.#emitPromise = null; - } - }); - } - } - /** - * Sub-classes **must** override this to emit the events on the provider. - * - * @abstract - * @param {SocketProvider} provider - The socket provider. - * @param {any} message - The message to emit. - * @returns {Promise} - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _emit(provider, message) { - throw new Error('sub-classes must implement this; _emit'); - } - } - /** - * A **SocketBlockSubscriber** listens for `newHeads` events and emits `"block"` events. - * - * @category Providers - */ - class SocketBlockSubscriber extends SocketSubscriber { - /** - * Creates a new **SocketBlockSubscriber**. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - */ - constructor(provider, zone) { - super(provider, ['newHeads'], zone); - } - /** - * Emit the block event. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - * @param {any} message - The message to emit. - * @returns {Promise} - */ - async _emit(provider, message) { - provider.emit('block', this.zone, parseInt(message.woHeader.number)); - } - } - /** - * A **SocketPendingSubscriber** listens for pending transactions and emits `"pending"` events. - * - * @category Providers - */ - class SocketPendingSubscriber extends SocketSubscriber { - /** - * Creates a new **SocketPendingSubscriber**. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - */ - constructor(provider, zone) { - super(provider, ['newPendingTransactions'], zone); - } - /** - * Emit the pending event. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - * @param {any} message - The message to emit. - * @returns {Promise} - */ - async _emit(provider, message) { - provider.emit('pending', message); - } - } - /** - * A **SocketEventSubscriber** listens for event logs. - * - * @category Providers - */ - class SocketEventSubscriber extends SocketSubscriber { - #logFilter; - /** - * The filter. - * - * @type {EventFilter} - */ - get logFilter() { - return JSON.parse(this.#logFilter); - } - /** - * Creates a new **SocketEventSubscriber**. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - * @param {EventFilter} filter - The event filter. - */ - constructor(provider, filter, zone) { - super(provider, ['logs', filter], zone); - this.#logFilter = JSON.stringify(filter); - } - /** - * Emit the event log. - * - * @ignore - * @param {SocketProvider} provider - The socket provider. - * @param {any} message - The message to emit. - * @returns {Promise} - */ - async _emit(provider, message) { - provider.emit(this.logFilter, this.zone, provider._wrapLog(message, provider._network)); - } - } - /** - * A **SocketProvider** is backed by a long-lived connection over a socket, which can subscribe and receive real-time - * messages over its communication channel. - * - * @category Providers - */ - class SocketProvider extends JsonRpcApiProvider { - #callbacks; - // Maps each filterId to its subscriber - #subs; - // If any events come in before a subscriber has finished - // registering, queue them - #pending; - /** - * Creates a new **SocketProvider** connected to `network`. - * - * If unspecified, the network will be discovered. - * - * @param {Networkish} [network] - The network to connect to. - * @param {JsonRpcApiProviderOptions} [_options] - The options for the provider. - */ - constructor(network, _options) { - // Copy the options - const options = Object.assign({}, _options != null ? _options : {}); - // Support for batches is generally not supported for - // connection-base providers; if this changes in the future - // the _send should be updated to reflect this - assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1, 'sockets-based providers do not support batches', 'options.batchMaxCount', _options); - options.batchMaxCount = 1; - // Socket-based Providers (generally) cannot change their network, - // since they have a long-lived connection; but let people override - // this if they have just cause. - if (options.staticNetwork == null) { - options.staticNetwork = true; - } - super(network, options); - this.#callbacks = new Map(); - this.#subs = new Map(); - this.#pending = new Map(); - } - /** - * Get the subscriber for a given subscription. - * - * @ignore - * @param {Subscription} sub - The subscription. - * @returns {Subscriber} The subscriber. - */ - _getSubscriber(sub) { - switch (sub.type) { - case 'close': - return new UnmanagedSubscriber('close'); - case 'block': - return new SocketBlockSubscriber(this, sub.zone); - case 'pending': - return new SocketPendingSubscriber(this, sub.zone); - case 'event': - return new SocketEventSubscriber(this, sub.filter, sub.zone); - case 'orphan': - // Handled auto-matically within AbstractProvider - // when the log.removed = true - if (sub.filter.orphan === 'drop-log') { - return new UnmanagedSubscriber('drop-log'); - } - } - return super._getSubscriber(sub); - } - /** - * Register a new subscriber. This is used internally by Subscribers and generally is unnecessary unless extending - * capabilities. - * - * @ignore - * @param {number | string} filterId - The filter ID. - * @param {SocketSubscriber} subscriber - The subscriber. - */ - _register(filterId, subscriber) { - this.#subs.set(filterId, subscriber); - const pending = this.#pending.get(filterId); - if (pending) { - for (const message of pending) { - subscriber._handleMessage(message); - } - this.#pending.delete(filterId); - } - } - /** - * Send a JSON-RPC payload. - * - * @ignore - * @param {JsonRpcPayload | JsonRpcPayload[]} payload - The payload to send. - * @param {Shard} [shard] - The shard. - * @param {boolean} [now] - Whether to send immediately. - * @returns {Promise<(JsonRpcResult | JsonRpcError)[]>} The result or error. - */ - async _send(payload, shard, now) { - if (this._initFailed) { - console.log('Provider failed to initialize on creation. Run initialize or create a new provider.'); - return [ - { - id: Array.isArray(payload) ? payload[0].id : payload.id, - error: { - code: -32000, - message: 'Provider failed to initialize on creation. Run initialize or create a new provider.', - }, - }, - ]; - } - // WebSocket provider doesn't accept batches - assertArgument(!Array.isArray(payload), 'WebSocket does not support batch send', 'payload', payload); - // @TODO: stringify payloads here and store to prevent mutations - // Prepare a promise to respond to - const promise = new Promise((resolve, reject) => { - this.#callbacks.set(payload.id, { payload, resolve, reject }); - }); - // Wait until the socket is connected before writing to it - try { - if (!now) { - await this._waitUntilReady(); - } - } - catch (error) { - this.#callbacks.delete(payload.id); - return [ - { - id: Array.isArray(payload) ? payload[0].id : payload.id, - error: { - code: -32000, - message: 'Provider failed to initialize on creation. Run initialize or create a new provider.', - }, - }, - ]; - } - // Write the request to the socket - await this._write(JSON.stringify(payload), shard); - return [await promise]; - } - /** - * Sub-classes **must** call this with messages received over their transport to be processed and dispatched. - * - * @ignore - * @param {string} message - The message to process. - */ - async _processMessage(message) { - const result = JSON.parse(message); - if (result && typeof result === 'object' && 'id' in result) { - const callback = this.#callbacks.get(result.id); - if (callback == null) { - this.emit('error', undefined, makeError('received result for unknown id', 'UNKNOWN_ERROR', { - reasonCode: 'UNKNOWN_ID', - result, - })); - return; - } - this.#callbacks.delete(result.id); - callback.resolve(result); - } - else if (result && result.method === 'quai_subscription') { - const filterId = result.params.subscription; - const subscriber = this.#subs.get(filterId); - if (subscriber) { - subscriber._handleMessage(result.params.result); - } - else { - let pending = this.#pending.get(filterId); - if (pending == null) { - pending = []; - this.#pending.set(filterId, pending); - } - pending.push(result.params.result); - } - } - else { - this.emit('error', undefined, makeError('received unexpected message', 'UNKNOWN_ERROR', { - reasonCode: 'UNEXPECTED_MESSAGE', - result, - })); - return; - } - } - /** - * Sub-classes **must** override this to send `message` over their transport. - * - * @ignore - * @param {string} message - The message to send. - * @param {Shard} [shard] - The shard. - * @returns {Promise} - */ - // eslint-disable-next-line @typescript-eslint/no-unused-vars - async _write(message, shard) { - throw new Error('sub-classes must override this'); - } - validateUrl(url) { - const urlPattern = /^(ws):\/\/[a-zA-Z0-9.-]+(:\d+)?$/; - if (!urlPattern.test(url)) { - let errorMessage = 'Invalid URL: '; - if (!/^ws:\/\//.test(url)) { - errorMessage += 'URL must start with ws://. '; - } - if (url.endsWith('/')) { - errorMessage += 'URL should not end with a /. '; - } - if (/\/[^/]+/.test(url)) { - errorMessage += 'URL should not contain a path, query string, or fragment. '; - } - throw new Error(errorMessage.trim()); - } - } - } - - function getGlobal() { - if (typeof self !== 'undefined') { - return self; - } - if (typeof window !== 'undefined') { - return window; - } - if (typeof global !== 'undefined') { - return global; - } - throw new Error('unable to locate global object'); - } - const _WebSocket = getGlobal().WebSocket; - - /** - * A JSON-RPC provider which is backed by a WebSocket. - * - * WebSockets are often preferred because they retain a live connection to a server, which permits more instant access - * to events. - * - * However, this incurs higher server infrastructure costs, so additional resources may be required to host your own - * WebSocket nodes and many third-party services charge additional fees for WebSocket endpoints. - * - * @category Providers - * @extends SocketProvider - */ - class WebSocketProvider extends SocketProvider { - #websockets; - /** - * A map to track the readiness of each shard. - * - * @type {Map} - */ - readyMap = new Map(); - /** - * Get the array of WebSocketLike objects. - * - * @returns {WebSocketLike[]} The array of WebSocketLike objects. - * @throws {Error} If the websocket is closed. - */ - get websocket() { - if (this.#websockets == null) { - throw new Error('websocket closed'); - } - return this.#websockets; - } - /** - * Create a new WebSocketProvider. - * - * @param {string | string[] | WebSocketLike | WebSocketCreator} url - The URL(s) or WebSocket object or creator. - * @param {Networkish} [network] - The network to connect to. - * @param {JsonRpcApiProviderOptions} [options] - The options for the JSON-RPC API provider. - */ - constructor(url, network, options) { - super(network, options); - this.#websockets = []; - if (typeof url === 'string') { - this.validateUrl(url); - } - else if (Array.isArray(url)) { - url.forEach((it) => this.validateUrl(it)); - } - else if (typeof url === 'function') { - this.validateUrl(url().url); - } - else { - this.validateUrl(url.url); - } - this.initialize(typeof url === 'string' ? [url] : url); - } - /** - * Initialize a WebSocket connection for a shard. - * - * @ignore - * @param {WebSocketLike} websocket - The WebSocket object. - * @param {Shard} shard - The shard identifier. - */ - initWebSocket(websocket, shard) { - websocket.onerror = (error) => { - console.log('WebsocketProvider error', error); - websocket.close(); - }; - websocket.onopen = async () => { - try { - await this._start(); - this.resume(); - this.readyMap.set(shard, true); - } - catch (error) { - console.log('failed to start WebsocketProvider', error); - this.readyMap.set(shard, false); - // @TODO: now what? Attempt reconnect? - } - }; - websocket.onmessage = (message) => { - this._processMessage(message.data); - }; - } - /** - * Wait until the shard is ready. Max wait time is ~8 seconds. - * - * @param {Shard} shard - The shard identifier. - * @returns {Promise} A promise that resolves when the shard is ready. - * @throws {Error} If the shard is not ready within the timeout period. - */ - async waitShardReady(shard) { - let count = 0; - while (!this.readyMap.get(shard)) { - await new Promise((resolve) => setTimeout(resolve, Math.pow(2, count))); - if (count > 11) { - throw new Error('Timeout waiting for shard to be ready'); - } - count++; - } - } - /** - * Initialize the URL map with WebSocket connections. - * - * @ignore - * @param {U} urls - The URLs or WebSocket object or creator. - * @returns {Promise} A promise that resolves when the URL map is initialized. - */ - async initialize(urls) { - //clear websockets - this.#websockets = []; - this._urlMap.clear(); - try { - const primeSuffix = this._getOption('usePathing') ? `/${fromShard(exports.Shard.Prime, 'nickname')}` : ':8001'; - const createWebSocket = (baseUrl, suffix) => { - const tempWs = new _WebSocket(`${baseUrl}${suffix}`); - return tempWs; - // wait 2 minutes - }; - const initShardWebSockets = async (baseUrl) => { - const shards = await this._getRunningLocations(exports.Shard.Prime, true); - await Promise.all(shards.map(async (shard) => { - const port = 8200 + 20 * shard[0] + shard[1]; - const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`); - const shardSuffix = this._getOption('usePathing') - ? `/${fromShard(shardEnum, 'nickname')}` - : `:${port}`; - const shardUrl = baseUrl.split(':').slice(0, 2).join(':'); - const websocket = createWebSocket(shardUrl, shardSuffix); - this.initWebSocket(websocket, shardEnum); - this.#websockets.push(websocket); - this._urlMap.set(shardEnum, websocket); - try { - await this.waitShardReady(shardEnum); - } - catch (error) { - console.log('failed to waitShardReady', error); - this._initFailed = true; - } - })); - }; - if (Array.isArray(urls)) { - for (const url of urls) { - const baseUrl = `${url.split(':')[0]}:${url.split(':')[1]}`; - const primeWebsocket = createWebSocket(baseUrl, primeSuffix); - this.initWebSocket(primeWebsocket, exports.Shard.Prime); - this.#websockets.push(primeWebsocket); - this._urlMap.set(exports.Shard.Prime, primeWebsocket); - await this.waitShardReady(exports.Shard.Prime); - await initShardWebSockets(baseUrl); - } - } - else if (typeof urls === 'function') { - const primeWebsocket = urls(); - this.initWebSocket(primeWebsocket, exports.Shard.Prime); - this.#websockets.push(primeWebsocket); - this._urlMap.set(exports.Shard.Prime, primeWebsocket); - await this.waitShardReady(exports.Shard.Prime); - const baseUrl = this.#websockets[0].url.split(':').slice(0, 2).join(':'); - await initShardWebSockets(baseUrl); - } - else { - const primeWebsocket = urls; - this.initWebSocket(primeWebsocket, exports.Shard.Prime); - this.#websockets.push(primeWebsocket); - this._urlMap.set(exports.Shard.Prime, primeWebsocket); - await this.waitShardReady(exports.Shard.Prime); - const baseUrl = primeWebsocket.url.split(':').slice(0, 2).join(':'); - await initShardWebSockets(baseUrl); - } - if (this.initResolvePromise) - this.initResolvePromise(); - } - catch (error) { - this._initFailed = true; - console.log('failed to initialize', error); - //clear websockets - this.#websockets = []; - if (this.initRejectPromise) - this.initRejectPromise(error); - return; - } - } - /** - * Write a message to the WebSocket. - * - * @ignore - * @param {string} message - The message to send. - * @param {Shard} [shard] - The shard identifier. - * @returns {Promise} A promise that resolves when the message is sent. - * @throws {Error} If the WebSocket is closed or the shard is not found. - */ - async _write(message, shard) { - if (this.websocket.length < 1) { - throw new Error('Websocket closed'); - } - if (shard && !this._urlMap.has(shard)) { - throw new Error('Shard not found'); - } - const websocket = shard ? this._urlMap.get(shard) : this.websocket[this.websocket.length - 1]; - if (!websocket) { - throw new Error('Websocket is undefined'); - } - if (shard) { - await this.waitShardReady(shard); - } - websocket.send(message); - } - /** - * Destroy the WebSocket connections and clean up resources. - * - * @returns {Promise} A promise that resolves when the WebSocket connections are closed. - */ - async destroy() { - this.#websockets.forEach((it) => it.close()); - this.#websockets = []; - super.destroy(); - } - } - - const Base64 = ')!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'; - /** - * @ignore - */ - function decodeBits(width, data) { - const maxValue = (1 << width) - 1; - const result = []; - let accum = 0, bits = 0, flood = 0; - for (let i = 0; i < data.length; i++) { - // Accumulate 6 bits of data - accum = (accum << 6) | Base64.indexOf(data[i]); - bits += 6; - // While we have enough for a word... - while (bits >= width) { - // ...read the word - const value = accum >> (bits - width); - accum &= (1 << (bits - width)) - 1; - bits -= width; - // A value of 0 indicates we exceeded maxValue, it - // floods over into the next value - if (value === 0) { - flood += maxValue; - } - else { - result.push(value + flood); - flood = 0; - } - } - } - return result; - } - - /** - * @ignore - */ - function decodeOwlA(data, accents) { - let words = decodeOwl(data).join(','); - // Inject the accents - accents.split(/,/g).forEach((accent) => { - const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); - assertArgument(match !== null, 'internal error parsing accents', 'accents', accents); - let posOffset = 0; - const positions = decodeBits(parseInt(match[3]), match[4]); - const charCode = parseInt(match[2]); - const regex = new RegExp(`([${match[1]}])`, 'g'); - words = words.replace(regex, (all, letter) => { - const rem = --positions[posOffset]; - if (rem === 0) { - letter = String.fromCharCode(letter.charCodeAt(0), charCode); - posOffset++; - } - return letter; - }); - }); - return words.split(','); - } - - /** - * An OWL-A format Wordlist extends the OWL format to add an overlay onto an OWL format Wordlist to support diacritic - * marks. - * - * This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages - * based on latin-1 small. - * - * If necessary, there are tools within the `generation/` folder to create the necessary data. - * - * @category Wordlists - */ - class WordlistOwlA extends WordlistOwl { - #accent; - /** - * Creates a new Wordlist for `locale` using the OWLA `data` and `accent` data and validated against the `checksum`. - */ - constructor(locale, data, accent, checksum) { - super(locale, data, checksum); - this.#accent = accent; - } - /** - * The OWLA-encoded accent data. - * - * @ignore - */ - get _accent() { - return this.#accent; - } - /** - * Decode all the words for the wordlist. - * - * @ignore - */ - _decodeWords() { - return decodeOwlA(this._data, this._accent); - } - } - - const words = "0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_LoAmpuAnc]ApaAr]I>Is)IvoOqueOzaUle%Up 0Cl.EgoE=EnEr#F[G +M->NeN%P_sR>Rue]SneTaU{d2Am^AnA+AseAveI,)ImaInica2B_Cc~|i'Ci`CoDigoDoF_G!He)JinJoL/ch/eg$Lg Lin/l LmoLum`Mba)M!Mi{Mo&Mpr-deNej}g-oc!Nsej}t PaPi(az.Rba%RchoR&nR.(r!S!SmosS%2AneoAt!E Ec!Ei&EmaIaIm,Ip%IsisOmoOnicaOque%U&Uz2Ad+Ar#At+BoBr*| aEl=En#Er{Es%EvaId Lebr/p/#Mb_Mpl*N-e%O%P.Pul( R$Se'Sf[zVaVi'5BleCeL^Ming}N Ra&Rm*RAu%EchaOrO%U*UjoU^2B@CaGa%G.L$Lle#N&Rm(+Rtun(z SaTo2AcaA'AsaAtisAveIe%Il=IpeIsI#OG Gu!aJaMb_Ng}^Nr((mig('St?Yo5E>ElgaEr%ENgl-$Nt Pit!R S#V,?Zg :7Lo5A]:B$C$C[DoD+nG #GrimaGu`I>M!Mi`Mp --ch-gos%NzaPizRgoRvaStimaTaTexT*U_lV Zo3AlCc~|eC#rErG~Gumb_Ja'Ngu-#NaOnOp &S~TalT[VeY,{3B!%dB+C^D!Di EnzoGaG!oMaMi)M.Mp$NceN&Ne-go)N}t!`Qui&SoS%T!aT$T+2AgaAmaAn#AveEg En Ev Or Ov!Uv@2BoC~CoCu[GicaG+MbrizM}jaTe5|aC*G J}-esPaSt+ToZ:Ce%|oD!aD_Du+Est+F@G@GoIzL{dLe%Ll/oMaMboMutN>N&Nej Ng-iquiNj N}Re(f?Rg,Ri&RmolR+nR)sRzoSaSc aSivoT T!@TizTrizXimoY^Z^ca3|aDal]D$Du]J?]J^L,/.M^i-^NsajeN)NuRca&R,gueRi#SS.TaT!To&T+Zc]3E&ElEmb+G/Lag+Lit Ll.M}-!}im}u#OpeR SaS!@S?SmoTadTo5|?aC~DaDe=HoJ LdeL!Li'M,#Mi- c-ed-j-#NoRad(d!Re'R*R+Rs(%lScaStr TivoV!V?Zo5|oD EbleE]Er)Est[G_J!L/e%L%N&Nec(alRoScu=SeoSgoSicaS=:C C~D IpeRanj(izRr SalTalTivoTu[lUseaValVeVi{d3C$Ct G Goc$G+OnRv$ToUt+V V!a3|oDoEb]E#NezNoTi&Vel5Bleza|eMin(i(m()TaTic@Va#Ve]V$5BeCaCleoD?=DoE[EveEzLoM!oTr@:Sis0EC~E[In On!T TicaUes#1Ac~A&rAlBi%CaD,EjaGa'G@Gul=I,)Ig,Il]OQues%Uga0Ad@Cu+Ez'OT[0O'Ro1EjaU=1I&Ige'0En)0O':C#D_El]Gi`GoIsJ oLabr/>Le%Li&Lm/om/p NNalNi>Nt!-ue=PaPelP?]Que)R Rcel(edR*RoRpa&RqueR[foR)S SeoS~SoS%TaT$Tr@UsaU%VoYa<3A#nCa&C!a|oDalD*G IneL L{'Le/ig+LlejoLoLuc--s N.OnOrPi'Que'R(ch(d!Rez(f?Ri>Rl(mizEgun%Em$EnsaE|!oD^Eb=Er%Es#Lg/*Lm.LpoLrNd*N%P #Pet*PoN{PaP!oSaScaSt+T 5BiB^DoE{G*I&In/e%LoMboM^Ptu[TaTi`:Ba&B!B$BleC GazG[&L/&L!oL*Lm.L.Ls/#LudLv Mb-c~Ndi-e Ng_Ni{dN}#PoQueRdin()nSt_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv! 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 values resolved.\n *\n * @category Utils\n * @param {Object} value - The object to resolve.\n *\n * @returns {Promise} The resolved object.\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// Crawl up the constructor chain to find a static method\nexport function getStatic(ctor, key) {\n for (let i = 0; i < 32; i++) {\n if (ctor[key]) {\n return ctor[key];\n }\n if (!ctor.prototype || typeof ctor.prototype !== 'object') {\n break;\n }\n ctor = Object.getPrototypeOf(ctor.prototype).constructor;\n }\n return null;\n}\n/**\n * Assigns the `values` to `target` as read-only values.\n *\n * It `types` is specified, the values are checked.\n *\n * @category Utils\n * @param {Object} target - The target object to assign to.\n * @param {Object} values - The values to assign.\n * @param {Object} types - The types to check.\n */\nexport function defineProperties(target, values, types) {\n for (const key in values) {\n const 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 quais include properties to ensure they are both human-readable (i.e. `.message`) and machine-readable\n * (i.e. `.code`).\n *\n * The {@link isError | **isError**} function can be used to check the error `code` and provide a type guard for the\n * properties present on that error interface.\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 quais that matches the error `code`.\n *\n * In TypeScript environments, this can be used to check that `error` matches an quaisError type, which means the\n * expected properties will be set.\n *\n * @category Utils\n * @example\n *\n * ```ts\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 * ```\n *\n * @see [ErrorCodes](api:ErrorCode)\n */\nexport function isError(error, code) {\n return error && error.code === code;\n}\n/**\n * Returns true if `error` is a {@link CallExceptionError | **CallExceptionError**}.\n *\n * @category Utils\n */\nexport function isCallException(error) {\n return isError(error, 'CALL_EXCEPTION');\n}\n/**\n * Returns a new Error configured to the format quais emits errors, with the `message`, {@link ErrorCode | **ErrorCode**}\n * `code` and additional properties for the corresponding quaisError.\n *\n * Each error in quais includes the version of quais, a machine-readable {@link ErrorCode | **ErrorCode**}, and depending\n * on `code`, additional required properties. The error message will also include the `message`, quais version, `code`\n * and all additional properties, serialized.\n *\n * @category Utils\n * @param {string} message - The error message.\n * @param {ErrorCode} code - The error code.\n * @param {ErrorInfo} [info] - Additional properties for the error.\n * @returns {T} The new error.\n */\nexport function makeError(message, code, info) {\n const 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 details.push(key + '=' + stringify(value));\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 quaisError with `message`, `code` and additional error `info` when `check` is falsish..\n *\n * @category Utils\n * @param {unknown} check - The value to check.\n * @param {string} message - The error message.\n * @param {ErrorCode} code - The error code.\n * @param {ErrorInfo} [info] - Additional properties for the error.\n * @throws {T} Throws the error if `check` is falsish.\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 constraints, throwing if not.\n *\n * In TypeScript environments, the `check` has been asserted true, so any further code does not need additional\n * compile-time checks.\n *\n * @category Utils\n * @param {unknown} check - The value to check.\n * @param {string} message - The error message.\n * @param {string} name - The name of the argument.\n * @param {unknown} value - The value of the argument.\n * @throws {InvalidArgumentError} Throws if `check` is falsish.\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 arguemnts' + 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 /* 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 // eslint-disable-next-line no-empty\n }\n catch (error) { }\n return accum;\n}, []);\n/**\n * Throws if the normalization `form` is not supported.\n *\n * @category Utils\n * @param {string} form - The normalization form.\n * @throws {UnsupportedOperationError} Throws if the 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',\n info: { form },\n });\n}\n/**\n * Many classes use file-scoped values to guard the constructor, making it effectively private. This facilitates that\n * pattern by ensuring the `givenGuard` matches the file-scoped `guard`, throwing if not, indicating the `className%% if\n * provided.\n *\n * @category Utils\n * @param {any} givenGuard - The guard provided to the constructor.\n * @param {any} guard - The file-scoped guard.\n * @param {string} [className] - The class name.\n * @throws {UnsupportedOperationError} Throws if the guards do not match.\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 */\nimport { assert, assertArgument } from './errors.js';\n/**\n * Converts a BytesLike value to a Uint8Array.\n *\n * @ignore\n * @category Utils\n * @param {BytesLike} value - The value to convert.\n * @param {string} [name] - The name of the value for error context.\n * @param {boolean} [copy] - Whether to create a copy of the value.\n *\n * @returns {Uint8Array} The converted Uint8Array.\n * @throws {Error} If the value is not a valid BytesLike.\n */\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 the original `value` is returned; if a copy is required\n * use {@link getBytesCopy | **getBytesCopy**}.\n *\n * @category Utils\n * @param {BytesLike} value - The value to convert to a Uint8Array.\n * @param {string} [name] - The name of the value for error context.\n *\n * @returns {Uint8Array} The typed Uint8Array.\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 to prevent any modifications of the returned value\n * from being reflected elsewhere.\n *\n * @category Utils\n * @param {BytesLike} value - The value to convert to a Uint8Array.\n * @param {string} [name] - The name of the value for error context.\n *\n * @returns {Uint8Array} The typed Uint8Array.\n */\nexport function getBytesCopy(value, name) {\n return _getBytes(value, name, true);\n}\n/**\n * Returns true if `value` is a valid {@link HexString | **HexString**}.\n *\n * If `length` is `true` or a number, it also checks that `value` is a valid {@link DataHexString | **DataHexString**} of\n * `length` (if a number) bytes of data (e.g. `0x1234` is 2 bytes).\n *\n * @category Utils\n * @param {any} value - The value to check.\n * @param {number | boolean} [length] - The expected length of the data.\n *\n * @returns {boolean} True if the value is a valid {@link HexString | **HexString**}.\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 data (i.e. a valid\n * {@link DataHexString | **DataHexString**} or a Uint8Array).\n *\n * @category Utils\n * @param {any} value - The value to check.\n *\n * @returns {boolean} True if the value is a valid {@link DataHexString | **DataHexString**}.\n */\nexport function isBytesLike(value) {\n return isHexString(value, true) || value instanceof Uint8Array;\n}\nconst HexCharacters = '0123456789abcdef';\n/**\n * Returns a {@link DataHexString | **DataHexString**} representation of `data`.\n *\n * @category Utils\n * @param {BytesLike} data - The data to convert to a hex string.\n *\n * @returns {string} The hex string.\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 {@link DataHexString | **DataHexString** } by concatenating all values within `data`.\n *\n * @category Utils\n * @param {ReadonlyArray} datas - The data to concatenate.\n *\n * @returns {string} The concatenated 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 *\n * @category Utils\n * @param {BytesLike} data - The data to get the length of.\n *\n * @returns {number} The length of the data.\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 {@link DataHexString | **DataHexString** } by slicing `data` from the `start` offset to the `end` offset.\n *\n * By default `start` is 0 and `end` is the length of `data`.\n *\n * @category Utils\n * @param {BytesLike} data - The data to slice.\n * @param {number} [start] - The start offset.\n * @param {number} [end] - The end offset.\n *\n * @returns {string} The sliced data.\n * @throws {Error} If the end offset is beyond the data bounds.\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,\n length: bytes.length,\n offset: end,\n });\n }\n return hexlify(bytes.slice(start == null ? 0 : start, end == null ? bytes.length : end));\n}\n/**\n * Return the {@link DataHexString | **DataHexString**} result by stripping all **leading** zero bytes from `data`.\n *\n * @category Utils\n * @param {BytesLike} data - The data to strip.\n *\n * @returns {string} The stripped 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}\n/**\n * Pads the data to the specified length.\n *\n * @ignore\n * @category Utils\n * @param {BytesLike} data - The data to pad.\n * @param {number} length - The length to pad to.\n * @param {boolean} left - Whether to pad on the left.\n *\n * @returns {string} The padded data.\n * @throws {Error} If the padding exceeds data length.\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 {@link DataHexString | **DataHexString**} of `data` padded on the **left** to `length` bytes.\n *\n * If `data` already exceeds `length`, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown.\n *\n * This pads data the same as **values** are in Solidity (e.g. `uint128`).\n *\n * @category Utils\n * @param {BytesLike} data - The data to pad.\n * @param {number} length - The length to pad to.\n *\n * @returns {string} The padded data.\n */\nexport function zeroPadValue(data, length) {\n return zeroPad(data, length, true);\n}\n/**\n * Return the {@link DataHexString | **DataHexString**} of `data` padded on the **right** to `length` bytes.\n *\n * If `data` already exceeds %%length%%, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown.\n *\n * This pads data the same as **bytes** are in Solidity (e.g. `bytes16`).\n *\n * @category Utils\n * @param {BytesLike} data - The data to pad.\n * @param {number} length - The length to pad to.\n *\n * @returns {string} The padded data.\n */\nexport function zeroPadBytes(data, length) {\n return zeroPad(data, length, false);\n}\n//# sourceMappingURL=data.js.map","import { defineProperties } from './properties.js';\n/**\n * When an {@link EventEmitterable | **EventEmitterable**} triggers a Listener, the callback always ahas one additional\n * argument passed, which is an **EventPayload**.\n *\n * @category Utils\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 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","import { getBytes } from '../utils/data.js';\nexport function decodeBase64(textData) {\n textData = atob(textData);\n const data = new Uint8Array(textData.length);\n for (let i = 0; i < textData.length; i++) {\n data[i] = textData.charCodeAt(i);\n }\n return getBytes(data);\n}\nexport function encodeBase64(_data) {\n const data = getBytes(_data);\n let textData = '';\n for (let i = 0; i < data.length; i++) {\n textData += String.fromCharCode(data[i]);\n }\n return btoa(textData);\n}\n//# sourceMappingURL=base64-browser.js.map","/**\n * Provides utility functions for encoding and decoding strings in the Bytes32 format.\n *\n * @category Application Binary Interface\n */\nimport { getBytes, zeroPadBytes } from '../utils/index.js';\nimport { toUtf8Bytes, toUtf8String } from './index.js';\n/**\n * Encodes a string as a Bytes32 string. This is used to encode ABI data.\n *\n * @category Encoding\n * @param {string} text - The string to encode.\n *\n * @returns {string} The Bytes32-encoded string.\n * @throws {Error} If the string is too long to fit in a Bytes32 format.\n */\nexport function encodeBytes32(text) {\n // Get the bytes\n const bytes = toUtf8Bytes(text);\n // Check we have room for null-termination\n if (bytes.length > 31) {\n throw new Error('bytes32 string must be less than 32 bytes');\n }\n // Zero-pad (implicitly null-terminates)\n return zeroPadBytes(bytes, 32);\n}\n/**\n * Decodes a Bytes32-encoded string into a regular string. This is used to decode ABI-encoded data.\n *\n * @category Encoding\n * @param {BytesLike} _bytes - The Bytes32-encoded data.\n *\n * @returns {string} The decoded string.\n * @throws {Error} If the input is not exactly 32 bytes long or lacks a null terminator.\n */\nexport function decodeBytes32(_bytes) {\n const data = getBytes(_bytes, 'bytes');\n // Must be 32 bytes with a null-termination\n if (data.length !== 32) {\n throw new Error('invalid bytes32 - not 32 bytes long');\n }\n if (data[31] !== 0) {\n throw new Error('invalid bytes32 string - no null terminator');\n }\n // Find the null termination\n let length = 31;\n while (data[length - 1] === 0) {\n length--;\n }\n // Determine the string value\n return toUtf8String(data.slice(0, length));\n}\n//# sourceMappingURL=bytes32.js.map","/**\n * Some mathematic operations.\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` bits to its value.\n *\n * If the highest bit is `1`, the result will be negative.\n *\n * @category Utils\n * @param {BigNumberish} _value - The value to convert.\n * @param {Numeric} _width - The width of the value in bits.\n * @returns {bigint} The value.\n * @throws {Error} If the value is too large for the width.\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',\n fault: 'overflow',\n 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 `width` bits.\n *\n * The result will always be positive.\n *\n * @category Utils\n * @param {BigNumberish} _value - The value to convert.\n * @param {Numeric} _width - The width of the value in bits.\n * @returns {bigint} The value.\n * @throws {Error} If the value is too large for the width.\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',\n fault: 'overflow',\n 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',\n fault: 'overflow',\n value: _value,\n });\n }\n return value;\n}\n/**\n * Mask `value` with a bitmask of `bits` ones.\n *\n * @category Utils\n * @param {BigNumberish} _value - The value to mask.\n * @param {Numeric} _bits - The number of bits to mask.\n * @returns {bigint} The masked value.\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 a BigInt, then an ArgumentError will be thrown for `name`.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @param {string} name - The name of the value.\n * @returns {bigint} The value.\n */\nexport function getBigInt(value, name) {\n switch (typeof value) {\n case 'bigint':\n 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 absolute value of bigint `value`.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @returns {bigint} The absolute value.\n */\nexport function bigIntAbs(value) {\n value = getBigInt(value);\n // if value is negative (including -0), return -value, else return value\n if (value === -BN_0 || value < BN_0) {\n return -value;\n }\n return value;\n}\n/**\n * Returns `value` as a bigint, validating it is valid as a bigint value and that it is positive.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @param {string} name - The name of the value.\n * @returns {bigint} The value.\n * @throws {Error} If the value is negative.\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',\n operation: 'getUint',\n value,\n });\n return result;\n}\nconst Nibbles = '0123456789abcdef';\n/**\n * Converts `value` to a BigInt. If `value` is a Uint8Array, it is treated as Big Endian data.\n *\n * @category Utils\n * @param {BigNumberish | Uint8Array} value - The value to convert.\n * @returns {bigint} The value.\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 a number, then an ArgumentError will be thrown for `name`.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @param {string} name - The name of the value.\n * @returns {number} The value.\n * @throws {Error} If the value is invalid.\n * @throws {Error} If the value is too large.\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 is treated as Big Endian data. Throws if the value is\n * not safe.\n *\n * @category Utils\n * @param {BigNumberish | Uint8Array} value - The value to convert.\n * @returns {number} The value.\n * @throws {Error} If the value is not safe to convert to a number.\n */\nexport function toNumber(value) {\n return getNumber(toBigInt(value));\n}\n/**\n * Converts `value` to a Big Endian hexstring, optionally padded to `width` bytes.\n *\n * @category Utils\n * @param {BigNumberish} _value - The value to convert.\n * @param {Numeric} _width - The width of the value in bytes.\n * @returns {string} The hexstring.\n * @throws {Error} If the value exceeds the width.\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 *\n * @category Utils\n * @param {BigNumberish} _value - The value to convert.\n * @returns {Uint8Array} The value.\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 the literal value `0x0`. This is most commonly used\n * for JSSON-RPC numeric values.\n *\n * @category Utils\n * @param {BigNumberish | Uint8Array} value - The value to convert.\n * @returns {string} The quantity.\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](https://en.bitcoinwiki.org/wiki/Base58) scheme allows a **numeric** value to be encoded as a\n * compact string using a radix of 58 using only alpha-numeric characters. Confusingly similar characters are omitted\n * (i.e. `\"l0O\"`).\n *\n * Note that Base58 encodes a **numeric** value, not arbitrary bytes, since any zero-bytes on the left would get\n * removed. To mitigate this issue most schemes that use Base58 choose specific high-order values to ensure non-zero\n * prefixes.\n */\nimport { getBytes } from '../utils/data.js';\nimport { assertArgument } from '../utils/errors.js';\nimport { toBigInt } from '../utils/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 *\n * @category Encoding\n * @param {BytesLike} _value - The value to encode.\n *\n * @returns {string} The 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 *\n * @category Encoding\n * @param {string} value - The Base58-encoded value.\n *\n * @returns {bigint} The decoded 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 * Generated by the protoc-gen-ts. DO NOT EDIT!\n * compiler version: 4.25.3\n * source: proto_common.proto\n * git: https://github.com/thesayyn/protoc-gen-ts */\nimport * as pb_1 from \"google-protobuf\";\nexport var common;\n(function (common) {\n class ProtoLocation extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n }\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set value(value) {\n pb_1.Message.setField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoLocation({});\n if (data.value != null) {\n message.value = data.value;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.value != null) {\n data.value = this.value;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.value.length)\n writer.writeBytes(1, this.value);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLocation();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.value = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoLocation.deserialize(bytes);\n }\n }\n common.ProtoLocation = ProtoLocation;\n class ProtoHash extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n }\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set value(value) {\n pb_1.Message.setField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoHash({});\n if (data.value != null) {\n message.value = data.value;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.value != null) {\n data.value = this.value;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.value.length)\n writer.writeBytes(1, this.value);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHash();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.value = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoHash.deserialize(bytes);\n }\n }\n common.ProtoHash = ProtoHash;\n class ProtoHashes extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"hashes\" in data && data.hashes != undefined) {\n this.hashes = data.hashes;\n }\n }\n }\n get hashes() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoHash, 1);\n }\n set hashes(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoHashes({});\n if (data.hashes != null) {\n message.hashes = data.hashes.map(item => ProtoHash.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.hashes != null) {\n data.hashes = this.hashes.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.hashes.length)\n writer.writeRepeatedMessage(1, this.hashes, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHashes();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.hashes, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoHash.deserialize(reader), ProtoHash));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoHashes.deserialize(bytes);\n }\n }\n common.ProtoHashes = ProtoHashes;\n class ProtoAddress extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n }\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set value(value) {\n pb_1.Message.setField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoAddress({});\n if (data.value != null) {\n message.value = data.value;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.value != null) {\n data.value = this.value;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.value.length)\n writer.writeBytes(1, this.value);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoAddress();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.value = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoAddress.deserialize(bytes);\n }\n }\n common.ProtoAddress = ProtoAddress;\n class ProtoNumber extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n }\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 1, 0);\n }\n set value(value) {\n pb_1.Message.setField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoNumber({});\n if (data.value != null) {\n message.value = data.value;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.value != null) {\n data.value = this.value;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.value != 0)\n writer.writeUint64(1, this.value);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoNumber();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.value = reader.readUint64();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoNumber.deserialize(bytes);\n }\n }\n common.ProtoNumber = ProtoNumber;\n class ProtoLocations extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"locations\" in data && data.locations != undefined) {\n this.locations = data.locations;\n }\n }\n }\n get locations() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoLocation, 1);\n }\n set locations(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoLocations({});\n if (data.locations != null) {\n message.locations = data.locations.map(item => ProtoLocation.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.locations != null) {\n data.locations = this.locations.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.locations.length)\n writer.writeRepeatedMessage(1, this.locations, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLocations();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.locations, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoLocation.deserialize(reader), ProtoLocation));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoLocations.deserialize(bytes);\n }\n }\n common.ProtoLocations = ProtoLocations;\n})(common || (common = {}));\n//# sourceMappingURL=proto_common.js.map","/**\n * Generated by the protoc-gen-ts. DO NOT EDIT!\n * compiler version: 4.25.3\n * source: proto_block.proto\n * git: https://github.com/thesayyn/protoc-gen-ts */\nimport * as dependency_1 from \"./proto_common.js\";\nimport * as pb_1 from \"google-protobuf\";\nexport var block;\n(function (block) {\n class ProtoHeader extends pb_1.Message {\n #one_of_decls = [[2], [3], [4], [5], [6], [7], [9], [10], [14], [16], [17], [18], [19], [20], [21], [22], [23], [24], [25], [26], [27], [28], [29], [30]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1, 8, 11, 12, 13, 15], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"parent_hash\" in data && data.parent_hash != undefined) {\n this.parent_hash = data.parent_hash;\n }\n if (\"uncle_hash\" in data && data.uncle_hash != undefined) {\n this.uncle_hash = data.uncle_hash;\n }\n if (\"coinbase\" in data && data.coinbase != undefined) {\n this.coinbase = data.coinbase;\n }\n if (\"evm_root\" in data && data.evm_root != undefined) {\n this.evm_root = data.evm_root;\n }\n if (\"tx_hash\" in data && data.tx_hash != undefined) {\n this.tx_hash = data.tx_hash;\n }\n if (\"etx_hash\" in data && data.etx_hash != undefined) {\n this.etx_hash = data.etx_hash;\n }\n if (\"etx_rollup_hash\" in data && data.etx_rollup_hash != undefined) {\n this.etx_rollup_hash = data.etx_rollup_hash;\n }\n if (\"manifest_hash\" in data && data.manifest_hash != undefined) {\n this.manifest_hash = data.manifest_hash;\n }\n if (\"receipt_hash\" in data && data.receipt_hash != undefined) {\n this.receipt_hash = data.receipt_hash;\n }\n if (\"difficulty\" in data && data.difficulty != undefined) {\n this.difficulty = data.difficulty;\n }\n if (\"parent_entropy\" in data && data.parent_entropy != undefined) {\n this.parent_entropy = data.parent_entropy;\n }\n if (\"parent_delta_s\" in data && data.parent_delta_s != undefined) {\n this.parent_delta_s = data.parent_delta_s;\n }\n if (\"parent_uncled_sub_delta_s\" in data && data.parent_uncled_sub_delta_s != undefined) {\n this.parent_uncled_sub_delta_s = data.parent_uncled_sub_delta_s;\n }\n if (\"uncled_s\" in data && data.uncled_s != undefined) {\n this.uncled_s = data.uncled_s;\n }\n if (\"number\" in data && data.number != undefined) {\n this.number = data.number;\n }\n if (\"gas_limit\" in data && data.gas_limit != undefined) {\n this.gas_limit = data.gas_limit;\n }\n if (\"gas_used\" in data && data.gas_used != undefined) {\n this.gas_used = data.gas_used;\n }\n if (\"base_fee\" in data && data.base_fee != undefined) {\n this.base_fee = data.base_fee;\n }\n if (\"location\" in data && data.location != undefined) {\n this.location = data.location;\n }\n if (\"extra\" in data && data.extra != undefined) {\n this.extra = data.extra;\n }\n if (\"mix_hash\" in data && data.mix_hash != undefined) {\n this.mix_hash = data.mix_hash;\n }\n if (\"nonce\" in data && data.nonce != undefined) {\n this.nonce = data.nonce;\n }\n if (\"utxo_root\" in data && data.utxo_root != undefined) {\n this.utxo_root = data.utxo_root;\n }\n if (\"etx_set_hash\" in data && data.etx_set_hash != undefined) {\n this.etx_set_hash = data.etx_set_hash;\n }\n if (\"efficiency_score\" in data && data.efficiency_score != undefined) {\n this.efficiency_score = data.efficiency_score;\n }\n if (\"threshold_count\" in data && data.threshold_count != undefined) {\n this.threshold_count = data.threshold_count;\n }\n if (\"expansion_number\" in data && data.expansion_number != undefined) {\n this.expansion_number = data.expansion_number;\n }\n if (\"etx_eligible_slices\" in data && data.etx_eligible_slices != undefined) {\n this.etx_eligible_slices = data.etx_eligible_slices;\n }\n if (\"prime_terminus\" in data && data.prime_terminus != undefined) {\n this.prime_terminus = data.prime_terminus;\n }\n if (\"interlink_root_hash\" in data && data.interlink_root_hash != undefined) {\n this.interlink_root_hash = data.interlink_root_hash;\n }\n }\n }\n get parent_hash() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set parent_hash(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n get uncle_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set uncle_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[0], value);\n }\n get has_uncle_hash() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get coinbase() {\n return pb_1.Message.getFieldWithDefault(this, 3, new Uint8Array(0));\n }\n set coinbase(value) {\n pb_1.Message.setOneofField(this, 3, this.#one_of_decls[1], value);\n }\n get has_coinbase() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get evm_root() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 4);\n }\n set evm_root(value) {\n pb_1.Message.setOneofWrapperField(this, 4, this.#one_of_decls[2], value);\n }\n get has_evm_root() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get tx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 5);\n }\n set tx_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 5, this.#one_of_decls[3], value);\n }\n get has_tx_hash() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get etx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 6);\n }\n set etx_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 6, this.#one_of_decls[4], value);\n }\n get has_etx_hash() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get etx_rollup_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 7);\n }\n set etx_rollup_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 7, this.#one_of_decls[5], value);\n }\n get has_etx_rollup_hash() {\n return pb_1.Message.getField(this, 7) != null;\n }\n get manifest_hash() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 8);\n }\n set manifest_hash(value) {\n pb_1.Message.setRepeatedWrapperField(this, 8, value);\n }\n get receipt_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 9);\n }\n set receipt_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 9, this.#one_of_decls[6], value);\n }\n get has_receipt_hash() {\n return pb_1.Message.getField(this, 9) != null;\n }\n get difficulty() {\n return pb_1.Message.getFieldWithDefault(this, 10, new Uint8Array(0));\n }\n set difficulty(value) {\n pb_1.Message.setOneofField(this, 10, this.#one_of_decls[7], value);\n }\n get has_difficulty() {\n return pb_1.Message.getField(this, 10) != null;\n }\n get parent_entropy() {\n return pb_1.Message.getFieldWithDefault(this, 11, []);\n }\n set parent_entropy(value) {\n pb_1.Message.setField(this, 11, value);\n }\n get parent_delta_s() {\n return pb_1.Message.getFieldWithDefault(this, 12, []);\n }\n set parent_delta_s(value) {\n pb_1.Message.setField(this, 12, value);\n }\n get parent_uncled_sub_delta_s() {\n return pb_1.Message.getFieldWithDefault(this, 13, []);\n }\n set parent_uncled_sub_delta_s(value) {\n pb_1.Message.setField(this, 13, value);\n }\n get uncled_s() {\n return pb_1.Message.getFieldWithDefault(this, 14, new Uint8Array(0));\n }\n set uncled_s(value) {\n pb_1.Message.setOneofField(this, 14, this.#one_of_decls[8], value);\n }\n get has_uncled_s() {\n return pb_1.Message.getField(this, 14) != null;\n }\n get number() {\n return pb_1.Message.getFieldWithDefault(this, 15, []);\n }\n set number(value) {\n pb_1.Message.setField(this, 15, value);\n }\n get gas_limit() {\n return pb_1.Message.getFieldWithDefault(this, 16, 0);\n }\n set gas_limit(value) {\n pb_1.Message.setOneofField(this, 16, this.#one_of_decls[9], value);\n }\n get has_gas_limit() {\n return pb_1.Message.getField(this, 16) != null;\n }\n get gas_used() {\n return pb_1.Message.getFieldWithDefault(this, 17, 0);\n }\n set gas_used(value) {\n pb_1.Message.setOneofField(this, 17, this.#one_of_decls[10], value);\n }\n get has_gas_used() {\n return pb_1.Message.getField(this, 17) != null;\n }\n get base_fee() {\n return pb_1.Message.getFieldWithDefault(this, 18, new Uint8Array(0));\n }\n set base_fee(value) {\n pb_1.Message.setOneofField(this, 18, this.#one_of_decls[11], value);\n }\n get has_base_fee() {\n return pb_1.Message.getField(this, 18) != null;\n }\n get location() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoLocation, 19);\n }\n set location(value) {\n pb_1.Message.setOneofWrapperField(this, 19, this.#one_of_decls[12], value);\n }\n get has_location() {\n return pb_1.Message.getField(this, 19) != null;\n }\n get extra() {\n return pb_1.Message.getFieldWithDefault(this, 20, new Uint8Array(0));\n }\n set extra(value) {\n pb_1.Message.setOneofField(this, 20, this.#one_of_decls[13], value);\n }\n get has_extra() {\n return pb_1.Message.getField(this, 20) != null;\n }\n get mix_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 21);\n }\n set mix_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 21, this.#one_of_decls[14], value);\n }\n get has_mix_hash() {\n return pb_1.Message.getField(this, 21) != null;\n }\n get nonce() {\n return pb_1.Message.getFieldWithDefault(this, 22, 0);\n }\n set nonce(value) {\n pb_1.Message.setOneofField(this, 22, this.#one_of_decls[15], value);\n }\n get has_nonce() {\n return pb_1.Message.getField(this, 22) != null;\n }\n get utxo_root() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 23);\n }\n set utxo_root(value) {\n pb_1.Message.setOneofWrapperField(this, 23, this.#one_of_decls[16], value);\n }\n get has_utxo_root() {\n return pb_1.Message.getField(this, 23) != null;\n }\n get etx_set_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 24);\n }\n set etx_set_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 24, this.#one_of_decls[17], value);\n }\n get has_etx_set_hash() {\n return pb_1.Message.getField(this, 24) != null;\n }\n get efficiency_score() {\n return pb_1.Message.getFieldWithDefault(this, 25, 0);\n }\n set efficiency_score(value) {\n pb_1.Message.setOneofField(this, 25, this.#one_of_decls[18], value);\n }\n get has_efficiency_score() {\n return pb_1.Message.getField(this, 25) != null;\n }\n get threshold_count() {\n return pb_1.Message.getFieldWithDefault(this, 26, 0);\n }\n set threshold_count(value) {\n pb_1.Message.setOneofField(this, 26, this.#one_of_decls[19], value);\n }\n get has_threshold_count() {\n return pb_1.Message.getField(this, 26) != null;\n }\n get expansion_number() {\n return pb_1.Message.getFieldWithDefault(this, 27, 0);\n }\n set expansion_number(value) {\n pb_1.Message.setOneofField(this, 27, this.#one_of_decls[20], value);\n }\n get has_expansion_number() {\n return pb_1.Message.getField(this, 27) != null;\n }\n get etx_eligible_slices() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 28);\n }\n set etx_eligible_slices(value) {\n pb_1.Message.setOneofWrapperField(this, 28, this.#one_of_decls[21], value);\n }\n get has_etx_eligible_slices() {\n return pb_1.Message.getField(this, 28) != null;\n }\n get prime_terminus() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 29);\n }\n set prime_terminus(value) {\n pb_1.Message.setOneofWrapperField(this, 29, this.#one_of_decls[22], value);\n }\n get has_prime_terminus() {\n return pb_1.Message.getField(this, 29) != null;\n }\n get interlink_root_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 30);\n }\n set interlink_root_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 30, this.#one_of_decls[23], value);\n }\n get has_interlink_root_hash() {\n return pb_1.Message.getField(this, 30) != null;\n }\n get _uncle_hash() {\n const cases = {\n 0: \"none\",\n 2: \"uncle_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _coinbase() {\n const cases = {\n 0: \"none\",\n 3: \"coinbase\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n get _evm_root() {\n const cases = {\n 0: \"none\",\n 4: \"evm_root\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [4])];\n }\n get _tx_hash() {\n const cases = {\n 0: \"none\",\n 5: \"tx_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [5])];\n }\n get _etx_hash() {\n const cases = {\n 0: \"none\",\n 6: \"etx_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [6])];\n }\n get _etx_rollup_hash() {\n const cases = {\n 0: \"none\",\n 7: \"etx_rollup_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [7])];\n }\n get _receipt_hash() {\n const cases = {\n 0: \"none\",\n 9: \"receipt_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [9])];\n }\n get _difficulty() {\n const cases = {\n 0: \"none\",\n 10: \"difficulty\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [10])];\n }\n get _uncled_s() {\n const cases = {\n 0: \"none\",\n 14: \"uncled_s\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [14])];\n }\n get _gas_limit() {\n const cases = {\n 0: \"none\",\n 16: \"gas_limit\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [16])];\n }\n get _gas_used() {\n const cases = {\n 0: \"none\",\n 17: \"gas_used\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [17])];\n }\n get _base_fee() {\n const cases = {\n 0: \"none\",\n 18: \"base_fee\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [18])];\n }\n get _location() {\n const cases = {\n 0: \"none\",\n 19: \"location\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [19])];\n }\n get _extra() {\n const cases = {\n 0: \"none\",\n 20: \"extra\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [20])];\n }\n get _mix_hash() {\n const cases = {\n 0: \"none\",\n 21: \"mix_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [21])];\n }\n get _nonce() {\n const cases = {\n 0: \"none\",\n 22: \"nonce\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [22])];\n }\n get _utxo_root() {\n const cases = {\n 0: \"none\",\n 23: \"utxo_root\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [23])];\n }\n get _etx_set_hash() {\n const cases = {\n 0: \"none\",\n 24: \"etx_set_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [24])];\n }\n get _efficiency_score() {\n const cases = {\n 0: \"none\",\n 25: \"efficiency_score\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [25])];\n }\n get _threshold_count() {\n const cases = {\n 0: \"none\",\n 26: \"threshold_count\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [26])];\n }\n get _expansion_number() {\n const cases = {\n 0: \"none\",\n 27: \"expansion_number\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [27])];\n }\n get _etx_eligible_slices() {\n const cases = {\n 0: \"none\",\n 28: \"etx_eligible_slices\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [28])];\n }\n get _prime_terminus() {\n const cases = {\n 0: \"none\",\n 29: \"prime_terminus\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [29])];\n }\n get _interlink_root_hash() {\n const cases = {\n 0: \"none\",\n 30: \"interlink_root_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [30])];\n }\n static fromObject(data) {\n const message = new ProtoHeader({});\n if (data.parent_hash != null) {\n message.parent_hash = data.parent_hash.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n if (data.uncle_hash != null) {\n message.uncle_hash = dependency_1.common.ProtoHash.fromObject(data.uncle_hash);\n }\n if (data.coinbase != null) {\n message.coinbase = data.coinbase;\n }\n if (data.evm_root != null) {\n message.evm_root = dependency_1.common.ProtoHash.fromObject(data.evm_root);\n }\n if (data.tx_hash != null) {\n message.tx_hash = dependency_1.common.ProtoHash.fromObject(data.tx_hash);\n }\n if (data.etx_hash != null) {\n message.etx_hash = dependency_1.common.ProtoHash.fromObject(data.etx_hash);\n }\n if (data.etx_rollup_hash != null) {\n message.etx_rollup_hash = dependency_1.common.ProtoHash.fromObject(data.etx_rollup_hash);\n }\n if (data.manifest_hash != null) {\n message.manifest_hash = data.manifest_hash.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n if (data.receipt_hash != null) {\n message.receipt_hash = dependency_1.common.ProtoHash.fromObject(data.receipt_hash);\n }\n if (data.difficulty != null) {\n message.difficulty = data.difficulty;\n }\n if (data.parent_entropy != null) {\n message.parent_entropy = data.parent_entropy;\n }\n if (data.parent_delta_s != null) {\n message.parent_delta_s = data.parent_delta_s;\n }\n if (data.parent_uncled_sub_delta_s != null) {\n message.parent_uncled_sub_delta_s = data.parent_uncled_sub_delta_s;\n }\n if (data.uncled_s != null) {\n message.uncled_s = data.uncled_s;\n }\n if (data.number != null) {\n message.number = data.number;\n }\n if (data.gas_limit != null) {\n message.gas_limit = data.gas_limit;\n }\n if (data.gas_used != null) {\n message.gas_used = data.gas_used;\n }\n if (data.base_fee != null) {\n message.base_fee = data.base_fee;\n }\n if (data.location != null) {\n message.location = dependency_1.common.ProtoLocation.fromObject(data.location);\n }\n if (data.extra != null) {\n message.extra = data.extra;\n }\n if (data.mix_hash != null) {\n message.mix_hash = dependency_1.common.ProtoHash.fromObject(data.mix_hash);\n }\n if (data.nonce != null) {\n message.nonce = data.nonce;\n }\n if (data.utxo_root != null) {\n message.utxo_root = dependency_1.common.ProtoHash.fromObject(data.utxo_root);\n }\n if (data.etx_set_hash != null) {\n message.etx_set_hash = dependency_1.common.ProtoHash.fromObject(data.etx_set_hash);\n }\n if (data.efficiency_score != null) {\n message.efficiency_score = data.efficiency_score;\n }\n if (data.threshold_count != null) {\n message.threshold_count = data.threshold_count;\n }\n if (data.expansion_number != null) {\n message.expansion_number = data.expansion_number;\n }\n if (data.etx_eligible_slices != null) {\n message.etx_eligible_slices = dependency_1.common.ProtoHash.fromObject(data.etx_eligible_slices);\n }\n if (data.prime_terminus != null) {\n message.prime_terminus = dependency_1.common.ProtoHash.fromObject(data.prime_terminus);\n }\n if (data.interlink_root_hash != null) {\n message.interlink_root_hash = dependency_1.common.ProtoHash.fromObject(data.interlink_root_hash);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.parent_hash != null) {\n data.parent_hash = this.parent_hash.map((item) => item.toObject());\n }\n if (this.uncle_hash != null) {\n data.uncle_hash = this.uncle_hash.toObject();\n }\n if (this.coinbase != null) {\n data.coinbase = this.coinbase;\n }\n if (this.evm_root != null) {\n data.evm_root = this.evm_root.toObject();\n }\n if (this.tx_hash != null) {\n data.tx_hash = this.tx_hash.toObject();\n }\n if (this.etx_hash != null) {\n data.etx_hash = this.etx_hash.toObject();\n }\n if (this.etx_rollup_hash != null) {\n data.etx_rollup_hash = this.etx_rollup_hash.toObject();\n }\n if (this.manifest_hash != null) {\n data.manifest_hash = this.manifest_hash.map((item) => item.toObject());\n }\n if (this.receipt_hash != null) {\n data.receipt_hash = this.receipt_hash.toObject();\n }\n if (this.difficulty != null) {\n data.difficulty = this.difficulty;\n }\n if (this.parent_entropy != null) {\n data.parent_entropy = this.parent_entropy;\n }\n if (this.parent_delta_s != null) {\n data.parent_delta_s = this.parent_delta_s;\n }\n if (this.parent_uncled_sub_delta_s != null) {\n data.parent_uncled_sub_delta_s = this.parent_uncled_sub_delta_s;\n }\n if (this.uncled_s != null) {\n data.uncled_s = this.uncled_s;\n }\n if (this.number != null) {\n data.number = this.number;\n }\n if (this.gas_limit != null) {\n data.gas_limit = this.gas_limit;\n }\n if (this.gas_used != null) {\n data.gas_used = this.gas_used;\n }\n if (this.base_fee != null) {\n data.base_fee = this.base_fee;\n }\n if (this.location != null) {\n data.location = this.location.toObject();\n }\n if (this.extra != null) {\n data.extra = this.extra;\n }\n if (this.mix_hash != null) {\n data.mix_hash = this.mix_hash.toObject();\n }\n if (this.nonce != null) {\n data.nonce = this.nonce;\n }\n if (this.utxo_root != null) {\n data.utxo_root = this.utxo_root.toObject();\n }\n if (this.etx_set_hash != null) {\n data.etx_set_hash = this.etx_set_hash.toObject();\n }\n if (this.efficiency_score != null) {\n data.efficiency_score = this.efficiency_score;\n }\n if (this.threshold_count != null) {\n data.threshold_count = this.threshold_count;\n }\n if (this.expansion_number != null) {\n data.expansion_number = this.expansion_number;\n }\n if (this.etx_eligible_slices != null) {\n data.etx_eligible_slices = this.etx_eligible_slices.toObject();\n }\n if (this.prime_terminus != null) {\n data.prime_terminus = this.prime_terminus.toObject();\n }\n if (this.interlink_root_hash != null) {\n data.interlink_root_hash = this.interlink_root_hash.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.parent_hash.length)\n writer.writeRepeatedMessage(1, this.parent_hash, (item) => item.serialize(writer));\n if (this.has_uncle_hash)\n writer.writeMessage(2, this.uncle_hash, () => this.uncle_hash.serialize(writer));\n if (this.has_coinbase)\n writer.writeBytes(3, this.coinbase);\n if (this.has_evm_root)\n writer.writeMessage(4, this.evm_root, () => this.evm_root.serialize(writer));\n if (this.has_tx_hash)\n writer.writeMessage(5, this.tx_hash, () => this.tx_hash.serialize(writer));\n if (this.has_etx_hash)\n writer.writeMessage(6, this.etx_hash, () => this.etx_hash.serialize(writer));\n if (this.has_etx_rollup_hash)\n writer.writeMessage(7, this.etx_rollup_hash, () => this.etx_rollup_hash.serialize(writer));\n if (this.manifest_hash.length)\n writer.writeRepeatedMessage(8, this.manifest_hash, (item) => item.serialize(writer));\n if (this.has_receipt_hash)\n writer.writeMessage(9, this.receipt_hash, () => this.receipt_hash.serialize(writer));\n if (this.has_difficulty)\n writer.writeBytes(10, this.difficulty);\n if (this.parent_entropy.length)\n writer.writeRepeatedBytes(11, this.parent_entropy);\n if (this.parent_delta_s.length)\n writer.writeRepeatedBytes(12, this.parent_delta_s);\n if (this.parent_uncled_sub_delta_s.length)\n writer.writeRepeatedBytes(13, this.parent_uncled_sub_delta_s);\n if (this.has_uncled_s)\n writer.writeBytes(14, this.uncled_s);\n if (this.number.length)\n writer.writeRepeatedBytes(15, this.number);\n if (this.has_gas_limit)\n writer.writeUint64(16, this.gas_limit);\n if (this.has_gas_used)\n writer.writeUint64(17, this.gas_used);\n if (this.has_base_fee)\n writer.writeBytes(18, this.base_fee);\n if (this.has_location)\n writer.writeMessage(19, this.location, () => this.location.serialize(writer));\n if (this.has_extra)\n writer.writeBytes(20, this.extra);\n if (this.has_mix_hash)\n writer.writeMessage(21, this.mix_hash, () => this.mix_hash.serialize(writer));\n if (this.has_nonce)\n writer.writeUint64(22, this.nonce);\n if (this.has_utxo_root)\n writer.writeMessage(23, this.utxo_root, () => this.utxo_root.serialize(writer));\n if (this.has_etx_set_hash)\n writer.writeMessage(24, this.etx_set_hash, () => this.etx_set_hash.serialize(writer));\n if (this.has_efficiency_score)\n writer.writeUint64(25, this.efficiency_score);\n if (this.has_threshold_count)\n writer.writeUint64(26, this.threshold_count);\n if (this.has_expansion_number)\n writer.writeUint64(27, this.expansion_number);\n if (this.has_etx_eligible_slices)\n writer.writeMessage(28, this.etx_eligible_slices, () => this.etx_eligible_slices.serialize(writer));\n if (this.has_prime_terminus)\n writer.writeMessage(29, this.prime_terminus, () => this.prime_terminus.serialize(writer));\n if (this.has_interlink_root_hash)\n writer.writeMessage(30, this.interlink_root_hash, () => this.interlink_root_hash.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHeader();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.parent_hash, () => pb_1.Message.addToRepeatedWrapperField(message, 1, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n case 2:\n reader.readMessage(message.uncle_hash, () => message.uncle_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 3:\n message.coinbase = reader.readBytes();\n break;\n case 4:\n reader.readMessage(message.evm_root, () => message.evm_root = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 5:\n reader.readMessage(message.tx_hash, () => message.tx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 6:\n reader.readMessage(message.etx_hash, () => message.etx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 7:\n reader.readMessage(message.etx_rollup_hash, () => message.etx_rollup_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 8:\n reader.readMessage(message.manifest_hash, () => pb_1.Message.addToRepeatedWrapperField(message, 8, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n case 9:\n reader.readMessage(message.receipt_hash, () => message.receipt_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 10:\n message.difficulty = reader.readBytes();\n break;\n case 11:\n pb_1.Message.addToRepeatedField(message, 11, reader.readBytes());\n break;\n case 12:\n pb_1.Message.addToRepeatedField(message, 12, reader.readBytes());\n break;\n case 13:\n pb_1.Message.addToRepeatedField(message, 13, reader.readBytes());\n break;\n case 14:\n message.uncled_s = reader.readBytes();\n break;\n case 15:\n pb_1.Message.addToRepeatedField(message, 15, reader.readBytes());\n break;\n case 16:\n message.gas_limit = reader.readUint64();\n break;\n case 17:\n message.gas_used = reader.readUint64();\n break;\n case 18:\n message.base_fee = reader.readBytes();\n break;\n case 19:\n reader.readMessage(message.location, () => message.location = dependency_1.common.ProtoLocation.deserialize(reader));\n break;\n case 20:\n message.extra = reader.readBytes();\n break;\n case 21:\n reader.readMessage(message.mix_hash, () => message.mix_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 22:\n message.nonce = reader.readUint64();\n break;\n case 23:\n reader.readMessage(message.utxo_root, () => message.utxo_root = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 24:\n reader.readMessage(message.etx_set_hash, () => message.etx_set_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 25:\n message.efficiency_score = reader.readUint64();\n break;\n case 26:\n message.threshold_count = reader.readUint64();\n break;\n case 27:\n message.expansion_number = reader.readUint64();\n break;\n case 28:\n reader.readMessage(message.etx_eligible_slices, () => message.etx_eligible_slices = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 29:\n reader.readMessage(message.prime_terminus, () => message.prime_terminus = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 30:\n reader.readMessage(message.interlink_root_hash, () => message.interlink_root_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoHeader.deserialize(bytes);\n }\n }\n block.ProtoHeader = ProtoHeader;\n class ProtoTransaction extends pb_1.Message {\n #one_of_decls = [[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12], [13], [14], [15], [16], [17], [18], [19]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"type\" in data && data.type != undefined) {\n this.type = data.type;\n }\n if (\"to\" in data && data.to != undefined) {\n this.to = data.to;\n }\n if (\"nonce\" in data && data.nonce != undefined) {\n this.nonce = data.nonce;\n }\n if (\"value\" in data && data.value != undefined) {\n this.value = data.value;\n }\n if (\"gas\" in data && data.gas != undefined) {\n this.gas = data.gas;\n }\n if (\"data\" in data && data.data != undefined) {\n this.data = data.data;\n }\n if (\"chain_id\" in data && data.chain_id != undefined) {\n this.chain_id = data.chain_id;\n }\n if (\"gas_fee_cap\" in data && data.gas_fee_cap != undefined) {\n this.gas_fee_cap = data.gas_fee_cap;\n }\n if (\"gas_tip_cap\" in data && data.gas_tip_cap != undefined) {\n this.gas_tip_cap = data.gas_tip_cap;\n }\n if (\"access_list\" in data && data.access_list != undefined) {\n this.access_list = data.access_list;\n }\n if (\"v\" in data && data.v != undefined) {\n this.v = data.v;\n }\n if (\"r\" in data && data.r != undefined) {\n this.r = data.r;\n }\n if (\"s\" in data && data.s != undefined) {\n this.s = data.s;\n }\n if (\"originating_tx_hash\" in data && data.originating_tx_hash != undefined) {\n this.originating_tx_hash = data.originating_tx_hash;\n }\n if (\"etx_index\" in data && data.etx_index != undefined) {\n this.etx_index = data.etx_index;\n }\n if (\"tx_ins\" in data && data.tx_ins != undefined) {\n this.tx_ins = data.tx_ins;\n }\n if (\"tx_outs\" in data && data.tx_outs != undefined) {\n this.tx_outs = data.tx_outs;\n }\n if (\"signature\" in data && data.signature != undefined) {\n this.signature = data.signature;\n }\n if (\"etx_sender\" in data && data.etx_sender != undefined) {\n this.etx_sender = data.etx_sender;\n }\n }\n }\n get type() {\n return pb_1.Message.getFieldWithDefault(this, 1, 0);\n }\n set type(value) {\n pb_1.Message.setOneofField(this, 1, this.#one_of_decls[0], value);\n }\n get has_type() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get to() {\n return pb_1.Message.getFieldWithDefault(this, 2, new Uint8Array(0));\n }\n set to(value) {\n pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value);\n }\n get has_to() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get nonce() {\n return pb_1.Message.getFieldWithDefault(this, 3, 0);\n }\n set nonce(value) {\n pb_1.Message.setOneofField(this, 3, this.#one_of_decls[2], value);\n }\n get has_nonce() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get value() {\n return pb_1.Message.getFieldWithDefault(this, 4, new Uint8Array(0));\n }\n set value(value) {\n pb_1.Message.setOneofField(this, 4, this.#one_of_decls[3], value);\n }\n get has_value() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get gas() {\n return pb_1.Message.getFieldWithDefault(this, 5, 0);\n }\n set gas(value) {\n pb_1.Message.setOneofField(this, 5, this.#one_of_decls[4], value);\n }\n get has_gas() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get data() {\n return pb_1.Message.getFieldWithDefault(this, 6, new Uint8Array(0));\n }\n set data(value) {\n pb_1.Message.setOneofField(this, 6, this.#one_of_decls[5], value);\n }\n get has_data() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get chain_id() {\n return pb_1.Message.getFieldWithDefault(this, 7, new Uint8Array(0));\n }\n set chain_id(value) {\n pb_1.Message.setOneofField(this, 7, this.#one_of_decls[6], value);\n }\n get has_chain_id() {\n return pb_1.Message.getField(this, 7) != null;\n }\n get gas_fee_cap() {\n return pb_1.Message.getFieldWithDefault(this, 8, new Uint8Array(0));\n }\n set gas_fee_cap(value) {\n pb_1.Message.setOneofField(this, 8, this.#one_of_decls[7], value);\n }\n get has_gas_fee_cap() {\n return pb_1.Message.getField(this, 8) != null;\n }\n get gas_tip_cap() {\n return pb_1.Message.getFieldWithDefault(this, 9, new Uint8Array(0));\n }\n set gas_tip_cap(value) {\n pb_1.Message.setOneofField(this, 9, this.#one_of_decls[8], value);\n }\n get has_gas_tip_cap() {\n return pb_1.Message.getField(this, 9) != null;\n }\n get access_list() {\n return pb_1.Message.getWrapperField(this, ProtoAccessList, 10);\n }\n set access_list(value) {\n pb_1.Message.setOneofWrapperField(this, 10, this.#one_of_decls[9], value);\n }\n get has_access_list() {\n return pb_1.Message.getField(this, 10) != null;\n }\n get v() {\n return pb_1.Message.getFieldWithDefault(this, 11, new Uint8Array(0));\n }\n set v(value) {\n pb_1.Message.setOneofField(this, 11, this.#one_of_decls[10], value);\n }\n get has_v() {\n return pb_1.Message.getField(this, 11) != null;\n }\n get r() {\n return pb_1.Message.getFieldWithDefault(this, 12, new Uint8Array(0));\n }\n set r(value) {\n pb_1.Message.setOneofField(this, 12, this.#one_of_decls[11], value);\n }\n get has_r() {\n return pb_1.Message.getField(this, 12) != null;\n }\n get s() {\n return pb_1.Message.getFieldWithDefault(this, 13, new Uint8Array(0));\n }\n set s(value) {\n pb_1.Message.setOneofField(this, 13, this.#one_of_decls[12], value);\n }\n get has_s() {\n return pb_1.Message.getField(this, 13) != null;\n }\n get originating_tx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 14);\n }\n set originating_tx_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 14, this.#one_of_decls[13], value);\n }\n get has_originating_tx_hash() {\n return pb_1.Message.getField(this, 14) != null;\n }\n get etx_index() {\n return pb_1.Message.getFieldWithDefault(this, 15, 0);\n }\n set etx_index(value) {\n pb_1.Message.setOneofField(this, 15, this.#one_of_decls[14], value);\n }\n get has_etx_index() {\n return pb_1.Message.getField(this, 15) != null;\n }\n get tx_ins() {\n return pb_1.Message.getWrapperField(this, ProtoTxIns, 16);\n }\n set tx_ins(value) {\n pb_1.Message.setOneofWrapperField(this, 16, this.#one_of_decls[15], value);\n }\n get has_tx_ins() {\n return pb_1.Message.getField(this, 16) != null;\n }\n get tx_outs() {\n return pb_1.Message.getWrapperField(this, ProtoTxOuts, 17);\n }\n set tx_outs(value) {\n pb_1.Message.setOneofWrapperField(this, 17, this.#one_of_decls[16], value);\n }\n get has_tx_outs() {\n return pb_1.Message.getField(this, 17) != null;\n }\n get signature() {\n return pb_1.Message.getFieldWithDefault(this, 18, new Uint8Array(0));\n }\n set signature(value) {\n pb_1.Message.setOneofField(this, 18, this.#one_of_decls[17], value);\n }\n get has_signature() {\n return pb_1.Message.getField(this, 18) != null;\n }\n get etx_sender() {\n return pb_1.Message.getFieldWithDefault(this, 19, new Uint8Array(0));\n }\n set etx_sender(value) {\n pb_1.Message.setOneofField(this, 19, this.#one_of_decls[18], value);\n }\n get has_etx_sender() {\n return pb_1.Message.getField(this, 19) != null;\n }\n get _type() {\n const cases = {\n 0: \"none\",\n 1: \"type\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _to() {\n const cases = {\n 0: \"none\",\n 2: \"to\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _nonce() {\n const cases = {\n 0: \"none\",\n 3: \"nonce\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n get _value() {\n const cases = {\n 0: \"none\",\n 4: \"value\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [4])];\n }\n get _gas() {\n const cases = {\n 0: \"none\",\n 5: \"gas\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [5])];\n }\n get _data() {\n const cases = {\n 0: \"none\",\n 6: \"data\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [6])];\n }\n get _chain_id() {\n const cases = {\n 0: \"none\",\n 7: \"chain_id\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [7])];\n }\n get _gas_fee_cap() {\n const cases = {\n 0: \"none\",\n 8: \"gas_fee_cap\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [8])];\n }\n get _gas_tip_cap() {\n const cases = {\n 0: \"none\",\n 9: \"gas_tip_cap\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [9])];\n }\n get _access_list() {\n const cases = {\n 0: \"none\",\n 10: \"access_list\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [10])];\n }\n get _v() {\n const cases = {\n 0: \"none\",\n 11: \"v\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [11])];\n }\n get _r() {\n const cases = {\n 0: \"none\",\n 12: \"r\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [12])];\n }\n get _s() {\n const cases = {\n 0: \"none\",\n 13: \"s\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [13])];\n }\n get _originating_tx_hash() {\n const cases = {\n 0: \"none\",\n 14: \"originating_tx_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [14])];\n }\n get _etx_index() {\n const cases = {\n 0: \"none\",\n 15: \"etx_index\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [15])];\n }\n get _tx_ins() {\n const cases = {\n 0: \"none\",\n 16: \"tx_ins\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [16])];\n }\n get _tx_outs() {\n const cases = {\n 0: \"none\",\n 17: \"tx_outs\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [17])];\n }\n get _signature() {\n const cases = {\n 0: \"none\",\n 18: \"signature\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [18])];\n }\n get _etx_sender() {\n const cases = {\n 0: \"none\",\n 19: \"etx_sender\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [19])];\n }\n static fromObject(data) {\n const message = new ProtoTransaction({});\n if (data.type != null) {\n message.type = data.type;\n }\n if (data.to != null) {\n message.to = data.to;\n }\n if (data.nonce != null) {\n message.nonce = data.nonce;\n }\n if (data.value != null) {\n message.value = data.value;\n }\n if (data.gas != null) {\n message.gas = data.gas;\n }\n if (data.data != null) {\n message.data = data.data;\n }\n if (data.chain_id != null) {\n message.chain_id = data.chain_id;\n }\n if (data.gas_fee_cap != null) {\n message.gas_fee_cap = data.gas_fee_cap;\n }\n if (data.gas_tip_cap != null) {\n message.gas_tip_cap = data.gas_tip_cap;\n }\n if (data.access_list != null) {\n message.access_list = ProtoAccessList.fromObject(data.access_list);\n }\n if (data.v != null) {\n message.v = data.v;\n }\n if (data.r != null) {\n message.r = data.r;\n }\n if (data.s != null) {\n message.s = data.s;\n }\n if (data.originating_tx_hash != null) {\n message.originating_tx_hash = dependency_1.common.ProtoHash.fromObject(data.originating_tx_hash);\n }\n if (data.etx_index != null) {\n message.etx_index = data.etx_index;\n }\n if (data.tx_ins != null) {\n message.tx_ins = ProtoTxIns.fromObject(data.tx_ins);\n }\n if (data.tx_outs != null) {\n message.tx_outs = ProtoTxOuts.fromObject(data.tx_outs);\n }\n if (data.signature != null) {\n message.signature = data.signature;\n }\n if (data.etx_sender != null) {\n message.etx_sender = data.etx_sender;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.type != null) {\n data.type = this.type;\n }\n if (this.to != null) {\n data.to = this.to;\n }\n if (this.nonce != null) {\n data.nonce = this.nonce;\n }\n if (this.value != null) {\n data.value = this.value;\n }\n if (this.gas != null) {\n data.gas = this.gas;\n }\n if (this.data != null) {\n data.data = this.data;\n }\n if (this.chain_id != null) {\n data.chain_id = this.chain_id;\n }\n if (this.gas_fee_cap != null) {\n data.gas_fee_cap = this.gas_fee_cap;\n }\n if (this.gas_tip_cap != null) {\n data.gas_tip_cap = this.gas_tip_cap;\n }\n if (this.access_list != null) {\n data.access_list = this.access_list.toObject();\n }\n if (this.v != null) {\n data.v = this.v;\n }\n if (this.r != null) {\n data.r = this.r;\n }\n if (this.s != null) {\n data.s = this.s;\n }\n if (this.originating_tx_hash != null) {\n data.originating_tx_hash = this.originating_tx_hash.toObject();\n }\n if (this.etx_index != null) {\n data.etx_index = this.etx_index;\n }\n if (this.tx_ins != null) {\n data.tx_ins = this.tx_ins.toObject();\n }\n if (this.tx_outs != null) {\n data.tx_outs = this.tx_outs.toObject();\n }\n if (this.signature != null) {\n data.signature = this.signature;\n }\n if (this.etx_sender != null) {\n data.etx_sender = this.etx_sender;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_type)\n writer.writeUint64(1, this.type);\n if (this.has_to)\n writer.writeBytes(2, this.to);\n if (this.has_nonce)\n writer.writeUint64(3, this.nonce);\n if (this.has_value)\n writer.writeBytes(4, this.value);\n if (this.has_gas)\n writer.writeUint64(5, this.gas);\n if (this.has_data)\n writer.writeBytes(6, this.data);\n if (this.has_chain_id)\n writer.writeBytes(7, this.chain_id);\n if (this.has_gas_fee_cap)\n writer.writeBytes(8, this.gas_fee_cap);\n if (this.has_gas_tip_cap)\n writer.writeBytes(9, this.gas_tip_cap);\n if (this.has_access_list)\n writer.writeMessage(10, this.access_list, () => this.access_list.serialize(writer));\n if (this.has_v)\n writer.writeBytes(11, this.v);\n if (this.has_r)\n writer.writeBytes(12, this.r);\n if (this.has_s)\n writer.writeBytes(13, this.s);\n if (this.has_originating_tx_hash)\n writer.writeMessage(14, this.originating_tx_hash, () => this.originating_tx_hash.serialize(writer));\n if (this.has_etx_index)\n writer.writeUint32(15, this.etx_index);\n if (this.has_tx_ins)\n writer.writeMessage(16, this.tx_ins, () => this.tx_ins.serialize(writer));\n if (this.has_tx_outs)\n writer.writeMessage(17, this.tx_outs, () => this.tx_outs.serialize(writer));\n if (this.has_signature)\n writer.writeBytes(18, this.signature);\n if (this.has_etx_sender)\n writer.writeBytes(19, this.etx_sender);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTransaction();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.type = reader.readUint64();\n break;\n case 2:\n message.to = reader.readBytes();\n break;\n case 3:\n message.nonce = reader.readUint64();\n break;\n case 4:\n message.value = reader.readBytes();\n break;\n case 5:\n message.gas = reader.readUint64();\n break;\n case 6:\n message.data = reader.readBytes();\n break;\n case 7:\n message.chain_id = reader.readBytes();\n break;\n case 8:\n message.gas_fee_cap = reader.readBytes();\n break;\n case 9:\n message.gas_tip_cap = reader.readBytes();\n break;\n case 10:\n reader.readMessage(message.access_list, () => message.access_list = ProtoAccessList.deserialize(reader));\n break;\n case 11:\n message.v = reader.readBytes();\n break;\n case 12:\n message.r = reader.readBytes();\n break;\n case 13:\n message.s = reader.readBytes();\n break;\n case 14:\n reader.readMessage(message.originating_tx_hash, () => message.originating_tx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 15:\n message.etx_index = reader.readUint32();\n break;\n case 16:\n reader.readMessage(message.tx_ins, () => message.tx_ins = ProtoTxIns.deserialize(reader));\n break;\n case 17:\n reader.readMessage(message.tx_outs, () => message.tx_outs = ProtoTxOuts.deserialize(reader));\n break;\n case 18:\n message.signature = reader.readBytes();\n break;\n case 19:\n message.etx_sender = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTransaction.deserialize(bytes);\n }\n }\n block.ProtoTransaction = ProtoTransaction;\n class ProtoTransactions extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"transactions\" in data && data.transactions != undefined) {\n this.transactions = data.transactions;\n }\n }\n }\n get transactions() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoTransaction, 1);\n }\n set transactions(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoTransactions({});\n if (data.transactions != null) {\n message.transactions = data.transactions.map(item => ProtoTransaction.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.transactions != null) {\n data.transactions = this.transactions.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.transactions.length)\n writer.writeRepeatedMessage(1, this.transactions, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTransactions();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.transactions, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoTransaction.deserialize(reader), ProtoTransaction));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTransactions.deserialize(bytes);\n }\n }\n block.ProtoTransactions = ProtoTransactions;\n class ProtoHeaders extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"headers\" in data && data.headers != undefined) {\n this.headers = data.headers;\n }\n }\n }\n get headers() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoHeader, 1);\n }\n set headers(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoHeaders({});\n if (data.headers != null) {\n message.headers = data.headers.map(item => ProtoHeader.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.headers != null) {\n data.headers = this.headers.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.headers.length)\n writer.writeRepeatedMessage(1, this.headers, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoHeaders();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.headers, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoHeader.deserialize(reader), ProtoHeader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoHeaders.deserialize(bytes);\n }\n }\n block.ProtoHeaders = ProtoHeaders;\n class ProtoManifest extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"manifest\" in data && data.manifest != undefined) {\n this.manifest = data.manifest;\n }\n }\n }\n get manifest() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set manifest(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoManifest({});\n if (data.manifest != null) {\n message.manifest = data.manifest.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.manifest != null) {\n data.manifest = this.manifest.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.manifest.length)\n writer.writeRepeatedMessage(1, this.manifest, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoManifest();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.manifest, () => pb_1.Message.addToRepeatedWrapperField(message, 1, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoManifest.deserialize(bytes);\n }\n }\n block.ProtoManifest = ProtoManifest;\n class ProtoAccessList extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"access_tuples\" in data && data.access_tuples != undefined) {\n this.access_tuples = data.access_tuples;\n }\n }\n }\n get access_tuples() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoAccessTuple, 1);\n }\n set access_tuples(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoAccessList({});\n if (data.access_tuples != null) {\n message.access_tuples = data.access_tuples.map(item => ProtoAccessTuple.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.access_tuples != null) {\n data.access_tuples = this.access_tuples.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.access_tuples.length)\n writer.writeRepeatedMessage(1, this.access_tuples, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoAccessList();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.access_tuples, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoAccessTuple.deserialize(reader), ProtoAccessTuple));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoAccessList.deserialize(bytes);\n }\n }\n block.ProtoAccessList = ProtoAccessList;\n class ProtoWorkObjectHeader extends pb_1.Message {\n #one_of_decls = [[1], [2], [3], [4], [5], [6], [7], [8], [9]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"header_hash\" in data && data.header_hash != undefined) {\n this.header_hash = data.header_hash;\n }\n if (\"parent_hash\" in data && data.parent_hash != undefined) {\n this.parent_hash = data.parent_hash;\n }\n if (\"number\" in data && data.number != undefined) {\n this.number = data.number;\n }\n if (\"difficulty\" in data && data.difficulty != undefined) {\n this.difficulty = data.difficulty;\n }\n if (\"tx_hash\" in data && data.tx_hash != undefined) {\n this.tx_hash = data.tx_hash;\n }\n if (\"nonce\" in data && data.nonce != undefined) {\n this.nonce = data.nonce;\n }\n if (\"location\" in data && data.location != undefined) {\n this.location = data.location;\n }\n if (\"mix_hash\" in data && data.mix_hash != undefined) {\n this.mix_hash = data.mix_hash;\n }\n if (\"time\" in data && data.time != undefined) {\n this.time = data.time;\n }\n }\n }\n get header_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set header_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_header_hash() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get parent_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set parent_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_parent_hash() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get number() {\n return pb_1.Message.getFieldWithDefault(this, 3, new Uint8Array(0));\n }\n set number(value) {\n pb_1.Message.setOneofField(this, 3, this.#one_of_decls[2], value);\n }\n get has_number() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get difficulty() {\n return pb_1.Message.getFieldWithDefault(this, 4, new Uint8Array(0));\n }\n set difficulty(value) {\n pb_1.Message.setOneofField(this, 4, this.#one_of_decls[3], value);\n }\n get has_difficulty() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get tx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 5);\n }\n set tx_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 5, this.#one_of_decls[4], value);\n }\n get has_tx_hash() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get nonce() {\n return pb_1.Message.getFieldWithDefault(this, 6, 0);\n }\n set nonce(value) {\n pb_1.Message.setOneofField(this, 6, this.#one_of_decls[5], value);\n }\n get has_nonce() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get location() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoLocation, 7);\n }\n set location(value) {\n pb_1.Message.setOneofWrapperField(this, 7, this.#one_of_decls[6], value);\n }\n get has_location() {\n return pb_1.Message.getField(this, 7) != null;\n }\n get mix_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 8);\n }\n set mix_hash(value) {\n pb_1.Message.setOneofWrapperField(this, 8, this.#one_of_decls[7], value);\n }\n get has_mix_hash() {\n return pb_1.Message.getField(this, 8) != null;\n }\n get time() {\n return pb_1.Message.getFieldWithDefault(this, 9, 0);\n }\n set time(value) {\n pb_1.Message.setOneofField(this, 9, this.#one_of_decls[8], value);\n }\n get has_time() {\n return pb_1.Message.getField(this, 9) != null;\n }\n get _header_hash() {\n const cases = {\n 0: \"none\",\n 1: \"header_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _parent_hash() {\n const cases = {\n 0: \"none\",\n 2: \"parent_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _number() {\n const cases = {\n 0: \"none\",\n 3: \"number\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n get _difficulty() {\n const cases = {\n 0: \"none\",\n 4: \"difficulty\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [4])];\n }\n get _tx_hash() {\n const cases = {\n 0: \"none\",\n 5: \"tx_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [5])];\n }\n get _nonce() {\n const cases = {\n 0: \"none\",\n 6: \"nonce\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [6])];\n }\n get _location() {\n const cases = {\n 0: \"none\",\n 7: \"location\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [7])];\n }\n get _mix_hash() {\n const cases = {\n 0: \"none\",\n 8: \"mix_hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [8])];\n }\n get _time() {\n const cases = {\n 0: \"none\",\n 9: \"time\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [9])];\n }\n static fromObject(data) {\n const message = new ProtoWorkObjectHeader({});\n if (data.header_hash != null) {\n message.header_hash = dependency_1.common.ProtoHash.fromObject(data.header_hash);\n }\n if (data.parent_hash != null) {\n message.parent_hash = dependency_1.common.ProtoHash.fromObject(data.parent_hash);\n }\n if (data.number != null) {\n message.number = data.number;\n }\n if (data.difficulty != null) {\n message.difficulty = data.difficulty;\n }\n if (data.tx_hash != null) {\n message.tx_hash = dependency_1.common.ProtoHash.fromObject(data.tx_hash);\n }\n if (data.nonce != null) {\n message.nonce = data.nonce;\n }\n if (data.location != null) {\n message.location = dependency_1.common.ProtoLocation.fromObject(data.location);\n }\n if (data.mix_hash != null) {\n message.mix_hash = dependency_1.common.ProtoHash.fromObject(data.mix_hash);\n }\n if (data.time != null) {\n message.time = data.time;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.header_hash != null) {\n data.header_hash = this.header_hash.toObject();\n }\n if (this.parent_hash != null) {\n data.parent_hash = this.parent_hash.toObject();\n }\n if (this.number != null) {\n data.number = this.number;\n }\n if (this.difficulty != null) {\n data.difficulty = this.difficulty;\n }\n if (this.tx_hash != null) {\n data.tx_hash = this.tx_hash.toObject();\n }\n if (this.nonce != null) {\n data.nonce = this.nonce;\n }\n if (this.location != null) {\n data.location = this.location.toObject();\n }\n if (this.mix_hash != null) {\n data.mix_hash = this.mix_hash.toObject();\n }\n if (this.time != null) {\n data.time = this.time;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_header_hash)\n writer.writeMessage(1, this.header_hash, () => this.header_hash.serialize(writer));\n if (this.has_parent_hash)\n writer.writeMessage(2, this.parent_hash, () => this.parent_hash.serialize(writer));\n if (this.has_number)\n writer.writeBytes(3, this.number);\n if (this.has_difficulty)\n writer.writeBytes(4, this.difficulty);\n if (this.has_tx_hash)\n writer.writeMessage(5, this.tx_hash, () => this.tx_hash.serialize(writer));\n if (this.has_nonce)\n writer.writeUint64(6, this.nonce);\n if (this.has_location)\n writer.writeMessage(7, this.location, () => this.location.serialize(writer));\n if (this.has_mix_hash)\n writer.writeMessage(8, this.mix_hash, () => this.mix_hash.serialize(writer));\n if (this.has_time)\n writer.writeUint64(9, this.time);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjectHeader();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.header_hash, () => message.header_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.parent_hash, () => message.parent_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 3:\n message.number = reader.readBytes();\n break;\n case 4:\n message.difficulty = reader.readBytes();\n break;\n case 5:\n reader.readMessage(message.tx_hash, () => message.tx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 6:\n message.nonce = reader.readUint64();\n break;\n case 7:\n reader.readMessage(message.location, () => message.location = dependency_1.common.ProtoLocation.deserialize(reader));\n break;\n case 8:\n reader.readMessage(message.mix_hash, () => message.mix_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 9:\n message.time = reader.readUint64();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObjectHeader.deserialize(bytes);\n }\n }\n block.ProtoWorkObjectHeader = ProtoWorkObjectHeader;\n class ProtoWorkObjectHeaders extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"wo_headers\" in data && data.wo_headers != undefined) {\n this.wo_headers = data.wo_headers;\n }\n }\n }\n get wo_headers() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoWorkObjectHeader, 1);\n }\n set wo_headers(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoWorkObjectHeaders({});\n if (data.wo_headers != null) {\n message.wo_headers = data.wo_headers.map(item => ProtoWorkObjectHeader.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.wo_headers != null) {\n data.wo_headers = this.wo_headers.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.wo_headers.length)\n writer.writeRepeatedMessage(1, this.wo_headers, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjectHeaders();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.wo_headers, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoWorkObjectHeader.deserialize(reader), ProtoWorkObjectHeader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObjectHeaders.deserialize(bytes);\n }\n }\n block.ProtoWorkObjectHeaders = ProtoWorkObjectHeaders;\n class ProtoWorkObjectBody extends pb_1.Message {\n #one_of_decls = [[1], [2], [3], [4], [5], [6]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"header\" in data && data.header != undefined) {\n this.header = data.header;\n }\n if (\"transactions\" in data && data.transactions != undefined) {\n this.transactions = data.transactions;\n }\n if (\"uncles\" in data && data.uncles != undefined) {\n this.uncles = data.uncles;\n }\n if (\"ext_transactions\" in data && data.ext_transactions != undefined) {\n this.ext_transactions = data.ext_transactions;\n }\n if (\"manifest\" in data && data.manifest != undefined) {\n this.manifest = data.manifest;\n }\n if (\"interlink_hashes\" in data && data.interlink_hashes != undefined) {\n this.interlink_hashes = data.interlink_hashes;\n }\n }\n }\n get header() {\n return pb_1.Message.getWrapperField(this, ProtoHeader, 1);\n }\n set header(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_header() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get transactions() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 2);\n }\n set transactions(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_transactions() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get uncles() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObjectHeaders, 3);\n }\n set uncles(value) {\n pb_1.Message.setOneofWrapperField(this, 3, this.#one_of_decls[2], value);\n }\n get has_uncles() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get ext_transactions() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 4);\n }\n set ext_transactions(value) {\n pb_1.Message.setOneofWrapperField(this, 4, this.#one_of_decls[3], value);\n }\n get has_ext_transactions() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get manifest() {\n return pb_1.Message.getWrapperField(this, ProtoManifest, 5);\n }\n set manifest(value) {\n pb_1.Message.setOneofWrapperField(this, 5, this.#one_of_decls[4], value);\n }\n get has_manifest() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get interlink_hashes() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHashes, 6);\n }\n set interlink_hashes(value) {\n pb_1.Message.setOneofWrapperField(this, 6, this.#one_of_decls[5], value);\n }\n get has_interlink_hashes() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get _header() {\n const cases = {\n 0: \"none\",\n 1: \"header\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _transactions() {\n const cases = {\n 0: \"none\",\n 2: \"transactions\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _uncles() {\n const cases = {\n 0: \"none\",\n 3: \"uncles\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n get _ext_transactions() {\n const cases = {\n 0: \"none\",\n 4: \"ext_transactions\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [4])];\n }\n get _manifest() {\n const cases = {\n 0: \"none\",\n 5: \"manifest\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [5])];\n }\n get _interlink_hashes() {\n const cases = {\n 0: \"none\",\n 6: \"interlink_hashes\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [6])];\n }\n static fromObject(data) {\n const message = new ProtoWorkObjectBody({});\n if (data.header != null) {\n message.header = ProtoHeader.fromObject(data.header);\n }\n if (data.transactions != null) {\n message.transactions = ProtoTransactions.fromObject(data.transactions);\n }\n if (data.uncles != null) {\n message.uncles = ProtoWorkObjectHeaders.fromObject(data.uncles);\n }\n if (data.ext_transactions != null) {\n message.ext_transactions = ProtoTransactions.fromObject(data.ext_transactions);\n }\n if (data.manifest != null) {\n message.manifest = ProtoManifest.fromObject(data.manifest);\n }\n if (data.interlink_hashes != null) {\n message.interlink_hashes = dependency_1.common.ProtoHashes.fromObject(data.interlink_hashes);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.header != null) {\n data.header = this.header.toObject();\n }\n if (this.transactions != null) {\n data.transactions = this.transactions.toObject();\n }\n if (this.uncles != null) {\n data.uncles = this.uncles.toObject();\n }\n if (this.ext_transactions != null) {\n data.ext_transactions = this.ext_transactions.toObject();\n }\n if (this.manifest != null) {\n data.manifest = this.manifest.toObject();\n }\n if (this.interlink_hashes != null) {\n data.interlink_hashes = this.interlink_hashes.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_header)\n writer.writeMessage(1, this.header, () => this.header.serialize(writer));\n if (this.has_transactions)\n writer.writeMessage(2, this.transactions, () => this.transactions.serialize(writer));\n if (this.has_uncles)\n writer.writeMessage(3, this.uncles, () => this.uncles.serialize(writer));\n if (this.has_ext_transactions)\n writer.writeMessage(4, this.ext_transactions, () => this.ext_transactions.serialize(writer));\n if (this.has_manifest)\n writer.writeMessage(5, this.manifest, () => this.manifest.serialize(writer));\n if (this.has_interlink_hashes)\n writer.writeMessage(6, this.interlink_hashes, () => this.interlink_hashes.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjectBody();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.header, () => message.header = ProtoHeader.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.transactions, () => message.transactions = ProtoTransactions.deserialize(reader));\n break;\n case 3:\n reader.readMessage(message.uncles, () => message.uncles = ProtoWorkObjectHeaders.deserialize(reader));\n break;\n case 4:\n reader.readMessage(message.ext_transactions, () => message.ext_transactions = ProtoTransactions.deserialize(reader));\n break;\n case 5:\n reader.readMessage(message.manifest, () => message.manifest = ProtoManifest.deserialize(reader));\n break;\n case 6:\n reader.readMessage(message.interlink_hashes, () => message.interlink_hashes = dependency_1.common.ProtoHashes.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObjectBody.deserialize(bytes);\n }\n }\n block.ProtoWorkObjectBody = ProtoWorkObjectBody;\n class ProtoWorkObject extends pb_1.Message {\n #one_of_decls = [[1], [2], [3]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"wo_header\" in data && data.wo_header != undefined) {\n this.wo_header = data.wo_header;\n }\n if (\"wo_body\" in data && data.wo_body != undefined) {\n this.wo_body = data.wo_body;\n }\n if (\"tx\" in data && data.tx != undefined) {\n this.tx = data.tx;\n }\n }\n }\n get wo_header() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObjectHeader, 1);\n }\n set wo_header(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_wo_header() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get wo_body() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObjectBody, 2);\n }\n set wo_body(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_wo_body() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get tx() {\n return pb_1.Message.getWrapperField(this, ProtoTransaction, 3);\n }\n set tx(value) {\n pb_1.Message.setOneofWrapperField(this, 3, this.#one_of_decls[2], value);\n }\n get has_tx() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get _wo_header() {\n const cases = {\n 0: \"none\",\n 1: \"wo_header\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _wo_body() {\n const cases = {\n 0: \"none\",\n 2: \"wo_body\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n get _tx() {\n const cases = {\n 0: \"none\",\n 3: \"tx\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [3])];\n }\n static fromObject(data) {\n const message = new ProtoWorkObject({});\n if (data.wo_header != null) {\n message.wo_header = ProtoWorkObjectHeader.fromObject(data.wo_header);\n }\n if (data.wo_body != null) {\n message.wo_body = ProtoWorkObjectBody.fromObject(data.wo_body);\n }\n if (data.tx != null) {\n message.tx = ProtoTransaction.fromObject(data.tx);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.wo_header != null) {\n data.wo_header = this.wo_header.toObject();\n }\n if (this.wo_body != null) {\n data.wo_body = this.wo_body.toObject();\n }\n if (this.tx != null) {\n data.tx = this.tx.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_wo_header)\n writer.writeMessage(1, this.wo_header, () => this.wo_header.serialize(writer));\n if (this.has_wo_body)\n writer.writeMessage(2, this.wo_body, () => this.wo_body.serialize(writer));\n if (this.has_tx)\n writer.writeMessage(3, this.tx, () => this.tx.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObject();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.wo_header, () => message.wo_header = ProtoWorkObjectHeader.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.wo_body, () => message.wo_body = ProtoWorkObjectBody.deserialize(reader));\n break;\n case 3:\n reader.readMessage(message.tx, () => message.tx = ProtoTransaction.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObject.deserialize(bytes);\n }\n }\n block.ProtoWorkObject = ProtoWorkObject;\n class ProtoWorkObjects extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"work_objects\" in data && data.work_objects != undefined) {\n this.work_objects = data.work_objects;\n }\n }\n }\n get work_objects() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoWorkObject, 1);\n }\n set work_objects(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoWorkObjects({});\n if (data.work_objects != null) {\n message.work_objects = data.work_objects.map(item => ProtoWorkObject.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.work_objects != null) {\n data.work_objects = this.work_objects.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.work_objects.length)\n writer.writeRepeatedMessage(1, this.work_objects, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoWorkObjects();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.work_objects, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoWorkObject.deserialize(reader), ProtoWorkObject));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoWorkObjects.deserialize(bytes);\n }\n }\n block.ProtoWorkObjects = ProtoWorkObjects;\n class ProtoAccessTuple extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"address\" in data && data.address != undefined) {\n this.address = data.address;\n }\n if (\"storage_key\" in data && data.storage_key != undefined) {\n this.storage_key = data.storage_key;\n }\n }\n }\n get address() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set address(value) {\n pb_1.Message.setField(this, 1, value);\n }\n get storage_key() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set storage_key(value) {\n pb_1.Message.setRepeatedWrapperField(this, 2, value);\n }\n static fromObject(data) {\n const message = new ProtoAccessTuple({});\n if (data.address != null) {\n message.address = data.address;\n }\n if (data.storage_key != null) {\n message.storage_key = data.storage_key.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.address != null) {\n data.address = this.address;\n }\n if (this.storage_key != null) {\n data.storage_key = this.storage_key.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.address.length)\n writer.writeBytes(1, this.address);\n if (this.storage_key.length)\n writer.writeRepeatedMessage(2, this.storage_key, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoAccessTuple();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.address = reader.readBytes();\n break;\n case 2:\n reader.readMessage(message.storage_key, () => pb_1.Message.addToRepeatedWrapperField(message, 2, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoAccessTuple.deserialize(bytes);\n }\n }\n block.ProtoAccessTuple = ProtoAccessTuple;\n class ProtoReceiptForStorage extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"post_state_or_status\" in data && data.post_state_or_status != undefined) {\n this.post_state_or_status = data.post_state_or_status;\n }\n if (\"cumulative_gas_used\" in data && data.cumulative_gas_used != undefined) {\n this.cumulative_gas_used = data.cumulative_gas_used;\n }\n if (\"tx_hash\" in data && data.tx_hash != undefined) {\n this.tx_hash = data.tx_hash;\n }\n if (\"contract_address\" in data && data.contract_address != undefined) {\n this.contract_address = data.contract_address;\n }\n if (\"logs\" in data && data.logs != undefined) {\n this.logs = data.logs;\n }\n if (\"etxs\" in data && data.etxs != undefined) {\n this.etxs = data.etxs;\n }\n if (\"gas_used\" in data && data.gas_used != undefined) {\n this.gas_used = data.gas_used;\n }\n }\n }\n get post_state_or_status() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set post_state_or_status(value) {\n pb_1.Message.setField(this, 1, value);\n }\n get cumulative_gas_used() {\n return pb_1.Message.getFieldWithDefault(this, 2, 0);\n }\n set cumulative_gas_used(value) {\n pb_1.Message.setField(this, 2, value);\n }\n get tx_hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 3);\n }\n set tx_hash(value) {\n pb_1.Message.setWrapperField(this, 3, value);\n }\n get has_tx_hash() {\n return pb_1.Message.getField(this, 3) != null;\n }\n get contract_address() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoAddress, 4);\n }\n set contract_address(value) {\n pb_1.Message.setWrapperField(this, 4, value);\n }\n get has_contract_address() {\n return pb_1.Message.getField(this, 4) != null;\n }\n get logs() {\n return pb_1.Message.getWrapperField(this, ProtoLogsForStorage, 5);\n }\n set logs(value) {\n pb_1.Message.setWrapperField(this, 5, value);\n }\n get has_logs() {\n return pb_1.Message.getField(this, 5) != null;\n }\n get etxs() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 6);\n }\n set etxs(value) {\n pb_1.Message.setWrapperField(this, 6, value);\n }\n get has_etxs() {\n return pb_1.Message.getField(this, 6) != null;\n }\n get gas_used() {\n return pb_1.Message.getFieldWithDefault(this, 7, 0);\n }\n set gas_used(value) {\n pb_1.Message.setField(this, 7, value);\n }\n static fromObject(data) {\n const message = new ProtoReceiptForStorage({});\n if (data.post_state_or_status != null) {\n message.post_state_or_status = data.post_state_or_status;\n }\n if (data.cumulative_gas_used != null) {\n message.cumulative_gas_used = data.cumulative_gas_used;\n }\n if (data.tx_hash != null) {\n message.tx_hash = dependency_1.common.ProtoHash.fromObject(data.tx_hash);\n }\n if (data.contract_address != null) {\n message.contract_address = dependency_1.common.ProtoAddress.fromObject(data.contract_address);\n }\n if (data.logs != null) {\n message.logs = ProtoLogsForStorage.fromObject(data.logs);\n }\n if (data.etxs != null) {\n message.etxs = ProtoTransactions.fromObject(data.etxs);\n }\n if (data.gas_used != null) {\n message.gas_used = data.gas_used;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.post_state_or_status != null) {\n data.post_state_or_status = this.post_state_or_status;\n }\n if (this.cumulative_gas_used != null) {\n data.cumulative_gas_used = this.cumulative_gas_used;\n }\n if (this.tx_hash != null) {\n data.tx_hash = this.tx_hash.toObject();\n }\n if (this.contract_address != null) {\n data.contract_address = this.contract_address.toObject();\n }\n if (this.logs != null) {\n data.logs = this.logs.toObject();\n }\n if (this.etxs != null) {\n data.etxs = this.etxs.toObject();\n }\n if (this.gas_used != null) {\n data.gas_used = this.gas_used;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.post_state_or_status.length)\n writer.writeBytes(1, this.post_state_or_status);\n if (this.cumulative_gas_used != 0)\n writer.writeUint64(2, this.cumulative_gas_used);\n if (this.has_tx_hash)\n writer.writeMessage(3, this.tx_hash, () => this.tx_hash.serialize(writer));\n if (this.has_contract_address)\n writer.writeMessage(4, this.contract_address, () => this.contract_address.serialize(writer));\n if (this.has_logs)\n writer.writeMessage(5, this.logs, () => this.logs.serialize(writer));\n if (this.has_etxs)\n writer.writeMessage(6, this.etxs, () => this.etxs.serialize(writer));\n if (this.gas_used != 0)\n writer.writeUint64(7, this.gas_used);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoReceiptForStorage();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.post_state_or_status = reader.readBytes();\n break;\n case 2:\n message.cumulative_gas_used = reader.readUint64();\n break;\n case 3:\n reader.readMessage(message.tx_hash, () => message.tx_hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 4:\n reader.readMessage(message.contract_address, () => message.contract_address = dependency_1.common.ProtoAddress.deserialize(reader));\n break;\n case 5:\n reader.readMessage(message.logs, () => message.logs = ProtoLogsForStorage.deserialize(reader));\n break;\n case 6:\n reader.readMessage(message.etxs, () => message.etxs = ProtoTransactions.deserialize(reader));\n break;\n case 7:\n message.gas_used = reader.readUint64();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoReceiptForStorage.deserialize(bytes);\n }\n }\n block.ProtoReceiptForStorage = ProtoReceiptForStorage;\n class ProtoReceiptsForStorage extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"receipts\" in data && data.receipts != undefined) {\n this.receipts = data.receipts;\n }\n }\n }\n get receipts() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoReceiptForStorage, 1);\n }\n set receipts(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoReceiptsForStorage({});\n if (data.receipts != null) {\n message.receipts = data.receipts.map(item => ProtoReceiptForStorage.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.receipts != null) {\n data.receipts = this.receipts.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.receipts.length)\n writer.writeRepeatedMessage(1, this.receipts, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoReceiptsForStorage();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.receipts, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoReceiptForStorage.deserialize(reader), ProtoReceiptForStorage));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoReceiptsForStorage.deserialize(bytes);\n }\n }\n block.ProtoReceiptsForStorage = ProtoReceiptsForStorage;\n class ProtoLogForStorage extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [2], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"address\" in data && data.address != undefined) {\n this.address = data.address;\n }\n if (\"topics\" in data && data.topics != undefined) {\n this.topics = data.topics;\n }\n if (\"data\" in data && data.data != undefined) {\n this.data = data.data;\n }\n }\n }\n get address() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoAddress, 1);\n }\n set address(value) {\n pb_1.Message.setWrapperField(this, 1, value);\n }\n get has_address() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get topics() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set topics(value) {\n pb_1.Message.setRepeatedWrapperField(this, 2, value);\n }\n get data() {\n return pb_1.Message.getFieldWithDefault(this, 3, new Uint8Array(0));\n }\n set data(value) {\n pb_1.Message.setField(this, 3, value);\n }\n static fromObject(data) {\n const message = new ProtoLogForStorage({});\n if (data.address != null) {\n message.address = dependency_1.common.ProtoAddress.fromObject(data.address);\n }\n if (data.topics != null) {\n message.topics = data.topics.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n if (data.data != null) {\n message.data = data.data;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.address != null) {\n data.address = this.address.toObject();\n }\n if (this.topics != null) {\n data.topics = this.topics.map((item) => item.toObject());\n }\n if (this.data != null) {\n data.data = this.data;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_address)\n writer.writeMessage(1, this.address, () => this.address.serialize(writer));\n if (this.topics.length)\n writer.writeRepeatedMessage(2, this.topics, (item) => item.serialize(writer));\n if (this.data.length)\n writer.writeBytes(3, this.data);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLogForStorage();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.address, () => message.address = dependency_1.common.ProtoAddress.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.topics, () => pb_1.Message.addToRepeatedWrapperField(message, 2, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n case 3:\n message.data = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoLogForStorage.deserialize(bytes);\n }\n }\n block.ProtoLogForStorage = ProtoLogForStorage;\n class ProtoLogsForStorage extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"logs\" in data && data.logs != undefined) {\n this.logs = data.logs;\n }\n }\n }\n get logs() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoLogForStorage, 1);\n }\n set logs(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoLogsForStorage({});\n if (data.logs != null) {\n message.logs = data.logs.map(item => ProtoLogForStorage.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.logs != null) {\n data.logs = this.logs.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.logs.length)\n writer.writeRepeatedMessage(1, this.logs, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoLogsForStorage();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.logs, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoLogForStorage.deserialize(reader), ProtoLogForStorage));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoLogsForStorage.deserialize(bytes);\n }\n }\n block.ProtoLogsForStorage = ProtoLogsForStorage;\n class ProtoPendingHeader extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"wo\" in data && data.wo != undefined) {\n this.wo = data.wo;\n }\n if (\"termini\" in data && data.termini != undefined) {\n this.termini = data.termini;\n }\n }\n }\n get wo() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObject, 1);\n }\n set wo(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_wo() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get termini() {\n return pb_1.Message.getWrapperField(this, ProtoTermini, 2);\n }\n set termini(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_termini() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _wo() {\n const cases = {\n 0: \"none\",\n 1: \"wo\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _termini() {\n const cases = {\n 0: \"none\",\n 2: \"termini\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoPendingHeader({});\n if (data.wo != null) {\n message.wo = ProtoWorkObject.fromObject(data.wo);\n }\n if (data.termini != null) {\n message.termini = ProtoTermini.fromObject(data.termini);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.wo != null) {\n data.wo = this.wo.toObject();\n }\n if (this.termini != null) {\n data.termini = this.termini.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_wo)\n writer.writeMessage(1, this.wo, () => this.wo.serialize(writer));\n if (this.has_termini)\n writer.writeMessage(2, this.termini, () => this.termini.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoPendingHeader();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.wo, () => message.wo = ProtoWorkObject.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.termini, () => message.termini = ProtoTermini.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoPendingHeader.deserialize(bytes);\n }\n }\n block.ProtoPendingHeader = ProtoPendingHeader;\n class ProtoTermini extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1, 2], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"dom_termini\" in data && data.dom_termini != undefined) {\n this.dom_termini = data.dom_termini;\n }\n if (\"sub_termini\" in data && data.sub_termini != undefined) {\n this.sub_termini = data.sub_termini;\n }\n }\n }\n get dom_termini() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set dom_termini(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n get sub_termini() {\n return pb_1.Message.getRepeatedWrapperField(this, dependency_1.common.ProtoHash, 2);\n }\n set sub_termini(value) {\n pb_1.Message.setRepeatedWrapperField(this, 2, value);\n }\n static fromObject(data) {\n const message = new ProtoTermini({});\n if (data.dom_termini != null) {\n message.dom_termini = data.dom_termini.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n if (data.sub_termini != null) {\n message.sub_termini = data.sub_termini.map(item => dependency_1.common.ProtoHash.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.dom_termini != null) {\n data.dom_termini = this.dom_termini.map((item) => item.toObject());\n }\n if (this.sub_termini != null) {\n data.sub_termini = this.sub_termini.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.dom_termini.length)\n writer.writeRepeatedMessage(1, this.dom_termini, (item) => item.serialize(writer));\n if (this.sub_termini.length)\n writer.writeRepeatedMessage(2, this.sub_termini, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTermini();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.dom_termini, () => pb_1.Message.addToRepeatedWrapperField(message, 1, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n case 2:\n reader.readMessage(message.sub_termini, () => pb_1.Message.addToRepeatedWrapperField(message, 2, dependency_1.common.ProtoHash.deserialize(reader), dependency_1.common.ProtoHash));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTermini.deserialize(bytes);\n }\n }\n block.ProtoTermini = ProtoTermini;\n class ProtoEtxSet extends pb_1.Message {\n #one_of_decls = [[1]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"etx_hashes\" in data && data.etx_hashes != undefined) {\n this.etx_hashes = data.etx_hashes;\n }\n }\n }\n get etx_hashes() {\n return pb_1.Message.getFieldWithDefault(this, 1, new Uint8Array(0));\n }\n set etx_hashes(value) {\n pb_1.Message.setOneofField(this, 1, this.#one_of_decls[0], value);\n }\n get has_etx_hashes() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get _etx_hashes() {\n const cases = {\n 0: \"none\",\n 1: \"etx_hashes\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n static fromObject(data) {\n const message = new ProtoEtxSet({});\n if (data.etx_hashes != null) {\n message.etx_hashes = data.etx_hashes;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.etx_hashes != null) {\n data.etx_hashes = this.etx_hashes;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_etx_hashes)\n writer.writeBytes(1, this.etx_hashes);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoEtxSet();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.etx_hashes = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoEtxSet.deserialize(bytes);\n }\n }\n block.ProtoEtxSet = ProtoEtxSet;\n class ProtoPendingEtxs extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"header\" in data && data.header != undefined) {\n this.header = data.header;\n }\n if (\"etxs\" in data && data.etxs != undefined) {\n this.etxs = data.etxs;\n }\n }\n }\n get header() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObject, 1);\n }\n set header(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_header() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get etxs() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 2);\n }\n set etxs(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_etxs() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _header() {\n const cases = {\n 0: \"none\",\n 1: \"header\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _etxs() {\n const cases = {\n 0: \"none\",\n 2: \"etxs\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoPendingEtxs({});\n if (data.header != null) {\n message.header = ProtoWorkObject.fromObject(data.header);\n }\n if (data.etxs != null) {\n message.etxs = ProtoTransactions.fromObject(data.etxs);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.header != null) {\n data.header = this.header.toObject();\n }\n if (this.etxs != null) {\n data.etxs = this.etxs.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_header)\n writer.writeMessage(1, this.header, () => this.header.serialize(writer));\n if (this.has_etxs)\n writer.writeMessage(2, this.etxs, () => this.etxs.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoPendingEtxs();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.header, () => message.header = ProtoWorkObject.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.etxs, () => message.etxs = ProtoTransactions.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoPendingEtxs.deserialize(bytes);\n }\n }\n block.ProtoPendingEtxs = ProtoPendingEtxs;\n class ProtoPendingEtxsRollup extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"header\" in data && data.header != undefined) {\n this.header = data.header;\n }\n if (\"etxs_rollup\" in data && data.etxs_rollup != undefined) {\n this.etxs_rollup = data.etxs_rollup;\n }\n }\n }\n get header() {\n return pb_1.Message.getWrapperField(this, ProtoWorkObject, 1);\n }\n set header(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_header() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get etxs_rollup() {\n return pb_1.Message.getWrapperField(this, ProtoTransactions, 2);\n }\n set etxs_rollup(value) {\n pb_1.Message.setOneofWrapperField(this, 2, this.#one_of_decls[1], value);\n }\n get has_etxs_rollup() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _header() {\n const cases = {\n 0: \"none\",\n 1: \"header\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _etxs_rollup() {\n const cases = {\n 0: \"none\",\n 2: \"etxs_rollup\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoPendingEtxsRollup({});\n if (data.header != null) {\n message.header = ProtoWorkObject.fromObject(data.header);\n }\n if (data.etxs_rollup != null) {\n message.etxs_rollup = ProtoTransactions.fromObject(data.etxs_rollup);\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.header != null) {\n data.header = this.header.toObject();\n }\n if (this.etxs_rollup != null) {\n data.etxs_rollup = this.etxs_rollup.toObject();\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_header)\n writer.writeMessage(1, this.header, () => this.header.serialize(writer));\n if (this.has_etxs_rollup)\n writer.writeMessage(2, this.etxs_rollup, () => this.etxs_rollup.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoPendingEtxsRollup();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.header, () => message.header = ProtoWorkObject.deserialize(reader));\n break;\n case 2:\n reader.readMessage(message.etxs_rollup, () => message.etxs_rollup = ProtoTransactions.deserialize(reader));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoPendingEtxsRollup.deserialize(bytes);\n }\n }\n block.ProtoPendingEtxsRollup = ProtoPendingEtxsRollup;\n class ProtoTxIns extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"tx_ins\" in data && data.tx_ins != undefined) {\n this.tx_ins = data.tx_ins;\n }\n }\n }\n get tx_ins() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoTxIn, 1);\n }\n set tx_ins(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoTxIns({});\n if (data.tx_ins != null) {\n message.tx_ins = data.tx_ins.map(item => ProtoTxIn.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.tx_ins != null) {\n data.tx_ins = this.tx_ins.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.tx_ins.length)\n writer.writeRepeatedMessage(1, this.tx_ins, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxIns();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.tx_ins, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoTxIn.deserialize(reader), ProtoTxIn));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTxIns.deserialize(bytes);\n }\n }\n block.ProtoTxIns = ProtoTxIns;\n class ProtoTxOuts extends pb_1.Message {\n #one_of_decls = [];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [1], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"tx_outs\" in data && data.tx_outs != undefined) {\n this.tx_outs = data.tx_outs;\n }\n }\n }\n get tx_outs() {\n return pb_1.Message.getRepeatedWrapperField(this, ProtoTxOut, 1);\n }\n set tx_outs(value) {\n pb_1.Message.setRepeatedWrapperField(this, 1, value);\n }\n static fromObject(data) {\n const message = new ProtoTxOuts({});\n if (data.tx_outs != null) {\n message.tx_outs = data.tx_outs.map(item => ProtoTxOut.fromObject(item));\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.tx_outs != null) {\n data.tx_outs = this.tx_outs.map((item) => item.toObject());\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.tx_outs.length)\n writer.writeRepeatedMessage(1, this.tx_outs, (item) => item.serialize(writer));\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxOuts();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.tx_outs, () => pb_1.Message.addToRepeatedWrapperField(message, 1, ProtoTxOut.deserialize(reader), ProtoTxOut));\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTxOuts.deserialize(bytes);\n }\n }\n block.ProtoTxOuts = ProtoTxOuts;\n class ProtoTxIn extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"previous_out_point\" in data && data.previous_out_point != undefined) {\n this.previous_out_point = data.previous_out_point;\n }\n if (\"pub_key\" in data && data.pub_key != undefined) {\n this.pub_key = data.pub_key;\n }\n }\n }\n get previous_out_point() {\n return pb_1.Message.getWrapperField(this, ProtoOutPoint, 1);\n }\n set previous_out_point(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_previous_out_point() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get pub_key() {\n return pb_1.Message.getFieldWithDefault(this, 2, new Uint8Array(0));\n }\n set pub_key(value) {\n pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value);\n }\n get has_pub_key() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _previous_out_point() {\n const cases = {\n 0: \"none\",\n 1: \"previous_out_point\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _pub_key() {\n const cases = {\n 0: \"none\",\n 2: \"pub_key\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoTxIn({});\n if (data.previous_out_point != null) {\n message.previous_out_point = ProtoOutPoint.fromObject(data.previous_out_point);\n }\n if (data.pub_key != null) {\n message.pub_key = data.pub_key;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.previous_out_point != null) {\n data.previous_out_point = this.previous_out_point.toObject();\n }\n if (this.pub_key != null) {\n data.pub_key = this.pub_key;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_previous_out_point)\n writer.writeMessage(1, this.previous_out_point, () => this.previous_out_point.serialize(writer));\n if (this.has_pub_key)\n writer.writeBytes(2, this.pub_key);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxIn();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.previous_out_point, () => message.previous_out_point = ProtoOutPoint.deserialize(reader));\n break;\n case 2:\n message.pub_key = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTxIn.deserialize(bytes);\n }\n }\n block.ProtoTxIn = ProtoTxIn;\n class ProtoOutPoint extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"hash\" in data && data.hash != undefined) {\n this.hash = data.hash;\n }\n if (\"index\" in data && data.index != undefined) {\n this.index = data.index;\n }\n }\n }\n get hash() {\n return pb_1.Message.getWrapperField(this, dependency_1.common.ProtoHash, 1);\n }\n set hash(value) {\n pb_1.Message.setOneofWrapperField(this, 1, this.#one_of_decls[0], value);\n }\n get has_hash() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get index() {\n return pb_1.Message.getFieldWithDefault(this, 2, 0);\n }\n set index(value) {\n pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value);\n }\n get has_index() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _hash() {\n const cases = {\n 0: \"none\",\n 1: \"hash\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _index() {\n const cases = {\n 0: \"none\",\n 2: \"index\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoOutPoint({});\n if (data.hash != null) {\n message.hash = dependency_1.common.ProtoHash.fromObject(data.hash);\n }\n if (data.index != null) {\n message.index = data.index;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.hash != null) {\n data.hash = this.hash.toObject();\n }\n if (this.index != null) {\n data.index = this.index;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_hash)\n writer.writeMessage(1, this.hash, () => this.hash.serialize(writer));\n if (this.has_index)\n writer.writeUint32(2, this.index);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoOutPoint();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n reader.readMessage(message.hash, () => message.hash = dependency_1.common.ProtoHash.deserialize(reader));\n break;\n case 2:\n message.index = reader.readUint32();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoOutPoint.deserialize(bytes);\n }\n }\n block.ProtoOutPoint = ProtoOutPoint;\n class ProtoTxOut extends pb_1.Message {\n #one_of_decls = [[1], [2]];\n constructor(data) {\n super();\n pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], this.#one_of_decls);\n if (!Array.isArray(data) && typeof data == \"object\") {\n if (\"denomination\" in data && data.denomination != undefined) {\n this.denomination = data.denomination;\n }\n if (\"address\" in data && data.address != undefined) {\n this.address = data.address;\n }\n }\n }\n get denomination() {\n return pb_1.Message.getFieldWithDefault(this, 1, 0);\n }\n set denomination(value) {\n pb_1.Message.setOneofField(this, 1, this.#one_of_decls[0], value);\n }\n get has_denomination() {\n return pb_1.Message.getField(this, 1) != null;\n }\n get address() {\n return pb_1.Message.getFieldWithDefault(this, 2, new Uint8Array(0));\n }\n set address(value) {\n pb_1.Message.setOneofField(this, 2, this.#one_of_decls[1], value);\n }\n get has_address() {\n return pb_1.Message.getField(this, 2) != null;\n }\n get _denomination() {\n const cases = {\n 0: \"none\",\n 1: \"denomination\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [1])];\n }\n get _address() {\n const cases = {\n 0: \"none\",\n 2: \"address\"\n };\n return cases[pb_1.Message.computeOneofCase(this, [2])];\n }\n static fromObject(data) {\n const message = new ProtoTxOut({});\n if (data.denomination != null) {\n message.denomination = data.denomination;\n }\n if (data.address != null) {\n message.address = data.address;\n }\n return message;\n }\n toObject() {\n const data = {};\n if (this.denomination != null) {\n data.denomination = this.denomination;\n }\n if (this.address != null) {\n data.address = this.address;\n }\n return data;\n }\n serialize(w) {\n const writer = w || new pb_1.BinaryWriter();\n if (this.has_denomination)\n writer.writeUint32(1, this.denomination);\n if (this.has_address)\n writer.writeBytes(2, this.address);\n if (!w)\n return writer.getResultBuffer();\n }\n static deserialize(bytes) {\n const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new ProtoTxOut();\n while (reader.nextField()) {\n if (reader.isEndGroup())\n break;\n switch (reader.getFieldNumber()) {\n case 1:\n message.denomination = reader.readUint32();\n break;\n case 2:\n message.address = reader.readBytes();\n break;\n default: reader.skipField();\n }\n }\n return message;\n }\n serializeBinary() {\n return this.serialize();\n }\n static deserializeBinary(bytes) {\n return ProtoTxOut.deserialize(bytes);\n }\n }\n block.ProtoTxOut = ProtoTxOut;\n})(block || (block = {}));\n//# sourceMappingURL=proto_block.js.map","import { hexlify } from '../utils/index.js';\nimport * as Proto from './protoc/proto_block.js';\n/**\n * @category Encoding\n * @param {ProtoTransaction} protoTx - The signed constructed transaction\n * @returns {string} - The Protobuf encoded transaction\n */\nexport function encodeProtoTransaction(protoTx) {\n const tx = Proto.block.ProtoTransaction.fromObject(protoTx);\n return hexlify(tx.serialize());\n}\n/**\n * @category Encoding\n * @param {ProtoWorkObject} protoWo - The constructed WorkObject\n * @returns {string} - The Protobuf encoded WorkObject\n */\nexport function encodeProtoWorkObject(protoWo) {\n const wo = Proto.block.ProtoWorkObject.fromObject(protoWo);\n return hexlify(wo.serialize());\n}\n//# sourceMappingURL=proto-encode.js.map","import * as Proto from './protoc/proto_block.js';\n/**\n * @category Encoding\n * @param {Uint8Array} bytes - The Protobuf encoded transaction\n * @returns {ProtoTransaction} - The decoded transaction\n */\nexport function decodeProtoTransaction(bytes) {\n const tx = Proto.block.ProtoTransaction.deserialize(bytes);\n const result = tx.toObject();\n if (result.to?.length == 0) {\n result.to = null;\n }\n return result;\n}\n/**\n * @category Encoding\n * @param {Uint8Array} bytes - The Protobuf encoded work object\n * @returns {ProtoWorkObject} - The decoded work object\n */\nexport function decodeProtoWorkObject(bytes) {\n const wo = Proto.block.ProtoWorkObject.deserialize(bytes);\n return wo.toObject();\n}\n//# sourceMappingURL=proto-decode.js.map","/**\n * Using strings in Ethereum (or any security-basd system) requires additional care. These utilities attempt to mitigate\n * some of the safety issues as well as provide the ability to recover and analyse strings.\n *\n * @subsection api/utils:Strings and UTF-8 [about-strings]\n */\nimport { getBytes } from '../utils/data.js';\nimport { assertArgument, assertNormalize } from '../utils/errors.js';\n// `output` and `badCodepoint` are passed to calls below, but not used in the function\nfunction errorFunc(reason, offset, bytes, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\noutput, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nbadCodepoint) {\n assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, 'bytes', bytes);\n}\n// `output` and `badCodepoint` are passed to calls below, but not used in the function\nfunction ignoreFunc(reason, offset, bytes, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\noutput, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nbadCodepoint) {\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 non-canonical (overlong) codepoints (this is the default)\n *\n * **`\"ignore\"`** - silently drops any illegal UTF-8 sequence and accepts non-canonical (overlong) codepoints\n *\n * **`\"replace\"`** - replace any illegal UTF-8 sequence with the UTF-8 replacement character (i.e. `\"\\\\ufffd\"`) and\n * accepts non-canonical (overlong) codepoints\n *\n * @category Encoding\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 const 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 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 *\n * @category Encoding\n * @param {string} str - The string to convert.\n * @param {UnicodeNormalizationForm} [form] - The normalization form to use.\n *\n * @returns {Uint8Array} The UTF-8 byte representation.\n * @throws {Error} If the UTF-8 conversion fails.\n */\nexport function toUtf8Bytes(str, form) {\n if (form != null) {\n assertNormalize(form);\n str = str.normalize(form);\n }\n const 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 * @ignore\n */\nfunction _toUtf8String(codePoints) {\n return codePoints\n .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 })\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 errors allowing recovery using the\n * {@link Utf8ErrorFunc | **Utf8ErrorFunc**} API. (default: [error](Utf8ErrorFuncs))\n *\n * @category Encoding\n * @param {BytesLike} bytes - The UTF-8 data to convert.\n * @param {Utf8ErrorFunc} [onError] - The error handling function.\n *\n * @returns {string} The string.\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 *\n * @category Encoding\n * @param {string} str - The string to convert.\n * @param {UnicodeNormalizationForm} [form] - The normalization form to use.\n *\n * @returns {number[]} The UTF-8 code-points.\n */\nexport function toUtf8CodePoints(str, form) {\n return getUtf8CodePoints(toUtf8Bytes(str, form));\n}\n//# sourceMappingURL=utf8.js.map","import { assert } from './errors.js';\n// @TODO: timeout is completely ignored; start a Promise.any with a reject?\n// TODO: `options` is not used; remove?\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function createGetUrl(options) {\n async function getUrl(req, _signal) {\n const protocol = req.url.split(':')[0].toLowerCase();\n assert(protocol === 'http' || protocol === 'https', `unsupported protocol ${protocol}`, 'UNSUPPORTED_OPERATION', {\n info: { protocol },\n operation: 'request',\n });\n assert(protocol === 'https' || !req.credentials || req.allowInsecureAuthentication, 'insecure authorized connections unsupported', 'UNSUPPORTED_OPERATION', {\n operation: 'request',\n });\n let signal = undefined;\n if (_signal) {\n const controller = new AbortController();\n signal = controller.signal;\n _signal.addListener(() => {\n controller.abort();\n });\n }\n const init = {\n method: req.method,\n headers: new Headers(Array.from(req)),\n body: req.body || undefined,\n signal,\n };\n const resp = await fetch(req.url, init);\n const headers = {};\n resp.headers.forEach((value, key) => {\n headers[key.toLowerCase()] = value;\n });\n const respBody = await resp.arrayBuffer();\n const body = respBody == null ? null : new Uint8Array(respBody);\n return {\n statusCode: resp.status,\n statusMessage: resp.statusText,\n headers,\n body,\n };\n }\n return getUrl;\n}\n// @TODO: remove in v7; provided for backwards compat\nconst defaultGetUrl = createGetUrl({});\nexport async function getUrl(req, _signal) {\n return defaultGetUrl(req, _signal);\n}\n//# sourceMappingURL=geturl-browser.js.map","/**\n * Fetching content from the web is environment-specific, so quais provides an abstraction that each environment can\n * implement to provide this service.\n *\n * On [Node.js](https://nodejs.org/), the `http` and `https` libs are used to create a request object, register event\n * listeners and process data and populate the {@link FetchResponse | **FetchResponse**}.\n *\n * In a browser, the [DOM fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) is used, and the resulting\n * `Promise` is waited on to retrieve the payload.\n *\n * The {@link FetchRequest | **FetchRequest**} is responsible for handling many common situations, such as redirects,\n * server throttling, authentication, etc.\n *\n * It also handles common gateways, such as IPFS and data URIs.\n */\nimport { decodeBase64, encodeBase64 } from '../encoding/base64.js';\nimport { hexlify } from './data.js';\nimport { assert, assertArgument } from './errors.js';\nimport { defineProperties } from './properties.js';\nimport { toUtf8Bytes, toUtf8String } from '../encoding/index.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\n// TODO: `signal` is not used; remove?\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\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 {@link FetchGatewayFunc | **FetchGatewayFunc**} for fetching content from a standard IPFS gateway hosted at\n * `baseUrl`.\n *\n * @category Utils\n * @param {string} baseUrl - The base URL of the IPFS gateway.\n * @returns {FetchGatewayFunc} The gateway function.\n */\nfunction getIpfsGatewayFunc(baseUrl) {\n // TODO: `signal` is not used; remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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(() => {\n listener();\n }, 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() {\n return this.#cancelled;\n }\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:`, and `IPFS:`.\n *\n * Additional schemes can be added globally using {@link registerGateway | **registerGateway**}.\n *\n * @category Utils\n * @example\n *\n * ```ts\n * req = new FetchRequest('https://www.ricmoo.com');\n * resp = await req.send();\n * resp.body.length;\n * ```\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() {\n return this.#url;\n }\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 set and will be used if **not overridden** by\n * setting a custom header.\n *\n * If `body` is null, the body is cleared (along with the intrinsic `Content-Type`).\n *\n * If `body` is a string, the intrinsic `Content-Type` is set to `text/plain`.\n *\n * If `body` is a Uint8Array, the intrinsic `Content-Type` is set to `application/octet-stream`.\n *\n * If `body` is any other object, the intrinsic `Content-Type` is 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 has been explicitly set, then `GET` is used if the\n * body is 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 keys are lower-case.\n *\n * This object is a copy, so any changes will **NOT** be reflected 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 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 * @param {string} key - The header key to retrieve.\n * @returns {string} The header value.\n */\n getHeader(key) {\n return this.headers[key.toLowerCase()];\n }\n /**\n * Set the header for `key` to `value`. All values are coerced to a string.\n *\n * @param {string} key - The header key to set.\n * @param {string | number} value - The header value to set.\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]],\n 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 * @param {string} username - The username to use for basic authentication.\n * @param {string} password - The password to use for basic authentication.\n * @throws {Error} If the `username` contains a colon.\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 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 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. (default: 5 minutes)\n */\n get timeout() {\n return this.#timeout;\n }\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 during a redirection or retry in case of server\n * throttling.\n *\n * This offers an opportunity to populate headers or update 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 opportunity to provide client-level throttling or\n * updating 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 has not been reached), use\n * {@link FetchResponse.throwThrottleError | **FetchResponse.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 HTTPS URLs and is platform specific (e.g. nodejs vs\n * browsers).\n *\n * This is by default the currently registered global getUrl function, which can be changed using\n * {@link registerGetUrl | **registerGetUrl**}. If this has been set, setting is to `null` will cause this\n * FetchRequest (and any future clones) to revert back to using the currently registered global getUrl function.\n *\n * Setting this is generally not necessary, but may be useful 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 `.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 ``;\n }\n /**\n * Update the throttle parameters used to determine maximum attempts and exponential-backoff properties.\n *\n * @param {FetchThrottleParams} params - The throttle parameters to set.\n * @throws {Error} If the `slotInterval` is not a positive integer.\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',\n reason: 'timeout',\n 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 // eslint-disable-next-line no-empty\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 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', {\n operation: 'fetchRequest.send',\n });\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` error to be rejected from the\n * {@link FetchRequest.send | **send**}.\n */\n cancel() {\n assert(this.#signal != null, 'request has not been sent', 'UNSUPPORTED_OPERATION', {\n operation: 'fetchRequest.cancel',\n });\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 {@link FetchRequest | **FetchRequest**} that represents the redirection to `location`.\n *\n * @param {string} location - The location to redirect to.\n * @returns {FetchRequest} The new request.\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 return req;\n }\n /**\n * Create a new copy of this request.\n *\n * @returns {FetchRequest} The new 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.#getUrlFunc = this.#getUrlFunc;\n return clone;\n }\n /**\n * Locks all static configuration for gateways and FetchGetUrlFunc registration.\n */\n static lockConfig() {\n locked = true;\n }\n /**\n * Get the current Gateway function for `scheme`.\n *\n * @param {string} scheme - The scheme to get the gateway for.\n * @returns {FetchGatewayFunc | null} The gateway function, or null if not found.\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 {@link FetchRequest.lockConfig | **lockConfig**} has been called, no change is made and this throws.\n *\n * @param {string} scheme - The scheme to register the gateway for.\n * @param {FetchGatewayFunc} func - The gateway function to use.\n * @throws {Error} If the scheme is `http` or `https`.\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 {@link FetchRequest.lockConfig | **lockConfig**} has been called, no change is made and this throws.\n *\n * @param {FetchGetUrlFunc} getUrl - The function to use for fetching HTTP and HTTPS URIs.\n * @throws {Error} If the gateways are locked.\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 HTTPS URLs.\n *\n * The available `options` are dependent on the platform implementation of the default getUrl function.\n *\n * This is not generally something that is needed, but is useful when trying to customize simple behaviour when\n * fetching HTTP content.\n *\n * @param {Record} [options] - The options to use when creating the getUrl function.\n * @returns {FetchGetUrlFunc} The getUrl function.\n * @throws {Error} If the gateways are locked.\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 data URIs, so it is not necessary to register it.\n *\n * This is not generally something that is needed, but may be useful in a wrapper to perfom custom data URI\n * functionality.\n *\n * @returns {FetchGatewayFunc} The gateway function.\n */\n static createDataGateway() {\n return dataGatewayFunc;\n }\n /**\n * Creates a function that will fetch IPFS (unvalidated) from a custom gateway baseUrl.\n *\n * The default IPFS gateway used internally is `\"https:/\\/gateway.ipfs.io/ipfs/\"`.\n *\n * @param {string} baseUrl - The base URL of the IPFS gateway.\n * @returns {FetchGatewayFunc} The gateway function.\n */\n static createIpfsGatewayFunc(baseUrl) {\n return getIpfsGatewayFunc(baseUrl);\n }\n}\n/**\n * The response for a FetchRequest.\n *\n * @category Utils\n */\nexport class FetchResponse {\n #statusCode;\n #statusMessage;\n #headers;\n #body;\n #request;\n #error;\n toString() {\n return ``;\n }\n /**\n * The response status code.\n */\n get statusCode() {\n return this.#statusCode;\n }\n /**\n * The response status message.\n */\n get statusMessage() {\n return this.#statusMessage;\n }\n /**\n * The response headers. All keys are lower-case.\n */\n get headers() {\n return Object.assign({}, this.#headers);\n }\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 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',\n 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 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',\n 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]],\n 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 an error status code (i.e. 599) and `message` with an\n * optional `error`.\n *\n * @param {string} [message] - The error message to use.\n * @param {Error} [error] - The error to use.\n * @returns {FetchResponse} The error response.\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) call, causes the request to retry as if\n * throttled for `stall` milliseconds.\n *\n * @param {string} [message] - The error message to use.\n * @param {number} [stall] - The number of milliseconds to stall before retrying.\n * @throws {Error} If `stall` is not a non-negative integer.\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 * @param {string} key - The header key to retrieve.\n * @returns {string} The header value.\n */\n getHeader(key) {\n return this.headers[key.toLowerCase()];\n }\n /**\n * Returns true if the response has a body.\n *\n * @returns {boolean} True if the response has a body.\n * @throws {Error} If the body is invalid UTF-8 data.\n */\n hasBody() {\n return this.#body != null;\n }\n /**\n * The request made for this response.\n */\n get request() {\n return this.#request;\n }\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 * @throws {Error} If the response is not ok.\n */\n assertOk() {\n if (this.ok()) {\n return;\n }\n // eslint-disable-next-line prefer-const\n let { message, error } = this.#error;\n if (message === '') {\n message = `server response ${this.statusCode} ${this.statusMessage}`;\n }\n assert(false, message, 'SERVER_ERROR', {\n request: this.request || 'unknown request',\n response: this,\n error,\n });\n }\n}\nfunction getTime() {\n return new Date().getTime();\n}\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","/**\n * The **FixedNumber** class permits using values with decimal places, using fixed-pont math.\n *\n * Fixed-point math is still based on integers under-the-hood, but uses an internal offset to store fractional\n * components below, and each operation corrects for this after each operation.\n */\nimport { getBytes } from './data.js';\nimport { assert, assertArgument, assertPrivate } from './errors.js';\nimport { getBigInt, getNumber, fromTwos, mask, toBigInt } from './maths.js';\nimport { defineProperties } from './properties.js';\nconst BN_N1 = BigInt(-1);\nconst BN_0 = BigInt(0);\nconst BN_1 = BigInt(1);\nconst BN_5 = BigInt(5);\nconst _guard = {};\n// Constant to pull zeros from for multipliers\nlet Zeros = '0000';\nwhile (Zeros.length < 80) {\n Zeros += Zeros;\n}\n// Returns a string \"1\" followed by decimal \"0\"s\nfunction getTens(decimals) {\n let result = Zeros;\n while (result.length < decimals) {\n result += result;\n }\n return BigInt('1' + result.substring(0, decimals));\n}\nfunction checkValue(val, format, safeOp) {\n const width = BigInt(format.width);\n if (format.signed) {\n const limit = BN_1 << (width - BN_1);\n assert(safeOp == null || (val >= -limit && val < limit), 'overflow', 'NUMERIC_FAULT', {\n operation: safeOp,\n fault: 'overflow',\n value: val,\n });\n if (val > BN_0) {\n val = fromTwos(mask(val, width), width);\n }\n else {\n val = -fromTwos(mask(-val, width), width);\n }\n }\n else {\n const limit = BN_1 << width;\n assert(safeOp == null || (val >= 0 && val < limit), 'overflow', 'NUMERIC_FAULT', {\n operation: safeOp,\n fault: 'overflow',\n value: val,\n });\n val = ((val % limit) + limit) % limit & (limit - BN_1);\n }\n return val;\n}\nfunction getFormat(value) {\n if (typeof value === 'number') {\n value = `fixed128x${value}`;\n }\n let signed = true;\n let width = 128;\n let decimals = 18;\n if (typeof value === 'string') {\n // Parse the format string\n if (value === 'fixed') {\n // defaults...\n }\n else if (value === 'ufixed') {\n signed = false;\n }\n else {\n const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/);\n assertArgument(match, 'invalid fixed format', 'format', value);\n signed = match[1] !== 'u';\n width = parseInt(match[2]);\n decimals = parseInt(match[3]);\n }\n }\n else if (value) {\n // Extract the values from the object\n const v = value;\n const check = (key, type, defaultValue) => {\n if (v[key] == null) {\n return defaultValue;\n }\n assertArgument(typeof v[key] === type, 'invalid fixed format (' + key + ' not ' + type + ')', 'format.' + key, v[key]);\n return v[key];\n };\n signed = check('signed', 'boolean', signed);\n width = check('width', 'number', width);\n decimals = check('decimals', 'number', decimals);\n }\n assertArgument(width % 8 === 0, 'invalid FixedNumber width (not byte aligned)', 'format.width', width);\n assertArgument(decimals <= 80, 'invalid FixedNumber decimals (too large)', 'format.decimals', decimals);\n const name = (signed ? '' : 'u') + 'fixed' + String(width) + 'x' + String(decimals);\n return { signed, width, decimals, name };\n}\nfunction toString(val, decimals) {\n let negative = '';\n if (val < BN_0) {\n negative = '-';\n val *= BN_N1;\n }\n let str = val.toString();\n // No decimal point for whole values\n if (decimals === 0) {\n return negative + str;\n }\n // Pad out to the whole component (including a whole digit)\n while (str.length <= decimals) {\n str = Zeros + str;\n }\n // Insert the decimal point\n const index = str.length - decimals;\n str = str.substring(0, index) + '.' + str.substring(index);\n // Trim the whole component (leaving at least one 0)\n while (str[0] === '0' && str[1] !== '.') {\n str = str.substring(1);\n }\n // Trim the decimal component (leaving at least one 0)\n while (str[str.length - 1] === '0' && str[str.length - 2] !== '.') {\n str = str.substring(0, str.length - 1);\n }\n return negative + str;\n}\n/**\n * A FixedNumber represents a value over its {@link FixedFormat | **FixedFormat**} arithmetic field.\n *\n * A FixedNumber can be used to perform math, losslessly, on values which have decmial places.\n *\n * A FixedNumber has a fixed bit-width to store values in, and stores all values internally by multiplying the value by\n * 10 raised to the power of `decimals`.\n *\n * If operations are performed that cause a value to grow too high (close to positive infinity) or too low (close to\n * negative infinity), the value is said to overflow.\n *\n * For example, an 8-bit signed value, with 0 decimals may only be within the range `-128` to `127`; so `-128 - 1` will\n * overflow and become `127`. Likewise, `127 + 1` will overflow and become `-127`.\n *\n * Many operation have a normal and unsafe variant. The normal variant will throw a\n * [NumericFaultError](../interfaces/NumericFaultError) on any overflow, while the unsafe variant will silently allow\n * overflow, corrupting its value value.\n *\n * If operations are performed that cause a value to become too small (close to zero), the value loses precison and is\n * said to underflow.\n *\n * For example, an value with 1 decimal place may store a number as small as `0.1`, but the value of `0.1 / 2` is\n * `0.05`, which cannot fit into 1 decimal place, so underflow occurs which means precision is lost and the value\n * becomes `0`.\n *\n * Some operations have a normal and signalling variant. The normal variant will silently ignore underflow, while the\n * signalling variant will thow a [NumericFaultError](../interfaces/NumericFaultError) on underflow.\n *\n * @category Utils\n */\nexport class FixedNumber {\n /**\n * The specific fixed-point arithmetic field for this value.\n */\n format;\n #format;\n // The actual value (accounting for decimals)\n #val;\n // A base-10 value to multiple values by to maintain the magnitude\n #tens;\n /**\n * This is a property so console.log shows a human-meaningful value.\n *\n * @ignore\n */\n _value;\n // Use this when changing this file to get some typing info,\n // but then switch to any to mask the internal type\n // constructor(guard: any, value: bigint, format: _FixedFormat) {\n /**\n * @ignore\n */\n constructor(guard, value, format) {\n assertPrivate(guard, _guard, 'FixedNumber');\n this.#val = value;\n this.#format = format;\n const _value = toString(value, format.decimals);\n defineProperties(this, { format: format.name, _value });\n this.#tens = getTens(format.decimals);\n }\n /**\n * If true, negative values are permitted, otherwise only positive values and zero are allowed.\n */\n get signed() {\n return this.#format.signed;\n }\n /**\n * The number of bits available to store the value.\n */\n get width() {\n return this.#format.width;\n }\n /**\n * The number of decimal places in the fixed-point arithment field.\n */\n get decimals() {\n return this.#format.decimals;\n }\n /**\n * The value as an integer, based on the smallest unit the {@link FixedNumber.decimals | **decimals**} allow.\n */\n get value() {\n return this.#val;\n }\n #checkFormat(other) {\n assertArgument(this.format === other.format, 'incompatible format; use fixedNumber.toFormat', 'other', other);\n }\n #checkValue(val, safeOp) {\n val = checkValue(val, this.#format, safeOp);\n return new FixedNumber(_guard, val, this.#format);\n }\n #add(o, safeOp) {\n this.#checkFormat(o);\n return this.#checkValue(this.#val + o.#val, safeOp);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` added to `other`, ignoring overflow.\n *\n * @param {FixedNumber} other - The value to add to `this`.\n * @returns {FixedNumber} The result of the addition.\n */\n addUnsafe(other) {\n return this.#add(other);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` added to `other`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to add to `this`.\n * @returns {FixedNumber} The result of the addition.\n */\n add(other) {\n return this.#add(other, 'add');\n }\n #sub(o, safeOp) {\n this.#checkFormat(o);\n return this.#checkValue(this.#val - o.#val, safeOp);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `other` subtracted from `this`, ignoring\n * overflow.\n *\n * @param {FixedNumber} other - The value to subtract from `this`.\n * @returns {FixedNumber} The result of the subtraction.\n */\n subUnsafe(other) {\n return this.#sub(other);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `other` subtracted from `this`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to subtract from `this`.\n * @returns {FixedNumber} The result of the subtraction.\n */\n sub(other) {\n return this.#sub(other, 'sub');\n }\n #mul(o, safeOp) {\n this.#checkFormat(o);\n return this.#checkValue((this.#val * o.#val) / this.#tens, safeOp);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`, ignoring\n * overflow and underflow (precision loss).\n *\n * @param {FixedNumber} other - The value to multiply `this` by.\n * @returns {FixedNumber} The result of the multiplication.\n */\n mulUnsafe(other) {\n return this.#mul(other);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to multiply `this` by.\n * @returns {FixedNumber} The result of the multiplication.\n */\n mul(other) {\n return this.#mul(other, 'mul');\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` multiplied by `other`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs or if underflow (precision\n * loss) occurs.\n *\n * @param {FixedNumber} other - The value to multiply `this` by.\n * @returns {FixedNumber} The result of the multiplication.\n * @throws {NumericFaultError} Thrown if overflow or underflow occurs.\n * @throws {NumericFaultError} Thrown if division by 0 occurs.\n */\n mulSignal(other) {\n this.#checkFormat(other);\n const value = this.#val * other.#val;\n assert(value % this.#tens === BN_0, 'precision lost during signalling mul', 'NUMERIC_FAULT', {\n operation: 'mulSignal',\n fault: 'underflow',\n value: this,\n });\n return this.#checkValue(value / this.#tens, 'mulSignal');\n }\n #div(o, safeOp) {\n assert(o.#val !== BN_0, 'division by zero', 'NUMERIC_FAULT', {\n operation: 'div',\n fault: 'divide-by-zero',\n value: this,\n });\n this.#checkFormat(o);\n return this.#checkValue((this.#val * this.#tens) / o.#val, safeOp);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`, ignoring\n * underflow (precision loss). A [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to divide `this` by.\n * @returns {FixedNumber} The result of the division.\n */\n divUnsafe(other) {\n return this.#div(other);\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`, ignoring\n * underflow (precision loss). A [NumericFaultError](../interfaces/NumericFaultError) is thrown if overflow occurs.\n *\n * @param {FixedNumber} other - The value to divide `this` by.\n * @returns {FixedNumber} The result of the division.\n */\n div(other) {\n return this.#div(other, 'div');\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the result of `this` divided by `other`. A\n * [NumericFaultError](../interfaces/NumericFaultError) is thrown if underflow (precision loss) occurs.\n *\n * @param {FixedNumber} other - The value to divide `this` by.\n * @returns {FixedNumber} The result of the division.\n * @throws {NumericFaultError} Thrown if underflow occurs.\n */\n divSignal(other) {\n assert(other.#val !== BN_0, 'division by zero', 'NUMERIC_FAULT', {\n operation: 'div',\n fault: 'divide-by-zero',\n value: this,\n });\n this.#checkFormat(other);\n const value = this.#val * this.#tens;\n assert(value % other.#val === BN_0, 'precision lost during signalling div', 'NUMERIC_FAULT', {\n operation: 'divSignal',\n fault: 'underflow',\n value: this,\n });\n return this.#checkValue(value / other.#val, 'divSignal');\n }\n /**\n * Returns a comparison result between `this` and `other`.\n *\n * This is suitable for use in sorting, where `-1` implies `this` is smaller, `1` implies `this` is larger and `0`\n * implies both are equal.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {number} The comparison result.\n */\n cmp(other) {\n let a = this.value, b = other.value;\n // Coerce a and b to the same magnitude\n const delta = this.decimals - other.decimals;\n if (delta > 0) {\n b *= getTens(delta);\n }\n else if (delta < 0) {\n a *= getTens(-delta);\n }\n // Comnpare\n if (a < b) {\n return -1;\n }\n if (a > b) {\n return 1;\n }\n return 0;\n }\n /**\n * Returns true if `other` is equal to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is equal to `this`.\n */\n eq(other) {\n return this.cmp(other) === 0;\n }\n /**\n * Returns true if `other` is less than to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is less than to `this`.\n */\n lt(other) {\n return this.cmp(other) < 0;\n }\n /**\n * Returns true if `other` is less than or equal to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is less than or equal to `this`.\n */\n lte(other) {\n return this.cmp(other) <= 0;\n }\n /**\n * Returns true if `other` is greater than to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is greater than to `this`.\n */\n gt(other) {\n return this.cmp(other) > 0;\n }\n /**\n * Returns true if `other` is greater than or equal to `this`.\n *\n * @param {FixedNumber} other - The value to compare to `this`.\n * @returns {boolean} True if `other` is greater than or equal to `this`.\n */\n gte(other) {\n return this.cmp(other) >= 0;\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} which is the largest **integer** that is less than or equal to\n * `this`.\n *\n * The decimal component of the result will always be `0`.\n *\n * @returns {FixedNumber} The floored value.\n */\n floor() {\n let val = this.#val;\n if (this.#val < BN_0) {\n val -= this.#tens - BN_1;\n }\n val = (this.#val / this.#tens) * this.#tens;\n return this.#checkValue(val, 'floor');\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} which is the smallest **integer** that is greater than or\n * equal to `this`.\n *\n * The decimal component of the result will always be `0`.\n *\n * @returns {FixedNumber} The ceiling value.\n */\n ceiling() {\n let val = this.#val;\n if (this.#val > BN_0) {\n val += this.#tens - BN_1;\n }\n val = (this.#val / this.#tens) * this.#tens;\n return this.#checkValue(val, 'ceiling');\n }\n /**\n * Returns a new {@link FixedNumber | **FixedNumber**} with the decimal component rounded up on ties at `decimals`\n * places.\n *\n * @param {number} [decimals] - The number of decimal places to round to.\n * @returns {FixedNumber} The rounded value.\n */\n round(decimals) {\n if (decimals == null) {\n decimals = 0;\n }\n // Not enough precision to not already be rounded\n if (decimals >= this.decimals) {\n return this;\n }\n const delta = this.decimals - decimals;\n const bump = BN_5 * getTens(delta - 1);\n let value = this.value + bump;\n const tens = getTens(delta);\n value = (value / tens) * tens;\n checkValue(value, this.#format, 'round');\n return new FixedNumber(_guard, value, this.#format);\n }\n /**\n * Returns true if `this` is equal to `0`.\n *\n * @returns {boolean} True if `this` is equal to `0`.\n */\n isZero() {\n return this.#val === BN_0;\n }\n /**\n * Returns true if `this` is less than `0`.\n *\n * @returns {boolean} True if `this` is less than `0`.\n */\n isNegative() {\n return this.#val < BN_0;\n }\n /**\n * Returns the string representation of `this`.\n *\n * @returns {string} The string representation.\n */\n toString() {\n return this._value;\n }\n /**\n * Returns a float approximation.\n *\n * Due to IEEE 754 precission (or lack thereof), this function can only return an approximation and most values will\n * contain rounding errors.\n *\n * @returns {number} The float approximation.\n */\n toUnsafeFloat() {\n return parseFloat(this.toString());\n }\n /**\n * Return a new {@link FixedNumber | **FixedNumber**} with the same value but has had its field set to `format`.\n *\n * This will throw if the value cannot fit into `format`.\n *\n * @param {FixedFormat} format - The new format for the value.\n */\n toFormat(format) {\n return FixedNumber.fromString(this.toString(), format);\n }\n /**\n * Creates a new {@link FixedNumber | **FixedNumber**} for `value` divided by `decimal` places with `format`.\n *\n * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` (once adjusted for `decimals`)\n * cannot fit in `format`, either due to overflow or underflow (precision loss).\n *\n * @param {BigNumberish} _value - The value to create a FixedNumber for.\n * @param {Numeric} [_decimals] - The number of decimal places in `value`.\n * @param {FixedFormat} [_format] - The format for the FixedNumber.\n * @returns {FixedNumber} The FixedNumber for `value`.\n */\n static fromValue(_value, _decimals, _format) {\n const decimals = _decimals == null ? 0 : getNumber(_decimals);\n const format = getFormat(_format);\n let value = getBigInt(_value, 'value');\n const delta = decimals - format.decimals;\n if (delta > 0) {\n const tens = getTens(delta);\n assert(value % tens === BN_0, 'value loses precision for format', 'NUMERIC_FAULT', {\n operation: 'fromValue',\n fault: 'underflow',\n value: _value,\n });\n value /= tens;\n }\n else if (delta < 0) {\n value *= getTens(-delta);\n }\n checkValue(value, format, 'fromValue');\n return new FixedNumber(_guard, value, format);\n }\n /**\n * Creates a new {@link FixedNumber | **FixedNumber**} for `value` with `format`.\n *\n * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` cannot fit in `format`, either\n * due to overflow or underflow (precision loss).\n *\n * @param {BigNumberish} _value - The value to create a FixedNumber for.\n * @param {FixedFormat} [_format] - The format for the FixedNumber.\n * @returns {FixedNumber} The FixedNumber for `value`.\n */\n static fromString(_value, _format) {\n const match = _value.match(/^(-?)([0-9]*)\\.?([0-9]*)$/);\n assertArgument(match && match[2].length + match[3].length > 0, 'invalid FixedNumber string value', 'value', _value);\n const format = getFormat(_format);\n const whole = match[2] || '0';\n let decimal = match[3] || '';\n // Pad out the decimals\n while (decimal.length < format.decimals) {\n decimal += Zeros;\n }\n // Check precision is safe\n assert(decimal.substring(format.decimals).match(/^0*$/), 'too many decimals for format', 'NUMERIC_FAULT', {\n operation: 'fromString',\n fault: 'underflow',\n value: _value,\n });\n // Remove extra padding\n decimal = decimal.substring(0, format.decimals);\n const value = BigInt(match[1] + whole + decimal);\n checkValue(value, format, 'fromString');\n return new FixedNumber(_guard, value, format);\n }\n /**\n * Creates a new {@link FixedNumber | **FixedNumber**} with the big-endian representation `value` with `format`.\n *\n * This will throw a [NumericFaultError](../interfaces/NumericFaultError) if `value` cannot fit in `format` due to\n * overflow.\n *\n * @param {BytesLike} _value - The big-endian representation of the value.\n * @param {FixedFormat} [_format] - The format for the FixedNumber.\n * @returns {FixedNumber} The FixedNumber for `value`.\n */\n static fromBytes(_value, _format) {\n let value = toBigInt(getBytes(_value, 'value'));\n const format = getFormat(_format);\n if (format.signed) {\n value = fromTwos(value, format.width);\n }\n checkValue(value, format, 'fromBytes');\n return new FixedNumber(_guard, value, format);\n }\n}\n//# sourceMappingURL=fixednumber.js.map","/**\n * Most interactions with Ethereum requires integer values, which use the smallest magnitude unit.\n *\n * For example, imagine dealing with dollars and cents. Since dollars are divisible, non-integer values are possible,\n * such as `$10.77`. By using the smallest indivisible unit (i.e. cents), the value can be kept as the integer `1077`.\n *\n * When receiving decimal input from the user (as a decimal string), the value should be converted to an integer and\n * when showing a user a value, the integer value should be converted to a decimal string.\n *\n * This creates a clear distinction, between values to be used by code (integers) and values used for display logic to\n * users (decimals).\n *\n * The native unit in Ethereum, ether is divisible to 18 decimal places, where each individual unit is called a wei.\n */\nimport { assertArgument } from './errors.js';\nimport { FixedNumber } from './fixednumber.js';\nimport { getNumber } from './maths.js';\nconst names = ['wei', 'kwei', 'mwei', 'gwei', 'szabo', 'finney', 'ether'];\n/**\n * Converts `value` into a decimal string, assuming `unit` decimal places. The `unit` may be the number of decimal\n * places or the name of a unit (e.g. `\"gwei\"` for 9 decimal places).\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @param {string | Numeric} [unit=18] - The unit to convert to. Default is `18`\n * @returns {string} The converted value.\n * @throws {Error} If the unit is invalid.\n */\nexport function formatUnits(value, unit) {\n let decimals = 18;\n if (typeof unit === 'string') {\n const index = names.indexOf(unit);\n assertArgument(index >= 0, 'invalid unit', 'unit', unit);\n decimals = 3 * index;\n }\n else if (unit != null) {\n decimals = getNumber(unit, 'unit');\n }\n return FixedNumber.fromValue(value, decimals, { decimals, width: 512 }).toString();\n}\n/**\n * Converts the decimal string `value` to a BigInt, assuming `unit` decimal places. The `unit` may the number of decimal\n * places or the name of a unit (e.g. `\"gwei\"` for 9 decimal places).\n *\n * @category Utils\n * @param {string} value - The value to convert.\n * @param {string | Numeric} [unit=18] - The unit to convert from. Default is `18`\n * @returns {bigint} The converted value.\n * @throws {Error} If the unit is invalid.\n * @throws {Error} If the value is not a string.\n */\nexport function parseUnits(value, unit) {\n assertArgument(typeof value === 'string', 'value must be a string', 'value', value);\n let decimals = 18;\n if (typeof unit === 'string') {\n const index = names.indexOf(unit);\n assertArgument(index >= 0, 'invalid unit', 'unit', unit);\n decimals = 3 * index;\n }\n else if (unit != null) {\n decimals = getNumber(unit, 'unit');\n }\n return FixedNumber.fromString(value, { decimals, width: 512 }).value;\n}\n/**\n * Converts `value` into a decimal string sing 18 decimal places.\n *\n * @category Utils\n * @param {BigNumberish} wei - The value to convert.\n * @returns {string} The converted value.\n */\nexport function formatQuai(wei) {\n return formatUnits(wei, 18);\n}\n/**\n * Converts `value` into a decimal string using 3 decimal places.\n *\n * @category Utils\n * @param {BigNumberish} value - The value to convert.\n * @returns {string} The converted value.\n */\nexport function formatQi(value) {\n return formatUnits(value, 3);\n}\n/**\n * Converts the decimal string `quai` to a BigInt, using 18 decimal places.\n *\n * @category Utils\n * @param {string} ether - The value to convert.\n * @returns {bigint} The converted value.\n */\nexport function parseQuai(ether) {\n return parseUnits(ether, 18);\n}\n/**\n * Converts `value` into a decimal string using 3 decimal places.\n *\n * @category Utils\n * @param {string} value - The value to convert.\n * @returns {bigint} The converted value.\n */\nexport function parseQi(value) {\n return parseUnits(value, 3);\n}\n//# sourceMappingURL=units.js.map","/**\n * Explain UUID and link to RFC here.\n */\nimport { getBytes, hexlify } from './data.js';\n/**\n * Returns the version 4 [UUID](https://www.ietf.org/rfc/rfc4122.txt) for the `randomBytes`.\n *\n * @category Utils\n * @param {BytesLike} randomBytes - The random bytes to use.\n *\n * @returns {string} The UUID.\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","/**\n * A zone is the lowest level shard within the Quai network hierarchy. Zones are the only shards in the network that\n * accept user transactions. The value is a hexadecimal string representing the encoded value of the zone. Read more\n * [here](https://github.com/quai-network/qips/blob/master/qip-0002.md).\n *\n * @category Constants\n */\nexport var Zone;\n(function (Zone) {\n Zone[\"Cyprus1\"] = \"0x00\";\n Zone[\"Cyprus2\"] = \"0x01\";\n Zone[\"Cyprus3\"] = \"0x02\";\n Zone[\"Paxos1\"] = \"0x10\";\n Zone[\"Paxos2\"] = \"0x11\";\n Zone[\"Paxos3\"] = \"0x12\";\n Zone[\"Hydra1\"] = \"0x20\";\n Zone[\"Hydra2\"] = \"0x21\";\n Zone[\"Hydra3\"] = \"0x22\";\n})(Zone || (Zone = {}));\nexport var Ledger;\n(function (Ledger) {\n Ledger[Ledger[\"Quai\"] = 0] = \"Quai\";\n Ledger[Ledger[\"Qi\"] = 1] = \"Qi\";\n})(Ledger || (Ledger = {}));\nfunction zoneFromBytes(zone) {\n switch (zone) {\n case '0x00':\n return Zone.Cyprus1;\n case '0x01':\n return Zone.Cyprus2;\n case '0x02':\n return Zone.Cyprus3;\n case '0x10':\n return Zone.Paxos1;\n case '0x11':\n return Zone.Paxos2;\n case '0x12':\n return Zone.Paxos3;\n case '0x20':\n return Zone.Hydra1;\n case '0x21':\n return Zone.Hydra2;\n case '0x22':\n return Zone.Hydra3;\n default:\n throw new Error(`Invalid zone: ${zone}`);\n }\n}\nexport const ZoneData = [\n {\n name: 'Cyprus One',\n nickname: 'cyprus1',\n shard: 'zone-0-0',\n context: 2,\n byte: '0x00', //0000 0000 region-0 zone-0\n },\n {\n name: 'Cyprus Two',\n nickname: 'cyprus2',\n shard: 'zone-0-1',\n context: 2,\n byte: '0x01', // 0000 0001 region-0 zone-1\n },\n {\n name: 'Cyprus Three',\n nickname: 'cyprus3',\n shard: 'zone-0-2',\n context: 2,\n byte: '0x02', // 0000 0010 region-0 zone-2\n },\n {\n name: 'Paxos One',\n nickname: 'paxos1',\n shard: 'zone-1-0',\n context: 2,\n byte: '0x10', // 0001 0000 region-1 zone-0\n },\n {\n name: 'Paxos Two',\n nickname: 'paxos2',\n shard: 'zone-1-1',\n context: 2,\n byte: '0x11', // 0001 0001 region-1 zone-1\n },\n {\n name: 'Paxos Three',\n nickname: 'paxos3',\n shard: 'zone-1-2',\n context: 2,\n byte: '0x12', // 0001 0010 region-1 zone-2\n },\n {\n name: 'Hydra One',\n nickname: 'hydra1',\n shard: 'zone-2-0',\n context: 2,\n byte: '0x20', // 0010 0000 region-2 zone-0\n },\n {\n name: 'Hydra Two',\n nickname: 'hydra2',\n shard: 'zone-2-1',\n context: 2,\n byte: '0x21', // 0010 0001 region-2 zone-1\n },\n {\n name: 'Hydra Three',\n nickname: 'hydra3',\n shard: 'zone-2-2',\n context: 2,\n byte: '0x22', // 0010 0010 region-2 zone-2\n },\n];\nexport function toZone(shard) {\n return zoneFromBytes(ZoneData.find((it) => it.name == shard || it.byte == shard || it.nickname == shard || it.shard == shard)\n ?.byte || '');\n}\nexport function fromZone(zone, key) {\n return ZoneData.find((it) => it.byte == zone)?.[key] || '';\n}\n//# sourceMappingURL=zones.js.map","function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`Wrong positive integer: ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`Expected boolean, not ${b}`);\n}\nfunction bytes(b, ...lengths) {\n if (!(b instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","export const crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n//# sourceMappingURL=crypto.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nconst u8a = (a) => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n if (!u8a(data))\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC extends Hash {\n constructor(hash, _key) {\n super();\n this.finished = false;\n this.destroyed = false;\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create();\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create();\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++)\n pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to) {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to || (to = Object.create(Object.getPrototypeOf(this), {}));\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();\nhmac.create = (hash, key) => new HMAC(hash, key);\n//# sourceMappingURL=hmac.js.map","import { hash as assertHash, number as assertNumber } from './_assert.js';\nimport { hmac } from './hmac.js';\nimport { createView, toBytes, checkOpts, asyncLoop } from './utils.js';\n// Common prologue and epilogue for sync/async functions\nfunction pbkdf2Init(hash, _password, _salt, _opts) {\n assertHash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n assertNumber(c);\n assertNumber(dkLen);\n assertNumber(asyncTick);\n if (c < 1)\n throw new Error('PBKDF2: iterations (c) should be >= 1');\n const password = toBytes(_password);\n const salt = toBytes(_salt);\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\nfunction pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW)\n prfW.destroy();\n u.fill(0);\n return DK;\n}\n/**\n * PBKDF2-HMAC: RFC 2898 key derivation function\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated\n * @param salt - cryptographic salt\n * @param opts - {c, dkLen} where c is work factor and dkLen is output message size\n */\nexport function pbkdf2(hash, password, salt, opts) {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\nexport async function pbkdf2Async(hash, password, salt, opts) {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + ⋯ + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc−1)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++)\n Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n//# sourceMappingURL=pbkdf2.js.map","import { exists, output } from './_assert.js';\nimport { Hash, createView, toBytes } from './utils.js';\n// Polyfill for Safari 14\nfunction setBigUint64(view, byteOffset, value, isLE) {\n if (typeof view.setBigUint64 === 'function')\n return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n// Base SHA2 class (RFC 6234)\nexport class SHA2 extends Hash {\n constructor(blockLen, outputLen, padOffset, isLE) {\n super();\n this.blockLen = blockLen;\n this.outputLen = outputLen;\n this.padOffset = padOffset;\n this.isLE = isLE;\n this.finished = false;\n this.length = 0;\n this.pos = 0;\n this.destroyed = false;\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data) {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen)\n this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++)\n buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4)\n throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length)\n throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++)\n oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to) {\n to || (to = new this.constructor());\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen)\n to.buffer.set(buffer);\n return to;\n }\n}\n//# sourceMappingURL=_sha2.js.map","import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n// Choice: a ? b : c\nconst Chi = (a, b, c) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a, b, c) => (a & b) ^ (a & c) ^ (b & c);\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2 {\n constructor() {\n super(64, 32, 8, false);\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n this.A = IV[0] | 0;\n this.B = IV[1] | 0;\n this.C = IV[2] | 0;\n this.D = IV[3] | 0;\n this.E = IV[4] | 0;\n this.F = IV[5] | 0;\n this.G = IV[6] | 0;\n this.H = IV[7] | 0;\n }\n get() {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n set(A, B, C, D, E, F, G, H) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4)\n SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n constructor() {\n super();\n this.A = 0xc1059ed8 | 0;\n this.B = 0x367cd507 | 0;\n this.C = 0x3070dd17 | 0;\n this.D = 0xf70e5939 | 0;\n this.E = 0xffc00b31 | 0;\n this.F = 0x68581511 | 0;\n this.G = 0x64f98fa7 | 0;\n this.H = 0xbefa4fa4 | 0;\n this.outputLen = 28;\n }\n}\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n//# sourceMappingURL=sha256.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","import { SHA2 } from './_sha2.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends SHA2 {\n constructor() {\n super(128, 64, 16, false);\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x6a09e667 | 0;\n this.Al = 0xf3bcc908 | 0;\n this.Bh = 0xbb67ae85 | 0;\n this.Bl = 0x84caa73b | 0;\n this.Ch = 0x3c6ef372 | 0;\n this.Cl = 0xfe94f82b | 0;\n this.Dh = 0xa54ff53a | 0;\n this.Dl = 0x5f1d36f1 | 0;\n this.Eh = 0x510e527f | 0;\n this.El = 0xade682d1 | 0;\n this.Fh = 0x9b05688c | 0;\n this.Fl = 0x2b3e6c1f | 0;\n this.Gh = 0x1f83d9ab | 0;\n this.Gl = 0xfb41bd6b | 0;\n this.Hh = 0x5be0cd19 | 0;\n this.Hl = 0x137e2179 | 0;\n }\n // prettier-ignore\n get() {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n process(view, offset) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\nclass SHA512_224 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x8c3d37c8 | 0;\n this.Al = 0x19544da2 | 0;\n this.Bh = 0x73e19966 | 0;\n this.Bl = 0x89dcd4d6 | 0;\n this.Ch = 0x1dfab7ae | 0;\n this.Cl = 0x32ff9c82 | 0;\n this.Dh = 0x679dd514 | 0;\n this.Dl = 0x582f9fcf | 0;\n this.Eh = 0x0f6d2b69 | 0;\n this.El = 0x7bd44da8 | 0;\n this.Fh = 0x77e36f73 | 0;\n this.Fl = 0x04c48942 | 0;\n this.Gh = 0x3f9d85a8 | 0;\n this.Gl = 0x6a1d36c8 | 0;\n this.Hh = 0x1112e6ad | 0;\n this.Hl = 0x91d692a1 | 0;\n this.outputLen = 28;\n }\n}\nclass SHA512_256 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0x22312194 | 0;\n this.Al = 0xfc2bf72c | 0;\n this.Bh = 0x9f555fa3 | 0;\n this.Bl = 0xc84c64c2 | 0;\n this.Ch = 0x2393b86b | 0;\n this.Cl = 0x6f53b151 | 0;\n this.Dh = 0x96387719 | 0;\n this.Dl = 0x5940eabd | 0;\n this.Eh = 0x96283ee2 | 0;\n this.El = 0xa88effe3 | 0;\n this.Fh = 0xbe5e1e25 | 0;\n this.Fl = 0x53863992 | 0;\n this.Gh = 0x2b0199fc | 0;\n this.Gl = 0x2c85b8aa | 0;\n this.Hh = 0x0eb72ddc | 0;\n this.Hl = 0x81c52ca2 | 0;\n this.outputLen = 32;\n }\n}\nclass SHA384 extends SHA512 {\n constructor() {\n super();\n // h -- high 32 bits, l -- low 32 bits\n this.Ah = 0xcbbb9d5d | 0;\n this.Al = 0xc1059ed8 | 0;\n this.Bh = 0x629a292a | 0;\n this.Bl = 0x367cd507 | 0;\n this.Ch = 0x9159015a | 0;\n this.Cl = 0x3070dd17 | 0;\n this.Dh = 0x152fecd8 | 0;\n this.Dl = 0xf70e5939 | 0;\n this.Eh = 0x67332667 | 0;\n this.El = 0xffc00b31 | 0;\n this.Fh = 0x8eb44a87 | 0;\n this.Fl = 0x68581511 | 0;\n this.Gh = 0xdb0c2e0d | 0;\n this.Gl = 0x64f98fa7 | 0;\n this.Hh = 0x47b5481d | 0;\n this.Hl = 0xbefa4fa4 | 0;\n this.outputLen = 48;\n }\n}\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n//# sourceMappingURL=sha512.js.map","/* Browser Crypto Shims */\nimport { hmac } from '@noble/hashes/hmac';\nimport { pbkdf2 } from '@noble/hashes/pbkdf2';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { sha512 } from '@noble/hashes/sha512';\nimport { assert, assertArgument } from '../utils/index.js';\nfunction getGlobal() {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('unable to locate global object');\n}\nconst anyGlobal = getGlobal();\nconst crypto = anyGlobal.crypto || anyGlobal.msCrypto;\nexport function createHash(algo) {\n switch (algo) {\n case 'sha256':\n return sha256.create();\n case 'sha512':\n return sha512.create();\n }\n assertArgument(false, 'invalid hashing algorithm name', 'algorithm', algo);\n}\nexport function createHmac(_algo, key) {\n const algo = { sha256, sha512 }[_algo];\n assertArgument(algo != null, 'invalid hmac algorithm', 'algorithm', _algo);\n return hmac.create(algo, key);\n}\nexport function pbkdf2Sync(password, salt, iterations, keylen, _algo) {\n const algo = { sha256, sha512 }[_algo];\n assertArgument(algo != null, 'invalid pbkdf2 algorithm', 'algorithm', _algo);\n return pbkdf2(algo, password, salt, { c: iterations, dkLen: keylen });\n}\nexport function randomBytes(length) {\n assert(crypto != null, 'platform does not support secure random numbers', 'UNSUPPORTED_OPERATION', {\n operation: 'randomBytes',\n });\n assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, 'invalid length', 'length', length);\n const result = new Uint8Array(length);\n crypto.getRandomValues(result);\n return result;\n}\n//# sourceMappingURL=crypto-browser.js.map","/**\n * An **HMAC** enables verification that a given key was used to authenticate a payload.\n *\n * @see {@link https://en.wikipedia.org/wiki/HMAC | HMAC - Wikipedia}\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 `algo` used for compression.\n *\n * @category Crypto\n * @example\n *\n * ```js\n * key = id('some-secret');\n *\n * // Compute the HMAC\n * computeHmac('sha256', key, '0x1337');\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 * ```\n *\n * @param {'sha256' | 'sha512'} algorithm - The algorithm to use for compression.\n * @param {BytesLike} _key - The key to use for the HMAC.\n * @param {BytesLike} _data - The data to authenticate.\n * @returns {string} The HMAC of the data.\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 () {\n locked = true;\n};\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","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n keccakP(this.state32, this.rounds);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","/**\n * Cryptographic hashing functions\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 hash of UTF-8 data use the [**id**}(../functions/id)\n * function.\n *\n * @category Crypto\n * @example\n *\n * ```ts\n * keccak256('0x');\n *\n * keccak256('0x1337');\n *\n * keccak256(new Uint8Array([0x13, 0x37]));\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 * ```\n *\n * @param {BytesLike} _data - The data to hash.\n * @returns DataHexstring\n * @returns {string} The hash of the data.\n */\nexport function keccak256(_data) {\n const data = getBytes(_data, 'data');\n return hexlify(__keccak256(data));\n}\nkeccak256._ = _keccak256;\nkeccak256.lock = function () {\n locked = true;\n};\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 { SHA2 } from './_sha2.js';\nimport { wrapConstructor } from './utils.js';\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160.html\n// https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf\nconst Rho = /* @__PURE__ */ new Uint8Array([7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8]);\nconst Id = /* @__PURE__ */ Uint8Array.from({ length: 16 }, (_, i) => i);\nconst Pi = /* @__PURE__ */ Id.map((i) => (9 * i + 5) % 16);\nlet idxL = [Id];\nlet idxR = [Pi];\nfor (let i = 0; i < 4; i++)\n for (let j of [idxL, idxR])\n j.push(j[i].map((k) => Rho[k]));\nconst shifts = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => new Uint8Array(i));\nconst shiftsL = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst shiftsR = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts[i][j]));\nconst Kl = /* @__PURE__ */ new Uint32Array([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\nconst Kr = /* @__PURE__ */ new Uint32Array([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// The rotate left (circular left shift) operation for uint32\nconst rotl = (word, shift) => (word << shift) | (word >>> (32 - shift));\n// It's called f() in spec.\nfunction f(group, x, y, z) {\n if (group === 0)\n return x ^ y ^ z;\n else if (group === 1)\n return (x & y) | (~x & z);\n else if (group === 2)\n return (x | ~y) ^ z;\n else if (group === 3)\n return (x & z) | (y & ~z);\n else\n return x ^ (y | ~z);\n}\n// Temporary buffer, not used to store anything between runs\nconst BUF = /* @__PURE__ */ new Uint32Array(16);\nexport class RIPEMD160 extends SHA2 {\n constructor() {\n super(64, 20, 8, true);\n this.h0 = 0x67452301 | 0;\n this.h1 = 0xefcdab89 | 0;\n this.h2 = 0x98badcfe | 0;\n this.h3 = 0x10325476 | 0;\n this.h4 = 0xc3d2e1f0 | 0;\n }\n get() {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n set(h0, h1, h2, h3, h4) {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n process(view, offset) {\n for (let i = 0; i < 16; i++, offset += 4)\n BUF[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl[group], hbr = Kr[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL[group], sr = shiftsR[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);\n }\n roundClean() {\n BUF.fill(0);\n }\n destroy() {\n this.destroyed = true;\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0);\n }\n}\n/**\n * RIPEMD-160 - a hash function from 1990s.\n * @param message - msg that would be hashed\n */\nexport const ripemd160 = /* @__PURE__ */ wrapConstructor(() => new RIPEMD160());\n//# sourceMappingURL=ripemd160.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 * @category Crypto\n * @example\n *\n * ```ts\n * ripemd160('0x');\n *\n * ripemd160('0x1337');\n *\n * ripemd160(new Uint8Array([0x13, 0x37]));\n * ```\n *\n * @param {BytesLike} _data - The data to hash.\n * @returns DataHexstring\n * @returns {string} The hash of the data.\n */\nexport function ripemd160(_data) {\n const data = getBytes(_data, 'data');\n return hexlify(__ripemd160(data));\n}\nripemd160._ = _ripemd160;\nripemd160.lock = function () {\n locked = true;\n};\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 a sequence of bytes suitible as a **key** from a\n * human-rememberable password.\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 [PBKDF2](https://en.wikipedia.org/wiki/PBKDF2) for `keylen` bytes for `password` using the `salt` and\n * using `iterations` of `algo`.\n *\n * This PBKDF is outdated and should not be used in new projects, but is required to decrypt older files.\n *\n * @category Crypto\n * @example\n *\n * ```ts\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 * ```\n *\n * @param {BytesLike} _password - The password to use.\n * @param {BytesLike} _salt - The salt to use.\n * @param {number} iterations - The number of iterations to use.\n * @param {number} keylen - The length of the key to generate.\n * @param {'sha256' | 'sha512'} algo - The algorithm to use.\n * @returns {string} The key derived from the password.\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 () {\n locked = true;\n};\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 generated with additional care take to prevent\n * side-channels from allowing others to detect it and prevent others from through coincidence generate the same\n * values.\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 * @category Crypto\n * @example\n *\n * ```ts\n * randomBytes(8);\n * ```\n *\n * @param {number} length - The number of bytes to generate.\n * @returns {Uint8Array} The random bytes.\n */\nexport function randomBytes(length) {\n return __randomBytes(length);\n}\nrandomBytes._ = _randomBytes;\nrandomBytes.lock = function () {\n locked = true;\n};\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 { number as assertNumber } from './_assert.js';\nimport { sha256 } from './sha256.js';\nimport { pbkdf2 } from './pbkdf2.js';\nimport { asyncLoop, checkOpts, u32 } from './utils.js';\n// RFC 7914 Scrypt KDF\n// Left rotate for uint32\nconst rotl = (a, b) => (a << b) | (a >>> (32 - b));\n// The main Scrypt loop: uses Salsa extensively.\n// Six versions of the function were tried, this is the fastest one.\n// prettier-ignore\nfunction XorAndSalsa(prev, pi, input, ii, out, oi) {\n // Based on https://cr.yp.to/salsa20.html\n // Xor blocks\n let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];\n let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];\n let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];\n let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];\n let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];\n let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];\n let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];\n let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];\n // Save state to temporary variables (salsa)\n let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;\n // Main loop (salsa)\n for (let i = 0; i < 8; i += 2) {\n x04 ^= rotl(x00 + x12 | 0, 7);\n x08 ^= rotl(x04 + x00 | 0, 9);\n x12 ^= rotl(x08 + x04 | 0, 13);\n x00 ^= rotl(x12 + x08 | 0, 18);\n x09 ^= rotl(x05 + x01 | 0, 7);\n x13 ^= rotl(x09 + x05 | 0, 9);\n x01 ^= rotl(x13 + x09 | 0, 13);\n x05 ^= rotl(x01 + x13 | 0, 18);\n x14 ^= rotl(x10 + x06 | 0, 7);\n x02 ^= rotl(x14 + x10 | 0, 9);\n x06 ^= rotl(x02 + x14 | 0, 13);\n x10 ^= rotl(x06 + x02 | 0, 18);\n x03 ^= rotl(x15 + x11 | 0, 7);\n x07 ^= rotl(x03 + x15 | 0, 9);\n x11 ^= rotl(x07 + x03 | 0, 13);\n x15 ^= rotl(x11 + x07 | 0, 18);\n x01 ^= rotl(x00 + x03 | 0, 7);\n x02 ^= rotl(x01 + x00 | 0, 9);\n x03 ^= rotl(x02 + x01 | 0, 13);\n x00 ^= rotl(x03 + x02 | 0, 18);\n x06 ^= rotl(x05 + x04 | 0, 7);\n x07 ^= rotl(x06 + x05 | 0, 9);\n x04 ^= rotl(x07 + x06 | 0, 13);\n x05 ^= rotl(x04 + x07 | 0, 18);\n x11 ^= rotl(x10 + x09 | 0, 7);\n x08 ^= rotl(x11 + x10 | 0, 9);\n x09 ^= rotl(x08 + x11 | 0, 13);\n x10 ^= rotl(x09 + x08 | 0, 18);\n x12 ^= rotl(x15 + x14 | 0, 7);\n x13 ^= rotl(x12 + x15 | 0, 9);\n x14 ^= rotl(x13 + x12 | 0, 13);\n x15 ^= rotl(x14 + x13 | 0, 18);\n }\n // Write output (salsa)\n out[oi++] = (y00 + x00) | 0;\n out[oi++] = (y01 + x01) | 0;\n out[oi++] = (y02 + x02) | 0;\n out[oi++] = (y03 + x03) | 0;\n out[oi++] = (y04 + x04) | 0;\n out[oi++] = (y05 + x05) | 0;\n out[oi++] = (y06 + x06) | 0;\n out[oi++] = (y07 + x07) | 0;\n out[oi++] = (y08 + x08) | 0;\n out[oi++] = (y09 + x09) | 0;\n out[oi++] = (y10 + x10) | 0;\n out[oi++] = (y11 + x11) | 0;\n out[oi++] = (y12 + x12) | 0;\n out[oi++] = (y13 + x13) | 0;\n out[oi++] = (y14 + x14) | 0;\n out[oi++] = (y15 + x15) | 0;\n}\nfunction BlockMix(input, ii, out, oi, r) {\n // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)\n let head = oi + 0;\n let tail = oi + 16 * r;\n for (let i = 0; i < 16; i++)\n out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]\n for (let i = 0; i < r; i++, head += 16, ii += 16) {\n // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1\n XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])\n if (i > 0)\n tail += 16; // First iteration overwrites tmp value in tail\n XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])\n }\n}\n// Common prologue and epilogue for sync/async functions\nfunction scryptInit(password, salt, _opts) {\n // Maxmem - 1GB+1KB by default\n const opts = checkOpts({\n dkLen: 32,\n asyncTick: 10,\n maxmem: 1024 ** 3 + 1024,\n }, _opts);\n const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;\n assertNumber(N);\n assertNumber(r);\n assertNumber(p);\n assertNumber(dkLen);\n assertNumber(asyncTick);\n assertNumber(maxmem);\n if (onProgress !== undefined && typeof onProgress !== 'function')\n throw new Error('progressCb should be function');\n const blockSize = 128 * r;\n const blockSize32 = blockSize / 4;\n if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) {\n // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function\n // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future.\n throw new Error('Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32');\n }\n if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) {\n throw new Error('Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)');\n }\n if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) {\n throw new Error('Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32');\n }\n const memUsed = blockSize * (N + p);\n if (memUsed > maxmem) {\n throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`);\n }\n // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)\n // Since it has only one iteration there is no reason to use async variant\n const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });\n const B32 = u32(B);\n // Re-used between parallel iterations. Array(iterations) of B\n const V = u32(new Uint8Array(blockSize * N));\n const tmp = u32(new Uint8Array(blockSize));\n let blockMixCb = () => { };\n if (onProgress) {\n const totalBlockMix = 2 * N * p;\n // Invoke callback if progress changes from 10.01 to 10.02\n // Allows to draw smooth progress bar on up to 8K screen\n const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);\n let blockMixCnt = 0;\n blockMixCb = () => {\n blockMixCnt++;\n if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))\n onProgress(blockMixCnt / totalBlockMix);\n };\n }\n return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };\n}\nfunction scryptOutput(password, dkLen, B, V, tmp) {\n const res = pbkdf2(sha256, password, B, { c: 1, dkLen });\n B.fill(0);\n V.fill(0);\n tmp.fill(0);\n return res;\n}\n/**\n * Scrypt KDF from RFC 7914.\n * @param password - pass\n * @param salt - salt\n * @param opts - parameters\n * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)\n * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance\n * - `p` is parallelization factor (1 is common)\n * - `dkLen` is output key length in bytes e.g. 32.\n * - `asyncTick` - (default: 10) max time in ms for which async function can block execution\n * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt\n * - `onProgress` - callback function that would be executed for progress report\n * @returns Derived key\n */\nexport function scrypt(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n for (let i = 0, pos = 0; i < N - 1; i++) {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n }\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n for (let i = 0; i < N; i++) {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n }\n }\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n/**\n * Scrypt KDF from RFC 7914.\n */\nexport async function scryptAsync(password, salt, opts) {\n const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);\n for (let pi = 0; pi < p; pi++) {\n const Pi = blockSize32 * pi;\n for (let i = 0; i < blockSize32; i++)\n V[i] = B32[Pi + i]; // V[0] = B[i]\n let pos = 0;\n await asyncLoop(N - 1, asyncTick, () => {\n BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);\n blockMixCb();\n });\n BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element\n blockMixCb();\n await asyncLoop(N, asyncTick, () => {\n // First u32 of the last 64-byte block (u32 is LE)\n const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations\n for (let k = 0; k < blockSize32; k++)\n tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]\n BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])\n blockMixCb();\n });\n }\n return scryptOutput(password, dkLen, B, V, tmp);\n}\n//# sourceMappingURL=scrypt.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 [scrypt PBKDF](https://en.wikipedia.org/wiki/Scrypt) uses a memory and cpu hard method of derivation to increase\n * the resource cost to brute-force a password for a given key.\n *\n * This means this algorithm is intentionally slow, and can be tuned to become slower. As computation and memory speed\n * improve over time, 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 which knows their password requires only 5\n * seconds to unlock their account. A 6 character password has 68 billion possibilities, which would require an attacker\n * to invest over 10,000 years of CPU time. This is of course a crude example (as password generally aren't random), but\n * demonstrates to value of imposing large costs to decryption.\n *\n * For this reason, if building a UI which involved decrypting or encrypting datsa using scrypt, it is recommended to\n * use a [**ProgressCallback**](../types-aliases/ProgressCallback) (as event short periods can seem lik an eternity if\n * the UI freezes). Including the phrase //\"decrypting\"// in the UI can also help, assuring the user their waiting is\n * for a good reason.\n *\n * @category Crypto\n * @example\n *\n * ```ts\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 * ```\n *\n * @param {BytesLike} _passwd - The password to use.\n * @param {BytesLike} _salt - The salt to use.\n * @param {number} N - The CPU/memory cost parameter.\n * @param {number} r - The block size parameter.\n * @param {number} p - The parallelization parameter.\n * @param {number} dkLen - The length of the key to generate.\n * @param {ProgressCallback} [progress] - A callback to update the progress.\n * @returns {Promise} The key derived from the password.\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 () {\n lockedAsync = true;\n};\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 {@link scrypt | **scrypt**}.\n *\n * This will completely lock up and freeze the UI in a browser and will prevent any event loop from progressing. For\n * this reason, it is preferred to use the [async variant](scrypt).\n *\n * @category Crypto\n * @example\n *\n * ```ts\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 * ```\n *\n * @param {BytesLike} _passwd - The password to use.\n * @param {BytesLike} _salt - The salt to use.\n * @param {number} N - The CPU/memory cost parameter.\n * @param {number} r - The block size parameter.\n * @param {number} p - The parallelization parameter.\n * @param {number} dkLen - The length of the key to generate.\n * @returns {string} The key derived from the password.\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 () {\n lockedSync = true;\n};\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 * @category Crypto\n * @example\n *\n * ```ts\n * sha256('0x');\n *\n * sha256('0x1337');\n *\n * sha256(new Uint8Array([0x13, 0x37]));\n * ```\n *\n * @param {BytesLike} _data - The data to hash.\n * @returns {string} The hash of the data.\n */\nexport function sha256(_data) {\n const data = getBytes(_data, 'data');\n return hexlify(__sha256(data));\n}\nsha256._ = _sha256;\nsha256.lock = function () {\n locked256 = true;\n};\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 * @category Crypto\n * @example\n *\n * ```ts\n * sha512('0x');\n *\n * sha512('0x1337');\n *\n * sha512(new Uint8Array([0x13, 0x37]));\n * ```\n *\n * @param {BytesLike} _data - The data to hash.\n * @returns {string} The hash of the data.\n */\nexport function sha512(_data) {\n const data = getBytes(_data, 'data');\n return hexlify(__sha512(data));\n}\nsha512._ = _sha512;\nsha512.lock = function () {\n locked512 = true;\n};\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","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst u8a = (a) => a instanceof Uint8Array;\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\nexport function numberToHexUnpadded(num) {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\nexport function hexToNumber(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes) {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\nexport function numberToBytesBE(n, len) {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n, len) {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n) {\n return hexToBytes(numberToHexUnpadded(n));\n}\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title, hex, expectedLength) {\n let res;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n }\n catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n }\n else if (u8a(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n }\n else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\nexport function equalBytes(b1, b2) {\n // We don't care about timing attacks here\n if (b1.length !== b2.length)\n return false;\n for (let i = 0; i < b1.length; i++)\n if (b1[i] !== b2[i])\n return false;\n return true;\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n// Bit operations\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1)\n ;\n return len;\n}\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n, pos) {\n return (n >> BigInt(pos)) & _1n;\n}\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n, pos, value) => {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n};\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n) => (_2n << BigInt(n - 1)) - _1n;\n// DRBG\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr) => Uint8Array.from(arr); // another shortcut\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg(hashLen, qByteLen, hmacFn) {\n if (typeof hashLen !== 'number' || hashLen < 2)\n throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2)\n throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function')\n throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000)\n throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n// Validating curves and fields\nconst validatorFns = {\n bigint: (val) => typeof val === 'bigint',\n function: (val) => typeof val === 'function',\n boolean: (val) => typeof val === 'boolean',\n string: (val) => typeof val === 'string',\n stringOrUint8Array: (val) => typeof val === 'string' || val instanceof Uint8Array,\n isSafeInteger: (val) => Number.isSafeInteger(val),\n array: (val) => Array.isArray(val),\n field: (val, object) => object.Fp.isValid(val),\n hash: (val) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n};\n// type Record = { [P in K]: T; }\nexport function validateObject(object, validators, optValidators = {}) {\n const checkField = (fieldName, type, isOptional) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n const val = object[fieldName];\n if (isOptional && val === undefined)\n return;\n if (!checkVal(val, object)) {\n throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`);\n }\n };\n for (const [fieldName, type] of Object.entries(validators))\n checkField(fieldName, type, false);\n for (const [fieldName, type] of Object.entries(optValidators))\n checkField(fieldName, type, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n//# sourceMappingURL=utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport { bitMask, numberToBytesBE, numberToBytesLE, bytesToNumberBE, bytesToNumberLE, ensureBytes, validateObject, } from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n// Calculates a modulo b\nexport function mod(a, b) {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num, power, modulo) {\n if (modulo <= _0n || power < _0n)\n throw new Error('Expected power/modulo > 0');\n if (modulo === _1n)\n return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n)\n res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x, power, modulo) {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n// Inverses number over modulo\nexport function invert(number, modulo) {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n)\n throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) ≡ 1 if a is a square (mod p)\n // (a | p) ≡ -1 if a is not a square (mod p)\n // (a | p) ≡ 0 if a ≡ 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n let Q, S, Z;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)\n ;\n // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)\n ;\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast(Fp, n) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow(Fp, n) {\n // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))\n throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO))\n return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE))\n break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\nexport function FpSqrt(P) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n // P ≡ 3 (mod 4)\n // √n = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4(Fp, n) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8(Fp, n) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n))\n throw new Error('Cannot find square root');\n return root;\n };\n }\n // P ≡ 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n];\nexport function validateField(field) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n };\n const opts = FIELD_FIELDS.reduce((map, val) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n// Generic field functions\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow(f, num, power) {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n)\n throw new Error('Expected power > 0');\n if (power === _0n)\n return f.ONE;\n if (power === _1n)\n return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n)\n p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch(f, nums) {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num))\n return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\nexport function FpDiv(f, lhs, rhs) {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare(f) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x) => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n// CURVE.n lengths\nexport function nLength(n, nBitLength) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(ORDER, bitLen, isLE = false, redef = {}) {\n if (ORDER <= _0n)\n throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048)\n throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n });\n return Object.freeze(f);\n}\nexport function FpSqrtOdd(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\nexport function FpSqrtEven(Fp, elm) {\n if (!Fp.isOdd)\n throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(hash, groupOrder, isLE = false) {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder) {\n if (typeof fieldOrder !== 'bigint')\n throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder) {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key, fieldOrder, isLE = false) {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n//# sourceMappingURL=modular.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF(c, bits) {\n const constTimeNegate = (condition, item) => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm, n) {\n let p = c.ZERO;\n let d = elm;\n while (n > _0n) {\n if (n & _1n)\n p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:\n * - 𝑊 is the window size\n * - 𝑛 is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm, W) {\n const { windows, windowSize } = opts(W);\n const points = [];\n let p = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W, precomputes, n) {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n let p = c.ZERO;\n let f = c.BASE;\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n // Shift number by W bits.\n n >>= shiftBy;\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n }\n else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n wNAFCached(P, precomputesMap, n, transform) {\n // @ts-ignore\n const W = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W);\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\nexport function validateBasic(curve) {\n validateField(curve.Fp);\n validateObject(curve, {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n }, {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n });\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n });\n}\n//# sourceMappingURL=curve.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y² = x³ + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes } from './utils.js';\nimport { wNAF, validateBasic } from './curve.js';\nfunction validatePointOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n a: 'field',\n b: 'field',\n }, {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n });\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function') {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts });\n}\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data) {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02)\n throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len)\n throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000)\n throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex) {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n if (!(data instanceof Uint8Array))\n throw new Error('ui8a expected');\n let l = data.length;\n if (l < 2 || data[0] != 0x30)\n throw new E('Invalid signature tag');\n if (data[1] !== l - 2)\n throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length)\n throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig) {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s) => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\nexport function weierstrassPoints(opts) {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n const toBytes = CURVE.toBytes ||\n ((_c, point, _isCompressed) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes = CURVE.fromBytes ||\n ((bytes) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n /**\n * y² = x³ + ax + b: Short weierstrass curve formula\n * @returns y²\n */\n function weierstrassEquation(x) {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num) {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num) {\n if (!isWithinCurveOrder(num))\n throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key) {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (key instanceof Uint8Array)\n key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length))\n throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n }\n catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey)\n num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n const pointPrecomputes = new Map();\n function assertPrjPoint(other) {\n if (!(other instanceof Point))\n throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) ∋ (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n if (px == null || !Fp.isValid(px))\n throw new Error('x required');\n if (py == null || !Fp.isValid(py))\n throw new Error('y required');\n if (pz == null || !Fp.isValid(pz))\n throw new Error('z required');\n }\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p) {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('invalid affine point');\n if (p instanceof Point)\n throw new Error('projective point not allowed');\n const is0 = (i) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y))\n return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points) {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex) {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // A point on curve is valid if it conforms to equation.\n assertValidity() {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py))\n return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y))\n throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y²\n const right = weierstrassEquation(x); // x³ + ax + b\n if (!Fp.eql(left, right))\n throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree())\n throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY() {\n const { y } = this.toAffine();\n if (Fp.isOdd)\n return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n /**\n * Compare one point to another.\n */\n equals(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate() {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other) {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n subtract(other) {\n return this.add(other.negate());\n }\n is0() {\n return this.equals(Point.ZERO);\n }\n wNAF(n) {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n) {\n const I = Point.ZERO;\n if (n === _0n)\n return I;\n assertGE(n); // Will throw on 0\n if (n === _1n)\n return this;\n const { endo } = CURVE;\n if (!endo)\n return wnaf.unsafeLadder(this, n);\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n)\n k1p = k1p.add(d);\n if (k2 & _1n)\n k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg)\n k1p = k1p.negate();\n if (k2neg)\n k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar) {\n assertGE(scalar);\n let n = scalar;\n let point, fake; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n }\n else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q, a, b) {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (P, a // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) ∋ (x=x/z, y=y/z)\n toAffine(iz) {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null)\n iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0)\n return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE))\n throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree() {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n)\n return true; // No subgroups, always torsion-free\n if (isTorsionFree)\n return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor() {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n)\n return this; // Fast-path\n if (clearCofactor)\n return clearCofactor(Point, this);\n return this.multiplyUnsafe(CURVE.h);\n }\n toRawBytes(isCompressed = true) {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n toHex(isCompressed = true) {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\nfunction validateOpts(curve) {\n const opts = validateBasic(curve);\n ut.validateObject(opts, {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n }, {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n });\n return Object.freeze({ lowS: true, ...opts });\n}\nexport function weierstrass(curveDef) {\n const CURVE = validateOpts(curveDef);\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n function isValidFieldElement(num) {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a) {\n return mod.invert(a, CURVE_ORDER);\n }\n const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder, } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed) {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n }\n else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x))\n throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y² = x³ + ax + b\n let y = Fp.sqrt(y2); // y = y² ^ (p+1)/4\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd)\n y = Fp.neg(y);\n return { x, y };\n }\n else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n }\n else {\n throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`);\n }\n },\n });\n const numToNByteStr = (num) => ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n function isBiggerThanHalfOrder(number) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function normalizeS(s) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b, from, to) => ut.bytesToNumberBE(b.slice(from, to));\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity();\n }\n // pair (bytes of r, bytes of s)\n static fromCompact(hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n assertValidity() {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r))\n throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s))\n throw new Error('s must be 0 < s < CURVE.n');\n }\n addRecoveryBit(recovery) {\n return new Signature(this.r, this.s, recovery);\n }\n recoverPublicKey(msgHash) {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec))\n throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER)\n throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q)\n throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n // Signatures should be low-s, to prevent malleability.\n hasHighS() {\n return isBiggerThanHalfOrder(this.s);\n }\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n const utils = {\n isValidPrivateKey(privateKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n }\n catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: () => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE) {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey, isCompressed = true) {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item) {\n const arr = item instanceof Uint8Array;\n const str = typeof item === 'string';\n const len = (arr || str) && item.length;\n if (arr)\n return len === compressedLen || len === uncompressedLen;\n if (str)\n return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point)\n return true;\n return false;\n }\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA, publicB, isCompressed = true) {\n if (isProbPub(privateA))\n throw new Error('first arg must be private key');\n if (!isProbPub(publicB))\n throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int = CURVE.bits2int ||\n function (bytes) {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN = CURVE.bits2int_modN ||\n function (bytes) {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num) {\n if (typeof num !== 'bigint')\n throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash, privateKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash)\n msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes) {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k))\n return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n)\n return;\n // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n)\n return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery); // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts = { lowS: CURVE.lowS, prehash: false };\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G × k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash, privKey, opts = defaultSigOpts) {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1⋅G - U2⋅P\n * mod(R.x, n) == r\n * ```\n */\n function verify(signature, msgHash, publicKey, opts = defaultVerOpts) {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts)\n throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n let _sig = undefined;\n let P;\n try {\n if (typeof sg === 'string' || sg instanceof Uint8Array) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n }\n catch (derError) {\n if (!(derError instanceof DER.Err))\n throw derError;\n _sig = Signature.fromCompact(sg);\n }\n }\n else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n }\n else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n }\n catch (error) {\n if (error.message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS())\n return false;\n if (prehash)\n msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1⋅G + u2⋅P\n if (!R)\n return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio(Fp, Z) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n)\n l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u, v) => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u, v) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU(Fp, opts) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd)\n throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u) => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd(u) === Fp.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n//# sourceMappingURL=weierstrass.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass } from './abstract/weierstrass.js';\n// connects noble-curves to noble-hashes\nexport function getHash(hash) {\n return {\n hash,\n hmac: (key, ...msgs) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\nexport function createCurve(curveDef, defHash) {\n const create = (hash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n//# sourceMappingURL=_shortw_utils.js.map","/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a, b) => (a + b / _2n) / b;\n/**\n * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y) {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y))\n throw new Error('Cannot find square root');\n return root;\n}\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\nexport const secp256k1 = createCurve({\n a: BigInt(0),\n b: BigInt(7),\n Fp,\n n: secp256k1N,\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1),\n lowS: true,\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg)\n k1 = n - k1;\n if (k2neg)\n k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n}, sha256);\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES = {};\nfunction taggedHash(tag, ...messages) {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n) => numberToBytesBE(n, 32);\nconst modP = (x) => mod(x, secp256k1P);\nconst modN = (x) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q, a, b) => Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'⋅G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x) {\n if (!fe(x))\n throw new Error('bad x: need 0 < x < p'); // Fail if x ≥ p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x³ + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n)\n y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args) {\n return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey) {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G)\n}\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(message, privateKey, auxRand = randomBytes(32)) {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n)\n throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'⋅G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px))\n throw new Error('sign: Invalid signature produced');\n return sig;\n}\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature, message, publicKey) {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p.\n if (!fe(r))\n return false;\n const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n.\n if (!ge(s))\n return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s⋅G - e⋅P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r)\n return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r.\n }\n catch (error) {\n return false;\n }\n}\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\nconst isoMap = /* @__PURE__ */ (() => isogenyMap(Fp, [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n].map((i) => i.map((j) => BigInt(j)))))();\nconst mapSWU = /* @__PURE__ */ (() => mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n}))();\nconst htf = /* @__PURE__ */ (() => createHasher(secp256k1.ProjectivePoint, (scalars) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n}, {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n}))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n//# sourceMappingURL=secp256k1.js.map","/**\n * A constant for the zero address.\n *\n * (**i.e.** `\"0x0000000000000000000000000000000000000000\"`)\n *\n * @category Constants\n */\nexport const ZeroAddress = '0x0000000000000000000000000000000000000000';\n//# sourceMappingURL=addresses.js.map","/**\n * A constant for the zero hash.\n *\n * (**i.e.** `\"0x0000000000000000000000000000000000000000000000000000000000000000\"`)\n *\n * @category Constants\n */\nexport const ZeroHash = '0x0000000000000000000000000000000000000000000000000000000000000000';\n//# sourceMappingURL=hashes.js.map","/**\n * A constant for the order N for the secp256k1 curve.\n *\n * (**i.e.** `0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141n`)\n *\n * @category Constants\n */\nexport const N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\n/**\n * A constant for the number of wei in a single ether.\n *\n * (**i.e.** `1000000000000000000n`)\n *\n * @category Constants\n */\nexport const WeiPerEther = BigInt('1000000000000000000');\n/**\n * A constant for the maximum value for a `uint256`.\n *\n * (**i.e.** `0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn`)\n *\n * @category Constants\n */\nexport const MaxUint256 = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\n/**\n * A constant for the minimum value for an `int256`.\n *\n * (**i.e.** `-8000000000000000000000000000000000000000000000000000000000000000n`)\n *\n * @category Constants\n */\nexport const MinInt256 = BigInt('0x8000000000000000000000000000000000000000000000000000000000000000') * BigInt(-1);\n/**\n * A constant for the maximum value for an `int256`.\n *\n * (**i.e.** `0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn`)\n *\n * @category Constants\n */\nexport const MaxInt256 = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\n//# sourceMappingURL=numbers.js.map","// NFKC (composed) // (decomposed)\n/**\n * A constant for the ether symbol (normalized using NFKC).\n *\n * (**i.e.** `\"\\\\u039e\"`)\n *\n * @category Constants\n */\nexport const quaisymbol = '\\u039e'; // \"\\uD835\\uDF63\";\n/**\n * A constant for the Quai Network equivalent of the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal message\n * prefix.\n *\n * (**i.e.** `\"\\\\x19Quai Signed Message:\\\\n\"`)\n *\n * @category Constants\n */\nexport const MessagePrefix = '\\x19Quai Signed Message:\\n';\n/**\n * A constant for the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal message prefix.\n *\n * (**i.e.** `\"\\\\x19Ethereum Signed Message:\\\\n\"`)\n *\n * @category Constants\n */\nexport const EthMessagePrefix = '\\x19Ethereum Signed Message:\\n';\n//# sourceMappingURL=strings.js.map","import { ZoneData } from './zones.js';\n/**\n * A shard represents a chain within the Quai network hierarchy. A shard refer to the Prime chain, a region under the\n * Prime chain, or a Zone within a region. The value is a hexadecimal string representing the encoded value of the\n * shard. Read more [here](https://github.com/quai-network/qips/blob/master/qip-0002.md).\n *\n * @category Constants\n */\nexport var Shard;\n(function (Shard) {\n Shard[\"Cyprus\"] = \"0x0\";\n Shard[\"Cyprus1\"] = \"0x00\";\n Shard[\"Cyprus2\"] = \"0x01\";\n Shard[\"Cyprus3\"] = \"0x02\";\n Shard[\"Paxos\"] = \"0x1\";\n Shard[\"Paxos1\"] = \"0x10\";\n Shard[\"Paxos2\"] = \"0x11\";\n Shard[\"Paxos3\"] = \"0x12\";\n Shard[\"Hydra\"] = \"0x2\";\n Shard[\"Hydra1\"] = \"0x20\";\n Shard[\"Hydra2\"] = \"0x21\";\n Shard[\"Hydra3\"] = \"0x22\";\n Shard[\"Prime\"] = \"0x\";\n})(Shard || (Shard = {}));\nfunction shardFromBytes(shard) {\n switch (shard) {\n case '0x':\n return Shard.Prime;\n case '0x0':\n return Shard.Cyprus;\n case '0x1':\n return Shard.Paxos;\n case '0x2':\n return Shard.Hydra;\n case '0x00':\n return Shard.Cyprus1;\n case '0x01':\n return Shard.Cyprus2;\n case '0x02':\n return Shard.Cyprus3;\n case '0x10':\n return Shard.Paxos1;\n case '0x11':\n return Shard.Paxos2;\n case '0x12':\n return Shard.Paxos3;\n case '0x20':\n return Shard.Hydra1;\n case '0x21':\n return Shard.Hydra2;\n case '0x22':\n return Shard.Hydra3;\n default:\n throw new Error('Invalid shard');\n }\n}\n/**\n * Constant data that defines each shard within the network.\n *\n * @category Constants\n */\nexport const ShardData = [\n ...ZoneData,\n {\n name: 'Cyprus',\n nickname: 'cyprus',\n shard: 'region-0',\n context: 2,\n byte: '0x0',\n },\n {\n name: 'Paxos',\n nickname: 'paxos',\n shard: 'region-1',\n context: 2,\n byte: '0x1',\n },\n {\n name: 'Hydra',\n nickname: 'hydra',\n shard: 'region-2',\n context: 2,\n byte: '0x2',\n },\n {\n name: 'Prime',\n nickname: 'prime',\n shard: 'prime',\n context: 2,\n byte: '0x',\n },\n];\nexport function toShard(shard) {\n return shardFromBytes(ShardData.find((it) => it.name == shard || it.byte == shard || it.nickname == shard || it.shard == shard)\n ?.byte || '');\n}\nexport function fromShard(shard, key) {\n return ShardData.find((it) => it.byte == shard)?.[key] || '';\n}\n//# sourceMappingURL=shards.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 * @category Crypto\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 challenge point, from which the `y` can be computed.\n */\n get r() {\n return this.#r;\n }\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() {\n return this.#s;\n }\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 its correspondin `y`, the `v` indicates which of the\n * two `y` values to use.\n *\n * It is normalized to the values `27` or `28` for legacy purposes.\n */\n get v() {\n return this.#v;\n }\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 transactions, this value is `null`.\n */\n get networkV() {\n return this.#networkV;\n }\n /**\n * The chain ID for EIP-155 legacy transactions. For non-legacy 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 [EIP-2098](https://eips.ethereum.org/EIPS/eip-2098) compact representation of the `yParity` and `s` compacted\n * 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 [EIP-2098](https://eips.ethereum.org/EIPS/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 * @ignore\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 {@link Signature | **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,\n s: this.s,\n v: this.v,\n };\n }\n /**\n * Compute the chain ID from the `v` in a legacy EIP-155 transactions.\n *\n * @example\n *\n * ```ts\n * Signature.getChainId(45);\n *\n * Signature.getChainId(46);\n * ```\n *\n * @param {BigNumberish} v - The `v` value from the signature.\n * @returns {bigint} The chain ID.\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 [EIP-155](https://eips.ethereum.org/EIPS/eip-155) hijack the `v` property to\n * include the chain ID.\n *\n * @example\n *\n * ```ts\n * Signature.getChainIdV(5, 27);\n *\n * Signature.getChainIdV(5, 28);\n * ```\n *\n * @param {BigNumberish} chainId - The chain ID.\n * @param {27 | 28} v - The `v` value.\n * @returns {bigint} The `v` value.\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`, a legacy transaction `v` or a legacy\n * [EIP-155](https://eips.ethereum.org/EIPS/eip-155) transaction.\n *\n * @example\n *\n * ```ts\n * // The values 0 and 1 imply v is actually yParity\n * Signature.getNormalizedV(0);\n *\n * // Legacy non-EIP-1559 transaction (i.e. 27 or 28)\n * Signature.getNormalizedV(27);\n *\n * // Legacy EIP-155 transaction (i.e. >= 35)\n * Signature.getNormalizedV(46);\n *\n * // Invalid values throw\n * Signature.getNormalizedV(5);\n * ```\n *\n * @param {BigNumberish} v - The `v` value.\n * @returns {27 | 28} The normalized `v` value.\n * @throws {Error} Thrown if the `v` is invalid.\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 {@link Signature | **Signature**}.\n *\n * If no `sig` is provided, a new {@link Signature | **Signature**} is created with default values.\n *\n * If `sig` is a string, it is parsed.\n *\n * @param {SignatureLike} [sig] - The signature to create.\n * @returns {Signature} The new signature.\n */\n static from(sig) {\n function assertError(check, message) {\n assertArgument(check, message, 'signature', sig);\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 (yParity) {\n case 0:\n return { v: 27 };\n case 1:\n 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(!('yParity' in sig && sig.yParity !== result.yParity), 'yParity mismatch');\n assertError(!('yParityAndS' in sig && sig.yParityAndS !== result.yParityAndS), 'yParityAndS mismatch');\n return result;\n }\n}\n//# sourceMappingURL=signature.js.map","/**\n * Add details about signing here.\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 cryptography (ECC) operations and key management.\n *\n * @category Crypto\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() {\n return this.#privateKey;\n }\n /**\n * The uncompressed public key.\n *\n * This will always begin with the prefix `0x04` and be 132 characters long (the `0x` prefix and 130 hexadecimal\n * nibbles).\n */\n get publicKey() {\n return SigningKey.computePublicKey(this.#privateKey);\n }\n /**\n * The compressed public key.\n *\n * This will always begin with either the prefix `0x02` or `0x03` and be 68 characters long (the `0x` prefix and 33\n * hexadecimal nibbles)\n */\n get compressedPublicKey() {\n return SigningKey.computePublicKey(this.#privateKey, true);\n }\n /**\n * Return the signature of the signed `digest`.\n *\n * @param {BytesLike} digest - The data to sign.\n * @returns {Signature} The signature of the data.\n * @throws {Error} If the digest is not 32 bytes long.\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('0x' + sig.r.toString(16), 32),\n s: toBeHex('0x' + sig.s.toString(16), 32),\n v: sig.recovery ? 0x1c : 0x1b,\n });\n }\n /**\n * Returns the [ECDH](https://en.wikipedia.org/wiki/Elliptic-curve_Diffie-Hellman) 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, a compressed/uncompressed pubic key or aprivate key.\n *\n * Best practice is usually to use a cryptographic hash on the returned value before using it as a symetric secret.\n *\n * @example\n *\n * ```ts\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 *\n * // ...is equal to privB.computeSharedSecret(pubA).\n * sign2.computeSharedSecret(sign1.publicKey);\n * ```\n *\n * @param {BytesLike} other - The other key to compute the shared secret with.\n * @returns {string} The shared secret.\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 compressed/uncompressed public key or private key.\n *\n * @example\n *\n * ```ts\n * sign = new SigningKey(id('some-secret'));\n *\n * // Compute the uncompressed public key for a private key\n * SigningKey.computePublicKey(sign.privateKey);\n *\n * // Compute the compressed public key for a private key\n * SigningKey.computePublicKey(sign.privateKey, true);\n *\n * // Compute the uncompressed public key\n * SigningKey.computePublicKey(sign.publicKey, false);\n *\n * // Compute the Compressed a public key\n * SigningKey.computePublicKey(sign.publicKey, true);\n * ```\n *\n * @param {BytesLike} key - The key to compute the public key for.\n * @param {boolean} [compressed] - Whether to return the compressed public key.\n * @returns {string} The public key.\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 `signature` for the given `digest`.\n *\n * @example\n *\n * ```ts\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 *\n * // ...is equal to the recovered public key\n * SigningKey.recoverPublicKey(digest, sig);\n * ```\n *\n * @param {BytesLike} digest - The data that was signed.\n * @param {SignatureLike} signature - The signature of the data.\n * @returns {string} The public key.\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 `p0` and `p1`.\n *\n * This is not a common function most developers should require, but can be useful for certain privacy-specific\n * techniques.\n *\n * For example, it is used by [**QuaiHDWallet**](../classes/QuaiHDWallet) to compute child addresses from parent\n * public keys and chain codes.\n *\n * @param {BytesLike} p0 - The first point to add.\n * @param {BytesLike} p1 - The second point to add.\n * @param {boolean} [compressed] - Whether to return the compressed public key.\n * @returns {string} The sum of the points.\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 { sha256 } from '@noble/hashes/sha256';\nimport { secp256k1, schnorr } from '@noble/curves/secp256k1';\n// BigInt / Uint8Array versions of Crypto functions that do not require point\n// math. If your JS interpreter has BigInt, you can use all of these. If not,\n// you'll need to either shim it in or override more of these functions.\n// Idea from noble-secp256k1, be nice to bad JS parsers\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _3n = BigInt(3);\nconst _5n = BigInt(5);\nconst _7n = BigInt(7);\nconst _64n = BigInt(64);\nconst _64mask = BigInt('0xFFFFFFFFFFFFFFFF');\nconst CURVE = {\n b: BigInt(7),\n P: BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F'),\n n: BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141'),\n};\n// Big Endian\nfunction read32b(bytes) {\n if (bytes.length !== 32)\n throw new Error(`Expected 32-bytes, not ${bytes.length}`);\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);\n let b = view.getBigUint64(0);\n for (let offs = 8; offs < bytes.length; offs += 8) {\n b <<= _64n;\n b += view.getBigUint64(offs);\n }\n return b;\n}\nfunction write32b(num, dest = new Uint8Array(32)) {\n // All input values are modulo P or n, so no bounds checking needed\n const view = new DataView(dest.buffer, dest.byteOffset, dest.length);\n for (let offs = 24; offs >= 0; offs -= 8) {\n view.setBigUint64(offs, num & _64mask);\n num >>= _64n;\n }\n return dest;\n}\nfunction readScalar(bytes) {\n const a = read32b(bytes);\n if (a >= CURVE.n)\n throw new Error('Expected value mod n');\n return a;\n}\nfunction readSecret(bytes) {\n const a = readScalar(bytes);\n if (a === 0n)\n throw new Error('Expected non-zero');\n return a;\n}\n// The short Weierstrass form curve equation simplifes to y^2 = x^3 + 7.\nfunction secp256k1Right(x) {\n const x2 = (x * x) % CURVE.P;\n const x3 = (x2 * x) % CURVE.P;\n return (x3 + CURVE.b) % CURVE.P;\n}\n// For prime P, the Jacobi Symbol of 'a' is 1 if and only if 'a' is a quadratic\n// residue mod P, ie. there exists a value 'x' for whom x^2 = a.\nfunction jacobiSymbol(a) {\n if (a === _0n)\n return 0; // Vanishingly improbable\n let p = CURVE.P;\n let sign = 1;\n // This algorithm is fairly heavily optimized, so don't simplify it w/o benchmarking\n for (;;) {\n let and3;\n // Handle runs of zeros efficiently w/o flipping sign each time\n for (and3 = a & _3n; and3 === _0n; a >>= _2n, and3 = a & _3n)\n ;\n // If there's one more zero, shift it off and flip the sign\n if (and3 === _2n) {\n a >>= _1n;\n const pand7 = p & _7n;\n if (pand7 === _3n || pand7 === _5n)\n sign = -sign;\n }\n if (a === _1n)\n break;\n if ((_3n & a) === _3n && (_3n & p) === _3n)\n sign = -sign;\n [a, p] = [p % a, a];\n }\n return sign > 0 ? 1 : -1;\n}\nfunction isPoint(p) {\n if (p.length < 33)\n return false;\n const t = p[0];\n if (p.length === 33) {\n return (t === 0x02 || t === 0x03) && isXOnlyPoint(p.subarray(1));\n }\n if (t !== 0x04 || p.length !== 65)\n return false;\n const x = read32b(p.subarray(1, 33));\n if (x === _0n)\n return false;\n if (x >= CURVE.P)\n return false;\n const y = read32b(p.subarray(33));\n if (y === _0n)\n return false;\n if (y >= CURVE.P)\n return false;\n const left = (y * y) % CURVE.P;\n const right = secp256k1Right(x);\n return left === right;\n}\nfunction isXOnlyPoint(p) {\n if (p.length !== 32)\n return false;\n const x = read32b(p);\n if (x === _0n)\n return false;\n if (x >= CURVE.P)\n return false;\n const y2 = secp256k1Right(x);\n return jacobiSymbol(y2) === 1; // If sqrt(y^2) exists, x is on the curve.\n}\nfunction scalarAdd(a, b) {\n const aN = readScalar(a);\n const bN = readScalar(b);\n const sum = (aN + bN) % CURVE.n;\n return write32b(sum);\n}\nfunction scalarMultiply(a, b) {\n const aN = readScalar(a);\n const bN = readScalar(b);\n const product = (aN * bN) % CURVE.n;\n return write32b(product);\n}\nfunction scalarNegate(a) {\n const aN = readScalar(a);\n const negated = aN === _0n ? _0n : CURVE.n - aN;\n return write32b(negated);\n}\nfunction scalarMod(a) {\n const aN = read32b(a);\n const remainder = aN % CURVE.n;\n return write32b(remainder);\n}\nfunction isScalar(t) {\n try {\n readScalar(t);\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isSecret(s) {\n try {\n readSecret(s);\n return true;\n }\n catch {\n return false;\n }\n}\nfunction pointNegate(p) {\n // hasEvenY does basic structure check, so start there\n const even = hasEvenY(p);\n // `from` because node.Buffer.slice doesn't copy but looks like a Uint8Array\n const negated = Uint8Array.from(p);\n if (p.length === 33) {\n negated[0] = even ? 3 : 2;\n }\n else if (p.length === 65) {\n const y = read32b(p.subarray(33));\n if (y >= CURVE.P)\n throw new Error('Expected Y coordinate mod P');\n const minusY = y === _0n ? _0n : CURVE.P - y;\n write32b(minusY, negated.subarray(33));\n }\n return negated;\n}\nfunction pointX(p) {\n if (p.length === 32)\n return p;\n hasEvenY(p); // hasEvenY throws if not well structured\n return p.slice(1, 33);\n}\nfunction hasEvenY(p) {\n if (p.length === 33) {\n if (p[0] === 2)\n return true;\n else if (p[0] === 3)\n return false;\n else\n throw new Error('Wrong first byte to be a point');\n }\n if (p.length === 65) {\n if (p[0] !== 4)\n throw new Error('Wrong first byte to be point');\n return p[64] % 2 === 0;\n }\n throw new Error('Wrong length to be a point');\n}\nfunction pointMultiplyUnsafe(p, a, compress) {\n try {\n const product = secp256k1.ProjectivePoint.fromHex(p).multiplyAndAddUnsafe(secp256k1.ProjectivePoint.ZERO, BigInt(`0x${Buffer.from(a).toString('hex')}`), BigInt(1));\n if (!product)\n return null;\n return product.toRawBytes(compress);\n }\n catch {\n return null;\n }\n}\nfunction pointMultiplyAndAddUnsafe(p1, a, p2, compress) {\n try {\n const p2p = secp256k1.ProjectivePoint.fromHex(p2);\n const p = secp256k1.ProjectivePoint.fromHex(p1).multiplyAndAddUnsafe(p2p, BigInt(`0x${Buffer.from(a).toString('hex')}`), BigInt(1));\n if (!p)\n return null;\n return p.toRawBytes(compress);\n }\n catch {\n return null;\n }\n}\nfunction pointAdd(a, b, compress) {\n try {\n return secp256k1.ProjectivePoint.fromHex(a).add(secp256k1.ProjectivePoint.fromHex(b)).toRawBytes(compress);\n }\n catch {\n return null;\n }\n}\nfunction pointAddTweak(p, tweak, compress) {\n try {\n const P = secp256k1.ProjectivePoint.fromHex(p);\n const t = readSecret(tweak);\n const Q = secp256k1.ProjectivePoint.BASE.multiplyAndAddUnsafe(P, t, 1n);\n if (!Q)\n throw new Error('Tweaked point at infinity');\n return Q.toRawBytes(compress);\n }\n catch {\n return null;\n }\n}\nfunction pointCompress(p, compress = true) {\n return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(compress);\n}\nfunction liftX(p) {\n try {\n return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(false);\n }\n catch {\n return null;\n }\n}\nfunction getPublicKey(s, compress) {\n try {\n return secp256k1.getPublicKey(s, compress);\n }\n catch {\n return null;\n }\n}\nfunction taggedHash(tag, ...messages) {\n return schnorr.utils.taggedHash(tag, ...messages);\n}\nfunction sha256Hash(...messages) {\n const h = sha256.create();\n for (const message of messages)\n h.update(message);\n return h.digest();\n}\nexport const musigCrypto = {\n read32b,\n write32b,\n readScalar,\n readSecret,\n secp256k1Right,\n jacobiSymbol,\n isPoint,\n isXOnlyPoint,\n scalarAdd,\n scalarMultiply,\n scalarNegate,\n scalarMod,\n isScalar,\n isSecret,\n pointNegate,\n pointX,\n hasEvenY,\n pointMultiplyUnsafe,\n pointMultiplyAndAddUnsafe,\n pointAdd,\n pointAddTweak,\n pointCompress,\n liftX,\n getPublicKey,\n taggedHash,\n sha256: sha256Hash,\n};\n//# sourceMappingURL=musig.js.map","/**\n * A fundamental building block of Ethereum is the underlying cryptographic primitives.\n */\nnull;\n// We import all these so we can export lock()\nimport { computeHmac } from './hmac.js';\nimport { keccak256 } from './keccak.js';\nimport { ripemd160 } from './ripemd160.js';\nimport { pbkdf2 } from './pbkdf2.js';\nimport { randomBytes } from './random.js';\nimport { scrypt, scryptSync } from './scrypt.js';\nimport { sha256, sha512 } from './sha2.js';\nexport { computeHmac, randomBytes, keccak256, ripemd160, sha256, sha512, pbkdf2, scrypt, scryptSync };\nexport { SigningKey } from './signing-key.js';\nexport { Signature } from './signature.js';\n/**\n * Once called, prevents any future change to the underlying cryptographic primitives using the `.register` feature for\n * hooks.\n *\n * @category Crypto\n */\nfunction lock() {\n computeHmac.lock();\n keccak256.lock();\n pbkdf2.lock();\n randomBytes.lock();\n ripemd160.lock();\n scrypt.lock();\n scryptSync.lock();\n sha256.lock();\n sha512.lock();\n randomBytes.lock();\n}\nexport { lock };\nexport { musigCrypto } from './musig.js';\n//# sourceMappingURL=index.js.map","import { keccak256, SigningKey } from '../crypto/index.js';\nimport { getBytes, assertArgument, concat, zeroPadValue, dataSlice, toBigInt, toBeHex, stripZerosLeft, } from '../utils/index.js';\nexport function formatMixedCaseChecksumAddress(address) {\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/**\n * Returns a normalized and checksumed address for `address`. This accepts non-checksum addressesa and checksum\n * addresses.\n *\n * The checksum in Quai uses the capitalization (upper-case 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 assumed to already be a checksum address and its checksum\n * is validated, and if the address fails its expected checksum an error is thrown.\n *\n * If you wish the checksum of `address` to be ignore, it should be converted to lower-case (i.e. `.toLowercase()`)\n * before being passed in. This should be a very rare situation though, that you wish to bypass the safeguards in place\n * to protect against an address that has been incorrectly copied from another source.\n *\n * @category Address\n * @example\n *\n * ```js\n * // Adds the checksum (via upper-casing specific letters)\n * getAddress('0x8ba1f109551bd432803012645ac136ddd64dba72');\n *\n * // Throws an error if an address contains mixed case,\n * // but the checksum fails\n * getAddress('0x8Ba1f109551bD432803012645Ac136ddd64DBA72');\n * ```\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 = formatMixedCaseChecksumAddress(address);\n // If original address is mix cased and recomputed version doesn't\n // match the original this could indicate a potential typo or mispaste.\n assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, 'invalid address checksum', 'address', address);\n return result;\n }\n assertArgument(false, 'invalid address string format', 'address', address);\n}\nexport function getContractAddress(from, nonce, data) {\n const nonceBytes = zeroPadValue(toBeHex(toBigInt(nonce)), 8);\n return getAddress(dataSlice(keccak256(concat([getAddress(from), nonceBytes, stripZerosLeft(data)])), 12));\n}\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 *\n * @category Address\n * @param {string | SigningKey} key - The key to compute the address for.\n * @returns {string} The address.\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 used to sign `digest` that resulted in `signature`.\n *\n * @category Address\n * @param {BytesLike} digest - The digest of the message.\n * @param {SignatureLike} signature - The signature.\n * @returns {string} The address.\n */\nexport function recoverAddress(digest, signature) {\n return computeAddress(SigningKey.recoverPublicKey(digest, signature));\n}\n//# sourceMappingURL=address.js.map","import { assertArgument } from '../utils/index.js';\nimport { formatMixedCaseChecksumAddress, getAddress } from './address.js';\n/**\n * Returns true if `value` is an object which implements the [**Addressable**](../interfaces/Addressable) interface.\n *\n * @category Address\n * @example\n *\n * ```js\n * // Wallets and AbstractSigner sub-classes\n * isAddressable(Wallet.createRandom());\n *\n * // Contracts\n * contract = new Contract('0x643aA0A61eADCC9Cc202D1915D942d35D005400C', [], provider);\n * isAddressable(contract);\n * ```\n *\n * @param {any} value - The value to check.\n * @returns {boolean} True if the value is an Addressable.\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 * @category Address\n * @example\n *\n * ```js\n * // Valid address\n * isAddress('0x8ba1f109551bD432803012645Ac136ddd64DBA72');\n *\n * // Invalid checksum\n * isAddress('0x8Ba1f109551bD432803012645Ac136ddd64DBa72');\n * ```\n *\n * @param {any} value - The value to check.\n * @returns {boolean} True if the value is a valid address.\n */\nexport function isAddress(value) {\n try {\n getAddress(value);\n return true;\n // eslint-disable-next-line no-empty\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 assertArgument(false, 'invalid AddressLike value; did not resolve to a value address', 'target', target);\n }\n return result;\n}\n/**\n * Resolves to an address for the `target`, which may be any supported address type, an\n * [**Addressable**](../interfaces/Addressable) or a Promise which resolves to an address.\n *\n * @category Address\n * @example\n *\n * ```js\n * addr = '0x6B175474E89094C44Da98b954EedeAC495271d0F';\n *\n * // Addresses are return synchronously\n * resolveAddress(addr, provider);\n *\n * // Address promises are resolved asynchronously\n * resolveAddress(Promise.resolve(addr));\n *\n * // Addressable objects are resolved asynchronously\n * contract = new Contract(addr, []);\n * resolveAddress(contract, provider);\n * ```\n *\n * @param {AddressLike} target - The target to resolve to an address.\n * @returns {string | Promise} The resolved address.\n */\nexport function resolveAddress(target) {\n if (typeof target === 'string') {\n if (target.match(/^0x[0-9a-f]{40}$/i)) {\n return target;\n }\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/**\n * Checks if the address is a valid mixed case checksummed address.\n *\n * @category Address\n * @param address - The address to validate.\n * @returns True if the address is a valid mixed case checksummed address.\n */\nexport function validateAddress(address) {\n assertArgument(typeof address === 'string', 'address must be string', 'address', address);\n assertArgument(Boolean(address.match(/^(0x)?[0-9a-fA-F]{40}$/)), 'invalid address string format', 'address', address);\n assertArgument(formatMixedCaseChecksumAddress(address) === address, 'invalid address checksum', 'address', address);\n}\n/**\n * Checks whether a given address is in the Qi ledger scope by checking the 9th bit of the address.\n *\n * @category Address\n * @param {string} address - The address to check\n * @returns {boolean} True if the address is in the Qi ledger scope, false otherwise.\n */\nexport function isQiAddress(address) {\n const secondByte = address.substring(4, 6);\n const binaryString = parseInt(secondByte, 16).toString(2).padStart(8, '0');\n const isUTXO = binaryString[0] === '1';\n return isUTXO;\n}\n/**\n * Checks whether a given address is in the Quai ledger scope by checking the 9th bit of the address.\n *\n * @category Address\n * @param {string} address - The address to check\n * @returns {boolean} True if the address is in the Quai ledger scope, false otherwise.\n */\nexport function isQuaiAddress(address) {\n return !isQiAddress(address);\n}\n//# sourceMappingURL=checks.js.map","import { Ledger, toZone } from '../constants/zones.js';\nimport { isQiAddress } from '../address/checks.js';\n/**\n * Retrieves the shard information for a given address based on its byte prefix. The function parses the address to\n * extract its byte prefix, then filters the ShardData to find a matching shard entry. If no matching shard is found, it\n * returns null.\n *\n * @category Utils\n * @param {string} address - The blockchain address to be analyzed. The address should start with \"0x\" followed by the\n * hexadecimal representation.\n * @returns {Object | null} An object containing the shard information, or null if no\n */\nexport function getZoneForAddress(address) {\n try {\n return toZone(address.slice(0, 4));\n }\n catch (error) {\n return null;\n }\n}\n/**\n * Extracts both zone and UTXO information from a given blockchain address. This function first determines the address's\n * zone by its byte prefix, then checks the 9th bit of the address to ascertain if it's a UTXO or non-UTXO address.\n *\n * @category Utils\n * @param {string} address - The blockchain address to be analyzed, expected to start with \"0x\" followed by its\n * hexadecimal representation.\n * @returns {Object | null} An object containing the zone and UTXO information, or null if no address is found.\n */\nexport function getAddressDetails(address) {\n const isQiLedger = (parseInt(address.substring(4, 5), 16) & 0x1) === Ledger.Qi;\n return { zone: toZone(address.substring(0, 4)), ledger: isQiLedger ? Ledger.Qi : Ledger.Quai };\n}\n/**\n * Determines the transaction type based on the sender and recipient addresses. The function checks if both addresses\n * are UTXO addresses, in which case it returns 2. If only the sender address is a UTXO address, it returns 1.\n * Otherwise, it returns 0.\n *\n * @category Utils\n * @param {string | null} from - The sender address. If null, the function returns 0.\n * @param {string | null} to - The recipient address. If null, the function returns 0.\n * @returns {number} The transaction type based on the addresses.\n */\nexport function getTxType(from, to) {\n if (from === null || to === null)\n return 0;\n const senderAddressIsQi = isQiAddress(from);\n const recipientAddressIsQi = isQiAddress(to);\n switch (true) {\n case senderAddressIsQi && recipientAddressIsQi:\n return 2;\n case senderAddressIsQi && !recipientAddressIsQi:\n return 1;\n default:\n return 0;\n }\n}\n/**\n * Location of a chain within the Quai hierarchy\n *\n * Prime = [] region[0] = [0] zone[1,2] = [1, 2]\n *\n * @param shard - The shard to get the location for\n * @returns The location of the chain within the Quai hierarchy\n */\nexport function getNodeLocationFromZone(zone) {\n const zoneId = zone.slice(2);\n if (zoneId.length > 2) {\n throw new Error(`Invalid zone: ${zone}`);\n }\n else if (zoneId.length === 0) {\n return [];\n }\n return zoneId.split('').map(Number);\n}\nexport function getZoneFromNodeLocation(location) {\n if (location.length > 2) {\n throw new Error('Invalid location');\n }\n return toZone(`0x${location.join('')}`);\n}\n//# sourceMappingURL=shards.js.map","import { defineProperties, concat, getBytesCopy, getNumber, hexlify, toBeArray, toBigInt, toNumber, assert, assertArgument, } 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 = {};\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}\n/**\n * A {@link Result | **Result**} is a sub-class of Array, which allows accessing any of its values either positionally by\n * its index or, if keys are provided by its name.\n *\n * @category Application Binary Interface\n */\nexport class Result extends Array {\n #names;\n /**\n * @ignore\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, keys?: Array);\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) => {\n this[index] = item;\n });\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 this.#names = 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 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 return 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 }\n /**\n * Returns the Result as a normal Array.\n *\n * This will throw if there are any outstanding deferred errors.\n */\n toArray() {\n const result = [];\n this.forEach((item, index) => {\n if (item instanceof Error) {\n throwError(`index ${index}`, item);\n }\n result.push(item);\n });\n return result;\n }\n /**\n * Returns the Result as an Object with each name-value pair.\n *\n * This will throw if any value is unnamed, or if there are any outstanding deferred errors.\n */\n toObject() {\n return this.#names.reduce(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n (accum, name, index) => {\n assert(name != null, 'value at index ${ index } unnamed', 'UNSUPPORTED_OPERATION', {\n operation: 'toObject()',\n });\n // Add values for names that don't conflict\n if (!(name in accum)) {\n accum[name] = this.getValue(name);\n }\n return accum;\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 result = [], names = [];\n for (let i = start; i < end; i++) {\n result.push(this[i]);\n names.push(this.#names[i]);\n }\n return new Result(_guard, result, names);\n }\n /**\n * @ignore\n */\n filter(callback, thisArg) {\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(this.#names[i]);\n }\n }\n return new Result(_guard, result, names);\n }\n /**\n * @ignore\n */\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-constraint\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 a method on a {@link Result | **Result**} or its\n * superclass Array, or any JavaScript keyword, this ensures all named values are still accessible by name.\n *\n * @param {string} name - The name of the value to retrieve.\n *\n * @returns The value for `name`.\n */\n getValue(name) {\n const index = this.#names.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 {@link Result | **Result**} for `items` with each entry also accessible by its corresponding name in\n * `keys`.\n *\n * @param {any[]} items - The items to include in the Result.\n * @param {(null | string)[]} [keys] - The names for each item in `items`.\n *\n * @returns The new Result.\n */\n static fromItems(items, keys) {\n return new Result(_guard, items, keys);\n }\n}\n/**\n * Returns all errors found in a {@link Result | **Result**}.\n *\n * Since certain errors encountered when creating a {@link Result | **Result**} do not impact the ability to continue\n * parsing data, they are deferred until they are actually accessed. Hence a faulty string in an Event that is never\n * used does not impact the program flow.\n *\n * However, sometimes it may be useful to access, identify or validate correctness of a {@link Result | **Result**}.\n *\n * @category Application Binary Interface\n * @param {Result} result - The Result to check for errors.\n *\n * @returns An array of objects with the path to the error and the error itself.\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 (const 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', {\n buffer: bytes,\n length: WordSize,\n offset: bytes.length,\n });\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',\n type: 'string',\n localName: 'string',\n 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() {\n return this.#dataLength;\n }\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() {\n return hexlify(this.#data);\n }\n get dataLength() {\n return this.#data.length;\n }\n get consumed() {\n return this.#offset;\n }\n get bytes() {\n return new Uint8Array(this.#data);\n }\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, \n // eslint-disable-next-line no-useless-escape\n `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),\n offset: this.#offset,\n length: count,\n 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 const 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","import { keccak256 } from '../crypto/index.js';\nimport { concat, dataSlice, getBigInt, getBytes, 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 deployed to by an EOA when sending a deployment\n * transaction (i.e. when the `to` address is `null`).\n *\n * This can also be used to compute the address a contract will be deployed to by a contract, by using the contract's\n * address as the `to` and the contract's nonce.\n *\n * @category Address\n * @example\n *\n * ```js\n * from = '0x8ba1f109551bD432803012645Ac136ddd64DBA72';\n * nonce = 5;\n *\n * getCreateAddress({ from, nonce });\n * ```\n *\n * @param {object} tx - The transaction object.\n * @param {string} tx.from - The address of the sender.\n * @param {BigNumberish} tx.nonce - The nonce of the sender.\n * @param {string} [tx.data] - The data of the transaction.\n */\nexport function getCreateAddress(tx) {\n const from = getAddress(tx.from);\n const nonce = getBigInt(tx.nonce, 'tx.nonce');\n const nonceBytes = bigEndianNonce(nonce);\n const fromBytes = getBytes(from);\n const codeBytes = tx.data ? getBytes(tx.data) : new Uint8Array();\n const concatenated = new Uint8Array([...fromBytes, ...nonceBytes, ...codeBytes]);\n const hash = keccak256(concatenated);\n return getAddress(dataSlice(hash, 12));\n}\n/**\n * Returns the address that would result from a `CREATE2` operation with the given `from`, `salt` and `initCodeHash`.\n *\n * To compute the `initCodeHash` from a contract's init code, use the [**keccak256**](../functions/keccak256) function.\n *\n * For a quick overview and example of `CREATE2`, see [Wisps: The Magical World of\n * Create2](https://blog.ricmoo.com/wisps-the-magical-world-of-create2-5c2177027604).\n *\n * @category Address\n * @example\n *\n * ```js\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 * ```\n *\n * @param {string} _from - The address of the sender.\n * @param {BytesLike} _salt - The salt value.\n * @param {BytesLike} _initCodeHash - The hash of the init code.\n * @returns {string} The computed address.\n * @throws {Error} If the salt is not exactly 32 bytes long.\n * @throws {Error} If the initCodeHash is not exactly 32 bytes long.\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// Helper function to convert a BigInt nonce to a big-endian byte array\nfunction bigEndianNonce(nonce) {\n const buffer = new ArrayBuffer(8);\n const view = new DataView(buffer);\n view.setBigUint64(0, nonce, false);\n return new Uint8Array(buffer);\n}\n//# sourceMappingURL=contract-address.js.map","/**\n * A Typed object allows a value to have its type explicitly specified.\n *\n * For example, in Solidity, the value `45` could represent a `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 APIs which what the type is, this allows transparent\n * interoperation with Soldity.\n *\n * @category Application Binary Interface\n */\nimport { assertPrivate, defineProperties } from '../utils/index.js';\nconst _guard = {};\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(_guard, `${signed ? '' : 'u'}int${width}`, value, { signed, width });\n}\nfunction b(value, size) {\n // @TODO: Check range is valid for value\n return new Typed(_guard, `bytes${size ? size : ''}`, value, { size });\n}\nconst _typedSymbol = Symbol.for('_quais_typed');\n/**\n * The **Typed** class to wrap values providing explicit type information.\n *\n * @category Application Binary Interface\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(guard, type, value, options) {\n if (options == null) {\n options = null;\n }\n assertPrivate(_guard, guard, '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 * @returns The human-readable type for the provided type.\n * @throws If the type is array or dynamic array.\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 * @returns The default value for this type.\n */\n defaultValue() {\n return 0;\n }\n /**\n * The minimum value for numeric types.\n *\n * @returns The minimum value for the provided numeric type.\n */\n minValue() {\n return 0;\n }\n /**\n * The maximum value for numeric types.\n *\n * @returns The maximum value for the provided numeric type.\n */\n maxValue() {\n return 0;\n }\n /**\n * Returns whether this is a {@link TypedBigInt | **TypedBigInt**}. If true, a type guard is provided.\n *\n * @returns `true` if this is a big integer.\n */\n isBigInt() {\n return !!this.type.match(/^u?int[0-9]+$/);\n }\n /**\n * Returns whether this is a {@link TypedData | **TypedData**}. If true, a type guard is provided.\n *\n * @returns {boolean} `true` if this is a number.\n */\n isData() {\n return this.type.startsWith('bytes');\n }\n /**\n * Return whether this is a {@link TypedString | **TypedString**}. If true, a type guard is provided.\n *\n * @returns {boolean} `true` if this is a string.\n */\n isString() {\n return this.type === 'string';\n }\n /**\n * Returns the tuple name.\n *\n * @returns {boolean} The tuple name if this is a tuple.\n * @throws If this is not a tuple.\n */\n get tupleName() {\n if (this.type !== 'tuple') {\n throw TypeError('not a tuple');\n }\n return this.#options;\n }\n /**\n * Returns the length of a typed array.\n *\n * @returns {number} The length of the array type or `-1` if it is dynamic.\n * @throws If this 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 * @param {string} type - The type to use.\n * @param {any} value - The value to use.\n */\n static from(type, value) {\n return new Typed(_guard, type, value);\n }\n /**\n * Return a new `uint8` type for v.\n *\n * @param {BigNumberish} v - The value to convert to a `uint8`.\n *\n * @returns {uint8} A new `uint8` type for `v`.\n */\n static uint8(v) {\n return n(v, 8);\n }\n /**\n * Return a new `uint16` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint16`.\n *\n * @returns A new `uint16` type for `v`.\n */\n static uint16(v) {\n return n(v, 16);\n }\n /**\n * Return a new `uint24` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint24`.\n *\n * @returns A new `uint24` type for `v`.\n */\n static uint24(v) {\n return n(v, 24);\n }\n /**\n * Return a new `uint32` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint32`.\n *\n * @returns A new `uint32` type for `v`.\n */\n static uint32(v) {\n return n(v, 32);\n }\n /**\n * Return a new `uint40` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint40`.\n *\n * @returns A new `uint40` type for `v`.\n */\n static uint40(v) {\n return n(v, 40);\n }\n /**\n * Return a new `uint48` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint48`.\n *\n * @returns A new `uint48` type for `v`.\n */\n static uint48(v) {\n return n(v, 48);\n }\n /**\n * Return a new `uint56` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint56`.\n *\n * @returns A new `uint56` type for `v`.\n */\n static uint56(v) {\n return n(v, 56);\n }\n /**\n * Return a new `uint64` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint64`.\n *\n * @returns A new `uint64` type for `v`.\n */\n static uint64(v) {\n return n(v, 64);\n }\n /**\n * Return a new `uint72` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint72`.\n *\n * @returns A new `uint72` type for `v`.\n */\n static uint72(v) {\n return n(v, 72);\n }\n /**\n * Return a new `uint80` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint80`.\n *\n * @returns A new `uint80` type for `v`.\n */\n static uint80(v) {\n return n(v, 80);\n }\n /**\n * Return a new `uint88` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint88`.\n *\n * @returns A new `uint88` type for `v`.\n */\n static uint88(v) {\n return n(v, 88);\n }\n /**\n * Return a new `uint96` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint96`.\n *\n * @returns A new `uint96` type for `v`.\n */\n static uint96(v) {\n return n(v, 96);\n }\n /**\n * Return a new `uint104` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint104`.\n *\n * @returns A new `uint104` type for `v`.\n */\n static uint104(v) {\n return n(v, 104);\n }\n /**\n * Return a new `uint112` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint112`.\n *\n * @returns A new `uint112` type for `v`.\n */\n static uint112(v) {\n return n(v, 112);\n }\n /**\n * Return a new `uint120` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint120`.\n *\n * @returns A new `uint120` type for `v`.\n */\n static uint120(v) {\n return n(v, 120);\n }\n /**\n * Return a new `uint128` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint128`.\n *\n * @returns A new `uint128` type for `v`.\n */\n static uint128(v) {\n return n(v, 128);\n }\n /**\n * Return a new `uint136` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint136`.\n *\n * @returns A new `uint136` type for `v`.\n */\n static uint136(v) {\n return n(v, 136);\n }\n /**\n * Return a new `uint144` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint144`.\n *\n * @returns A new `uint144` type for `v`.\n */\n static uint144(v) {\n return n(v, 144);\n }\n /**\n * Return a new `uint152` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint152`.\n *\n * @returns A new `uint152` type for `v`.\n */\n static uint152(v) {\n return n(v, 152);\n }\n /**\n * Return a new `uint160` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint160`.\n *\n * @returns A new `uint160` type for `v`.\n */\n static uint160(v) {\n return n(v, 160);\n }\n /**\n * Return a new `uint168` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint168`.\n *\n * @returns A new `uint168` type for `v`.\n */\n static uint168(v) {\n return n(v, 168);\n }\n /**\n * Return a new `uint176` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint176`.\n *\n * @returns A new `uint176` type for `v`.\n */\n static uint176(v) {\n return n(v, 176);\n }\n /**\n * Return a new `uint184` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint184`.\n *\n * @returns A new `uint184` type for `v`.\n */\n static uint184(v) {\n return n(v, 184);\n }\n /**\n * Return a new `uint192` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint192`.\n *\n * @returns A new `uint192` type for `v`.\n */\n static uint192(v) {\n return n(v, 192);\n }\n /**\n * Return a new `uint200` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint200`.\n *\n * @returns A new `uint200` type for `v`.\n */\n static uint200(v) {\n return n(v, 200);\n }\n /**\n * Return a new `uint208` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint208`.\n *\n * @returns A new `uint208` type for `v`.\n */\n static uint208(v) {\n return n(v, 208);\n }\n /**\n * Return a new `uint216` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint216`.\n *\n * @returns A new `uint216` type for `v`.\n */\n static uint216(v) {\n return n(v, 216);\n }\n /**\n * Return a new `uint224` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint224`.\n *\n * @returns A new `uint224` type for `v`.\n */\n static uint224(v) {\n return n(v, 224);\n }\n /**\n * Return a new `uint232` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint232`.\n *\n * @returns A new `uint232` type for `v`.\n */\n static uint232(v) {\n return n(v, 232);\n }\n /**\n * Return a new `uint240` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint240`.\n *\n * @returns A new `uint240` type for `v`.\n */\n static uint240(v) {\n return n(v, 240);\n }\n /**\n * Return a new `uint248` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint248`.\n *\n * @returns A new `uint248` type for `v`.\n */\n static uint248(v) {\n return n(v, 248);\n }\n /**\n * Return a new `uint256` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint256`.\n *\n * @returns A new `uint256` type for `v`.\n */\n static uint256(v) {\n return n(v, 256);\n }\n /**\n * Return a new `uint256` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to a `uint256`.\n *\n * @returns A new `uint256` type for `v`.\n */\n static uint(v) {\n return n(v, 256);\n }\n /**\n * Return a new `int8` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int8`.\n *\n * @returns A new `int8` type for `v`.\n */\n static int8(v) {\n return n(v, -8);\n }\n /**\n * Return a new `int16` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int16`.\n *\n * @returns A new `int16` type for `v`.\n */\n static int16(v) {\n return n(v, -16);\n }\n /**\n * Return a new `int24` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int24`.\n *\n * @returns A new `int24` type for `v`.\n */\n static int24(v) {\n return n(v, -24);\n }\n /**\n * Return a new `int32` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int32`.\n *\n * @returns A new `int32` type for `v`.\n */\n static int32(v) {\n return n(v, -32);\n }\n /**\n * Return a new `int40` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int40`.\n *\n * @returns A new `int40` type for `v`.\n */\n static int40(v) {\n return n(v, -40);\n }\n /**\n * Return a new `int48` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int48`.\n *\n * @returns A new `int48` type for `v`.\n */\n static int48(v) {\n return n(v, -48);\n }\n /**\n * Return a new `int56` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int56`.\n *\n * @returns A new `int56` type for `v`.\n */\n static int56(v) {\n return n(v, -56);\n }\n /**\n * Return a new `int64` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int64`.\n *\n * @returns A new `int64` type for `v`.\n */\n static int64(v) {\n return n(v, -64);\n }\n /**\n * Return a new `int72` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int72`.\n *\n * @returns A new `int72` type for `v`.\n */\n static int72(v) {\n return n(v, -72);\n }\n /**\n * Return a new `int80` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int80`.\n *\n * @returns A new `int80` type for `v`.\n */\n static int80(v) {\n return n(v, -80);\n }\n /**\n * Return a new `int88` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int88`.\n *\n * @returns A new `int88` type for `v`.\n */\n static int88(v) {\n return n(v, -88);\n }\n /**\n * Return a new `int96` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int96`.\n *\n * @returns A new `int96` type for `v`.\n */\n static int96(v) {\n return n(v, -96);\n }\n /**\n * Return a new `int104` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int104`.\n *\n * @returns A new `int104` type for `v`.\n */\n static int104(v) {\n return n(v, -104);\n }\n /**\n * Return a new `int112` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int112`.\n *\n * @returns A new `int112` type for `v`.\n */\n static int112(v) {\n return n(v, -112);\n }\n /**\n * Return a new `int120` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int120`.\n *\n * @returns A new `int120` type for `v`.\n */\n static int120(v) {\n return n(v, -120);\n }\n /**\n * Return a new `int128` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int128`.\n *\n * @returns A new `int128` type for `v`.\n */\n static int128(v) {\n return n(v, -128);\n }\n /**\n * Return a new `int136` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int136`.\n *\n * @returns A new `int136` type for `v`.\n */\n static int136(v) {\n return n(v, -136);\n }\n /**\n * Return a new `int144` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int144`.\n *\n * @returns A new `int144` type for `v`.\n */\n static int144(v) {\n return n(v, -144);\n }\n /**\n * Return a new `int152` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int152`.\n *\n * @returns A new `int152` type for `v`.\n */\n static int152(v) {\n return n(v, -152);\n }\n /**\n * Return a new `int160` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int160`.\n *\n * @returns A new `int160` type for `v`.\n */\n static int160(v) {\n return n(v, -160);\n }\n /**\n * Return a new `int168` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int168`.\n *\n * @returns A new `int168` type for `v`.\n */\n static int168(v) {\n return n(v, -168);\n }\n /**\n * Return a new `int176` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int176`.\n *\n * @returns A new `int176` type for `v`.\n */\n static int176(v) {\n return n(v, -176);\n }\n /**\n * Return a new `int184` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int184`.\n *\n * @returns A new `int184` type for `v`.\n */\n static int184(v) {\n return n(v, -184);\n }\n /**\n * Return a new `int192` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int192`.\n *\n * @returns A new `int192` type for `v`.\n */\n static int192(v) {\n return n(v, -192);\n }\n /**\n * Return a new `int200` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int200`.\n *\n * @returns A new `int200` type for `v`.\n */\n static int200(v) {\n return n(v, -200);\n }\n /**\n * Return a new `int208` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int208`.\n *\n * @returns A new `int208` type for `v`.\n */\n static int208(v) {\n return n(v, -208);\n }\n /**\n * Return a new `int216` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int216`.\n *\n * @returns A new `int216` type for `v`.\n */\n static int216(v) {\n return n(v, -216);\n }\n /**\n * Return a new `int224` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int224`.\n *\n * @returns A new `int224` type for `v`.\n */\n static int224(v) {\n return n(v, -224);\n }\n /**\n * Return a new `int232` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int232`.\n *\n * @returns A new `int232` type for `v`.\n */\n static int232(v) {\n return n(v, -232);\n }\n /**\n * Return a new `int240` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int240`.\n *\n * @returns A new `int240` type for `v`.\n */\n static int240(v) {\n return n(v, -240);\n }\n /**\n * Return a new `int248` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int248`.\n *\n * @returns A new `int248` type for `v`.\n */\n static int248(v) {\n return n(v, -248);\n }\n /**\n * Return a new `int256` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int256`.\n *\n * @returns A new `int256` type for `v`.\n */\n static int256(v) {\n return n(v, -256);\n }\n /**\n * Return a new `int256` type for `v`.\n *\n * @param {BigNumberish} v - The value to convert to an `int256`.\n *\n * @returns A new `int256` type for `v`.\n */\n static int(v) {\n return n(v, -256);\n }\n /**\n * Return a new `bytes1` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes1`.\n *\n * @returns A new `bytes1` type for `v`.\n */\n static bytes1(v) {\n return b(v, 1);\n }\n /**\n * Return a new `bytes2` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes2`.\n *\n * @returns A new `bytes2` type for `v`.\n */\n static bytes2(v) {\n return b(v, 2);\n }\n /**\n * Return a new `bytes3` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes3`.\n *\n * @returns A new `bytes3` type for `v`.\n */\n static bytes3(v) {\n return b(v, 3);\n }\n /**\n * Return a new `bytes4` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes4`.\n *\n * @returns A new `bytes4` type for `v`.\n */\n static bytes4(v) {\n return b(v, 4);\n }\n /**\n * Return a new `bytes5` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes5`.\n *\n * @returns A new `bytes5` type for `v`.\n */\n static bytes5(v) {\n return b(v, 5);\n }\n /**\n * Return a new `bytes6` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes6`.\n *\n * @returns A new `bytes6` type for `v`.\n */\n static bytes6(v) {\n return b(v, 6);\n }\n /**\n * Return a new `bytes7` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes7`.\n *\n * @returns A new `bytes7` type for `v`.\n */\n static bytes7(v) {\n return b(v, 7);\n }\n /**\n * Return a new `bytes8` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes8`.\n *\n * @returns A new `bytes8` type for `v`.\n */\n static bytes8(v) {\n return b(v, 8);\n }\n /**\n * Return a new `bytes9` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes9`.\n *\n * @returns A new `bytes9` type for `v`.\n */\n static bytes9(v) {\n return b(v, 9);\n }\n /**\n * Return a new `bytes10` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes10`.\n *\n * @returns A new `bytes10` type for `v`.\n */\n static bytes10(v) {\n return b(v, 10);\n }\n /**\n * Return a new `bytes11` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes11`.\n *\n * @returns A new `bytes11` type for `v`.\n */\n static bytes11(v) {\n return b(v, 11);\n }\n /**\n * Return a new `bytes12` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes12`.\n *\n * @returns A new `bytes12` type for `v`.\n */\n static bytes12(v) {\n return b(v, 12);\n }\n /**\n * Return a new `bytes13` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes13`.\n *\n * @returns A new `bytes13` type for `v`.\n */\n static bytes13(v) {\n return b(v, 13);\n }\n /**\n * Return a new `bytes14` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes14`.\n *\n * @returns A new `bytes14` type for `v`.\n */\n static bytes14(v) {\n return b(v, 14);\n }\n /**\n * Return a new `bytes15` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes15`.\n *\n * @returns A new `bytes15` type for `v`.\n */\n static bytes15(v) {\n return b(v, 15);\n }\n /**\n * Return a new `bytes16` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes16`.\n *\n * @returns A new `bytes16` type for `v`.\n */\n static bytes16(v) {\n return b(v, 16);\n }\n /**\n * Return a new `bytes17` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes17`.\n *\n * @returns A new `bytes17` type for `v`.\n */\n static bytes17(v) {\n return b(v, 17);\n }\n /**\n * Return a new `bytes18` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes18`.\n *\n * @returns A new `bytes18` type for `v`.\n */\n static bytes18(v) {\n return b(v, 18);\n }\n /**\n * Return a new `bytes19` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes19`.\n *\n * @returns A new `bytes19` type for `v`.\n */\n static bytes19(v) {\n return b(v, 19);\n }\n /**\n * Return a new `bytes20` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes20`.\n *\n * @returns A new `bytes20` type for `v`.\n */\n static bytes20(v) {\n return b(v, 20);\n }\n /**\n * Return a new `bytes21` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes21`.\n *\n * @returns A new `bytes21` type for `v`.\n */\n static bytes21(v) {\n return b(v, 21);\n }\n /**\n * Return a new `bytes22` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes22`.\n *\n * @returns A new `bytes22` type for `v`.\n */\n static bytes22(v) {\n return b(v, 22);\n }\n /**\n * Return a new `bytes23` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes23`.\n *\n * @returns A new `bytes23` type for `v`.\n */\n static bytes23(v) {\n return b(v, 23);\n }\n /**\n * Return a new `bytes24` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes24`.\n *\n * @returns A new `bytes24` type for `v`.\n */\n static bytes24(v) {\n return b(v, 24);\n }\n /**\n * Return a new `bytes25` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes25`.\n *\n * @returns A new `bytes25` type for `v`.\n */\n static bytes25(v) {\n return b(v, 25);\n }\n /**\n * Return a new `bytes26` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes26`.\n *\n * @returns A new `bytes26` type for `v`.\n */\n static bytes26(v) {\n return b(v, 26);\n }\n /**\n * Return a new `bytes27` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes27`.\n *\n * @returns A new `bytes27` type for `v`.\n */\n static bytes27(v) {\n return b(v, 27);\n }\n /**\n * Return a new `bytes28` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes28`.\n *\n * @returns A new `bytes28` type for `v`.\n */\n static bytes28(v) {\n return b(v, 28);\n }\n /**\n * Return a new `bytes29` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes29`.\n *\n * @returns A new `bytes29` type for `v`.\n */\n static bytes29(v) {\n return b(v, 29);\n }\n /**\n * Return a new `bytes30` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes30`.\n *\n * @returns A new `bytes30` type for `v`.\n */\n static bytes30(v) {\n return b(v, 30);\n }\n /**\n * Return a new `bytes31` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes31`.\n *\n * @returns A new `bytes31` type for `v`.\n */\n static bytes31(v) {\n return b(v, 31);\n }\n /**\n * Return a new `bytes32` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes32`.\n *\n * @returns A new `bytes32` type for `v`.\n */\n static bytes32(v) {\n return b(v, 32);\n }\n /**\n * Return a new `address` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to an `address`.\n *\n * @returns A new `address` type for `v`.\n */\n static address(v) {\n return new Typed(_guard, 'address', v);\n }\n /**\n * Return a new `bool` type for `v`.\n *\n * @param {any} v - The value to convert to a `bool`.\n *\n * @returns A new `bool` type for `v`.\n */\n static bool(v) {\n return new Typed(_guard, 'bool', !!v);\n }\n /**\n * Return a new `bytes` type for `v`.\n *\n * @param {BytesLike} v - The value to convert to a `bytes`.\n *\n * @returns A new `bytes` type for `v`.\n */\n static bytes(v) {\n return new Typed(_guard, 'bytes', v);\n }\n /**\n * Return a new `string` type for `v`.\n *\n * @param {string} v - The value to convert to a `string`.\n *\n * @returns A new `string` type for `v`.\n */\n static string(v) {\n return new Typed(_guard, 'string', v);\n }\n /**\n * Return a new `array` type for v, allowing dynamic length.\n *\n * @param {(any | Typed)[]} v - The value to convert to an `array`.\n * @param {null | boolean} dynamic - Whether the array is dynamic.\n *\n * @returns A new `array` type for `v`.\n */\n static array(v, dynamic) {\n throw new Error('not implemented yet');\n return new Typed(_guard, 'array', v, dynamic);\n }\n /**\n * Return a new `tuple` type for v, with the optional name.\n *\n * @param {(any | Typed)[]} v - The value to convert to a `tuple`.\n * @param {string} name - The name of the tuple.\n *\n * @returns A new `tuple` type for `v`.\n */\n static tuple(v, name) {\n throw new Error('not implemented yet');\n return new Typed(_guard, 'tuple', v, name);\n }\n /**\n * Return a new `overrides` type with the provided properties.\n *\n * @param {Record} v - A record containing the properties to be included in the `overrides` type.\n *\n * @returns A new `overrides` type with the given properties.\n */\n static overrides(v) {\n return new Typed(_guard, 'overrides', Object.assign({}, v));\n }\n /**\n * Returns true only if `value` is a {@link Typed | **Typed**} instance.\n *\n * @param {any} value - The value to check.\n *\n * @returns {boolean} True if `value` is a {@link Typed | **Typed**} instance.\n */\n static isTyped(value) {\n return value && typeof value === 'object' && '_typedSymbol' in value && value._typedSymbol === _typedSymbol;\n }\n /**\n * If the value is a {@link Typed | **Typed**} instance, validates the underlying value and returns it, otherwise\n * returns value directly.\n *\n * This is useful for functions that with to accept either a {@link Typed | **Typed**} object or values.\n *\n * @param {Typed | T} value - The value to dereference.\n * @param {string} type - The dereferenced value.\n */\n static dereference(value, type) {\n if (Typed.isTyped(value)) {\n if (value.type !== type) {\n throw new Error(`invalid type: expected ${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 \"../../encoding/index.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 '../encoding/index.js';\n/**\n * A simple hashing function which operates on UTF-8 strings to compute an 32-byte identifier.\n *\n * This simply computes the {@link toUtf8Bytes | **UTF-8 bytes**} and computes the {@link keccak256 | **keccak256**}.\n *\n * @category Hash\n * @example\n *\n * ```ts\n * id('hello world');\n * ```\n *\n * @param {string} value - The string to hash.\n * @returns {string} The 32-byte identifier.\n */\nexport function id(value) {\n return keccak256(toUtf8Bytes(value));\n}\n//# sourceMappingURL=id.js.map","import { keccak256 } from '../crypto/index.js';\nimport { MessagePrefix } from '../constants/index.js';\nimport { recoverAddress } from '../address/index.js';\nimport { concat } from '../utils/index.js';\nimport { toUtf8Bytes } from '../encoding/index.js';\nimport { EthMessagePrefix } from '../constants/strings.js';\n/**\n * Computes the Quai Network equivalent of the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal-sign message\n * digest to sign.\n *\n * This prefixes the message with {@link MessagePrefix | **MessagePrefix**} and the decimal length of `message` and\n * computes the {@link keccak256 | **keccak256**} digest.\n *\n * If `message` is a string, it is converted to its UTF-8 bytes first. To compute the digest of a\n * [**DataHexString**](../types-aliases/DataHex), it must be converted to [**bytes**](../functions/getBytes).\n *\n * @category Hash\n * @example\n *\n * ```ts\n * hashMessage('Hello World');\n *\n * // Hashes the SIX (6) string characters, i.e.\n * // [ \"0\", \"x\", \"4\", \"2\", \"4\", \"3\" ]\n * hashMessage('0x4243');\n *\n * // Hashes the TWO (2) bytes [ 0x42, 0x43 ]...\n * hashMessage(getBytes('0x4243'));\n *\n * // ...which is equal to using data\n * hashMessage(new Uint8Array([0x42, 0x43]));\n * ```\n *\n * @param {Uint8Array | string} message - The message to hash.\n * @returns {string} The message digest.\n */\nexport function hashMessage(message) {\n if (typeof message === 'string') {\n message = toUtf8Bytes(message);\n }\n return keccak256(concat([toUtf8Bytes(MessagePrefix), toUtf8Bytes(String(message.length)), message]));\n}\n/**\n * Return the address of the private key that produced the signature `sig` during signing for `message`.\n *\n * @category Hash\n * @param {Uint8Array | string} message - The message that was signed.\n * @param {SignatureLike} sig - The signature to verify.\n * @returns {string} The address of the signer.\n */\nexport function verifyMessage(message, sig) {\n const digest = hashMessage(message);\n return recoverAddress(digest, sig);\n}\n/**\n * Computes the [EIP-191](https://eips.ethereum.org/EIPS/eip-191) personal-sign message digest to sign.\n *\n * This prefixes the message with {@link EthMessagePrefix | **EthMessagePrefix**} and the decimal length of `message` and\n * computes the {@link keccak256 | **keccak256**} digest.\n *\n * If `message` is a string, it is converted to its UTF-8 bytes first. To compute the digest of a\n * [**DataHexString**](../types-aliases/DataHex), it must be converted to [**bytes**](../functions/getBytes).\n *\n * This is the same as `hashMessage` except it uses `EthMessagePrefix` instead of `MessagePrefix` and is available for\n * broader compatibility with EVM signing practices.\n *\n * @category Hash\n * @param message\n * @returns\n */\nexport function ethHashMessage(message) {\n if (typeof message === 'string') {\n message = toUtf8Bytes(message);\n }\n return keccak256(concat([toUtf8Bytes(EthMessagePrefix), toUtf8Bytes(String(message.length)), message]));\n}\n/**\n * Return the address of the private key that produced the signature `sig` during signing for `message`.\n *\n * This is the same as `verifyMessage` except it uses `EthMessagePrefix` instead of `MessagePrefix` and is available for\n * broader compatibility with EVM signing practices.\n *\n * @category Hash\n * @param message - The message that was signed.\n * @param sig - The signature to verify.\n * @returns {string} The address of the signer.\n */\nexport function ethVerifyMessage(message, sig) {\n const digest = ethHashMessage(message);\n return recoverAddress(digest, sig);\n}\n//# sourceMappingURL=message.js.map","import { getAddress } from '../address/index.js';\nimport { keccak256 as _keccak256, sha256 as _sha256 } from '../crypto/index.js';\nimport { concat, dataLength, getBytes, hexlify, toBeArray, toTwos, zeroPadBytes, zeroPadValue, assertArgument, } from '../utils/index.js';\nimport { toUtf8Bytes } from '../encoding/index.js';\nconst regexBytes = new RegExp('^bytes([0-9]+)$');\nconst regexNumber = new RegExp('^(u?int)([0-9]*)$');\nconst regexArray = new RegExp('^(.*)\\\\[([0-9]*)\\\\]$');\nfunction _pack(type, value, isArray) {\n switch (type) {\n case 'address':\n if (isArray) {\n return getBytes(zeroPadValue(value, 32));\n }\n return getBytes(getAddress(value));\n case 'string':\n return toUtf8Bytes(value);\n case 'bytes':\n return getBytes(value);\n case 'bool':\n value = value ? '0x01' : '0x00';\n if (isArray) {\n return getBytes(zeroPadValue(value, 32));\n }\n return getBytes(value);\n }\n let match = type.match(regexNumber);\n if (match) {\n const signed = match[1] === 'int';\n let size = parseInt(match[2] || '256');\n assertArgument((!match[2] || match[2] === String(size)) && size % 8 === 0 && size !== 0 && size <= 256, 'invalid number type', 'type', type);\n if (isArray) {\n size = 256;\n }\n if (signed) {\n value = toTwos(value, size);\n }\n return getBytes(zeroPadValue(toBeArray(value), size / 8));\n }\n match = type.match(regexBytes);\n if (match) {\n const size = parseInt(match[1]);\n assertArgument(String(size) === match[1] && size !== 0 && size <= 32, 'invalid bytes type', 'type', type);\n assertArgument(dataLength(value) === size, `invalid value for ${type}`, 'value', value);\n if (isArray) {\n return getBytes(zeroPadBytes(value, 32));\n }\n return value;\n }\n match = type.match(regexArray);\n if (match && Array.isArray(value)) {\n const baseType = match[1];\n const count = parseInt(match[2] || String(value.length));\n assertArgument(count === value.length, `invalid array length for ${type}`, 'value', value);\n const result = [];\n value.forEach(function (value) {\n result.push(_pack(baseType, value, true));\n });\n return getBytes(concat(result));\n }\n assertArgument(false, 'invalid type', 'type', type);\n}\n// @TODO: Array Enum\n/**\n * Computes the [Non-Standard Packed\n * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) representation of `values`\n * respectively to their `types`.\n *\n * @category Hash\n * @example\n *\n * ```ts\n * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72';\n * solidityPacked(['address', 'uint'], [addr, 45]);\n * ```\n *\n * @param {string[]} types - The types of the values.\n * @param {ReadonlyArray} values - The values to pack.\n * @returns {string} The packed values.\n */\nexport function solidityPacked(types, values) {\n assertArgument(types.length === values.length, 'wrong number of values; expected ${ types.length }', 'values', values);\n const tight = [];\n types.forEach(function (type, index) {\n tight.push(_pack(type, values[index]));\n });\n return hexlify(concat(tight));\n}\n/**\n * Computes the [Non-Standard Packed\n * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode)\n * [**keccak256**](../functions/keccak256) hash of `values` respectively to their `types`.\n *\n * @category Hash\n * @example\n *\n * ```ts\n * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72';\n * solidityPackedKeccak256(['address', 'uint'], [addr, 45]);\n * ```\n *\n * @param {ReadonlyArray} types - The types of the values.\n * @param {ReadonlyArray} values - The values to hash.\n * @returns {string} The hash of the packed values.\n */\nexport function solidityPackedKeccak256(types, values) {\n return _keccak256(solidityPacked(types, values));\n}\n/**\n * Computes the [Non-Standard Packed\n * Mode](https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#non-standard-packed-mode) [sha256](../functions/sha256)\n * hash of `values` respectively to their `types`.\n *\n * @category Hash\n * @example\n *\n * ```ts\n * addr = '0x8ba1f109551bd432803012645ac136ddd64dba72';\n * solidityPackedSha256(['address', 'uint'], [addr, 45]);\n * ```\n *\n * @param {ReadonlyArray} types - The types of the values.\n * @param {ReadonlyArray} values - The values to hash.\n * @returns {string} The hash of the packed values.\n */\nexport function solidityPackedSha256(types, values) {\n return _sha256(solidityPacked(types, values));\n}\n//# sourceMappingURL=solidity.js.map","//import { TypedDataDomain, TypedDataField } from \"@quaisproject/providerabstract-signer\";\nimport { getAddress } from '../address/index.js';\nimport { keccak256 } from '../crypto/index.js';\nimport { recoverAddress } from '../address/index.js';\nimport { concat, defineProperties, getBigInt, getBytes, hexlify, 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');\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 = ['name', 'version', 'chainId', 'verifyingContract', 'salt'];\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);\n // eslint-disable-next-line no-empty\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] || '256');\n assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && (match[2] == null || 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':\n return function (value) {\n return zeroPadValue(getAddress(value), 32);\n };\n case 'bool':\n return function (value) {\n return !value ? hexFalse : hexTrue;\n };\n case 'bytes':\n return function (value) {\n return keccak256(value);\n };\n case 'string':\n 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/**\n * A **TypedDataEncode** prepares and encodes [EIP-712](https://eips.ethereum.org/EIPS/eip-712) payloads for signed\n * typed data.\n *\n * This is useful for those that wish to compute various components of a typed data hash, primary types, or\n * sub-components, but generally the higher level [`Signer.signTypedData`](../classes/Signer#signTypedData) is more\n * useful.\n *\n * @category Hash\n */\nexport class TypedDataEncoder {\n /**\n * The primary type for the structured {@link types | **types**}.\n *\n * This is derived automatically from the {@link types | **types**}, since no recursion is possible, once the DAG for\n * the types is consturcted internally, the primary type must be the only remaining type with 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 do not violate the\n * [EIP-712](https://eips.ethereum.org/EIPS/eip-712) structural constraints as well as computes the\n * {@link primaryType | **primaryType**}.\n */\n constructor(types) {\n this.#types = JSON.stringify(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 Object.keys(types).forEach((type) => {\n links.set(type, new Set());\n parents.set(type, []);\n subtypes.set(type, new Set());\n });\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 = field.type.match(/^([^\\x5b]*)(\\x5b|$)/)[1] || null;\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 * @param {string} type - The type to get the encoder for.\n *\n * @returns {(value: any) => string} The encoder for the 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 match = type.match(/^(.*)(\\x5b(\\d*)\\x5d)$/);\n if (match) {\n const subtype = match[1];\n const subEncoder = this.getEncoder(subtype);\n return (value) => {\n assertArgument(!match[3] || parseInt(match[3]) === value.length, `array length mismatch; expected length ${parseInt(match[3])}`, '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 * @param {string} name - The name to get the full type for.\n *\n * @returns {string} The full type.\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 * @param {string} type - The type to encode the value for.\n * @param {any} value - The value to encode.\n *\n * @returns {string} The encoded value.\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 * @param {string} name - The name of the type.\n * @param {Record} value - The value to hash.\n *\n * @returns {string} The hash of the value.\n */\n hashStruct(name, value) {\n return keccak256(this.encodeData(name, value));\n }\n /**\n * Return the fulled encoded `value` for the {@link types | **types**}.\n *\n * @param {Record} value - The value to encode.\n *\n * @returns {string} The encoded value.\n */\n encode(value) {\n return this.encodeData(this.primaryType, value);\n }\n /**\n * Return the hash of the fully encoded `value` for the {@link types | **types**}.\n *\n * @param {Record} value - The value to hash.\n *\n * @returns {string} The hash of the value.\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 match = type.match(/^(.*)(\\x5b(\\d*)\\x5d)$/);\n if (match) {\n assertArgument(!match[3] || parseInt(match[3]) === value.length, `array length mismatch; expected length ${parseInt(match[3])}`, 'value', value);\n return value.map((v) => this._visit(match[1], 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 component within `value`.\n *\n * This is useful for replacing addresses or other transformation that may be desired on each component, based on\n * its type.\n *\n * @param {Record} value - The value to visit.\n * @param {(type: string, data: any) => any} callback - The callback to call for each value.\n *\n * @returns {any} The result of the callback.\n */\n visit(value, callback) {\n return this._visit(this.primaryType, value, callback);\n }\n /**\n * Create a new **TypedDataEncoder** for `types`.\n *\n * @param {Record} types - The types to encode.\n *\n * @returns {TypedDataEncoder} The encoder for the types.\n * @throws {Error} If the types are invalid.\n */\n static from(types) {\n return new TypedDataEncoder(types);\n }\n /**\n * Return the primary type for `types`.\n *\n * @param {Record} types - The types to get the primary type for.\n *\n * @returns {string} The primary type.\n * @throws {Error} If the types are invalid.\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 * @param {string} name - The name of the type.\n * @param {Record} types - The types to hash.\n * @param {Record} value - The value to hash.\n *\n * @returns {string} The hash of the value.\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 * @param {TypedDataDomain} domain - The domain to hash.\n *\n * @returns {string} The hash of the domain.\n * @throws {Error} If the domain is invalid.\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 [EIP-712](https://eips.ethereum.org/EIPS/eip-712) `value` for `types` with `domain`.\n *\n * @param {TypedDataDomain} domain - The domain to use.\n * @param {Record} types - The types to encode.\n * @param {Record} value - The value to encode.\n *\n * @returns {string} The encoded value.\n */\n static encode(domain, types, value) {\n return concat(['0x1901', TypedDataEncoder.hashDomain(domain), TypedDataEncoder.from(types).hash(value)]);\n }\n /**\n * Return the hash of the fully encoded [EIP-712](https://eips.ethereum.org/EIPS/eip-712) `value` for `types` with\n * `domain`.\n *\n * @param {TypedDataDomain} domain - The domain to use.\n * @param {Record} types - The types to hash.\n * @param {Record} value - The value to hash.\n *\n * @returns {string} The hash of the value.\n */\n static hash(domain, types, value) {\n return keccak256(TypedDataEncoder.encode(domain, types, value));\n }\n /**\n * Returns the JSON-encoded payload expected by nodes which implement the JSON-RPC\n * [EIP-712](https://eips.ethereum.org/EIPS/eip-712) method.\n *\n * @param {TypedDataDomain} domain - The domain to use.\n * @param {Record} types - The types to encode.\n * @param {Record} value - The value to encode.\n *\n * @returns {any} The JSON-encoded payload.\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 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 *\n * @category Hash\n * @param {TypedDataDomain} domain - The domain of the typed data.\n * @param {Record} types - The types of the typed data.\n * @param {Record} value - The value of the typed data.\n * @param {SignatureLike} signature - The signature to verify.\n *\n * @returns {string} The address that signed the typed data.\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 * - {@link FunctionFragment | Functions}\n * - {@link EventFragment | Events}\n * - {@link ConstructorFragment | Constructors}\n * - Custom {@link ErrorFragment | Errors}\n * - {@link FallbackFragment | Fallback or Recieve} functions\n *\n * @category Application Binary Interface\n */\nimport { defineProperties, getBigInt, getNumber, assert, assertPrivate, assertArgument } from '../utils/index.js';\nimport { id } from '../hash/index.js';\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';\nconst KwVisibDeploy = setify(_kwVisibDeploy.split(' '));\n// Visibility Keywords\nconst _kwVisib = 'constant external internal payable private public pure view';\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',\n ')': 'CLOSE_PAREN',\n '[': 'OPEN_BRACKET',\n ']': 'CLOSE_BRACKET',\n ',': 'COMMA',\n '@': '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]*))$');\n/**\n * Represents a parsed list of tokens.\n *\n * @category Application Binary Interface\n */\nclass TokenString {\n #offset;\n #tokens;\n get offset() {\n return this.#offset;\n }\n get length() {\n return this.#tokens.length - this.#offset;\n }\n constructor(tokens) {\n this.#offset = 0;\n this.#tokens = tokens.slice();\n }\n /**\n * Returns a clone of the current token string.\n *\n * @returns {TokenString} A cloned TokenString object.\n */\n clone() {\n return new TokenString(this.#tokens);\n }\n reset() {\n this.#offset = 0;\n }\n /**\n * @ignore\n */\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 throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`);\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 ``;\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 const brackets = [];\n const 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 = {\n depth: brackets.length,\n linkBack: -1,\n linkNext: -1,\n match: -1,\n type: '',\n text: '',\n offset,\n value: -1,\n };\n tokens.push(token);\n const 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 const 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 // eslint-disable-next-line no-constant-condition\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 const 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: ${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('_quais_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 {@link Fragment | **Fragment**} is an Array of {@link ParamType | **ParamType**}.\n *\n * @category Application Binary Interface\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)\"`, `\"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 * @ignore\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,\n type,\n baseType,\n indexed,\n components,\n arrayLength,\n 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 * @returns {string} The formatted type.\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 +=\n '(' + 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 * This provides a type guard ensuring that {@link arrayChildren | **arrayChildren**} and\n * {@link arrayLength | **arrayLength**} are non-null.\n *\n * @returns {boolean} True if this is an Array type.\n */\n isArray() {\n return this.baseType === 'array';\n }\n /**\n * This provides a type guard ensuring that {@link components | **components**} is non-null.\n *\n * @returns {boolean} True if this is a Tuple type.\n */\n isTuple() {\n return this.baseType === 'tuple';\n }\n /**\n * This provides a type guard ensuring that {@link indexed | **indexed**} is non-null.\n *\n * @returns {boolean} True if this is an Indexable type.\n */\n isIndexable() {\n return this.indexed != null;\n }\n /**\n * Walks the **ParamType** with `value`, calling `process` 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 // eslint-disable-next-line @typescript-eslint/no-this-alias\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 // eslint-disable-next-line @typescript-eslint/no-this-alias\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 /**\n * @ignore\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 () {\n setValue(await result);\n })());\n }\n else {\n setValue(result);\n }\n }\n /**\n * Walks the **ParamType** with `value`, asynchronously calling `process` on each type, destructing the `value`\n * recursively.\n *\n * This can be used to resolve ENS naes by walking and resolving each `\"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, 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 const 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 *\n * @category Application Binary Interface\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 * @ignore\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 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 // eslint-disable-next-line no-empty\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':\n return ConstructorFragment.from(obj);\n case 'error':\n return ErrorFragment.from(obj);\n case 'event':\n return EventFragment.from(obj);\n case 'fallback':\n case 'receive':\n return FallbackFragment.from(obj);\n case 'function':\n return FunctionFragment.from(obj);\n case 'struct':\n return StructFragment.from(obj);\n }\n }\n else if (typeof obj === 'object') {\n // JSON ABI\n switch (obj.type) {\n case 'constructor':\n return ConstructorFragment.from(obj);\n case 'error':\n return ErrorFragment.from(obj);\n case 'event':\n return EventFragment.from(obj);\n case 'fallback':\n case 'receive':\n return FallbackFragment.from(obj);\n case 'function':\n return FunctionFragment.from(obj);\n case 'struct':\n 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 {@link ConstructorFragment | **ConstructorFragment**}.\n */\n static isConstructor(value) {\n return ConstructorFragment.isFragment(value);\n }\n /**\n * Returns true if `value` is an {@link ErrorFragment | **ErrorFragment**}.\n */\n static isError(value) {\n return ErrorFragment.isFragment(value);\n }\n /**\n * Returns true if `value` is an {@link EventFragment | **EventFragment**}.\n */\n static isEvent(value) {\n return EventFragment.isFragment(value);\n }\n /**\n * Returns true if `value` is a {@link FunctionFragment | **FunctionFragment**}.\n */\n static isFunction(value) {\n return FunctionFragment.isFragment(value);\n }\n /**\n * Returns true if `value` is a {@link StructFragment | **StructFragment**}.\n */\n static isStruct(value) {\n return StructFragment.isFragment(value);\n }\n}\n/**\n * An abstract class to represent An individual fragment which has a name from a parse ABI.\n *\n * @category Application Binary Interface\n */\nexport class NamedFragment extends Fragment {\n /**\n * The name of the fragment.\n */\n name;\n /**\n * @ignore\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 *\n * @category Application Binary Interface\n */\nexport class ErrorFragment extends NamedFragment {\n /**\n * @ignore\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 **ErrorFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === ErrorFragmentInternal;\n }\n}\n/**\n * A Fragment which represents an Event.\n *\n * @category Application Binary Interface\n */\nexport class EventFragment extends NamedFragment {\n /**\n * Whether this event is anonymous.\n */\n anonymous;\n /**\n * @ignore\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 **EventFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === EventFragmentInternal;\n }\n}\n/**\n * A Fragment which represents a constructor.\n *\n * @category Application Binary Interface\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 * @ignore\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 **ConstructorFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === ConstructorFragmentInternal;\n }\n}\n/**\n * A Fragment which represents a method.\n *\n * @category Application Binary Interface\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 **FallbackFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === FallbackFragmentInternal;\n }\n}\n/**\n * A Fragment which represents a method.\n *\n * @category Application Binary Interface\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` 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 * @ignore\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 **FunctionFragment**.\n */\n static isFragment(value) {\n return value && value[internal] === FunctionFragmentInternal;\n }\n}\n/**\n * A Fragment which represents a structure.\n *\n * @category Application Binary Interface\n */\nexport class StructFragment extends NamedFragment {\n /**\n * @ignore\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 **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](../classes/Contract), the data is generally encoded\n * using the [ABI\n * Specification](https://docs.soliditylang.org/en/v0.8.19/abi-spec.html#formal-specification-of-the-encoding).\n *\n * The AbiCoder provides a utility to encode values to ABI data and decode values from ABI data.\n *\n * Most of the time, developers should favor the [Contract](../classes/Contract) class, which further abstracts the\n * finer details of ABI data.\n *\n * @category Application Binary Interface\n */\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,\n data,\n reason,\n transaction,\n invocation,\n revert,\n });\n}\n/**\n * The **AbiCoder** is a low-level class responsible for encoding JavaScript values into binary data and decoding binary\n * data into JavaScript values.\n *\n * @category Application Binary Interface\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 const 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 const 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. For example, a `uint` is by default `0` and `bool` is by default\n * `false`.\n *\n * @param {(string | ParamType)[]} types - Array of parameter types to get default values for.\n * @returns {Result} The default values corresponding to the given types.\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 specified types into ABI data.\n *\n * @param {(string | ParamType)[]} types - Array of parameter types.\n * @param {any[]} values - Array of values to encode.\n * @returns {string} The encoded data in hexadecimal format.\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 not enforced. Some older versions of Solidity incorrectly\n * padded event data emitted from `external` functions.\n *\n * @param {(string | ParamType)[]} types - Array of parameter types.\n * @param {BytesLike} data - The ABI data to decode.\n * @param {boolean} [loose=false] - Enable loose decoding. Default is `false`\n * @returns {Result} The decoded values.\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 /**\n * Set the default maximum inflation factor.\n *\n * @ignore\n * @param {number} value - The new inflation factor.\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 {@link AbiCoder | **AbiCoder**}.\n *\n * On the first call, the instance is created internally.\n *\n * @returns {AbiCoder} The default ABI coder instance.\n */\n static defaultAbiCoder() {\n if (defaultCoder == null) {\n defaultCoder = new AbiCoder();\n }\n return defaultCoder;\n }\n /**\n * Returns a quais-compatible {@link CallExceptionError | **CallExceptionError**} for the given result data.\n *\n * @param {CallExceptionAction} action - The action that triggered the exception.\n * @param {Object} tx - The transaction information.\n * @param {BytesLike | null} data - The data associated with the call exception.\n * @returns {CallExceptionError} The corresponding call exception error.\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 ABI and provides all the necessary functionality to encode\n * and decode paramaters to and results from methods, events and errors.\n *\n * It also provides several convenience methods to automatically search and find matching transactions and events to\n * parse them.\n *\n * @category Application Binary Interface\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 {@link Interface.parseLog | **Interface.parseLog**} to automatically match a Log to its event for\n * parsing, a **LogDescription** is returned.\n *\n * @category Application Binary Interface\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,\n name,\n signature,\n topic,\n args,\n });\n }\n}\n/**\n * When using the {@link Interface.parseTransaction | **Interface.parseTransaction**} to automatically match a\n * transaction data to its function for parsing, a **TransactionDescription** is returned.\n *\n * @category Application Binary Interface\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,\n name,\n args,\n signature,\n selector,\n value,\n });\n }\n}\n/**\n * When using the {@link Interface.parseError | **Interface.parseError**} to automatically match an error for a call\n * result for parsing, an **ErrorDescription** is returned.\n *\n * @category Application Binary Interface\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,\n name,\n args,\n signature,\n selector,\n });\n }\n}\n/**\n * An **Indexed** is used as a value when a value that does not fit within a topic (i.e. not a fixed-length, 32-byte\n * type). It is the `keccak256` of the value, and used for types such as arrays, tuples, bytes and strings.\n *\n * @category Application Binary Interface\n */\nexport class Indexed {\n /**\n * The `keccak256` of the value logged.\n */\n hash;\n /**\n * @ignore\n */\n _isIndexed;\n /**\n * Check if a value is an **Indexed** This provides a Type Guard for property access.\n *\n * @param value - The value to check.\n *\n * @returns `true` if the value is an **Indexed**.\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 encoding and decoding the data on the blockchain.\n *\n * An ABI provides information on how to encode data to send to a Contract, how to decode the results and events and how\n * to interpret revert errors.\n *\n * The ABI can be specified by {@link InterfaceAbi | any supported format}.\n *\n * @category Application Binary Interface\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;\n #abiCoder;\n /**\n * Create a new Interface for the fragments.\n *\n * @param {InterfaceAbi} fragments - The ABI 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 const frags = [];\n for (const a of abi) {\n try {\n frags.push(Fragment.from(a));\n }\n catch (error) {\n console.log('Error parsing ABI fragment', error);\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 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 bucket = this.#functions;\n break;\n case 'event':\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 signatures, optionally as `minimal` strings, which removes\n * 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 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 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, function name or function signature that\n * 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 function signature) is present in the ABI.\n *\n * In the case of a function name, the name may be ambiguous, so accessing the\n * {@link FunctionFragment | **FunctionFragment**} may require refinement.\n */\n hasFunction(key) {\n return !!this.#getFunction(key, null, false);\n }\n /**\n * Get the {@link FunctionFragment | **FunctionFragment**} for `key`, which may be a function selector, function name\n * or function signature that belongs to the ABI.\n *\n * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple functions match by\n * name.\n *\n * If the `key` and `values` do not refine to a single function in 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, 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 event signature) is present in the ABI.\n *\n * In the case of an event name, the name may be ambiguous, so accessing the\n * {@link EventFragment | **EventFragment**} may require refinement.\n */\n hasEvent(key) {\n return !!this.#getEvent(key, null, false);\n }\n /**\n * Get the {@link EventFragment | **EventFragment**} for `key`, which may be a topic hash, event name or event\n * signature that belongs to the ABI.\n *\n * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple events match by name.\n *\n * If the `key` and `values` do not refine to a single event in 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 {@link ErrorFragment | **ErroFragment**} for `key`, which may be an error selector, error name or error\n * signature that belongs to the ABI.\n *\n * If `values` is provided, it will use the Typed API to handle ambiguous cases where multiple errors match by name.\n *\n * If the `key` and `values` do not refine to a single error in the ABI, this will throw.\n */\n // TODO: `values` is not used, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 /**\n * @ignore\n */\n _decodeParams(params, data) {\n return this.#abiCoder.decode(params, data);\n }\n /**\n * @ignore\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 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 `quai_call`) for the specified error (see {@link getError | **getError**}\n * for valid values for `key`).\n *\n * Most developers should prefer the {@link parseCallResult | **parseCallResult**} method instead, which will\n * automatically detect a `CALL_EXCEPTION` and throw the 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 reverted from the the Contract with the sepcified\n * `error` (see {@link getError | **getError**} for valid values for `fragment`) with the `values`.\n *\n * This is generally not used by most developers, unless trying to mock 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([fragment.selector, this._encodeParams(fragment.inputs, values || [])]);\n }\n /**\n * Decodes the `data` from a transaction `tx.data` for the function specified (see\n * {@link getFunction | **getFunction**} for valid values for `fragment`).\n *\n * Most developers should prefer the {@link parseTransaction | **parseTransaction**} method instead, which will\n * 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 specified (see\n * {@link getFunction | **getFunction**} for valid values for `fragment`) with 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([fragment.selector, this._encodeParams(fragment.inputs, values || [])]);\n }\n /**\n * Decodes the result `data` (e.g. from an `quai_call`) for the specified function (see\n * {@link getFunction | **getFunction**} for valid values for `key`).\n *\n * Most developers should prefer the {@link parseCallResult | **parseCallResult**} method instead, which will\n * automatically detect a `CALL_EXCEPTION` and throw the 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,\n signature: ef.format(),\n 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 `quai_call`) for the specified function (see\n * {@link getFunction | **getFunction**} for valid values for `fragment`) with `values`.\n *\n * This is generally not used by most developers, unless trying to mock 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 // Create the filter for the event with search criteria (e.g. for quai_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 // TODO: `index` is not used, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n fragment.inputs.forEach((param, index) => {\n if (param.indexed) {\n if (param.type === 'string' ||\n param.type === 'bytes' ||\n param.baseType === 'tuple' ||\n 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 & { [ 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 the parameter values along with other useful\n * 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 // TODO: not implemented\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n parseCallResult(data) {\n throw new Error('@TODO');\n }\n /**\n * Parses a receipt log, finding the matching event and extracts the parameter values along with other useful event\n * 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 the parameter values along with other useful error\n * 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 {@link Interface | **Interface**} from the ABI `value`.\n *\n * The `value` may be provided as an existing {@link Interface | **Interface**} object, a JSON-encoded ABI or any\n * 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 // Maybe an interface from an older version, or from a symlinked copy\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 { validateAddress } from '../address/index.js';\nimport { getAddress } from '../address/index.js';\nimport { assertArgument, isHexString } from '../utils/index.js';\n/**\n * Converts an address and storage keys into an access set.\n *\n * @param {string} addr - The address to validate and convert.\n * @param {Array} storageKeys - The storage keys to validate and convert.\n * @returns {{ address: string; storageKeys: Array }} The access set.\n */\nfunction accessSetify(addr, storageKeys) {\n validateAddress(addr);\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 an {@link AccessList | **AccessList**} from any quasi-supported access-list structure.\n *\n * @category Transaction\n * @param {AccessListish} value - The value to convert to an access list.\n * @returns {AccessList} The access list.\n * @throws {Error} If the value is not a valid access list.\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 { keccak256, Signature } from '../crypto/index.js';\nimport { getBigInt, assert, assertArgument } from '../utils/index.js';\nimport { encodeProtoTransaction } from '../encoding/proto-encode.js';\n/**\n * An **AbstractTransaction** describes the common operations to be executed on Quai and Qi ledgers by an Externally\n * Owned Account (EOA). This class must be subclassed by concrete implementations of transactions on each ledger.\n */\nexport class AbstractTransaction {\n _type;\n _signature;\n _chainId;\n /**\n * The transaction type.\n *\n * If null, the type will be automatically inferred based on explicit properties.\n */\n get type() {\n return this._type;\n }\n set type(value) {\n switch (value) {\n case null:\n this._type = null;\n break;\n case 0:\n case 'standard':\n this._type = 0;\n break;\n case 2:\n case 'utxo':\n this._type = 2;\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:\n return 'standard';\n case 1:\n return 'external';\n case 2:\n return 'utxo';\n }\n return null;\n }\n /**\n * The chain ID this transaction is valid on.\n */\n get chainId() {\n return this._chainId;\n }\n set chainId(value) {\n this._chainId = getBigInt(value);\n }\n /**\n * If signed, the signature for this transaction.\n */\n get signature() {\n return (this._signature || null);\n }\n set signature(value) {\n if (typeof value === 'string') {\n this._signature = value;\n }\n else {\n this._signature = (value == null ? null : Signature.from(value));\n }\n }\n /**\n * Creates a new Transaction with default values.\n */\n constructor() {\n this._type = null;\n this._chainId = BigInt(0);\n this._signature = null;\n }\n /**\n * The pre-image hash of this transaction.\n *\n * This is the digest that a [Signer](../interfaces/Signer) must sign to authorize this transaction.\n */\n get digest() {\n return keccak256(this.unsignedSerialized);\n }\n /**\n * Returns true if signed.\n *\n * This provides a Type Guard that properties requiring a signed transaction are non-null.\n *\n * @returns {boolean} Indicates if the transaction is signed.\n */\n isSigned() {\n return this.signature != null;\n }\n /**\n * The serialized transaction.\n *\n * This throws if the transaction is unsigned. For the pre-image, use\n * {@link AbstractTransaction.unsignedSerialized | **unsignedSerialized** }.\n */\n get serialized() {\n assert(this.signature != null, 'cannot serialize unsigned transaction; maybe you meant .unsignedSerialized', 'UNSUPPORTED_OPERATION', { operation: '.serialized' });\n return encodeProtoTransaction(this.toProtobuf(true));\n }\n /**\n * The transaction pre-image.\n *\n * The hash of this is the digest which needs to be signed to authorize this transaction.\n */\n get unsignedSerialized() {\n return encodeProtoTransaction(this.toProtobuf(false));\n }\n /**\n * Return the most \"likely\" type; currently the highest supported transaction type.\n *\n * @returns {number} The inferred transaction type.\n */\n inferType() {\n return this.inferTypes().pop();\n }\n /**\n * Check if the transaction is external.\n *\n * @returns {boolean} True if the transaction is external.\n */\n get isExternal() {\n return this.destZone !== undefined && this.originZone !== this.destZone;\n }\n}\n//# sourceMappingURL=abstract-transaction.js.map","import { validateAddress } from '../address/index.js';\nimport { getBigInt } from '../utils/index.js';\n/**\n * List of supported Qi denominations.\n *\n * @category Transaction\n */\nexport const denominations = [\n BigInt(1),\n BigInt(5),\n BigInt(10),\n BigInt(50),\n BigInt(100),\n BigInt(250),\n BigInt(500),\n BigInt(1000),\n BigInt(5000),\n BigInt(10000),\n BigInt(20000),\n BigInt(50000),\n BigInt(100000),\n BigInt(1000000),\n BigInt(10000000),\n BigInt(100000000),\n BigInt(1000000000), // 1000000 Qi\n];\n/**\n * Checks if the provided denomination is valid.\n *\n * @category Transaction\n * @param {bigint} denomination - The denomination to check.\n * @returns {boolean} True if the denomination is valid, false otherwise.\n */\nfunction isValidDenomination(denomination) {\n return denominations.includes(denomination);\n}\n/**\n * Handles conversion of string to bigint, specifically for transaction parameters.\n *\n * @ignore\n * @category Transaction\n * @param {string} value - The value to convert.\n * @param {string} param - The parameter name.\n * @returns {bigint} The converted value.\n */\nfunction handleBigInt(value, param) {\n if (value === '0x') {\n return BigInt(0);\n }\n return getBigInt(value, param);\n}\n/**\n * Given a value, returns an array of supported denominations that sum to the value.\n *\n * @category Transaction\n * @param {bigint} value - The value to denominate.\n * @returns {bigint[]} An array of denominations that sum to the value.\n * @throws {Error} If the value is less than or equal to 0 or cannot be matched with available denominations.\n */\nexport function denominate(value) {\n if (value <= BigInt(0)) {\n throw new Error('Value must be greater than 0');\n }\n const result = [];\n let remainingValue = value;\n // Iterate through denominations in descending order\n for (let i = denominations.length - 1; i >= 0; i--) {\n const denomination = denominations[i];\n // Add the denomination to the result array as many times as possible\n while (remainingValue >= denomination) {\n result.push(denomination);\n remainingValue -= denomination;\n }\n }\n if (remainingValue > 0) {\n throw new Error('Unable to match the value with available denominations');\n }\n return result;\n}\n/**\n * Represents a UTXO (Unspent Transaction Output).\n *\n * @category Transaction\n * @implements {UTXOLike}\n */\nexport class UTXO {\n #txhash;\n #index;\n #address;\n #denomination;\n /**\n * Gets the transaction hash.\n *\n * @returns {null | string} The transaction hash.\n */\n get txhash() {\n return this.#txhash;\n }\n /**\n * Sets the transaction hash.\n *\n * @param {null | string} value - The transaction hash.\n */\n set txhash(value) {\n this.#txhash = value;\n }\n /**\n * Gets the index.\n *\n * @returns {null | number} The index.\n */\n get index() {\n return this.#index;\n }\n /**\n * Sets the index.\n *\n * @param {null | number} value - The index.\n */\n set index(value) {\n this.#index = value;\n }\n /**\n * Gets the address.\n *\n * @returns {string} The address.\n */\n get address() {\n return this.#address || '';\n }\n /**\n * Sets the address.\n *\n * @param {string} value - The address.\n * @throws {Error} If the address is invalid.\n */\n set address(value) {\n validateAddress(value);\n this.#address = value;\n }\n /**\n * Gets the denomination.\n *\n * @returns {null | bigint} The denomination.\n */\n get denomination() {\n return this.#denomination;\n }\n /**\n * Sets the denomination.\n *\n * @param {null | BigNumberish} value - The denomination.\n * @throws {Error} If the denomination value is invalid.\n */\n set denomination(value) {\n if (value == null) {\n this.#denomination = null;\n return;\n }\n const denominationBigInt = handleBigInt(value.toString(), 'denomination');\n if (!isValidDenomination(denominationBigInt)) {\n throw new Error('Invalid denomination value');\n }\n this.#denomination = denominationBigInt;\n }\n /**\n * Constructs a new UTXO instance with null properties.\n */\n constructor() {\n this.#txhash = null;\n this.#index = null;\n this.#address = null;\n this.#denomination = null;\n }\n /**\n * Converts the UTXO instance to a JSON object.\n *\n * @returns {any} A JSON representation of the UTXO instance.\n */\n toJSON() {\n return {\n txhash: this.txhash,\n index: this.index,\n address: this.address,\n denomination: this.denomination,\n };\n }\n /**\n * Creates a UTXO instance from a UTXOLike object.\n *\n * @param {UTXOLike} utxo - The UTXOLike object to convert.\n * @returns {UTXO} The UTXO instance.\n */\n static from(utxo) {\n if (utxo === null) {\n return new UTXO();\n }\n const result = utxo instanceof UTXO ? utxo : new UTXO();\n if (utxo.txhash != null) {\n result.txhash = utxo.txhash;\n }\n if (utxo.index != null) {\n result.index = utxo.index;\n }\n if (utxo.address != null && utxo.address !== '') {\n result.address = utxo.address;\n }\n if (utxo.denomination != null) {\n result.denomination = utxo.denomination;\n }\n return result;\n }\n}\n//# sourceMappingURL=utxo.js.map","import { UTXO } from './utxo.js';\n/**\n * An **AbstractCoinSelector** provides a base class for other sub-classes to implement the functionality for selecting\n * UTXOs for a spend and to properly handle spend and change outputs.\n *\n * This class is abstract and should not be used directly. Sub-classes should implement the\n * {@link AbstractCoinSelector#performSelection | **performSelection**} method to provide the actual coin selection\n * logic.\n *\n * @category Transaction\n * @abstract\n */\nexport class AbstractCoinSelector {\n #availableUXTOs;\n #spendOutputs;\n #changeOutputs;\n /**\n * Gets the available UTXOs.\n * @returns {UTXO[]} The available UTXOs.\n */\n get availableUXTOs() {\n return this.#availableUXTOs;\n }\n /**\n * Sets the available UTXOs.\n * @param {UTXOLike[]} value - The UTXOs to set.\n */\n set availableUXTOs(value) {\n this.#availableUXTOs = value.map((val) => {\n const utxo = UTXO.from(val);\n this._validateUTXO(utxo);\n return utxo;\n });\n }\n /**\n * Gets the spend outputs.\n * @returns {UTXO[]} The spend outputs.\n */\n get spendOutputs() {\n return this.#spendOutputs;\n }\n /**\n * Sets the spend outputs.\n * @param {UTXOLike[]} value - The spend outputs to set.\n */\n set spendOutputs(value) {\n this.#spendOutputs = value.map((utxo) => UTXO.from(utxo));\n }\n /**\n * Gets the change outputs.\n * @returns {UTXO[]} The change outputs.\n */\n get changeOutputs() {\n return this.#changeOutputs;\n }\n /**\n * Sets the change outputs.\n * @param {UTXOLike[]} value - The change outputs to set.\n */\n set changeOutputs(value) {\n this.#changeOutputs = value.map((utxo) => UTXO.from(utxo));\n }\n /**\n * Constructs a new AbstractCoinSelector instance with an empty UTXO array.\n * @param {UTXOEntry[]} [availableUXTOs=[]] - The initial available UTXOs.\n */\n constructor(availableUXTOs = []) {\n this.#availableUXTOs = availableUXTOs.map((val) => {\n const utxo = UTXO.from(val);\n this._validateUTXO(utxo);\n return utxo;\n });\n this.#spendOutputs = [];\n this.#changeOutputs = [];\n }\n /**\n * Validates the provided UTXO instance. In order to be valid for coin selection, the UTXO must have a valid address\n * and denomination.\n *\n * @param {UTXO} utxo - The UTXO to validate.\n * @throws {Error} If the UTXO is invalid.\n * @protected\n */\n _validateUTXO(utxo) {\n if (utxo.address == null) {\n throw new Error('UTXO address is required');\n }\n if (utxo.denomination == null) {\n throw new Error('UTXO denomination is required');\n }\n }\n}\n//# sourceMappingURL=abstract-coinselector.js.map","import { bigIntAbs } from '../utils/maths.js';\nimport { AbstractCoinSelector } from './abstract-coinselector.js';\nimport { UTXO, denominate } from './utxo.js';\n/**\n * The FewestCoinSelector class provides a coin selection algorithm that selects the fewest UTXOs required to meet the\n * target amount. This algorithm is useful for minimizing the size of the transaction and the fees associated with it.\n *\n * This class is a sub-class of {@link AbstractCoinSelector | **AbstractCoinSelector** } and implements the\n * {@link AbstractCoinSelector.performSelection | **performSelection** } method to provide the actual coin selection\n * logic.\n *\n * @category Transaction\n */\nexport class FewestCoinSelector extends AbstractCoinSelector {\n /**\n * The largest first coin selection algorithm.\n *\n * This algorithm selects the largest UTXOs first, and continues to select UTXOs until the target amount is reached.\n * If the total value of the selected UTXOs is greater than the target amount, the remaining value is returned as a\n * change output.\n *\n * @param {SpendTarget} target - The target amount to spend.\n *\n * @returns {SelectedCoinsResult} The selected UTXOs and change outputs.\n */\n performSelection(target) {\n this.validateTarget(target);\n this.validateUTXOs();\n const sortedUTXOs = this.sortUTXOsByDenomination(this.availableUXTOs, 'desc');\n let totalValue = BigInt(0);\n let selectedUTXOs = [];\n // Get UTXOs that meets or exceeds the target value\n const UTXOsEqualOrGreaterThanTarget = sortedUTXOs.filter((utxo) => utxo.denomination && utxo.denomination >= target.value);\n if (UTXOsEqualOrGreaterThanTarget.length > 0) {\n // Find the smallest UTXO that meets or exceeds the target value\n const optimalUTXO = UTXOsEqualOrGreaterThanTarget.reduce((minDenominationUTXO, currentUTXO) => {\n if (!currentUTXO.denomination)\n return minDenominationUTXO;\n return currentUTXO.denomination < minDenominationUTXO.denomination ? currentUTXO : minDenominationUTXO;\n }, UTXOsEqualOrGreaterThanTarget[0]); // Initialize with the first UTXO in the list\n selectedUTXOs.push(optimalUTXO);\n totalValue += optimalUTXO.denomination;\n }\n else {\n // If no single UTXO meets or exceeds the target, aggregate smaller denominations\n // until the target is met/exceeded or there are no more UTXOs to aggregate\n while (sortedUTXOs.length > 0 && totalValue < target.value) {\n const nextOptimalUTXO = sortedUTXOs.reduce((closest, utxo) => {\n if (!utxo.denomination)\n return closest;\n // Prioritize UTXOs that bring totalValue closer to target.value\n const absThisDiff = bigIntAbs(target.value - (totalValue + utxo.denomination));\n const currentClosestDiff = closest && closest.denomination\n ? bigIntAbs(target.value - (totalValue + closest.denomination))\n : BigInt(Infinity);\n return absThisDiff < currentClosestDiff ? utxo : closest;\n }, sortedUTXOs[0]);\n // Add the selected UTXO to the selection and update totalValue\n selectedUTXOs.push(nextOptimalUTXO);\n totalValue += nextOptimalUTXO.denomination;\n // Remove the selected UTXO from the list of available UTXOs\n const index = sortedUTXOs.findIndex((utxo) => utxo.denomination === nextOptimalUTXO.denomination && utxo.address === nextOptimalUTXO.address);\n sortedUTXOs.splice(index, 1);\n }\n }\n // Check if the selected UTXOs meet or exceed the target amount\n if (totalValue < target.value) {\n throw new Error('Insufficient funds');\n }\n // Check if any denominations can be removed from the input set and it still remain valid\n selectedUTXOs = this.sortUTXOsByDenomination(selectedUTXOs, 'asc');\n let runningTotal = totalValue;\n let lastRemovableIndex = -1; // Index of the last UTXO that can be removed\n // Iterate through selectedUTXOs to find the last removable UTXO\n for (let i = 0; i < selectedUTXOs.length; i++) {\n const utxo = selectedUTXOs[i];\n if (utxo.denomination) {\n if (runningTotal - utxo.denomination >= target.value) {\n runningTotal -= utxo.denomination;\n lastRemovableIndex = i;\n }\n else {\n // Once a UTXO makes the total less than target.value, stop the loop\n break;\n }\n }\n }\n if (lastRemovableIndex >= 0) {\n totalValue -= selectedUTXOs[lastRemovableIndex].denomination;\n selectedUTXOs.splice(lastRemovableIndex, 1);\n }\n // Break down the total spend into properly denominatated UTXOs\n const spendDenominations = denominate(target.value);\n this.spendOutputs = spendDenominations.map((denomination) => {\n const utxo = new UTXO();\n utxo.denomination = denomination;\n utxo.address = target.address;\n return utxo;\n });\n // Calculate change to be returned\n const change = totalValue - target.value;\n // If there's change, break it down into properly denominatated UTXOs\n if (change > BigInt(0)) {\n const changeDenominations = denominate(change);\n this.changeOutputs = changeDenominations.map((denomination) => {\n const utxo = new UTXO();\n utxo.denomination = denomination;\n // We do not have access to change addresses here so leave it null\n return utxo;\n });\n }\n else {\n this.changeOutputs = [];\n }\n return {\n inputs: selectedUTXOs,\n spendOutputs: this.spendOutputs,\n changeOutputs: this.changeOutputs,\n };\n }\n /**\n * Sorts UTXOs by their denomination.\n *\n * @param {UTXO[]} utxos - The UTXOs to sort.\n * @param {'asc' | 'desc'} direction - The direction to sort ('asc' for ascending, 'desc' for descending).\n * @returns {UTXO[]} The sorted UTXOs.\n */\n sortUTXOsByDenomination(utxos, direction) {\n if (direction === 'asc') {\n return [...utxos].sort((a, b) => {\n const diff = (a.denomination ?? BigInt(0)) - (b.denomination ?? BigInt(0));\n return diff > 0 ? 1 : diff < 0 ? -1 : 0;\n });\n }\n return [...utxos].sort((a, b) => {\n const diff = (b.denomination ?? BigInt(0)) - (a.denomination ?? BigInt(0));\n return diff > 0 ? 1 : diff < 0 ? -1 : 0;\n });\n }\n /**\n * Validates the target amount.\n *\n * @param {SpendTarget} target - The target amount to validate.\n * @throws Will throw an error if the target amount is less than or equal to 0.\n */\n validateTarget(target) {\n if (target.value <= BigInt(0)) {\n throw new Error('Target amount must be greater than 0');\n }\n }\n /**\n * Validates the available UTXOs.\n *\n * @throws Will throw an error if there are no available UTXOs.\n */\n validateUTXOs() {\n if (this.availableUXTOs.length === 0) {\n throw new Error('No UTXOs available');\n }\n }\n}\n//# sourceMappingURL=coinselector-fewest.js.map","/**\n * @ignore\n */\nimport { getAddress } from '../address/index.js';\nimport { Signature } from '../crypto/index.js';\nimport { accessListify } from '../transaction/index.js';\nimport { hexlify } from '../utils/data.js';\nimport { getBigInt, getNumber, isHexString, zeroPadValue, assert, assertArgument, toBeArray, } 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) {\n return (array) => {\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), '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}\nexport function handleNumber(_value, param) {\n if (_value === '0x') {\n return 0;\n }\n return getNumber(_value, param);\n}\nexport function 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}\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 _formatHeader = object({\n baseFeePerGas: getBigInt,\n efficiencyScore: getBigInt,\n etxEligibleSlices: formatHash,\n etxSetRoot: formatHash,\n evmRoot: formatHash,\n expansionNumber: getNumber,\n extRollupRoot: formatHash,\n extTransactionsRoot: formatHash,\n extraData: formatData,\n gasLimit: getBigInt,\n gasUsed: getBigInt,\n hash: formatHash,\n interlinkRootHash: formatHash,\n manifestHash: arrayOf(formatHash),\n number: arrayOf(getNumber),\n parentDeltaS: arrayOf(getBigInt),\n parentEntropy: arrayOf(getBigInt),\n parentHash: arrayOf(formatHash),\n parentUncledS: arrayOf(allowNull(getBigInt)),\n parentUncledSubDeltaS: arrayOf(getBigInt),\n primeTerminus: formatHash,\n receiptsRoot: formatHash,\n sha3Uncles: formatHash,\n size: getBigInt,\n thresholdCount: getBigInt,\n transactionsRoot: formatHash,\n uncledS: getBigInt,\n utxoRoot: formatHash,\n});\nconst _formatUncle = object({\n coinbase: allowNull(getAddress),\n difficulty: getBigInt,\n headerHash: formatHash,\n location: formatData,\n mixHash: formatHash,\n nonce: formatData,\n number: getNumber,\n parentHash: formatHash,\n primeTerminusNumber: getNumber,\n time: getBigInt,\n txHash: formatHash,\n workShare: formatBoolean,\n});\nconst _formatWoHeader = object({\n coinbase: getAddress,\n difficulty: getNumber,\n headerHash: formatHash,\n location: formatData,\n mixHash: formatHash,\n nonce: formatData,\n number: getNumber,\n parentHash: formatHash,\n primeTerminusNumber: getNumber,\n time: formatData,\n txHash: formatHash,\n});\nconst _formatBlock = object({\n extTransactions: arrayOf((tx) => {\n if (typeof tx === 'string') {\n return formatHash(tx);\n }\n return formatExternalTransactionResponse(tx);\n }),\n hash: formatHash,\n header: _formatHeader,\n interlinkHashes: arrayOf(formatHash),\n order: getNumber,\n size: getBigInt,\n subManifest: arrayOf(formatData),\n totalEntropy: getBigInt,\n transactions: arrayOf((tx) => {\n if (typeof tx === 'string') {\n return formatHash(tx);\n }\n return formatTransactionResponse(tx);\n }),\n uncles: allowNull(arrayOf(_formatUncle), []),\n woHeader: _formatWoHeader,\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 if ('originatingTxHash' in tx) {\n return formatExternalTransactionResponse(tx);\n }\n return formatTransactionResponse(tx);\n });\n result.extTransactions = value.extTransactions.map((tx) => {\n if (typeof tx === 'string') {\n return tx;\n }\n return formatExternalTransactionResponse(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 _formatEtx = object({\n type: allowNull(getNumber, 0),\n nonce: allowNull(getNumber),\n gasPrice: allowNull(getBigInt),\n maxPriorityFeePerGas: allowNull(getBigInt),\n maxFeePerGas: allowNull(getBigInt),\n gas: allowNull(getBigInt),\n value: allowNull(getBigInt, BN_0),\n input: allowNull(formatData),\n to: allowNull(getAddress, null),\n accessList: allowNull(accessListify, null),\n isCoinbase: allowNull(getNumber, 0),\n sender: getAddress,\n originatingTxHash: formatHash,\n etxIndex: getNumber,\n chainId: allowNull(getBigInt, null),\n hash: formatHash,\n}, {\n from: ['sender'],\n});\nexport function formatEtx(value) {\n return _formatEtx(value);\n}\nconst _formatTransactionReceipt = object({\n to: allowNull(getAddress, null),\n from: allowNull(getAddress, null),\n contractAddress: allowNull(getAddress, null),\n index: getNumber,\n gasUsed: getBigInt,\n logsBloom: allowNull(formatData),\n blockHash: formatHash,\n hash: formatHash,\n logs: arrayOf(formatReceiptLog),\n blockNumber: getNumber,\n cumulativeGasUsed: getBigInt,\n effectiveGasPrice: allowNull(getBigInt),\n status: allowNull(getNumber),\n type: allowNull(getNumber, 0),\n etxs: (value) => (value === null ? [] : arrayOf(formatEtx)(value)),\n}, {\n hash: ['transactionHash'],\n index: ['transactionIndex'],\n});\nexport function formatTransactionReceipt(value) {\n const result = _formatTransactionReceipt(value);\n return result;\n}\nexport function formatExternalTransactionResponse(value) {\n const result = object({\n hash: formatHash,\n type: (value) => {\n if (value === '0x' || value == null) {\n return 0;\n }\n return parseInt(value, 16);\n },\n accessList: allowNull(accessListify, null),\n blockHash: allowNull(formatHash, null),\n blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null),\n index: allowNull((value) => (value ? BigInt(value) : null), null),\n from: allowNull(getAddress, null),\n sender: allowNull(getAddress, null),\n maxPriorityFeePerGas: allowNull((value) => (value ? BigInt(value) : null)),\n maxFeePerGas: allowNull((value) => (value ? BigInt(value) : null)),\n gasLimit: allowNull((value) => (value ? BigInt(value) : null), null),\n to: allowNull(getAddress, null),\n value: allowNull((value) => (value ? BigInt(value) : null), null),\n nonce: allowNull((value) => (value ? parseInt(value, 10) : null), null),\n creates: allowNull(getAddress, null),\n chainId: allowNull((value) => (value ? BigInt(value) : null), null),\n isCoinbase: allowNull((value) => (value ? parseInt(value, 10) : null), null),\n originatingTxHash: allowNull(formatHash, null),\n etxIndex: allowNull((value) => (value ? parseInt(value, 10) : null), null),\n etxType: allowNull((value) => value, null),\n data: (value) => value,\n }, {\n data: ['input'],\n gasLimit: ['gas'],\n index: ['transactionIndex'],\n })(value);\n // 0x0000... should actually be null\n if (result.blockHash && getBigInt(result.blockHash) === BN_0) {\n result.blockHash = null;\n }\n return result;\n}\nexport function formatTransactionResponse(value) {\n // Determine if it is a Quai or Qi transaction based on the type\n const transactionType = parseInt(value.type, 16);\n let result;\n if (transactionType === 0x0 || transactionType === 0x1) {\n // QuaiTransactionResponseParams\n result = object({\n hash: formatHash,\n type: (value) => {\n if (value === '0x' || value == null) {\n return 0;\n }\n return parseInt(value, 16);\n },\n accessList: allowNull(accessListify, null),\n blockHash: allowNull(formatHash, null),\n blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null),\n index: allowNull((value) => (value ? BigInt(value) : null), null),\n from: allowNull(getAddress, null),\n sender: allowNull(getAddress, null),\n maxPriorityFeePerGas: allowNull((value) => (value ? BigInt(value) : null)),\n maxFeePerGas: allowNull((value) => (value ? BigInt(value) : null)),\n gasLimit: allowNull((value) => (value ? BigInt(value) : null), null),\n to: allowNull(getAddress, null),\n value: allowNull((value) => (value ? BigInt(value) : null), null),\n nonce: allowNull((value) => (value ? parseInt(value, 10) : null), null),\n creates: allowNull(getAddress, null),\n chainId: allowNull((value) => (value ? BigInt(value) : null), null),\n etxType: allowNull((value) => value, null),\n data: (value) => value,\n }, {\n data: ['input'],\n gasLimit: ['gas'],\n index: ['transactionIndex'],\n })(value);\n // Add an access list to supported transaction types\n if ((value.type === 0 || 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 // 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 }\n // 0x0000... should actually be null\n if (result.blockHash && getBigInt(result.blockHash) === BN_0) {\n result.blockHash = null;\n }\n }\n else if (transactionType === 0x2) {\n // QiTransactionResponseParams\n result = object({\n hash: formatHash,\n type: (value) => {\n if (value === '0x' || value == null) {\n return 0;\n }\n return parseInt(value, 16);\n },\n blockHash: allowNull(formatHash, null),\n blockNumber: allowNull((value) => (value ? parseInt(value, 16) : null), null),\n index: allowNull((value) => (value ? BigInt(value) : null), null),\n chainId: allowNull((value) => (value ? BigInt(value) : null), null),\n signature: (value) => value,\n txInputs: allowNull((value) => value.map(_formatTxInput), null),\n txOutputs: allowNull((value) => value.map(_formatTxOutput), null),\n }, {\n index: ['transactionIndex'],\n signature: ['utxoSignature'],\n txInputs: ['inputs'],\n txOutputs: ['outputs'],\n })(value);\n }\n else {\n throw new Error('Unknown transaction type');\n }\n return result;\n}\nconst _formatTxInput = object({\n txhash: formatTxHash,\n index: formatIndex,\n pubkey: hexlify,\n}, {\n txhash: ['PreviousOutPoint', 'TxHash'],\n index: ['PreviousOutPoint', 'Index'],\n pubkey: ['PubKey'],\n});\nfunction extractTxHash(value) {\n if (value && value.TxHash) {\n return value.TxHash;\n }\n throw new Error('Invalid PreviousOutPoint');\n}\nfunction formatTxHash(value) {\n return formatHash(extractTxHash(value));\n}\nfunction extractIndex(value) {\n if (value && value.Index !== undefined) {\n return value.Index;\n }\n throw new Error('Invalid PreviousOutPoint');\n}\nfunction formatIndex(value) {\n return getNumber(extractIndex(value));\n}\nconst _formatTxOutput = object({\n address: (addr) => hexlify(getAddress(addr)),\n denomination: getNumber,\n});\n//# sourceMappingURL=format.js.map","import { keccak256 } from '../crypto/index.js';\nimport { AbstractTransaction } from './index.js';\nimport { assertArgument, getBytes, getZoneForAddress, hexlify, toBigInt } from '../utils/index.js';\nimport { decodeProtoTransaction } from '../encoding/index.js';\nimport { formatNumber } from '../providers/format.js';\nimport { computeAddress, isQiAddress } from '../address/index.js';\n/**\n * Class representing a QiTransaction.\n *\n * @category Transaction\n * @extends {AbstractTransaction}\n * @implements {QiTransactionLike}\n */\nexport class QiTransaction extends AbstractTransaction {\n #txInputs;\n #txOutputs;\n /**\n * Get transaction inputs.\n *\n * @returns {TxInput[]} The transaction inputs.\n */\n get txInputs() {\n return (this.#txInputs ?? []).map((entry) => ({ ...entry }));\n }\n /**\n * Set transaction inputs.\n *\n * @param {TxInput[] | null} value - The transaction inputs.\n * @throws {Error} If the value is not an array.\n */\n set txInputs(value) {\n if (!Array.isArray(value)) {\n throw new Error('txInputs must be an array');\n }\n this.#txInputs = value.map((entry) => ({ ...entry }));\n }\n /**\n * Get transaction outputs.\n *\n * @returns {TxOutput[]} The transaction outputs.\n */\n get txOutputs() {\n return (this.#txOutputs ?? []).map((output) => ({ ...output }));\n }\n /**\n * Set transaction outputs.\n *\n * @param {TxOutput[] | null} value - The transaction outputs.\n * @throws {Error} If the value is not an array.\n */\n set txOutputs(value) {\n if (!Array.isArray(value)) {\n throw new Error('txOutputs must be an array');\n }\n this.#txOutputs = value.map((output) => ({ ...output }));\n }\n /**\n * Get the permuted hash of the transaction as specified by QIP-0010.\n *\n * @returns {string | null} The transaction hash.\n * @throws {Error} If the transaction has no inputs or outputs, or if cross-zone & cross-ledger transactions are not\n * supported.\n * @see {@link [QIP0010](https://github.com/quai-network/qips/blob/master/qip-0010.md)}\n */\n get hash() {\n if (this.signature == null) {\n return null;\n }\n if (this.txInputs.length < 1 || this.txOutputs.length < 1) {\n throw new Error('Transaction must have at least one input and one output');\n }\n const senderAddr = computeAddress(this.txInputs[0].pubkey || '');\n if (!this.destZone || !this.originZone) {\n throw new Error(`Invalid zones: origin ${this.originZone} -> destination ${this.destZone} (address: ${senderAddr})`);\n }\n const isSameLedger = isQiAddress(senderAddr) === isQiAddress(hexlify(this.txOutputs[0].address) || '');\n if (this.isExternal && !isSameLedger) {\n throw new Error('Cross-zone & cross-ledger transactions are not supported');\n }\n const hexString = this.serialized.startsWith('0x') ? this.serialized.substring(2) : this.serialized;\n const dataBuffer = Buffer.from(hexString, 'hex');\n const hashHex = keccak256(dataBuffer);\n const hashBuffer = Buffer.from(hashHex.substring(2), 'hex');\n const origin = this.originZone ? parseInt(this.originZone.slice(2), 16) : 0;\n hashBuffer[0] = origin;\n hashBuffer[1] |= 0x80;\n hashBuffer[2] = origin;\n hashBuffer[3] |= 0x80;\n return '0x' + hashBuffer.toString('hex');\n }\n /**\n * Get the zone of the sender address.\n *\n * @returns {Zone | undefined} The origin zone.\n */\n get originZone() {\n const senderAddr = computeAddress(this.txInputs[0].pubkey || '');\n const zone = getZoneForAddress(senderAddr);\n return zone ?? undefined;\n }\n /**\n * Get the zone of the recipient address.\n *\n * @returns {Zone | undefined} The destination zone.\n */\n get destZone() {\n const zone = getZoneForAddress(this.txOutputs[0].address);\n return zone ?? undefined;\n }\n /**\n * Creates a new Transaction with default values.\n */\n constructor() {\n super();\n this.#txInputs = [];\n this.#txOutputs = [];\n }\n /**\n * Validates the explicit properties and returns a list of compatible transaction types.\n *\n * @returns {number[]} The compatible transaction types.\n */\n inferTypes() {\n const types = [];\n // Explicit type\n if (this.type != null) {\n types.push(this.type);\n }\n else {\n types.push(2);\n }\n types.sort();\n return types;\n }\n /**\n * Create a copy of this transaction.\n *\n * @returns {QiTransaction} The cloned transaction.\n */\n clone() {\n return QiTransaction.from(this);\n }\n /**\n * Return a JSON-friendly object.\n *\n * @returns {QiTransactionLike} The 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 chainId: s(this.chainId),\n signature: this.signature ? this.signature : null,\n hash: this.hash,\n txInputs: this.txInputs,\n txOutputs: this.txOutputs,\n };\n }\n /**\n * Return a protobuf-friendly JSON object.\n *\n * @param {boolean} [includeSignature=true] - Whether to include the signature. Default is `true`\n * @returns {ProtoTransaction} The protobuf-friendly JSON object.\n */\n toProtobuf(includeSignature = true) {\n const protoTx = {\n type: this.type || 2,\n chain_id: formatNumber(this.chainId || 0, 'chainId'),\n tx_ins: {\n tx_ins: this.txInputs.map((input) => ({\n previous_out_point: {\n hash: { value: getBytes(input.txhash) },\n index: input.index,\n },\n pub_key: getBytes(input.pubkey),\n })),\n },\n tx_outs: {\n tx_outs: this.txOutputs.map((output) => ({\n address: getBytes(output.address),\n denomination: output.denomination,\n })),\n },\n };\n if (this.signature && includeSignature) {\n protoTx.signature = getBytes(this.signature);\n }\n return protoTx;\n }\n /**\n * Create a Transaction from a serialized transaction or a Transaction-like object.\n *\n * @param {string | QiTransactionLike} tx - The transaction to decode.\n * @returns {QiTransaction} The decoded transaction.\n * @throws {Error} If the transaction is unsigned and defines a hash.\n */\n static from(tx) {\n if (typeof tx === 'string') {\n const decodedProtoTx = decodeProtoTransaction(getBytes(tx));\n return QiTransaction.fromProto(decodedProtoTx);\n }\n const result = new QiTransaction();\n if (tx.type != null) {\n result.type = tx.type;\n }\n if (tx.chainId != null) {\n result.chainId = tx.chainId;\n }\n if (tx.signature != null && tx.signature !== '') {\n result.signature = tx.signature;\n }\n if (tx.txInputs != null) {\n result.txInputs = tx.txInputs;\n }\n if (tx.txOutputs != null) {\n result.txOutputs = tx.txOutputs;\n }\n if (tx.hash != null) {\n assertArgument(result.isSigned(), 'unsigned transaction cannot define hash', 'tx', tx);\n }\n return result;\n }\n /**\n * Create a Transaction from a ProtoTransaction object.\n *\n * @param {ProtoTransaction} protoTx - The transaction to decode.\n * @returns {QiTransaction} The decoded transaction.\n */\n static fromProto(protoTx) {\n const tx = new QiTransaction();\n tx.type = protoTx.type;\n tx.chainId = toBigInt(protoTx.chain_id);\n if (protoTx.type == 2) {\n tx.txInputs =\n protoTx.tx_ins?.tx_ins.map((input) => ({\n txhash: hexlify(input.previous_out_point.hash.value),\n index: input.previous_out_point.index,\n pubkey: hexlify(input.pub_key),\n })) ?? [];\n tx.txOutputs =\n protoTx.tx_outs?.tx_outs.map((output) => ({\n address: hexlify(output.address),\n denomination: output.denomination,\n })) ?? [];\n }\n if (protoTx.signature) {\n tx.signature = hexlify(protoTx.signature);\n }\n return tx;\n }\n}\n//# sourceMappingURL=qi-transaction.js.map","import { keccak256, Signature } from '../crypto/index.js';\nimport { accessListify, AbstractTransaction } from './index.js';\nimport { assert, assertArgument, getBigInt, getBytes, getNumber, getZoneForAddress, hexlify, toBeArray, toBigInt, zeroPadValue, } from '../utils/index.js';\nimport { decodeProtoTransaction, encodeProtoTransaction } from '../encoding/index.js';\nimport { getAddress, recoverAddress, validateAddress, isQuaiAddress } from '../address/index.js';\nimport { formatNumber, handleNumber } from '../providers/format.js';\n/**\n * Parses a signature from an array of fields.\n *\n * @ignore\n * @param {string[]} fields - The fields to parse.\n * @returns {Signature} The parsed signature.\n */\nexport function _parseSignature(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 return Signature.from({ r, s, yParity });\n}\n/**\n * Represents a Quai transaction.\n *\n * @category Transaction\n */\nexport class QuaiTransaction extends AbstractTransaction {\n #to;\n #data;\n #nonce;\n #gasLimit;\n #gasPrice;\n #maxPriorityFeePerGas;\n #maxFeePerGas;\n #value;\n #accessList;\n from;\n /**\n * The `to` address for the transaction or `null` if the transaction is an `init` transaction.\n *\n * @type {null | string}\n */\n get to() {\n return this.#to;\n }\n set to(value) {\n if (value !== null)\n validateAddress(value);\n this.#to = value;\n }\n /**\n * The permuted hash of the transaction as specified by\n * [QIP-0010](https://github.com/quai-network/qips/blob/master/qip-0010.md).\n *\n * @type {null | string}\n * @throws {Error} If the transaction is not signed.\n */\n get hash() {\n if (this.signature == null)\n return null;\n if (!this.originZone) {\n throw new Error('Invalid Zone for from address');\n }\n if (!this.from) {\n throw new Error('Missing from address');\n }\n const isSameLedger = !this.to || isQuaiAddress(this.from) === isQuaiAddress(this.to);\n if (this.isExternal && !isSameLedger) {\n throw new Error('Cross-zone & cross-ledger transactions are not supported');\n }\n const hexString = this.serialized.startsWith('0x') ? this.serialized.substring(2) : this.serialized;\n const dataBuffer = Buffer.from(hexString, 'hex');\n const hashHex = keccak256(dataBuffer);\n const hashBuffer = Buffer.from(hashHex.substring(2), 'hex');\n const origin = this.originZone ? parseInt(this.originZone.slice(2), 16) : 0;\n hashBuffer[0] = origin;\n hashBuffer[1] &= 0x7f;\n hashBuffer[2] = origin;\n hashBuffer[3] &= 0x7f;\n return '0x' + hashBuffer.toString('hex');\n }\n /**\n * The zone of the sender address\n *\n * @type {Zone | undefined}\n */\n get originZone() {\n const zone = this.from ? getZoneForAddress(this.from) : undefined;\n return zone ?? undefined;\n }\n /**\n * The zone of the recipient address\n *\n * @type {Zone | undefined}\n */\n get destZone() {\n const zone = this.to !== null ? getZoneForAddress(this.to || '') : undefined;\n return zone ?? undefined;\n }\n /**\n * The transaction nonce.\n *\n * @type {number}\n */\n get nonce() {\n return this.#nonce;\n }\n set nonce(value) {\n this.#nonce = getNumber(value, 'value');\n }\n /**\n * The gas limit.\n *\n * @type {bigint}\n */\n get gasLimit() {\n return this.#gasLimit;\n }\n set gasLimit(value) {\n this.#gasLimit = getBigInt(value);\n }\n /**\n * The gas price.\n *\n * On legacy networks this defines the fee that will be paid. On EIP-1559 networks, this should be `null`.\n *\n * @type {null | bigint}\n */\n get gasPrice() {\n const value = this.#gasPrice;\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 networks this should be `null`.\n *\n * @type {null | bigint}\n */\n get maxPriorityFeePerGas() {\n const value = this.#maxPriorityFeePerGas;\n if (value == null) {\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 networks this should be `null`.\n *\n * @type {null | bigint}\n */\n get maxFeePerGas() {\n const value = this.#maxFeePerGas;\n if (value == null) {\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 deployment code.\n *\n * @type {string}\n */\n get data() {\n return this.#data;\n }\n set data(value) {\n this.#data = hexlify(value);\n }\n /**\n * The amount of ether to send in this transactions.\n *\n * @type {bigint}\n */\n get value() {\n return this.#value;\n }\n set value(value) {\n this.#value = getBigInt(value, 'value');\n }\n /**\n * The access list.\n *\n * An access list permits discounted (but pre-paid) access to bytecode and state variable access within contract\n * execution.\n *\n * @type {null | AccessList}\n */\n get accessList() {\n const value = this.#accessList || null;\n if (value == null) {\n return null;\n }\n return value;\n }\n set accessList(value) {\n this.#accessList = value == null ? null : accessListify(value);\n }\n /**\n * Creates a new Transaction with default values.\n *\n * @param {string} [from] - The sender address.\n */\n constructor(from) {\n super();\n this.#to = null;\n this.#nonce = 0;\n this.#gasLimit = BigInt(0);\n this.#gasPrice = null;\n this.#maxPriorityFeePerGas = null;\n this.#maxFeePerGas = null;\n this.#data = '0x';\n this.#value = BigInt(0);\n this.#accessList = null;\n this.from = from;\n }\n /**\n * Validates the explicit properties and returns a list of compatible transaction types.\n *\n * @returns {number[]} The compatible transaction types.\n */\n inferTypes() {\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 assert(this.type !== 0 && this.type !== 1, 'transaction type cannot have externalGasLimit, externalGasTip, externalGasPrice, externalData, or externalAccessList', 'BAD_DATA', { value: this });\n const types = [];\n // Explicit type\n if (this.type != null) {\n types.push(this.type);\n }\n else {\n types.push(0);\n }\n types.sort();\n return types;\n }\n /**\n * Create a copy of this transaction.\n *\n * @returns {QuaiTransaction} The cloned transaction.\n */\n clone() {\n return QuaiTransaction.from(this);\n }\n /**\n * Return a JSON-friendly object.\n *\n * @returns {QuaiTransactionLike} The 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 signature: this.signature ? this.signature.toJSON() : null,\n hash: this.hash,\n accessList: this.accessList,\n };\n }\n /**\n * Return a protobuf-friendly JSON object.\n *\n * @param {boolean} [includeSignature=true] - Whether to include the signature. Default is `true`\n * @returns {ProtoTransaction} The protobuf-friendly JSON object.\n */\n toProtobuf(includeSignature = true) {\n const protoTx = {\n type: this.type || 0,\n chain_id: formatNumber(this.chainId || 0, 'chainId'),\n nonce: this.nonce || 0,\n gas_tip_cap: formatNumber(this.maxPriorityFeePerGas || 0, 'maxPriorityFeePerGas'),\n gas_fee_cap: formatNumber(this.maxFeePerGas || 0, 'maxFeePerGas'),\n gas: Number(this.gasLimit || 0),\n to: this.to != null ? getBytes(this.to) : null,\n value: formatNumber(this.value || 0, 'value'),\n data: getBytes(this.data || '0x'),\n access_list: { access_tuples: [] },\n };\n if (this.signature && includeSignature) {\n protoTx.v = formatNumber(this.signature.yParity, 'yParity');\n protoTx.r = toBeArray(this.signature.r);\n protoTx.s = toBeArray(this.signature.s);\n }\n return protoTx;\n }\n /**\n * Create a **Transaction** from a serialized transaction or a Transaction-like object.\n *\n * @param {string | QuaiTransactionLike} tx - The transaction to decode.\n * @returns {QuaiTransaction} The decoded transaction.\n */\n static from(tx) {\n if (typeof tx === 'string') {\n const decodedProtoTx = decodeProtoTransaction(getBytes(tx));\n return QuaiTransaction.fromProto(decodedProtoTx);\n }\n const result = new QuaiTransaction(tx.from);\n if (tx.type != null) {\n result.type = tx.type;\n }\n if (tx.to != null) {\n validateAddress(tx.to);\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.maxPriorityFeePerGas != null) {\n result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas;\n }\n if (tx.maxFeePerGas != null) {\n result.maxFeePerGas = tx.maxFeePerGas;\n }\n if (tx.data != null && tx.data !== '') {\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 if (tx.hash != null) {\n assertArgument(result.isSigned(), 'unsigned transaction cannot define hash', 'tx', tx);\n }\n if (tx.from != null) {\n assertArgument(isQuaiAddress(tx.from), 'from address must be a Quai address', 'tx.from', tx.from);\n assertArgument((result.from || '').toLowerCase() === (tx.from || '').toLowerCase(), 'from mismatch', 'tx', tx);\n result.from = tx.from;\n }\n return result;\n }\n /**\n * Create a **Transaction** from a ProtoTransaction object.\n *\n * @param {ProtoTransaction} protoTx - The transaction to decode.\n * @returns {QuaiTransaction} The decoded transaction.\n */\n static fromProto(protoTx) {\n // TODO: Fix this because new tx instance requires a 'from' address\n let signature = null;\n let address = '';\n if (protoTx.v && protoTx.r && protoTx.s) {\n // check if protoTx.r is zero\n if (protoTx.r.reduce((acc, val) => (acc += val), 0) == 0) {\n throw new Error('Proto decoding only supported for signed transactions');\n }\n const signatureFields = [hexlify(protoTx.v), hexlify(protoTx.r), hexlify(protoTx.s)];\n signature = _parseSignature(signatureFields);\n const protoTxCopy = structuredClone(protoTx);\n delete protoTxCopy.v;\n delete protoTxCopy.r;\n delete protoTxCopy.s;\n delete protoTxCopy.signature;\n delete protoTxCopy.etx_sender;\n delete protoTxCopy.etx_index;\n address = recoverAddress(keccak256(encodeProtoTransaction(protoTxCopy)), signature);\n }\n const tx = new QuaiTransaction(address);\n if (signature) {\n tx.signature = signature;\n }\n if (protoTx.to !== null) {\n const toAddr = hexlify(protoTx.to);\n tx.to = getAddress(toAddr);\n }\n tx.type = protoTx.type;\n tx.chainId = toBigInt(protoTx.chain_id);\n tx.nonce = Number(protoTx.nonce);\n tx.maxPriorityFeePerGas = toBigInt(protoTx.gas_tip_cap);\n tx.maxFeePerGas = toBigInt(protoTx.gas_fee_cap);\n tx.gasLimit = toBigInt(protoTx.gas);\n tx.value = protoTx.value !== null ? toBigInt(protoTx.value) : BigInt(0);\n tx.data = hexlify(protoTx.data);\n tx.accessList = protoTx.access_list.access_tuples.map((tuple) => ({\n address: hexlify(tuple.address),\n storageKeys: tuple.storage_key.map((key) => hexlify(key)),\n }));\n return tx;\n }\n}\n//# sourceMappingURL=quai-transaction.js.map","import { defineProperties, getBigInt, getNumber, hexlify, resolveProperties, assert, assertArgument, isError, makeError, } from '../utils/index.js';\nimport { computeAddress } from '../address/index.js';\nimport { accessListify } from '../transaction/index.js';\nconst BN_0 = BigInt(0);\nimport { toShard, toZone } from '../constants/index.js';\nimport { getZoneFromNodeLocation, getZoneForAddress } from '../utils/shards.js';\n/**\n * Get the value if it is not null or undefined.\n *\n * @ignore\n * @param {undefined | null | T} value - The value to check.\n * @returns {null | T} The value if not null or undefined, otherwise null.\n */\nfunction getValue(value) {\n if (value == null) {\n return null;\n }\n return value;\n}\n/**\n * Convert a value to a JSON-friendly string.\n *\n * @ignore\n * @param {null | bigint | string} value - The value to convert.\n * @returns {null | string} The JSON-friendly string or null.\n */\nfunction toJson(value) {\n if (value == null) {\n return null;\n }\n return value.toString();\n}\n/**\n * A **FeeData** wraps all the fee-related values associated with the network.\n *\n * @category Providers\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 congestion, increasing the cost during times of heavy\n * load and lowering when less busy.\n *\n * The actual fee per gas will be the base fee for the block 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](https://eips.ethereum.org/EIPS/eip-1559))\n */\n maxFeePerGas;\n /**\n * The additional amount to pay per gas to encourage a validator to include the transaction.\n *\n * The purpose of this is to compensate the validator for the adjusted risk for including a given transaction.\n *\n * This will be `null` on legacy networks (i.e. [pre-EIP-1559](https://eips.ethereum.org/EIPS/eip-1559))\n */\n maxPriorityFeePerGas;\n /**\n * Creates a new FeeData for `gasPrice`, `maxFeePerGas` and `maxPriorityFeePerGas`.\n *\n * @param {null | bigint} [gasPrice] - The gas price.\n * @param {null | bigint} [maxFeePerGas] - The maximum fee per gas.\n * @param {null | bigint} [maxPriorityFeePerGas] - The maximum priority fee per gas.\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 * @returns {any} The 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 * Determines the address from a transaction request.\n *\n * @param {TransactionRequest} tx - The transaction request.\n * @returns {AddressLike} The address from the transaction request.\n * @throws {Error} If unable to determine the address.\n */\nexport function addressFromTransactionRequest(tx) {\n if ('from' in tx && !!tx.from) {\n return tx.from;\n }\n if ('txInputs' in tx && !!tx.txInputs) {\n return computeAddress(tx.txInputs[0].pubkey);\n }\n if ('to' in tx && !!tx.to) {\n return tx.to;\n }\n throw new Error('Unable to determine address from transaction inputs, from or to field');\n}\n/**\n * Returns a copy of `req` with all properties coerced to their strict types.\n *\n * @category Providers\n * @param {TransactionRequest} req - The transaction request to copy.\n * @returns {PreparedTransactionRequest} The prepared transaction request.\n * @throws {Error} If the request is invalid.\n */\nexport function copyRequest(req) {\n const result = {};\n // These could be addresses or Addressables\n if ('to' in req && req.to) {\n result.to = req.to;\n }\n if ('from' in req && req.from) {\n result.from = req.from;\n }\n if ('data' in req && req.data) {\n result.data = hexlify(req.data);\n }\n const bigIntKeys = 'chainId,gasLimit,gasPrice,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 ('accessList' in req && req.accessList) {\n result.accessList = accessListify(req.accessList);\n }\n if ('blockTag' in req) {\n result.blockTag = req.blockTag;\n }\n if ('customData' in req) {\n result.customData = req.customData;\n }\n if ('txInputs' in req && req.txInputs) {\n result.txInputs = req.txInputs.map((entry) => ({ ...entry }));\n }\n if ('txOutputs' in req && req.txOutputs) {\n result.txOutputs = req.txOutputs.map((entry) => ({ ...entry }));\n }\n return result;\n}\n/**\n * Represents the header of a block.\n *\n * @category Providers\n */\nexport class BlockHeader {\n baseFeePerGas;\n efficiencyScore;\n etxEligibleSlices;\n etxSetRoot;\n evmRoot;\n expansionNumber;\n extRollupRoot;\n extTransactionsRoot;\n extraData;\n gasLimit;\n gasUsed;\n hash;\n interlinkRootHash;\n manifestHash;\n number;\n parentDeltaS;\n parentEntropy;\n parentHash;\n parentUncledS;\n parentUncledSubDeltaS;\n primeTerminus;\n receiptsRoot;\n sha3Uncles;\n size;\n thresholdCount;\n transactionsRoot;\n uncledS;\n utxoRoot;\n constructor(params) {\n this.baseFeePerGas = params.baseFeePerGas;\n this.efficiencyScore = params.efficiencyScore;\n this.etxEligibleSlices = params.etxEligibleSlices;\n this.etxSetRoot = params.etxSetRoot;\n this.evmRoot = params.evmRoot;\n this.expansionNumber = params.expansionNumber;\n this.extRollupRoot = params.extRollupRoot;\n this.extTransactionsRoot = params.extTransactionsRoot;\n this.extraData = params.extraData;\n this.gasLimit = params.gasLimit;\n this.gasUsed = params.gasUsed;\n this.hash = params.hash;\n this.interlinkRootHash = params.interlinkRootHash;\n this.manifestHash = params.manifestHash;\n this.number = params.number;\n this.parentDeltaS = params.parentDeltaS;\n this.parentEntropy = params.parentEntropy;\n this.parentHash = params.parentHash;\n this.parentUncledS = params.parentUncledS;\n this.parentUncledSubDeltaS = params.parentUncledSubDeltaS;\n this.primeTerminus = params.primeTerminus;\n this.receiptsRoot = params.receiptsRoot;\n this.sha3Uncles = params.sha3Uncles;\n this.size = params.size;\n this.thresholdCount = params.thresholdCount;\n this.transactionsRoot = params.transactionsRoot;\n this.uncledS = params.uncledS;\n this.utxoRoot = params.utxoRoot;\n }\n toJSON() {\n return {\n baseFeePerGas: this.baseFeePerGas,\n efficiencyScore: this.efficiencyScore,\n etxEligibleSlices: this.etxEligibleSlices,\n etxSetRoot: this.etxSetRoot,\n evmRoot: this.evmRoot,\n expansionNumber: this.expansionNumber,\n extRollupRoot: this.extRollupRoot,\n extTransactionsRoot: this.extTransactionsRoot,\n extraData: this.extraData,\n gasLimit: this.gasLimit,\n gasUsed: this.gasUsed,\n hash: this.hash,\n interlinkRootHash: this.interlinkRootHash,\n manifestHash: this.manifestHash,\n number: this.number,\n parentDeltaS: this.parentDeltaS,\n parentEntropy: this.parentEntropy,\n parentHash: this.parentHash,\n parentUncledS: this.parentUncledS,\n parentUncledSubDeltaS: this.parentUncledSubDeltaS,\n primeTerminus: this.primeTerminus,\n receiptsRoot: this.receiptsRoot,\n sha3Uncles: this.sha3Uncles,\n size: this.size,\n thresholdCount: this.thresholdCount,\n transactionsRoot: this.transactionsRoot,\n uncledS: this.uncledS,\n utxoRoot: this.utxoRoot,\n };\n }\n}\n/**\n * Represents the header of a work object.\n *\n * @category Providers\n */\nexport class WoHeader {\n difficulty;\n headerHash;\n location;\n mixHash;\n nonce;\n number;\n parentHash;\n time;\n txHash;\n /**\n * Creates a new WoHeader instance.\n *\n * @param {WoHeaderParams} params - The parameters for the WoHeader.\n */\n constructor(params) {\n this.difficulty = params.difficulty;\n this.headerHash = params.headerHash;\n this.location = params.location;\n this.mixHash = params.mixHash;\n this.nonce = params.nonce;\n this.number = params.number;\n this.parentHash = params.parentHash;\n this.time = params.time;\n this.txHash = params.txHash;\n }\n toJSON() {\n return {\n difficulty: this.difficulty,\n headerHash: this.headerHash,\n location: this.location,\n mixHash: this.mixHash,\n nonce: this.nonce,\n number: this.number,\n parentHash: this.parentHash,\n time: this.time,\n txHash: this.txHash,\n };\n }\n}\n/**\n * A **Block** represents the data associated with a full block on Ethereum.\n *\n * @category Providers\n */\nexport class Block {\n #extTransactions;\n hash;\n header;\n interlinkHashes; // New parameter\n order;\n size;\n subManifest;\n totalEntropy;\n #transactions;\n uncles;\n woHeader; // New nested parameter structure\n /**\n * The provider connected to the block used to fetch additional details if necessary.\n */\n provider;\n /**\n * Create a new **Block** object.\n *\n * This should generally not be necessary as the unless implementing a low-level library.\n *\n * @param {BlockParams} block - The block parameters.\n * @param {Provider} provider - The provider.\n */\n constructor(block, provider) {\n this.#transactions = block.transactions.map((tx) => {\n if (typeof tx === 'string') {\n return tx;\n }\n if ('originatingTxHash' in tx) {\n return new ExternalTransactionResponse(tx, provider);\n }\n if ('from' in tx) {\n return new QuaiTransactionResponse(tx, provider);\n }\n return new QiTransactionResponse(tx, provider);\n });\n this.#extTransactions = block.extTransactions.map((tx) => {\n if (typeof tx !== 'string') {\n return new ExternalTransactionResponse(tx, provider);\n }\n return tx;\n });\n this.hash = block.hash;\n this.header = new BlockHeader(block.header);\n this.interlinkHashes = block.interlinkHashes;\n this.order = block.order;\n this.size = block.size;\n this.subManifest = block.subManifest;\n this.totalEntropy = block.totalEntropy;\n this.uncles = block.uncles;\n this.woHeader = new WoHeader(block.woHeader);\n this.provider = provider;\n }\n /**\n * Returns the list of transaction hashes, in the order they were executed within the block.\n *\n * @returns {ReadonlyArray} The list of transaction hashes.\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 list of extended transaction hashes, in the order they were executed within the block.\n *\n * @returns {ReadonlyArray} The list of extended transaction hashes.\n */\n get extTransactions() {\n return this.#extTransactions.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 were executed within the block.\n *\n * This is only available for blocks which prefetched transactions, by passing `true` to `prefetchTxs` into\n * {@link Provider.getBlock | **getBlock**}.\n *\n * @returns {TransactionResponse[]} The list of prefetched transactions.\n * @throws {Error} If the transactions were not prefetched.\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 the complete extended transactions, in the order they were executed within the block.\n *\n * This is only available for blocks which prefetched transactions, by passing `true` to `prefetchTxs` into\n * {@link Provider.getBlock | **getBlock**}.\n *\n * @returns {TransactionResponse[]} The list of prefetched extended transactions.\n * @throws {Error} If the transactions were not prefetched.\n */\n get prefetchedExtTransactions() {\n const txs = this.#extTransactions.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 * @returns {any} The JSON-friendly value.\n */\n toJSON() {\n const { hash, header, interlinkHashes, order, size, subManifest, totalEntropy, uncles, woHeader } = this;\n // Using getters to retrieve the transactions and extTransactions\n const transactions = this.transactions;\n const extTransactions = this.extTransactions;\n return {\n _type: 'Block',\n hash,\n header: header.toJSON(),\n interlinkHashes,\n order,\n size: toJson(size),\n subManifest,\n totalEntropy: toJson(totalEntropy),\n uncles,\n woHeader: woHeader.toJSON(),\n transactions,\n extTransactions, // Includes the extended transaction hashes or full transactions based on the prefetched data\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++],\n done: false,\n };\n }\n return { value: undefined, done: true };\n },\n };\n }\n /**\n * The number of transactions in this block.\n *\n * @returns {number} The number of transactions.\n */\n get length() {\n return this.#transactions.length;\n }\n /**\n * The [Date](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) this block was\n * included at.\n *\n * @returns {null | Date} The date this block was included at, or null if the timestamp is not available.\n */\n get date() {\n const timestampHex = this.woHeader.time;\n if (!timestampHex) {\n return null;\n }\n const timestamp = parseInt(timestampHex, 16);\n return new Date(timestamp * 1000);\n }\n /**\n * Get the transaction at `index` within this block.\n *\n * @param {number | string} indexOrHash - The index or hash of the transaction.\n * @returns {Promise} A promise resolving to the transaction.\n * @throws {Error} If the transaction is not found.\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 * Get the extended transaction at `index` within this block.\n *\n * @param {number | string} indexOrHash - The index or hash of the extended transaction.\n * @returns {Promise} A promise resolving to the extended transaction.\n * @throws {Error} If the extended transaction is not found.\n */\n async getExtTransaction(indexOrHash) {\n // Find the internal value by its index or hash\n let tx = undefined;\n if (typeof indexOrHash === 'number') {\n tx = this.#extTransactions[indexOrHash];\n }\n else {\n const hash = indexOrHash.toLowerCase();\n for (const v of this.#extTransactions) {\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 throw new Error(\"External Transaction isn't prefetched\");\n }\n else {\n return tx;\n }\n }\n /**\n * If a **Block** was fetched with a request to include the transactions this will allow synchronous access to those\n * transactions.\n *\n * If the transactions were not prefetched, this will throw.\n *\n * @param {number | string} indexOrHash - The index or hash of the transaction.\n * @returns {TransactionResponse} The transaction.\n * @throws {Error} If the transaction is not found.\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 for all properties on a\n * {@link MinedBlock | **MinedBlock**}.\n *\n * @returns {boolean} True if the block has been mined.\n */\n isMined() {\n return !!this.header.hash;\n }\n /**\n * @ignore\n */\n orphanedEvent() {\n if (!this.isMined() || !this.woHeader.number) {\n throw new Error('');\n }\n return createOrphanedBlockFilter({\n hash: this.header.hash,\n number: parseInt(this.woHeader.number, 16),\n });\n }\n}\n//////////////////////\n// Log\n/**\n * A **Log** in Ethereum represents an event that has been included in a transaction using the `LOG*` opcodes, which are\n * most commonly used by Solidity's emit for announcing events.\n *\n * @category Providers\n */\nexport class Log {\n /**\n * The provider connected to the log used to fetch additional details if necessary.\n */\n provider;\n /**\n * The transaction hash of the transaction this log occurred in. Use the\n * {@link Log.getTransaction | **Log.getTransaction**} to get the\n * {@link TransactionResponse | **TransactionResponse}.\n */\n transactionHash;\n /**\n * The block hash of the block this log occurred in. Use the {@link Log.getBlock | **Log.getBlock**} to get the\n * {@link Block | **Block**}.\n */\n blockHash;\n /**\n * The block number of the block this log occurred in. It is preferred to use the {@link Block.hash | **Block.hash**}\n * when fetching the related {@link Block | **Block**}, since in the case of an orphaned block, the block at that\n * height may have changed.\n */\n blockNumber;\n /**\n * If the **Log** represents a block that was removed due to an orphaned 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 efficiently filtered using the\n * {@link Provider.getLogs | **Provider.getLogs**} method.\n */\n topics;\n /**\n * The index within the block this log occurred at. This is generally not useful to developers, but can be used with\n * the various roots 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,\n blockHash,\n blockNumber,\n data,\n index,\n removed,\n topics,\n transactionHash,\n transactionIndex,\n };\n }\n /**\n * Returns the block that this log occurred in.\n *\n * @param {Shard} shard - The shard to fetch the block from.\n * @returns {Promise} A promise resolving to the block.\n */\n async getBlock(shard) {\n const block = await this.provider.getBlock(shard, 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 * @returns {Promise} A promise resolving to the transaction.\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 log occurred in.\n *\n * @returns {Promise} A promise resolving to the transaction receipt.\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\nexport function zoneFromHash(hash) {\n return toZone(hash.slice(0, 4));\n}\n/**\n * A **TransactionReceipt** includes additional information about a transaction that is only available after it has been\n * mined.\n *\n * @category Providers\n */\nexport class TransactionReceipt {\n /**\n * The provider connected to the log used to fetch additional details 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 responsible for deploying one.\n *\n * This is non-null **only** if the `to` is empty and the `data` 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 {@link Block | **Block**} this transaction was included in.\n */\n blockHash;\n /**\n * The block number of the {@link Block | **Block**} this transaction was included in.\n */\n blockNumber;\n /**\n * The bloom filter bytes that represent all logs that occurred within this transaction. This is generally not\n * useful for most developers, 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 only be approximated, but the sender must\n * pay the gas fee for the entire gas limit. After the transaction, the difference is refunded.\n */\n gasUsed;\n /**\n * The amount of gas used by all transactions within the block for this and all transactions with a lower `index`.\n *\n * This is generally not useful for developers but can be used to validate certain aspects of execution.\n */\n cumulativeGasUsed;\n /**\n * The actual gas price used during execution.\n *\n * Due to the complexity of [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) this value can only be caluclated\n * after the transaction has been mined, snce the base fee is protocol-enforced.\n */\n gasPrice;\n /**\n * The [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction type.\n */\n type;\n //readonly byzantium!: boolean;\n /**\n * The status of this transaction, indicating success (i.e. `1`) or a revert (i.e. `0`).\n *\n * This is available in post-byzantium blocks, but some backends may 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 could be used to validate certain parts of\n * the receipt.\n */\n #logs;\n etxs = [];\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 const etxs = tx.etxs\n ? tx.etxs.map((etx) => {\n const safeConvert = (value, name) => {\n try {\n if (value != null) {\n return BigInt(value);\n }\n return null;\n }\n catch (error) {\n console.error(`Conversion to BigInt failed for ${name}: ${value}, error: ${error}`);\n return null;\n }\n };\n return {\n type: etx.type,\n nonce: etx.nonce,\n gasPrice: safeConvert(etx.gasPrice, 'gasPrice'),\n maxPriorityFeePerGas: safeConvert(etx.maxPriorityFeePerGas, 'maxPriorityFeePerGas'),\n maxFeePerGas: safeConvert(etx.maxFeePerGas, 'maxFeePerGas'),\n gas: safeConvert(etx.gas, 'gas'),\n value: safeConvert(etx.value, 'value'),\n input: etx.input,\n to: etx.to,\n accessList: etx.accessList,\n chainId: safeConvert(etx.chainId, 'chainId'),\n sender: etx.sender,\n hash: etx.hash,\n isCoinbase: etx.isCoinbase,\n originatingTxHash: etx.originatingTxHash,\n etxIndex: etx.etxIndex,\n };\n })\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 gasPrice,\n etxs: etxs,\n type: tx.type,\n status: tx.status,\n });\n }\n /**\n * The logs for this transaction.\n */\n get logs() {\n return this.#logs;\n }\n /**\n * Returns a JSON-compatible representation.\n */\n toJSON() {\n const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, //byzantium,\n status, etxs, } = this;\n return {\n _type: 'TransactionReceipt',\n blockHash,\n blockNumber,\n contractAddress,\n cumulativeGasUsed: toJson(this.cumulativeGasUsed),\n from,\n gasPrice: toJson(this.gasPrice),\n gasUsed: toJson(this.gasUsed),\n hash,\n index,\n logs,\n logsBloom,\n status,\n to,\n etxs: etxs ?? [],\n };\n }\n /**\n * @ignore\n */\n get length() {\n return this.logs.length;\n }\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 * @param {Shard} shard - The shard to fetch the block from.\n * @returns {Promise} A promise resolving to the block.\n * @throws {Error} If the block is not found.\n */\n async getBlock(shard) {\n const block = await this.provider.getBlock(shard, 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 * @returns {Promise} A promise resolving to the transaction.\n * @throws {Error} If the transaction is not found.\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 with the `debug_` or `trace_` API enabled.\n *\n * @returns {Promise} A promise resolving to the return value of the transaction.\n * @throws {Error} If the transaction is not found.\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 * @returns {Promise} A promise resolving to the number of confirmations.\n * @throws {Error} If the block is not found.\n */\n async confirmations() {\n const zone = zoneFromHash(this.hash);\n return (await this.provider.getBlockNumber(toShard(zone))) - 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', {\n operation: 'reorderedEvent(other)',\n });\n return createReorderedTransactionFilter(this, other);\n }\n}\nexport class ExternalTransactionResponse {\n /**\n * The provider this is connected to, which will influence how its methods will resolve its async inspection\n * 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 [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy\n * transactions types.\n */\n type;\n /**\n * The receiver of this transaction.\n *\n * If `null`, then the transaction is an initcode transaction. This means the result of executing the\n * {@link ExternalTransactionResponse.data | **data** } will be deployed as a new contract on chain (assuming it does\n * not revert) and the address may be computed using [getCreateAddress](../functions/getCreateAddress).\n */\n to;\n /**\n * The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and\n * the {@link QuaiTransactionResponse.signature | **signature** } using ecrecover.\n */\n from;\n /**\n * The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender\n * are explicitly ordered.\n *\n * When sending a transaction, this must be equal to the number of transactions ever sent by\n * {@link ExternalTransactionResponse.from | **from** }.\n */\n nonce;\n /**\n * The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is\n * reverted and the sender is charged for the full amount, despite not state changes being made.\n */\n gasLimit;\n /**\n * The data.\n */\n data;\n /**\n * The value, in wei. Use [formatEther](../functions/formatEther) to format this value as ether.\n */\n value;\n /**\n * The chain ID.\n */\n chainId;\n /**\n * The signature.\n */\n signature;\n /**\n * The [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list for transaction types that support it,\n * otherwise `null`.\n */\n accessList;\n etxType;\n isCoinbase;\n originatingTxHash;\n sender;\n etxIndex;\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.chainId = tx.chainId;\n this.signature = tx.signature;\n this.accessList = tx.accessList != null ? tx.accessList : null;\n this.startBlock = -1;\n this.originatingTxHash = tx.originatingTxHash != null ? tx.originatingTxHash : null;\n this.isCoinbase = tx.isCoinbase != null ? tx.isCoinbase : null;\n this.etxType = tx.etxType != null ? tx.etxType : null;\n this.sender = tx.sender;\n this.etxIndex = tx.etxIndex;\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, etxType, isCoinbase, originatingTxHash, etxIndex, sender, } = this;\n const result = {\n _type: 'TransactionReceipt',\n accessList,\n blockNumber,\n blockHash,\n chainId: toJson(this.chainId),\n data,\n from,\n gasLimit: toJson(this.gasLimit),\n hash,\n nonce,\n signature,\n to,\n index,\n type,\n etxType,\n isCoinbase,\n originatingTxHash,\n sender,\n etxIndex,\n value: toJson(this.value),\n };\n return result;\n }\n replaceableTransaction(startBlock) {\n assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock);\n const tx = new ExternalTransactionResponse(this, this.provider);\n tx.startBlock = startBlock;\n return tx;\n }\n}\n/**\n * A **QuaiTransactionResponse** includes all properties about a Quai transaction that was sent to the network, which\n * may or may not be included in a block.\n *\n * The {@link TransactionResponse.isMined | **TransactionResponse.isMined**} can be used to check if the transaction has\n * been mined as well as type guard that the otherwise possibly `null` properties are defined.\n *\n * @category Providers\n */\nexport class QuaiTransactionResponse {\n /**\n * The provider this is connected to, which will influence how its methods will resolve its async inspection\n * 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 [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy\n * transactions types.\n */\n type;\n /**\n * The receiver of this transaction.\n *\n * If `null`, then the transaction is an initcode transaction. This means the result of executing the\n * {@link QuaiTransactionResponse.data | **data** } will be deployed as a new contract on chain (assuming it does not\n * revert) and the address may be computed using [getCreateAddress](../functions/getCreateAddress).\n */\n to;\n /**\n * The sender of this transaction. It is implicitly computed from the transaction pre-image hash (as the digest) and\n * the {@link QuaiTransactionResponse.signature | **signature** } using ecrecover.\n */\n from;\n /**\n * The nonce, which is used to prevent replay attacks and offer a method to ensure transactions from a given sender\n * are explicitly ordered.\n *\n * When sending a transaction, this must be equal to the number of transactions ever sent by\n * {@link QuaiTransactionResponse.from | **from** }.\n */\n nonce;\n /**\n * The maximum units of gas this transaction can consume. If execution exceeds this, the entries transaction is\n * reverted and the sender is charged for the full amount, despite not state changes being made.\n */\n gasLimit;\n /**\n * The maximum priority fee (per unit of gas) to allow a validator to charge the sender. This is inclusive of the\n * {@link QuaiTransactionResponse.maxFeePerGas | **maxFeePerGas** }.\n */\n maxPriorityFeePerGas;\n /**\n * The maximum fee (per unit of gas) to allow this transaction to charge the sender.\n */\n maxFeePerGas;\n /**\n * The data.\n */\n data;\n /**\n * The value, in wei. Use [formatEther](../functions/formatEther) to format this value as ether.\n */\n value;\n /**\n * The chain ID.\n */\n chainId;\n /**\n * The signature.\n */\n signature;\n /**\n * The [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) access list for transaction types that support it,\n * otherwise `null`.\n */\n accessList;\n etxType;\n sender;\n originatingTxHash;\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.maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? tx.maxPriorityFeePerGas : null;\n this.maxFeePerGas = tx.maxFeePerGas != null ? tx.maxFeePerGas : null;\n this.chainId = tx.chainId;\n this.signature = tx.signature;\n this.accessList = tx.accessList != null ? tx.accessList : null;\n this.startBlock = -1;\n this.etxType = tx.etxType != null ? tx.etxType : null;\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 } = this;\n const result = {\n _type: 'TransactionReceipt',\n accessList,\n blockNumber,\n blockHash,\n chainId: toJson(this.chainId),\n data,\n from,\n gasLimit: toJson(this.gasLimit),\n hash,\n maxFeePerGas: toJson(this.maxFeePerGas),\n maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas),\n nonce,\n signature,\n to,\n index,\n type,\n value: toJson(this.value),\n };\n return result;\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 * @param {Shard} shard - The shard to fetch the block from.\n * @returns {null | Promise} A promise resolving to the block.\n */\n async getBlock(shard) {\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(shard, 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 provider. This can be used if you have an unmined\n * transaction and wish to get an up-to-date populated instance.\n *\n * @returns {null | Promise} A promise resolving to the transaction, or null if not found.\n */\n async getTransaction() {\n const transaction = this.provider.getTransaction(this.hash);\n if (transaction instanceof QuaiTransactionResponse) {\n return transaction;\n }\n else {\n return null;\n }\n }\n /**\n * Resolve to the number of confirmations this transaction has.\n *\n * @returns {Promise} A promise resolving to the number of confirmations.\n * @throws {Error} If the block is not found.\n */\n async confirmations() {\n const zone = zoneFromHash(this.hash);\n if (this.blockNumber == null) {\n const { tx, blockNumber } = await resolveProperties({\n tx: this.getTransaction(),\n blockNumber: this.provider.getBlockNumber(toShard(zone)),\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(toShard(zone));\n return blockNumber - this.blockNumber + 1;\n }\n /**\n * Resolves once this transaction has been mined and has `confirms` blocks including it (default: `1`) with an\n * optional `timeout`.\n *\n * This can resolve to `null` only if `confirms` is `0` and the transaction has not been mined, otherwise this will\n * wait until enough confirmations have completed.\n *\n * @param {number} [_confirms] - The number of confirmations to wait for.\n * @param {number} [_timeout] - The number of milliseconds to wait before rejecting.\n * @returns {Promise} A promise resolving to the transaction receipt.\n * @throws {Error} If the transaction was replaced, repriced, or cancelled.\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 zone = zoneFromHash(this.hash);\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(toShard(zone)),\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(toShard(zone), 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 ('from' in tx && 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,\n reason: null,\n invocation: null,\n revert: null,\n transaction: {\n to: receipt.to,\n from: receipt.from,\n data: '', // @TODO: in v7, split out sendTransaction properties\n },\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 = () => {\n cancellers.forEach((c) => c());\n };\n // On cancel, stop scanning for replacements\n cancellers.push(() => {\n stopScanning = true;\n });\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(() => {\n clearTimeout(timer);\n });\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(() => {\n this.provider.off(this.hash, txListener);\n });\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(() => {\n this.provider.off('block', replaceListener);\n });\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 was instantiated. To get up-to-date information,\n * use {@link QuaiTransactionResponse.getTransaction | **getTransaction**}.\n *\n * This provides a Type Guard that this transaction will have non-null property values for properties that are null\n * for unmined transactions.\n *\n * @returns {QuaiMinedTransactionResponse} True if the transaction has been mined.\n * @throws {Error} If the transaction was replaced, repriced, or cancelled.\n */\n isMined() {\n return this.blockHash != null;\n }\n /**\n * Returns a filter which can be used to listen for orphan events that evict this transaction.\n *\n * @returns {OrphanFilter} The orphan filter.\n */\n removedEvent() {\n assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n return createRemovedTransactionFilter(this);\n }\n /**\n * Returns a filter which can be used to listen for orphan events that re-order this event against `other`.\n *\n * @param {TransactionResponse} [other] - The other transaction to compare against.\n * @returns {OrphanFilter} The orphan filter.\n */\n reorderedEvent(other) {\n assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n assert(!other || other.isMined(), \"unmined 'other' transaction canot be orphaned\", 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n return createReorderedTransactionFilter(this, other);\n }\n /**\n * Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the\n * transaction is replaced, which will begin scanning at `startBlock`.\n *\n * This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect\n * `startBlock` can have devastating performance consequences if used incorrectly.\n *\n * @param {number} startBlock - The block number to start scanning for replacements.\n * @returns {QuaiTransactionResponse} The replaceable transaction.\n */\n replaceableTransaction(startBlock) {\n assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock);\n const tx = new QuaiTransactionResponse(this, this.provider);\n tx.startBlock = startBlock;\n return tx;\n }\n}\n/**\n * A **QiTransactionResponse** includes all properties about a Qi transaction that was sent to the network, which may or\n * may not be included in a block.\n *\n * The {@link TransactionResponse.isMined | **TransactionResponse.isMined**} can be used to check if the transaction has\n * been mined as well as type guard that the otherwise possibly `null` properties are defined.\n *\n * @category Providers\n */\nexport class QiTransactionResponse {\n /**\n * The provider this is connected to, which will influence how its methods will resolve its async inspection\n * 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 [EIP-2718](https://eips.ethereum.org/EIPS/eip-2718) transaction envelope type. This is `0` for legacy\n * transactions types.\n */\n type;\n /**\n * The chain ID.\n */\n chainId;\n /**\n * The signature.\n */\n signature;\n txInputs;\n txOutputs;\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.chainId = tx.chainId;\n this.signature = tx.signature;\n this.startBlock = -1;\n this.txInputs = tx.txInputs;\n this.txOutputs = tx.txOutputs;\n }\n /**\n * Returns a JSON-compatible representation of this transaction.\n */\n toJSON() {\n const { blockNumber, blockHash, index, hash, type, signature, txInputs, txOutputs } = this;\n const result = {\n _type: 'TransactionReceipt',\n blockNumber,\n blockHash,\n chainId: toJson(this.chainId),\n hash,\n signature,\n index,\n type,\n txInputs: JSON.parse(JSON.stringify(txInputs)),\n txOutputs: JSON.parse(JSON.stringify(txOutputs)),\n };\n return result;\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 * @param {Shard} shard - The shard to fetch the block from.\n * @returns {null | Promise} A promise resolving to the block or null if not found.\n */\n async getBlock(shard) {\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(shard, 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 provider. This can be used if you have an unmined\n * transaction and wish to get an up-to-date populated instance.\n *\n * @returns {null | Promise} A promise resolving to the transaction, or null if not found.\n * @throws {Error} If the transaction is not found.\n */\n async getTransaction() {\n const transaction = this.provider.getTransaction(this.hash);\n if (transaction instanceof QiTransactionResponse) {\n return transaction;\n }\n else {\n return null;\n }\n }\n /**\n * Resolve to the number of confirmations this transaction has.\n *\n * @returns {Promise} A promise resolving to the number of confirmations.\n */\n async confirmations() {\n const zone = zoneFromHash(this.hash);\n if (this.blockNumber == null) {\n const { tx, blockNumber } = await resolveProperties({\n tx: this.getTransaction(),\n blockNumber: this.provider.getBlockNumber(toShard(zone)),\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(toShard(zone));\n return blockNumber - this.blockNumber + 1;\n }\n /**\n * Returns `true` if this transaction has been included.\n *\n * This is effective only as of the time the TransactionResponse was instantiated. To get up-to-date information,\n * use {@link QiTransactionResponse.getTransaction | **getTransaction**}.\n *\n * This provides a Type Guard that this transaction will have non-null property values for properties that are null\n * for unmined transactions.\n *\n * @returns {QiMinedTransactionResponse} True if the transaction has been mined or false otherwise.\n */\n isMined() {\n return this.blockHash != null;\n }\n /**\n * Returns a filter which can be used to listen for orphan events that evict this transaction.\n *\n * @returns {OrphanFilter} The orphan filter.\n */\n removedEvent() {\n assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n return createRemovedTransactionFilter(this);\n }\n /**\n * Returns a filter which can be used to listen for orphan events that re-order this event against `other`.\n *\n * @param {TransactionResponse} [other] - The other transaction to compare against.\n * @returns {OrphanFilter} The orphan filter.\n */\n reorderedEvent(other) {\n assert(this.isMined(), 'unmined transaction canot be orphaned', 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n assert(!other || other.isMined(), \"unmined 'other' transaction canot be orphaned\", 'UNSUPPORTED_OPERATION', {\n operation: 'removeEvent()',\n });\n return createReorderedTransactionFilter(this, other);\n }\n /**\n * Returns a new TransactionResponse instance which has the ability to detect (and throw an error) if the\n * transaction is replaced, which will begin scanning at `startBlock`.\n *\n * This should generally not be used by developers and is intended primarily for internal use. Setting an incorrect\n * `startBlock` can have devastating performance consequences if used incorrectly.\n *\n * @param {number} startBlock - The block number to start scanning for replacements.\n * @returns {QiTransactionResponse} The replaceable transaction.\n */\n replaceableTransaction(startBlock) {\n assertArgument(Number.isInteger(startBlock) && startBlock >= 0, 'invalid startBlock', 'startBlock', startBlock);\n const tx = new QiTransactionResponse(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 {\n orphan: 'drop-log',\n 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}\nexport function getZoneFromEventFilter(filter) {\n let zone = null;\n if (filter.nodeLocation) {\n zone = getZoneFromNodeLocation(filter.nodeLocation);\n }\n else if (filter.address) {\n let address;\n if (Array.isArray(filter.address)) {\n address = filter.address[0];\n }\n else {\n address = filter.address;\n }\n const addressZone = getZoneForAddress(address);\n if (addressZone) {\n zone = toZone(addressZone);\n }\n else {\n return null;\n }\n }\n return zone;\n}\n//# sourceMappingURL=provider.js.map","// import from provider.ts instead of index.ts to prevent circular dep\n// from quaiscanProvider\nimport { Log, QuaiTransactionResponse, TransactionReceipt } from '../providers/provider.js';\nimport { defineProperties, EventPayload } from '../utils/index.js';\n/**\n * An **EventLog** contains additional properties parsed from the {@link Log | **Log**}.\n *\n * @category Contract\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() {\n return this.fragment.name;\n }\n /**\n * The signature of the event.\n */\n get eventSignature() {\n return this.fragment.format();\n }\n}\n/**\n * An **EventLog** contains additional properties parsed from the {@link Log | **Log**}.\n *\n * @category Contract\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 {@link TransactionReceipt | **TransactionReceipt**}.\n *\n * @category Contract\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 {@link Log | **Log**} which has a matching event in the 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 {@link ContractTransactionReceipt | **ContractTransactionReceipt**}\n * when waited on.\n *\n * @category Contract\n */\nexport class ContractTransactionResponse extends QuaiTransactionResponse {\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 `confirms` blocks including it (default: `1`) with an\n * optional `timeout`.\n *\n * This can resolve to `null` only if `confirms` is `0` and the transaction has not been mined, otherwise this will\n * wait until enough confirmations have completed.\n *\n * @param {number} confirms - The number of confirmations to wait for.\n *\n * @returns {Promise} The transaction receipt, or `null` if `confirms` is `0`.\n */\n async wait(confirms) {\n const receipt = await super.wait(confirms);\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 Contract Events when the event does not match\n * any events in the ABI.\n *\n * @category Contract\n */\nexport class ContractUnknownEventPayload extends EventPayload {\n /**\n * The log with no matching events.\n */\n log;\n /**\n * @ignore\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 * @param {Shard} shard - The shard to get the block from.\n *\n * @returns {Promise} A promise resolving to the block the event occured in.\n */\n async getBlock(shard) {\n return await this.log.getBlock(shard);\n }\n /**\n * Resolves to the transaction the event occured in.\n *\n * @returns {Promise} A promise resolving 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 * @returns {Promise} A promise resolving 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 Contract Events when the event is known.\n *\n * @category Contract\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, validateAddress } from '../address/index.js';\n// import from provider.ts instead of index.ts to prevent circular dep\n// from quaiscanProvider\nimport { copyRequest, Log, } from '../providers/provider.js';\nimport { defineProperties, getBigInt, isCallException, isHexString, resolveProperties, isError, assert, assertArgument, getZoneForAddress, } from '../utils/index.js';\nimport { ContractEventPayload, ContractUnknownEventPayload, ContractTransactionResponse, EventLog, UndecodedEventLog, } from './wrappers.js';\nimport { getNodeLocationFromZone } from '../utils/shards.js';\nconst BN_0 = BigInt(0);\n/**\n * Check if the value can call transactions.\n *\n * @param {any} value - The value to check.\n * @returns {value is ContractRunnerCaller} True if the value can call transactions.\n */\nfunction canCall(value) {\n return value && typeof value.call === 'function';\n}\n/**\n * Check if the value can estimate gas.\n *\n * @param {any} value - The value to check.\n * @returns {value is ContractRunnerEstimater} True if the value can estimate gas.\n */\nfunction canEstimate(value) {\n return value && typeof value.estimateGas === 'function';\n}\n/**\n * Check if the value can send transactions.\n *\n * @param {any} value - The value to check.\n * @returns {value is ContractRunnerSender} True if the value can send transactions.\n */\nfunction canSend(value) {\n return value && typeof value.sendTransaction === 'function';\n}\n/**\n * Class representing a prepared topic filter.\n *\n * @implements {DeferredTopicFilter}\n */\nclass PreparedTopicFilter {\n #filter;\n fragment;\n /**\n * @ignore\n */\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 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)));\n }\n return resolveAddress(value);\n }\n return value;\n });\n }));\n return contract.interface.encodeFilterTopics(fragment, resolvedArgs);\n })();\n }\n /**\n * Get the topic filter.\n *\n * @returns {Promise} The topic filter.\n */\n getTopicFilter() {\n return this.#filter;\n }\n}\n/**\n * Get the runner for a specific feature.\n *\n * @param {any} value - The value to check.\n * @param {keyof ContractRunner} feature - The feature to check for.\n * @returns {null | T} The runner if available, otherwise null.\n */\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}\n/**\n * Get the provider from a contract runner.\n *\n * @param {null | ContractRunner} value - The contract runner.\n * @returns {null | Provider} The provider if available, otherwise null.\n */\nfunction getProvider(value) {\n if (value == null) {\n return null;\n }\n return value.provider || null;\n}\n/**\n * @ignore Copy overrides and validate them.\n * @param {any} arg - The argument containing overrides.\n * @param {string[]} [allowed] - The allowed override keys.\n * @returns {Promise>} The copied and validated overrides.\n * @throws {Error} If the overrides are invalid.\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(!('to' in overrides) || overrides.to == null || (allowed || []).indexOf('to') >= 0, 'cannot override to', 'overrides.to', overrides);\n assertArgument(!('data' in overrides) || overrides.data == null || (allowed || []).indexOf('data') >= 0, 'cannot override data', 'overrides.data', overrides);\n // Resolve any from\n if ('from' in overrides && overrides.from) {\n overrides.from = await overrides.from;\n }\n return overrides;\n}\n/**\n * @ignore Resolve arguments for a contract runner.\n * @param {null | ContractRunner} _runner - The contract runner.\n * @param {ReadonlyArray} inputs - The input parameter types.\n * @param {any[]} args - The arguments to resolve.\n * @returns {Promise} The resolved arguments.\n */\nexport async function resolveArgs(_runner, inputs, args) {\n // Recursively descend into args and resolve any addresses\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);\n }\n return value;\n });\n }));\n}\n/**\n * Build a wrapped fallback method for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @returns {WrappedFallback} The wrapped fallback method.\n */\nfunction buildWrappedFallback(contract) {\n /**\n * Populate a transaction with overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The populated transaction.\n * @throws {Error} If the overrides are invalid.\n */\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 validateAddress(tx.to);\n if (tx.from) {\n tx.from = await resolveAddress(tx.from);\n validateAddress(tx.from);\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 /**\n * Perform a static call with the given overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The result of the static call.\n * @throws {Error} If the call fails.\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', {\n operation: 'call',\n });\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 /**\n * Send a transaction with the given overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the transaction fails.\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', {\n operation: 'sendTransaction',\n });\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 /**\n * Estimate the gas required for a transaction with the given overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The estimated gas.\n * @throws {Error} If the gas estimation fails.\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', {\n operation: 'estimateGas',\n });\n return await runner.estimateGas(await populateTransaction(overrides));\n };\n /**\n * Send a transaction with the given overrides.\n *\n * @param {Omit} [overrides] - The transaction overrides.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the transaction fails.\n */\n const method = async (overrides) => {\n return await send(overrides);\n };\n defineProperties(method, {\n _contract: contract,\n estimateGas,\n populateTransaction,\n send,\n staticCall,\n });\n return method;\n}\n/**\n * Build a wrapped method for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {string} key - The method key.\n * @returns {BaseContractMethod} The wrapped method.\n */\nfunction buildWrappedMethod(contract, key) {\n /**\n * Get the function fragment for the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {FunctionFragment} The function fragment.\n * @throws {Error} If no matching fragment is found.\n */\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 /**\n * Populate a transaction with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The populated transaction.\n * @throws {Error} If the arguments are invalid.\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 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 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 await resolveProperties({\n to: contract.getAddress(),\n from: args.pop()?.from,\n data: contract.interface.encodeFunctionData(fragment, resolvedArgs),\n });\n };\n /**\n * Perform a static call with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The result of the static call.\n * @throws {Error} If the call fails.\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 /**\n * Send a transaction with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the transaction fails.\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', {\n operation: 'sendTransaction',\n });\n const pop = await populateTransaction(...args);\n if (!pop.from && 'address' in runner && typeof runner.address === 'string') {\n pop.from = await resolveAddress(runner.address);\n }\n const tx = (await runner.sendTransaction(await pop));\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 /**\n * Estimate the gas required for a transaction with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The estimated gas.\n * @throws {Error} If the gas estimation fails.\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', {\n operation: 'estimateGas',\n });\n return await runner.estimateGas(await populateTransaction(...args));\n };\n /**\n * Perform a static call and return the result with the given arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The result of the static call.\n * @throws {Error} If the call fails.\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', {\n operation: 'call',\n });\n const tx = await populateTransaction(...args);\n if (!tx.from && 'address' in runner && typeof runner.address === 'string') {\n tx.from = await resolveAddress(runner.address);\n }\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 /**\n * Send a transaction or perform a static call based on the method arguments.\n *\n * @param {...ContractMethodArgs} args - The method arguments.\n * @returns {Promise} The result of the method call.\n * @throws {Error} If the method call fails.\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,\n _key: key,\n getFragment,\n estimateGas,\n populateTransaction,\n send,\n staticCall,\n 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}\n/**\n * Build a wrapped event for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {string} key - The event key.\n * @returns {ContractEvent} The wrapped event.\n */\nfunction buildWrappedEvent(contract, key) {\n /**\n * Get the event fragment for the given arguments.\n *\n * @param {...ContractEventArgs} args - The event arguments.\n * @returns {EventFragment} The event fragment.\n * @throws {Error} If no matching fragment is found.\n */\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 /**\n * Create a prepared topic filter for the event.\n *\n * @param {...ContractMethodArgs} args - The event arguments.\n * @returns {PreparedTopicFilter} The prepared topic filter.\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,\n _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('_quaisInternal_contract');\nconst internalValues = new WeakMap();\n/**\n * Set internal values for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {Internal} values - The internal values.\n */\nfunction setInternal(contract, values) {\n internalValues.set(contract[internal], values);\n}\n/**\n * Get internal values for a contract.\n *\n * @param {BaseContract} contract - The contract instance.\n * @returns {Internal} The internal values.\n */\nfunction getInternal(contract) {\n return internalValues.get(contract[internal]);\n}\n/**\n * Check if a value is a deferred topic filter.\n *\n * @param {any} value - The value to check.\n * @returns {value is DeferredTopicFilter} True if the value is a deferred topic filter.\n */\nfunction isDeferred(value) {\n return (value &&\n typeof value === 'object' &&\n 'getTopicFilter' in value &&\n typeof value.getTopicFilter === 'function' &&\n value.fragment);\n}\n/**\n * Get subscription information for an event.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {ContractEventName} event - The event name.\n * @returns {Promise<{ fragment: null | EventFragment; tag: string; topics: TopicFilter }>} The subscription\n * information.\n * @throws {Error} If the event name is unknown.\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 (event && '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\n .map((t) => {\n if (t == null) {\n return 'null';\n }\n if (Array.isArray(t)) {\n return t.join('|');\n }\n return t;\n })\n .join('&');\n return { fragment, tag, topics };\n}\n/**\n * Check if a contract has a subscription for an event.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {ContractEventName} event - The event name.\n * @returns {Promise} The subscription if available, otherwise null.\n */\nasync function hasSub(contract, event) {\n const { subs } = getInternal(contract);\n return subs.get((await getSubInfo(contract, event)).tag) || null;\n}\n/**\n * Get a subscription for an event.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {string} operation - The operation name.\n * @param {ContractEventName} event - The event name.\n * @returns {Promise} The subscription.\n * @throws {Error} If the contract runner does not support subscribing.\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 // eslint-disable-next-line no-empty\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 const zone = getZoneForAddress(await resolveAddress(address));\n let starting = [];\n const start = () => {\n if (starting.length) {\n return;\n }\n starting.push(provider.on(filter, listener, zone));\n };\n const stop = async () => {\n if (starting.length == 0) {\n return;\n }\n const started = starting;\n starting = [];\n await Promise.all(started);\n provider.off(filter, listener, zone);\n };\n sub = { tag, listeners: [], start, stop };\n subs.set(tag, sub);\n }\n return sub;\n}\n/**\n * We use this to ensure one emit resolves before firing the next to ensure correct ordering (note this cannot throw and\n * just adds the notice to the event queue using setTimeout).\n */\nlet lastEmit = Promise.resolve();\n/**\n * Emit an event with the given arguments and payload function.\n *\n * @ignore\n * @param {BaseContract} contract - The contract instance.\n * @param {ContractEventName} event - The event name.\n * @param {any[]} args - The arguments to pass to the listeners.\n * @param {null | PayloadFunc} payloadFunc - The payload function.\n * @returns {Promise} Resolves to true if any listeners were called.\n */\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 // eslint-disable-next-line no-empty\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}\n/**\n * Emit an event with the given arguments and payload function.\n *\n * @param {BaseContract} contract - The contract instance.\n * @param {ContractEventName} event - The event name.\n * @param {any[]} args - The arguments to pass to the listeners.\n * @param {null | PayloadFunc} payloadFunc - The payload function.\n * @returns {Promise} Resolves to true if any listeners were called.\n */\nasync function emit(contract, event, args, payloadFunc) {\n try {\n await lastEmit;\n // eslint-disable-next-line no-empty\n }\n catch (error) { }\n const resultPromise = _emit(contract, event, args, payloadFunc);\n lastEmit = resultPromise;\n return await resultPromise;\n}\nconst passProperties = ['then'];\n/**\n * Creates a new contract connected to target with the abi and optionally connected to a runner to perform operations on\n * behalf of.\n *\n * @category Contract\n */\nexport class BaseContract {\n /**\n * The target to connect to.\n *\n * This can be an address or any [Addressable](../interfaces/Addressable), such as another contract. To get the\n * resolved address, use the `getAddress` method.\n */\n target;\n /**\n * The contract Interface.\n */\n interface;\n /**\n * The connected runner. This is generally a [**Provider**](../interfaces/Provider) or a\n * [**Signer**](../interfaces/Signer), which dictates what operations are supported.\n *\n * For example, a **Contract** connected to a [**Provider**](../interfaces/Provider) may only execute read-only\n * 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 optionally connected to a `runner` to perform\n * operations on behalf of.\n *\n * @ignore\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 const subs = new Map();\n // Resolve the target as the address\n if (typeof target === 'string') {\n addr = target;\n addrPromise = Promise.resolve(target);\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 a different `runner`.\n *\n * @param {null | ContractRunner} runner - The runner to use.\n * @returns {BaseContract} The new contract instance.\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 a different `target`.\n *\n * @param {string | Addressable} target - The target to connect to.\n * @returns {BaseContract} The new contract instance.\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 * @returns {Promise} The resolved address.\n */\n async getAddress() {\n return await getInternal(this).addrPromise;\n }\n /**\n * Return the deployed bytecode or null if no bytecode is found.\n *\n * @returns {Promise} The deployed bytecode or null.\n * @throws {Error} If the runner does not support .provider.\n */\n async getDeployedCode() {\n const provider = getProvider(this.runner);\n assert(provider, 'runner does not support .provider', 'UNSUPPORTED_OPERATION', {\n operation: 'getDeployedCode',\n });\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 resolve immediately if already deployed.\n *\n * @returns {Promise} The contract instance.\n * @throws {Error} If the contract runner does not support .provider.\n */\n async waitForDeployment() {\n // We have the deployment transaction; just use that (throws if deployment 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', {\n operation: 'waitForDeployment',\n });\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 [**ContractFactor**](../classes/ContractFactory).\n *\n * @returns The transaction used to deploy this contract or `null`.\n */\n deploymentTransaction() {\n return getInternal(this).deployTx;\n }\n /**\n * Return the function for a given name. This is useful when a contract method name conflicts with a JavaScript name\n * such as `prototype` or when using a Contract programatically.\n *\n * @param {string | FunctionFragment} key - The name of the function to return.\n * @returns The function for the given name.\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 event name conflicts with a JavaScript name\n * such as `prototype` or when using a Contract programatically.\n *\n * @param {string | EventFragment} key - The name of the event to return.\n * @returns The event for the given name.\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 // TODO: implement\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async queryTransaction(hash) {\n throw new Error('@TODO');\n }\n /**\n * Provide historic access to event data for `event` in the range `fromBlock` (default: `0`) to `toBlock` (default:\n * `\"latest\"`) inclusive.\n *\n * @param {Zone} zone - The zone to query.\n * @param {ContractEventName} event - The event to query.\n * @param {BlockTag} fromBlock - The block to start querying from.\n * @param {BlockTag} toBlock - The block to stop querying at.\n * @returns An array of event logs.\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 zone = getZoneForAddress(address);\n const filter = { address, topics, fromBlock, toBlock, nodeLocation: getNodeLocationFromZone(zone) };\n const provider = getProvider(this.runner);\n assert(provider, 'contract runner does not have a provider', 'UNSUPPORTED_OPERATION', {\n operation: 'queryFilter',\n });\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 // eslint-disable-next-line no-empty\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 * @param {ContractEventName} event - The event to listen for.\n * @param {Listener} listener - The listener to call when the event is emitted.\n * @returns This contract instance.\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 after it is fired once.\n *\n * @param {ContractEventName} event - The event to listen for.\n * @param {Listener} listener - The listener to call when the event is emitted.\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 * @param {ContractEventName} event - The event to emit.\n * @param {any[]} args - The arguments to pass to the listeners.\n * @returns `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 of listeners if unspecified.\n *\n * @param {ContractEventName} event - The event to count listeners for.\n * @returns {number} The number of listeners.\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 if unspecified.\n *\n * @param {ContractEventName} event - The event to get listeners for.\n * @returns {Listener[]} The listeners.\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 all listeners if unspecified.\n *\n * @param {ContractEventName} event - The event to remove the listener from.\n * @param {Listener} listener - The listener to remove.\n * @returns This contract instance.\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 unspecified.\n *\n * @param {ContractEventName} event - The event to remove the listeners from.\n * @returns This contract instance.\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 {@link BaseContract.on | **on**}.\n *\n * @param {ContractEventName} event - The event to listen for.\n * @param {Listener} listener - The listener to call when the event is emitted.\n */\n async addListener(event, listener) {\n return await this.on(event, listener);\n }\n /**\n * Alias for {@link BaseContract.off | **off**}.\n *\n * @param {ContractEventName} event - The event to remove the listener from.\n * @param {Listener} listener - The listener to remove.\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 * @param {Interface | InterfaceAbi} abi - The ABI to create the class from.\n * @returns The 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 * Create a new BaseContract with a specified Interface.\n *\n * @param {string} target - The target to connect to.\n * @param {Interface | InterfaceAbi} abi - The ABI to use.\n * @param {null | ContractRunner} runner - The runner to use.\n * @returns The new BaseContract.\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 {@link BaseContract | **BaseContract**} with no type guards on its methods or events.\n *\n * @category Contract\n */\nexport class Contract extends _ContractBase() {\n}\n//# sourceMappingURL=contract.js.map","/**\n * Generally the [Wallet](../classes/Wallet) and [JsonRpcSigner](../classes/JsonRpcSigner) and their sub-classes are\n * sufficent for most developers, but this is provided to fascilitate more complex Signers.\n */\nimport { resolveAddress, validateAddress } from '../address/index.js';\nimport { defineProperties, getBigInt, resolveProperties, assert, assertArgument } from '../utils/index.js';\nimport { addressFromTransactionRequest, copyRequest } from '../providers/provider.js';\nimport { getTxType } from '../utils/index.js';\nimport { QuaiTransaction } from '../transaction/index.js';\nimport { toZone } from '../constants/index.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 const pop = copyRequest(tx);\n if (pop.to != null) {\n pop.to = resolveAddress(pop.to);\n validateAddress(pop.to);\n }\n if (pop.from != null) {\n const from = pop.from;\n pop.from = await Promise.all([signer.getAddress(), resolveAddress(from)]).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 = await signer.getAddress();\n }\n validateAddress(pop.from);\n return await resolveProperties(pop);\n}\n/**\n * An **AbstractSigner** includes most of teh functionality required to get a {@link Signer | **Signer**} working as\n * expected, but requires a few Signer-specific methods be overridden.\n *\n * @category Signers\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 /**\n * @ignore\n */\n _getAddress(address) {\n return resolveAddress(address);\n }\n async zoneFromAddress(_address) {\n const address = this._getAddress(_address);\n return toZone((await address).slice(0, 4));\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 populateQuaiTransaction(tx) {\n const provider = checkProvider(this, 'populateTransaction');\n const zone = await this.zoneFromAddress(tx.from);\n const pop = (await populate(this, tx));\n if (pop.type == null) {\n pop.type = await getTxType(pop.from ?? null, pop.to ?? null);\n }\n if (pop.nonce == null) {\n pop.nonce = await this.getNonce('pending');\n }\n if (pop.type == null) {\n pop.type = getTxType(pop.from ?? null, pop.to ?? null);\n }\n if (pop.gasLimit == null) {\n if (pop.type == 0)\n pop.gasLimit = await this.estimateGas(pop);\n else {\n //Special cases for type 2 tx to bypass address out of scope in the node\n const temp = pop.to;\n pop.to = '0x0000000000000000000000000000000000000000';\n pop.gasLimit = getBigInt(2 * Number(await this.estimateGas(pop)));\n pop.to = temp;\n }\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', zone);\n }\n else {\n pop.chainId = network.chainId;\n }\n if (pop.maxFeePerGas == null || pop.maxPriorityFeePerGas == null) {\n const feeData = await provider.getFeeData(zone);\n if (pop.maxFeePerGas == null) {\n pop.maxFeePerGas = feeData.maxFeePerGas;\n }\n if (pop.maxPriorityFeePerGas == null) {\n pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas || 10n;\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 sendTransaction(tx) {\n const provider = checkProvider(this, 'sendTransaction');\n const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx));\n const pop = await this.populateQuaiTransaction(tx);\n const txObj = QuaiTransaction.from(pop);\n const sender = await this.getAddress();\n const signedTx = await this.signTransaction(txObj);\n return await provider.broadcastTransaction(zone, signedTx, sender);\n }\n}\n/**\n * A **VoidSigner** is a class deisgned to allow an address to be used in any API which accepts a Signer, but for which\n * there are no credentials available to perform any actual signing.\n *\n * This for example allow impersonating an account for the purpose of static calls or estimating gas, but does not allow\n * sending transactions.\n *\n * @category Signers\n */\nexport class VoidSigner extends AbstractSigner {\n /**\n * The signer address.\n */\n address;\n /**\n * Creates a new **VoidSigner** with `address` attached to `provider`.\n */\n constructor(address, provider) {\n super(provider);\n defineProperties(this, { address });\n }\n async getAddress() {\n return this.address;\n }\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 // TODO: `domain`, `types` and `value` are not used, remove?\n // TODO: this function only throws, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async signTransaction(tx) {\n this.#throwUnsupported('transactions', 'signTransaction');\n }\n // TODO: `domain`, `types` and `value` are not used, remove?\n // TODO: this function only throws, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async signMessage(message) {\n this.#throwUnsupported('messages', 'signMessage');\n }\n // TODO: `domain`, `types` and `value` are not used, remove?\n // TODO: this function only throws, remove?\n async signTypedData(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n domain, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n types, \n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n value) {\n this.#throwUnsupported('typed-data', 'signTypedData');\n }\n}\n//# sourceMappingURL=abstract-signer.js.map","import { getAddress, computeAddress, resolveAddress, validateAddress } from '../address/index.js';\nimport { hashMessage, TypedDataEncoder } from '../hash/index.js';\nimport { AbstractSigner } from '../signers/index.js';\nimport { resolveProperties, assertArgument } from '../utils/index.js';\nimport { QuaiTransaction } from '../transaction/quai-transaction.js';\nimport { keccak256 } from '../crypto/index.js';\n/**\n * The **BaseWallet** is a stream-lined implementation of a {@link AbstractSigner} that operates with a private\n * key.\n *\n * It is preferred to use the {@link Wallet} class, as it offers additional functionality and simplifies\n * loading a variety of JSON formats, Mnemonic Phrases, etc.\n *\n * This class may be of use for those attempting to implement a minimal Signer.\n *\n * @category Wallet\n */\nexport class BaseWallet extends AbstractSigner {\n /**\n * The wallet address.\n * @type {string}\n * @readonly\n */\n #address;\n /**\n * The signing key used for signing payloads.\n * @type {SigningKey}\n * @readonly\n */\n #signingKey;\n /**\n * Creates a new BaseWallet for `privateKey`, optionally connected to `provider`.\n *\n * If `provider` is not specified, only offline methods can be used.\n *\n * @param {SigningKey} privateKey - The private key for the wallet.\n * @param {null | Provider} [provider] - The provider to connect to.\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 this.#address = computeAddress(this.signingKey.publicKey);\n }\n // Store private values behind getters to reduce visibility\n /**\n * The address of this wallet.\n * @type {string}\n * @readonly\n */\n get address() {\n return this.#address;\n }\n /**\n * The {@link SigningKey | **SigningKey**} used for signing payloads.\n * @type {SigningKey}\n * @readonly\n */\n get signingKey() {\n return this.#signingKey;\n }\n /**\n * The private key for this wallet.\n * @type {string}\n * @readonly\n */\n get privateKey() {\n return this.signingKey.privateKey;\n }\n // TODO: `_zone` is not used, should it be removed?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n /**\n * Returns the address of this wallet.\n *\n * @param {string} [_zone] - The zone (optional).\n * @returns {Promise} The wallet address.\n */\n async getAddress(_zone) {\n return this.#address;\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {null | Provider} provider - The provider to connect to.\n * @returns {BaseWallet} The connected wallet.\n */\n connect(provider) {\n return new BaseWallet(this.#signingKey, provider);\n }\n /**\n * Signs a transaction.\n *\n * @param {QuaiTransactionRequest} tx - The transaction request.\n * @returns {Promise} The signed transaction.\n */\n async signTransaction(tx) {\n // Replace any Addressable with an address\n const { to, from } = await resolveProperties({\n to: tx.to ? resolveAddress(tx.to) : undefined,\n from: tx.from ? resolveAddress(tx.from) : undefined,\n });\n if (to !== undefined) {\n validateAddress(to);\n tx.to = to;\n }\n if (from !== undefined) {\n assertArgument(getAddress(from) === this.#address, 'transaction from address mismatch', 'tx.from', from);\n }\n else {\n // No `from` specified, use the wallet's address\n tx.from = this.#address;\n }\n const btx = QuaiTransaction.from(tx);\n const digest = keccak256(btx.unsignedSerialized);\n btx.signature = this.signingKey.sign(digest);\n return btx.serialized;\n }\n /**\n * Signs a message.\n *\n * @param {string | Uint8Array} message - The message to sign.\n * @returns {Promise} The signed message.\n * @async\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 * @param {string | Uint8Array} message - The message to sign.\n * @returns {string} The serialized signature.\n */\n signMessageSync(message) {\n return this.signingKey.sign(hashMessage(message)).serialized;\n }\n /**\n * Signs typed data.\n *\n * @param {TypedDataDomain} domain - The domain of the typed data.\n * @param {Record>} types - The types of the typed data.\n * @param {Record} value - The value of the typed data.\n * @returns {Promise} The signed typed data.\n * @async\n */\n async signTypedData(domain, types, value) {\n return this.signingKey.sign(TypedDataEncoder.hash(domain, types, 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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 words used to encode and devoce\n * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) encoded data by mapping words to 11-bit values and vice versa.\n *\n * @category Wordlists\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, passing in the locale string of the language.\n *\n * Generally there is no need to create instances of a Wordlist, since each language-specific Wordlist creates an\n * instance and 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 method for spliting `phrase` into individual words.\n *\n * By default, `phrase` is split using any sequences of white-space as defined by regular expressions (i.e.\n * `/\\s+/`).\n *\n * @param {string} phrase - The phrase to split.\n *\n * @returns {string[]} The split words in the phrase.\n */\n split(phrase) {\n return phrase.toLowerCase().split(/\\s+/g);\n }\n /**\n * Sub-classes may override this to provider a language-specific method for joining `words` into a phrase.\n *\n * By default, `words` are joined by a single space.\n *\n * @param {string[]} words - The words to join.\n *\n * @returns {string} The joined phrase.\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 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 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 to create the necessary data.\n *\n * @category Wordlists\n */\nexport class WordlistOwl extends Wordlist {\n #data;\n #checksum;\n /**\n * Creates a new Wordlist for `locale` using the OWL `data` 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 * @ignore\n */\n get _data() {\n return this.#data;\n }\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_{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 M3AgramAlAm#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/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-PM&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryFN Noc|PutQuirySSue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+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)IdeIghtImOgAyEakEelEmEpE*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~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO\";\nconst checksum = '0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60';\nlet wordlist = null;\n/**\n * The [English wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt) for [mnemonic\n * phrases](https://en.bitcoin.it/wiki/BIP_0039).\n *\n * @category 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 {@link langEn} should suffice.\n *\n * @ignore\n */\n constructor() {\n super('en', words, checksum);\n }\n /**\n * Returns a singleton instance of a `LangEn`, creating it 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, } from '../utils/index.js';\nimport { toUtf8Bytes } from '../encoding/index.js';\nimport { LangEn } from '../wordlists/lang-en.js';\n/**\n * Returns a byte with the MSB bits set.\n *\n * @param {number} bits - The number of bits to set.\n * @returns {number} The byte with the MSB bits set.\n */\nfunction getUpperMask(bits) {\n return (((1 << bits) - 1) << (8 - bits)) & 0xff;\n}\n/**\n * Returns a byte with the LSB bits set.\n *\n * @param {number} bits - The number of bits to set.\n * @returns {number} The byte with the LSB bits set.\n */\nfunction getLowerMask(bits) {\n return ((1 << bits) - 1) & 0xff;\n}\n/**\n * Converts a mnemonic phrase to entropy.\n *\n * @param {string} mnemonic - The mnemonic phrase.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {string} The entropy.\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 const 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}\n/**\n * Converts entropy to a mnemonic phrase.\n *\n * @param {Uint8Array} entropy - The entropy.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {string} The mnemonic phrase.\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 [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) seeds and\n * convert between phrases and entropy.\n *\n * @category Wallet\n */\nexport class Mnemonic {\n /**\n * The mnemonic phrase of 12, 15, 18, 21 or 24 words.\n *\n * Use the {@link wordlist | **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 is the empty string (i.e. `\"\"`) as per the\n * 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 * @param {any} guard - The guard object.\n * @param {string} entropy - The entropy.\n * @param {string} phrase - The mnemonic phrase.\n * @param {string} [password] - The password for the mnemonic.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\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 * @returns {string} The seed.\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 wordlist is the {@link LangEn | **English wordlist**}.\n *\n * @param {string} phrase - The mnemonic phrase.\n * @param {string} [password] - The password for the mnemonic.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {Mnemonic} The new Mnemonic object.\n */\n static fromPhrase(phrase, password, wordlist) {\n // Normalize the case and space; throws if invalid\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n if (password == null) {\n password = '';\n }\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 wordlist is the [{@link LangEn | **English wordlist**}.\n *\n * @param {BytesLike} _entropy - The entropy for the mnemonic.\n * @param {string} [password] - The password for the mnemonic.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {Mnemonic} The new Mnemonic object.\n */\n static fromEntropy(_entropy, password, wordlist) {\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n if (password == null) {\n password = '';\n }\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 * @param {BytesLike} _entropy - The entropy for the mnemonic.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {string} The mnemonic phrase.\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 * @param {string} phrase - The mnemonic phrase.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {string} The entropy.\n */\n static phraseToEntropy(phrase, wordlist) {\n return mnemonicToEntropy(phrase, wordlist);\n }\n /**\n * Returns true if `phrase` is a valid [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) phrase.\n *\n * This checks all the provided words belong to the `wordlist`, that the length is valid and the checksum is\n * correct.\n *\n * @param {string} phrase - The mnemonic phrase.\n * @param {Wordlist} [wordlist] - The wordlist for the mnemonic.\n * @returns {boolean} True if the phrase is valid.\n * @throws {Error} If the phrase is invalid.\n */\n static isValidMnemonic(phrase, wordlist) {\n try {\n mnemonicToEntropy(phrase, wordlist);\n return true;\n // eslint-disable-next-line no-empty\n }\n catch (error) { }\n return false;\n }\n}\n//# sourceMappingURL=mnemonic.js.map","/*! MIT License. Copyright 2015-2022 Richard Moore . See LICENSE.txt. */\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _AES_key, _AES_Kd, _AES_Ke;\n// Number of rounds by keysize\nconst numberOfRounds = { 16: 10, 24: 12, 32: 14 };\n// Round constant words\nconst rcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91];\n// S-box and Inverse S-box (S is for Substitution)\nconst S = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16];\nconst Si = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d];\n// Transformations for encryption\nconst T1 = [0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a];\nconst T2 = [0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616];\nconst T3 = [0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16];\nconst T4 = [0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c];\n// Transformations for decryption\nconst T5 = [0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742];\nconst T6 = [0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857];\nconst T7 = [0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8];\nconst T8 = [0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0];\n// Transformations for decryption key expansion\nconst U1 = [0x00000000, 0x0e090d0b, 0x1c121a16, 0x121b171d, 0x3824342c, 0x362d3927, 0x24362e3a, 0x2a3f2331, 0x70486858, 0x7e416553, 0x6c5a724e, 0x62537f45, 0x486c5c74, 0x4665517f, 0x547e4662, 0x5a774b69, 0xe090d0b0, 0xee99ddbb, 0xfc82caa6, 0xf28bc7ad, 0xd8b4e49c, 0xd6bde997, 0xc4a6fe8a, 0xcaaff381, 0x90d8b8e8, 0x9ed1b5e3, 0x8ccaa2fe, 0x82c3aff5, 0xa8fc8cc4, 0xa6f581cf, 0xb4ee96d2, 0xbae79bd9, 0xdb3bbb7b, 0xd532b670, 0xc729a16d, 0xc920ac66, 0xe31f8f57, 0xed16825c, 0xff0d9541, 0xf104984a, 0xab73d323, 0xa57ade28, 0xb761c935, 0xb968c43e, 0x9357e70f, 0x9d5eea04, 0x8f45fd19, 0x814cf012, 0x3bab6bcb, 0x35a266c0, 0x27b971dd, 0x29b07cd6, 0x038f5fe7, 0x0d8652ec, 0x1f9d45f1, 0x119448fa, 0x4be30393, 0x45ea0e98, 0x57f11985, 0x59f8148e, 0x73c737bf, 0x7dce3ab4, 0x6fd52da9, 0x61dc20a2, 0xad766df6, 0xa37f60fd, 0xb16477e0, 0xbf6d7aeb, 0x955259da, 0x9b5b54d1, 0x894043cc, 0x87494ec7, 0xdd3e05ae, 0xd33708a5, 0xc12c1fb8, 0xcf2512b3, 0xe51a3182, 0xeb133c89, 0xf9082b94, 0xf701269f, 0x4de6bd46, 0x43efb04d, 0x51f4a750, 0x5ffdaa5b, 0x75c2896a, 0x7bcb8461, 0x69d0937c, 0x67d99e77, 0x3daed51e, 0x33a7d815, 0x21bccf08, 0x2fb5c203, 0x058ae132, 0x0b83ec39, 0x1998fb24, 0x1791f62f, 0x764dd68d, 0x7844db86, 0x6a5fcc9b, 0x6456c190, 0x4e69e2a1, 0x4060efaa, 0x527bf8b7, 0x5c72f5bc, 0x0605bed5, 0x080cb3de, 0x1a17a4c3, 0x141ea9c8, 0x3e218af9, 0x302887f2, 0x223390ef, 0x2c3a9de4, 0x96dd063d, 0x98d40b36, 0x8acf1c2b, 0x84c61120, 0xaef93211, 0xa0f03f1a, 0xb2eb2807, 0xbce2250c, 0xe6956e65, 0xe89c636e, 0xfa877473, 0xf48e7978, 0xdeb15a49, 0xd0b85742, 0xc2a3405f, 0xccaa4d54, 0x41ecdaf7, 0x4fe5d7fc, 0x5dfec0e1, 0x53f7cdea, 0x79c8eedb, 0x77c1e3d0, 0x65daf4cd, 0x6bd3f9c6, 0x31a4b2af, 0x3fadbfa4, 0x2db6a8b9, 0x23bfa5b2, 0x09808683, 0x07898b88, 0x15929c95, 0x1b9b919e, 0xa17c0a47, 0xaf75074c, 0xbd6e1051, 0xb3671d5a, 0x99583e6b, 0x97513360, 0x854a247d, 0x8b432976, 0xd134621f, 0xdf3d6f14, 0xcd267809, 0xc32f7502, 0xe9105633, 0xe7195b38, 0xf5024c25, 0xfb0b412e, 0x9ad7618c, 0x94de6c87, 0x86c57b9a, 0x88cc7691, 0xa2f355a0, 0xacfa58ab, 0xbee14fb6, 0xb0e842bd, 0xea9f09d4, 0xe49604df, 0xf68d13c2, 0xf8841ec9, 0xd2bb3df8, 0xdcb230f3, 0xcea927ee, 0xc0a02ae5, 0x7a47b13c, 0x744ebc37, 0x6655ab2a, 0x685ca621, 0x42638510, 0x4c6a881b, 0x5e719f06, 0x5078920d, 0x0a0fd964, 0x0406d46f, 0x161dc372, 0x1814ce79, 0x322bed48, 0x3c22e043, 0x2e39f75e, 0x2030fa55, 0xec9ab701, 0xe293ba0a, 0xf088ad17, 0xfe81a01c, 0xd4be832d, 0xdab78e26, 0xc8ac993b, 0xc6a59430, 0x9cd2df59, 0x92dbd252, 0x80c0c54f, 0x8ec9c844, 0xa4f6eb75, 0xaaffe67e, 0xb8e4f163, 0xb6edfc68, 0x0c0a67b1, 0x02036aba, 0x10187da7, 0x1e1170ac, 0x342e539d, 0x3a275e96, 0x283c498b, 0x26354480, 0x7c420fe9, 0x724b02e2, 0x605015ff, 0x6e5918f4, 0x44663bc5, 0x4a6f36ce, 0x587421d3, 0x567d2cd8, 0x37a10c7a, 0x39a80171, 0x2bb3166c, 0x25ba1b67, 0x0f853856, 0x018c355d, 0x13972240, 0x1d9e2f4b, 0x47e96422, 0x49e06929, 0x5bfb7e34, 0x55f2733f, 0x7fcd500e, 0x71c45d05, 0x63df4a18, 0x6dd64713, 0xd731dcca, 0xd938d1c1, 0xcb23c6dc, 0xc52acbd7, 0xef15e8e6, 0xe11ce5ed, 0xf307f2f0, 0xfd0efffb, 0xa779b492, 0xa970b999, 0xbb6bae84, 0xb562a38f, 0x9f5d80be, 0x91548db5, 0x834f9aa8, 0x8d4697a3];\nconst U2 = [0x00000000, 0x0b0e090d, 0x161c121a, 0x1d121b17, 0x2c382434, 0x27362d39, 0x3a24362e, 0x312a3f23, 0x58704868, 0x537e4165, 0x4e6c5a72, 0x4562537f, 0x74486c5c, 0x7f466551, 0x62547e46, 0x695a774b, 0xb0e090d0, 0xbbee99dd, 0xa6fc82ca, 0xadf28bc7, 0x9cd8b4e4, 0x97d6bde9, 0x8ac4a6fe, 0x81caaff3, 0xe890d8b8, 0xe39ed1b5, 0xfe8ccaa2, 0xf582c3af, 0xc4a8fc8c, 0xcfa6f581, 0xd2b4ee96, 0xd9bae79b, 0x7bdb3bbb, 0x70d532b6, 0x6dc729a1, 0x66c920ac, 0x57e31f8f, 0x5ced1682, 0x41ff0d95, 0x4af10498, 0x23ab73d3, 0x28a57ade, 0x35b761c9, 0x3eb968c4, 0x0f9357e7, 0x049d5eea, 0x198f45fd, 0x12814cf0, 0xcb3bab6b, 0xc035a266, 0xdd27b971, 0xd629b07c, 0xe7038f5f, 0xec0d8652, 0xf11f9d45, 0xfa119448, 0x934be303, 0x9845ea0e, 0x8557f119, 0x8e59f814, 0xbf73c737, 0xb47dce3a, 0xa96fd52d, 0xa261dc20, 0xf6ad766d, 0xfda37f60, 0xe0b16477, 0xebbf6d7a, 0xda955259, 0xd19b5b54, 0xcc894043, 0xc787494e, 0xaedd3e05, 0xa5d33708, 0xb8c12c1f, 0xb3cf2512, 0x82e51a31, 0x89eb133c, 0x94f9082b, 0x9ff70126, 0x464de6bd, 0x4d43efb0, 0x5051f4a7, 0x5b5ffdaa, 0x6a75c289, 0x617bcb84, 0x7c69d093, 0x7767d99e, 0x1e3daed5, 0x1533a7d8, 0x0821bccf, 0x032fb5c2, 0x32058ae1, 0x390b83ec, 0x241998fb, 0x2f1791f6, 0x8d764dd6, 0x867844db, 0x9b6a5fcc, 0x906456c1, 0xa14e69e2, 0xaa4060ef, 0xb7527bf8, 0xbc5c72f5, 0xd50605be, 0xde080cb3, 0xc31a17a4, 0xc8141ea9, 0xf93e218a, 0xf2302887, 0xef223390, 0xe42c3a9d, 0x3d96dd06, 0x3698d40b, 0x2b8acf1c, 0x2084c611, 0x11aef932, 0x1aa0f03f, 0x07b2eb28, 0x0cbce225, 0x65e6956e, 0x6ee89c63, 0x73fa8774, 0x78f48e79, 0x49deb15a, 0x42d0b857, 0x5fc2a340, 0x54ccaa4d, 0xf741ecda, 0xfc4fe5d7, 0xe15dfec0, 0xea53f7cd, 0xdb79c8ee, 0xd077c1e3, 0xcd65daf4, 0xc66bd3f9, 0xaf31a4b2, 0xa43fadbf, 0xb92db6a8, 0xb223bfa5, 0x83098086, 0x8807898b, 0x9515929c, 0x9e1b9b91, 0x47a17c0a, 0x4caf7507, 0x51bd6e10, 0x5ab3671d, 0x6b99583e, 0x60975133, 0x7d854a24, 0x768b4329, 0x1fd13462, 0x14df3d6f, 0x09cd2678, 0x02c32f75, 0x33e91056, 0x38e7195b, 0x25f5024c, 0x2efb0b41, 0x8c9ad761, 0x8794de6c, 0x9a86c57b, 0x9188cc76, 0xa0a2f355, 0xabacfa58, 0xb6bee14f, 0xbdb0e842, 0xd4ea9f09, 0xdfe49604, 0xc2f68d13, 0xc9f8841e, 0xf8d2bb3d, 0xf3dcb230, 0xeecea927, 0xe5c0a02a, 0x3c7a47b1, 0x37744ebc, 0x2a6655ab, 0x21685ca6, 0x10426385, 0x1b4c6a88, 0x065e719f, 0x0d507892, 0x640a0fd9, 0x6f0406d4, 0x72161dc3, 0x791814ce, 0x48322bed, 0x433c22e0, 0x5e2e39f7, 0x552030fa, 0x01ec9ab7, 0x0ae293ba, 0x17f088ad, 0x1cfe81a0, 0x2dd4be83, 0x26dab78e, 0x3bc8ac99, 0x30c6a594, 0x599cd2df, 0x5292dbd2, 0x4f80c0c5, 0x448ec9c8, 0x75a4f6eb, 0x7eaaffe6, 0x63b8e4f1, 0x68b6edfc, 0xb10c0a67, 0xba02036a, 0xa710187d, 0xac1e1170, 0x9d342e53, 0x963a275e, 0x8b283c49, 0x80263544, 0xe97c420f, 0xe2724b02, 0xff605015, 0xf46e5918, 0xc544663b, 0xce4a6f36, 0xd3587421, 0xd8567d2c, 0x7a37a10c, 0x7139a801, 0x6c2bb316, 0x6725ba1b, 0x560f8538, 0x5d018c35, 0x40139722, 0x4b1d9e2f, 0x2247e964, 0x2949e069, 0x345bfb7e, 0x3f55f273, 0x0e7fcd50, 0x0571c45d, 0x1863df4a, 0x136dd647, 0xcad731dc, 0xc1d938d1, 0xdccb23c6, 0xd7c52acb, 0xe6ef15e8, 0xede11ce5, 0xf0f307f2, 0xfbfd0eff, 0x92a779b4, 0x99a970b9, 0x84bb6bae, 0x8fb562a3, 0xbe9f5d80, 0xb591548d, 0xa8834f9a, 0xa38d4697];\nconst U3 = [0x00000000, 0x0d0b0e09, 0x1a161c12, 0x171d121b, 0x342c3824, 0x3927362d, 0x2e3a2436, 0x23312a3f, 0x68587048, 0x65537e41, 0x724e6c5a, 0x7f456253, 0x5c74486c, 0x517f4665, 0x4662547e, 0x4b695a77, 0xd0b0e090, 0xddbbee99, 0xcaa6fc82, 0xc7adf28b, 0xe49cd8b4, 0xe997d6bd, 0xfe8ac4a6, 0xf381caaf, 0xb8e890d8, 0xb5e39ed1, 0xa2fe8cca, 0xaff582c3, 0x8cc4a8fc, 0x81cfa6f5, 0x96d2b4ee, 0x9bd9bae7, 0xbb7bdb3b, 0xb670d532, 0xa16dc729, 0xac66c920, 0x8f57e31f, 0x825ced16, 0x9541ff0d, 0x984af104, 0xd323ab73, 0xde28a57a, 0xc935b761, 0xc43eb968, 0xe70f9357, 0xea049d5e, 0xfd198f45, 0xf012814c, 0x6bcb3bab, 0x66c035a2, 0x71dd27b9, 0x7cd629b0, 0x5fe7038f, 0x52ec0d86, 0x45f11f9d, 0x48fa1194, 0x03934be3, 0x0e9845ea, 0x198557f1, 0x148e59f8, 0x37bf73c7, 0x3ab47dce, 0x2da96fd5, 0x20a261dc, 0x6df6ad76, 0x60fda37f, 0x77e0b164, 0x7aebbf6d, 0x59da9552, 0x54d19b5b, 0x43cc8940, 0x4ec78749, 0x05aedd3e, 0x08a5d337, 0x1fb8c12c, 0x12b3cf25, 0x3182e51a, 0x3c89eb13, 0x2b94f908, 0x269ff701, 0xbd464de6, 0xb04d43ef, 0xa75051f4, 0xaa5b5ffd, 0x896a75c2, 0x84617bcb, 0x937c69d0, 0x9e7767d9, 0xd51e3dae, 0xd81533a7, 0xcf0821bc, 0xc2032fb5, 0xe132058a, 0xec390b83, 0xfb241998, 0xf62f1791, 0xd68d764d, 0xdb867844, 0xcc9b6a5f, 0xc1906456, 0xe2a14e69, 0xefaa4060, 0xf8b7527b, 0xf5bc5c72, 0xbed50605, 0xb3de080c, 0xa4c31a17, 0xa9c8141e, 0x8af93e21, 0x87f23028, 0x90ef2233, 0x9de42c3a, 0x063d96dd, 0x0b3698d4, 0x1c2b8acf, 0x112084c6, 0x3211aef9, 0x3f1aa0f0, 0x2807b2eb, 0x250cbce2, 0x6e65e695, 0x636ee89c, 0x7473fa87, 0x7978f48e, 0x5a49deb1, 0x5742d0b8, 0x405fc2a3, 0x4d54ccaa, 0xdaf741ec, 0xd7fc4fe5, 0xc0e15dfe, 0xcdea53f7, 0xeedb79c8, 0xe3d077c1, 0xf4cd65da, 0xf9c66bd3, 0xb2af31a4, 0xbfa43fad, 0xa8b92db6, 0xa5b223bf, 0x86830980, 0x8b880789, 0x9c951592, 0x919e1b9b, 0x0a47a17c, 0x074caf75, 0x1051bd6e, 0x1d5ab367, 0x3e6b9958, 0x33609751, 0x247d854a, 0x29768b43, 0x621fd134, 0x6f14df3d, 0x7809cd26, 0x7502c32f, 0x5633e910, 0x5b38e719, 0x4c25f502, 0x412efb0b, 0x618c9ad7, 0x6c8794de, 0x7b9a86c5, 0x769188cc, 0x55a0a2f3, 0x58abacfa, 0x4fb6bee1, 0x42bdb0e8, 0x09d4ea9f, 0x04dfe496, 0x13c2f68d, 0x1ec9f884, 0x3df8d2bb, 0x30f3dcb2, 0x27eecea9, 0x2ae5c0a0, 0xb13c7a47, 0xbc37744e, 0xab2a6655, 0xa621685c, 0x85104263, 0x881b4c6a, 0x9f065e71, 0x920d5078, 0xd9640a0f, 0xd46f0406, 0xc372161d, 0xce791814, 0xed48322b, 0xe0433c22, 0xf75e2e39, 0xfa552030, 0xb701ec9a, 0xba0ae293, 0xad17f088, 0xa01cfe81, 0x832dd4be, 0x8e26dab7, 0x993bc8ac, 0x9430c6a5, 0xdf599cd2, 0xd25292db, 0xc54f80c0, 0xc8448ec9, 0xeb75a4f6, 0xe67eaaff, 0xf163b8e4, 0xfc68b6ed, 0x67b10c0a, 0x6aba0203, 0x7da71018, 0x70ac1e11, 0x539d342e, 0x5e963a27, 0x498b283c, 0x44802635, 0x0fe97c42, 0x02e2724b, 0x15ff6050, 0x18f46e59, 0x3bc54466, 0x36ce4a6f, 0x21d35874, 0x2cd8567d, 0x0c7a37a1, 0x017139a8, 0x166c2bb3, 0x1b6725ba, 0x38560f85, 0x355d018c, 0x22401397, 0x2f4b1d9e, 0x642247e9, 0x692949e0, 0x7e345bfb, 0x733f55f2, 0x500e7fcd, 0x5d0571c4, 0x4a1863df, 0x47136dd6, 0xdccad731, 0xd1c1d938, 0xc6dccb23, 0xcbd7c52a, 0xe8e6ef15, 0xe5ede11c, 0xf2f0f307, 0xfffbfd0e, 0xb492a779, 0xb999a970, 0xae84bb6b, 0xa38fb562, 0x80be9f5d, 0x8db59154, 0x9aa8834f, 0x97a38d46];\nconst U4 = [0x00000000, 0x090d0b0e, 0x121a161c, 0x1b171d12, 0x24342c38, 0x2d392736, 0x362e3a24, 0x3f23312a, 0x48685870, 0x4165537e, 0x5a724e6c, 0x537f4562, 0x6c5c7448, 0x65517f46, 0x7e466254, 0x774b695a, 0x90d0b0e0, 0x99ddbbee, 0x82caa6fc, 0x8bc7adf2, 0xb4e49cd8, 0xbde997d6, 0xa6fe8ac4, 0xaff381ca, 0xd8b8e890, 0xd1b5e39e, 0xcaa2fe8c, 0xc3aff582, 0xfc8cc4a8, 0xf581cfa6, 0xee96d2b4, 0xe79bd9ba, 0x3bbb7bdb, 0x32b670d5, 0x29a16dc7, 0x20ac66c9, 0x1f8f57e3, 0x16825ced, 0x0d9541ff, 0x04984af1, 0x73d323ab, 0x7ade28a5, 0x61c935b7, 0x68c43eb9, 0x57e70f93, 0x5eea049d, 0x45fd198f, 0x4cf01281, 0xab6bcb3b, 0xa266c035, 0xb971dd27, 0xb07cd629, 0x8f5fe703, 0x8652ec0d, 0x9d45f11f, 0x9448fa11, 0xe303934b, 0xea0e9845, 0xf1198557, 0xf8148e59, 0xc737bf73, 0xce3ab47d, 0xd52da96f, 0xdc20a261, 0x766df6ad, 0x7f60fda3, 0x6477e0b1, 0x6d7aebbf, 0x5259da95, 0x5b54d19b, 0x4043cc89, 0x494ec787, 0x3e05aedd, 0x3708a5d3, 0x2c1fb8c1, 0x2512b3cf, 0x1a3182e5, 0x133c89eb, 0x082b94f9, 0x01269ff7, 0xe6bd464d, 0xefb04d43, 0xf4a75051, 0xfdaa5b5f, 0xc2896a75, 0xcb84617b, 0xd0937c69, 0xd99e7767, 0xaed51e3d, 0xa7d81533, 0xbccf0821, 0xb5c2032f, 0x8ae13205, 0x83ec390b, 0x98fb2419, 0x91f62f17, 0x4dd68d76, 0x44db8678, 0x5fcc9b6a, 0x56c19064, 0x69e2a14e, 0x60efaa40, 0x7bf8b752, 0x72f5bc5c, 0x05bed506, 0x0cb3de08, 0x17a4c31a, 0x1ea9c814, 0x218af93e, 0x2887f230, 0x3390ef22, 0x3a9de42c, 0xdd063d96, 0xd40b3698, 0xcf1c2b8a, 0xc6112084, 0xf93211ae, 0xf03f1aa0, 0xeb2807b2, 0xe2250cbc, 0x956e65e6, 0x9c636ee8, 0x877473fa, 0x8e7978f4, 0xb15a49de, 0xb85742d0, 0xa3405fc2, 0xaa4d54cc, 0xecdaf741, 0xe5d7fc4f, 0xfec0e15d, 0xf7cdea53, 0xc8eedb79, 0xc1e3d077, 0xdaf4cd65, 0xd3f9c66b, 0xa4b2af31, 0xadbfa43f, 0xb6a8b92d, 0xbfa5b223, 0x80868309, 0x898b8807, 0x929c9515, 0x9b919e1b, 0x7c0a47a1, 0x75074caf, 0x6e1051bd, 0x671d5ab3, 0x583e6b99, 0x51336097, 0x4a247d85, 0x4329768b, 0x34621fd1, 0x3d6f14df, 0x267809cd, 0x2f7502c3, 0x105633e9, 0x195b38e7, 0x024c25f5, 0x0b412efb, 0xd7618c9a, 0xde6c8794, 0xc57b9a86, 0xcc769188, 0xf355a0a2, 0xfa58abac, 0xe14fb6be, 0xe842bdb0, 0x9f09d4ea, 0x9604dfe4, 0x8d13c2f6, 0x841ec9f8, 0xbb3df8d2, 0xb230f3dc, 0xa927eece, 0xa02ae5c0, 0x47b13c7a, 0x4ebc3774, 0x55ab2a66, 0x5ca62168, 0x63851042, 0x6a881b4c, 0x719f065e, 0x78920d50, 0x0fd9640a, 0x06d46f04, 0x1dc37216, 0x14ce7918, 0x2bed4832, 0x22e0433c, 0x39f75e2e, 0x30fa5520, 0x9ab701ec, 0x93ba0ae2, 0x88ad17f0, 0x81a01cfe, 0xbe832dd4, 0xb78e26da, 0xac993bc8, 0xa59430c6, 0xd2df599c, 0xdbd25292, 0xc0c54f80, 0xc9c8448e, 0xf6eb75a4, 0xffe67eaa, 0xe4f163b8, 0xedfc68b6, 0x0a67b10c, 0x036aba02, 0x187da710, 0x1170ac1e, 0x2e539d34, 0x275e963a, 0x3c498b28, 0x35448026, 0x420fe97c, 0x4b02e272, 0x5015ff60, 0x5918f46e, 0x663bc544, 0x6f36ce4a, 0x7421d358, 0x7d2cd856, 0xa10c7a37, 0xa8017139, 0xb3166c2b, 0xba1b6725, 0x8538560f, 0x8c355d01, 0x97224013, 0x9e2f4b1d, 0xe9642247, 0xe0692949, 0xfb7e345b, 0xf2733f55, 0xcd500e7f, 0xc45d0571, 0xdf4a1863, 0xd647136d, 0x31dccad7, 0x38d1c1d9, 0x23c6dccb, 0x2acbd7c5, 0x15e8e6ef, 0x1ce5ede1, 0x07f2f0f3, 0x0efffbfd, 0x79b492a7, 0x70b999a9, 0x6bae84bb, 0x62a38fb5, 0x5d80be9f, 0x548db591, 0x4f9aa883, 0x4697a38d];\nfunction convertToInt32(bytes) {\n const result = [];\n for (let i = 0; i < bytes.length; i += 4) {\n result.push((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]);\n }\n return result;\n}\nexport class AES {\n get key() { return __classPrivateFieldGet(this, _AES_key, \"f\").slice(); }\n constructor(key) {\n _AES_key.set(this, void 0);\n _AES_Kd.set(this, void 0);\n _AES_Ke.set(this, void 0);\n if (!(this instanceof AES)) {\n throw Error('AES must be instanitated with `new`');\n }\n __classPrivateFieldSet(this, _AES_key, new Uint8Array(key), \"f\");\n const rounds = numberOfRounds[this.key.length];\n if (rounds == null) {\n throw new TypeError('invalid key size (must be 16, 24 or 32 bytes)');\n }\n // encryption round keys\n __classPrivateFieldSet(this, _AES_Ke, [], \"f\");\n // decryption round keys\n __classPrivateFieldSet(this, _AES_Kd, [], \"f\");\n for (let i = 0; i <= rounds; i++) {\n __classPrivateFieldGet(this, _AES_Ke, \"f\").push([0, 0, 0, 0]);\n __classPrivateFieldGet(this, _AES_Kd, \"f\").push([0, 0, 0, 0]);\n }\n const roundKeyCount = (rounds + 1) * 4;\n const KC = this.key.length / 4;\n // convert the key into ints\n const tk = convertToInt32(this.key);\n // copy values into round key arrays\n let index;\n for (let i = 0; i < KC; i++) {\n index = i >> 2;\n __classPrivateFieldGet(this, _AES_Ke, \"f\")[index][i % 4] = tk[i];\n __classPrivateFieldGet(this, _AES_Kd, \"f\")[rounds - index][i % 4] = tk[i];\n }\n // key expansion (fips-197 section 5.2)\n let rconpointer = 0;\n let t = KC, tt;\n while (t < roundKeyCount) {\n tt = tk[KC - 1];\n tk[0] ^= ((S[(tt >> 16) & 0xFF] << 24) ^\n (S[(tt >> 8) & 0xFF] << 16) ^\n (S[tt & 0xFF] << 8) ^\n S[(tt >> 24) & 0xFF] ^\n (rcon[rconpointer] << 24));\n rconpointer += 1;\n // key expansion (for non-256 bit)\n if (KC != 8) {\n for (let i = 1; i < KC; i++) {\n tk[i] ^= tk[i - 1];\n }\n // key expansion for 256-bit keys is \"slightly different\" (fips-197)\n }\n else {\n for (let i = 1; i < (KC / 2); i++) {\n tk[i] ^= tk[i - 1];\n }\n tt = tk[(KC / 2) - 1];\n tk[KC / 2] ^= (S[tt & 0xFF] ^\n (S[(tt >> 8) & 0xFF] << 8) ^\n (S[(tt >> 16) & 0xFF] << 16) ^\n (S[(tt >> 24) & 0xFF] << 24));\n for (let i = (KC / 2) + 1; i < KC; i++) {\n tk[i] ^= tk[i - 1];\n }\n }\n // copy values into round key arrays\n let i = 0, r, c;\n while (i < KC && t < roundKeyCount) {\n r = t >> 2;\n c = t % 4;\n __classPrivateFieldGet(this, _AES_Ke, \"f\")[r][c] = tk[i];\n __classPrivateFieldGet(this, _AES_Kd, \"f\")[rounds - r][c] = tk[i++];\n t++;\n }\n }\n // inverse-cipher-ify the decryption round key (fips-197 section 5.3)\n for (let r = 1; r < rounds; r++) {\n for (let c = 0; c < 4; c++) {\n tt = __classPrivateFieldGet(this, _AES_Kd, \"f\")[r][c];\n __classPrivateFieldGet(this, _AES_Kd, \"f\")[r][c] = (U1[(tt >> 24) & 0xFF] ^\n U2[(tt >> 16) & 0xFF] ^\n U3[(tt >> 8) & 0xFF] ^\n U4[tt & 0xFF]);\n }\n }\n }\n encrypt(plaintext) {\n if (plaintext.length != 16) {\n throw new TypeError('invalid plaintext size (must be 16 bytes)');\n }\n const rounds = __classPrivateFieldGet(this, _AES_Ke, \"f\").length - 1;\n const a = [0, 0, 0, 0];\n // convert plaintext to (ints ^ key)\n let t = convertToInt32(plaintext);\n for (let i = 0; i < 4; i++) {\n t[i] ^= __classPrivateFieldGet(this, _AES_Ke, \"f\")[0][i];\n }\n // apply round transforms\n for (let r = 1; r < rounds; r++) {\n for (let i = 0; i < 4; i++) {\n a[i] = (T1[(t[i] >> 24) & 0xff] ^\n T2[(t[(i + 1) % 4] >> 16) & 0xff] ^\n T3[(t[(i + 2) % 4] >> 8) & 0xff] ^\n T4[t[(i + 3) % 4] & 0xff] ^\n __classPrivateFieldGet(this, _AES_Ke, \"f\")[r][i]);\n }\n t = a.slice();\n }\n // the last round is special\n const result = new Uint8Array(16);\n let tt = 0;\n for (let i = 0; i < 4; i++) {\n tt = __classPrivateFieldGet(this, _AES_Ke, \"f\")[rounds][i];\n result[4 * i] = (S[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;\n result[4 * i + 1] = (S[(t[(i + 1) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;\n result[4 * i + 2] = (S[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;\n result[4 * i + 3] = (S[t[(i + 3) % 4] & 0xff] ^ tt) & 0xff;\n }\n return result;\n }\n decrypt(ciphertext) {\n if (ciphertext.length != 16) {\n throw new TypeError('invalid ciphertext size (must be 16 bytes)');\n }\n const rounds = __classPrivateFieldGet(this, _AES_Kd, \"f\").length - 1;\n const a = [0, 0, 0, 0];\n // convert plaintext to (ints ^ key)\n let t = convertToInt32(ciphertext);\n for (let i = 0; i < 4; i++) {\n t[i] ^= __classPrivateFieldGet(this, _AES_Kd, \"f\")[0][i];\n }\n // apply round transforms\n for (let r = 1; r < rounds; r++) {\n for (let i = 0; i < 4; i++) {\n a[i] = (T5[(t[i] >> 24) & 0xff] ^\n T6[(t[(i + 3) % 4] >> 16) & 0xff] ^\n T7[(t[(i + 2) % 4] >> 8) & 0xff] ^\n T8[t[(i + 1) % 4] & 0xff] ^\n __classPrivateFieldGet(this, _AES_Kd, \"f\")[r][i]);\n }\n t = a.slice();\n }\n // the last round is special\n const result = new Uint8Array(16);\n let tt = 0;\n for (let i = 0; i < 4; i++) {\n tt = __classPrivateFieldGet(this, _AES_Kd, \"f\")[rounds][i];\n result[4 * i] = (Si[(t[i] >> 24) & 0xff] ^ (tt >> 24)) & 0xff;\n result[4 * i + 1] = (Si[(t[(i + 3) % 4] >> 16) & 0xff] ^ (tt >> 16)) & 0xff;\n result[4 * i + 2] = (Si[(t[(i + 2) % 4] >> 8) & 0xff] ^ (tt >> 8)) & 0xff;\n result[4 * i + 3] = (Si[t[(i + 1) % 4] & 0xff] ^ tt) & 0xff;\n }\n return result;\n }\n}\n_AES_key = new WeakMap(), _AES_Kd = new WeakMap(), _AES_Ke = new WeakMap();\n//# sourceMappingURL=aes.js.map","import { AES } from \"./aes.js\";\nexport class ModeOfOperation {\n constructor(name, key, cls) {\n if (cls && !(this instanceof cls)) {\n throw new Error(`${name} must be instantiated with \"new\"`);\n }\n Object.defineProperties(this, {\n aes: { enumerable: true, value: new AES(key) },\n name: { enumerable: true, value: name }\n });\n }\n}\n//# sourceMappingURL=mode.js.map","// Counter Mode\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _CTR_remaining, _CTR_remainingIndex, _CTR_counter;\nimport { ModeOfOperation } from \"./mode.js\";\nexport class CTR extends ModeOfOperation {\n constructor(key, initialValue) {\n super(\"CTR\", key, CTR);\n // Remaining bytes for the one-time pad\n _CTR_remaining.set(this, void 0);\n _CTR_remainingIndex.set(this, void 0);\n // The current counter\n _CTR_counter.set(this, void 0);\n __classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), \"f\");\n __classPrivateFieldGet(this, _CTR_counter, \"f\").fill(0);\n __classPrivateFieldSet(this, _CTR_remaining, __classPrivateFieldGet(this, _CTR_counter, \"f\"), \"f\"); // This will be discarded immediately\n __classPrivateFieldSet(this, _CTR_remainingIndex, 16, \"f\");\n if (initialValue == null) {\n initialValue = 1;\n }\n if (typeof (initialValue) === \"number\") {\n this.setCounterValue(initialValue);\n }\n else {\n this.setCounterBytes(initialValue);\n }\n }\n get counter() { return new Uint8Array(__classPrivateFieldGet(this, _CTR_counter, \"f\")); }\n setCounterValue(value) {\n if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) {\n throw new TypeError(\"invalid counter initial integer value\");\n }\n for (let index = 15; index >= 0; --index) {\n __classPrivateFieldGet(this, _CTR_counter, \"f\")[index] = value % 256;\n value = Math.floor(value / 256);\n }\n }\n setCounterBytes(value) {\n if (value.length !== 16) {\n throw new TypeError(\"invalid counter initial Uint8Array value length\");\n }\n __classPrivateFieldGet(this, _CTR_counter, \"f\").set(value);\n }\n increment() {\n for (let i = 15; i >= 0; i--) {\n if (__classPrivateFieldGet(this, _CTR_counter, \"f\")[i] === 255) {\n __classPrivateFieldGet(this, _CTR_counter, \"f\")[i] = 0;\n }\n else {\n __classPrivateFieldGet(this, _CTR_counter, \"f\")[i]++;\n break;\n }\n }\n }\n encrypt(plaintext) {\n var _a, _b;\n const crypttext = new Uint8Array(plaintext);\n for (let i = 0; i < crypttext.length; i++) {\n if (__classPrivateFieldGet(this, _CTR_remainingIndex, \"f\") === 16) {\n __classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet(this, _CTR_counter, \"f\")), \"f\");\n __classPrivateFieldSet(this, _CTR_remainingIndex, 0, \"f\");\n this.increment();\n }\n crypttext[i] ^= __classPrivateFieldGet(this, _CTR_remaining, \"f\")[__classPrivateFieldSet(this, _CTR_remainingIndex, (_b = __classPrivateFieldGet(this, _CTR_remainingIndex, \"f\"), _a = _b++, _b), \"f\"), _a];\n }\n return crypttext;\n }\n decrypt(ciphertext) {\n return this.encrypt(ciphertext);\n }\n}\n_CTR_remaining = new WeakMap(), _CTR_remainingIndex = new WeakMap(), _CTR_counter = new WeakMap();\n//# sourceMappingURL=mode-ctr.js.map","/**\n * @module wallet/utils\n */\nimport { getBytesCopy, assertArgument, concat, dataSlice, getBytes, assert, } from '../utils/index.js';\nimport { computeHmac, sha256 } from '../crypto/index.js';\nimport { encodeBase58, toUtf8Bytes } from '../encoding/index.js';\n/**\n * Converts a hex string to a Uint8Array. If the string does not start with '0x', it adds it.\n * @param {string} hexString - The hex string to convert.\n * @returns {Uint8Array} The resulting byte array.\n */\nexport function looseArrayify(hexString) {\n if (typeof hexString === 'string' && !hexString.startsWith('0x')) {\n hexString = '0x' + hexString;\n }\n return getBytesCopy(hexString);\n}\n/**\n * Converts a password to a Uint8Array. If the password is a string, it converts it to UTF-8 bytes.\n * @param {string|Uint8Array} password - The password to convert.\n * @returns {Uint8Array} The resulting byte array.\n */\nexport function getPassword(password) {\n if (typeof password === 'string') {\n return toUtf8Bytes(password, 'NFKC');\n }\n return getBytesCopy(password);\n}\n/**\n * Traverses an object based on a path and returns the value at that path.\n * @param {any} object - The object to traverse.\n * @param {string} _path - The path to traverse.\n * @returns {T} The value at the specified path.\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// HDNODEWallet and UTXO Wallet util methods\n/** \"Bitcoin seed\" */\nexport const MasterSecret = new Uint8Array([66, 105, 116, 99, 111, 105, 110, 32, 115, 101, 101, 100]);\n/** Hardened bit constant */\nexport const HardenedBit = 0x80000000;\n/** Constant N used in cryptographic operations */\nexport const N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\n/** Hexadecimal characters */\nexport const Nibbles = '0123456789abcdef';\n/**\n * Pads a value with leading zeros to a specified length.\n * @param {string|number} value - The value to pad.\n * @param {number} length - The desired length.\n * @returns {string} The padded value.\n */\nexport function zpad(value, length) {\n // Determine if the value is hexadecimal\n const isHex = typeof value === 'string' && value.startsWith('0x');\n // Handle hexadecimal values\n if (isHex) {\n let hexValue = value.substring(2); // Remove the \"0x\" prefix\n while (hexValue.length < length * 2) {\n // Hexadecimal characters count double\n hexValue = '0' + hexValue;\n }\n return '0x' + hexValue;\n }\n // Handle numbers or non-hexadecimal strings\n let result = String(value);\n while (result.length < length) {\n result = '0' + result;\n }\n return result;\n}\n/**\n * Encodes a value using Base58Check encoding.\n * @param {BytesLike} _value - The value to encode.\n * @returns {string} The Base58Check encoded string.\n */\nexport function 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}\n/**\n * Serializes an index, chain code, public key, and private key into a pair of derived keys.\n * @param {number} index - The index to serialize.\n * @param {string} chainCode - The chain code.\n * @param {string} publicKey - The public key.\n * @param {null|string} privateKey - The private key.\n * @returns {{IL: Uint8Array, IR: Uint8Array}} The derived keys.\n */\nexport function 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}\n//# sourceMappingURL=utils.js.map","/**\n * The JSON Wallet formats allow a simple way to store the private keys needed in Ethereum along with related\n * information and allows for extensible forms of encryption.\n *\n * These utilities facilitate decrypting and encrypting the most common JSON Wallet formats.\n */\nimport { CTR } from 'aes-js';\nimport { getAddress, computeAddress } from '../address/index.js';\nimport { keccak256, pbkdf2, randomBytes, scrypt, scryptSync } from '../crypto/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'/994'/0'/0/0\";\n/**\n * Returns true if `json` is a valid JSON Keystore Wallet.\n *\n * @category Wallet\n * @param {string} json - The JSON data to check.\n *\n * @returns {boolean} True if the JSON data is a valid 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 // eslint-disable-next-line no-empty\n }\n catch (error) { }\n return false;\n}\n/**\n * Decrypts the given ciphertext using the provided key and data.\n *\n * @param {any} data - The data containing encryption parameters.\n * @param {Uint8Array} key - The key to use for decryption.\n * @param {Uint8Array} ciphertext - The ciphertext to decrypt.\n *\n * @returns {string} The decrypted data as a hex string.\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}\n/**\n * Retrieves the account details from the given data and key.\n *\n * @param {any} data - The data containing account information.\n * @param {string} _key - The key to use for decryption.\n *\n * @returns {KeystoreAccount} The decrypted account details.\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-quais metadata must contain an encrypted mnemonic phrase\n const version = spelunk(data, 'x-quais.version:string');\n if (version === '0.1') {\n const mnemonicKey = key.slice(32, 64);\n const mnemonicCiphertext = spelunk(data, 'x-quais.mnemonicCiphertext:data!');\n const mnemonicIv = spelunk(data, 'x-quais.mnemonicCounter:data!');\n const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv);\n account.mnemonic = {\n path: spelunk(data, 'x-quais.path:string') || defaultPath,\n locale: spelunk(data, 'x-quais.locale:string') || 'en',\n entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))),\n };\n }\n return account;\n}\n/**\n * Retrieves the key derivation function parameters from the given data.\n *\n * @param {any} data - The data containing KDF parameters.\n *\n * @returns {KdfParams} The key derivation function parameters.\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` using `password`.\n *\n * It is preferred to use the {@link decryptKeystoreJson | **async version**} instead, which allows a\n * {@link ProgressCallback | **ProgressCallback} to keep the user informed as to the decryption status.\n *\n * This method will block the event loop (freezing all UI) until decryption is complete, which can take quite some time,\n * depending on the wallet paramters and platform.\n *\n * @category Wallet\n * @param {string} json - The JSON data to decrypt.\n * @param {string | Uint8Array} _password - The password to decrypt the JSON data.\n *\n * @returns {KeystoreAccount} The decrypted account.\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}\n/**\n * Pauses execution for the specified duration.\n *\n * @param {number} duration - The duration to stall in milliseconds.\n *\n * @returns {Promise} A promise that resolves after the specified duration.\n */\nfunction stall(duration) {\n return new Promise((resolve) => {\n setTimeout(() => {\n resolve();\n }, duration);\n });\n}\n/**\n * Resolves to the decrypted JSON Keystore Wallet `json` using the `password`.\n *\n * If provided, `progress` will be called periodically during the decrpytion to provide feedback, and if the function\n * returns `false` will halt decryption.\n *\n * The `progressCallback` will **always** receive `0` before decryption begins and `1` when complete.\n *\n * @category Wallet\n * @param {string} json - The JSON data to decrypt.\n * @param {string | Uint8Array} _password - The password to decrypt the JSON data.\n * @param {ProgressCallback} [progress] - The callback to receive progress updates.\n *\n * @returns {Promise} The decrypted account.\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}\n/**\n * Retrieves the key derivation function parameters for encryption.\n *\n * @param {EncryptOptions} options - The encryption options.\n *\n * @returns {ScryptParams} The key derivation function parameters.\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}\n/**\n * Encrypts the keystore with the given key, KDF parameters, account, and options.\n *\n * @ignore\n * @param {Uint8Array} key - The key to use for encryption.\n * @param {ScryptParams} kdf - The key derivation function parameters.\n * @param {KeystoreAccount} account - The account to encrypt.\n * @param {EncryptOptions} options - The encryption options.\n *\n * @returns {any} The encrypted keystore data.\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 quais 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 : `quais/${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 '-' +\n zpad(now.getUTCMonth() + 1, 2) +\n '-' +\n zpad(now.getUTCDate(), 2) +\n 'T' +\n zpad(now.getUTCHours(), 2) +\n '-' +\n zpad(now.getUTCMinutes(), 2) +\n '-' +\n zpad(now.getUTCSeconds(), 2) +\n '.0Z';\n const gethFilename = 'UTC--' + timestamp + '--' + data.address;\n data['x-quais'] = {\n client,\n gethFilename,\n path,\n 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 `password`.\n *\n * The `options` can be used to tune the password-based key derivation function parameters, explicitly set the random\n * values used. Any provided {@link ProgressCallback | **ProgressCallback**} is ignored.\n *\n * @category Wallet\n * @param {KeystoreAccount} account - The account to encrypt.\n * @param {string | Uint8Array} password - The password to encrypt the JSON data.\n * @param {EncryptOptions} [options] - The options to use when encrypting the JSON data.\n *\n * @returns {string} The encrypted JSON data.\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 with `password`.\n *\n * The `options` can be used to tune the password-based key derivation function parameters, explicitly set the random\n * values used and provide a {@link ProgressCallback | **ProgressCallback**} to receive periodic updates on the\n * completion status..\n *\n * @category Wallet\n * @param {KeystoreAccount} account - The account to encrypt.\n * @param {string | Uint8Array} password - The password to encrypt the JSON data.\n * @param {EncryptOptions} [options] - The options to use when encrypting the JSON data.\n *\n * @returns {Promise} The encrypted JSON data.\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","import { computeHmac, randomBytes, ripemd160, SigningKey, sha256 } from '../crypto/index.js';\nimport { VoidSigner } from '../signers/index.js';\nimport { computeAddress } from '../address/index.js';\nimport { decodeBase58, encodeBase58 } from '../encoding/index.js';\nimport { concat, dataSlice, defineProperties, 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// \"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 from an HD Node using the [[link-bip-32]]\n * standard.\n *\n * An HD Node forms a hierarchical structure with each HD Node having a private key and the ability to derive child HD\n * Nodes, defined by a path indicating the index of each child.\n */\nexport class HDNodeWallet extends BaseWallet {\n /**\n * The compressed public key.\n *\n * @type {string}\n */\n publicKey;\n /**\n * The fingerprint.\n *\n * A fingerprint allows a quick way to detect parent and child nodes, but developers should be prepared to deal with\n * collisions as it is only 4 bytes.\n *\n * @type {string}\n */\n fingerprint;\n /**\n * The parent fingerprint.\n *\n * @type {string}\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 which case this will be `null`.\n *\n * @type {null | Mnemonic}\n */\n mnemonic;\n /**\n * The chaincode, which is effectively a public key used to derive children.\n *\n * @type {string}\n */\n chainCode;\n /**\n * The derivation path of this wallet.\n *\n * Since extended keys do not provide full path details, this may be `null`, if instantiated from a source that does\n * not encode it.\n *\n * @type {null | string}\n */\n path;\n /**\n * The child index of this wallet. Values over `2 ** 31` indicate the node is hardened.\n *\n * @type {number}\n */\n index;\n /**\n * The depth of this wallet, which is the number of components in its path.\n *\n * @type {number}\n */\n depth;\n /**\n * @param {any} guard\n * @param {SigningKey} signingKey\n * @param {string} parentFingerprint\n * @param {string} chainCode\n * @param {null | string} path\n * @param {number} index\n * @param {number} depth\n * @param {null | Mnemonic} mnemonic\n * @param {null | Provider} provider\n * @ignore\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,\n fingerprint,\n chainCode,\n path,\n index,\n depth,\n });\n defineProperties(this, { mnemonic });\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {null | Provider} provider\n *\n * @returns {HDNodeWallet}\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 /**\n * @returns {KeystoreAccount}\n * @ignore\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 `password`.\n *\n * If `progressCallback` is specified, it will receive periodic updates as the encryption process progresses.\n *\n * @param {Uint8Array | string} password\n * @param {ProgressCallback} [progressCallback]\n *\n * @returns {Promise}\n */\n async encrypt(password, progressCallback) {\n return await encryptKeystoreJson(this.#account(), password, { progressCallback });\n }\n /**\n * Returns a [JSON Keystore Wallet](json-wallets) encrypted with `password`.\n *\n * It is preferred to use the [async version](encrypt) instead, which allows a `ProgressCallback` to keep the user\n * informed.\n *\n * This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial\n * duration.\n *\n * @param {Uint8Array | string} password\n *\n * @returns {string}\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 reconstruct this HD Node to derive its children.\n *\n * @returns {string}\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', {\n operation: 'extendedKey',\n });\n return encodeBase58Check(concat([\n '0x0488ADE4',\n zpad(this.depth, 1),\n this.parentFingerprint,\n zpad(this.index, 4),\n this.chainCode,\n concat(['0x00', this.privateKey]),\n ]));\n }\n /**\n * Returns true if this wallet has a path, providing a Type Guard that the path is non-null.\n *\n * @returns {boolean}\n */\n hasPath() {\n return this.path != null;\n }\n /**\n * Returns a neutered HD Node, which removes the private details of an HD Node.\n *\n * A neutered node has no private key, but can be used to derive child addresses and other public data about the HD\n * Node.\n *\n * @returns {HDNodeVoidWallet}\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 * @param {Numeric} _index\n *\n * @returns {HDNodeWallet}\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 * @param {string} path\n *\n * @returns {HDNodeWallet}\n */\n derivePath(path) {\n return derivePath(this, path);\n }\n /**\n\n * @param {BytesLike} _seed\n * @param {null | Mnemonic} mnemonic\n *\n * @returns {HDNodeWallet}\n * @ignore\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 `xpriv`, returning a neutered HD Node\n * ([[HDNodeVoidWallet]]) or full HD Node ([[HDNodeWallet]]) respectively.\n *\n * @param {string} extendedKey\n *\n * @returns {HDNodeWallet | HDNodeVoidWallet}\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 * @param {string} path\n * @param {string} [password]\n * @param {Wordlist} [wordlist]\n *\n * @returns {HDNodeWallet}\n */\n static createRandom(path, password, wordlist) {\n if (password == null) {\n password = '';\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 * @param {Mnemonic} mnemonic\n * @param {string} path\n *\n * @returns {HDNodeWallet}\n */\n static fromMnemonic(mnemonic, path) {\n return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path);\n }\n /**\n * Creates an HD Node from a mnemonic `phrase`.\n *\n * @param {string} phrase\n * @param {string} path\n * @param {string} [password]\n * @param {Wordlist} [wordlist]\n *\n * @returns {HDNodeWallet}\n */\n static fromPhrase(phrase, path, password, wordlist) {\n if (password == null) {\n password = '';\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 * @param {BytesLike} seed\n *\n * @returns {HDNodeWallet}\n */\n static fromSeed(seed) {\n return HDNodeWallet.#fromSeed(seed, null);\n }\n}\n/**\n * A **HDNodeVoidWallet** cannot sign, but provides access to the children nodes of a [[link-bip-32]] HD wallet\n * addresses.\n *\n * They can be created by using an extended `xpub` key to [[HDNodeWallet_fromExtendedKey]] or by\n * [neutering](HDNodeWallet-neuter) a [[HDNodeWallet]].\n */\nexport class HDNodeVoidWallet extends VoidSigner {\n /**\n * The compressed public key.\n *\n * @type {string}\n */\n publicKey;\n /**\n * The fingerprint.\n *\n * A fingerprint allows a quick way to detect parent and child nodes, but developers should be prepared to deal with\n * collisions as it is only 4 bytes.\n *\n * @type {string}\n */\n fingerprint;\n /**\n * The parent node fingerprint.\n *\n * @type {string}\n */\n parentFingerprint;\n /**\n * The chaincode, which is effectively a public key used to derive children.\n *\n * @type {string}\n */\n chainCode;\n /**\n * The derivation path of this wallet.\n *\n * Since extended keys do not provide full path details, this may be `null`, if instantiated from a source that does\n * not encode it.\n *\n * @type {null | string}\n */\n path;\n /**\n * The child index of this wallet. Values over `2 ** 31` indicate the node is hardened.\n *\n * @type {number}\n */\n index;\n /**\n * The depth of this wallet, which is the number of components in its path.\n *\n * @type {number}\n */\n depth;\n /**\n * @param {any} guard\n * @param {string} address\n * @param {string} publicKey\n * @param {string} parentFingerprint\n * @param {string} chainCode\n * @param {null | string} path\n * @param {number} index\n * @param {number} depth\n * @param {null | Provider} provider\n * @ignore\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,\n fingerprint,\n parentFingerprint,\n chainCode,\n path,\n index,\n depth,\n });\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {null | Provider} provider\n *\n * @returns {HDNodeVoidWallet}\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 reconstruct this neutered key to derive its\n * children addresses.\n *\n * @returns {string}\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 that the path is non-null.\n *\n * @returns {boolean}\n */\n hasPath() {\n return this.path != null;\n }\n /**\n * Return the child for `index`.\n *\n * @param {Numeric} _index\n *\n * @returns {HDNodeVoidWallet}\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 * @param {string} path\n *\n * @returns {HDNodeVoidWallet}\n */\n derivePath(path) {\n return derivePath(this, path);\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 some software.\n *\n * @param {Numeric} _index\n *\n * @returns {string}\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, at `index`.\n *\n * This derivation path uses the `index` component rather than the `account` component to derive sequential accounts.\n *\n * This is the pattern used by wallets like MetaMask.\n *\n * @param {Numeric} _index\n *\n * @returns {string}\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=hdnodewallet.js.map","import { HDNodeWallet } from './hdnodewallet.js';\nimport { Mnemonic } from './mnemonic.js';\nimport { LangEn } from '../wordlists/lang-en.js';\nimport { randomBytes } from '../crypto/index.js';\nimport { getZoneForAddress, assertPrivate } from '../utils/index.js';\nimport { isQiAddress } from '../address/index.js';\nimport { Zone } from '../constants/index.js';\n/**\n * Constant to represent the maximum attempt to derive an address.\n */\nconst MAX_ADDRESS_DERIVATION_ATTEMPTS = 10000000;\nexport const _guard = {};\n/**\n * Abstract class representing a Hierarchical Deterministic (HD) wallet.\n */\nclass AbstractHDWallet {\n static _version = 1;\n static _coinType;\n // Map of addresses to address info\n _addresses = new Map();\n /**\n * Root node of the HD wallet.\n */\n _root;\n provider;\n /**\n * @param {HDNodeWallet} root - The root node of the HD wallet.\n * @param {Provider} [provider] - The provider for the HD wallet.\n */\n constructor(guard, root, provider) {\n assertPrivate(guard, _guard, 'AbstractHDWallet');\n this._root = root;\n this.provider = provider;\n }\n /**\n * Returns the parent path for a given coin type.\n *\n * @param {number} coinType - The coin type.\n * @returns {string} The parent path.\n */\n static parentPath(coinType) {\n return `m/44'/${coinType}'`;\n }\n /**\n * Returns the coin type of the wallet.\n *\n * @returns {AllowedCoinType} The coin type.\n */\n coinType() {\n return this.constructor._coinType;\n }\n /**\n * Returns the extended public key of the root node of the HD wallet.\n *\n * @returns {string} The extended public key.\n */\n get xPub() {\n return this._root.extendedKey;\n }\n /**\n * Derives the next valid address node for a specified account, starting index, and zone. The method ensures the\n * derived address belongs to the correct shard and ledger, as defined by the Quai blockchain specifications.\n *\n * @param {number} account - The account number from which to derive the address node.\n * @param {number} startingIndex - The index from which to start deriving addresses.\n * @param {Zone} zone - The zone (shard) for which the address should be valid.\n * @param {boolean} [isChange=false] - Whether to derive a change address. Default is `false`\n * @returns {HDNodeWallet} - The derived HD node wallet containing a valid address for the specified zone.\n * @throws {Error} If a valid address for the specified zone cannot be derived within the allowed attempts.\n */\n deriveNextAddressNode(account, startingIndex, zone, isChange = false) {\n const changeIndex = isChange ? 1 : 0;\n const changeNode = this._root.deriveChild(account).deriveChild(changeIndex);\n let addrIndex = startingIndex;\n let addressNode;\n const isValidAddressForZone = (address) => {\n const addressZone = getZoneForAddress(address);\n if (!addressZone) {\n return false;\n }\n const isCorrectShard = addressZone === zone;\n const isCorrectLedger = this.coinType() === 969 ? isQiAddress(address) : !isQiAddress(address);\n return isCorrectShard && isCorrectLedger;\n };\n for (let attempts = 0; attempts < MAX_ADDRESS_DERIVATION_ATTEMPTS; attempts++) {\n addressNode = changeNode.deriveChild(addrIndex++);\n if (isValidAddressForZone(addressNode.address)) {\n return addressNode;\n }\n }\n throw new Error(`Failed to derive a valid address for the zone ${zone} after ${MAX_ADDRESS_DERIVATION_ATTEMPTS} attempts.`);\n }\n /**\n * Adds an address to the wallet.\n *\n * @param {number} account - The account number.\n * @param {number} addressIndex - The address index.\n * @param {boolean} [isChange=false] - Whether the address is a change address. Default is `false`\n * @returns {NeuteredAddressInfo} The added address info.\n */\n addAddress(account, addressIndex, isChange = false) {\n return this._addAddress(this._addresses, account, addressIndex, isChange);\n }\n /**\n * Helper method to add an address to the wallet address map.\n *\n * @param {Map} addressMap - The address map.\n * @param {number} account - The account number.\n * @param {number} addressIndex - The address index.\n * @param {boolean} [isChange=false] - Whether the address is a change address. Default is `false`\n * @returns {NeuteredAddressInfo} The added address info.\n * @throws {Error} If the address for the index already exists.\n */\n _addAddress(addressMap, account, addressIndex, isChange = false) {\n // check if address already exists for the index\n this._addresses.forEach((addressInfo) => {\n if (addressInfo.index === addressIndex) {\n throw new Error(`Address for index ${addressIndex} already exists`);\n }\n });\n // derive the address node and validate the zone\n const changeIndex = isChange ? 1 : 0;\n const addressNode = this._root.deriveChild(account).deriveChild(changeIndex).deriveChild(addressIndex);\n const zone = getZoneForAddress(addressNode.address);\n if (!zone) {\n throw new Error(`Failed to derive a valid address zone for the index ${addressIndex}`);\n }\n return this.createAndStoreAddressInfo(addressNode, account, zone, isChange, addressMap);\n }\n /**\n * Promise that resolves to the next address for the specified account and zone.\n *\n * @param {number} account - The index of the account for which to retrieve the next address.\n * @param {Zone} zone - The zone in which to retrieve the next address.\n * @returns {Promise} The next neutered address information.\n */\n async getNextAddress(account, zone) {\n return Promise.resolve(this._getNextAddress(account, zone, false, this._addresses));\n }\n /**\n * Synchronously retrieves the next address for the specified account and zone.\n *\n * @param {number} account - The index of the account for which to retrieve the next address.\n * @param {Zone} zone - The zone in which to retrieve the next address.\n * @returns {NeuteredAddressInfo} The next neutered address information.\n */\n getNextAddressSync(account, zone) {\n return this._getNextAddress(account, zone, false, this._addresses);\n }\n /**\n * Derives and returns the next address information for the specified account and zone.\n *\n * @param {number} accountIndex - The index of the account for which the address is being generated.\n * @param {Zone} zone - The zone in which the address is to be used.\n * @param {boolean} isChange - A flag indicating whether the address is a change address.\n * @param {Map} addressMap - A map storing the neutered address information.\n * @returns {NeuteredAddressInfo} The derived neutered address information.\n * @throws {Error} If the zone is invalid.\n */\n _getNextAddress(accountIndex, zone, isChange, addressMap) {\n this.validateZone(zone);\n const lastIndex = this.getLastAddressIndex(addressMap, zone, accountIndex, isChange);\n const addressNode = this.deriveNextAddressNode(accountIndex, lastIndex + 1, zone, isChange);\n return this.createAndStoreAddressInfo(addressNode, accountIndex, zone, isChange, addressMap);\n }\n /**\n * Gets the address info for a given address.\n *\n * @param {string} address - The address.\n * @returns {NeuteredAddressInfo | null} The address info or null if not found.\n */\n getAddressInfo(address) {\n const addressInfo = this._addresses.get(address);\n if (!addressInfo) {\n return null;\n }\n return addressInfo;\n }\n /**\n * Returns the private key for a given address. This method should be used with caution as it exposes the private\n * key to the user.\n *\n * @param {string} address - The address associated with the desired private key.\n * @returns {string} The private key.\n */\n getPrivateKey(address) {\n const hdNode = this._getHDNodeForAddress(address);\n return hdNode.privateKey;\n }\n /**\n * Gets the addresses for a given account.\n *\n * @param {number} account - The account number.\n * @returns {NeuteredAddressInfo[]} The addresses for the account.\n */\n getAddressesForAccount(account) {\n const addresses = this._addresses.values();\n return Array.from(addresses).filter((addressInfo) => addressInfo.account === account);\n }\n /**\n * Gets the addresses for a given zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {NeuteredAddressInfo[]} The addresses for the zone.\n */\n getAddressesForZone(zone) {\n this.validateZone(zone);\n const addresses = this._addresses.values();\n return Array.from(addresses).filter((addressInfo) => addressInfo.zone === zone);\n }\n /**\n * Creates an instance of the HD wallet.\n *\n * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet.\n * @param {Mnemonic} mnemonic - The mnemonic.\n * @returns {T} The created instance.\n */\n static createInstance(mnemonic) {\n const coinType = this._coinType;\n const root = HDNodeWallet.fromMnemonic(mnemonic, this.parentPath(coinType));\n return new this(_guard, root);\n }\n /**\n * Creates an HD wallet from a mnemonic.\n *\n * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet.\n * @param {Mnemonic} mnemonic - The mnemonic.\n * @returns {T} The created instance.\n */\n static fromMnemonic(mnemonic) {\n return this.createInstance(mnemonic);\n }\n /**\n * Creates a random HD wallet.\n *\n * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet.\n * @param {string} [password] - The password.\n * @param {Wordlist} [wordlist] - The wordlist.\n * @returns {T} The created instance.\n */\n static createRandom(password, wordlist) {\n if (password == null) {\n password = '';\n }\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist);\n return this.createInstance(mnemonic);\n }\n /**\n * Creates an HD wallet from a phrase.\n *\n * @param {new (root: HDNodeWallet) => T} this - The constructor of the HD wallet.\n * @param {string} phrase - The phrase.\n * @param {string} [password] - The password.\n * @param {Wordlist} [wordlist] - The wordlist.\n * @returns {T} The created instance.\n */\n static fromPhrase(phrase, password, wordlist) {\n if (password == null) {\n password = '';\n }\n if (wordlist == null) {\n wordlist = LangEn.wordlist();\n }\n const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist);\n return this.createInstance(mnemonic);\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {Provider} provider - The provider.\n */\n connect(provider) {\n this.provider = provider;\n }\n /**\n * Validates the zone.\n *\n * @param {Zone} zone - The zone.\n * @throws {Error} If the zone is invalid.\n */\n validateZone(zone) {\n if (!Object.values(Zone).includes(zone)) {\n throw new Error(`Invalid zone: ${zone}`);\n }\n }\n /**\n * Derives and returns the Hierarchical Deterministic (HD) node wallet associated with a given address.\n *\n * This method fetches the account and address information from the wallet's internal storage, derives the\n * appropriate change node based on whether the address is a change address, and further derives the final HD node\n * using the address index.\n *\n * @param {string} addr - The address for which to derive the HD node.\n * @returns {HDNodeWallet} The derived HD node wallet corresponding to the given address.\n * @throws {Error} If the given address is not known to the wallet.\n * @throws {Error} If the account associated with the address is not found.\n */\n _getHDNodeForAddress(addr) {\n const addressInfo = this._addresses.get(addr);\n if (!addressInfo) {\n throw new Error(`Address ${addr} is not known to this wallet`);\n }\n const changeIndex = addressInfo.change ? 1 : 0;\n return this._root.deriveChild(addressInfo.account).deriveChild(changeIndex).deriveChild(addressInfo.index);\n }\n /**\n * Serializes the HD wallet state into a format suitable for storage or transmission.\n *\n * @returns {SerializedHDWallet} An object representing the serialized state of the HD wallet, including version,\n * mnemonic phrase, coin type, and addresses.\n */\n serialize() {\n const addresses = Array.from(this._addresses.values());\n return {\n version: this.constructor._version,\n phrase: this._root.mnemonic.phrase,\n coinType: this.coinType(),\n addresses: addresses,\n };\n }\n /**\n * Deserializes a serialized HD wallet object and reconstructs the wallet instance. This method must be implemented\n * in the subclass.\n *\n * @param {SerializedHDWallet} _serialized - The serialized object representing the state of an HD wallet.\n * @returns {AbstractHDWallet} An instance of AbstractHDWallet.\n * @throws {Error} This method must be implemented in the subclass.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n static async deserialize(_serialized) {\n throw new Error('deserialize method must be implemented in the subclass');\n }\n /**\n * Validates the version and coinType of the serialized wallet.\n *\n * @param {SerializedHDWallet} serialized - The serialized wallet data to be validated.\n * @throws {Error} If the version or coinType of the serialized wallet does not match the expected values.\n * @protected\n * @static\n */\n static validateSerializedWallet(serialized) {\n if (serialized.version !== this._version) {\n throw new Error(`Invalid version ${serialized.version} for wallet (expected ${this._version})`);\n }\n if (serialized.coinType !== this._coinType) {\n throw new Error(`Invalid coinType ${serialized.coinType} for wallet (expected ${this._coinType})`);\n }\n }\n /**\n * Imports addresses from a serialized wallet into the addresses map. Before adding the addresses, a validation is\n * performed to ensure the address, public key, and zone match the expected values.\n *\n * @param {Map} addressMap - The map where the addresses will be imported.\n * @param {NeuteredAddressInfo[]} addresses - The array of addresses to be imported, each containing account, index,\n * change, address, pubKey, and zone information.\n * @throws {Error} If there is a mismatch between the expected and actual address, public key, or zone.\n * @protected\n */\n importSerializedAddresses(addressMap, addresses) {\n for (const addressInfo of addresses) {\n const newAddressInfo = this._addAddress(addressMap, addressInfo.account, addressInfo.index, addressInfo.change);\n // validate the address info\n if (addressInfo.address !== newAddressInfo.address) {\n throw new Error(`Address mismatch: ${addressInfo.address} != ${newAddressInfo.address}`);\n }\n if (addressInfo.pubKey !== newAddressInfo.pubKey) {\n throw new Error(`Public key mismatch: ${addressInfo.pubKey} != ${newAddressInfo.pubKey}`);\n }\n if (addressInfo.zone !== newAddressInfo.zone) {\n throw new Error(`Zone mismatch: ${addressInfo.zone} != ${newAddressInfo.zone}`);\n }\n }\n }\n /**\n * Retrieves the highest address index from the given address map for a specified zone, account, and change type.\n *\n * This method filters the address map based on the provided zone, account, and change type, then determines the\n * maximum address index from the filtered addresses.\n *\n * @param {Map} addressMap - The map containing address information, where the key is\n * an address string and the value is a NeuteredAddressInfo object.\n * @param {Zone} zone - The specific zone to filter the addresses by.\n * @param {number} account - The account number to filter the addresses by.\n * @param {boolean} isChange - A boolean indicating whether to filter for change addresses (true) or receiving\n * addresses (false).\n * @returns {number} - The highest address index for the specified criteria, or -1 if no addresses match.\n * @protected\n */\n getLastAddressIndex(addressMap, zone, account, isChange) {\n const addresses = Array.from(addressMap.values()).filter((addressInfo) => addressInfo.account === account && addressInfo.zone === zone && addressInfo.change === isChange);\n return addresses.reduce((maxIndex, addressInfo) => Math.max(maxIndex, addressInfo.index), -1);\n }\n /**\n * Creates and stores address information in the address map for a specified account, zone, and change type.\n *\n * This method constructs a NeuteredAddressInfo object using the provided HDNodeWallet and other parameters, then\n * stores this information in the provided address map.\n *\n * @param {HDNodeWallet} addressNode - The HDNodeWallet object containing the address and public key information.\n * @param {number} account - The account number to associate with the address.\n * @param {Zone} zone - The specific zone to associate with the address.\n * @param {boolean} isChange - A boolean indicating whether the address is a change address (true) or a receiving\n * address (false).\n * @param {Map} addressMap - The map to store the created NeuteredAddressInfo, with the\n * address as the key.\n * @returns {NeuteredAddressInfo} - The created NeuteredAddressInfo object.\n * @protected\n */\n createAndStoreAddressInfo(addressNode, account, zone, isChange, addressMap) {\n const neuteredAddressInfo = {\n pubKey: addressNode.publicKey,\n address: addressNode.address,\n account,\n index: addressNode.index,\n change: isChange,\n zone,\n };\n addressMap.set(neuteredAddressInfo.address, neuteredAddressInfo);\n return neuteredAddressInfo;\n }\n}\nexport { AbstractHDWallet };\n//# sourceMappingURL=hdwallet.js.map","import { AbstractHDWallet, _guard } from './hdwallet.js';\nimport { HDNodeWallet } from './hdnodewallet.js';\nimport { resolveAddress } from '../address/index.js';\nimport { Mnemonic } from './mnemonic.js';\n/**\n * The Quai HD wallet is a BIP44-compliant hierarchical deterministic wallet used for managing a set of addresses in the\n * Quai ledger. This is the easiest way to manage the interaction of managing accounts and addresses on the Quai\n * network, however, if your use case requires a single address Quai address, you can use the {@link Wallet} class.\n *\n * The Quai HD wallet supports:\n *\n * - Adding accounts to the wallet heierchy\n * - Generating addresses for a specific account in any {@link Zone}\n * - Signing and sending transactions for any address in the wallet\n * - Signing and verifying EIP1193 typed data for any address in the wallet.\n * - Serializing the wallet to JSON and deserializing it back to a wallet instance.\n *\n * @category Wallet\n * @example\n *\n * ```ts\n * import { QuaiHDWallet, Zone } from 'quais';\n *\n * const wallet = new QuaiHDWallet();\n * const cyrpus1Address = await wallet.getNextAddress(0, Zone.Cyrpus1); // get the first address in the Cyrpus1 zone\n * await wallet.sendTransaction({ from: address, to: '0x...', value: 100 }); // send a transaction\n * const serializedWallet = wallet.serialize(); // serialize current (account/address) state of the wallet\n * .\n * .\n * .\n * const deserializedWallet = QuaiHDWallet.deserialize(serializedWallet); // create a new wallet instance from the serialized data\n * ```\n */\nclass QuaiHDWallet extends AbstractHDWallet {\n /**\n * The version of the wallet.\n *\n * @type {number}\n * @static\n */\n static _version = 1;\n /**\n * The coin type for the wallet.\n *\n * @type {AllowedCoinType}\n * @static\n */\n static _coinType = 994;\n /**\n * Create a QuaiHDWallet instance.\n *\n * @param {HDNodeWallet} root - The root HD node wallet.\n * @param {Provider} [provider] - The provider.\n */\n constructor(guard, root, provider) {\n super(guard, root, provider);\n }\n /**\n * Sign a transaction.\n *\n * @param {QuaiTransactionRequest} tx - The transaction request.\n * @returns {Promise} A promise that resolves to the signed transaction.\n */\n async signTransaction(tx) {\n const from = await resolveAddress(tx.from);\n const fromNode = this._getHDNodeForAddress(from);\n const signedTx = await fromNode.signTransaction(tx);\n return signedTx;\n }\n /**\n * Send a transaction.\n *\n * @param {QuaiTransactionRequest} tx - The transaction request.\n * @returns {Promise} A promise that resolves to the transaction response.\n * @throws {Error} If the provider is not set.\n */\n async sendTransaction(tx) {\n if (!this.provider) {\n throw new Error('Provider is not set');\n }\n const from = await resolveAddress(tx.from);\n const fromNode = this._getHDNodeForAddress(from);\n const fromNodeConnected = fromNode.connect(this.provider);\n return await fromNodeConnected.sendTransaction(tx);\n }\n /**\n * Sign a message.\n *\n * @param {string} address - The address.\n * @param {string | Uint8Array} message - The message to sign.\n * @returns {Promise} A promise that resolves to the signed message.\n */\n async signMessage(address, message) {\n const addrNode = this._getHDNodeForAddress(address);\n return await addrNode.signMessage(message);\n }\n /**\n * Deserializes the given serialized HD wallet data into an instance of QuaiHDWallet.\n *\n * @async\n * @param {SerializedHDWallet} serialized - The serialized wallet data to be deserialized.\n * @returns {Promise} A promise that resolves to an instance of QuaiHDWallet.\n * @throws {Error} If validation of the serialized wallet data fails or if deserialization fails.\n * @public\n * @static\n */\n static async deserialize(serialized) {\n super.validateSerializedWallet(serialized);\n // create the wallet instance\n const mnemonic = Mnemonic.fromPhrase(serialized.phrase);\n const path = this.parentPath(serialized.coinType);\n const root = HDNodeWallet.fromMnemonic(mnemonic, path);\n const wallet = new this(_guard, root);\n // import the addresses\n wallet.importSerializedAddresses(wallet._addresses, serialized.addresses);\n return wallet;\n }\n /**\n * Signs typed data using the private key associated with the given address.\n *\n * @param {string} address - The address for which the typed data is to be signed.\n * @param {TypedDataDomain} domain - The domain information of the typed data, defining the scope of the signature.\n * @param {Record} types - The types of the data to be signed, mapping each data type name\n * to its fields.\n * @param {Record} value - The actual data to be signed.\n * @returns {Promise} A promise that resolves to the signed data in string format.\n * @throws {Error} If the address does not correspond to a valid HD node or if signing fails.\n */\n async signTypedData(address, domain, types, value) {\n const addrNode = this._getHDNodeForAddress(address);\n return addrNode.signTypedData(domain, types, value);\n }\n}\nexport { QuaiHDWallet };\n//# sourceMappingURL=quai-hdwallet.js.map","import { SigningKey } from '../crypto/index.js';\nimport { assertArgument } from '../utils/index.js';\nimport { BaseWallet } from './base-wallet.js';\nimport { decryptKeystoreJson, decryptKeystoreJsonSync, encryptKeystoreJson, encryptKeystoreJsonSync, isKeystoreJson, } from './json-keystore.js';\n/**\n * A **Wallet** manages a single private key which is used to sign transactions, messages and other common payloads.\n *\n * This class is generally the main entry point for developers that wish to use a private key directly, as it can create\n * instances from a large variety of common sources, including raw private key,\n * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) mnemonics and encrypted JSON wallets.\n *\n * @category Wallet\n */\nexport class Wallet extends BaseWallet {\n /**\n * Create a new wallet for the private `key`, optionally connected to `provider`.\n *\n * @param {string | SigningKey} key - The private key.\n * @param {null | Provider} [provider] - The provider to connect to.\n */\n constructor(key, provider) {\n if (typeof key === 'string' && !key.startsWith('0x')) {\n key = '0x' + key;\n }\n const signingKey = typeof key === 'string' ? new SigningKey(key) : key;\n super(signingKey, provider);\n }\n /**\n * Connects the wallet to a provider.\n *\n * @param {null | Provider} provider - The provider to connect to.\n *\n * @returns {Wallet} The connected wallet.\n */\n connect(provider) {\n return new Wallet(this.signingKey, provider);\n }\n /**\n * Resolves to a [JSON Keystore Wallet](json-wallets) encrypted with `password`.\n *\n * If `progressCallback` is specified, it will receive periodic updates as the encryption process progresses.\n *\n * @param {Uint8Array | string} password - The password to encrypt the wallet with.\n * @param {ProgressCallback} [progressCallback] - An optional callback to keep the user informed.\n *\n * @returns {Promise} The encrypted JSON wallet.\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) encrypted with `password`.\n *\n * It is preferred to use the [async version](encrypt) instead, which allows a\n * {@link ProgressCallback | **ProgressCallback**} to keep the user informed.\n *\n * This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial\n * duration.\n *\n * @param {Uint8Array | string} password - The password to encrypt the wallet with.\n *\n * @returns {string} The encrypted JSON wallet.\n */\n encryptSync(password) {\n const account = { address: this.address, privateKey: this.privateKey };\n return encryptKeystoreJsonSync(account, password);\n }\n /**\n * Creates a wallet from a keystore account.\n *\n * @ignore\n * @param {KeystoreAccount} account - The keystore account.\n *\n * @returns {Wallet} The wallet instance.\n */\n static #fromAccount(account) {\n assertArgument(account, 'invalid JSON wallet', 'json', '[ REDACTED ]');\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` with `password`.\n *\n * If `progress` is provided, it is called periodically during decryption so that any UI can be updated.\n *\n * @param {string} json - The JSON data to decrypt.\n * @param {Uint8Array | string} password - The password to decrypt the JSON data.\n * @param {ProgressCallback} [progress] - An optional callback to keep the user informed.\n *\n * @returns {Promise} The decrypted wallet.\n */\n static async fromEncryptedJson(json, password, progress) {\n let account;\n if (isKeystoreJson(json)) {\n account = await decryptKeystoreJson(json, password, progress);\n return Wallet.#fromAccount(account);\n }\n throw new Error('invalid JSON wallet');\n }\n /**\n * Creates a **Wallet** by decrypting the `json` with `password`.\n *\n * The {@link Wallet.fromEncryptedJson | **fromEncryptedJson**} method is preferred, as this method will lock up and\n * freeze the UI during decryption, which may take some time.\n *\n * @param {string} json - The JSON data to decrypt.\n * @param {Uint8Array | string} password - The password to decrypt the JSON data.\n *\n * @returns {QuaiHDWallet | Wallet} The decrypted wallet.\n */\n static fromEncryptedJsonSync(json, password) {\n let account = null;\n if (isKeystoreJson(json)) {\n account = decryptKeystoreJsonSync(json, password);\n }\n else {\n assertArgument(false, 'invalid JSON wallet', 'json', '[ REDACTED ]');\n }\n return Wallet.#fromAccount(account);\n }\n}\n//# sourceMappingURL=wallet.js.map","/*! musig-js - MIT License (c) 2022 Brandon Black */\nconst TAGS = {\n challenge: 'BIP0340/challenge',\n keyagg_list: 'KeyAgg list',\n keyagg_coef: 'KeyAgg coefficient',\n musig_aux: 'MuSig/aux',\n musig_nonce: 'MuSig/nonce',\n musig_deterministic_nonce: 'MuSig/deterministic/nonce',\n musig_noncecoef: 'MuSig/noncecoef',\n};\nfunction compare32b(a, b) {\n if (a.length !== 32 || b.length !== 32) throw new Error('Invalid array');\n const aD = new DataView(a.buffer, a.byteOffset, a.length);\n const bD = new DataView(b.buffer, b.byteOffset, b.length);\n for (let i = 0; i < 8; i++) {\n const cmp = aD.getUint32(i * 4) - bD.getUint32(i * 4);\n if (cmp !== 0) return cmp;\n }\n return 0;\n}\nfunction compare33b(a, b) {\n if (a.length !== 33 || b.length !== 33) throw new Error('Invalid array');\n const cmp = a[0] - b[0];\n if (cmp !== 0) return cmp;\n return compare32b(a.subarray(1), b.subarray(1));\n}\nconst makeSessionId =\n typeof self === 'object' && (self.crypto || self.msCrypto)\n ? () => (self.crypto || self.msCrypto).getRandomValues(new Uint8Array(32))\n : () => require('crypto').randomBytes(32);\nconst _keyAggCache = new WeakMap();\nconst _coefCache = new WeakMap();\nconst _nonceCache = new WeakMap();\nconst _sessionCache = new WeakMap();\nexport function MuSigFactory(ecc) {\n const CPOINT_INF = new Uint8Array(33);\n const SCALAR_0 = new Uint8Array(32);\n const SCALAR_1 = new Uint8Array(32);\n SCALAR_1[31] = 1;\n const SCALAR_MINUS_1 = ecc.scalarNegate(SCALAR_1);\n function keyAggCoeff(publicKeys, publicKey) {\n let coefCache = _coefCache.get(publicKeys);\n if (coefCache === undefined) {\n coefCache = new Map();\n _coefCache.set(publicKeys, coefCache);\n }\n let coefficient = coefCache.get(publicKey);\n if (coefficient) return coefficient;\n coefficient = SCALAR_1;\n let secondPublicKey;\n let publicKeyHash;\n let keyAggCache = _keyAggCache.get(publicKeys);\n if (keyAggCache === undefined) {\n const pkIdx2 = publicKeys.findIndex((pk) => compare33b(pk, publicKeys[0]) !== 0);\n secondPublicKey = publicKeys[pkIdx2];\n publicKeyHash = ecc.taggedHash(TAGS.keyagg_list, ...publicKeys);\n keyAggCache = { publicKeyHash, secondPublicKey };\n _keyAggCache.set(publicKeys, keyAggCache);\n } else {\n ({ publicKeyHash, secondPublicKey } = keyAggCache);\n }\n if (secondPublicKey === undefined || compare33b(publicKey, secondPublicKey) !== 0)\n coefficient = ecc.taggedHash(TAGS.keyagg_coef, publicKeyHash, publicKey);\n coefCache.set(publicKey, coefficient);\n return coefficient;\n }\n function addTweak(ctx, t) {\n const tweak = 'tweak' in t ? t : { tweak: t };\n if (!ecc.isScalar(tweak.tweak))\n throw new TypeError('Expected tweak to be a valid scalar with curve order');\n let { gacc, tacc } = ctx;\n let aggPublicKey = ctx.aggPublicKey;\n if (!ecc.hasEvenY(aggPublicKey) && tweak.xOnly) {\n gacc = ecc.scalarNegate(gacc);\n tacc = ecc.scalarNegate(tacc);\n aggPublicKey = ecc.pointNegate(aggPublicKey);\n }\n aggPublicKey = ecc.pointAddTweak(aggPublicKey, tweak.tweak, false);\n if (aggPublicKey === null) throw new Error('Unexpected point at infinity during tweaking');\n tacc = ecc.scalarAdd(tweak.tweak, tacc);\n return { aggPublicKey, gacc, tacc };\n }\n function keyAgg(publicKeys, ...tweaks) {\n checkArgs({ publicKeys });\n const multipliedPublicKeys = publicKeys.map((publicKey) => {\n const coefficient = keyAggCoeff(publicKeys, publicKey);\n let multipliedPublicKey;\n if (compare32b(coefficient, SCALAR_1) === 0) {\n multipliedPublicKey = publicKey;\n } else {\n multipliedPublicKey = ecc.pointMultiplyUnsafe(publicKey, coefficient, false);\n }\n if (multipliedPublicKey === null) throw new Error('Point at infinity during aggregation');\n return multipliedPublicKey;\n });\n const aggPublicKey = multipliedPublicKeys.reduce((a, b) => {\n const next = ecc.pointAdd(a, b, false);\n if (next === null) throw new Error('Point at infinity during aggregation');\n return next;\n });\n return tweaks.reduce((ctx, tweak) => addTweak(ctx, tweak), {\n aggPublicKey,\n gacc: SCALAR_1,\n tacc: SCALAR_0,\n });\n }\n function getSessionValues(sessionKey) {\n const sessionValues = _sessionCache.get(sessionKey);\n if (!sessionValues) throw new Error('Invalid session key, please call `startSigningSession`');\n return sessionValues;\n }\n function nonceAgg(publicNonces) {\n checkArgs({ publicNonces });\n const aggNonces = [publicNonces[0].subarray(0, 33), publicNonces[0].subarray(33)];\n for (let i = 1; i < publicNonces.length; i++) {\n if (aggNonces[0] !== null)\n aggNonces[0] = ecc.pointAdd(aggNonces[0], publicNonces[i].subarray(0, 33), false);\n if (aggNonces[1] !== null)\n aggNonces[1] = ecc.pointAdd(aggNonces[1], publicNonces[i].subarray(33), false);\n }\n const aggNonce = new Uint8Array(66);\n if (aggNonces[0] !== null) aggNonce.set(ecc.pointCompress(aggNonces[0]), 0);\n if (aggNonces[1] !== null) aggNonce.set(ecc.pointCompress(aggNonces[1]), 33);\n return aggNonce;\n }\n function startSigningSessionInner(aggNonce, msg, publicKeys, ctx) {\n const pubKeyX = ecc.pointX(ctx.aggPublicKey);\n const coefficient = ecc.taggedHash(TAGS.musig_noncecoef, aggNonce, pubKeyX, msg);\n const aggNonces = [aggNonce.subarray(0, 33), aggNonce.subarray(33)];\n let r = null;\n if (compare33b(aggNonces[1], CPOINT_INF) !== 0 && compare33b(aggNonces[0], CPOINT_INF) !== 0) {\n r = ecc.pointMultiplyAndAddUnsafe(aggNonces[1], coefficient, aggNonces[0], false);\n } else if (compare33b(aggNonces[0], CPOINT_INF) !== 0) {\n r = ecc.pointCompress(aggNonces[0], false);\n } else if (compare33b(aggNonces[1], CPOINT_INF) !== 0) {\n r = ecc.pointMultiplyUnsafe(aggNonces[1], coefficient, false);\n }\n if (r === null) r = ecc.getPublicKey(SCALAR_1, false);\n if (r === null) throw new Error('Failed to get G');\n const challenge = ecc.scalarMod(ecc.taggedHash(TAGS.challenge, ecc.pointX(r), pubKeyX, msg));\n const key = { publicKey: ctx.aggPublicKey, aggNonce, msg };\n _sessionCache.set(key, { ...ctx, coefficient, challenge, finalNonce: r, publicKeys });\n return key;\n }\n function partialVerifyInner({ sig, publicKey, publicNonces, sessionKey }) {\n const { msg } = sessionKey;\n const { aggPublicKey, gacc, challenge, coefficient, finalNonce, publicKeys } =\n getSessionValues(sessionKey);\n const rePrime = ecc.pointMultiplyAndAddUnsafe(\n publicNonces[1],\n coefficient,\n publicNonces[0],\n false\n );\n if (rePrime === null) throw new Error('Unexpected public nonce at infinity');\n const re = ecc.hasEvenY(finalNonce) ? rePrime : ecc.pointNegate(rePrime);\n const a = keyAggCoeff(publicKeys, publicKey);\n const g = ecc.hasEvenY(aggPublicKey) ? gacc : ecc.scalarNegate(gacc);\n const ea = ecc.scalarMultiply(challenge, a);\n const eag = ecc.scalarMultiply(ea, g);\n const ver = ecc.pointMultiplyAndAddUnsafe(publicKey, eag, re, true);\n if (ver === null) throw new Error('Unexpected verification point at infinity');\n const sG = ecc.getPublicKey(sig, true);\n if (sG === null) throw new Error('Unexpected signature point at infinity');\n return compare33b(ver, sG) === 0;\n }\n function partialSignInner({ secretKey, publicKey, secretNonces, sessionKey }) {\n const { msg } = sessionKey;\n const { aggPublicKey, gacc, challenge, coefficient, finalNonce, publicKeys } =\n getSessionValues(sessionKey);\n const [k1, k2] = secretNonces.map((k) => (ecc.hasEvenY(finalNonce) ? k : ecc.scalarNegate(k)));\n const a = keyAggCoeff(publicKeys, publicKey);\n const g = ecc.hasEvenY(aggPublicKey) ? gacc : ecc.scalarNegate(gacc);\n const d = ecc.scalarMultiply(g, secretKey);\n const bk2 = ecc.scalarMultiply(coefficient, k2);\n const k1bk2 = ecc.scalarAdd(k1, bk2);\n const ea = ecc.scalarMultiply(challenge, a);\n const ead = ecc.scalarMultiply(ea, d);\n const sig = ecc.scalarAdd(k1bk2, ead);\n return sig;\n }\n function partialSign({ secretKey, publicNonce, sessionKey, verify = true }) {\n checkArgs({ publicNonce, secretKey });\n const secretNonce = _nonceCache.get(publicNonce);\n if (secretNonce === undefined)\n throw new Error('No secret nonce found for specified public nonce');\n _nonceCache.delete(publicNonce);\n const publicKey = ecc.getPublicKey(secretKey, true);\n if (publicKey === null) throw new Error('Invalid secret key, no corresponding public key');\n if (compare33b(publicKey, secretNonce.subarray(64)) !== 0)\n throw new Error('Secret nonce pubkey mismatch');\n const secretNonces = [secretNonce.subarray(0, 32), secretNonce.subarray(32, 64)];\n const sig = partialSignInner({\n secretKey,\n publicKey,\n secretNonces,\n sessionKey,\n });\n if (verify) {\n const publicNonces = [publicNonce.subarray(0, 33), publicNonce.subarray(33)];\n const valid = partialVerifyInner({\n sig,\n publicKey,\n publicNonces,\n sessionKey,\n });\n if (!valid) throw new Error('Partial signature failed verification');\n }\n return sig;\n }\n function deterministicSign({\n secretKey,\n aggOtherNonce,\n publicKeys,\n tweaks = [],\n msg,\n rand,\n verify = true,\n nonceOnly = false,\n }) {\n checkArgs({ rand, secretKey, aggOtherNonce });\n const publicKey = ecc.getPublicKey(secretKey, true);\n if (publicKey === null) throw new Error('Secret key has no corresponding public key');\n let secretKeyPrime;\n if (rand !== undefined) {\n secretKeyPrime = ecc.taggedHash(TAGS.musig_aux, rand);\n for (let i = 0; i < 32; i++) {\n secretKeyPrime[i] = secretKeyPrime[i] ^ secretKey[i];\n }\n } else {\n secretKeyPrime = secretKey;\n }\n const ctx = keyAgg(publicKeys, ...tweaks);\n const aggPublicKey = ecc.pointX(ctx.aggPublicKey);\n const mLength = new Uint8Array(8);\n new DataView(mLength.buffer).setBigUint64(0, BigInt(msg.length));\n const secretNonce = new Uint8Array(97);\n const publicNonce = new Uint8Array(66);\n for (let i = 0; i < 2; i++) {\n const kH = ecc.taggedHash(\n TAGS.musig_deterministic_nonce,\n ...[secretKeyPrime, aggOtherNonce, aggPublicKey, mLength, msg, Uint8Array.of(i)]\n );\n const k = ecc.scalarMod(kH);\n if (compare32b(SCALAR_0, k) === 0) throw new Error('0 secret nonce');\n const pub = ecc.getPublicKey(k, true);\n if (pub === null) throw new Error('Secret nonce has no corresponding public nonce');\n secretNonce.set(k, i * 32);\n publicNonce.set(pub, i * 33);\n }\n secretNonce.set(publicKey, 64);\n if (nonceOnly) return { publicNonce };\n _nonceCache.set(publicNonce, secretNonce);\n const aggNonce = nonceAgg([aggOtherNonce, publicNonce]);\n const sessionKey = startSigningSessionInner(aggNonce, msg, publicKeys, ctx);\n const sig = partialSign({\n secretKey,\n publicNonce,\n sessionKey,\n verify,\n });\n return { sig, sessionKey, publicNonce };\n }\n const pubKeyArgs = ['publicKey', 'publicKeys'];\n const scalarArgs = ['tweak', 'sig', 'sigs', 'tacc', 'gacc'];\n const otherArgs32b = ['xOnlyPublicKey', 'rand', 'sessionId'];\n const args32b = ['secretKey', ...scalarArgs, ...otherArgs32b];\n const pubNonceArgs = ['publicNonce', 'publicNonces', 'aggNonce', 'aggOtherNonce', 'finalNonce'];\n const otherArgs = ['aggPublicKey', 'secretNonce'];\n const argLengths = new Map();\n args32b.forEach((a) => argLengths.set(a, 32));\n pubKeyArgs.forEach((a) => argLengths.set(a, 33));\n pubNonceArgs.forEach((a) => argLengths.set(a, 66));\n argLengths.set('secretNonce', 97);\n argLengths.set('aggPublicKey', 65);\n const scalarNames = new Set();\n scalarArgs.forEach((n) => scalarNames.add(n));\n function checkArgs(args) {\n for (let [name, values] of Object.entries(args)) {\n if (values === undefined) continue;\n values = Array.isArray(values) ? values : [values];\n if (values.length === 0) throw new TypeError(`0-length ${name}s not supported`);\n for (const value of values) {\n if (argLengths.get(name) !== value.length)\n throw new TypeError(`Invalid ${name} length (${value.length})`);\n if (name === 'secretKey') {\n if (!ecc.isSecret(value)) throw new TypeError(`Invalid secretKey`);\n } else if (name === 'secretNonce') {\n for (let i = 0; i < 64; i += 32)\n if (!ecc.isSecret(value.subarray(i, i + 32)))\n throw new TypeError(`Invalid secretNonce`);\n } else if (scalarNames.has(name)) {\n for (let i = 0; i < value.length; i += 32)\n if (!ecc.isScalar(value.subarray(i, i + 32))) throw new TypeError(`Invalid ${name}`);\n }\n }\n }\n }\n return {\n getXOnlyPubkey: (ctx) => {\n if ('aggPublicKey' in ctx) return ecc.pointX(ctx.aggPublicKey);\n return ecc.pointX(getSessionValues(ctx).aggPublicKey);\n },\n getPlainPubkey: (ctx) => {\n if ('aggPublicKey' in ctx) return ecc.pointCompress(ctx.aggPublicKey);\n return ecc.pointCompress(getSessionValues(ctx).aggPublicKey);\n },\n keySort: (publicKeys) => {\n checkArgs({ publicKeys });\n return [...publicKeys].sort((a, b) => compare33b(a, b));\n },\n keyAgg,\n addTweaks: (ctx, ...tweaks) => {\n checkArgs(ctx);\n return tweaks.reduce((c, tweak) => addTweak(c, tweak), ctx);\n },\n nonceGen: ({\n sessionId = makeSessionId(),\n secretKey,\n publicKey,\n xOnlyPublicKey,\n msg,\n extraInput,\n }) => {\n if (extraInput !== undefined && extraInput.length > Math.pow(2, 32) - 1)\n throw new TypeError('extraInput is limited to 2^32-1 bytes');\n checkArgs({ sessionId, secretKey, publicKey, xOnlyPublicKey });\n let rand;\n if (secretKey !== undefined) {\n rand = ecc.taggedHash(TAGS.musig_aux, sessionId);\n for (let i = 0; i < 32; i++) {\n rand[i] = rand[i] ^ secretKey[i];\n }\n } else {\n rand = sessionId;\n }\n if (xOnlyPublicKey === undefined) xOnlyPublicKey = new Uint8Array();\n const mPrefixed = [Uint8Array.of(0)];\n if (msg !== undefined) {\n mPrefixed[0][0] = 1;\n mPrefixed.push(new Uint8Array(8));\n new DataView(mPrefixed[1].buffer).setBigUint64(0, BigInt(msg.length));\n mPrefixed.push(msg);\n }\n if (extraInput === undefined) extraInput = new Uint8Array();\n const eLength = new Uint8Array(4);\n new DataView(eLength.buffer).setUint32(0, extraInput.length);\n const secretNonce = new Uint8Array(97);\n const publicNonce = new Uint8Array(66);\n for (let i = 0; i < 2; i++) {\n const kH = ecc.taggedHash(\n TAGS.musig_nonce,\n rand,\n Uint8Array.of(publicKey.length),\n publicKey,\n Uint8Array.of(xOnlyPublicKey.length),\n xOnlyPublicKey,\n ...mPrefixed,\n eLength,\n extraInput,\n Uint8Array.of(i)\n );\n const k = ecc.scalarMod(kH);\n if (compare32b(SCALAR_0, k) === 0) throw new Error('0 secret nonce');\n const pub = ecc.getPublicKey(k, true);\n if (pub === null) throw new Error('Secret nonce has no corresponding public nonce');\n secretNonce.set(k, i * 32);\n publicNonce.set(pub, i * 33);\n }\n secretNonce.set(publicKey, 64);\n _nonceCache.set(publicNonce, secretNonce);\n return publicNonce;\n },\n addExternalNonce: (publicNonce, secretNonce) => {\n checkArgs({ publicNonce, secretNonce });\n _nonceCache.set(publicNonce, secretNonce);\n },\n deterministicNonceGen: (args) => deterministicSign({ ...args, nonceOnly: true }),\n deterministicSign,\n nonceAgg,\n startSigningSession: (aggNonce, msg, publicKeys, ...tweaks) => {\n checkArgs({ aggNonce });\n const ctx = keyAgg(publicKeys, ...tweaks);\n return startSigningSessionInner(aggNonce, msg, publicKeys, ctx);\n },\n partialSign,\n partialVerify: ({ sig, publicKey, publicNonce, sessionKey }) => {\n checkArgs({ sig, publicKey, publicNonce });\n const publicNonces = [publicNonce.subarray(0, 33), publicNonce.subarray(33)];\n const valid = partialVerifyInner({\n sig,\n publicKey,\n publicNonces,\n sessionKey,\n });\n return valid;\n },\n signAgg: (sigs, sessionKey) => {\n checkArgs({ sigs });\n const { aggPublicKey, tacc, challenge, finalNonce } = getSessionValues(sessionKey);\n let sPart = ecc.scalarMultiply(challenge, tacc);\n if (!ecc.hasEvenY(aggPublicKey)) {\n sPart = ecc.scalarNegate(sPart);\n }\n const aggS = sigs.reduce((a, b) => ecc.scalarAdd(a, b), sPart);\n const sig = new Uint8Array(64);\n sig.set(ecc.pointX(finalNonce), 0);\n sig.set(aggS, 32);\n return sig;\n },\n };\n}\n","import { AbstractHDWallet, _guard } from './hdwallet.js';\nimport { HDNodeWallet } from './hdnodewallet.js';\nimport { computeAddress } from '../address/index.js';\nimport { getBytes, hexlify } from '../utils/index.js';\nimport { QiTransaction } from '../transaction/index.js';\nimport { MuSigFactory } from '@brandonblack/musig';\nimport { schnorr } from '@noble/curves/secp256k1';\nimport { keccak_256 } from '@noble/hashes/sha3';\nimport { musigCrypto } from '../crypto/index.js';\nimport { getZoneForAddress } from '../utils/index.js';\nimport { Mnemonic } from './mnemonic.js';\n/**\n * The Qi HD wallet is a BIP44-compliant hierarchical deterministic wallet used for managing a set of addresses in the\n * Qi ledger. This is wallet implementation is the primary way to interact with the Qi UTXO ledger on the Quai network.\n *\n * The Qi HD wallet supports:\n *\n * - Adding accounts to the wallet heierchy\n * - Generating addresses for a specific account in any {@link Zone}\n * - Signing and sending transactions for any address in the wallet\n * - Serializing the wallet to JSON and deserializing it back to a wallet instance.\n *\n * @category Wallet\n * @example\n *\n * ```ts\n * import { QiHDWallet, Zone } from 'quais';\n *\n * const wallet = new QiHDWallet();\n * const cyrpus1Address = await wallet.getNextAddress(0, Zone.Cyrpus1); // get the first address in the Cyrpus1 zone\n * await wallet.sendTransaction({ txInputs: [...], txOutputs: [...] }); // send a transaction\n * const serializedWallet = wallet.serialize(); // serialize current (account/address) state of the wallet\n * .\n * .\n * .\n * const deserializedWallet = QiHDWallet.deserialize(serializedWallet); // create a new wallet instance from the serialized data\n * ```\n */\nclass QiHDWallet extends AbstractHDWallet {\n /**\n * @ignore\n * @type {number}\n */\n static _version = 1;\n /**\n * @ignore\n * @type {number}\n */\n static _GAP_LIMIT = 20;\n /**\n * @ignore\n * @type {AllowedCoinType}\n */\n static _coinType = 969;\n /**\n * Map of change addresses to address info.\n *\n * @ignore\n * @type {Map}\n */\n _changeAddresses = new Map();\n /**\n * Array of gap addresses.\n *\n * @ignore\n * @type {NeuteredAddressInfo[]}\n */\n _gapChangeAddresses = [];\n /**\n * Array of gap change addresses.\n *\n * @ignore\n * @type {NeuteredAddressInfo[]}\n */\n _gapAddresses = [];\n /**\n * Array of outpoint information.\n *\n * @ignore\n * @type {OutpointInfo[]}\n */\n _outpoints = [];\n /**\n * @ignore\n * @param {HDNodeWallet} root - The root HDNodeWallet.\n * @param {Provider} [provider] - The provider (optional).\n */\n constructor(guard, root, provider) {\n super(guard, root, provider);\n }\n /**\n * Promise that resolves to the next change address for the specified account and zone.\n *\n * @param {number} account - The index of the account for which to retrieve the next change address.\n * @param {Zone} zone - The zone in which to retrieve the next change address.\n * @returns {Promise} The next change neutered address information.\n */\n async getNextChangeAddress(account, zone) {\n return Promise.resolve(this._getNextAddress(account, zone, true, this._changeAddresses));\n }\n /**\n * Synchronously retrieves the next change address for the specified account and zone.\n *\n * @param {number} account - The index of the account for which to retrieve the next change address.\n * @param {Zone} zone - The zone in which to retrieve the next change address.\n * @returns {NeuteredAddressInfo} The next change neutered address information.\n */\n getNextChangeAddressSync(account, zone) {\n return this._getNextAddress(account, zone, true, this._changeAddresses);\n }\n /**\n * Imports an array of outpoints.\n *\n * @param {OutpointInfo[]} outpoints - The outpoints to import.\n */\n importOutpoints(outpoints) {\n this.validateOutpointInfo(outpoints);\n this._outpoints.push(...outpoints);\n }\n /**\n * Gets the outpoints for the specified zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {OutpointInfo[]} The outpoints for the zone.\n */\n getOutpoints(zone) {\n this.validateZone(zone);\n return this._outpoints.filter((outpoint) => outpoint.zone === zone);\n }\n /**\n * Signs a Qi transaction and returns the serialized transaction.\n *\n * @param {QiTransactionRequest} tx - The transaction to sign.\n * @returns {Promise} The serialized transaction.\n * @throws {Error} If the UTXO transaction is invalid.\n */\n async signTransaction(tx) {\n const txobj = QiTransaction.from(tx);\n if (!txobj.txInputs || txobj.txInputs.length == 0 || !txobj.txOutputs)\n throw new Error('Invalid UTXO transaction, missing inputs or outputs');\n const hash = keccak_256(txobj.unsignedSerialized);\n let signature;\n if (txobj.txInputs.length == 1) {\n signature = this.createSchnorrSignature(txobj.txInputs[0], hash);\n }\n else {\n signature = this.createMuSigSignature(txobj, hash);\n }\n txobj.signature = signature;\n return txobj.serialized;\n }\n /**\n * Sends a Qi transaction.\n *\n * @param {QiTransactionRequest} tx - The transaction to send.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the provider is not set or if the transaction has no inputs.\n */\n async sendTransaction(tx) {\n if (!this.provider) {\n throw new Error('Provider is not set');\n }\n if (!tx.txInputs || tx.txInputs.length === 0) {\n throw new Error('Transaction has no inputs');\n }\n const input = tx.txInputs[0];\n const address = computeAddress(input.pubkey);\n const shard = getZoneForAddress(address);\n if (!shard) {\n throw new Error(`Address ${address} not found in any shard`);\n }\n // verify all inputs are from the same shard\n if (tx.txInputs.some((input) => getZoneForAddress(computeAddress(input.pubkey)) !== shard)) {\n throw new Error('All inputs must be from the same shard');\n }\n const signedTx = await this.signTransaction(tx);\n return await this.provider.broadcastTransaction(shard, signedTx);\n }\n /**\n * Returns a schnorr signature for the given message and private key.\n *\n * @ignore\n * @param {TxInput} input - The transaction input.\n * @param {Uint8Array} hash - The hash of the message.\n * @returns {string} The schnorr signature.\n */\n createSchnorrSignature(input, hash) {\n const privKey = this.getPrivateKeyForTxInput(input);\n const signature = schnorr.sign(hash, getBytes(privKey));\n return hexlify(signature);\n }\n /**\n * Returns a MuSig signature for the given message and private keys corresponding to the input addresses.\n *\n * @ignore\n * @param {QiTransaction} tx - The Qi transaction.\n * @param {Uint8Array} hash - The hash of the message.\n * @returns {string} The MuSig signature.\n */\n createMuSigSignature(tx, hash) {\n const musig = MuSigFactory(musigCrypto);\n // Collect private keys corresponding to the pubkeys found on the inputs\n const privKeysSet = new Set();\n tx.txInputs.forEach((input) => {\n const privKey = this.getPrivateKeyForTxInput(input);\n privKeysSet.add(privKey);\n });\n const privKeys = Array.from(privKeysSet);\n // Create an array of public keys corresponding to the private keys for musig aggregation\n const pubKeys = privKeys\n .map((privKey) => musigCrypto.getPublicKey(getBytes(privKey), true))\n .filter((pubKey) => pubKey !== null);\n // Generate nonces for each public key\n const nonces = pubKeys.map((pk) => musig.nonceGen({ publicKey: getBytes(pk) }));\n const aggNonce = musig.nonceAgg(nonces);\n const signingSession = musig.startSigningSession(aggNonce, hash, pubKeys);\n // Create partial signatures for each private key\n const partialSignatures = privKeys.map((sk, index) => musig.partialSign({\n secretKey: getBytes(sk || ''),\n publicNonce: nonces[index],\n sessionKey: signingSession,\n verify: true,\n }));\n // Aggregate the partial signatures into a final aggregated signature\n const finalSignature = musig.signAgg(partialSignatures, signingSession);\n return hexlify(finalSignature);\n }\n /**\n * Retrieves the private key for a given transaction input.\n *\n * This method derives the private key for a transaction input by following these steps:\n *\n * 1. Ensures the input contains a public key.\n * 2. Computes the address from the public key.\n * 3. Fetches address information associated with the computed address.\n * 4. Derives the hierarchical deterministic (HD) node corresponding to the address.\n * 5. Returns the private key of the derived HD node.\n *\n * @ignore\n * @param {TxInput} input - The transaction input containing the public key.\n * @returns {string} The private key corresponding to the transaction input.\n * @throws {Error} If the input does not contain a public key or if the address information cannot be found.\n */\n getPrivateKeyForTxInput(input) {\n if (!input.pubkey)\n throw new Error('Missing public key for input');\n const address = computeAddress(input.pubkey);\n // get address info\n const addressInfo = this.getAddressInfo(address);\n if (!addressInfo)\n throw new Error(`Address not found: ${address}`);\n // derive an HDNode for the address and get the private key\n const changeIndex = addressInfo.change ? 1 : 0;\n const addressNode = this._root\n .deriveChild(addressInfo.account)\n .deriveChild(changeIndex)\n .deriveChild(addressInfo.index);\n return addressNode.privateKey;\n }\n /**\n * Scans the specified zone for addresses with unspent outputs. Starting at index 0, it will generate new addresses\n * until the gap limit is reached for both gap and change addresses.\n *\n * @param {Zone} zone - The zone in which to scan for addresses.\n * @param {number} [account=0] - The index of the account to scan. Default is `0`\n * @returns {Promise} A promise that resolves when the scan is complete.\n * @throws {Error} If the zone is invalid.\n */\n async scan(zone, account = 0) {\n this.validateZone(zone);\n // flush the existing addresses and outpoints\n this._addresses = new Map();\n this._changeAddresses = new Map();\n this._gapAddresses = [];\n this._gapChangeAddresses = [];\n this._outpoints = [];\n await this._scan(zone, account);\n }\n /**\n * Scans the specified zone for addresses with unspent outputs. Starting at the last address index, it will generate\n * new addresses until the gap limit is reached for both gap and change addresses. If no account is specified, it\n * will scan all accounts known to the wallet.\n *\n * @param {Zone} zone - The zone in which to sync addresses.\n * @param {number} [account] - The index of the account to sync. If not specified, all accounts will be scanned.\n * @returns {Promise} A promise that resolves when the sync is complete.\n * @throws {Error} If the zone is invalid.\n */\n async sync(zone, account) {\n this.validateZone(zone);\n // if no account is specified, scan all accounts.\n if (account === undefined) {\n const addressInfos = Array.from(this._addresses.values());\n const accounts = addressInfos.reduce((unique, info) => {\n if (!unique.includes(info.account)) {\n unique.push(info.account);\n }\n return unique;\n }, []);\n for (const acc of accounts) {\n await this._scan(zone, acc);\n }\n }\n else {\n await this._scan(zone, account);\n }\n return;\n }\n /**\n * Internal method to scan the specified zone for addresses with unspent outputs. This method handles the actual\n * scanning logic, generating new addresses until the gap limit is reached for both gap and change addresses.\n *\n * @param {Zone} zone - The zone in which to scan for addresses.\n * @param {number} [account=0] - The index of the account to scan. Default is `0`\n * @returns {Promise} A promise that resolves when the scan is complete.\n * @throws {Error} If the provider is not set.\n */\n async _scan(zone, account = 0) {\n if (!this.provider)\n throw new Error('Provider not set');\n let gapAddressesCount = 0;\n let changeGapAddressesCount = 0;\n while (gapAddressesCount < QiHDWallet._GAP_LIMIT || changeGapAddressesCount < QiHDWallet._GAP_LIMIT) {\n [gapAddressesCount, changeGapAddressesCount] = await Promise.all([\n gapAddressesCount < QiHDWallet._GAP_LIMIT\n ? this.scanAddress(zone, account, false, gapAddressesCount)\n : gapAddressesCount,\n changeGapAddressesCount < QiHDWallet._GAP_LIMIT\n ? this.scanAddress(zone, account, true, changeGapAddressesCount)\n : changeGapAddressesCount,\n ]);\n }\n }\n /**\n * Scans for the next address in the specified zone and account, checking for associated outpoints, and updates the\n * address count and gap addresses accordingly.\n *\n * @param {Zone} zone - The zone in which the address is being scanned.\n * @param {number} account - The index of the account for which the address is being scanned.\n * @param {boolean} isChange - A flag indicating whether the address is a change address.\n * @param {number} addressesCount - The current count of addresses scanned.\n * @returns {Promise} A promise that resolves to the updated address count.\n * @throws {Error} If an error occurs during the address scanning or outpoints retrieval process.\n */\n async scanAddress(zone, account, isChange, addressesCount) {\n const addressMap = isChange ? this._changeAddresses : this._addresses;\n const addressInfo = this._getNextAddress(account, zone, isChange, addressMap);\n const outpoints = await this.getOutpointsByAddress(addressInfo.address);\n if (outpoints.length > 0) {\n this.importOutpoints(outpoints.map((outpoint) => ({\n outpoint,\n address: addressInfo.address,\n zone,\n account,\n })));\n addressesCount = 0;\n isChange ? (this._gapChangeAddresses = []) : (this._gapAddresses = []);\n }\n else {\n addressesCount++;\n isChange ? this._gapChangeAddresses.push(addressInfo) : this._gapAddresses.push(addressInfo);\n }\n return addressesCount;\n }\n /**\n * Queries the network node for the outpoints of the specified address.\n *\n * @ignore\n * @param {string} address - The address to query.\n * @returns {Promise} The outpoints for the address.\n * @throws {Error} If the query fails.\n */\n async getOutpointsByAddress(address) {\n try {\n const outpointsMap = await this.provider.getOutpointsByAddress(address);\n if (!outpointsMap) {\n return [];\n }\n return Object.values(outpointsMap);\n }\n catch (error) {\n throw new Error(`Failed to get outpoints for address: ${address} - error: ${error}`);\n }\n }\n /**\n * Gets the change addresses for the specified zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {NeuteredAddressInfo[]} The change addresses for the zone.\n */\n getChangeAddressesForZone(zone) {\n this.validateZone(zone);\n const changeAddresses = this._changeAddresses.values();\n return Array.from(changeAddresses).filter((addressInfo) => addressInfo.zone === zone);\n }\n /**\n * Gets the gap addresses for the specified zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {NeuteredAddressInfo[]} The gap addresses for the zone.\n */\n getGapAddressesForZone(zone) {\n this.validateZone(zone);\n const gapAddresses = this._gapAddresses.filter((addressInfo) => addressInfo.zone === zone);\n return gapAddresses;\n }\n /**\n * Gets the gap change addresses for the specified zone.\n *\n * @param {Zone} zone - The zone.\n * @returns {NeuteredAddressInfo[]} The gap change addresses for the zone.\n */\n getGapChangeAddressesForZone(zone) {\n this.validateZone(zone);\n const gapChangeAddresses = this._gapChangeAddresses.filter((addressInfo) => addressInfo.zone === zone);\n return gapChangeAddresses;\n }\n /**\n * Signs a message using the private key associated with the given address.\n *\n * @param {string} address - The address for which the message is to be signed.\n * @param {string | Uint8Array} message - The message to be signed, either as a string or Uint8Array.\n * @returns {Promise} A promise that resolves to the signature of the message in hexadecimal string format.\n * @throws {Error} If the address does not correspond to a valid HD node or if signing fails.\n */\n async signMessage(address, message) {\n const addrNode = this._getHDNodeForAddress(address);\n const privKey = addrNode.privateKey;\n const digest = keccak_256(message);\n const signature = schnorr.sign(digest, getBytes(privKey));\n return hexlify(signature);\n }\n /**\n * Serializes the HD wallet state into a format suitable for storage or transmission.\n *\n * @returns {SerializedQiHDWallet} An object representing the serialized state of the HD wallet, including\n * outpoints, change addresses, gap addresses, and other inherited properties.\n */\n serialize() {\n const hdwalletSerialized = super.serialize();\n return {\n outpoints: this._outpoints,\n changeAddresses: Array.from(this._changeAddresses.values()),\n gapAddresses: this._gapAddresses,\n gapChangeAddresses: this._gapChangeAddresses,\n ...hdwalletSerialized,\n };\n }\n /**\n * Deserializes a serialized QiHDWallet object and reconstructs the wallet instance.\n *\n * @param {SerializedQiHDWallet} serialized - The serialized object representing the state of a QiHDWallet.\n * @returns {Promise} A promise that resolves to a reconstructed QiHDWallet instance.\n * @throws {Error} If the serialized data is invalid or if any addresses in the gap addresses or gap change\n * addresses do not exist in the wallet.\n */\n static async deserialize(serialized) {\n super.validateSerializedWallet(serialized);\n // create the wallet instance\n const mnemonic = Mnemonic.fromPhrase(serialized.phrase);\n const path = this.parentPath(serialized.coinType);\n const root = HDNodeWallet.fromMnemonic(mnemonic, path);\n const wallet = new this(_guard, root);\n // import the addresses\n wallet.importSerializedAddresses(wallet._addresses, serialized.addresses);\n // import the change addresses\n wallet.importSerializedAddresses(wallet._changeAddresses, serialized.changeAddresses);\n // import the gap addresses, verifying they already exist in the wallet\n for (const gapAddressInfo of serialized.gapAddresses) {\n const gapAddress = gapAddressInfo.address;\n if (!wallet._addresses.has(gapAddress)) {\n throw new Error(`Address ${gapAddress} not found in wallet`);\n }\n wallet._gapAddresses.push(gapAddressInfo);\n }\n // import the gap change addresses, verifying they already exist in the wallet\n for (const gapChangeAddressInfo of serialized.gapChangeAddresses) {\n const gapChangeAddress = gapChangeAddressInfo.address;\n if (!wallet._changeAddresses.has(gapChangeAddress)) {\n throw new Error(`Address ${gapChangeAddress} not found in wallet`);\n }\n wallet._gapChangeAddresses.push(gapChangeAddressInfo);\n }\n // validate the outpoints and import them\n wallet.validateOutpointInfo(serialized.outpoints);\n wallet._outpoints.push(...serialized.outpoints);\n return wallet;\n }\n /**\n * Validates an array of OutpointInfo objects. This method checks the validity of each OutpointInfo object by\n * performing the following validations:\n *\n * - Validates the zone using the `validateZone` method.\n * - Checks if the address exists in the wallet.\n * - Checks if the account (if provided) exists in the wallet.\n * - Validates the Outpoint by ensuring that `Txhash`, `Index`, and `Denomination` are not null.\n *\n * @ignore\n * @param {OutpointInfo[]} outpointInfo - An array of OutpointInfo objects to be validated.\n * @throws {Error} If any of the validations fail, an error is thrown with a descriptive message.\n */\n validateOutpointInfo(outpointInfo) {\n outpointInfo.forEach((info) => {\n // validate zone\n this.validateZone(info.zone);\n // validate address and account\n const addressInfo = this.getAddressInfo(info.address);\n if (!addressInfo) {\n throw new Error(`Address ${info.address} not found in wallet`);\n }\n if (info.account !== undefined && info.account !== addressInfo.account) {\n throw new Error(`Account ${info.account} not found for address ${info.address}`);\n }\n // validate Outpoint\n if (info.outpoint.txhash == null || info.outpoint.index == null || info.outpoint.denomination == null) {\n throw new Error(`Invalid Outpoint: ${JSON.stringify(info)} `);\n }\n });\n }\n}\nexport { QiHDWallet };\n//# sourceMappingURL=qi-hdwallet.js.map","/**\n * A **Network** encapsulates the various properties required to interact with a specific chain.\n * @category Providers\n */\nimport { getBigInt, assertArgument } from '../utils/index.js';\nconst Networks = new Map();\n/**\n * A **Network** provides access to a chain's properties and allows for plug-ins to extend functionality.\n *\n * @category Providers\n */\nexport class Network {\n #name;\n #chainId;\n /**\n * Creates a new **Network** for `name` and `chainId`.\n * @param {string} name - The network name.\n * @param {BigNumberish} chainId - The network chain ID.\n */\n constructor(name, chainId) {\n this.#name = name;\n this.#chainId = getBigInt(chainId);\n }\n /**\n * Returns a JSON-compatible representation of a Network.\n * @returns {Object} The JSON representation of the 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 might have multiple names.\n * @returns {string} The network name.\n */\n get name() {\n return this.#name;\n }\n /**\n * Sets the network name.\n * @param {string} value - The new network name.\n */\n set name(value) {\n this.#name = value;\n }\n /**\n * The network chain ID.\n * @returns {bigint} The network chain ID.\n */\n get chainId() {\n return this.#chainId;\n }\n /**\n * Sets the network chain ID.\n * @param {BigNumberish} value - The new network chain ID.\n */\n set chainId(value) {\n this.#chainId = getBigInt(value, 'chainId');\n }\n /**\n * Returns true if `other` matches this network. Any chain ID must match, and if no chain ID is present, the name\n * must match.\n *\n * This method does not currently check for additional properties, such as plug-in compatibility.\n *\n * @param {Networkish} other - The network to compare.\n * @returns {boolean} True if the networks match.\n * @ignore\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 // eslint-disable-next-line no-empty\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 // eslint-disable-next-line no-empty\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 // eslint-disable-next-line no-empty\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 * Create a copy of this Network.\n * @returns {Network} A new Network instance.\n */\n clone() {\n const clone = new Network(this.name, this.chainId);\n return clone;\n }\n /**\n * Returns a new Network for the `network` name or chainId.\n *\n * @param {Networkish} [network] - The network to get.\n * @returns {Network} The Network instance.\n * @throws {Error} If the network is invalid.\n */\n static from(network) {\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 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 return custom;\n }\n assertArgument(false, 'invalid network', 'network', network);\n }\n /**\n * Register `nameOrChainId` with a function which returns an instance of a Network representing that chain.\n *\n * @param {string | number | bigint} nameOrChainId - The name or chain ID to register.\n * @param {() => Network} networkFunc - The function to create the Network.\n * @throws {Error} If a network is already registered for `nameOrChainId`.\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//# sourceMappingURL=network.js.map","import { toZone } from '../constants/index.js';\nimport { toShard } from '../constants/shards.js';\nimport { assert, isHexString } from '../utils/index.js';\nimport { getZoneFromNodeLocation } from '../utils/shards.js';\nimport { getZoneFromEventFilter } from './provider.js';\n/**\n * Deep copies an object.\n *\n * @param {any} obj - The object to copy.\n * @returns {any} The copied object.\n */\nfunction copy(obj) {\n return JSON.parse(JSON.stringify(obj));\n}\n/**\n * Return the polling subscriber for common events.\n *\n * @category Providers\n * @param {AbstractProvider} provider - The provider to attach the subscriber to.\n * @param {ProviderEvent} event - The event to subscribe to.\n * @returns {Subscriber} The polling subscriber.\n * @throws {Error} If the event is unsupported.\n */\nexport function getPollingSubscriber(provider, event, zone) {\n if (event === 'block') {\n return new PollingBlockSubscriber(provider, zone);\n }\n if (isHexString(event, 32)) {\n return new PollingTransactionSubscriber(provider, event, zone);\n }\n assert(false, 'unsupported polling event', 'UNSUPPORTED_OPERATION', {\n operation: 'getPollingSubscriber',\n info: { event },\n });\n}\n/**\n * A **PollingBlockSubscriber** polls at a regular interval for a change in the block number.\n *\n * @category Providers\n */\nexport class PollingBlockSubscriber {\n #provider;\n #poller;\n #interval;\n #zone;\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 * @ignore\n */\n constructor(provider, zone) {\n this.#provider = provider;\n this.#zone = zone;\n this.#poller = null;\n this.#interval = 4000;\n this.#blockNumber = -2;\n }\n /**\n * The polling interval.\n *\n * @returns {number} The current polling interval.\n */\n get pollingInterval() {\n return this.#interval;\n }\n /**\n * Sets the polling interval.\n *\n * @param {number} value - The new polling interval.\n */\n set pollingInterval(value) {\n this.#interval = value;\n }\n /**\n * Polls for new blocks.\n *\n * @ignore\n * @returns {Promise} A promise that resolves when polling is complete.\n */\n async #poll() {\n try {\n const blockNumber = await this.#provider.getBlockNumber(toShard(this.#zone));\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', this.#zone, 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 }\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 /**\n * Starts the polling process.\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 /**\n * Stops the polling process.\n */\n stop() {\n if (!this.#poller) {\n return;\n }\n this.#provider._clearTimeout(this.#poller);\n this.#poller = null;\n }\n /**\n * Pauses the polling process.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused.\n */\n pause(dropWhilePaused) {\n this.stop();\n if (dropWhilePaused) {\n this.#blockNumber = -2;\n }\n }\n /**\n * Resumes the polling process.\n */\n resume() {\n this.start();\n }\n}\n/**\n * An **OnBlockSubscriber** can be sub-classed, with a {@link OnBlockSubscriber._poll | **_poll**} implementation which\n * will be called on every new block.\n *\n * @category Providers\n */\nexport class OnBlockSubscriber {\n #provider;\n #poll;\n #running;\n #zone;\n /**\n * Create a new **OnBlockSubscriber** attached to `provider`.\n *\n * @ignore\n */\n constructor(provider, zone) {\n this.#provider = provider;\n this.#zone = zone;\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 * @ignore\n * @param {number} blockNumber - The block number.\n * @param {AbstractProvider} provider - The provider.\n * @returns {Promise} A promise that resolves when the poll is complete.\n * @throws {Error} If the method is not overridden by a subclass.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _poll(blockNumber, provider) {\n throw new Error('sub-classes must override this');\n }\n /**\n * Starts the subscriber.\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, this.#zone);\n }\n /**\n * Stops the subscriber.\n */\n stop() {\n if (!this.#running) {\n return;\n }\n this.#running = false;\n this.#provider.off('block', this.#poll, this.#zone);\n }\n /**\n * Pauses the subscriber.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pause(dropWhilePaused) {\n this.stop();\n }\n /**\n * Resumes the subscriber.\n */\n resume() {\n this.start();\n }\n}\n/**\n * @ignore\n */\nexport class PollingOrphanSubscriber extends OnBlockSubscriber {\n #filter;\n /**\n * Create a new **PollingOrphanSubscriber** attached to `provider`, listening for `filter`.\n *\n * @ignore\n */\n constructor(provider, filter, zone) {\n super(provider, zone);\n this.#filter = copy(filter);\n }\n /**\n * Polls for orphaned blocks.\n *\n * @ignore\n * @param {number} blockNumber - The block number.\n * @param {AbstractProvider} provider - The provider.\n * @returns {Promise} A promise that resolves when the poll is complete.\n * @throws {Error} If the method is not implemented.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 hash for its receipt.\n *\n * @category Providers\n */\nexport class PollingTransactionSubscriber extends OnBlockSubscriber {\n #hash;\n /**\n * Create a new **PollingTransactionSubscriber** attached to `provider`, listening for `hash`.\n *\n * @ignore\n */\n constructor(provider, hash, zone) {\n super(provider, zone);\n this.#hash = hash;\n }\n /**\n * Polls for the transaction receipt.\n *\n * @ignore\n * @param {number} blockNumber - The block number.\n * @param {AbstractProvider} provider - The provider.\n * @returns {Promise} A promise that resolves when the poll is complete.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _poll(blockNumber, provider) {\n const tx = await provider.getTransactionReceipt(this.#hash);\n if (tx) {\n provider.emit(this.#hash, toZone(this.#hash.slice(0, 4)), tx);\n }\n }\n}\n/**\n * A **PollingEventSubscriber** will poll for a given filter for its logs.\n *\n * @category Providers\n */\nexport class PollingEventSubscriber {\n #provider;\n #filter;\n #poller;\n #running;\n #blockNumber;\n #zone;\n /**\n * Create a new **PollingEventSubscriber** attached to `provider`, listening for `filter`.\n *\n * @ignore\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 const zone = getZoneFromEventFilter(this.#filter);\n if (zone) {\n this.#zone = zone;\n }\n else {\n throw new Error('Unable to determine zone for event filter');\n }\n }\n /**\n * Polls for logs based on the filter.\n *\n * @ignore\n * @param {number} blockNumber - The block number.\n * @returns {Promise} A promise that resolves when the poll is complete.\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, getZoneFromNodeLocation(this.#filter.nodeLocation), 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 /**\n * Starts the subscriber.\n */\n start() {\n if (this.#running) {\n return;\n }\n this.#running = true;\n if (this.#blockNumber === -2) {\n this.#provider.getBlockNumber(toShard(this.#zone)).then((blockNumber) => {\n this.#blockNumber = blockNumber;\n });\n }\n this.#provider.on('block', this.#poller, this.#zone);\n }\n /**\n * Stops the subscriber.\n */\n stop() {\n if (!this.#running) {\n return;\n }\n this.#running = false;\n this.#provider.off('block', this.#poller, this.#zone);\n }\n /**\n * Pauses the subscriber.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop the block number while paused.\n */\n pause(dropWhilePaused) {\n this.stop();\n if (dropWhilePaused) {\n this.#blockNumber = -2;\n }\n }\n /**\n * Resumes the subscriber.\n */\n resume() {\n this.start();\n }\n}\n//# sourceMappingURL=subscriber-polling.js.map","/**\n * The available providers should suffice for most developers purposes, but the\n * {@link AbstractProvider | **AbstractProvider**} class has many features which enable sub-classing it for specific\n * purposes.\n */\n/**\n * Event coalescence When we register an event with an async value (e.g. address is a Signer), we need to add it\n * immediately for the Event API, but also 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 of Signer to address so we can sync respond\n * to listenerCount.\n */\nimport { computeAddress, resolveAddress, formatMixedCaseChecksumAddress } from '../address/index.js';\nimport { Shard, toShard, toZone } from '../constants/index.js';\nimport { hexlify, isHexString, getBigInt, getBytes, getNumber, makeError, assert, assertArgument, FetchRequest, toQuantity, defineProperties, EventPayload, resolveProperties, } from '../utils/index.js';\nimport { decodeProtoTransaction } from '../encoding/index.js';\nimport { formatBlock, formatLog, formatTransactionReceipt, formatTransactionResponse } from './format.js';\nimport { Network } from './network.js';\nimport { copyRequest, Block, FeeData, Log, TransactionReceipt, addressFromTransactionRequest, QuaiTransactionResponse, QiTransactionResponse, } from './provider.js';\nimport { QiTransaction, QuaiTransaction } from '../transaction/index.js';\nimport { PollingBlockSubscriber, PollingEventSubscriber, PollingOrphanSubscriber, PollingTransactionSubscriber, } from './subscriber-polling.js';\nimport { getNodeLocationFromZone, getZoneFromNodeLocation } from '../utils/shards.js';\nimport { fromShard } from '../constants/shards.js';\n/**\n * Constants\n */\nconst BN_2 = BigInt(2);\n/**\n * Check if a value is a Promise.\n *\n * @param {any} value - The value to check.\n * @returns {boolean} True if the value is a Promise, false otherwise.\n */\nfunction isPromise(value) {\n return value && typeof value.then === 'function';\n}\n/**\n * Get a tag string based on a prefix and value.\n *\n * @param {string} prefix - The prefix for the tag.\n * @param {any} value - The value to include in the tag.\n * @returns {string} The generated tag.\n */\nfunction getTag(prefix, value) {\n return (prefix +\n ':' +\n 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 any additional management, such as `\"debug\"`\n * which only requires emit in synchronous event loop triggered calls.\n *\n * @category Providers\n */\nexport class UnmanagedSubscriber {\n /**\n * The name of the event.\n */\n name;\n /**\n * Create a new UnmanagedSubscriber with `name`.\n *\n * @param {string} name - The name of the event.\n */\n constructor(name) {\n defineProperties(this, { name });\n }\n start() { }\n stop() { }\n // todo `dropWhilePaused` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pause(dropWhilePaused) { }\n resume() { }\n}\n/**\n * Create a deep copy of a value.\n *\n * @param {T} value - The value to copy.\n * @returns {T} The copied value.\n */\nfunction copy(value) {\n return JSON.parse(JSON.stringify(value));\n}\n/**\n * Remove duplicates and sort an array of strings.\n *\n * @param {string[]} items - The array of strings.\n * @returns {string[]} The concisified array.\n */\nfunction concisify(items) {\n items = Array.from(new Set(items).values());\n items.sort();\n return items;\n}\n// todo `provider` is not used, remove or re-write\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nasync function getSubscription(_event, zone) {\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 if (_event === 'debug') {\n return { type: _event, tag: _event };\n }\n switch (_event) {\n case 'block':\n case 'pending':\n if (!zone) {\n throw new Error('zone is required for block and pending events');\n }\n return { type: 'block', tag: _event, zone };\n case 'error':\n case 'finalized':\n case 'network':\n case 'safe': {\n return { type: _event, tag: _event };\n }\n }\n }\n if (isHexString(_event, 32)) {\n const hash = _event.toLowerCase();\n zone = toZone(hash.slice(0, 4));\n return { type: 'transaction', tag: getTag('tx', { hash }), hash, zone };\n }\n if (_event.orphan) {\n const event = _event;\n if (!zone) {\n const hash = event.hash ||\n event.tx.hash ||\n event.other?.hash ||\n event.log.transactionHash ||\n null;\n if (hash == null) {\n throw new Error('orphan event must specify a hash');\n }\n zone = toZone(hash.slice(0, 4));\n }\n // @todo Should lowercase and whatnot things here instead of copy...\n return { type: 'orphan', tag: getTag('orphan', event), filter: copy(event), zone };\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.nodeLocation) {\n filter.nodeLocation = event.nodeLocation;\n }\n if (event.address) {\n const addresses = [];\n const promises = [];\n const addAddress = (addr) => {\n if (isHexString(addr)) {\n addresses.push(formatMixedCaseChecksumAddress(addr));\n }\n else {\n promises.push((async () => {\n addresses.push(formatMixedCaseChecksumAddress(await resolveAddress(addr)));\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 if (!zone) {\n zone = toZone(addresses[0].slice(0, 4));\n }\n filter.address = concisify(addresses.map((a) => a.toLowerCase()));\n if (!filter.nodeLocation) {\n filter.nodeLocation = getNodeLocationFromZone(zone);\n }\n }\n else {\n if (!zone) {\n throw new Error('zone is required for event');\n }\n }\n return { filter, tag: getTag('event', filter), type: 'event', zone };\n }\n assertArgument(false, 'unknown ProviderEvent', 'event', _event);\n}\n/**\n * Get the current time in milliseconds.\n *\n * @returns {number} The current time in milliseconds.\n */\nfunction getTime() {\n return new Date().getTime();\n}\nconst defaultOptions = {\n cacheTimeout: 250,\n pollingInterval: 4000,\n usePathing: false,\n};\n/**\n * An **AbstractProvider** provides a base class for other sub-classes to implement the {@link Provider | **Provider**}\n * API by normalizing input arguments and formatting output results as well as tracking events for consistent behaviour\n * on an eventually-consistent network.\n *\n * @category Providers\n */\nexport class AbstractProvider {\n /**\n * @ignore\n */\n _urlMap;\n #connect;\n #subs;\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 #options;\n _initFailed;\n initResolvePromise;\n initRejectPromise;\n initPromise;\n /**\n * Create a new **AbstractProvider** connected to `network`, or use the various network detection capabilities to\n * discover the {@link Network | **Network**} if necessary.\n *\n * @param _network - The network to connect to, or `\"any\"` to\n * @param options - The options to configure the provider.\n */\n constructor(_network, options) {\n this._initFailed = false;\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(() => {\n this.emit('network', undefined, network, null);\n }, 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.#pausedState = null;\n this.#destroyed = false;\n this.#nextTimer = 1;\n this.#timers = new Map();\n this.#connect = [];\n this._urlMap = new Map();\n this.initResolvePromise = null;\n this.initRejectPromise = null;\n this.initPromise = new Promise((resolve, reject) => {\n this.initResolvePromise = resolve;\n this.initRejectPromise = reject;\n });\n }\n /**\n * Initialize the URL map with the provided URLs.\n *\n * @param {U} urls - The URLs to initialize the map with.\n * @returns {Promise} A promise that resolves when the map is initialized.\n */\n async initialize(urls) {\n try {\n const primeSuffix = this.#options.usePathing ? `/${fromShard(Shard.Prime, 'nickname')}` : ':9001';\n if (urls instanceof FetchRequest) {\n urls.url = urls.url.split(':')[0] + ':' + urls.url.split(':')[1] + primeSuffix;\n this._urlMap.set(Shard.Prime, urls);\n this.#connect.push(urls);\n const shards = await this.getRunningLocations();\n shards.forEach((shard) => {\n const port = 9200 + 20 * shard[0] + shard[1];\n const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);\n const shardSuffix = this.#options.usePathing ? `/${fromShard(shardEnum, 'nickname')}` : `:${port}`;\n this._urlMap.set(shardEnum, new FetchRequest(urls.url.split(':')[0] + ':' + urls.url.split(':')[1] + shardSuffix));\n });\n return;\n }\n if (Array.isArray(urls)) {\n for (const url of urls) {\n const primeUrl = url.split(':')[0] + ':' + url.split(':')[1] + primeSuffix;\n const primeConnect = new FetchRequest(primeUrl);\n this._urlMap.set(Shard.Prime, primeConnect);\n this.#connect.push(primeConnect);\n const shards = await this.getRunningLocations();\n shards.forEach((shard) => {\n const port = 9200 + 20 * shard[0] + shard[1];\n const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);\n const shardSuffix = this.#options.usePathing\n ? `/${fromShard(shardEnum, 'nickname')}`\n : `:${port}`;\n this._urlMap.set(toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`), new FetchRequest(url.split(':')[0] + ':' + url.split(':')[1] + shardSuffix));\n });\n }\n }\n if (this.initResolvePromise)\n this.initResolvePromise();\n }\n catch (error) {\n this._initFailed = true;\n console.log('Error initializing URL map:', error);\n if (this.initRejectPromise)\n this.initRejectPromise(error);\n }\n }\n /**\n * Get the list of connected FetchRequests.\n *\n * @returns {FetchRequest[]} The list of connected FetchRequests.\n */\n get connect() {\n return this.#connect;\n }\n /**\n * Get the zone from an address.\n *\n * @param {AddressLike} _address - The address to get the zone from.\n * @returns {Promise} A promise that resolves to the zone.\n */\n async zoneFromAddress(_address) {\n const address = this._getAddress(_address);\n return toZone((await address).slice(0, 4));\n }\n /**\n * Get the shard from a hash.\n *\n * @param {string} hash - The hash to get the shard from.\n * @returns {Shard} The shard.\n */\n shardFromHash(hash) {\n return toShard(hash.slice(0, 4));\n }\n /**\n * Get the zone from a hash.\n *\n * @param {string} hash - The hash to get the zone from.\n * @returns {Zone} The zone.\n */\n zoneFromHash(hash) {\n return toZone(hash.slice(0, 4));\n }\n /**\n * Get the latest Quai rate for a zone.\n *\n * @param {Zone} zone - The zone to get the rate for.\n * @param {number} [amt=1] - The amount to get the rate for. Default is `1`\n * @returns {Promise} A promise that resolves to the latest Quai rate.\n */\n async getLatestQuaiRate(zone, amt = 1) {\n const blockNumber = await this.getBlockNumber(toShard(zone));\n return this.getQuaiRateAtBlock(zone, blockNumber, amt);\n }\n /**\n * Get the Quai rate at a specific block.\n *\n * @param {Zone} zone - The zone to get the rate for.\n * @param {BlockTag} blockTag - The block tag to get the rate at.\n * @param {number} [amt=1] - The amount to get the rate for. Default is `1`\n * @returns {Promise} A promise that resolves to the Quai rate at the specified block.\n */\n async getQuaiRateAtBlock(zone, blockTag, amt = 1) {\n let resolvedBlockTag = this._getBlockTag(toShard(zone), blockTag);\n if (typeof resolvedBlockTag !== 'string') {\n resolvedBlockTag = await resolvedBlockTag;\n }\n return await this.#perform({\n method: 'getQuaiRateAtBlock',\n blockTag: resolvedBlockTag,\n amt,\n zone: zone,\n });\n }\n /**\n * Get the protocol expansion number.\n *\n * @returns {Promise} A promise that resolves to the protocol expansion number.\n */\n async getProtocolExpansionNumber() {\n return await this.#perform({\n method: 'getProtocolExpansionNumber',\n });\n }\n /**\n * Get the latest Qi rate for a zone.\n *\n * @param {Zone} zone - The zone to get the rate for.\n * @param {number} [amt=1] - The amount to get the rate for. Default is `1`\n * @returns {Promise} A promise that resolves to the latest Qi rate.\n */\n async getLatestQiRate(zone, amt = 1) {\n const blockNumber = await this.getBlockNumber(toShard(zone));\n return this.getQiRateAtBlock(zone, blockNumber, amt);\n }\n /**\n * Get the Qi rate at a specific block.\n *\n * @param {Zone} zone - The zone to get the rate for.\n * @param {BlockTag} blockTag - The block tag to get the rate at.\n * @param {number} [amt=1] - The amount to get the rate for. Default is `1`\n * @returns {Promise} A promise that resolves to the Qi rate at the specified block.\n */\n async getQiRateAtBlock(zone, blockTag, amt = 1) {\n let resolvedBlockTag = this._getBlockTag(toShard(zone), blockTag);\n if (typeof resolvedBlockTag !== 'string') {\n resolvedBlockTag = await resolvedBlockTag;\n }\n return await this.#perform({\n method: 'getQiRateAtBlock',\n blockTag: resolvedBlockTag,\n amt,\n zone: zone,\n });\n }\n /**\n * Get the polling interval.\n *\n * @returns {number} The polling interval.\n */\n get pollingInterval() {\n return this.#options.pollingInterval;\n }\n /**\n * Returns `this`, to allow an **AbstractProvider** to implement the [Contract Runner](../classes/ContractRunner)\n * interface.\n *\n * @returns {this} The provider instance.\n */\n get provider() {\n return this;\n }\n /**\n * Shares multiple identical requests made during the same 250ms.\n *\n * @ignore\n * @param {PerformActionRequest} req - The request to perform.\n * @returns {Promise} A promise that resolves to the result of the operation.\n */\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 || tag.includes('pending') || tag.includes('latest')) {\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 * Provides the opportunity for a sub-class to wrap a block before returning it, to add additional properties or an\n * alternate sub-class of {@link Block | **Block**}.\n *\n * @ignore\n * @param {BlockParams} value - The block to wrap.\n * @param {Network} network - The network the block was on.\n * @returns {Block} The wrapped block.\n */\n // @todo `network` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _wrapBlock(value, network) {\n // Handle known node by -> remove null values from the number array\n value.header.number = Array.isArray(value.header.number)\n ? value.header.number.filter((n) => n != null)\n : value.header.number;\n return new Block(formatBlock(value), this);\n }\n /**\n * Provides the opportunity for a sub-class to wrap a log before returning it, to add additional properties or an\n * alternate sub-class of {@link Log | **Log**}.\n *\n * @ignore\n * @param {LogParams} value - The log to wrap.\n * @param {Network} network - The network the log was on.\n * @returns {Log} The wrapped log.\n */\n // @todo `network` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 receipt before returning it, to add additional\n * properties or an {@link TransactionReceipt | **TransactionReceipt**}.\n *\n * @ignore\n * @param {TransactionReceiptParams} value - The transaction receipt to wrap.\n * @param {Network} network - The network the transaction was on.\n * @returns {TransactionReceipt} The wrapped transaction receipt.\n */\n // @todo `network` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _wrapTransactionReceipt(value, network) {\n const formattedReceipt = formatTransactionReceipt(value);\n return new TransactionReceipt(formattedReceipt, this);\n }\n /**\n * Provides the opportunity for a sub-class to wrap a transaction response before returning it, to add additional\n * properties or an alternate sub-class of {@link TransactionResponse | **TransactionResponse**}.\n *\n * @ignore\n * @param {TransactionResponseParams} tx - The transaction response to wrap.\n * @param {Network} network - The network the transaction was on.\n * @returns {TransactionResponse} The wrapped transaction response.\n */\n // TODO: `newtork` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _wrapTransactionResponse(tx, network) {\n if ('from' in tx) {\n return new QuaiTransactionResponse(formatTransactionResponse(tx), this);\n }\n else {\n return new QiTransactionResponse(formatTransactionResponse(tx), this);\n }\n }\n /**\n * Resolves to the Network, forcing a network detection using whatever technique the sub-class requires.\n *\n * Sub-classes **must** override this.\n *\n * @ignore\n * @param {Shard} [shard] - The shard to use for the network detection.\n * @returns {Promise} A promise resolving to the network.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 methods sanitizes and normalizes the values\n * passed into this.\n *\n * Sub-classes **must** override this.\n *\n * @ignore\n * @param {PerformActionRequest} req - The request to perform.\n * @returns {Promise} A promise resolving to the result of the operation.\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(shard) {\n const blockNumber = getNumber(await this.#perform({ method: 'getBlockNumber', shard: shard }), '%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 {@link Addressable | **Addressable**} objects and\n * returning if already an address.\n *\n * @ignore\n * @param {AddressLike} address - The address to normalize.\n * @returns {string | Promise} The normalized address.\n */\n _getAddress(address) {\n return resolveAddress(address);\n }\n /**\n * Returns or resolves to a valid block tag for `blockTag`, resolving negative values and returning if already a\n * valid block tag.\n *\n * @ignore\n * @param {Shard} [shard] - The shard to use for the block tag.\n * @param {BlockTag} [blockTag] - The block tag to normalize.\n * @returns {string | Promise} A promise that resolves to a valid block tag.\n */\n _getBlockTag(shard, 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(shard).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 {@link Addressable | **Addressable**} object and\n * returning if already a valid filter.\n *\n * @ignore\n * @param {Filter | FilterByBlockHash} filter - The filter to normalize.\n * @returns {PerformActionFilter | Promise} A promise that resolves to a valid 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, nodeLocation) => {\n let address = undefined;\n switch (_address.length) {\n case 0:\n 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 if (nodeLocation) {\n filter.nodeLocation = nodeLocation;\n }\n return filter;\n };\n // Addresses could be async (Addressables)\n const 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 const zone = getZoneFromNodeLocation(filter.nodeLocation);\n let fromBlock = undefined;\n if ('fromBlock' in filter) {\n fromBlock = this._getBlockTag(toShard(zone), filter.fromBlock);\n }\n let toBlock = undefined;\n if ('toBlock' in filter) {\n toBlock = this._getBlockTag(toShard(zone), filter.toBlock);\n }\n let nodeLocation = undefined;\n if (filter.nodeLocation) {\n nodeLocation = filter.nodeLocation;\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, nodeLocation]).then((result) => {\n return resolve(result[0], result[1], result[2], result[3]);\n });\n }\n return resolve(address, fromBlock, toBlock, nodeLocation);\n }\n /**\n * Returns or resovles to a transaction for `request`, resolving any {@link Addressable | **Addressable**} and\n * returning if already a valid transaction.\n *\n * @ignore\n * @param {PerformActionTransaction} _request - The transaction to normalize.\n * @returns {PerformActionTransaction | Promise} A promise that resolves to a valid\n * transaction.\n */\n _getTransactionRequest(_request) {\n const request = copyRequest(_request);\n const promises = [];\n ['to', 'from', 'inputs', 'outputs'].forEach((key) => {\n if (request[key] == null) {\n return;\n }\n const addr = Array.isArray(request[key])\n ? 'address' in request[key][0]\n ? request[key].map((it) => it.address)\n : request[key].map((it) => computeAddress(it.pubkey))\n : resolveAddress(request[key]);\n if (isPromise(addr)) {\n if (Array.isArray(addr)) {\n for (let i = 0; i < addr.length; i++) {\n promises.push((async function () {\n request[key][i].address = await addr[i];\n })());\n }\n }\n else {\n promises.push((async function () {\n request[key] = await addr;\n })());\n }\n }\n else {\n request[key] = addr;\n }\n });\n if (request.blockTag != null) {\n const blockTag = this._getBlockTag(toShard(request.chainId.toString()), request.blockTag);\n if (isPromise(blockTag)) {\n promises.push((async function () {\n request.blockTag = await blockTag;\n })());\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', undefined, 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', undefined, 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 _getRunningLocations(shard, now) {\n now = now ? now : false;\n return await this.#perform(shard\n ? { method: 'getRunningLocations', shard: shard, now: now }\n : { method: 'getRunningLocations', now: now });\n }\n async getRunningLocations(shard) {\n return await this._getRunningLocations(shard);\n }\n async getProtocolTrieExpansionCount(shard) {\n return await this.#perform({ method: 'getProtocolTrieExpansionCount', shard: shard });\n }\n async getFeeData(zone, txType = true) {\n const getFeeDataFunc = async () => {\n const { gasPrice, priorityFee } = await resolveProperties({\n gasPrice: (async () => {\n try {\n const value = await this.#perform({ method: 'getGasPrice', txType, zone: zone });\n return getBigInt(value, '%response');\n }\n catch (error) {\n console.log(error);\n }\n return null;\n })(),\n priorityFee: (async () => {\n try {\n const value = txType\n ? await this.#perform({ method: 'getMaxPriorityFeePerGas', zone: zone })\n : 0;\n return getBigInt(value, '%response');\n // eslint-disable-next-line no-empty\n }\n catch (error) { }\n return null;\n })(),\n });\n if (gasPrice == null) {\n throw new Error('could not determine gasPrice');\n }\n let maxFeePerGas = null;\n let maxPriorityFeePerGas = null;\n // These are the recommended EIP-1559 heuristics for fee data\n maxPriorityFeePerGas = priorityFee != null ? priorityFee : BigInt('1000000000');\n maxFeePerGas = gasPrice * BN_2 + maxPriorityFeePerGas;\n return new FeeData(gasPrice, maxFeePerGas, 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 const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx));\n return getBigInt(await this.#perform({\n method: 'estimateGas',\n transaction: tx,\n zone: zone,\n }), '%response');\n }\n // TODO: `attempt` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async #call(tx, blockTag, attempt, zone) {\n // This came in as a PerformActionTransaction, so to/from are safe; we can cast\n const transaction = copyRequest(tx);\n return hexlify(await this._perform({ method: 'call', transaction, blockTag, zone }));\n }\n // TODO: `shard` is not used, remove or re-write\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async #checkNetwork(promise, shard) {\n const { value } = await resolveProperties({\n network: this.getNetwork(),\n value: promise,\n });\n return value;\n }\n async call(_tx) {\n const zone = await this.zoneFromAddress(addressFromTransactionRequest(_tx));\n const shard = toShard(zone);\n const { tx, blockTag } = await resolveProperties({\n tx: this._getTransactionRequest(_tx),\n blockTag: this._getBlockTag(shard, _tx.blockTag),\n });\n return await this.#checkNetwork(this.#call(tx, blockTag, -1, zone), shard);\n }\n // Account\n async #getAccountValue(request, _address, _blockTag) {\n let address = this._getAddress(_address);\n const zone = await this.zoneFromAddress(_address);\n const shard = toShard(zone);\n let blockTag = this._getBlockTag(shard, _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, zone: zone })), shard);\n }\n async getBalance(address, blockTag) {\n return getBigInt(await this.#getAccountValue({ method: 'getBalance' }, address, blockTag), '%response');\n }\n async getOutpointsByAddress(address) {\n const outpoints = await this.#getAccountValue({ method: 'getOutpointsByAddress' }, address, 'latest');\n const outpointsArray = Array.isArray(outpoints) ? outpoints : [];\n return outpointsArray.map((outpoint) => ({\n txhash: outpoint.Txhash,\n index: outpoint.Index,\n denomination: outpoint.Denomination,\n }));\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 async getPendingHeader() {\n return await this.#perform({ method: 'getPendingHeader' });\n }\n async getTxPoolContent(zone) {\n return await this.#perform({ method: 'getTxPoolContent', zone: zone });\n }\n async txPoolInspect(zone) {\n return await this.#perform({ method: 'txPoolInspect', zone: zone });\n }\n // Write\n async broadcastTransaction(zone, signedTx) {\n const type = decodeProtoTransaction(getBytes(signedTx)).type;\n const { blockNumber, hash, network } = await resolveProperties({\n blockNumber: this.getBlockNumber(toShard(zone)),\n hash: this._perform({\n method: 'broadcastTransaction',\n signedTransaction: signedTx,\n zone: zone,\n }),\n network: this.getNetwork(),\n });\n const tx = type == 2 ? QiTransaction.from(signedTx) : QuaiTransaction.from(signedTx);\n this.#validateTransactionHash(tx.hash || '', hash);\n return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber);\n }\n #validateTransactionHash(computedHash, nodehash) {\n if (computedHash !== nodehash) {\n throw new Error('Transaction hash mismatch');\n }\n }\n validateUrl(url) {\n const urlPattern = /^(https?):\\/\\/[a-zA-Z0-9.-]+(:\\d+)?$/;\n if (!urlPattern.test(url)) {\n let errorMessage = 'Invalid URL: ';\n if (!/^https?:\\/\\//.test(url)) {\n errorMessage += 'URL must start with http:// or https://. ';\n }\n if (url.endsWith('/')) {\n errorMessage += 'URL should not end with a /. ';\n }\n if (/\\/[^/]+/.test(url)) {\n errorMessage += 'URL should not contain a path, query string, or fragment. ';\n }\n throw new Error(errorMessage.trim());\n }\n }\n async #getBlock(shard, block, includeTransactions) {\n if (isHexString(block, 32)) {\n return await this.#perform({\n method: 'getBlock',\n blockHash: block,\n includeTransactions,\n shard: shard,\n });\n }\n let blockTag = this._getBlockTag(shard, block);\n if (typeof blockTag !== 'string') {\n blockTag = await blockTag;\n }\n return await this.#perform({\n method: 'getBlock',\n blockTag,\n includeTransactions,\n shard: shard,\n });\n }\n // Queries\n async getBlock(shard, block, prefetchTxs) {\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#getBlock(shard, block, !!prefetchTxs),\n });\n if (params == null) {\n return null;\n }\n return this._wrapBlock(params, network);\n }\n async getTransaction(hash) {\n const zone = toZone(this.shardFromHash(hash));\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#perform({ method: 'getTransaction', hash, zone: zone }),\n });\n if (params == null) {\n return null;\n }\n return this._wrapTransactionResponse(params, network);\n }\n async getTransactionReceipt(hash) {\n const zone = toZone(this.shardFromHash(hash));\n const { network, params } = await resolveProperties({\n network: this.getNetwork(),\n params: this.#perform({ method: 'getTransactionReceipt', hash, zone: zone }),\n });\n if (params == null) {\n return null;\n }\n // Some backends did not backfill the effectiveGasPrice in to 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, zone: zone });\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 zone = toZone(this.shardFromHash(hash));\n const { result } = await resolveProperties({\n network: this.getNetwork(),\n result: this.#perform({ method: 'getTransactionResult', hash, zone: zone }),\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({\n method: 'getLogs',\n filter,\n zone: getZoneFromNodeLocation(filter.nodeLocation),\n }),\n });\n return params.map((p) => this._wrapLog(p, network));\n }\n /**\n * @ignore\n */\n // TODO: unsupported, remove?\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _getProvider(chainId) {\n assert(false, 'provider cannot connect to target network', 'UNSUPPORTED_OPERATION', {\n operation: '_getProvider()',\n });\n }\n async waitForTransaction(hash, _confirms, timeout) {\n const zone = this.zoneFromHash(hash);\n const confirms = _confirms != null ? _confirms : 1;\n if (confirms === 0) {\n return this.getTransactionReceipt(hash);\n }\n // eslint-disable-next-line no-async-promise-executor\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('Error occured while waiting for transaction:', error);\n }\n this.once('block', listener, zone);\n };\n if (timeout != null) {\n timer = setTimeout(() => {\n if (timer == null) {\n return;\n }\n timer = null;\n this.off('block', listener, zone);\n reject(makeError('timeout', 'TIMEOUT', { reason: 'timeout' }));\n }, timeout);\n }\n listener(await this.getBlockNumber(toShard(zone)));\n });\n }\n // TODO: not implemented yet\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async waitForBlock(shard, blockTag) {\n assert(false, 'not implemented yet', 'NOT_IMPLEMENTED', {\n operation: 'waitForBlock',\n });\n }\n /**\n * Clear a timer created using the {@link AbstractProvider._setTimeout | **_setTimeout**} method.\n *\n * @param {number} timerId - The ID of the timer to clear.\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` (in ms). If `timeout` is unspecified, then\n * `func` will execute in the next event loop.\n *\n * {@link AbstractProvider.pause | **Pausing**} the provider will pause any associated timers.\n *\n * @ignore\n * @ignore\n * @param {() => void} _func - The function to execute.\n * @param {number} [timeout] - The time to wait before executing `func`.\n * @returns {number} The ID of the timer.\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 * @ignore\n * @param {(s: Subscriber) => void} func - The function to perform.\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 implementations.\n *\n * @ignore\n * @param {Subscription} sub - The subscription to get the subscriber for.\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, sub.zone);\n subscriber.pollingInterval = this.pollingInterval;\n return subscriber;\n }\n //! TODO: implement this for quais\n // case \"safe\": 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, sub.zone);\n case 'orphan':\n return new PollingOrphanSubscriber(this, sub.filter, sub.zone);\n }\n throw new Error(`unsupported event: ${sub.type}`);\n }\n /**\n * If a {@link Subscriber | **Subscriber**} fails and needs to replace itself, this method may be used.\n *\n * For example, this is used for providers when using the `quai_getFilterChanges` method, which can return null if\n * state filters are not supported by the backend, allowing the Subscriber to swap in a `PollingEventSubscriber`.\n *\n * @ignore\n * @param {Subscriber} oldSub - The subscriber to replace.\n * @param {Subscriber} newSub - The new subscriber.\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, zone) {\n let sub = await getSubscription(event, zone);\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] }, zone);\n }\n return this.#subs.get(sub.tag) || null;\n }\n async #getSub(event, zone) {\n const subscription = await getSubscription(event, zone);\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: [], zone: subscription.zone };\n this.#subs.set(tag, sub);\n }\n return sub;\n }\n async on(event, listener, zone) {\n const sub = await this.#getSub(event, zone);\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, zone) {\n const sub = await this.#getSub(event, zone);\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, zone, ...args) {\n const sub = await this.#hasSub(event, args, zone);\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 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 // eslint-disable-next-line no-empty\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, zone) {\n const sub = await this.#hasSub(event, [], zone);\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, zone) {\n return await this.on(event, listener, zone);\n }\n // Alias for \"off\"\n async removeListener(event, listener, zone) {\n return this.off(event, listener, zone);\n }\n /**\n * If this provider has been destroyed using the {@link AbstractProvider.destroy | **destroy**} method.\n *\n * Once destroyed, all resources are reclaimed, internal event loops and timers are cleaned up and no further\n * requests may be sent to 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 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 not make any requests to the network, but that\n * is up to sub-classes to manage.\n *\n * Setting `paused = true` is identical to calling `.pause(false)`, which will buffer any events that occur while\n * paused until the provider is unpaused.\n *\n * @returns {boolean} Whether the provider is paused.\n */\n get paused() {\n return this.#pausedState != null;\n }\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 while paused are dropped, otherwise all events\n * will be emitted once the provider is unpaused.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop events while paused.\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}\n//# sourceMappingURL=abstract-provider.js.map","import { isError } from '../utils/index.js';\nimport { PollingEventSubscriber } from './subscriber-polling.js';\nimport { getZoneFromEventFilter } from './provider.js';\n/**\n * Deep copies an object.\n *\n * @param {any} obj - The object to copy.\n * @returns {any} A deep copy of the object.\n */\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 **Filter ID**. At this point the node dedicates\n * resources to the filter, so that periodic calls to follow up on the **Filter ID** will receive any events since the\n * last call.\n *\n * @category Providers\n */\nexport class FilterIdSubscriber {\n #provider;\n #filterIdPromise;\n #poller;\n #running;\n #network;\n #hault;\n zone;\n /**\n * @ignore Creates A new **FilterIdSubscriber** which will use {@link FilterIdSubscriber._subscribe | **_subscribe**}\n * and {@link FilterIdSubscriber._emitResults | **_emitResults**} to setup the subscription and provide the event\n * to the `provider`.\n * @param {JsonRpcApiProvider} provider - The provider to use.\n */\n constructor(provider, zone) {\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 this.zone = zone;\n }\n /**\n * Sub-classes **must** override this to begin the subscription.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @returns {Promise} A promise that resolves to the subscription ID.\n * @throws {Error} If the method is not overridden.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _subscribe(provider) {\n throw new Error('subclasses must override this');\n }\n /**\n * Sub-classes **must** override this to handle the events.\n *\n * @ignore\n * @param {AbstractProvider} provider - The provider to use.\n * @param {any[]} result - The results to handle.\n * @returns {Promise} A promise that resolves when the results are handled.\n * @throws {Error} If the method is not overridden.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _emitResults(provider, result) {\n throw new Error('subclasses must override this');\n }\n /**\n * Sub-classes **must** override this to handle recovery on errors.\n *\n * @ignore\n * @param {AbstractProvider} provider - The provider to use.\n * @returns {Subscriber} The recovered subscriber.\n * @throws {Error} If the method is not overridden.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _recover(provider) {\n throw new Error('subclasses must override this');\n }\n /**\n * Polls for new events.\n *\n * @ignore\n * @param {number} blockNumber - The block number to poll from.\n * @returns {Promise} A promise that resolves when polling is complete.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 !== 'quai_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('chain changed');\n }\n if (this.#hault) {\n return;\n }\n const result = await this.#provider.send('quai_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, this.zone);\n }\n /**\n * Tears down the subscription.\n *\n * @ignore\n */\n #teardown() {\n const filterIdPromise = this.#filterIdPromise;\n if (filterIdPromise) {\n this.#filterIdPromise = null;\n filterIdPromise.then((filterId) => {\n this.#provider.send('quai_uninstallFilter', [filterId]);\n });\n }\n }\n /**\n * Starts the subscriber.\n */\n start() {\n if (this.#running) {\n return;\n }\n this.#running = true;\n this.#poll(-2);\n }\n /**\n * Stops the subscriber.\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, this.zone);\n }\n /**\n * Pauses the subscriber.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop the subscription while paused.\n */\n pause(dropWhilePaused) {\n if (dropWhilePaused) {\n this.#teardown();\n }\n this.#provider.off('block', this.#poller, this.zone);\n }\n /**\n * Resumes the subscriber.\n */\n resume() {\n this.start();\n }\n}\n/**\n * A **FilterIdSubscriber** for receiving contract events.\n *\n * @category Providers\n */\nexport class FilterIdEventSubscriber extends FilterIdSubscriber {\n #event;\n /**\n * @ignore Creates A new **FilterIdEventSubscriber** attached to `provider` listening for `filter`.\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @param {EventFilter} filter - The event filter to use.\n */\n constructor(provider, filter) {\n const zone = getZoneFromEventFilter(filter);\n if (zone == null) {\n throw new Error('Unable to determine zone for event filter');\n }\n super(provider, zone);\n this.#event = copy(filter);\n }\n /**\n * Recovers the subscriber.\n *\n * @ignore\n * @param {AbstractProvider} provider - The provider to use.\n * @returns {Subscriber} The recovered subscriber.\n */\n _recover(provider) {\n return new PollingEventSubscriber(provider, this.#event);\n }\n /**\n * Subscribes to the event filter.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @returns {Promise} A promise that resolves to the subscription ID.\n */\n async _subscribe(provider) {\n const filterId = await provider.send('quai_newFilter', [this.#event]);\n return filterId;\n }\n /**\n * Emits the results of the event filter.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @param {any[]} results - The results to emit.\n * @returns {Promise} A promise that resolves when the results are emitted.\n */\n async _emitResults(provider, results) {\n for (const result of results) {\n provider.emit(this.#event, this.zone, provider._wrapLog(result, provider._network));\n }\n }\n}\n/**\n * A **FilterIdSubscriber** for receiving pending transactions events.\n *\n * @category Providers\n */\nexport class FilterIdPendingSubscriber extends FilterIdSubscriber {\n /**\n * Subscribes to the pending transactions filter.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @returns {Promise} A promise that resolves to the subscription ID.\n */\n async _subscribe(provider) {\n return await provider.send('quai_newPendingTransactionFilter', []);\n }\n /**\n * Emits the results of the pending transactions filter.\n *\n * @ignore\n * @param {JsonRpcApiProvider} provider - The provider to use.\n * @param {any[]} results - The results to emit.\n * @returns {Promise} A promise that resolves when the results are emitted.\n */\n async _emitResults(provider, results) {\n for (const result of results) {\n provider.emit('pending', this.zone, result);\n }\n }\n}\n//# sourceMappingURL=subscriber-filterid.js.map","/**\n * One of the most common ways to interact with the blockchain is by a node running a JSON-RPC interface which can be\n * connected to, based on the transport, using:\n *\n * - HTTP or HTTPS - {@link JsonRpcProvider | **JsonRpcProvider**}\n * - WebSocket - {@link WebSocketProvider | **WebSocketProvider**}\n * - IPC - {@link IpcSocketProvider | **IpcSocketProvider**}\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 { accessListify } from '../transaction/index.js';\nimport { getBigInt, hexlify, isHexString, toQuantity, makeError, assert, assertArgument, isError, FetchRequest, defineProperties, resolveProperties, } from '../utils/index.js';\nimport { AbstractProvider, UnmanagedSubscriber } from './abstract-provider.js';\nimport { Network } from './network.js';\nimport { FilterIdEventSubscriber, FilterIdPendingSubscriber } from './subscriber-filterid.js';\nimport { Shard, toShard, toZone } from '../constants/index.js';\nimport { TypedDataEncoder } from '../hash/index.js';\nimport { AbstractSigner } from '../signers/index.js';\nimport { toUtf8Bytes } from '../encoding/index.js';\nimport { addressFromTransactionRequest, zoneFromHash } from './provider.js';\nconst Primitive = 'bigint,boolean,function,number,string,symbol'.split(/,/g);\n/**\n * Deeply copies a value.\n *\n * @ignore\n * @param {T} value - The value to copy.\n * @returns {T} The copied value.\n */\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}\n/**\n * Stalls execution for a specified duration.\n *\n * @ignore\n * @param {number} duration - The duration to stall in milliseconds.\n * @returns {Promise} A promise that resolves after the duration.\n */\nfunction stall(duration) {\n return new Promise((resolve) => {\n setTimeout(resolve, duration);\n });\n}\nconst defaultOptions = {\n staticNetwork: null,\n batchStallTime: 10,\n batchMaxSize: 1 << 20,\n batchMaxCount: 100,\n cacheTimeout: 250,\n usePathing: false,\n};\n// @TODO: Unchecked Signers\n/**\n * A signer that uses JSON-RPC to sign transactions and messages.\n *\n * @category Providers\n */\nexport class JsonRpcSigner extends AbstractSigner {\n address;\n /**\n * Creates a new JsonRpcSigner instance.\n *\n * @param {JsonRpcApiProvider} provider - The JSON-RPC provider.\n * @param {string} address - The address of the signer.\n */\n constructor(provider, address) {\n super(provider);\n address = getAddress(address);\n defineProperties(this, { address });\n }\n /**\n * Connects the signer to a provider.\n *\n * @param {null | Provider} provider - The provider to connect to.\n * @returns {Signer} The connected signer.\n * @throws {Error} If the signer cannot be reconnected.\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n connect(provider) {\n assert(false, 'cannot reconnect JsonRpcSigner', 'UNSUPPORTED_OPERATION', {\n operation: 'signer.connect',\n });\n }\n /**\n * Gets the address of the signer.\n *\n * @returns {Promise} The address of the signer.\n */\n async getAddress() {\n return this.address;\n }\n /**\n * Populates a Quai transaction.\n *\n * @ignore\n * @param {QuaiTransactionRequest} tx - The transaction request.\n * @returns {Promise} The populated transaction.\n */\n async populateQuaiTransaction(tx) {\n return (await this.populateCall(tx));\n }\n /**\n * Sends an unchecked transaction.\n *\n * @ignore\n * @param {TransactionRequest} _tx - The transaction request.\n * @returns {Promise} The transaction hash.\n */\n async sendUncheckedTransaction(_tx) {\n const tx = deepCopy(_tx);\n const promises = [];\n if ('from' in tx) {\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);\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 quai_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);\n })());\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('quai_sendTransaction', [hexTx]);\n }\n /**\n * Sends a transaction.\n *\n * @param {TransactionRequest} tx - The transaction request.\n * @returns {Promise} The transaction response.\n * @throws {Error} If the transaction cannot be sent.\n */\n async sendTransaction(tx) {\n const zone = await this.zoneFromAddress(addressFromTransactionRequest(tx));\n // This cannot be mined any earlier than any recent block\n const blockNumber = await this.provider.getBlockNumber(toShard(zone));\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') ||\n isError(error, 'BAD_DATA') ||\n isError(error, 'NETWORK_ERROR') ||\n 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', zoneFromHash(hash), makeError('failed to fetch transation after sending (will try again)', 'UNKNOWN_ERROR', {\n error,\n }));\n }\n // Wait another 4 seconds\n this.provider._setTimeout(() => {\n checkTx();\n }, timeouts.pop() || 4000);\n };\n checkTx();\n });\n }\n /**\n * Signs a transaction.\n *\n * @param {TransactionRequest} _tx - The transaction request.\n * @returns {Promise} The signed transaction.\n * @throws {Error} If the transaction cannot be signed.\n */\n async signTransaction(_tx) {\n const tx = deepCopy(_tx);\n // QuaiTransactionRequest\n if ('from' in tx) {\n if (tx.from) {\n const from = await resolveAddress(tx.from);\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 }\n else {\n throw new Error('No QI signing implementation in provider-jsonrpc');\n }\n const hexTx = this.provider.getRpcTransaction(tx);\n return await this.provider.send('quai_signTransaction', [hexTx]);\n }\n /**\n * Signs a message.\n *\n * @param {string | Uint8Array} _message - The message to sign.\n * @returns {Promise} The signed message.\n */\n async signMessage(_message) {\n const message = typeof _message === 'string' ? toUtf8Bytes(_message) : _message;\n return await this.provider.send('personal_sign', [hexlify(message), this.address.toLowerCase()]);\n }\n /**\n * Signs typed data.\n *\n * @param {TypedDataDomain} domain - The domain of the typed data.\n * @param {Record} types - The types of the typed data.\n * @param {Record} _value - The value of the typed data.\n * @returns {Promise} The signed typed data.\n */\n async signTypedData(domain, types, _value) {\n const value = deepCopy(_value);\n return await this.provider.send('quai_signTypedData_v4', [\n this.address.toLowerCase(),\n JSON.stringify(TypedDataEncoder.getPayload(domain, types, value)),\n ]);\n }\n /**\n * Unlocks the account.\n *\n * @param {string} password - The password to unlock the account.\n * @returns {Promise} True if the account is unlocked, false otherwise.\n */\n async unlock(password) {\n return this.provider.send('personal_unlockAccount', [this.address.toLowerCase(), password, null]);\n }\n /**\n * Signs a message using the legacy method.\n *\n * @ignore\n * @param {string | Uint8Array} _message - The message to sign.\n * @returns {Promise} The signed message.\n */\n async _legacySignMessage(_message) {\n const message = typeof _message === 'string' ? toUtf8Bytes(_message) : _message;\n return await this.provider.send('quai_sign', [this.address.toLowerCase(), hexlify(message)]);\n }\n}\n/**\n * The JsonRpcApiProvider is an abstract class and **MUST** be sub-classed.\n *\n * It provides the base for all JSON-RPC-based Provider interaction.\n *\n * Sub-classing Notes:\n *\n * - A sub-class MUST override _send\n * - A sub-class MUST call the `_start()` method once connected\n *\n * @category Providers\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 /**\n * Schedules the draining of the payload queue.\n *\n * @ignore\n */\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 payloadMap = new Map();\n const nowPayloadMap = new Map();\n for (let i = 0; i < batch.length; i++) {\n if (batch[i].now) {\n if (!nowPayloadMap.has(batch[i].shard)) {\n if (batch[i].payload != null) {\n nowPayloadMap.set(batch[i].shard, [batch[i].payload]);\n }\n }\n else {\n nowPayloadMap.get(batch[i].shard)?.push(batch[i].payload);\n }\n }\n else {\n if (!payloadMap.has(batch[i].shard)) {\n if (batch[i].payload != null) {\n payloadMap.set(batch[i].shard, [batch[i].payload]);\n }\n }\n else {\n payloadMap.get(batch[i].shard)?.push(batch[i].payload);\n }\n }\n }\n const rawResult = [];\n const processPayloads = async (key, value, now) => {\n const payload = value.length === 1 ? value[0] : value;\n const shard = key ? toShard(key) : Shard.Prime;\n const zone = shard.length < 4 ? undefined : toZone(shard);\n this.emit('debug', zone, { action: 'sendRpcPayload', payload });\n rawResult.push(await this._send(payload, shard, now));\n this.emit('debug', zone, { action: 'receiveRpcResult', payload });\n };\n await Promise.all(Array.from(nowPayloadMap)\n .map(async ([key, value]) => {\n await processPayloads(key, value, true);\n })\n .concat(Array.from(payloadMap).map(async ([key, value]) => {\n await processPayloads(key, value);\n })));\n const result = rawResult.flat();\n let lastZone;\n try {\n // Process results in batch order\n for (const { resolve, reject, payload, shard } of batch) {\n if (this.destroyed) {\n reject(makeError('provider destroyed; cancelled request', 'UNSUPPORTED_OPERATION', {\n operation: payload.method,\n }));\n continue;\n }\n if (shard) {\n lastZone = shard.length < 4 ? undefined : toZone(shard);\n }\n else {\n lastZone = undefined;\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,\n info: { payload },\n });\n this.emit('error', lastZone, error);\n reject(error);\n continue;\n }\n // The response is an error\n if ('error' in resp) {\n reject(this.getRpcError(payload, resp, shard));\n continue;\n }\n // All good; send the result\n resolve(resp.result);\n }\n }\n catch (error) {\n this.emit('debug', lastZone, { 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 /**\n * Creates a new JsonRpcApiProvider instance.\n *\n * @param {Networkish} [network] - The network to connect to.\n * @param {JsonRpcApiProviderOptions} [options] - The options for the provider.\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 * @ignore\n * @param {keyof JsonRpcApiProviderOptions} key - The option key.\n * @returns {JsonRpcApiProviderOptions[key]} The option value.\n */\n _getOption(key) {\n return this.#options[key];\n }\n /**\n * Gets the {@link Network | **Network**} this provider has committed to. On each call, the network is detected, and\n * if it has changed, the call will reject.\n *\n * @ignore\n * @returns {Network} The network.\n * @throws {Error} If the network is not available yet.\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, and should generally call `super._perform` as a\n * fallback.\n *\n * @ignore\n * @param {PerformActionRequest} req - The request to perform.\n * @returns {Promise} The result of the request.\n * @throws {Error} If the request fails.\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 !== 'getRunningLocations') {\n await this.initPromise;\n }\n if (req.method === 'call' || req.method === 'estimateGas') {\n const tx = req.transaction;\n if (tx && tx.type != null && getBigInt(tx.type)) {\n // If there are no EIP-1559 properties, it might be non-EIP-a559\n if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) {\n const feeData = await this.getFeeData(req.zone);\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 const shard = 'shard' in req ? req.shard : 'zone' in req ? toShard(req.zone) : undefined;\n if (req.method === 'getRunningLocations') {\n return await this.send(request.method, request.args, shard, req.now);\n }\n else {\n return await this.send(request.method, request.args, shard);\n }\n }\n return super._perform(req);\n }\n /**\n * Sub-classes may override this; it detects the _actual_ network that we are **currently** connected to.\n *\n * Keep in mind that {@link JsonRpcApiProvider.send | **send**} may only be used once\n * {@link JsonRpcApiProvider.ready | **ready**}, otherwise the _send primitive must be used instead.\n *\n * @ignore\n * @returns {Promise} The detected network.\n * @throws {Error} If network detection fails.\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('quai_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++,\n method: 'quai_chainId',\n params: [],\n jsonrpc: '2.0',\n };\n this.emit('debug', undefined, { 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', undefined, { action: 'receiveRpcError', error });\n throw error;\n }\n this.emit('debug', undefined, { 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 {@link JsonRpcApiProvider._start | **_start**} has been called, no calls\n * will be passed to {@link JsonRpcApiProvider._send | **_send**} from {@link JsonRpcApiProvider.send | **send**} . If\n * it is overridden, then `super._start()` **MUST** be called.\n *\n * Calling it multiple times is safe and has no effect.\n *\n * @ignore\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 let retries = 0;\n const maxRetries = 5;\n while (this.#network == null && !this.destroyed && retries < maxRetries) {\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', undefined, makeError('failed to bootstrap network detection', 'NETWORK_ERROR', {\n event: 'initial-network-discovery',\n info: { error },\n }));\n await stall(1000);\n retries++;\n }\n }\n if (retries >= maxRetries) {\n throw new Error('Failed to detect network after maximum retries');\n }\n // Start dispatching requests\n this.#scheduleDrain();\n })();\n }\n /**\n * Resolves once the {@link JsonRpcApiProvider._start | **_start**} has been called. This can be used in sub-classes\n * to defer sending data until the connection has been established.\n *\n * @ignore\n * @returns {Promise} A promise that resolves once the provider is ready.\n */\n async _waitUntilReady() {\n if (this._initFailed) {\n throw new Error('Provider failed to initialize on creation. Run initialize or create a new provider.');\n }\n await this.initPromise;\n }\n /**\n * Return a Subscriber that will manage the `sub`.\n *\n * Sub-classes may override this to modify the behavior of subscription management.\n *\n * @ignore\n * @param {Subscription} sub - The subscription to manage.\n * @returns {Subscriber} The subscriber that will manage the subscription.\n */\n _getSubscriber(sub) {\n // Pending Filters aren't availble via polling\n if (sub.type === 'pending') {\n return new FilterIdPendingSubscriber(this, sub.zone);\n }\n if (sub.type === 'event') {\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 {@link JsonRpcApiProvider._start | **_start**} has been called.\n *\n * @returns {boolean} True if the provider is ready.\n */\n get ready() {\n return this.#notReady == null;\n }\n /**\n * Returns `tx` as a normalized JSON-RPC transaction request, which has all values hexlified and any numeric values\n * converted to Quantity values.\n *\n * @ignore\n * @param {TransactionRequest} tx - The transaction to normalize.\n * @returns {JsonRpcTransactionRequest} The normalized transaction.\n * @throws {Error} If the transaction is invalid.\n */\n getRpcTransaction(tx) {\n const result = {};\n if ('from' in tx || ('to' in tx && 'data' in tx)) {\n // JSON-RPC now requires numeric values to be \"quantity\" values\n [\n 'chainId',\n 'gasLimit',\n 'gasPrice',\n 'type',\n 'maxFeePerGas',\n 'maxPriorityFeePerGas',\n 'nonce',\n 'value',\n ].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 ('accessList' in tx && tx.accessList) {\n result['accessList'] = accessListify(tx.accessList);\n }\n }\n else {\n throw new Error('No Qi getRPCTransaction implementation yet');\n }\n return result;\n }\n /**\n * Returns the request method and arguments required to perform `req`.\n *\n * @ignore\n * @param {PerformActionRequest} req - The request to perform.\n * @returns {null | { method: string; args: any[] }} The method and arguments to use.\n * @throws {Error} If the request is not supported or invalid.\n */\n getRpcRequest(req) {\n switch (req.method) {\n case 'chainId':\n return { method: 'quai_chainId', args: [] };\n case 'getBlockNumber':\n return { method: 'quai_blockNumber', args: [] };\n case 'getGasPrice':\n return {\n method: 'quai_baseFee',\n args: [req.txType],\n };\n case 'getMaxPriorityFeePerGas':\n return { method: 'quai_maxPriorityFeePerGas', args: [] };\n case 'getPendingHeader':\n return { method: 'quai_getPendingHeader', args: [] };\n case 'getBalance':\n return {\n method: 'quai_getBalance',\n args: [req.address, req.blockTag],\n };\n case 'getOutpointsByAddress':\n return {\n method: 'quai_getOutpointsByAddress',\n args: [req.address],\n };\n case 'getTransactionCount':\n return {\n method: 'quai_getTransactionCount',\n args: [req.address, req.blockTag],\n };\n case 'getCode':\n return {\n method: 'quai_getCode',\n args: [req.address, req.blockTag],\n };\n case 'getStorage':\n return {\n method: 'quai_getStorageAt',\n args: [req.address, '0x' + req.position.toString(16), req.blockTag],\n };\n case 'broadcastTransaction':\n return {\n method: 'quai_sendRawTransaction',\n args: [req.signedTransaction],\n };\n case 'getBlock':\n if ('blockTag' in req) {\n return {\n method: 'quai_getBlockByNumber',\n args: [req.blockTag, !!req.includeTransactions],\n };\n }\n else if ('blockHash' in req) {\n return {\n method: 'quai_getBlockByHash',\n args: [req.blockHash, !!req.includeTransactions],\n };\n }\n break;\n case 'getTransaction':\n return {\n method: 'quai_getTransactionByHash',\n args: [req.hash],\n };\n case 'getTransactionReceipt':\n return {\n method: 'quai_getTransactionReceipt',\n args: [req.hash],\n };\n case 'call':\n return {\n method: 'quai_call',\n args: [this.getRpcTransaction(req.transaction), req.blockTag],\n };\n case 'estimateGas': {\n return {\n method: 'quai_estimateGas',\n args: [this.getRpcTransaction(req.transaction)],\n };\n }\n case 'getRunningLocations': {\n return {\n method: 'quai_listRunningChains',\n args: [],\n };\n }\n case 'getProtocolTrieExpansionCount': {\n return {\n method: 'quai_getProtocolExpansionNumber',\n args: [],\n };\n }\n case 'getProtocolExpansionNumber': {\n return {\n method: 'quai_getProtocolExpansionNumber',\n args: [],\n };\n }\n case 'getQiRateAtBlock': {\n return {\n method: 'quai_qiRateAtBlock',\n args: [req.blockTag, req.amt],\n };\n }\n case 'getQuaiRateAtBlock': {\n return {\n method: 'quai_quaiRateAtBlock',\n args: [req.blockTag, req.amt],\n };\n }\n case 'getLogs':\n return { method: 'quai_getLogs', args: [req.filter] };\n case 'getTxPoolContent':\n return { method: 'txpool_content', args: [] };\n case 'txPoolInspect':\n return { method: 'txpool_inspect', args: [] };\n }\n return null;\n }\n /**\n * Returns an quais-style Error for the given JSON-RPC error `payload`, coalescing the various strings and error\n * shapes that different nodes return, coercing them into a machine-readable standardized error.\n *\n * @ignore\n * @param {JsonRpcPayload} payload - The payload that was sent.\n * @param {JsonRpcError} _error - The error that was received.\n * @returns {Error} The coalesced error.\n */\n getRpcError(payload, _error, shard) {\n const { method } = payload;\n const { error } = _error;\n if (method === 'quai_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, shard },\n });\n }\n }\n if (method === 'quai_call' || method === 'quai_estimateGas') {\n const result = spelunkData(error);\n const e = AbiCoder.getBuiltinCallException(method === 'quai_call' ? 'call' : 'estimateGas', payload.params[0], result ? result.data : null);\n e.info = { error, payload, shard };\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 (method === 'quai_getTransactionByHash' && error.message && error.message.match(/transaction not found/i)) {\n return makeError('transaction not found', 'TRANSACTION_NOT_FOUND', { info: { payload, error, shard } });\n }\n if (typeof error.message === 'string' && error.message.match(/user denied|quais-user-denied/i)) {\n const actionMap = {\n quai_sign: 'signMessage',\n personal_sign: 'signMessage',\n quai_signTypedData_v4: 'signTypedData',\n quai_signTransaction: 'signTransaction',\n quai_sendTransaction: 'sendTransaction',\n quai_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, shard },\n });\n }\n if (method === 'quai_sendRawTransaction' || method === 'quai_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,\n info: { error, shard },\n });\n }\n if (message.match(/nonce/i) && message.match(/too low/i)) {\n return makeError('nonce has already been used', 'NONCE_EXPIRED', {\n transaction,\n info: { error, shard },\n });\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', {\n transaction,\n info: { error, shard },\n });\n }\n if (message.match(/only replay-protected/i)) {\n return makeError('legacy pre-eip-155 transactions not supported', 'UNSUPPORTED_OPERATION', {\n operation: method,\n info: { transaction, info: { error, shard } },\n });\n }\n if (message.match(/already known/i)) {\n return makeError('transaction already known', 'TRANSACTION_ALREADY_KNOWN', { info: { error, shard } });\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,\n info: { error, payload, shard },\n });\n }\n if (message.match('Provider failed to initialize on creation. Run initialize or create a new provider.')) {\n return makeError('Provider failed to initialize on creation. Run initUrlMap or create a new provider.', 'PROVIDER_FAILED_TO_INITIALIZE', {\n info: { payload, error, shard },\n });\n }\n return makeError('could not coalesce error', 'UNKNOWN_ERROR', { error, payload, shard });\n }\n /**\n * Requests the `method` with `params` via the JSON-RPC protocol over the underlying channel. This can be used to\n * call methods on the backend that do not have a high-level API within the Provider API.\n *\n * This method queues requests according to the batch constraints in the options, assigns the request a unique ID.\n *\n * **Do NOT override** this method in sub-classes; instead override {@link JsonRpcApiProvider._send | **_send**} or\n * force the options values in the call to the constructor to modify this method's behavior.\n *\n * @param {string} method - The method to call.\n * @param {any[] | Record} params - The parameters to pass to the method.\n * @param {Shard} shard - The shard to send the request to.\n * @param {boolean} now - If true, the request will be sent immediately.\n * @returns {Promise} A promise that resolves to the result of the method call.\n */\n send(method, params, shard, now) {\n const continueSend = () => {\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,\n reject,\n payload: { method, params, id, jsonrpc: '2.0' },\n shard: shard,\n now: now,\n });\n });\n // If there is not a pending drainTimer, set one\n this.#scheduleDrain();\n return promise;\n };\n // @TODO: cache chainId?? purge on switch_networks\n // We have been destroyed; no operations are supported anymore\n if (method !== 'quai_listRunningChains') {\n return this.initPromise.then(() => {\n return continueSend();\n });\n }\n else {\n return continueSend();\n }\n }\n /**\n * Returns a JsonRpcSigner for the given address.\n *\n * @param {number | string} [address] - The address or index of the account.\n * @returns {Promise} A promise that resolves to the JsonRpcSigner.\n * @throws {Error} If the account is invalid.\n */\n async getSigner(address) {\n if (address == null) {\n address = 0;\n }\n const accountsPromise = this.send('quai_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 /**\n * Returns a list of JsonRpcSigners for all accounts.\n *\n * @returns {Promise} A promise that resolves to an array of JsonRpcSigners.\n */\n async listAccounts() {\n const accounts = await this.send('quai_accounts', []);\n return accounts.map((a) => new JsonRpcSigner(this, a));\n }\n /**\n * Destroys the provider, stopping all processing and canceling all pending requests.\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', {\n operation: payload.method,\n }));\n }\n this.#payloads = [];\n // Parent clean-up\n super.destroy();\n }\n}\n/**\n * The JsonRpcProvider is one of the most common Providers, which performs all operations over HTTP (or HTTPS) requests.\n *\n * Events are processed by polling the backend for the current block number; when it advances, all block-base events are\n * then checked for updates.\n *\n * @category Providers\n */\nexport class JsonRpcProvider extends JsonRpcApiProvider {\n constructor(urls, network, options) {\n if (urls == null) {\n urls = ['http://localhost:8545'];\n }\n super(network, options);\n if (Array.isArray(urls)) {\n urls.forEach((url) => {\n this.validateUrl(url);\n });\n this.initialize(urls);\n }\n else if (typeof urls === 'string') {\n this.validateUrl(urls);\n this.initialize([urls]);\n }\n else {\n this.validateUrl(urls.url);\n this.initialize(urls.clone());\n }\n }\n _getSubscriber(sub) {\n const subscriber = super._getSubscriber(sub);\n return subscriber;\n }\n _getConnection(shard) {\n if (this._initFailed) {\n throw new Error('Provider failed to initialize on creation. Run initUrlMap or create a new provider.');\n }\n let connection;\n if (shard !== undefined) {\n connection = this._urlMap.get(shard) ?? this.connect[this.connect.length - 1].clone();\n }\n else {\n connection = this.connect[this.connect.length - 1].clone();\n }\n return new FetchRequest(connection.url);\n }\n async send(method, params, shard, now) {\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. quai_chainId) until we absolutely have to.\n await this._start();\n return await super.send(method, params, shard, now);\n }\n async _send(payload, shard) {\n // Configure a POST connection for the requested method\n const request = this._getConnection(shard);\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 // eslint-disable-next-line no-empty\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 // eslint-disable-next-line no-empty\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 { Interface } from '../abi/index.js';\nimport { concat, defineProperties, getBytes, hexlify, assert, assertArgument } from '../utils/index.js';\nimport { BaseContract, copyOverrides, resolveArgs } from './contract.js';\nimport { validateAddress } from '../address/index.js';\nimport { getZoneForAddress } from '../utils/index.js';\nimport { Wallet } from '../wallet/index.js';\nimport { randomBytes } from '../crypto/index.js';\nimport { getContractAddress, isQiAddress } from '../address/index.js';\nimport { getStatic } from '../utils/properties.js';\nimport { JsonRpcSigner } from '../providers/provider-jsonrpc.js';\n// A = Arguments to the constructor\n// I = Interface of deployed contracts\n/**\n * A **ContractFactory** is used to deploy a Contract to the blockchain.\n *\n * @category Contract\n */\nexport class ContractFactory {\n /**\n * The Contract Interface.\n */\n interface;\n /**\n * The Contract deployment bytecode. Often called the initcode.\n */\n bytecode;\n /**\n * The ContractRunner to deploy the Contract as.\n */\n runner;\n /**\n * Create a new **ContractFactory** with `abi` and `bytecode`, optionally connected to `runner`.\n *\n * The `bytecode` may be the `bytecode` property within the standard Solidity JSON output.\n */\n constructor(abi, bytecode, runner) {\n const iface = Interface.from(abi);\n // Dereference Solidity bytecode objects and allow a missing `0x`-prefix\n if (bytecode instanceof Uint8Array) {\n bytecode = hexlify(getBytes(bytecode));\n }\n else {\n if (typeof bytecode === 'object') {\n bytecode = bytecode.object;\n }\n if (!bytecode.startsWith('0x')) {\n bytecode = '0x' + bytecode;\n }\n bytecode = hexlify(getBytes(bytecode));\n }\n defineProperties(this, {\n bytecode,\n interface: iface,\n runner: runner || null,\n });\n }\n attach(target) {\n return new BaseContract(target, this.interface, this.runner);\n }\n /**\n * Resolves to the transaction to deploy the contract, passing `args` into the constructor.\n *\n * @param {ContractMethods} args - The arguments to the constructor.\n * @returns {Promise} A promise resolving to the deployment transaction.\n */\n async getDeployTransaction(...args) {\n let overrides;\n const fragment = this.interface.deploy;\n if (fragment.inputs.length + 1 === args.length) {\n overrides = await copyOverrides(args.pop());\n const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args);\n const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]);\n return Object.assign({}, overrides, { data });\n }\n if (fragment.inputs.length !== args.length) {\n throw new Error('incorrect number of arguments to constructor');\n }\n const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args);\n const data = concat([this.bytecode, this.interface.encodeDeploy(resolvedArgs)]);\n const from = args.pop()?.from || undefined;\n return Object.assign({}, from, { data });\n }\n /**\n * Resolves to the Contract deployed by passing `args` into the constructor.\n *\n * This will resovle to the Contract before it has been deployed to the network, so the\n * [baseContract.waitForDeployment](../classes/BaseContract#waitForDeployment) should be used before sending any\n * transactions to it.\n *\n * @param {ContractMethods} args - The arguments to the constructor.\n * @returns {Promise<\n * BaseContract & { deploymentTransaction(): ContractTransactionResponse } & Omit\n * >}\n * A promise resolving to the Contract.\n */\n async deploy(...args) {\n const tx = await this.getDeployTransaction(...args);\n assert(this.runner && typeof this.runner.sendTransaction === 'function', 'factory runner does not support sending transactions', 'UNSUPPORTED_OPERATION', {\n operation: 'sendTransaction',\n });\n if (this.runner instanceof Wallet || this.runner instanceof JsonRpcSigner) {\n validateAddress(this.runner.address);\n tx.from = this.runner.address;\n }\n const grindedTx = await this.grindContractAddress(tx);\n const sentTx = await this.runner.sendTransaction(grindedTx);\n const address = getStatic(this.constructor, 'getContractAddress')?.(tx);\n return new BaseContract(address, this.interface, this.runner, sentTx);\n }\n static getContractAddress(transaction) {\n return getContractAddress(transaction.from, BigInt(transaction.nonce), // Fix: Convert BigInt to bigint\n transaction.data);\n }\n async grindContractAddress(tx) {\n if (tx.nonce == null && tx.from) {\n tx.nonce = await this.runner?.provider?.getTransactionCount(tx.from);\n }\n const sender = String(tx.from);\n const toShard = getZoneForAddress(sender);\n let i = 0;\n const startingData = tx.data;\n while (i < 10000) {\n const contractAddress = getContractAddress(sender, BigInt(tx.nonce || 0), tx.data || '');\n const contractShard = getZoneForAddress(contractAddress);\n const utxo = isQiAddress(contractAddress);\n if (contractShard === toShard && !utxo) {\n return tx;\n }\n const salt = randomBytes(32);\n tx.data = hexlify(concat([String(startingData), salt]));\n i++;\n }\n return tx;\n }\n /**\n * Return a new **ContractFactory** with the same ABI and bytecode, but connected to `runner`.\n *\n * @param {ContractRunner} runner - The runner to connect to.\n * @returns {ContractFactory} A new ContractFactory.\n */\n connect(runner) {\n return new ContractFactory(this.interface, this.bytecode, runner);\n }\n /**\n * Create a new **ContractFactory** from the standard Solidity JSON output.\n *\n * @param {any} output - The Solidity JSON output.\n * @param {ContractRunner} runner - The runner to connect to.\n * @returns {ContractFactory} A new ContractFactory.\n */\n static fromSolidity(output, runner) {\n assertArgument(output != null, 'bad compiler output', 'output', output);\n if (typeof output === 'string') {\n output = JSON.parse(output);\n }\n const abi = output.abi;\n let bytecode = '';\n if (output.bytecode) {\n bytecode = output.bytecode;\n }\n else if (output.evm && output.evm.bytecode) {\n bytecode = output.evm.bytecode;\n }\n return new this(abi, bytecode, runner);\n }\n}\n//# sourceMappingURL=factory.js.map","import { assertArgument } from '../utils/index.js';\nimport { JsonRpcApiProvider } from './provider-jsonrpc.js';\n/**\n * A **BrowserProvider** is intended to wrap an injected provider which adheres to the\n * [EIP-1193](https://eips.ethereum.org/EIPS/eip-1193) standard, which most (if not all) currently do.\n *\n * @category Providers\n * @class\n * @extends JsonRpcApiProvider\n */\nexport class BrowserProvider extends JsonRpcApiProvider {\n #request;\n /**\n * Connect to the `ethereum` provider, optionally forcing the `network`.\n *\n * @class\n * @param {Eip1193Provider} ethereum - The EIP-1193 provider.\n * @param {Networkish} [network] - The network to connect to.\n */\n constructor(ethereum, network) {\n super(network, { batchMaxCount: 1 });\n this.#request = async (method, params) => {\n const payload = { method, params };\n this.emit('debug', undefined, { action: 'sendEip1193Request', payload });\n try {\n const result = await ethereum.request(payload);\n this.emit('debug', undefined, { 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', undefined, { action: 'receiveEip1193Error', error });\n throw error;\n }\n };\n }\n /**\n * Resolves to `true` if the provider manages the `address`.\n *\n * @param {number | string} address - The address to check.\n * @returns {Promise} 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('quai_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 /**\n * Sends a JSON-RPC request.\n *\n * @param {string} method - The method name.\n * @param {any[] | Record} params - The parameters for the method.\n * @returns {Promise} The result of the request.\n */\n async send(method, params) {\n await this._start();\n return await super.send(method, params);\n }\n /**\n * Sends a JSON-RPC payload.\n *\n * @ignore\n * @ignore\n * @param {JsonRpcPayload | JsonRpcPayload[]} payload - The JSON-RPC payload.\n * @returns {Promise<(JsonRpcResult | JsonRpcError)[]>} The result of the request.\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 {\n id: payload.id,\n error: { code: e.code, data: e.data, message: e.message },\n },\n ];\n }\n }\n /**\n * Gets the RPC error.\n *\n * @param {JsonRpcPayload} payload - The JSON-RPC payload.\n * @param {JsonRpcError} error - The JSON-RPC error.\n * @returns {Error} The RPC error.\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 = `quais-user-denied: ${error.error.message}`;\n break;\n case 4200:\n error.error.message = `quais-unsupported: ${error.error.message}`;\n break;\n }\n return super.getRpcError(payload, error);\n }\n /**\n * Gets the signer for the given address.\n *\n * @param {number | string} [address] - The address to get the signer for.\n * @returns {Promise} The signer for the address.\n */\n async getSigner(address) {\n if (address == null) {\n address = 0;\n }\n if (!(await this.hasSigner(address))) {\n try {\n await this.#request('quai_requestAccounts', []);\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 { UnmanagedSubscriber } from './abstract-provider.js';\nimport { assert, assertArgument, makeError } from '../utils/index.js';\nimport { JsonRpcApiProvider } from './provider-jsonrpc.js';\nimport { toShard } from '../constants/index.js';\n/**\n * A **SocketSubscriber** uses a socket transport to handle events and should use\n * {@link SocketSubscriber._emit | **_emit**} to manage the events.\n *\n * - A sub-class MUST call the `_start()` method once connected\n * - A sub-class MUST override the `_write(string)` method\n * - A sub-class MUST call `_processMessage(string)` for each message\n *\n * @category Providers\n */\nexport class SocketSubscriber {\n #provider;\n #filter;\n /**\n * The filter.\n *\n * @type {any[]}\n */\n get filter() {\n return JSON.parse(this.#filter);\n }\n #filterId;\n #paused;\n #emitPromise;\n zone;\n shard;\n /**\n * Creates a new **SocketSubscriber** attached to `provider` listening to `filter`.\n *\n * @param {SocketProvider} provider - The socket provider.\n * @param {any[]} filter - The filter.\n */\n constructor(provider, filter, zone) {\n this.#provider = provider;\n this.#filter = JSON.stringify(filter);\n this.#filterId = null;\n this.#paused = null;\n this.#emitPromise = null;\n this.zone = zone;\n this.shard = toShard(zone);\n }\n /**\n * Start the subscriber.\n */\n start() {\n this.#filterId = this.#provider.send('quai_subscribe', this.filter, this.shard).then((filterId) => {\n this.#provider._register(filterId, this);\n return filterId;\n });\n }\n /**\n * Stop the subscriber.\n */\n stop() {\n this.#filterId.then((filterId) => {\n this.#provider.send('quai_unsubscribe', [filterId], this.shard);\n });\n this.#filterId = null;\n }\n /**\n * Pause the subscriber.\n *\n * @param {boolean} [dropWhilePaused] - Whether to drop logs while paused.\n */\n pause(dropWhilePaused) {\n assert(dropWhilePaused, 'preserve logs while paused not supported by SocketSubscriber yet', 'UNSUPPORTED_OPERATION', { operation: 'pause(false)' });\n this.#paused = !!dropWhilePaused;\n }\n /**\n * Resume the subscriber.\n */\n resume() {\n this.#paused = null;\n }\n /**\n * Handle incoming messages.\n *\n * @ignore\n * @param {any} message - The message to handle.\n */\n _handleMessage(message) {\n if (this.#filterId == null) {\n return;\n }\n if (this.#paused === null) {\n let emitPromise = this.#emitPromise;\n if (emitPromise == null) {\n emitPromise = this._emit(this.#provider, message);\n }\n else {\n emitPromise = emitPromise.then(async () => {\n await this._emit(this.#provider, message);\n });\n }\n this.#emitPromise = emitPromise.then(() => {\n if (this.#emitPromise === emitPromise) {\n this.#emitPromise = null;\n }\n });\n }\n }\n /**\n * Sub-classes **must** override this to emit the events on the provider.\n *\n * @abstract\n * @param {SocketProvider} provider - The socket provider.\n * @param {any} message - The message to emit.\n * @returns {Promise}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _emit(provider, message) {\n throw new Error('sub-classes must implement this; _emit');\n }\n}\n/**\n * A **SocketBlockSubscriber** listens for `newHeads` events and emits `\"block\"` events.\n *\n * @category Providers\n */\nexport class SocketBlockSubscriber extends SocketSubscriber {\n /**\n * Creates a new **SocketBlockSubscriber**.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n */\n constructor(provider, zone) {\n super(provider, ['newHeads'], zone);\n }\n /**\n * Emit the block event.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n * @param {any} message - The message to emit.\n * @returns {Promise}\n */\n async _emit(provider, message) {\n provider.emit('block', this.zone, parseInt(message.woHeader.number));\n }\n}\n/**\n * A **SocketPendingSubscriber** listens for pending transactions and emits `\"pending\"` events.\n *\n * @category Providers\n */\nexport class SocketPendingSubscriber extends SocketSubscriber {\n /**\n * Creates a new **SocketPendingSubscriber**.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n */\n constructor(provider, zone) {\n super(provider, ['newPendingTransactions'], zone);\n }\n /**\n * Emit the pending event.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n * @param {any} message - The message to emit.\n * @returns {Promise}\n */\n async _emit(provider, message) {\n provider.emit('pending', message);\n }\n}\n/**\n * A **SocketEventSubscriber** listens for event logs.\n *\n * @category Providers\n */\nexport class SocketEventSubscriber extends SocketSubscriber {\n #logFilter;\n /**\n * The filter.\n *\n * @type {EventFilter}\n */\n get logFilter() {\n return JSON.parse(this.#logFilter);\n }\n /**\n * Creates a new **SocketEventSubscriber**.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n * @param {EventFilter} filter - The event filter.\n */\n constructor(provider, filter, zone) {\n super(provider, ['logs', filter], zone);\n this.#logFilter = JSON.stringify(filter);\n }\n /**\n * Emit the event log.\n *\n * @ignore\n * @param {SocketProvider} provider - The socket provider.\n * @param {any} message - The message to emit.\n * @returns {Promise}\n */\n async _emit(provider, message) {\n provider.emit(this.logFilter, this.zone, provider._wrapLog(message, provider._network));\n }\n}\n/**\n * A **SocketProvider** is backed by a long-lived connection over a socket, which can subscribe and receive real-time\n * messages over its communication channel.\n *\n * @category Providers\n */\nexport class SocketProvider extends JsonRpcApiProvider {\n #callbacks;\n // Maps each filterId to its subscriber\n #subs;\n // If any events come in before a subscriber has finished\n // registering, queue them\n #pending;\n /**\n * Creates a new **SocketProvider** connected to `network`.\n *\n * If unspecified, the network will be discovered.\n *\n * @param {Networkish} [network] - The network to connect to.\n * @param {JsonRpcApiProviderOptions} [_options] - The options for the provider.\n */\n constructor(network, _options) {\n // Copy the options\n const options = Object.assign({}, _options != null ? _options : {});\n // Support for batches is generally not supported for\n // connection-base providers; if this changes in the future\n // the _send should be updated to reflect this\n assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1, 'sockets-based providers do not support batches', 'options.batchMaxCount', _options);\n options.batchMaxCount = 1;\n // Socket-based Providers (generally) cannot change their network,\n // since they have a long-lived connection; but let people override\n // this if they have just cause.\n if (options.staticNetwork == null) {\n options.staticNetwork = true;\n }\n super(network, options);\n this.#callbacks = new Map();\n this.#subs = new Map();\n this.#pending = new Map();\n }\n /**\n * Get the subscriber for a given subscription.\n *\n * @ignore\n * @param {Subscription} sub - The subscription.\n * @returns {Subscriber} The subscriber.\n */\n _getSubscriber(sub) {\n switch (sub.type) {\n case 'close':\n return new UnmanagedSubscriber('close');\n case 'block':\n return new SocketBlockSubscriber(this, sub.zone);\n case 'pending':\n return new SocketPendingSubscriber(this, sub.zone);\n case 'event':\n return new SocketEventSubscriber(this, sub.filter, sub.zone);\n case 'orphan':\n // Handled auto-matically within AbstractProvider\n // when the log.removed = true\n if (sub.filter.orphan === 'drop-log') {\n return new UnmanagedSubscriber('drop-log');\n }\n }\n return super._getSubscriber(sub);\n }\n /**\n * Register a new subscriber. This is used internally by Subscribers and generally is unnecessary unless extending\n * capabilities.\n *\n * @ignore\n * @param {number | string} filterId - The filter ID.\n * @param {SocketSubscriber} subscriber - The subscriber.\n */\n _register(filterId, subscriber) {\n this.#subs.set(filterId, subscriber);\n const pending = this.#pending.get(filterId);\n if (pending) {\n for (const message of pending) {\n subscriber._handleMessage(message);\n }\n this.#pending.delete(filterId);\n }\n }\n /**\n * Send a JSON-RPC payload.\n *\n * @ignore\n * @param {JsonRpcPayload | JsonRpcPayload[]} payload - The payload to send.\n * @param {Shard} [shard] - The shard.\n * @param {boolean} [now] - Whether to send immediately.\n * @returns {Promise<(JsonRpcResult | JsonRpcError)[]>} The result or error.\n */\n async _send(payload, shard, now) {\n if (this._initFailed) {\n console.log('Provider failed to initialize on creation. Run initialize or create a new provider.');\n return [\n {\n id: Array.isArray(payload) ? payload[0].id : payload.id,\n error: {\n code: -32000,\n message: 'Provider failed to initialize on creation. Run initialize or create a new provider.',\n },\n },\n ];\n }\n // WebSocket provider doesn't accept batches\n assertArgument(!Array.isArray(payload), 'WebSocket does not support batch send', 'payload', payload);\n // @TODO: stringify payloads here and store to prevent mutations\n // Prepare a promise to respond to\n const promise = new Promise((resolve, reject) => {\n this.#callbacks.set(payload.id, { payload, resolve, reject });\n });\n // Wait until the socket is connected before writing to it\n try {\n if (!now) {\n await this._waitUntilReady();\n }\n }\n catch (error) {\n this.#callbacks.delete(payload.id);\n return [\n {\n id: Array.isArray(payload) ? payload[0].id : payload.id,\n error: {\n code: -32000,\n message: 'Provider failed to initialize on creation. Run initialize or create a new provider.',\n },\n },\n ];\n }\n // Write the request to the socket\n await this._write(JSON.stringify(payload), shard);\n return [await promise];\n }\n /**\n * Sub-classes **must** call this with messages received over their transport to be processed and dispatched.\n *\n * @ignore\n * @param {string} message - The message to process.\n */\n async _processMessage(message) {\n const result = JSON.parse(message);\n if (result && typeof result === 'object' && 'id' in result) {\n const callback = this.#callbacks.get(result.id);\n if (callback == null) {\n this.emit('error', undefined, makeError('received result for unknown id', 'UNKNOWN_ERROR', {\n reasonCode: 'UNKNOWN_ID',\n result,\n }));\n return;\n }\n this.#callbacks.delete(result.id);\n callback.resolve(result);\n }\n else if (result && result.method === 'quai_subscription') {\n const filterId = result.params.subscription;\n const subscriber = this.#subs.get(filterId);\n if (subscriber) {\n subscriber._handleMessage(result.params.result);\n }\n else {\n let pending = this.#pending.get(filterId);\n if (pending == null) {\n pending = [];\n this.#pending.set(filterId, pending);\n }\n pending.push(result.params.result);\n }\n }\n else {\n this.emit('error', undefined, makeError('received unexpected message', 'UNKNOWN_ERROR', {\n reasonCode: 'UNEXPECTED_MESSAGE',\n result,\n }));\n return;\n }\n }\n /**\n * Sub-classes **must** override this to send `message` over their transport.\n *\n * @ignore\n * @param {string} message - The message to send.\n * @param {Shard} [shard] - The shard.\n * @returns {Promise}\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n async _write(message, shard) {\n throw new Error('sub-classes must override this');\n }\n validateUrl(url) {\n const urlPattern = /^(ws):\\/\\/[a-zA-Z0-9.-]+(:\\d+)?$/;\n if (!urlPattern.test(url)) {\n let errorMessage = 'Invalid URL: ';\n if (!/^ws:\\/\\//.test(url)) {\n errorMessage += 'URL must start with ws://. ';\n }\n if (url.endsWith('/')) {\n errorMessage += 'URL should not end with a /. ';\n }\n if (/\\/[^/]+/.test(url)) {\n errorMessage += 'URL should not contain a path, query string, or fragment. ';\n }\n throw new Error(errorMessage.trim());\n }\n }\n}\n//# sourceMappingURL=provider-socket.js.map","function getGlobal() {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('unable to locate global object');\n}\nconst _WebSocket = getGlobal().WebSocket;\nexport { _WebSocket as WebSocket };\n//# sourceMappingURL=ws-browser.js.map","import { WebSocket as _WebSocket } from './ws.js'; /*-browser*/\nimport { SocketProvider } from './provider-socket.js';\nimport { Shard, toShard } from '../constants/index.js';\nimport { fromShard } from '../constants/shards.js';\n/**\n * A JSON-RPC provider which is backed by a WebSocket.\n *\n * WebSockets are often preferred because they retain a live connection to a server, which permits more instant access\n * to events.\n *\n * However, this incurs higher server infrastructure costs, so additional resources may be required to host your own\n * WebSocket nodes and many third-party services charge additional fees for WebSocket endpoints.\n *\n * @category Providers\n * @extends SocketProvider\n */\nexport class WebSocketProvider extends SocketProvider {\n #websockets;\n /**\n * A map to track the readiness of each shard.\n *\n * @type {Map}\n */\n readyMap = new Map();\n /**\n * Get the array of WebSocketLike objects.\n *\n * @returns {WebSocketLike[]} The array of WebSocketLike objects.\n * @throws {Error} If the websocket is closed.\n */\n get websocket() {\n if (this.#websockets == null) {\n throw new Error('websocket closed');\n }\n return this.#websockets;\n }\n /**\n * Create a new WebSocketProvider.\n *\n * @param {string | string[] | WebSocketLike | WebSocketCreator} url - The URL(s) or WebSocket object or creator.\n * @param {Networkish} [network] - The network to connect to.\n * @param {JsonRpcApiProviderOptions} [options] - The options for the JSON-RPC API provider.\n */\n constructor(url, network, options) {\n super(network, options);\n this.#websockets = [];\n if (typeof url === 'string') {\n this.validateUrl(url);\n }\n else if (Array.isArray(url)) {\n url.forEach((it) => this.validateUrl(it));\n }\n else if (typeof url === 'function') {\n this.validateUrl(url().url);\n }\n else {\n this.validateUrl(url.url);\n }\n this.initialize(typeof url === 'string' ? [url] : url);\n }\n /**\n * Initialize a WebSocket connection for a shard.\n *\n * @ignore\n * @param {WebSocketLike} websocket - The WebSocket object.\n * @param {Shard} shard - The shard identifier.\n */\n initWebSocket(websocket, shard) {\n websocket.onerror = (error) => {\n console.log('WebsocketProvider error', error);\n websocket.close();\n };\n websocket.onopen = async () => {\n try {\n await this._start();\n this.resume();\n this.readyMap.set(shard, true);\n }\n catch (error) {\n console.log('failed to start WebsocketProvider', error);\n this.readyMap.set(shard, false);\n // @TODO: now what? Attempt reconnect?\n }\n };\n websocket.onmessage = (message) => {\n this._processMessage(message.data);\n };\n }\n /**\n * Wait until the shard is ready. Max wait time is ~8 seconds.\n *\n * @param {Shard} shard - The shard identifier.\n * @returns {Promise} A promise that resolves when the shard is ready.\n * @throws {Error} If the shard is not ready within the timeout period.\n */\n async waitShardReady(shard) {\n let count = 0;\n while (!this.readyMap.get(shard)) {\n await new Promise((resolve) => setTimeout(resolve, Math.pow(2, count)));\n if (count > 11) {\n throw new Error('Timeout waiting for shard to be ready');\n }\n count++;\n }\n }\n /**\n * Initialize the URL map with WebSocket connections.\n *\n * @ignore\n * @param {U} urls - The URLs or WebSocket object or creator.\n * @returns {Promise} A promise that resolves when the URL map is initialized.\n */\n async initialize(urls) {\n //clear websockets\n this.#websockets = [];\n this._urlMap.clear();\n try {\n const primeSuffix = this._getOption('usePathing') ? `/${fromShard(Shard.Prime, 'nickname')}` : ':8001';\n const createWebSocket = (baseUrl, suffix) => {\n const tempWs = new _WebSocket(`${baseUrl}${suffix}`);\n return tempWs;\n // wait 2 minutes\n };\n const initShardWebSockets = async (baseUrl) => {\n const shards = await this._getRunningLocations(Shard.Prime, true);\n await Promise.all(shards.map(async (shard) => {\n const port = 8200 + 20 * shard[0] + shard[1];\n const shardEnum = toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);\n const shardSuffix = this._getOption('usePathing')\n ? `/${fromShard(shardEnum, 'nickname')}`\n : `:${port}`;\n const shardUrl = baseUrl.split(':').slice(0, 2).join(':');\n const websocket = createWebSocket(shardUrl, shardSuffix);\n this.initWebSocket(websocket, shardEnum);\n this.#websockets.push(websocket);\n this._urlMap.set(shardEnum, websocket);\n try {\n await this.waitShardReady(shardEnum);\n }\n catch (error) {\n console.log('failed to waitShardReady', error);\n this._initFailed = true;\n }\n }));\n };\n if (Array.isArray(urls)) {\n for (const url of urls) {\n const baseUrl = `${url.split(':')[0]}:${url.split(':')[1]}`;\n const primeWebsocket = createWebSocket(baseUrl, primeSuffix);\n this.initWebSocket(primeWebsocket, Shard.Prime);\n this.#websockets.push(primeWebsocket);\n this._urlMap.set(Shard.Prime, primeWebsocket);\n await this.waitShardReady(Shard.Prime);\n await initShardWebSockets(baseUrl);\n }\n }\n else if (typeof urls === 'function') {\n const primeWebsocket = urls();\n this.initWebSocket(primeWebsocket, Shard.Prime);\n this.#websockets.push(primeWebsocket);\n this._urlMap.set(Shard.Prime, primeWebsocket);\n await this.waitShardReady(Shard.Prime);\n const baseUrl = this.#websockets[0].url.split(':').slice(0, 2).join(':');\n await initShardWebSockets(baseUrl);\n }\n else {\n const primeWebsocket = urls;\n this.initWebSocket(primeWebsocket, Shard.Prime);\n this.#websockets.push(primeWebsocket);\n this._urlMap.set(Shard.Prime, primeWebsocket);\n await this.waitShardReady(Shard.Prime);\n const baseUrl = primeWebsocket.url.split(':').slice(0, 2).join(':');\n await initShardWebSockets(baseUrl);\n }\n if (this.initResolvePromise)\n this.initResolvePromise();\n }\n catch (error) {\n this._initFailed = true;\n console.log('failed to initialize', error);\n //clear websockets\n this.#websockets = [];\n if (this.initRejectPromise)\n this.initRejectPromise(error);\n return;\n }\n }\n /**\n * Write a message to the WebSocket.\n *\n * @ignore\n * @param {string} message - The message to send.\n * @param {Shard} [shard] - The shard identifier.\n * @returns {Promise} A promise that resolves when the message is sent.\n * @throws {Error} If the WebSocket is closed or the shard is not found.\n */\n async _write(message, shard) {\n if (this.websocket.length < 1) {\n throw new Error('Websocket closed');\n }\n if (shard && !this._urlMap.has(shard)) {\n throw new Error('Shard not found');\n }\n const websocket = shard ? this._urlMap.get(shard) : this.websocket[this.websocket.length - 1];\n if (!websocket) {\n throw new Error('Websocket is undefined');\n }\n if (shard) {\n await this.waitShardReady(shard);\n }\n websocket.send(message);\n }\n /**\n * Destroy the WebSocket connections and clean up resources.\n *\n * @returns {Promise} A promise that resolves when the WebSocket connections are closed.\n */\n async destroy() {\n this.#websockets.forEach((it) => it.close());\n this.#websockets = [];\n super.destroy();\n }\n}\n//# sourceMappingURL=provider-websocket.js.map","const Base64 = ')!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';\n/**\n * @ignore\n */\nexport function decodeBits(width, data) {\n const maxValue = (1 << width) - 1;\n const result = [];\n let accum = 0, bits = 0, flood = 0;\n for (let i = 0; i < data.length; i++) {\n // Accumulate 6 bits of data\n accum = (accum << 6) | Base64.indexOf(data[i]);\n bits += 6;\n // While we have enough for a word...\n while (bits >= width) {\n // ...read the word\n const value = accum >> (bits - width);\n accum &= (1 << (bits - width)) - 1;\n bits -= width;\n // A value of 0 indicates we exceeded maxValue, it\n // floods over into the next value\n if (value === 0) {\n flood += maxValue;\n }\n else {\n result.push(value + flood);\n flood = 0;\n }\n }\n }\n return result;\n}\n//# sourceMappingURL=bit-reader.js.map","import { assertArgument } from '../utils/index.js';\nimport { decodeBits } from './bit-reader.js';\nimport { decodeOwl } from './decode-owl.js';\n/**\n * @ignore\n */\nexport function decodeOwlA(data, accents) {\n let words = decodeOwl(data).join(',');\n // Inject the accents\n accents.split(/,/g).forEach((accent) => {\n const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);\n assertArgument(match !== null, 'internal error parsing accents', 'accents', accents);\n let posOffset = 0;\n const positions = decodeBits(parseInt(match[3]), match[4]);\n const charCode = parseInt(match[2]);\n const regex = new RegExp(`([${match[1]}])`, 'g');\n words = words.replace(regex, (all, letter) => {\n const rem = --positions[posOffset];\n if (rem === 0) {\n letter = String.fromCharCode(letter.charCodeAt(0), charCode);\n posOffset++;\n }\n return letter;\n });\n });\n return words.split(',');\n}\n//# sourceMappingURL=decode-owla.js.map","import { WordlistOwl } from './wordlist-owl.js';\nimport { decodeOwlA } from './decode-owla.js';\n/**\n * An OWL-A format Wordlist extends the OWL format to add an overlay onto an OWL format Wordlist to support diacritic\n * marks.\n *\n * This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages\n * based on latin-1 small.\n *\n * If necessary, there are tools within the `generation/` folder to create the necessary data.\n *\n * @category Wordlists\n */\nexport class WordlistOwlA extends WordlistOwl {\n #accent;\n /**\n * Creates a new Wordlist for `locale` using the OWLA `data` and `accent` data and validated against the `checksum`.\n */\n constructor(locale, data, accent, checksum) {\n super(locale, data, checksum);\n this.#accent = accent;\n }\n /**\n * The OWLA-encoded accent data.\n *\n * @ignore\n */\n get _accent() {\n return this.#accent;\n }\n /**\n * Decode all the words for the wordlist.\n *\n * @ignore\n */\n _decodeWords() {\n return decodeOwlA(this._data, this._accent);\n }\n}\n//# sourceMappingURL=wordlist-owla.js.map","import { WordlistOwlA } from './wordlist-owla.js';\nconst words = \"0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_LoAmpuAnc]ApaAr]I>Is)IvoOqueOzaUle%Up 0Cl.EgoE=EnEr#F[G +M->NeN%P_sR>Rue]SneTaU{d2Am^AnA+AseAveI,)ImaInica2B_Cc~|i'Ci`CoDigoDoF_G!He)JinJoL/ch/eg$Lg Lin/l LmoLum`Mba)M!Mi{Mo&Mpr-deNej}g-oc!Nsej}t PaPi(az.Rba%RchoR&nR.(r!S!SmosS%2AneoAt!E Ec!Ei&EmaIaIm,Ip%IsisOmoOnicaOque%U&Uz2Ad+Ar#At+BoBr*| aEl=En#Er{Es%EvaId Lebr/p/#Mb_Mpl*N-e%O%P.Pul( R$Se'Sf[zVaVi'5BleCeL^Ming}N Ra&Rm*RAu%EchaOrO%U*UjoU^2B@CaGa%G.L$Lle#N&Rm(+Rtun(z SaTo2AcaA'AsaAtisAveIe%Il=IpeIsI#OG Gu!aJaMb_Ng}^Nr((mig('St?Yo5E>ElgaEr%ENgl-$Nt Pit!R S#V,?Zg :7Lo5A]:B$C$C[DoD+nG #GrimaGu`I>M!Mi`Mp --ch-gos%NzaPizRgoRvaStimaTaTexT*U_lV Zo3AlCc~|eC#rErG~Gumb_Ja'Ngu-#NaOnOp &S~TalT[VeY,{3B!%dB+C^D!Di EnzoGaG!oMaMi)M.Mp$NceN&Ne-go)N}t!`Qui&SoS%T!aT$T+2AgaAmaAn#AveEg En Ev Or Ov!Uv@2BoC~CoCu[GicaG+MbrizM}jaTe5|aC*G J}-esPaSt+ToZ:Ce%|oD!aD_Du+Est+F@G@GoIzL{dLe%Ll/oMaMboMutN>N&Nej Ng-iquiNj N}Re(f?Rg,Ri&RmolR+nR)sRzoSaSc aSivoT T!@TizTrizXimoY^Z^ca3|aDal]D$Du]J?]J^L,/.M^i-^NsajeN)NuRca&R,gueRi#SS.TaT!To&T+Zc]3E&ElEmb+G/Lag+Lit Ll.M}-!}im}u#OpeR SaS!@S?SmoTadTo5|?aC~DaDe=HoJ LdeL!Li'M,#Mi- c-ed-j-#NoRad(d!Re'R*R+Rs(%lScaStr TivoV!V?Zo5|oD EbleE]Er)Est[G_J!L/e%L%N&Nec(alRoScu=SeoSgoSicaS=:C C~D IpeRanj(izRr SalTalTivoTu[lUseaValVeVi{d3C$Ct G Goc$G+OnRv$ToUt+V V!a3|oDoEb]E#NezNoTi&Vel5Bleza|eMin(i(m()TaTic@Va#Ve]V$5BeCaCleoD?=DoE[EveEzLoM!oTr@:Sis0EC~E[In On!T TicaUes#1Ac~A&rAlBi%CaD,EjaGa'G@Gul=I,)Ig,Il]OQues%Uga0Ad@Cu+Ez'OT[0O'Ro1EjaU=1I&Ige'0En)0O':C#D_El]Gi`GoIsJ oLabr/>Le%Li&Lm/om/p NNalNi>Nt!-ue=PaPelP?]Que)R Rcel(edR*RoRpa&RqueR[foR)S SeoS~SoS%TaT$Tr@UsaU%VoYa<3A#nCa&C!a|oDalD*G IneL L{'Le/ig+LlejoLoLuc--s N.OnOrPi'Que'R(ch(d!Rez(f?Ri>Rl(mizEgun%Em$EnsaE|!oD^Eb=Er%Es#Lg/*Lm.LpoLrNd*N%P #Pet*PoN{PaP!oSaScaSt+T 5BiB^DoE{G*I&In/e%LoMboM^Ptu[TaTi`:Ba&B!B$BleC GazG[&L/&L!oL*Lm.L.Ls/#LudLv Mb-c~Ndi-e Ng_Ni{dN}#PoQueRdin()nSt_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv!t.trim());for(let i=0;iPromise.resolve(value[k])));return results.reduce((accum,v,index)=>{accum[keys[index]]=v;return accum},{})}function getStatic(ctor,key){for(let i=0;i<32;i++){if(ctor[key]){return ctor[key]}if(!ctor.prototype||typeof ctor.prototype!=="object"){break}ctor=Object.getPrototypeOf(ctor.prototype).constructor}return null}function defineProperties(target,values,types){for(const key in values){const value=values[key];const type=types?types[key]:null;if(type){checkType(value,type,key)}Object.defineProperty(target,key,{enumerable:true,value:value,writable:false})}}function stringify(value){if(value==null){return"null"}if(Array.isArray(value)){return"[ "+value.map(stringify).join(", ")+" ]"}if(value instanceof Uint8Array){const HEX="0123456789abcdef";let result="0x";for(let i=0;i>4];result+=HEX[value[i]&15]}return result}if(typeof value==="object"&&typeof value.toJSON==="function"){return stringify(value.toJSON())}switch(typeof value){case"boolean":case"symbol":return value.toString();case"bigint":return BigInt(value).toString();case"number":return value.toString();case"string":return JSON.stringify(value);case"object":{const keys=Object.keys(value);keys.sort();return"{ "+keys.map(k=>`${stringify(k)}: ${stringify(value[k])}`).join(", ")+" }"}}return`[ COULD NOT SERIALIZE ]`}function isError(error,code){return error&&error.code===code}function isCallException(error){return isError(error,"CALL_EXCEPTION")}function makeError(message,code,info){const shortMessage=message;{const details=[];if(info){if("message"in info||"code"in info||"name"in info){throw new Error(`value will overwrite populated values: ${stringify(info)}`)}for(const key in info){if(key==="shortMessage"){continue}const value=info[key];details.push(key+"="+stringify(value))}}details.push(`code=${code}`);details.push(`version=${version}`);if(details.length){message+=" ("+details.join(", ")+")"}}let error;switch(code){case"INVALID_ARGUMENT":error=new TypeError(message);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":error=new RangeError(message);break;default:error=new Error(message)}defineProperties(error,{code:code});if(info){Object.assign(error,info)}if(error.shortMessage==null){defineProperties(error,{shortMessage:shortMessage})}return error}function assert(check,message,code,info){if(!check){throw makeError(message,code,info)}}function assertArgument(check,message,name,value){assert(check,message,"INVALID_ARGUMENT",{argument:name,value:value})}function assertArgumentCount(count,expectedCount,message){if(message==null){message=""}if(message){message=": "+message}assert(count>=expectedCount,"missing arguemnt"+message,"MISSING_ARGUMENT",{count:count,expectedCount:expectedCount});assert(count<=expectedCount,"too many arguemnts"+message,"UNEXPECTED_ARGUMENT",{count:count,expectedCount:expectedCount})}const _normalizeForms=["NFD","NFC","NFKD","NFKC"].reduce((accum,form)=>{try{if("test".normalize(form)!=="test"){throw new Error("bad")}if(form==="NFD"){const check=String.fromCharCode(233).normalize("NFD");const expected=String.fromCharCode(101,769);if(check!==expected){throw new Error("broken")}}accum.push(form)}catch(error){}return accum},[]);function assertNormalize(form){assert(_normalizeForms.indexOf(form)>=0,"platform missing String.prototype.normalize","UNSUPPORTED_OPERATION",{operation:"String.prototype.normalize",info:{form:form}})}function assertPrivate(givenGuard,guard,className){if(className==null){className=""}if(givenGuard!==guard){let method=className,operation="new";if(className){method+=".";operation+=" "+className}assert(false,`private constructor; use ${method}from* methods`,"UNSUPPORTED_OPERATION",{operation:operation})}}function _getBytes(value,name,copy){if(value instanceof Uint8Array){if(copy){return new Uint8Array(value)}return value}if(typeof value==="string"&&value.match(/^0x([0-9a-f][0-9a-f])*$/i)){const result=new Uint8Array((value.length-2)/2);let offset=2;for(let i=0;i>4]+HexCharacters[v&15]}return result}function concat(datas){return"0x"+datas.map(d=>hexlify(d).substring(2)).join("")}function dataLength(data){if(isHexString(data,true)){return(data.length-2)/2}return getBytes(data).length}function dataSlice(data,start,end){const bytes=getBytes(data);if(end!=null&&end>bytes.length){assert(false,"cannot slice beyond data bounds","BUFFER_OVERRUN",{buffer:bytes,length:bytes.length,offset:end})}return hexlify(bytes.slice(start==null?0:start,end==null?bytes.length:end))}function stripZerosLeft(data){let bytes=hexlify(data).substring(2);while(bytes.startsWith("00")){bytes=bytes.substring(2)}return"0x"+bytes}function zeroPad(data,length,left){const bytes=getBytes(data);assert(length>=bytes.length,"padding exceeds data length","BUFFER_OVERRUN",{buffer:new Uint8Array(bytes),length:length,offset:length+1});const result=new Uint8Array(length);result.fill(0);if(left){result.set(bytes,length-bytes.length)}else{result.set(bytes,0)}return hexlify(result)}function zeroPadValue(data,length){return zeroPad(data,length,true)}function zeroPadBytes(data,length){return zeroPad(data,length,false)}class EventPayload{filter;emitter;#listener;constructor(emitter,listener,filter){this.#listener=listener;defineProperties(this,{emitter:emitter,filter:filter})}async removeListener(){if(this.#listener==null){return}await this.emitter.off(this.filter,this.#listener)}}function decodeBase64(textData){textData=atob(textData);const data=new Uint8Array(textData.length);for(let i=0;i31){throw new Error("bytes32 string must be less than 32 bytes")}return zeroPadBytes(bytes,32)}function decodeBytes32(_bytes){const data=getBytes(_bytes,"bytes");if(data.length!==32){throw new Error("invalid bytes32 - not 32 bytes long")}if(data[31]!==0){throw new Error("invalid bytes32 string - no null terminator")}let length=31;while(data[length-1]===0){length--}return toUtf8String(data.slice(0,length))}const BN_0$8=BigInt(0);const BN_1$4=BigInt(1);const maxValue=9007199254740991;function fromTwos(_value,_width){const value=getUint(_value,"value");const width=BigInt(getNumber(_width,"width"));assert(value>>width===BN_0$8,"overflow","NUMERIC_FAULT",{operation:"fromTwos",fault:"overflow",value:_value});if(value>>width-BN_1$4){const mask=(BN_1$4<=-maxValue&&value<=maxValue,"overflow",name||"value",value);return BigInt(value);case"string":try{if(value===""){throw new Error("empty string")}if(value[0]==="-"&&value[1]!=="-"){return-BigInt(value.substring(1))}return BigInt(value)}catch(e){assertArgument(false,`invalid BigNumberish string: ${e.message}`,name||"value",value)}}assertArgument(false,"invalid BigNumberish value",name||"value",value)}function bigIntAbs(value){value=getBigInt(value);if(value===-BN_0$8||value=BN_0$8,"unsigned value cannot be negative","NUMERIC_FAULT",{fault:"overflow",operation:"getUint",value:value});return result}const Nibbles$1="0123456789abcdef";function toBigInt(value){if(value instanceof Uint8Array){let result="0x0";for(const v of value){result+=Nibbles$1[v>>4];result+=Nibbles$1[v&15]}return BigInt(result)}return getBigInt(value)}function getNumber(value,name){switch(typeof value){case"bigint":assertArgument(value>=-maxValue&&value<=maxValue,"overflow",name||"value",value);return Number(value);case"number":assertArgument(Number.isInteger(value),"underflow",name||"value",value);assertArgument(value>=-maxValue&&value<=maxValue,"overflow",name||"value",value);return value;case"string":try{if(value===""){throw new Error("empty string")}return getNumber(BigInt(value),name)}catch(e){assertArgument(false,`invalid numeric string: ${e.message}`,name||"value",value)}}assertArgument(false,"invalid numeric value",name||"value",value)}function toNumber(value){return getNumber(toBigInt(value))}function toBeHex(_value,_width){const value=getUint(_value,"value");let result=value.toString(16);if(_width==null){if(result.length%2){result="0"+result}}else{const width=getNumber(_width,"width");assert(width*2>=result.length,`value exceeds width (${width} bytes)`,"NUMERIC_FAULT",{operation:"toBeHex",fault:"overflow",value:_value});while(result.lengthProtoHash.fromObject(item))}return message}toObject(){const data={};if(this.hashes!=null){data.hashes=this.hashes.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.hashes.length)writer.writeRepeatedMessage(1,this.hashes,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoHashes;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.hashes,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoHash.deserialize(reader),ProtoHash));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoHashes.deserialize(bytes)}}common.ProtoHashes=ProtoHashes;class ProtoAddress extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("value"in data&&data.value!=undefined){this.value=data.value}}}get value(){return pb_1__namespace.Message.getFieldWithDefault(this,1,new Uint8Array(0))}set value(value){pb_1__namespace.Message.setField(this,1,value)}static fromObject(data){const message=new ProtoAddress({});if(data.value!=null){message.value=data.value}return message}toObject(){const data={};if(this.value!=null){data.value=this.value}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.value.length)writer.writeBytes(1,this.value);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoAddress;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.value=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoAddress.deserialize(bytes)}}common.ProtoAddress=ProtoAddress;class ProtoNumber extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("value"in data&&data.value!=undefined){this.value=data.value}}}get value(){return pb_1__namespace.Message.getFieldWithDefault(this,1,0)}set value(value){pb_1__namespace.Message.setField(this,1,value)}static fromObject(data){const message=new ProtoNumber({});if(data.value!=null){message.value=data.value}return message}toObject(){const data={};if(this.value!=null){data.value=this.value}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.value!=0)writer.writeUint64(1,this.value);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoNumber;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.value=reader.readUint64();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoNumber.deserialize(bytes)}}common.ProtoNumber=ProtoNumber;class ProtoLocations extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("locations"in data&&data.locations!=undefined){this.locations=data.locations}}}get locations(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoLocation,1)}set locations(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoLocations({});if(data.locations!=null){message.locations=data.locations.map(item=>ProtoLocation.fromObject(item))}return message}toObject(){const data={};if(this.locations!=null){data.locations=this.locations.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.locations.length)writer.writeRepeatedMessage(1,this.locations,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoLocations;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.locations,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoLocation.deserialize(reader),ProtoLocation));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoLocations.deserialize(bytes)}}common.ProtoLocations=ProtoLocations})(common||(common={}));var block;(function(block){class ProtoHeader extends pb_1__namespace.Message{#one_of_decls=[[2],[3],[4],[5],[6],[7],[9],[10],[14],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1,8,11,12,13,15],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("parent_hash"in data&&data.parent_hash!=undefined){this.parent_hash=data.parent_hash}if("uncle_hash"in data&&data.uncle_hash!=undefined){this.uncle_hash=data.uncle_hash}if("coinbase"in data&&data.coinbase!=undefined){this.coinbase=data.coinbase}if("evm_root"in data&&data.evm_root!=undefined){this.evm_root=data.evm_root}if("tx_hash"in data&&data.tx_hash!=undefined){this.tx_hash=data.tx_hash}if("etx_hash"in data&&data.etx_hash!=undefined){this.etx_hash=data.etx_hash}if("etx_rollup_hash"in data&&data.etx_rollup_hash!=undefined){this.etx_rollup_hash=data.etx_rollup_hash}if("manifest_hash"in data&&data.manifest_hash!=undefined){this.manifest_hash=data.manifest_hash}if("receipt_hash"in data&&data.receipt_hash!=undefined){this.receipt_hash=data.receipt_hash}if("difficulty"in data&&data.difficulty!=undefined){this.difficulty=data.difficulty}if("parent_entropy"in data&&data.parent_entropy!=undefined){this.parent_entropy=data.parent_entropy}if("parent_delta_s"in data&&data.parent_delta_s!=undefined){this.parent_delta_s=data.parent_delta_s}if("parent_uncled_sub_delta_s"in data&&data.parent_uncled_sub_delta_s!=undefined){this.parent_uncled_sub_delta_s=data.parent_uncled_sub_delta_s}if("uncled_s"in data&&data.uncled_s!=undefined){this.uncled_s=data.uncled_s}if("number"in data&&data.number!=undefined){this.number=data.number}if("gas_limit"in data&&data.gas_limit!=undefined){this.gas_limit=data.gas_limit}if("gas_used"in data&&data.gas_used!=undefined){this.gas_used=data.gas_used}if("base_fee"in data&&data.base_fee!=undefined){this.base_fee=data.base_fee}if("location"in data&&data.location!=undefined){this.location=data.location}if("extra"in data&&data.extra!=undefined){this.extra=data.extra}if("mix_hash"in data&&data.mix_hash!=undefined){this.mix_hash=data.mix_hash}if("nonce"in data&&data.nonce!=undefined){this.nonce=data.nonce}if("utxo_root"in data&&data.utxo_root!=undefined){this.utxo_root=data.utxo_root}if("etx_set_hash"in data&&data.etx_set_hash!=undefined){this.etx_set_hash=data.etx_set_hash}if("efficiency_score"in data&&data.efficiency_score!=undefined){this.efficiency_score=data.efficiency_score}if("threshold_count"in data&&data.threshold_count!=undefined){this.threshold_count=data.threshold_count}if("expansion_number"in data&&data.expansion_number!=undefined){this.expansion_number=data.expansion_number}if("etx_eligible_slices"in data&&data.etx_eligible_slices!=undefined){this.etx_eligible_slices=data.etx_eligible_slices}if("prime_terminus"in data&&data.prime_terminus!=undefined){this.prime_terminus=data.prime_terminus}if("interlink_root_hash"in data&&data.interlink_root_hash!=undefined){this.interlink_root_hash=data.interlink_root_hash}}}get parent_hash(){return pb_1__namespace.Message.getRepeatedWrapperField(this,common.ProtoHash,1)}set parent_hash(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}get uncle_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,2)}set uncle_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,2,this.#one_of_decls[0],value)}get has_uncle_hash(){return pb_1__namespace.Message.getField(this,2)!=null}get coinbase(){return pb_1__namespace.Message.getFieldWithDefault(this,3,new Uint8Array(0))}set coinbase(value){pb_1__namespace.Message.setOneofField(this,3,this.#one_of_decls[1],value)}get has_coinbase(){return pb_1__namespace.Message.getField(this,3)!=null}get evm_root(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,4)}set evm_root(value){pb_1__namespace.Message.setOneofWrapperField(this,4,this.#one_of_decls[2],value)}get has_evm_root(){return pb_1__namespace.Message.getField(this,4)!=null}get tx_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,5)}set tx_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,5,this.#one_of_decls[3],value)}get has_tx_hash(){return pb_1__namespace.Message.getField(this,5)!=null}get etx_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,6)}set etx_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,6,this.#one_of_decls[4],value)}get has_etx_hash(){return pb_1__namespace.Message.getField(this,6)!=null}get etx_rollup_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,7)}set etx_rollup_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,7,this.#one_of_decls[5],value)}get has_etx_rollup_hash(){return pb_1__namespace.Message.getField(this,7)!=null}get manifest_hash(){return pb_1__namespace.Message.getRepeatedWrapperField(this,common.ProtoHash,8)}set manifest_hash(value){pb_1__namespace.Message.setRepeatedWrapperField(this,8,value)}get receipt_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,9)}set receipt_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,9,this.#one_of_decls[6],value)}get has_receipt_hash(){return pb_1__namespace.Message.getField(this,9)!=null}get difficulty(){return pb_1__namespace.Message.getFieldWithDefault(this,10,new Uint8Array(0))}set difficulty(value){pb_1__namespace.Message.setOneofField(this,10,this.#one_of_decls[7],value)}get has_difficulty(){return pb_1__namespace.Message.getField(this,10)!=null}get parent_entropy(){return pb_1__namespace.Message.getFieldWithDefault(this,11,[])}set parent_entropy(value){pb_1__namespace.Message.setField(this,11,value)}get parent_delta_s(){return pb_1__namespace.Message.getFieldWithDefault(this,12,[])}set parent_delta_s(value){pb_1__namespace.Message.setField(this,12,value)}get parent_uncled_sub_delta_s(){return pb_1__namespace.Message.getFieldWithDefault(this,13,[])}set parent_uncled_sub_delta_s(value){pb_1__namespace.Message.setField(this,13,value)}get uncled_s(){return pb_1__namespace.Message.getFieldWithDefault(this,14,new Uint8Array(0))}set uncled_s(value){pb_1__namespace.Message.setOneofField(this,14,this.#one_of_decls[8],value)}get has_uncled_s(){return pb_1__namespace.Message.getField(this,14)!=null}get number(){return pb_1__namespace.Message.getFieldWithDefault(this,15,[])}set number(value){pb_1__namespace.Message.setField(this,15,value)}get gas_limit(){return pb_1__namespace.Message.getFieldWithDefault(this,16,0)}set gas_limit(value){pb_1__namespace.Message.setOneofField(this,16,this.#one_of_decls[9],value)}get has_gas_limit(){return pb_1__namespace.Message.getField(this,16)!=null}get gas_used(){return pb_1__namespace.Message.getFieldWithDefault(this,17,0)}set gas_used(value){pb_1__namespace.Message.setOneofField(this,17,this.#one_of_decls[10],value)}get has_gas_used(){return pb_1__namespace.Message.getField(this,17)!=null}get base_fee(){return pb_1__namespace.Message.getFieldWithDefault(this,18,new Uint8Array(0))}set base_fee(value){pb_1__namespace.Message.setOneofField(this,18,this.#one_of_decls[11],value)}get has_base_fee(){return pb_1__namespace.Message.getField(this,18)!=null}get location(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoLocation,19)}set location(value){pb_1__namespace.Message.setOneofWrapperField(this,19,this.#one_of_decls[12],value)}get has_location(){return pb_1__namespace.Message.getField(this,19)!=null}get extra(){return pb_1__namespace.Message.getFieldWithDefault(this,20,new Uint8Array(0))}set extra(value){pb_1__namespace.Message.setOneofField(this,20,this.#one_of_decls[13],value)}get has_extra(){return pb_1__namespace.Message.getField(this,20)!=null}get mix_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,21)}set mix_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,21,this.#one_of_decls[14],value)}get has_mix_hash(){return pb_1__namespace.Message.getField(this,21)!=null}get nonce(){return pb_1__namespace.Message.getFieldWithDefault(this,22,0)}set nonce(value){pb_1__namespace.Message.setOneofField(this,22,this.#one_of_decls[15],value)}get has_nonce(){return pb_1__namespace.Message.getField(this,22)!=null}get utxo_root(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,23)}set utxo_root(value){pb_1__namespace.Message.setOneofWrapperField(this,23,this.#one_of_decls[16],value)}get has_utxo_root(){return pb_1__namespace.Message.getField(this,23)!=null}get etx_set_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,24)}set etx_set_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,24,this.#one_of_decls[17],value)}get has_etx_set_hash(){return pb_1__namespace.Message.getField(this,24)!=null}get efficiency_score(){return pb_1__namespace.Message.getFieldWithDefault(this,25,0)}set efficiency_score(value){pb_1__namespace.Message.setOneofField(this,25,this.#one_of_decls[18],value)}get has_efficiency_score(){return pb_1__namespace.Message.getField(this,25)!=null}get threshold_count(){return pb_1__namespace.Message.getFieldWithDefault(this,26,0)}set threshold_count(value){pb_1__namespace.Message.setOneofField(this,26,this.#one_of_decls[19],value)}get has_threshold_count(){return pb_1__namespace.Message.getField(this,26)!=null}get expansion_number(){return pb_1__namespace.Message.getFieldWithDefault(this,27,0)}set expansion_number(value){pb_1__namespace.Message.setOneofField(this,27,this.#one_of_decls[20],value)}get has_expansion_number(){return pb_1__namespace.Message.getField(this,27)!=null}get etx_eligible_slices(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,28)}set etx_eligible_slices(value){pb_1__namespace.Message.setOneofWrapperField(this,28,this.#one_of_decls[21],value)}get has_etx_eligible_slices(){return pb_1__namespace.Message.getField(this,28)!=null}get prime_terminus(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,29)}set prime_terminus(value){pb_1__namespace.Message.setOneofWrapperField(this,29,this.#one_of_decls[22],value)}get has_prime_terminus(){return pb_1__namespace.Message.getField(this,29)!=null}get interlink_root_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,30)}set interlink_root_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,30,this.#one_of_decls[23],value)}get has_interlink_root_hash(){return pb_1__namespace.Message.getField(this,30)!=null}get _uncle_hash(){const cases={0:"none",2:"uncle_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}get _coinbase(){const cases={0:"none",3:"coinbase"};return cases[pb_1__namespace.Message.computeOneofCase(this,[3])]}get _evm_root(){const cases={0:"none",4:"evm_root"};return cases[pb_1__namespace.Message.computeOneofCase(this,[4])]}get _tx_hash(){const cases={0:"none",5:"tx_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[5])]}get _etx_hash(){const cases={0:"none",6:"etx_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[6])]}get _etx_rollup_hash(){const cases={0:"none",7:"etx_rollup_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[7])]}get _receipt_hash(){const cases={0:"none",9:"receipt_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[9])]}get _difficulty(){const cases={0:"none",10:"difficulty"};return cases[pb_1__namespace.Message.computeOneofCase(this,[10])]}get _uncled_s(){const cases={0:"none",14:"uncled_s"};return cases[pb_1__namespace.Message.computeOneofCase(this,[14])]}get _gas_limit(){const cases={0:"none",16:"gas_limit"};return cases[pb_1__namespace.Message.computeOneofCase(this,[16])]}get _gas_used(){const cases={0:"none",17:"gas_used"};return cases[pb_1__namespace.Message.computeOneofCase(this,[17])]}get _base_fee(){const cases={0:"none",18:"base_fee"};return cases[pb_1__namespace.Message.computeOneofCase(this,[18])]}get _location(){const cases={0:"none",19:"location"};return cases[pb_1__namespace.Message.computeOneofCase(this,[19])]}get _extra(){const cases={0:"none",20:"extra"};return cases[pb_1__namespace.Message.computeOneofCase(this,[20])]}get _mix_hash(){const cases={0:"none",21:"mix_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[21])]}get _nonce(){const cases={0:"none",22:"nonce"};return cases[pb_1__namespace.Message.computeOneofCase(this,[22])]}get _utxo_root(){const cases={0:"none",23:"utxo_root"};return cases[pb_1__namespace.Message.computeOneofCase(this,[23])]}get _etx_set_hash(){const cases={0:"none",24:"etx_set_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[24])]}get _efficiency_score(){const cases={0:"none",25:"efficiency_score"};return cases[pb_1__namespace.Message.computeOneofCase(this,[25])]}get _threshold_count(){const cases={0:"none",26:"threshold_count"};return cases[pb_1__namespace.Message.computeOneofCase(this,[26])]}get _expansion_number(){const cases={0:"none",27:"expansion_number"};return cases[pb_1__namespace.Message.computeOneofCase(this,[27])]}get _etx_eligible_slices(){const cases={0:"none",28:"etx_eligible_slices"};return cases[pb_1__namespace.Message.computeOneofCase(this,[28])]}get _prime_terminus(){const cases={0:"none",29:"prime_terminus"};return cases[pb_1__namespace.Message.computeOneofCase(this,[29])]}get _interlink_root_hash(){const cases={0:"none",30:"interlink_root_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[30])]}static fromObject(data){const message=new ProtoHeader({});if(data.parent_hash!=null){message.parent_hash=data.parent_hash.map(item=>common.ProtoHash.fromObject(item))}if(data.uncle_hash!=null){message.uncle_hash=common.ProtoHash.fromObject(data.uncle_hash)}if(data.coinbase!=null){message.coinbase=data.coinbase}if(data.evm_root!=null){message.evm_root=common.ProtoHash.fromObject(data.evm_root)}if(data.tx_hash!=null){message.tx_hash=common.ProtoHash.fromObject(data.tx_hash)}if(data.etx_hash!=null){message.etx_hash=common.ProtoHash.fromObject(data.etx_hash)}if(data.etx_rollup_hash!=null){message.etx_rollup_hash=common.ProtoHash.fromObject(data.etx_rollup_hash)}if(data.manifest_hash!=null){message.manifest_hash=data.manifest_hash.map(item=>common.ProtoHash.fromObject(item))}if(data.receipt_hash!=null){message.receipt_hash=common.ProtoHash.fromObject(data.receipt_hash)}if(data.difficulty!=null){message.difficulty=data.difficulty}if(data.parent_entropy!=null){message.parent_entropy=data.parent_entropy}if(data.parent_delta_s!=null){message.parent_delta_s=data.parent_delta_s}if(data.parent_uncled_sub_delta_s!=null){message.parent_uncled_sub_delta_s=data.parent_uncled_sub_delta_s}if(data.uncled_s!=null){message.uncled_s=data.uncled_s}if(data.number!=null){message.number=data.number}if(data.gas_limit!=null){message.gas_limit=data.gas_limit}if(data.gas_used!=null){message.gas_used=data.gas_used}if(data.base_fee!=null){message.base_fee=data.base_fee}if(data.location!=null){message.location=common.ProtoLocation.fromObject(data.location)}if(data.extra!=null){message.extra=data.extra}if(data.mix_hash!=null){message.mix_hash=common.ProtoHash.fromObject(data.mix_hash)}if(data.nonce!=null){message.nonce=data.nonce}if(data.utxo_root!=null){message.utxo_root=common.ProtoHash.fromObject(data.utxo_root)}if(data.etx_set_hash!=null){message.etx_set_hash=common.ProtoHash.fromObject(data.etx_set_hash)}if(data.efficiency_score!=null){message.efficiency_score=data.efficiency_score}if(data.threshold_count!=null){message.threshold_count=data.threshold_count}if(data.expansion_number!=null){message.expansion_number=data.expansion_number}if(data.etx_eligible_slices!=null){message.etx_eligible_slices=common.ProtoHash.fromObject(data.etx_eligible_slices)}if(data.prime_terminus!=null){message.prime_terminus=common.ProtoHash.fromObject(data.prime_terminus)}if(data.interlink_root_hash!=null){message.interlink_root_hash=common.ProtoHash.fromObject(data.interlink_root_hash)}return message}toObject(){const data={};if(this.parent_hash!=null){data.parent_hash=this.parent_hash.map(item=>item.toObject())}if(this.uncle_hash!=null){data.uncle_hash=this.uncle_hash.toObject()}if(this.coinbase!=null){data.coinbase=this.coinbase}if(this.evm_root!=null){data.evm_root=this.evm_root.toObject()}if(this.tx_hash!=null){data.tx_hash=this.tx_hash.toObject()}if(this.etx_hash!=null){data.etx_hash=this.etx_hash.toObject()}if(this.etx_rollup_hash!=null){data.etx_rollup_hash=this.etx_rollup_hash.toObject()}if(this.manifest_hash!=null){data.manifest_hash=this.manifest_hash.map(item=>item.toObject())}if(this.receipt_hash!=null){data.receipt_hash=this.receipt_hash.toObject()}if(this.difficulty!=null){data.difficulty=this.difficulty}if(this.parent_entropy!=null){data.parent_entropy=this.parent_entropy}if(this.parent_delta_s!=null){data.parent_delta_s=this.parent_delta_s}if(this.parent_uncled_sub_delta_s!=null){data.parent_uncled_sub_delta_s=this.parent_uncled_sub_delta_s}if(this.uncled_s!=null){data.uncled_s=this.uncled_s}if(this.number!=null){data.number=this.number}if(this.gas_limit!=null){data.gas_limit=this.gas_limit}if(this.gas_used!=null){data.gas_used=this.gas_used}if(this.base_fee!=null){data.base_fee=this.base_fee}if(this.location!=null){data.location=this.location.toObject()}if(this.extra!=null){data.extra=this.extra}if(this.mix_hash!=null){data.mix_hash=this.mix_hash.toObject()}if(this.nonce!=null){data.nonce=this.nonce}if(this.utxo_root!=null){data.utxo_root=this.utxo_root.toObject()}if(this.etx_set_hash!=null){data.etx_set_hash=this.etx_set_hash.toObject()}if(this.efficiency_score!=null){data.efficiency_score=this.efficiency_score}if(this.threshold_count!=null){data.threshold_count=this.threshold_count}if(this.expansion_number!=null){data.expansion_number=this.expansion_number}if(this.etx_eligible_slices!=null){data.etx_eligible_slices=this.etx_eligible_slices.toObject()}if(this.prime_terminus!=null){data.prime_terminus=this.prime_terminus.toObject()}if(this.interlink_root_hash!=null){data.interlink_root_hash=this.interlink_root_hash.toObject()}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.parent_hash.length)writer.writeRepeatedMessage(1,this.parent_hash,item=>item.serialize(writer));if(this.has_uncle_hash)writer.writeMessage(2,this.uncle_hash,()=>this.uncle_hash.serialize(writer));if(this.has_coinbase)writer.writeBytes(3,this.coinbase);if(this.has_evm_root)writer.writeMessage(4,this.evm_root,()=>this.evm_root.serialize(writer));if(this.has_tx_hash)writer.writeMessage(5,this.tx_hash,()=>this.tx_hash.serialize(writer));if(this.has_etx_hash)writer.writeMessage(6,this.etx_hash,()=>this.etx_hash.serialize(writer));if(this.has_etx_rollup_hash)writer.writeMessage(7,this.etx_rollup_hash,()=>this.etx_rollup_hash.serialize(writer));if(this.manifest_hash.length)writer.writeRepeatedMessage(8,this.manifest_hash,item=>item.serialize(writer));if(this.has_receipt_hash)writer.writeMessage(9,this.receipt_hash,()=>this.receipt_hash.serialize(writer));if(this.has_difficulty)writer.writeBytes(10,this.difficulty);if(this.parent_entropy.length)writer.writeRepeatedBytes(11,this.parent_entropy);if(this.parent_delta_s.length)writer.writeRepeatedBytes(12,this.parent_delta_s);if(this.parent_uncled_sub_delta_s.length)writer.writeRepeatedBytes(13,this.parent_uncled_sub_delta_s);if(this.has_uncled_s)writer.writeBytes(14,this.uncled_s);if(this.number.length)writer.writeRepeatedBytes(15,this.number);if(this.has_gas_limit)writer.writeUint64(16,this.gas_limit);if(this.has_gas_used)writer.writeUint64(17,this.gas_used);if(this.has_base_fee)writer.writeBytes(18,this.base_fee);if(this.has_location)writer.writeMessage(19,this.location,()=>this.location.serialize(writer));if(this.has_extra)writer.writeBytes(20,this.extra);if(this.has_mix_hash)writer.writeMessage(21,this.mix_hash,()=>this.mix_hash.serialize(writer));if(this.has_nonce)writer.writeUint64(22,this.nonce);if(this.has_utxo_root)writer.writeMessage(23,this.utxo_root,()=>this.utxo_root.serialize(writer));if(this.has_etx_set_hash)writer.writeMessage(24,this.etx_set_hash,()=>this.etx_set_hash.serialize(writer));if(this.has_efficiency_score)writer.writeUint64(25,this.efficiency_score);if(this.has_threshold_count)writer.writeUint64(26,this.threshold_count);if(this.has_expansion_number)writer.writeUint64(27,this.expansion_number);if(this.has_etx_eligible_slices)writer.writeMessage(28,this.etx_eligible_slices,()=>this.etx_eligible_slices.serialize(writer));if(this.has_prime_terminus)writer.writeMessage(29,this.prime_terminus,()=>this.prime_terminus.serialize(writer));if(this.has_interlink_root_hash)writer.writeMessage(30,this.interlink_root_hash,()=>this.interlink_root_hash.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoHeader;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.parent_hash,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,common.ProtoHash.deserialize(reader),common.ProtoHash));break;case 2:reader.readMessage(message.uncle_hash,()=>message.uncle_hash=common.ProtoHash.deserialize(reader));break;case 3:message.coinbase=reader.readBytes();break;case 4:reader.readMessage(message.evm_root,()=>message.evm_root=common.ProtoHash.deserialize(reader));break;case 5:reader.readMessage(message.tx_hash,()=>message.tx_hash=common.ProtoHash.deserialize(reader));break;case 6:reader.readMessage(message.etx_hash,()=>message.etx_hash=common.ProtoHash.deserialize(reader));break;case 7:reader.readMessage(message.etx_rollup_hash,()=>message.etx_rollup_hash=common.ProtoHash.deserialize(reader));break;case 8:reader.readMessage(message.manifest_hash,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,8,common.ProtoHash.deserialize(reader),common.ProtoHash));break;case 9:reader.readMessage(message.receipt_hash,()=>message.receipt_hash=common.ProtoHash.deserialize(reader));break;case 10:message.difficulty=reader.readBytes();break;case 11:pb_1__namespace.Message.addToRepeatedField(message,11,reader.readBytes());break;case 12:pb_1__namespace.Message.addToRepeatedField(message,12,reader.readBytes());break;case 13:pb_1__namespace.Message.addToRepeatedField(message,13,reader.readBytes());break;case 14:message.uncled_s=reader.readBytes();break;case 15:pb_1__namespace.Message.addToRepeatedField(message,15,reader.readBytes());break;case 16:message.gas_limit=reader.readUint64();break;case 17:message.gas_used=reader.readUint64();break;case 18:message.base_fee=reader.readBytes();break;case 19:reader.readMessage(message.location,()=>message.location=common.ProtoLocation.deserialize(reader));break;case 20:message.extra=reader.readBytes();break;case 21:reader.readMessage(message.mix_hash,()=>message.mix_hash=common.ProtoHash.deserialize(reader));break;case 22:message.nonce=reader.readUint64();break;case 23:reader.readMessage(message.utxo_root,()=>message.utxo_root=common.ProtoHash.deserialize(reader));break;case 24:reader.readMessage(message.etx_set_hash,()=>message.etx_set_hash=common.ProtoHash.deserialize(reader));break;case 25:message.efficiency_score=reader.readUint64();break;case 26:message.threshold_count=reader.readUint64();break;case 27:message.expansion_number=reader.readUint64();break;case 28:reader.readMessage(message.etx_eligible_slices,()=>message.etx_eligible_slices=common.ProtoHash.deserialize(reader));break;case 29:reader.readMessage(message.prime_terminus,()=>message.prime_terminus=common.ProtoHash.deserialize(reader));break;case 30:reader.readMessage(message.interlink_root_hash,()=>message.interlink_root_hash=common.ProtoHash.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoHeader.deserialize(bytes)}}block.ProtoHeader=ProtoHeader;class ProtoTransaction extends pb_1__namespace.Message{#one_of_decls=[[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("type"in data&&data.type!=undefined){this.type=data.type}if("to"in data&&data.to!=undefined){this.to=data.to}if("nonce"in data&&data.nonce!=undefined){this.nonce=data.nonce}if("value"in data&&data.value!=undefined){this.value=data.value}if("gas"in data&&data.gas!=undefined){this.gas=data.gas}if("data"in data&&data.data!=undefined){this.data=data.data}if("chain_id"in data&&data.chain_id!=undefined){this.chain_id=data.chain_id}if("gas_fee_cap"in data&&data.gas_fee_cap!=undefined){this.gas_fee_cap=data.gas_fee_cap}if("gas_tip_cap"in data&&data.gas_tip_cap!=undefined){this.gas_tip_cap=data.gas_tip_cap}if("access_list"in data&&data.access_list!=undefined){this.access_list=data.access_list}if("v"in data&&data.v!=undefined){this.v=data.v}if("r"in data&&data.r!=undefined){this.r=data.r}if("s"in data&&data.s!=undefined){this.s=data.s}if("originating_tx_hash"in data&&data.originating_tx_hash!=undefined){this.originating_tx_hash=data.originating_tx_hash}if("etx_index"in data&&data.etx_index!=undefined){this.etx_index=data.etx_index}if("tx_ins"in data&&data.tx_ins!=undefined){this.tx_ins=data.tx_ins}if("tx_outs"in data&&data.tx_outs!=undefined){this.tx_outs=data.tx_outs}if("signature"in data&&data.signature!=undefined){this.signature=data.signature}if("etx_sender"in data&&data.etx_sender!=undefined){this.etx_sender=data.etx_sender}}}get type(){return pb_1__namespace.Message.getFieldWithDefault(this,1,0)}set type(value){pb_1__namespace.Message.setOneofField(this,1,this.#one_of_decls[0],value)}get has_type(){return pb_1__namespace.Message.getField(this,1)!=null}get to(){return pb_1__namespace.Message.getFieldWithDefault(this,2,new Uint8Array(0))}set to(value){pb_1__namespace.Message.setOneofField(this,2,this.#one_of_decls[1],value)}get has_to(){return pb_1__namespace.Message.getField(this,2)!=null}get nonce(){return pb_1__namespace.Message.getFieldWithDefault(this,3,0)}set nonce(value){pb_1__namespace.Message.setOneofField(this,3,this.#one_of_decls[2],value)}get has_nonce(){return pb_1__namespace.Message.getField(this,3)!=null}get value(){return pb_1__namespace.Message.getFieldWithDefault(this,4,new Uint8Array(0))}set value(value){pb_1__namespace.Message.setOneofField(this,4,this.#one_of_decls[3],value)}get has_value(){return pb_1__namespace.Message.getField(this,4)!=null}get gas(){return pb_1__namespace.Message.getFieldWithDefault(this,5,0)}set gas(value){pb_1__namespace.Message.setOneofField(this,5,this.#one_of_decls[4],value)}get has_gas(){return pb_1__namespace.Message.getField(this,5)!=null}get data(){return pb_1__namespace.Message.getFieldWithDefault(this,6,new Uint8Array(0))}set data(value){pb_1__namespace.Message.setOneofField(this,6,this.#one_of_decls[5],value)}get has_data(){return pb_1__namespace.Message.getField(this,6)!=null}get chain_id(){return pb_1__namespace.Message.getFieldWithDefault(this,7,new Uint8Array(0))}set chain_id(value){pb_1__namespace.Message.setOneofField(this,7,this.#one_of_decls[6],value)}get has_chain_id(){return pb_1__namespace.Message.getField(this,7)!=null}get gas_fee_cap(){return pb_1__namespace.Message.getFieldWithDefault(this,8,new Uint8Array(0))}set gas_fee_cap(value){pb_1__namespace.Message.setOneofField(this,8,this.#one_of_decls[7],value)}get has_gas_fee_cap(){return pb_1__namespace.Message.getField(this,8)!=null}get gas_tip_cap(){return pb_1__namespace.Message.getFieldWithDefault(this,9,new Uint8Array(0))}set gas_tip_cap(value){pb_1__namespace.Message.setOneofField(this,9,this.#one_of_decls[8],value)}get has_gas_tip_cap(){return pb_1__namespace.Message.getField(this,9)!=null}get access_list(){return pb_1__namespace.Message.getWrapperField(this,ProtoAccessList,10)}set access_list(value){pb_1__namespace.Message.setOneofWrapperField(this,10,this.#one_of_decls[9],value)}get has_access_list(){return pb_1__namespace.Message.getField(this,10)!=null}get v(){return pb_1__namespace.Message.getFieldWithDefault(this,11,new Uint8Array(0))}set v(value){pb_1__namespace.Message.setOneofField(this,11,this.#one_of_decls[10],value)}get has_v(){return pb_1__namespace.Message.getField(this,11)!=null}get r(){return pb_1__namespace.Message.getFieldWithDefault(this,12,new Uint8Array(0))}set r(value){pb_1__namespace.Message.setOneofField(this,12,this.#one_of_decls[11],value)}get has_r(){return pb_1__namespace.Message.getField(this,12)!=null}get s(){return pb_1__namespace.Message.getFieldWithDefault(this,13,new Uint8Array(0))}set s(value){pb_1__namespace.Message.setOneofField(this,13,this.#one_of_decls[12],value)}get has_s(){return pb_1__namespace.Message.getField(this,13)!=null}get originating_tx_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,14)}set originating_tx_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,14,this.#one_of_decls[13],value)}get has_originating_tx_hash(){return pb_1__namespace.Message.getField(this,14)!=null}get etx_index(){return pb_1__namespace.Message.getFieldWithDefault(this,15,0)}set etx_index(value){pb_1__namespace.Message.setOneofField(this,15,this.#one_of_decls[14],value)}get has_etx_index(){return pb_1__namespace.Message.getField(this,15)!=null}get tx_ins(){return pb_1__namespace.Message.getWrapperField(this,ProtoTxIns,16)}set tx_ins(value){pb_1__namespace.Message.setOneofWrapperField(this,16,this.#one_of_decls[15],value)}get has_tx_ins(){return pb_1__namespace.Message.getField(this,16)!=null}get tx_outs(){return pb_1__namespace.Message.getWrapperField(this,ProtoTxOuts,17)}set tx_outs(value){pb_1__namespace.Message.setOneofWrapperField(this,17,this.#one_of_decls[16],value)}get has_tx_outs(){return pb_1__namespace.Message.getField(this,17)!=null}get signature(){return pb_1__namespace.Message.getFieldWithDefault(this,18,new Uint8Array(0))}set signature(value){pb_1__namespace.Message.setOneofField(this,18,this.#one_of_decls[17],value)}get has_signature(){return pb_1__namespace.Message.getField(this,18)!=null}get etx_sender(){return pb_1__namespace.Message.getFieldWithDefault(this,19,new Uint8Array(0))}set etx_sender(value){pb_1__namespace.Message.setOneofField(this,19,this.#one_of_decls[18],value)}get has_etx_sender(){return pb_1__namespace.Message.getField(this,19)!=null}get _type(){const cases={0:"none",1:"type"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _to(){const cases={0:"none",2:"to"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}get _nonce(){const cases={0:"none",3:"nonce"};return cases[pb_1__namespace.Message.computeOneofCase(this,[3])]}get _value(){const cases={0:"none",4:"value"};return cases[pb_1__namespace.Message.computeOneofCase(this,[4])]}get _gas(){const cases={0:"none",5:"gas"};return cases[pb_1__namespace.Message.computeOneofCase(this,[5])]}get _data(){const cases={0:"none",6:"data"};return cases[pb_1__namespace.Message.computeOneofCase(this,[6])]}get _chain_id(){const cases={0:"none",7:"chain_id"};return cases[pb_1__namespace.Message.computeOneofCase(this,[7])]}get _gas_fee_cap(){const cases={0:"none",8:"gas_fee_cap"};return cases[pb_1__namespace.Message.computeOneofCase(this,[8])]}get _gas_tip_cap(){const cases={0:"none",9:"gas_tip_cap"};return cases[pb_1__namespace.Message.computeOneofCase(this,[9])]}get _access_list(){const cases={0:"none",10:"access_list"};return cases[pb_1__namespace.Message.computeOneofCase(this,[10])]}get _v(){const cases={0:"none",11:"v"};return cases[pb_1__namespace.Message.computeOneofCase(this,[11])]}get _r(){const cases={0:"none",12:"r"};return cases[pb_1__namespace.Message.computeOneofCase(this,[12])]}get _s(){const cases={0:"none",13:"s"};return cases[pb_1__namespace.Message.computeOneofCase(this,[13])]}get _originating_tx_hash(){const cases={0:"none",14:"originating_tx_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[14])]}get _etx_index(){const cases={0:"none",15:"etx_index"};return cases[pb_1__namespace.Message.computeOneofCase(this,[15])]}get _tx_ins(){const cases={0:"none",16:"tx_ins"};return cases[pb_1__namespace.Message.computeOneofCase(this,[16])]}get _tx_outs(){const cases={0:"none",17:"tx_outs"};return cases[pb_1__namespace.Message.computeOneofCase(this,[17])]}get _signature(){const cases={0:"none",18:"signature"};return cases[pb_1__namespace.Message.computeOneofCase(this,[18])]}get _etx_sender(){const cases={0:"none",19:"etx_sender"};return cases[pb_1__namespace.Message.computeOneofCase(this,[19])]}static fromObject(data){const message=new ProtoTransaction({});if(data.type!=null){message.type=data.type}if(data.to!=null){message.to=data.to}if(data.nonce!=null){message.nonce=data.nonce}if(data.value!=null){message.value=data.value}if(data.gas!=null){message.gas=data.gas}if(data.data!=null){message.data=data.data}if(data.chain_id!=null){message.chain_id=data.chain_id}if(data.gas_fee_cap!=null){message.gas_fee_cap=data.gas_fee_cap}if(data.gas_tip_cap!=null){message.gas_tip_cap=data.gas_tip_cap}if(data.access_list!=null){message.access_list=ProtoAccessList.fromObject(data.access_list)}if(data.v!=null){message.v=data.v}if(data.r!=null){message.r=data.r}if(data.s!=null){message.s=data.s}if(data.originating_tx_hash!=null){message.originating_tx_hash=common.ProtoHash.fromObject(data.originating_tx_hash)}if(data.etx_index!=null){message.etx_index=data.etx_index}if(data.tx_ins!=null){message.tx_ins=ProtoTxIns.fromObject(data.tx_ins)}if(data.tx_outs!=null){message.tx_outs=ProtoTxOuts.fromObject(data.tx_outs)}if(data.signature!=null){message.signature=data.signature}if(data.etx_sender!=null){message.etx_sender=data.etx_sender}return message}toObject(){const data={};if(this.type!=null){data.type=this.type}if(this.to!=null){data.to=this.to}if(this.nonce!=null){data.nonce=this.nonce}if(this.value!=null){data.value=this.value}if(this.gas!=null){data.gas=this.gas}if(this.data!=null){data.data=this.data}if(this.chain_id!=null){data.chain_id=this.chain_id}if(this.gas_fee_cap!=null){data.gas_fee_cap=this.gas_fee_cap}if(this.gas_tip_cap!=null){data.gas_tip_cap=this.gas_tip_cap}if(this.access_list!=null){data.access_list=this.access_list.toObject()}if(this.v!=null){data.v=this.v}if(this.r!=null){data.r=this.r}if(this.s!=null){data.s=this.s}if(this.originating_tx_hash!=null){data.originating_tx_hash=this.originating_tx_hash.toObject()}if(this.etx_index!=null){data.etx_index=this.etx_index}if(this.tx_ins!=null){data.tx_ins=this.tx_ins.toObject()}if(this.tx_outs!=null){data.tx_outs=this.tx_outs.toObject()}if(this.signature!=null){data.signature=this.signature}if(this.etx_sender!=null){data.etx_sender=this.etx_sender}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_type)writer.writeUint64(1,this.type);if(this.has_to)writer.writeBytes(2,this.to);if(this.has_nonce)writer.writeUint64(3,this.nonce);if(this.has_value)writer.writeBytes(4,this.value);if(this.has_gas)writer.writeUint64(5,this.gas);if(this.has_data)writer.writeBytes(6,this.data);if(this.has_chain_id)writer.writeBytes(7,this.chain_id);if(this.has_gas_fee_cap)writer.writeBytes(8,this.gas_fee_cap);if(this.has_gas_tip_cap)writer.writeBytes(9,this.gas_tip_cap);if(this.has_access_list)writer.writeMessage(10,this.access_list,()=>this.access_list.serialize(writer));if(this.has_v)writer.writeBytes(11,this.v);if(this.has_r)writer.writeBytes(12,this.r);if(this.has_s)writer.writeBytes(13,this.s);if(this.has_originating_tx_hash)writer.writeMessage(14,this.originating_tx_hash,()=>this.originating_tx_hash.serialize(writer));if(this.has_etx_index)writer.writeUint32(15,this.etx_index);if(this.has_tx_ins)writer.writeMessage(16,this.tx_ins,()=>this.tx_ins.serialize(writer));if(this.has_tx_outs)writer.writeMessage(17,this.tx_outs,()=>this.tx_outs.serialize(writer));if(this.has_signature)writer.writeBytes(18,this.signature);if(this.has_etx_sender)writer.writeBytes(19,this.etx_sender);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoTransaction;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.type=reader.readUint64();break;case 2:message.to=reader.readBytes();break;case 3:message.nonce=reader.readUint64();break;case 4:message.value=reader.readBytes();break;case 5:message.gas=reader.readUint64();break;case 6:message.data=reader.readBytes();break;case 7:message.chain_id=reader.readBytes();break;case 8:message.gas_fee_cap=reader.readBytes();break;case 9:message.gas_tip_cap=reader.readBytes();break;case 10:reader.readMessage(message.access_list,()=>message.access_list=ProtoAccessList.deserialize(reader));break;case 11:message.v=reader.readBytes();break;case 12:message.r=reader.readBytes();break;case 13:message.s=reader.readBytes();break;case 14:reader.readMessage(message.originating_tx_hash,()=>message.originating_tx_hash=common.ProtoHash.deserialize(reader));break;case 15:message.etx_index=reader.readUint32();break;case 16:reader.readMessage(message.tx_ins,()=>message.tx_ins=ProtoTxIns.deserialize(reader));break;case 17:reader.readMessage(message.tx_outs,()=>message.tx_outs=ProtoTxOuts.deserialize(reader));break;case 18:message.signature=reader.readBytes();break;case 19:message.etx_sender=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTransaction.deserialize(bytes)}}block.ProtoTransaction=ProtoTransaction;class ProtoTransactions extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("transactions"in data&&data.transactions!=undefined){this.transactions=data.transactions}}}get transactions(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoTransaction,1)}set transactions(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoTransactions({});if(data.transactions!=null){message.transactions=data.transactions.map(item=>ProtoTransaction.fromObject(item))}return message}toObject(){const data={};if(this.transactions!=null){data.transactions=this.transactions.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.transactions.length)writer.writeRepeatedMessage(1,this.transactions,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoTransactions;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.transactions,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoTransaction.deserialize(reader),ProtoTransaction));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTransactions.deserialize(bytes)}}block.ProtoTransactions=ProtoTransactions;class ProtoHeaders extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("headers"in data&&data.headers!=undefined){this.headers=data.headers}}}get headers(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoHeader,1)}set headers(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoHeaders({});if(data.headers!=null){message.headers=data.headers.map(item=>ProtoHeader.fromObject(item))}return message}toObject(){const data={};if(this.headers!=null){data.headers=this.headers.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.headers.length)writer.writeRepeatedMessage(1,this.headers,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoHeaders;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.headers,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoHeader.deserialize(reader),ProtoHeader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoHeaders.deserialize(bytes)}}block.ProtoHeaders=ProtoHeaders;class ProtoManifest extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("manifest"in data&&data.manifest!=undefined){this.manifest=data.manifest}}}get manifest(){return pb_1__namespace.Message.getRepeatedWrapperField(this,common.ProtoHash,1)}set manifest(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoManifest({});if(data.manifest!=null){message.manifest=data.manifest.map(item=>common.ProtoHash.fromObject(item))}return message}toObject(){const data={};if(this.manifest!=null){data.manifest=this.manifest.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.manifest.length)writer.writeRepeatedMessage(1,this.manifest,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoManifest;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.manifest,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,common.ProtoHash.deserialize(reader),common.ProtoHash));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoManifest.deserialize(bytes)}}block.ProtoManifest=ProtoManifest;class ProtoAccessList extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("access_tuples"in data&&data.access_tuples!=undefined){this.access_tuples=data.access_tuples}}}get access_tuples(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoAccessTuple,1)}set access_tuples(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoAccessList({});if(data.access_tuples!=null){message.access_tuples=data.access_tuples.map(item=>ProtoAccessTuple.fromObject(item))}return message}toObject(){const data={};if(this.access_tuples!=null){data.access_tuples=this.access_tuples.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.access_tuples.length)writer.writeRepeatedMessage(1,this.access_tuples,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoAccessList;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.access_tuples,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoAccessTuple.deserialize(reader),ProtoAccessTuple));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoAccessList.deserialize(bytes)}}block.ProtoAccessList=ProtoAccessList;class ProtoWorkObjectHeader extends pb_1__namespace.Message{#one_of_decls=[[1],[2],[3],[4],[5],[6],[7],[8],[9]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("header_hash"in data&&data.header_hash!=undefined){this.header_hash=data.header_hash}if("parent_hash"in data&&data.parent_hash!=undefined){this.parent_hash=data.parent_hash}if("number"in data&&data.number!=undefined){this.number=data.number}if("difficulty"in data&&data.difficulty!=undefined){this.difficulty=data.difficulty}if("tx_hash"in data&&data.tx_hash!=undefined){this.tx_hash=data.tx_hash}if("nonce"in data&&data.nonce!=undefined){this.nonce=data.nonce}if("location"in data&&data.location!=undefined){this.location=data.location}if("mix_hash"in data&&data.mix_hash!=undefined){this.mix_hash=data.mix_hash}if("time"in data&&data.time!=undefined){this.time=data.time}}}get header_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,1)}set header_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_header_hash(){return pb_1__namespace.Message.getField(this,1)!=null}get parent_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,2)}set parent_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_parent_hash(){return pb_1__namespace.Message.getField(this,2)!=null}get number(){return pb_1__namespace.Message.getFieldWithDefault(this,3,new Uint8Array(0))}set number(value){pb_1__namespace.Message.setOneofField(this,3,this.#one_of_decls[2],value)}get has_number(){return pb_1__namespace.Message.getField(this,3)!=null}get difficulty(){return pb_1__namespace.Message.getFieldWithDefault(this,4,new Uint8Array(0))}set difficulty(value){pb_1__namespace.Message.setOneofField(this,4,this.#one_of_decls[3],value)}get has_difficulty(){return pb_1__namespace.Message.getField(this,4)!=null}get tx_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,5)}set tx_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,5,this.#one_of_decls[4],value)}get has_tx_hash(){return pb_1__namespace.Message.getField(this,5)!=null}get nonce(){return pb_1__namespace.Message.getFieldWithDefault(this,6,0)}set nonce(value){pb_1__namespace.Message.setOneofField(this,6,this.#one_of_decls[5],value)}get has_nonce(){return pb_1__namespace.Message.getField(this,6)!=null}get location(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoLocation,7)}set location(value){pb_1__namespace.Message.setOneofWrapperField(this,7,this.#one_of_decls[6],value)}get has_location(){return pb_1__namespace.Message.getField(this,7)!=null}get mix_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,8)}set mix_hash(value){pb_1__namespace.Message.setOneofWrapperField(this,8,this.#one_of_decls[7],value)}get has_mix_hash(){return pb_1__namespace.Message.getField(this,8)!=null}get time(){return pb_1__namespace.Message.getFieldWithDefault(this,9,0)}set time(value){pb_1__namespace.Message.setOneofField(this,9,this.#one_of_decls[8],value)}get has_time(){return pb_1__namespace.Message.getField(this,9)!=null}get _header_hash(){const cases={0:"none",1:"header_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _parent_hash(){const cases={0:"none",2:"parent_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}get _number(){const cases={0:"none",3:"number"};return cases[pb_1__namespace.Message.computeOneofCase(this,[3])]}get _difficulty(){const cases={0:"none",4:"difficulty"};return cases[pb_1__namespace.Message.computeOneofCase(this,[4])]}get _tx_hash(){const cases={0:"none",5:"tx_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[5])]}get _nonce(){const cases={0:"none",6:"nonce"};return cases[pb_1__namespace.Message.computeOneofCase(this,[6])]}get _location(){const cases={0:"none",7:"location"};return cases[pb_1__namespace.Message.computeOneofCase(this,[7])]}get _mix_hash(){const cases={0:"none",8:"mix_hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[8])]}get _time(){const cases={0:"none",9:"time"};return cases[pb_1__namespace.Message.computeOneofCase(this,[9])]}static fromObject(data){const message=new ProtoWorkObjectHeader({});if(data.header_hash!=null){message.header_hash=common.ProtoHash.fromObject(data.header_hash)}if(data.parent_hash!=null){message.parent_hash=common.ProtoHash.fromObject(data.parent_hash)}if(data.number!=null){message.number=data.number}if(data.difficulty!=null){message.difficulty=data.difficulty}if(data.tx_hash!=null){message.tx_hash=common.ProtoHash.fromObject(data.tx_hash)}if(data.nonce!=null){message.nonce=data.nonce}if(data.location!=null){message.location=common.ProtoLocation.fromObject(data.location)}if(data.mix_hash!=null){message.mix_hash=common.ProtoHash.fromObject(data.mix_hash)}if(data.time!=null){message.time=data.time}return message}toObject(){const data={};if(this.header_hash!=null){data.header_hash=this.header_hash.toObject()}if(this.parent_hash!=null){data.parent_hash=this.parent_hash.toObject()}if(this.number!=null){data.number=this.number}if(this.difficulty!=null){data.difficulty=this.difficulty}if(this.tx_hash!=null){data.tx_hash=this.tx_hash.toObject()}if(this.nonce!=null){data.nonce=this.nonce}if(this.location!=null){data.location=this.location.toObject()}if(this.mix_hash!=null){data.mix_hash=this.mix_hash.toObject()}if(this.time!=null){data.time=this.time}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_header_hash)writer.writeMessage(1,this.header_hash,()=>this.header_hash.serialize(writer));if(this.has_parent_hash)writer.writeMessage(2,this.parent_hash,()=>this.parent_hash.serialize(writer));if(this.has_number)writer.writeBytes(3,this.number);if(this.has_difficulty)writer.writeBytes(4,this.difficulty);if(this.has_tx_hash)writer.writeMessage(5,this.tx_hash,()=>this.tx_hash.serialize(writer));if(this.has_nonce)writer.writeUint64(6,this.nonce);if(this.has_location)writer.writeMessage(7,this.location,()=>this.location.serialize(writer));if(this.has_mix_hash)writer.writeMessage(8,this.mix_hash,()=>this.mix_hash.serialize(writer));if(this.has_time)writer.writeUint64(9,this.time);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoWorkObjectHeader;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.header_hash,()=>message.header_hash=common.ProtoHash.deserialize(reader));break;case 2:reader.readMessage(message.parent_hash,()=>message.parent_hash=common.ProtoHash.deserialize(reader));break;case 3:message.number=reader.readBytes();break;case 4:message.difficulty=reader.readBytes();break;case 5:reader.readMessage(message.tx_hash,()=>message.tx_hash=common.ProtoHash.deserialize(reader));break;case 6:message.nonce=reader.readUint64();break;case 7:reader.readMessage(message.location,()=>message.location=common.ProtoLocation.deserialize(reader));break;case 8:reader.readMessage(message.mix_hash,()=>message.mix_hash=common.ProtoHash.deserialize(reader));break;case 9:message.time=reader.readUint64();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObjectHeader.deserialize(bytes)}}block.ProtoWorkObjectHeader=ProtoWorkObjectHeader;class ProtoWorkObjectHeaders extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("wo_headers"in data&&data.wo_headers!=undefined){this.wo_headers=data.wo_headers}}}get wo_headers(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoWorkObjectHeader,1)}set wo_headers(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoWorkObjectHeaders({});if(data.wo_headers!=null){message.wo_headers=data.wo_headers.map(item=>ProtoWorkObjectHeader.fromObject(item))}return message}toObject(){const data={};if(this.wo_headers!=null){data.wo_headers=this.wo_headers.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.wo_headers.length)writer.writeRepeatedMessage(1,this.wo_headers,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoWorkObjectHeaders;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.wo_headers,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoWorkObjectHeader.deserialize(reader),ProtoWorkObjectHeader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObjectHeaders.deserialize(bytes)}}block.ProtoWorkObjectHeaders=ProtoWorkObjectHeaders;class ProtoWorkObjectBody extends pb_1__namespace.Message{#one_of_decls=[[1],[2],[3],[4],[5],[6]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("header"in data&&data.header!=undefined){this.header=data.header}if("transactions"in data&&data.transactions!=undefined){this.transactions=data.transactions}if("uncles"in data&&data.uncles!=undefined){this.uncles=data.uncles}if("ext_transactions"in data&&data.ext_transactions!=undefined){this.ext_transactions=data.ext_transactions}if("manifest"in data&&data.manifest!=undefined){this.manifest=data.manifest}if("interlink_hashes"in data&&data.interlink_hashes!=undefined){this.interlink_hashes=data.interlink_hashes}}}get header(){return pb_1__namespace.Message.getWrapperField(this,ProtoHeader,1)}set header(value){pb_1__namespace.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_header(){return pb_1__namespace.Message.getField(this,1)!=null}get transactions(){return pb_1__namespace.Message.getWrapperField(this,ProtoTransactions,2)}set transactions(value){pb_1__namespace.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_transactions(){return pb_1__namespace.Message.getField(this,2)!=null}get uncles(){return pb_1__namespace.Message.getWrapperField(this,ProtoWorkObjectHeaders,3)}set uncles(value){pb_1__namespace.Message.setOneofWrapperField(this,3,this.#one_of_decls[2],value)}get has_uncles(){return pb_1__namespace.Message.getField(this,3)!=null}get ext_transactions(){return pb_1__namespace.Message.getWrapperField(this,ProtoTransactions,4)}set ext_transactions(value){pb_1__namespace.Message.setOneofWrapperField(this,4,this.#one_of_decls[3],value)}get has_ext_transactions(){return pb_1__namespace.Message.getField(this,4)!=null}get manifest(){return pb_1__namespace.Message.getWrapperField(this,ProtoManifest,5)}set manifest(value){pb_1__namespace.Message.setOneofWrapperField(this,5,this.#one_of_decls[4],value)}get has_manifest(){return pb_1__namespace.Message.getField(this,5)!=null}get interlink_hashes(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHashes,6)}set interlink_hashes(value){pb_1__namespace.Message.setOneofWrapperField(this,6,this.#one_of_decls[5],value)}get has_interlink_hashes(){return pb_1__namespace.Message.getField(this,6)!=null}get _header(){const cases={0:"none",1:"header"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _transactions(){const cases={0:"none",2:"transactions"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}get _uncles(){const cases={0:"none",3:"uncles"};return cases[pb_1__namespace.Message.computeOneofCase(this,[3])]}get _ext_transactions(){const cases={0:"none",4:"ext_transactions"};return cases[pb_1__namespace.Message.computeOneofCase(this,[4])]}get _manifest(){const cases={0:"none",5:"manifest"};return cases[pb_1__namespace.Message.computeOneofCase(this,[5])]}get _interlink_hashes(){const cases={0:"none",6:"interlink_hashes"};return cases[pb_1__namespace.Message.computeOneofCase(this,[6])]}static fromObject(data){const message=new ProtoWorkObjectBody({});if(data.header!=null){message.header=ProtoHeader.fromObject(data.header)}if(data.transactions!=null){message.transactions=ProtoTransactions.fromObject(data.transactions)}if(data.uncles!=null){message.uncles=ProtoWorkObjectHeaders.fromObject(data.uncles)}if(data.ext_transactions!=null){message.ext_transactions=ProtoTransactions.fromObject(data.ext_transactions)}if(data.manifest!=null){message.manifest=ProtoManifest.fromObject(data.manifest)}if(data.interlink_hashes!=null){message.interlink_hashes=common.ProtoHashes.fromObject(data.interlink_hashes)}return message}toObject(){const data={};if(this.header!=null){data.header=this.header.toObject()}if(this.transactions!=null){data.transactions=this.transactions.toObject()}if(this.uncles!=null){data.uncles=this.uncles.toObject()}if(this.ext_transactions!=null){data.ext_transactions=this.ext_transactions.toObject()}if(this.manifest!=null){data.manifest=this.manifest.toObject()}if(this.interlink_hashes!=null){data.interlink_hashes=this.interlink_hashes.toObject()}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_header)writer.writeMessage(1,this.header,()=>this.header.serialize(writer));if(this.has_transactions)writer.writeMessage(2,this.transactions,()=>this.transactions.serialize(writer));if(this.has_uncles)writer.writeMessage(3,this.uncles,()=>this.uncles.serialize(writer));if(this.has_ext_transactions)writer.writeMessage(4,this.ext_transactions,()=>this.ext_transactions.serialize(writer));if(this.has_manifest)writer.writeMessage(5,this.manifest,()=>this.manifest.serialize(writer));if(this.has_interlink_hashes)writer.writeMessage(6,this.interlink_hashes,()=>this.interlink_hashes.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoWorkObjectBody;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.header,()=>message.header=ProtoHeader.deserialize(reader));break;case 2:reader.readMessage(message.transactions,()=>message.transactions=ProtoTransactions.deserialize(reader));break;case 3:reader.readMessage(message.uncles,()=>message.uncles=ProtoWorkObjectHeaders.deserialize(reader));break;case 4:reader.readMessage(message.ext_transactions,()=>message.ext_transactions=ProtoTransactions.deserialize(reader));break;case 5:reader.readMessage(message.manifest,()=>message.manifest=ProtoManifest.deserialize(reader));break;case 6:reader.readMessage(message.interlink_hashes,()=>message.interlink_hashes=common.ProtoHashes.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObjectBody.deserialize(bytes)}}block.ProtoWorkObjectBody=ProtoWorkObjectBody;class ProtoWorkObject extends pb_1__namespace.Message{#one_of_decls=[[1],[2],[3]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("wo_header"in data&&data.wo_header!=undefined){this.wo_header=data.wo_header}if("wo_body"in data&&data.wo_body!=undefined){this.wo_body=data.wo_body}if("tx"in data&&data.tx!=undefined){this.tx=data.tx}}}get wo_header(){return pb_1__namespace.Message.getWrapperField(this,ProtoWorkObjectHeader,1)}set wo_header(value){pb_1__namespace.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_wo_header(){return pb_1__namespace.Message.getField(this,1)!=null}get wo_body(){return pb_1__namespace.Message.getWrapperField(this,ProtoWorkObjectBody,2)}set wo_body(value){pb_1__namespace.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_wo_body(){return pb_1__namespace.Message.getField(this,2)!=null}get tx(){return pb_1__namespace.Message.getWrapperField(this,ProtoTransaction,3)}set tx(value){pb_1__namespace.Message.setOneofWrapperField(this,3,this.#one_of_decls[2],value)}get has_tx(){return pb_1__namespace.Message.getField(this,3)!=null}get _wo_header(){const cases={0:"none",1:"wo_header"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _wo_body(){const cases={0:"none",2:"wo_body"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}get _tx(){const cases={0:"none",3:"tx"};return cases[pb_1__namespace.Message.computeOneofCase(this,[3])]}static fromObject(data){const message=new ProtoWorkObject({});if(data.wo_header!=null){message.wo_header=ProtoWorkObjectHeader.fromObject(data.wo_header)}if(data.wo_body!=null){message.wo_body=ProtoWorkObjectBody.fromObject(data.wo_body)}if(data.tx!=null){message.tx=ProtoTransaction.fromObject(data.tx)}return message}toObject(){const data={};if(this.wo_header!=null){data.wo_header=this.wo_header.toObject()}if(this.wo_body!=null){data.wo_body=this.wo_body.toObject()}if(this.tx!=null){data.tx=this.tx.toObject()}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_wo_header)writer.writeMessage(1,this.wo_header,()=>this.wo_header.serialize(writer));if(this.has_wo_body)writer.writeMessage(2,this.wo_body,()=>this.wo_body.serialize(writer));if(this.has_tx)writer.writeMessage(3,this.tx,()=>this.tx.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoWorkObject;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.wo_header,()=>message.wo_header=ProtoWorkObjectHeader.deserialize(reader));break;case 2:reader.readMessage(message.wo_body,()=>message.wo_body=ProtoWorkObjectBody.deserialize(reader));break;case 3:reader.readMessage(message.tx,()=>message.tx=ProtoTransaction.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObject.deserialize(bytes)}}block.ProtoWorkObject=ProtoWorkObject;class ProtoWorkObjects extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("work_objects"in data&&data.work_objects!=undefined){this.work_objects=data.work_objects}}}get work_objects(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoWorkObject,1)}set work_objects(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoWorkObjects({});if(data.work_objects!=null){message.work_objects=data.work_objects.map(item=>ProtoWorkObject.fromObject(item))}return message}toObject(){const data={};if(this.work_objects!=null){data.work_objects=this.work_objects.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.work_objects.length)writer.writeRepeatedMessage(1,this.work_objects,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoWorkObjects;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.work_objects,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoWorkObject.deserialize(reader),ProtoWorkObject));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoWorkObjects.deserialize(bytes)}}block.ProtoWorkObjects=ProtoWorkObjects;class ProtoAccessTuple extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[2],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("address"in data&&data.address!=undefined){this.address=data.address}if("storage_key"in data&&data.storage_key!=undefined){this.storage_key=data.storage_key}}}get address(){return pb_1__namespace.Message.getFieldWithDefault(this,1,new Uint8Array(0))}set address(value){pb_1__namespace.Message.setField(this,1,value)}get storage_key(){return pb_1__namespace.Message.getRepeatedWrapperField(this,common.ProtoHash,2)}set storage_key(value){pb_1__namespace.Message.setRepeatedWrapperField(this,2,value)}static fromObject(data){const message=new ProtoAccessTuple({});if(data.address!=null){message.address=data.address}if(data.storage_key!=null){message.storage_key=data.storage_key.map(item=>common.ProtoHash.fromObject(item))}return message}toObject(){const data={};if(this.address!=null){data.address=this.address}if(this.storage_key!=null){data.storage_key=this.storage_key.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.address.length)writer.writeBytes(1,this.address);if(this.storage_key.length)writer.writeRepeatedMessage(2,this.storage_key,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoAccessTuple;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.address=reader.readBytes();break;case 2:reader.readMessage(message.storage_key,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,2,common.ProtoHash.deserialize(reader),common.ProtoHash));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoAccessTuple.deserialize(bytes)}}block.ProtoAccessTuple=ProtoAccessTuple;class ProtoReceiptForStorage extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("post_state_or_status"in data&&data.post_state_or_status!=undefined){this.post_state_or_status=data.post_state_or_status}if("cumulative_gas_used"in data&&data.cumulative_gas_used!=undefined){this.cumulative_gas_used=data.cumulative_gas_used}if("tx_hash"in data&&data.tx_hash!=undefined){this.tx_hash=data.tx_hash}if("contract_address"in data&&data.contract_address!=undefined){this.contract_address=data.contract_address}if("logs"in data&&data.logs!=undefined){this.logs=data.logs}if("etxs"in data&&data.etxs!=undefined){this.etxs=data.etxs}if("gas_used"in data&&data.gas_used!=undefined){this.gas_used=data.gas_used}}}get post_state_or_status(){return pb_1__namespace.Message.getFieldWithDefault(this,1,new Uint8Array(0))}set post_state_or_status(value){pb_1__namespace.Message.setField(this,1,value)}get cumulative_gas_used(){return pb_1__namespace.Message.getFieldWithDefault(this,2,0)}set cumulative_gas_used(value){pb_1__namespace.Message.setField(this,2,value)}get tx_hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,3)}set tx_hash(value){pb_1__namespace.Message.setWrapperField(this,3,value)}get has_tx_hash(){return pb_1__namespace.Message.getField(this,3)!=null}get contract_address(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoAddress,4)}set contract_address(value){pb_1__namespace.Message.setWrapperField(this,4,value)}get has_contract_address(){return pb_1__namespace.Message.getField(this,4)!=null}get logs(){return pb_1__namespace.Message.getWrapperField(this,ProtoLogsForStorage,5)}set logs(value){pb_1__namespace.Message.setWrapperField(this,5,value)}get has_logs(){return pb_1__namespace.Message.getField(this,5)!=null}get etxs(){return pb_1__namespace.Message.getWrapperField(this,ProtoTransactions,6)}set etxs(value){pb_1__namespace.Message.setWrapperField(this,6,value)}get has_etxs(){return pb_1__namespace.Message.getField(this,6)!=null}get gas_used(){return pb_1__namespace.Message.getFieldWithDefault(this,7,0)}set gas_used(value){pb_1__namespace.Message.setField(this,7,value)}static fromObject(data){const message=new ProtoReceiptForStorage({});if(data.post_state_or_status!=null){message.post_state_or_status=data.post_state_or_status}if(data.cumulative_gas_used!=null){message.cumulative_gas_used=data.cumulative_gas_used}if(data.tx_hash!=null){message.tx_hash=common.ProtoHash.fromObject(data.tx_hash)}if(data.contract_address!=null){message.contract_address=common.ProtoAddress.fromObject(data.contract_address)}if(data.logs!=null){message.logs=ProtoLogsForStorage.fromObject(data.logs)}if(data.etxs!=null){message.etxs=ProtoTransactions.fromObject(data.etxs)}if(data.gas_used!=null){message.gas_used=data.gas_used}return message}toObject(){const data={};if(this.post_state_or_status!=null){data.post_state_or_status=this.post_state_or_status}if(this.cumulative_gas_used!=null){data.cumulative_gas_used=this.cumulative_gas_used}if(this.tx_hash!=null){data.tx_hash=this.tx_hash.toObject()}if(this.contract_address!=null){data.contract_address=this.contract_address.toObject()}if(this.logs!=null){data.logs=this.logs.toObject()}if(this.etxs!=null){data.etxs=this.etxs.toObject()}if(this.gas_used!=null){data.gas_used=this.gas_used}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.post_state_or_status.length)writer.writeBytes(1,this.post_state_or_status);if(this.cumulative_gas_used!=0)writer.writeUint64(2,this.cumulative_gas_used);if(this.has_tx_hash)writer.writeMessage(3,this.tx_hash,()=>this.tx_hash.serialize(writer));if(this.has_contract_address)writer.writeMessage(4,this.contract_address,()=>this.contract_address.serialize(writer));if(this.has_logs)writer.writeMessage(5,this.logs,()=>this.logs.serialize(writer));if(this.has_etxs)writer.writeMessage(6,this.etxs,()=>this.etxs.serialize(writer));if(this.gas_used!=0)writer.writeUint64(7,this.gas_used);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoReceiptForStorage;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.post_state_or_status=reader.readBytes();break;case 2:message.cumulative_gas_used=reader.readUint64();break;case 3:reader.readMessage(message.tx_hash,()=>message.tx_hash=common.ProtoHash.deserialize(reader));break;case 4:reader.readMessage(message.contract_address,()=>message.contract_address=common.ProtoAddress.deserialize(reader));break;case 5:reader.readMessage(message.logs,()=>message.logs=ProtoLogsForStorage.deserialize(reader));break;case 6:reader.readMessage(message.etxs,()=>message.etxs=ProtoTransactions.deserialize(reader));break;case 7:message.gas_used=reader.readUint64();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoReceiptForStorage.deserialize(bytes)}}block.ProtoReceiptForStorage=ProtoReceiptForStorage;class ProtoReceiptsForStorage extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("receipts"in data&&data.receipts!=undefined){this.receipts=data.receipts}}}get receipts(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoReceiptForStorage,1)}set receipts(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoReceiptsForStorage({});if(data.receipts!=null){message.receipts=data.receipts.map(item=>ProtoReceiptForStorage.fromObject(item))}return message}toObject(){const data={};if(this.receipts!=null){data.receipts=this.receipts.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.receipts.length)writer.writeRepeatedMessage(1,this.receipts,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoReceiptsForStorage;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.receipts,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoReceiptForStorage.deserialize(reader),ProtoReceiptForStorage));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoReceiptsForStorage.deserialize(bytes)}}block.ProtoReceiptsForStorage=ProtoReceiptsForStorage;class ProtoLogForStorage extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[2],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("address"in data&&data.address!=undefined){this.address=data.address}if("topics"in data&&data.topics!=undefined){this.topics=data.topics}if("data"in data&&data.data!=undefined){this.data=data.data}}}get address(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoAddress,1)}set address(value){pb_1__namespace.Message.setWrapperField(this,1,value)}get has_address(){return pb_1__namespace.Message.getField(this,1)!=null}get topics(){return pb_1__namespace.Message.getRepeatedWrapperField(this,common.ProtoHash,2)}set topics(value){pb_1__namespace.Message.setRepeatedWrapperField(this,2,value)}get data(){return pb_1__namespace.Message.getFieldWithDefault(this,3,new Uint8Array(0))}set data(value){pb_1__namespace.Message.setField(this,3,value)}static fromObject(data){const message=new ProtoLogForStorage({});if(data.address!=null){message.address=common.ProtoAddress.fromObject(data.address)}if(data.topics!=null){message.topics=data.topics.map(item=>common.ProtoHash.fromObject(item))}if(data.data!=null){message.data=data.data}return message}toObject(){const data={};if(this.address!=null){data.address=this.address.toObject()}if(this.topics!=null){data.topics=this.topics.map(item=>item.toObject())}if(this.data!=null){data.data=this.data}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_address)writer.writeMessage(1,this.address,()=>this.address.serialize(writer));if(this.topics.length)writer.writeRepeatedMessage(2,this.topics,item=>item.serialize(writer));if(this.data.length)writer.writeBytes(3,this.data);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoLogForStorage;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.address,()=>message.address=common.ProtoAddress.deserialize(reader));break;case 2:reader.readMessage(message.topics,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,2,common.ProtoHash.deserialize(reader),common.ProtoHash));break;case 3:message.data=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoLogForStorage.deserialize(bytes)}}block.ProtoLogForStorage=ProtoLogForStorage;class ProtoLogsForStorage extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("logs"in data&&data.logs!=undefined){this.logs=data.logs}}}get logs(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoLogForStorage,1)}set logs(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoLogsForStorage({});if(data.logs!=null){message.logs=data.logs.map(item=>ProtoLogForStorage.fromObject(item))}return message}toObject(){const data={};if(this.logs!=null){data.logs=this.logs.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.logs.length)writer.writeRepeatedMessage(1,this.logs,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoLogsForStorage;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.logs,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoLogForStorage.deserialize(reader),ProtoLogForStorage));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoLogsForStorage.deserialize(bytes)}}block.ProtoLogsForStorage=ProtoLogsForStorage;class ProtoPendingHeader extends pb_1__namespace.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("wo"in data&&data.wo!=undefined){this.wo=data.wo}if("termini"in data&&data.termini!=undefined){this.termini=data.termini}}}get wo(){return pb_1__namespace.Message.getWrapperField(this,ProtoWorkObject,1)}set wo(value){pb_1__namespace.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_wo(){return pb_1__namespace.Message.getField(this,1)!=null}get termini(){return pb_1__namespace.Message.getWrapperField(this,ProtoTermini,2)}set termini(value){pb_1__namespace.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_termini(){return pb_1__namespace.Message.getField(this,2)!=null}get _wo(){const cases={0:"none",1:"wo"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _termini(){const cases={0:"none",2:"termini"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoPendingHeader({});if(data.wo!=null){message.wo=ProtoWorkObject.fromObject(data.wo)}if(data.termini!=null){message.termini=ProtoTermini.fromObject(data.termini)}return message}toObject(){const data={};if(this.wo!=null){data.wo=this.wo.toObject()}if(this.termini!=null){data.termini=this.termini.toObject()}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_wo)writer.writeMessage(1,this.wo,()=>this.wo.serialize(writer));if(this.has_termini)writer.writeMessage(2,this.termini,()=>this.termini.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoPendingHeader;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.wo,()=>message.wo=ProtoWorkObject.deserialize(reader));break;case 2:reader.readMessage(message.termini,()=>message.termini=ProtoTermini.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoPendingHeader.deserialize(bytes)}}block.ProtoPendingHeader=ProtoPendingHeader;class ProtoTermini extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1,2],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("dom_termini"in data&&data.dom_termini!=undefined){this.dom_termini=data.dom_termini}if("sub_termini"in data&&data.sub_termini!=undefined){this.sub_termini=data.sub_termini}}}get dom_termini(){return pb_1__namespace.Message.getRepeatedWrapperField(this,common.ProtoHash,1)}set dom_termini(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}get sub_termini(){return pb_1__namespace.Message.getRepeatedWrapperField(this,common.ProtoHash,2)}set sub_termini(value){pb_1__namespace.Message.setRepeatedWrapperField(this,2,value)}static fromObject(data){const message=new ProtoTermini({});if(data.dom_termini!=null){message.dom_termini=data.dom_termini.map(item=>common.ProtoHash.fromObject(item))}if(data.sub_termini!=null){message.sub_termini=data.sub_termini.map(item=>common.ProtoHash.fromObject(item))}return message}toObject(){const data={};if(this.dom_termini!=null){data.dom_termini=this.dom_termini.map(item=>item.toObject())}if(this.sub_termini!=null){data.sub_termini=this.sub_termini.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.dom_termini.length)writer.writeRepeatedMessage(1,this.dom_termini,item=>item.serialize(writer));if(this.sub_termini.length)writer.writeRepeatedMessage(2,this.sub_termini,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoTermini;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.dom_termini,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,common.ProtoHash.deserialize(reader),common.ProtoHash));break;case 2:reader.readMessage(message.sub_termini,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,2,common.ProtoHash.deserialize(reader),common.ProtoHash));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTermini.deserialize(bytes)}}block.ProtoTermini=ProtoTermini;class ProtoEtxSet extends pb_1__namespace.Message{#one_of_decls=[[1]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("etx_hashes"in data&&data.etx_hashes!=undefined){this.etx_hashes=data.etx_hashes}}}get etx_hashes(){return pb_1__namespace.Message.getFieldWithDefault(this,1,new Uint8Array(0))}set etx_hashes(value){pb_1__namespace.Message.setOneofField(this,1,this.#one_of_decls[0],value)}get has_etx_hashes(){return pb_1__namespace.Message.getField(this,1)!=null}get _etx_hashes(){const cases={0:"none",1:"etx_hashes"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}static fromObject(data){const message=new ProtoEtxSet({});if(data.etx_hashes!=null){message.etx_hashes=data.etx_hashes}return message}toObject(){const data={};if(this.etx_hashes!=null){data.etx_hashes=this.etx_hashes}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_etx_hashes)writer.writeBytes(1,this.etx_hashes);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoEtxSet;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.etx_hashes=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoEtxSet.deserialize(bytes)}}block.ProtoEtxSet=ProtoEtxSet;class ProtoPendingEtxs extends pb_1__namespace.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("header"in data&&data.header!=undefined){this.header=data.header}if("etxs"in data&&data.etxs!=undefined){this.etxs=data.etxs}}}get header(){return pb_1__namespace.Message.getWrapperField(this,ProtoWorkObject,1)}set header(value){pb_1__namespace.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_header(){return pb_1__namespace.Message.getField(this,1)!=null}get etxs(){return pb_1__namespace.Message.getWrapperField(this,ProtoTransactions,2)}set etxs(value){pb_1__namespace.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_etxs(){return pb_1__namespace.Message.getField(this,2)!=null}get _header(){const cases={0:"none",1:"header"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _etxs(){const cases={0:"none",2:"etxs"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoPendingEtxs({});if(data.header!=null){message.header=ProtoWorkObject.fromObject(data.header)}if(data.etxs!=null){message.etxs=ProtoTransactions.fromObject(data.etxs)}return message}toObject(){const data={};if(this.header!=null){data.header=this.header.toObject()}if(this.etxs!=null){data.etxs=this.etxs.toObject()}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_header)writer.writeMessage(1,this.header,()=>this.header.serialize(writer));if(this.has_etxs)writer.writeMessage(2,this.etxs,()=>this.etxs.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoPendingEtxs;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.header,()=>message.header=ProtoWorkObject.deserialize(reader));break;case 2:reader.readMessage(message.etxs,()=>message.etxs=ProtoTransactions.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoPendingEtxs.deserialize(bytes)}}block.ProtoPendingEtxs=ProtoPendingEtxs;class ProtoPendingEtxsRollup extends pb_1__namespace.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("header"in data&&data.header!=undefined){this.header=data.header}if("etxs_rollup"in data&&data.etxs_rollup!=undefined){this.etxs_rollup=data.etxs_rollup}}}get header(){return pb_1__namespace.Message.getWrapperField(this,ProtoWorkObject,1)}set header(value){pb_1__namespace.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_header(){return pb_1__namespace.Message.getField(this,1)!=null}get etxs_rollup(){return pb_1__namespace.Message.getWrapperField(this,ProtoTransactions,2)}set etxs_rollup(value){pb_1__namespace.Message.setOneofWrapperField(this,2,this.#one_of_decls[1],value)}get has_etxs_rollup(){return pb_1__namespace.Message.getField(this,2)!=null}get _header(){const cases={0:"none",1:"header"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _etxs_rollup(){const cases={0:"none",2:"etxs_rollup"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoPendingEtxsRollup({});if(data.header!=null){message.header=ProtoWorkObject.fromObject(data.header)}if(data.etxs_rollup!=null){message.etxs_rollup=ProtoTransactions.fromObject(data.etxs_rollup)}return message}toObject(){const data={};if(this.header!=null){data.header=this.header.toObject()}if(this.etxs_rollup!=null){data.etxs_rollup=this.etxs_rollup.toObject()}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_header)writer.writeMessage(1,this.header,()=>this.header.serialize(writer));if(this.has_etxs_rollup)writer.writeMessage(2,this.etxs_rollup,()=>this.etxs_rollup.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoPendingEtxsRollup;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.header,()=>message.header=ProtoWorkObject.deserialize(reader));break;case 2:reader.readMessage(message.etxs_rollup,()=>message.etxs_rollup=ProtoTransactions.deserialize(reader));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoPendingEtxsRollup.deserialize(bytes)}}block.ProtoPendingEtxsRollup=ProtoPendingEtxsRollup;class ProtoTxIns extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("tx_ins"in data&&data.tx_ins!=undefined){this.tx_ins=data.tx_ins}}}get tx_ins(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoTxIn,1)}set tx_ins(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoTxIns({});if(data.tx_ins!=null){message.tx_ins=data.tx_ins.map(item=>ProtoTxIn.fromObject(item))}return message}toObject(){const data={};if(this.tx_ins!=null){data.tx_ins=this.tx_ins.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.tx_ins.length)writer.writeRepeatedMessage(1,this.tx_ins,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoTxIns;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.tx_ins,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoTxIn.deserialize(reader),ProtoTxIn));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTxIns.deserialize(bytes)}}block.ProtoTxIns=ProtoTxIns;class ProtoTxOuts extends pb_1__namespace.Message{#one_of_decls=[];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[1],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("tx_outs"in data&&data.tx_outs!=undefined){this.tx_outs=data.tx_outs}}}get tx_outs(){return pb_1__namespace.Message.getRepeatedWrapperField(this,ProtoTxOut,1)}set tx_outs(value){pb_1__namespace.Message.setRepeatedWrapperField(this,1,value)}static fromObject(data){const message=new ProtoTxOuts({});if(data.tx_outs!=null){message.tx_outs=data.tx_outs.map(item=>ProtoTxOut.fromObject(item))}return message}toObject(){const data={};if(this.tx_outs!=null){data.tx_outs=this.tx_outs.map(item=>item.toObject())}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.tx_outs.length)writer.writeRepeatedMessage(1,this.tx_outs,item=>item.serialize(writer));if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoTxOuts;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.tx_outs,()=>pb_1__namespace.Message.addToRepeatedWrapperField(message,1,ProtoTxOut.deserialize(reader),ProtoTxOut));break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTxOuts.deserialize(bytes)}}block.ProtoTxOuts=ProtoTxOuts;class ProtoTxIn extends pb_1__namespace.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("previous_out_point"in data&&data.previous_out_point!=undefined){this.previous_out_point=data.previous_out_point}if("pub_key"in data&&data.pub_key!=undefined){this.pub_key=data.pub_key}}}get previous_out_point(){return pb_1__namespace.Message.getWrapperField(this,ProtoOutPoint,1)}set previous_out_point(value){pb_1__namespace.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_previous_out_point(){return pb_1__namespace.Message.getField(this,1)!=null}get pub_key(){return pb_1__namespace.Message.getFieldWithDefault(this,2,new Uint8Array(0))}set pub_key(value){pb_1__namespace.Message.setOneofField(this,2,this.#one_of_decls[1],value)}get has_pub_key(){return pb_1__namespace.Message.getField(this,2)!=null}get _previous_out_point(){const cases={0:"none",1:"previous_out_point"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _pub_key(){const cases={0:"none",2:"pub_key"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoTxIn({});if(data.previous_out_point!=null){message.previous_out_point=ProtoOutPoint.fromObject(data.previous_out_point)}if(data.pub_key!=null){message.pub_key=data.pub_key}return message}toObject(){const data={};if(this.previous_out_point!=null){data.previous_out_point=this.previous_out_point.toObject()}if(this.pub_key!=null){data.pub_key=this.pub_key}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_previous_out_point)writer.writeMessage(1,this.previous_out_point,()=>this.previous_out_point.serialize(writer));if(this.has_pub_key)writer.writeBytes(2,this.pub_key);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoTxIn;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.previous_out_point,()=>message.previous_out_point=ProtoOutPoint.deserialize(reader));break;case 2:message.pub_key=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTxIn.deserialize(bytes)}}block.ProtoTxIn=ProtoTxIn;class ProtoOutPoint extends pb_1__namespace.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("hash"in data&&data.hash!=undefined){this.hash=data.hash}if("index"in data&&data.index!=undefined){this.index=data.index}}}get hash(){return pb_1__namespace.Message.getWrapperField(this,common.ProtoHash,1)}set hash(value){pb_1__namespace.Message.setOneofWrapperField(this,1,this.#one_of_decls[0],value)}get has_hash(){return pb_1__namespace.Message.getField(this,1)!=null}get index(){return pb_1__namespace.Message.getFieldWithDefault(this,2,0)}set index(value){pb_1__namespace.Message.setOneofField(this,2,this.#one_of_decls[1],value)}get has_index(){return pb_1__namespace.Message.getField(this,2)!=null}get _hash(){const cases={0:"none",1:"hash"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _index(){const cases={0:"none",2:"index"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoOutPoint({});if(data.hash!=null){message.hash=common.ProtoHash.fromObject(data.hash)}if(data.index!=null){message.index=data.index}return message}toObject(){const data={};if(this.hash!=null){data.hash=this.hash.toObject()}if(this.index!=null){data.index=this.index}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_hash)writer.writeMessage(1,this.hash,()=>this.hash.serialize(writer));if(this.has_index)writer.writeUint32(2,this.index);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoOutPoint;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:reader.readMessage(message.hash,()=>message.hash=common.ProtoHash.deserialize(reader));break;case 2:message.index=reader.readUint32();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoOutPoint.deserialize(bytes)}}block.ProtoOutPoint=ProtoOutPoint;class ProtoTxOut extends pb_1__namespace.Message{#one_of_decls=[[1],[2]];constructor(data){super();pb_1__namespace.Message.initialize(this,Array.isArray(data)?data:[],0,-1,[],this.#one_of_decls);if(!Array.isArray(data)&&typeof data=="object"){if("denomination"in data&&data.denomination!=undefined){this.denomination=data.denomination}if("address"in data&&data.address!=undefined){this.address=data.address}}}get denomination(){return pb_1__namespace.Message.getFieldWithDefault(this,1,0)}set denomination(value){pb_1__namespace.Message.setOneofField(this,1,this.#one_of_decls[0],value)}get has_denomination(){return pb_1__namespace.Message.getField(this,1)!=null}get address(){return pb_1__namespace.Message.getFieldWithDefault(this,2,new Uint8Array(0))}set address(value){pb_1__namespace.Message.setOneofField(this,2,this.#one_of_decls[1],value)}get has_address(){return pb_1__namespace.Message.getField(this,2)!=null}get _denomination(){const cases={0:"none",1:"denomination"};return cases[pb_1__namespace.Message.computeOneofCase(this,[1])]}get _address(){const cases={0:"none",2:"address"};return cases[pb_1__namespace.Message.computeOneofCase(this,[2])]}static fromObject(data){const message=new ProtoTxOut({});if(data.denomination!=null){message.denomination=data.denomination}if(data.address!=null){message.address=data.address}return message}toObject(){const data={};if(this.denomination!=null){data.denomination=this.denomination}if(this.address!=null){data.address=this.address}return data}serialize(w){const writer=w||new pb_1__namespace.BinaryWriter;if(this.has_denomination)writer.writeUint32(1,this.denomination);if(this.has_address)writer.writeBytes(2,this.address);if(!w)return writer.getResultBuffer()}static deserialize(bytes){const reader=bytes instanceof pb_1__namespace.BinaryReader?bytes:new pb_1__namespace.BinaryReader(bytes),message=new ProtoTxOut;while(reader.nextField()){if(reader.isEndGroup())break;switch(reader.getFieldNumber()){case 1:message.denomination=reader.readUint32();break;case 2:message.address=reader.readBytes();break;default:reader.skipField()}}return message}serializeBinary(){return this.serialize()}static deserializeBinary(bytes){return ProtoTxOut.deserialize(bytes)}}block.ProtoTxOut=ProtoTxOut})(block||(block={}));function encodeProtoTransaction(protoTx){const tx=block.ProtoTransaction.fromObject(protoTx);return hexlify(tx.serialize())}function decodeProtoTransaction(bytes){const tx=block.ProtoTransaction.deserialize(bytes);const result=tx.toObject();if(result.to?.length==0){result.to=null}return result}function errorFunc(reason,offset,bytes,output,badCodepoint){assertArgument(false,`invalid codepoint at offset ${offset}; ${reason}`,"bytes",bytes)}function ignoreFunc(reason,offset,bytes,output,badCodepoint){if(reason==="BAD_PREFIX"||reason==="UNEXPECTED_CONTINUE"){let i=0;for(let o=offset+1;o>6!==2){break}i++}return i}if(reason==="OVERRUN"){return bytes.length-offset-1}return 0}function replaceFunc(reason,offset,bytes,output,badCodepoint){if(reason==="OVERLONG"){assertArgument(typeof badCodepoint==="number","invalid bad code point for replacement","badCodepoint",badCodepoint);output.push(badCodepoint);return 0}output.push(65533);return ignoreFunc(reason,offset,bytes)}const Utf8ErrorFuncs=Object.freeze({error:errorFunc,ignore:ignoreFunc,replace:replaceFunc});function getUtf8CodePoints(_bytes,onError){if(onError==null){onError=Utf8ErrorFuncs.error}const bytes=getBytes(_bytes,"bytes");const result=[];let i=0;while(i>7===0){result.push(c);continue}let extraLength=null;let overlongMask=null;if((c&224)===192){extraLength=1;overlongMask=127}else if((c&240)===224){extraLength=2;overlongMask=2047}else if((c&248)===240){extraLength=3;overlongMask=65535}else{if((c&192)===128){i+=onError("UNEXPECTED_CONTINUE",i-1,bytes,result)}else{i+=onError("BAD_PREFIX",i-1,bytes,result)}continue}if(i-1+extraLength>=bytes.length){i+=onError("OVERRUN",i-1,bytes,result);continue}let res=c&(1<<8-extraLength-1)-1;for(let j=0;j1114111){i+=onError("OUT_OF_RANGE",i-1-extraLength,bytes,result,res);continue}if(res>=55296&&res<=57343){i+=onError("UTF16_SURROGATE",i-1-extraLength,bytes,result,res);continue}if(res<=overlongMask){i+=onError("OVERLONG",i-1-extraLength,bytes,result,res);continue}result.push(res)}return result}function toUtf8Bytes(str,form){if(form!=null){assertNormalize(form);str=str.normalize(form)}const result=[];for(let i=0;i>6|192);result.push(c&63|128)}else if((c&64512)==55296){i++;const c2=str.charCodeAt(i);assertArgument(i>18|240);result.push(pair>>12&63|128);result.push(pair>>6&63|128);result.push(pair&63|128)}else{result.push(c>>12|224);result.push(c>>6&63|128);result.push(c&63|128)}}return new Uint8Array(result)}function _toUtf8String(codePoints){return codePoints.map(codePoint=>{if(codePoint<=65535){return String.fromCharCode(codePoint)}codePoint-=65536;return String.fromCharCode((codePoint>>10&1023)+55296,(codePoint&1023)+56320)}).join("")}function toUtf8String(bytes,onError){return _toUtf8String(getUtf8CodePoints(bytes,onError))}function toUtf8CodePoints(str,form){return getUtf8CodePoints(toUtf8Bytes(str,form))}function createGetUrl(options){async function getUrl(req,_signal){const protocol=req.url.split(":")[0].toLowerCase();assert(protocol==="http"||protocol==="https",`unsupported protocol ${protocol}`,"UNSUPPORTED_OPERATION",{info:{protocol:protocol},operation:"request"});assert(protocol==="https"||!req.credentials||req.allowInsecureAuthentication,"insecure authorized connections unsupported","UNSUPPORTED_OPERATION",{operation:"request"});let signal=undefined;if(_signal){const controller=new AbortController;signal=controller.signal;_signal.addListener(()=>{controller.abort()})}const init={method:req.method,headers:new Headers(Array.from(req)),body:req.body||undefined,signal:signal};const resp=await fetch(req.url,init);const headers={};resp.headers.forEach((value,key)=>{headers[key.toLowerCase()]=value});const respBody=await resp.arrayBuffer();const body=respBody==null?null:new Uint8Array(respBody);return{statusCode:resp.status,statusMessage:resp.statusText,headers:headers,body:body}}return getUrl}const MAX_ATTEMPTS=12;const SLOT_INTERVAL=250;let defaultGetUrlFunc=createGetUrl();const reData=new RegExp("^data:([^;:]*)?(;base64)?,(.*)$","i");const reIpfs=new RegExp("^ipfs://(ipfs/)?(.*)$","i");let locked$5=false;async function dataGatewayFunc(url,signal){try{const match=url.match(reData);if(!match){throw new Error("invalid data")}return new FetchResponse(200,"OK",{"content-type":match[1]||"text/plain"},match[2]?decodeBase64(match[3]):unpercent(match[3]))}catch(error){return new FetchResponse(599,"BAD REQUEST (invalid data: URI)",{},null,new FetchRequest(url))}}function getIpfsGatewayFunc(baseUrl){async function gatewayIpfs(url,signal){try{const match=url.match(reIpfs);if(!match){throw new Error("invalid link")}return new FetchRequest(`${baseUrl}${match[2]}`)}catch(error){return new FetchResponse(599,"BAD REQUEST (invalid IPFS URI)",{},null,new FetchRequest(url))}}return gatewayIpfs}const Gateways={data:dataGatewayFunc,ipfs:getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/")};const fetchSignals=new WeakMap;class FetchCancelSignal{#listeners;#cancelled;constructor(request){this.#listeners=[];this.#cancelled=false;fetchSignals.set(request,()=>{if(this.#cancelled){return}this.#cancelled=true;for(const listener of this.#listeners){setTimeout(()=>{listener()},0)}this.#listeners=[]})}addListener(listener){assert(!this.#cancelled,"singal already cancelled","UNSUPPORTED_OPERATION",{operation:"fetchCancelSignal.addCancelListener"});this.#listeners.push(listener)}get cancelled(){return this.#cancelled}checkSignal(){assert(!this.cancelled,"cancelled","CANCELLED",{})}}function checkSignal(signal){if(signal==null){throw new Error("missing signal; should not happen")}signal.checkSignal();return signal}class FetchRequest{#allowInsecure;#gzip;#headers;#method;#timeout;#url;#body;#bodyType;#creds;#preflight;#process;#retry;#signal;#throttle;#getUrlFunc;get url(){return this.#url}set url(url){this.#url=String(url)}get body(){if(this.#body==null){return null}return new Uint8Array(this.#body)}set body(body){if(body==null){this.#body=undefined;this.#bodyType=undefined}else if(typeof body==="string"){this.#body=toUtf8Bytes(body);this.#bodyType="text/plain"}else if(body instanceof Uint8Array){this.#body=body;this.#bodyType="application/octet-stream"}else if(typeof body==="object"){this.#body=toUtf8Bytes(JSON.stringify(body));this.#bodyType="application/json"}else{throw new Error("invalid body")}}hasBody(){return this.#body!=null}get method(){if(this.#method){return this.#method}if(this.hasBody()){return"POST"}return"GET"}set method(method){if(method==null){method=""}this.#method=String(method).toUpperCase()}get headers(){const headers=Object.assign({},this.#headers);if(this.#creds){headers["authorization"]=`Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`}if(this.allowGzip){headers["accept-encoding"]="gzip"}if(headers["content-type"]==null&&this.#bodyType){headers["content-type"]=this.#bodyType}if(this.body){headers["content-length"]=String(this.body.length)}return headers}getHeader(key){return this.headers[key.toLowerCase()]}setHeader(key,value){this.#headers[String(key).toLowerCase()]=String(value)}clearHeaders(){this.#headers={}}[Symbol.iterator](){const headers=this.headers;const keys=Object.keys(headers);let index=0;return{next:()=>{if(index=0,"timeout must be non-zero","timeout",timeout);this.#timeout=timeout}get preflightFunc(){return this.#preflight||null}set preflightFunc(preflight){this.#preflight=preflight}get processFunc(){return this.#process||null}set processFunc(process){this.#process=process}get retryFunc(){return this.#retry||null}set retryFunc(retry){this.#retry=retry}get getUrlFunc(){return this.#getUrlFunc||defaultGetUrlFunc}set getUrlFunc(value){this.#getUrlFunc=value}constructor(url){this.#url=String(url);this.#allowInsecure=false;this.#gzip=true;this.#headers={};this.#method="";this.#timeout=3e5;this.#throttle={slotInterval:SLOT_INTERVAL,maxAttempts:MAX_ATTEMPTS};this.#getUrlFunc=null}toString(){return``}setThrottleParams(params){if(params.slotInterval!=null){this.#throttle.slotInterval=params.slotInterval}if(params.maxAttempts!=null){this.#throttle.maxAttempts=params.maxAttempts}}async#send(attempt,expires,delay,_request,_response){if(attempt>=this.#throttle.maxAttempts){return _response.makeServerError("exceeded maximum retry limit")}assert(getTime$1()<=expires,"timeout","TIMEOUT",{operation:"request.send",reason:"timeout",request:_request});if(delay>0){await wait(delay)}let req=this.clone();const scheme=(req.url.split(":")[0]||"").toLowerCase();if(scheme in Gateways){const result=await Gateways[scheme](req.url,checkSignal(_request.#signal));if(result instanceof FetchResponse){let response=result;if(this.processFunc){checkSignal(_request.#signal);try{response=await this.processFunc(req,response)}catch(error){if(error.throttle==null||typeof error.stall!=="number"){response.makeServerError("error in post-processing function",error).assertOk()}}}return response}req=result}if(this.preflightFunc){req=await this.preflightFunc(req)}const resp=await this.getUrlFunc(req,checkSignal(_request.#signal));let response=new FetchResponse(resp.statusCode,resp.statusMessage,resp.headers,resp.body,_request);if(response.statusCode===301||response.statusCode===302){try{const location=response.headers.location||"";return req.redirect(location).#send(attempt+1,expires,0,_request,response)}catch(error){}return response}else if(response.statusCode===429){if(this.retryFunc==null||await this.retryFunc(req,response,attempt)){const retryAfter=response.headers["retry-after"];let delay=this.#throttle.slotInterval*Math.trunc(Math.random()*Math.pow(2,attempt));if(typeof retryAfter==="string"&&retryAfter.match(/^[1-9][0-9]*$/)){delay=parseInt(retryAfter)}return req.clone().#send(attempt+1,expires,delay,_request,response)}}if(this.processFunc){checkSignal(_request.#signal);try{response=await this.processFunc(req,response)}catch(error){if(error.throttle==null||typeof error.stall!=="number"){response.makeServerError("error in post-processing function",error).assertOk()}let delay=this.#throttle.slotInterval*Math.trunc(Math.random()*Math.pow(2,attempt));if(error.stall>=0){delay=error.stall}return req.clone().#send(attempt+1,expires,delay,_request,response)}}return response}send(){assert(this.#signal==null,"request already sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.send"});this.#signal=new FetchCancelSignal(this);return this.#send(0,getTime$1()+this.timeout,0,this,new FetchResponse(0,"",{},null,this))}cancel(){assert(this.#signal!=null,"request has not been sent","UNSUPPORTED_OPERATION",{operation:"fetchRequest.cancel"});const signal=fetchSignals.get(this);if(!signal){throw new Error("missing signal; should not happen")}signal()}redirect(location){const current=this.url.split(":")[0].toLowerCase();const target=location.split(":")[0].toLowerCase();assert(this.method==="GET"&&(current!=="https"||target!=="http")&&location.match(/^https?:/),`unsupported redirect`,"UNSUPPORTED_OPERATION",{operation:`redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})`});const req=new FetchRequest(location);req.method="GET";req.allowGzip=this.allowGzip;req.timeout=this.timeout;req.#headers=Object.assign({},this.#headers);if(this.#body){req.#body=new Uint8Array(this.#body)}req.#bodyType=this.#bodyType;return req}clone(){const clone=new FetchRequest(this.url);clone.#method=this.#method;if(this.#body){clone.#body=this.#body}clone.#bodyType=this.#bodyType;clone.#headers=Object.assign({},this.#headers);clone.#creds=this.#creds;if(this.allowGzip){clone.allowGzip=true}clone.timeout=this.timeout;if(this.allowInsecureAuthentication){clone.allowInsecureAuthentication=true}clone.#preflight=this.#preflight;clone.#process=this.#process;clone.#retry=this.#retry;clone.#getUrlFunc=this.#getUrlFunc;return clone}static lockConfig(){locked$5=true}static getGateway(scheme){return Gateways[scheme.toLowerCase()]||null}static registerGateway(scheme,func){scheme=scheme.toLowerCase();if(scheme==="http"||scheme==="https"){throw new Error(`cannot intercept ${scheme}; use registerGetUrl`)}if(locked$5){throw new Error("gateways locked")}Gateways[scheme]=func}static registerGetUrl(getUrl){if(locked$5){throw new Error("gateways locked")}defaultGetUrlFunc=getUrl}static createGetUrlFunc(options){return createGetUrl()}static createDataGateway(){return dataGatewayFunc}static createIpfsGatewayFunc(baseUrl){return getIpfsGatewayFunc(baseUrl)}}class FetchResponse{#statusCode;#statusMessage;#headers;#body;#request;#error;toString(){return``}get statusCode(){return this.#statusCode}get statusMessage(){return this.#statusMessage}get headers(){return Object.assign({},this.#headers)}get body(){return this.#body==null?null:new Uint8Array(this.#body)}get bodyText(){try{return this.#body==null?"":toUtf8String(this.#body)}catch(error){assert(false,"response body is not valid UTF-8 data","UNSUPPORTED_OPERATION",{operation:"bodyText",info:{response:this}})}}get bodyJson(){try{return JSON.parse(this.bodyText)}catch(error){assert(false,"response body is not valid JSON","UNSUPPORTED_OPERATION",{operation:"bodyJson",info:{response:this}})}}[Symbol.iterator](){const headers=this.headers;const keys=Object.keys(headers);let index=0;return{next:()=>{if(index{accum[k.toLowerCase()]=String(headers[k]);return accum},{});this.#body=body==null?null:new Uint8Array(body);this.#request=request||null;this.#error={message:""}}makeServerError(message,error){let statusMessage;if(!message){message=`${this.statusCode} ${this.statusMessage}`;statusMessage=`CLIENT ESCALATED SERVER ERROR (${message})`}else{statusMessage=`CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`}const response=new FetchResponse(599,statusMessage,this.headers,this.body,this.#request||undefined);response.#error={message:message,error:error};return response}throwThrottleError(message,stall){if(stall==null){stall=-1}else{assertArgument(Number.isInteger(stall)&&stall>=0,"invalid stall timeout","stall",stall)}const error=new Error(message||"throttling requests");defineProperties(error,{stall:stall,throttle:true});throw error}getHeader(key){return this.headers[key.toLowerCase()]}hasBody(){return this.#body!=null}get request(){return this.#request}ok(){return this.#error.message===""&&this.statusCode>=200&&this.statusCode<300}assertOk(){if(this.ok()){return}let{message,error}=this.#error;if(message===""){message=`server response ${this.statusCode} ${this.statusMessage}`}assert(false,message,"SERVER_ERROR",{request:this.request||"unknown request",response:this,error:error})}}function getTime$1(){return(new Date).getTime()}function unpercent(value){return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi,(all,code)=>{return String.fromCharCode(parseInt(code,16))}))}function wait(delay){return new Promise(resolve=>setTimeout(resolve,delay))}const BN_N1=BigInt(-1);const BN_0$6=BigInt(0);const BN_1$3=BigInt(1);const BN_5=BigInt(5);const _guard$7={};let Zeros="0000";while(Zeros.length<80){Zeros+=Zeros}function getTens(decimals){let result=Zeros;while(result.length=-limit&&valBN_0$6){val=fromTwos(mask(val,width),width)}else{val=-fromTwos(mask(-val,width),width)}}else{const limit=BN_1$3<=0&&val{if(v[key]==null){return defaultValue}assertArgument(typeof v[key]===type,"invalid fixed format ("+key+" not "+type+")","format."+key,v[key]);return v[key]};signed=check("signed","boolean",signed);width=check("width","number",width);decimals=check("decimals","number",decimals)}assertArgument(width%8===0,"invalid FixedNumber width (not byte aligned)","format.width",width);assertArgument(decimals<=80,"invalid FixedNumber decimals (too large)","format.decimals",decimals);const name=(signed?"":"u")+"fixed"+String(width)+"x"+String(decimals);return{signed:signed,width:width,decimals:decimals,name:name}}function toString(val,decimals){let negative="";if(val0){b*=getTens(delta)}else if(delta<0){a*=getTens(-delta)}if(ab){return 1}return 0}eq(other){return this.cmp(other)===0}lt(other){return this.cmp(other)<0}lte(other){return this.cmp(other)<=0}gt(other){return this.cmp(other)>0}gte(other){return this.cmp(other)>=0}floor(){let val=this.#val;if(this.#valBN_0$6){val+=this.#tens-BN_1$3}val=this.#val/this.#tens*this.#tens;return this.#checkValue(val,"ceiling")}round(decimals){if(decimals==null){decimals=0}if(decimals>=this.decimals){return this}const delta=this.decimals-decimals;const bump=BN_5*getTens(delta-1);let value=this.value+bump;const tens=getTens(delta);value=value/tens*tens;checkValue(value,this.#format,"round");return new FixedNumber(_guard$7,value,this.#format)}isZero(){return this.#val===BN_0$6}isNegative(){return this.#val0){const tens=getTens(delta);assert(value%tens===BN_0$6,"value loses precision for format","NUMERIC_FAULT",{operation:"fromValue",fault:"underflow",value:_value});value/=tens}else if(delta<0){value*=getTens(-delta)}checkValue(value,format,"fromValue");return new FixedNumber(_guard$7,value,format)}static fromString(_value,_format){const match=_value.match(/^(-?)([0-9]*)\.?([0-9]*)$/);assertArgument(match&&match[2].length+match[3].length>0,"invalid FixedNumber string value","value",_value);const format=getFormat(_format);const whole=match[2]||"0";let decimal=match[3]||"";while(decimal.length=0,"invalid unit","unit",unit);decimals=3*index}else if(unit!=null){decimals=getNumber(unit,"unit")}return FixedNumber.fromValue(value,decimals,{decimals:decimals,width:512}).toString()}function parseUnits(value,unit){assertArgument(typeof value==="string","value must be a string","value",value);let decimals=18;if(typeof unit==="string"){const index=names.indexOf(unit);assertArgument(index>=0,"invalid unit","unit",unit);decimals=3*index}else if(unit!=null){decimals=getNumber(unit,"unit")}return FixedNumber.fromString(value,{decimals:decimals,width:512}).value}function formatQuai(wei){return formatUnits(wei,18)}function parseQuai(ether){return parseUnits(ether,18)}function uuidV4(randomBytes){const bytes=getBytes(randomBytes,"randomBytes");bytes[6]=bytes[6]&15|64;bytes[8]=bytes[8]&63|128;const value=hexlify(bytes);return[value.substring(2,10),value.substring(10,14),value.substring(14,18),value.substring(18,22),value.substring(22,34)].join("-")}exports.Zone=void 0;(function(Zone){Zone["Cyprus1"]="0x00";Zone["Cyprus2"]="0x01";Zone["Cyprus3"]="0x02";Zone["Paxos1"]="0x10";Zone["Paxos2"]="0x11";Zone["Paxos3"]="0x12";Zone["Hydra1"]="0x20";Zone["Hydra2"]="0x21";Zone["Hydra3"]="0x22"})(exports.Zone||(exports.Zone={}));exports.Ledger=void 0;(function(Ledger){Ledger[Ledger["Quai"]=0]="Quai";Ledger[Ledger["Qi"]=1]="Qi"})(exports.Ledger||(exports.Ledger={}));function zoneFromBytes(zone){switch(zone){case"0x00":return exports.Zone.Cyprus1;case"0x01":return exports.Zone.Cyprus2;case"0x02":return exports.Zone.Cyprus3;case"0x10":return exports.Zone.Paxos1;case"0x11":return exports.Zone.Paxos2;case"0x12":return exports.Zone.Paxos3;case"0x20":return exports.Zone.Hydra1;case"0x21":return exports.Zone.Hydra2;case"0x22":return exports.Zone.Hydra3;default:throw new Error(`Invalid zone: ${zone}`)}}const ZoneData=[{name:"Cyprus One",nickname:"cyprus1",shard:"zone-0-0",context:2,byte:"0x00"},{name:"Cyprus Two",nickname:"cyprus2",shard:"zone-0-1",context:2,byte:"0x01"},{name:"Cyprus Three",nickname:"cyprus3",shard:"zone-0-2",context:2,byte:"0x02"},{name:"Paxos One",nickname:"paxos1",shard:"zone-1-0",context:2,byte:"0x10"},{name:"Paxos Two",nickname:"paxos2",shard:"zone-1-1",context:2,byte:"0x11"},{name:"Paxos Three",nickname:"paxos3",shard:"zone-1-2",context:2,byte:"0x12"},{name:"Hydra One",nickname:"hydra1",shard:"zone-2-0",context:2,byte:"0x20"},{name:"Hydra Two",nickname:"hydra2",shard:"zone-2-1",context:2,byte:"0x21"},{name:"Hydra Three",nickname:"hydra3",shard:"zone-2-2",context:2,byte:"0x22"}];function toZone(shard){return zoneFromBytes(ZoneData.find(it=>it.name==shard||it.byte==shard||it.nickname==shard||it.shard==shard)?.byte||"")}function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bytes(b,...lengths){if(!(b instanceof Uint8Array))throw new Error("Expected Uint8Array");if(lengths.length>0&&!lengths.includes(b.length))throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`)}function hash(hash){if(typeof hash!=="function"||typeof hash.create!=="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");number(hash.outputLen);number(hash.blockLen)}function exists(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function output(out,instance){bytes(out);const min=instance.outputLen;if(out.lengtha instanceof Uint8Array;const u32=arr=>new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4));const createView=arr=>new DataView(arr.buffer,arr.byteOffset,arr.byteLength);const rotr=(word,shift)=>word<<32-shift|word>>>shift;const isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");const nextTick=async()=>{};async function asyncLoop(iters,tick,cb){let ts=Date.now();for(let i=0;i=0&&diffsum+a.length,0));let pad=0;arrays.forEach(a=>{if(!u8a$1(a))throw new Error("Uint8Array expected");r.set(a,pad);pad+=a.length});return r}class Hash{clone(){return this._cloneInto()}}const toStr={}.toString;function checkOpts(defaults,opts){if(opts!==undefined&&toStr.call(opts)!=="[object Object]")throw new Error("Options should be object or undefined");const merged=Object.assign(defaults,opts);return merged}function wrapConstructor(hashCons){const hashC=msg=>hashCons().update(toBytes(msg)).digest();const tmp=hashCons();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashCons();return hashC}function randomBytes$2(bytesLength=32){if(crypto$1&&typeof crypto$1.getRandomValues==="function"){return crypto$1.getRandomValues(new Uint8Array(bytesLength))}throw new Error("crypto.getRandomValues must be defined")}class HMAC extends Hash{constructor(hash$1,_key){super();this.finished=false;this.destroyed=false;hash(hash$1);const key=toBytes(_key);this.iHash=hash$1.create();if(typeof this.iHash.update!=="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen;this.outputLen=this.iHash.outputLen;const blockLen=this.blockLen;const pad=new Uint8Array(blockLen);pad.set(key.length>blockLen?hash$1.create().update(key).digest():key);for(let i=0;inew HMAC(hash,key).update(message).digest();hmac.create=(hash,key)=>new HMAC(hash,key);function pbkdf2Init(hash$1,_password,_salt,_opts){hash(hash$1);const opts=checkOpts({dkLen:32,asyncTick:10},_opts);const{c,dkLen,asyncTick}=opts;number(c);number(dkLen);number(asyncTick);if(c<1)throw new Error("PBKDF2: iterations (c) should be >= 1");const password=toBytes(_password);const salt=toBytes(_salt);const DK=new Uint8Array(dkLen);const PRF=hmac.create(hash$1,password);const PRFSalt=PRF._cloneInto().update(salt);return{c:c,dkLen:dkLen,asyncTick:asyncTick,DK:DK,PRF:PRF,PRFSalt:PRFSalt}}function pbkdf2Output(PRF,PRFSalt,DK,prfW,u){PRF.destroy();PRFSalt.destroy();if(prfW)prfW.destroy();u.fill(0);return DK}function pbkdf2$1(hash,password,salt,opts){const{c,dkLen,DK,PRF,PRFSalt}=pbkdf2Init(hash,password,salt,opts);let prfW;const arr=new Uint8Array(4);const view=createView(arr);const u=new Uint8Array(PRF.outputLen);for(let ti=1,pos=0;pos>_32n&_u32_max);const wl=Number(value&_u32_max);const h=isLE?4:0;const l=isLE?0:4;view.setUint32(byteOffset+h,wh,isLE);view.setUint32(byteOffset+l,wl,isLE)}class SHA2 extends Hash{constructor(blockLen,outputLen,padOffset,isLE){super();this.blockLen=blockLen;this.outputLen=outputLen;this.padOffset=padOffset;this.isLE=isLE;this.finished=false;this.length=0;this.pos=0;this.destroyed=false;this.buffer=new Uint8Array(blockLen);this.view=createView(this.buffer)}update(data){exists(this);const{view,buffer,blockLen}=this;data=toBytes(data);const len=data.length;for(let pos=0;posblockLen-pos){this.process(view,0);pos=0}for(let i=pos;istate.length)throw new Error("_sha2: outputLen bigger than state");for(let i=0;ia&b^~a&c;const Maj=(a,b,c)=>a&b^a&c^b&c;const SHA256_K=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);const IV=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);const SHA256_W=new Uint32Array(64);class SHA256 extends SHA2{constructor(){super(64,32,8,false);this.A=IV[0]|0;this.B=IV[1]|0;this.C=IV[2]|0;this.D=IV[3]|0;this.E=IV[4]|0;this.F=IV[5]|0;this.G=IV[6]|0;this.H=IV[7]|0}get(){const{A,B,C,D,E,F,G,H}=this;return[A,B,C,D,E,F,G,H]}set(A,B,C,D,E,F,G,H){this.A=A|0;this.B=B|0;this.C=C|0;this.D=D|0;this.E=E|0;this.F=F|0;this.G=G|0;this.H=H|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)SHA256_W[i]=view.getUint32(offset,false);for(let i=16;i<64;i++){const W15=SHA256_W[i-15];const W2=SHA256_W[i-2];const s0=rotr(W15,7)^rotr(W15,18)^W15>>>3;const s1=rotr(W2,17)^rotr(W2,19)^W2>>>10;SHA256_W[i]=s1+SHA256_W[i-7]+s0+SHA256_W[i-16]|0}let{A,B,C,D,E,F,G,H}=this;for(let i=0;i<64;i++){const sigma1=rotr(E,6)^rotr(E,11)^rotr(E,25);const T1=H+sigma1+Chi(E,F,G)+SHA256_K[i]+SHA256_W[i]|0;const sigma0=rotr(A,2)^rotr(A,13)^rotr(A,22);const T2=sigma0+Maj(A,B,C)|0;H=G;G=F;F=E;E=D+T1|0;D=C;C=B;B=A;A=T1+T2|0}A=A+this.A|0;B=B+this.B|0;C=C+this.C|0;D=D+this.D|0;E=E+this.E|0;F=F+this.F|0;G=G+this.G|0;H=H+this.H|0;this.set(A,B,C,D,E,F,G,H)}roundClean(){SHA256_W.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0);this.buffer.fill(0)}}const sha256$1=wrapConstructor(()=>new SHA256);const U32_MASK64=BigInt(2**32-1);const _32n=BigInt(32);function fromBig(n,le=false){if(le)return{h:Number(n&U32_MASK64),l:Number(n>>_32n&U32_MASK64)};return{h:Number(n>>_32n&U32_MASK64)|0,l:Number(n&U32_MASK64)|0}}function split(lst,le=false){let Ah=new Uint32Array(lst.length);let Al=new Uint32Array(lst.length);for(let i=0;iBigInt(h>>>0)<<_32n|BigInt(l>>>0);const shrSH=(h,_l,s)=>h>>>s;const shrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrSH=(h,l,s)=>h>>>s|l<<32-s;const rotrSL=(h,l,s)=>h<<32-s|l>>>s;const rotrBH=(h,l,s)=>h<<64-s|l>>>s-32;const rotrBL=(h,l,s)=>h>>>s-32|l<<64-s;const rotr32H=(_h,l)=>l;const rotr32L=(h,_l)=>h;const rotlSH=(h,l,s)=>h<>>32-s;const rotlSL=(h,l,s)=>l<>>32-s;const rotlBH=(h,l,s)=>l<>>64-s;const rotlBL=(h,l,s)=>h<>>64-s;function add(Ah,Al,Bh,Bl){const l=(Al>>>0)+(Bl>>>0);return{h:Ah+Bh+(l/2**32|0)|0,l:l|0}}const add3L=(Al,Bl,Cl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0);const add3H=(low,Ah,Bh,Ch)=>Ah+Bh+Ch+(low/2**32|0)|0;const add4L=(Al,Bl,Cl,Dl)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0);const add4H=(low,Ah,Bh,Ch,Dh)=>Ah+Bh+Ch+Dh+(low/2**32|0)|0;const add5L=(Al,Bl,Cl,Dl,El)=>(Al>>>0)+(Bl>>>0)+(Cl>>>0)+(Dl>>>0)+(El>>>0);const add5H=(low,Ah,Bh,Ch,Dh,Eh)=>Ah+Bh+Ch+Dh+Eh+(low/2**32|0)|0;const u64={fromBig:fromBig,split:split,toBig:toBig,shrSH:shrSH,shrSL:shrSL,rotrSH:rotrSH,rotrSL:rotrSL,rotrBH:rotrBH,rotrBL:rotrBL,rotr32H:rotr32H,rotr32L:rotr32L,rotlSH:rotlSH,rotlSL:rotlSL,rotlBH:rotlBH,rotlBL:rotlBL,add:add,add3L:add3L,add3H:add3H,add4L:add4L,add4H:add4H,add5H:add5H,add5L:add5L};const[SHA512_Kh,SHA512_Kl]=(()=>u64.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))))();const SHA512_W_H=new Uint32Array(80);const SHA512_W_L=new Uint32Array(80);class SHA512 extends SHA2{constructor(){super(128,64,16,false);this.Ah=1779033703|0;this.Al=4089235720|0;this.Bh=3144134277|0;this.Bl=2227873595|0;this.Ch=1013904242|0;this.Cl=4271175723|0;this.Dh=2773480762|0;this.Dl=1595750129|0;this.Eh=1359893119|0;this.El=2917565137|0;this.Fh=2600822924|0;this.Fl=725511199|0;this.Gh=528734635|0;this.Gl=4215389547|0;this.Hh=1541459225|0;this.Hl=327033209|0}get(){const{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;return[Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl]}set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl){this.Ah=Ah|0;this.Al=Al|0;this.Bh=Bh|0;this.Bl=Bl|0;this.Ch=Ch|0;this.Cl=Cl|0;this.Dh=Dh|0;this.Dl=Dl|0;this.Eh=Eh|0;this.El=El|0;this.Fh=Fh|0;this.Fl=Fl|0;this.Gh=Gh|0;this.Gl=Gl|0;this.Hh=Hh|0;this.Hl=Hl|0}process(view,offset){for(let i=0;i<16;i++,offset+=4){SHA512_W_H[i]=view.getUint32(offset);SHA512_W_L[i]=view.getUint32(offset+=4)}for(let i=16;i<80;i++){const W15h=SHA512_W_H[i-15]|0;const W15l=SHA512_W_L[i-15]|0;const s0h=u64.rotrSH(W15h,W15l,1)^u64.rotrSH(W15h,W15l,8)^u64.shrSH(W15h,W15l,7);const s0l=u64.rotrSL(W15h,W15l,1)^u64.rotrSL(W15h,W15l,8)^u64.shrSL(W15h,W15l,7);const W2h=SHA512_W_H[i-2]|0;const W2l=SHA512_W_L[i-2]|0;const s1h=u64.rotrSH(W2h,W2l,19)^u64.rotrBH(W2h,W2l,61)^u64.shrSH(W2h,W2l,6);const s1l=u64.rotrSL(W2h,W2l,19)^u64.rotrBL(W2h,W2l,61)^u64.shrSL(W2h,W2l,6);const SUMl=u64.add4L(s0l,s1l,SHA512_W_L[i-7],SHA512_W_L[i-16]);const SUMh=u64.add4H(SUMl,s0h,s1h,SHA512_W_H[i-7],SHA512_W_H[i-16]);SHA512_W_H[i]=SUMh|0;SHA512_W_L[i]=SUMl|0}let{Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl}=this;for(let i=0;i<80;i++){const sigma1h=u64.rotrSH(Eh,El,14)^u64.rotrSH(Eh,El,18)^u64.rotrBH(Eh,El,41);const sigma1l=u64.rotrSL(Eh,El,14)^u64.rotrSL(Eh,El,18)^u64.rotrBL(Eh,El,41);const CHIh=Eh&Fh^~Eh&Gh;const CHIl=El&Fl^~El&Gl;const T1ll=u64.add5L(Hl,sigma1l,CHIl,SHA512_Kl[i],SHA512_W_L[i]);const T1h=u64.add5H(T1ll,Hh,sigma1h,CHIh,SHA512_Kh[i],SHA512_W_H[i]);const T1l=T1ll|0;const sigma0h=u64.rotrSH(Ah,Al,28)^u64.rotrBH(Ah,Al,34)^u64.rotrBH(Ah,Al,39);const sigma0l=u64.rotrSL(Ah,Al,28)^u64.rotrBL(Ah,Al,34)^u64.rotrBL(Ah,Al,39);const MAJh=Ah&Bh^Ah&Ch^Bh&Ch;const MAJl=Al&Bl^Al&Cl^Bl&Cl;Hh=Gh|0;Hl=Gl|0;Gh=Fh|0;Gl=Fl|0;Fh=Eh|0;Fl=El|0;({h:Eh,l:El}=u64.add(Dh|0,Dl|0,T1h|0,T1l|0));Dh=Ch|0;Dl=Cl|0;Ch=Bh|0;Cl=Bl|0;Bh=Ah|0;Bl=Al|0;const All=u64.add3L(T1l,sigma0l,MAJl);Ah=u64.add3H(All,T1h,sigma0h,MAJh);Al=All|0}({h:Ah,l:Al}=u64.add(this.Ah|0,this.Al|0,Ah|0,Al|0));({h:Bh,l:Bl}=u64.add(this.Bh|0,this.Bl|0,Bh|0,Bl|0));({h:Ch,l:Cl}=u64.add(this.Ch|0,this.Cl|0,Ch|0,Cl|0));({h:Dh,l:Dl}=u64.add(this.Dh|0,this.Dl|0,Dh|0,Dl|0));({h:Eh,l:El}=u64.add(this.Eh|0,this.El|0,Eh|0,El|0));({h:Fh,l:Fl}=u64.add(this.Fh|0,this.Fl|0,Fh|0,Fl|0));({h:Gh,l:Gl}=u64.add(this.Gh|0,this.Gl|0,Gh|0,Gl|0));({h:Hh,l:Hl}=u64.add(this.Hh|0,this.Hl|0,Hh|0,Hl|0));this.set(Ah,Al,Bh,Bl,Ch,Cl,Dh,Dl,Eh,El,Fh,Fl,Gh,Gl,Hh,Hl)}roundClean(){SHA512_W_H.fill(0);SHA512_W_L.fill(0)}destroy(){this.buffer.fill(0);this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const sha512$1=wrapConstructor(()=>new SHA512);function getGlobal$1(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")}const anyGlobal=getGlobal$1();const crypto=anyGlobal.crypto||anyGlobal.msCrypto;function createHash(algo){switch(algo){case"sha256":return sha256$1.create();case"sha512":return sha512$1.create()}assertArgument(false,"invalid hashing algorithm name","algorithm",algo)}function createHmac(_algo,key){const algo={sha256:sha256$1,sha512:sha512$1}[_algo];assertArgument(algo!=null,"invalid hmac algorithm","algorithm",_algo);return hmac.create(algo,key)}function pbkdf2Sync(password,salt,iterations,keylen,_algo){const algo={sha256:sha256$1,sha512:sha512$1}[_algo];assertArgument(algo!=null,"invalid pbkdf2 algorithm","algorithm",_algo);return pbkdf2$1(algo,password,salt,{c:iterations,dkLen:keylen})}function randomBytes$1(length){assert(crypto!=null,"platform does not support secure random numbers","UNSUPPORTED_OPERATION",{operation:"randomBytes"});assertArgument(Number.isInteger(length)&&length>0&&length<=1024,"invalid length","length",length);const result=new Uint8Array(length);crypto.getRandomValues(result);return result}let locked$4=false;const _computeHmac=function(algorithm,key,data){return createHmac(algorithm,key).update(data).digest()};let __computeHmac=_computeHmac;function computeHmac(algorithm,_key,_data){const key=getBytes(_key,"key");const data=getBytes(_data,"data");return hexlify(__computeHmac(algorithm,key,data))}computeHmac._=_computeHmac;computeHmac.lock=function(){locked$4=true};computeHmac.register=function(func){if(locked$4){throw new Error("computeHmac is locked")}__computeHmac=func};Object.freeze(computeHmac);const[SHA3_PI,SHA3_ROTL,_SHA3_IOTA]=[[],[],[]];const _0n$6=BigInt(0);const _1n$6=BigInt(1);const _2n$4=BigInt(2);const _7n$1=BigInt(7);const _256n=BigInt(256);const _0x71n=BigInt(113);for(let round=0,R=_1n$6,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5];SHA3_PI.push(2*(5*y+x));SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n$6;for(let j=0;j<7;j++){R=(R<<_1n$6^(R>>_7n$1)*_0x71n)%_256n;if(R&_2n$4)t^=_1n$6<<(_1n$6<s>32?rotlBH(h,l,s):rotlSH(h,l,s);const rotlL=(h,l,s)=>s>32?rotlBL(h,l,s):rotlSL(h,l,s);function keccakP(s,rounds=24){const B=new Uint32Array(5*2);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){const idx1=(x+8)%10;const idx0=(x+2)%10;const B0=B[idx0];const B1=B[idx0+1];const Th=rotlH(B0,B1,1)^B[idx1];const Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10){s[x+y]^=Th;s[x+y+1]^=Tl}}let curH=s[2];let curL=s[3];for(let t=0;t<24;t++){const shift=SHA3_ROTL[t];const Th=rotlH(curH,curL,shift);const Tl=rotlL(curH,curL,shift);const PI=SHA3_PI[t];curH=s[PI];curL=s[PI+1];s[PI]=Th;s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round];s[1]^=SHA3_IOTA_L[round]}B.fill(0)}class Keccak extends Hash{constructor(blockLen,suffix,outputLen,enableXOF=false,rounds=24){super();this.blockLen=blockLen;this.suffix=suffix;this.outputLen=outputLen;this.enableXOF=enableXOF;this.rounds=rounds;this.pos=0;this.posOut=0;this.finished=false;this.destroyed=false;number(outputLen);if(0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200);this.state32=u32(this.state)}keccak(){keccakP(this.state32,this.rounds);this.posOut=0;this.pos=0}update(data){exists(this);const{blockLen,state}=this;data=toBytes(data);const len=data.length;for(let pos=0;pos=blockLen)this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos);this.posOut+=take;pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){number(bytes);return this.xofInto(new Uint8Array(bytes))}digestInto(out){output(out,this);if(this.finished)throw new Error("digest() was already called");this.writeInto(out);this.destroy();return out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true;this.state.fill(0)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds));to.state32.set(this.state32);to.pos=this.pos;to.posOut=this.posOut;to.finished=this.finished;to.rounds=rounds;to.suffix=suffix;to.outputLen=outputLen;to.enableXOF=enableXOF;to.destroyed=this.destroyed;return to}}const gen=(suffix,blockLen,outputLen)=>wrapConstructor(()=>new Keccak(blockLen,suffix,outputLen));const keccak_256=gen(1,136,256/8);let locked$3=false;const _keccak256=function(data){return keccak_256(data)};let __keccak256=_keccak256;function keccak256(_data){const data=getBytes(_data,"data");return hexlify(__keccak256(data))}keccak256._=_keccak256;keccak256.lock=function(){locked$3=true};keccak256.register=function(func){if(locked$3){throw new TypeError("keccak256 is locked")}__keccak256=func};Object.freeze(keccak256);const Rho=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]);const Id=Uint8Array.from({length:16},(_,i)=>i);const Pi=Id.map(i=>(9*i+5)%16);let idxL=[Id];let idxR=[Pi];for(let i=0;i<4;i++)for(let j of[idxL,idxR])j.push(j[i].map(k=>Rho[k]));const shifts=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(i=>new Uint8Array(i));const shiftsL=idxL.map((idx,i)=>idx.map(j=>shifts[i][j]));const shiftsR=idxR.map((idx,i)=>idx.map(j=>shifts[i][j]));const Kl=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]);const Kr=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);const rotl$1=(word,shift)=>word<>>32-shift;function f(group,x,y,z){if(group===0)return x^y^z;else if(group===1)return x&y|~x&z;else if(group===2)return(x|~y)^z;else if(group===3)return x&z|y&~z;else return x^(y|~z)}const BUF=new Uint32Array(16);class RIPEMD160 extends SHA2{constructor(){super(64,20,8,true);this.h0=1732584193|0;this.h1=4023233417|0;this.h2=2562383102|0;this.h3=271733878|0;this.h4=3285377520|0}get(){const{h0,h1,h2,h3,h4}=this;return[h0,h1,h2,h3,h4]}set(h0,h1,h2,h3,h4){this.h0=h0|0;this.h1=h1|0;this.h2=h2|0;this.h3=h3|0;this.h4=h4|0}process(view,offset){for(let i=0;i<16;i++,offset+=4)BUF[i]=view.getUint32(offset,true);let al=this.h0|0,ar=al,bl=this.h1|0,br=bl,cl=this.h2|0,cr=cl,dl=this.h3|0,dr=dl,el=this.h4|0,er=el;for(let group=0;group<5;group++){const rGroup=4-group;const hbl=Kl[group],hbr=Kr[group];const rl=idxL[group],rr=idxR[group];const sl=shiftsL[group],sr=shiftsR[group];for(let i=0;i<16;i++){const tl=rotl$1(al+f(group,bl,cl,dl)+BUF[rl[i]]+hbl,sl[i])+el|0;al=el,el=dl,dl=rotl$1(cl,10)|0,cl=bl,bl=tl}for(let i=0;i<16;i++){const tr=rotl$1(ar+f(rGroup,br,cr,dr)+BUF[rr[i]]+hbr,sr[i])+er|0;ar=er,er=dr,dr=rotl$1(cr,10)|0,cr=br,br=tr}}this.set(this.h1+cl+dr|0,this.h2+dl+er|0,this.h3+el+ar|0,this.h4+al+br|0,this.h0+bl+cr|0)}roundClean(){BUF.fill(0)}destroy(){this.destroyed=true;this.buffer.fill(0);this.set(0,0,0,0,0)}}const ripemd160$1=wrapConstructor(()=>new RIPEMD160);let locked$2=false;const _ripemd160=function(data){return ripemd160$1(data)};let __ripemd160=_ripemd160;function ripemd160(_data){const data=getBytes(_data,"data");return hexlify(__ripemd160(data))}ripemd160._=_ripemd160;ripemd160.lock=function(){locked$2=true};ripemd160.register=function(func){if(locked$2){throw new TypeError("ripemd160 is locked")}__ripemd160=func};Object.freeze(ripemd160);let locked$1=false;const _pbkdf2=function(password,salt,iterations,keylen,algo){return pbkdf2Sync(password,salt,iterations,keylen,algo)};let __pbkdf2=_pbkdf2;function pbkdf2(_password,_salt,iterations,keylen,algo){const password=getBytes(_password,"password");const salt=getBytes(_salt,"salt");return hexlify(__pbkdf2(password,salt,iterations,keylen,algo))}pbkdf2._=_pbkdf2;pbkdf2.lock=function(){locked$1=true};pbkdf2.register=function(func){if(locked$1){throw new Error("pbkdf2 is locked")}__pbkdf2=func};Object.freeze(pbkdf2);let locked=false;const _randomBytes=function(length){return new Uint8Array(randomBytes$1(length))};let __randomBytes=_randomBytes;function randomBytes(length){return __randomBytes(length)}randomBytes._=_randomBytes;randomBytes.lock=function(){locked=true};randomBytes.register=function(func){if(locked){throw new Error("randomBytes is locked")}__randomBytes=func};Object.freeze(randomBytes);const rotl=(a,b)=>a<>>32-b;function XorAndSalsa(prev,pi,input,ii,out,oi){let y00=prev[pi++]^input[ii++],y01=prev[pi++]^input[ii++];let y02=prev[pi++]^input[ii++],y03=prev[pi++]^input[ii++];let y04=prev[pi++]^input[ii++],y05=prev[pi++]^input[ii++];let y06=prev[pi++]^input[ii++],y07=prev[pi++]^input[ii++];let y08=prev[pi++]^input[ii++],y09=prev[pi++]^input[ii++];let y10=prev[pi++]^input[ii++],y11=prev[pi++]^input[ii++];let y12=prev[pi++]^input[ii++],y13=prev[pi++]^input[ii++];let y14=prev[pi++]^input[ii++],y15=prev[pi++]^input[ii++];let x00=y00,x01=y01,x02=y02,x03=y03,x04=y04,x05=y05,x06=y06,x07=y07,x08=y08,x09=y09,x10=y10,x11=y11,x12=y12,x13=y13,x14=y14,x15=y15;for(let i=0;i<8;i+=2){x04^=rotl(x00+x12|0,7);x08^=rotl(x04+x00|0,9);x12^=rotl(x08+x04|0,13);x00^=rotl(x12+x08|0,18);x09^=rotl(x05+x01|0,7);x13^=rotl(x09+x05|0,9);x01^=rotl(x13+x09|0,13);x05^=rotl(x01+x13|0,18);x14^=rotl(x10+x06|0,7);x02^=rotl(x14+x10|0,9);x06^=rotl(x02+x14|0,13);x10^=rotl(x06+x02|0,18);x03^=rotl(x15+x11|0,7);x07^=rotl(x03+x15|0,9);x11^=rotl(x07+x03|0,13);x15^=rotl(x11+x07|0,18);x01^=rotl(x00+x03|0,7);x02^=rotl(x01+x00|0,9);x03^=rotl(x02+x01|0,13);x00^=rotl(x03+x02|0,18);x06^=rotl(x05+x04|0,7);x07^=rotl(x06+x05|0,9);x04^=rotl(x07+x06|0,13);x05^=rotl(x04+x07|0,18);x11^=rotl(x10+x09|0,7);x08^=rotl(x11+x10|0,9);x09^=rotl(x08+x11|0,13);x10^=rotl(x09+x08|0,18);x12^=rotl(x15+x14|0,7);x13^=rotl(x12+x15|0,9);x14^=rotl(x13+x12|0,13);x15^=rotl(x14+x13|0,18)}out[oi++]=y00+x00|0;out[oi++]=y01+x01|0;out[oi++]=y02+x02|0;out[oi++]=y03+x03|0;out[oi++]=y04+x04|0;out[oi++]=y05+x05|0;out[oi++]=y06+x06|0;out[oi++]=y07+x07|0;out[oi++]=y08+x08|0;out[oi++]=y09+x09|0;out[oi++]=y10+x10|0;out[oi++]=y11+x11|0;out[oi++]=y12+x12|0;out[oi++]=y13+x13|0;out[oi++]=y14+x14|0;out[oi++]=y15+x15|0}function BlockMix(input,ii,out,oi,r){let head=oi+0;let tail=oi+16*r;for(let i=0;i<16;i++)out[tail+i]=input[ii+(2*r-1)*16+i];for(let i=0;i0)tail+=16;XorAndSalsa(out,head,input,ii+=16,out,tail)}}function scryptInit(password,salt,_opts){const opts=checkOpts({dkLen:32,asyncTick:10,maxmem:1024**3+1024},_opts);const{N,r,p,dkLen,asyncTick,maxmem,onProgress}=opts;number(N);number(r);number(p);number(dkLen);number(asyncTick);number(maxmem);if(onProgress!==undefined&&typeof onProgress!=="function")throw new Error("progressCb should be function");const blockSize=128*r;const blockSize32=blockSize/4;if(N<=1||(N&N-1)!==0||N>=2**(blockSize/8)||N>2**32){throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32")}if(p<0||p>(2**32-1)*32/blockSize){throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)")}if(dkLen<0||dkLen>(2**32-1)*32){throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32")}const memUsed=blockSize*(N+p);if(memUsed>maxmem){throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`)}const B=pbkdf2$1(sha256$1,password,salt,{c:1,dkLen:blockSize*p});const B32=u32(B);const V=u32(new Uint8Array(blockSize*N));const tmp=u32(new Uint8Array(blockSize));let blockMixCb=()=>{};if(onProgress){const totalBlockMix=2*N*p;const callbackPer=Math.max(Math.floor(totalBlockMix/1e4),1);let blockMixCnt=0;blockMixCb=()=>{blockMixCnt++;if(onProgress&&(!(blockMixCnt%callbackPer)||blockMixCnt===totalBlockMix))onProgress(blockMixCnt/totalBlockMix)}}return{N:N,r:r,p:p,dkLen:dkLen,blockSize32:blockSize32,V:V,B32:B32,B:B,tmp:tmp,blockMixCb:blockMixCb,asyncTick:asyncTick}}function scryptOutput(password,dkLen,B,V,tmp){const res=pbkdf2$1(sha256$1,password,B,{c:1,dkLen:dkLen});B.fill(0);V.fill(0);tmp.fill(0);return res}function scrypt$1(password,salt,opts){const{N,r,p,dkLen,blockSize32,V,B32,B,tmp,blockMixCb}=scryptInit(password,salt,opts);for(let pi=0;pi{BlockMix(V,pos,V,pos+=blockSize32,r);blockMixCb()});BlockMix(V,(N-1)*blockSize32,B32,Pi,r);blockMixCb();await asyncLoop(N,asyncTick,()=>{const j=B32[Pi+blockSize32-16]%N;for(let k=0;ka instanceof Uint8Array;const hexes=Array.from({length:256},(_,i)=>i.toString(16).padStart(2,"0"));function bytesToHex(bytes){if(!u8a(bytes))throw new Error("Uint8Array expected");let hex="";for(let i=0;isum+a.length,0));let pad=0;arrays.forEach(a=>{if(!u8a(a))throw new Error("Uint8Array expected");r.set(a,pad);pad+=a.length});return r}function equalBytes(b1,b2){if(b1.length!==b2.length)return false;for(let i=0;i_0n$5;n>>=_1n$5,len+=1);return len}function bitGet(n,pos){return n>>BigInt(pos)&_1n$5}const bitSet=(n,pos,value)=>{return n|(value?_1n$5:_0n$5)<(_2n$3<new Uint8Array(data);const u8fr=arr=>Uint8Array.from(arr);function createHmacDrbg(hashLen,qByteLen,hmacFn){if(typeof hashLen!=="number"||hashLen<2)throw new Error("hashLen must be a number");if(typeof qByteLen!=="number"||qByteLen<2)throw new Error("qByteLen must be a number");if(typeof hmacFn!=="function")throw new Error("hmacFn must be a function");let v=u8n(hashLen);let k=u8n(hashLen);let i=0;const reset=()=>{v.fill(1);k.fill(0);i=0};const h=(...b)=>hmacFn(k,v,...b);const reseed=(seed=u8n())=>{k=h(u8fr([0]),seed);v=h();if(seed.length===0)return;k=h(u8fr([1]),seed);v=h()};const gen=()=>{if(i++>=1e3)throw new Error("drbg: tried 1000 values");let len=0;const out=[];while(len{reset();reseed(seed);let res=undefined;while(!(res=pred(gen())))reseed();reset();return res};return genUntil}const validatorFns={bigint:val=>typeof val==="bigint",function:val=>typeof val==="function",boolean:val=>typeof val==="boolean",string:val=>typeof val==="string",stringOrUint8Array:val=>typeof val==="string"||val instanceof Uint8Array,isSafeInteger:val=>Number.isSafeInteger(val),array:val=>Array.isArray(val),field:(val,object)=>object.Fp.isValid(val),hash:val=>typeof val==="function"&&Number.isSafeInteger(val.outputLen)};function validateObject(object,validators,optValidators={}){const checkField=(fieldName,type,isOptional)=>{const checkVal=validatorFns[type];if(typeof checkVal!=="function")throw new Error(`Invalid validator "${type}", expected function`);const val=object[fieldName];if(isOptional&&val===undefined)return;if(!checkVal(val,object)){throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`)}};for(const[fieldName,type]of Object.entries(validators))checkField(fieldName,type,false);for(const[fieldName,type]of Object.entries(optValidators))checkField(fieldName,type,true);return object}var ut=Object.freeze({__proto__:null,bitGet:bitGet,bitLen:bitLen,bitMask:bitMask,bitSet:bitSet,bytesToHex:bytesToHex,bytesToNumberBE:bytesToNumberBE,bytesToNumberLE:bytesToNumberLE,concatBytes:concatBytes,createHmacDrbg:createHmacDrbg,ensureBytes:ensureBytes,equalBytes:equalBytes,hexToBytes:hexToBytes,hexToNumber:hexToNumber,numberToBytesBE:numberToBytesBE,numberToBytesLE:numberToBytesLE,numberToHexUnpadded:numberToHexUnpadded,numberToVarBytesBE:numberToVarBytesBE,utf8ToBytes:utf8ToBytes,validateObject:validateObject});const _0n$4=BigInt(0),_1n$4=BigInt(1),_2n$2=BigInt(2),_3n$2=BigInt(3);const _4n=BigInt(4),_5n$1=BigInt(5),_8n=BigInt(8);BigInt(9);BigInt(16);function mod(a,b){const result=a%b;return result>=_0n$4?result:b+result}function pow(num,power,modulo){if(modulo<=_0n$4||power<_0n$4)throw new Error("Expected power/modulo > 0");if(modulo===_1n$4)return _0n$4;let res=_1n$4;while(power>_0n$4){if(power&_1n$4)res=res*num%modulo;num=num*num%modulo;power>>=_1n$4}return res}function pow2(x,power,modulo){let res=x;while(power-- >_0n$4){res*=res;res%=modulo}return res}function invert(number,modulo){if(number===_0n$4||modulo<=_0n$4){throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`)}let a=mod(number,modulo);let b=modulo;let x=_0n$4,u=_1n$4;while(a!==_0n$4){const q=b/a;const r=b%a;const m=x-u*q;b=a,a=r,x=u,u=m}const gcd=b;if(gcd!==_1n$4)throw new Error("invert: does not exist");return mod(x,modulo)}function tonelliShanks(P){const legendreC=(P-_1n$4)/_2n$2;let Q,S,Z;for(Q=P-_1n$4,S=0;Q%_2n$2===_0n$4;Q/=_2n$2,S++);for(Z=_2n$2;Z{map[val]="function";return map},initial);return validateObject(field,opts)}function FpPow(f,num,power){if(power<_0n$4)throw new Error("Expected power > 0");if(power===_0n$4)return f.ONE;if(power===_1n$4)return num;let p=f.ONE;let d=num;while(power>_0n$4){if(power&_1n$4)p=f.mul(p,d);d=f.sqr(d);power>>=_1n$4}return p}function FpInvertBatch(f,nums){const tmp=new Array(nums.length);const lastMultiplied=nums.reduce((acc,num,i)=>{if(f.is0(num))return acc;tmp[i]=acc;return f.mul(acc,num)},f.ONE);const inverted=f.inv(lastMultiplied);nums.reduceRight((acc,num,i)=>{if(f.is0(num))return acc;tmp[i]=f.mul(acc,tmp[i]);return f.mul(acc,num)},inverted);return tmp}function nLength(n,nBitLength){const _nBitLength=nBitLength!==undefined?nBitLength:n.toString(2).length;const nByteLength=Math.ceil(_nBitLength/8);return{nBitLength:_nBitLength,nByteLength:nByteLength}}function Field(ORDER,bitLen,isLE=false,redef={}){if(ORDER<=_0n$4)throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);const{nBitLength:BITS,nByteLength:BYTES}=nLength(ORDER,bitLen);if(BYTES>2048)throw new Error("Field lengths over 2048 bytes are not supported");const sqrtP=FpSqrt(ORDER);const f=Object.freeze({ORDER:ORDER,BITS:BITS,BYTES:BYTES,MASK:bitMask(BITS),ZERO:_0n$4,ONE:_1n$4,create:num=>mod(num,ORDER),isValid:num=>{if(typeof num!=="bigint")throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);return _0n$4<=num&&numnum===_0n$4,isOdd:num=>(num&_1n$4)===_1n$4,neg:num=>mod(-num,ORDER),eql:(lhs,rhs)=>lhs===rhs,sqr:num=>mod(num*num,ORDER),add:(lhs,rhs)=>mod(lhs+rhs,ORDER),sub:(lhs,rhs)=>mod(lhs-rhs,ORDER),mul:(lhs,rhs)=>mod(lhs*rhs,ORDER),pow:(num,power)=>FpPow(f,num,power),div:(lhs,rhs)=>mod(lhs*invert(rhs,ORDER),ORDER),sqrN:num=>num*num,addN:(lhs,rhs)=>lhs+rhs,subN:(lhs,rhs)=>lhs-rhs,mulN:(lhs,rhs)=>lhs*rhs,inv:num=>invert(num,ORDER),sqrt:redef.sqrt||(n=>sqrtP(f,n)),invertBatch:lst=>FpInvertBatch(f,lst),cmov:(a,b,c)=>c?b:a,toBytes:num=>isLE?numberToBytesLE(num,BYTES):numberToBytesBE(num,BYTES),fromBytes:bytes=>{if(bytes.length!==BYTES)throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);return isLE?bytesToNumberLE(bytes):bytesToNumberBE(bytes)}});return Object.freeze(f)}function getFieldBytesLength(fieldOrder){if(typeof fieldOrder!=="bigint")throw new Error("field order must be bigint");const bitLength=fieldOrder.toString(2).length;return Math.ceil(bitLength/8)}function getMinHashLength(fieldOrder){const length=getFieldBytesLength(fieldOrder);return length+Math.ceil(length/2)}function mapHashToField(key,fieldOrder,isLE=false){const len=key.length;const fieldLen=getFieldBytesLength(fieldOrder);const minLen=getMinHashLength(fieldOrder);if(len<16||len1024)throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);const num=isLE?bytesToNumberBE(key):bytesToNumberLE(key);const reduced=mod(num,fieldOrder-_1n$4)+_1n$4;return isLE?numberToBytesLE(reduced,fieldLen):numberToBytesBE(reduced,fieldLen)}const _0n$3=BigInt(0);const _1n$3=BigInt(1);function wNAF(c,bits){const constTimeNegate=(condition,item)=>{const neg=item.negate();return condition?neg:item};const opts=W=>{const windows=Math.ceil(bits/W)+1;const windowSize=2**(W-1);return{windows:windows,windowSize:windowSize}};return{constTimeNegate:constTimeNegate,unsafeLadder(elm,n){let p=c.ZERO;let d=elm;while(n>_0n$3){if(n&_1n$3)p=p.add(d);d=d.double();n>>=_1n$3}return p},precomputeWindow(elm,W){const{windows,windowSize}=opts(W);const points=[];let p=elm;let base=p;for(let window=0;window>=shiftBy;if(wbits>windowSize){wbits-=maxNumber;n+=_1n$3}const offset1=offset;const offset2=offset+Math.abs(wbits)-1;const cond1=window%2!==0;const cond2=wbits<0;if(wbits===0){f=f.add(constTimeNegate(cond1,precomputes[offset1]))}else{p=p.add(constTimeNegate(cond2,precomputes[offset2]))}}return{p:p,f:f}},wNAFCached(P,precomputesMap,n,transform){const W=P._WINDOW_SIZE||1;let comp=precomputesMap.get(P);if(!comp){comp=this.precomputeWindow(P,W);if(W!==1){precomputesMap.set(P,transform(comp))}}return this.wNAF(W,comp,n)}}}function validateBasic(curve){validateField(curve.Fp);validateObject(curve,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"});return Object.freeze({...nLength(curve.n,curve.nBitLength),...curve,...{p:curve.Fp.ORDER}})}function validatePointOpts(curve){const opts=validateBasic(curve);validateObject(opts,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo,Fp,a}=opts;if(endo){if(!Fp.eql(a,Fp.ZERO)){throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0")}if(typeof endo!=="object"||typeof endo.beta!=="bigint"||typeof endo.splitScalar!=="function"){throw new Error("Expected endomorphism with beta: bigint and splitScalar: function")}}return Object.freeze({...opts})}const{bytesToNumberBE:b2n,hexToBytes:h2b}=ut;const DER={Err:class DERErr extends Error{constructor(m=""){super(m)}},_parseInt(data){const{Err:E}=DER;if(data.length<2||data[0]!==2)throw new E("Invalid signature integer tag");const len=data[1];const res=data.subarray(2,len+2);if(!len||res.length!==len)throw new E("Invalid signature integer: wrong length");if(res[0]&128)throw new E("Invalid signature integer: negative");if(res[0]===0&&!(res[1]&128))throw new E("Invalid signature integer: unnecessary leading zero");return{d:b2n(res),l:data.subarray(len+2)}},toSig(hex){const{Err:E}=DER;const data=typeof hex==="string"?h2b(hex):hex;if(!(data instanceof Uint8Array))throw new Error("ui8a expected");let l=data.length;if(l<2||data[0]!=48)throw new E("Invalid signature tag");if(data[1]!==l-2)throw new E("Invalid signature: incorrect length");const{d:r,l:sBytes}=DER._parseInt(data.subarray(2));const{d:s,l:rBytesLeft}=DER._parseInt(sBytes);if(rBytesLeft.length)throw new E("Invalid signature: left bytes after parsing");return{r:r,s:s}},hexFromSig(sig){const slice=s=>Number.parseInt(s[0],16)&8?"00"+s:s;const h=num=>{const hex=num.toString(16);return hex.length&1?`0${hex}`:hex};const s=slice(h(sig.s));const r=slice(h(sig.r));const shl=s.length/2;const rhl=r.length/2;const sl=h(shl);const rl=h(rhl);return`30${h(rhl+shl+4)}02${rl}${r}02${sl}${s}`}};const _0n$2=BigInt(0),_1n$2=BigInt(1);BigInt(2);const _3n$1=BigInt(3);BigInt(4);function weierstrassPoints(opts){const CURVE=validatePointOpts(opts);const{Fp}=CURVE;const toBytes=CURVE.toBytes||((_c,point,_isCompressed)=>{const a=point.toAffine();return concatBytes(Uint8Array.from([4]),Fp.toBytes(a.x),Fp.toBytes(a.y))});const fromBytes=CURVE.fromBytes||(bytes=>{const tail=bytes.subarray(1);const x=Fp.fromBytes(tail.subarray(0,Fp.BYTES));const y=Fp.fromBytes(tail.subarray(Fp.BYTES,2*Fp.BYTES));return{x:x,y:y}});function weierstrassEquation(x){const{a,b}=CURVE;const x2=Fp.sqr(x);const x3=Fp.mul(x2,x);return Fp.add(Fp.add(x3,Fp.mul(x,a)),b)}if(!Fp.eql(Fp.sqr(CURVE.Gy),weierstrassEquation(CURVE.Gx)))throw new Error("bad generator point: equation left != right");function isWithinCurveOrder(num){return typeof num==="bigint"&&_0n$2Fp.eql(i,Fp.ZERO);if(is0(x)&&is0(y))return Point.ZERO;return new Point(x,y,Fp.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(points){const toInv=Fp.invertBatch(points.map(p=>p.pz));return points.map((p,i)=>p.toAffine(toInv[i])).map(Point.fromAffine)}static fromHex(hex){const P=Point.fromAffine(fromBytes(ensureBytes("pointHex",hex)));P.assertValidity();return P}static fromPrivateKey(privateKey){return Point.BASE.multiply(normPrivateKeyToScalar(privateKey))}_setWindowSize(windowSize){this._WINDOW_SIZE=windowSize;pointPrecomputes.delete(this)}assertValidity(){if(this.is0()){if(CURVE.allowInfinityPoint&&!Fp.is0(this.py))return;throw new Error("bad point: ZERO")}const{x,y}=this.toAffine();if(!Fp.isValid(x)||!Fp.isValid(y))throw new Error("bad point: x or y not FE");const left=Fp.sqr(y);const right=weierstrassEquation(x);if(!Fp.eql(left,right))throw new Error("bad point: equation left != right");if(!this.isTorsionFree())throw new Error("bad point: not in prime-order subgroup")}hasEvenY(){const{y}=this.toAffine();if(Fp.isOdd)return!Fp.isOdd(y);throw new Error("Field doesn't support isOdd")}equals(other){assertPrjPoint(other);const{px:X1,py:Y1,pz:Z1}=this;const{px:X2,py:Y2,pz:Z2}=other;const U1=Fp.eql(Fp.mul(X1,Z2),Fp.mul(X2,Z1));const U2=Fp.eql(Fp.mul(Y1,Z2),Fp.mul(Y2,Z1));return U1&&U2}negate(){return new Point(this.px,Fp.neg(this.py),this.pz)}double(){const{a,b}=CURVE;const b3=Fp.mul(b,_3n$1);const{px:X1,py:Y1,pz:Z1}=this;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;let t0=Fp.mul(X1,X1);let t1=Fp.mul(Y1,Y1);let t2=Fp.mul(Z1,Z1);let t3=Fp.mul(X1,Y1);t3=Fp.add(t3,t3);Z3=Fp.mul(X1,Z1);Z3=Fp.add(Z3,Z3);X3=Fp.mul(a,Z3);Y3=Fp.mul(b3,t2);Y3=Fp.add(X3,Y3);X3=Fp.sub(t1,Y3);Y3=Fp.add(t1,Y3);Y3=Fp.mul(X3,Y3);X3=Fp.mul(t3,X3);Z3=Fp.mul(b3,Z3);t2=Fp.mul(a,t2);t3=Fp.sub(t0,t2);t3=Fp.mul(a,t3);t3=Fp.add(t3,Z3);Z3=Fp.add(t0,t0);t0=Fp.add(Z3,t0);t0=Fp.add(t0,t2);t0=Fp.mul(t0,t3);Y3=Fp.add(Y3,t0);t2=Fp.mul(Y1,Z1);t2=Fp.add(t2,t2);t0=Fp.mul(t2,t3);X3=Fp.sub(X3,t0);Z3=Fp.mul(t2,t1);Z3=Fp.add(Z3,Z3);Z3=Fp.add(Z3,Z3);return new Point(X3,Y3,Z3)}add(other){assertPrjPoint(other);const{px:X1,py:Y1,pz:Z1}=this;const{px:X2,py:Y2,pz:Z2}=other;let X3=Fp.ZERO,Y3=Fp.ZERO,Z3=Fp.ZERO;const a=CURVE.a;const b3=Fp.mul(CURVE.b,_3n$1);let t0=Fp.mul(X1,X2);let t1=Fp.mul(Y1,Y2);let t2=Fp.mul(Z1,Z2);let t3=Fp.add(X1,Y1);let t4=Fp.add(X2,Y2);t3=Fp.mul(t3,t4);t4=Fp.add(t0,t1);t3=Fp.sub(t3,t4);t4=Fp.add(X1,Z1);let t5=Fp.add(X2,Z2);t4=Fp.mul(t4,t5);t5=Fp.add(t0,t2);t4=Fp.sub(t4,t5);t5=Fp.add(Y1,Z1);X3=Fp.add(Y2,Z2);t5=Fp.mul(t5,X3);X3=Fp.add(t1,t2);t5=Fp.sub(t5,X3);Z3=Fp.mul(a,t4);X3=Fp.mul(b3,t2);Z3=Fp.add(X3,Z3);X3=Fp.sub(t1,Z3);Z3=Fp.add(t1,Z3);Y3=Fp.mul(X3,Z3);t1=Fp.add(t0,t0);t1=Fp.add(t1,t0);t2=Fp.mul(a,t2);t4=Fp.mul(b3,t4);t1=Fp.add(t1,t2);t2=Fp.sub(t0,t2);t2=Fp.mul(a,t2);t4=Fp.add(t4,t2);t0=Fp.mul(t1,t4);Y3=Fp.add(Y3,t0);t0=Fp.mul(t5,t4);X3=Fp.mul(t3,X3);X3=Fp.sub(X3,t0);t0=Fp.mul(t3,t1);Z3=Fp.mul(t5,Z3);Z3=Fp.add(Z3,t0);return new Point(X3,Y3,Z3)}subtract(other){return this.add(other.negate())}is0(){return this.equals(Point.ZERO)}wNAF(n){return wnaf.wNAFCached(this,pointPrecomputes,n,comp=>{const toInv=Fp.invertBatch(comp.map(p=>p.pz));return comp.map((p,i)=>p.toAffine(toInv[i])).map(Point.fromAffine)})}multiplyUnsafe(n){const I=Point.ZERO;if(n===_0n$2)return I;assertGE(n);if(n===_1n$2)return this;const{endo}=CURVE;if(!endo)return wnaf.unsafeLadder(this,n);let{k1neg,k1,k2neg,k2}=endo.splitScalar(n);let k1p=I;let k2p=I;let d=this;while(k1>_0n$2||k2>_0n$2){if(k1&_1n$2)k1p=k1p.add(d);if(k2&_1n$2)k2p=k2p.add(d);d=d.double();k1>>=_1n$2;k2>>=_1n$2}if(k1neg)k1p=k1p.negate();if(k2neg)k2p=k2p.negate();k2p=new Point(Fp.mul(k2p.px,endo.beta),k2p.py,k2p.pz);return k1p.add(k2p)}multiply(scalar){assertGE(scalar);let n=scalar;let point,fake;const{endo}=CURVE;if(endo){const{k1neg,k1,k2neg,k2}=endo.splitScalar(n);let{p:k1p,f:f1p}=this.wNAF(k1);let{p:k2p,f:f2p}=this.wNAF(k2);k1p=wnaf.constTimeNegate(k1neg,k1p);k2p=wnaf.constTimeNegate(k2neg,k2p);k2p=new Point(Fp.mul(k2p.px,endo.beta),k2p.py,k2p.pz);point=k1p.add(k2p);fake=f1p.add(f2p)}else{const{p,f}=this.wNAF(n);point=p;fake=f}return Point.normalizeZ([point,fake])[0]}multiplyAndAddUnsafe(Q,a,b){const G=Point.BASE;const mul=(P,a)=>a===_0n$2||a===_1n$2||!P.equals(G)?P.multiplyUnsafe(a):P.multiply(a);const sum=mul(this,a).add(mul(Q,b));return sum.is0()?undefined:sum}toAffine(iz){const{px:x,py:y,pz:z}=this;const is0=this.is0();if(iz==null)iz=is0?Fp.ONE:Fp.inv(z);const ax=Fp.mul(x,iz);const ay=Fp.mul(y,iz);const zz=Fp.mul(z,iz);if(is0)return{x:Fp.ZERO,y:Fp.ZERO};if(!Fp.eql(zz,Fp.ONE))throw new Error("invZ was invalid");return{x:ax,y:ay}}isTorsionFree(){const{h:cofactor,isTorsionFree}=CURVE;if(cofactor===_1n$2)return true;if(isTorsionFree)return isTorsionFree(Point,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:cofactor,clearCofactor}=CURVE;if(cofactor===_1n$2)return this;if(clearCofactor)return clearCofactor(Point,this);return this.multiplyUnsafe(CURVE.h)}toRawBytes(isCompressed=true){this.assertValidity();return toBytes(Point,this,isCompressed)}toHex(isCompressed=true){return bytesToHex(this.toRawBytes(isCompressed))}}Point.BASE=new Point(CURVE.Gx,CURVE.Gy,Fp.ONE);Point.ZERO=new Point(Fp.ZERO,Fp.ONE,Fp.ZERO);const _bits=CURVE.nBitLength;const wnaf=wNAF(Point,CURVE.endo?Math.ceil(_bits/2):_bits);return{CURVE:CURVE,ProjectivePoint:Point,normPrivateKeyToScalar:normPrivateKeyToScalar,weierstrassEquation:weierstrassEquation,isWithinCurveOrder:isWithinCurveOrder}}function validateOpts(curve){const opts=validateBasic(curve);validateObject(opts,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"});return Object.freeze({lowS:true,...opts})}function weierstrass(curveDef){const CURVE=validateOpts(curveDef);const{Fp,n:CURVE_ORDER}=CURVE;const compressedLen=Fp.BYTES+1;const uncompressedLen=2*Fp.BYTES+1;function isValidFieldElement(num){return _0n$2bytesToHex(numberToBytesBE(num,CURVE.nByteLength));function isBiggerThanHalfOrder(number){const HALF=CURVE_ORDER>>_1n$2;return number>HALF}function normalizeS(s){return isBiggerThanHalfOrder(s)?modN(-s):s}const slcNum=(b,from,to)=>bytesToNumberBE(b.slice(from,to));class Signature{constructor(r,s,recovery){this.r=r;this.s=s;this.recovery=recovery;this.assertValidity()}static fromCompact(hex){const l=CURVE.nByteLength;hex=ensureBytes("compactSignature",hex,l*2);return new Signature(slcNum(hex,0,l),slcNum(hex,l,2*l))}static fromDER(hex){const{r,s}=DER.toSig(ensureBytes("DER",hex));return new Signature(r,s)}assertValidity(){if(!isWithinCurveOrder(this.r))throw new Error("r must be 0 < r < CURVE.n");if(!isWithinCurveOrder(this.s))throw new Error("s must be 0 < s < CURVE.n")}addRecoveryBit(recovery){return new Signature(this.r,this.s,recovery)}recoverPublicKey(msgHash){const{r,s,recovery:rec}=this;const h=bits2int_modN(ensureBytes("msgHash",msgHash));if(rec==null||![0,1,2,3].includes(rec))throw new Error("recovery id invalid");const radj=rec===2||rec===3?r+CURVE.n:r;if(radj>=Fp.ORDER)throw new Error("recovery id 2 or 3 invalid");const prefix=(rec&1)===0?"02":"03";const R=Point.fromHex(prefix+numToNByteStr(radj));const ir=invN(radj);const u1=modN(-h*ir);const u2=modN(s*ir);const Q=Point.BASE.multiplyAndAddUnsafe(R,u1,u2);if(!Q)throw new Error("point at infinify");Q.assertValidity();return Q}hasHighS(){return isBiggerThanHalfOrder(this.s)}normalizeS(){return this.hasHighS()?new Signature(this.r,modN(-this.s),this.recovery):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){return DER.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numToNByteStr(this.r)+numToNByteStr(this.s)}}const utils={isValidPrivateKey(privateKey){try{normPrivateKeyToScalar(privateKey);return true}catch(error){return false}},normPrivateKeyToScalar:normPrivateKeyToScalar,randomPrivateKey:()=>{const length=getMinHashLength(CURVE.n);return mapHashToField(CURVE.randomBytes(length),CURVE.n)},precompute(windowSize=8,point=Point.BASE){point._setWindowSize(windowSize);point.multiply(BigInt(3));return point}};function getPublicKey(privateKey,isCompressed=true){return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed)}function isProbPub(item){const arr=item instanceof Uint8Array;const str=typeof item==="string";const len=(arr||str)&&item.length;if(arr)return len===compressedLen||len===uncompressedLen;if(str)return len===2*compressedLen||len===2*uncompressedLen;if(item instanceof Point)return true;return false}function getSharedSecret(privateA,publicB,isCompressed=true){if(isProbPub(privateA))throw new Error("first arg must be private key");if(!isProbPub(publicB))throw new Error("second arg must be public key");const b=Point.fromHex(publicB);return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed)}const bits2int=CURVE.bits2int||function(bytes){const num=bytesToNumberBE(bytes);const delta=bytes.length*8-CURVE.nBitLength;return delta>0?num>>BigInt(delta):num};const bits2int_modN=CURVE.bits2int_modN||function(bytes){return modN(bits2int(bytes))};const ORDER_MASK=bitMask(CURVE.nBitLength);function int2octets(num){if(typeof num!=="bigint")throw new Error("bigint expected");if(!(_0n$2<=num&&numk in opts))throw new Error("sign() legacy options not supported");const{hash,randomBytes}=CURVE;let{lowS,prehash,extraEntropy:ent}=opts;if(lowS==null)lowS=true;msgHash=ensureBytes("msgHash",msgHash);if(prehash)msgHash=ensureBytes("prehashed msgHash",hash(msgHash));const h1int=bits2int_modN(msgHash);const d=normPrivateKeyToScalar(privateKey);const seedArgs=[int2octets(d),int2octets(h1int)];if(ent!=null){const e=ent===true?randomBytes(Fp.BYTES):ent;seedArgs.push(ensureBytes("extraEntropy",e))}const seed=concatBytes(...seedArgs);const m=h1int;function k2sig(kBytes){const k=bits2int(kBytes);if(!isWithinCurveOrder(k))return;const ik=invN(k);const q=Point.BASE.multiply(k).toAffine();const r=modN(q.x);if(r===_0n$2)return;const s=modN(ik*modN(m+r*d));if(s===_0n$2)return;let recovery=(q.x===r?0:2)|Number(q.y&_1n$2);let normS=s;if(lowS&&isBiggerThanHalfOrder(s)){normS=normalizeS(s);recovery^=1}return new Signature(r,normS,recovery)}return{seed:seed,k2sig:k2sig}}const defaultSigOpts={lowS:CURVE.lowS,prehash:false};const defaultVerOpts={lowS:CURVE.lowS,prehash:false};function sign(msgHash,privKey,opts=defaultSigOpts){const{seed,k2sig}=prepSig(msgHash,privKey,opts);const C=CURVE;const drbg=createHmacDrbg(C.hash.outputLen,C.nByteLength,C.hmac);return drbg(seed,k2sig)}Point.BASE._setWindowSize(8);function verify(signature,msgHash,publicKey,opts=defaultVerOpts){const sg=signature;msgHash=ensureBytes("msgHash",msgHash);publicKey=ensureBytes("publicKey",publicKey);if("strict"in opts)throw new Error("options.strict was renamed to lowS");const{lowS,prehash}=opts;let _sig=undefined;let P;try{if(typeof sg==="string"||sg instanceof Uint8Array){try{_sig=Signature.fromDER(sg)}catch(derError){if(!(derError instanceof DER.Err))throw derError;_sig=Signature.fromCompact(sg)}}else if(typeof sg==="object"&&typeof sg.r==="bigint"&&typeof sg.s==="bigint"){const{r,s}=sg;_sig=new Signature(r,s)}else{throw new Error("PARSE")}P=Point.fromHex(publicKey)}catch(error){if(error.message==="PARSE")throw new Error(`signature must be Signature instance, Uint8Array or hex string`);return false}if(lowS&&_sig.hasHighS())return false;if(prehash)msgHash=CURVE.hash(msgHash);const{r,s}=_sig;const h=bits2int_modN(msgHash);const is=invN(s);const u1=modN(h*is);const u2=modN(r*is);const R=Point.BASE.multiplyAndAddUnsafe(P,u1,u2)?.toAffine();if(!R)return false;const v=modN(R.x);return v===r}return{CURVE:CURVE,getPublicKey:getPublicKey,getSharedSecret:getSharedSecret,sign:sign,verify:verify,ProjectivePoint:Point,Signature:Signature,utils:utils}}function getHash(hash){return{hash:hash,hmac:(key,...msgs)=>hmac(hash,key,concatBytes$1(...msgs)),randomBytes:randomBytes$2}}function createCurve(curveDef,defHash){const create=hash=>weierstrass({...curveDef,...getHash(hash)});return Object.freeze({...create(defHash),create:create})}const secp256k1P=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f");const secp256k1N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const _1n$1=BigInt(1);const _2n$1=BigInt(2);const divNearest=(a,b)=>(a+b/_2n$1)/b;function sqrtMod(y){const P=secp256k1P;const _3n=BigInt(3),_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22);const _23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88);const b2=y*y*y%P;const b3=b2*b2*y%P;const b6=pow2(b3,_3n,P)*b3%P;const b9=pow2(b6,_3n,P)*b3%P;const b11=pow2(b9,_2n$1,P)*b2%P;const b22=pow2(b11,_11n,P)*b11%P;const b44=pow2(b22,_22n,P)*b22%P;const b88=pow2(b44,_44n,P)*b44%P;const b176=pow2(b88,_88n,P)*b88%P;const b220=pow2(b176,_44n,P)*b44%P;const b223=pow2(b220,_3n,P)*b3%P;const t1=pow2(b223,_23n,P)*b22%P;const t2=pow2(t1,_6n,P)*b2%P;const root=pow2(t2,_2n$1,P);if(!Fp.eql(Fp.sqr(root),y))throw new Error("Cannot find square root");return root}const Fp=Field(secp256k1P,undefined,undefined,{sqrt:sqrtMod});const secp256k1=createCurve({a:BigInt(0),b:BigInt(7),Fp:Fp,n:secp256k1N,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:true,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:k=>{const n=secp256k1N;const a1=BigInt("0x3086d221a7d46bcde86c90e49284eb15");const b1=-_1n$1*BigInt("0xe4437ed6010e88286f547fa90abfe4c3");const a2=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8");const b2=a1;const POW_2_128=BigInt("0x100000000000000000000000000000000");const c1=divNearest(b2*k,n);const c2=divNearest(-b1*k,n);let k1=mod(k-c1*a1-c2*a2,n);let k2=mod(-c1*b1-c2*b2,n);const k1neg=k1>POW_2_128;const k2neg=k2>POW_2_128;if(k1neg)k1=n-k1;if(k2neg)k2=n-k2;if(k1>POW_2_128||k2>POW_2_128){throw new Error("splitScalar: Endomorphism failed, k="+k)}return{k1neg:k1neg,k1:k1,k2neg:k2neg,k2:k2}}}},sha256$1);const _0n$1=BigInt(0);const fe=x=>typeof x==="bigint"&&_0n$1typeof x==="bigint"&&_0n$1c.charCodeAt(0)));tagP=concatBytes(tagH,tagH);TAGGED_HASH_PREFIXES[tag]=tagP}return sha256$1(concatBytes(tagP,...messages))}const pointToBytes=point=>point.toRawBytes(true).slice(1);const numTo32b=n=>numberToBytesBE(n,32);const modP=x=>mod(x,secp256k1P);const modN=x=>mod(x,secp256k1N);const Point=secp256k1.ProjectivePoint;const GmulAdd=(Q,a,b)=>Point.BASE.multiplyAndAddUnsafe(Q,a,b);function schnorrGetExtPubKey(priv){let d_=secp256k1.utils.normPrivateKeyToScalar(priv);let p=Point.fromPrivateKey(d_);const scalar=p.hasEvenY()?d_:modN(-d_);return{scalar:scalar,bytes:pointToBytes(p)}}function lift_x(x){if(!fe(x))throw new Error("bad x: need 0 < x < p");const xx=modP(x*x);const c=modP(xx*x+BigInt(7));let y=sqrtMod(c);if(y%_2n$1!==_0n$1)y=modP(-y);const p=new Point(x,y,_1n$1);p.assertValidity();return p}function challenge(...args){return modN(bytesToNumberBE(taggedHash$1("BIP0340/challenge",...args)))}function schnorrGetPublicKey(privateKey){return schnorrGetExtPubKey(privateKey).bytes}function schnorrSign(message,privateKey,auxRand=randomBytes$2(32)){const m=ensureBytes("message",message);const{bytes:px,scalar:d}=schnorrGetExtPubKey(privateKey);const a=ensureBytes("auxRand",auxRand,32);const t=numTo32b(d^bytesToNumberBE(taggedHash$1("BIP0340/aux",a)));const rand=taggedHash$1("BIP0340/nonce",t,px,m);const k_=modN(bytesToNumberBE(rand));if(k_===_0n$1)throw new Error("sign failed: k is zero");const{bytes:rx,scalar:k}=schnorrGetExtPubKey(k_);const e=challenge(rx,px,m);const sig=new Uint8Array(64);sig.set(rx,0);sig.set(numTo32b(modN(k+e*d)),32);if(!schnorrVerify(sig,m,px))throw new Error("sign: Invalid signature produced");return sig}function schnorrVerify(signature,message,publicKey){const sig=ensureBytes("signature",signature,64);const m=ensureBytes("message",message);const pub=ensureBytes("publicKey",publicKey,32);try{const P=lift_x(bytesToNumberBE(pub));const r=bytesToNumberBE(sig.subarray(0,32));if(!fe(r))return false;const s=bytesToNumberBE(sig.subarray(32,64));if(!ge(s))return false;const e=challenge(numTo32b(r),pointToBytes(P),m);const R=GmulAdd(P,s,modN(-e));if(!R||!R.hasEvenY()||R.toAffine().x!==r)return false;return true}catch(error){return false}}const schnorr=(()=>({getPublicKey:schnorrGetPublicKey,sign:schnorrSign,verify:schnorrVerify,utils:{randomPrivateKey:secp256k1.utils.randomPrivateKey,lift_x:lift_x,pointToBytes:pointToBytes,numberToBytesBE:numberToBytesBE,bytesToNumberBE:bytesToNumberBE,taggedHash:taggedHash$1,mod:mod}}))();const ZeroAddress="0x0000000000000000000000000000000000000000";const ZeroHash="0x0000000000000000000000000000000000000000000000000000000000000000";const N$1=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const WeiPerEther=BigInt("1000000000000000000");const MaxUint256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const MinInt256=BigInt("0x8000000000000000000000000000000000000000000000000000000000000000")*BigInt(-1);const MaxInt256=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");const quaisymbol="Ξ";const MessagePrefix="Quai Signed Message:\n";const EthMessagePrefix="Ethereum Signed Message:\n";exports.Shard=void 0;(function(Shard){Shard["Cyprus"]="0x0";Shard["Cyprus1"]="0x00";Shard["Cyprus2"]="0x01";Shard["Cyprus3"]="0x02";Shard["Paxos"]="0x1";Shard["Paxos1"]="0x10";Shard["Paxos2"]="0x11";Shard["Paxos3"]="0x12";Shard["Hydra"]="0x2";Shard["Hydra1"]="0x20";Shard["Hydra2"]="0x21";Shard["Hydra3"]="0x22";Shard["Prime"]="0x"})(exports.Shard||(exports.Shard={}));function shardFromBytes(shard){switch(shard){case"0x":return exports.Shard.Prime;case"0x0":return exports.Shard.Cyprus;case"0x1":return exports.Shard.Paxos;case"0x2":return exports.Shard.Hydra;case"0x00":return exports.Shard.Cyprus1;case"0x01":return exports.Shard.Cyprus2;case"0x02":return exports.Shard.Cyprus3;case"0x10":return exports.Shard.Paxos1;case"0x11":return exports.Shard.Paxos2;case"0x12":return exports.Shard.Paxos3;case"0x20":return exports.Shard.Hydra1;case"0x21":return exports.Shard.Hydra2;case"0x22":return exports.Shard.Hydra3;default:throw new Error("Invalid shard")}}const ShardData=[...ZoneData,{name:"Cyprus",nickname:"cyprus",shard:"region-0",context:2,byte:"0x0"},{name:"Paxos",nickname:"paxos",shard:"region-1",context:2,byte:"0x1"},{name:"Hydra",nickname:"hydra",shard:"region-2",context:2,byte:"0x2"},{name:"Prime",nickname:"prime",shard:"prime",context:2,byte:"0x"}];function toShard(shard){return shardFromBytes(ShardData.find(it=>it.name==shard||it.byte==shard||it.nickname==shard||it.shard==shard)?.byte||"")}function fromShard(shard,key){return ShardData.find(it=>it.byte==shard)?.[key]||""}const BN_0$5=BigInt(0);const BN_1$2=BigInt(1);const BN_2$1=BigInt(2);const BN_27=BigInt(27);const BN_28=BigInt(28);const BN_35=BigInt(35);const _guard$6={};function toUint256(value){return zeroPadValue(toBeArray(value),32)}class Signature{#r;#s;#v;#networkV;get r(){return this.#r}set r(value){assertArgument(dataLength(value)===32,"invalid r","value",value);this.#r=hexlify(value)}get s(){return this.#s}set s(_value){assertArgument(dataLength(_value)===32,"invalid s","value",_value);const value=hexlify(_value);assertArgument(parseInt(value.substring(0,3))<8,"non-canonical s","value",value);this.#s=value}get v(){return this.#v}set v(value){const v=getNumber(value,"value");assertArgument(v===27||v===28,"invalid v","v",value);this.#v=v}get networkV(){return this.#networkV}get legacyChainId(){const v=this.networkV;if(v==null){return null}return Signature.getChainId(v)}get yParity(){return this.v===27?0:1}get yParityAndS(){const yParityAndS=getBytes(this.s);if(this.yParity){yParityAndS[0]|=128}return hexlify(yParityAndS)}get compactSerialized(){return concat([this.r,this.yParityAndS])}get serialized(){return concat([this.r,this.s,this.yParity?"0x1c":"0x1b"])}constructor(guard,r,s,v){assertPrivate(guard,_guard$6,"Signature");this.#r=r;this.#s=s;this.#v=v;this.#networkV=null}[Symbol.for("nodejs.util.inspect.custom")](){return`Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`}clone(){const clone=new Signature(_guard$6,this.r,this.s,this.v);if(this.networkV){clone.#networkV=this.networkV}return clone}toJSON(){const networkV=this.networkV;return{_type:"signature",networkV:networkV!=null?networkV.toString():null,r:this.r,s:this.s,v:this.v}}static getChainId(v){const bv=getBigInt(v,"v");if(bv==BN_27||bv==BN_28){return BN_0$5}assertArgument(bv>=BN_35,"invalid EIP-155 v","v",v);return(bv-BN_35)/BN_2$1}static getChainIdV(chainId,v){return getBigInt(chainId)*BN_2$1+BigInt(35+v-27)}static getNormalizedV(v){const bv=getBigInt(v);if(bv===BN_0$5||bv===BN_27){return 27}if(bv===BN_1$2||bv===BN_28){return 28}assertArgument(bv>=BN_35,"invalid v","v",v);return bv&BN_1$2?27:28}static from(sig){function assertError(check,message){assertArgument(check,message,"signature",sig)}if(sig==null){return new Signature(_guard$6,ZeroHash,ZeroHash,27)}if(typeof sig==="string"){const bytes=getBytes(sig,"signature");if(bytes.length===64){const r=hexlify(bytes.slice(0,32));const s=bytes.slice(32,64);const v=s[0]&128?28:27;s[0]&=127;return new Signature(_guard$6,r,hexlify(s),v)}if(bytes.length===65){const r=hexlify(bytes.slice(0,32));const s=bytes.slice(32,64);assertError((s[0]&128)===0,"non-canonical s");const v=Signature.getNormalizedV(bytes[64]);return new Signature(_guard$6,r,hexlify(s),v)}assertError(false,"invalid raw signature length")}if(sig instanceof Signature){return sig.clone()}const _r=sig.r;assertError(_r!=null,"missing r");const r=toUint256(_r);const s=function(s,yParityAndS){if(s!=null){return toUint256(s)}if(yParityAndS!=null){assertError(isHexString(yParityAndS,32),"invalid yParityAndS");const bytes=getBytes(yParityAndS);bytes[0]&=127;return hexlify(bytes)}assertError(false,"missing s")}(sig.s,sig.yParityAndS);assertError((getBytes(s)[0]&128)==0,"non-canonical s");const{networkV,v}=function(_v,yParityAndS,yParity){if(_v!=null){const v=getBigInt(_v);return{networkV:v>=BN_35?v:undefined,v:Signature.getNormalizedV(v)}}if(yParityAndS!=null){assertError(isHexString(yParityAndS,32),"invalid yParityAndS");return{v:getBytes(yParityAndS)[0]&128?28:27}}if(yParity!=null){switch(yParity){case 0:return{v:27};case 1:return{v:28}}assertError(false,"invalid yParity")}assertError(false,"missing v")}(sig.v,sig.yParityAndS,sig.yParity);const result=new Signature(_guard$6,r,s,v);if(networkV){result.#networkV=networkV}assertError(!("yParity"in sig&&sig.yParity!==result.yParity),"yParity mismatch");assertError(!("yParityAndS"in sig&&sig.yParityAndS!==result.yParityAndS),"yParityAndS mismatch");return result}}class SigningKey{#privateKey;constructor(privateKey){assertArgument(dataLength(privateKey)===32,"invalid private key","privateKey","[REDACTED]");this.#privateKey=hexlify(privateKey)}get privateKey(){return this.#privateKey}get publicKey(){return SigningKey.computePublicKey(this.#privateKey)}get compressedPublicKey(){return SigningKey.computePublicKey(this.#privateKey,true)}sign(digest){assertArgument(dataLength(digest)===32,"invalid digest length","digest",digest);const sig=secp256k1.sign(getBytesCopy(digest),getBytesCopy(this.#privateKey),{lowS:true});return Signature.from({r:toBeHex("0x"+sig.r.toString(16),32),s:toBeHex("0x"+sig.s.toString(16),32),v:sig.recovery?28:27})}computeSharedSecret(other){const pubKey=SigningKey.computePublicKey(other);return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey),getBytes(pubKey),false))}static computePublicKey(key,compressed){let bytes=getBytes(key,"key");if(bytes.length===32){const pubKey=secp256k1.getPublicKey(bytes,!!compressed);return hexlify(pubKey)}if(bytes.length===64){const pub=new Uint8Array(65);pub[0]=4;pub.set(bytes,1);bytes=pub}const point=secp256k1.ProjectivePoint.fromHex(bytes);return hexlify(point.toRawBytes(compressed))}static recoverPublicKey(digest,signature){assertArgument(dataLength(digest)===32,"invalid digest length","digest",digest);const sig=Signature.from(signature);let secpSig=secp256k1.Signature.fromCompact(getBytesCopy(concat([sig.r,sig.s])));secpSig=secpSig.addRecoveryBit(sig.yParity);const pubKey=secpSig.recoverPublicKey(getBytesCopy(digest));assertArgument(pubKey!=null,"invalid signautre for digest","signature",signature);return"0x"+pubKey.toHex(false)}static addPoints(p0,p1,compressed){const pub0=secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p0).substring(2));const pub1=secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p1).substring(2));return"0x"+pub0.add(pub1).toHex(!!compressed)}}const _0n=BigInt(0);const _1n=BigInt(1);const _2n=BigInt(2);const _3n=BigInt(3);const _5n=BigInt(5);const _7n=BigInt(7);const _64n=BigInt(64);const _64mask=BigInt("0xFFFFFFFFFFFFFFFF");const CURVE={b:BigInt(7),P:BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"),n:BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141")};function read32b(bytes){if(bytes.length!==32)throw new Error(`Expected 32-bytes, not ${bytes.length}`);const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.length);let b=view.getBigUint64(0);for(let offs=8;offs=0;offs-=8){view.setBigUint64(offs,num&_64mask);num>>=_64n}return dest}function readScalar(bytes){const a=read32b(bytes);if(a>=CURVE.n)throw new Error("Expected value mod n");return a}function readSecret(bytes){const a=readScalar(bytes);if(a===0n)throw new Error("Expected non-zero");return a}function secp256k1Right(x){const x2=x*x%CURVE.P;const x3=x2*x%CURVE.P;return(x3+CURVE.b)%CURVE.P}function jacobiSymbol(a){if(a===_0n)return 0;let p=CURVE.P;let sign=1;for(;;){let and3;for(and3=a&_3n;and3===_0n;a>>=_2n,and3=a&_3n);if(and3===_2n){a>>=_1n;const pand7=p&_7n;if(pand7===_3n||pand7===_5n)sign=-sign}if(a===_1n)break;if((_3n&a)===_3n&&(_3n&p)===_3n)sign=-sign;[a,p]=[p%a,a]}return sign>0?1:-1}function isPoint(p){if(p.length<33)return false;const t=p[0];if(p.length===33){return(t===2||t===3)&&isXOnlyPoint(p.subarray(1))}if(t!==4||p.length!==65)return false;const x=read32b(p.subarray(1,33));if(x===_0n)return false;if(x>=CURVE.P)return false;const y=read32b(p.subarray(33));if(y===_0n)return false;if(y>=CURVE.P)return false;const left=y*y%CURVE.P;const right=secp256k1Right(x);return left===right}function isXOnlyPoint(p){if(p.length!==32)return false;const x=read32b(p);if(x===_0n)return false;if(x>=CURVE.P)return false;const y2=secp256k1Right(x);return jacobiSymbol(y2)===1}function scalarAdd(a,b){const aN=readScalar(a);const bN=readScalar(b);const sum=(aN+bN)%CURVE.n;return write32b(sum)}function scalarMultiply(a,b){const aN=readScalar(a);const bN=readScalar(b);const product=aN*bN%CURVE.n;return write32b(product)}function scalarNegate(a){const aN=readScalar(a);const negated=aN===_0n?_0n:CURVE.n-aN;return write32b(negated)}function scalarMod(a){const aN=read32b(a);const remainder=aN%CURVE.n;return write32b(remainder)}function isScalar(t){try{readScalar(t);return true}catch{return false}}function isSecret(s){try{readSecret(s);return true}catch{return false}}function pointNegate(p){const even=hasEvenY(p);const negated=Uint8Array.from(p);if(p.length===33){negated[0]=even?3:2}else if(p.length===65){const y=read32b(p.subarray(33));if(y>=CURVE.P)throw new Error("Expected Y coordinate mod P");const minusY=y===_0n?_0n:CURVE.P-y;write32b(minusY,negated.subarray(33))}return negated}function pointX(p){if(p.length===32)return p;hasEvenY(p);return p.slice(1,33)}function hasEvenY(p){if(p.length===33){if(p[0]===2)return true;else if(p[0]===3)return false;else throw new Error("Wrong first byte to be a point")}if(p.length===65){if(p[0]!==4)throw new Error("Wrong first byte to be point");return p[64]%2===0}throw new Error("Wrong length to be a point")}function pointMultiplyUnsafe(p,a,compress){try{const product=secp256k1.ProjectivePoint.fromHex(p).multiplyAndAddUnsafe(secp256k1.ProjectivePoint.ZERO,BigInt(`0x${Buffer.from(a).toString("hex")}`),BigInt(1));if(!product)return null;return product.toRawBytes(compress)}catch{return null}}function pointMultiplyAndAddUnsafe(p1,a,p2,compress){try{const p2p=secp256k1.ProjectivePoint.fromHex(p2);const p=secp256k1.ProjectivePoint.fromHex(p1).multiplyAndAddUnsafe(p2p,BigInt(`0x${Buffer.from(a).toString("hex")}`),BigInt(1));if(!p)return null;return p.toRawBytes(compress)}catch{return null}}function pointAdd(a,b,compress){try{return secp256k1.ProjectivePoint.fromHex(a).add(secp256k1.ProjectivePoint.fromHex(b)).toRawBytes(compress)}catch{return null}}function pointAddTweak(p,tweak,compress){try{const P=secp256k1.ProjectivePoint.fromHex(p);const t=readSecret(tweak);const Q=secp256k1.ProjectivePoint.BASE.multiplyAndAddUnsafe(P,t,1n);if(!Q)throw new Error("Tweaked point at infinity");return Q.toRawBytes(compress)}catch{return null}}function pointCompress(p,compress=true){return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(compress)}function liftX(p){try{return secp256k1.ProjectivePoint.fromHex(p).toRawBytes(false)}catch{return null}}function getPublicKey(s,compress){try{return secp256k1.getPublicKey(s,compress)}catch{return null}}function taggedHash(tag,...messages){return schnorr.utils.taggedHash(tag,...messages)}function sha256Hash(...messages){const h=sha256$1.create();for(const message of messages)h.update(message);return h.digest()}const musigCrypto={read32b:read32b,write32b:write32b,readScalar:readScalar,readSecret:readSecret,secp256k1Right:secp256k1Right,jacobiSymbol:jacobiSymbol,isPoint:isPoint,isXOnlyPoint:isXOnlyPoint,scalarAdd:scalarAdd,scalarMultiply:scalarMultiply,scalarNegate:scalarNegate,scalarMod:scalarMod,isScalar:isScalar,isSecret:isSecret,pointNegate:pointNegate,pointX:pointX,hasEvenY:hasEvenY,pointMultiplyUnsafe:pointMultiplyUnsafe,pointMultiplyAndAddUnsafe:pointMultiplyAndAddUnsafe,pointAdd:pointAdd,pointAddTweak:pointAddTweak,pointCompress:pointCompress,liftX:liftX,getPublicKey:getPublicKey,taggedHash:taggedHash,sha256:sha256Hash};function lock(){computeHmac.lock();keccak256.lock();pbkdf2.lock();randomBytes.lock();ripemd160.lock();scrypt.lock();scryptSync.lock();sha256.lock();sha512.lock();randomBytes.lock()}function formatMixedCaseChecksumAddress(address){address=address.toLowerCase();const chars=address.substring(2).split("");const expanded=new Uint8Array(40);for(let i=0;i<40;i++){expanded[i]=chars[i].charCodeAt(0)}const hashed=getBytes(keccak256(expanded));for(let i=0;i<40;i+=2){if(hashed[i>>1]>>4>=8){chars[i]=chars[i].toUpperCase()}if((hashed[i>>1]&15)>=8){chars[i+1]=chars[i+1].toUpperCase()}}return"0x"+chars.join("")}function getAddress(address){assertArgument(typeof address==="string","invalid address","address",address);if(address.match(/^(0x)?[0-9a-fA-F]{40}$/)){if(!address.startsWith("0x")){address="0x"+address}const result=formatMixedCaseChecksumAddress(address);assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/)||result===address,"invalid address checksum","address",address);return result}assertArgument(false,"invalid address string format","address",address)}function getContractAddress(from,nonce,data){const nonceBytes=zeroPadValue(toBeHex(toBigInt(nonce)),8);return getAddress(dataSlice(keccak256(concat([getAddress(from),nonceBytes,stripZerosLeft(data)])),12))}function computeAddress(key){let pubkey;if(typeof key==="string"){pubkey=SigningKey.computePublicKey(key,false)}else{pubkey=key.publicKey}return getAddress(keccak256("0x"+pubkey.substring(4)).substring(26))}function recoverAddress(digest,signature){return computeAddress(SigningKey.recoverPublicKey(digest,signature))}function isAddressable(value){return value&&typeof value.getAddress==="function"}function isAddress(value){try{getAddress(value);return true}catch(error){}return false}async function checkAddress(target,promise){const result=await promise;if(result==null||result==="0x0000000000000000000000000000000000000000"){assertArgument(false,"invalid AddressLike value; did not resolve to a value address","target",target)}return result}function resolveAddress(target){if(typeof target==="string"){if(target.match(/^0x[0-9a-f]{40}$/i)){return target}}else if(isAddressable(target)){return checkAddress(target,target.getAddress())}else if(target&&typeof target.then==="function"){return checkAddress(target,target)}assertArgument(false,"unsupported addressable value","target",target)}function validateAddress(address){assertArgument(typeof address==="string","address must be string","address",address);assertArgument(Boolean(address.match(/^(0x)?[0-9a-fA-F]{40}$/)),"invalid address string format","address",address);assertArgument(formatMixedCaseChecksumAddress(address)===address,"invalid address checksum","address",address)}function isQiAddress(address){const secondByte=address.substring(4,6);const binaryString=parseInt(secondByte,16).toString(2).padStart(8,"0");const isUTXO=binaryString[0]==="1";return isUTXO}function isQuaiAddress(address){return!isQiAddress(address)}function getZoneForAddress(address){try{return toZone(address.slice(0,4))}catch(error){return null}}function getAddressDetails(address){const isQiLedger=(parseInt(address.substring(4,5),16)&1)===exports.Ledger.Qi;return{zone:toZone(address.substring(0,4)),ledger:isQiLedger?exports.Ledger.Qi:exports.Ledger.Quai}}function getTxType(from,to){if(from===null||to===null)return 0;const senderAddressIsQi=isQiAddress(from);const recipientAddressIsQi=isQiAddress(to);switch(true){case senderAddressIsQi&&recipientAddressIsQi:return 2;case senderAddressIsQi&&!recipientAddressIsQi:return 1;default:return 0}}function getNodeLocationFromZone(zone){const zoneId=zone.slice(2);if(zoneId.length>2){throw new Error(`Invalid zone: ${zone}`)}else if(zoneId.length===0){return[]}return zoneId.split("").map(Number)}function getZoneFromNodeLocation(location){if(location.length>2){throw new Error("Invalid location")}return toZone(`0x${location.join("")}`)}const WordSize=32;const Padding=new Uint8Array(WordSize);const passProperties$1=["then"];const _guard$5={};function throwError(name,error){const wrapped=new Error(`deferred error during ABI decoding triggered accessing ${name}`);wrapped.error=error;throw wrapped}class Result extends Array{#names;constructor(...args){const guard=args[0];let items=args[1];let names=(args[2]||[]).slice();let wrap=true;if(guard!==_guard$5){items=args;names=[];wrap=false}super(items.length);items.forEach((item,index)=>{this[index]=item});const nameCounts=names.reduce((accum,name)=>{if(typeof name==="string"){accum.set(name,(accum.get(name)||0)+1)}return accum},new Map);this.#names=Object.freeze(items.map((item,index)=>{const name=names[index];if(name!=null&&nameCounts.get(name)===1){return name}return null}));if(!wrap){return}Object.freeze(this);return new Proxy(this,{get:(target,prop,receiver)=>{if(typeof prop==="string"){if(prop.match(/^[0-9]+$/)){const index=getNumber(prop,"%index");if(index<0||index>=this.length){throw new RangeError("out of result range")}const item=target[index];if(item instanceof Error){throwError(`index ${index}`,item)}return item}if(passProperties$1.indexOf(prop)>=0){return Reflect.get(target,prop,receiver)}const value=target[prop];if(value instanceof Function){return function(...args){return value.apply(this===receiver?target:this,args)}}else if(!(prop in target)){return target.getValue.apply(this===receiver?target:this,[prop])}}return Reflect.get(target,prop,receiver)}})}toArray(){const result=[];this.forEach((item,index)=>{if(item instanceof Error){throwError(`index ${index}`,item)}result.push(item)});return result}toObject(){return this.#names.reduce((accum,name,index)=>{assert(name!=null,"value at index ${ index } unnamed","UNSUPPORTED_OPERATION",{operation:"toObject()"});if(!(name in accum)){accum[name]=this.getValue(name)}return accum},{})}slice(start,end){if(start==null){start=0}if(start<0){start+=this.length;if(start<0){start=0}}if(end==null){end=this.length}if(end<0){end+=this.length;if(end<0){end=0}}if(end>this.length){end=this.length}const result=[],names=[];for(let i=start;i{this.#data[offset]=getValue$1(value)}}}class Reader{allowLoose;#data;#offset;#bytesRead;#parent;#maxInflation;constructor(data,allowLoose,maxInflation){defineProperties(this,{allowLoose:!!allowLoose});this.#data=getBytesCopy(data);this.#bytesRead=0;this.#parent=null;this.#maxInflation=maxInflation!=null?maxInflation:1024;this.#offset=0}get data(){return hexlify(this.#data)}get dataLength(){return this.#data.length}get consumed(){return this.#offset}get bytes(){return new Uint8Array(this.#data)}#incrementBytesRead(count){if(this.#parent){return this.#parent.#incrementBytesRead(count)}this.#bytesRead+=count;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",{buffer:getBytesCopy(this.#data),offset:this.#offset,length:count,info:{bytesRead:this.#bytesRead,dataLength:this.dataLength}})}#peekBytes(offset,length,loose){let alignedLength=Math.ceil(length/WordSize)*WordSize;if(this.#offset+alignedLength>this.#data.length){if(this.allowLoose&&loose&&this.#offset+length<=this.#data.length){alignedLength=length}else{assert(false,"data out-of-bounds","BUFFER_OVERRUN",{buffer:getBytesCopy(this.#data),length:this.#data.length,offset:this.#offset+alignedLength})}}return this.#data.slice(this.#offset,this.#offset+alignedLength)}subReader(offset){const reader=new Reader(this.#data.slice(this.#offset+offset),this.allowLoose,this.#maxInflation);reader.#parent=this;return reader}readBytes(length,loose){const bytes=this.#peekBytes(0,length,!!loose);this.#incrementBytesRead(length);this.#offset+=bytes.length;return bytes.slice(0,length)}readValue(){return toBigInt(this.readBytes(WordSize))}readIndex(){return toNumber(this.readBytes(WordSize))}}function getCreateAddress(tx){const from=getAddress(tx.from);const nonce=getBigInt(tx.nonce,"tx.nonce");const nonceBytes=bigEndianNonce(nonce);const fromBytes=getBytes(from);const codeBytes=tx.data?getBytes(tx.data):new Uint8Array;const concatenated=new Uint8Array([...fromBytes,...nonceBytes,...codeBytes]);const hash=keccak256(concatenated);return getAddress(dataSlice(hash,12))}function getCreate2Address(_from,_salt,_initCodeHash){const from=getAddress(_from);const salt=getBytes(_salt,"salt");const initCodeHash=getBytes(_initCodeHash,"initCodeHash");assertArgument(salt.length===32,"salt must be 32 bytes","salt",_salt);assertArgument(initCodeHash.length===32,"initCodeHash must be 32 bytes","initCodeHash",_initCodeHash);return getAddress(dataSlice(keccak256(concat(["0xff",from,salt,initCodeHash])),12))}function bigEndianNonce(nonce){const buffer=new ArrayBuffer(8);const view=new DataView(buffer);view.setBigUint64(0,nonce,false);return new Uint8Array(buffer)}const _guard$4={};function n(value,width){let signed=false;if(width<0){signed=true;width*=-1}return new Typed(_guard$4,`${signed?"":"u"}int${width}`,value,{signed:signed,width:width})}function b(value,size){return new Typed(_guard$4,`bytes${size?size:""}`,value,{size:size})}const _typedSymbol=Symbol.for("_quais_typed");class Typed{type;value;#options;_typedSymbol;constructor(guard,type,value,options){if(options==null){options=null}assertPrivate(_guard$4,guard,"Typed");defineProperties(this,{_typedSymbol:_typedSymbol,type:type,value:value});this.#options=options;this.format()}format(){if(this.type==="array"){throw new Error("")}else if(this.type==="dynamicArray"){throw new Error("")}else if(this.type==="tuple"){return`tuple(${this.value.map(v=>v.format()).join(",")})`}return this.type}defaultValue(){return 0}minValue(){return 0}maxValue(){return 0}isBigInt(){return!!this.type.match(/^u?int[0-9]+$/)}isData(){return this.type.startsWith("bytes")}isString(){return this.type==="string"}get tupleName(){if(this.type!=="tuple"){throw TypeError("not a tuple")}return this.#options}get arrayLength(){if(this.type!=="array"){throw TypeError("not an array")}if(this.#options===true){return-1}if(this.#options===false){return this.value.length}return null}static from(type,value){return new Typed(_guard$4,type,value)}static uint8(v){return n(v,8)}static uint16(v){return n(v,16)}static uint24(v){return n(v,24)}static uint32(v){return n(v,32)}static uint40(v){return n(v,40)}static uint48(v){return n(v,48)}static uint56(v){return n(v,56)}static uint64(v){return n(v,64)}static uint72(v){return n(v,72)}static uint80(v){return n(v,80)}static uint88(v){return n(v,88)}static uint96(v){return n(v,96)}static uint104(v){return n(v,104)}static uint112(v){return n(v,112)}static uint120(v){return n(v,120)}static uint128(v){return n(v,128)}static uint136(v){return n(v,136)}static uint144(v){return n(v,144)}static uint152(v){return n(v,152)}static uint160(v){return n(v,160)}static uint168(v){return n(v,168)}static uint176(v){return n(v,176)}static uint184(v){return n(v,184)}static uint192(v){return n(v,192)}static uint200(v){return n(v,200)}static uint208(v){return n(v,208)}static uint216(v){return n(v,216)}static uint224(v){return n(v,224)}static uint232(v){return n(v,232)}static uint240(v){return n(v,240)}static uint248(v){return n(v,248)}static uint256(v){return n(v,256)}static uint(v){return n(v,256)}static int8(v){return n(v,-8)}static int16(v){return n(v,-16)}static int24(v){return n(v,-24)}static int32(v){return n(v,-32)}static int40(v){return n(v,-40)}static int48(v){return n(v,-48)}static int56(v){return n(v,-56)}static int64(v){return n(v,-64)}static int72(v){return n(v,-72)}static int80(v){return n(v,-80)}static int88(v){return n(v,-88)}static int96(v){return n(v,-96)}static int104(v){return n(v,-104)}static int112(v){return n(v,-112)}static int120(v){return n(v,-120)}static int128(v){return n(v,-128)}static int136(v){return n(v,-136)}static int144(v){return n(v,-144)}static int152(v){return n(v,-152)}static int160(v){return n(v,-160)}static int168(v){return n(v,-168)}static int176(v){return n(v,-176)}static int184(v){return n(v,-184)}static int192(v){return n(v,-192)}static int200(v){return n(v,-200)}static int208(v){return n(v,-208)}static int216(v){return n(v,-216)}static int224(v){return n(v,-224)}static int232(v){return n(v,-232)}static int240(v){return n(v,-240)}static int248(v){return n(v,-248)}static int256(v){return n(v,-256)}static int(v){return n(v,-256)}static bytes1(v){return b(v,1)}static bytes2(v){return b(v,2)}static bytes3(v){return b(v,3)}static bytes4(v){return b(v,4)}static bytes5(v){return b(v,5)}static bytes6(v){return b(v,6)}static bytes7(v){return b(v,7)}static bytes8(v){return b(v,8)}static bytes9(v){return b(v,9)}static bytes10(v){return b(v,10)}static bytes11(v){return b(v,11)}static bytes12(v){return b(v,12)}static bytes13(v){return b(v,13)}static bytes14(v){return b(v,14)}static bytes15(v){return b(v,15)}static bytes16(v){return b(v,16)}static bytes17(v){return b(v,17)}static bytes18(v){return b(v,18)}static bytes19(v){return b(v,19)}static bytes20(v){return b(v,20)}static bytes21(v){return b(v,21)}static bytes22(v){return b(v,22)}static bytes23(v){return b(v,23)}static bytes24(v){return b(v,24)}static bytes25(v){return b(v,25)}static bytes26(v){return b(v,26)}static bytes27(v){return b(v,27)}static bytes28(v){return b(v,28)}static bytes29(v){return b(v,29)}static bytes30(v){return b(v,30)}static bytes31(v){return b(v,31)}static bytes32(v){return b(v,32)}static address(v){return new Typed(_guard$4,"address",v)}static bool(v){return new Typed(_guard$4,"bool",!!v)}static bytes(v){return new Typed(_guard$4,"bytes",v)}static string(v){return new Typed(_guard$4,"string",v)}static array(v,dynamic){throw new Error("not implemented yet")}static tuple(v,name){throw new Error("not implemented yet")}static overrides(v){return new Typed(_guard$4,"overrides",Object.assign({},v))}static isTyped(value){return value&&typeof value==="object"&&"_typedSymbol"in value&&value._typedSymbol===_typedSymbol}static dereference(value,type){if(Typed.isTyped(value)){if(value.type!==type){throw new Error(`invalid type: expected ${type}, got ${value.type}`)}return value.value}return value}}class AddressCoder extends Coder{constructor(localName){super("address","address",localName,false)}defaultValue(){return"0x0000000000000000000000000000000000000000"}encode(writer,_value){let value=Typed.dereference(_value,"string");try{value=getAddress(value)}catch(error){return this._throwError(error.message,_value)}return writer.writeValue(value)}decode(reader){return getAddress(toBeHex(reader.readValue(),20))}}class AnonymousCoder extends Coder{coder;constructor(coder){super(coder.name,coder.type,"_",coder.dynamic);this.coder=coder}defaultValue(){return this.coder.defaultValue()}encode(writer,value){return this.coder.encode(writer,value)}decode(reader){return this.coder.decode(reader)}}function pack(writer,coders,values){let arrayValues=[];if(Array.isArray(values)){arrayValues=values}else if(values&&typeof values==="object"){let unique={};arrayValues=coders.map(coder=>{const name=coder.localName;assert(name,"cannot encode object for signature with missing names","INVALID_ARGUMENT",{argument:"values",info:{coder:coder},value:values});assert(!unique[name],"cannot encode object for signature with duplicate names","INVALID_ARGUMENT",{argument:"values",info:{coder:coder},value:values});unique[name]=true;return values[name]})}else{assertArgument(false,"invalid tuple value","tuple",values)}assertArgument(coders.length===arrayValues.length,"types/value length mismatch","tuple",values);let staticWriter=new Writer;let dynamicWriter=new Writer;let updateFuncs=[];coders.forEach((coder,index)=>{let value=arrayValues[index];if(coder.dynamic){let dynamicOffset=dynamicWriter.length;coder.encode(dynamicWriter,value);let updateFunc=staticWriter.writeUpdatableValue();updateFuncs.push(baseOffset=>{updateFunc(baseOffset+dynamicOffset)})}else{coder.encode(staticWriter,value)}});updateFuncs.forEach(func=>{func(staticWriter.length)});let length=writer.appendWriter(staticWriter);length+=writer.appendWriter(dynamicWriter);return length}function unpack(reader,coders){let values=[];let keys=[];let baseReader=reader.subReader(0);coders.forEach(coder=>{let value=null;if(coder.dynamic){let offset=reader.readIndex();let offsetReader=baseReader.subReader(offset);try{value=coder.decode(offsetReader)}catch(error){if(isError(error,"BUFFER_OVERRUN")){throw error}value=error;value.baseType=coder.name;value.name=coder.localName;value.type=coder.type}}else{try{value=coder.decode(reader)}catch(error){if(isError(error,"BUFFER_OVERRUN")){throw error}value=error;value.baseType=coder.name;value.name=coder.localName;value.type=coder.type}}if(value==undefined){throw new Error("investigate")}values.push(value);keys.push(coder.localName||null)});return Result.fromItems(values,keys)}class ArrayCoder extends Coder{coder;length;constructor(coder,length,localName){const type=coder.type+"["+(length>=0?length:"")+"]";const dynamic=length===-1||coder.dynamic;super("array",type,localName,dynamic);defineProperties(this,{coder:coder,length:length})}defaultValue(){const defaultChild=this.coder.defaultValue();const result=[];for(let i=0;ibounds||value<-(bounds+BN_1$1)){this._throwError("value out-of-bounds",_value)}value=toTwos(value,8*WordSize)}else if(valuemask(maxUintValue,this.size*8)){this._throwError("value out-of-bounds",_value)}return writer.writeValue(value)}decode(reader){let value=mask(reader.readValue(),this.size*8);if(this.signed){value=fromTwos(value,this.size*8)}return value}}class StringCoder extends DynamicBytesCoder{constructor(localName){super("string",localName)}defaultValue(){return""}encode(writer,_value){return super.encode(writer,toUtf8Bytes(Typed.dereference(_value,"string")))}decode(reader){return toUtf8String(super.decode(reader))}}class TupleCoder extends Coder{coders;constructor(coders,localName){let dynamic=false;const types=[];coders.forEach(coder=>{if(coder.dynamic){dynamic=true}types.push(coder.type)});const type="tuple("+types.join(",")+")";super("tuple",type,localName,dynamic);defineProperties(this,{coders:Object.freeze(coders.slice())})}defaultValue(){const values=[];this.coders.forEach(coder=>{values.push(coder.defaultValue())});const uniqueNames=this.coders.reduce((accum,coder)=>{const name=coder.localName;if(name){if(!accum[name]){accum[name]=0}accum[name]++}return accum},{});this.coders.forEach((coder,index)=>{let name=coder.localName;if(!name||uniqueNames[name]!==1){return}if(name==="length"){name="_length"}if(values[name]!=null){return}values[name]=values[index]});return Object.freeze(values)}encode(writer,_value){const value=Typed.dereference(_value,"tuple");return pack(writer,this.coders,value)}decode(reader){return unpack(reader,this.coders)}}function id(value){return keccak256(toUtf8Bytes(value))}function hashMessage(message){if(typeof message==="string"){message=toUtf8Bytes(message)}return keccak256(concat([toUtf8Bytes(MessagePrefix),toUtf8Bytes(String(message.length)),message]))}function verifyMessage(message,sig){const digest=hashMessage(message);return recoverAddress(digest,sig)}function ethHashMessage(message){if(typeof message==="string"){message=toUtf8Bytes(message)}return keccak256(concat([toUtf8Bytes(EthMessagePrefix),toUtf8Bytes(String(message.length)),message]))}function ethVerifyMessage(message,sig){const digest=ethHashMessage(message);return recoverAddress(digest,sig)}const regexBytes=new RegExp("^bytes([0-9]+)$");const regexNumber=new RegExp("^(u?int)([0-9]*)$");const regexArray=new RegExp("^(.*)\\[([0-9]*)\\]$");function _pack(type,value,isArray){switch(type){case"address":if(isArray){return getBytes(zeroPadValue(value,32))}return getBytes(getAddress(value));case"string":return toUtf8Bytes(value);case"bytes":return getBytes(value);case"bool":value=value?"0x01":"0x00";if(isArray){return getBytes(zeroPadValue(value,32))}return getBytes(value)}let match=type.match(regexNumber);if(match){const signed=match[1]==="int";let size=parseInt(match[2]||"256");assertArgument((!match[2]||match[2]===String(size))&&size%8===0&&size!==0&&size<=256,"invalid number type","type",type);if(isArray){size=256}if(signed){value=toTwos(value,size)}return getBytes(zeroPadValue(toBeArray(value),size/8))}match=type.match(regexBytes);if(match){const size=parseInt(match[1]);assertArgument(String(size)===match[1]&&size!==0&&size<=32,"invalid bytes type","type",type);assertArgument(dataLength(value)===size,`invalid value for ${type}`,"value",value);if(isArray){return getBytes(zeroPadBytes(value,32))}return value}match=type.match(regexArray);if(match&&Array.isArray(value)){const baseType=match[1];const count=parseInt(match[2]||String(value.length));assertArgument(count===value.length,`invalid array length for ${type}`,"value",value);const result=[];value.forEach(function(value){result.push(_pack(baseType,value,true))});return getBytes(concat(result))}assertArgument(false,"invalid type","type",type)}function solidityPacked(types,values){assertArgument(types.length===values.length,"wrong number of values; expected ${ types.length }","values",values);const tight=[];types.forEach(function(type,index){tight.push(_pack(type,values[index]))});return hexlify(concat(tight))}function solidityPackedKeccak256(types,values){return keccak256(solidityPacked(types,values))}function solidityPackedSha256(types,values){return sha256(solidityPacked(types,values))}const padding=new Uint8Array(32);padding.fill(0);const BN__1=BigInt(-1);const BN_0$3=BigInt(0);const BN_1=BigInt(1);const BN_MAX_UINT256=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");function hexPadRight(value){const bytes=getBytes(value);const padOffset=bytes.length%32;if(padOffset){return concat([bytes,padding.slice(padOffset)])}return hexlify(bytes)}const hexTrue=toBeHex(BN_1,32);const hexFalse=toBeHex(BN_0$3,32);const domainFieldTypes={name:"string",version:"string",chainId:"uint256",verifyingContract:"address",salt:"bytes32"};const domainFieldNames=["name","version","chainId","verifyingContract","salt"];function checkString(key){return function(value){assertArgument(typeof value==="string",`invalid domain value for ${JSON.stringify(key)}`,`domain.${key}`,value);return value}}const domainChecks={name:checkString("name"),version:checkString("version"),chainId:function(_value){const value=getBigInt(_value,"domain.chainId");assertArgument(value>=0,"invalid chain ID","domain.chainId",_value);if(Number.isSafeInteger(value)){return Number(value)}return toQuantity(value)},verifyingContract:function(value){try{return getAddress(value)}catch(error){}assertArgument(false,`invalid domain value "verifyingContract"`,"domain.verifyingContract",value)},salt:function(value){const bytes=getBytes(value,"domain.salt");assertArgument(bytes.length===32,`invalid domain value "salt"`,"domain.salt",value);return hexlify(bytes)}};function getBaseEncoder(type){{const match=type.match(/^(u?)int(\d*)$/);if(match){const signed=match[1]==="";const width=parseInt(match[2]||"256");assertArgument(width%8===0&&width!==0&&width<=256&&(match[2]==null||match[2]===String(width)),"invalid numeric width","type",type);const boundsUpper=mask(BN_MAX_UINT256,signed?width-1:width);const boundsLower=signed?(boundsUpper+BN_1)*BN__1:BN_0$3;return function(_value){const value=getBigInt(_value,"value");assertArgument(value>=boundsLower&&value<=boundsUpper,`value out-of-bounds for ${type}`,"value",value);return toBeHex(signed?toTwos(value,256):value,32)}}}{const match=type.match(/^bytes(\d+)$/);if(match){const width=parseInt(match[1]);assertArgument(width!==0&&width<=32&&match[1]===String(width),"invalid bytes width","type",type);return function(value){const bytes=getBytes(value);assertArgument(bytes.length===width,`invalid length for ${type}`,"value",value);return hexPadRight(value)}}}switch(type){case"address":return function(value){return zeroPadValue(getAddress(value),32)};case"bool":return function(value){return!value?hexFalse:hexTrue};case"bytes":return function(value){return keccak256(value)};case"string":return function(value){return id(value)}}return null}function encodeType(name,fields){return`${name}(${fields.map(({name,type})=>type+" "+name).join(",")})`}class TypedDataEncoder{primaryType;#types;get types(){return JSON.parse(this.#types)}#fullTypes;#encoderCache;constructor(types){this.#types=JSON.stringify(types);this.#fullTypes=new Map;this.#encoderCache=new Map;const links=new Map;const parents=new Map;const subtypes=new Map;Object.keys(types).forEach(type=>{links.set(type,new Set);parents.set(type,[]);subtypes.set(type,new Set)});for(const name in types){const uniqueNames=new Set;for(const field of types[name]){assertArgument(!uniqueNames.has(field.name),`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`,"types",types);uniqueNames.add(field.name);const baseType=field.type.match(/^([^\x5b]*)(\x5b|$)/)[1]||null;assertArgument(baseType!==name,`circular type reference to ${JSON.stringify(baseType)}`,"types",types);const encoder=getBaseEncoder(baseType);if(encoder){continue}assertArgument(parents.has(baseType),`unknown type ${JSON.stringify(baseType)}`,"types",types);parents.get(baseType).push(name);links.get(name).add(baseType)}}const primaryTypes=Array.from(parents.keys()).filter(n=>parents.get(n).length===0);assertArgument(primaryTypes.length!==0,"missing primary type","types",types);assertArgument(primaryTypes.length===1,`ambiguous primary types or unused types: ${primaryTypes.map(t=>JSON.stringify(t)).join(", ")}`,"types",types);defineProperties(this,{primaryType:primaryTypes[0]});function checkCircular(type,found){assertArgument(!found.has(type),`circular type reference to ${JSON.stringify(type)}`,"types",types);found.add(type);for(const child of links.get(type)){if(!parents.has(child)){continue}checkCircular(child,found);for(const subtype of found){subtypes.get(subtype).add(child)}}found.delete(type)}checkCircular(this.primaryType,new Set);for(const[name,set]of subtypes){const st=Array.from(set);st.sort();this.#fullTypes.set(name,encodeType(name,types[name])+st.map(t=>encodeType(t,types[t])).join(""))}}getEncoder(type){let encoder=this.#encoderCache.get(type);if(!encoder){encoder=this.#getEncoder(type);this.#encoderCache.set(type,encoder)}return encoder}#getEncoder(type){{const encoder=getBaseEncoder(type);if(encoder){return encoder}}const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){const subtype=match[1];const subEncoder=this.getEncoder(subtype);return value=>{assertArgument(!match[3]||parseInt(match[3])===value.length,`array length mismatch; expected length ${parseInt(match[3])}`,"value",value);let result=value.map(subEncoder);if(this.#fullTypes.has(subtype)){result=result.map(keccak256)}return keccak256(concat(result))}}const fields=this.types[type];if(fields){const encodedType=id(this.#fullTypes.get(type));return value=>{const values=fields.map(({name,type})=>{const result=this.getEncoder(type)(value[name]);if(this.#fullTypes.has(type)){return keccak256(result)}return result});values.unshift(encodedType);return concat(values)}}assertArgument(false,`unknown type: ${type}`,"type",type)}encodeType(name){const result=this.#fullTypes.get(name);assertArgument(result,`unknown type: ${JSON.stringify(name)}`,"name",name);return result}encodeData(type,value){return this.getEncoder(type)(value)}hashStruct(name,value){return keccak256(this.encodeData(name,value))}encode(value){return this.encodeData(this.primaryType,value)}hash(value){return this.hashStruct(this.primaryType,value)}_visit(type,value,callback){{const encoder=getBaseEncoder(type);if(encoder){return callback(type,value)}}const match=type.match(/^(.*)(\x5b(\d*)\x5d)$/);if(match){assertArgument(!match[3]||parseInt(match[3])===value.length,`array length mismatch; expected length ${parseInt(match[3])}`,"value",value);return value.map(v=>this._visit(match[1],v,callback))}const fields=this.types[type];if(fields){return fields.reduce((accum,{name,type})=>{accum[name]=this._visit(type,value[name],callback);return accum},{})}assertArgument(false,`unknown type: ${type}`,"type",type)}visit(value,callback){return this._visit(this.primaryType,value,callback)}static from(types){return new TypedDataEncoder(types)}static getPrimaryType(types){return TypedDataEncoder.from(types).primaryType}static hashStruct(name,types,value){return TypedDataEncoder.from(types).hashStruct(name,value)}static hashDomain(domain){const domainFields=[];for(const name in domain){if(domain[name]==null){continue}const type=domainFieldTypes[name];assertArgument(type,`invalid typed-data domain key: ${JSON.stringify(name)}`,"domain",domain);domainFields.push({name:name,type:type})}domainFields.sort((a,b)=>{return domainFieldNames.indexOf(a.name)-domainFieldNames.indexOf(b.name)});return TypedDataEncoder.hashStruct("EIP712Domain",{EIP712Domain:domainFields},domain)}static encode(domain,types,value){return concat(["0x1901",TypedDataEncoder.hashDomain(domain),TypedDataEncoder.from(types).hash(value)])}static hash(domain,types,value){return keccak256(TypedDataEncoder.encode(domain,types,value))}static getPayload(domain,types,value){TypedDataEncoder.hashDomain(domain);const domainValues={};const domainTypes=[];domainFieldNames.forEach(name=>{const value=domain[name];if(value==null){return}domainValues[name]=domainChecks[name](value);domainTypes.push({name:name,type:domainFieldTypes[name]})});const encoder=TypedDataEncoder.from(types);const typesWithDomain=Object.assign({},types);assertArgument(typesWithDomain.EIP712Domain==null,"types must not contain EIP712Domain type","types.EIP712Domain",types);typesWithDomain.EIP712Domain=domainTypes;encoder.encode(value);return{types:typesWithDomain,domain:domainValues,primaryType:encoder.primaryType,message:encoder.visit(value,(type,value)=>{if(type.match(/^bytes(\d*)/)){return hexlify(getBytes(value))}if(type.match(/^u?int/)){return getBigInt(value).toString()}switch(type){case"address":return value.toLowerCase();case"bool":return!!value;case"string":assertArgument(typeof value==="string","invalid string","value",value);return value}assertArgument(false,"unsupported type","type",type)})}}}function verifyTypedData(domain,types,value,signature){return recoverAddress(TypedDataEncoder.hash(domain,types,value),signature)}function setify(items){const result=new Set;items.forEach(k=>result.add(k));return Object.freeze(result)}const _kwVisibDeploy="external public payable";const KwVisibDeploy=setify(_kwVisibDeploy.split(" "));const _kwVisib="constant external internal payable private public pure view";const KwVisib=setify(_kwVisib.split(" "));const _kwTypes="constructor error event fallback function receive struct";const KwTypes=setify(_kwTypes.split(" "));const _kwModifiers="calldata memory storage payable indexed";const KwModifiers=setify(_kwModifiers.split(" "));const _kwOther="tuple returns";const _keywords=[_kwTypes,_kwModifiers,_kwOther,_kwVisib].join(" ");const Keywords=setify(_keywords.split(" "));const SimpleTokens={"(":"OPEN_PAREN",")":"CLOSE_PAREN","[":"OPEN_BRACKET","]":"CLOSE_BRACKET",",":"COMMA","@":"AT"};const regexWhitespacePrefix=new RegExp("^(\\s*)");const regexNumberPrefix=new RegExp("^([0-9]+)");const regexIdPrefix=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)");const regexId=new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$");const regexType=new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");class TokenString{#offset;#tokens;get offset(){return this.#offset}get length(){return this.#tokens.length-this.#offset}constructor(tokens){this.#offset=0;this.#tokens=tokens.slice()}clone(){return new TokenString(this.#tokens)}reset(){this.#offset=0}#subTokenString(from=0,to=0){return new TokenString(this.#tokens.slice(from,to).map(t=>{return Object.freeze(Object.assign({},t,{match:t.match-from,linkBack:t.linkBack-from,linkNext:t.linkNext-from}))}))}popKeyword(allowed){const top=this.peek();if(top.type!=="KEYWORD"||!allowed.has(top.text)){throw new Error(`expected keyword ${top.text}`)}return this.pop().text}popType(type){if(this.peek().type!==type){throw new Error(`expected ${type}; got ${JSON.stringify(this.peek())}`)}return this.pop().text}popParen(){const top=this.peek();if(top.type!=="OPEN_PAREN"){throw new Error("bad start")}const result=this.#subTokenString(this.#offset+1,top.match+1);this.#offset=top.match+1;return result}popParams(){const top=this.peek();if(top.type!=="OPEN_PAREN"){throw new Error("bad start")}const result=[];while(this.#offset=this.#tokens.length){throw new Error("out-of-bounds")}return this.#tokens[this.#offset]}peekKeyword(allowed){const top=this.peekType("KEYWORD");return top!=null&&allowed.has(top)?top:null}peekType(type){if(this.length===0){return null}const top=this.peek();return top.type===type?top.text:null}pop(){const result=this.peek();this.#offset++;return result}toString(){const tokens=[];for(let i=this.#offset;i`}}function lex(text){const tokens=[];const throwError=message=>{const token=offset0&&tokens[tokens.length-1].type==="NUMBER"){const value=tokens.pop().text;suffix=value+suffix;tokens[tokens.length-1].value=getNumber(value)}if(tokens.length===0||tokens[tokens.length-1].type!=="BRACKET"){throw new Error("missing opening bracket")}tokens[tokens.length-1].text+=suffix}continue}match=cur.match(regexIdPrefix);if(match){token.text=match[1];offset+=token.text.length;if(Keywords.has(token.text)){token.type="KEYWORD";continue}if(token.text.match(regexType)){token.type="TYPE";continue}token.type="ID";continue}match=cur.match(regexNumberPrefix);if(match){token.text=match[1];token.type="NUMBER";offset+=token.text.length;continue}throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`)}return new TokenString(tokens.map(t=>Object.freeze(t)))}function allowSingle(set,allowed){const included=[];for(const key in allowed.keys()){if(set.has(key)){included.push(key)}}if(included.length>1){throw new Error(`conflicting types: ${included.join(", ")}`)}}function consumeName(type,tokens){if(tokens.peekKeyword(KwTypes)){const keyword=tokens.pop().text;if(keyword!==type){throw new Error(`expected ${type}, got ${keyword}`)}}return tokens.popType("ID")}function consumeKeywords(tokens,allowed){const keywords=new Set;while(true){const keyword=tokens.peekType("KEYWORD");if(keyword==null||allowed&&!allowed.has(keyword)){break}tokens.pop();if(keywords.has(keyword)){throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`)}keywords.add(keyword)}return Object.freeze(keywords)}function consumeMutability(tokens){const modifiers=consumeKeywords(tokens,KwVisib);allowSingle(modifiers,setify("constant payable nonpayable".split(" ")));allowSingle(modifiers,setify("pure view payable nonpayable".split(" ")));if(modifiers.has("view")){return"view"}if(modifiers.has("pure")){return"pure"}if(modifiers.has("payable")){return"payable"}if(modifiers.has("nonpayable")){return"nonpayable"}if(modifiers.has("constant")){return"view"}return"nonpayable"}function consumeParams(tokens,allowIndexed){return tokens.popParams().map(t=>ParamType.from(t,allowIndexed))}function consumeGas(tokens){if(tokens.peekType("AT")){tokens.pop();if(tokens.peekType("NUMBER")){return getBigInt(tokens.pop().text)}throw new Error("invalid gas")}return null}function consumeEoi(tokens){if(tokens.length){throw new Error(`unexpected tokens: ${tokens.toString()}`)}}const regexArrayType=new RegExp(/^(.*)\[([0-9]*)\]$/);function verifyBasicType(type){const match=type.match(regexType);assertArgument(match,"invalid type","type",type);if(type==="uint"){return"uint256"}if(type==="int"){return"int256"}if(match[2]){const length=parseInt(match[2]);assertArgument(length!==0&&length<=32,"invalid bytes length","type",type)}else if(match[3]){const size=parseInt(match[3]);assertArgument(size!==0&&size<=256&&size%8===0,"invalid numeric width","type",type)}return type}const _guard$3={};const internal$1=Symbol.for("_quais_internal");const ParamTypeInternal="_ParamTypeInternal";const ErrorFragmentInternal="_ErrorInternal";const EventFragmentInternal="_EventInternal";const ConstructorFragmentInternal="_ConstructorInternal";const FallbackFragmentInternal="_FallbackInternal";const FunctionFragmentInternal="_FunctionInternal";const StructFragmentInternal="_StructInternal";class ParamType{name;type;baseType;indexed;components;arrayLength;arrayChildren;constructor(guard,name,type,baseType,indexed,components,arrayLength,arrayChildren){assertPrivate(guard,_guard$3,"ParamType");Object.defineProperty(this,internal$1,{value:ParamTypeInternal});if(components){components=Object.freeze(components.slice())}if(baseType==="array"){if(arrayLength==null||arrayChildren==null){throw new Error("")}}else if(arrayLength!=null||arrayChildren!=null){throw new Error("")}if(baseType==="tuple"){if(components==null){throw new Error("")}}else if(components!=null){throw new Error("")}defineProperties(this,{name:name,type:type,baseType:baseType,indexed:indexed,components:components,arrayLength:arrayLength,arrayChildren:arrayChildren})}format(format){if(format==null){format="sighash"}if(format==="json"){const name=this.name||"";if(this.isArray()){const result=JSON.parse(this.arrayChildren.format("json"));result.name=name;result.type+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`;return JSON.stringify(result)}const result={type:this.baseType==="tuple"?"tuple":this.type,name:name};if(typeof this.indexed==="boolean"){result.indexed=this.indexed}if(this.isTuple()){result.components=this.components.map(c=>JSON.parse(c.format(format)))}return JSON.stringify(result)}let result="";if(this.isArray()){result+=this.arrayChildren.format(format);result+=`[${this.arrayLength<0?"":String(this.arrayLength)}]`}else{if(this.isTuple()){result+="("+this.components.map(comp=>comp.format(format)).join(format==="full"?", ":",")+")"}else{result+=this.type}}if(format!=="sighash"){if(this.indexed===true){result+=" indexed"}if(format==="full"&&this.name){result+=" "+this.name}}return result}isArray(){return this.baseType==="array"}isTuple(){return this.baseType==="tuple"}isIndexable(){return this.indexed!=null}walk(value,process){if(this.isArray()){if(!Array.isArray(value)){throw new Error("invalid array value")}if(this.arrayLength!==-1&&value.length!==this.arrayLength){throw new Error("array is wrong length")}const _this=this;return value.map(v=>_this.arrayChildren.walk(v,process))}if(this.isTuple()){if(!Array.isArray(value)){throw new Error("invalid tuple value")}if(value.length!==this.components.length){throw new Error("array is wrong length")}const _this=this;return value.map((v,i)=>_this.components[i].walk(v,process))}return process(this.type,value)}#walkAsync(promises,value,process,setValue){if(this.isArray()){if(!Array.isArray(value)){throw new Error("invalid array value")}if(this.arrayLength!==-1&&value.length!==this.arrayLength){throw new Error("array is wrong length")}const childType=this.arrayChildren;const result=value.slice();result.forEach((value,index)=>{childType.#walkAsync(promises,value,process,value=>{result[index]=value})});setValue(result);return}if(this.isTuple()){const components=this.components;let result;if(Array.isArray(value)){result=value.slice()}else{if(value==null||typeof value!=="object"){throw new Error("invalid tuple value")}result=components.map(param=>{if(!param.name){throw new Error("cannot use object value with unnamed components")}if(!(param.name in value)){throw new Error(`missing value for component ${param.name}`)}return value[param.name]})}if(result.length!==this.components.length){throw new Error("array is wrong length")}result.forEach((value,index)=>{components[index].#walkAsync(promises,value,process,value=>{result[index]=value})});setValue(result);return}const result=process(this.type,value);if(result.then){promises.push(async function(){setValue(await result)}())}else{setValue(result)}}async walkAsync(value,process){const promises=[];const result=[value];this.#walkAsync(promises,value,process,value=>{result[0]=value});if(promises.length){await Promise.all(promises)}return result[0]}static from(obj,allowIndexed){if(ParamType.isParamType(obj)){return obj}if(typeof obj==="string"){try{return ParamType.from(lex(obj),allowIndexed)}catch(error){assertArgument(false,"invalid param type","obj",obj)}}else if(obj instanceof TokenString){let type="",baseType="";let comps=null;if(consumeKeywords(obj,setify(["tuple"])).has("tuple")||obj.peekType("OPEN_PAREN")){baseType="tuple";comps=obj.popParams().map(t=>ParamType.from(t));type=`tuple(${comps.map(c=>c.format()).join(",")})`}else{type=verifyBasicType(obj.popType("TYPE"));baseType=type}let arrayChildren=null;let arrayLength=null;while(obj.length&&obj.peekType("BRACKET")){const bracket=obj.pop();arrayChildren=new ParamType(_guard$3,"",type,baseType,null,comps,arrayLength,arrayChildren);arrayLength=bracket.value;type+=bracket.text;baseType="array";comps=null}let indexed=null;const keywords=consumeKeywords(obj,KwModifiers);if(keywords.has("indexed")){if(!allowIndexed){throw new Error("")}indexed=true}const name=obj.peekType("ID")?obj.pop().text:"";if(obj.length){throw new Error("leftover tokens")}return new ParamType(_guard$3,name,type,baseType,indexed,comps,arrayLength,arrayChildren)}const name=obj.name;assertArgument(!name||typeof name==="string"&&name.match(regexId),"invalid name","obj.name",name);let indexed=obj.indexed;if(indexed!=null){assertArgument(allowIndexed,"parameter cannot be indexed","obj.indexed",obj.indexed);indexed=!!indexed}let type=obj.type;const arrayMatch=type.match(regexArrayType);if(arrayMatch){const arrayLength=parseInt(arrayMatch[2]||"-1");const arrayChildren=ParamType.from({type:arrayMatch[1],components:obj.components});return new ParamType(_guard$3,name||"",type,"array",indexed,null,arrayLength,arrayChildren)}if(type==="tuple"||type.startsWith("tuple(")||type.startsWith("(")){const comps=obj.components!=null?obj.components.map(c=>ParamType.from(c)):null;const tuple=new ParamType(_guard$3,name||"",type,"tuple",indexed,comps,null,null);return tuple}type=verifyBasicType(obj.type);return new ParamType(_guard$3,name||"",type,type,indexed,null,null,null)}static isParamType(value){return value&&value[internal$1]===ParamTypeInternal}}class Fragment{type;inputs;constructor(guard,type,inputs){assertPrivate(guard,_guard$3,"Fragment");inputs=Object.freeze(inputs.slice());defineProperties(this,{type:type,inputs:inputs})}static from(obj){if(typeof obj==="string"){try{Fragment.from(JSON.parse(obj))}catch(e){}return Fragment.from(lex(obj))}if(obj instanceof TokenString){const type=obj.peekKeyword(KwTypes);switch(type){case"constructor":return ConstructorFragment.from(obj);case"error":return ErrorFragment.from(obj);case"event":return EventFragment.from(obj);case"fallback":case"receive":return FallbackFragment.from(obj);case"function":return FunctionFragment.from(obj);case"struct":return StructFragment.from(obj)}}else if(typeof obj==="object"){switch(obj.type){case"constructor":return ConstructorFragment.from(obj);case"error":return ErrorFragment.from(obj);case"event":return EventFragment.from(obj);case"fallback":case"receive":return FallbackFragment.from(obj);case"function":return FunctionFragment.from(obj);case"struct":return StructFragment.from(obj)}assert(false,`unsupported type: ${obj.type}`,"UNSUPPORTED_OPERATION",{operation:"Fragment.from"})}assertArgument(false,"unsupported frgament object","obj",obj)}static isConstructor(value){return ConstructorFragment.isFragment(value)}static isError(value){return ErrorFragment.isFragment(value)}static isEvent(value){return EventFragment.isFragment(value)}static isFunction(value){return FunctionFragment.isFragment(value)}static isStruct(value){return StructFragment.isFragment(value)}}class NamedFragment extends Fragment{name;constructor(guard,type,name,inputs){super(guard,type,inputs);assertArgument(typeof name==="string"&&name.match(regexId),"invalid identifier","name",name);inputs=Object.freeze(inputs.slice());defineProperties(this,{name:name})}}function joinParams(format,params){return"("+params.map(p=>p.format(format)).join(format==="full"?", ":",")+")"}class ErrorFragment extends NamedFragment{constructor(guard,name,inputs){super(guard,"error",name,inputs);Object.defineProperty(this,internal$1,{value:ErrorFragmentInternal})}get selector(){return id(this.format("sighash")).substring(0,10)}format(format){if(format==null){format="sighash"}if(format==="json"){return JSON.stringify({type:"error",name:this.name,inputs:this.inputs.map(input=>JSON.parse(input.format(format)))})}const result=[];if(format!=="sighash"){result.push("error")}result.push(this.name+joinParams(format,this.inputs));return result.join(" ")}static from(obj){if(ErrorFragment.isFragment(obj)){return obj}if(typeof obj==="string"){return ErrorFragment.from(lex(obj))}else if(obj instanceof TokenString){const name=consumeName("error",obj);const inputs=consumeParams(obj);consumeEoi(obj);return new ErrorFragment(_guard$3,name,inputs)}return new ErrorFragment(_guard$3,obj.name,obj.inputs?obj.inputs.map(ParamType.from):[])}static isFragment(value){return value&&value[internal$1]===ErrorFragmentInternal}}class EventFragment extends NamedFragment{anonymous;constructor(guard,name,inputs,anonymous){super(guard,"event",name,inputs);Object.defineProperty(this,internal$1,{value:EventFragmentInternal});defineProperties(this,{anonymous:anonymous})}get topicHash(){return id(this.format("sighash"))}format(format){if(format==null){format="sighash"}if(format==="json"){return JSON.stringify({type:"event",anonymous:this.anonymous,name:this.name,inputs:this.inputs.map(i=>JSON.parse(i.format(format)))})}const result=[];if(format!=="sighash"){result.push("event")}result.push(this.name+joinParams(format,this.inputs));if(format!=="sighash"&&this.anonymous){result.push("anonymous")}return result.join(" ")}static getTopicHash(name,params){params=(params||[]).map(p=>ParamType.from(p));const fragment=new EventFragment(_guard$3,name,params,false);return fragment.topicHash}static from(obj){if(EventFragment.isFragment(obj)){return obj}if(typeof obj==="string"){try{return EventFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid event fragment","obj",obj)}}else if(obj instanceof TokenString){const name=consumeName("event",obj);const inputs=consumeParams(obj,true);const anonymous=!!consumeKeywords(obj,setify(["anonymous"])).has("anonymous");consumeEoi(obj);return new EventFragment(_guard$3,name,inputs,anonymous)}return new EventFragment(_guard$3,obj.name,obj.inputs?obj.inputs.map(p=>ParamType.from(p,true)):[],!!obj.anonymous)}static isFragment(value){return value&&value[internal$1]===EventFragmentInternal}}class ConstructorFragment extends Fragment{payable;gas;constructor(guard,type,inputs,payable,gas){super(guard,type,inputs);Object.defineProperty(this,internal$1,{value:ConstructorFragmentInternal});defineProperties(this,{payable:payable,gas:gas})}format(format){assert(format!=null&&format!=="sighash","cannot format a constructor for sighash","UNSUPPORTED_OPERATION",{operation:"format(sighash)"});if(format==="json"){return JSON.stringify({type:"constructor",stateMutability:this.payable?"payable":"undefined",payable:this.payable,gas:this.gas!=null?this.gas:undefined,inputs:this.inputs.map(i=>JSON.parse(i.format(format)))})}const result=[`constructor${joinParams(format,this.inputs)}`];if(this.payable){result.push("payable")}if(this.gas!=null){result.push(`@${this.gas.toString()}`)}return result.join(" ")}static from(obj){if(ConstructorFragment.isFragment(obj)){return obj}if(typeof obj==="string"){try{return ConstructorFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid constuctor fragment","obj",obj)}}else if(obj instanceof TokenString){consumeKeywords(obj,setify(["constructor"]));const inputs=consumeParams(obj);const payable=!!consumeKeywords(obj,KwVisibDeploy).has("payable");const gas=consumeGas(obj);consumeEoi(obj);return new ConstructorFragment(_guard$3,"constructor",inputs,payable,gas)}return new ConstructorFragment(_guard$3,"constructor",obj.inputs?obj.inputs.map(ParamType.from):[],!!obj.payable,obj.gas!=null?obj.gas:null)}static isFragment(value){return value&&value[internal$1]===ConstructorFragmentInternal}}class FallbackFragment extends Fragment{payable;constructor(guard,inputs,payable){super(guard,"fallback",inputs);Object.defineProperty(this,internal$1,{value:FallbackFragmentInternal});defineProperties(this,{payable:payable})}format(format){const type=this.inputs.length===0?"receive":"fallback";if(format==="json"){const stateMutability=this.payable?"payable":"nonpayable";return JSON.stringify({type:type,stateMutability:stateMutability})}return`${type}()${this.payable?" payable":""}`}static from(obj){if(FallbackFragment.isFragment(obj)){return obj}if(typeof obj==="string"){try{return FallbackFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid fallback fragment","obj",obj)}}else if(obj instanceof TokenString){const errorObj=obj.toString();const topIsValid=obj.peekKeyword(setify(["fallback","receive"]));assertArgument(topIsValid,"type must be fallback or receive","obj",errorObj);const type=obj.popKeyword(setify(["fallback","receive"]));if(type==="receive"){const inputs=consumeParams(obj);assertArgument(inputs.length===0,`receive cannot have arguments`,"obj.inputs",inputs);consumeKeywords(obj,setify(["payable"]));consumeEoi(obj);return new FallbackFragment(_guard$3,[],true)}let inputs=consumeParams(obj);if(inputs.length){assertArgument(inputs.length===1&&inputs[0].type==="bytes","invalid fallback inputs","obj.inputs",inputs.map(i=>i.format("minimal")).join(", "))}else{inputs=[ParamType.from("bytes")]}const mutability=consumeMutability(obj);assertArgument(mutability==="nonpayable"||mutability==="payable","fallback cannot be constants","obj.stateMutability",mutability);if(consumeKeywords(obj,setify(["returns"])).has("returns")){const outputs=consumeParams(obj);assertArgument(outputs.length===1&&outputs[0].type==="bytes","invalid fallback outputs","obj.outputs",outputs.map(i=>i.format("minimal")).join(", "))}consumeEoi(obj);return new FallbackFragment(_guard$3,inputs,mutability==="payable")}if(obj.type==="receive"){return new FallbackFragment(_guard$3,[],true)}if(obj.type==="fallback"){const inputs=[ParamType.from("bytes")];const payable=obj.stateMutability==="payable";return new FallbackFragment(_guard$3,inputs,payable)}assertArgument(false,"invalid fallback description","obj",obj)}static isFragment(value){return value&&value[internal$1]===FallbackFragmentInternal}}class FunctionFragment extends NamedFragment{constant;outputs;stateMutability;payable;gas;constructor(guard,name,stateMutability,inputs,outputs,gas){super(guard,"function",name,inputs);Object.defineProperty(this,internal$1,{value:FunctionFragmentInternal});outputs=Object.freeze(outputs.slice());const constant=stateMutability==="view"||stateMutability==="pure";const payable=stateMutability==="payable";defineProperties(this,{constant:constant,gas:gas,outputs:outputs,payable:payable,stateMutability:stateMutability})}get selector(){return id(this.format("sighash")).substring(0,10)}format(format){if(format==null){format="sighash"}if(format==="json"){return JSON.stringify({type:"function",name:this.name,constant:this.constant,stateMutability:this.stateMutability!=="nonpayable"?this.stateMutability:undefined,payable:this.payable,gas:this.gas!=null?this.gas:undefined,inputs:this.inputs.map(i=>JSON.parse(i.format(format))),outputs:this.outputs.map(o=>JSON.parse(o.format(format)))})}const result=[];if(format!=="sighash"){result.push("function")}result.push(this.name+joinParams(format,this.inputs));if(format!=="sighash"){if(this.stateMutability!=="nonpayable"){result.push(this.stateMutability)}if(this.outputs&&this.outputs.length){result.push("returns");result.push(joinParams(format,this.outputs))}if(this.gas!=null){result.push(`@${this.gas.toString()}`)}}return result.join(" ")}static getSelector(name,params){params=(params||[]).map(p=>ParamType.from(p));const fragment=new FunctionFragment(_guard$3,name,"view",params,[],null);return fragment.selector}static from(obj){if(FunctionFragment.isFragment(obj)){return obj}if(typeof obj==="string"){try{return FunctionFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid function fragment","obj",obj)}}else if(obj instanceof TokenString){const name=consumeName("function",obj);const inputs=consumeParams(obj);const mutability=consumeMutability(obj);let outputs=[];if(consumeKeywords(obj,setify(["returns"])).has("returns")){outputs=consumeParams(obj)}const gas=consumeGas(obj);consumeEoi(obj);return new FunctionFragment(_guard$3,name,mutability,inputs,outputs,gas)}let stateMutability=obj.stateMutability;if(stateMutability==null){stateMutability="payable";if(typeof obj.constant==="boolean"){stateMutability="view";if(!obj.constant){stateMutability="payable";if(typeof obj.payable==="boolean"&&!obj.payable){stateMutability="nonpayable"}}}else if(typeof obj.payable==="boolean"&&!obj.payable){stateMutability="nonpayable"}}return new FunctionFragment(_guard$3,obj.name,stateMutability,obj.inputs?obj.inputs.map(ParamType.from):[],obj.outputs?obj.outputs.map(ParamType.from):[],obj.gas!=null?obj.gas:null)}static isFragment(value){return value&&value[internal$1]===FunctionFragmentInternal}}class StructFragment extends NamedFragment{constructor(guard,name,inputs){super(guard,"struct",name,inputs);Object.defineProperty(this,internal$1,{value:StructFragmentInternal})}format(){throw new Error("@TODO")}static from(obj){if(typeof obj==="string"){try{return StructFragment.from(lex(obj))}catch(error){assertArgument(false,"invalid struct fragment","obj",obj)}}else if(obj instanceof TokenString){const name=consumeName("struct",obj);const inputs=consumeParams(obj);consumeEoi(obj);return new StructFragment(_guard$3,name,inputs)}return new StructFragment(_guard$3,obj.name,obj.inputs?obj.inputs.map(ParamType.from):[])}static isFragment(value){return value&&value[internal$1]===StructFragmentInternal}}const PanicReasons$1=new Map;PanicReasons$1.set(0,"GENERIC_PANIC");PanicReasons$1.set(1,"ASSERT_FALSE");PanicReasons$1.set(17,"OVERFLOW");PanicReasons$1.set(18,"DIVIDE_BY_ZERO");PanicReasons$1.set(33,"ENUM_RANGE_ERROR");PanicReasons$1.set(34,"BAD_STORAGE_DATA");PanicReasons$1.set(49,"STACK_UNDERFLOW");PanicReasons$1.set(50,"ARRAY_RANGE_ERROR");PanicReasons$1.set(65,"OUT_OF_MEMORY");PanicReasons$1.set(81,"UNINITIALIZED_FUNCTION_CALL");const paramTypeBytes=new RegExp(/^bytes([0-9]*)$/);const paramTypeNumber=new RegExp(/^(u?int)([0-9]*)$/);let defaultCoder=null;let defaultMaxInflation=1024;function getBuiltinCallException(action,tx,data,abiCoder){let message="missing revert data";let reason=null;const invocation=null;let revert=null;if(data){message="execution reverted";const bytes=getBytes(data);data=hexlify(data);if(bytes.length===0){message+=" (no data present; likely require(false) occurred";reason="require(false)"}else if(bytes.length%32!==4){message+=" (could not decode reason; invalid data length)"}else if(hexlify(bytes.slice(0,4))==="0x08c379a0"){try{reason=abiCoder.decode(["string"],bytes.slice(4))[0];revert={signature:"Error(string)",name:"Error",args:[reason]};message+=`: ${JSON.stringify(reason)}`}catch(error){message+=" (could not decode reason; invalid string data)"}}else if(hexlify(bytes.slice(0,4))==="0x4e487b71"){try{const code=Number(abiCoder.decode(["uint256"],bytes.slice(4))[0]);revert={signature:"Panic(uint256)",name:"Panic",args:[code]};reason=`Panic due to ${PanicReasons$1.get(code)||"UNKNOWN"}(${code})`;message+=`: ${reason}`}catch(error){message+=" (could not decode panic code)"}}else{message+=" (unknown custom error)"}}const transaction={to:tx.to?getAddress(tx.to):null,data:tx.data||"0x"};if(tx.from){transaction.from=getAddress(tx.from)}return makeError(message,"CALL_EXCEPTION",{action:action,data:data,reason:reason,transaction:transaction,invocation:invocation,revert:revert})}class AbiCoder{#getCoder(param){if(param.isArray()){return new ArrayCoder(this.#getCoder(param.arrayChildren),param.arrayLength,param.name)}if(param.isTuple()){return new TupleCoder(param.components.map(c=>this.#getCoder(c)),param.name)}switch(param.baseType){case"address":return new AddressCoder(param.name);case"bool":return new BooleanCoder(param.name);case"string":return new StringCoder(param.name);case"bytes":return new BytesCoder(param.name);case"":return new NullCoder(param.name)}let match=param.type.match(paramTypeNumber);if(match){const size=parseInt(match[2]||"256");assertArgument(size!==0&&size<=256&&size%8===0,"invalid "+match[1]+" bit length","param",param);return new NumberCoder(size/8,match[1]==="int",param.name)}match=param.type.match(paramTypeBytes);if(match){const size=parseInt(match[1]);assertArgument(size!==0&&size<=32,"invalid bytes length","param",param);return new FixedBytesCoder(size,param.name)}assertArgument(false,"invalid type","type",param.type)}getDefaultValue(types){const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");return coder.defaultValue()}encode(types,values){assertArgumentCount(values.length,types.length,"types/values length mismatch");const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");const writer=new Writer;coder.encode(writer,values);return writer.data}decode(types,data,loose){const coders=types.map(type=>this.#getCoder(ParamType.from(type)));const coder=new TupleCoder(coders,"_");return coder.decode(new Reader(data,loose,defaultMaxInflation))}static _setDefaultMaxInflation(value){assertArgument(typeof value==="number"&&Number.isInteger(value),"invalid defaultMaxInflation factor","value",value);defaultMaxInflation=value}static defaultAbiCoder(){if(defaultCoder==null){defaultCoder=new AbiCoder}return defaultCoder}static getBuiltinCallException(action,tx,data){return getBuiltinCallException(action,tx,data,AbiCoder.defaultAbiCoder())}}class LogDescription{fragment;name;signature;topic;args;constructor(fragment,topic,args){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,signature:signature,topic:topic,args:args})}}class TransactionDescription{fragment;name;args;signature;selector;value;constructor(fragment,selector,args,value){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,args:args,signature:signature,selector:selector,value:value})}}class ErrorDescription{fragment;name;args;signature;selector;constructor(fragment,selector,args){const name=fragment.name,signature=fragment.format();defineProperties(this,{fragment:fragment,name:name,args:args,signature:signature,selector:selector})}}class Indexed{hash;_isIndexed;static isIndexed(value){return!!(value&&value._isIndexed)}constructor(hash){defineProperties(this,{hash:hash,_isIndexed:true})}}const PanicReasons={0:"generic panic",1:"assert(false)",17:"arithmetic overflow",18:"division or modulo by zero",33:"enum overflow",34:"invalid encoded storage byte array accessed",49:"out-of-bounds array access; popping on an empty array",50:"out-of-bounds access of an array or bytesN",65:"out of memory",81:"uninitialized function"};const BuiltinErrors={"0x08c379a0":{signature:"Error(string)",name:"Error",inputs:["string"],reason:message=>{return`reverted with reason string ${JSON.stringify(message)}`}},"0x4e487b71":{signature:"Panic(uint256)",name:"Panic",inputs:["uint256"],reason:code=>{let reason="unknown panic code";if(code>=0&&code<=255&&PanicReasons[code.toString()]){reason=PanicReasons[code.toString()]}return`reverted with panic code 0x${code.toString(16)} (${reason})`}}};class Interface{fragments;deploy;fallback;receive;#errors;#events;#functions;#abiCoder;constructor(fragments){let abi=[];if(typeof fragments==="string"){abi=JSON.parse(fragments)}else{abi=fragments}this.#functions=new Map;this.#errors=new Map;this.#events=new Map;const frags=[];for(const a of abi){try{frags.push(Fragment.from(a))}catch(error){console.log("Error parsing ABI fragment",error)}}defineProperties(this,{fragments:Object.freeze(frags)});let fallback=null;let receive=false;this.#abiCoder=this.getAbiCoder();this.fragments.forEach((fragment,index)=>{let bucket;switch(fragment.type){case"constructor":if(this.deploy){console.log("duplicate definition - constructor");return}defineProperties(this,{deploy:fragment});return;case"fallback":if(fragment.inputs.length===0){receive=true}else{assertArgument(!fallback||fragment.payable!==fallback.payable,"conflicting fallback fragments",`fragments[${index}]`,fragment);fallback=fragment;receive=fallback.payable}return;case"function":bucket=this.#functions;break;case"event":bucket=this.#events;break;case"error":bucket=this.#errors;break;default:return}const signature=fragment.format();if(bucket.has(signature)){return}bucket.set(signature,fragment)});if(!this.deploy){defineProperties(this,{deploy:ConstructorFragment.from("constructor()")})}defineProperties(this,{fallback:fallback,receive:receive})}format(minimal){const format=minimal?"minimal":"full";const abi=this.fragments.map(f=>f.format(format));return abi}formatJson(){const abi=this.fragments.map(f=>f.format("json"));return JSON.stringify(abi.map(j=>JSON.parse(j)))}getAbiCoder(){return AbiCoder.defaultAbiCoder()}#getFunction(key,values,forceUnique){if(isHexString(key)){const selector=key.toLowerCase();for(const fragment of this.#functions.values()){if(selector===fragment.selector){return fragment}}return null}if(key.indexOf("(")===-1){const matching=[];for(const[name,fragment]of this.#functions){if(name.split("(")[0]===key){matching.push(fragment)}}if(values){const lastValue=values.length>0?values[values.length-1]:null;let valueLength=values.length;let allowOptions=true;if(Typed.isTyped(lastValue)&&lastValue.type==="overrides"){allowOptions=false;valueLength--}for(let i=matching.length-1;i>=0;i--){const inputs=matching[i].inputs.length;if(inputs!==valueLength&&(!allowOptions||inputs!==valueLength-1)){matching.splice(i,1)}}for(let i=matching.length-1;i>=0;i--){const inputs=matching[i].inputs;for(let j=0;j=inputs.length){if(values[j].type==="overrides"){continue}matching.splice(i,1);break}if(values[j].type!==inputs[j].baseType){matching.splice(i,1);break}}}}if(matching.length===1&&values&&values.length!==matching[0].inputs.length){const lastArg=values[values.length-1];if(lastArg==null||Array.isArray(lastArg)||typeof lastArg!=="object"){matching.splice(0,1)}}if(matching.length===0){return null}if(matching.length>1&&forceUnique){const matchStr=matching.map(m=>JSON.stringify(m.format())).join(", ");assertArgument(false,`ambiguous function description (i.e. matches ${matchStr})`,"key",key)}return matching[0]}const result=this.#functions.get(FunctionFragment.from(key).format());if(result){return result}return null}getFunctionName(key){const fragment=this.#getFunction(key,null,false);assertArgument(fragment,"no matching function","key",key);return fragment.name}hasFunction(key){return!!this.#getFunction(key,null,false)}getFunction(key,values){return this.#getFunction(key,values||null,true)}forEachFunction(callback){const names=Array.from(this.#functions.keys());names.sort((a,b)=>a.localeCompare(b));for(let i=0;i=0;i--){if(matching[i].inputs.length=0;i--){const inputs=matching[i].inputs;for(let j=0;j1&&forceUnique){const matchStr=matching.map(m=>JSON.stringify(m.format())).join(", ");assertArgument(false,`ambiguous event description (i.e. matches ${matchStr})`,"key",key)}return matching[0]}const result=this.#events.get(EventFragment.from(key).format());if(result){return result}return null}getEventName(key){const fragment=this.#getEvent(key,null,false);assertArgument(fragment,"no matching event","key",key);return fragment.name}hasEvent(key){return!!this.#getEvent(key,null,false)}getEvent(key,values){return this.#getEvent(key,values||null,true)}forEachEvent(callback){const names=Array.from(this.#events.keys());names.sort((a,b)=>a.localeCompare(b));for(let i=0;i1){const matchStr=matching.map(m=>JSON.stringify(m.format())).join(", ");assertArgument(false,`ambiguous error description (i.e. ${matchStr})`,"name",key)}return matching[0]}key=ErrorFragment.from(key).format();if(key==="Error(string)"){return ErrorFragment.from("error Error(string)")}if(key==="Panic(uint256)"){return ErrorFragment.from("error Panic(uint256)")}const result=this.#errors.get(key);if(result){return result}return null}forEachError(callback){const names=Array.from(this.#errors.keys());names.sort((a,b)=>a.localeCompare(b));for(let i=0;i{if(param.type==="string"){return id(value)}else if(param.type==="bytes"){return keccak256(hexlify(value))}if(param.type==="bool"&&typeof value==="boolean"){value=value?"0x01":"0x00"}else if(param.type.match(/^u?int/)){value=toBeHex(value)}else if(param.type.match(/^bytes/)){value=zeroPadBytes(value,32)}else if(param.type==="address"){this.#abiCoder.encode(["address"],[value])}return zeroPadValue(hexlify(value),32)};values.forEach((value,index)=>{const param=fragment.inputs[index];if(!param.indexed){assertArgument(value==null,"cannot filter non-indexed parameters; must be null","contract."+param.name,value);return}if(value==null){topics.push(null)}else if(param.baseType==="array"||param.baseType==="tuple"){assertArgument(false,"filtering with tuples or arrays not supported","contract."+param.name,value)}else if(Array.isArray(value)){topics.push(value.map(value=>encodeTopic(param,value)))}else{topics.push(encodeTopic(param,value))}});while(topics.length&&topics[topics.length-1]===null){topics.pop()}return topics}encodeEventLog(fragment,values){if(typeof fragment==="string"){const f=this.getEvent(fragment);assertArgument(f,"unknown event","eventFragment",fragment);fragment=f}const topics=[];const dataTypes=[];const dataValues=[];if(!fragment.anonymous){topics.push(fragment.topicHash)}assertArgument(values.length===fragment.inputs.length,"event arguments/values mismatch","values",values);fragment.inputs.forEach((param,index)=>{const value=values[index];if(param.indexed){if(param.type==="string"){topics.push(id(value))}else if(param.type==="bytes"){topics.push(keccak256(value))}else if(param.baseType==="tuple"||param.baseType==="array"){throw new Error("not implemented")}else{topics.push(this.#abiCoder.encode([param.type],[value]))}}else{dataTypes.push(param);dataValues.push(value)}});return{data:this.#abiCoder.encode(dataTypes,dataValues),topics:topics}}decodeEventLog(fragment,data,topics){if(typeof fragment==="string"){const f=this.getEvent(fragment);assertArgument(f,"unknown event","eventFragment",fragment);fragment=f}if(topics!=null&&!fragment.anonymous){const eventTopic=fragment.topicHash;assertArgument(isHexString(topics[0],32)&&topics[0].toLowerCase()===eventTopic,"fragment/topic mismatch","topics[0]",topics[0]);topics=topics.slice(1)}const indexed=[];const nonIndexed=[];const dynamic=[];fragment.inputs.forEach((param,index)=>{if(param.indexed){if(param.type==="string"||param.type==="bytes"||param.baseType==="tuple"||param.baseType==="array"){indexed.push(ParamType.from({type:"bytes32",name:param.name}));dynamic.push(true)}else{indexed.push(param);dynamic.push(false)}}else{nonIndexed.push(param);dynamic.push(false)}});const resultIndexed=topics!=null?this.#abiCoder.decode(indexed,concat(topics)):null;const resultNonIndexed=this.#abiCoder.decode(nonIndexed,data,true);const values=[];const keys=[];let nonIndexedIndex=0,indexedIndex=0;fragment.inputs.forEach((param,index)=>{let value=null;if(param.indexed){if(resultIndexed==null){value=new Indexed(null)}else if(dynamic[index]){value=new Indexed(resultIndexed[indexedIndex++])}else{try{value=resultIndexed[indexedIndex++]}catch(error){value=error}}}else{try{value=resultNonIndexed[nonIndexedIndex++]}catch(error){value=error}}values.push(value);keys.push(param.name||null)});return Result.fromItems(values,keys)}parseTransaction(tx){const data=getBytes(tx.data,"tx.data");const value=getBigInt(tx.value!=null?tx.value:0,"tx.value");const fragment=this.getFunction(hexlify(data.slice(0,4)));if(!fragment){return null}const args=this.#abiCoder.decode(fragment.inputs,data.slice(4));return new TransactionDescription(fragment,fragment.selector,args,value)}parseCallResult(data){throw new Error("@TODO")}parseLog(log){const fragment=this.getEvent(log.topics[0]);if(!fragment||fragment.anonymous){return null}return new LogDescription(fragment,fragment.topicHash,this.decodeEventLog(fragment,log.data,log.topics))}parseError(data){const hexData=hexlify(data);const fragment=this.getError(dataSlice(hexData,0,4));if(!fragment){return null}const args=this.#abiCoder.decode(fragment.inputs,dataSlice(hexData,4));return new ErrorDescription(fragment,fragment.selector,args)}static from(value){if(value instanceof Interface){return value}if(typeof value==="string"){return new Interface(JSON.parse(value))}if(typeof value.format==="function"){return new Interface(value.format("json"))}return new Interface(value)}}function accessSetify(addr,storageKeys){validateAddress(addr);return{address:getAddress(addr),storageKeys:storageKeys.map((storageKey,index)=>{assertArgument(isHexString(storageKey,32),"invalid slot",`storageKeys[${index}]`,storageKey);return storageKey.toLowerCase()})}}function accessListify(value){if(Array.isArray(value)){return value.map((set,index)=>{if(Array.isArray(set)){assertArgument(set.length===2,"invalid slot set",`value[${index}]`,set);return accessSetify(set[0],set[1])}assertArgument(set!=null&&typeof set==="object","invalid address-slot set","value",value);return accessSetify(set.address,set.storageKeys)})}assertArgument(value!=null&&typeof value==="object","invalid access list","value",value);const result=Object.keys(value).map(addr=>{const storageKeys=value[addr].reduce((accum,storageKey)=>{accum[storageKey]=true;return accum},{});return accessSetify(addr,Object.keys(storageKeys).sort())});result.sort((a,b)=>a.address.localeCompare(b.address));return result}class AbstractTransaction{_type;_signature;_chainId;get type(){return this._type}set type(value){switch(value){case null:this._type=null;break;case 0:case"standard":this._type=0;break;case 2:case"utxo":this._type=2;break;default:assertArgument(false,"unsupported transaction type","type",value)}}get typeName(){switch(this.type){case 0:return"standard";case 1:return"external";case 2:return"utxo"}return null}get chainId(){return this._chainId}set chainId(value){this._chainId=getBigInt(value)}get signature(){return this._signature||null}set signature(value){if(typeof value==="string"){this._signature=value}else{this._signature=value==null?null:Signature.from(value)}}constructor(){this._type=null;this._chainId=BigInt(0);this._signature=null}get digest(){return keccak256(this.unsignedSerialized)}isSigned(){return this.signature!=null}get serialized(){assert(this.signature!=null,"cannot serialize unsigned transaction; maybe you meant .unsignedSerialized","UNSUPPORTED_OPERATION",{operation:".serialized"});return encodeProtoTransaction(this.toProtobuf(true))}get unsignedSerialized(){return encodeProtoTransaction(this.toProtobuf(false))}inferType(){return this.inferTypes().pop()}get isExternal(){return this.destZone!==undefined&&this.originZone!==this.destZone}}const denominations=[BigInt(1),BigInt(5),BigInt(10),BigInt(50),BigInt(100),BigInt(250),BigInt(500),BigInt(1e3),BigInt(5e3),BigInt(1e4),BigInt(2e4),BigInt(5e4),BigInt(1e5),BigInt(1e6),BigInt(1e7),BigInt(1e8),BigInt(1e9)];function isValidDenomination(denomination){return denominations.includes(denomination)}function handleBigInt(value,param){if(value==="0x"){return BigInt(0)}return getBigInt(value,param)}function denominate(value){if(value<=BigInt(0)){throw new Error("Value must be greater than 0")}const result=[];let remainingValue=value;for(let i=denominations.length-1;i>=0;i--){const denomination=denominations[i];while(remainingValue>=denomination){result.push(denomination);remainingValue-=denomination}}if(remainingValue>0){throw new Error("Unable to match the value with available denominations")}return result}class UTXO{#txhash;#index;#address;#denomination;get txhash(){return this.#txhash}set txhash(value){this.#txhash=value}get index(){return this.#index}set index(value){this.#index=value}get address(){return this.#address||""}set address(value){validateAddress(value);this.#address=value}get denomination(){return this.#denomination}set denomination(value){if(value==null){this.#denomination=null;return}const denominationBigInt=handleBigInt(value.toString(),"denomination");if(!isValidDenomination(denominationBigInt)){throw new Error("Invalid denomination value")}this.#denomination=denominationBigInt}constructor(){this.#txhash=null;this.#index=null;this.#address=null;this.#denomination=null}toJSON(){return{txhash:this.txhash,index:this.index,address:this.address,denomination:this.denomination}}static from(utxo){if(utxo===null){return new UTXO}const result=utxo instanceof UTXO?utxo:new UTXO;if(utxo.txhash!=null){result.txhash=utxo.txhash}if(utxo.index!=null){result.index=utxo.index}if(utxo.address!=null&&utxo.address!==""){result.address=utxo.address}if(utxo.denomination!=null){result.denomination=utxo.denomination}return result}}class AbstractCoinSelector{#availableUXTOs;#spendOutputs;#changeOutputs;get availableUXTOs(){return this.#availableUXTOs}set availableUXTOs(value){this.#availableUXTOs=value.map(val=>{const utxo=UTXO.from(val);this._validateUTXO(utxo);return utxo})}get spendOutputs(){return this.#spendOutputs}set spendOutputs(value){this.#spendOutputs=value.map(utxo=>UTXO.from(utxo))}get changeOutputs(){return this.#changeOutputs}set changeOutputs(value){this.#changeOutputs=value.map(utxo=>UTXO.from(utxo))}constructor(availableUXTOs=[]){this.#availableUXTOs=availableUXTOs.map(val=>{const utxo=UTXO.from(val);this._validateUTXO(utxo);return utxo});this.#spendOutputs=[];this.#changeOutputs=[]}_validateUTXO(utxo){if(utxo.address==null){throw new Error("UTXO address is required")}if(utxo.denomination==null){throw new Error("UTXO denomination is required")}}}class FewestCoinSelector extends AbstractCoinSelector{performSelection(target){this.validateTarget(target);this.validateUTXOs();const sortedUTXOs=this.sortUTXOsByDenomination(this.availableUXTOs,"desc");let totalValue=BigInt(0);let selectedUTXOs=[];const UTXOsEqualOrGreaterThanTarget=sortedUTXOs.filter(utxo=>utxo.denomination&&utxo.denomination>=target.value);if(UTXOsEqualOrGreaterThanTarget.length>0){const optimalUTXO=UTXOsEqualOrGreaterThanTarget.reduce((minDenominationUTXO,currentUTXO)=>{if(!currentUTXO.denomination)return minDenominationUTXO;return currentUTXO.denomination0&&totalValue{if(!utxo.denomination)return closest;const absThisDiff=bigIntAbs(target.value-(totalValue+utxo.denomination));const currentClosestDiff=closest&&closest.denomination?bigIntAbs(target.value-(totalValue+closest.denomination)):BigInt(Infinity);return absThisDiffutxo.denomination===nextOptimalUTXO.denomination&&utxo.address===nextOptimalUTXO.address);sortedUTXOs.splice(index,1)}}if(totalValue=target.value){runningTotal-=utxo.denomination;lastRemovableIndex=i}else{break}}}if(lastRemovableIndex>=0){totalValue-=selectedUTXOs[lastRemovableIndex].denomination;selectedUTXOs.splice(lastRemovableIndex,1)}const spendDenominations=denominate(target.value);this.spendOutputs=spendDenominations.map(denomination=>{const utxo=new UTXO;utxo.denomination=denomination;utxo.address=target.address;return utxo});const change=totalValue-target.value;if(change>BigInt(0)){const changeDenominations=denominate(change);this.changeOutputs=changeDenominations.map(denomination=>{const utxo=new UTXO;utxo.denomination=denomination;return utxo})}else{this.changeOutputs=[]}return{inputs:selectedUTXOs,spendOutputs:this.spendOutputs,changeOutputs:this.changeOutputs}}sortUTXOsByDenomination(utxos,direction){if(direction==="asc"){return[...utxos].sort((a,b)=>{const diff=(a.denomination??BigInt(0))-(b.denomination??BigInt(0));return diff>0?1:diff<0?-1:0})}return[...utxos].sort((a,b)=>{const diff=(b.denomination??BigInt(0))-(a.denomination??BigInt(0));return diff>0?1:diff<0?-1:0})}validateTarget(target){if(target.value<=BigInt(0)){throw new Error("Target amount must be greater than 0")}}validateUTXOs(){if(this.availableUXTOs.length===0){throw new Error("No UTXOs available")}}}const BN_0$2=BigInt(0);function allowNull(format,nullValue){return function(value){if(value==null){return nullValue}return format(value)}}function arrayOf(format){return array=>{if(!Array.isArray(array)){throw new Error("not an array")}return array.map(i=>format(i))}}function object(format,altNames){return value=>{const result={};for(const key in format){let srcKey=key;if(altNames&&key in altNames&&!(srcKey in value)){for(const altKey of altNames[key]){if(altKey in value){srcKey=altKey;break}}}try{const nv=format[key](value[srcKey]);if(nv!==undefined){result[key]=nv}}catch(error){const message=error instanceof Error?error.message:"not-an-error";assert(false,`invalid value for value.${key} (${message})`,"BAD_DATA",{value:value})}}return result}}function formatBoolean(value){switch(value){case true:case"true":return true;case false:case"false":return false}assertArgument(false,`invalid boolean; ${JSON.stringify(value)}`,"value",value)}function formatData(value){assertArgument(isHexString(value),"invalid data","value",value);return value}function formatHash(value){assertArgument(isHexString(value,32),"invalid hash","value",value);return value}function handleNumber(_value,param){if(_value==="0x"){return 0}return getNumber(_value,param)}function formatNumber(_value,name){const value=getBigInt(_value,"value");const result=toBeArray(value);assertArgument(result.length<=32,`value too large`,`tx.${name}`,value);return result}const _formatLog=object({address:getAddress,blockHash:formatHash,blockNumber:getNumber,data:formatData,index:getNumber,removed:allowNull(formatBoolean,false),topics:arrayOf(formatHash),transactionHash:formatHash,transactionIndex:getNumber},{index:["logIndex"]});function formatLog(value){return _formatLog(value)}const _formatHeader=object({baseFeePerGas:getBigInt,efficiencyScore:getBigInt,etxEligibleSlices:formatHash,etxSetRoot:formatHash,evmRoot:formatHash,expansionNumber:getNumber,extRollupRoot:formatHash,extTransactionsRoot:formatHash,extraData:formatData,gasLimit:getBigInt,gasUsed:getBigInt,hash:formatHash,interlinkRootHash:formatHash,manifestHash:arrayOf(formatHash),number:arrayOf(getNumber),parentDeltaS:arrayOf(getBigInt),parentEntropy:arrayOf(getBigInt),parentHash:arrayOf(formatHash),parentUncledS:arrayOf(allowNull(getBigInt)),parentUncledSubDeltaS:arrayOf(getBigInt),primeTerminus:formatHash,receiptsRoot:formatHash,sha3Uncles:formatHash,size:getBigInt,thresholdCount:getBigInt,transactionsRoot:formatHash,uncledS:getBigInt,utxoRoot:formatHash});const _formatUncle=object({coinbase:allowNull(getAddress),difficulty:getBigInt,headerHash:formatHash,location:formatData,mixHash:formatHash,nonce:formatData,number:getNumber,parentHash:formatHash,primeTerminusNumber:getNumber,time:getBigInt,txHash:formatHash,workShare:formatBoolean});const _formatWoHeader=object({coinbase:getAddress,difficulty:getNumber,headerHash:formatHash,location:formatData,mixHash:formatHash,nonce:formatData,number:getNumber,parentHash:formatHash,primeTerminusNumber:getNumber,time:formatData,txHash:formatHash});const _formatBlock=object({extTransactions:arrayOf(tx=>{if(typeof tx==="string"){return formatHash(tx)}return formatExternalTransactionResponse(tx)}),hash:formatHash,header:_formatHeader,interlinkHashes:arrayOf(formatHash),order:getNumber,size:getBigInt,subManifest:arrayOf(formatData),totalEntropy:getBigInt,transactions:arrayOf(tx=>{if(typeof tx==="string"){return formatHash(tx)}return formatTransactionResponse(tx)}),uncles:allowNull(arrayOf(_formatUncle),[]),woHeader:_formatWoHeader});function formatBlock(value){const result=_formatBlock(value);result.transactions=value.transactions.map(tx=>{if(typeof tx==="string"){return tx}if("originatingTxHash"in tx){return formatExternalTransactionResponse(tx)}return formatTransactionResponse(tx)});result.extTransactions=value.extTransactions.map(tx=>{if(typeof tx==="string"){return tx}return formatExternalTransactionResponse(tx)});return result}const _formatReceiptLog=object({transactionIndex:getNumber,blockNumber:getNumber,transactionHash:formatHash,address:getAddress,topics:arrayOf(formatHash),data:formatData,index:getNumber,blockHash:formatHash},{index:["logIndex"]});function formatReceiptLog(value){return _formatReceiptLog(value)}const _formatEtx=object({type:allowNull(getNumber,0),nonce:allowNull(getNumber),gasPrice:allowNull(getBigInt),maxPriorityFeePerGas:allowNull(getBigInt),maxFeePerGas:allowNull(getBigInt),gas:allowNull(getBigInt),value:allowNull(getBigInt,BN_0$2),input:allowNull(formatData),to:allowNull(getAddress,null),accessList:allowNull(accessListify,null),isCoinbase:allowNull(getNumber,0),sender:getAddress,originatingTxHash:formatHash,etxIndex:getNumber,chainId:allowNull(getBigInt,null),hash:formatHash},{from:["sender"]});function formatEtx(value){return _formatEtx(value)}const _formatTransactionReceipt=object({to:allowNull(getAddress,null),from:allowNull(getAddress,null),contractAddress:allowNull(getAddress,null),index:getNumber,gasUsed:getBigInt,logsBloom:allowNull(formatData),blockHash:formatHash,hash:formatHash,logs:arrayOf(formatReceiptLog),blockNumber:getNumber,cumulativeGasUsed:getBigInt,effectiveGasPrice:allowNull(getBigInt),status:allowNull(getNumber),type:allowNull(getNumber,0),etxs:value=>value===null?[]:arrayOf(formatEtx)(value)},{hash:["transactionHash"],index:["transactionIndex"]});function formatTransactionReceipt(value){const result=_formatTransactionReceipt(value);return result}function formatExternalTransactionResponse(value){const result=object({hash:formatHash,type:value=>{if(value==="0x"||value==null){return 0}return parseInt(value,16)},accessList:allowNull(accessListify,null),blockHash:allowNull(formatHash,null),blockNumber:allowNull(value=>value?parseInt(value,16):null,null),index:allowNull(value=>value?BigInt(value):null,null),from:allowNull(getAddress,null),sender:allowNull(getAddress,null),maxPriorityFeePerGas:allowNull(value=>value?BigInt(value):null),maxFeePerGas:allowNull(value=>value?BigInt(value):null),gasLimit:allowNull(value=>value?BigInt(value):null,null),to:allowNull(getAddress,null),value:allowNull(value=>value?BigInt(value):null,null),nonce:allowNull(value=>value?parseInt(value,10):null,null),creates:allowNull(getAddress,null),chainId:allowNull(value=>value?BigInt(value):null,null),isCoinbase:allowNull(value=>value?parseInt(value,10):null,null),originatingTxHash:allowNull(formatHash,null),etxIndex:allowNull(value=>value?parseInt(value,10):null,null),etxType:allowNull(value=>value,null),data:value=>value},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(value);if(result.blockHash&&getBigInt(result.blockHash)===BN_0$2){result.blockHash=null}return result}function formatTransactionResponse(value){const transactionType=parseInt(value.type,16);let result;if(transactionType===0||transactionType===1){result=object({hash:formatHash,type:value=>{if(value==="0x"||value==null){return 0}return parseInt(value,16)},accessList:allowNull(accessListify,null),blockHash:allowNull(formatHash,null),blockNumber:allowNull(value=>value?parseInt(value,16):null,null),index:allowNull(value=>value?BigInt(value):null,null),from:allowNull(getAddress,null),sender:allowNull(getAddress,null),maxPriorityFeePerGas:allowNull(value=>value?BigInt(value):null),maxFeePerGas:allowNull(value=>value?BigInt(value):null),gasLimit:allowNull(value=>value?BigInt(value):null,null),to:allowNull(getAddress,null),value:allowNull(value=>value?BigInt(value):null,null),nonce:allowNull(value=>value?parseInt(value,10):null,null),creates:allowNull(getAddress,null),chainId:allowNull(value=>value?BigInt(value):null,null),etxType:allowNull(value=>value,null),data:value=>value},{data:["input"],gasLimit:["gas"],index:["transactionIndex"]})(value);if((value.type===0||value.type===2)&&value.accessList==null){result.accessList=[]}if(value.signature){result.signature=Signature.from(value.signature);if(result.chainId==null){const chainId=result.signature.legacyChainId;if(chainId!=null){result.chainId=chainId}}}if(result.blockHash&&getBigInt(result.blockHash)===BN_0$2){result.blockHash=null}}else if(transactionType===2){result=object({hash:formatHash,type:value=>{if(value==="0x"||value==null){return 0}return parseInt(value,16)},blockHash:allowNull(formatHash,null),blockNumber:allowNull(value=>value?parseInt(value,16):null,null),index:allowNull(value=>value?BigInt(value):null,null),chainId:allowNull(value=>value?BigInt(value):null,null),signature:value=>value,txInputs:allowNull(value=>value.map(_formatTxInput),null),txOutputs:allowNull(value=>value.map(_formatTxOutput),null)},{index:["transactionIndex"],signature:["utxoSignature"],txInputs:["inputs"],txOutputs:["outputs"]})(value)}else{throw new Error("Unknown transaction type")}return result}const _formatTxInput=object({txhash:formatTxHash,index:formatIndex,pubkey:hexlify},{txhash:["PreviousOutPoint","TxHash"],index:["PreviousOutPoint","Index"],pubkey:["PubKey"]});function extractTxHash(value){if(value&&value.TxHash){return value.TxHash}throw new Error("Invalid PreviousOutPoint")}function formatTxHash(value){return formatHash(extractTxHash(value))}function extractIndex(value){if(value&&value.Index!==undefined){return value.Index}throw new Error("Invalid PreviousOutPoint")}function formatIndex(value){return getNumber(extractIndex(value))}const _formatTxOutput=object({address:addr=>hexlify(getAddress(addr)),denomination:getNumber});class QiTransaction extends AbstractTransaction{#txInputs;#txOutputs;get txInputs(){return(this.#txInputs??[]).map(entry=>({...entry}))}set txInputs(value){if(!Array.isArray(value)){throw new Error("txInputs must be an array")}this.#txInputs=value.map(entry=>({...entry}))}get txOutputs(){return(this.#txOutputs??[]).map(output=>({...output}))}set txOutputs(value){if(!Array.isArray(value)){throw new Error("txOutputs must be an array")}this.#txOutputs=value.map(output=>({...output}))}get hash(){if(this.signature==null){return null}if(this.txInputs.length<1||this.txOutputs.length<1){throw new Error("Transaction must have at least one input and one output")}const senderAddr=computeAddress(this.txInputs[0].pubkey||"");if(!this.destZone||!this.originZone){throw new Error(`Invalid zones: origin ${this.originZone} -> destination ${this.destZone} (address: ${senderAddr})`)}const isSameLedger=isQiAddress(senderAddr)===isQiAddress(hexlify(this.txOutputs[0].address)||"");if(this.isExternal&&!isSameLedger){throw new Error("Cross-zone & cross-ledger transactions are not supported")}const hexString=this.serialized.startsWith("0x")?this.serialized.substring(2):this.serialized;const dataBuffer=Buffer.from(hexString,"hex");const hashHex=keccak256(dataBuffer);const hashBuffer=Buffer.from(hashHex.substring(2),"hex");const origin=this.originZone?parseInt(this.originZone.slice(2),16):0;hashBuffer[0]=origin;hashBuffer[1]|=128;hashBuffer[2]=origin;hashBuffer[3]|=128;return"0x"+hashBuffer.toString("hex")}get originZone(){const senderAddr=computeAddress(this.txInputs[0].pubkey||"");const zone=getZoneForAddress(senderAddr);return zone??undefined}get destZone(){const zone=getZoneForAddress(this.txOutputs[0].address);return zone??undefined}constructor(){super();this.#txInputs=[];this.#txOutputs=[]}inferTypes(){const types=[];if(this.type!=null){types.push(this.type)}else{types.push(2)}types.sort();return types}clone(){return QiTransaction.from(this)}toJSON(){const s=v=>{if(v==null){return null}return v.toString()};return{type:this.type,chainId:s(this.chainId),signature:this.signature?this.signature:null,hash:this.hash,txInputs:this.txInputs,txOutputs:this.txOutputs}}toProtobuf(includeSignature=true){const protoTx={type:this.type||2,chain_id:formatNumber(this.chainId||0,"chainId"),tx_ins:{tx_ins:this.txInputs.map(input=>({previous_out_point:{hash:{value:getBytes(input.txhash)},index:input.index},pub_key:getBytes(input.pubkey)}))},tx_outs:{tx_outs:this.txOutputs.map(output=>({address:getBytes(output.address),denomination:output.denomination}))}};if(this.signature&&includeSignature){protoTx.signature=getBytes(this.signature)}return protoTx}static from(tx){if(typeof tx==="string"){const decodedProtoTx=decodeProtoTransaction(getBytes(tx));return QiTransaction.fromProto(decodedProtoTx)}const result=new QiTransaction;if(tx.type!=null){result.type=tx.type}if(tx.chainId!=null){result.chainId=tx.chainId}if(tx.signature!=null&&tx.signature!==""){result.signature=tx.signature}if(tx.txInputs!=null){result.txInputs=tx.txInputs}if(tx.txOutputs!=null){result.txOutputs=tx.txOutputs}if(tx.hash!=null){assertArgument(result.isSigned(),"unsigned transaction cannot define hash","tx",tx)}return result}static fromProto(protoTx){const tx=new QiTransaction;tx.type=protoTx.type;tx.chainId=toBigInt(protoTx.chain_id);if(protoTx.type==2){tx.txInputs=protoTx.tx_ins?.tx_ins.map(input=>({txhash:hexlify(input.previous_out_point.hash.value),index:input.previous_out_point.index,pubkey:hexlify(input.pub_key)}))??[];tx.txOutputs=protoTx.tx_outs?.tx_outs.map(output=>({address:hexlify(output.address),denomination:output.denomination}))??[]}if(protoTx.signature){tx.signature=hexlify(protoTx.signature)}return tx}}function _parseSignature(fields){let yParity;try{yParity=handleNumber(fields[0],"yParity");if(yParity!==0&&yParity!==1){throw new Error("bad yParity")}}catch(error){assertArgument(false,"invalid yParity","yParity",fields[0])}const r=zeroPadValue(fields[1],32);const s=zeroPadValue(fields[2],32);return Signature.from({r:r,s:s,yParity:yParity})}class QuaiTransaction extends AbstractTransaction{#to;#data;#nonce;#gasLimit;#gasPrice;#maxPriorityFeePerGas;#maxFeePerGas;#value;#accessList;from;get to(){return this.#to}set to(value){if(value!==null)validateAddress(value);this.#to=value}get hash(){if(this.signature==null)return null;if(!this.originZone){throw new Error("Invalid Zone for from address")}if(!this.from){throw new Error("Missing from address")}const isSameLedger=!this.to||isQuaiAddress(this.from)===isQuaiAddress(this.to);if(this.isExternal&&!isSameLedger){throw new Error("Cross-zone & cross-ledger transactions are not supported")}const hexString=this.serialized.startsWith("0x")?this.serialized.substring(2):this.serialized;const dataBuffer=Buffer.from(hexString,"hex");const hashHex=keccak256(dataBuffer);const hashBuffer=Buffer.from(hashHex.substring(2),"hex");const origin=this.originZone?parseInt(this.originZone.slice(2),16):0;hashBuffer[0]=origin;hashBuffer[1]&=127;hashBuffer[2]=origin;hashBuffer[3]&=127;return"0x"+hashBuffer.toString("hex")}get originZone(){const zone=this.from?getZoneForAddress(this.from):undefined;return zone??undefined}get destZone(){const zone=this.to!==null?getZoneForAddress(this.to||""):undefined;return zone??undefined}get nonce(){return this.#nonce}set nonce(value){this.#nonce=getNumber(value,"value")}get gasLimit(){return this.#gasLimit}set gasLimit(value){this.#gasLimit=getBigInt(value)}get gasPrice(){const value=this.#gasPrice;return value}set gasPrice(value){this.#gasPrice=value==null?null:getBigInt(value,"gasPrice")}get maxPriorityFeePerGas(){const value=this.#maxPriorityFeePerGas;if(value==null){return null}return value}set maxPriorityFeePerGas(value){this.#maxPriorityFeePerGas=value==null?null:getBigInt(value,"maxPriorityFeePerGas")}get maxFeePerGas(){const value=this.#maxFeePerGas;if(value==null){return null}return value}set maxFeePerGas(value){this.#maxFeePerGas=value==null?null:getBigInt(value,"maxFeePerGas")}get data(){return this.#data}set data(value){this.#data=hexlify(value)}get value(){return this.#value}set value(value){this.#value=getBigInt(value,"value")}get accessList(){const value=this.#accessList||null;if(value==null){return null}return value}set accessList(value){this.#accessList=value==null?null:accessListify(value)}constructor(from){super();this.#to=null;this.#nonce=0;this.#gasLimit=BigInt(0);this.#gasPrice=null;this.#maxPriorityFeePerGas=null;this.#maxFeePerGas=null;this.#data="0x";this.#value=BigInt(0);this.#accessList=null;this.from=from}inferTypes(){if(this.maxFeePerGas!=null&&this.maxPriorityFeePerGas!=null){assert(this.maxFeePerGas>=this.maxPriorityFeePerGas,"priorityFee cannot be more than maxFee","BAD_DATA",{value:this})}assert(this.type!==0&&this.type!==1,"transaction type cannot have externalGasLimit, externalGasTip, externalGasPrice, externalData, or externalAccessList","BAD_DATA",{value:this});const types=[];if(this.type!=null){types.push(this.type)}else{types.push(0)}types.sort();return types}clone(){return QuaiTransaction.from(this)}toJSON(){const s=v=>{if(v==null){return null}return v.toString()};return{type:this.type,to:this.to,from:this.from,data:this.data,nonce:this.nonce,gasLimit:s(this.gasLimit),gasPrice:s(this.gasPrice),maxPriorityFeePerGas:s(this.maxPriorityFeePerGas),maxFeePerGas:s(this.maxFeePerGas),value:s(this.value),chainId:s(this.chainId),signature:this.signature?this.signature.toJSON():null,hash:this.hash,accessList:this.accessList}}toProtobuf(includeSignature=true){const protoTx={type:this.type||0,chain_id:formatNumber(this.chainId||0,"chainId"),nonce:this.nonce||0,gas_tip_cap:formatNumber(this.maxPriorityFeePerGas||0,"maxPriorityFeePerGas"),gas_fee_cap:formatNumber(this.maxFeePerGas||0,"maxFeePerGas"),gas:Number(this.gasLimit||0),to:this.to!=null?getBytes(this.to):null,value:formatNumber(this.value||0,"value"),data:getBytes(this.data||"0x"),access_list:{access_tuples:[]}};if(this.signature&&includeSignature){protoTx.v=formatNumber(this.signature.yParity,"yParity");protoTx.r=toBeArray(this.signature.r);protoTx.s=toBeArray(this.signature.s)}return protoTx}static from(tx){if(typeof tx==="string"){const decodedProtoTx=decodeProtoTransaction(getBytes(tx));return QuaiTransaction.fromProto(decodedProtoTx)}const result=new QuaiTransaction(tx.from);if(tx.type!=null){result.type=tx.type}if(tx.to!=null){validateAddress(tx.to);result.to=tx.to}if(tx.nonce!=null){result.nonce=tx.nonce}if(tx.gasLimit!=null){result.gasLimit=tx.gasLimit}if(tx.maxPriorityFeePerGas!=null){result.maxPriorityFeePerGas=tx.maxPriorityFeePerGas}if(tx.maxFeePerGas!=null){result.maxFeePerGas=tx.maxFeePerGas}if(tx.data!=null&&tx.data!==""){result.data=tx.data}if(tx.value!=null){result.value=tx.value}if(tx.chainId!=null){result.chainId=tx.chainId}if(tx.signature!=null){result.signature=Signature.from(tx.signature)}if(tx.accessList!=null){result.accessList=tx.accessList}if(tx.hash!=null){assertArgument(result.isSigned(),"unsigned transaction cannot define hash","tx",tx)}if(tx.from!=null){assertArgument(isQuaiAddress(tx.from),"from address must be a Quai address","tx.from",tx.from);assertArgument((result.from||"").toLowerCase()===(tx.from||"").toLowerCase(),"from mismatch","tx",tx);result.from=tx.from}return result}static fromProto(protoTx){let signature=null;let address="";if(protoTx.v&&protoTx.r&&protoTx.s){if(protoTx.r.reduce((acc,val)=>acc+=val,0)==0){throw new Error("Proto decoding only supported for signed transactions")}const signatureFields=[hexlify(protoTx.v),hexlify(protoTx.r),hexlify(protoTx.s)];signature=_parseSignature(signatureFields);const protoTxCopy=structuredClone(protoTx);delete protoTxCopy.v;delete protoTxCopy.r;delete protoTxCopy.s;delete protoTxCopy.signature;delete protoTxCopy.etx_sender;delete protoTxCopy.etx_index;address=recoverAddress(keccak256(encodeProtoTransaction(protoTxCopy)),signature)}const tx=new QuaiTransaction(address);if(signature){tx.signature=signature}if(protoTx.to!==null){const toAddr=hexlify(protoTx.to);tx.to=getAddress(toAddr)}tx.type=protoTx.type;tx.chainId=toBigInt(protoTx.chain_id);tx.nonce=Number(protoTx.nonce);tx.maxPriorityFeePerGas=toBigInt(protoTx.gas_tip_cap);tx.maxFeePerGas=toBigInt(protoTx.gas_fee_cap);tx.gasLimit=toBigInt(protoTx.gas);tx.value=protoTx.value!==null?toBigInt(protoTx.value):BigInt(0);tx.data=hexlify(protoTx.data);tx.accessList=protoTx.access_list.access_tuples.map(tuple=>({address:hexlify(tuple.address),storageKeys:tuple.storage_key.map(key=>hexlify(key))}));return tx}}const BN_0$1=BigInt(0);function getValue(value){if(value==null){return null}return value}function toJson(value){if(value==null){return null}return value.toString()}class FeeData{gasPrice;maxFeePerGas;maxPriorityFeePerGas;constructor(gasPrice,maxFeePerGas,maxPriorityFeePerGas){defineProperties(this,{gasPrice:getValue(gasPrice),maxFeePerGas:getValue(maxFeePerGas),maxPriorityFeePerGas:getValue(maxPriorityFeePerGas)})}toJSON(){const{gasPrice,maxFeePerGas,maxPriorityFeePerGas}=this;return{_type:"FeeData",gasPrice:toJson(gasPrice),maxFeePerGas:toJson(maxFeePerGas),maxPriorityFeePerGas:toJson(maxPriorityFeePerGas)}}}function addressFromTransactionRequest(tx){if("from"in tx&&!!tx.from){return tx.from}if("txInputs"in tx&&!!tx.txInputs){return computeAddress(tx.txInputs[0].pubkey)}if("to"in tx&&!!tx.to){return tx.to}throw new Error("Unable to determine address from transaction inputs, from or to field")}function copyRequest(req){const result={};if("to"in req&&req.to){result.to=req.to}if("from"in req&&req.from){result.from=req.from}if("data"in req&&req.data){result.data=hexlify(req.data)}const bigIntKeys="chainId,gasLimit,gasPrice,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/);for(const key of bigIntKeys){if(!(key in req)||req[key]==null){continue}result[key]=getBigInt(req[key],`request.${key}`)}const numberKeys="type,nonce".split(/,/);for(const key of numberKeys){if(!(key in req)||req[key]==null){continue}result[key]=getNumber(req[key],`request.${key}`)}if("accessList"in req&&req.accessList){result.accessList=accessListify(req.accessList)}if("blockTag"in req){result.blockTag=req.blockTag}if("customData"in req){result.customData=req.customData}if("txInputs"in req&&req.txInputs){result.txInputs=req.txInputs.map(entry=>({...entry}))}if("txOutputs"in req&&req.txOutputs){result.txOutputs=req.txOutputs.map(entry=>({...entry}))}return result}class BlockHeader{baseFeePerGas;efficiencyScore;etxEligibleSlices;etxSetRoot;evmRoot;expansionNumber;extRollupRoot;extTransactionsRoot;extraData;gasLimit;gasUsed;hash;interlinkRootHash;manifestHash;number;parentDeltaS;parentEntropy;parentHash;parentUncledS;parentUncledSubDeltaS;primeTerminus;receiptsRoot;sha3Uncles;size;thresholdCount;transactionsRoot;uncledS;utxoRoot;constructor(params){this.baseFeePerGas=params.baseFeePerGas;this.efficiencyScore=params.efficiencyScore;this.etxEligibleSlices=params.etxEligibleSlices;this.etxSetRoot=params.etxSetRoot;this.evmRoot=params.evmRoot;this.expansionNumber=params.expansionNumber;this.extRollupRoot=params.extRollupRoot;this.extTransactionsRoot=params.extTransactionsRoot;this.extraData=params.extraData;this.gasLimit=params.gasLimit;this.gasUsed=params.gasUsed;this.hash=params.hash;this.interlinkRootHash=params.interlinkRootHash;this.manifestHash=params.manifestHash;this.number=params.number;this.parentDeltaS=params.parentDeltaS;this.parentEntropy=params.parentEntropy;this.parentHash=params.parentHash;this.parentUncledS=params.parentUncledS;this.parentUncledSubDeltaS=params.parentUncledSubDeltaS;this.primeTerminus=params.primeTerminus;this.receiptsRoot=params.receiptsRoot;this.sha3Uncles=params.sha3Uncles;this.size=params.size;this.thresholdCount=params.thresholdCount;this.transactionsRoot=params.transactionsRoot;this.uncledS=params.uncledS;this.utxoRoot=params.utxoRoot}toJSON(){return{baseFeePerGas:this.baseFeePerGas,efficiencyScore:this.efficiencyScore,etxEligibleSlices:this.etxEligibleSlices,etxSetRoot:this.etxSetRoot,evmRoot:this.evmRoot,expansionNumber:this.expansionNumber,extRollupRoot:this.extRollupRoot,extTransactionsRoot:this.extTransactionsRoot,extraData:this.extraData,gasLimit:this.gasLimit,gasUsed:this.gasUsed,hash:this.hash,interlinkRootHash:this.interlinkRootHash,manifestHash:this.manifestHash,number:this.number,parentDeltaS:this.parentDeltaS,parentEntropy:this.parentEntropy,parentHash:this.parentHash,parentUncledS:this.parentUncledS,parentUncledSubDeltaS:this.parentUncledSubDeltaS,primeTerminus:this.primeTerminus,receiptsRoot:this.receiptsRoot,sha3Uncles:this.sha3Uncles,size:this.size,thresholdCount:this.thresholdCount,transactionsRoot:this.transactionsRoot,uncledS:this.uncledS,utxoRoot:this.utxoRoot}}}class WoHeader{difficulty;headerHash;location;mixHash;nonce;number;parentHash;time;txHash;constructor(params){this.difficulty=params.difficulty;this.headerHash=params.headerHash;this.location=params.location;this.mixHash=params.mixHash;this.nonce=params.nonce;this.number=params.number;this.parentHash=params.parentHash;this.time=params.time;this.txHash=params.txHash}toJSON(){return{difficulty:this.difficulty,headerHash:this.headerHash,location:this.location,mixHash:this.mixHash,nonce:this.nonce,number:this.number,parentHash:this.parentHash,time:this.time,txHash:this.txHash}}}class Block{#extTransactions;hash;header;interlinkHashes;order;size;subManifest;totalEntropy;#transactions;uncles;woHeader;provider;constructor(block,provider){this.#transactions=block.transactions.map(tx=>{if(typeof tx==="string"){return tx}if("originatingTxHash"in tx){return new ExternalTransactionResponse(tx,provider)}if("from"in tx){return new QuaiTransactionResponse(tx,provider)}return new QiTransactionResponse(tx,provider)});this.#extTransactions=block.extTransactions.map(tx=>{if(typeof tx!=="string"){return new ExternalTransactionResponse(tx,provider)}return tx});this.hash=block.hash;this.header=new BlockHeader(block.header);this.interlinkHashes=block.interlinkHashes;this.order=block.order;this.size=block.size;this.subManifest=block.subManifest;this.totalEntropy=block.totalEntropy;this.uncles=block.uncles;this.woHeader=new WoHeader(block.woHeader);this.provider=provider}get transactions(){return this.#transactions.map(tx=>{if(typeof tx==="string"){return tx}return tx.hash})}get extTransactions(){return this.#extTransactions.map(tx=>{if(typeof tx==="string"){return tx}return tx.hash})}get prefetchedTransactions(){const txs=this.#transactions.slice();if(txs.length===0){return[]}assert(typeof txs[0]==="object","transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"});return txs}get prefetchedExtTransactions(){const txs=this.#extTransactions.slice();if(txs.length===0){return[]}assert(typeof txs[0]==="object","transactions were not prefetched with block request","UNSUPPORTED_OPERATION",{operation:"transactionResponses()"});return txs}toJSON(){const{hash,header,interlinkHashes,order,size,subManifest,totalEntropy,uncles,woHeader}=this;const transactions=this.transactions;const extTransactions=this.extTransactions;return{_type:"Block",hash:hash,header:header.toJSON(),interlinkHashes:interlinkHashes,order:order,size:toJson(size),subManifest:subManifest,totalEntropy:toJson(totalEntropy),uncles:uncles,woHeader:woHeader.toJSON(),transactions:transactions,extTransactions:extTransactions}}[Symbol.iterator](){let index=0;const txs=this.transactions;return{next:()=>{if(index{return new Log(log,provider)}));let gasPrice=BN_0$1;if(tx.effectiveGasPrice!=null){gasPrice=tx.effectiveGasPrice}else if(tx.gasPrice!=null){gasPrice=tx.gasPrice}const etxs=tx.etxs?tx.etxs.map(etx=>{const safeConvert=(value,name)=>{try{if(value!=null){return BigInt(value)}return null}catch(error){console.error(`Conversion to BigInt failed for ${name}: ${value}, error: ${error}`);return null}};return{type:etx.type,nonce:etx.nonce,gasPrice:safeConvert(etx.gasPrice,"gasPrice"),maxPriorityFeePerGas:safeConvert(etx.maxPriorityFeePerGas,"maxPriorityFeePerGas"),maxFeePerGas:safeConvert(etx.maxFeePerGas,"maxFeePerGas"),gas:safeConvert(etx.gas,"gas"),value:safeConvert(etx.value,"value"),input:etx.input,to:etx.to,accessList:etx.accessList,chainId:safeConvert(etx.chainId,"chainId"),sender:etx.sender,hash:etx.hash,isCoinbase:etx.isCoinbase,originatingTxHash:etx.originatingTxHash,etxIndex:etx.etxIndex}}):[];defineProperties(this,{provider:provider,to:tx.to,from:tx.from,contractAddress:tx.contractAddress,hash:tx.hash,index:tx.index,blockHash:tx.blockHash,blockNumber:tx.blockNumber,logsBloom:tx.logsBloom,gasUsed:tx.gasUsed,cumulativeGasUsed:tx.cumulativeGasUsed,gasPrice:gasPrice,etxs:etxs,type:tx.type,status:tx.status})}get logs(){return this.#logs}toJSON(){const{to,from,contractAddress,hash,index,blockHash,blockNumber,logsBloom,logs,status,etxs}=this;return{_type:"TransactionReceipt",blockHash:blockHash,blockNumber:blockNumber,contractAddress:contractAddress,cumulativeGasUsed:toJson(this.cumulativeGasUsed),from:from,gasPrice:toJson(this.gasPrice),gasUsed:toJson(this.gasUsed),hash:hash,index:index,logs:logs,logsBloom:logsBloom,status:status,to:to,etxs:etxs??[]}}get length(){return this.logs.length}[Symbol.iterator](){let index=0;return{next:()=>{if(index=0,"invalid startBlock","startBlock",startBlock);const tx=new ExternalTransactionResponse(this,this.provider);tx.startBlock=startBlock;return tx}}class QuaiTransactionResponse{provider;blockNumber;blockHash;index;hash;type;to;from;nonce;gasLimit;maxPriorityFeePerGas;maxFeePerGas;data;value;chainId;signature;accessList;etxType;sender;originatingTxHash;startBlock;constructor(tx,provider){this.provider=provider;this.blockNumber=tx.blockNumber!=null?tx.blockNumber:null;this.blockHash=tx.blockHash!=null?tx.blockHash:null;this.hash=tx.hash;this.index=tx.index;this.type=tx.type;this.from=tx.from;this.to=tx.to||null;this.gasLimit=tx.gasLimit;this.nonce=tx.nonce;this.data=tx.data;this.value=tx.value;this.maxPriorityFeePerGas=tx.maxPriorityFeePerGas!=null?tx.maxPriorityFeePerGas:null;this.maxFeePerGas=tx.maxFeePerGas!=null?tx.maxFeePerGas:null;this.chainId=tx.chainId;this.signature=tx.signature;this.accessList=tx.accessList!=null?tx.accessList:null;this.startBlock=-1;this.etxType=tx.etxType!=null?tx.etxType:null}toJSON(){const{blockNumber,blockHash,index,hash,type,to,from,nonce,data,signature,accessList}=this;const result={_type:"TransactionReceipt",accessList:accessList,blockNumber:blockNumber,blockHash:blockHash,chainId:toJson(this.chainId),data:data,from:from,gasLimit:toJson(this.gasLimit),hash:hash,maxFeePerGas:toJson(this.maxFeePerGas),maxPriorityFeePerGas:toJson(this.maxPriorityFeePerGas),nonce:nonce,signature:signature,to:to,index:index,type:type,value:toJson(this.value)};return result}async getBlock(shard){let blockNumber=this.blockNumber;if(blockNumber==null){const tx=await this.getTransaction();if(tx){blockNumber=tx.blockNumber}}if(blockNumber==null){return null}const block=this.provider.getBlock(shard,blockNumber);if(block==null){throw new Error("TODO")}return block}async getTransaction(){const transaction=this.provider.getTransaction(this.hash);if(transaction instanceof QuaiTransactionResponse){return transaction}else{return null}}async confirmations(){const zone=zoneFromHash(this.hash);if(this.blockNumber==null){const{tx,blockNumber}=await resolveProperties({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber(toShard(zone))});if(tx==null||tx.blockNumber==null){return 0}return blockNumber-tx.blockNumber+1}const blockNumber=await this.provider.getBlockNumber(toShard(zone));return blockNumber-this.blockNumber+1}async wait(_confirms,_timeout){const confirms=_confirms==null?1:_confirms;const timeout=_timeout==null?0:_timeout;let startBlock=this.startBlock;let nextScan=-1;let stopScanning=startBlock===-1?true:false;const zone=zoneFromHash(this.hash);const checkReplacement=async()=>{if(stopScanning){return null}const{blockNumber,nonce}=await resolveProperties({blockNumber:this.provider.getBlockNumber(toShard(zone)),nonce:this.provider.getTransactionCount(this.from)});if(nonce{if(receipt==null||receipt.status!==0){return receipt}assert(false,"transaction execution reverted","CALL_EXCEPTION",{action:"sendTransaction",data:null,reason:null,invocation:null,revert:null,transaction:{to:receipt.to,from:receipt.from,data:""},receipt:receipt})};const receipt=await this.provider.getTransactionReceipt(this.hash);if(confirms===0){return checkReceipt(receipt)}if(receipt){if(await receipt.confirmations()>=confirms){return checkReceipt(receipt)}}else{await checkReplacement();if(confirms===0){return null}}const waiter=new Promise((resolve,reject)=>{const cancellers=[];const cancel=()=>{cancellers.forEach(c=>c())};cancellers.push(()=>{stopScanning=true});if(timeout>0){const timer=setTimeout(()=>{cancel();reject(makeError("wait for transaction timeout","TIMEOUT"))},timeout);cancellers.push(()=>{clearTimeout(timer)})}const txListener=async receipt=>{if(await receipt.confirmations()>=confirms){cancel();try{resolve(checkReceipt(receipt))}catch(error){reject(error)}}};cancellers.push(()=>{this.provider.off(this.hash,txListener)});this.provider.on(this.hash,txListener);if(startBlock>=0){const replaceListener=async()=>{try{await checkReplacement()}catch(error){if(isError(error,"TRANSACTION_REPLACED")){cancel();reject(error);return}}if(!stopScanning){this.provider.once("block",replaceListener)}};cancellers.push(()=>{this.provider.off("block",replaceListener)});this.provider.once("block",replaceListener)}});return await waiter}isMined(){return this.blockHash!=null}removedEvent(){assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});return createRemovedTransactionFilter(this)}reorderedEvent(other){assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});assert(!other||other.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});return createReorderedTransactionFilter(this,other)}replaceableTransaction(startBlock){assertArgument(Number.isInteger(startBlock)&&startBlock>=0,"invalid startBlock","startBlock",startBlock);const tx=new QuaiTransactionResponse(this,this.provider);tx.startBlock=startBlock;return tx}}class QiTransactionResponse{provider;blockNumber;blockHash;index;hash;type;chainId;signature;txInputs;txOutputs;startBlock;constructor(tx,provider){this.provider=provider;this.blockNumber=tx.blockNumber!=null?tx.blockNumber:null;this.blockHash=tx.blockHash!=null?tx.blockHash:null;this.hash=tx.hash;this.index=tx.index;this.type=tx.type;this.chainId=tx.chainId;this.signature=tx.signature;this.startBlock=-1;this.txInputs=tx.txInputs;this.txOutputs=tx.txOutputs}toJSON(){const{blockNumber,blockHash,index,hash,type,signature,txInputs,txOutputs}=this;const result={_type:"TransactionReceipt",blockNumber:blockNumber,blockHash:blockHash,chainId:toJson(this.chainId),hash:hash,signature:signature,index:index,type:type,txInputs:JSON.parse(JSON.stringify(txInputs)),txOutputs:JSON.parse(JSON.stringify(txOutputs))};return result}async getBlock(shard){let blockNumber=this.blockNumber;if(blockNumber==null){const tx=await this.getTransaction();if(tx){blockNumber=tx.blockNumber}}if(blockNumber==null){return null}const block=this.provider.getBlock(shard,blockNumber);if(block==null){throw new Error("TODO")}return block}async getTransaction(){const transaction=this.provider.getTransaction(this.hash);if(transaction instanceof QiTransactionResponse){return transaction}else{return null}}async confirmations(){const zone=zoneFromHash(this.hash);if(this.blockNumber==null){const{tx,blockNumber}=await resolveProperties({tx:this.getTransaction(),blockNumber:this.provider.getBlockNumber(toShard(zone))});if(tx==null||tx.blockNumber==null){return 0}return blockNumber-tx.blockNumber+1}const blockNumber=await this.provider.getBlockNumber(toShard(zone));return blockNumber-this.blockNumber+1}isMined(){return this.blockHash!=null}removedEvent(){assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});return createRemovedTransactionFilter(this)}reorderedEvent(other){assert(this.isMined(),"unmined transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});assert(!other||other.isMined(),"unmined 'other' transaction canot be orphaned","UNSUPPORTED_OPERATION",{operation:"removeEvent()"});return createReorderedTransactionFilter(this,other)}replaceableTransaction(startBlock){assertArgument(Number.isInteger(startBlock)&&startBlock>=0,"invalid startBlock","startBlock",startBlock);const tx=new QiTransactionResponse(this,this.provider);tx.startBlock=startBlock;return tx}}function createOrphanedBlockFilter(block){return{orphan:"drop-block",hash:block.hash,number:block.number}}function createReorderedTransactionFilter(tx,other){return{orphan:"reorder-transaction",tx:tx,other:other}}function createRemovedTransactionFilter(tx){return{orphan:"drop-transaction",tx:tx}}function createRemovedLogFilter(log){return{orphan:"drop-log",log:{transactionHash:log.transactionHash,blockHash:log.blockHash,blockNumber:log.blockNumber,address:log.address,data:log.data,topics:Object.freeze(log.topics.slice()),index:log.index}}}function getZoneFromEventFilter(filter){let zone=null;if(filter.nodeLocation){zone=getZoneFromNodeLocation(filter.nodeLocation)}else if(filter.address){let address;if(Array.isArray(filter.address)){address=filter.address[0]}else{address=filter.address}const addressZone=getZoneForAddress(address);if(addressZone){zone=toZone(addressZone)}else{return null}}return zone}class EventLog extends Log{interface;fragment;args;constructor(log,iface,fragment){super(log,log.provider);const args=iface.decodeEventLog(fragment,log.data,log.topics);defineProperties(this,{args:args,fragment:fragment,interface:iface})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}class UndecodedEventLog extends Log{error;constructor(log,error){super(log,log.provider);defineProperties(this,{error:error})}}class ContractTransactionReceipt extends TransactionReceipt{#iface;constructor(iface,provider,tx){super(tx,provider);this.#iface=iface}get logs(){return super.logs.map(log=>{const fragment=log.topics.length?this.#iface.getEvent(log.topics[0]):null;if(fragment){try{return new EventLog(log,this.#iface,fragment)}catch(error){return new UndecodedEventLog(log,error)}}return log})}}class ContractTransactionResponse extends QuaiTransactionResponse{#iface;constructor(iface,provider,tx){super(tx,provider);this.#iface=iface}async wait(confirms){const receipt=await super.wait(confirms);if(receipt==null){return null}return new ContractTransactionReceipt(this.#iface,this.provider,receipt)}}class ContractUnknownEventPayload extends EventPayload{log;constructor(contract,listener,filter,log){super(contract,listener,filter);defineProperties(this,{log:log})}async getBlock(shard){return await this.log.getBlock(shard)}async getTransaction(){return await this.log.getTransaction()}async getTransactionReceipt(){return await this.log.getTransactionReceipt()}}class ContractEventPayload extends ContractUnknownEventPayload{constructor(contract,listener,filter,fragment,_log){super(contract,listener,filter,new EventLog(_log,contract.interface,fragment));const args=contract.interface.decodeEventLog(fragment,this.log.data,this.log.topics);defineProperties(this,{args:args,fragment:fragment})}get eventName(){return this.fragment.name}get eventSignature(){return this.fragment.format()}}const BN_0=BigInt(0);function canCall(value){return value&&typeof value.call==="function"}function canEstimate(value){return value&&typeof value.estimateGas==="function"}function canSend(value){return value&&typeof value.sendTransaction==="function"}class PreparedTopicFilter{#filter;fragment;constructor(contract,fragment,args){defineProperties(this,{fragment:fragment});if(fragment.inputs.length{const arg=args[index];if(arg==null){return null}return param.walkAsync(args[index],(type,value)=>{if(type==="address"){if(Array.isArray(value)){return Promise.all(value.map(v=>resolveAddress(v)))}return resolveAddress(value)}return value})}));return contract.interface.encodeFilterTopics(fragment,resolvedArgs)}()}getTopicFilter(){return this.#filter}}function getRunner(value,feature){if(value==null){return null}if(typeof value[feature]==="function"){return value}if(value.provider&&typeof value.provider[feature]==="function"){return value.provider}return null}function getProvider(value){if(value==null){return null}return value.provider||null}async function copyOverrides(arg,allowed){const _overrides=Typed.dereference(arg,"overrides");assertArgument(typeof _overrides==="object","invalid overrides parameter","overrides",arg);const overrides=copyRequest(_overrides);assertArgument(!("to"in overrides)||overrides.to==null||(allowed||[]).indexOf("to")>=0,"cannot override to","overrides.to",overrides);assertArgument(!("data"in overrides)||overrides.data==null||(allowed||[]).indexOf("data")>=0,"cannot override data","overrides.data",overrides);if("from"in overrides&&overrides.from){overrides.from=await overrides.from}return overrides}async function resolveArgs(_runner,inputs,args){return await Promise.all(inputs.map((param,index)=>{return param.walkAsync(args[index],(type,value)=>{value=Typed.dereference(value,type);if(type==="address"){return resolveAddress(value)}return value})}))}function buildWrappedFallback(contract){const populateTransaction=async function(overrides){const tx=await copyOverrides(overrides,["data"]);tx.to=await contract.getAddress();validateAddress(tx.to);if(tx.from){tx.from=await resolveAddress(tx.from);validateAddress(tx.from)}const iface=contract.interface;const noValue=getBigInt(tx.value||BN_0,"overrides.value")===BN_0;const noData=(tx.data||"0x")==="0x";if(iface.fallback&&!iface.fallback.payable&&iface.receive&&!noData&&!noValue){assertArgument(false,"cannot send data to receive or send value to non-payable fallback","overrides",overrides)}assertArgument(iface.fallback||noData,"cannot send data to receive-only contract","overrides.data",tx.data);const payable=iface.receive||iface.fallback&&iface.fallback.payable;assertArgument(payable||noValue,"cannot send value to non-payable fallback","overrides.value",tx.value);assertArgument(iface.fallback||noData,"cannot send data to receive-only contract","overrides.data",tx.data);return tx};const staticCall=async function(overrides){const runner=getRunner(contract.runner,"call");assert(canCall(runner),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const tx=await populateTransaction(overrides);try{return await runner.call(tx)}catch(error){if(isCallException(error)&&error.data){throw contract.interface.makeError(error.data,tx)}throw error}};const send=async function(overrides){const runner=contract.runner;assert(canSend(runner),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const tx=await runner.sendTransaction(await populateTransaction(overrides));const provider=getProvider(contract.runner);return new ContractTransactionResponse(contract.interface,provider,tx)};const estimateGas=async function(overrides){const runner=getRunner(contract.runner,"estimateGas");assert(canEstimate(runner),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"});return await runner.estimateGas(await populateTransaction(overrides))};const method=async overrides=>{return await send(overrides)};defineProperties(method,{_contract:contract,estimateGas:estimateGas,populateTransaction:populateTransaction,send:send,staticCall:staticCall});return method}function buildWrappedMethod(contract,key){const getFragment=function(...args){const fragment=contract.interface.getFunction(key,args);assert(fragment,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:key,args:args}});return fragment};const populateTransaction=async function(...args){const fragment=getFragment(...args);let overrides;if(fragment.inputs.length+1===args.length){overrides=await copyOverrides(args.pop());const resolvedArgs=await resolveArgs(contract.runner,fragment.inputs,args);return Object.assign({},overrides,await resolveProperties({to:contract.getAddress(),data:contract.interface.encodeFunctionData(fragment,resolvedArgs)}))}if(fragment.inputs.length!==args.length){throw new Error("internal error: fragment inputs doesn't match arguments; should not happen")}const resolvedArgs=await resolveArgs(contract.runner,fragment.inputs,args);return await resolveProperties({to:contract.getAddress(),from:args.pop()?.from,data:contract.interface.encodeFunctionData(fragment,resolvedArgs)})};const staticCall=async function(...args){const result=await staticCallResult(...args);if(result.length===1){return result[0]}return result};const send=async function(...args){const runner=contract.runner;assert(canSend(runner),"contract runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});const pop=await populateTransaction(...args);if(!pop.from&&"address"in runner&&typeof runner.address==="string"){pop.from=await resolveAddress(runner.address)}const tx=await runner.sendTransaction(await pop);const provider=getProvider(contract.runner);return new ContractTransactionResponse(contract.interface,provider,tx)};const estimateGas=async function(...args){const runner=getRunner(contract.runner,"estimateGas");assert(canEstimate(runner),"contract runner does not support gas estimation","UNSUPPORTED_OPERATION",{operation:"estimateGas"});return await runner.estimateGas(await populateTransaction(...args))};const staticCallResult=async function(...args){const runner=getRunner(contract.runner,"call");assert(canCall(runner),"contract runner does not support calling","UNSUPPORTED_OPERATION",{operation:"call"});const tx=await populateTransaction(...args);if(!tx.from&&"address"in runner&&typeof runner.address==="string"){tx.from=await resolveAddress(runner.address)}let result="0x";try{result=await runner.call(tx)}catch(error){if(isCallException(error)&&error.data){throw contract.interface.makeError(error.data,tx)}throw error}const fragment=getFragment(...args);return contract.interface.decodeFunctionResult(fragment,result)};const method=async(...args)=>{const fragment=getFragment(...args);if(fragment.constant){return await staticCall(...args)}return await send(...args)};defineProperties(method,{name:contract.interface.getFunctionName(key),_contract:contract,_key:key,getFragment:getFragment,estimateGas:estimateGas,populateTransaction:populateTransaction,send:send,staticCall:staticCall,staticCallResult:staticCallResult});Object.defineProperty(method,"fragment",{configurable:false,enumerable:true,get:()=>{const fragment=contract.interface.getFunction(key);assert(fragment,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:key}});return fragment}});return method}function buildWrappedEvent(contract,key){const getFragment=function(...args){const fragment=contract.interface.getEvent(key,args);assert(fragment,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:key,args:args}});return fragment};const method=function(...args){return new PreparedTopicFilter(contract,getFragment(...args),args)};defineProperties(method,{name:contract.interface.getEventName(key),_contract:contract,_key:key,getFragment:getFragment});Object.defineProperty(method,"fragment",{configurable:false,enumerable:true,get:()=>{const fragment=contract.interface.getEvent(key);assert(fragment,"no matching fragment","UNSUPPORTED_OPERATION",{operation:"fragment",info:{key:key}});return fragment}});return method}const internal=Symbol.for("_quaisInternal_contract");const internalValues=new WeakMap;function setInternal(contract,values){internalValues.set(contract[internal],values)}function getInternal(contract){return internalValues.get(contract[internal])}function isDeferred(value){return value&&typeof value==="object"&&"getTopicFilter"in value&&typeof value.getTopicFilter==="function"&&value.fragment}async function getSubInfo(contract,event){let topics;let fragment=null;if(Array.isArray(event)){const topicHashify=function(name){if(isHexString(name,32)){return name}const fragment=contract.interface.getEvent(name);assertArgument(fragment,"unknown fragment","name",name);return fragment.topicHash};topics=event.map(e=>{if(e==null){return null}if(Array.isArray(e)){return e.map(topicHashify)}return topicHashify(e)})}else if(event==="*"){topics=[null]}else if(typeof event==="string"){if(isHexString(event,32)){topics=[event]}else{fragment=contract.interface.getEvent(event);assertArgument(fragment,"unknown fragment","event",event);topics=[fragment.topicHash]}}else if(isDeferred(event)){topics=await event.getTopicFilter()}else if(event&&"fragment"in event){fragment=event.fragment;topics=[fragment.topicHash]}else{assertArgument(false,"unknown event name","event",event)}topics=topics.map(t=>{if(t==null){return null}if(Array.isArray(t)){const items=Array.from(new Set(t.map(t=>t.toLowerCase())).values());if(items.length===1){return items[0]}items.sort();return items}return t.toLowerCase()});const tag=topics.map(t=>{if(t==null){return"null"}if(Array.isArray(t)){return t.join("|")}return t}).join("&");return{fragment:fragment,tag:tag,topics:topics}}async function hasSub(contract,event){const{subs}=getInternal(contract);return subs.get((await getSubInfo(contract,event)).tag)||null}async function getSub(contract,operation,event){const provider=getProvider(contract.runner);assert(provider,"contract runner does not support subscribing","UNSUPPORTED_OPERATION",{operation:operation});const{fragment,tag,topics}=await getSubInfo(contract,event);const{addr,subs}=getInternal(contract);let sub=subs.get(tag);if(!sub){const address=addr?addr:contract;const filter={address:address,topics:topics};const listener=log=>{let foundFragment=fragment;if(foundFragment==null){try{foundFragment=contract.interface.getEvent(log.topics[0])}catch(error){}}if(foundFragment){const _foundFragment=foundFragment;const args=fragment?contract.interface.decodeEventLog(fragment,log.data,log.topics):[];emit(contract,event,args,listener=>{return new ContractEventPayload(contract,listener,event,_foundFragment,log)})}else{emit(contract,event,[],listener=>{return new ContractUnknownEventPayload(contract,listener,event,log)})}};const zone=getZoneForAddress(await resolveAddress(address));let starting=[];const start=()=>{if(starting.length){return}starting.push(provider.on(filter,listener,zone))};const stop=async()=>{if(starting.length==0){return}const started=starting;starting=[];await Promise.all(started);provider.off(filter,listener,zone)};sub={tag:tag,listeners:[],start:start,stop:stop};subs.set(tag,sub)}return sub}let lastEmit=Promise.resolve();async function _emit(contract,event,args,payloadFunc){await lastEmit;const sub=await hasSub(contract,event);if(!sub){return false}const count=sub.listeners.length;sub.listeners=sub.listeners.filter(({listener,once})=>{const passArgs=Array.from(args);if(payloadFunc){passArgs.push(payloadFunc(once?null:listener))}try{listener.call(contract,...passArgs)}catch(error){}return!once});if(sub.listeners.length===0){sub.stop();getInternal(contract).subs.delete(sub.tag)}return count>0}async function emit(contract,event,args,payloadFunc){try{await lastEmit}catch(error){}const resultPromise=_emit(contract,event,args,payloadFunc);lastEmit=resultPromise;return await resultPromise}const passProperties=["then"];class BaseContract{target;interface;runner;filters;[internal];fallback;constructor(target,abi,runner,_deployTx){assertArgument(typeof target==="string"||isAddressable(target),"invalid value for Contract target","target",target);if(runner==null){runner=null}const iface=Interface.from(abi);defineProperties(this,{target:target,runner:runner,interface:iface});Object.defineProperty(this,internal,{value:{}});let addrPromise;let addr=null;let deployTx=null;if(_deployTx){const provider=getProvider(runner);deployTx=new ContractTransactionResponse(this.interface,provider,_deployTx)}const subs=new Map;if(typeof target==="string"){addr=target;addrPromise=Promise.resolve(target)}else{addrPromise=target.getAddress().then(addr=>{if(addr==null){throw new Error("TODO")}getInternal(this).addr=addr;return addr})}setInternal(this,{addrPromise:addrPromise,addr:addr,deployTx:deployTx,subs:subs});const filters=new Proxy({},{get:(target,prop,receiver)=>{if(typeof prop==="symbol"||passProperties.indexOf(prop)>=0){return Reflect.get(target,prop,receiver)}try{return this.getEvent(prop)}catch(error){if(!isError(error,"INVALID_ARGUMENT")||error.argument!=="key"){throw error}}return undefined},has:(target,prop)=>{if(passProperties.indexOf(prop)>=0){return Reflect.has(target,prop)}return Reflect.has(target,prop)||this.interface.hasEvent(String(prop))}});defineProperties(this,{filters:filters});defineProperties(this,{fallback:iface.receive||iface.fallback?buildWrappedFallback(this):null});return new Proxy(this,{get:(target,prop,receiver)=>{if(typeof prop==="symbol"||prop in target||passProperties.indexOf(prop)>=0){return Reflect.get(target,prop,receiver)}try{return target.getFunction(prop)}catch(error){if(!isError(error,"INVALID_ARGUMENT")||error.argument!=="key"){throw error}}return undefined},has:(target,prop)=>{if(typeof prop==="symbol"||prop in target||passProperties.indexOf(prop)>=0){return Reflect.has(target,prop)}return target.interface.hasFunction(prop)}})}connect(runner){return new BaseContract(this.target,this.interface,runner)}attach(target){return new BaseContract(target,this.interface,this.runner)}async getAddress(){return await getInternal(this).addrPromise}async getDeployedCode(){const provider=getProvider(this.runner);assert(provider,"runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"getDeployedCode"});const code=await provider.getCode(await this.getAddress());if(code==="0x"){return null}return code}async waitForDeployment(){const deployTx=this.deploymentTransaction();if(deployTx){await deployTx.wait();return this}const code=await this.getDeployedCode();if(code!=null){return this}const provider=getProvider(this.runner);assert(provider!=null,"contract runner does not support .provider","UNSUPPORTED_OPERATION",{operation:"waitForDeployment"});return new Promise((resolve,reject)=>{const checkCode=async()=>{try{const code=await this.getDeployedCode();if(code!=null){return resolve(this)}provider.once("block",checkCode)}catch(error){reject(error)}};checkCode()})}deploymentTransaction(){return getInternal(this).deployTx}getFunction(key){if(typeof key!=="string"){key=key.format()}const func=buildWrappedMethod(this,key);return func}getEvent(key){if(typeof key!=="string"){key=key.format()}return buildWrappedEvent(this,key)}async queryTransaction(hash){throw new Error("@TODO")}async queryFilter(event,fromBlock,toBlock){if(fromBlock==null){fromBlock=0}if(toBlock==null){toBlock="latest"}const{addr,addrPromise}=getInternal(this);const address=addr?addr:await addrPromise;const{fragment,topics}=await getSubInfo(this,event);const zone=getZoneForAddress(address);const filter={address:address,topics:topics,fromBlock:fromBlock,toBlock:toBlock,nodeLocation:getNodeLocationFromZone(zone)};const provider=getProvider(this.runner);assert(provider,"contract runner does not have a provider","UNSUPPORTED_OPERATION",{operation:"queryFilter"});return(await provider.getLogs(filter)).map(log=>{let foundFragment=fragment;if(foundFragment==null){try{foundFragment=this.interface.getEvent(log.topics[0])}catch(error){}}if(foundFragment){try{return new EventLog(log,this.interface,foundFragment)}catch(error){return new UndecodedEventLog(log,error)}}return new Log(log,provider)})}async on(event,listener){const sub=await getSub(this,"on",event);sub.listeners.push({listener:listener,once:false});sub.start();return this}async once(event,listener){const sub=await getSub(this,"once",event);sub.listeners.push({listener:listener,once:true});sub.start();return this}async emit(event,...args){return await emit(this,event,args,null)}async listenerCount(event){if(event){const sub=await hasSub(this,event);if(!sub){return 0}return sub.listeners.length}const{subs}=getInternal(this);let total=0;for(const{listeners}of subs.values()){total+=listeners.length}return total}async listeners(event){if(event){const sub=await hasSub(this,event);if(!sub){return[]}return sub.listeners.map(({listener})=>listener)}const{subs}=getInternal(this);let result=[];for(const{listeners}of subs.values()){result=result.concat(listeners.map(({listener})=>listener))}return result}async off(event,listener){const sub=await hasSub(this,event);if(!sub){return this}if(listener){const index=sub.listeners.map(({listener})=>listener).indexOf(listener);if(index>=0){sub.listeners.splice(index,1)}}if(listener==null||sub.listeners.length===0){sub.stop();getInternal(this).subs.delete(sub.tag)}return this}async removeAllListeners(event){if(event){const sub=await hasSub(this,event);if(!sub){return this}sub.stop();getInternal(this).subs.delete(sub.tag)}else{const{subs}=getInternal(this);for(const{tag,stop}of subs.values()){stop();subs.delete(tag)}}return this}async addListener(event,listener){return await this.on(event,listener)}async removeListener(event,listener){return await this.off(event,listener)}static buildClass(abi){class CustomContract extends BaseContract{constructor(address,runner=null){super(address,abi,runner)}}return CustomContract}static from(target,abi,runner){if(runner==null){runner=null}const contract=new this(target,abi,runner);return contract}}function _ContractBase(){return BaseContract}class Contract extends _ContractBase(){}function checkProvider(signer,operation){if(signer.provider){return signer.provider}assert(false,"missing provider","UNSUPPORTED_OPERATION",{operation:operation})}async function populate(signer,tx){const pop=copyRequest(tx);if(pop.to!=null){pop.to=resolveAddress(pop.to);validateAddress(pop.to)}if(pop.from!=null){const from=pop.from;pop.from=await Promise.all([signer.getAddress(),resolveAddress(from)]).then(([address,from])=>{assertArgument(address.toLowerCase()===from.toLowerCase(),"transaction from mismatch","tx.from",from);return address})}else{pop.from=await signer.getAddress()}validateAddress(pop.from);return await resolveProperties(pop)}class AbstractSigner{provider;constructor(provider){defineProperties(this,{provider:provider||null})}_getAddress(address){return resolveAddress(address)}async zoneFromAddress(_address){const address=this._getAddress(_address);return toZone((await address).slice(0,4))}async getNonce(blockTag){return checkProvider(this,"getTransactionCount").getTransactionCount(await this.getAddress(),blockTag)}async populateCall(tx){const pop=await populate(this,tx);return pop}async populateQuaiTransaction(tx){const provider=checkProvider(this,"populateTransaction");const zone=await this.zoneFromAddress(tx.from);const pop=await populate(this,tx);if(pop.type==null){pop.type=await getTxType(pop.from??null,pop.to??null)}if(pop.nonce==null){pop.nonce=await this.getNonce("pending")}if(pop.type==null){pop.type=getTxType(pop.from??null,pop.to??null)}if(pop.gasLimit==null){if(pop.type==0)pop.gasLimit=await this.estimateGas(pop);else{const temp=pop.to;pop.to="0x0000000000000000000000000000000000000000";pop.gasLimit=getBigInt(2*Number(await this.estimateGas(pop)));pop.to=temp}}const network=await this.provider.getNetwork();if(pop.chainId!=null){const chainId=getBigInt(pop.chainId);assertArgument(chainId===network.chainId,"transaction chainId mismatch","tx.chainId",zone)}else{pop.chainId=network.chainId}if(pop.maxFeePerGas==null||pop.maxPriorityFeePerGas==null){const feeData=await provider.getFeeData(zone);if(pop.maxFeePerGas==null){pop.maxFeePerGas=feeData.maxFeePerGas}if(pop.maxPriorityFeePerGas==null){pop.maxPriorityFeePerGas=feeData.maxPriorityFeePerGas||10n}}return await resolveProperties(pop)}async estimateGas(tx){return checkProvider(this,"estimateGas").estimateGas(await this.populateCall(tx))}async call(tx){return checkProvider(this,"call").call(await this.populateCall(tx))}async sendTransaction(tx){const provider=checkProvider(this,"sendTransaction");const zone=await this.zoneFromAddress(addressFromTransactionRequest(tx));const pop=await this.populateQuaiTransaction(tx);const txObj=QuaiTransaction.from(pop);const sender=await this.getAddress();const signedTx=await this.signTransaction(txObj);return await provider.broadcastTransaction(zone,signedTx,sender)}}class VoidSigner extends AbstractSigner{address;constructor(address,provider){super(provider);defineProperties(this,{address:address})}async getAddress(){return this.address}connect(provider){return new VoidSigner(this.address,provider)}#throwUnsupported(suffix,operation){assert(false,`VoidSigner cannot sign ${suffix}`,"UNSUPPORTED_OPERATION",{operation:operation})}async signTransaction(tx){this.#throwUnsupported("transactions","signTransaction")}async signMessage(message){this.#throwUnsupported("messages","signMessage")}async signTypedData(domain,types,value){this.#throwUnsupported("typed-data","signTypedData")}}class BaseWallet extends AbstractSigner{#address;#signingKey;constructor(privateKey,provider){super(provider);assertArgument(privateKey&&typeof privateKey.sign==="function","invalid private key","privateKey","[ REDACTED ]");this.#signingKey=privateKey;this.#address=computeAddress(this.signingKey.publicKey)}get address(){return this.#address}get signingKey(){return this.#signingKey}get privateKey(){return this.signingKey.privateKey}async getAddress(_zone){return this.#address}connect(provider){return new BaseWallet(this.#signingKey,provider)}async signTransaction(tx){const{to,from}=await resolveProperties({to:tx.to?resolveAddress(tx.to):undefined,from:tx.from?resolveAddress(tx.from):undefined});if(to!==undefined){validateAddress(to);tx.to=to}if(from!==undefined){assertArgument(getAddress(from)===this.#address,"transaction from address mismatch","tx.from",from)}else{tx.from=this.#address}const btx=QuaiTransaction.from(tx);const digest=keccak256(btx.unsignedSerialized);btx.signature=this.signingKey.sign(digest);return btx.serialized}async signMessage(message){return this.signMessageSync(message)}signMessageSync(message){return this.signingKey.sign(hashMessage(message)).serialized}async signTypedData(domain,types,value){return this.signingKey.sign(TypedDataEncoder.hash(domain,types,value)).serialized}}const subsChrs=" !#$%&'()*+,-./<=>?@[]^_`{|}~";const Word=/^[a-z]*$/i;function unfold(words,sep){let initial=97;return words.reduce((accum,word)=>{if(word===sep){initial++}else if(word.match(Word)){accum.push(String.fromCharCode(initial)+word)}else{initial=97;accum.push(word)}return accum},[])}function decode(data,subs){for(let i=subsChrs.length-1;i>=0;i--){data=data.split(subsChrs[i]).join(subs.substring(2*i,2*i+2))}const clumps=[];const leftover=data.replace(/(:|([0-9])|([A-Z][a-z]*))/g,(all,item,semi,word)=>{if(semi){for(let i=parseInt(semi);i>=0;i--){clumps.push(";")}}else{clumps.push(item.toLowerCase())}return""});if(leftover){throw new Error(`leftovers: ${JSON.stringify(leftover)}`)}return unfold(unfold(clumps,";"),":")}function decodeOwl(data){assertArgument(data[0]==="0","unsupported auwl data","data",data);return decode(data.substring(1+2*subsChrs.length),data.substring(1,1+2*subsChrs.length))}class Wordlist{locale;constructor(locale){defineProperties(this,{locale:locale})}split(phrase){return phrase.toLowerCase().split(/\s+/g)}join(words){return words.join(" ")}}class WordlistOwl extends Wordlist{#data;#checksum;constructor(locale,data,checksum){super(locale);this.#data=data;this.#checksum=checksum;this.#words=null}get _data(){return this.#data}_decodeWords(){return decodeOwl(this.#data)}#words;#loadWords(){if(this.#words==null){const words=this._decodeWords();const checksum=id(words.join("\n")+"\n");if(checksum!==this.#checksum){throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`)}this.#words=words}return this.#words}getWord(index){const words=this.#loadWords();assertArgument(index>=0&&index=12&&words.length<=24,"invalid mnemonic length","mnemonic","[ REDACTED ]");const entropy=new Uint8Array(Math.ceil(11*words.length/8));let offset=0;for(let i=0;i=0,`invalid mnemonic word at index ${i}`,"mnemonic","[ REDACTED ]");for(let bit=0;bit<11;bit++){if(index&1<<10-bit){entropy[offset>>3]|=1<<7-offset%8}offset++}}const entropyBits=32*words.length/3;const checksumBits=words.length/3;const checksumMask=getUpperMask(checksumBits);const checksum=getBytes(sha256(entropy.slice(0,entropyBits/8)))[0]&checksumMask;assertArgument(checksum===(entropy[entropy.length-1]&checksumMask),"invalid mnemonic checksum","mnemonic","[ REDACTED ]");return hexlify(entropy.slice(0,entropyBits/8))}function entropyToMnemonic(entropy,wordlist){assertArgument(entropy.length%4===0&&entropy.length>=16&&entropy.length<=32,"invalid entropy size","entropy","[ REDACTED ]");if(wordlist==null){wordlist=LangEn.wordlist()}const indices=[0];let remainingBits=11;for(let i=0;i8){indices[indices.length-1]<<=8;indices[indices.length-1]|=entropy[i];remainingBits-=8}else{indices[indices.length-1]<<=remainingBits;indices[indices.length-1]|=entropy[i]>>8-remainingBits;indices.push(entropy[i]&getLowerMask(8-remainingBits));remainingBits+=3}}const checksumBits=entropy.length/4;const checksum=parseInt(sha256(entropy).substring(2,4),16)&getUpperMask(checksumBits);indices[indices.length-1]<<=checksumBits;indices[indices.length-1]|=checksum>>8-checksumBits;return wordlist.join(indices.map(index=>wordlist.getWord(index)))}const _guard$2={};class Mnemonic{phrase;password;wordlist;entropy;constructor(guard,entropy,phrase,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}assertPrivate(guard,_guard$2,"Mnemonic");defineProperties(this,{phrase:phrase,password:password,wordlist:wordlist,entropy:entropy})}computeSeed(){const salt=toUtf8Bytes("mnemonic"+this.password,"NFKD");return pbkdf2(toUtf8Bytes(this.phrase,"NFKD"),salt,2048,64,"sha512")}static fromPhrase(phrase,password,wordlist){if(wordlist==null){wordlist=LangEn.wordlist()}if(password==null){password=""}const entropy=mnemonicToEntropy(phrase,wordlist);phrase=entropyToMnemonic(getBytes(entropy),wordlist);return new Mnemonic(_guard$2,entropy,phrase,password,wordlist)}static fromEntropy(_entropy,password,wordlist){if(wordlist==null){wordlist=LangEn.wordlist()}if(password==null){password=""}const entropy=getBytes(_entropy,"entropy");const phrase=entropyToMnemonic(entropy,wordlist);return new Mnemonic(_guard$2,hexlify(entropy),phrase,password,wordlist)}static entropyToPhrase(_entropy,wordlist){const entropy=getBytes(_entropy,"entropy");return entropyToMnemonic(entropy,wordlist)}static phraseToEntropy(phrase,wordlist){return mnemonicToEntropy(phrase,wordlist)}static isValidMnemonic(phrase,wordlist){try{mnemonicToEntropy(phrase,wordlist);return true}catch(error){}return false}}var __classPrivateFieldGet$1=__$G&&__$G.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var __classPrivateFieldSet$1=__$G&&__$G.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var _AES_key,_AES_Kd,_AES_Ke;const numberOfRounds={16:10,24:12,32:14};const rcon=[1,2,4,8,16,32,64,128,27,54,108,216,171,77,154,47,94,188,99,198,151,53,106,212,179,125,250,239,197,145];const S=[99,124,119,123,242,107,111,197,48,1,103,43,254,215,171,118,202,130,201,125,250,89,71,240,173,212,162,175,156,164,114,192,183,253,147,38,54,63,247,204,52,165,229,241,113,216,49,21,4,199,35,195,24,150,5,154,7,18,128,226,235,39,178,117,9,131,44,26,27,110,90,160,82,59,214,179,41,227,47,132,83,209,0,237,32,252,177,91,106,203,190,57,74,76,88,207,208,239,170,251,67,77,51,133,69,249,2,127,80,60,159,168,81,163,64,143,146,157,56,245,188,182,218,33,16,255,243,210,205,12,19,236,95,151,68,23,196,167,126,61,100,93,25,115,96,129,79,220,34,42,144,136,70,238,184,20,222,94,11,219,224,50,58,10,73,6,36,92,194,211,172,98,145,149,228,121,231,200,55,109,141,213,78,169,108,86,244,234,101,122,174,8,186,120,37,46,28,166,180,198,232,221,116,31,75,189,139,138,112,62,181,102,72,3,246,14,97,53,87,185,134,193,29,158,225,248,152,17,105,217,142,148,155,30,135,233,206,85,40,223,140,161,137,13,191,230,66,104,65,153,45,15,176,84,187,22];const Si=[82,9,106,213,48,54,165,56,191,64,163,158,129,243,215,251,124,227,57,130,155,47,255,135,52,142,67,68,196,222,233,203,84,123,148,50,166,194,35,61,238,76,149,11,66,250,195,78,8,46,161,102,40,217,36,178,118,91,162,73,109,139,209,37,114,248,246,100,134,104,152,22,212,164,92,204,93,101,182,146,108,112,72,80,253,237,185,218,94,21,70,87,167,141,157,132,144,216,171,0,140,188,211,10,247,228,88,5,184,179,69,6,208,44,30,143,202,63,15,2,193,175,189,3,1,19,138,107,58,145,17,65,79,103,220,234,151,242,207,206,240,180,230,115,150,172,116,34,231,173,53,133,226,249,55,232,28,117,223,110,71,241,26,113,29,41,197,137,111,183,98,14,170,24,190,27,252,86,62,75,198,210,121,32,154,219,192,254,120,205,90,244,31,221,168,51,136,7,199,49,177,18,16,89,39,128,236,95,96,81,127,169,25,181,74,13,45,229,122,159,147,201,156,239,160,224,59,77,174,42,245,176,200,235,187,60,131,83,153,97,23,43,4,126,186,119,214,38,225,105,20,99,85,33,12,125];const T1=[3328402341,4168907908,4000806809,4135287693,4294111757,3597364157,3731845041,2445657428,1613770832,33620227,3462883241,1445669757,3892248089,3050821474,1303096294,3967186586,2412431941,528646813,2311702848,4202528135,4026202645,2992200171,2387036105,4226871307,1101901292,3017069671,1604494077,1169141738,597466303,1403299063,3832705686,2613100635,1974974402,3791519004,1033081774,1277568618,1815492186,2118074177,4126668546,2211236943,1748251740,1369810420,3521504564,4193382664,3799085459,2883115123,1647391059,706024767,134480908,2512897874,1176707941,2646852446,806885416,932615841,168101135,798661301,235341577,605164086,461406363,3756188221,3454790438,1311188841,2142417613,3933566367,302582043,495158174,1479289972,874125870,907746093,3698224818,3025820398,1537253627,2756858614,1983593293,3084310113,2108928974,1378429307,3722699582,1580150641,327451799,2790478837,3117535592,0,3253595436,1075847264,3825007647,2041688520,3059440621,3563743934,2378943302,1740553945,1916352843,2487896798,2555137236,2958579944,2244988746,3151024235,3320835882,1336584933,3992714006,2252555205,2588757463,1714631509,293963156,2319795663,3925473552,67240454,4269768577,2689618160,2017213508,631218106,1269344483,2723238387,1571005438,2151694528,93294474,1066570413,563977660,1882732616,4059428100,1673313503,2008463041,2950355573,1109467491,537923632,3858759450,4260623118,3218264685,2177748300,403442708,638784309,3287084079,3193921505,899127202,2286175436,773265209,2479146071,1437050866,4236148354,2050833735,3362022572,3126681063,840505643,3866325909,3227541664,427917720,2655997905,2749160575,1143087718,1412049534,999329963,193497219,2353415882,3354324521,1807268051,672404540,2816401017,3160301282,369822493,2916866934,3688947771,1681011286,1949973070,336202270,2454276571,201721354,1210328172,3093060836,2680341085,3184776046,1135389935,3294782118,965841320,831886756,3554993207,4068047243,3588745010,2345191491,1849112409,3664604599,26054028,2983581028,2622377682,1235855840,3630984372,2891339514,4092916743,3488279077,3395642799,4101667470,1202630377,268961816,1874508501,4034427016,1243948399,1546530418,941366308,1470539505,1941222599,2546386513,3421038627,2715671932,3899946140,1042226977,2521517021,1639824860,227249030,260737669,3765465232,2084453954,1907733956,3429263018,2420656344,100860677,4160157185,470683154,3261161891,1781871967,2924959737,1773779408,394692241,2579611992,974986535,664706745,3655459128,3958962195,731420851,571543859,3530123707,2849626480,126783113,865375399,765172662,1008606754,361203602,3387549984,2278477385,2857719295,1344809080,2782912378,59542671,1503764984,160008576,437062935,1707065306,3622233649,2218934982,3496503480,2185314755,697932208,1512910199,504303377,2075177163,2824099068,1841019862,739644986];const T2=[2781242211,2230877308,2582542199,2381740923,234877682,3184946027,2984144751,1418839493,1348481072,50462977,2848876391,2102799147,434634494,1656084439,3863849899,2599188086,1167051466,2636087938,1082771913,2281340285,368048890,3954334041,3381544775,201060592,3963727277,1739838676,4250903202,3930435503,3206782108,4149453988,2531553906,1536934080,3262494647,484572669,2923271059,1783375398,1517041206,1098792767,49674231,1334037708,1550332980,4098991525,886171109,150598129,2481090929,1940642008,1398944049,1059722517,201851908,1385547719,1699095331,1587397571,674240536,2704774806,252314885,3039795866,151914247,908333586,2602270848,1038082786,651029483,1766729511,3447698098,2682942837,454166793,2652734339,1951935532,775166490,758520603,3000790638,4004797018,4217086112,4137964114,1299594043,1639438038,3464344499,2068982057,1054729187,1901997871,2534638724,4121318227,1757008337,0,750906861,1614815264,535035132,3363418545,3988151131,3201591914,1183697867,3647454910,1265776953,3734260298,3566750796,3903871064,1250283471,1807470800,717615087,3847203498,384695291,3313910595,3617213773,1432761139,2484176261,3481945413,283769337,100925954,2180939647,4037038160,1148730428,3123027871,3813386408,4087501137,4267549603,3229630528,2315620239,2906624658,3156319645,1215313976,82966005,3747855548,3245848246,1974459098,1665278241,807407632,451280895,251524083,1841287890,1283575245,337120268,891687699,801369324,3787349855,2721421207,3431482436,959321879,1469301956,4065699751,2197585534,1199193405,2898814052,3887750493,724703513,2514908019,2696962144,2551808385,3516813135,2141445340,1715741218,2119445034,2872807568,2198571144,3398190662,700968686,3547052216,1009259540,2041044702,3803995742,487983883,1991105499,1004265696,1449407026,1316239930,504629770,3683797321,168560134,1816667172,3837287516,1570751170,1857934291,4014189740,2797888098,2822345105,2754712981,936633572,2347923833,852879335,1133234376,1500395319,3084545389,2348912013,1689376213,3533459022,3762923945,3034082412,4205598294,133428468,634383082,2949277029,2398386810,3913789102,403703816,3580869306,2297460856,1867130149,1918643758,607656988,4049053350,3346248884,1368901318,600565992,2090982877,2632479860,557719327,3717614411,3697393085,2249034635,2232388234,2430627952,1115438654,3295786421,2865522278,3633334344,84280067,33027830,303828494,2747425121,1600795957,4188952407,3496589753,2434238086,1486471617,658119965,3106381470,953803233,334231800,3005978776,857870609,3151128937,1890179545,2298973838,2805175444,3056442267,574365214,2450884487,550103529,1233637070,4289353045,2018519080,2057691103,2399374476,4166623649,2148108681,387583245,3664101311,836232934,3330556482,3100665960,3280093505,2955516313,2002398509,287182607,3413881008,4238890068,3597515707,975967766];const T3=[1671808611,2089089148,2006576759,2072901243,4061003762,1807603307,1873927791,3310653893,810573872,16974337,1739181671,729634347,4263110654,3613570519,2883997099,1989864566,3393556426,2191335298,3376449993,2106063485,4195741690,1508618841,1204391495,4027317232,2917941677,3563566036,2734514082,2951366063,2629772188,2767672228,1922491506,3227229120,3082974647,4246528509,2477669779,644500518,911895606,1061256767,4144166391,3427763148,878471220,2784252325,3845444069,4043897329,1905517169,3631459288,827548209,356461077,67897348,3344078279,593839651,3277757891,405286936,2527147926,84871685,2595565466,118033927,305538066,2157648768,3795705826,3945188843,661212711,2999812018,1973414517,152769033,2208177539,745822252,439235610,455947803,1857215598,1525593178,2700827552,1391895634,994932283,3596728278,3016654259,695947817,3812548067,795958831,2224493444,1408607827,3513301457,0,3979133421,543178784,4229948412,2982705585,1542305371,1790891114,3410398667,3201918910,961245753,1256100938,1289001036,1491644504,3477767631,3496721360,4012557807,2867154858,4212583931,1137018435,1305975373,861234739,2241073541,1171229253,4178635257,33948674,2139225727,1357946960,1011120188,2679776671,2833468328,1374921297,2751356323,1086357568,2408187279,2460827538,2646352285,944271416,4110742005,3168756668,3066132406,3665145818,560153121,271589392,4279952895,4077846003,3530407890,3444343245,202643468,322250259,3962553324,1608629855,2543990167,1154254916,389623319,3294073796,2817676711,2122513534,1028094525,1689045092,1575467613,422261273,1939203699,1621147744,2174228865,1339137615,3699352540,577127458,712922154,2427141008,2290289544,1187679302,3995715566,3100863416,339486740,3732514782,1591917662,186455563,3681988059,3762019296,844522546,978220090,169743370,1239126601,101321734,611076132,1558493276,3260915650,3547250131,2901361580,1655096418,2443721105,2510565781,3828863972,2039214713,3878868455,3359869896,928607799,1840765549,2374762893,3580146133,1322425422,2850048425,1823791212,1459268694,4094161908,3928346602,1706019429,2056189050,2934523822,135794696,3134549946,2022240376,628050469,779246638,472135708,2800834470,3032970164,3327236038,3894660072,3715932637,1956440180,522272287,1272813131,3185336765,2340818315,2323976074,1888542832,1044544574,3049550261,1722469478,1222152264,50660867,4127324150,236067854,1638122081,895445557,1475980887,3117443513,2257655686,3243809217,489110045,2662934430,3778599393,4162055160,2561878936,288563729,1773916777,3648039385,2391345038,2493985684,2612407707,505560094,2274497927,3911240169,3460925390,1442818645,678973480,3749357023,2358182796,2717407649,2306869641,219617805,3218761151,3862026214,1120306242,1756942440,1103331905,2578459033,762796589,252780047,2966125488,1425844308,3151392187,372911126];const T4=[1667474886,2088535288,2004326894,2071694838,4075949567,1802223062,1869591006,3318043793,808472672,16843522,1734846926,724270422,4278065639,3621216949,2880169549,1987484396,3402253711,2189597983,3385409673,2105378810,4210693615,1499065266,1195886990,4042263547,2913856577,3570689971,2728590687,2947541573,2627518243,2762274643,1920112356,3233831835,3082273397,4261223649,2475929149,640051788,909531756,1061110142,4160160501,3435941763,875846760,2779116625,3857003729,4059105529,1903268834,3638064043,825316194,353713962,67374088,3351728789,589522246,3284360861,404236336,2526454071,84217610,2593830191,117901582,303183396,2155911963,3806477791,3958056653,656894286,2998062463,1970642922,151591698,2206440989,741110872,437923380,454765878,1852748508,1515908788,2694904667,1381168804,993742198,3604373943,3014905469,690584402,3823320797,791638366,2223281939,1398011302,3520161977,0,3991743681,538992704,4244381667,2981218425,1532751286,1785380564,3419096717,3200178535,960056178,1246420628,1280103576,1482221744,3486468741,3503319995,4025428677,2863326543,4227536621,1128514950,1296947098,859002214,2240123921,1162203018,4193849577,33687044,2139062782,1347481760,1010582648,2678045221,2829640523,1364325282,2745433693,1077985408,2408548869,2459086143,2644360225,943212656,4126475505,3166494563,3065430391,3671750063,555836226,269496352,4294908645,4092792573,3537006015,3452783745,202118168,320025894,3974901699,1600119230,2543297077,1145359496,387397934,3301201811,2812801621,2122220284,1027426170,1684319432,1566435258,421079858,1936954854,1616945344,2172753945,1330631070,3705438115,572679748,707427924,2425400123,2290647819,1179044492,4008585671,3099120491,336870440,3739122087,1583276732,185277718,3688593069,3772791771,842159716,976899700,168435220,1229577106,101059084,606366792,1549591736,3267517855,3553849021,2897014595,1650632388,2442242105,2509612081,3840161747,2038008818,3890688725,3368567691,926374254,1835907034,2374863873,3587531953,1313788572,2846482505,1819063512,1448540844,4109633523,3941213647,1701162954,2054852340,2930698567,134748176,3132806511,2021165296,623210314,774795868,471606328,2795958615,3031746419,3334885783,3907527627,3722280097,1953799400,522133822,1263263126,3183336545,2341176845,2324333839,1886425312,1044267644,3048588401,1718004428,1212733584,50529542,4143317495,235803164,1633788866,892690282,1465383342,3115962473,2256965911,3250673817,488449850,2661202215,3789633753,4177007595,2560144171,286339874,1768537042,3654906025,2391705863,2492770099,2610673197,505291324,2273808917,3924369609,3469625735,1431699370,673740880,3755965093,2358021891,2711746649,2307489801,218961690,3217021541,3873845719,1111672452,1751693520,1094828930,2576986153,757954394,252645662,2964376443,1414855848,3149649517,370555436];const T5=[1374988112,2118214995,437757123,975658646,1001089995,530400753,2902087851,1273168787,540080725,2910219766,2295101073,4110568485,1340463100,3307916247,641025152,3043140495,3736164937,632953703,1172967064,1576976609,3274667266,2169303058,2370213795,1809054150,59727847,361929877,3211623147,2505202138,3569255213,1484005843,1239443753,2395588676,1975683434,4102977912,2572697195,666464733,3202437046,4035489047,3374361702,2110667444,1675577880,3843699074,2538681184,1649639237,2976151520,3144396420,4269907996,4178062228,1883793496,2403728665,2497604743,1383856311,2876494627,1917518562,3810496343,1716890410,3001755655,800440835,2261089178,3543599269,807962610,599762354,33778362,3977675356,2328828971,2809771154,4077384432,1315562145,1708848333,101039829,3509871135,3299278474,875451293,2733856160,92987698,2767645557,193195065,1080094634,1584504582,3178106961,1042385657,2531067453,3711829422,1306967366,2438237621,1908694277,67556463,1615861247,429456164,3602770327,2302690252,1742315127,2968011453,126454664,3877198648,2043211483,2709260871,2084704233,4169408201,0,159417987,841739592,504459436,1817866830,4245618683,260388950,1034867998,908933415,168810852,1750902305,2606453969,607530554,202008497,2472011535,3035535058,463180190,2160117071,1641816226,1517767529,470948374,3801332234,3231722213,1008918595,303765277,235474187,4069246893,766945465,337553864,1475418501,2943682380,4003061179,2743034109,4144047775,1551037884,1147550661,1543208500,2336434550,3408119516,3069049960,3102011747,3610369226,1113818384,328671808,2227573024,2236228733,3535486456,2935566865,3341394285,496906059,3702665459,226906860,2009195472,733156972,2842737049,294930682,1206477858,2835123396,2700099354,1451044056,573804783,2269728455,3644379585,2362090238,2564033334,2801107407,2776292904,3669462566,1068351396,742039012,1350078989,1784663195,1417561698,4136440770,2430122216,775550814,2193862645,2673705150,1775276924,1876241833,3475313331,3366754619,270040487,3902563182,3678124923,3441850377,1851332852,3969562369,2203032232,3868552805,2868897406,566021896,4011190502,3135740889,1248802510,3936291284,699432150,832877231,708780849,3332740144,899835584,1951317047,4236429990,3767586992,866637845,4043610186,1106041591,2144161806,395441711,1984812685,1139781709,3433712980,3835036895,2664543715,1282050075,3240894392,1181045119,2640243204,25965917,4203181171,4211818798,3009879386,2463879762,3910161971,1842759443,2597806476,933301370,1509430414,3943906441,3467192302,3076639029,3776767469,2051518780,2631065433,1441952575,404016761,1942435775,1408749034,1610459739,3745345300,2017778566,3400528769,3110650942,941896748,3265478751,371049330,3168937228,675039627,4279080257,967311729,135050206,3635733660,1683407248,2076935265,3576870512,1215061108,3501741890];const T6=[1347548327,1400783205,3273267108,2520393566,3409685355,4045380933,2880240216,2471224067,1428173050,4138563181,2441661558,636813900,4233094615,3620022987,2149987652,2411029155,1239331162,1730525723,2554718734,3781033664,46346101,310463728,2743944855,3328955385,3875770207,2501218972,3955191162,3667219033,768917123,3545789473,692707433,1150208456,1786102409,2029293177,1805211710,3710368113,3065962831,401639597,1724457132,3028143674,409198410,2196052529,1620529459,1164071807,3769721975,2226875310,486441376,2499348523,1483753576,428819965,2274680428,3075636216,598438867,3799141122,1474502543,711349675,129166120,53458370,2592523643,2782082824,4063242375,2988687269,3120694122,1559041666,730517276,2460449204,4042459122,2706270690,3446004468,3573941694,533804130,2328143614,2637442643,2695033685,839224033,1973745387,957055980,2856345839,106852767,1371368976,4181598602,1033297158,2933734917,1179510461,3046200461,91341917,1862534868,4284502037,605657339,2547432937,3431546947,2003294622,3182487618,2282195339,954669403,3682191598,1201765386,3917234703,3388507166,0,2198438022,1211247597,2887651696,1315723890,4227665663,1443857720,507358933,657861945,1678381017,560487590,3516619604,975451694,2970356327,261314535,3535072918,2652609425,1333838021,2724322336,1767536459,370938394,182621114,3854606378,1128014560,487725847,185469197,2918353863,3106780840,3356761769,2237133081,1286567175,3152976349,4255350624,2683765030,3160175349,3309594171,878443390,1988838185,3704300486,1756818940,1673061617,3403100636,272786309,1075025698,545572369,2105887268,4174560061,296679730,1841768865,1260232239,4091327024,3960309330,3497509347,1814803222,2578018489,4195456072,575138148,3299409036,446754879,3629546796,4011996048,3347532110,3252238545,4270639778,915985419,3483825537,681933534,651868046,2755636671,3828103837,223377554,2607439820,1649704518,3270937875,3901806776,1580087799,4118987695,3198115200,2087309459,2842678573,3016697106,1003007129,2802849917,1860738147,2077965243,164439672,4100872472,32283319,2827177882,1709610350,2125135846,136428751,3874428392,3652904859,3460984630,3572145929,3593056380,2939266226,824852259,818324884,3224740454,930369212,2801566410,2967507152,355706840,1257309336,4148292826,243256656,790073846,2373340630,1296297904,1422699085,3756299780,3818836405,457992840,3099667487,2135319889,77422314,1560382517,1945798516,788204353,1521706781,1385356242,870912086,325965383,2358957921,2050466060,2388260884,2313884476,4006521127,901210569,3990953189,1014646705,1503449823,1062597235,2031621326,3212035895,3931371469,1533017514,350174575,2256028891,2177544179,1052338372,741876788,1606591296,1914052035,213705253,2334669897,1107234197,1899603969,3725069491,2631447780,2422494913,1635502980,1893020342,1950903388,1120974935];const T7=[2807058932,1699970625,2764249623,1586903591,1808481195,1173430173,1487645946,59984867,4199882800,1844882806,1989249228,1277555970,3623636965,3419915562,1149249077,2744104290,1514790577,459744698,244860394,3235995134,1963115311,4027744588,2544078150,4190530515,1608975247,2627016082,2062270317,1507497298,2200818878,567498868,1764313568,3359936201,2305455554,2037970062,1047239e3,1910319033,1337376481,2904027272,2892417312,984907214,1243112415,830661914,861968209,2135253587,2011214180,2927934315,2686254721,731183368,1750626376,4246310725,1820824798,4172763771,3542330227,48394827,2404901663,2871682645,671593195,3254988725,2073724613,145085239,2280796200,2779915199,1790575107,2187128086,472615631,3029510009,4075877127,3802222185,4107101658,3201631749,1646252340,4270507174,1402811438,1436590835,3778151818,3950355702,3963161475,4020912224,2667994737,273792366,2331590177,104699613,95345982,3175501286,2377486676,1560637892,3564045318,369057872,4213447064,3919042237,1137477952,2658625497,1119727848,2340947849,1530455833,4007360968,172466556,266959938,516552836,0,2256734592,3980931627,1890328081,1917742170,4294704398,945164165,3575528878,958871085,3647212047,2787207260,1423022939,775562294,1739656202,3876557655,2530391278,2443058075,3310321856,547512796,1265195639,437656594,3121275539,719700128,3762502690,387781147,218828297,3350065803,2830708150,2848461854,428169201,122466165,3720081049,1627235199,648017665,4122762354,1002783846,2117360635,695634755,3336358691,4234721005,4049844452,3704280881,2232435299,574624663,287343814,612205898,1039717051,840019705,2708326185,793451934,821288114,1391201670,3822090177,376187827,3113855344,1224348052,1679968233,2361698556,1058709744,752375421,2431590963,1321699145,3519142200,2734591178,188127444,2177869557,3727205754,2384911031,3215212461,2648976442,2450346104,3432737375,1180849278,331544205,3102249176,4150144569,2952102595,2159976285,2474404304,766078933,313773861,2570832044,2108100632,1668212892,3145456443,2013908262,418672217,3070356634,2594734927,1852171925,3867060991,3473416636,3907448597,2614737639,919489135,164948639,2094410160,2997825956,590424639,2486224549,1723872674,3157750862,3399941250,3501252752,3625268135,2555048196,3673637356,1343127501,4130281361,3599595085,2957853679,1297403050,81781910,3051593425,2283490410,532201772,1367295589,3926170974,895287692,1953757831,1093597963,492483431,3528626907,1446242576,1192455638,1636604631,209336225,344873464,1015671571,669961897,3375740769,3857572124,2973530695,3747192018,1933530610,3464042516,935293895,3454686199,2858115069,1863638845,3683022916,4085369519,3292445032,875313188,1080017571,3279033885,621591778,1233856572,2504130317,24197544,3017672716,3835484340,3247465558,2220981195,3060847922,1551124588,1463996600];const T8=[4104605777,1097159550,396673818,660510266,2875968315,2638606623,4200115116,3808662347,821712160,1986918061,3430322568,38544885,3856137295,718002117,893681702,1654886325,2975484382,3122358053,3926825029,4274053469,796197571,1290801793,1184342925,3556361835,2405426947,2459735317,1836772287,1381620373,3196267988,1948373848,3764988233,3385345166,3263785589,2390325492,1480485785,3111247143,3780097726,2293045232,548169417,3459953789,3746175075,439452389,1362321559,1400849762,1685577905,1806599355,2174754046,137073913,1214797936,1174215055,3731654548,2079897426,1943217067,1258480242,529487843,1437280870,3945269170,3049390895,3313212038,923313619,679998e3,3215307299,57326082,377642221,3474729866,2041877159,133361907,1776460110,3673476453,96392454,878845905,2801699524,777231668,4082475170,2330014213,4142626212,2213296395,1626319424,1906247262,1846563261,562755902,3708173718,1040559837,3871163981,1418573201,3294430577,114585348,1343618912,2566595609,3186202582,1078185097,3651041127,3896688048,2307622919,425408743,3371096953,2081048481,1108339068,2216610296,0,2156299017,736970802,292596766,1517440620,251657213,2235061775,2933202493,758720310,265905162,1554391400,1532285339,908999204,174567692,1474760595,4002861748,2610011675,3234156416,3693126241,2001430874,303699484,2478443234,2687165888,585122620,454499602,151849742,2345119218,3064510765,514443284,4044981591,1963412655,2581445614,2137062819,19308535,1928707164,1715193156,4219352155,1126790795,600235211,3992742070,3841024952,836553431,1669664834,2535604243,3323011204,1243905413,3141400786,4180808110,698445255,2653899549,2989552604,2253581325,3252932727,3004591147,1891211689,2487810577,3915653703,4237083816,4030667424,2100090966,865136418,1229899655,953270745,3399679628,3557504664,4118925222,2061379749,3079546586,2915017791,983426092,2022837584,1607244650,2118541908,2366882550,3635996816,972512814,3283088770,1568718495,3499326569,3576539503,621982671,2895723464,410887952,2623762152,1002142683,645401037,1494807662,2595684844,1335535747,2507040230,4293295786,3167684641,367585007,3885750714,1865862730,2668221674,2960971305,2763173681,1059270954,2777952454,2724642869,1320957812,2194319100,2429595872,2815956275,77089521,3973773121,3444575871,2448830231,1305906550,4021308739,2857194700,2516901860,3518358430,1787304780,740276417,1699839814,1592394909,2352307457,2272556026,188821243,1729977011,3687994002,274084841,3594982253,3613494426,2701949495,4162096729,322734571,2837966542,1640576439,484830689,1202797690,3537852828,4067639125,349075736,3342319475,4157467219,4255800159,1030690015,1155237496,2951971274,1757691577,607398968,2738905026,499347990,3794078908,1011452712,227885567,2818666809,213114376,3034881240,1455525988,3414450555,850817237,1817998408,3092726480];const U1=[0,235474187,470948374,303765277,941896748,908933415,607530554,708780849,1883793496,2118214995,1817866830,1649639237,1215061108,1181045119,1417561698,1517767529,3767586992,4003061179,4236429990,4069246893,3635733660,3602770327,3299278474,3400528769,2430122216,2664543715,2362090238,2193862645,2835123396,2801107407,3035535058,3135740889,3678124923,3576870512,3341394285,3374361702,3810496343,3977675356,4279080257,4043610186,2876494627,2776292904,3076639029,3110650942,2472011535,2640243204,2403728665,2169303058,1001089995,899835584,666464733,699432150,59727847,226906860,530400753,294930682,1273168787,1172967064,1475418501,1509430414,1942435775,2110667444,1876241833,1641816226,2910219766,2743034109,2976151520,3211623147,2505202138,2606453969,2302690252,2269728455,3711829422,3543599269,3240894392,3475313331,3843699074,3943906441,4178062228,4144047775,1306967366,1139781709,1374988112,1610459739,1975683434,2076935265,1775276924,1742315127,1034867998,866637845,566021896,800440835,92987698,193195065,429456164,395441711,1984812685,2017778566,1784663195,1683407248,1315562145,1080094634,1383856311,1551037884,101039829,135050206,437757123,337553864,1042385657,807962610,573804783,742039012,2531067453,2564033334,2328828971,2227573024,2935566865,2700099354,3001755655,3168937228,3868552805,3902563182,4203181171,4102977912,3736164937,3501741890,3265478751,3433712980,1106041591,1340463100,1576976609,1408749034,2043211483,2009195472,1708848333,1809054150,832877231,1068351396,766945465,599762354,159417987,126454664,361929877,463180190,2709260871,2943682380,3178106961,3009879386,2572697195,2538681184,2236228733,2336434550,3509871135,3745345300,3441850377,3274667266,3910161971,3877198648,4110568485,4211818798,2597806476,2497604743,2261089178,2295101073,2733856160,2902087851,3202437046,2968011453,3936291284,3835036895,4136440770,4169408201,3535486456,3702665459,3467192302,3231722213,2051518780,1951317047,1716890410,1750902305,1113818384,1282050075,1584504582,1350078989,168810852,67556463,371049330,404016761,841739592,1008918595,775550814,540080725,3969562369,3801332234,4035489047,4269907996,3569255213,3669462566,3366754619,3332740144,2631065433,2463879762,2160117071,2395588676,2767645557,2868897406,3102011747,3069049960,202008497,33778362,270040487,504459436,875451293,975658646,675039627,641025152,2084704233,1917518562,1615861247,1851332852,1147550661,1248802510,1484005843,1451044056,933301370,967311729,733156972,632953703,260388950,25965917,328671808,496906059,1206477858,1239443753,1543208500,1441952575,2144161806,1908694277,1675577880,1842759443,3610369226,3644379585,3408119516,3307916247,4011190502,3776767469,4077384432,4245618683,2809771154,2842737049,3144396420,3043140495,2673705150,2438237621,2203032232,2370213795];const U2=[0,185469197,370938394,487725847,741876788,657861945,975451694,824852259,1483753576,1400783205,1315723890,1164071807,1950903388,2135319889,1649704518,1767536459,2967507152,3152976349,2801566410,2918353863,2631447780,2547432937,2328143614,2177544179,3901806776,3818836405,4270639778,4118987695,3299409036,3483825537,3535072918,3652904859,2077965243,1893020342,1841768865,1724457132,1474502543,1559041666,1107234197,1257309336,598438867,681933534,901210569,1052338372,261314535,77422314,428819965,310463728,3409685355,3224740454,3710368113,3593056380,3875770207,3960309330,4045380933,4195456072,2471224067,2554718734,2237133081,2388260884,3212035895,3028143674,2842678573,2724322336,4138563181,4255350624,3769721975,3955191162,3667219033,3516619604,3431546947,3347532110,2933734917,2782082824,3099667487,3016697106,2196052529,2313884476,2499348523,2683765030,1179510461,1296297904,1347548327,1533017514,1786102409,1635502980,2087309459,2003294622,507358933,355706840,136428751,53458370,839224033,957055980,605657339,790073846,2373340630,2256028891,2607439820,2422494913,2706270690,2856345839,3075636216,3160175349,3573941694,3725069491,3273267108,3356761769,4181598602,4063242375,4011996048,3828103837,1033297158,915985419,730517276,545572369,296679730,446754879,129166120,213705253,1709610350,1860738147,1945798516,2029293177,1239331162,1120974935,1606591296,1422699085,4148292826,4233094615,3781033664,3931371469,3682191598,3497509347,3446004468,3328955385,2939266226,2755636671,3106780840,2988687269,2198438022,2282195339,2501218972,2652609425,1201765386,1286567175,1371368976,1521706781,1805211710,1620529459,2105887268,1988838185,533804130,350174575,164439672,46346101,870912086,954669403,636813900,788204353,2358957921,2274680428,2592523643,2441661558,2695033685,2880240216,3065962831,3182487618,3572145929,3756299780,3270937875,3388507166,4174560061,4091327024,4006521127,3854606378,1014646705,930369212,711349675,560487590,272786309,457992840,106852767,223377554,1678381017,1862534868,1914052035,2031621326,1211247597,1128014560,1580087799,1428173050,32283319,182621114,401639597,486441376,768917123,651868046,1003007129,818324884,1503449823,1385356242,1333838021,1150208456,1973745387,2125135846,1673061617,1756818940,2970356327,3120694122,2802849917,2887651696,2637442643,2520393566,2334669897,2149987652,3917234703,3799141122,4284502037,4100872472,3309594171,3460984630,3545789473,3629546796,2050466060,1899603969,1814803222,1730525723,1443857720,1560382517,1075025698,1260232239,575138148,692707433,878443390,1062597235,243256656,91341917,409198410,325965383,3403100636,3252238545,3704300486,3620022987,3874428392,3990953189,4042459122,4227665663,2460449204,2578018489,2226875310,2411029155,3198115200,3046200461,2827177882,2743944855];const U3=[0,218828297,437656594,387781147,875313188,958871085,775562294,590424639,1750626376,1699970625,1917742170,2135253587,1551124588,1367295589,1180849278,1265195639,3501252752,3720081049,3399941250,3350065803,3835484340,3919042237,4270507174,4085369519,3102249176,3051593425,2734591178,2952102595,2361698556,2177869557,2530391278,2614737639,3145456443,3060847922,2708326185,2892417312,2404901663,2187128086,2504130317,2555048196,3542330227,3727205754,3375740769,3292445032,3876557655,3926170974,4246310725,4027744588,1808481195,1723872674,1910319033,2094410160,1608975247,1391201670,1173430173,1224348052,59984867,244860394,428169201,344873464,935293895,984907214,766078933,547512796,1844882806,1627235199,2011214180,2062270317,1507497298,1423022939,1137477952,1321699145,95345982,145085239,532201772,313773861,830661914,1015671571,731183368,648017665,3175501286,2957853679,2807058932,2858115069,2305455554,2220981195,2474404304,2658625497,3575528878,3625268135,3473416636,3254988725,3778151818,3963161475,4213447064,4130281361,3599595085,3683022916,3432737375,3247465558,3802222185,4020912224,4172763771,4122762354,3201631749,3017672716,2764249623,2848461854,2331590177,2280796200,2431590963,2648976442,104699613,188127444,472615631,287343814,840019705,1058709744,671593195,621591778,1852171925,1668212892,1953757831,2037970062,1514790577,1463996600,1080017571,1297403050,3673637356,3623636965,3235995134,3454686199,4007360968,3822090177,4107101658,4190530515,2997825956,3215212461,2830708150,2779915199,2256734592,2340947849,2627016082,2443058075,172466556,122466165,273792366,492483431,1047239e3,861968209,612205898,695634755,1646252340,1863638845,2013908262,1963115311,1446242576,1530455833,1277555970,1093597963,1636604631,1820824798,2073724613,1989249228,1436590835,1487645946,1337376481,1119727848,164948639,81781910,331544205,516552836,1039717051,821288114,669961897,719700128,2973530695,3157750862,2871682645,2787207260,2232435299,2283490410,2667994737,2450346104,3647212047,3564045318,3279033885,3464042516,3980931627,3762502690,4150144569,4199882800,3070356634,3121275539,2904027272,2686254721,2200818878,2384911031,2570832044,2486224549,3747192018,3528626907,3310321856,3359936201,3950355702,3867060991,4049844452,4234721005,1739656202,1790575107,2108100632,1890328081,1402811438,1586903591,1233856572,1149249077,266959938,48394827,369057872,418672217,1002783846,919489135,567498868,752375421,209336225,24197544,376187827,459744698,945164165,895287692,574624663,793451934,1679968233,1764313568,2117360635,1933530610,1343127501,1560637892,1243112415,1192455638,3704280881,3519142200,3336358691,3419915562,3907448597,3857572124,4075877127,4294704398,3029510009,3113855344,2927934315,2744104290,2159976285,2377486676,2594734927,2544078150];const U4=[0,151849742,303699484,454499602,607398968,758720310,908999204,1059270954,1214797936,1097159550,1517440620,1400849762,1817998408,1699839814,2118541908,2001430874,2429595872,2581445614,2194319100,2345119218,3034881240,3186202582,2801699524,2951971274,3635996816,3518358430,3399679628,3283088770,4237083816,4118925222,4002861748,3885750714,1002142683,850817237,698445255,548169417,529487843,377642221,227885567,77089521,1943217067,2061379749,1640576439,1757691577,1474760595,1592394909,1174215055,1290801793,2875968315,2724642869,3111247143,2960971305,2405426947,2253581325,2638606623,2487810577,3808662347,3926825029,4044981591,4162096729,3342319475,3459953789,3576539503,3693126241,1986918061,2137062819,1685577905,1836772287,1381620373,1532285339,1078185097,1229899655,1040559837,923313619,740276417,621982671,439452389,322734571,137073913,19308535,3871163981,4021308739,4104605777,4255800159,3263785589,3414450555,3499326569,3651041127,2933202493,2815956275,3167684641,3049390895,2330014213,2213296395,2566595609,2448830231,1305906550,1155237496,1607244650,1455525988,1776460110,1626319424,2079897426,1928707164,96392454,213114376,396673818,514443284,562755902,679998e3,865136418,983426092,3708173718,3557504664,3474729866,3323011204,4180808110,4030667424,3945269170,3794078908,2507040230,2623762152,2272556026,2390325492,2975484382,3092726480,2738905026,2857194700,3973773121,3856137295,4274053469,4157467219,3371096953,3252932727,3673476453,3556361835,2763173681,2915017791,3064510765,3215307299,2156299017,2307622919,2459735317,2610011675,2081048481,1963412655,1846563261,1729977011,1480485785,1362321559,1243905413,1126790795,878845905,1030690015,645401037,796197571,274084841,425408743,38544885,188821243,3613494426,3731654548,3313212038,3430322568,4082475170,4200115116,3780097726,3896688048,2668221674,2516901860,2366882550,2216610296,3141400786,2989552604,2837966542,2687165888,1202797690,1320957812,1437280870,1554391400,1669664834,1787304780,1906247262,2022837584,265905162,114585348,499347990,349075736,736970802,585122620,972512814,821712160,2595684844,2478443234,2293045232,2174754046,3196267988,3079546586,2895723464,2777952454,3537852828,3687994002,3234156416,3385345166,4142626212,4293295786,3841024952,3992742070,174567692,57326082,410887952,292596766,777231668,660510266,1011452712,893681702,1108339068,1258480242,1343618912,1494807662,1715193156,1865862730,1948373848,2100090966,2701949495,2818666809,3004591147,3122358053,2235061775,2352307457,2535604243,2653899549,3915653703,3764988233,4219352155,4067639125,3444575871,3294430577,3746175075,3594982253,836553431,953270745,600235211,718002117,367585007,484830689,133361907,251657213,2041877159,1891211689,1806599355,1654886325,1568718495,1418573201,1335535747,1184342925];function convertToInt32(bytes){const result=[];for(let i=0;i>2;__classPrivateFieldGet$1(this,_AES_Ke,"f")[index][i%4]=tk[i];__classPrivateFieldGet$1(this,_AES_Kd,"f")[rounds-index][i%4]=tk[i]}let rconpointer=0;let t=KC,tt;while(t>16&255]<<24^S[tt>>8&255]<<16^S[tt&255]<<8^S[tt>>24&255]^rcon[rconpointer]<<24;rconpointer+=1;if(KC!=8){for(let i=1;i>8&255]<<8^S[tt>>16&255]<<16^S[tt>>24&255]<<24;for(let i=KC/2+1;i>2;c=t%4;__classPrivateFieldGet$1(this,_AES_Ke,"f")[r][c]=tk[i];__classPrivateFieldGet$1(this,_AES_Kd,"f")[rounds-r][c]=tk[i++];t++}}for(let r=1;r>24&255]^U2[tt>>16&255]^U3[tt>>8&255]^U4[tt&255]}}}encrypt(plaintext){if(plaintext.length!=16){throw new TypeError("invalid plaintext size (must be 16 bytes)")}const rounds=__classPrivateFieldGet$1(this,_AES_Ke,"f").length-1;const a=[0,0,0,0];let t=convertToInt32(plaintext);for(let i=0;i<4;i++){t[i]^=__classPrivateFieldGet$1(this,_AES_Ke,"f")[0][i]}for(let r=1;r>24&255]^T2[t[(i+1)%4]>>16&255]^T3[t[(i+2)%4]>>8&255]^T4[t[(i+3)%4]&255]^__classPrivateFieldGet$1(this,_AES_Ke,"f")[r][i]}t=a.slice()}const result=new Uint8Array(16);let tt=0;for(let i=0;i<4;i++){tt=__classPrivateFieldGet$1(this,_AES_Ke,"f")[rounds][i];result[4*i]=(S[t[i]>>24&255]^tt>>24)&255;result[4*i+1]=(S[t[(i+1)%4]>>16&255]^tt>>16)&255;result[4*i+2]=(S[t[(i+2)%4]>>8&255]^tt>>8)&255;result[4*i+3]=(S[t[(i+3)%4]&255]^tt)&255}return result}decrypt(ciphertext){if(ciphertext.length!=16){throw new TypeError("invalid ciphertext size (must be 16 bytes)")}const rounds=__classPrivateFieldGet$1(this,_AES_Kd,"f").length-1;const a=[0,0,0,0];let t=convertToInt32(ciphertext);for(let i=0;i<4;i++){t[i]^=__classPrivateFieldGet$1(this,_AES_Kd,"f")[0][i]}for(let r=1;r>24&255]^T6[t[(i+3)%4]>>16&255]^T7[t[(i+2)%4]>>8&255]^T8[t[(i+1)%4]&255]^__classPrivateFieldGet$1(this,_AES_Kd,"f")[r][i]}t=a.slice()}const result=new Uint8Array(16);let tt=0;for(let i=0;i<4;i++){tt=__classPrivateFieldGet$1(this,_AES_Kd,"f")[rounds][i];result[4*i]=(Si[t[i]>>24&255]^tt>>24)&255;result[4*i+1]=(Si[t[(i+3)%4]>>16&255]^tt>>16)&255;result[4*i+2]=(Si[t[(i+2)%4]>>8&255]^tt>>8)&255;result[4*i+3]=(Si[t[(i+1)%4]&255]^tt)&255}return result}}_AES_key=new WeakMap,_AES_Kd=new WeakMap,_AES_Ke=new WeakMap;class ModeOfOperation{constructor(name,key,cls){if(cls&&!(this instanceof cls)){throw new Error(`${name} must be instantiated with "new"`)}Object.defineProperties(this,{aes:{enumerable:true,value:new AES(key)},name:{enumerable:true,value:name}})}}var __classPrivateFieldSet=__$G&&__$G.__classPrivateFieldSet||function(receiver,state,value,kind,f){if(kind==="m")throw new TypeError("Private method is not writable");if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a setter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot write private member to an object whose class did not declare it");return kind==="a"?f.call(receiver,value):f?f.value=value:state.set(receiver,value),value};var __classPrivateFieldGet=__$G&&__$G.__classPrivateFieldGet||function(receiver,state,kind,f){if(kind==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof state==="function"?receiver!==state||!f:!state.has(receiver))throw new TypeError("Cannot read private member from an object whose class did not declare it");return kind==="m"?f:kind==="a"?f.call(receiver):f?f.value:state.get(receiver)};var _CTR_remaining,_CTR_remainingIndex,_CTR_counter;class CTR extends ModeOfOperation{constructor(key,initialValue){super("CTR",key,CTR);_CTR_remaining.set(this,void 0);_CTR_remainingIndex.set(this,void 0);_CTR_counter.set(this,void 0);__classPrivateFieldSet(this,_CTR_counter,new Uint8Array(16),"f");__classPrivateFieldGet(this,_CTR_counter,"f").fill(0);__classPrivateFieldSet(this,_CTR_remaining,__classPrivateFieldGet(this,_CTR_counter,"f"),"f");__classPrivateFieldSet(this,_CTR_remainingIndex,16,"f");if(initialValue==null){initialValue=1}if(typeof initialValue==="number"){this.setCounterValue(initialValue)}else{this.setCounterBytes(initialValue)}}get counter(){return new Uint8Array(__classPrivateFieldGet(this,_CTR_counter,"f"))}setCounterValue(value){if(!Number.isInteger(value)||value<0||value>Number.MAX_SAFE_INTEGER){throw new TypeError("invalid counter initial integer value")}for(let index=15;index>=0;--index){__classPrivateFieldGet(this,_CTR_counter,"f")[index]=value%256;value=Math.floor(value/256)}}setCounterBytes(value){if(value.length!==16){throw new TypeError("invalid counter initial Uint8Array value length")}__classPrivateFieldGet(this,_CTR_counter,"f").set(value)}increment(){for(let i=15;i>=0;i--){if(__classPrivateFieldGet(this,_CTR_counter,"f")[i]===255){__classPrivateFieldGet(this,_CTR_counter,"f")[i]=0}else{__classPrivateFieldGet(this,_CTR_counter,"f")[i]++;break}}}encrypt(plaintext){var _a,_b;const crypttext=new Uint8Array(plaintext);for(let i=0;i0&&(N&N-1)===0,"invalid kdf.N","kdf.N",N);assertArgument(r>0&&p>0,"invalid kdf","kdf",kdf);const dkLen=spelunk(data,"crypto.kdfparams.dklen:int!");assertArgument(dkLen===32,"invalid kdf.dklen","kdf.dflen",dkLen);return{name:"scrypt",salt:salt,N:N,r:r,p:p,dkLen:64}}else if(kdf.toLowerCase()==="pbkdf2"){const salt=spelunk(data,"crypto.kdfparams.salt:data!");const prf=spelunk(data,"crypto.kdfparams.prf:string!");const algorithm=prf.split("-").pop();assertArgument(algorithm==="sha256"||algorithm==="sha512","invalid kdf.pdf","kdf.pdf",prf);const count=spelunk(data,"crypto.kdfparams.c:int!");const dkLen=spelunk(data,"crypto.kdfparams.dklen:int!");assertArgument(dkLen===32,"invalid kdf.dklen","kdf.dklen",dkLen);return{name:"pbkdf2",salt:salt,count:count,dkLen:dkLen,algorithm:algorithm}}}assertArgument(false,"unsupported key-derivation function","kdf",kdf)}function decryptKeystoreJsonSync(json,_password){const data=JSON.parse(json);const password=getPassword(_password);const params=getDecryptKdfParams(data);if(params.name==="pbkdf2"){const{salt,count,dkLen,algorithm}=params;const key=pbkdf2(password,salt,count,dkLen,algorithm);return getAccount(data,key)}assert(params.name==="scrypt","cannot be reached","UNKNOWN_ERROR",{params:params});const{salt,N,r,p,dkLen}=params;const key=scryptSync(password,salt,N,r,p,dkLen);return getAccount(data,key)}function stall$1(duration){return new Promise(resolve=>{setTimeout(()=>{resolve()},duration)})}async function decryptKeystoreJson(json,_password,progress){const data=JSON.parse(json);const password=getPassword(_password);const params=getDecryptKdfParams(data);if(params.name==="pbkdf2"){if(progress){progress(0);await stall$1(0)}const{salt,count,dkLen,algorithm}=params;const key=pbkdf2(password,salt,count,dkLen,algorithm);if(progress){progress(1);await stall$1(0)}return getAccount(data,key)}assert(params.name==="scrypt","cannot be reached","UNKNOWN_ERROR",{params:params});const{salt,N,r,p,dkLen}=params;const key=await scrypt(password,salt,N,r,p,dkLen,progress);return getAccount(data,key)}function getEncryptKdfParams(options){const salt=options.salt!=null?getBytes(options.salt,"options.salt"):randomBytes(32);let N=1<<17,r=8,p=1;if(options.scrypt){if(options.scrypt.N){N=options.scrypt.N}if(options.scrypt.r){r=options.scrypt.r}if(options.scrypt.p){p=options.scrypt.p}}assertArgument(typeof N==="number"&&N>0&&Number.isSafeInteger(N)&&(BigInt(N)&BigInt(N-1))===BigInt(0),"invalid scrypt N parameter","options.N",N);assertArgument(typeof r==="number"&&r>0&&Number.isSafeInteger(r),"invalid scrypt r parameter","options.r",r);assertArgument(typeof p==="number"&&p>0&&Number.isSafeInteger(p),"invalid scrypt p parameter","options.p",p);return{name:"scrypt",dkLen:32,salt:salt,N:N,r:r,p:p}}function _encryptKeystore(key,kdf,account,options){const privateKey=getBytes(account.privateKey,"privateKey");const iv=options.iv!=null?getBytes(options.iv,"options.iv"):randomBytes(16);assertArgument(iv.length===16,"invalid options.iv length","options.iv",options.iv);const uuidRandom=options.uuid!=null?getBytes(options.uuid,"options.uuid"):randomBytes(16);assertArgument(uuidRandom.length===16,"invalid options.uuid length","options.uuid",options.iv);const derivedKey=key.slice(0,16);const macPrefix=key.slice(16,32);const aesCtr=new CTR(derivedKey,iv);const ciphertext=getBytes(aesCtr.encrypt(privateKey));const mac=keccak256(concat([macPrefix,ciphertext]));const data={address:account.address.substring(2).toLowerCase(),id:uuidV4(uuidRandom),version:3,Crypto:{cipher:"aes-128-ctr",cipherparams:{iv:hexlify(iv).substring(2)},ciphertext:hexlify(ciphertext).substring(2),kdf:"scrypt",kdfparams:{salt:hexlify(kdf.salt).substring(2),n:kdf.N,dklen:32,p:kdf.p,r:kdf.r},mac:mac.substring(2)}};if(account.mnemonic){const client=options.client!=null?options.client:`quais/${version}`;const path=account.mnemonic.path||defaultPath;const locale=account.mnemonic.locale||"en";const mnemonicKey=key.slice(32,64);const entropy=getBytes(account.mnemonic.entropy,"account.mnemonic.entropy");const mnemonicIv=randomBytes(16);const mnemonicAesCtr=new CTR(mnemonicKey,mnemonicIv);const mnemonicCiphertext=getBytes(mnemonicAesCtr.encrypt(entropy));const now=new Date;const timestamp=now.getUTCFullYear()+"-"+zpad$1(now.getUTCMonth()+1,2)+"-"+zpad$1(now.getUTCDate(),2)+"T"+zpad$1(now.getUTCHours(),2)+"-"+zpad$1(now.getUTCMinutes(),2)+"-"+zpad$1(now.getUTCSeconds(),2)+".0Z";const gethFilename="UTC--"+timestamp+"--"+data.address;data["x-quais"]={client:client,gethFilename:gethFilename,path:path,locale:locale,mnemonicCounter:hexlify(mnemonicIv).substring(2),mnemonicCiphertext:hexlify(mnemonicCiphertext).substring(2),version:"0.1"}}return JSON.stringify(data)}function encryptKeystoreJsonSync(account,password,options){if(options==null){options={}}const passwordBytes=getPassword(password);const kdf=getEncryptKdfParams(options);const key=scryptSync(passwordBytes,kdf.salt,kdf.N,kdf.r,kdf.p,64);return _encryptKeystore(getBytes(key),kdf,account,options)}async function encryptKeystoreJson(account,password,options){if(options==null){options={}}const passwordBytes=getPassword(password);const kdf=getEncryptKdfParams(options);const key=await scrypt(passwordBytes,kdf.salt,kdf.N,kdf.r,kdf.p,64,options.progressCallback);return _encryptKeystore(getBytes(key),kdf,account,options)}const MasterSecret=new Uint8Array([66,105,116,99,111,105,110,32,115,101,101,100]);const HardenedBit=2147483648;const N=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");const Nibbles="0123456789abcdef";function zpad(value,length){let result="";while(value){result=Nibbles[value%16]+result;value=Math.trunc(value/16)}while(result.length=0;i-=8){data[33+(i>>3)]=index>>24-i&255}const I=getBytes(computeHmac("sha512",chainCode,data));return{IL:I.slice(0,32),IR:I.slice(32)}}function derivePath(node,path){const components=path.split("/");assertArgument(components.length>0,"invalid path","path",path);if(components[0]==="m"){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);components.shift()}let result=node;for(let i=0;i=16&&seed.length<=64,"invalid seed","seed","[REDACTED]");const I=getBytes(computeHmac("sha512",MasterSecret,seed));const signingKey=new SigningKey(hexlify(I.slice(0,32)));return new HDNodeWallet(_guard$1,signingKey,"0x00000000",hexlify(I.slice(32)),"m",0,0,mnemonic,null)}static fromExtendedKey(extendedKey){const bytes=toBeArray(decodeBase58(extendedKey));assertArgument(bytes.length===82||encodeBase58Check(bytes.slice(0,78))===extendedKey,"invalid extended key","extendedKey","[ REDACTED ]");const depth=bytes[4];const parentFingerprint=hexlify(bytes.slice(5,9));const index=parseInt(hexlify(bytes.slice(9,13)).substring(2),16);const chainCode=hexlify(bytes.slice(13,45));const key=bytes.slice(45,78);switch(hexlify(bytes.slice(0,4))){case"0x0488b21e":case"0x043587cf":{const publicKey=hexlify(key);return new HDNodeVoidWallet(_guard$1,computeAddress(publicKey),publicKey,parentFingerprint,chainCode,null,index,depth,null)}case"0x0488ade4":case"0x04358394 ":if(key[0]!==0){break}return new HDNodeWallet(_guard$1,new SigningKey(key.slice(1)),parentFingerprint,chainCode,null,index,depth,null,null)}assertArgument(false,"invalid extended key prefix","extendedKey","[ REDACTED ]")}static createRandom(path,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}const mnemonic=Mnemonic.fromEntropy(randomBytes(16),password,wordlist);return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromMnemonic(mnemonic,path){return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromPhrase(phrase,path,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}const mnemonic=Mnemonic.fromPhrase(phrase,password,wordlist);return HDNodeWallet.#fromSeed(mnemonic.computeSeed(),mnemonic).derivePath(path)}static fromSeed(seed){return HDNodeWallet.#fromSeed(seed,null)}}class HDNodeVoidWallet extends VoidSigner{publicKey;fingerprint;parentFingerprint;chainCode;path;index;depth;constructor(guard,address,publicKey,parentFingerprint,chainCode,path,index,depth,provider){super(address,provider);assertPrivate(guard,_guard$1,"HDNodeVoidWallet");defineProperties(this,{publicKey:publicKey});const fingerprint=dataSlice(ripemd160(sha256(publicKey)),0,4);defineProperties(this,{publicKey:publicKey,fingerprint:fingerprint,parentFingerprint:parentFingerprint,chainCode:chainCode,path:path,index:index,depth:depth})}connect(provider){return new HDNodeVoidWallet(_guard$1,this.address,this.publicKey,this.parentFingerprint,this.chainCode,this.path,this.index,this.depth,provider)}get extendedKey(){assert(this.depth<256,"Depth too deep","UNSUPPORTED_OPERATION",{operation:"extendedKey"});return encodeBase58Check(concat(["0x0488B21E",zpad(this.depth,1),this.parentFingerprint,zpad(this.index,4),this.chainCode,this.publicKey]))}hasPath(){return this.path!=null}deriveChild(_index){const index=getNumber(_index,"index");assertArgument(index<=4294967295,"invalid index","index",index);let path=this.path;if(path){path+="/"+(index&~HardenedBit);if(index&HardenedBit){path+="'"}}const{IR,IL}=ser_I(index,this.chainCode,this.publicKey,null);const Ki=SigningKey.addPoints(IL,this.publicKey,true);const address=computeAddress(Ki);return new HDNodeVoidWallet(_guard$1,address,Ki,this.fingerprint,hexlify(IR),path,index,this.depth+1,this.provider)}derivePath(path){return derivePath(this,path)}}const MAX_ADDRESS_DERIVATION_ATTEMPTS=1e7;const _guard={};class AbstractHDWallet{static _version=1;static _coinType;_addresses=new Map;_root;provider;constructor(guard,root,provider){assertPrivate(guard,_guard,"AbstractHDWallet");this._root=root;this.provider=provider}static parentPath(coinType){return`m/44'/${coinType}'`}coinType(){return this.constructor._coinType}get xPub(){return this._root.extendedKey}deriveNextAddressNode(account,startingIndex,zone,isChange=false){const changeIndex=isChange?1:0;const changeNode=this._root.deriveChild(account).deriveChild(changeIndex);let addrIndex=startingIndex;let addressNode;const isValidAddressForZone=address=>{const addressZone=getZoneForAddress(address);if(!addressZone){return false}const isCorrectShard=addressZone===zone;const isCorrectLedger=this.coinType()===969?isQiAddress(address):!isQiAddress(address);return isCorrectShard&&isCorrectLedger};for(let attempts=0;attempts{if(addressInfo.index===addressIndex){throw new Error(`Address for index ${addressIndex} already exists`)}});const changeIndex=isChange?1:0;const addressNode=this._root.deriveChild(account).deriveChild(changeIndex).deriveChild(addressIndex);const zone=getZoneForAddress(addressNode.address);if(!zone){throw new Error(`Failed to derive a valid address zone for the index ${addressIndex}`)}return this.createAndStoreAddressInfo(addressNode,account,zone,isChange,addressMap)}async getNextAddress(account,zone){return Promise.resolve(this._getNextAddress(account,zone,false,this._addresses))}getNextAddressSync(account,zone){return this._getNextAddress(account,zone,false,this._addresses)}_getNextAddress(accountIndex,zone,isChange,addressMap){this.validateZone(zone);const lastIndex=this.getLastAddressIndex(addressMap,zone,accountIndex,isChange);const addressNode=this.deriveNextAddressNode(accountIndex,lastIndex+1,zone,isChange);return this.createAndStoreAddressInfo(addressNode,accountIndex,zone,isChange,addressMap)}getAddressInfo(address){const addressInfo=this._addresses.get(address);if(!addressInfo){return null}return addressInfo}getPrivateKey(address){const hdNode=this._getHDNodeForAddress(address);return hdNode.privateKey}getAddressesForAccount(account){const addresses=this._addresses.values();return Array.from(addresses).filter(addressInfo=>addressInfo.account===account)}getAddressesForZone(zone){this.validateZone(zone);const addresses=this._addresses.values();return Array.from(addresses).filter(addressInfo=>addressInfo.zone===zone)}static createInstance(mnemonic){const coinType=this._coinType;const root=HDNodeWallet.fromMnemonic(mnemonic,this.parentPath(coinType));return new this(_guard,root)}static fromMnemonic(mnemonic){return this.createInstance(mnemonic)}static createRandom(password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}const mnemonic=Mnemonic.fromEntropy(randomBytes(16),password,wordlist);return this.createInstance(mnemonic)}static fromPhrase(phrase,password,wordlist){if(password==null){password=""}if(wordlist==null){wordlist=LangEn.wordlist()}const mnemonic=Mnemonic.fromPhrase(phrase,password,wordlist);return this.createInstance(mnemonic)}connect(provider){this.provider=provider}validateZone(zone){if(!Object.values(exports.Zone).includes(zone)){throw new Error(`Invalid zone: ${zone}`)}}_getHDNodeForAddress(addr){const addressInfo=this._addresses.get(addr);if(!addressInfo){throw new Error(`Address ${addr} is not known to this wallet`)}const changeIndex=addressInfo.change?1:0;return this._root.deriveChild(addressInfo.account).deriveChild(changeIndex).deriveChild(addressInfo.index)}serialize(){const addresses=Array.from(this._addresses.values());return{version:this.constructor._version,phrase:this._root.mnemonic.phrase,coinType:this.coinType(),addresses:addresses}}static async deserialize(_serialized){throw new Error("deserialize method must be implemented in the subclass")}static validateSerializedWallet(serialized){if(serialized.version!==this._version){throw new Error(`Invalid version ${serialized.version} for wallet (expected ${this._version})`)}if(serialized.coinType!==this._coinType){throw new Error(`Invalid coinType ${serialized.coinType} for wallet (expected ${this._coinType})`)}}importSerializedAddresses(addressMap,addresses){for(const addressInfo of addresses){const newAddressInfo=this._addAddress(addressMap,addressInfo.account,addressInfo.index,addressInfo.change);if(addressInfo.address!==newAddressInfo.address){throw new Error(`Address mismatch: ${addressInfo.address} != ${newAddressInfo.address}`)}if(addressInfo.pubKey!==newAddressInfo.pubKey){throw new Error(`Public key mismatch: ${addressInfo.pubKey} != ${newAddressInfo.pubKey}`)}if(addressInfo.zone!==newAddressInfo.zone){throw new Error(`Zone mismatch: ${addressInfo.zone} != ${newAddressInfo.zone}`)}}}getLastAddressIndex(addressMap,zone,account,isChange){const addresses=Array.from(addressMap.values()).filter(addressInfo=>addressInfo.account===account&&addressInfo.zone===zone&&addressInfo.change===isChange);return addresses.reduce((maxIndex,addressInfo)=>Math.max(maxIndex,addressInfo.index),-1)}createAndStoreAddressInfo(addressNode,account,zone,isChange,addressMap){const neuteredAddressInfo={pubKey:addressNode.publicKey,address:addressNode.address,account:account,index:addressNode.index,change:isChange,zone:zone};addressMap.set(neuteredAddressInfo.address,neuteredAddressInfo);return neuteredAddressInfo}}class QuaiHDWallet extends AbstractHDWallet{static _version=1;static _coinType=994;constructor(guard,root,provider){super(guard,root,provider)}async signTransaction(tx){const from=await resolveAddress(tx.from);const fromNode=this._getHDNodeForAddress(from);const signedTx=await fromNode.signTransaction(tx);return signedTx}async sendTransaction(tx){if(!this.provider){throw new Error("Provider is not set")}const from=await resolveAddress(tx.from);const fromNode=this._getHDNodeForAddress(from);const fromNodeConnected=fromNode.connect(this.provider);return await fromNodeConnected.sendTransaction(tx)}async signMessage(address,message){const addrNode=this._getHDNodeForAddress(address);return await addrNode.signMessage(message)}static async deserialize(serialized){super.validateSerializedWallet(serialized);const mnemonic=Mnemonic.fromPhrase(serialized.phrase);const path=this.parentPath(serialized.coinType);const root=HDNodeWallet.fromMnemonic(mnemonic,path);const wallet=new this(_guard,root);wallet.importSerializedAddresses(wallet._addresses,serialized.addresses);return wallet}async signTypedData(address,domain,types,value){const addrNode=this._getHDNodeForAddress(address);return addrNode.signTypedData(domain,types,value)}}class Wallet extends BaseWallet{constructor(key,provider){if(typeof key==="string"&&!key.startsWith("0x")){key="0x"+key}const signingKey=typeof key==="string"?new SigningKey(key):key;super(signingKey,provider)}connect(provider){return new Wallet(this.signingKey,provider)}async encrypt(password,progressCallback){const account={address:this.address,privateKey:this.privateKey};return await encryptKeystoreJson(account,password,{progressCallback:progressCallback})}encryptSync(password){const account={address:this.address,privateKey:this.privateKey};return encryptKeystoreJsonSync(account,password)}static#fromAccount(account){assertArgument(account,"invalid JSON wallet","json","[ REDACTED ]");const wallet=new Wallet(account.privateKey);assertArgument(wallet.address===account.address,"address/privateKey mismatch","json","[ REDACTED ]");return wallet}static async fromEncryptedJson(json,password,progress){let account;if(isKeystoreJson(json)){account=await decryptKeystoreJson(json,password,progress);return Wallet.#fromAccount(account)}throw new Error("invalid JSON wallet")}static fromEncryptedJsonSync(json,password){let account=null;if(isKeystoreJson(json)){account=decryptKeystoreJsonSync(json,password)}else{assertArgument(false,"invalid JSON wallet","json","[ REDACTED ]")}return Wallet.#fromAccount(account)}}const TAGS={challenge:"BIP0340/challenge",keyagg_list:"KeyAgg list",keyagg_coef:"KeyAgg coefficient",musig_aux:"MuSig/aux",musig_nonce:"MuSig/nonce",musig_deterministic_nonce:"MuSig/deterministic/nonce",musig_noncecoef:"MuSig/noncecoef"};function compare32b(a,b){if(a.length!==32||b.length!==32)throw new Error("Invalid array");const aD=new DataView(a.buffer,a.byteOffset,a.length);const bD=new DataView(b.buffer,b.byteOffset,b.length);for(let i=0;i<8;i++){const cmp=aD.getUint32(i*4)-bD.getUint32(i*4);if(cmp!==0)return cmp}return 0}function compare33b(a,b){if(a.length!==33||b.length!==33)throw new Error("Invalid array");const cmp=a[0]-b[0];if(cmp!==0)return cmp;return compare32b(a.subarray(1),b.subarray(1))}const makeSessionId=typeof self==="object"&&(self.crypto||self.msCrypto)?()=>(self.crypto||self.msCrypto).getRandomValues(new Uint8Array(32)):()=>require("crypto").randomBytes(32);const _keyAggCache=new WeakMap;const _coefCache=new WeakMap;const _nonceCache=new WeakMap;const _sessionCache=new WeakMap;function MuSigFactory(ecc){const CPOINT_INF=new Uint8Array(33);const SCALAR_0=new Uint8Array(32);const SCALAR_1=new Uint8Array(32);SCALAR_1[31]=1;ecc.scalarNegate(SCALAR_1);function keyAggCoeff(publicKeys,publicKey){let coefCache=_coefCache.get(publicKeys);if(coefCache===undefined){coefCache=new Map;_coefCache.set(publicKeys,coefCache)}let coefficient=coefCache.get(publicKey);if(coefficient)return coefficient;coefficient=SCALAR_1;let secondPublicKey;let publicKeyHash;let keyAggCache=_keyAggCache.get(publicKeys);if(keyAggCache===undefined){const pkIdx2=publicKeys.findIndex(pk=>compare33b(pk,publicKeys[0])!==0);secondPublicKey=publicKeys[pkIdx2];publicKeyHash=ecc.taggedHash(TAGS.keyagg_list,...publicKeys);keyAggCache={publicKeyHash:publicKeyHash,secondPublicKey:secondPublicKey};_keyAggCache.set(publicKeys,keyAggCache)}else{({publicKeyHash,secondPublicKey}=keyAggCache)}if(secondPublicKey===undefined||compare33b(publicKey,secondPublicKey)!==0)coefficient=ecc.taggedHash(TAGS.keyagg_coef,publicKeyHash,publicKey);coefCache.set(publicKey,coefficient);return coefficient}function addTweak(ctx,t){const tweak="tweak"in t?t:{tweak:t};if(!ecc.isScalar(tweak.tweak))throw new TypeError("Expected tweak to be a valid scalar with curve order");let{gacc,tacc}=ctx;let aggPublicKey=ctx.aggPublicKey;if(!ecc.hasEvenY(aggPublicKey)&&tweak.xOnly){gacc=ecc.scalarNegate(gacc);tacc=ecc.scalarNegate(tacc);aggPublicKey=ecc.pointNegate(aggPublicKey)}aggPublicKey=ecc.pointAddTweak(aggPublicKey,tweak.tweak,false);if(aggPublicKey===null)throw new Error("Unexpected point at infinity during tweaking");tacc=ecc.scalarAdd(tweak.tweak,tacc);return{aggPublicKey:aggPublicKey,gacc:gacc,tacc:tacc}}function keyAgg(publicKeys,...tweaks){checkArgs({publicKeys:publicKeys});const multipliedPublicKeys=publicKeys.map(publicKey=>{const coefficient=keyAggCoeff(publicKeys,publicKey);let multipliedPublicKey;if(compare32b(coefficient,SCALAR_1)===0){multipliedPublicKey=publicKey}else{multipliedPublicKey=ecc.pointMultiplyUnsafe(publicKey,coefficient,false)}if(multipliedPublicKey===null)throw new Error("Point at infinity during aggregation");return multipliedPublicKey});const aggPublicKey=multipliedPublicKeys.reduce((a,b)=>{const next=ecc.pointAdd(a,b,false);if(next===null)throw new Error("Point at infinity during aggregation");return next});return tweaks.reduce((ctx,tweak)=>addTweak(ctx,tweak),{aggPublicKey:aggPublicKey,gacc:SCALAR_1,tacc:SCALAR_0})}function getSessionValues(sessionKey){const sessionValues=_sessionCache.get(sessionKey);if(!sessionValues)throw new Error("Invalid session key, please call `startSigningSession`");return sessionValues}function nonceAgg(publicNonces){checkArgs({publicNonces:publicNonces});const aggNonces=[publicNonces[0].subarray(0,33),publicNonces[0].subarray(33)];for(let i=1;iecc.hasEvenY(finalNonce)?k:ecc.scalarNegate(k));const a=keyAggCoeff(publicKeys,publicKey);const g=ecc.hasEvenY(aggPublicKey)?gacc:ecc.scalarNegate(gacc);const d=ecc.scalarMultiply(g,secretKey);const bk2=ecc.scalarMultiply(coefficient,k2);const k1bk2=ecc.scalarAdd(k1,bk2);const ea=ecc.scalarMultiply(challenge,a);const ead=ecc.scalarMultiply(ea,d);const sig=ecc.scalarAdd(k1bk2,ead);return sig}function partialSign({secretKey,publicNonce,sessionKey,verify=true}){checkArgs({publicNonce:publicNonce,secretKey:secretKey});const secretNonce=_nonceCache.get(publicNonce);if(secretNonce===undefined)throw new Error("No secret nonce found for specified public nonce");_nonceCache.delete(publicNonce);const publicKey=ecc.getPublicKey(secretKey,true);if(publicKey===null)throw new Error("Invalid secret key, no corresponding public key");if(compare33b(publicKey,secretNonce.subarray(64))!==0)throw new Error("Secret nonce pubkey mismatch");const secretNonces=[secretNonce.subarray(0,32),secretNonce.subarray(32,64)];const sig=partialSignInner({secretKey:secretKey,publicKey:publicKey,secretNonces:secretNonces,sessionKey:sessionKey});if(verify){const publicNonces=[publicNonce.subarray(0,33),publicNonce.subarray(33)];const valid=partialVerifyInner({sig:sig,publicKey:publicKey,publicNonces:publicNonces,sessionKey:sessionKey});if(!valid)throw new Error("Partial signature failed verification")}return sig}function deterministicSign({secretKey,aggOtherNonce,publicKeys,tweaks=[],msg,rand,verify=true,nonceOnly=false}){checkArgs({rand:rand,secretKey:secretKey,aggOtherNonce:aggOtherNonce});const publicKey=ecc.getPublicKey(secretKey,true);if(publicKey===null)throw new Error("Secret key has no corresponding public key");let secretKeyPrime;if(rand!==undefined){secretKeyPrime=ecc.taggedHash(TAGS.musig_aux,rand);for(let i=0;i<32;i++){secretKeyPrime[i]=secretKeyPrime[i]^secretKey[i]}}else{secretKeyPrime=secretKey}const ctx=keyAgg(publicKeys,...tweaks);const aggPublicKey=ecc.pointX(ctx.aggPublicKey);const mLength=new Uint8Array(8);new DataView(mLength.buffer).setBigUint64(0,BigInt(msg.length));const secretNonce=new Uint8Array(97);const publicNonce=new Uint8Array(66);for(let i=0;i<2;i++){const kH=ecc.taggedHash(TAGS.musig_deterministic_nonce,...[secretKeyPrime,aggOtherNonce,aggPublicKey,mLength,msg,Uint8Array.of(i)]);const k=ecc.scalarMod(kH);if(compare32b(SCALAR_0,k)===0)throw new Error("0 secret nonce");const pub=ecc.getPublicKey(k,true);if(pub===null)throw new Error("Secret nonce has no corresponding public nonce");secretNonce.set(k,i*32);publicNonce.set(pub,i*33)}secretNonce.set(publicKey,64);if(nonceOnly)return{publicNonce:publicNonce};_nonceCache.set(publicNonce,secretNonce);const aggNonce=nonceAgg([aggOtherNonce,publicNonce]);const sessionKey=startSigningSessionInner(aggNonce,msg,publicKeys,ctx);const sig=partialSign({secretKey:secretKey,publicNonce:publicNonce,sessionKey:sessionKey,verify:verify});return{sig:sig,sessionKey:sessionKey,publicNonce:publicNonce}}const pubKeyArgs=["publicKey","publicKeys"];const scalarArgs=["tweak","sig","sigs","tacc","gacc"];const otherArgs32b=["xOnlyPublicKey","rand","sessionId"];const args32b=["secretKey",...scalarArgs,...otherArgs32b];const pubNonceArgs=["publicNonce","publicNonces","aggNonce","aggOtherNonce","finalNonce"];const argLengths=new Map;args32b.forEach(a=>argLengths.set(a,32));pubKeyArgs.forEach(a=>argLengths.set(a,33));pubNonceArgs.forEach(a=>argLengths.set(a,66));argLengths.set("secretNonce",97);argLengths.set("aggPublicKey",65);const scalarNames=new Set;scalarArgs.forEach(n=>scalarNames.add(n));function checkArgs(args){for(let[name,values]of Object.entries(args)){if(values===undefined)continue;values=Array.isArray(values)?values:[values];if(values.length===0)throw new TypeError(`0-length ${name}s not supported`);for(const value of values){if(argLengths.get(name)!==value.length)throw new TypeError(`Invalid ${name} length (${value.length})`);if(name==="secretKey"){if(!ecc.isSecret(value))throw new TypeError(`Invalid secretKey`)}else if(name==="secretNonce"){for(let i=0;i<64;i+=32)if(!ecc.isSecret(value.subarray(i,i+32)))throw new TypeError(`Invalid secretNonce`)}else if(scalarNames.has(name)){for(let i=0;i{if("aggPublicKey"in ctx)return ecc.pointX(ctx.aggPublicKey);return ecc.pointX(getSessionValues(ctx).aggPublicKey)},getPlainPubkey:ctx=>{if("aggPublicKey"in ctx)return ecc.pointCompress(ctx.aggPublicKey);return ecc.pointCompress(getSessionValues(ctx).aggPublicKey)},keySort:publicKeys=>{checkArgs({publicKeys:publicKeys});return[...publicKeys].sort((a,b)=>compare33b(a,b))},keyAgg:keyAgg,addTweaks:(ctx,...tweaks)=>{checkArgs(ctx);return tweaks.reduce((c,tweak)=>addTweak(c,tweak),ctx)},nonceGen:({sessionId=makeSessionId(),secretKey,publicKey,xOnlyPublicKey,msg,extraInput})=>{if(extraInput!==undefined&&extraInput.length>Math.pow(2,32)-1)throw new TypeError("extraInput is limited to 2^32-1 bytes");checkArgs({sessionId:sessionId,secretKey:secretKey,publicKey:publicKey,xOnlyPublicKey:xOnlyPublicKey});let rand;if(secretKey!==undefined){rand=ecc.taggedHash(TAGS.musig_aux,sessionId);for(let i=0;i<32;i++){rand[i]=rand[i]^secretKey[i]}}else{rand=sessionId}if(xOnlyPublicKey===undefined)xOnlyPublicKey=new Uint8Array;const mPrefixed=[Uint8Array.of(0)];if(msg!==undefined){mPrefixed[0][0]=1;mPrefixed.push(new Uint8Array(8));new DataView(mPrefixed[1].buffer).setBigUint64(0,BigInt(msg.length));mPrefixed.push(msg)}if(extraInput===undefined)extraInput=new Uint8Array;const eLength=new Uint8Array(4);new DataView(eLength.buffer).setUint32(0,extraInput.length);const secretNonce=new Uint8Array(97);const publicNonce=new Uint8Array(66);for(let i=0;i<2;i++){const kH=ecc.taggedHash(TAGS.musig_nonce,rand,Uint8Array.of(publicKey.length),publicKey,Uint8Array.of(xOnlyPublicKey.length),xOnlyPublicKey,...mPrefixed,eLength,extraInput,Uint8Array.of(i));const k=ecc.scalarMod(kH);if(compare32b(SCALAR_0,k)===0)throw new Error("0 secret nonce");const pub=ecc.getPublicKey(k,true);if(pub===null)throw new Error("Secret nonce has no corresponding public nonce");secretNonce.set(k,i*32);publicNonce.set(pub,i*33)}secretNonce.set(publicKey,64);_nonceCache.set(publicNonce,secretNonce);return publicNonce},addExternalNonce:(publicNonce,secretNonce)=>{checkArgs({publicNonce:publicNonce,secretNonce:secretNonce});_nonceCache.set(publicNonce,secretNonce)},deterministicNonceGen:args=>deterministicSign({...args,nonceOnly:true}),deterministicSign:deterministicSign,nonceAgg:nonceAgg,startSigningSession:(aggNonce,msg,publicKeys,...tweaks)=>{checkArgs({aggNonce:aggNonce});const ctx=keyAgg(publicKeys,...tweaks);return startSigningSessionInner(aggNonce,msg,publicKeys,ctx)},partialSign:partialSign,partialVerify:({sig,publicKey,publicNonce,sessionKey})=>{checkArgs({sig:sig,publicKey:publicKey,publicNonce:publicNonce});const publicNonces=[publicNonce.subarray(0,33),publicNonce.subarray(33)];const valid=partialVerifyInner({sig:sig,publicKey:publicKey,publicNonces:publicNonces,sessionKey:sessionKey});return valid},signAgg:(sigs,sessionKey)=>{checkArgs({sigs:sigs});const{aggPublicKey,tacc,challenge,finalNonce}=getSessionValues(sessionKey);let sPart=ecc.scalarMultiply(challenge,tacc);if(!ecc.hasEvenY(aggPublicKey)){sPart=ecc.scalarNegate(sPart)}const aggS=sigs.reduce((a,b)=>ecc.scalarAdd(a,b),sPart);const sig=new Uint8Array(64);sig.set(ecc.pointX(finalNonce),0);sig.set(aggS,32);return sig}}}class QiHDWallet extends AbstractHDWallet{static _version=1;static _GAP_LIMIT=20;static _coinType=969;_changeAddresses=new Map;_gapChangeAddresses=[];_gapAddresses=[];_outpoints=[];constructor(guard,root,provider){super(guard,root,provider)}async getNextChangeAddress(account,zone){return Promise.resolve(this._getNextAddress(account,zone,true,this._changeAddresses))}getNextChangeAddressSync(account,zone){return this._getNextAddress(account,zone,true,this._changeAddresses)}importOutpoints(outpoints){this.validateOutpointInfo(outpoints);this._outpoints.push(...outpoints)}getOutpoints(zone){this.validateZone(zone);return this._outpoints.filter(outpoint=>outpoint.zone===zone)}async signTransaction(tx){const txobj=QiTransaction.from(tx);if(!txobj.txInputs||txobj.txInputs.length==0||!txobj.txOutputs)throw new Error("Invalid UTXO transaction, missing inputs or outputs");const hash=keccak_256(txobj.unsignedSerialized);let signature;if(txobj.txInputs.length==1){signature=this.createSchnorrSignature(txobj.txInputs[0],hash)}else{signature=this.createMuSigSignature(txobj,hash)}txobj.signature=signature;return txobj.serialized}async sendTransaction(tx){if(!this.provider){throw new Error("Provider is not set")}if(!tx.txInputs||tx.txInputs.length===0){throw new Error("Transaction has no inputs")}const input=tx.txInputs[0];const address=computeAddress(input.pubkey);const shard=getZoneForAddress(address);if(!shard){throw new Error(`Address ${address} not found in any shard`)}if(tx.txInputs.some(input=>getZoneForAddress(computeAddress(input.pubkey))!==shard)){throw new Error("All inputs must be from the same shard")}const signedTx=await this.signTransaction(tx);return await this.provider.broadcastTransaction(shard,signedTx)}createSchnorrSignature(input,hash){const privKey=this.getPrivateKeyForTxInput(input);const signature=schnorr.sign(hash,getBytes(privKey));return hexlify(signature)}createMuSigSignature(tx,hash){const musig=MuSigFactory(musigCrypto);const privKeysSet=new Set;tx.txInputs.forEach(input=>{const privKey=this.getPrivateKeyForTxInput(input);privKeysSet.add(privKey)});const privKeys=Array.from(privKeysSet);const pubKeys=privKeys.map(privKey=>musigCrypto.getPublicKey(getBytes(privKey),true)).filter(pubKey=>pubKey!==null);const nonces=pubKeys.map(pk=>musig.nonceGen({publicKey:getBytes(pk)}));const aggNonce=musig.nonceAgg(nonces);const signingSession=musig.startSigningSession(aggNonce,hash,pubKeys);const partialSignatures=privKeys.map((sk,index)=>musig.partialSign({secretKey:getBytes(sk||""),publicNonce:nonces[index],sessionKey:signingSession,verify:true}));const finalSignature=musig.signAgg(partialSignatures,signingSession);return hexlify(finalSignature)}getPrivateKeyForTxInput(input){if(!input.pubkey)throw new Error("Missing public key for input");const address=computeAddress(input.pubkey);const addressInfo=this.getAddressInfo(address);if(!addressInfo)throw new Error(`Address not found: ${address}`);const changeIndex=addressInfo.change?1:0;const addressNode=this._root.deriveChild(addressInfo.account).deriveChild(changeIndex).deriveChild(addressInfo.index);return addressNode.privateKey}async scan(zone,account=0){this.validateZone(zone);this._addresses=new Map;this._changeAddresses=new Map;this._gapAddresses=[];this._gapChangeAddresses=[];this._outpoints=[];await this._scan(zone,account)}async sync(zone,account){this.validateZone(zone);if(account===undefined){const addressInfos=Array.from(this._addresses.values());const accounts=addressInfos.reduce((unique,info)=>{if(!unique.includes(info.account)){unique.push(info.account)}return unique},[]);for(const acc of accounts){await this._scan(zone,acc)}}else{await this._scan(zone,account)}return}async _scan(zone,account=0){if(!this.provider)throw new Error("Provider not set");let gapAddressesCount=0;let changeGapAddressesCount=0;while(gapAddressesCount0){this.importOutpoints(outpoints.map(outpoint=>({outpoint:outpoint,address:addressInfo.address,zone:zone,account:account})));addressesCount=0;isChange?this._gapChangeAddresses=[]:this._gapAddresses=[]}else{addressesCount++;isChange?this._gapChangeAddresses.push(addressInfo):this._gapAddresses.push(addressInfo)}return addressesCount}async getOutpointsByAddress(address){try{const outpointsMap=await this.provider.getOutpointsByAddress(address);if(!outpointsMap){return[]}return Object.values(outpointsMap)}catch(error){throw new Error(`Failed to get outpoints for address: ${address} - error: ${error}`)}}getChangeAddressesForZone(zone){this.validateZone(zone);const changeAddresses=this._changeAddresses.values();return Array.from(changeAddresses).filter(addressInfo=>addressInfo.zone===zone)}getGapAddressesForZone(zone){this.validateZone(zone);const gapAddresses=this._gapAddresses.filter(addressInfo=>addressInfo.zone===zone);return gapAddresses}getGapChangeAddressesForZone(zone){this.validateZone(zone);const gapChangeAddresses=this._gapChangeAddresses.filter(addressInfo=>addressInfo.zone===zone);return gapChangeAddresses}async signMessage(address,message){const addrNode=this._getHDNodeForAddress(address);const privKey=addrNode.privateKey;const digest=keccak_256(message);const signature=schnorr.sign(digest,getBytes(privKey));return hexlify(signature)}serialize(){const hdwalletSerialized=super.serialize();return{outpoints:this._outpoints,changeAddresses:Array.from(this._changeAddresses.values()),gapAddresses:this._gapAddresses,gapChangeAddresses:this._gapChangeAddresses,...hdwalletSerialized}}static async deserialize(serialized){super.validateSerializedWallet(serialized);const mnemonic=Mnemonic.fromPhrase(serialized.phrase);const path=this.parentPath(serialized.coinType);const root=HDNodeWallet.fromMnemonic(mnemonic,path);const wallet=new this(_guard,root);wallet.importSerializedAddresses(wallet._addresses,serialized.addresses);wallet.importSerializedAddresses(wallet._changeAddresses,serialized.changeAddresses);for(const gapAddressInfo of serialized.gapAddresses){const gapAddress=gapAddressInfo.address;if(!wallet._addresses.has(gapAddress)){throw new Error(`Address ${gapAddress} not found in wallet`)}wallet._gapAddresses.push(gapAddressInfo)}for(const gapChangeAddressInfo of serialized.gapChangeAddresses){const gapChangeAddress=gapChangeAddressInfo.address;if(!wallet._changeAddresses.has(gapChangeAddress)){throw new Error(`Address ${gapChangeAddress} not found in wallet`)}wallet._gapChangeAddresses.push(gapChangeAddressInfo)}wallet.validateOutpointInfo(serialized.outpoints);wallet._outpoints.push(...serialized.outpoints);return wallet}validateOutpointInfo(outpointInfo){outpointInfo.forEach(info=>{this.validateZone(info.zone);const addressInfo=this.getAddressInfo(info.address);if(!addressInfo){throw new Error(`Address ${info.address} not found in wallet`)}if(info.account!==undefined&&info.account!==addressInfo.account){throw new Error(`Account ${info.account} not found for address ${info.address}`)}if(info.outpoint.txhash==null||info.outpoint.index==null||info.outpoint.denomination==null){throw new Error(`Invalid Outpoint: ${JSON.stringify(info)} `)}})}}const Networks=new Map;class Network{#name;#chainId;constructor(name,chainId){this.#name=name;this.#chainId=getBigInt(chainId)}toJSON(){return{name:this.name,chainId:String(this.chainId)}}get name(){return this.#name}set name(value){this.#name=value}get chainId(){return this.#chainId}set chainId(value){this.#chainId=getBigInt(value,"chainId")}matches(other){if(other==null){return false}if(typeof other==="string"){try{return this.chainId===getBigInt(other)}catch(error){}return this.name===other}if(typeof other==="number"||typeof other==="bigint"){try{return this.chainId===getBigInt(other)}catch(error){}return false}if(typeof other==="object"){if(other.chainId!=null){try{return this.chainId===getBigInt(other.chainId)}catch(error){}return false}if(other.name!=null){return this.name===other.name}return false}return false}clone(){const clone=new Network(this.name,this.chainId);return clone}static from(network){if(network==null){return Network.from("mainnet")}if(typeof network==="number"){network=BigInt(network)}if(typeof network==="string"||typeof network==="bigint"){const networkFunc=Networks.get(network);if(networkFunc){return networkFunc()}if(typeof network==="bigint"){return new Network("unknown",network)}assertArgument(false,"unknown network","network",network)}if(typeof network.clone==="function"){const clone=network.clone();return clone}if(typeof network==="object"){assertArgument(typeof network.name==="string"&&typeof network.chainId==="number","invalid network object name or chainId","network",network);const custom=new Network(network.name,network.chainId);return custom}assertArgument(false,"invalid network","network",network)}static register(nameOrChainId,networkFunc){if(typeof nameOrChainId==="number"){nameOrChainId=BigInt(nameOrChainId)}const existing=Networks.get(nameOrChainId);if(existing){assertArgument(false,`conflicting network for ${JSON.stringify(existing.name)}`,"nameOrChainId",nameOrChainId)}Networks.set(nameOrChainId,networkFunc)}}function copy$2(obj){return JSON.parse(JSON.stringify(obj))}class PollingBlockSubscriber{#provider;#poller;#interval;#zone;#blockNumber;constructor(provider,zone){this.#provider=provider;this.#zone=zone;this.#poller=null;this.#interval=4e3;this.#blockNumber=-2}get pollingInterval(){return this.#interval}set pollingInterval(value){this.#interval=value}async#poll(){try{const blockNumber=await this.#provider.getBlockNumber(toShard(this.#zone));if(this.#blockNumber===-2){this.#blockNumber=blockNumber;return}if(blockNumber!==this.#blockNumber){for(let b=this.#blockNumber+1;b<=blockNumber;b++){if(this.#poller==null){return}await this.#provider.emit("block",this.#zone,b)}this.#blockNumber=blockNumber}}catch(error){}if(this.#poller==null){return}this.#poller=this.#provider._setTimeout(this.#poll.bind(this),this.#interval)}start(){if(this.#poller){return}this.#poller=this.#provider._setTimeout(this.#poll.bind(this),this.#interval);this.#poll()}stop(){if(!this.#poller){return}this.#provider._clearTimeout(this.#poller);this.#poller=null}pause(dropWhilePaused){this.stop();if(dropWhilePaused){this.#blockNumber=-2}}resume(){this.start()}}class OnBlockSubscriber{#provider;#poll;#running;#zone;constructor(provider,zone){this.#provider=provider;this.#zone=zone;this.#running=false;this.#poll=blockNumber=>{this._poll(blockNumber,this.#provider)}}async _poll(blockNumber,provider){throw new Error("sub-classes must override this")}start(){if(this.#running){return}this.#running=true;this.#poll(-2);this.#provider.on("block",this.#poll,this.#zone)}stop(){if(!this.#running){return}this.#running=false;this.#provider.off("block",this.#poll,this.#zone)}pause(dropWhilePaused){this.stop()}resume(){this.start()}}class PollingOrphanSubscriber extends OnBlockSubscriber{#filter;constructor(provider,filter,zone){super(provider,zone);this.#filter=copy$2(filter)}async _poll(blockNumber,provider){throw new Error("@TODO")}}class PollingTransactionSubscriber extends OnBlockSubscriber{#hash;constructor(provider,hash,zone){super(provider,zone);this.#hash=hash}async _poll(blockNumber,provider){const tx=await provider.getTransactionReceipt(this.#hash);if(tx){provider.emit(this.#hash,toZone(this.#hash.slice(0,4)),tx)}}}class PollingEventSubscriber{#provider;#filter;#poller;#running;#blockNumber;#zone;constructor(provider,filter){this.#provider=provider;this.#filter=copy$2(filter);this.#poller=this.#poll.bind(this);this.#running=false;this.#blockNumber=-2;const zone=getZoneFromEventFilter(this.#filter);if(zone){this.#zone=zone}else{throw new Error("Unable to determine zone for event filter")}}async#poll(blockNumber){if(this.#blockNumber===-2){return}const filter=copy$2(this.#filter);filter.fromBlock=this.#blockNumber+1;filter.toBlock=blockNumber;const logs=await this.#provider.getLogs(filter);if(logs.length===0){if(this.#blockNumber{this.#blockNumber=blockNumber})}this.#provider.on("block",this.#poller,this.#zone)}stop(){if(!this.#running){return}this.#running=false;this.#provider.off("block",this.#poller,this.#zone)}pause(dropWhilePaused){this.stop();if(dropWhilePaused){this.#blockNumber=-2}}resume(){this.start()}}const BN_2=BigInt(2);function isPromise(value){return value&&typeof value.then==="function"}function getTag(prefix,value){return prefix+":"+JSON.stringify(value,(k,v)=>{if(v==null){return"null"}if(typeof v==="bigint"){return`bigint:${v.toString()}`}if(typeof v==="string"){return v.toLowerCase()}if(typeof v==="object"&&!Array.isArray(v)){const keys=Object.keys(v);keys.sort();return keys.reduce((accum,key)=>{accum[key]=v[key];return accum},{})}return v})}class UnmanagedSubscriber{name;constructor(name){defineProperties(this,{name:name})}start(){}stop(){}pause(dropWhilePaused){}resume(){}}function copy$1(value){return JSON.parse(JSON.stringify(value))}function concisify(items){items=Array.from(new Set(items).values());items.sort();return items}async function getSubscription(_event,zone){if(_event==null){throw new Error("invalid event")}if(Array.isArray(_event)){_event={topics:_event}}if(typeof _event==="string"){if(_event==="debug"){return{type:_event,tag:_event}}switch(_event){case"block":case"pending":if(!zone){throw new Error("zone is required for block and pending events")}return{type:"block",tag:_event,zone:zone};case"error":case"finalized":case"network":case"safe":{return{type:_event,tag:_event}}}}if(isHexString(_event,32)){const hash=_event.toLowerCase();zone=toZone(hash.slice(0,4));return{type:"transaction",tag:getTag("tx",{hash:hash}),hash:hash,zone:zone}}if(_event.orphan){const event=_event;if(!zone){const hash=event.hash||event.tx.hash||event.other?.hash||event.log.transactionHash||null;if(hash==null){throw new Error("orphan event must specify a hash")}zone=toZone(hash.slice(0,4))}return{type:"orphan",tag:getTag("orphan",event),filter:copy$1(event),zone:zone}}if(_event.address||_event.topics){const event=_event;const filter={topics:(event.topics||[]).map(t=>{if(t==null){return null}if(Array.isArray(t)){return concisify(t.map(t=>t.toLowerCase()))}return t.toLowerCase()})};if(event.nodeLocation){filter.nodeLocation=event.nodeLocation}if(event.address){const addresses=[];const promises=[];const addAddress=addr=>{if(isHexString(addr)){addresses.push(formatMixedCaseChecksumAddress(addr))}else{promises.push((async()=>{addresses.push(formatMixedCaseChecksumAddress(await resolveAddress(addr)))})())}};if(Array.isArray(event.address)){event.address.forEach(addAddress)}else{addAddress(event.address)}if(promises.length){await Promise.all(promises)}if(!zone){zone=toZone(addresses[0].slice(0,4))}filter.address=concisify(addresses.map(a=>a.toLowerCase()));if(!filter.nodeLocation){filter.nodeLocation=getNodeLocationFromZone(zone)}}else{if(!zone){throw new Error("zone is required for event")}}return{filter:filter,tag:getTag("event",filter),type:"event",zone:zone}}assertArgument(false,"unknown ProviderEvent","event",_event)}function getTime(){return(new Date).getTime()}const defaultOptions$1={cacheTimeout:250,pollingInterval:4e3,usePathing:false};class AbstractProvider{_urlMap;#connect;#subs;#pausedState;#destroyed;#networkPromise;#anyNetwork;#performCache;#lastBlockNumber;#nextTimer;#timers;#options;_initFailed;initResolvePromise;initRejectPromise;initPromise;constructor(_network,options){this._initFailed=false;this.#options=Object.assign({},defaultOptions$1,options||{});if(_network==="any"){this.#anyNetwork=true;this.#networkPromise=null}else if(_network){const network=Network.from(_network);this.#anyNetwork=false;this.#networkPromise=Promise.resolve(network);setTimeout(()=>{this.emit("network",undefined,network,null)},0)}else{this.#anyNetwork=false;this.#networkPromise=null}this.#lastBlockNumber=-1;this.#performCache=new Map;this.#subs=new Map;this.#pausedState=null;this.#destroyed=false;this.#nextTimer=1;this.#timers=new Map;this.#connect=[];this._urlMap=new Map;this.initResolvePromise=null;this.initRejectPromise=null;this.initPromise=new Promise((resolve,reject)=>{this.initResolvePromise=resolve;this.initRejectPromise=reject})}async initialize(urls){try{const primeSuffix=this.#options.usePathing?`/${fromShard(exports.Shard.Prime,"nickname")}`:":9001";if(urls instanceof FetchRequest){urls.url=urls.url.split(":")[0]+":"+urls.url.split(":")[1]+primeSuffix;this._urlMap.set(exports.Shard.Prime,urls);this.#connect.push(urls);const shards=await this.getRunningLocations();shards.forEach(shard=>{const port=9200+20*shard[0]+shard[1];const shardEnum=toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);const shardSuffix=this.#options.usePathing?`/${fromShard(shardEnum,"nickname")}`:`:${port}`;this._urlMap.set(shardEnum,new FetchRequest(urls.url.split(":")[0]+":"+urls.url.split(":")[1]+shardSuffix))});return}if(Array.isArray(urls)){for(const url of urls){const primeUrl=url.split(":")[0]+":"+url.split(":")[1]+primeSuffix;const primeConnect=new FetchRequest(primeUrl);this._urlMap.set(exports.Shard.Prime,primeConnect);this.#connect.push(primeConnect);const shards=await this.getRunningLocations();shards.forEach(shard=>{const port=9200+20*shard[0]+shard[1];const shardEnum=toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);const shardSuffix=this.#options.usePathing?`/${fromShard(shardEnum,"nickname")}`:`:${port}`;this._urlMap.set(toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`),new FetchRequest(url.split(":")[0]+":"+url.split(":")[1]+shardSuffix))})}}if(this.initResolvePromise)this.initResolvePromise()}catch(error){this._initFailed=true;console.log("Error initializing URL map:",error);if(this.initRejectPromise)this.initRejectPromise(error)}}get connect(){return this.#connect}async zoneFromAddress(_address){const address=this._getAddress(_address);return toZone((await address).slice(0,4))}shardFromHash(hash){return toShard(hash.slice(0,4))}zoneFromHash(hash){return toZone(hash.slice(0,4))}async getLatestQuaiRate(zone,amt=1){const blockNumber=await this.getBlockNumber(toShard(zone));return this.getQuaiRateAtBlock(zone,blockNumber,amt)}async getQuaiRateAtBlock(zone,blockTag,amt=1){let resolvedBlockTag=this._getBlockTag(toShard(zone),blockTag);if(typeof resolvedBlockTag!=="string"){resolvedBlockTag=await resolvedBlockTag}return await this.#perform({method:"getQuaiRateAtBlock",blockTag:resolvedBlockTag,amt:amt,zone:zone})}async getProtocolExpansionNumber(){return await this.#perform({method:"getProtocolExpansionNumber"})}async getLatestQiRate(zone,amt=1){const blockNumber=await this.getBlockNumber(toShard(zone));return this.getQiRateAtBlock(zone,blockNumber,amt)}async getQiRateAtBlock(zone,blockTag,amt=1){let resolvedBlockTag=this._getBlockTag(toShard(zone),blockTag);if(typeof resolvedBlockTag!=="string"){resolvedBlockTag=await resolvedBlockTag}return await this.#perform({method:"getQiRateAtBlock",blockTag:resolvedBlockTag,amt:amt,zone:zone})}get pollingInterval(){return this.#options.pollingInterval}get provider(){return this}async#perform(req){const timeout=this.#options.cacheTimeout;if(timeout<0){return await this._perform(req)}const tag=getTag(req.method,req);let perform=this.#performCache.get(tag);if(!perform||tag.includes("pending")||tag.includes("latest")){perform=this._perform(req);this.#performCache.set(tag,perform);setTimeout(()=>{if(this.#performCache.get(tag)===perform){this.#performCache.delete(tag)}},timeout)}return await perform}_wrapBlock(value,network){value.header.number=Array.isArray(value.header.number)?value.header.number.filter(n=>n!=null):value.header.number;return new Block(formatBlock(value),this)}_wrapLog(value,network){return new Log(formatLog(value),this)}_wrapTransactionReceipt(value,network){const formattedReceipt=formatTransactionReceipt(value);return new TransactionReceipt(formattedReceipt,this)}_wrapTransactionResponse(tx,network){if("from"in tx){return new QuaiTransactionResponse(formatTransactionResponse(tx),this)}else{return new QiTransactionResponse(formatTransactionResponse(tx),this)}}_detectNetwork(){assert(false,"sub-classes must implement this","UNSUPPORTED_OPERATION",{operation:"_detectNetwork"})}async _perform(req){assert(false,`unsupported method: ${req.method}`,"UNSUPPORTED_OPERATION",{operation:req.method,info:req})}async getBlockNumber(shard){const blockNumber=getNumber(await this.#perform({method:"getBlockNumber",shard:shard}),"%response");if(this.#lastBlockNumber>=0){this.#lastBlockNumber=blockNumber}return blockNumber}_getAddress(address){return resolveAddress(address)}_getBlockTag(shard,blockTag){if(blockTag==null){return"latest"}switch(blockTag){case"earliest":return"0x0";case"finalized":case"latest":case"pending":case"safe":return blockTag}if(isHexString(blockTag)){if(isHexString(blockTag,32)){return blockTag}return toQuantity(blockTag)}if(typeof blockTag==="bigint"){blockTag=getNumber(blockTag,"blockTag")}if(typeof blockTag==="number"){if(blockTag>=0){return toQuantity(blockTag)}if(this.#lastBlockNumber>=0){return toQuantity(this.#lastBlockNumber+blockTag)}return this.getBlockNumber(shard).then(b=>toQuantity(b+blockTag))}assertArgument(false,"invalid blockTag","blockTag",blockTag)}_getFilter(filter){const topics=(filter.topics||[]).map(t=>{if(t==null){return null}if(Array.isArray(t)){return concisify(t.map(t=>t.toLowerCase()))}return t.toLowerCase()});const blockHash="blockHash"in filter?filter.blockHash:undefined;const resolve=(_address,fromBlock,toBlock,nodeLocation)=>{let address=undefined;switch(_address.length){case 0:break;case 1:address=_address[0];break;default:_address.sort();address=_address}if(blockHash){if(fromBlock!=null||toBlock!=null){throw new Error("invalid filter")}}const filter={};if(address){filter.address=address}if(topics.length){filter.topics=topics}if(fromBlock){filter.fromBlock=fromBlock}if(toBlock){filter.toBlock=toBlock}if(blockHash){filter.blockHash=blockHash}if(nodeLocation){filter.nodeLocation=nodeLocation}return filter};const address=[];if(filter.address){if(Array.isArray(filter.address)){for(const addr of filter.address){address.push(this._getAddress(addr))}}else{address.push(this._getAddress(filter.address))}}const zone=getZoneFromNodeLocation(filter.nodeLocation);let fromBlock=undefined;if("fromBlock"in filter){fromBlock=this._getBlockTag(toShard(zone),filter.fromBlock)}let toBlock=undefined;if("toBlock"in filter){toBlock=this._getBlockTag(toShard(zone),filter.toBlock)}let nodeLocation=undefined;if(filter.nodeLocation){nodeLocation=filter.nodeLocation}if(address.filter(a=>typeof a!=="string").length||fromBlock!=null&&typeof fromBlock!=="string"||toBlock!=null&&typeof toBlock!=="string"){return Promise.all([Promise.all(address),fromBlock,toBlock,nodeLocation]).then(result=>{return resolve(result[0],result[1],result[2],result[3])})}return resolve(address,fromBlock,toBlock,nodeLocation)}_getTransactionRequest(_request){const request=copyRequest(_request);const promises=[];["to","from","inputs","outputs"].forEach(key=>{if(request[key]==null){return}const addr=Array.isArray(request[key])?"address"in request[key][0]?request[key].map(it=>it.address):request[key].map(it=>computeAddress(it.pubkey)):resolveAddress(request[key]);if(isPromise(addr)){if(Array.isArray(addr)){for(let i=0;i{try{const network=await this._detectNetwork();this.emit("network",undefined,network,null);return network}catch(error){if(this.#networkPromise===detectNetwork){this.#networkPromise=null}throw error}})();this.#networkPromise=detectNetwork;return(await detectNetwork).clone()}const networkPromise=this.#networkPromise;const[expected,actual]=await Promise.all([networkPromise,this._detectNetwork()]);if(expected.chainId!==actual.chainId){if(this.#anyNetwork){this.emit("network",undefined,actual,expected);if(this.#networkPromise===networkPromise){this.#networkPromise=Promise.resolve(actual)}}else{assert(false,`network changed: ${expected.chainId} => ${actual.chainId} `,"NETWORK_ERROR",{event:"changed"})}}return expected.clone()}async _getRunningLocations(shard,now){now=now?now:false;return await this.#perform(shard?{method:"getRunningLocations",shard:shard,now:now}:{method:"getRunningLocations",now:now})}async getRunningLocations(shard){return await this._getRunningLocations(shard)}async getProtocolTrieExpansionCount(shard){return await this.#perform({method:"getProtocolTrieExpansionCount",shard:shard})}async getFeeData(zone,txType=true){const getFeeDataFunc=async()=>{const{gasPrice,priorityFee}=await resolveProperties({gasPrice:(async()=>{try{const value=await this.#perform({method:"getGasPrice",txType:txType,zone:zone});return getBigInt(value,"%response")}catch(error){console.log(error)}return null})(),priorityFee:(async()=>{try{const value=txType?await this.#perform({method:"getMaxPriorityFeePerGas",zone:zone}):0;return getBigInt(value,"%response")}catch(error){}return null})()});if(gasPrice==null){throw new Error("could not determine gasPrice")}let maxFeePerGas=null;let maxPriorityFeePerGas=null;maxPriorityFeePerGas=priorityFee!=null?priorityFee:BigInt("1000000000");maxFeePerGas=gasPrice*BN_2+maxPriorityFeePerGas;return new FeeData(gasPrice,maxFeePerGas,maxPriorityFeePerGas)};return await getFeeDataFunc()}async estimateGas(_tx){let tx=this._getTransactionRequest(_tx);if(isPromise(tx)){tx=await tx}const zone=await this.zoneFromAddress(addressFromTransactionRequest(tx));return getBigInt(await this.#perform({method:"estimateGas",transaction:tx,zone:zone}),"%response")}async#call(tx,blockTag,attempt,zone){const transaction=copyRequest(tx);return hexlify(await this._perform({method:"call",transaction:transaction,blockTag:blockTag,zone:zone}))}async#checkNetwork(promise,shard){const{value}=await resolveProperties({network:this.getNetwork(),value:promise});return value}async call(_tx){const zone=await this.zoneFromAddress(addressFromTransactionRequest(_tx));const shard=toShard(zone);const{tx,blockTag}=await resolveProperties({tx:this._getTransactionRequest(_tx),blockTag:this._getBlockTag(shard,_tx.blockTag)});return await this.#checkNetwork(this.#call(tx,blockTag,-1,zone),shard)}async#getAccountValue(request,_address,_blockTag){let address=this._getAddress(_address);const zone=await this.zoneFromAddress(_address);const shard=toShard(zone);let blockTag=this._getBlockTag(shard,_blockTag);if(typeof address!=="string"||typeof blockTag!=="string"){[address,blockTag]=await Promise.all([address,blockTag])}return await this.#checkNetwork(this.#perform(Object.assign(request,{address:address,blockTag:blockTag,zone:zone})),shard)}async getBalance(address,blockTag){return getBigInt(await this.#getAccountValue({method:"getBalance"},address,blockTag),"%response")}async getOutpointsByAddress(address){const outpoints=await this.#getAccountValue({method:"getOutpointsByAddress"},address,"latest");const outpointsArray=Array.isArray(outpoints)?outpoints:[];return outpointsArray.map(outpoint=>({txhash:outpoint.Txhash,index:outpoint.Index,denomination:outpoint.Denomination}))}async getTransactionCount(address,blockTag){return getNumber(await this.#getAccountValue({method:"getTransactionCount"},address,blockTag),"%response")}async getCode(address,blockTag){return hexlify(await this.#getAccountValue({method:"getCode"},address,blockTag))}async getStorage(address,_position,blockTag){const position=getBigInt(_position,"position");return hexlify(await this.#getAccountValue({method:"getStorage",position:position},address,blockTag))}async getPendingHeader(){return await this.#perform({method:"getPendingHeader"})}async getTxPoolContent(zone){return await this.#perform({method:"getTxPoolContent",zone:zone})}async txPoolInspect(zone){return await this.#perform({method:"txPoolInspect",zone:zone})}async broadcastTransaction(zone,signedTx){const type=decodeProtoTransaction(getBytes(signedTx)).type;const{blockNumber,hash,network}=await resolveProperties({blockNumber:this.getBlockNumber(toShard(zone)),hash:this._perform({method:"broadcastTransaction",signedTransaction:signedTx,zone:zone}),network:this.getNetwork()});const tx=type==2?QiTransaction.from(signedTx):QuaiTransaction.from(signedTx);this.#validateTransactionHash(tx.hash||"",hash);return this._wrapTransactionResponse(tx,network).replaceableTransaction(blockNumber)}#validateTransactionHash(computedHash,nodehash){if(computedHash!==nodehash){throw new Error("Transaction hash mismatch")}}validateUrl(url){const urlPattern=/^(https?):\/\/[a-zA-Z0-9.-]+(:\d+)?$/;if(!urlPattern.test(url)){let errorMessage="Invalid URL: ";if(!/^https?:\/\//.test(url)){errorMessage+="URL must start with http:// or https://. "}if(url.endsWith("/")){errorMessage+="URL should not end with a /. "}if(/\/[^/]+/.test(url)){errorMessage+="URL should not contain a path, query string, or fragment. "}throw new Error(errorMessage.trim())}}async#getBlock(shard,block,includeTransactions){if(isHexString(block,32)){return await this.#perform({method:"getBlock",blockHash:block,includeTransactions:includeTransactions,shard:shard})}let blockTag=this._getBlockTag(shard,block);if(typeof blockTag!=="string"){blockTag=await blockTag}return await this.#perform({method:"getBlock",blockTag:blockTag,includeTransactions:includeTransactions,shard:shard})}async getBlock(shard,block,prefetchTxs){const{network,params}=await resolveProperties({network:this.getNetwork(),params:this.#getBlock(shard,block,!!prefetchTxs)});if(params==null){return null}return this._wrapBlock(params,network)}async getTransaction(hash){const zone=toZone(this.shardFromHash(hash));const{network,params}=await resolveProperties({network:this.getNetwork(),params:this.#perform({method:"getTransaction",hash:hash,zone:zone})});if(params==null){return null}return this._wrapTransactionResponse(params,network)}async getTransactionReceipt(hash){const zone=toZone(this.shardFromHash(hash));const{network,params}=await resolveProperties({network:this.getNetwork(),params:this.#perform({method:"getTransactionReceipt",hash:hash,zone:zone})});if(params==null){return null}if(params.gasPrice==null&¶ms.effectiveGasPrice==null){const tx=await this.#perform({method:"getTransaction",hash:hash,zone:zone});if(tx==null){throw new Error("report this; could not find tx or effectiveGasPrice")}params.effectiveGasPrice=tx.gasPrice}return this._wrapTransactionReceipt(params,network)}async getTransactionResult(hash){const zone=toZone(this.shardFromHash(hash));const{result}=await resolveProperties({network:this.getNetwork(),result:this.#perform({method:"getTransactionResult",hash:hash,zone:zone})});if(result==null){return null}return hexlify(result)}async getLogs(_filter){let filter=this._getFilter(_filter);if(isPromise(filter)){filter=await filter}const{network,params}=await resolveProperties({network:this.getNetwork(),params:this.#perform({method:"getLogs",filter:filter,zone:getZoneFromNodeLocation(filter.nodeLocation)})});return params.map(p=>this._wrapLog(p,network))}_getProvider(chainId){assert(false,"provider cannot connect to target network","UNSUPPORTED_OPERATION",{operation:"_getProvider()"})}async waitForTransaction(hash,_confirms,timeout){const zone=this.zoneFromHash(hash);const confirms=_confirms!=null?_confirms:1;if(confirms===0){return this.getTransactionReceipt(hash)}return new Promise(async(resolve,reject)=>{let timer=null;const listener=async blockNumber=>{try{const receipt=await this.getTransactionReceipt(hash);if(receipt!=null){if(blockNumber-receipt.blockNumber+1>=confirms){resolve(receipt);if(timer){clearTimeout(timer);timer=null}return}}}catch(error){console.log("Error occured while waiting for transaction:",error)}this.once("block",listener,zone)};if(timeout!=null){timer=setTimeout(()=>{if(timer==null){return}timer=null;this.off("block",listener,zone);reject(makeError("timeout","TIMEOUT",{reason:"timeout"}))},timeout)}listener(await this.getBlockNumber(toShard(zone)))})}async waitForBlock(shard,blockTag){assert(false,"not implemented yet","NOT_IMPLEMENTED",{operation:"waitForBlock"})}_clearTimeout(timerId){const timer=this.#timers.get(timerId);if(!timer){return}if(timer.timer){clearTimeout(timer.timer)}this.#timers.delete(timerId)}_setTimeout(_func,timeout){if(timeout==null){timeout=0}const timerId=this.#nextTimer++;const func=()=>{this.#timers.delete(timerId);_func()};if(this.paused){this.#timers.set(timerId,{timer:null,func:func,time:timeout})}else{const timer=setTimeout(func,timeout);this.#timers.set(timerId,{timer:timer,func:func,time:getTime()})}return timerId}_forEachSubscriber(func){for(const sub of this.#subs.values()){func(sub.subscriber)}}_getSubscriber(sub){switch(sub.type){case"debug":case"error":case"network":return new UnmanagedSubscriber(sub.type);case"block":{const subscriber=new PollingBlockSubscriber(this,sub.zone);subscriber.pollingInterval=this.pollingInterval;return subscriber}case"event":return new PollingEventSubscriber(this,sub.filter);case"transaction":return new PollingTransactionSubscriber(this,sub.hash,sub.zone);case"orphan":return new PollingOrphanSubscriber(this,sub.filter,sub.zone)}throw new Error(`unsupported event: ${sub.type}`)}_recoverSubscriber(oldSub,newSub){for(const sub of this.#subs.values()){if(sub.subscriber===oldSub){if(sub.started){sub.subscriber.stop()}sub.subscriber=newSub;if(sub.started){newSub.start()}if(this.#pausedState!=null){newSub.pause(this.#pausedState)}break}}}async#hasSub(event,emitArgs,zone){let sub=await getSubscription(event,zone);if(sub.type==="event"&&emitArgs&&emitArgs.length>0&&emitArgs[0].removed===true){sub=await getSubscription({orphan:"drop-log",log:emitArgs[0]},zone)}return this.#subs.get(sub.tag)||null}async#getSub(event,zone){const subscription=await getSubscription(event,zone);const tag=subscription.tag;let sub=this.#subs.get(tag);if(!sub){const subscriber=this._getSubscriber(subscription);const addressableMap=new WeakMap;const nameMap=new Map;sub={subscriber:subscriber,tag:tag,addressableMap:addressableMap,nameMap:nameMap,started:false,listeners:[],zone:subscription.zone};this.#subs.set(tag,sub)}return sub}async on(event,listener,zone){const sub=await this.#getSub(event,zone);sub.listeners.push({listener:listener,once:false});if(!sub.started){sub.subscriber.start();sub.started=true;if(this.#pausedState!=null){sub.subscriber.pause(this.#pausedState)}}return this}async once(event,listener,zone){const sub=await this.#getSub(event,zone);sub.listeners.push({listener:listener,once:true});if(!sub.started){sub.subscriber.start();sub.started=true;if(this.#pausedState!=null){sub.subscriber.pause(this.#pausedState)}}return this}async emit(event,zone,...args){const sub=await this.#hasSub(event,args,zone);if(!sub||sub.listeners.length===0){return false}const count=sub.listeners.length;sub.listeners=sub.listeners.filter(({listener,once})=>{const payload=new EventPayload(this,once?null:listener,event);try{listener.call(this,...args,payload)}catch(error){}return!once});if(sub.listeners.length===0){if(sub.started){sub.subscriber.stop()}this.#subs.delete(sub.tag)}return count>0}async listenerCount(event){if(event){const sub=await this.#hasSub(event);if(!sub){return 0}return sub.listeners.length}let total=0;for(const{listeners}of this.#subs.values()){total+=listeners.length}return total}async listeners(event){if(event){const sub=await this.#hasSub(event);if(!sub){return[]}return sub.listeners.map(({listener})=>listener)}let result=[];for(const{listeners}of this.#subs.values()){result=result.concat(listeners.map(({listener})=>listener))}return result}async off(event,listener,zone){const sub=await this.#hasSub(event,[],zone);if(!sub){return this}if(listener){const index=sub.listeners.map(({listener})=>listener).indexOf(listener);if(index>=0){sub.listeners.splice(index,1)}}if(!listener||sub.listeners.length===0){if(sub.started){sub.subscriber.stop()}this.#subs.delete(sub.tag)}return this}async removeAllListeners(event){if(event){const{tag,started,subscriber}=await this.#getSub(event);if(started){subscriber.stop()}this.#subs.delete(tag)}else{for(const[tag,{started,subscriber}]of this.#subs){if(started){subscriber.stop()}this.#subs.delete(tag)}}return this}async addListener(event,listener,zone){return await this.on(event,listener,zone)}async removeListener(event,listener,zone){return this.off(event,listener,zone)}get destroyed(){return this.#destroyed}destroy(){this.removeAllListeners();for(const timerId of this.#timers.keys()){this._clearTimeout(timerId)}this.#destroyed=true}get paused(){return this.#pausedState!=null}set paused(pause){if(!!pause===this.paused){return}if(this.paused){this.resume()}else{this.pause(false)}}pause(dropWhilePaused){this.#lastBlockNumber=-1;if(this.#pausedState!=null){if(this.#pausedState==!!dropWhilePaused){return}assert(false,"cannot change pause type; resume first","UNSUPPORTED_OPERATION",{operation:"pause"})}this._forEachSubscriber(s=>s.pause(dropWhilePaused));this.#pausedState=!!dropWhilePaused;for(const timer of this.#timers.values()){if(timer.timer){clearTimeout(timer.timer)}timer.time=getTime()-timer.time}}resume(){if(this.#pausedState==null){return}this._forEachSubscriber(s=>s.resume());this.#pausedState=null;for(const timer of this.#timers.values()){let timeout=timer.time;if(timeout<0){timeout=0}timer.time=getTime();setTimeout(timer.func,timeout)}}}function copy(obj){return JSON.parse(JSON.stringify(obj))}class FilterIdSubscriber{#provider;#filterIdPromise;#poller;#running;#network;#hault;zone;constructor(provider,zone){this.#provider=provider;this.#filterIdPromise=null;this.#poller=this.#poll.bind(this);this.#running=false;this.#network=null;this.#hault=false;this.zone=zone}_subscribe(provider){throw new Error("subclasses must override this")}_emitResults(provider,result){throw new Error("subclasses must override this")}_recover(provider){throw new Error("subclasses must override this")}async#poll(blockNumber){try{if(this.#filterIdPromise==null){this.#filterIdPromise=this._subscribe(this.#provider)}let filterId=null;try{filterId=await this.#filterIdPromise}catch(error){if(!isError(error,"UNSUPPORTED_OPERATION")||error.operation!=="quai_newFilter"){throw error}}if(filterId==null){this.#filterIdPromise=null;this.#provider._recoverSubscriber(this,this._recover(this.#provider));return}const network=await this.#provider.getNetwork();if(!this.#network){this.#network=network}if(this.#network.chainId!==network.chainId){throw new Error("chain changed")}if(this.#hault){return}const result=await this.#provider.send("quai_getFilterChanges",[filterId]);await this._emitResults(this.#provider,result)}catch(error){console.log("@TODO",error)}this.#provider.once("block",this.#poller,this.zone)}#teardown(){const filterIdPromise=this.#filterIdPromise;if(filterIdPromise){this.#filterIdPromise=null;filterIdPromise.then(filterId=>{this.#provider.send("quai_uninstallFilter",[filterId])})}}start(){if(this.#running){return}this.#running=true;this.#poll(-2)}stop(){if(!this.#running){return}this.#running=false;this.#hault=true;this.#teardown();this.#provider.off("block",this.#poller,this.zone)}pause(dropWhilePaused){if(dropWhilePaused){this.#teardown()}this.#provider.off("block",this.#poller,this.zone)}resume(){this.start()}}class FilterIdEventSubscriber extends FilterIdSubscriber{#event;constructor(provider,filter){const zone=getZoneFromEventFilter(filter);if(zone==null){throw new Error("Unable to determine zone for event filter")}super(provider,zone);this.#event=copy(filter)}_recover(provider){return new PollingEventSubscriber(provider,this.#event)}async _subscribe(provider){const filterId=await provider.send("quai_newFilter",[this.#event]);return filterId}async _emitResults(provider,results){for(const result of results){provider.emit(this.#event,this.zone,provider._wrapLog(result,provider._network))}}}class FilterIdPendingSubscriber extends FilterIdSubscriber{async _subscribe(provider){return await provider.send("quai_newPendingTransactionFilter",[])}async _emitResults(provider,results){for(const result of results){provider.emit("pending",this.zone,result)}}}const Primitive="bigint,boolean,function,number,string,symbol".split(/,/g);function deepCopy(value){if(value==null||Primitive.indexOf(typeof value)>=0){return value}if(typeof value.getAddress==="function"){return value}if(Array.isArray(value)){return value.map(deepCopy)}if(typeof value==="object"){return Object.keys(value).reduce((accum,key)=>{accum[key]=value[key];return accum},{})}throw new Error(`should not happen: ${value} (${typeof value})`)}function stall(duration){return new Promise(resolve=>{setTimeout(resolve,duration)})}const defaultOptions={staticNetwork:null,batchStallTime:10,batchMaxSize:1<<20,batchMaxCount:100,cacheTimeout:250,usePathing:false};class JsonRpcSigner extends AbstractSigner{address;constructor(provider,address){super(provider);address=getAddress(address);defineProperties(this,{address:address})}connect(provider){assert(false,"cannot reconnect JsonRpcSigner","UNSUPPORTED_OPERATION",{operation:"signer.connect"})}async getAddress(){return this.address}async populateQuaiTransaction(tx){return await this.populateCall(tx)}async sendUncheckedTransaction(_tx){const tx=deepCopy(_tx);const promises=[];if("from"in tx){if(tx.from){const _from=tx.from;promises.push((async()=>{const from=await resolveAddress(_from);assertArgument(from!=null&&from.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",_tx);tx.from=from})())}else{tx.from=this.address}if(tx.gasLimit==null){promises.push((async()=>{tx.gasLimit=await this.provider.estimateGas({...tx,from:this.address})})())}if(tx.to!=null){const _to=tx.to;promises.push((async()=>{tx.to=await resolveAddress(_to)})())}}if(promises.length){await Promise.all(promises)}const hexTx=this.provider.getRpcTransaction(tx);return this.provider.send("quai_sendTransaction",[hexTx])}async sendTransaction(tx){const zone=await this.zoneFromAddress(addressFromTransactionRequest(tx));const blockNumber=await this.provider.getBlockNumber(toShard(zone));const hash=await this.sendUncheckedTransaction(tx);return await new Promise((resolve,reject)=>{const timeouts=[1e3,100];let invalids=0;const checkTx=async()=>{try{const tx=await this.provider.getTransaction(hash);if(tx!=null){resolve(tx.replaceableTransaction(blockNumber));return}}catch(error){if(isError(error,"CANCELLED")||isError(error,"BAD_DATA")||isError(error,"NETWORK_ERROR")||isError(error,"UNSUPPORTED_OPERATION")){if(error.info==null){error.info={}}error.info.sendTransactionHash=hash;reject(error);return}if(isError(error,"INVALID_ARGUMENT")){invalids++;if(error.info==null){error.info={}}error.info.sendTransactionHash=hash;if(invalids>10){reject(error);return}}this.provider.emit("error",zoneFromHash(hash),makeError("failed to fetch transation after sending (will try again)","UNKNOWN_ERROR",{error:error}))}this.provider._setTimeout(()=>{checkTx()},timeouts.pop()||4e3)};checkTx()})}async signTransaction(_tx){const tx=deepCopy(_tx);if("from"in tx){if(tx.from){const from=await resolveAddress(tx.from);assertArgument(from!=null&&from.toLowerCase()===this.address.toLowerCase(),"from address mismatch","transaction",_tx);tx.from=from}else{tx.from=this.address}}else{throw new Error("No QI signing implementation in provider-jsonrpc")}const hexTx=this.provider.getRpcTransaction(tx);return await this.provider.send("quai_signTransaction",[hexTx])}async signMessage(_message){const message=typeof _message==="string"?toUtf8Bytes(_message):_message;return await this.provider.send("personal_sign",[hexlify(message),this.address.toLowerCase()])}async signTypedData(domain,types,_value){const value=deepCopy(_value);return await this.provider.send("quai_signTypedData_v4",[this.address.toLowerCase(),JSON.stringify(TypedDataEncoder.getPayload(domain,types,value))])}async unlock(password){return this.provider.send("personal_unlockAccount",[this.address.toLowerCase(),password,null])}async _legacySignMessage(_message){const message=typeof _message==="string"?toUtf8Bytes(_message):_message;return await this.provider.send("quai_sign",[this.address.toLowerCase(),hexlify(message)])}}class JsonRpcApiProvider extends AbstractProvider{#options;#nextId;#payloads;#drainTimer;#notReady;#network;#pendingDetectNetwork;#scheduleDrain(){if(this.#drainTimer){return}const stallTime=this._getOption("batchMaxCount")===1?0:this._getOption("batchStallTime");this.#drainTimer=setTimeout(()=>{this.#drainTimer=null;const payloads=this.#payloads;this.#payloads=[];while(payloads.length){const batch=[payloads.shift()];while(payloads.length){if(batch.length===this.#options.batchMaxCount){break}batch.push(payloads.shift());const bytes=JSON.stringify(batch.map(p=>p.payload));if(bytes.length>this.#options.batchMaxSize){payloads.unshift(batch.pop());break}}(async()=>{const payloadMap=new Map;const nowPayloadMap=new Map;for(let i=0;i{const payload=value.length===1?value[0]:value;const shard=key?toShard(key):exports.Shard.Prime;const zone=shard.length<4?undefined:toZone(shard);this.emit("debug",zone,{action:"sendRpcPayload",payload:payload});rawResult.push(await this._send(payload,shard,now));this.emit("debug",zone,{action:"receiveRpcResult",payload:payload})};await Promise.all(Array.from(nowPayloadMap).map(async([key,value])=>{await processPayloads(key,value,true)}).concat(Array.from(payloadMap).map(async([key,value])=>{await processPayloads(key,value)})));const result=rawResult.flat();let lastZone;try{for(const{resolve,reject,payload,shard}of batch){if(this.destroyed){reject(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:payload.method}));continue}if(shard){lastZone=shard.length<4?undefined:toZone(shard)}else{lastZone=undefined}const resp=result.filter(r=>r.id===payload.id)[0];if(resp==null){const error=makeError("missing response for request","BAD_DATA",{value:result,info:{payload:payload}});this.emit("error",lastZone,error);reject(error);continue}if("error"in resp){reject(this.getRpcError(payload,resp,shard));continue}resolve(resp.result)}}catch(error){this.emit("debug",lastZone,{action:"receiveRpcError",error:error});for(const{reject}of batch){reject(error)}}})()}},stallTime)}constructor(network,options){super(network,options);this.#nextId=1;this.#options=Object.assign({},defaultOptions,options||{});this.#payloads=[];this.#drainTimer=null;this.#network=null;this.#pendingDetectNetwork=null;{let resolve=null;const promise=new Promise(_resolve=>{resolve=_resolve});this.#notReady={promise:promise,resolve:resolve}}const staticNetwork=this._getOption("staticNetwork");if(typeof staticNetwork==="boolean"){assertArgument(!staticNetwork||network!=="any","staticNetwork cannot be used on special network 'any'","options",options);if(staticNetwork&&network!=null){this.#network=Network.from(network)}}else if(staticNetwork){assertArgument(network==null||staticNetwork.matches(network),"staticNetwork MUST match network object","options",options);this.#network=staticNetwork}}_getOption(key){return this.#options[key]}get _network(){assert(this.#network,"network is not available yet","NETWORK_ERROR");return this.#network}async _perform(req){if(req.method!=="getRunningLocations"){await this.initPromise}if(req.method==="call"||req.method==="estimateGas"){const tx=req.transaction;if(tx&&tx.type!=null&&getBigInt(tx.type)){if(tx.maxFeePerGas==null&&tx.maxPriorityFeePerGas==null){const feeData=await this.getFeeData(req.zone);if(feeData.maxFeePerGas==null&&feeData.maxPriorityFeePerGas==null){req=Object.assign({},req,{transaction:Object.assign({},tx,{type:undefined})})}}}}const request=this.getRpcRequest(req);if(request!=null){const shard="shard"in req?req.shard:"zone"in req?toShard(req.zone):undefined;if(req.method==="getRunningLocations"){return await this.send(request.method,request.args,shard,req.now)}else{return await this.send(request.method,request.args,shard)}}return super._perform(req)}async _detectNetwork(){const network=this._getOption("staticNetwork");if(network){if(network===true){if(this.#network){return this.#network}}else{return network}}if(this.#pendingDetectNetwork){return await this.#pendingDetectNetwork}if(this.ready){this.#pendingDetectNetwork=(async()=>{try{const result=Network.from(getBigInt(await this.send("quai_chainId",[])));this.#pendingDetectNetwork=null;return result}catch(error){this.#pendingDetectNetwork=null;throw error}})();return await this.#pendingDetectNetwork}this.#pendingDetectNetwork=(async()=>{const payload={id:this.#nextId++,method:"quai_chainId",params:[],jsonrpc:"2.0"};this.emit("debug",undefined,{action:"sendRpcPayload",payload:payload});let result;try{result=(await this._send(payload))[0];this.#pendingDetectNetwork=null}catch(error){this.#pendingDetectNetwork=null;this.emit("debug",undefined,{action:"receiveRpcError",error:error});throw error}this.emit("debug",undefined,{action:"receiveRpcResult",result:result});if("result"in result){return Network.from(getBigInt(result.result))}throw this.getRpcError(payload,result)})();return await this.#pendingDetectNetwork}_start(){if(this.#notReady==null||this.#notReady.resolve==null){return}this.#notReady.resolve();this.#notReady=null;(async()=>{let retries=0;const maxRetries=5;while(this.#network==null&&!this.destroyed&&retries=maxRetries){throw new Error("Failed to detect network after maximum retries")}this.#scheduleDrain()})()}async _waitUntilReady(){if(this._initFailed){throw new Error("Provider failed to initialize on creation. Run initialize or create a new provider.")}await this.initPromise}_getSubscriber(sub){if(sub.type==="pending"){return new FilterIdPendingSubscriber(this,sub.zone)}if(sub.type==="event"){return new FilterIdEventSubscriber(this,sub.filter)}if(sub.type==="orphan"&&sub.filter.orphan==="drop-log"){return new UnmanagedSubscriber("orphan")}return super._getSubscriber(sub)}get ready(){return this.#notReady==null}getRpcTransaction(tx){const result={};if("from"in tx||"to"in tx&&"data"in tx){["chainId","gasLimit","gasPrice","type","maxFeePerGas","maxPriorityFeePerGas","nonce","value"].forEach(key=>{if(tx[key]==null){return}let dstKey=key;if(key==="gasLimit"){dstKey="gas"}result[dstKey]=toQuantity(getBigInt(tx[key],`tx.${key}`))});["from","to","data"].forEach(key=>{if(tx[key]==null){return}result[key]=hexlify(tx[key])});if("accessList"in tx&&tx.accessList){result["accessList"]=accessListify(tx.accessList)}}else{throw new Error("No Qi getRPCTransaction implementation yet")}return result}getRpcRequest(req){switch(req.method){case"chainId":return{method:"quai_chainId",args:[]};case"getBlockNumber":return{method:"quai_blockNumber",args:[]};case"getGasPrice":return{method:"quai_baseFee",args:[req.txType]};case"getMaxPriorityFeePerGas":return{method:"quai_maxPriorityFeePerGas",args:[]};case"getPendingHeader":return{method:"quai_getPendingHeader",args:[]};case"getBalance":return{method:"quai_getBalance",args:[req.address,req.blockTag]};case"getOutpointsByAddress":return{method:"quai_getOutpointsByAddress",args:[req.address]};case"getTransactionCount":return{method:"quai_getTransactionCount",args:[req.address,req.blockTag]};case"getCode":return{method:"quai_getCode",args:[req.address,req.blockTag]};case"getStorage":return{method:"quai_getStorageAt",args:[req.address,"0x"+req.position.toString(16),req.blockTag]};case"broadcastTransaction":return{method:"quai_sendRawTransaction",args:[req.signedTransaction]};case"getBlock":if("blockTag"in req){return{method:"quai_getBlockByNumber",args:[req.blockTag,!!req.includeTransactions]}}else if("blockHash"in req){return{method:"quai_getBlockByHash",args:[req.blockHash,!!req.includeTransactions]}}break;case"getTransaction":return{method:"quai_getTransactionByHash",args:[req.hash]};case"getTransactionReceipt":return{method:"quai_getTransactionReceipt",args:[req.hash]};case"call":return{method:"quai_call",args:[this.getRpcTransaction(req.transaction),req.blockTag]};case"estimateGas":{return{method:"quai_estimateGas",args:[this.getRpcTransaction(req.transaction)]}}case"getRunningLocations":{return{method:"quai_listRunningChains",args:[]}}case"getProtocolTrieExpansionCount":{return{method:"quai_getProtocolExpansionNumber",args:[]}}case"getProtocolExpansionNumber":{return{method:"quai_getProtocolExpansionNumber",args:[]}}case"getQiRateAtBlock":{return{method:"quai_qiRateAtBlock",args:[req.blockTag,req.amt]}}case"getQuaiRateAtBlock":{return{method:"quai_quaiRateAtBlock",args:[req.blockTag,req.amt]}}case"getLogs":return{method:"quai_getLogs",args:[req.filter]};case"getTxPoolContent":return{method:"txpool_content",args:[]};case"txPoolInspect":return{method:"txpool_inspect",args:[]}}return null}getRpcError(payload,_error,shard){const{method}=payload;const{error}=_error;if(method==="quai_estimateGas"&&error.message){const msg=error.message;if(!msg.match(/revert/i)&&msg.match(/insufficient funds/i)){return makeError("insufficient funds","INSUFFICIENT_FUNDS",{transaction:payload.params[0],info:{payload:payload,error:error,shard:shard}})}}if(method==="quai_call"||method==="quai_estimateGas"){const result=spelunkData(error);const e=AbiCoder.getBuiltinCallException(method==="quai_call"?"call":"estimateGas",payload.params[0],result?result.data:null);e.info={error:error,payload:payload,shard:shard};return e}const message=JSON.stringify(spelunkMessage(error));if(method==="quai_getTransactionByHash"&&error.message&&error.message.match(/transaction not found/i)){return makeError("transaction not found","TRANSACTION_NOT_FOUND",{info:{payload:payload,error:error,shard:shard}})}if(typeof error.message==="string"&&error.message.match(/user denied|quais-user-denied/i)){const actionMap={quai_sign:"signMessage",personal_sign:"signMessage",quai_signTypedData_v4:"signTypedData",quai_signTransaction:"signTransaction",quai_sendTransaction:"sendTransaction",quai_requestAccounts:"requestAccess",wallet_requestAccounts:"requestAccess"};return makeError(`user rejected action`,"ACTION_REJECTED",{action:actionMap[method]||"unknown",reason:"rejected",info:{payload:payload,error:error,shard:shard}})}if(method==="quai_sendRawTransaction"||method==="quai_sendTransaction"){const transaction=payload.params[0];if(message.match(/insufficient funds|base fee exceeds gas limit/i)){return makeError("insufficient funds for intrinsic transaction cost","INSUFFICIENT_FUNDS",{transaction:transaction,info:{error:error,shard:shard}})}if(message.match(/nonce/i)&&message.match(/too low/i)){return makeError("nonce has already been used","NONCE_EXPIRED",{transaction:transaction,info:{error:error,shard:shard}})}if(message.match(/replacement transaction/i)&&message.match(/underpriced/i)){return makeError("replacement fee too low","REPLACEMENT_UNDERPRICED",{transaction:transaction,info:{error:error,shard:shard}})}if(message.match(/only replay-protected/i)){return makeError("legacy pre-eip-155 transactions not supported","UNSUPPORTED_OPERATION",{operation:method,info:{transaction:transaction,info:{error:error,shard:shard}}})}if(message.match(/already known/i)){return makeError("transaction already known","TRANSACTION_ALREADY_KNOWN",{info:{error:error,shard:shard}})}}let unsupported=!!message.match(/the method .* does not exist/i);if(!unsupported){if(error&&error.details&&error.details.startsWith("Unauthorized method:")){unsupported=true}}if(unsupported){return makeError("unsupported operation","UNSUPPORTED_OPERATION",{operation:payload.method,info:{error:error,payload:payload,shard:shard}})}if(message.match("Provider failed to initialize on creation. Run initialize or create a new provider.")){return makeError("Provider failed to initialize on creation. Run initUrlMap or create a new provider.","PROVIDER_FAILED_TO_INITIALIZE",{info:{payload:payload,error:error,shard:shard}})}return makeError("could not coalesce error","UNKNOWN_ERROR",{error:error,payload:payload,shard:shard})}send(method,params,shard,now){const continueSend=()=>{if(this.destroyed){return Promise.reject(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:method}))}const id=this.#nextId++;const promise=new Promise((resolve,reject)=>{this.#payloads.push({resolve:resolve,reject:reject,payload:{method:method,params:params,id:id,jsonrpc:"2.0"},shard:shard,now:now})});this.#scheduleDrain();return promise};if(method!=="quai_listRunningChains"){return this.initPromise.then(()=>{return continueSend()})}else{return continueSend()}}async getSigner(address){if(address==null){address=0}const accountsPromise=this.send("quai_accounts",[]);if(typeof address==="number"){const accounts=await accountsPromise;if(address>=accounts.length){throw new Error("no such account")}return new JsonRpcSigner(this,accounts[address])}const{accounts}=await resolveProperties({network:this.getNetwork(),accounts:accountsPromise});address=getAddress(address);for(const account of accounts){if(getAddress(account)===address){return new JsonRpcSigner(this,address)}}throw new Error("invalid account")}async listAccounts(){const accounts=await this.send("quai_accounts",[]);return accounts.map(a=>new JsonRpcSigner(this,a))}destroy(){if(this.#drainTimer){clearTimeout(this.#drainTimer);this.#drainTimer=null}for(const{payload,reject}of this.#payloads){reject(makeError("provider destroyed; cancelled request","UNSUPPORTED_OPERATION",{operation:payload.method}))}this.#payloads=[];super.destroy()}}class JsonRpcProvider extends JsonRpcApiProvider{constructor(urls,network,options){if(urls==null){urls=["http://localhost:8545"]}super(network,options);if(Array.isArray(urls)){urls.forEach(url=>{this.validateUrl(url)});this.initialize(urls)}else if(typeof urls==="string"){this.validateUrl(urls);this.initialize([urls])}else{this.validateUrl(urls.url);this.initialize(urls.clone())}}_getSubscriber(sub){const subscriber=super._getSubscriber(sub);return subscriber}_getConnection(shard){if(this._initFailed){throw new Error("Provider failed to initialize on creation. Run initUrlMap or create a new provider.")}let connection;if(shard!==undefined){connection=this._urlMap.get(shard)??this.connect[this.connect.length-1].clone()}else{connection=this.connect[this.connect.length-1].clone()}return new FetchRequest(connection.url)}async send(method,params,shard,now){await this._start();return await super.send(method,params,shard,now)}async _send(payload,shard){const request=this._getConnection(shard);request.body=JSON.stringify(payload);request.setHeader("content-type","application/json");const response=await request.send();response.assertOk();let resp=response.bodyJson;if(!Array.isArray(resp)){resp=[resp]}return resp}}function spelunkData(value){if(value==null){return null}if(typeof value.message==="string"&&value.message.match(/revert/i)&&isHexString(value.data)){return{message:value.message,data:value.data}}if(typeof value==="object"){for(const key in value){const result=spelunkData(value[key]);if(result){return result}}return null}if(typeof value==="string"){try{return spelunkData(JSON.parse(value))}catch(error){}}return null}function _spelunkMessage(value,result){if(value==null){return}if(typeof value.message==="string"){result.push(value.message)}if(typeof value==="object"){for(const key in value){_spelunkMessage(value[key],result)}}if(typeof value==="string"){try{return _spelunkMessage(JSON.parse(value),result)}catch(error){}}}function spelunkMessage(value){const result=[];_spelunkMessage(value,result);return result}class ContractFactory{interface;bytecode;runner;constructor(abi,bytecode,runner){const iface=Interface.from(abi);if(bytecode instanceof Uint8Array){bytecode=hexlify(getBytes(bytecode))}else{if(typeof bytecode==="object"){bytecode=bytecode.object}if(!bytecode.startsWith("0x")){bytecode="0x"+bytecode}bytecode=hexlify(getBytes(bytecode))}defineProperties(this,{bytecode:bytecode,interface:iface,runner:runner||null})}attach(target){return new BaseContract(target,this.interface,this.runner)}async getDeployTransaction(...args){let overrides;const fragment=this.interface.deploy;if(fragment.inputs.length+1===args.length){overrides=await copyOverrides(args.pop());const resolvedArgs=await resolveArgs(this.runner,fragment.inputs,args);const data=concat([this.bytecode,this.interface.encodeDeploy(resolvedArgs)]);return Object.assign({},overrides,{data:data})}if(fragment.inputs.length!==args.length){throw new Error("incorrect number of arguments to constructor")}const resolvedArgs=await resolveArgs(this.runner,fragment.inputs,args);const data=concat([this.bytecode,this.interface.encodeDeploy(resolvedArgs)]);const from=args.pop()?.from||undefined;return Object.assign({},from,{data:data})}async deploy(...args){const tx=await this.getDeployTransaction(...args);assert(this.runner&&typeof this.runner.sendTransaction==="function","factory runner does not support sending transactions","UNSUPPORTED_OPERATION",{operation:"sendTransaction"});if(this.runner instanceof Wallet||this.runner instanceof JsonRpcSigner){validateAddress(this.runner.address);tx.from=this.runner.address}const grindedTx=await this.grindContractAddress(tx);const sentTx=await this.runner.sendTransaction(grindedTx);const address=getStatic(this.constructor,"getContractAddress")?.(tx);return new BaseContract(address,this.interface,this.runner,sentTx)}static getContractAddress(transaction){return getContractAddress(transaction.from,BigInt(transaction.nonce),transaction.data)}async grindContractAddress(tx){if(tx.nonce==null&&tx.from){tx.nonce=await this.runner?.provider?.getTransactionCount(tx.from)}const sender=String(tx.from);const toShard=getZoneForAddress(sender);let i=0;const startingData=tx.data;while(i<1e4){const contractAddress=getContractAddress(sender,BigInt(tx.nonce||0),tx.data||"");const contractShard=getZoneForAddress(contractAddress);const utxo=isQiAddress(contractAddress);if(contractShard===toShard&&!utxo){return tx}const salt=randomBytes(32);tx.data=hexlify(concat([String(startingData),salt]));i++}return tx}connect(runner){return new ContractFactory(this.interface,this.bytecode,runner)}static fromSolidity(output,runner){assertArgument(output!=null,"bad compiler output","output",output);if(typeof output==="string"){output=JSON.parse(output)}const abi=output.abi;let bytecode="";if(output.bytecode){bytecode=output.bytecode}else if(output.evm&&output.evm.bytecode){bytecode=output.evm.bytecode}return new this(abi,bytecode,runner)}}class BrowserProvider extends JsonRpcApiProvider{#request;constructor(ethereum,network){super(network,{batchMaxCount:1});this.#request=async(method,params)=>{const payload={method:method,params:params};this.emit("debug",undefined,{action:"sendEip1193Request",payload:payload});try{const result=await ethereum.request(payload);this.emit("debug",undefined,{action:"receiveEip1193Result",result:result});return result}catch(e){const error=new Error(e.message);error.code=e.code;error.data=e.data;error.payload=payload;this.emit("debug",undefined,{action:"receiveEip1193Error",error:error});throw error}}}async hasSigner(address){if(address==null){address=0}const accounts=await this.send("quai_accounts",[]);if(typeof address==="number"){return accounts.length>address}address=address.toLowerCase();return accounts.filter(a=>a.toLowerCase()===address).length!==0}async send(method,params){await this._start();return await super.send(method,params)}async _send(payload){assertArgument(!Array.isArray(payload),"EIP-1193 does not support batch request","payload",payload);try{const result=await this.#request(payload.method,payload.params||[]);return[{id:payload.id,result:result}]}catch(e){return[{id:payload.id,error:{code:e.code,data:e.data,message:e.message}}]}}getRpcError(payload,error){error=JSON.parse(JSON.stringify(error));switch(error.error.code||-1){case 4001:error.error.message=`quais-user-denied: ${error.error.message}`;break;case 4200:error.error.message=`quais-unsupported: ${error.error.message}`;break}return super.getRpcError(payload,error)}async getSigner(address){if(address==null){address=0}if(!await this.hasSigner(address)){try{await this.#request("quai_requestAccounts",[])}catch(error){const payload=error.payload;throw this.getRpcError(payload,{id:payload.id,error:error})}}return await super.getSigner(address)}}class SocketSubscriber{#provider;#filter;get filter(){return JSON.parse(this.#filter)}#filterId;#paused;#emitPromise;zone;shard;constructor(provider,filter,zone){this.#provider=provider;this.#filter=JSON.stringify(filter);this.#filterId=null;this.#paused=null;this.#emitPromise=null;this.zone=zone;this.shard=toShard(zone)}start(){this.#filterId=this.#provider.send("quai_subscribe",this.filter,this.shard).then(filterId=>{this.#provider._register(filterId,this);return filterId})}stop(){this.#filterId.then(filterId=>{this.#provider.send("quai_unsubscribe",[filterId],this.shard)});this.#filterId=null}pause(dropWhilePaused){assert(dropWhilePaused,"preserve logs while paused not supported by SocketSubscriber yet","UNSUPPORTED_OPERATION",{operation:"pause(false)"});this.#paused=!!dropWhilePaused}resume(){this.#paused=null}_handleMessage(message){if(this.#filterId==null){return}if(this.#paused===null){let emitPromise=this.#emitPromise;if(emitPromise==null){emitPromise=this._emit(this.#provider,message)}else{emitPromise=emitPromise.then(async()=>{await this._emit(this.#provider,message)})}this.#emitPromise=emitPromise.then(()=>{if(this.#emitPromise===emitPromise){this.#emitPromise=null}})}}async _emit(provider,message){throw new Error("sub-classes must implement this; _emit")}}class SocketBlockSubscriber extends SocketSubscriber{constructor(provider,zone){super(provider,["newHeads"],zone)}async _emit(provider,message){provider.emit("block",this.zone,parseInt(message.woHeader.number))}}class SocketPendingSubscriber extends SocketSubscriber{constructor(provider,zone){super(provider,["newPendingTransactions"],zone)}async _emit(provider,message){provider.emit("pending",message)}}class SocketEventSubscriber extends SocketSubscriber{#logFilter;get logFilter(){return JSON.parse(this.#logFilter)}constructor(provider,filter,zone){super(provider,["logs",filter],zone);this.#logFilter=JSON.stringify(filter)}async _emit(provider,message){provider.emit(this.logFilter,this.zone,provider._wrapLog(message,provider._network))}}class SocketProvider extends JsonRpcApiProvider{#callbacks;#subs;#pending;constructor(network,_options){const options=Object.assign({},_options!=null?_options:{});assertArgument(options.batchMaxCount==null||options.batchMaxCount===1,"sockets-based providers do not support batches","options.batchMaxCount",_options);options.batchMaxCount=1;if(options.staticNetwork==null){options.staticNetwork=true}super(network,options);this.#callbacks=new Map;this.#subs=new Map;this.#pending=new Map}_getSubscriber(sub){switch(sub.type){case"close":return new UnmanagedSubscriber("close");case"block":return new SocketBlockSubscriber(this,sub.zone);case"pending":return new SocketPendingSubscriber(this,sub.zone);case"event":return new SocketEventSubscriber(this,sub.filter,sub.zone);case"orphan":if(sub.filter.orphan==="drop-log"){return new UnmanagedSubscriber("drop-log")}}return super._getSubscriber(sub)}_register(filterId,subscriber){this.#subs.set(filterId,subscriber);const pending=this.#pending.get(filterId);if(pending){for(const message of pending){subscriber._handleMessage(message)}this.#pending.delete(filterId)}}async _send(payload,shard,now){if(this._initFailed){console.log("Provider failed to initialize on creation. Run initialize or create a new provider.");return[{id:Array.isArray(payload)?payload[0].id:payload.id,error:{code:-32e3,message:"Provider failed to initialize on creation. Run initialize or create a new provider."}}]}assertArgument(!Array.isArray(payload),"WebSocket does not support batch send","payload",payload);const promise=new Promise((resolve,reject)=>{this.#callbacks.set(payload.id,{payload:payload,resolve:resolve,reject:reject})});try{if(!now){await this._waitUntilReady()}}catch(error){this.#callbacks.delete(payload.id);return[{id:Array.isArray(payload)?payload[0].id:payload.id,error:{code:-32e3,message:"Provider failed to initialize on creation. Run initialize or create a new provider."}}]}await this._write(JSON.stringify(payload),shard);return[await promise]}async _processMessage(message){const result=JSON.parse(message);if(result&&typeof result==="object"&&"id"in result){const callback=this.#callbacks.get(result.id);if(callback==null){this.emit("error",undefined,makeError("received result for unknown id","UNKNOWN_ERROR",{reasonCode:"UNKNOWN_ID",result:result}));return}this.#callbacks.delete(result.id);callback.resolve(result)}else if(result&&result.method==="quai_subscription"){const filterId=result.params.subscription;const subscriber=this.#subs.get(filterId);if(subscriber){subscriber._handleMessage(result.params.result)}else{let pending=this.#pending.get(filterId);if(pending==null){pending=[];this.#pending.set(filterId,pending)}pending.push(result.params.result)}}else{this.emit("error",undefined,makeError("received unexpected message","UNKNOWN_ERROR",{reasonCode:"UNEXPECTED_MESSAGE",result:result}));return}}async _write(message,shard){throw new Error("sub-classes must override this")}validateUrl(url){const urlPattern=/^(ws):\/\/[a-zA-Z0-9.-]+(:\d+)?$/;if(!urlPattern.test(url)){let errorMessage="Invalid URL: ";if(!/^ws:\/\//.test(url)){errorMessage+="URL must start with ws://. "}if(url.endsWith("/")){errorMessage+="URL should not end with a /. "}if(/\/[^/]+/.test(url)){errorMessage+="URL should not contain a path, query string, or fragment. "}throw new Error(errorMessage.trim())}}}function getGlobal(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")}const _WebSocket=getGlobal().WebSocket;class WebSocketProvider extends SocketProvider{#websockets;readyMap=new Map;get websocket(){if(this.#websockets==null){throw new Error("websocket closed")}return this.#websockets}constructor(url,network,options){super(network,options);this.#websockets=[];if(typeof url==="string"){this.validateUrl(url)}else if(Array.isArray(url)){url.forEach(it=>this.validateUrl(it))}else if(typeof url==="function"){this.validateUrl(url().url)}else{this.validateUrl(url.url)}this.initialize(typeof url==="string"?[url]:url)}initWebSocket(websocket,shard){websocket.onerror=error=>{console.log("WebsocketProvider error",error);websocket.close()};websocket.onopen=async()=>{try{await this._start();this.resume();this.readyMap.set(shard,true)}catch(error){console.log("failed to start WebsocketProvider",error);this.readyMap.set(shard,false)}};websocket.onmessage=message=>{this._processMessage(message.data)}}async waitShardReady(shard){let count=0;while(!this.readyMap.get(shard)){await new Promise(resolve=>setTimeout(resolve,Math.pow(2,count)));if(count>11){throw new Error("Timeout waiting for shard to be ready")}count++}}async initialize(urls){this.#websockets=[];this._urlMap.clear();try{const primeSuffix=this._getOption("usePathing")?`/${fromShard(exports.Shard.Prime,"nickname")}`:":8001";const createWebSocket=(baseUrl,suffix)=>{const tempWs=new _WebSocket(`${baseUrl}${suffix}`);return tempWs};const initShardWebSockets=async baseUrl=>{const shards=await this._getRunningLocations(exports.Shard.Prime,true);await Promise.all(shards.map(async shard=>{const port=8200+20*shard[0]+shard[1];const shardEnum=toShard(`0x${shard[0].toString(16)}${shard[1].toString(16)}`);const shardSuffix=this._getOption("usePathing")?`/${fromShard(shardEnum,"nickname")}`:`:${port}`;const shardUrl=baseUrl.split(":").slice(0,2).join(":");const websocket=createWebSocket(shardUrl,shardSuffix);this.initWebSocket(websocket,shardEnum);this.#websockets.push(websocket);this._urlMap.set(shardEnum,websocket);try{await this.waitShardReady(shardEnum)}catch(error){console.log("failed to waitShardReady",error);this._initFailed=true}}))};if(Array.isArray(urls)){for(const url of urls){const baseUrl=`${url.split(":")[0]}:${url.split(":")[1]}`;const primeWebsocket=createWebSocket(baseUrl,primeSuffix);this.initWebSocket(primeWebsocket,exports.Shard.Prime);this.#websockets.push(primeWebsocket);this._urlMap.set(exports.Shard.Prime,primeWebsocket);await this.waitShardReady(exports.Shard.Prime);await initShardWebSockets(baseUrl)}}else if(typeof urls==="function"){const primeWebsocket=urls();this.initWebSocket(primeWebsocket,exports.Shard.Prime);this.#websockets.push(primeWebsocket);this._urlMap.set(exports.Shard.Prime,primeWebsocket);await this.waitShardReady(exports.Shard.Prime);const baseUrl=this.#websockets[0].url.split(":").slice(0,2).join(":");await initShardWebSockets(baseUrl)}else{const primeWebsocket=urls;this.initWebSocket(primeWebsocket,exports.Shard.Prime);this.#websockets.push(primeWebsocket);this._urlMap.set(exports.Shard.Prime,primeWebsocket);await this.waitShardReady(exports.Shard.Prime);const baseUrl=primeWebsocket.url.split(":").slice(0,2).join(":");await initShardWebSockets(baseUrl)}if(this.initResolvePromise)this.initResolvePromise()}catch(error){this._initFailed=true;console.log("failed to initialize",error);this.#websockets=[];if(this.initRejectPromise)this.initRejectPromise(error);return}}async _write(message,shard){if(this.websocket.length<1){throw new Error("Websocket closed")}if(shard&&!this._urlMap.has(shard)){throw new Error("Shard not found")}const websocket=shard?this._urlMap.get(shard):this.websocket[this.websocket.length-1];if(!websocket){throw new Error("Websocket is undefined")}if(shard){await this.waitShardReady(shard)}websocket.send(message)}async destroy(){this.#websockets.forEach(it=>it.close());this.#websockets=[];super.destroy()}}const Base64=")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_";function decodeBits(width,data){const maxValue=(1<=width){const value=accum>>bits-width;accum&=(1<{const match=accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);assertArgument(match!==null,"internal error parsing accents","accents",accents);let posOffset=0;const positions=decodeBits(parseInt(match[3]),match[4]);const charCode=parseInt(match[2]);const regex=new RegExp(`([${match[1]}])`,"g");words=words.replace(regex,(all,letter)=>{const rem=--positions[posOffset];if(rem===0){letter=String.fromCharCode(letter.charCodeAt(0),charCode);posOffset++}return letter})});return words.split(",")}class WordlistOwlA extends WordlistOwl{#accent;constructor(locale,data,accent,checksum){super(locale,data,checksum);this.#accent=accent}get _accent(){return this.#accent}_decodeWords(){return decodeOwlA(this._data,this._accent)}}const words="0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_LoAmpuAnc]ApaAr]I>Is)IvoOqueOzaUle%Up 0Cl.EgoE=EnEr#F[G +M->NeN%P_sR>Rue]SneTaU{d2Am^AnA+AseAveI,)ImaInica2B_Cc~|i'Ci`CoDigoDoF_G!He)JinJoL/ch/eg$Lg Lin/l LmoLum`Mba)M!Mi{Mo&Mpr-deNej}g-oc!Nsej}t PaPi(az.Rba%RchoR&nR.(r!S!SmosS%2AneoAt!E Ec!Ei&EmaIaIm,Ip%IsisOmoOnicaOque%U&Uz2Ad+Ar#At+BoBr*| aEl=En#Er{Es%EvaId Lebr/p/#Mb_Mpl*N-e%O%P.Pul( R$Se'Sf[zVaVi'5BleCeL^Ming}N Ra&Rm*RAu%EchaOrO%U*UjoU^2B@CaGa%G.L$Lle#N&Rm(+Rtun(z SaTo2AcaA'AsaAtisAveIe%Il=IpeIsI#OG Gu!aJaMb_Ng}^Nr((mig('St?Yo5E>ElgaEr%ENgl-$Nt Pit!R S#V,?Zg :7Lo5A]:B$C$C[DoD+nG #GrimaGu`I>M!Mi`Mp --ch-gos%NzaPizRgoRvaStimaTaTexT*U_lV Zo3AlCc~|eC#rErG~Gumb_Ja'Ngu-#NaOnOp &S~TalT[VeY,{3B!%dB+C^D!Di EnzoGaG!oMaMi)M.Mp$NceN&Ne-go)N}t!`Qui&SoS%T!aT$T+2AgaAmaAn#AveEg En Ev Or Ov!Uv@2BoC~CoCu[GicaG+MbrizM}jaTe5|aC*G J}-esPaSt+ToZ:Ce%|oD!aD_Du+Est+F@G@GoIzL{dLe%Ll/oMaMboMutN>N&Nej Ng-iquiNj N}Re(f?Rg,Ri&RmolR+nR)sRzoSaSc aSivoT T!@TizTrizXimoY^Z^ca3|aDal]D$Du]J?]J^L,/.M^i-^NsajeN)NuRca&R,gueRi#SS.TaT!To&T+Zc]3E&ElEmb+G/Lag+Lit Ll.M}-!}im}u#OpeR SaS!@S?SmoTadTo5|?aC~DaDe=HoJ LdeL!Li'M,#Mi- c-ed-j-#NoRad(d!Re'R*R+Rs(%lScaStr TivoV!V?Zo5|oD EbleE]Er)Est[G_J!L/e%L%N&Nec(alRoScu=SeoSgoSicaS=:C C~D IpeRanj(izRr SalTalTivoTu[lUseaValVeVi{d3C$Ct G Goc$G+OnRv$ToUt+V V!a3|oDoEb]E#NezNoTi&Vel5Bleza|eMin(i(m()TaTic@Va#Ve]V$5BeCaCleoD?=DoE[EveEzLoM!oTr@:Sis0EC~E[In On!T TicaUes#1Ac~A&rAlBi%CaD,EjaGa'G@Gul=I,)Ig,Il]OQues%Uga0Ad@Cu+Ez'OT[0O'Ro1EjaU=1I&Ige'0En)0O':C#D_El]Gi`GoIsJ oLabr/>Le%Li&Lm/om/p NNalNi>Nt!-ue=PaPelP?]Que)R Rcel(edR*RoRpa&RqueR[foR)S SeoS~SoS%TaT$Tr@UsaU%VoYa<3A#nCa&C!a|oDalD*G IneL L{'Le/ig+LlejoLoLuc--s N.OnOrPi'Que'R(ch(d!Rez(f?Ri>Rl(mizEgun%Em$EnsaE|!oD^Eb=Er%Es#Lg/*Lm.LpoLrNd*N%P #Pet*PoN{PaP!oSaScaSt+T 5BiB^DoE{G*I&In/e%LoMboM^Ptu[TaTi`:Ba&B!B$BleC GazG[&L/&L!oL*Lm.L.Ls/#LudLv Mb-c~Ndi-e Ng_Ni{dN}#PoQueRdin()nSt_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv! 0 && !lengths.includes(b.length)) - throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); -} -function exists(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error('Hash instance has been destroyed'); - if (checkFinished && instance.finished) - throw new Error('Hash#digest() has already been called'); -} -function output(out, instance) { - bytes(out); - const min = instance.outputLen; - if (out.length < min) { - throw new Error(`digestInto() expects output buffer of length at least ${min}`); - } -} - -/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ -// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. -// node.js versions earlier than v19 don't declare it in global scope. -// For node.js, package.json#exports field mapping rewrites import -// from `crypto` to `cryptoNode`, which imports native module. -// Makes the utils un-importable in browsers without a bundler. -// Once node.js 18 is deprecated, we can just drop the import. -const u8a = (a) => a instanceof Uint8Array; -const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -// big-endian hardware is rare. Just in case someone still decides to run hashes: -// early-throw an error because we don't support BE yet. -const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44; -if (!isLE) - throw new Error('Non little-endian hardware is not supported'); -/** - * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99]) - */ -function utf8ToBytes(str) { - if (typeof str !== 'string') - throw new Error(`utf8ToBytes expected string, got ${typeof str}`); - return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 -} -/** - * Normalizes (non-hex) string or Uint8Array to Uint8Array. - * Warning: when Uint8Array is passed, it would NOT get copied. - * Keep in mind for future mutable operations. - */ -function toBytes(data) { - if (typeof data === 'string') - data = utf8ToBytes(data); - if (!u8a(data)) - throw new Error(`expected Uint8Array, got ${typeof data}`); - return data; -} -// For runtime check if class implements interface -class Hash { - // Safe version that clones internal state - clone() { - return this._cloneInto(); - } -} -function wrapConstructor(hashCons) { - const hashC = (msg) => hashCons().update(toBytes(msg)).digest(); - const tmp = hashCons(); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.create = () => hashCons(); - return hashC; -} - -const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); -const _32n = /* @__PURE__ */ BigInt(32); -// We are not using BigUint64Array, because they are extremely slow as per 2022 -function fromBig(n, le = false) { - if (le) - return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; - return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; -} -function split(lst, le = false) { - let Ah = new Uint32Array(lst.length); - let Al = new Uint32Array(lst.length); - for (let i = 0; i < lst.length; i++) { - const { h, l } = fromBig(lst[i], le); - [Ah[i], Al[i]] = [h, l]; - } - return [Ah, Al]; -} -// Left rotate for Shift in [1, 32) -const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); -const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); -// Left rotate for Shift in (32, 64), NOTE: 32 is special case. -const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); -const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); - -/* Do NOT modify this file; see /src/_admin/update-version.ts */ -/** - * The current version of quais. - * - * @ignore - */ -const version = '1.0.0-alpha.5'; - -/** - * Property helper functions. - */ -/** - * Assigns the `values` to `target` as read-only values. - * - * It `types` is specified, the values are checked. - * - * @category Utils - * @param {Object} target - The target object to assign to. - * @param {Object} values - The values to assign. - * @param {Object} types - The types to check. - */ -function defineProperties(target, values, types) { - for (const key in values) { - const value = values[key]; - Object.defineProperty(target, key, { enumerable: true, value, writable: false }); - } -} - -/** - * All errors in quais include properties to ensure they are both human-readable (i.e. `.message`) and machine-readable - * (i.e. `.code`). - * - * The {@link isError | **isError**} function can be used to check the error `code` and provide a type guard for the - * properties present on that error interface. - */ -function stringify(value) { - if (value == null) { - return 'null'; - } - if (Array.isArray(value)) { - return '[ ' + value.map(stringify).join(', ') + ' ]'; - } - if (value instanceof Uint8Array) { - const HEX = '0123456789abcdef'; - let result = '0x'; - for (let i = 0; i < value.length; i++) { - result += HEX[value[i] >> 4]; - result += HEX[value[i] & 0xf]; - } - return result; - } - if (typeof value === 'object' && typeof value.toJSON === 'function') { - return stringify(value.toJSON()); - } - switch (typeof value) { - case 'boolean': - case 'symbol': - return value.toString(); - case 'bigint': - return BigInt(value).toString(); - case 'number': - return value.toString(); - case 'string': - return JSON.stringify(value); - case 'object': { - const keys = Object.keys(value); - keys.sort(); - return '{ ' + keys.map((k) => `${stringify(k)}: ${stringify(value[k])}`).join(', ') + ' }'; - } - } - return `[ COULD NOT SERIALIZE ]`; -} -/** - * Returns a new Error configured to the format quais emits errors, with the `message`, {@link ErrorCode | **ErrorCode**} - * `code` and additional properties for the corresponding quaisError. - * - * Each error in quais includes the version of quais, a machine-readable {@link ErrorCode | **ErrorCode**}, and depending - * on `code`, additional required properties. The error message will also include the `message`, quais version, `code` - * and all additional properties, serialized. - * - * @category Utils - * @param {string} message - The error message. - * @param {ErrorCode} code - The error code. - * @param {ErrorInfo} [info] - Additional properties for the error. - * @returns {T} The new error. - */ -function makeError(message, code, info) { - const shortMessage = message; - { - const details = []; - if (info) { - if ('message' in info || 'code' in info || 'name' in info) { - throw new Error(`value will overwrite populated values: ${stringify(info)}`); - } - for (const key in info) { - if (key === 'shortMessage') { - continue; - } - const value = info[key]; - details.push(key + '=' + stringify(value)); - } - } - details.push(`code=${code}`); - details.push(`version=${version}`); - if (details.length) { - message += ' (' + details.join(', ') + ')'; - } - } - let error; - switch (code) { - case 'INVALID_ARGUMENT': - error = new TypeError(message); - break; - case 'NUMERIC_FAULT': - case 'BUFFER_OVERRUN': - error = new RangeError(message); - break; - default: - error = new Error(message); - } - defineProperties(error, { code }); - if (info) { - Object.assign(error, info); - } - if (error.shortMessage == null) { - defineProperties(error, { shortMessage }); - } - return error; -} -/** - * Throws an quaisError with `message`, `code` and additional error `info` when `check` is falsish.. - * - * @category Utils - * @param {unknown} check - The value to check. - * @param {string} message - The error message. - * @param {ErrorCode} code - The error code. - * @param {ErrorInfo} [info] - Additional properties for the error. - * @throws {T} Throws the error if `check` is falsish. - */ -function assert(check, message, code, info) { - if (!check) { - throw makeError(message, code, info); - } -} -/** - * A simple helper to simply ensuring provided arguments match expected constraints, throwing if not. - * - * In TypeScript environments, the `check` has been asserted true, so any further code does not need additional - * compile-time checks. - * - * @category Utils - * @param {unknown} check - The value to check. - * @param {string} message - The error message. - * @param {string} name - The name of the argument. - * @param {unknown} value - The value of the argument. - * @throws {InvalidArgumentError} Throws if `check` is falsish. - */ -function assertArgument(check, message, name, value) { - assert(check, message, 'INVALID_ARGUMENT', { argument: name, value: value }); -} -['NFD', 'NFC', 'NFKD', 'NFKC'].reduce((accum, form) => { - try { - // General test for normalize - /* c8 ignore start */ - if ('test'.normalize(form) !== 'test') { - throw new Error('bad'); - } - /* c8 ignore stop */ - if (form === 'NFD') { - const check = String.fromCharCode(0xe9).normalize('NFD'); - const expected = String.fromCharCode(0x65, 0x0301); - /* c8 ignore start */ - if (check !== expected) { - throw new Error('broken'); - } - /* c8 ignore stop */ - } - accum.push(form); - // eslint-disable-next-line no-empty - } - catch (error) { } - return accum; -}, []); - -/** - * Some data helpers. - */ -/** - * Converts a BytesLike value to a Uint8Array. - * - * @ignore - * @category Utils - * @param {BytesLike} value - The value to convert. - * @param {string} [name] - The name of the value for error context. - * @param {boolean} [copy] - Whether to create a copy of the value. - * - * @returns {Uint8Array} The converted Uint8Array. - * @throws {Error} If the value is not a valid BytesLike. - */ -function _getBytes(value, name, copy) { - if (value instanceof Uint8Array) { - return value; - } - if (typeof value === 'string' && value.match(/^0x([0-9a-f][0-9a-f])*$/i)) { - const result = new Uint8Array((value.length - 2) / 2); - let offset = 2; - for (let i = 0; i < result.length; i++) { - result[i] = parseInt(value.substring(offset, offset + 2), 16); - offset += 2; - } - return result; - } - assertArgument(false, 'invalid BytesLike value', name || 'value', value); -} -/** - * Get a typed Uint8Array for `value`. If already a Uint8Array the original `value` is returned; if a copy is required - * use {@link getBytesCopy | **getBytesCopy**}. - * - * @category Utils - * @param {BytesLike} value - The value to convert to a Uint8Array. - * @param {string} [name] - The name of the value for error context. - * - * @returns {Uint8Array} The typed Uint8Array. - */ -function getBytes(value, name) { - return _getBytes(value, name); -} -const HexCharacters = '0123456789abcdef'; -/** - * Returns a {@link DataHexString | **DataHexString**} representation of `data`. - * - * @category Utils - * @param {BytesLike} data - The data to convert to a hex string. - * - * @returns {string} The hex string. - */ -function hexlify(data) { - const bytes = getBytes(data); - let result = '0x'; - for (let i = 0; i < bytes.length; i++) { - const v = bytes[i]; - result += HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]; - } - return result; -} - -/** - * Using strings in Ethereum (or any security-basd system) requires additional care. These utilities attempt to mitigate - * some of the safety issues as well as provide the ability to recover and analyse strings. - * - * @subsection api/utils:Strings and UTF-8 [about-strings] - */ -// `output` and `badCodepoint` are passed to calls below, but not used in the function -function errorFunc(reason, offset, bytes, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -output, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -badCodepoint) { - assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, 'bytes', bytes); -} -// `output` and `badCodepoint` are passed to calls below, but not used in the function -function ignoreFunc(reason, offset, bytes, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -output, -// eslint-disable-next-line @typescript-eslint/no-unused-vars -badCodepoint) { - // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes - if (reason === 'BAD_PREFIX' || reason === 'UNEXPECTED_CONTINUE') { - let i = 0; - for (let o = offset + 1; o < bytes.length; o++) { - if (bytes[o] >> 6 !== 0x02) { - break; - } - i++; - } - return i; - } - // This byte runs us past the end of the string, so just jump to the end - // (but the first byte was read already read and therefore skipped) - if (reason === 'OVERRUN') { - return bytes.length - offset - 1; - } - // Nothing to skip - return 0; -} -function replaceFunc(reason, offset, bytes, output, badCodepoint) { - // Overlong representations are otherwise "valid" code points; just non-deistingtished - if (reason === 'OVERLONG') { - assertArgument(typeof badCodepoint === 'number', 'invalid bad code point for replacement', 'badCodepoint', badCodepoint); - output.push(badCodepoint); - return 0; - } - // Put the replacement character into the output - output.push(0xfffd); - // Otherwise, process as if ignoring errors - return ignoreFunc(reason, offset, bytes); -} -/** - * A handful of popular, built-in UTF-8 error handling strategies. - * - * **`"error"`** - throws on ANY illegal UTF-8 sequence or non-canonical (overlong) codepoints (this is the default) - * - * **`"ignore"`** - silently drops any illegal UTF-8 sequence and accepts non-canonical (overlong) codepoints - * - * **`"replace"`** - replace any illegal UTF-8 sequence with the UTF-8 replacement character (i.e. `"\\ufffd"`) and - * accepts non-canonical (overlong) codepoints - * - * @category Encoding - * @returns Record<"error" | "ignore" | "replace", Utf8ErrorFunc> - */ -const Utf8ErrorFuncs = Object.freeze({ - error: errorFunc, - ignore: ignoreFunc, - replace: replaceFunc, -}); -// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499 -function getUtf8CodePoints(_bytes, onError) { - if (onError == null) { - onError = Utf8ErrorFuncs.error; - } - const bytes = getBytes(_bytes, 'bytes'); - const result = []; - let i = 0; - // Invalid bytes are ignored - while (i < bytes.length) { - const c = bytes[i++]; - // 0xxx xxxx - if (c >> 7 === 0) { - result.push(c); - continue; - } - // Multibyte; how many bytes left for this character? - let extraLength = null; - let overlongMask = null; - // 110x xxxx 10xx xxxx - if ((c & 0xe0) === 0xc0) { - extraLength = 1; - overlongMask = 0x7f; - // 1110 xxxx 10xx xxxx 10xx xxxx - } - else if ((c & 0xf0) === 0xe0) { - extraLength = 2; - overlongMask = 0x7ff; - // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx - } - else if ((c & 0xf8) === 0xf0) { - extraLength = 3; - overlongMask = 0xffff; - } - else { - if ((c & 0xc0) === 0x80) { - i += onError('UNEXPECTED_CONTINUE', i - 1, bytes, result); - } - else { - i += onError('BAD_PREFIX', i - 1, bytes, result); - } - continue; - } - // Do we have enough bytes in our data? - if (i - 1 + extraLength >= bytes.length) { - i += onError('OVERRUN', i - 1, bytes, result); - continue; - } - // Remove the length prefix from the char - let res = c & ((1 << (8 - extraLength - 1)) - 1); - for (let j = 0; j < extraLength; j++) { - const nextChar = bytes[i]; - // Invalid continuation byte - if ((nextChar & 0xc0) != 0x80) { - i += onError('MISSING_CONTINUE', i, bytes, result); - res = null; - break; - } - res = (res << 6) | (nextChar & 0x3f); - i++; - } - // See above loop for invalid continuation byte - if (res === null) { - continue; - } - // Maximum code point - if (res > 0x10ffff) { - i += onError('OUT_OF_RANGE', i - 1 - extraLength, bytes, result, res); - continue; - } - // Reserved for UTF-16 surrogate halves - if (res >= 0xd800 && res <= 0xdfff) { - i += onError('UTF16_SURROGATE', i - 1 - extraLength, bytes, result, res); - continue; - } - // Check for overlong sequences (more bytes than needed) - if (res <= overlongMask) { - i += onError('OVERLONG', i - 1 - extraLength, bytes, result, res); - continue; - } - result.push(res); - } - return result; -} -// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array -/** - * Returns the UTF-8 byte representation of `str`. - * - * If `form` is specified, the string is normalized. - * - * @category Encoding - * @param {string} str - The string to convert. - * @param {UnicodeNormalizationForm} [form] - The normalization form to use. - * - * @returns {Uint8Array} The UTF-8 byte representation. - * @throws {Error} If the UTF-8 conversion fails. - */ -function toUtf8Bytes(str, form) { - const result = []; - for (let i = 0; i < str.length; i++) { - const c = str.charCodeAt(i); - if (c < 0x80) { - result.push(c); - } - else if (c < 0x800) { - result.push((c >> 6) | 0xc0); - result.push((c & 0x3f) | 0x80); - } - else if ((c & 0xfc00) == 0xd800) { - i++; - const c2 = str.charCodeAt(i); - assertArgument(i < str.length && (c2 & 0xfc00) === 0xdc00, 'invalid surrogate pair', 'str', str); - // Surrogate Pair - const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff); - result.push((pair >> 18) | 0xf0); - result.push(((pair >> 12) & 0x3f) | 0x80); - result.push(((pair >> 6) & 0x3f) | 0x80); - result.push((pair & 0x3f) | 0x80); - } - else { - result.push((c >> 12) | 0xe0); - result.push(((c >> 6) & 0x3f) | 0x80); - result.push((c & 0x3f) | 0x80); - } - } - return new Uint8Array(result); -} -/** - * @ignore - */ -function _toUtf8String(codePoints) { - return codePoints - .map((codePoint) => { - if (codePoint <= 0xffff) { - return String.fromCharCode(codePoint); - } - codePoint -= 0x10000; - return String.fromCharCode(((codePoint >> 10) & 0x3ff) + 0xd800, (codePoint & 0x3ff) + 0xdc00); - }) - .join(''); -} -/** - * Returns the string represented by the UTF-8 data `bytes`. - * - * When `onError` function is specified, it is called on UTF-8 errors allowing recovery using the - * {@link Utf8ErrorFunc | **Utf8ErrorFunc**} API. (default: [error](Utf8ErrorFuncs)) - * - * @category Encoding - * @param {BytesLike} bytes - The UTF-8 data to convert. - * @param {Utf8ErrorFunc} [onError] - The error handling function. - * - * @returns {string} The string. - */ -function toUtf8String(bytes, onError) { - return _toUtf8String(getUtf8CodePoints(bytes, onError)); -} - -// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size. -// It's called a sponge function. -// Various per round constants calculations -const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []]; -const _0n = /* @__PURE__ */ BigInt(0); -const _1n = /* @__PURE__ */ BigInt(1); -const _2n = /* @__PURE__ */ BigInt(2); -const _7n = /* @__PURE__ */ BigInt(7); -const _256n = /* @__PURE__ */ BigInt(256); -const _0x71n = /* @__PURE__ */ BigInt(0x71); -for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { - // Pi - [x, y] = [y, (2 * x + 3 * y) % 5]; - SHA3_PI.push(2 * (5 * y + x)); - // Rotational - SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); - // Iota - let t = _0n; - for (let j = 0; j < 7; j++) { - R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; - if (R & _2n) - t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n); - } - _SHA3_IOTA.push(t); -} -const [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); -// Left rotation (without 0, 32, 64) -const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); -const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); -// Same as keccakf1600, but allows to skip some rounds -function keccakP(s, rounds = 24) { - const B = new Uint32Array(5 * 2); - // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) - for (let round = 24 - rounds; round < 24; round++) { - // Theta θ - for (let x = 0; x < 10; x++) - B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; - for (let x = 0; x < 10; x += 2) { - const idx1 = (x + 8) % 10; - const idx0 = (x + 2) % 10; - const B0 = B[idx0]; - const B1 = B[idx0 + 1]; - const Th = rotlH(B0, B1, 1) ^ B[idx1]; - const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; - for (let y = 0; y < 50; y += 10) { - s[x + y] ^= Th; - s[x + y + 1] ^= Tl; - } - } - // Rho (ρ) and Pi (π) - let curH = s[2]; - let curL = s[3]; - for (let t = 0; t < 24; t++) { - const shift = SHA3_ROTL[t]; - const Th = rotlH(curH, curL, shift); - const Tl = rotlL(curH, curL, shift); - const PI = SHA3_PI[t]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = Th; - s[PI + 1] = Tl; - } - // Chi (χ) - for (let y = 0; y < 50; y += 10) { - for (let x = 0; x < 10; x++) - B[x] = s[y + x]; - for (let x = 0; x < 10; x++) - s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; - } - // Iota (ι) - s[0] ^= SHA3_IOTA_H[round]; - s[1] ^= SHA3_IOTA_L[round]; - } - B.fill(0); -} -class Keccak extends Hash { - // NOTE: we accept arguments in bytes instead of bits here. - constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { - super(); - this.blockLen = blockLen; - this.suffix = suffix; - this.outputLen = outputLen; - this.enableXOF = enableXOF; - this.rounds = rounds; - this.pos = 0; - this.posOut = 0; - this.finished = false; - this.destroyed = false; - // Can be passed from user as dkLen - number(outputLen); - // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes - if (0 >= this.blockLen || this.blockLen >= 200) - throw new Error('Sha3 supports only keccak-f1600 function'); - this.state = new Uint8Array(200); - this.state32 = u32(this.state); - } - keccak() { - keccakP(this.state32, this.rounds); - this.posOut = 0; - this.pos = 0; - } - update(data) { - exists(this); - const { blockLen, state } = this; - data = toBytes(data); - const len = data.length; - for (let pos = 0; pos < len;) { - const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0; i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); - } - return this; - } - finish() { - if (this.finished) - return; - this.finished = true; - const { state, suffix, pos, blockLen } = this; - // Do the padding - state[pos] ^= suffix; - if ((suffix & 0x80) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 0x80; - this.keccak(); - } - writeInto(out) { - exists(this, false); - bytes(out); - this.finish(); - const bufferOut = this.state; - const { blockLen } = this; - for (let pos = 0, len = out.length; pos < len;) { - if (this.posOut >= blockLen) - this.keccak(); - const take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; - } - return out; - } - xofInto(out) { - // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF - if (!this.enableXOF) - throw new Error('XOF is not possible for this instance'); - return this.writeInto(out); - } - xof(bytes) { - number(bytes); - return this.xofInto(new Uint8Array(bytes)); - } - digestInto(out) { - output(out, this); - if (this.finished) - throw new Error('digest() was already called'); - this.writeInto(out); - this.destroy(); - return out; - } - digest() { - return this.digestInto(new Uint8Array(this.outputLen)); - } - destroy() { - this.destroyed = true; - this.state.fill(0); - } - _cloneInto(to) { - const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); - to.state32.set(this.state32); - to.pos = this.pos; - to.posOut = this.posOut; - to.finished = this.finished; - to.rounds = rounds; - // Suffix can change in cSHAKE - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.destroyed = this.destroyed; - return to; - } -} -const gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); -/** - * keccak-256 hash function. Different from SHA3-256. - * @param message - that would be hashed - */ -const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8); - -/** - * Cryptographic hashing functions - */ -let locked = false; -const _keccak256 = function (data) { - return keccak_256(data); -}; -let __keccak256 = _keccak256; -/** - * Compute the cryptographic KECCAK256 hash of `data`. - * - * The `data` **must** be a data representation, to compute the hash of UTF-8 data use the [**id**}(../functions/id) - * function. - * - * @category Crypto - * @example - * - * ```ts - * keccak256('0x'); - * - * keccak256('0x1337'); - * - * keccak256(new Uint8Array([0x13, 0x37])); - * - * // Strings are assumed to be DataHexString, otherwise it will - * // throw. To hash UTF-8 data, see the note above. - * keccak256('Hello World'); - * ``` - * - * @param {BytesLike} _data - The data to hash. - * @returns DataHexstring - * @returns {string} The hash of the data. - */ -function keccak256(_data) { - const data = getBytes(_data, 'data'); - return hexlify(__keccak256(data)); -} -keccak256._ = _keccak256; -keccak256.lock = function () { - locked = true; -}; -keccak256.register = function (func) { - if (locked) { - throw new TypeError('keccak256 is locked'); - } - __keccak256 = func; -}; -Object.freeze(keccak256); - -/** - * A simple hashing function which operates on UTF-8 strings to compute an 32-byte identifier. - * - * This simply computes the {@link toUtf8Bytes | **UTF-8 bytes**} and computes the {@link keccak256 | **keccak256**}. - * - * @category Hash - * @example - * - * ```ts - * id('hello world'); - * ``` - * - * @param {string} value - The string to hash. - * @returns {string} The 32-byte identifier. - */ -function id(value) { - return keccak256(toUtf8Bytes(value)); -} - -const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; -const Word = /^[a-z]*$/i; -function unfold(words, sep) { - let initial = 97; - return words.reduce((accum, word) => { - if (word === sep) { - initial++; - } - else if (word.match(Word)) { - accum.push(String.fromCharCode(initial) + word); - } - else { - initial = 97; - accum.push(word); - } - return accum; - }, []); -} -/** - * @ignore - */ -function decode(data, subs) { - // Replace all the substitutions with their expanded form - for (let i = subsChrs.length - 1; i >= 0; i--) { - data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); - } - // Get all tle clumps; each suffix, first-increment and second-increment - const clumps = []; - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word) => { - if (semi) { - for (let i = parseInt(semi); i >= 0; i--) { - clumps.push(';'); - } - } - else { - clumps.push(item.toLowerCase()); - } - return ''; - }); - /* c8 ignore start */ - if (leftover) { - throw new Error(`leftovers: ${JSON.stringify(leftover)}`); - } - /* c8 ignore stop */ - return unfold(unfold(clumps, ';'), ':'); -} -/** - * @ignore - */ -function decodeOwl(data) { - assertArgument(data[0] === '0', 'unsupported auwl data', 'data', data); - return decode(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); -} - -/** - * A Wordlist represents a collection of language-specific words used to encode and devoce - * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) encoded data by mapping words to 11-bit values and vice versa. - * - * @category Wordlists - */ -class Wordlist { - locale; - /** - * Creates a new Wordlist instance. - * - * Sub-classes MUST call this if they provide their own constructor, passing in the locale string of the language. - * - * Generally there is no need to create instances of a Wordlist, since each language-specific Wordlist creates an - * instance and there is no state kept internally, so they are safe to share. - */ - constructor(locale) { - defineProperties(this, { locale }); - } - /** - * Sub-classes may override this to provide a language-specific method for spliting `phrase` into individual words. - * - * By default, `phrase` is split using any sequences of white-space as defined by regular expressions (i.e. - * `/\s+/`). - * - * @param {string} phrase - The phrase to split. - * - * @returns {string[]} The split words in the phrase. - */ - split(phrase) { - return phrase.toLowerCase().split(/\s+/g); - } - /** - * Sub-classes may override this to provider a language-specific method for joining `words` into a phrase. - * - * By default, `words` are joined by a single space. - * - * @param {string[]} words - The words to join. - * - * @returns {string} The joined phrase. - */ - join(words) { - return words.join(' '); - } -} - -// Use the encode-latin.js script to create the necessary -// data files to be consumed by this class -/** - * An OWL format Wordlist is an encoding method that exploits the general locality of alphabetically sorted words to - * achieve a simple but effective means of compression. - * - * This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages - * based on ASCII-7 small. - * - * If necessary, there are tools within the `generation/` folder to create the necessary data. - * - * @category Wordlists - */ -class WordlistOwl extends Wordlist { - #data; - #checksum; - /** - * Creates a new Wordlist for `locale` using the OWL `data` and validated against the `checksum`. - */ - constructor(locale, data, checksum) { - super(locale); - this.#data = data; - this.#checksum = checksum; - this.#words = null; - } - /** - * The OWL-encoded data. - * - * @ignore - */ - get _data() { - return this.#data; - } - /** - * Decode all the words for the wordlist. - */ - _decodeWords() { - return decodeOwl(this.#data); - } - #words; - #loadWords() { - if (this.#words == null) { - const words = this._decodeWords(); - // Verify the computed list matches the official list - const checksum = id(words.join('\n') + '\n'); - /* c8 ignore start */ - if (checksum !== this.#checksum) { - throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); - } - /* c8 ignore stop */ - this.#words = words; - } - return this.#words; - } - getWord(index) { - const words = this.#loadWords(); - assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, 'index', index); - return words[index]; - } - getWordIndex(word) { - return this.#loadWords().indexOf(word); - } -} - -const words$4 = "0itatkastcenaovo$taouleraeki&chor*teci%enbalodaeladet'!Chn=0Di#%E%^1Resa2Rese3CeT'#0EjKohol0Pu)%0A&sDul#Ekdo)Ke)Ti#Ul|3}aOgan%0FaltI$@tPi,%TmaTronom0LasL{i#Ol0Tobus4Yl:B#}R'?TaUb_U/!U^U+Ur!Xer2A^v#Ambo,An#AtrEp)Ike)KoLohOnzOskevUn{#Usin#Z^Zy2Bl.Bn|})D _D#D'aF{Jar(Kv?LdokLvaN^NkrRzaTikVolZola3D+tL.T'#0Ukot:PartRev&3DrDu+J/JnLaLerLkemLn?N.Nn(N'#NtrumNzZ(2O&2KolivUv!4It_N(0Dn(Ke)KrPot0Ak~AlIkRkot2Kli$a:L-oRe[T_Tum1E,1B!a}'#Cib_Fic Fla%KlKr{Mokr!PreseRbyS#T-tiv3Kob,zKt|O^P]mSkSp+jV`]Vo/2AhaOuhoUhopis1Es0BroByt-C@t}ut DnesH+dHo^H,JemJn?Kl`KolaKtAzeDolObn(OgerieOzdSn(T Z(2B@}'noD-HaH'#S SnoT(0Oj?Or>2Nam :9O]gOnomie0EktronIpsa0AilIseO%P!ie2Izo^O/aOpejOs2EjEn%K<)Kymo0Ike)0FR&S]Zky3StOhOup(T!Ub.U/o)0AtO)Yz0IsOjivoOut0Bl.Boj}DinyDl!Dno)D|Jn(KejLin#L#LubMo+N [No,%RalR^RizontRkoRliv>RmonRn.RoskopR$voSpo^St.T'(U[UfUp!Us#V<2Ad[An?Av(Az^Bo+kD.D]D(N-Ob#Oma^OtOu^Oz@St#Ub(Yz!2B@(B~D[KotMrS aSto)0Ozd2Bn(D,ntGie&M&Sterik:2Yl#3Ned2O&0Uze0Un a0F-%Fla%KasoOva%Sp-%Tern{Vali^Ve$N)rRmarkRoSanSnoT#VD+Dn!_HlanKotL@L oMn(NomP?S{erV Zd>Zero3NakNdyNo/Sk,Sto)Trn?Zva3En|1Gurt5R):Bar{B_Bin{}&D{Did]HanJakJu)KaoKtusLam aLhotyLibrLn(Me,MkolivM&Ni[lNoeNtB#BlihaBylaC*rH=J@>KosKtejlLapsLe^LizeLoMandoMe)MikMn!aMo,MpasMun aN!N%ptNd?N>NfeseNgresN.NkursN)ktNzervaPan>PieP~Pr'#Rb_R-tSt#T_T+)T*lUk!Up_&Us-Uz]VbojZaZMe+cMivoOcanOkOni#Op OupaOv#T-Uh`]Up?Ut(Vin#Y/+Yp)Y$alYt2Dlan#FrJn(KlaLaj^Li/L#Lom{Ltu,NaPodivuRtRzV`]:B,d<})nDn(IkKom>M_aMpaN'#S?SoStu,Tin#V.3B#CkdyD@Dn?D'#Dv.G@^GieG,%H%Hk(H~KtvarNo/odNtil#P@#Pid]T`]T>TmoTokruhVhartV a%Vobok3B,}ot#DojedDsk(H'.Jav>L-M{#NieN#No+umStop`T.T|5Bi$aDivodGi#GopedKal aK{Mc|P!aPu/RdSosTrU^lUhU#Usk!V>3Tiv(1Cer&CiferMpSkSt,%0I%2RaRi#S.:DamD]Gi$rHagonJ{-J _J< aKakK'?Kr_aL[L.L|Lv?Min#Nd+NkoRn(SakrSkotSopu$T?Tri#Tur aZan>ZivoZl Zur#2Lo[0}anikD a%D'.LasaL*nNtol#TlaTo^TrZe,3G,%H~Hu+K.KrofonL@>Lim{rL(Mi#Nc'&Ni[rNom{Nul(S#StrX|2Ad(HaH'.OkS!Uv 1I/Ohem0BilCn(D_#Dl [HylaKroL-ulaM@t#Nar/aNoklN$rumNt|NzunSazSkytStTiva%T<#Ty#U/aUdr(Zai#Z-Zol2AmKevTvolaZ{Zut(0T _1DrcF]nL!MieN?S{Ta%ZeumZi#nt3Sliv>0Da:B*r!}yt!Da%Dbyt-DhozDobroDpisHlasHn!Hodi+H,d Iv aJedn*Ji$oJm=K]n Kon>Krm LevoMaz!Mluv Nom{rOkoOpakO$roP`!PevnoPln P~Pos+dPr(oRod RubyRy/]S` S-!S+poSt!TolikV@-Vr/VzdR&Ru[RysSahSluhaS)r!UvVazVin VodVyk+Yv!_Z<0AsElEn Hl` Ho)H,&It~0BojByt}odCiz Ebr!Esl!Evzd!EzvaH`%Hod J{JinudKazK*p LivLu#Ml#Oln(P`PisPl=PLivoLu[Mf+tMls-N@#Ni#N&N|N$voNtof+Pri#Rke)RodieR)Ru#Ry[Se#Siv aSt_#T@tTro&V*kZnehtZ*r-3C#DagogJs-K]LotonNal)Ndr-NzeRiskopRoStr(Tar^T?Tro+jVn.Xeso3Ani$aHaJav?K+KnikL.Ln(Lul#Nze)Pe)S!_Sto+Tev&Vn?V'ar2A%n)Ak!Am@Ane)A$i#At Avid]AzE/Em@oEn)EsEtivoEv_Iv!N NoO/aOd.Om[OutUkYn2Bav Byt}odC Ctiv>D!D%n Deps!Dh+dDiv Dkl`Dman DnikDo[Dpo,D,zD$!aDvodDzimEzieHan#Hnut#H'S*d SpoluS)vaSud-SypTahT#nT+skTom-T,vaTupaTvo,U#zUtoUzdroVahaVidlaVlakVozVr/V$!VykVzde/Zd,vZem-Zn!-ZAp<-AseAv^IncipKnoObud O%ntoOdejOfeseOh,Oj-tO]m Omi+Onik!Op`OrokOs[OtonOut-OvazS#v#St@Udk(UtV-VohOvodTruh0Actvo0Ber)}DlKav>Kl.Kr+LtMpaNcP@SaSin#St.T|Ty#3Rami^SkT_::C-}otDia%Dn?DonFtGbyKe)K'.M@oMp*/NdeRa/R aS'&StrTo+$Zan%Zid]3Ag|Ak%CeptDaktMizd!Mo)N #Rdin#San#T_ Z[Z@?0Or0H|1B,n#CeseD`]Dim@tD]Hn!Jm=Ke,K)Kun^KvojeM@oNoRvisS` Sho,SkokSl!St,SuvSyp!T[T.Tk!T~Trv!VerZ&m2O^R~0FonLn?R#Rot-RupTua%1AfandrAliskoAnz@AutEptikIcaL`[L@?LoLuzO[O#nOroRip)RzUp.V(Vr&0Abi#Adid]An.A$Avn(Ed|Ep>EvaEz.IbI&Izn?OnOup-OvoU/UhaUn%Up#Za0A,gdE)&Il$voL*vaOgR`RkRt#Ut-Ysl0AdAhaOb0Bo)}aD'#KolP#TvaUbojUc Ud%UhlasUl`Um,kUp,vaUsedUtokUvis{0Al'&As _IsLavOd-Oj@>OluOnzOvn!P@StUb1An?Ar(aAti#Av[EhnoEz#OdolaO+kOpaOrnoOup!Ra/ResRh~RomRu&Ud&Upn?VolYk0Bj-tBtropy}arD(KnoNd!N=Rik!aR'.0AhAl$voEtrAt[Az-Is+It-Obo^Odid]Or#Rab2Kav#KotN-N'>P!Pk(R'(S_T(:B+t#Bu+H*nJemnoJfunJgaJ Jn(Kti#Mh+MponNc|N>NkerPe)V@.Z!_3}ni#HdyKut.LefonMno)Nd@%Ni$aNU/l Uhl?UsV!2DyH~H(Nd,Ri$aR&jZemsko0ArohOr[Rd(Rz2GrKev:0Oh(OzeR!R*s-RusYt'&0HoTiv(0Iv 3R` 1Edn!I$ M=0Az!_Lidn Lon Otv Roj 0I%I)Ov 0Yv`]0Av IfR*s 1Al Oln Oz'#3D,v ElEn.L.N!:GonL/aL*nNaN^lNil#RanRhanyR|1ElkuHod0Ova0DroGe)%J%Lbl*dL{rhL _LmocLry[Nk'Ran^RzeS_#SkrzeSn?SpoduS)Ter.Ver#3B,%}rDeoh,D.D+LaN?S{Tal aZeZ #0Ezd0L`Us0Aj#AkAs>EvoHk(IvN'#Oup!1Uc|Uk0DaDiv(Doz&kD$voJ@skyJ&JskoLantL[L LnoSk'#Zid]Z'&0Ravo1Ab>A%tAhA)Ba}o+kH!StvaTu+0Ad T*p Tup0Ip4Bav Br!}|D!D,Fot H+d!H~Hod H,d Hub Jasn J{Jm=K]p Kon!L-!Maz!Mez Miz{Mys+tNe/!Nik!Nut P`!Pl! P,v Pu$ Raz R'n!Rv!Sl' SokoS)v Su~Syp!Tas Tes!Tr! Vi~Vol!Vrh_Zdob Zn!0AduBud }op DJ{Ji$ K+p!K*p Lep Mez Mot!Mys+tNe/!Nik!Pl! Poj Ps!Raz S)v Su~Taj Temn Tk~Ujm=Val Ve+tVin Vol!Vrt!Zvon 0Av RusuUd|Yt-1A+#ArmaAtn(IvoOb RojVihYm`]0L@.ManM.Pt!Z`uZdola2At Lt~Lubo#Ot' Ru[0MaMn?0Emn 0Lam!Oum!R!#Umav#0AtoEh#O[OmO$Ozvyk0Ap|ArAt-IjeIz{Ocn Odr!Rzl.Ut|0AkAl(Am@!Ovu0B,z Tav Ub-Ufa+0Lod Omal RavaR( Rud#Rvu1A^An C`]N (NoOv&Y/l Zav(1I/aR! 0B'.Br0Ed~EnkuEs_aOnR!Uk'odYk"; -const checksum$4 = '0x25f44555f4af25b51a711136e1c7d6e50ce9f8917d39d6b1f076b2bb4d2fac1a'; -let wordlist$6 = null; -/** - * The [Czech wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/czech.txt) for [mnemonic - * phrases](https://en.bitcoin.it/wiki/BIP_0039). - */ -class LangCz extends WordlistOwl { - /** - * Creates a new instance of the Czech language Wordlist. - * - * Using the constructor should be unnecessary, instead use the {@link wordlist | **wordlist**} singleton method. - * - * @ignore - */ - constructor() { - super('cz', words$4, checksum$4); - } - /** - * Returns a singleton instance of a `LangCz`, creating it if this is the first time being called. - */ - static wordlist() { - if (wordlist$6 == null) { - wordlist$6 = new LangCz(); - } - return wordlist$6; - } -} - -const Base64 = ')!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'; -/** - * @ignore - */ -function decodeBits(width, data) { - const maxValue = (1 << width) - 1; - const result = []; - let accum = 0, bits = 0, flood = 0; - for (let i = 0; i < data.length; i++) { - // Accumulate 6 bits of data - accum = (accum << 6) | Base64.indexOf(data[i]); - bits += 6; - // While we have enough for a word... - while (bits >= width) { - // ...read the word - const value = accum >> (bits - width); - accum &= (1 << (bits - width)) - 1; - bits -= width; - // A value of 0 indicates we exceeded maxValue, it - // floods over into the next value - if (value === 0) { - flood += maxValue; - } - else { - result.push(value + flood); - flood = 0; - } - } - } - return result; -} - -/** - * @ignore - */ -function decodeOwlA(data, accents) { - let words = decodeOwl(data).join(','); - // Inject the accents - accents.split(/,/g).forEach((accent) => { - const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); - assertArgument(match !== null, 'internal error parsing accents', 'accents', accents); - let posOffset = 0; - const positions = decodeBits(parseInt(match[3]), match[4]); - const charCode = parseInt(match[2]); - const regex = new RegExp(`([${match[1]}])`, 'g'); - words = words.replace(regex, (all, letter) => { - const rem = --positions[posOffset]; - if (rem === 0) { - letter = String.fromCharCode(letter.charCodeAt(0), charCode); - posOffset++; - } - return letter; - }); - }); - return words.split(','); -} - -/** - * An OWL-A format Wordlist extends the OWL format to add an overlay onto an OWL format Wordlist to support diacritic - * marks. - * - * This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages - * based on latin-1 small. - * - * If necessary, there are tools within the `generation/` folder to create the necessary data. - * - * @category Wordlists - */ -class WordlistOwlA extends WordlistOwl { - #accent; - /** - * Creates a new Wordlist for `locale` using the OWLA `data` and `accent` data and validated against the `checksum`. - */ - constructor(locale, data, accent, checksum) { - super(locale, data, checksum); - this.#accent = accent; - } - /** - * The OWLA-encoded accent data. - * - * @ignore - */ - get _accent() { - return this.#accent; - } - /** - * Decode all the words for the wordlist. - * - * @ignore - */ - _decodeWords() { - return decodeOwlA(this._data, this._accent); - } -} - -const words$3 = "0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_LoAmpuAnc]ApaAr]I>Is)IvoOqueOzaUle%Up 0Cl.EgoE=EnEr#F[G +M->NeN%P_sR>Rue]SneTaU{d2Am^AnA+AseAveI,)ImaInica2B_Cc~|i'Ci`CoDigoDoF_G!He)JinJoL/ch/eg$Lg Lin/l LmoLum`Mba)M!Mi{Mo&Mpr-deNej}g-oc!Nsej}t PaPi(az.Rba%RchoR&nR.(r!S!SmosS%2AneoAt!E Ec!Ei&EmaIaIm,Ip%IsisOmoOnicaOque%U&Uz2Ad+Ar#At+BoBr*| aEl=En#Er{Es%EvaId Lebr/p/#Mb_Mpl*N-e%O%P.Pul( R$Se'Sf[zVaVi'5BleCeL^Ming}N Ra&Rm*RAu%EchaOrO%U*UjoU^2B@CaGa%G.L$Lle#N&Rm(+Rtun(z SaTo2AcaA'AsaAtisAveIe%Il=IpeIsI#OG Gu!aJaMb_Ng}^Nr((mig('St?Yo5E>ElgaEr%ENgl-$Nt Pit!R S#V,?Zg :7Lo5A]:B$C$C[DoD+nG #GrimaGu`I>M!Mi`Mp --ch-gos%NzaPizRgoRvaStimaTaTexT*U_lV Zo3AlCc~|eC#rErG~Gumb_Ja'Ngu-#NaOnOp &S~TalT[VeY,{3B!%dB+C^D!Di EnzoGaG!oMaMi)M.Mp$NceN&Ne-go)N}t!`Qui&SoS%T!aT$T+2AgaAmaAn#AveEg En Ev Or Ov!Uv@2BoC~CoCu[GicaG+MbrizM}jaTe5|aC*G J}-esPaSt+ToZ:Ce%|oD!aD_Du+Est+F@G@GoIzL{dLe%Ll/oMaMboMutN>N&Nej Ng-iquiNj N}Re(f?Rg,Ri&RmolR+nR)sRzoSaSc aSivoT T!@TizTrizXimoY^Z^ca3|aDal]D$Du]J?]J^L,/.M^i-^NsajeN)NuRca&R,gueRi#SS.TaT!To&T+Zc]3E&ElEmb+G/Lag+Lit Ll.M}-!}im}u#OpeR SaS!@S?SmoTadTo5|?aC~DaDe=HoJ LdeL!Li'M,#Mi- c-ed-j-#NoRad(d!Re'R*R+Rs(%lScaStr TivoV!V?Zo5|oD EbleE]Er)Est[G_J!L/e%L%N&Nec(alRoScu=SeoSgoSicaS=:C C~D IpeRanj(izRr SalTalTivoTu[lUseaValVeVi{d3C$Ct G Goc$G+OnRv$ToUt+V V!a3|oDoEb]E#NezNoTi&Vel5Bleza|eMin(i(m()TaTic@Va#Ve]V$5BeCaCleoD?=DoE[EveEzLoM!oTr@:Sis0EC~E[In On!T TicaUes#1Ac~A&rAlBi%CaD,EjaGa'G@Gul=I,)Ig,Il]OQues%Uga0Ad@Cu+Ez'OT[0O'Ro1EjaU=1I&Ige'0En)0O':C#D_El]Gi`GoIsJ oLabr/>Le%Li&Lm/om/p NNalNi>Nt!-ue=PaPelP?]Que)R Rcel(edR*RoRpa&RqueR[foR)S SeoS~SoS%TaT$Tr@UsaU%VoYa<3A#nCa&C!a|oDalD*G IneL L{'Le/ig+LlejoLoLuc--s N.OnOrPi'Que'R(ch(d!Rez(f?Ri>Rl(mizEgun%Em$EnsaE|!oD^Eb=Er%Es#Lg/*Lm.LpoLrNd*N%P #Pet*PoN{PaP!oSaScaSt+T 5BiB^DoE{G*I&In/e%LoMboM^Ptu[TaTi`:Ba&B!B$BleC GazG[&L/&L!oL*Lm.L.Ls/#LudLv Mb-c~Ndi-e Ng_Ni{dN}#PoQueRdin()nSt_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv! b) { - return 1; - } - return 0; - } - // Load all the words - for (let length = 3; length <= 9; length++) { - const d = data$2[length - 3]; - for (let offset = 0; offset < d.length; offset += length) { - const word = []; - for (let i = 0; i < length; i++) { - const k = mapping.indexOf(d[offset + i]); - word.push(227); - word.push(k & 0x40 ? 130 : 129); - word.push((k & 0x3f) + 128); - } - wordlist.push(toString(word)); - } - } - wordlist.sort(sortJapanese); - // For some reason kyoku and kiyoku are flipped in node (!!). - // The order SHOULD be: - // - kyoku - // - kiyoku - // This should ignore "if", but that doesn't work here?? - /* c8 ignore start */ - if (hex(wordlist[442]) === KiYoKu && hex(wordlist[443]) === KyoKu) { - const tmp = wordlist[442]; - wordlist[442] = wordlist[443]; - wordlist[443] = tmp; - } - /* c8 ignore stop */ - // Verify the computed list matches the official list - /* istanbul ignore if */ - const checksum = id(wordlist.join('\n') + '\n'); - /* c8 ignore start */ - if (checksum !== '0xcb36b09e6baa935787fd762ce65e80b0c6a8dabdfbc3a7f86ac0e2c4fd111600') { - throw new Error('BIP39 Wordlist for ja (Japanese) FAILED'); - } - /* c8 ignore stop */ - _wordlist$2 = wordlist; - return wordlist; -} -let wordlist$3 = null; -/** - * The [Japanese wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/japanese.txt) for [mnemonic - * phrases](https://en.bitcoin.it/wiki/BIP_0039). - */ -class LangJa extends Wordlist { - /** - * Creates a new instance of the Japanese language Wordlist. - * - * This should be unnecessary most of the time as the exported {@link langJa} should suffice. - * - * @ignore - */ - constructor() { - super('ja'); - } - getWord(index) { - const words = loadWords$2(); - assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, 'index', index); - return words[index]; - } - getWordIndex(word) { - return loadWords$2().indexOf(word); - } - split(phrase) { - //logger.assertNormalize(); - return phrase.split(/(?:\u3000| )+/g); - } - join(words) { - return words.join('\u3000'); - } - /** - * Returns a singleton instance of a `LangJa`, creating it if this is the first time being called. - */ - static wordlist() { - if (wordlist$3 == null) { - wordlist$3 = new LangJa(); - } - return wordlist$3; - } -} - -const data$1 = [ - 'OYAa', - 'ATAZoATBl3ATCTrATCl8ATDloATGg3ATHT8ATJT8ATJl3ATLlvATLn4ATMT8ATMX8ATMboATMgoAToLbAToMTATrHgATvHnAT3AnAT3JbAT3MTAT8DbAT8JTAT8LmAT8MYAT8MbAT#LnAUHT8AUHZvAUJXrAUJX8AULnrAXJnvAXLUoAXLgvAXMn6AXRg3AXrMbAX3JTAX3QbAYLn3AZLgvAZrSUAZvAcAZ8AaAZ8AbAZ8AnAZ8HnAZ8LgAZ8MYAZ8MgAZ8OnAaAboAaDTrAaFTrAaJTrAaJboAaLVoAaMXvAaOl8AaSeoAbAUoAbAg8AbAl4AbGnrAbMT8AbMXrAbMn4AbQb8AbSV8AbvRlAb8AUAb8AnAb8HgAb8JTAb8NTAb8RbAcGboAcLnvAcMT8AcMX8AcSToAcrAaAcrFnAc8AbAc8MgAfGgrAfHboAfJnvAfLV8AfLkoAfMT8AfMnoAfQb8AfScrAfSgrAgAZ8AgFl3AgGX8AgHZvAgHgrAgJXoAgJX8AgJboAgLZoAgLn4AgOX8AgoATAgoAnAgoCUAgoJgAgoLXAgoMYAgoSeAgrDUAgrJTAhrFnAhrLjAhrQgAjAgoAjJnrAkMX8AkOnoAlCTvAlCV8AlClvAlFg4AlFl6AlFn3AloSnAlrAXAlrAfAlrFUAlrFbAlrGgAlrOXAlvKnAlvMTAl3AbAl3MnAnATrAnAcrAnCZ3AnCl8AnDg8AnFboAnFl3AnHX4AnHbrAnHgrAnIl3AnJgvAnLXoAnLX4AnLbrAnLgrAnLhrAnMXoAnMgrAnOn3AnSbrAnSeoAnvLnAn3OnCTGgvCTSlvCTvAUCTvKnCTvNTCT3CZCT3GUCT3MTCT8HnCUCZrCULf8CULnvCU3HnCU3JUCY6NUCbDb8CbFZoCbLnrCboOTCboScCbrFnCbvLnCb8AgCb8HgCb$LnCkLfoClBn3CloDUDTHT8DTLl3DTSU8DTrAaDTrLXDTrLjDTrOYDTrOgDTvFXDTvFnDT3HUDT3LfDUCT9DUDT4DUFVoDUFV8DUFkoDUGgrDUJnrDULl8DUMT8DUMXrDUMX4DUMg8DUOUoDUOgvDUOg8DUSToDUSZ8DbDXoDbDgoDbGT8DbJn3DbLg3DbLn4DbMXrDbMg8DbOToDboJXGTClvGTDT8GTFZrGTLVoGTLlvGTLl3GTMg8GTOTvGTSlrGToCUGTrDgGTrJYGTrScGTtLnGTvAnGTvQgGUCZrGUDTvGUFZoGUHXrGULnvGUMT8GUoMgGXoLnGXrMXGXrMnGXvFnGYLnvGZOnvGZvOnGZ8LaGZ8LmGbAl3GbDYvGbDlrGbHX3GbJl4GbLV8GbLn3GbMn4GboJTGboRfGbvFUGb3GUGb4JnGgDX3GgFl$GgJlrGgLX6GgLZoGgLf8GgOXoGgrAgGgrJXGgrMYGgrScGgvATGgvOYGnAgoGnJgvGnLZoGnLg3GnLnrGnQn8GnSbrGnrMgHTClvHTDToHTFT3HTQT8HToJTHToJgHTrDUHTrMnHTvFYHTvRfHT8MnHT8SUHUAZ8HUBb4HUDTvHUoMYHXFl6HXJX6HXQlrHXrAUHXrMnHXrSbHXvFYHXvKXHX3LjHX3MeHYvQlHZrScHZvDbHbAcrHbFT3HbFl3HbJT8HbLTrHbMT8HbMXrHbMbrHbQb8HbSX3HboDbHboJTHbrFUHbrHgHbrJTHb8JTHb8MnHb8QgHgAlrHgDT3HgGgrHgHgrHgJTrHgJT8HgLX@HgLnrHgMT8HgMX8HgMboHgOnrHgQToHgRg3HgoHgHgrCbHgrFnHgrLVHgvAcHgvAfHnAloHnCTrHnCnvHnGTrHnGZ8HnGnvHnJT8HnLf8HnLkvHnMg8HnRTrITvFUITvFnJTAXrJTCV8JTFT3JTFT8JTFn4JTGgvJTHT8JTJT8JTJXvJTJl3JTJnvJTLX4JTLf8JTLhvJTMT8JTMXrJTMnrJTObrJTQT8JTSlvJT8DUJT8FkJT8MTJT8OXJT8OgJT8QUJT8RfJUHZoJXFT4JXFlrJXGZ8JXGnrJXLV8JXLgvJXMXoJXMX3JXNboJXPlvJXoJTJXoLkJXrAXJXrHUJXrJgJXvJTJXvOnJX4KnJYAl3JYJT8JYLhvJYQToJYrQXJY6NUJbAl3JbCZrJbDloJbGT8JbGgrJbJXvJbJboJbLf8JbLhrJbLl3JbMnvJbRg8JbSZ8JboDbJbrCZJbrSUJb3KnJb8LnJfRn8JgAXrJgCZrJgDTrJgGZrJgGZ8JgHToJgJT8JgJXoJgJgvJgLX4JgLZ3JgLZ8JgLn4JgMgrJgMn4JgOgvJgPX6JgRnvJgSToJgoCZJgoJbJgoMYJgrJXJgrJgJgrLjJg6MTJlCn3JlGgvJlJl8Jl4AnJl8FnJl8HgJnAToJnATrJnAbvJnDUoJnGnrJnJXrJnJXvJnLhvJnLnrJnLnvJnMToJnMT8JnMXvJnMX3JnMg8JnMlrJnMn4JnOX8JnST4JnSX3JnoAgJnoAnJnoJTJnoObJnrAbJnrAkJnrHnJnrJTJnrJYJnrOYJnrScJnvCUJnvFaJnvJgJnvJnJnvOYJnvQUJnvRUJn3FnJn3JTKnFl3KnLT6LTDlvLTMnoLTOn3LTRl3LTSb4LTSlrLToAnLToJgLTrAULTrAcLTrCULTrHgLTrMgLT3JnLULnrLUMX8LUoJgLVATrLVDTrLVLb8LVoJgLV8MgLV8RTLXDg3LXFlrLXrCnLXrLXLX3GTLX4GgLX4OYLZAXrLZAcrLZAgrLZAhrLZDXyLZDlrLZFbrLZFl3LZJX6LZJX8LZLc8LZLnrLZSU8LZoJTLZoJnLZrAgLZrAnLZrJYLZrLULZrMgLZrSkLZvAnLZvGULZvJeLZvOTLZ3FZLZ4JXLZ8STLZ8ScLaAT3LaAl3LaHT8LaJTrLaJT8LaJXrLaJgvLaJl4LaLVoLaMXrLaMXvLaMX8LbClvLbFToLbHlrLbJn4LbLZ3LbLhvLbMXrLbMnoLbvSULcLnrLc8HnLc8MTLdrMnLeAgoLeOgvLeOn3LfAl3LfLnvLfMl3LfOX8Lf8AnLf8JXLf8LXLgJTrLgJXrLgJl8LgMX8LgRZrLhCToLhrAbLhrFULhrJXLhvJYLjHTrLjHX4LjJX8LjLhrLjSX3LjSZ4LkFX4LkGZ8LkGgvLkJTrLkMXoLkSToLkSU8LkSZ8LkoOYLl3FfLl3MgLmAZrLmCbrLmGgrLmHboLmJnoLmJn3LmLfoLmLhrLmSToLnAX6LnAb6LnCZ3LnCb3LnDTvLnDb8LnFl3LnGnrLnHZvLnHgvLnITvLnJT8LnJX8LnJlvLnLf8LnLg6LnLhvLnLnoLnMXrLnMg8LnQlvLnSbrLnrAgLnrAnLnrDbLnrFkLnrJdLnrMULnrOYLnrSTLnvAnLnvDULnvHgLnvOYLnvOnLn3GgLn4DULn4JTLn4JnMTAZoMTAloMTDb8MTFT8MTJnoMTJnrMTLZrMTLhrMTLkvMTMX8MTRTrMToATMTrDnMTrOnMT3JnMT4MnMT8FUMT8FaMT8FlMT8GTMT8GbMT8GnMT8HnMT8JTMT8JbMT8OTMUCl8MUJTrMUJU8MUMX8MURTrMUSToMXAX6MXAb6MXCZoMXFXrMXHXrMXLgvMXOgoMXrAUMXrAnMXrHgMXrJYMXrJnMXrMTMXrMgMXrOYMXrSZMXrSgMXvDUMXvOTMX3JgMX3OTMX4JnMX8DbMX8FnMX8HbMX8HgMX8HnMX8LbMX8MnMX8OnMYAb8MYGboMYHTvMYHX4MYLTrMYLnvMYMToMYOgvMYRg3MYSTrMbAToMbAXrMbAl3MbAn8MbGZ8MbJT8MbJXrMbMXvMbMX8MbMnoMbrMUMb8AfMb8FbMb8FkMcJXoMeLnrMgFl3MgGTvMgGXoMgGgrMgGnrMgHT8MgHZrMgJnoMgLnrMgLnvMgMT8MgQUoMgrHnMgvAnMg8HgMg8JYMg8LfMloJnMl8ATMl8AXMl8JYMnAToMnAT4MnAZ8MnAl3MnAl4MnCl8MnHT8MnHg8MnJnoMnLZoMnLhrMnMXoMnMX3MnMnrMnOgvMnrFbMnrFfMnrFnMnrNTMnvJXNTMl8OTCT3OTFV8OTFn3OTHZvOTJXrOTOl3OT3ATOT3JUOT3LZOT3LeOT3MbOT8ATOT8AbOT8AgOT8MbOUCXvOUMX3OXHXvOXLl3OXrMUOXvDbOX6NUOX8JbOYFZoOYLbrOYLkoOYMg8OYSX3ObHTrObHT4ObJgrObLhrObMX3ObOX8Ob8FnOeAlrOeJT8OeJXrOeJnrOeLToOeMb8OgJXoOgLXoOgMnrOgOXrOgOloOgoAgOgoJbOgoMYOgoSTOg8AbOjLX4OjMnoOjSV8OnLVoOnrAgOn3DUPXQlrPXvFXPbvFTPdAT3PlFn3PnvFbQTLn4QToAgQToMTQULV8QURg8QUoJnQXCXvQbFbrQb8AaQb8AcQb8FbQb8MYQb8ScQeAlrQeLhrQjAn3QlFXoQloJgQloSnRTLnvRTrGURTrJTRUJZrRUoJlRUrQnRZrLmRZrMnRZrSnRZ8ATRZ8JbRZ8ScRbMT8RbST3RfGZrRfMX8RfMgrRfSZrRnAbrRnGT8RnvJgRnvLfRnvMTRn8AaSTClvSTJgrSTOXrSTRg3STRnvSToAcSToAfSToAnSToHnSToLjSToMTSTrAaSTrEUST3BYST8AgST8LmSUAZvSUAgrSUDT4SUDT8SUGgvSUJXoSUJXvSULTrSU8JTSU8LjSV8AnSV8JgSXFToSXLf8SYvAnSZrDUSZrMUSZrMnSZ8HgSZ8JTSZ8JgSZ8MYSZ8QUSaQUoSbCT3SbHToSbQYvSbSl4SboJnSbvFbSb8HbSb8JgSb8OTScGZrScHgrScJTvScMT8ScSToScoHbScrMTScvAnSeAZrSeAcrSeHboSeJUoSeLhrSeMT8SeMXrSe6JgSgHTrSkJnoSkLnvSk8CUSlFl3SlrSnSl8GnSmAboSmGT8SmJU8', - 'ATLnDlATrAZoATrJX4ATrMT8ATrMX4ATrRTrATvDl8ATvJUoATvMl8AT3AToAT3MX8AT8CT3AT8DT8AT8HZrAT8HgoAUAgFnAUCTFnAXoMX8AXrAT8AXrGgvAXrJXvAXrOgoAXvLl3AZvAgoAZvFbrAZvJXoAZvJl8AZvJn3AZvMX8AZvSbrAZ8FZoAZ8LZ8AZ8MU8AZ8OTvAZ8SV8AZ8SX3AbAgFZAboJnoAbvGboAb8ATrAb8AZoAb8AgrAb8Al4Ab8Db8Ab8JnoAb8LX4Ab8LZrAb8LhrAb8MT8Ab8OUoAb8Qb8Ab8ST8AcrAUoAcrAc8AcrCZ3AcrFT3AcrFZrAcrJl4AcrJn3AcrMX3AcrOTvAc8AZ8Ac8MT8AfAcJXAgoFn4AgoGgvAgoGnrAgoLc8AgoMXoAgrLnrAkrSZ8AlFXCTAloHboAlrHbrAlrLhrAlrLkoAl3CZrAl3LUoAl3LZrAnrAl4AnrMT8An3HT4BT3IToBX4MnvBb!Ln$CTGXMnCToLZ4CTrHT8CT3JTrCT3RZrCT#GTvCU6GgvCU8Db8CU8GZrCU8HT8CboLl3CbrGgrCbrMU8Cb8DT3Cb8GnrCb8LX4Cb8MT8Cb8ObrCgrGgvCgrKX4Cl8FZoDTrAbvDTrDboDTrGT6DTrJgrDTrMX3DTrRZrDTrRg8DTvAVvDTvFZoDT3DT8DT3Ln3DT4HZrDT4MT8DT8AlrDT8MT8DUAkGbDUDbJnDYLnQlDbDUOYDbMTAnDbMXSnDboAT3DboFn4DboLnvDj6JTrGTCgFTGTGgFnGTJTMnGTLnPlGToJT8GTrCT3GTrLVoGTrLnvGTrMX3GTrMboGTvKl3GZClFnGZrDT3GZ8DTrGZ8FZ8GZ8MXvGZ8On8GZ8ST3GbCnQXGbMbFnGboFboGboJg3GboMXoGb3JTvGb3JboGb3Mn6Gb3Qb8GgDXLjGgMnAUGgrDloGgrHX4GgrSToGgvAXrGgvAZvGgvFbrGgvLl3GgvMnvGnDnLXGnrATrGnrMboGnuLl3HTATMnHTAgCnHTCTCTHTrGTvHTrHTvHTrJX8HTrLl8HTrMT8HTrMgoHTrOTrHTuOn3HTvAZrHTvDTvHTvGboHTvJU8HTvLl3HTvMXrHTvQb4HT4GT6HT4JT8HT4Jb#HT8Al3HT8GZrHT8GgrHT8HX4HT8Jb8HT8JnoHT8LTrHT8LgvHT8SToHT8SV8HUoJUoHUoJX8HUoLnrHXrLZoHXvAl3HX3LnrHX4FkvHX4LhrHX4MXoHX4OnoHZrAZ8HZrDb8HZrGZ8HZrJnrHZvGZ8HZvLnvHZ8JnvHZ8LhrHbCXJlHbMTAnHboJl4HbpLl3HbrJX8HbrLnrHbrMnvHbvRYrHgoSTrHgrFV8HgrGZ8HgrJXoHgrRnvHgvBb!HgvGTrHgvHX4HgvHn!HgvLTrHgvSU8HnDnLbHnFbJbHnvDn8Hn6GgvHn!BTvJTCTLnJTQgFnJTrAnvJTrLX4JTrOUoJTvFn3JTvLnrJTvNToJT3AgoJT3Jn4JT3LhvJT3ObrJT8AcrJT8Al3JT8JT8JT8JnoJT8LX4JT8LnrJT8MX3JT8Rg3JT8Sc8JUoBTvJU8AToJU8GZ8JU8GgvJU8JTrJU8JXrJU8JnrJU8LnvJU8ScvJXHnJlJXrGgvJXrJU8JXrLhrJXrMT8JXrMXrJXrQUoJXvCTvJXvGZ8JXvGgrJXvQT8JX8Ab8JX8DT8JX8GZ8JX8HZvJX8LnrJX8MT8JX8MXoJX8MnvJX8ST3JYGnCTJbAkGbJbCTAnJbLTAcJboDT3JboLb6JbrAnvJbrCn3JbrDl8JbrGboJbrIZoJbrJnvJbrMnvJbrQb4Jb8RZrJeAbAnJgJnFbJgScAnJgrATrJgvHZ8JgvMn4JlJlFbJlLiQXJlLjOnJlRbOlJlvNXoJlvRl3Jl4AcrJl8AUoJl8MnrJnFnMlJnHgGbJnoDT8JnoFV8JnoGgvJnoIT8JnoQToJnoRg3JnrCZ3JnrGgrJnrHTvJnrLf8JnrOX8JnvAT3JnvFZoJnvGT8JnvJl4JnvMT8JnvMX8JnvOXrJnvPX6JnvSX3JnvSZrJn3MT8Jn3MX8Jn3RTrLTATKnLTJnLTLTMXKnLTRTQlLToGb8LTrAZ8LTrCZ8LTrDb8LTrHT8LT3PX6LT4FZoLT$CTvLT$GgrLUvHX3LVoATrLVoAgoLVoJboLVoMX3LVoRg3LV8CZ3LV8FZoLV8GTvLXrDXoLXrFbrLXvAgvLXvFlrLXvLl3LXvRn6LX4Mb8LX8GT8LYCXMnLYrMnrLZoSTvLZrAZvLZrAloLZrFToLZrJXvLZrJboLZrJl4LZrLnrLZrMT8LZrOgvLZrRnvLZrST4LZvMX8LZvSlvLZ8AgoLZ8CT3LZ8JT8LZ8LV8LZ8LZoLZ8Lg8LZ8SV8LZ8SbrLZ$HT8LZ$Mn4La6CTvLbFbMnLbRYFTLbSnFZLboJT8LbrAT9LbrGb3LbrQb8LcrJX8LcrMXrLerHTvLerJbrLerNboLgrDb8LgrGZ8LgrHTrLgrMXrLgrSU8LgvJTrLgvLl3Lg6Ll3LhrLnrLhrMT8LhvAl4LiLnQXLkoAgrLkoJT8LkoJn4LlrSU8Ll3FZoLl3HTrLl3JX8Ll3JnoLl3LToLmLeFbLnDUFbLnLVAnLnrATrLnrAZoLnrAb8LnrAlrLnrGgvLnrJU8LnrLZrLnrLhrLnrMb8LnrOXrLnrSZ8LnvAb4LnvDTrLnvDl8LnvHTrLnvHbrLnvJT8LnvJU8LnvJbrLnvLhvLnvMX8LnvMb8LnvNnoLnvSU8Ln3Al3Ln4FZoLn4GT6Ln4JgvLn4LhrLn4MT8Ln4SToMToCZrMToJX8MToLX4MToLf8MToRg3MTrEloMTvGb6MT3BTrMT3Lb6MT8AcrMT8AgrMT8GZrMT8JnoMT8LnrMT8MX3MUOUAnMXAbFnMXoAloMXoJX8MXoLf8MXoLl8MXrAb8MXrDTvMXrGT8MXrGgrMXrHTrMXrLf8MXrMU8MXrOXvMXrQb8MXvGT8MXvHTrMXvLVoMX3AX3MX3Jn3MX3LhrMX3MX3MX4AlrMX4OboMX8GTvMX8GZrMX8GgrMX8JT8MX8JX8MX8LhrMX8MT8MYDUFbMYMgDbMbGnFfMbvLX4MbvLl3Mb8Mb8Mb8ST4MgGXCnMg8ATrMg8AgoMg8CZrMg8DTrMg8DboMg8HTrMg8JgrMg8LT8MloJXoMl8AhrMl8JT8MnLgAUMnoJXrMnoLX4MnoLhrMnoMT8MnrAl4MnrDb8MnrOTvMnrOgvMnrQb8MnrSU8MnvGgrMnvHZ8Mn3MToMn4DTrMn4LTrMn4Mg8NnBXAnOTFTFnOToAToOTrGgvOTrJX8OT3JXoOT6MTrOT8GgrOT8HTpOT8MToOUoHT8OUoJT8OUoLn3OXrAgoOXrDg8OXrMT8OXvSToOX6CTvOX8CZrOX8OgrOb6HgvOb8AToOb8MT8OcvLZ8OgvAlrOgvHTvOgvJTrOgvJnrOgvLZrOgvLn4OgvMT8OgvRTrOg8AZoOg8DbvOnrOXoOnvJn4OnvLhvOnvRTrOn3GgoOn3JnvOn6JbvOn8OTrPTGYFTPbBnFnPbGnDnPgDYQTPlrAnvPlrETvPlrLnvPlrMXvPlvFX4QTMTAnQTrJU8QYCnJlQYJlQlQbGTQbQb8JnrQb8LZoQb8LnvQb8MT8Qb8Ml8Qb8ST4QloAl4QloHZvQloJX8QloMn8QnJZOlRTrAZvRTrDTrRTvJn4RTvLhvRT4Jb8RZrAZrRZ8AkrRZ8JU8RZ8LV8RZ8LnvRbJlQXRg3GboRg3MnvRg8AZ8Rg8JboRg8Jl4RnLTCbRnvFl3RnvQb8SToAl4SToCZrSToFZoSToHXrSToJU8SToJgvSToJl4SToLhrSToMX3STrAlvSTrCT9STrCgrSTrGgrSTrHXrSTrHboSTrJnoSTrNboSTvLnrST4AZoST8Ab8ST8JT8SUoJn3SU6HZ#SU6JTvSU8Db8SU8HboSU8LgrSV8JT8SZrAcrSZrAl3SZrJT8SZrJnvSZrMT8SZvLUoSZ4FZoSZ8JnoSZ8RZrScoLnrScoMT8ScoMX8ScrAT4ScrAZ8ScrLZ8ScrLkvScvDb8ScvLf8ScvNToSgrFZrShvKnrSloHUoSloLnrSlrMXoSl8HgrSmrJUoSn3BX6', - 'ATFlOn3ATLgrDYAT4MTAnAT8LTMnAYJnRTrAbGgJnrAbLV8LnAbvNTAnAeFbLg3AgOYMXoAlQbFboAnDboAfAnJgoJTBToDgAnBUJbAl3BboDUAnCTDlvLnCTFTrSnCYoQTLnDTwAbAnDUDTrSnDUHgHgrDX8LXFnDbJXAcrETvLTLnGTFTQbrGTMnGToGT3DUFbGUJlPX3GbQg8LnGboJbFnGb3GgAYGgAg8ScGgMbAXrGgvAbAnGnJTLnvGnvATFgHTDT6ATHTrDlJnHYLnMn8HZrSbJTHZ8LTFnHbFTJUoHgSeMT8HgrLjAnHgvAbAnHlFUrDlHnDgvAnHnHTFT3HnQTGnrJTAaMXvJTGbCn3JTOgrAnJXvAXMnJbMg8SnJbMnRg3Jb8LTMnJnAl3OnJnGYrQlJnJlQY3LTDlCn3LTJjLg3LTLgvFXLTMg3GTLV8HUOgLXFZLg3LXNXrMnLX8QXFnLX9AlMYLYLXPXrLZAbJU8LZDUJU8LZMXrSnLZ$AgFnLaPXrDULbFYrMnLbMn8LXLboJgJgLeFbLg3LgLZrSnLgOYAgoLhrRnJlLkCTrSnLkOnLhrLnFX%AYLnFZoJXLnHTvJbLnLloAbMTATLf8MTHgJn3MTMXrAXMT3MTFnMUITvFnMXFX%AYMXMXvFbMXrFTDbMYAcMX3MbLf8SnMb8JbFnMgMXrMTMgvAXFnMgvGgCmMnAloSnMnFnJTrOXvMXSnOX8HTMnObJT8ScObLZFl3ObMXCZoPTLgrQXPUFnoQXPU3RXJlPX3RkQXPbrJXQlPlrJbFnQUAhrDbQXGnCXvQYLnHlvQbLfLnvRTOgvJbRXJYrQlRYLnrQlRbLnrQlRlFT8JlRlFnrQXSTClCn3STHTrAnSTLZQlrSTMnGTrSToHgGbSTrGTDnSTvGXCnST3HgFbSU3HXAXSbAnJn3SbFT8LnScLfLnv', - 'AT3JgJX8AT8FZoSnAT8JgFV8AT8LhrDbAZ8JT8DbAb8GgLhrAb8SkLnvAe8MT8SnAlMYJXLVAl3GYDTvAl3LfLnvBUDTvLl3CTOn3HTrCT3DUGgrCU8MT8AbCbFTrJUoCgrDb8MTDTLV8JX8DTLnLXQlDT8LZrSnDUQb8FZ8DUST4JnvDb8ScOUoDj6GbJl4GTLfCYMlGToAXvFnGboAXvLnGgAcrJn3GgvFnSToGnLf8JnvGn#HTDToHTLnFXJlHTvATFToHTvHTDToHTvMTAgoHT3STClvHT4AlFl6HT8HTDToHUoDgJTrHUoScMX3HbRZrMXoHboJg8LTHgDb8JTrHgMToLf8HgvLnLnoHnHn3HT4Hn6MgvAnJTJU8ScvJT3AaQT8JT8HTrAnJXrRg8AnJbAloMXoJbrATFToJbvMnoSnJgDb6GgvJgDb8MXoJgSX3JU8JguATFToJlPYLnQlJlQkDnLbJlQlFYJlJl8Lf8OTJnCTFnLbJnLTHXMnJnLXGXCnJnoFfRg3JnrMYRg3Jn3HgFl3KT8Dg8LnLTRlFnPTLTvPbLbvLVoSbrCZLXMY6HT3LXNU7DlrLXNXDTATLX8DX8LnLZDb8JU8LZMnoLhrLZSToJU8LZrLaLnrLZvJn3SnLZ8LhrSnLaJnoMT8LbFlrHTvLbrFTLnrLbvATLlvLb6OTFn3LcLnJZOlLeAT6Mn4LeJT3ObrLg6LXFlrLhrJg8LnLhvDlPX4LhvLfLnvLj6JTFT3LnFbrMXoLnQluCTvLnrQXCY6LnvLfLnvLnvMgLnvLnvSeLf8MTMbrJn3MT3JgST3MT8AnATrMT8LULnrMUMToCZrMUScvLf8MXoDT8SnMX6ATFToMX8AXMT8MX8FkMT8MX8HTrDUMX8ScoSnMYJT6CTvMgAcrMXoMg8SToAfMlvAXLg3MnFl3AnvOT3AnFl3OUoATHT8OU3RnLXrOXrOXrSnObPbvFn6Og8HgrSnOg8OX8DbPTvAgoJgPU3RYLnrPXrDnJZrPb8CTGgvPlrLTDlvPlvFUJnoQUvFXrQlQeMnoAl3QlrQlrSnRTFTrJUoSTDlLiLXSTFg6HT3STJgoMn4STrFTJTrSTrLZFl3ST4FnMXoSUrDlHUoScvHTvSnSfLkvMXo', - 'AUoAcrMXoAZ8HboAg8AbOg6ATFgAg8AloMXoAl3AT8JTrAl8MX8MXoCT3SToJU8Cl8Db8MXoDT8HgrATrDboOT8MXoGTOTrATMnGT8LhrAZ8GnvFnGnQXHToGgvAcrHTvAXvLl3HbrAZoMXoHgBlFXLg3HgMnFXrSnHgrSb8JUoHn6HT8LgvITvATrJUoJUoLZrRnvJU8HT8Jb8JXvFX8QT8JXvLToJTrJYrQnGnQXJgrJnoATrJnoJU8ScvJnvMnvMXoLTCTLgrJXLTJlRTvQlLbRnJlQYvLbrMb8LnvLbvFn3RnoLdCVSTGZrLeSTvGXCnLg3MnoLn3MToLlrETvMT8SToAl3MbrDU6GTvMb8LX4LhrPlrLXGXCnSToLf8Rg3STrDb8LTrSTvLTHXMnSb3RYLnMnSgOg6ATFg', - 'HUDlGnrQXrJTrHgLnrAcJYMb8DULc8LTvFgGnCk3Mg8JbAnLX4QYvFYHnMXrRUoJnGnvFnRlvFTJlQnoSTrBXHXrLYSUJgLfoMT8Se8DTrHbDb', - 'AbDl8SToJU8An3RbAb8ST8DUSTrGnrAgoLbFU6Db8LTrMg8AaHT8Jb8ObDl8SToJU8Pb3RlvFYoJl', -]; -const codes$1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*'; -function getHangul(code) { - if (code >= 40) { - code = code + 168 - 40; - } - else if (code >= 19) { - code = code + 97 - 19; - } - return toUtf8String(new Uint8Array([225, (code >> 6) + 132, (code & 0x3f) + 128])); -} -let _wordlist$1 = null; -function loadWords$1() { - if (_wordlist$1 != null) { - return _wordlist$1; - } - const wordlist = []; - data$1.forEach((data, length) => { - length += 4; - for (let i = 0; i < data.length; i += length) { - let word = ''; - for (let j = 0; j < length; j++) { - word += getHangul(codes$1.indexOf(data[i + j])); - } - wordlist.push(word); - } - }); - wordlist.sort(); - // Verify the computed list matches the official list - /* istanbul ignore if */ - const checksum = id(wordlist.join('\n') + '\n'); - /* c8 ignore start */ - if (checksum !== '0xf9eddeace9c5d3da9c93cf7d3cd38f6a13ed3affb933259ae865714e8a3ae71a') { - throw new Error('BIP39 Wordlist for ko (Korean) FAILED'); - } - /* c8 ignore stop */ - _wordlist$1 = wordlist; - return wordlist; -} -let wordlist$2 = null; -/** - * The [Korean wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/korean.txt) for [mnemonic - * phrases](https://en.bitcoin.it/wiki/BIP_0039). - */ -class LangKo extends Wordlist { - /** - * Creates a new instance of the Korean language Wordlist. - * - * This should be unnecessary most of the time as the exported {@link langKo} should suffice. - * - * @ignore - */ - constructor() { - super('ko'); - } - getWord(index) { - const words = loadWords$1(); - assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, 'index', index); - return words[index]; - } - getWordIndex(word) { - return loadWords$1().indexOf(word); - } - /** - * Returns a singleton instance of a `LangKo`, creating it if this is the first time being called. - */ - static wordlist() { - if (wordlist$2 == null) { - wordlist$2 = new LangKo(); - } - return wordlist$2; - } -} - -const words$1 = "0torea noica!iosorolotaleratelanena%oiadoencotivomai t ca%a0A]Bagl'Bin#E.Is(Oli!Rasi_Rog#0Cade!C[$Cus#E Roba+U 0Ag'Deb{DomeEgu#Eri!IpeOtt&Ul&1Fabi,Fe|Fis(F-n Oris`O(R~$0AveEn.E_,Ganc'I!It&OnismoR>*Rume Uzzo4AbardaA Bat)Ber#BoBumeCeCol>E|Ertu-OdePari!Pe^ Pogg'P)@Pun Ri,1Ab~AchideAgos+Ald~Anc'Atu-AzzoBit)Chiv'D{Eni,G[ GiSoTef%eZil*0Ciu|Col EpsiEtt>Fal I$O/Pir#P)Sagg'SeSolu Sur@TaT[u T%eT-|0Av>EismoOm>O$TesaTiv&Tor$Tr{Tua,0Sil'Str?Tis+To$moTun$0Anz#E!V[i!Vi(Volge!3IoS(Tos+Ttu U,VaVosa3C]FfaLg'LvaNdaNe_,Nig$Nzi=ReRli=Ta3Bi+CiDoR@S]Tan>T^$Zzo*2Acc'AdipoA`An}Avu-E.l/Eve|EzzaIgl?Il/n.Ind&Oc]*O@Onzi=Ul*U$2BboT+di$UffoVet+Vi,2Ass>In~O)2C]Dar@D%eE!n.G$meLl&Lm#Lo!Lpo(L^v#LzaMaMe+M`n@Mo@Mpu.rMuS+n.Ttu-V#2A.!Avat+E#Ede!Emo(Esci+E+Ice I=,IsiIt>OceO=}Os++Uc?,Us}2Ci!Cu*Gi$Ll#Po/R#!R(!R_Sci$S de:DoI$L`+Meri$Nie/N$(Nz&T#Van^Vve)3Bu|C[n'Ci(Cli$Col*C! D%#Fin{FormeG$Leg&Lfi$Lir'L+M[zaNot#Nt)Pos{Rapa+Riv&RogaScri|Ser Sider'Sume!Tersi_Vo 3Amet)Cemb!Ed)Fe(Ffu(Geri!Gi+,Luv'Nam>N=nziPin P*`Po*Rad&ReRo|RupoSag'Sc! Sf&Sge*Spos S+nzaSu`$ToVa$Vel Vide!Vor#5B*I}MoSaU(0An#B,`Es(I)O^_Oz'U*0Dem>Du)Erg?FasiO.}Tr&Zi`1A^.I*goI(d'O},Pu!0U#!0Ar'BaBo(EdeEmi+Ige!Met>OeOsi_Ran.0Ago$AmeAnimeAudi!CaEmp'Erc{Ib{Ig[.Is.!I OfagoOrt#O(Pan(P!s(S[zaSoTe(Tim&Ton?T)(Ult&0Il>N>Rus]To0ClideoRopa0A(Id[zaIt#Olu Viva:Bbr~Cc[daChi)L]Migl?Na,Nfa-NgoN+s`ReRfal/Ri$(R`]Sc?S (Sul*T%&ToVo*(3Bb!Co/DeG#LpaLt)Mmi=Nde!Nome$Rm[ R)R^,Ssu-S^_T+U@3AbaDuc?FaGur#LoNanzaNest-Ni!O!S},S>Ume2A]Cacc?Co(Der#Gl'La+Lc*!Lgo!Nd[.Net>N?N+=Rb{Rchet+Res+Rm~R='RoR.zzaRz&Sf#S(2A}s(A=Assi$A.l*Eccet+E=+Es]IgoOlli$OndeUga,Ut+2Ci/+Cs?Gg[.LmiT Ud'ZeboZzel/3CoLa^=L(Mel*Mm#NeN{!N='No^poRgo2Epar@Iacc'Isa0Al*LdaNep)Oc&Oiel*Or$OveR#RoAmmoAndeAtt&A_(Az?E}EggeIfoIll'O*RaR>Roge$2IeLude!0Bal*Bevu Boc]Bu MaO.siP~1IdeLandaOn>Rig#Ror&0Ol#O poTer>Titu Tr%e0Al?Er&:::Bb)Birin C}Cer#Cri`Cu=D@veGoMpoNcet+N.r=R@(RgaRingeSt-T[zaTi$TtugaVag=Vo)3Ga,Gge)MboN.zzaNzaOGl?G<.G)Iol~LafedeLg-@Lin.(Lsa$L Lumo!NaNc?N@r/Ngi&Nifes N=)Nov-NsardaN^deNubr'PpaR#=Rci!Ret+RmoRsup'Sche-Ssa?S^$Te-s(Tr>/T Ce=.DesimoDit&GaLassaLisLod?NingeNoN(/Rcur'R[daR*Schi$SeSse!S *Tal*To@T.!3Agol&CaCel'Che,C)boDol*E,Gl'!La$Li.MosaNe-,NiNo!Ri$R^l*Sce/SsivaS Sur&TezzaTig&T-T.n.4Emon>0Del*Dif~Du*Ga$G'LeLos(Nas.)N]Ndi=Ne+r'Ni,No $N(3Cch?NfaTi@5Bi,Ci_DoMeMi=Rd>R`,RvegeseSt-$T&Tiz?Ttur$Vel/5C,oL/Me)O_Tri!Vo/Z?,:Si0Bedi!BligoElis]L'O*So, 0Cas'B-EgaIss'<0Do(E!IceNi_)O!_,Ta1Er#In'IgiDel/D)Ri.RolisiTo2AceboAn&As`A+$E=r'2ChezzaDe)(DismoEs?Ggi&L[+Ligo$Ll%eLmoni.Lpet+L(Lt)=Lve!M%eMo@)N.Po*(Rfi@Ro(Rpo-R!R++SaSi^_Sses(Stul#Tass'Te!2AnzoAssiAt~Eclu(Ed~Efis(Egi#Elie_Eme!E$t&Epar#Es[zaE.s Eval(I`IncipeIv#Ob,`Ocu-Odur!OfumoOge|OlungaOmessaO$meOpos+O)gaO.(OvaUd[.Ug=Ur{0Iche1Bbl>D~Gil#G$LceL{Lsan.Nt&PazzoPil/Ro:99Ad)Al]saAsiE!/O+:C]l D@pp'D~,Dun#Ff~GazzoG'*Dur!Fas&F,s(For`Fug'G&Gett#Ghel*Lass#Lev#MaT)_Un'Bus Cc?CoDagg'De!D{!G{Ll'Mant>Mpe!Nz'Sol&SpoTan.Ton@Tu/Vesc'5BizzoBr~GaLli$Mi:B#Bbi&Bot#Go`Las(Ldatu-Lgem`Liv&LmoEtt)HedaHie=IarpaI[zaInde!IppoI)ppoI_*Ler&Odel/Olp{Ompar Onfor Opri!Or+Os(Mul#Nfon?Ngo*Nist)NoN.siNu(idePar'S`S ,Tu#2It+Ogatu-Ove$0Arr{Emor#En^ E-l@IlzoOnt&Ott#Uss#0Elli!Erv#O@0BbalzoBr'C]r(C?,Da,Ffi|G$Ld#L[M`NdaNe|Nnife)Pi!Ppe(P-Rge!Rpas(Rri(R(R.gg'R_l#Spi)S+T^,0AdaAl/Arge!A /Av[ Azzo/EcieEdi!EgRappoReg#Ridu*Rozz&Ru|Ucc&UfoUp[@0B[t)C](Do!Gger{GoL+$On&PerboPpor Rgel#R)g#Ssur)Tu-0Ag&EdeseEgl'El&Enu Ez?IluppoIs+Izze-Ol+Uot&:Bac]Bul#Cci&Citur$LeLis`$MpoVer=Vo/+Zza3CaCn>Lefo$Me-r'MpoMu N@Pog-foRagg'RoTan'To*Tuban.Z'Zzo<5Cc&L,r&L Mbo/MoNfoNsil/Paz'Po*g?PpaRbaRn&R)L,t+Lo)(Lut&L_/Mpa+Ng&N{(NoN+gg'Nve-Po!Ra$Rc#R?n.S}3Det+DovaDu Ge+,I]*Lc)Li=Llu LoceN#Ndemm?N RaceRba,Rgog=Rif~RoRru}Rt~,Sc~Ssil*S+,Te-$Tri=Tus 3Andan.B-n.C[daChingoCi=nzaDim&Gil?G< Go!LeL/$MiniNc{!O/Pe-Rgo/Ro*goRu,n S](S'5Cche)Fo*LuPpa"; -const checksum$1 = '0x5c1362d88fd4cf614a96f3234941d29f7d37c08c5292fde03bf62c2db6ff7620'; -let wordlist$1 = null; -/** - * The [Italian wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/italian.txt) for [mnemonic - * phrases](https://en.bitcoin.it/wiki/BIP_0039). - */ -class LangIt extends WordlistOwl { - /** - * Creates a new instance of the Italian language Wordlist. - * - * This should be unnecessary most of the time as the exported {@link langIt} should suffice. - * - * @ignore - */ - constructor() { - super('it', words$1, checksum$1); - } - /** - * Returns a singleton instance of a `LangIt`, creating it if this is the first time being called. - */ - static wordlist() { - if (wordlist$1 == null) { - wordlist$1 = new LangIt(); - } - return wordlist$1; - } -} - -const words = "0arad!ototealirertainrasoent hoandoaR#riareha!aroele'oronul0Aca%AixoAl A%rDuz'El]Er$IsmoO$ Rum S-&T(i&TigoVo[=0F&.Il#P' S?S* So&/Sun$Tr&0Ac#Adu+Al/A[f E End(Er_EuIng'Ir?IvoOl{oRac Revi=RizU&Um0Di$rM-.R>o+TismoT|@Tu 0Ali An%Ar@Ent&Es,I?Is Ul,1Ila1Ar E=Ei%Ulejo:B BosaC&]uCh `C@GagemI+c>~/Se#S)n%Ta)Te=rTidaTomTuc Unil]3B(IjoIr^IsebolLd!eLezaLgaLisc Ndi$Ng&aNz(RimbauRl*d>_Sou_XigaZ(_3CoCu=En&Foc&Furc G|naLhe%Mest[Mo$rOlog@OmboOsf(aPol Rr-$Scoi$Sne$SpoSsex$TolaZ _2Ind#OcoOque 2A$BagemC#CejoChec]Ico.L^LetimL]LoMb{oNdeNecoNi)Rb~h>d>e&R+c]V*oXe?2AncoAsaAvezaEuIgaIl/Inc OaOchu+Onze O$Uxo2C]DismoF LeRacoScaS$Z*a:Bimb Rn{oRpe%R['>)zRv&/SacoScaSeb[S%loS~oT a)Tiv UleUs?U%l V&oV(na3BolaDil]G}]Lebr L~ Nou+N,N%ioRc Rr#R%'oRvejaTimV^2Aco)Al{aAm#Ap^ArmeAticeAveEfeEg^E'oEqueIco%If[In`oOc&/Ov(UmboU.Uva0CatrizCl}eD!eD['aEn%Gcui$Rurg@T 2A[zaE_Ic OneUbe2A=Ag'Ba@B($rBr C^El/Ent_E,Gum`oIb'IfaIo%L L{aLh(Lid'Lme@L}oLunaM<=Mb* M-.MitivaMov(MplexoMumNc]N=rNec.Nfu,Ng` Nhec(Njug Nsum'Nt+$Nvi%Op( P{oPi?PoQue%lRagemRdi&Rne)R}h>p|&R[ioR%joRuj>voSs-oS%laT}e%U_UveVilZ*]2A%+AvoEcheE=rEmeErEspoI^Im*&Io~oIseItic Os)UaUz{o2B+m SafioSbo.Sc<,S-/Sfi#Sgas%Sigu&SlizeSmam SovaSpesaS)queSvi T&h T-$rT} Tri$UsaV(Vi=Vot#Z-a3Ag+maAle$Da)Fu,Gi.Lat#Lu-%M*u'Nast@Nh{oOceseRe$Sc[)Sf ceSp oSque%Ssip S)n%T?UrnoV(,Vi,rV~g Z(5Br?L|i=M?M*#NativoNz`>m-%Rs&SagemUr#U$r2EnagemIbleOg @2El EndeE$PloQues><%Vi=,:1Lod'O Olog@0Ific It&Uc#1Ei$Etiv 3E.1Ab| Eg(Ei$rEncoEv?Im* Ogi 0B goBol#Br~/Buti=EndaErg'Is,rPat@P-/P*#Polg P[goPurr Ul?0CaixeC-#Ch-%C}t_Deus Doss Faix Fei%FimGaj#G-/Glob Gom#G+x Gu@Jo La.Qu<$Raiz Rol#Rug SaioSe^S*oSop#T<$Te#Tid!eT|.Tr^T~/V(g Vi#Volv(XameX($Xof[Xu$1Id(me0Uip 0E$Gui=Ra)VaVil]0Bopeu0Acu Ap| AsivoEntu&Id-%Olu'1Ag(oAl Am* A$Aus$Ces,Ci.Clam Ecu.EmploIb'Ig-%On( Pof>p>tu+T@T|V|i)X*aZ-da3Ch#Ijo^I+n%L*oM**oNdaNoR>i#RrugemRv(S%j T&Ud&3ApoB_seC Ch{oGur#L{aL/LmeLtr RmezaSg^Ssu+TaV`aX?Xo2AcidezAm*goAn`aEch^O+Utu Uxo2C&C*/Foc GoGue%IceLg#Lhe$Rj Rmig>noR%ScoSsa2Aga)AldaAngoAscoA%rnoE'aEn%E.IezaI,Itu+On]Ustr U%'a2G'L+faSodu$S$TaTil/Ve)Z`a3L#Le@LoM^M(Mi=N(o,NgivaNi&NomaN_Ologi>?Rm* S,S$r3Nas)Nc*o2Aci&IcoseOb&Orio,2ElaIabaLfeLpe Rdu+Rje)R_S$,T{aV(n 2AcejoAdu&Afi%Al]AmpoAn^Atui$Ave$AxaEgoElh EveIloIs&/I.@Os,O%scoUd#Unhi=U)2AcheA+niAx*imEr[ I Inc/Is#LaLo,Ru:Bi.Rm}@S%V(3C.eRd Res@Si.3A$B(n D+.EnaNoPismoPnosePo%ca5JeLofo%MemNes$Nr#Rm}&Sped 5M|#:Te2E@O,2N|#RejaUdimR_SmimToV&iZida3Jum9An*]Elh^G?I>n&Rr Vem5BaDeuDocaIzLg?L/R#Ris)RoS)::B edaB|&C[C)n%Dril/G )GoaJeMb(M-.M* MpejoNchePid P,R{>gu+S<]St_T(&Ti=VfimRgemR*/Rmi)Ro$RquiseR[coR%loRujoSco%Sm|+SsagemStig Tag&T(noT*&Tu.Xil 3D&]DidaDusaGaf}eIgaLc/Sc~ SeuSic&:Ci}&D?JaMo_R*>r#Sc(TivaTu[zaV&]Veg Vio3Bl*aB~o,GativaGoci Gri$Rvo,TaUr&VascaVo{o3N N/TidezV` 5B[zaI%IvaMe M*&Rdes%R% T Tici TurnoV`oVil/Vo5Bl#DezM(&Pci&Tr'Vem:0Cec#Edec(JetivoRig#Scu_S%t+T(Tur 0Id-%Io,Orr(Ulis)Up#2Eg<%EnsivaEr-daIc*aUsc#0Iva4Ar@Eo,H Iv{a0B_Ele%Is,It'0D~#E_,Tem1Ci}&Er?On-%OrtunoOs$1ArBi.DemD*&Fci&Rd&RedeRtidaSmoSs#S%lTam T-%T* T_noUl^Us 3C~i D& Dest[D@t+D+G^I$r&IxeLeLicplexoRsi<>%nceRucaSc#SquisaS,aTisc 3AdaC#Ed!eGm-$Last+Lh#Lo.M-)Nc`NguimN]No%N.On{oPocaQue%ResRue)Sc S$laTg-$Rje)Tur Ud!eXof}eZ}&3C C~ DaD-$Di#Do,Du$rGm-$G[=Gun=IvaLe$LvagemM<&M-%N?N/rNsu&Nt#P #Rei>*g>+RvoTemb_T|3GiloLhue)Lic}eMetr@Mpat@M~ N&Nc(oNg~ NopseN$ni>-eRiTu#5B(fis)Rp[s>[&Rt'Sp'oS%n$:B`aBle%Bu^C/G `aLh(LoLvezMdioRef>j>+xaTuagemUr*oXativoXis)3Atr&C(Ci=Cl#Dio,IaIm Lef}eLh#Mp(oN-%N,rN.Rm&RnoRr-oSeSou+St#ToXtu+Xugo3A+G`aJoloMbr MidezNgi=N%'oRagemT~ 5Al]C]L( LiceM^Mil/N`Ntu+Pe%R>ci=RneioRqueRr!>$S.UcaUp{aX*a2Ab&/Acej Adu$rAfeg Aje$AmaAnc ApoAs{oAt?Av E*oEm(Epid EvoIagemIboIcicloId-%Ilog@Ind!eIploItur Iunf&Oc Ombe)OvaUnfoUque2B~ CquesaT` T|i&:7V 3Bigo0HaId!eIf|me3Olog@SoTigaUbu0A=InaUfru':C*aDi G o,I=,LaL-%Lid!eLo[sN)gemQu{oRe)Rr(Sc~ Sil]S,u+Z Zio3A=D Ge.Ic~ L{oLhiceLu=Nce=rNdav&N( Nt[Rb&Rd!eRe?Rg}h>m`/RnizRs R%n%SpaSti=T|i&3Adu$AgemAj Atu+Br?D{aDr @ElaGaG-%Gi G| L ejoNcoNhe)NilOle)R!>tudeSi.S$Tr&V{oZ*/5A=rArG&L<%LeibolL)gemLumo,Nt!e5L$Vuz`a::D[zRope3QueRe.Rife3Ng ::Ng#Rp 3BuL?9Mb Olog@5Mbi="; -const checksum = '0x2219000926df7b50d8aa0a3d495826b988287df4657fbd100e6fe596c8f737ac'; -let wordlist = null; -/** - * The [Portuguese wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/portuguese.txt) for [mnemonic - * phrases](https://en.bitcoin.it/wiki/BIP_0039). - */ -class LangPt extends WordlistOwl { - /** - * Creates a new instance of the Portuguese language Wordlist. - * - * This should be unnecessary most of the time as the exported {@link langPt} should suffice. - * - * @ignore - */ - constructor() { - super('pt', words, checksum); - } - /** - * Returns a singleton instance of a `LangPt`, creating it if this is the first time being called. - */ - static wordlist() { - if (wordlist == null) { - wordlist = new LangPt(); - } - return wordlist; - } -} - -const data = '}aE#4A=Yv&co#4N#6G=cJ&SM#66|/Z#4t&kn~46#4K~4q%b9=IR#7l,mB#7W_X2*dl}Uo~7s}Uf&Iw#9c&cw~6O&H6&wx&IG%v5=IQ~8a&Pv#47$PR&50%Ko&QM&3l#5f,D9#4L|/H&tQ;v0~6n]nN> 2), 128 + codes.indexOf(data[i * 3 + 1]), 128 + codes.indexOf(data[i * 3 + 2])]; - if (locale === 'zh_tw') { - const common = s % 4; - for (let i = common; i < 3; i++) { - bytes[i] = codes.indexOf(deltaData[deltaOffset++]) + (i == 0 ? 228 : 128); - } - } - wordlist.push(toUtf8String(new Uint8Array(bytes))); - } - // Verify the computed list matches the official list - const checksum = id(wordlist.join('\n') + '\n'); - /* c8 ignore start */ - if (checksum !== Checks[locale]) { - throw new Error(`BIP39 Wordlist for ${locale} (Chinese) FAILED`); - } - /* c8 ignore stop */ - _wordlist[locale] = wordlist; - return wordlist; -} -const wordlists = {}; -/** - * The [Tradional Chinese wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/chinese_traditional.txt) and - * [Simplified Chinese wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/chinese_simplified.txt) for - * [mnemonic phrases](https://en.bitcoin.it/wiki/BIP_0039)). - */ -class LangZh extends Wordlist { - /** - * Creates a new instance of the Chinese language Wordlist for the `dialect`, either `"cn"` or `"tw"` for simplified - * or traditional, respectively. - * - * This should be unnecessary most of the time as the exported langZhCn and langZhTw should suffice. - * - * @ignore - */ - constructor(dialect) { - super('zh_' + dialect); - } - getWord(index) { - const words = loadWords(this.locale); - assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, 'index', index); - return words[index]; - } - getWordIndex(word) { - return loadWords(this.locale).indexOf(word); - } - split(phrase) { - phrase = phrase.replace(/(?:\u3000| )+/g, ''); - return phrase.split(''); - } - /** - * Returns a singleton instance of a `LangZh` for `dialect`, creating it if this is the first time being called. - * - * Use the `dialect` `"cn"` or `"tw"` for simplified or traditional, respectively. - */ - static wordlist(dialect) { - if (wordlists[dialect] == null) { - wordlists[dialect] = new LangZh(dialect); - } - return wordlists[dialect]; - } -} - -export { LangCz, LangEs, LangFr, LangIt, LangJa, LangKo, LangPt, LangZh }; -//# sourceMappingURL=wordlists-extra.js.map diff --git a/dist/wordlists-extra.js.map b/dist/wordlists-extra.js.map deleted file mode 100644 index 6b3450e3..00000000 --- a/dist/wordlists-extra.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"wordlists-extra.js","sources":["../node_modules/@noble/hashes/esm/_assert.js","../node_modules/@noble/hashes/esm/utils.js","../node_modules/@noble/hashes/esm/_u64.js","../lib/esm/_version.js","../lib/esm/utils/properties.js","../lib/esm/utils/errors.js","../lib/esm/utils/data.js","../lib/esm/encoding/utf8.js","../node_modules/@noble/hashes/esm/sha3.js","../lib/esm/crypto/keccak.js","../lib/esm/hash/id.js","../lib/esm/wordlists/decode-owl.js","../lib/esm/wordlists/wordlist.js","../lib/esm/wordlists/wordlist-owl.js","../lib/esm/wordlists/lang-cz.js","../lib/esm/wordlists/bit-reader.js","../lib/esm/wordlists/decode-owla.js","../lib/esm/wordlists/wordlist-owla.js","../lib/esm/wordlists/lang-es.js","../lib/esm/wordlists/lang-fr.js","../lib/esm/wordlists/lang-ja.js","../lib/esm/wordlists/lang-ko.js","../lib/esm/wordlists/lang-it.js","../lib/esm/wordlists/lang-pt.js","../lib/esm/wordlists/lang-zh.js"],"sourcesContent":["function number(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error(`Wrong positive integer: ${n}`);\n}\nfunction bool(b) {\n if (typeof b !== 'boolean')\n throw new Error(`Expected boolean, not ${b}`);\n}\nfunction bytes(b, ...lengths) {\n if (!(b instanceof Uint8Array))\n throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\nfunction hash(hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\nfunction exists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\nfunction output(out, instance) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\nexport { number, bool, bytes, hash, exists, output };\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n//# sourceMappingURL=_assert.js.map","/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated, we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nconst u8a = (a) => a instanceof Uint8Array;\n// Cast array to different type\nexport const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n// Cast array to view\nexport const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE)\n throw new Error('Non little-endian hardware is not supported');\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n if (!u8a(bytes))\n throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n const len = hex.length;\n if (len % 2)\n throw new Error('padded hex string expected, got unpadded hex of length ' + len);\n const array = new Uint8Array(len / 2);\n for (let i = 0; i < array.length; i++) {\n const j = i * 2;\n const hexByte = hex.slice(j, j + 2);\n const byte = Number.parseInt(hexByte, 16);\n if (Number.isNaN(byte) || byte < 0)\n throw new Error('Invalid byte sequence');\n array[i] = byte;\n }\n return array;\n}\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => { };\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n if (!u8a(data))\n throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n const r = new Uint8Array(arrays.reduce((sum, a) => sum + a.length, 0));\n let pad = 0; // walk through each item, ensure they have proper type\n arrays.forEach((a) => {\n if (!u8a(a))\n throw new Error('Uint8Array expected');\n r.set(a, pad);\n pad += a.length;\n });\n return r;\n}\n// For runtime check if class implements interface\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nconst toStr = {}.toString;\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/* Do NOT modify this file; see /src/_admin/update-version.ts */\n/**\n * The current version of quais.\n *\n * @ignore\n */\nexport const version = '1.0.0-alpha.5';\n//# sourceMappingURL=_version.js.map","/**\n * Property helper functions.\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 values resolved.\n *\n * @category Utils\n * @param {Object} value - The object to resolve.\n *\n * @returns {Promise} The resolved object.\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// Crawl up the constructor chain to find a static method\nexport function getStatic(ctor, key) {\n for (let i = 0; i < 32; i++) {\n if (ctor[key]) {\n return ctor[key];\n }\n if (!ctor.prototype || typeof ctor.prototype !== 'object') {\n break;\n }\n ctor = Object.getPrototypeOf(ctor.prototype).constructor;\n }\n return null;\n}\n/**\n * Assigns the `values` to `target` as read-only values.\n *\n * It `types` is specified, the values are checked.\n *\n * @category Utils\n * @param {Object} target - The target object to assign to.\n * @param {Object} values - The values to assign.\n * @param {Object} types - The types to check.\n */\nexport function defineProperties(target, values, types) {\n for (const key in values) {\n const 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 quais include properties to ensure they are both human-readable (i.e. `.message`) and machine-readable\n * (i.e. `.code`).\n *\n * The {@link isError | **isError**} function can be used to check the error `code` and provide a type guard for the\n * properties present on that error interface.\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 quais that matches the error `code`.\n *\n * In TypeScript environments, this can be used to check that `error` matches an quaisError type, which means the\n * expected properties will be set.\n *\n * @category Utils\n * @example\n *\n * ```ts\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 * ```\n *\n * @see [ErrorCodes](api:ErrorCode)\n */\nexport function isError(error, code) {\n return error && error.code === code;\n}\n/**\n * Returns true if `error` is a {@link CallExceptionError | **CallExceptionError**}.\n *\n * @category Utils\n */\nexport function isCallException(error) {\n return isError(error, 'CALL_EXCEPTION');\n}\n/**\n * Returns a new Error configured to the format quais emits errors, with the `message`, {@link ErrorCode | **ErrorCode**}\n * `code` and additional properties for the corresponding quaisError.\n *\n * Each error in quais includes the version of quais, a machine-readable {@link ErrorCode | **ErrorCode**}, and depending\n * on `code`, additional required properties. The error message will also include the `message`, quais version, `code`\n * and all additional properties, serialized.\n *\n * @category Utils\n * @param {string} message - The error message.\n * @param {ErrorCode} code - The error code.\n * @param {ErrorInfo} [info] - Additional properties for the error.\n * @returns {T} The new error.\n */\nexport function makeError(message, code, info) {\n const 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 details.push(key + '=' + stringify(value));\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 quaisError with `message`, `code` and additional error `info` when `check` is falsish..\n *\n * @category Utils\n * @param {unknown} check - The value to check.\n * @param {string} message - The error message.\n * @param {ErrorCode} code - The error code.\n * @param {ErrorInfo} [info] - Additional properties for the error.\n * @throws {T} Throws the error if `check` is falsish.\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 constraints, throwing if not.\n *\n * In TypeScript environments, the `check` has been asserted true, so any further code does not need additional\n * compile-time checks.\n *\n * @category Utils\n * @param {unknown} check - The value to check.\n * @param {string} message - The error message.\n * @param {string} name - The name of the argument.\n * @param {unknown} value - The value of the argument.\n * @throws {InvalidArgumentError} Throws if `check` is falsish.\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 arguemnts' + 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 /* 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 // eslint-disable-next-line no-empty\n }\n catch (error) { }\n return accum;\n}, []);\n/**\n * Throws if the normalization `form` is not supported.\n *\n * @category Utils\n * @param {string} form - The normalization form.\n * @throws {UnsupportedOperationError} Throws if the 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',\n info: { form },\n });\n}\n/**\n * Many classes use file-scoped values to guard the constructor, making it effectively private. This facilitates that\n * pattern by ensuring the `givenGuard` matches the file-scoped `guard`, throwing if not, indicating the `className%% if\n * provided.\n *\n * @category Utils\n * @param {any} givenGuard - The guard provided to the constructor.\n * @param {any} guard - The file-scoped guard.\n * @param {string} [className] - The class name.\n * @throws {UnsupportedOperationError} Throws if the guards do not match.\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 */\nimport { assert, assertArgument } from './errors.js';\n/**\n * Converts a BytesLike value to a Uint8Array.\n *\n * @ignore\n * @category Utils\n * @param {BytesLike} value - The value to convert.\n * @param {string} [name] - The name of the value for error context.\n * @param {boolean} [copy] - Whether to create a copy of the value.\n *\n * @returns {Uint8Array} The converted Uint8Array.\n * @throws {Error} If the value is not a valid BytesLike.\n */\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 the original `value` is returned; if a copy is required\n * use {@link getBytesCopy | **getBytesCopy**}.\n *\n * @category Utils\n * @param {BytesLike} value - The value to convert to a Uint8Array.\n * @param {string} [name] - The name of the value for error context.\n *\n * @returns {Uint8Array} The typed Uint8Array.\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 to prevent any modifications of the returned value\n * from being reflected elsewhere.\n *\n * @category Utils\n * @param {BytesLike} value - The value to convert to a Uint8Array.\n * @param {string} [name] - The name of the value for error context.\n *\n * @returns {Uint8Array} The typed Uint8Array.\n */\nexport function getBytesCopy(value, name) {\n return _getBytes(value, name, true);\n}\n/**\n * Returns true if `value` is a valid {@link HexString | **HexString**}.\n *\n * If `length` is `true` or a number, it also checks that `value` is a valid {@link DataHexString | **DataHexString**} of\n * `length` (if a number) bytes of data (e.g. `0x1234` is 2 bytes).\n *\n * @category Utils\n * @param {any} value - The value to check.\n * @param {number | boolean} [length] - The expected length of the data.\n *\n * @returns {boolean} True if the value is a valid {@link HexString | **HexString**}.\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 data (i.e. a valid\n * {@link DataHexString | **DataHexString**} or a Uint8Array).\n *\n * @category Utils\n * @param {any} value - The value to check.\n *\n * @returns {boolean} True if the value is a valid {@link DataHexString | **DataHexString**}.\n */\nexport function isBytesLike(value) {\n return isHexString(value, true) || value instanceof Uint8Array;\n}\nconst HexCharacters = '0123456789abcdef';\n/**\n * Returns a {@link DataHexString | **DataHexString**} representation of `data`.\n *\n * @category Utils\n * @param {BytesLike} data - The data to convert to a hex string.\n *\n * @returns {string} The hex string.\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 {@link DataHexString | **DataHexString** } by concatenating all values within `data`.\n *\n * @category Utils\n * @param {ReadonlyArray} datas - The data to concatenate.\n *\n * @returns {string} The concatenated 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 *\n * @category Utils\n * @param {BytesLike} data - The data to get the length of.\n *\n * @returns {number} The length of the data.\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 {@link DataHexString | **DataHexString** } by slicing `data` from the `start` offset to the `end` offset.\n *\n * By default `start` is 0 and `end` is the length of `data`.\n *\n * @category Utils\n * @param {BytesLike} data - The data to slice.\n * @param {number} [start] - The start offset.\n * @param {number} [end] - The end offset.\n *\n * @returns {string} The sliced data.\n * @throws {Error} If the end offset is beyond the data bounds.\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,\n length: bytes.length,\n offset: end,\n });\n }\n return hexlify(bytes.slice(start == null ? 0 : start, end == null ? bytes.length : end));\n}\n/**\n * Return the {@link DataHexString | **DataHexString**} result by stripping all **leading** zero bytes from `data`.\n *\n * @category Utils\n * @param {BytesLike} data - The data to strip.\n *\n * @returns {string} The stripped 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}\n/**\n * Pads the data to the specified length.\n *\n * @ignore\n * @category Utils\n * @param {BytesLike} data - The data to pad.\n * @param {number} length - The length to pad to.\n * @param {boolean} left - Whether to pad on the left.\n *\n * @returns {string} The padded data.\n * @throws {Error} If the padding exceeds data length.\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 {@link DataHexString | **DataHexString**} of `data` padded on the **left** to `length` bytes.\n *\n * If `data` already exceeds `length`, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown.\n *\n * This pads data the same as **values** are in Solidity (e.g. `uint128`).\n *\n * @category Utils\n * @param {BytesLike} data - The data to pad.\n * @param {number} length - The length to pad to.\n *\n * @returns {string} The padded data.\n */\nexport function zeroPadValue(data, length) {\n return zeroPad(data, length, true);\n}\n/**\n * Return the {@link DataHexString | **DataHexString**} of `data` padded on the **right** to `length` bytes.\n *\n * If `data` already exceeds %%length%%, a [BufferOverrunError](../interfaces/BufferOverrunError) is thrown.\n *\n * This pads data the same as **bytes** are in Solidity (e.g. `bytes16`).\n *\n * @category Utils\n * @param {BytesLike} data - The data to pad.\n * @param {number} length - The length to pad to.\n *\n * @returns {string} The padded data.\n */\nexport function zeroPadBytes(data, length) {\n return zeroPad(data, length, false);\n}\n//# sourceMappingURL=data.js.map","/**\n * Using strings in Ethereum (or any security-basd system) requires additional care. These utilities attempt to mitigate\n * some of the safety issues as well as provide the ability to recover and analyse strings.\n *\n * @subsection api/utils:Strings and UTF-8 [about-strings]\n */\nimport { getBytes } from '../utils/data.js';\nimport { assertArgument, assertNormalize } from '../utils/errors.js';\n// `output` and `badCodepoint` are passed to calls below, but not used in the function\nfunction errorFunc(reason, offset, bytes, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\noutput, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nbadCodepoint) {\n assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, 'bytes', bytes);\n}\n// `output` and `badCodepoint` are passed to calls below, but not used in the function\nfunction ignoreFunc(reason, offset, bytes, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\noutput, \n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nbadCodepoint) {\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 non-canonical (overlong) codepoints (this is the default)\n *\n * **`\"ignore\"`** - silently drops any illegal UTF-8 sequence and accepts non-canonical (overlong) codepoints\n *\n * **`\"replace\"`** - replace any illegal UTF-8 sequence with the UTF-8 replacement character (i.e. `\"\\\\ufffd\"`) and\n * accepts non-canonical (overlong) codepoints\n *\n * @category Encoding\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 const 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 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 *\n * @category Encoding\n * @param {string} str - The string to convert.\n * @param {UnicodeNormalizationForm} [form] - The normalization form to use.\n *\n * @returns {Uint8Array} The UTF-8 byte representation.\n * @throws {Error} If the UTF-8 conversion fails.\n */\nexport function toUtf8Bytes(str, form) {\n if (form != null) {\n assertNormalize(form);\n str = str.normalize(form);\n }\n const 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 * @ignore\n */\nfunction _toUtf8String(codePoints) {\n return codePoints\n .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 })\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 errors allowing recovery using the\n * {@link Utf8ErrorFunc | **Utf8ErrorFunc**} API. (default: [error](Utf8ErrorFuncs))\n *\n * @category Encoding\n * @param {BytesLike} bytes - The UTF-8 data to convert.\n * @param {Utf8ErrorFunc} [onError] - The error handling function.\n *\n * @returns {string} The string.\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 *\n * @category Encoding\n * @param {string} str - The string to convert.\n * @param {UnicodeNormalizationForm} [form] - The normalization form to use.\n *\n * @returns {number[]} The UTF-8 code-points.\n */\nexport function toUtf8CodePoints(str, form) {\n return getUtf8CodePoints(toUtf8Bytes(str, form));\n}\n//# sourceMappingURL=utf8.js.map","import { bytes, exists, number, output } from './_assert.js';\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.js';\nimport { Hash, u32, toBytes, wrapConstructor, wrapXOFConstructorWithOpts, } from './utils.js';\n// SHA3 (keccak) is based on a new design: basically, the internal state is bigger than output size.\n// It's called a sponge function.\n// Various per round constants calculations\nconst [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [[], [], []];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n// Same as keccakf1600, but allows to skip some rounds\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n // Can be passed from user as dkLen\n number(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n keccakP(this.state32, this.rounds);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n exists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n exists(this, false);\n bytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n number(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n output(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/**\n * SHA3-256 hash function\n * @param message - that would be hashed\n */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/**\n * keccak-256 hash function. Different from SHA3-256.\n * @param message - that would be hashed\n */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","/**\n * Cryptographic hashing functions\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 hash of UTF-8 data use the [**id**}(../functions/id)\n * function.\n *\n * @category Crypto\n * @example\n *\n * ```ts\n * keccak256('0x');\n *\n * keccak256('0x1337');\n *\n * keccak256(new Uint8Array([0x13, 0x37]));\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 * ```\n *\n * @param {BytesLike} _data - The data to hash.\n * @returns DataHexstring\n * @returns {string} The hash of the data.\n */\nexport function keccak256(_data) {\n const data = getBytes(_data, 'data');\n return hexlify(__keccak256(data));\n}\nkeccak256._ = _keccak256;\nkeccak256.lock = function () {\n locked = true;\n};\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 { keccak256 } from '../crypto/index.js';\nimport { toUtf8Bytes } from '../encoding/index.js';\n/**\n * A simple hashing function which operates on UTF-8 strings to compute an 32-byte identifier.\n *\n * This simply computes the {@link toUtf8Bytes | **UTF-8 bytes**} and computes the {@link keccak256 | **keccak256**}.\n *\n * @category Hash\n * @example\n *\n * ```ts\n * id('hello world');\n * ```\n *\n * @param {string} value - The string to hash.\n * @returns {string} The 32-byte identifier.\n */\nexport function id(value) {\n return keccak256(toUtf8Bytes(value));\n}\n//# sourceMappingURL=id.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 // eslint-disable-next-line @typescript-eslint/no-unused-vars\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 words used to encode and devoce\n * [BIP-39](https://en.bitcoin.it/wiki/BIP_0039) encoded data by mapping words to 11-bit values and vice versa.\n *\n * @category Wordlists\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, passing in the locale string of the language.\n *\n * Generally there is no need to create instances of a Wordlist, since each language-specific Wordlist creates an\n * instance and 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 method for spliting `phrase` into individual words.\n *\n * By default, `phrase` is split using any sequences of white-space as defined by regular expressions (i.e.\n * `/\\s+/`).\n *\n * @param {string} phrase - The phrase to split.\n *\n * @returns {string[]} The split words in the phrase.\n */\n split(phrase) {\n return phrase.toLowerCase().split(/\\s+/g);\n }\n /**\n * Sub-classes may override this to provider a language-specific method for joining `words` into a phrase.\n *\n * By default, `words` are joined by a single space.\n *\n * @param {string[]} words - The words to join.\n *\n * @returns {string} The joined phrase.\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 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 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 to create the necessary data.\n *\n * @category Wordlists\n */\nexport class WordlistOwl extends Wordlist {\n #data;\n #checksum;\n /**\n * Creates a new Wordlist for `locale` using the OWL `data` 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 * @ignore\n */\n get _data() {\n return this.#data;\n }\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 = \"0itatkastcenaovo$taouleraeki&chor*teci%enbalodaeladet'!Chn=0Di#%E%^1Resa2Rese3CeT'#0EjKohol0Pu)%0A&sDul#Ekdo)Ke)Ti#Ul|3}aOgan%0FaltI$@tPi,%TmaTronom0LasL{i#Ol0Tobus4Yl:B#}R'?TaUb_U/!U^U+Ur!Xer2A^v#Ambo,An#AtrEp)Ike)KoLohOnzOskevUn{#Usin#Z^Zy2Bl.Bn|})D _D#D'aF{Jar(Kv?LdokLvaN^NkrRzaTikVolZola3D+tL.T'#0Ukot:PartRev&3DrDu+J/JnLaLerLkemLn?N.Nn(N'#NtrumNzZ(2O&2KolivUv!4It_N(0Dn(Ke)KrPot0Ak~AlIkRkot2Kli$a:L-oRe[T_Tum1E,1B!a}'#Cib_Fic Fla%KlKr{Mokr!PreseRbyS#T-tiv3Kob,zKt|O^P]mSkSp+jV`]Vo/2AhaOuhoUhopis1Es0BroByt-C@t}ut DnesH+dHo^H,JemJn?Kl`KolaKtAzeDolObn(OgerieOzdSn(T Z(2B@}'noD-HaH'#S SnoT(0Oj?Or>2Nam :9O]gOnomie0EktronIpsa0AilIseO%P!ie2Izo^O/aOpejOs2EjEn%K<)Kymo0Ike)0FR&S]Zky3StOhOup(T!Ub.U/o)0AtO)Yz0IsOjivoOut0Bl.Boj}DinyDl!Dno)D|Jn(KejLin#L#LubMo+N [No,%RalR^RizontRkoRliv>RmonRn.RoskopR$voSpo^St.T'(U[UfUp!Us#V<2Ad[An?Av(Az^Bo+kD.D]D(N-Ob#Oma^OtOu^Oz@St#Ub(Yz!2B@(B~D[KotMrS aSto)0Ozd2Bn(D,ntGie&M&Sterik:2Yl#3Ned2O&0Uze0Un a0F-%Fla%KasoOva%Sp-%Tern{Vali^Ve$N)rRmarkRoSanSnoT#VD+Dn!_HlanKotL@L oMn(NomP?S{erV Zd>Zero3NakNdyNo/Sk,Sto)Trn?Zva3En|1Gurt5R):Bar{B_Bin{}&D{Did]HanJakJu)KaoKtusLam aLhotyLibrLn(Me,MkolivM&Ni[lNoeNtB#BlihaBylaC*rH=J@>KosKtejlLapsLe^LizeLoMandoMe)MikMn!aMo,MpasMun aN!N%ptNd?N>NfeseNgresN.NkursN)ktNzervaPan>PieP~Pr'#Rb_R-tSt#T_T+)T*lUk!Up_&Us-Uz]VbojZaZMe+cMivoOcanOkOni#Op OupaOv#T-Uh`]Up?Ut(Vin#Y/+Yp)Y$alYt2Dlan#FrJn(KlaLaj^Li/L#Lom{Ltu,NaPodivuRtRzV`]:B,d<})nDn(IkKom>M_aMpaN'#S?SoStu,Tin#V.3B#CkdyD@Dn?D'#Dv.G@^GieG,%H%Hk(H~KtvarNo/odNtil#P@#Pid]T`]T>TmoTokruhVhartV a%Vobok3B,}ot#DojedDsk(H'.Jav>L-M{#NieN#No+umStop`T.T|5Bi$aDivodGi#GopedKal aK{Mc|P!aPu/RdSosTrU^lUhU#Usk!V>3Tiv(1Cer&CiferMpSkSt,%0I%2RaRi#S.:DamD]Gi$rHagonJ{-J _J< aKakK'?Kr_aL[L.L|Lv?Min#Nd+NkoRn(SakrSkotSopu$T?Tri#Tur aZan>ZivoZl Zur#2Lo[0}anikD a%D'.LasaL*nNtol#TlaTo^TrZe,3G,%H~Hu+K.KrofonL@>Lim{rL(Mi#Nc'&Ni[rNom{Nul(S#StrX|2Ad(HaH'.OkS!Uv 1I/Ohem0BilCn(D_#Dl [HylaKroL-ulaM@t#Nar/aNoklN$rumNt|NzunSazSkytStTiva%T<#Ty#U/aUdr(Zai#Z-Zol2AmKevTvolaZ{Zut(0T _1DrcF]nL!MieN?S{Ta%ZeumZi#nt3Sliv>0Da:B*r!}yt!Da%Dbyt-DhozDobroDpisHlasHn!Hodi+H,d Iv aJedn*Ji$oJm=K]n Kon>Krm LevoMaz!Mluv Nom{rOkoOpakO$roP`!PevnoPln P~Pos+dPr(oRod RubyRy/]S` S-!S+poSt!TolikV@-Vr/VzdR&Ru[RysSahSluhaS)r!UvVazVin VodVyk+Yv!_Z<0AsElEn Hl` Ho)H,&It~0BojByt}odCiz Ebr!Esl!Evzd!EzvaH`%Hod J{JinudKazK*p LivLu#Ml#Oln(P`PisPl=PLivoLu[Mf+tMls-N@#Ni#N&N|N$voNtof+Pri#Rke)RodieR)Ru#Ry[Se#Siv aSt_#T@tTro&V*kZnehtZ*r-3C#DagogJs-K]LotonNal)Ndr-NzeRiskopRoStr(Tar^T?Tro+jVn.Xeso3Ani$aHaJav?K+KnikL.Ln(Lul#Nze)Pe)S!_Sto+Tev&Vn?V'ar2A%n)Ak!Am@Ane)A$i#At Avid]AzE/Em@oEn)EsEtivoEv_Iv!N NoO/aOd.Om[OutUkYn2Bav Byt}odC Ctiv>D!D%n Deps!Dh+dDiv Dkl`Dman DnikDo[Dpo,D,zD$!aDvodDzimEzieHan#Hnut#H'S*d SpoluS)vaSud-SypTahT#nT+skTom-T,vaTupaTvo,U#zUtoUzdroVahaVidlaVlakVozVr/V$!VykVzde/Zd,vZem-Zn!-ZAp<-AseAv^IncipKnoObud O%ntoOdejOfeseOh,Oj-tO]m Omi+Onik!Op`OrokOs[OtonOut-OvazS#v#St@Udk(UtV-VohOvodTruh0Actvo0Ber)}DlKav>Kl.Kr+LtMpaNcP@SaSin#St.T|Ty#3Rami^SkT_::C-}otDia%Dn?DonFtGbyKe)K'.M@oMp*/NdeRa/R aS'&StrTo+$Zan%Zid]3Ag|Ak%CeptDaktMizd!Mo)N #Rdin#San#T_ Z[Z@?0Or0H|1B,n#CeseD`]Dim@tD]Hn!Jm=Ke,K)Kun^KvojeM@oNoRvisS` Sho,SkokSl!St,SuvSyp!T[T.Tk!T~Trv!VerZ&m2O^R~0FonLn?R#Rot-RupTua%1AfandrAliskoAnz@AutEptikIcaL`[L@?LoLuzO[O#nOroRip)RzUp.V(Vr&0Abi#Adid]An.A$Avn(Ed|Ep>EvaEz.IbI&Izn?OnOup-OvoU/UhaUn%Up#Za0A,gdE)&Il$voL*vaOgR`RkRt#Ut-Ysl0AdAhaOb0Bo)}aD'#KolP#TvaUbojUc Ud%UhlasUl`Um,kUp,vaUsedUtokUvis{0Al'&As _IsLavOd-Oj@>OluOnzOvn!P@StUb1An?Ar(aAti#Av[EhnoEz#OdolaO+kOpaOrnoOup!Ra/ResRh~RomRu&Ud&Upn?VolYk0Bj-tBtropy}arD(KnoNd!N=Rik!aR'.0AhAl$voEtrAt[Az-Is+It-Obo^Odid]Or#Rab2Kav#KotN-N'>P!Pk(R'(S_T(:B+t#Bu+H*nJemnoJfunJgaJ Jn(Kti#Mh+MponNc|N>NkerPe)V@.Z!_3}ni#HdyKut.LefonMno)Nd@%Ni$aNU/l Uhl?UsV!2DyH~H(Nd,Ri$aR&jZemsko0ArohOr[Rd(Rz2GrKev:0Oh(OzeR!R*s-RusYt'&0HoTiv(0Iv 3R` 1Edn!I$ M=0Az!_Lidn Lon Otv Roj 0I%I)Ov 0Yv`]0Av IfR*s 1Al Oln Oz'#3D,v ElEn.L.N!:GonL/aL*nNaN^lNil#RanRhanyR|1ElkuHod0Ova0DroGe)%J%Lbl*dL{rhL _LmocLry[Nk'Ran^RzeS_#SkrzeSn?SpoduS)Ter.Ver#3B,%}rDeoh,D.D+LaN?S{Tal aZeZ #0Ezd0L`Us0Aj#AkAs>EvoHk(IvN'#Oup!1Uc|Uk0DaDiv(Doz&kD$voJ@skyJ&JskoLantL[L LnoSk'#Zid]Z'&0Ravo1Ab>A%tAhA)Ba}o+kH!StvaTu+0Ad T*p Tup0Ip4Bav Br!}|D!D,Fot H+d!H~Hod H,d Hub Jasn J{Jm=K]p Kon!L-!Maz!Mez Miz{Mys+tNe/!Nik!Nut P`!Pl! P,v Pu$ Raz R'n!Rv!Sl' SokoS)v Su~Syp!Tas Tes!Tr! Vi~Vol!Vrh_Zdob Zn!0AduBud }op DJ{Ji$ K+p!K*p Lep Mez Mot!Mys+tNe/!Nik!Pl! Poj Ps!Raz S)v Su~Taj Temn Tk~Ujm=Val Ve+tVin Vol!Vrt!Zvon 0Av RusuUd|Yt-1A+#ArmaAtn(IvoOb RojVihYm`]0L@.ManM.Pt!Z`uZdola2At Lt~Lubo#Ot' Ru[0MaMn?0Emn 0Lam!Oum!R!#Umav#0AtoEh#O[OmO$Ozvyk0Ap|ArAt-IjeIz{Ocn Odr!Rzl.Ut|0AkAl(Am@!Ovu0B,z Tav Ub-Ufa+0Lod Omal RavaR( Rud#Rvu1A^An C`]N (NoOv&Y/l Zav(1I/aR! 0B'.Br0Ed~EnkuEs_aOnR!Uk'odYk\";\nconst checksum = '0x25f44555f4af25b51a711136e1c7d6e50ce9f8917d39d6b1f076b2bb4d2fac1a';\nlet wordlist = null;\n/**\n * The [Czech wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/czech.txt) for [mnemonic\n * phrases](https://en.bitcoin.it/wiki/BIP_0039).\n */\nexport class LangCz extends WordlistOwl {\n /**\n * Creates a new instance of the Czech language Wordlist.\n *\n * Using the constructor should be unnecessary, instead use the {@link wordlist | **wordlist**} singleton method.\n *\n * @ignore\n */\n constructor() {\n super('cz', words, checksum);\n }\n /**\n * Returns a singleton instance of a `LangCz`, creating it if this is the first time being called.\n */\n static wordlist() {\n if (wordlist == null) {\n wordlist = new LangCz();\n }\n return wordlist;\n }\n}\n//# sourceMappingURL=lang-cz.js.map","const Base64 = ')!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_';\n/**\n * @ignore\n */\nexport function decodeBits(width, data) {\n const maxValue = (1 << width) - 1;\n const result = [];\n let accum = 0, bits = 0, flood = 0;\n for (let i = 0; i < data.length; i++) {\n // Accumulate 6 bits of data\n accum = (accum << 6) | Base64.indexOf(data[i]);\n bits += 6;\n // While we have enough for a word...\n while (bits >= width) {\n // ...read the word\n const value = accum >> (bits - width);\n accum &= (1 << (bits - width)) - 1;\n bits -= width;\n // A value of 0 indicates we exceeded maxValue, it\n // floods over into the next value\n if (value === 0) {\n flood += maxValue;\n }\n else {\n result.push(value + flood);\n flood = 0;\n }\n }\n }\n return result;\n}\n//# sourceMappingURL=bit-reader.js.map","import { assertArgument } from '../utils/index.js';\nimport { decodeBits } from './bit-reader.js';\nimport { decodeOwl } from './decode-owl.js';\n/**\n * @ignore\n */\nexport function decodeOwlA(data, accents) {\n let words = decodeOwl(data).join(',');\n // Inject the accents\n accents.split(/,/g).forEach((accent) => {\n const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);\n assertArgument(match !== null, 'internal error parsing accents', 'accents', accents);\n let posOffset = 0;\n const positions = decodeBits(parseInt(match[3]), match[4]);\n const charCode = parseInt(match[2]);\n const regex = new RegExp(`([${match[1]}])`, 'g');\n words = words.replace(regex, (all, letter) => {\n const rem = --positions[posOffset];\n if (rem === 0) {\n letter = String.fromCharCode(letter.charCodeAt(0), charCode);\n posOffset++;\n }\n return letter;\n });\n });\n return words.split(',');\n}\n//# sourceMappingURL=decode-owla.js.map","import { WordlistOwl } from './wordlist-owl.js';\nimport { decodeOwlA } from './decode-owla.js';\n/**\n * An OWL-A format Wordlist extends the OWL format to add an overlay onto an OWL format Wordlist to support diacritic\n * marks.\n *\n * This class is generally not useful to most developers as it is used mainly internally to keep Wordlists for languages\n * based on latin-1 small.\n *\n * If necessary, there are tools within the `generation/` folder to create the necessary data.\n *\n * @category Wordlists\n */\nexport class WordlistOwlA extends WordlistOwl {\n #accent;\n /**\n * Creates a new Wordlist for `locale` using the OWLA `data` and `accent` data and validated against the `checksum`.\n */\n constructor(locale, data, accent, checksum) {\n super(locale, data, checksum);\n this.#accent = accent;\n }\n /**\n * The OWLA-encoded accent data.\n *\n * @ignore\n */\n get _accent() {\n return this.#accent;\n }\n /**\n * Decode all the words for the wordlist.\n *\n * @ignore\n */\n _decodeWords() {\n return decodeOwlA(this._data, this._accent);\n }\n}\n//# sourceMappingURL=wordlist-owla.js.map","import { WordlistOwlA } from './wordlist-owla.js';\nconst words = \"0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_LoAmpuAnc]ApaAr]I>Is)IvoOqueOzaUle%Up 0Cl.EgoE=EnEr#F[G +M->NeN%P_sR>Rue]SneTaU{d2Am^AnA+AseAveI,)ImaInica2B_Cc~|i'Ci`CoDigoDoF_G!He)JinJoL/ch/eg$Lg Lin/l LmoLum`Mba)M!Mi{Mo&Mpr-deNej}g-oc!Nsej}t PaPi(az.Rba%RchoR&nR.(r!S!SmosS%2AneoAt!E Ec!Ei&EmaIaIm,Ip%IsisOmoOnicaOque%U&Uz2Ad+Ar#At+BoBr*| aEl=En#Er{Es%EvaId Lebr/p/#Mb_Mpl*N-e%O%P.Pul( R$Se'Sf[zVaVi'5BleCeL^Ming}N Ra&Rm*RAu%EchaOrO%U*UjoU^2B@CaGa%G.L$Lle#N&Rm(+Rtun(z SaTo2AcaA'AsaAtisAveIe%Il=IpeIsI#OG Gu!aJaMb_Ng}^Nr((mig('St?Yo5E>ElgaEr%ENgl-$Nt Pit!R S#V,?Zg :7Lo5A]:B$C$C[DoD+nG #GrimaGu`I>M!Mi`Mp --ch-gos%NzaPizRgoRvaStimaTaTexT*U_lV Zo3AlCc~|eC#rErG~Gumb_Ja'Ngu-#NaOnOp &S~TalT[VeY,{3B!%dB+C^D!Di EnzoGaG!oMaMi)M.Mp$NceN&Ne-go)N}t!`Qui&SoS%T!aT$T+2AgaAmaAn#AveEg En Ev Or Ov!Uv@2BoC~CoCu[GicaG+MbrizM}jaTe5|aC*G J}-esPaSt+ToZ:Ce%|oD!aD_Du+Est+F@G@GoIzL{dLe%Ll/oMaMboMutN>N&Nej Ng-iquiNj N}Re(f?Rg,Ri&RmolR+nR)sRzoSaSc aSivoT T!@TizTrizXimoY^Z^ca3|aDal]D$Du]J?]J^L,/.M^i-^NsajeN)NuRca&R,gueRi#SS.TaT!To&T+Zc]3E&ElEmb+G/Lag+Lit Ll.M}-!}im}u#OpeR SaS!@S?SmoTadTo5|?aC~DaDe=HoJ LdeL!Li'M,#Mi- c-ed-j-#NoRad(d!Re'R*R+Rs(%lScaStr TivoV!V?Zo5|oD EbleE]Er)Est[G_J!L/e%L%N&Nec(alRoScu=SeoSgoSicaS=:C C~D IpeRanj(izRr SalTalTivoTu[lUseaValVeVi{d3C$Ct G Goc$G+OnRv$ToUt+V V!a3|oDoEb]E#NezNoTi&Vel5Bleza|eMin(i(m()TaTic@Va#Ve]V$5BeCaCleoD?=DoE[EveEzLoM!oTr@:Sis0EC~E[In On!T TicaUes#1Ac~A&rAlBi%CaD,EjaGa'G@Gul=I,)Ig,Il]OQues%Uga0Ad@Cu+Ez'OT[0O'Ro1EjaU=1I&Ige'0En)0O':C#D_El]Gi`GoIsJ oLabr/>Le%Li&Lm/om/p NNalNi>Nt!-ue=PaPelP?]Que)R Rcel(edR*RoRpa&RqueR[foR)S SeoS~SoS%TaT$Tr@UsaU%VoYa<3A#nCa&C!a|oDalD*G IneL L{'Le/ig+LlejoLoLuc--s N.OnOrPi'Que'R(ch(d!Rez(f?Ri>Rl(mizEgun%Em$EnsaE|!oD^Eb=Er%Es#Lg/*Lm.LpoLrNd*N%P #Pet*PoN{PaP!oSaScaSt+T 5BiB^DoE{G*I&In/e%LoMboM^Ptu[TaTi`:Ba&B!B$BleC GazG[&L/&L!oL*Lm.L.Ls/#LudLv Mb-c~Ndi-e Ng_Ni{dN}#PoQueRdin()nSt_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv!Mab#S/-0Ou,Us,1Arm Chim+Er&Geb!G)I_ I?ntLeg Lia.Lou Lum O'd*PagaTesS' TicotT!Tu-0El>O?RiumRo-Ta^T_%fT* Trap 0Ba(eB .Da-Dib#G' Ro!Tom[Tru~e0A]Anc Ari-En*EreNqu>Rb>R`R$R^Rra.Ss(S%$Ta`#Te|T,+Udr>Vard 3Let&L>Lo&Nefi-R-|Rg Rl(eRmudaSa-Sog[Ta`Ur!3B $Cyc#Du#JouL/L(g)LlardNai!Olog+Ops+OtypeScuitS$Sto'iTu?Zar!2AfardAg)An~*Ess/tInd OndOqu Ous$2BardB(eI!I}Li@Nb$Nd*Nhe'Nif>NusRdu!R[T&Uc#Ue{Ug+Ul$Uqu(UrAveEbisE~eEuva.Ico]Iga@Ill/tIo~eI^O~u!Od Onz OusS^Ssu!U}U%$V=>V [Viar3D`#Intu!Les&Llu#Ndr>Ns' Ntr=Rc#Rebr=RiEr~ Ev=I_Iff!Ign$Im eIotLoru!OcolatOis*OI_tIgn ImatIva.O~eOna.Opor&2B=tBraCasFf!Gn Hesi$Iff Inc L eLibriLl(eLma,L$elMbatMed+Mm/@MpactNc tNdui!Nf>N.]Nno,Ns$[NtactNvexePa(P+Ra`Rbe|Rda.Rni~eRpusR!ctR&.Smi^Stu?T$U@Upu!Ura.U&|Uvr*Yo&2AbeA(&Ava&Ay$Eatu!Edi,E?{Eu}Evet&Ib]I Ist=I,eOi!Oqu Ota#Uci=UelYp,2Bi^E`l*Il]eIs(eIv!Lm( L%v Mu]Pi@Ra%fR<'3Anu!C#L(d!Ni^:Ign M>Ng N<'Uph(3Batt!Bi,Bord Brid But/tC= Cemb!Ch* Cid Clar Cor Cri!Cup]Da#Duc%fEsTa~ Tes,To' T!sTa%$U/>Ub#U-'U,Y_2Ag$Ap Es}Ibb]Oitu!2P +P#xeRab#Rc*3Nas%e:0Lou*0Ar,HarpeHel#La* LipUqu 1Fac Fec%fFig+FortFray Fusi$0Ali}Ar 2Ec,1Abor Arg*Ectr$Eg/tEph/tEveIgib#I%s?O.Ucid Ud 0B=]Bell*Bry$Er|@Issi$M_ O%$Ouvo*P e'Ploy Por,PriTo' Trav Um Vah*Viab#Voy Zy?0L+n0Aiss*Arg[At/tAu#Ic +I@m+I Ilog)I[Iso@ItapheO^ReuveRouv Uis/t0U !Uipe0Ig Osi$Re'Up%$0C=>Pad$Pe-P+g#Po*PritQuiv Say S_-S+uSor Ti?TomacTra@0Ag eA]An~eA%^E(d!Endo*Er[lH/olHi^Hn+Ir Off Oi#Onn/tO'd*R/.RoitU@0Phor+0Alu Asi$Enta`I@n-I,Olu%fOqu 1ActAg Auc Cel]Cit/tClusifCuPlor Po}Prim QuisT_sifTrai!Ul,:B#Bu#{Cet&Ci#Ctu!Ibl*Lai3AscoCe]C%fDe#Gu!Latu!Leta.L>eL#ulLm LouLtr N/c N*O#R?Ssu!X 2A* Am?As^At&'E|E~eE'Exi$Oc$O!Uctu Ui@Uvi=2L+Nd +Ngib#Nta(eRc Rg $Rmu]Rtu[Ssi#Ud!Ug eU`]Ulu!Urmi2Agi#AiC]RafeV!2A-AiveIs}ObeOi!Or+{2Lfe'M?Nf]R.R`#Udr$Uff!UlotUp`#Urm/dUt&2Ad)lAffi%A(eAndApp(AtuitAv*EnatIffu!Il]Imp Ogn Ond Ot&OupeUg U% Uy e2EpardErr>I@Im|veIta!Sta%f3Mnas&Rostat:Bitu@Cho*L&Me|NgarN[t$RicotRm$+Rp$Sard3LiumMato?RbeRiss$Rm(eR$Si,U!{3B n BouLar/tStoi!V 5MardMma.Mo.[N['Nor N&{R@Riz$Rlo.Rm$eRrib#U#{Us<5BlotI#{Ma(Mb#Mi@Mo'R]3Dro?lG+[M[Pno<:2Yl#2Nor U/e4Lici&Lusi$0A.Bib I,M_ReelRi,0O]2Oi!Res<:GuarIll*MbeNv>Rd(Ug U[Velot3Tab#T$UdiU[s<9Ind!N~ Ng]Ue'UissifUrn=Vi=Y|Ye{5Bi]Ge?ntNiorP$Ris&S%-Te{V_i#:Yak7M$oOs^:BelBi=Bo' C CtoVaboVo*3Ctu!G=G Gu?SsiveTt!V>Xi^Zard3AseS,ThiumTi.Ttor=V!'5Gi^Inta(Is*MbricT +U UrdUt!UveY=5B+Ci@Cra%fE'Gub!Is/tM>eNai!NdiR$T,X){:Ch(eGas(G_taGi^Ig!Ill$In%_Ir+Is$Jor Lax Lefi-Lhe'Li-L#t&MmouthNda,Niab#Nqu/tN&|N)lRath$Rb!R~/dRdiRi%?R^'Rr$R&]Scot&SsifT +lT>eTra^Udi!Ussa@UveXim=3Ch/tC$nuDa`#Dec(Di,DuUb#3Au]CrobeEt&Gn$Gr L+uLli$Mi^N-N =Nim=Nor Nu&Rac#Roi,Ssi#X&5Bi#D [El#{Ndi=Ni&'Nna+Not$eNst!Ntag[Nu?ntQ)'R-|Rsu!R% Te'TifU~eUf#Ul(Uss$Ut$Uv/t5L%p#Ni%$Ra`#Re[Rmu!Sc#SeumSic+nTa%$T T)l3Ria@R%l#S,eThi^:Ge'PpeRquoisRr Ta%$Ti$Tu!Ufra.U%^Vi!3Bu#{CtarFas&Ga%$Glig Goc>I.Rve{Ttoy Ur$eUtr$Veu3CheCkelTra&Ve|5B#CifCt'[Ir-'IToi!Urr*Uve|Va&'Vemb!Vi-5A.Anc I!Isib#M oP%=Q)Tri%f:0E*Jec%fLig Sc'S v Stac#T_*T' 0Casi$Cup E/Tob!Troy Tup]Ulai!0E'Or/t1F_}Fic>Fr*0Ive1Se|S`l$2Fac%fIv>0Bra.Ett!0Ct){Du]E!{Iri^1A#A^Er Ini$PortunPrim T Ti^1A.{An.Bi&D$n E`#G/eG)`Ifi-Ne?ntQ)T+0C`]MoPo,PyrusRadoxeR-l#ResIss$Iv!Lai!Lic>L#nLyg$eMma@Mp>Nct)lNd NeyR%^Si%$SZz#3Rami@:99AsarE!l#Es%$Ietu@It,O%_t:C(eC$,D+{G$d(I@'Is(L_%rLl$.Mas}Pi@Sa.Tis}Vag V(Y$n 3Ac%fAg*Ali}Anim Cevo*Ci,Clam Col,Cru,Cu]Cyc]Dig Dou,Fai!F#xeForm Fra(Fu.G=+nGi$Gla.Gul>I, Je,Jou La%fLev L+fMar^Me@MiPor,Prie5Che{M/-Mp!N-Nd(Se|S>Ta%fTorTu#U.U`#U#|U%[Y|?5B/BisCheEl#G){In Is<|S S%^3Th?:B]Bo,B!Co~eFariGesRcas?Rd(eT' Ug!nuUm$U,Uva.V/tV$n 1AlpelAnda#E]atEnarioEpt!HemaI_-Ind O!Ru%nUlp,1An-Cab#Ch Cou C!,Da%fDui!Ig['Jo'Lec%fMa(eMb]M_-M(=Na&'Nsib#N&n-Par Q)n-Re(R.ntR+{Rru!RumRvi-Sa?V*Vra.Xtup#3D =Ec#Eg Ff]G#Gn=L_-LiciumMp#Nc eNist!Ph$RopSmi^Tu 1I 3Ci=C#DiumIg[{LdatLe`Litu@Lub#Mb!M?`Mno]N@N.'N[t&No!Rc>R%rS+T%Rfa-Rica&R?n RpriC%#Il]L_tLism/L$n Mbo'Mi}Ngib#PisQu( Rd RifR%[SI$I^Itai!Iv s3AniumBa(Tic/t0A.I[UelU!0I#Op+:Car?Cc(Gab$dG)Ill/tInc!Is<|Lab#LiSe{Ss=S&3C&'Det&Get=Hicu#InardLo-Nd!diN Ng Ni?{Ntou b) {\n return 1;\n }\n return 0;\n }\n // Load all the words\n for (let length = 3; length <= 9; length++) {\n const d = data[length - 3];\n for (let offset = 0; offset < d.length; offset += length) {\n const word = [];\n for (let i = 0; i < length; i++) {\n const k = mapping.indexOf(d[offset + i]);\n word.push(227);\n word.push(k & 0x40 ? 130 : 129);\n word.push((k & 0x3f) + 128);\n }\n wordlist.push(toString(word));\n }\n }\n wordlist.sort(sortJapanese);\n // For some reason kyoku and kiyoku are flipped in node (!!).\n // The order SHOULD be:\n // - kyoku\n // - kiyoku\n // This should ignore \"if\", but that doesn't work here??\n /* c8 ignore start */\n if (hex(wordlist[442]) === KiYoKu && hex(wordlist[443]) === KyoKu) {\n const tmp = wordlist[442];\n wordlist[442] = wordlist[443];\n wordlist[443] = tmp;\n }\n /* c8 ignore stop */\n // Verify the computed list matches the official list\n /* istanbul ignore if */\n const checksum = id(wordlist.join('\\n') + '\\n');\n /* c8 ignore start */\n if (checksum !== '0xcb36b09e6baa935787fd762ce65e80b0c6a8dabdfbc3a7f86ac0e2c4fd111600') {\n throw new Error('BIP39 Wordlist for ja (Japanese) FAILED');\n }\n /* c8 ignore stop */\n _wordlist = wordlist;\n return wordlist;\n}\nlet wordlist = null;\n/**\n * The [Japanese wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/japanese.txt) for [mnemonic\n * phrases](https://en.bitcoin.it/wiki/BIP_0039).\n */\nexport class LangJa extends Wordlist {\n /**\n * Creates a new instance of the Japanese language Wordlist.\n *\n * This should be unnecessary most of the time as the exported {@link langJa} should suffice.\n *\n * @ignore\n */\n constructor() {\n super('ja');\n }\n getWord(index) {\n const words = loadWords();\n assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, 'index', index);\n return words[index];\n }\n getWordIndex(word) {\n return loadWords().indexOf(word);\n }\n split(phrase) {\n //logger.assertNormalize();\n return phrase.split(/(?:\\u3000| )+/g);\n }\n join(words) {\n return words.join('\\u3000');\n }\n /**\n * Returns a singleton instance of a `LangJa`, creating it if this is the first time being called.\n */\n static wordlist() {\n if (wordlist == null) {\n wordlist = new LangJa();\n }\n return wordlist;\n }\n}\n//# sourceMappingURL=lang-ja.js.map","import { id } from '../hash/index.js';\nimport { assertArgument } from '../utils/index.js';\nimport { toUtf8String } from '../encoding/index.js';\nimport { Wordlist } from './wordlist.js';\nconst data = [\n 'OYAa',\n 'ATAZoATBl3ATCTrATCl8ATDloATGg3ATHT8ATJT8ATJl3ATLlvATLn4ATMT8ATMX8ATMboATMgoAToLbAToMTATrHgATvHnAT3AnAT3JbAT3MTAT8DbAT8JTAT8LmAT8MYAT8MbAT#LnAUHT8AUHZvAUJXrAUJX8AULnrAXJnvAXLUoAXLgvAXMn6AXRg3AXrMbAX3JTAX3QbAYLn3AZLgvAZrSUAZvAcAZ8AaAZ8AbAZ8AnAZ8HnAZ8LgAZ8MYAZ8MgAZ8OnAaAboAaDTrAaFTrAaJTrAaJboAaLVoAaMXvAaOl8AaSeoAbAUoAbAg8AbAl4AbGnrAbMT8AbMXrAbMn4AbQb8AbSV8AbvRlAb8AUAb8AnAb8HgAb8JTAb8NTAb8RbAcGboAcLnvAcMT8AcMX8AcSToAcrAaAcrFnAc8AbAc8MgAfGgrAfHboAfJnvAfLV8AfLkoAfMT8AfMnoAfQb8AfScrAfSgrAgAZ8AgFl3AgGX8AgHZvAgHgrAgJXoAgJX8AgJboAgLZoAgLn4AgOX8AgoATAgoAnAgoCUAgoJgAgoLXAgoMYAgoSeAgrDUAgrJTAhrFnAhrLjAhrQgAjAgoAjJnrAkMX8AkOnoAlCTvAlCV8AlClvAlFg4AlFl6AlFn3AloSnAlrAXAlrAfAlrFUAlrFbAlrGgAlrOXAlvKnAlvMTAl3AbAl3MnAnATrAnAcrAnCZ3AnCl8AnDg8AnFboAnFl3AnHX4AnHbrAnHgrAnIl3AnJgvAnLXoAnLX4AnLbrAnLgrAnLhrAnMXoAnMgrAnOn3AnSbrAnSeoAnvLnAn3OnCTGgvCTSlvCTvAUCTvKnCTvNTCT3CZCT3GUCT3MTCT8HnCUCZrCULf8CULnvCU3HnCU3JUCY6NUCbDb8CbFZoCbLnrCboOTCboScCbrFnCbvLnCb8AgCb8HgCb$LnCkLfoClBn3CloDUDTHT8DTLl3DTSU8DTrAaDTrLXDTrLjDTrOYDTrOgDTvFXDTvFnDT3HUDT3LfDUCT9DUDT4DUFVoDUFV8DUFkoDUGgrDUJnrDULl8DUMT8DUMXrDUMX4DUMg8DUOUoDUOgvDUOg8DUSToDUSZ8DbDXoDbDgoDbGT8DbJn3DbLg3DbLn4DbMXrDbMg8DbOToDboJXGTClvGTDT8GTFZrGTLVoGTLlvGTLl3GTMg8GTOTvGTSlrGToCUGTrDgGTrJYGTrScGTtLnGTvAnGTvQgGUCZrGUDTvGUFZoGUHXrGULnvGUMT8GUoMgGXoLnGXrMXGXrMnGXvFnGYLnvGZOnvGZvOnGZ8LaGZ8LmGbAl3GbDYvGbDlrGbHX3GbJl4GbLV8GbLn3GbMn4GboJTGboRfGbvFUGb3GUGb4JnGgDX3GgFl$GgJlrGgLX6GgLZoGgLf8GgOXoGgrAgGgrJXGgrMYGgrScGgvATGgvOYGnAgoGnJgvGnLZoGnLg3GnLnrGnQn8GnSbrGnrMgHTClvHTDToHTFT3HTQT8HToJTHToJgHTrDUHTrMnHTvFYHTvRfHT8MnHT8SUHUAZ8HUBb4HUDTvHUoMYHXFl6HXJX6HXQlrHXrAUHXrMnHXrSbHXvFYHXvKXHX3LjHX3MeHYvQlHZrScHZvDbHbAcrHbFT3HbFl3HbJT8HbLTrHbMT8HbMXrHbMbrHbQb8HbSX3HboDbHboJTHbrFUHbrHgHbrJTHb8JTHb8MnHb8QgHgAlrHgDT3HgGgrHgHgrHgJTrHgJT8HgLX@HgLnrHgMT8HgMX8HgMboHgOnrHgQToHgRg3HgoHgHgrCbHgrFnHgrLVHgvAcHgvAfHnAloHnCTrHnCnvHnGTrHnGZ8HnGnvHnJT8HnLf8HnLkvHnMg8HnRTrITvFUITvFnJTAXrJTCV8JTFT3JTFT8JTFn4JTGgvJTHT8JTJT8JTJXvJTJl3JTJnvJTLX4JTLf8JTLhvJTMT8JTMXrJTMnrJTObrJTQT8JTSlvJT8DUJT8FkJT8MTJT8OXJT8OgJT8QUJT8RfJUHZoJXFT4JXFlrJXGZ8JXGnrJXLV8JXLgvJXMXoJXMX3JXNboJXPlvJXoJTJXoLkJXrAXJXrHUJXrJgJXvJTJXvOnJX4KnJYAl3JYJT8JYLhvJYQToJYrQXJY6NUJbAl3JbCZrJbDloJbGT8JbGgrJbJXvJbJboJbLf8JbLhrJbLl3JbMnvJbRg8JbSZ8JboDbJbrCZJbrSUJb3KnJb8LnJfRn8JgAXrJgCZrJgDTrJgGZrJgGZ8JgHToJgJT8JgJXoJgJgvJgLX4JgLZ3JgLZ8JgLn4JgMgrJgMn4JgOgvJgPX6JgRnvJgSToJgoCZJgoJbJgoMYJgrJXJgrJgJgrLjJg6MTJlCn3JlGgvJlJl8Jl4AnJl8FnJl8HgJnAToJnATrJnAbvJnDUoJnGnrJnJXrJnJXvJnLhvJnLnrJnLnvJnMToJnMT8JnMXvJnMX3JnMg8JnMlrJnMn4JnOX8JnST4JnSX3JnoAgJnoAnJnoJTJnoObJnrAbJnrAkJnrHnJnrJTJnrJYJnrOYJnrScJnvCUJnvFaJnvJgJnvJnJnvOYJnvQUJnvRUJn3FnJn3JTKnFl3KnLT6LTDlvLTMnoLTOn3LTRl3LTSb4LTSlrLToAnLToJgLTrAULTrAcLTrCULTrHgLTrMgLT3JnLULnrLUMX8LUoJgLVATrLVDTrLVLb8LVoJgLV8MgLV8RTLXDg3LXFlrLXrCnLXrLXLX3GTLX4GgLX4OYLZAXrLZAcrLZAgrLZAhrLZDXyLZDlrLZFbrLZFl3LZJX6LZJX8LZLc8LZLnrLZSU8LZoJTLZoJnLZrAgLZrAnLZrJYLZrLULZrMgLZrSkLZvAnLZvGULZvJeLZvOTLZ3FZLZ4JXLZ8STLZ8ScLaAT3LaAl3LaHT8LaJTrLaJT8LaJXrLaJgvLaJl4LaLVoLaMXrLaMXvLaMX8LbClvLbFToLbHlrLbJn4LbLZ3LbLhvLbMXrLbMnoLbvSULcLnrLc8HnLc8MTLdrMnLeAgoLeOgvLeOn3LfAl3LfLnvLfMl3LfOX8Lf8AnLf8JXLf8LXLgJTrLgJXrLgJl8LgMX8LgRZrLhCToLhrAbLhrFULhrJXLhvJYLjHTrLjHX4LjJX8LjLhrLjSX3LjSZ4LkFX4LkGZ8LkGgvLkJTrLkMXoLkSToLkSU8LkSZ8LkoOYLl3FfLl3MgLmAZrLmCbrLmGgrLmHboLmJnoLmJn3LmLfoLmLhrLmSToLnAX6LnAb6LnCZ3LnCb3LnDTvLnDb8LnFl3LnGnrLnHZvLnHgvLnITvLnJT8LnJX8LnJlvLnLf8LnLg6LnLhvLnLnoLnMXrLnMg8LnQlvLnSbrLnrAgLnrAnLnrDbLnrFkLnrJdLnrMULnrOYLnrSTLnvAnLnvDULnvHgLnvOYLnvOnLn3GgLn4DULn4JTLn4JnMTAZoMTAloMTDb8MTFT8MTJnoMTJnrMTLZrMTLhrMTLkvMTMX8MTRTrMToATMTrDnMTrOnMT3JnMT4MnMT8FUMT8FaMT8FlMT8GTMT8GbMT8GnMT8HnMT8JTMT8JbMT8OTMUCl8MUJTrMUJU8MUMX8MURTrMUSToMXAX6MXAb6MXCZoMXFXrMXHXrMXLgvMXOgoMXrAUMXrAnMXrHgMXrJYMXrJnMXrMTMXrMgMXrOYMXrSZMXrSgMXvDUMXvOTMX3JgMX3OTMX4JnMX8DbMX8FnMX8HbMX8HgMX8HnMX8LbMX8MnMX8OnMYAb8MYGboMYHTvMYHX4MYLTrMYLnvMYMToMYOgvMYRg3MYSTrMbAToMbAXrMbAl3MbAn8MbGZ8MbJT8MbJXrMbMXvMbMX8MbMnoMbrMUMb8AfMb8FbMb8FkMcJXoMeLnrMgFl3MgGTvMgGXoMgGgrMgGnrMgHT8MgHZrMgJnoMgLnrMgLnvMgMT8MgQUoMgrHnMgvAnMg8HgMg8JYMg8LfMloJnMl8ATMl8AXMl8JYMnAToMnAT4MnAZ8MnAl3MnAl4MnCl8MnHT8MnHg8MnJnoMnLZoMnLhrMnMXoMnMX3MnMnrMnOgvMnrFbMnrFfMnrFnMnrNTMnvJXNTMl8OTCT3OTFV8OTFn3OTHZvOTJXrOTOl3OT3ATOT3JUOT3LZOT3LeOT3MbOT8ATOT8AbOT8AgOT8MbOUCXvOUMX3OXHXvOXLl3OXrMUOXvDbOX6NUOX8JbOYFZoOYLbrOYLkoOYMg8OYSX3ObHTrObHT4ObJgrObLhrObMX3ObOX8Ob8FnOeAlrOeJT8OeJXrOeJnrOeLToOeMb8OgJXoOgLXoOgMnrOgOXrOgOloOgoAgOgoJbOgoMYOgoSTOg8AbOjLX4OjMnoOjSV8OnLVoOnrAgOn3DUPXQlrPXvFXPbvFTPdAT3PlFn3PnvFbQTLn4QToAgQToMTQULV8QURg8QUoJnQXCXvQbFbrQb8AaQb8AcQb8FbQb8MYQb8ScQeAlrQeLhrQjAn3QlFXoQloJgQloSnRTLnvRTrGURTrJTRUJZrRUoJlRUrQnRZrLmRZrMnRZrSnRZ8ATRZ8JbRZ8ScRbMT8RbST3RfGZrRfMX8RfMgrRfSZrRnAbrRnGT8RnvJgRnvLfRnvMTRn8AaSTClvSTJgrSTOXrSTRg3STRnvSToAcSToAfSToAnSToHnSToLjSToMTSTrAaSTrEUST3BYST8AgST8LmSUAZvSUAgrSUDT4SUDT8SUGgvSUJXoSUJXvSULTrSU8JTSU8LjSV8AnSV8JgSXFToSXLf8SYvAnSZrDUSZrMUSZrMnSZ8HgSZ8JTSZ8JgSZ8MYSZ8QUSaQUoSbCT3SbHToSbQYvSbSl4SboJnSbvFbSb8HbSb8JgSb8OTScGZrScHgrScJTvScMT8ScSToScoHbScrMTScvAnSeAZrSeAcrSeHboSeJUoSeLhrSeMT8SeMXrSe6JgSgHTrSkJnoSkLnvSk8CUSlFl3SlrSnSl8GnSmAboSmGT8SmJU8',\n 'ATLnDlATrAZoATrJX4ATrMT8ATrMX4ATrRTrATvDl8ATvJUoATvMl8AT3AToAT3MX8AT8CT3AT8DT8AT8HZrAT8HgoAUAgFnAUCTFnAXoMX8AXrAT8AXrGgvAXrJXvAXrOgoAXvLl3AZvAgoAZvFbrAZvJXoAZvJl8AZvJn3AZvMX8AZvSbrAZ8FZoAZ8LZ8AZ8MU8AZ8OTvAZ8SV8AZ8SX3AbAgFZAboJnoAbvGboAb8ATrAb8AZoAb8AgrAb8Al4Ab8Db8Ab8JnoAb8LX4Ab8LZrAb8LhrAb8MT8Ab8OUoAb8Qb8Ab8ST8AcrAUoAcrAc8AcrCZ3AcrFT3AcrFZrAcrJl4AcrJn3AcrMX3AcrOTvAc8AZ8Ac8MT8AfAcJXAgoFn4AgoGgvAgoGnrAgoLc8AgoMXoAgrLnrAkrSZ8AlFXCTAloHboAlrHbrAlrLhrAlrLkoAl3CZrAl3LUoAl3LZrAnrAl4AnrMT8An3HT4BT3IToBX4MnvBb!Ln$CTGXMnCToLZ4CTrHT8CT3JTrCT3RZrCT#GTvCU6GgvCU8Db8CU8GZrCU8HT8CboLl3CbrGgrCbrMU8Cb8DT3Cb8GnrCb8LX4Cb8MT8Cb8ObrCgrGgvCgrKX4Cl8FZoDTrAbvDTrDboDTrGT6DTrJgrDTrMX3DTrRZrDTrRg8DTvAVvDTvFZoDT3DT8DT3Ln3DT4HZrDT4MT8DT8AlrDT8MT8DUAkGbDUDbJnDYLnQlDbDUOYDbMTAnDbMXSnDboAT3DboFn4DboLnvDj6JTrGTCgFTGTGgFnGTJTMnGTLnPlGToJT8GTrCT3GTrLVoGTrLnvGTrMX3GTrMboGTvKl3GZClFnGZrDT3GZ8DTrGZ8FZ8GZ8MXvGZ8On8GZ8ST3GbCnQXGbMbFnGboFboGboJg3GboMXoGb3JTvGb3JboGb3Mn6Gb3Qb8GgDXLjGgMnAUGgrDloGgrHX4GgrSToGgvAXrGgvAZvGgvFbrGgvLl3GgvMnvGnDnLXGnrATrGnrMboGnuLl3HTATMnHTAgCnHTCTCTHTrGTvHTrHTvHTrJX8HTrLl8HTrMT8HTrMgoHTrOTrHTuOn3HTvAZrHTvDTvHTvGboHTvJU8HTvLl3HTvMXrHTvQb4HT4GT6HT4JT8HT4Jb#HT8Al3HT8GZrHT8GgrHT8HX4HT8Jb8HT8JnoHT8LTrHT8LgvHT8SToHT8SV8HUoJUoHUoJX8HUoLnrHXrLZoHXvAl3HX3LnrHX4FkvHX4LhrHX4MXoHX4OnoHZrAZ8HZrDb8HZrGZ8HZrJnrHZvGZ8HZvLnvHZ8JnvHZ8LhrHbCXJlHbMTAnHboJl4HbpLl3HbrJX8HbrLnrHbrMnvHbvRYrHgoSTrHgrFV8HgrGZ8HgrJXoHgrRnvHgvBb!HgvGTrHgvHX4HgvHn!HgvLTrHgvSU8HnDnLbHnFbJbHnvDn8Hn6GgvHn!BTvJTCTLnJTQgFnJTrAnvJTrLX4JTrOUoJTvFn3JTvLnrJTvNToJT3AgoJT3Jn4JT3LhvJT3ObrJT8AcrJT8Al3JT8JT8JT8JnoJT8LX4JT8LnrJT8MX3JT8Rg3JT8Sc8JUoBTvJU8AToJU8GZ8JU8GgvJU8JTrJU8JXrJU8JnrJU8LnvJU8ScvJXHnJlJXrGgvJXrJU8JXrLhrJXrMT8JXrMXrJXrQUoJXvCTvJXvGZ8JXvGgrJXvQT8JX8Ab8JX8DT8JX8GZ8JX8HZvJX8LnrJX8MT8JX8MXoJX8MnvJX8ST3JYGnCTJbAkGbJbCTAnJbLTAcJboDT3JboLb6JbrAnvJbrCn3JbrDl8JbrGboJbrIZoJbrJnvJbrMnvJbrQb4Jb8RZrJeAbAnJgJnFbJgScAnJgrATrJgvHZ8JgvMn4JlJlFbJlLiQXJlLjOnJlRbOlJlvNXoJlvRl3Jl4AcrJl8AUoJl8MnrJnFnMlJnHgGbJnoDT8JnoFV8JnoGgvJnoIT8JnoQToJnoRg3JnrCZ3JnrGgrJnrHTvJnrLf8JnrOX8JnvAT3JnvFZoJnvGT8JnvJl4JnvMT8JnvMX8JnvOXrJnvPX6JnvSX3JnvSZrJn3MT8Jn3MX8Jn3RTrLTATKnLTJnLTLTMXKnLTRTQlLToGb8LTrAZ8LTrCZ8LTrDb8LTrHT8LT3PX6LT4FZoLT$CTvLT$GgrLUvHX3LVoATrLVoAgoLVoJboLVoMX3LVoRg3LV8CZ3LV8FZoLV8GTvLXrDXoLXrFbrLXvAgvLXvFlrLXvLl3LXvRn6LX4Mb8LX8GT8LYCXMnLYrMnrLZoSTvLZrAZvLZrAloLZrFToLZrJXvLZrJboLZrJl4LZrLnrLZrMT8LZrOgvLZrRnvLZrST4LZvMX8LZvSlvLZ8AgoLZ8CT3LZ8JT8LZ8LV8LZ8LZoLZ8Lg8LZ8SV8LZ8SbrLZ$HT8LZ$Mn4La6CTvLbFbMnLbRYFTLbSnFZLboJT8LbrAT9LbrGb3LbrQb8LcrJX8LcrMXrLerHTvLerJbrLerNboLgrDb8LgrGZ8LgrHTrLgrMXrLgrSU8LgvJTrLgvLl3Lg6Ll3LhrLnrLhrMT8LhvAl4LiLnQXLkoAgrLkoJT8LkoJn4LlrSU8Ll3FZoLl3HTrLl3JX8Ll3JnoLl3LToLmLeFbLnDUFbLnLVAnLnrATrLnrAZoLnrAb8LnrAlrLnrGgvLnrJU8LnrLZrLnrLhrLnrMb8LnrOXrLnrSZ8LnvAb4LnvDTrLnvDl8LnvHTrLnvHbrLnvJT8LnvJU8LnvJbrLnvLhvLnvMX8LnvMb8LnvNnoLnvSU8Ln3Al3Ln4FZoLn4GT6Ln4JgvLn4LhrLn4MT8Ln4SToMToCZrMToJX8MToLX4MToLf8MToRg3MTrEloMTvGb6MT3BTrMT3Lb6MT8AcrMT8AgrMT8GZrMT8JnoMT8LnrMT8MX3MUOUAnMXAbFnMXoAloMXoJX8MXoLf8MXoLl8MXrAb8MXrDTvMXrGT8MXrGgrMXrHTrMXrLf8MXrMU8MXrOXvMXrQb8MXvGT8MXvHTrMXvLVoMX3AX3MX3Jn3MX3LhrMX3MX3MX4AlrMX4OboMX8GTvMX8GZrMX8GgrMX8JT8MX8JX8MX8LhrMX8MT8MYDUFbMYMgDbMbGnFfMbvLX4MbvLl3Mb8Mb8Mb8ST4MgGXCnMg8ATrMg8AgoMg8CZrMg8DTrMg8DboMg8HTrMg8JgrMg8LT8MloJXoMl8AhrMl8JT8MnLgAUMnoJXrMnoLX4MnoLhrMnoMT8MnrAl4MnrDb8MnrOTvMnrOgvMnrQb8MnrSU8MnvGgrMnvHZ8Mn3MToMn4DTrMn4LTrMn4Mg8NnBXAnOTFTFnOToAToOTrGgvOTrJX8OT3JXoOT6MTrOT8GgrOT8HTpOT8MToOUoHT8OUoJT8OUoLn3OXrAgoOXrDg8OXrMT8OXvSToOX6CTvOX8CZrOX8OgrOb6HgvOb8AToOb8MT8OcvLZ8OgvAlrOgvHTvOgvJTrOgvJnrOgvLZrOgvLn4OgvMT8OgvRTrOg8AZoOg8DbvOnrOXoOnvJn4OnvLhvOnvRTrOn3GgoOn3JnvOn6JbvOn8OTrPTGYFTPbBnFnPbGnDnPgDYQTPlrAnvPlrETvPlrLnvPlrMXvPlvFX4QTMTAnQTrJU8QYCnJlQYJlQlQbGTQbQb8JnrQb8LZoQb8LnvQb8MT8Qb8Ml8Qb8ST4QloAl4QloHZvQloJX8QloMn8QnJZOlRTrAZvRTrDTrRTvJn4RTvLhvRT4Jb8RZrAZrRZ8AkrRZ8JU8RZ8LV8RZ8LnvRbJlQXRg3GboRg3MnvRg8AZ8Rg8JboRg8Jl4RnLTCbRnvFl3RnvQb8SToAl4SToCZrSToFZoSToHXrSToJU8SToJgvSToJl4SToLhrSToMX3STrAlvSTrCT9STrCgrSTrGgrSTrHXrSTrHboSTrJnoSTrNboSTvLnrST4AZoST8Ab8ST8JT8SUoJn3SU6HZ#SU6JTvSU8Db8SU8HboSU8LgrSV8JT8SZrAcrSZrAl3SZrJT8SZrJnvSZrMT8SZvLUoSZ4FZoSZ8JnoSZ8RZrScoLnrScoMT8ScoMX8ScrAT4ScrAZ8ScrLZ8ScrLkvScvDb8ScvLf8ScvNToSgrFZrShvKnrSloHUoSloLnrSlrMXoSl8HgrSmrJUoSn3BX6',\n 'ATFlOn3ATLgrDYAT4MTAnAT8LTMnAYJnRTrAbGgJnrAbLV8LnAbvNTAnAeFbLg3AgOYMXoAlQbFboAnDboAfAnJgoJTBToDgAnBUJbAl3BboDUAnCTDlvLnCTFTrSnCYoQTLnDTwAbAnDUDTrSnDUHgHgrDX8LXFnDbJXAcrETvLTLnGTFTQbrGTMnGToGT3DUFbGUJlPX3GbQg8LnGboJbFnGb3GgAYGgAg8ScGgMbAXrGgvAbAnGnJTLnvGnvATFgHTDT6ATHTrDlJnHYLnMn8HZrSbJTHZ8LTFnHbFTJUoHgSeMT8HgrLjAnHgvAbAnHlFUrDlHnDgvAnHnHTFT3HnQTGnrJTAaMXvJTGbCn3JTOgrAnJXvAXMnJbMg8SnJbMnRg3Jb8LTMnJnAl3OnJnGYrQlJnJlQY3LTDlCn3LTJjLg3LTLgvFXLTMg3GTLV8HUOgLXFZLg3LXNXrMnLX8QXFnLX9AlMYLYLXPXrLZAbJU8LZDUJU8LZMXrSnLZ$AgFnLaPXrDULbFYrMnLbMn8LXLboJgJgLeFbLg3LgLZrSnLgOYAgoLhrRnJlLkCTrSnLkOnLhrLnFX%AYLnFZoJXLnHTvJbLnLloAbMTATLf8MTHgJn3MTMXrAXMT3MTFnMUITvFnMXFX%AYMXMXvFbMXrFTDbMYAcMX3MbLf8SnMb8JbFnMgMXrMTMgvAXFnMgvGgCmMnAloSnMnFnJTrOXvMXSnOX8HTMnObJT8ScObLZFl3ObMXCZoPTLgrQXPUFnoQXPU3RXJlPX3RkQXPbrJXQlPlrJbFnQUAhrDbQXGnCXvQYLnHlvQbLfLnvRTOgvJbRXJYrQlRYLnrQlRbLnrQlRlFT8JlRlFnrQXSTClCn3STHTrAnSTLZQlrSTMnGTrSToHgGbSTrGTDnSTvGXCnST3HgFbSU3HXAXSbAnJn3SbFT8LnScLfLnv',\n 'AT3JgJX8AT8FZoSnAT8JgFV8AT8LhrDbAZ8JT8DbAb8GgLhrAb8SkLnvAe8MT8SnAlMYJXLVAl3GYDTvAl3LfLnvBUDTvLl3CTOn3HTrCT3DUGgrCU8MT8AbCbFTrJUoCgrDb8MTDTLV8JX8DTLnLXQlDT8LZrSnDUQb8FZ8DUST4JnvDb8ScOUoDj6GbJl4GTLfCYMlGToAXvFnGboAXvLnGgAcrJn3GgvFnSToGnLf8JnvGn#HTDToHTLnFXJlHTvATFToHTvHTDToHTvMTAgoHT3STClvHT4AlFl6HT8HTDToHUoDgJTrHUoScMX3HbRZrMXoHboJg8LTHgDb8JTrHgMToLf8HgvLnLnoHnHn3HT4Hn6MgvAnJTJU8ScvJT3AaQT8JT8HTrAnJXrRg8AnJbAloMXoJbrATFToJbvMnoSnJgDb6GgvJgDb8MXoJgSX3JU8JguATFToJlPYLnQlJlQkDnLbJlQlFYJlJl8Lf8OTJnCTFnLbJnLTHXMnJnLXGXCnJnoFfRg3JnrMYRg3Jn3HgFl3KT8Dg8LnLTRlFnPTLTvPbLbvLVoSbrCZLXMY6HT3LXNU7DlrLXNXDTATLX8DX8LnLZDb8JU8LZMnoLhrLZSToJU8LZrLaLnrLZvJn3SnLZ8LhrSnLaJnoMT8LbFlrHTvLbrFTLnrLbvATLlvLb6OTFn3LcLnJZOlLeAT6Mn4LeJT3ObrLg6LXFlrLhrJg8LnLhvDlPX4LhvLfLnvLj6JTFT3LnFbrMXoLnQluCTvLnrQXCY6LnvLfLnvLnvMgLnvLnvSeLf8MTMbrJn3MT3JgST3MT8AnATrMT8LULnrMUMToCZrMUScvLf8MXoDT8SnMX6ATFToMX8AXMT8MX8FkMT8MX8HTrDUMX8ScoSnMYJT6CTvMgAcrMXoMg8SToAfMlvAXLg3MnFl3AnvOT3AnFl3OUoATHT8OU3RnLXrOXrOXrSnObPbvFn6Og8HgrSnOg8OX8DbPTvAgoJgPU3RYLnrPXrDnJZrPb8CTGgvPlrLTDlvPlvFUJnoQUvFXrQlQeMnoAl3QlrQlrSnRTFTrJUoSTDlLiLXSTFg6HT3STJgoMn4STrFTJTrSTrLZFl3ST4FnMXoSUrDlHUoScvHTvSnSfLkvMXo',\n 'AUoAcrMXoAZ8HboAg8AbOg6ATFgAg8AloMXoAl3AT8JTrAl8MX8MXoCT3SToJU8Cl8Db8MXoDT8HgrATrDboOT8MXoGTOTrATMnGT8LhrAZ8GnvFnGnQXHToGgvAcrHTvAXvLl3HbrAZoMXoHgBlFXLg3HgMnFXrSnHgrSb8JUoHn6HT8LgvITvATrJUoJUoLZrRnvJU8HT8Jb8JXvFX8QT8JXvLToJTrJYrQnGnQXJgrJnoATrJnoJU8ScvJnvMnvMXoLTCTLgrJXLTJlRTvQlLbRnJlQYvLbrMb8LnvLbvFn3RnoLdCVSTGZrLeSTvGXCnLg3MnoLn3MToLlrETvMT8SToAl3MbrDU6GTvMb8LX4LhrPlrLXGXCnSToLf8Rg3STrDb8LTrSTvLTHXMnSb3RYLnMnSgOg6ATFg',\n 'HUDlGnrQXrJTrHgLnrAcJYMb8DULc8LTvFgGnCk3Mg8JbAnLX4QYvFYHnMXrRUoJnGnvFnRlvFTJlQnoSTrBXHXrLYSUJgLfoMT8Se8DTrHbDb',\n 'AbDl8SToJU8An3RbAb8ST8DUSTrGnrAgoLbFU6Db8LTrMg8AaHT8Jb8ObDl8SToJU8Pb3RlvFYoJl',\n];\nconst codes = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';\nfunction getHangul(code) {\n if (code >= 40) {\n code = code + 168 - 40;\n }\n else if (code >= 19) {\n code = code + 97 - 19;\n }\n return toUtf8String(new Uint8Array([225, (code >> 6) + 132, (code & 0x3f) + 128]));\n}\nlet _wordlist = null;\nfunction loadWords() {\n if (_wordlist != null) {\n return _wordlist;\n }\n const wordlist = [];\n data.forEach((data, length) => {\n length += 4;\n for (let i = 0; i < data.length; i += length) {\n let word = '';\n for (let j = 0; j < length; j++) {\n word += getHangul(codes.indexOf(data[i + j]));\n }\n wordlist.push(word);\n }\n });\n wordlist.sort();\n // Verify the computed list matches the official list\n /* istanbul ignore if */\n const checksum = id(wordlist.join('\\n') + '\\n');\n /* c8 ignore start */\n if (checksum !== '0xf9eddeace9c5d3da9c93cf7d3cd38f6a13ed3affb933259ae865714e8a3ae71a') {\n throw new Error('BIP39 Wordlist for ko (Korean) FAILED');\n }\n /* c8 ignore stop */\n _wordlist = wordlist;\n return wordlist;\n}\nlet wordlist = null;\n/**\n * The [Korean wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/korean.txt) for [mnemonic\n * phrases](https://en.bitcoin.it/wiki/BIP_0039).\n */\nexport class LangKo extends Wordlist {\n /**\n * Creates a new instance of the Korean language Wordlist.\n *\n * This should be unnecessary most of the time as the exported {@link langKo} should suffice.\n *\n * @ignore\n */\n constructor() {\n super('ko');\n }\n getWord(index) {\n const words = loadWords();\n assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, 'index', index);\n return words[index];\n }\n getWordIndex(word) {\n return loadWords().indexOf(word);\n }\n /**\n * Returns a singleton instance of a `LangKo`, creating it if this is the first time being called.\n */\n static wordlist() {\n if (wordlist == null) {\n wordlist = new LangKo();\n }\n return wordlist;\n }\n}\n//# sourceMappingURL=lang-ko.js.map","import { WordlistOwl } from './wordlist-owl.js';\nconst words = \"0torea noica!iosorolotaleratelanena%oiadoencotivomai t ca%a0A]Bagl'Bin#E.Is(Oli!Rasi_Rog#0Cade!C[$Cus#E Roba+U 0Ag'Deb{DomeEgu#Eri!IpeOtt&Ul&1Fabi,Fe|Fis(F-n Oris`O(R~$0AveEn.E_,Ganc'I!It&OnismoR>*Rume Uzzo4AbardaA Bat)Ber#BoBumeCeCol>E|Ertu-OdePari!Pe^ Pogg'P)@Pun Ri,1Ab~AchideAgos+Ald~Anc'Atu-AzzoBit)Chiv'D{Eni,G[ GiSoTef%eZil*0Ciu|Col EpsiEtt>Fal I$O/Pir#P)Sagg'SeSolu Sur@TaT[u T%eT-|0Av>EismoOm>O$TesaTiv&Tor$Tr{Tua,0Sil'Str?Tis+To$moTun$0Anz#E!V[i!Vi(Volge!3IoS(Tos+Ttu U,VaVosa3C]FfaLg'LvaNdaNe_,Nig$Nzi=ReRli=Ta3Bi+CiDoR@S]Tan>T^$Zzo*2Acc'AdipoA`An}Avu-E.l/Eve|EzzaIgl?Il/n.Ind&Oc]*O@Onzi=Ul*U$2BboT+di$UffoVet+Vi,2Ass>In~O)2C]Dar@D%eE!n.G$meLl&Lm#Lo!Lpo(L^v#LzaMaMe+M`n@Mo@Mpu.rMuS+n.Ttu-V#2A.!Avat+E#Ede!Emo(Esci+E+Ice I=,IsiIt>OceO=}Os++Uc?,Us}2Ci!Cu*Gi$Ll#Po/R#!R(!R_Sci$S de:DoI$L`+Meri$Nie/N$(Nz&T#Van^Vve)3Bu|C[n'Ci(Cli$Col*C! D%#Fin{FormeG$Leg&Lfi$Lir'L+M[zaNot#Nt)Pos{Rapa+Riv&RogaScri|Ser Sider'Sume!Tersi_Vo 3Amet)Cemb!Ed)Fe(Ffu(Geri!Gi+,Luv'Nam>N=nziPin P*`Po*Rad&ReRo|RupoSag'Sc! Sf&Sge*Spos S+nzaSu`$ToVa$Vel Vide!Vor#5B*I}MoSaU(0An#B,`Es(I)O^_Oz'U*0Dem>Du)Erg?FasiO.}Tr&Zi`1A^.I*goI(d'O},Pu!0U#!0Ar'BaBo(EdeEmi+Ige!Met>OeOsi_Ran.0Ago$AmeAnimeAudi!CaEmp'Erc{Ib{Ig[.Is.!I OfagoOrt#O(Pan(P!s(S[zaSoTe(Tim&Ton?T)(Ult&0Il>N>Rus]To0ClideoRopa0A(Id[zaIt#Olu Viva:Bbr~Cc[daChi)L]Migl?Na,Nfa-NgoN+s`ReRfal/Ri$(R`]Sc?S (Sul*T%&ToVo*(3Bb!Co/DeG#LpaLt)Mmi=Nde!Nome$Rm[ R)R^,Ssu-S^_T+U@3AbaDuc?FaGur#LoNanzaNest-Ni!O!S},S>Ume2A]Cacc?Co(Der#Gl'La+Lc*!Lgo!Nd[.Net>N?N+=Rb{Rchet+Res+Rm~R='RoR.zzaRz&Sf#S(2A}s(A=Assi$A.l*Eccet+E=+Es]IgoOlli$OndeUga,Ut+2Ci/+Cs?Gg[.LmiT Ud'ZeboZzel/3CoLa^=L(Mel*Mm#NeN{!N='No^poRgo2Epar@Iacc'Isa0Al*LdaNep)Oc&Oiel*Or$OveR#RoAmmoAndeAtt&A_(Az?E}EggeIfoIll'O*RaR>Roge$2IeLude!0Bal*Bevu Boc]Bu MaO.siP~1IdeLandaOn>Rig#Ror&0Ol#O poTer>Titu Tr%e0Al?Er&:::Bb)Birin C}Cer#Cri`Cu=D@veGoMpoNcet+N.r=R@(RgaRingeSt-T[zaTi$TtugaVag=Vo)3Ga,Gge)MboN.zzaNzaOGl?G<.G)Iol~LafedeLg-@Lin.(Lsa$L Lumo!NaNc?N@r/Ngi&Nifes N=)Nov-NsardaN^deNubr'PpaR#=Rci!Ret+RmoRsup'Sche-Ssa?S^$Te-s(Tr>/T Ce=.DesimoDit&GaLassaLisLod?NingeNoN(/Rcur'R[daR*Schi$SeSse!S *Tal*To@T.!3Agol&CaCel'Che,C)boDol*E,Gl'!La$Li.MosaNe-,NiNo!Ri$R^l*Sce/SsivaS Sur&TezzaTig&T-T.n.4Emon>0Del*Dif~Du*Ga$G'LeLos(Nas.)N]Ndi=Ne+r'Ni,No $N(3Cch?NfaTi@5Bi,Ci_DoMeMi=Rd>R`,RvegeseSt-$T&Tiz?Ttur$Vel/5C,oL/Me)O_Tri!Vo/Z?,:Si0Bedi!BligoElis]L'O*So, 0Cas'B-EgaIss'<0Do(E!IceNi_)O!_,Ta1Er#In'IgiDel/D)Ri.RolisiTo2AceboAn&As`A+$E=r'2ChezzaDe)(DismoEs?Ggi&L[+Ligo$Ll%eLmoni.Lpet+L(Lt)=Lve!M%eMo@)N.Po*(Rfi@Ro(Rpo-R!R++SaSi^_Sses(Stul#Tass'Te!2AnzoAssiAt~Eclu(Ed~Efis(Egi#Elie_Eme!E$t&Epar#Es[zaE.s Eval(I`IncipeIv#Ob,`Ocu-Odur!OfumoOge|OlungaOmessaO$meOpos+O)gaO.(OvaUd[.Ug=Ur{0Iche1Bbl>D~Gil#G$LceL{Lsan.Nt&PazzoPil/Ro:99Ad)Al]saAsiE!/O+:C]l D@pp'D~,Dun#Ff~GazzoG'*Dur!Fas&F,s(For`Fug'G&Gett#Ghel*Lass#Lev#MaT)_Un'Bus Cc?CoDagg'De!D{!G{Ll'Mant>Mpe!Nz'Sol&SpoTan.Ton@Tu/Vesc'5BizzoBr~GaLli$Mi:B#Bbi&Bot#Go`Las(Ldatu-Lgem`Liv&LmoEtt)HedaHie=IarpaI[zaInde!IppoI)ppoI_*Ler&Odel/Olp{Ompar Onfor Opri!Or+Os(Mul#Nfon?Ngo*Nist)NoN.siNu(idePar'S`S ,Tu#2It+Ogatu-Ove$0Arr{Emor#En^ E-l@IlzoOnt&Ott#Uss#0Elli!Erv#O@0BbalzoBr'C]r(C?,Da,Ffi|G$Ld#L[M`NdaNe|Nnife)Pi!Ppe(P-Rge!Rpas(Rri(R(R.gg'R_l#Spi)S+T^,0AdaAl/Arge!A /Av[ Azzo/EcieEdi!EgRappoReg#Ridu*Rozz&Ru|Ucc&UfoUp[@0B[t)C](Do!Gger{GoL+$On&PerboPpor Rgel#R)g#Ssur)Tu-0Ag&EdeseEgl'El&Enu Ez?IluppoIs+Izze-Ol+Uot&:Bac]Bul#Cci&Citur$LeLis`$MpoVer=Vo/+Zza3CaCn>Lefo$Me-r'MpoMu N@Pog-foRagg'RoTan'To*Tuban.Z'Zzo<5Cc&L,r&L Mbo/MoNfoNsil/Paz'Po*g?PpaRbaRn&R)L,t+Lo)(Lut&L_/Mpa+Ng&N{(NoN+gg'Nve-Po!Ra$Rc#R?n.S}3Det+DovaDu Ge+,I]*Lc)Li=Llu LoceN#Ndemm?N RaceRba,Rgog=Rif~RoRru}Rt~,Sc~Ssil*S+,Te-$Tri=Tus 3Andan.B-n.C[daChingoCi=nzaDim&Gil?G< Go!LeL/$MiniNc{!O/Pe-Rgo/Ro*goRu,n S](S'5Cche)Fo*LuPpa\";\nconst checksum = '0x5c1362d88fd4cf614a96f3234941d29f7d37c08c5292fde03bf62c2db6ff7620';\nlet wordlist = null;\n/**\n * The [Italian wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/italian.txt) for [mnemonic\n * phrases](https://en.bitcoin.it/wiki/BIP_0039).\n */\nexport class LangIt extends WordlistOwl {\n /**\n * Creates a new instance of the Italian language Wordlist.\n *\n * This should be unnecessary most of the time as the exported {@link langIt} should suffice.\n *\n * @ignore\n */\n constructor() {\n super('it', words, checksum);\n }\n /**\n * Returns a singleton instance of a `LangIt`, creating it if this is the first time being called.\n */\n static wordlist() {\n if (wordlist == null) {\n wordlist = new LangIt();\n }\n return wordlist;\n }\n}\n//# sourceMappingURL=lang-it.js.map","import { WordlistOwl } from './wordlist-owl.js';\nconst words = \"0arad!ototealirertainrasoent hoandoaR#riareha!aroele'oronul0Aca%AixoAl A%rDuz'El]Er$IsmoO$ Rum S-&T(i&TigoVo[=0F&.Il#P' S?S* So&/Sun$Tr&0Ac#Adu+Al/A[f E End(Er_EuIng'Ir?IvoOl{oRac Revi=RizU&Um0Di$rM-.R>o+TismoT|@Tu 0Ali An%Ar@Ent&Es,I?Is Ul,1Ila1Ar E=Ei%Ulejo:B BosaC&]uCh `C@GagemI+c>~/Se#S)n%Ta)Te=rTidaTomTuc Unil]3B(IjoIr^IsebolLd!eLezaLgaLisc Ndi$Ng&aNz(RimbauRl*d>_Sou_XigaZ(_3CoCu=En&Foc&Furc G|naLhe%Mest[Mo$rOlog@OmboOsf(aPol Rr-$Scoi$Sne$SpoSsex$TolaZ _2Ind#OcoOque 2A$BagemC#CejoChec]Ico.L^LetimL]LoMb{oNdeNecoNi)Rb~h>d>e&R+c]V*oXe?2AncoAsaAvezaEuIgaIl/Inc OaOchu+Onze O$Uxo2C]DismoF LeRacoScaS$Z*a:Bimb Rn{oRpe%R['>)zRv&/SacoScaSeb[S%loS~oT a)Tiv UleUs?U%l V&oV(na3BolaDil]G}]Lebr L~ Nou+N,N%ioRc Rr#R%'oRvejaTimV^2Aco)Al{aAm#Ap^ArmeAticeAveEfeEg^E'oEqueIco%If[In`oOc&/Ov(UmboU.Uva0CatrizCl}eD!eD['aEn%Gcui$Rurg@T 2A[zaE_Ic OneUbe2A=Ag'Ba@B($rBr C^El/Ent_E,Gum`oIb'IfaIo%L L{aLh(Lid'Lme@L}oLunaM<=Mb* M-.MitivaMov(MplexoMumNc]N=rNec.Nfu,Ng` Nhec(Njug Nsum'Nt+$Nvi%Op( P{oPi?PoQue%lRagemRdi&Rne)R}h>p|&R[ioR%joRuj>voSs-oS%laT}e%U_UveVilZ*]2A%+AvoEcheE=rEmeErEspoI^Im*&Io~oIseItic Os)UaUz{o2B+m SafioSbo.Sc<,S-/Sfi#Sgas%Sigu&SlizeSmam SovaSpesaS)queSvi T&h T-$rT} Tri$UsaV(Vi=Vot#Z-a3Ag+maAle$Da)Fu,Gi.Lat#Lu-%M*u'Nast@Nh{oOceseRe$Sc[)Sf ceSp oSque%Ssip S)n%T?UrnoV(,Vi,rV~g Z(5Br?L|i=M?M*#NativoNz`>m-%Rs&SagemUr#U$r2EnagemIbleOg @2El EndeE$PloQues><%Vi=,:1Lod'O Olog@0Ific It&Uc#1Ei$Etiv 3E.1Ab| Eg(Ei$rEncoEv?Im* Ogi 0B goBol#Br~/Buti=EndaErg'Is,rPat@P-/P*#Polg P[goPurr Ul?0CaixeC-#Ch-%C}t_Deus Doss Faix Fei%FimGaj#G-/Glob Gom#G+x Gu@Jo La.Qu<$Raiz Rol#Rug SaioSe^S*oSop#T<$Te#Tid!eT|.Tr^T~/V(g Vi#Volv(XameX($Xof[Xu$1Id(me0Uip 0E$Gui=Ra)VaVil]0Bopeu0Acu Ap| AsivoEntu&Id-%Olu'1Ag(oAl Am* A$Aus$Ces,Ci.Clam Ecu.EmploIb'Ig-%On( Pof>p>tu+T@T|V|i)X*aZ-da3Ch#Ijo^I+n%L*oM**oNdaNoR>i#RrugemRv(S%j T&Ud&3ApoB_seC Ch{oGur#L{aL/LmeLtr RmezaSg^Ssu+TaV`aX?Xo2AcidezAm*goAn`aEch^O+Utu Uxo2C&C*/Foc GoGue%IceLg#Lhe$Rj Rmig>noR%ScoSsa2Aga)AldaAngoAscoA%rnoE'aEn%E.IezaI,Itu+On]Ustr U%'a2G'L+faSodu$S$TaTil/Ve)Z`a3L#Le@LoM^M(Mi=N(o,NgivaNi&NomaN_Ologi>?Rm* S,S$r3Nas)Nc*o2Aci&IcoseOb&Orio,2ElaIabaLfeLpe Rdu+Rje)R_S$,T{aV(n 2AcejoAdu&Afi%Al]AmpoAn^Atui$Ave$AxaEgoElh EveIloIs&/I.@Os,O%scoUd#Unhi=U)2AcheA+niAx*imEr[ I Inc/Is#LaLo,Ru:Bi.Rm}@S%V(3C.eRd Res@Si.3A$B(n D+.EnaNoPismoPnosePo%ca5JeLofo%MemNes$Nr#Rm}&Sped 5M|#:Te2E@O,2N|#RejaUdimR_SmimToV&iZida3Jum9An*]Elh^G?I>n&Rr Vem5BaDeuDocaIzLg?L/R#Ris)RoS)::B edaB|&C[C)n%Dril/G )GoaJeMb(M-.M* MpejoNchePid P,R{>gu+S<]St_T(&Ti=VfimRgemR*/Rmi)Ro$RquiseR[coR%loRujoSco%Sm|+SsagemStig Tag&T(noT*&Tu.Xil 3D&]DidaDusaGaf}eIgaLc/Sc~ SeuSic&:Ci}&D?JaMo_R*>r#Sc(TivaTu[zaV&]Veg Vio3Bl*aB~o,GativaGoci Gri$Rvo,TaUr&VascaVo{o3N N/TidezV` 5B[zaI%IvaMe M*&Rdes%R% T Tici TurnoV`oVil/Vo5Bl#DezM(&Pci&Tr'Vem:0Cec#Edec(JetivoRig#Scu_S%t+T(Tur 0Id-%Io,Orr(Ulis)Up#2Eg<%EnsivaEr-daIc*aUsc#0Iva4Ar@Eo,H Iv{a0B_Ele%Is,It'0D~#E_,Tem1Ci}&Er?On-%OrtunoOs$1ArBi.DemD*&Fci&Rd&RedeRtidaSmoSs#S%lTam T-%T* T_noUl^Us 3C~i D& Dest[D@t+D+G^I$r&IxeLeLicplexoRsi<>%nceRucaSc#SquisaS,aTisc 3AdaC#Ed!eGm-$Last+Lh#Lo.M-)Nc`NguimN]No%N.On{oPocaQue%ResRue)Sc S$laTg-$Rje)Tur Ud!eXof}eZ}&3C C~ DaD-$Di#Do,Du$rGm-$G[=Gun=IvaLe$LvagemM<&M-%N?N/rNsu&Nt#P #Rei>*g>+RvoTemb_T|3GiloLhue)Lic}eMetr@Mpat@M~ N&Nc(oNg~ NopseN$ni>-eRiTu#5B(fis)Rp[s>[&Rt'Sp'oS%n$:B`aBle%Bu^C/G `aLh(LoLvezMdioRef>j>+xaTuagemUr*oXativoXis)3Atr&C(Ci=Cl#Dio,IaIm Lef}eLh#Mp(oN-%N,rN.Rm&RnoRr-oSeSou+St#ToXtu+Xugo3A+G`aJoloMbr MidezNgi=N%'oRagemT~ 5Al]C]L( LiceM^Mil/N`Ntu+Pe%R>ci=RneioRqueRr!>$S.UcaUp{aX*a2Ab&/Acej Adu$rAfeg Aje$AmaAnc ApoAs{oAt?Av E*oEm(Epid EvoIagemIboIcicloId-%Ilog@Ind!eIploItur Iunf&Oc Ombe)OvaUnfoUque2B~ CquesaT` T|i&:7V 3Bigo0HaId!eIf|me3Olog@SoTigaUbu0A=InaUfru':C*aDi G o,I=,LaL-%Lid!eLo[sN)gemQu{oRe)Rr(Sc~ Sil]S,u+Z Zio3A=D Ge.Ic~ L{oLhiceLu=Nce=rNdav&N( Nt[Rb&Rd!eRe?Rg}h>m`/RnizRs R%n%SpaSti=T|i&3Adu$AgemAj Atu+Br?D{aDr @ElaGaG-%Gi G| L ejoNcoNhe)NilOle)R!>tudeSi.S$Tr&V{oZ*/5A=rArG&L<%LeibolL)gemLumo,Nt!e5L$Vuz`a::D[zRope3QueRe.Rife3Ng ::Ng#Rp 3BuL?9Mb Olog@5Mbi=\";\nconst checksum = '0x2219000926df7b50d8aa0a3d495826b988287df4657fbd100e6fe596c8f737ac';\nlet wordlist = null;\n/**\n * The [Portuguese wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/portuguese.txt) for [mnemonic\n * phrases](https://en.bitcoin.it/wiki/BIP_0039).\n */\nexport class LangPt extends WordlistOwl {\n /**\n * Creates a new instance of the Portuguese language Wordlist.\n *\n * This should be unnecessary most of the time as the exported {@link langPt} should suffice.\n *\n * @ignore\n */\n constructor() {\n super('pt', words, checksum);\n }\n /**\n * Returns a singleton instance of a `LangPt`, creating it if this is the first time being called.\n */\n static wordlist() {\n if (wordlist == null) {\n wordlist = new LangPt();\n }\n return wordlist;\n }\n}\n//# sourceMappingURL=lang-pt.js.map","import { id } from '../hash/index.js';\nimport { assertArgument } from '../utils/index.js';\nimport { toUtf8String } from '../encoding/index.js';\nimport { Wordlist } from './wordlist.js';\nconst data = '}aE#4A=Yv&co#4N#6G=cJ&SM#66|/Z#4t&kn~46#4K~4q%b9=IR#7l,mB#7W_X2*dl}Uo~7s}Uf&Iw#9c&cw~6O&H6&wx&IG%v5=IQ~8a&Pv#47$PR&50%Ko&QM&3l#5f,D9#4L|/H&tQ;v0~6n]nN> 2), 128 + codes.indexOf(data[i * 3 + 1]), 128 + codes.indexOf(data[i * 3 + 2])];\n if (locale === 'zh_tw') {\n const common = s % 4;\n for (let i = common; i < 3; i++) {\n bytes[i] = codes.indexOf(deltaData[deltaOffset++]) + (i == 0 ? 228 : 128);\n }\n }\n wordlist.push(toUtf8String(new Uint8Array(bytes)));\n }\n // Verify the computed list matches the official list\n const checksum = id(wordlist.join('\\n') + '\\n');\n /* c8 ignore start */\n if (checksum !== Checks[locale]) {\n throw new Error(`BIP39 Wordlist for ${locale} (Chinese) FAILED`);\n }\n /* c8 ignore stop */\n _wordlist[locale] = wordlist;\n return wordlist;\n}\nconst wordlists = {};\n/**\n * The [Tradional Chinese wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/chinese_traditional.txt) and\n * [Simplified Chinese wordlist](https://github.com/bitcoin/bips/blob/master/bip-0039/chinese_simplified.txt) for\n * [mnemonic phrases](https://en.bitcoin.it/wiki/BIP_0039)).\n */\nexport class LangZh extends Wordlist {\n /**\n * Creates a new instance of the Chinese language Wordlist for the `dialect`, either `\"cn\"` or `\"tw\"` for simplified\n * or traditional, respectively.\n *\n * This should be unnecessary most of the time as the exported langZhCn and langZhTw should suffice.\n *\n * @ignore\n */\n constructor(dialect) {\n super('zh_' + dialect);\n }\n getWord(index) {\n const words = loadWords(this.locale);\n assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, 'index', index);\n return words[index];\n }\n getWordIndex(word) {\n return loadWords(this.locale).indexOf(word);\n }\n split(phrase) {\n phrase = phrase.replace(/(?:\\u3000| )+/g, '');\n return phrase.split('');\n }\n /**\n * Returns a singleton instance of a `LangZh` for `dialect`, creating it if this is the first time being called.\n *\n * Use the `dialect` `\"cn\"` or `\"tw\"` for simplified or traditional, respectively.\n */\n static wordlist(dialect) {\n if (wordlists[dialect] == null) {\n wordlists[dialect] = new LangZh(dialect);\n }\n return wordlists[dialect];\n }\n}\n//# sourceMappingURL=lang-zh.js.map"],"names":["words","checksum","wordlist","accents","data","_wordlist","loadWords","codes"],"mappings":"AAAA,SAAS,MAAM,CAAC,CAAC,EAAE;AACnB,IAAI,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;AACzC,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,wBAAwB,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;AACxD,CAAC;AAKD,SAAS,KAAK,CAAC,CAAC,EAAE,GAAG,OAAO,EAAE;AAC9B,IAAI,IAAI,EAAE,CAAC,YAAY,UAAU,CAAC;AAClC,QAAQ,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC/C,IAAI,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC;AACzD,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,8BAA8B,EAAE,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AAC/F,CAAC;AAOD,SAAS,MAAM,CAAC,QAAQ,EAAE,aAAa,GAAG,IAAI,EAAE;AAChD,IAAI,IAAI,QAAQ,CAAC,SAAS;AAC1B,QAAQ,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAC;AAC5D,IAAI,IAAI,aAAa,IAAI,QAAQ,CAAC,QAAQ;AAC1C,QAAQ,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACjE,CAAC;AACD,SAAS,MAAM,CAAC,GAAG,EAAE,QAAQ,EAAE;AAC/B,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;AACf,IAAI,MAAM,GAAG,GAAG,QAAQ,CAAC,SAAS,CAAC;AACnC,IAAI,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE;AAC1B,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,sDAAsD,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AACxF,KAAK;AACL;;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA,MAAM,GAAG,GAAG,CAAC,CAAC,KAAK,CAAC,YAAY,UAAU,CAAC;AAGpC,MAAM,GAAG,GAAG,CAAC,GAAG,KAAK,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC;AAKxG;AACA;AACO,MAAM,IAAI,GAAG,IAAI,UAAU,CAAC,IAAI,WAAW,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC;AACrF,IAAI,CAAC,IAAI;AACT,IAAI,MAAM,IAAI,KAAK,CAAC,6CAA6C,CAAC,CAAC;AAoDnE;AACA;AACA;AACO,SAAS,WAAW,CAAC,GAAG,EAAE;AACjC,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAC/B,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,iCAAiC,EAAE,OAAO,GAAG,CAAC,CAAC,CAAC,CAAC;AAC1E,IAAI,OAAO,IAAI,UAAU,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AACzD,CAAC;AACD;AACA;AACA;AACA;AACA;AACO,SAAS,OAAO,CAAC,IAAI,EAAE;AAC9B,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ;AAChC,QAAQ,IAAI,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC;AACjC,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;AAClB,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,yBAAyB,EAAE,OAAO,IAAI,CAAC,CAAC,CAAC,CAAC;AACnE,IAAI,OAAO,IAAI,CAAC;AAChB,CAAC;AAeD;AACO,MAAM,IAAI,CAAC;AAClB;AACA,IAAI,KAAK,GAAG;AACZ,QAAQ,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;AACjC,KAAK;AACL,CAAC;AAQM,SAAS,eAAe,CAAC,QAAQ,EAAE;AAC1C,IAAI,MAAM,KAAK,GAAG,CAAC,GAAG,KAAK,QAAQ,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC;AACpE,IAAI,MAAM,GAAG,GAAG,QAAQ,EAAE,CAAC;AAC3B,IAAI,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC,SAAS,CAAC;AACpC,IAAI,KAAK,CAAC,QAAQ,GAAG,GAAG,CAAC,QAAQ,CAAC;AAClC,IAAI,KAAK,CAAC,MAAM,GAAG,MAAM,QAAQ,EAAE,CAAC;AACpC,IAAI,OAAO,KAAK,CAAC;AACjB;;AC/HA,MAAM,UAAU,mBAAmB,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvD,MAAM,IAAI,mBAAmB,MAAM,CAAC,EAAE,CAAC,CAAC;AACxC;AACA,SAAS,OAAO,CAAC,CAAC,EAAE,EAAE,GAAG,KAAK,EAAE;AAChC,IAAI,IAAI,EAAE;AACV,QAAQ,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,IAAI,UAAU,CAAC,EAAE,CAAC;AAClF,IAAI,OAAO,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC,IAAI,IAAI,IAAI,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,CAAC,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;AACtF,CAAC;AACD,SAAS,KAAK,CAAC,GAAG,EAAE,EAAE,GAAG,KAAK,EAAE;AAChC,IAAI,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;AACzC,IAAI,IAAI,EAAE,GAAG,IAAI,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;AACzC,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACzC,QAAQ,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC7C,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAChC,KAAK;AACL,IAAI,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AACpB,CAAC;AAcD;AACA,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AACxD,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AACxD;AACA,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;AAC/D,MAAM,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,KAAK,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;;ACnC9D;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,OAAO,GAAG,eAAe;;ACNtC;AACA;AACA;AAmDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE;AACxD,IAAI,KAAK,MAAM,GAAG,IAAI,MAAM,EAAE;AAC9B,QAAQ,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAKlC,QAAQ,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE,GAAG,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC;AACzF,KAAK;AACL;;ACxEA;AACA;AACA;AACA;AACA;AACA;AACA;AAGA,SAAS,SAAS,CAAC,KAAK,EAAE;AAC1B,IAAI,IAAI,KAAK,IAAI,IAAI,EAAE;AACvB,QAAQ,OAAO,MAAM,CAAC;AACtB,KAAK;AACL,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;AAC9B,QAAQ,OAAO,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AAC7D,KAAK;AACL,IAAI,IAAI,KAAK,YAAY,UAAU,EAAE;AACrC,QAAQ,MAAM,GAAG,GAAG,kBAAkB,CAAC;AACvC,QAAQ,IAAI,MAAM,GAAG,IAAI,CAAC;AAC1B,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC/C,YAAY,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AACzC,YAAY,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC;AAC1C,SAAS;AACT,QAAQ,OAAO,MAAM,CAAC;AACtB,KAAK;AACL,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,MAAM,KAAK,UAAU,EAAE;AACzE,QAAQ,OAAO,SAAS,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;AACzC,KAAK;AACL,IAAI,QAAQ,OAAO,KAAK;AACxB,QAAQ,KAAK,SAAS,CAAC;AACvB,QAAQ,KAAK,QAAQ;AACrB,YAAY,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;AACpC,QAAQ,KAAK,QAAQ;AACrB,YAAY,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,CAAC;AAC5C,QAAQ,KAAK,QAAQ;AACrB,YAAY,OAAO,KAAK,CAAC,QAAQ,EAAE,CAAC;AACpC,QAAQ,KAAK,QAAQ;AACrB,YAAY,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACzC,QAAQ,KAAK,QAAQ,EAAE;AACvB,YAAY,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC5C,YAAY,IAAI,CAAC,IAAI,EAAE,CAAC;AACxB,YAAY,OAAO,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;AACvG,SAAS;AACT,KAAK;AACL,IAAI,OAAO,CAAC,uBAAuB,CAAC,CAAC;AACrC,CAAC;AAkCD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE;AAC/C,IAAI,MAAM,YAAY,GAAG,OAAO,CAAC;AACjC,IAAI;AACJ,QAAQ,MAAM,OAAO,GAAG,EAAE,CAAC;AAC3B,QAAQ,IAAI,IAAI,EAAE;AAClB,YAAY,IAAI,SAAS,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI,EAAE;AACvE,gBAAgB,MAAM,IAAI,KAAK,CAAC,CAAC,uCAAuC,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AAC7F,aAAa;AACb,YAAY,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE;AACpC,gBAAgB,IAAI,GAAG,KAAK,cAAc,EAAE;AAC5C,oBAAoB,SAAS;AAC7B,iBAAiB;AACjB,gBAAgB,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;AACxC,gBAAgB,OAAO,CAAC,IAAI,CAAC,GAAG,GAAG,GAAG,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;AAC3D,aAAa;AACb,SAAS;AACT,QAAQ,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;AACrC,QAAQ,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;AAC3C,QAAQ,IAAI,OAAO,CAAC,MAAM,EAAE;AAC5B,YAAY,OAAO,IAAI,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC;AACvD,SAAS;AACT,KAAK;AACL,IAAI,IAAI,KAAK,CAAC;AACd,IAAI,QAAQ,IAAI;AAChB,QAAQ,KAAK,kBAAkB;AAC/B,YAAY,KAAK,GAAG,IAAI,SAAS,CAAC,OAAO,CAAC,CAAC;AAC3C,YAAY,MAAM;AAClB,QAAQ,KAAK,eAAe,CAAC;AAC7B,QAAQ,KAAK,gBAAgB;AAC7B,YAAY,KAAK,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC;AAC5C,YAAY,MAAM;AAClB,QAAQ;AACR,YAAY,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;AACvC,KAAK;AACL,IAAI,gBAAgB,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;AACtC,IAAI,IAAI,IAAI,EAAE;AACd,QAAQ,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACnC,KAAK;AACL,IAAI,IAAI,KAAK,CAAC,YAAY,IAAI,IAAI,EAAE;AACpC,QAAQ,gBAAgB,CAAC,KAAK,EAAE,EAAE,YAAY,EAAE,CAAC,CAAC;AAClD,KAAK;AACL,IAAI,OAAO,KAAK,CAAC;AACjB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE;AACnD,IAAI,IAAI,CAAC,KAAK,EAAE;AAChB,QAAQ,MAAM,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC7C,KAAK;AACL,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,cAAc,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE;AAC5D,IAAI,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,kBAAkB,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;AACjF,CAAC;AAiBuB,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,IAAI,KAAK;AAC/E,IAAI,IAAI;AACR;AACA;AACA,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,KAAK,MAAM,EAAE;AAC/C,YAAY,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;AACnC,SAAS;AACT;AACA,QAAQ,IAAI,IAAI,KAAK,KAAK,EAAE;AAC5B,YAAY,MAAM,KAAK,GAAG,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AACrE,YAAY,MAAM,QAAQ,GAAG,MAAM,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAC/D;AACA,YAAY,IAAI,KAAK,KAAK,QAAQ,EAAE;AACpC,gBAAgB,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,CAAC;AAC1C,aAAa;AACb;AACA,SAAS;AACT,QAAQ,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB;AACA,KAAK;AACL,IAAI,OAAO,KAAK,EAAE,GAAG;AACrB,IAAI,OAAO,KAAK,CAAC;AACjB,CAAC,EAAE,EAAE;;AC7ML;AACA;AACA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE;AACtC,IAAI,IAAI,KAAK,YAAY,UAAU,EAAE;AAIrC,QAAQ,OAAO,KAAK,CAAC;AACrB,KAAK;AACL,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,CAAC,0BAA0B,CAAC,EAAE;AAC9E,QAAQ,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;AAC9D,QAAQ,IAAI,MAAM,GAAG,CAAC,CAAC;AACvB,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAChD,YAAY,MAAM,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC1E,YAAY,MAAM,IAAI,CAAC,CAAC;AACxB,SAAS;AACT,QAAQ,OAAO,MAAM,CAAC;AACtB,KAAK;AACL,IAAI,cAAc,CAAC,KAAK,EAAE,yBAAyB,EAAE,IAAI,IAAI,OAAO,EAAE,KAAK,CAAC,CAAC;AAC7E,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,QAAQ,CAAC,KAAK,EAAE,IAAI,EAAE;AACtC,IAAI,OAAO,SAAS,CAAC,KAAK,EAAE,IAAW,CAAC,CAAC;AACzC,CAAC;AAkDD,MAAM,aAAa,GAAG,kBAAkB,CAAC;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,OAAO,CAAC,IAAI,EAAE;AAC9B,IAAI,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;AACjC,IAAI,IAAI,MAAM,GAAG,IAAI,CAAC;AACtB,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC3C,QAAQ,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AAC3B,QAAQ,MAAM,IAAI,aAAa,CAAC,CAAC,CAAC,GAAG,IAAI,KAAK,CAAC,CAAC,GAAG,aAAa,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC;AAC3E,KAAK;AACL,IAAI,OAAO,MAAM,CAAC;AAClB;;ACjHA;AACA;AACA;AACA;AACA;AACA;AAGA;AACA,SAAS,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK;AACxC;AACA,MAAM;AACN;AACA,YAAY,EAAE;AACd,IAAI,cAAc,CAAC,KAAK,EAAE,CAAC,4BAA4B,EAAE,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC9F,CAAC;AACD;AACA,SAAS,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK;AACzC;AACA,MAAM;AACN;AACA,YAAY,EAAE;AACd;AACA,IAAI,IAAI,MAAM,KAAK,YAAY,IAAI,MAAM,KAAK,qBAAqB,EAAE;AACrE,QAAQ,IAAI,CAAC,GAAG,CAAC,CAAC;AAClB,QAAQ,KAAK,IAAI,CAAC,GAAG,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACxD,YAAY,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;AACxC,gBAAgB,MAAM;AACtB,aAAa;AACb,YAAY,CAAC,EAAE,CAAC;AAChB,SAAS;AACT,QAAQ,OAAO,CAAC,CAAC;AACjB,KAAK;AACL;AACA;AACA,IAAI,IAAI,MAAM,KAAK,SAAS,EAAE;AAC9B,QAAQ,OAAO,KAAK,CAAC,MAAM,GAAG,MAAM,GAAG,CAAC,CAAC;AACzC,KAAK;AACL;AACA,IAAI,OAAO,CAAC,CAAC;AACb,CAAC;AACD,SAAS,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE;AAClE;AACA,IAAI,IAAI,MAAM,KAAK,UAAU,EAAE;AAC/B,QAAQ,cAAc,CAAC,OAAO,YAAY,KAAK,QAAQ,EAAE,wCAAwC,EAAE,cAAc,EAAE,YAAY,CAAC,CAAC;AACjI,QAAQ,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAClC,QAAQ,OAAO,CAAC,CAAC;AACjB,KAAK;AACL;AACA,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AACxB;AACA,IAAI,OAAO,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,KAA2B,CAAC,CAAC;AACnE,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;AAC5C,IAAI,KAAK,EAAE,SAAS;AACpB,IAAI,MAAM,EAAE,UAAU;AACtB,IAAI,OAAO,EAAE,WAAW;AACxB,CAAC,CAAC,CAAC;AACH;AACA,SAAS,iBAAiB,CAAC,MAAM,EAAE,OAAO,EAAE;AAC5C,IAAI,IAAI,OAAO,IAAI,IAAI,EAAE;AACzB,QAAQ,OAAO,GAAG,cAAc,CAAC,KAAK,CAAC;AACvC,KAAK;AACL,IAAI,MAAM,KAAK,GAAG,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAC5C,IAAI,MAAM,MAAM,GAAG,EAAE,CAAC;AACtB,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC;AACd;AACA,IAAI,OAAO,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE;AAC7B,QAAQ,MAAM,CAAC,GAAG,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC;AAC7B;AACA,QAAQ,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;AAC1B,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC3B,YAAY,SAAS;AACrB,SAAS;AACT;AACA,QAAQ,IAAI,WAAW,GAAG,IAAI,CAAC;AAC/B,QAAQ,IAAI,YAAY,GAAG,IAAI,CAAC;AAChC;AACA,QAAQ,IAAI,CAAC,CAAC,GAAG,IAAI,MAAM,IAAI,EAAE;AACjC,YAAY,WAAW,GAAG,CAAC,CAAC;AAC5B,YAAY,YAAY,GAAG,IAAI,CAAC;AAChC;AACA,SAAS;AACT,aAAa,IAAI,CAAC,CAAC,GAAG,IAAI,MAAM,IAAI,EAAE;AACtC,YAAY,WAAW,GAAG,CAAC,CAAC;AAC5B,YAAY,YAAY,GAAG,KAAK,CAAC;AACjC;AACA,SAAS;AACT,aAAa,IAAI,CAAC,CAAC,GAAG,IAAI,MAAM,IAAI,EAAE;AACtC,YAAY,WAAW,GAAG,CAAC,CAAC;AAC5B,YAAY,YAAY,GAAG,MAAM,CAAC;AAClC,SAAS;AACT,aAAa;AACb,YAAY,IAAI,CAAC,CAAC,GAAG,IAAI,MAAM,IAAI,EAAE;AACrC,gBAAgB,CAAC,IAAI,OAAO,CAAC,qBAAqB,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC1E,aAAa;AACb,iBAAiB;AACjB,gBAAgB,CAAC,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACjE,aAAa;AACb,YAAY,SAAS;AACrB,SAAS;AACT;AACA,QAAQ,IAAI,CAAC,GAAG,CAAC,GAAG,WAAW,IAAI,KAAK,CAAC,MAAM,EAAE;AACjD,YAAY,CAAC,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AAC1D,YAAY,SAAS;AACrB,SAAS;AACT;AACA,QAAQ,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC;AACzD,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE,EAAE;AAC9C,YAAY,MAAM,QAAQ,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;AACtC;AACA,YAAY,IAAI,CAAC,QAAQ,GAAG,IAAI,KAAK,IAAI,EAAE;AAC3C,gBAAgB,CAAC,IAAI,OAAO,CAAC,kBAAkB,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC;AACnE,gBAAgB,GAAG,GAAG,IAAI,CAAC;AAC3B,gBAAgB,MAAM;AACtB,aAAa;AACb,YAAY,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,QAAQ,GAAG,IAAI,CAAC,CAAC;AACjD,YAAY,CAAC,EAAE,CAAC;AAChB,SAAS;AACT;AACA,QAAQ,IAAI,GAAG,KAAK,IAAI,EAAE;AAC1B,YAAY,SAAS;AACrB,SAAS;AACT;AACA,QAAQ,IAAI,GAAG,GAAG,QAAQ,EAAE;AAC5B,YAAY,CAAC,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC,GAAG,CAAC,GAAG,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;AAClF,YAAY,SAAS;AACrB,SAAS;AACT;AACA,QAAQ,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG,IAAI,MAAM,EAAE;AAC5C,YAAY,CAAC,IAAI,OAAO,CAAC,iBAAiB,EAAE,CAAC,GAAG,CAAC,GAAG,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;AACrF,YAAY,SAAS;AACrB,SAAS;AACT;AACA,QAAQ,IAAI,GAAG,IAAI,YAAY,EAAE;AACjC,YAAY,CAAC,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC,GAAG,CAAC,GAAG,WAAW,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;AAC9E,YAAY,SAAS;AACrB,SAAS;AACT,QAAQ,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACzB,KAAK;AACL,IAAI,OAAO,MAAM,CAAC;AAClB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,WAAW,CAAC,GAAG,EAAE,IAAI,EAAE;AAKvC,IAAI,MAAM,MAAM,GAAG,EAAE,CAAC;AACtB,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AACzC,QAAQ,MAAM,CAAC,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACpC,QAAQ,IAAI,CAAC,GAAG,IAAI,EAAE;AACtB,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC3B,SAAS;AACT,aAAa,IAAI,CAAC,GAAG,KAAK,EAAE;AAC5B,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC;AACzC,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC;AAC3C,SAAS;AACT,aAAa,IAAI,CAAC,CAAC,GAAG,MAAM,KAAK,MAAM,EAAE;AACzC,YAAY,CAAC,EAAE,CAAC;AAChB,YAAY,MAAM,EAAE,GAAG,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AACzC,YAAY,cAAc,CAAC,CAAC,GAAG,GAAG,CAAC,MAAM,IAAI,CAAC,EAAE,GAAG,MAAM,MAAM,MAAM,EAAE,wBAAwB,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC;AAC7G;AACA,YAAY,MAAM,IAAI,GAAG,OAAO,IAAI,CAAC,CAAC,GAAG,MAAM,KAAK,EAAE,CAAC,IAAI,EAAE,GAAG,MAAM,CAAC,CAAC;AACxE,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,IAAI,EAAE,IAAI,IAAI,CAAC,CAAC;AAC7C,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,EAAE,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC;AACtD,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC;AACrD,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC;AAC9C,SAAS;AACT,aAAa;AACb,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,IAAI,IAAI,CAAC,CAAC;AAC1C,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC;AAClD,YAAY,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,IAAI,CAAC,CAAC;AAC3C,SAAS;AACT,KAAK;AACL,IAAI,OAAO,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC;AAClC,CAAC;AACD;AACA;AACA;AACA,SAAS,aAAa,CAAC,UAAU,EAAE;AACnC,IAAI,OAAO,UAAU;AACrB,SAAS,GAAG,CAAC,CAAC,SAAS,KAAK;AAC5B,QAAQ,IAAI,SAAS,IAAI,MAAM,EAAE;AACjC,YAAY,OAAO,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;AAClD,SAAS;AACT,QAAQ,SAAS,IAAI,OAAO,CAAC;AAC7B,QAAQ,OAAO,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS,IAAI,EAAE,IAAI,KAAK,IAAI,MAAM,EAAE,CAAC,SAAS,GAAG,KAAK,IAAI,MAAM,CAAC,CAAC;AACvG,KAAK,CAAC;AACN,SAAS,IAAI,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC;AACD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE;AAC7C,IAAI,OAAO,aAAa,CAAC,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC;AAC5D;;ACnOA;AACA;AACA;AACA,MAAM,CAAC,OAAO,EAAE,SAAS,EAAE,UAAU,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AACtD,MAAM,GAAG,mBAAmB,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,mBAAmB,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,mBAAmB,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,mBAAmB,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,KAAK,mBAAmB,MAAM,CAAC,GAAG,CAAC,CAAC;AAC1C,MAAM,MAAM,mBAAmB,MAAM,CAAC,IAAI,CAAC,CAAC;AAC5C,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,GAAG,EAAE,EAAE,KAAK,EAAE,EAAE;AAChE;AACA,IAAI,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC;AACtC,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AAClC;AACA,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,KAAK,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;AAC3D;AACA,IAAI,IAAI,CAAC,GAAG,GAAG,CAAC;AAChB,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AAChC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,KAAK,CAAC,CAAC,IAAI,GAAG,IAAI,MAAM,CAAC,IAAI,KAAK,CAAC;AACzD,QAAQ,IAAI,CAAC,GAAG,GAAG;AACnB,YAAY,CAAC,IAAI,GAAG,KAAK,CAAC,GAAG,oBAAoB,MAAM,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC;AACnE,KAAK;AACL,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACvB,CAAC;AACD,MAAM,CAAC,WAAW,EAAE,WAAW,CAAC,mBAAmB,KAAK,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;AAC3E;AACA,MAAM,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AACxE,MAAM,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;AACxE;AACO,SAAS,OAAO,CAAC,CAAC,EAAE,MAAM,GAAG,EAAE,EAAE;AACxC,IAAI,MAAM,CAAC,GAAG,IAAI,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACrC;AACA,IAAI,KAAK,IAAI,KAAK,GAAG,EAAE,GAAG,MAAM,EAAE,KAAK,GAAG,EAAE,EAAE,KAAK,EAAE,EAAE;AACvD;AACA,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE;AACnC,YAAY,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AACxE,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE;AACxC,YAAY,MAAM,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;AACtC,YAAY,MAAM,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC;AACtC,YAAY,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;AAC/B,YAAY,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;AACnC,YAAY,MAAM,EAAE,GAAG,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;AAClD,YAAY,MAAM,EAAE,GAAG,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,CAAC;AACtD,YAAY,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;AAC7C,gBAAgB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;AAC/B,gBAAgB,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;AACnC,aAAa;AACb,SAAS;AACT;AACA,QAAQ,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACxB,QAAQ,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACxB,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE;AACrC,YAAY,MAAM,KAAK,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;AACvC,YAAY,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;AAChD,YAAY,MAAM,EAAE,GAAG,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;AAChD,YAAY,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;AAClC,YAAY,IAAI,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;AACzB,YAAY,IAAI,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC;AAC7B,YAAY,CAAC,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC;AACvB,YAAY,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,EAAE,CAAC;AAC3B,SAAS;AACT;AACA,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;AACzC,YAAY,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE;AACvC,gBAAgB,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAChC,YAAY,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE;AACvC,gBAAgB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;AAC/D,SAAS;AACT;AACA,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;AACnC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,WAAW,CAAC,KAAK,CAAC,CAAC;AACnC,KAAK;AACL,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACd,CAAC;AACM,MAAM,MAAM,SAAS,IAAI,CAAC;AACjC;AACA,IAAI,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,GAAG,KAAK,EAAE,MAAM,GAAG,EAAE,EAAE;AAC7E,QAAQ,KAAK,EAAE,CAAC;AAChB,QAAQ,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;AACjC,QAAQ,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;AAC7B,QAAQ,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;AACnC,QAAQ,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;AACnC,QAAQ,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;AAC7B,QAAQ,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;AACrB,QAAQ,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;AACxB,QAAQ,IAAI,CAAC,QAAQ,GAAG,KAAK,CAAC;AAC9B,QAAQ,IAAI,CAAC,SAAS,GAAG,KAAK,CAAC;AAC/B;AACA,QAAQ,MAAM,CAAC,SAAS,CAAC,CAAC;AAC1B;AACA,QAAQ,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,IAAI,GAAG;AACtD,YAAY,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;AACxE,QAAQ,IAAI,CAAC,KAAK,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,CAAC;AACzC,QAAQ,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACvC,KAAK;AACL,IAAI,MAAM,GAAG;AACb,QAAQ,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;AAC3C,QAAQ,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;AACxB,QAAQ,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;AACrB,KAAK;AACL,IAAI,MAAM,CAAC,IAAI,EAAE;AACjB,QAAQ,MAAM,CAAC,IAAI,CAAC,CAAC;AACrB,QAAQ,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC;AACzC,QAAQ,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAC7B,QAAQ,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;AAChC,QAAQ,KAAK,IAAI,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,GAAG,GAAG;AACtC,YAAY,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC;AAClE,YAAY,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE;AACzC,gBAAgB,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;AACjD,YAAY,IAAI,IAAI,CAAC,GAAG,KAAK,QAAQ;AACrC,gBAAgB,IAAI,CAAC,MAAM,EAAE,CAAC;AAC9B,SAAS;AACT,QAAQ,OAAO,IAAI,CAAC;AACpB,KAAK;AACL,IAAI,MAAM,GAAG;AACb,QAAQ,IAAI,IAAI,CAAC,QAAQ;AACzB,YAAY,OAAO;AACnB,QAAQ,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;AAC7B,QAAQ,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;AACtD;AACA,QAAQ,KAAK,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC;AAC7B,QAAQ,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,GAAG,KAAK,QAAQ,GAAG,CAAC;AACzD,YAAY,IAAI,CAAC,MAAM,EAAE,CAAC;AAC1B,QAAQ,KAAK,CAAC,QAAQ,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC;AACpC,QAAQ,IAAI,CAAC,MAAM,EAAE,CAAC;AACtB,KAAK;AACL,IAAI,SAAS,CAAC,GAAG,EAAE;AACnB,QAAQ,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;AAC5B,QAAQ,KAAK,CAAC,GAAG,CAAC,CAAC;AACnB,QAAQ,IAAI,CAAC,MAAM,EAAE,CAAC;AACtB,QAAQ,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAC;AACrC,QAAQ,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;AAClC,QAAQ,KAAK,IAAI,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,GAAG,CAAC,MAAM,EAAE,GAAG,GAAG,GAAG,GAAG;AACxD,YAAY,IAAI,IAAI,CAAC,MAAM,IAAI,QAAQ;AACvC,gBAAgB,IAAI,CAAC,MAAM,EAAE,CAAC;AAC9B,YAAY,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC;AACrE,YAAY,GAAG,CAAC,GAAG,CAAC,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC;AAC9E,YAAY,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC;AAChC,YAAY,GAAG,IAAI,IAAI,CAAC;AACxB,SAAS;AACT,QAAQ,OAAO,GAAG,CAAC;AACnB,KAAK;AACL,IAAI,OAAO,CAAC,GAAG,EAAE;AACjB;AACA,QAAQ,IAAI,CAAC,IAAI,CAAC,SAAS;AAC3B,YAAY,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACrE,QAAQ,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AACnC,KAAK;AACL,IAAI,GAAG,CAAC,KAAK,EAAE;AACf,QAAQ,MAAM,CAAC,KAAK,CAAC,CAAC;AACtB,QAAQ,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC;AACnD,KAAK;AACL,IAAI,UAAU,CAAC,GAAG,EAAE;AACpB,QAAQ,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAC1B,QAAQ,IAAI,IAAI,CAAC,QAAQ;AACzB,YAAY,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;AAC3D,QAAQ,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AAC5B,QAAQ,IAAI,CAAC,OAAO,EAAE,CAAC;AACvB,QAAQ,OAAO,GAAG,CAAC;AACnB,KAAK;AACL,IAAI,MAAM,GAAG;AACb,QAAQ,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;AAC/D,KAAK;AACL,IAAI,OAAO,GAAG;AACd,QAAQ,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;AAC9B,QAAQ,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC3B,KAAK;AACL,IAAI,UAAU,CAAC,EAAE,EAAE;AACnB,QAAQ,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;AACxE,QAAQ,EAAE,KAAK,EAAE,GAAG,IAAI,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;AAChF,QAAQ,EAAE,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AACrC,QAAQ,EAAE,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;AAC1B,QAAQ,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC;AAChC,QAAQ,EAAE,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;AACpC,QAAQ,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;AAC3B;AACA,QAAQ,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC;AAC3B,QAAQ,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;AACjC,QAAQ,EAAE,CAAC,SAAS,GAAG,SAAS,CAAC;AACjC,QAAQ,EAAE,CAAC,SAAS,GAAG,IAAI,CAAC,SAAS,CAAC;AACtC,QAAQ,OAAO,EAAE,CAAC;AAClB,KAAK;AACL,CAAC;AACD,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,SAAS,KAAK,eAAe,CAAC,MAAM,IAAI,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAU5G;AACA;AACA;AACA;AACO,MAAM,UAAU,mBAAmB,GAAG,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,GAAG,CAAC,CAAC;;ACzMjE;AACA;AACA;AAGA,IAAI,MAAM,GAAG,KAAK,CAAC;AACnB,MAAM,UAAU,GAAG,UAAU,IAAI,EAAE;AACnC,IAAI,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC;AAC5B,CAAC,CAAC;AACF,IAAI,WAAW,GAAG,UAAU,CAAC;AAC7B;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,SAAS,CAAC,KAAK,EAAE;AACjC,IAAI,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;AACzC,IAAI,OAAO,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;AACtC,CAAC;AACD,SAAS,CAAC,CAAC,GAAG,UAAU,CAAC;AACzB,SAAS,CAAC,IAAI,GAAG,YAAY;AAC7B,IAAI,MAAM,GAAG,IAAI,CAAC;AAClB,CAAC,CAAC;AACF,SAAS,CAAC,QAAQ,GAAG,UAAU,IAAI,EAAE;AACrC,IAAI,IAAI,MAAM,EAAE;AAChB,QAAQ,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAC;AACnD,KAAK;AACL,IAAI,WAAW,GAAG,IAAI,CAAC;AACvB,CAAC,CAAC;AACF,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC;;AC/CxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,EAAE,CAAC,KAAK,EAAE;AAC1B,IAAI,OAAO,SAAS,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC;AACzC;;AClBA,MAAM,QAAQ,GAAG,+BAA+B,CAAC;AACjD,MAAM,IAAI,GAAG,WAAW,CAAC;AACzB,SAAS,MAAM,CAAC,KAAK,EAAE,GAAG,EAAE;AAC5B,IAAI,IAAI,OAAO,GAAG,EAAE,CAAC;AACrB,IAAI,OAAO,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,IAAI,KAAK;AACzC,QAAQ,IAAI,IAAI,KAAK,GAAG,EAAE;AAC1B,YAAY,OAAO,EAAE,CAAC;AACtB,SAAS;AACT,aAAa,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE;AACnC,YAAY,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC;AAC5D,SAAS;AACT,aAAa;AACb,YAAY,OAAO,GAAG,EAAE,CAAC;AACzB,YAAY,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC7B,SAAS;AACT,QAAQ,OAAO,KAAK,CAAC;AACrB,KAAK,EAAE,EAAE,CAAC,CAAC;AACX,CAAC;AACD;AACA;AACA;AACO,SAAS,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE;AACnC;AACA,IAAI,KAAK,IAAI,CAAC,GAAG,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;AACnD,QAAQ,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AAC9E,KAAK;AACL;AACA,IAAI,MAAM,MAAM,GAAG,EAAE,CAAC;AACtB;AACA,IAAI,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,4BAA4B,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,KAAK;AAC3F,QAAQ,IAAI,IAAI,EAAE;AAClB,YAAY,KAAK,IAAI,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE;AACtD,gBAAgB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjC,aAAa;AACb,SAAS;AACT,aAAa;AACb,YAAY,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;AAC5C,SAAS;AACT,QAAQ,OAAO,EAAE,CAAC;AAClB,KAAK,CAAC,CAAC;AACP;AACA,IAAI,IAAI,QAAQ,EAAE;AAClB,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;AAClE,KAAK;AACL;AACA,IAAI,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC;AACD;AACA;AACA;AACO,SAAS,SAAS,CAAC,IAAI,EAAE;AAChC,IAAI,cAAc,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,uBAAuB,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;AAC3E,IAAI,OAAO,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC;AACvG;;ACrDA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,QAAQ,CAAC;AACtB,IAAI,MAAM,CAAC;AACX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,WAAW,CAAC,MAAM,EAAE;AACxB,QAAQ,gBAAgB,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;AAC3C,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,KAAK,CAAC,MAAM,EAAE;AAClB,QAAQ,OAAO,MAAM,CAAC,WAAW,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAClD,KAAK;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,IAAI,CAAC,KAAK,EAAE;AAChB,QAAQ,OAAO,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/B,KAAK;AACL;;AC7CA;AACA;AAKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,WAAW,SAAS,QAAQ,CAAC;AAC1C,IAAI,KAAK,CAAC;AACV,IAAI,SAAS,CAAC;AACd;AACA;AACA;AACA,IAAI,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;AACxC,QAAQ,KAAK,CAAC,MAAM,CAAC,CAAC;AACtB,QAAQ,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;AAC1B,QAAQ,IAAI,CAAC,SAAS,GAAG,QAAQ,CAAC;AAClC,QAAQ,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;AAC3B,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,IAAI,IAAI,KAAK,GAAG;AAChB,QAAQ,OAAO,IAAI,CAAC,KAAK,CAAC;AAC1B,KAAK;AACL;AACA;AACA;AACA,IAAI,YAAY,GAAG;AACnB,QAAQ,OAAO,SAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACrC,KAAK;AACL,IAAI,MAAM,CAAC;AACX,IAAI,UAAU,GAAG;AACjB,QAAQ,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,EAAE;AACjC,YAAY,MAAM,KAAK,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;AAC9C;AACA,YAAY,MAAM,QAAQ,GAAG,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AACzD;AACA,YAAY,IAAI,QAAQ,KAAK,IAAI,CAAC,SAAS,EAAE;AAC7C,gBAAgB,MAAM,IAAI,KAAK,CAAC,CAAC,mBAAmB,EAAE,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;AAC5E,aAAa;AACb;AACA,YAAY,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;AAChC,SAAS;AACT,QAAQ,OAAO,IAAI,CAAC,MAAM,CAAC;AAC3B,KAAK;AACL,IAAI,OAAO,CAAC,KAAK,EAAE;AACnB,QAAQ,MAAM,KAAK,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;AACxC,QAAQ,cAAc,CAAC,KAAK,IAAI,CAAC,IAAI,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC3G,QAAQ,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;AAC5B,KAAK;AACL,IAAI,YAAY,CAAC,IAAI,EAAE;AACvB,QAAQ,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AAC/C,KAAK;AACL;;ACjEA,MAAMA,OAAK,GAAG,q9NAAq9N,CAAC;AACp+N,MAAMC,UAAQ,GAAG,oEAAoE,CAAC;AACtF,IAAIC,UAAQ,GAAG,IAAI,CAAC;AACpB;AACA;AACA;AACA;AACO,MAAM,MAAM,SAAS,WAAW,CAAC;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,WAAW,GAAG;AAClB,QAAQ,KAAK,CAAC,IAAI,EAAEF,OAAK,EAAEC,UAAQ,CAAC,CAAC;AACrC,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,QAAQ,GAAG;AACtB,QAAQ,IAAIC,UAAQ,IAAI,IAAI,EAAE;AAC9B,YAAYA,UAAQ,GAAG,IAAI,MAAM,EAAE,CAAC;AACpC,SAAS;AACT,QAAQ,OAAOA,UAAQ,CAAC;AACxB,KAAK;AACL;;AC5BA,MAAM,MAAM,GAAG,kEAAkE,CAAC;AAClF;AACA;AACA;AACO,SAAS,UAAU,CAAC,KAAK,EAAE,IAAI,EAAE;AACxC,IAAI,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AACtC,IAAI,MAAM,MAAM,GAAG,EAAE,CAAC;AACtB,IAAI,IAAI,KAAK,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC;AACvC,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC1C;AACA,QAAQ,KAAK,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;AACvD,QAAQ,IAAI,IAAI,CAAC,CAAC;AAClB;AACA,QAAQ,OAAO,IAAI,IAAI,KAAK,EAAE;AAC9B;AACA,YAAY,MAAM,KAAK,GAAG,KAAK,KAAK,IAAI,GAAG,KAAK,CAAC,CAAC;AAClD,YAAY,KAAK,IAAI,CAAC,CAAC,KAAK,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC,CAAC;AAC/C,YAAY,IAAI,IAAI,KAAK,CAAC;AAC1B;AACA;AACA,YAAY,IAAI,KAAK,KAAK,CAAC,EAAE;AAC7B,gBAAgB,KAAK,IAAI,QAAQ,CAAC;AAClC,aAAa;AACb,iBAAiB;AACjB,gBAAgB,MAAM,CAAC,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC;AAC3C,gBAAgB,KAAK,GAAG,CAAC,CAAC;AAC1B,aAAa;AACb,SAAS;AACT,KAAK;AACL,IAAI,OAAO,MAAM,CAAC;AAClB;;AC3BA;AACA;AACA;AACO,SAAS,UAAU,CAAC,IAAI,EAAE,OAAO,EAAE;AAC1C,IAAI,IAAI,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC1C;AACA,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,MAAM,KAAK;AAC5C,QAAQ,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACpE,QAAQ,cAAc,CAAC,KAAK,KAAK,IAAI,EAAE,gCAAgC,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;AAC7F,QAAQ,IAAI,SAAS,GAAG,CAAC,CAAC;AAC1B,QAAQ,MAAM,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AACnE,QAAQ,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;AAC5C,QAAQ,MAAM,KAAK,GAAG,IAAI,MAAM,CAAC,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AACzD,QAAQ,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK;AACtD,YAAY,MAAM,GAAG,GAAG,EAAE,SAAS,CAAC,SAAS,CAAC,CAAC;AAC/C,YAAY,IAAI,GAAG,KAAK,CAAC,EAAE;AAC3B,gBAAgB,MAAM,GAAG,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC7E,gBAAgB,SAAS,EAAE,CAAC;AAC5B,aAAa;AACb,YAAY,OAAO,MAAM,CAAC;AAC1B,SAAS,CAAC,CAAC;AACX,KAAK,CAAC,CAAC;AACP,IAAI,OAAO,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;AAC5B;;ACxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,YAAY,SAAS,WAAW,CAAC;AAC9C,IAAI,OAAO,CAAC;AACZ;AACA;AACA;AACA,IAAI,WAAW,CAAC,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE;AAChD,QAAQ,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC;AACtC,QAAQ,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;AAC9B,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,IAAI,IAAI,OAAO,GAAG;AAClB,QAAQ,OAAO,IAAI,CAAC,OAAO,CAAC;AAC5B,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,IAAI,YAAY,GAAG;AACnB,QAAQ,OAAO,UAAU,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;AACpD,KAAK;AACL;;ACrCA,MAAMF,OAAK,GAAG,iwLAAiwL,CAAC;AAChxL,MAAMG,SAAO,GAAG,gWAAgW,CAAC;AACjX,MAAMF,UAAQ,GAAG,oEAAoE,CAAC;AACtF,IAAIC,UAAQ,GAAG,IAAI,CAAC;AACpB;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,MAAM,SAAS,YAAY,CAAC;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,WAAW,GAAG;AAClB,QAAQ,KAAK,CAAC,IAAI,EAAEF,OAAK,EAAEG,SAAO,EAAEF,UAAQ,CAAC,CAAC;AAC9C,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,QAAQ,GAAG;AACtB,QAAQ,IAAIC,UAAQ,IAAI,IAAI,EAAE;AAC9B,YAAYA,UAAQ,GAAG,IAAI,MAAM,EAAE,CAAC;AACpC,SAAS;AACT,QAAQ,OAAOA,UAAQ,CAAC;AACxB,KAAK;AACL;;AC9BA,MAAMF,OAAK,GAAG,u9OAAu9O,CAAC;AACt+O,MAAM,OAAO,GAAG,kWAAkW,CAAC;AACnX,MAAMC,UAAQ,GAAG,oEAAoE,CAAC;AACtF,IAAIC,UAAQ,GAAG,IAAI,CAAC;AACpB;AACA;AACA;AACA;AACO,MAAM,MAAM,SAAS,YAAY,CAAC;AACzC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,WAAW,GAAG;AAClB,QAAQ,KAAK,CAAC,IAAI,EAAEF,OAAK,EAAE,OAAO,EAAEC,UAAQ,CAAC,CAAC;AAC9C,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,QAAQ,GAAG;AACtB,QAAQ,IAAIC,UAAQ,IAAI,IAAI,EAAE;AAC9B,YAAYA,UAAQ,GAAG,IAAI,MAAM,EAAE,CAAC;AACpC,SAAS;AACT,QAAQ,OAAOA,UAAQ,CAAC;AACxB,KAAK;AACL;;ACzBA,MAAME,MAAI,GAAG;AACb;AACA,IAAI,orEAAorE;AACxrE;AACA,IAAI,ssGAAssG;AAC1sG;AACA,IAAI,4uDAA4uD;AAChvD;AACA,IAAI,olBAAolB;AACxlB;AACA,IAAI,4JAA4J;AAChK;AACA,IAAI,0GAA0G;AAC9G;AACA,IAAI,WAAW;AACf,CAAC,CAAC;AACF;AACA,MAAM,OAAO,GAAG,6FAA6F,CAAC;AAC9G,IAAIC,WAAS,GAAG,IAAI,CAAC;AACrB,SAAS,GAAG,CAAC,IAAI,EAAE;AACnB,IAAI,OAAO,OAAO,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC;AACtC,CAAC;AACD,MAAM,MAAM,GAAG,sBAAsB,CAAC;AACtC,MAAM,KAAK,GAAG,sBAAsB,CAAC;AACrC,SAAS,QAAQ,CAAC,IAAI,EAAE;AACxB,IAAI,OAAO,YAAY,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;AAC9C,CAAC;AACD,SAASC,WAAS,GAAG;AACrB,IAAI,IAAID,WAAS,KAAK,IAAI,EAAE;AAC5B,QAAQ,OAAOA,WAAS,CAAC;AACzB,KAAK;AACL,IAAI,MAAM,QAAQ,GAAG,EAAE,CAAC;AACxB;AACA,IAAI,MAAM,SAAS,GAAG,EAAE,CAAC;AACzB;AACA,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;AACjD,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC;AACjD;AACA,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AACrE,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AACrE,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AACrE,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;AACrE;AACA,IAAI,SAAS,SAAS,CAAC,IAAI,EAAE;AAC7B,QAAQ,IAAI,MAAM,GAAG,EAAE,CAAC;AACxB,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;AAC9C,YAAY,IAAI,IAAI,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;AAC/B,YAAY,MAAM,MAAM,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC;AAC3C,YAAY,IAAI,MAAM,KAAK,KAAK,EAAE;AAClC,gBAAgB,SAAS;AACzB,aAAa;AACb,YAAY,IAAI,MAAM,EAAE;AACxB,gBAAgB,IAAI,GAAG,MAAM,CAAC;AAC9B,aAAa;AACb,YAAY,MAAM,IAAI,IAAI,CAAC;AAC3B,SAAS;AACT,QAAQ,OAAO,MAAM,CAAC;AACtB,KAAK;AACL;AACA,IAAI,SAAS,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE;AAChC,QAAQ,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;AACzB,QAAQ,CAAC,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;AACzB,QAAQ,IAAI,CAAC,GAAG,CAAC,EAAE;AACnB,YAAY,OAAO,CAAC,CAAC,CAAC;AACtB,SAAS;AACT,QAAQ,IAAI,CAAC,GAAG,CAAC,EAAE;AACnB,YAAY,OAAO,CAAC,CAAC;AACrB,SAAS;AACT,QAAQ,OAAO,CAAC,CAAC;AACjB,KAAK;AACL;AACA,IAAI,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE;AAChD,QAAQ,MAAM,CAAC,GAAGD,MAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACnC,QAAQ,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,IAAI,MAAM,EAAE;AAClE,YAAY,MAAM,IAAI,GAAG,EAAE,CAAC;AAC5B,YAAY,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE;AAC7C,gBAAgB,MAAM,CAAC,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;AACzD,gBAAgB,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AAC/B,gBAAgB,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;AAChD,gBAAgB,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,IAAI,GAAG,CAAC,CAAC;AAC5C,aAAa;AACb,YAAY,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1C,SAAS;AACT,KAAK;AACL,IAAI,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC;AAChC;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,KAAK,MAAM,IAAI,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,KAAK,KAAK,EAAE;AACvE,QAAQ,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;AAClC,QAAQ,QAAQ,CAAC,GAAG,CAAC,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;AACtC,QAAQ,QAAQ,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC;AAC5B,KAAK;AACL;AACA;AACA;AACA,IAAI,MAAM,QAAQ,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AACpD;AACA,IAAI,IAAI,QAAQ,KAAK,oEAAoE,EAAE;AAC3F,QAAQ,MAAM,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC;AACnE,KAAK;AACL;AACA,IAAIC,WAAS,GAAG,QAAQ,CAAC;AACzB,IAAI,OAAO,QAAQ,CAAC;AACpB,CAAC;AACD,IAAIH,UAAQ,GAAG,IAAI,CAAC;AACpB;AACA;AACA;AACA;AACO,MAAM,MAAM,SAAS,QAAQ,CAAC;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,WAAW,GAAG;AAClB,QAAQ,KAAK,CAAC,IAAI,CAAC,CAAC;AACpB,KAAK;AACL,IAAI,OAAO,CAAC,KAAK,EAAE;AACnB,QAAQ,MAAM,KAAK,GAAGI,WAAS,EAAE,CAAC;AAClC,QAAQ,cAAc,CAAC,KAAK,IAAI,CAAC,IAAI,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC3G,QAAQ,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;AAC5B,KAAK;AACL,IAAI,YAAY,CAAC,IAAI,EAAE;AACvB,QAAQ,OAAOA,WAAS,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACzC,KAAK;AACL,IAAI,KAAK,CAAC,MAAM,EAAE;AAClB;AACA,QAAQ,OAAO,MAAM,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;AAC9C,KAAK;AACL,IAAI,IAAI,CAAC,KAAK,EAAE;AAChB,QAAQ,OAAO,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;AACpC,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,QAAQ,GAAG;AACtB,QAAQ,IAAIJ,UAAQ,IAAI,IAAI,EAAE;AAC9B,YAAYA,UAAQ,GAAG,IAAI,MAAM,EAAE,CAAC;AACpC,SAAS;AACT,QAAQ,OAAOA,UAAQ,CAAC;AACxB,KAAK;AACL;;ACpJA,MAAME,MAAI,GAAG;AACb,IAAI,MAAM;AACV,IAAI,y5JAAy5J;AAC75J,IAAI,8lIAA8lI;AAClmI,IAAI,i8BAAi8B;AACr8B,IAAI,koCAAkoC;AACtoC,IAAI,yaAAya;AAC7a,IAAI,gHAAgH;AACpH,IAAI,+EAA+E;AACnF,CAAC,CAAC;AACF,MAAMG,OAAK,GAAG,wEAAwE,CAAC;AACvF,SAAS,SAAS,CAAC,IAAI,EAAE;AACzB,IAAI,IAAI,IAAI,IAAI,EAAE,EAAE;AACpB,QAAQ,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG,EAAE,CAAC;AAC/B,KAAK;AACL,SAAS,IAAI,IAAI,IAAI,EAAE,EAAE;AACzB,QAAQ,IAAI,GAAG,IAAI,GAAG,EAAE,GAAG,EAAE,CAAC;AAC9B,KAAK;AACL,IAAI,OAAO,YAAY,CAAC,IAAI,UAAU,CAAC,CAAC,GAAG,EAAE,CAAC,IAAI,IAAI,CAAC,IAAI,GAAG,EAAE,CAAC,IAAI,GAAG,IAAI,IAAI,GAAG,CAAC,CAAC,CAAC,CAAC;AACvF,CAAC;AACD,IAAIF,WAAS,GAAG,IAAI,CAAC;AACrB,SAASC,WAAS,GAAG;AACrB,IAAI,IAAID,WAAS,IAAI,IAAI,EAAE;AAC3B,QAAQ,OAAOA,WAAS,CAAC;AACzB,KAAK;AACL,IAAI,MAAM,QAAQ,GAAG,EAAE,CAAC;AACxB,IAAID,MAAI,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,MAAM,KAAK;AACnC,QAAQ,MAAM,IAAI,CAAC,CAAC;AACpB,QAAQ,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,IAAI,MAAM,EAAE;AACtD,YAAY,IAAI,IAAI,GAAG,EAAE,CAAC;AAC1B,YAAY,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EAAE,CAAC,EAAE,EAAE;AAC7C,gBAAgB,IAAI,IAAI,SAAS,CAACG,OAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9D,aAAa;AACb,YAAY,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAChC,SAAS;AACT,KAAK,CAAC,CAAC;AACP,IAAI,QAAQ,CAAC,IAAI,EAAE,CAAC;AACpB;AACA;AACA,IAAI,MAAM,QAAQ,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AACpD;AACA,IAAI,IAAI,QAAQ,KAAK,oEAAoE,EAAE;AAC3F,QAAQ,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;AACjE,KAAK;AACL;AACA,IAAIF,WAAS,GAAG,QAAQ,CAAC;AACzB,IAAI,OAAO,QAAQ,CAAC;AACpB,CAAC;AACD,IAAIH,UAAQ,GAAG,IAAI,CAAC;AACpB;AACA;AACA;AACA;AACO,MAAM,MAAM,SAAS,QAAQ,CAAC;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,WAAW,GAAG;AAClB,QAAQ,KAAK,CAAC,IAAI,CAAC,CAAC;AACpB,KAAK;AACL,IAAI,OAAO,CAAC,KAAK,EAAE;AACnB,QAAQ,MAAM,KAAK,GAAGI,WAAS,EAAE,CAAC;AAClC,QAAQ,cAAc,CAAC,KAAK,IAAI,CAAC,IAAI,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC3G,QAAQ,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;AAC5B,KAAK;AACL,IAAI,YAAY,CAAC,IAAI,EAAE;AACvB,QAAQ,OAAOA,WAAS,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACzC,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,QAAQ,GAAG;AACtB,QAAQ,IAAIJ,UAAQ,IAAI,IAAI,EAAE;AAC9B,YAAYA,UAAQ,GAAG,IAAI,MAAM,EAAE,CAAC;AACpC,SAAS;AACT,QAAQ,OAAOA,UAAQ,CAAC;AACxB,KAAK;AACL;;ACpFA,MAAMF,OAAK,GAAG,0+OAA0+O,CAAC;AACz/O,MAAMC,UAAQ,GAAG,oEAAoE,CAAC;AACtF,IAAIC,UAAQ,GAAG,IAAI,CAAC;AACpB;AACA;AACA;AACA;AACO,MAAM,MAAM,SAAS,WAAW,CAAC;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,WAAW,GAAG;AAClB,QAAQ,KAAK,CAAC,IAAI,EAAEF,OAAK,EAAEC,UAAQ,CAAC,CAAC;AACrC,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,QAAQ,GAAG;AACtB,QAAQ,IAAIC,UAAQ,IAAI,IAAI,EAAE;AAC9B,YAAYA,UAAQ,GAAG,IAAI,MAAM,EAAE,CAAC;AACpC,SAAS;AACT,QAAQ,OAAOA,UAAQ,CAAC;AACxB,KAAK;AACL;;AC3BA,MAAM,KAAK,GAAG,s0OAAs0O,CAAC;AACr1O,MAAM,QAAQ,GAAG,oEAAoE,CAAC;AACtF,IAAI,QAAQ,GAAG,IAAI,CAAC;AACpB;AACA;AACA;AACA;AACO,MAAM,MAAM,SAAS,WAAW,CAAC;AACxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,WAAW,GAAG;AAClB,QAAQ,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,CAAC;AACrC,KAAK;AACL;AACA;AACA;AACA,IAAI,OAAO,QAAQ,GAAG;AACtB,QAAQ,IAAI,QAAQ,IAAI,IAAI,EAAE;AAC9B,YAAY,QAAQ,GAAG,IAAI,MAAM,EAAE,CAAC;AACpC,SAAS;AACT,QAAQ,OAAO,QAAQ,CAAC;AACxB,KAAK;AACL;;ACxBA,MAAM,IAAI,GAAG,kgMAAkgM,CAAC;AAChhM,MAAM,SAAS,GAAG,6lDAA6lD,CAAC;AAChnD,MAAM,SAAS,GAAG;AAClB,IAAI,KAAK,EAAE,IAAI;AACf,IAAI,KAAK,EAAE,IAAI;AACf,CAAC,CAAC;AACF,MAAM,MAAM,GAAG;AACf,IAAI,KAAK,EAAE,oEAAoE;AAC/E,IAAI,KAAK,EAAE,oEAAoE;AAC/E,CAAC,CAAC;AACF,MAAM,KAAK,GAAG,kEAAkE,CAAC;AACjF,MAAM,KAAK,GAAG,4BAA4B,CAAC;AAC3C,SAAS,SAAS,CAAC,MAAM,EAAE;AAC3B,IAAI,IAAI,SAAS,CAAC,MAAM,CAAC,IAAI,IAAI,EAAE;AACnC,QAAQ,OAAO,SAAS,CAAC,MAAM,CAAC,CAAC;AACjC,KAAK;AACL,IAAI,MAAM,QAAQ,GAAG,EAAE,CAAC;AACxB,IAAI,IAAI,WAAW,GAAG,CAAC,CAAC;AACxB,IAAI,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,EAAE,CAAC,EAAE,EAAE;AACnC,QAAQ,MAAM,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;AAC7C,QAAQ,MAAM,KAAK,GAAG,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;AACnH,QAAQ,IAAI,MAAM,KAAK,OAAO,EAAE;AAChC,YAAY,MAAM,MAAM,GAAG,CAAC,GAAG,CAAC,CAAC;AACjC,YAAY,KAAK,IAAI,CAAC,GAAG,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;AAC7C,gBAAgB,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;AAC1F,aAAa;AACb,SAAS;AACT,QAAQ,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AAC3D,KAAK;AACL;AACA,IAAI,MAAM,QAAQ,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AACpD;AACA,IAAI,IAAI,QAAQ,KAAK,MAAM,CAAC,MAAM,CAAC,EAAE;AACrC,QAAQ,MAAM,IAAI,KAAK,CAAC,CAAC,mBAAmB,EAAE,MAAM,CAAC,iBAAiB,CAAC,CAAC,CAAC;AACzE,KAAK;AACL;AACA,IAAI,SAAS,CAAC,MAAM,CAAC,GAAG,QAAQ,CAAC;AACjC,IAAI,OAAO,QAAQ,CAAC;AACpB,CAAC;AACD,MAAM,SAAS,GAAG,EAAE,CAAC;AACrB;AACA;AACA;AACA;AACA;AACO,MAAM,MAAM,SAAS,QAAQ,CAAC;AACrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,WAAW,CAAC,OAAO,EAAE;AACzB,QAAQ,KAAK,CAAC,KAAK,GAAG,OAAO,CAAC,CAAC;AAC/B,KAAK;AACL,IAAI,OAAO,CAAC,KAAK,EAAE;AACnB,QAAQ,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAC7C,QAAQ,cAAc,CAAC,KAAK,IAAI,CAAC,IAAI,KAAK,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC;AAC3G,QAAQ,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC;AAC5B,KAAK;AACL,IAAI,YAAY,CAAC,IAAI,EAAE;AACvB,QAAQ,OAAO,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;AACpD,KAAK;AACL,IAAI,KAAK,CAAC,MAAM,EAAE;AAClB,QAAQ,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,gBAAgB,EAAE,EAAE,CAAC,CAAC;AACtD,QAAQ,OAAO,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAChC,KAAK;AACL;AACA;AACA;AACA;AACA;AACA,IAAI,OAAO,QAAQ,CAAC,OAAO,EAAE;AAC7B,QAAQ,IAAI,SAAS,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE;AACxC,YAAY,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC,CAAC;AACrD,SAAS;AACT,QAAQ,OAAO,SAAS,CAAC,OAAO,CAAC,CAAC;AAClC,KAAK;AACL;;;;","x_google_ignoreList":[0,1,2,8]} \ No newline at end of file diff --git a/dist/wordlists-extra.min.js b/dist/wordlists-extra.min.js deleted file mode 100644 index 1ed78fe0..00000000 --- a/dist/wordlists-extra.min.js +++ /dev/null @@ -1 +0,0 @@ -function number(n){if(!Number.isSafeInteger(n)||n<0)throw new Error(`Wrong positive integer: ${n}`)}function bytes(b,...lengths){if(!(b instanceof Uint8Array))throw new Error("Expected Uint8Array");if(lengths.length>0&&!lengths.includes(b.length))throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`)}function exists(instance,checkFinished=true){if(instance.destroyed)throw new Error("Hash instance has been destroyed");if(checkFinished&&instance.finished)throw new Error("Hash#digest() has already been called")}function output(out,instance){bytes(out);const min=instance.outputLen;if(out.lengtha instanceof Uint8Array;const u32=arr=>new Uint32Array(arr.buffer,arr.byteOffset,Math.floor(arr.byteLength/4));const isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!isLE)throw new Error("Non little-endian hardware is not supported");function utf8ToBytes(str){if(typeof str!=="string")throw new Error(`utf8ToBytes expected string, got ${typeof str}`);return new Uint8Array((new TextEncoder).encode(str))}function toBytes(data){if(typeof data==="string")data=utf8ToBytes(data);if(!u8a(data))throw new Error(`expected Uint8Array, got ${typeof data}`);return data}class Hash{clone(){return this._cloneInto()}}function wrapConstructor(hashCons){const hashC=msg=>hashCons().update(toBytes(msg)).digest();const tmp=hashCons();hashC.outputLen=tmp.outputLen;hashC.blockLen=tmp.blockLen;hashC.create=()=>hashCons();return hashC}const U32_MASK64=BigInt(2**32-1);const _32n=BigInt(32);function fromBig(n,le=false){if(le)return{h:Number(n&U32_MASK64),l:Number(n>>_32n&U32_MASK64)};return{h:Number(n>>_32n&U32_MASK64)|0,l:Number(n&U32_MASK64)|0}}function split(lst,le=false){let Ah=new Uint32Array(lst.length);let Al=new Uint32Array(lst.length);for(let i=0;ih<>>32-s;const rotlSL=(h,l,s)=>l<>>32-s;const rotlBH=(h,l,s)=>l<>>64-s;const rotlBL=(h,l,s)=>h<>>64-s;const version="1.0.0-alpha.5";function defineProperties(target,values,types){for(const key in values){const value=values[key];Object.defineProperty(target,key,{enumerable:true,value:value,writable:false})}}function stringify(value){if(value==null){return"null"}if(Array.isArray(value)){return"[ "+value.map(stringify).join(", ")+" ]"}if(value instanceof Uint8Array){const HEX="0123456789abcdef";let result="0x";for(let i=0;i>4];result+=HEX[value[i]&15]}return result}if(typeof value==="object"&&typeof value.toJSON==="function"){return stringify(value.toJSON())}switch(typeof value){case"boolean":case"symbol":return value.toString();case"bigint":return BigInt(value).toString();case"number":return value.toString();case"string":return JSON.stringify(value);case"object":{const keys=Object.keys(value);keys.sort();return"{ "+keys.map(k=>`${stringify(k)}: ${stringify(value[k])}`).join(", ")+" }"}}return`[ COULD NOT SERIALIZE ]`}function makeError(message,code,info){const shortMessage=message;{const details=[];if(info){if("message"in info||"code"in info||"name"in info){throw new Error(`value will overwrite populated values: ${stringify(info)}`)}for(const key in info){if(key==="shortMessage"){continue}const value=info[key];details.push(key+"="+stringify(value))}}details.push(`code=${code}`);details.push(`version=${version}`);if(details.length){message+=" ("+details.join(", ")+")"}}let error;switch(code){case"INVALID_ARGUMENT":error=new TypeError(message);break;case"NUMERIC_FAULT":case"BUFFER_OVERRUN":error=new RangeError(message);break;default:error=new Error(message)}defineProperties(error,{code:code});if(info){Object.assign(error,info)}if(error.shortMessage==null){defineProperties(error,{shortMessage:shortMessage})}return error}function assert(check,message,code,info){if(!check){throw makeError(message,code,info)}}function assertArgument(check,message,name,value){assert(check,message,"INVALID_ARGUMENT",{argument:name,value:value})}["NFD","NFC","NFKD","NFKC"].reduce((accum,form)=>{try{if("test".normalize(form)!=="test"){throw new Error("bad")}if(form==="NFD"){const check=String.fromCharCode(233).normalize("NFD");const expected=String.fromCharCode(101,769);if(check!==expected){throw new Error("broken")}}accum.push(form)}catch(error){}return accum},[]);function _getBytes(value,name,copy){if(value instanceof Uint8Array){return value}if(typeof value==="string"&&value.match(/^0x([0-9a-f][0-9a-f])*$/i)){const result=new Uint8Array((value.length-2)/2);let offset=2;for(let i=0;i>4]+HexCharacters[v&15]}return result}function errorFunc(reason,offset,bytes,output,badCodepoint){assertArgument(false,`invalid codepoint at offset ${offset}; ${reason}`,"bytes",bytes)}function ignoreFunc(reason,offset,bytes,output,badCodepoint){if(reason==="BAD_PREFIX"||reason==="UNEXPECTED_CONTINUE"){let i=0;for(let o=offset+1;o>6!==2){break}i++}return i}if(reason==="OVERRUN"){return bytes.length-offset-1}return 0}function replaceFunc(reason,offset,bytes,output,badCodepoint){if(reason==="OVERLONG"){assertArgument(typeof badCodepoint==="number","invalid bad code point for replacement","badCodepoint",badCodepoint);output.push(badCodepoint);return 0}output.push(65533);return ignoreFunc(reason,offset,bytes)}const Utf8ErrorFuncs=Object.freeze({error:errorFunc,ignore:ignoreFunc,replace:replaceFunc});function getUtf8CodePoints(_bytes,onError){if(onError==null){onError=Utf8ErrorFuncs.error}const bytes=getBytes(_bytes,"bytes");const result=[];let i=0;while(i>7===0){result.push(c);continue}let extraLength=null;let overlongMask=null;if((c&224)===192){extraLength=1;overlongMask=127}else if((c&240)===224){extraLength=2;overlongMask=2047}else if((c&248)===240){extraLength=3;overlongMask=65535}else{if((c&192)===128){i+=onError("UNEXPECTED_CONTINUE",i-1,bytes,result)}else{i+=onError("BAD_PREFIX",i-1,bytes,result)}continue}if(i-1+extraLength>=bytes.length){i+=onError("OVERRUN",i-1,bytes,result);continue}let res=c&(1<<8-extraLength-1)-1;for(let j=0;j1114111){i+=onError("OUT_OF_RANGE",i-1-extraLength,bytes,result,res);continue}if(res>=55296&&res<=57343){i+=onError("UTF16_SURROGATE",i-1-extraLength,bytes,result,res);continue}if(res<=overlongMask){i+=onError("OVERLONG",i-1-extraLength,bytes,result,res);continue}result.push(res)}return result}function toUtf8Bytes(str,form){const result=[];for(let i=0;i>6|192);result.push(c&63|128)}else if((c&64512)==55296){i++;const c2=str.charCodeAt(i);assertArgument(i>18|240);result.push(pair>>12&63|128);result.push(pair>>6&63|128);result.push(pair&63|128)}else{result.push(c>>12|224);result.push(c>>6&63|128);result.push(c&63|128)}}return new Uint8Array(result)}function _toUtf8String(codePoints){return codePoints.map(codePoint=>{if(codePoint<=65535){return String.fromCharCode(codePoint)}codePoint-=65536;return String.fromCharCode((codePoint>>10&1023)+55296,(codePoint&1023)+56320)}).join("")}function toUtf8String(bytes,onError){return _toUtf8String(getUtf8CodePoints(bytes,onError))}const[SHA3_PI,SHA3_ROTL,_SHA3_IOTA]=[[],[],[]];const _0n=BigInt(0);const _1n=BigInt(1);const _2n=BigInt(2);const _7n=BigInt(7);const _256n=BigInt(256);const _0x71n=BigInt(113);for(let round=0,R=_1n,x=1,y=0;round<24;round++){[x,y]=[y,(2*x+3*y)%5];SHA3_PI.push(2*(5*y+x));SHA3_ROTL.push((round+1)*(round+2)/2%64);let t=_0n;for(let j=0;j<7;j++){R=(R<<_1n^(R>>_7n)*_0x71n)%_256n;if(R&_2n)t^=_1n<<(_1n<s>32?rotlBH(h,l,s):rotlSH(h,l,s);const rotlL=(h,l,s)=>s>32?rotlBL(h,l,s):rotlSL(h,l,s);function keccakP(s,rounds=24){const B=new Uint32Array(5*2);for(let round=24-rounds;round<24;round++){for(let x=0;x<10;x++)B[x]=s[x]^s[x+10]^s[x+20]^s[x+30]^s[x+40];for(let x=0;x<10;x+=2){const idx1=(x+8)%10;const idx0=(x+2)%10;const B0=B[idx0];const B1=B[idx0+1];const Th=rotlH(B0,B1,1)^B[idx1];const Tl=rotlL(B0,B1,1)^B[idx1+1];for(let y=0;y<50;y+=10){s[x+y]^=Th;s[x+y+1]^=Tl}}let curH=s[2];let curL=s[3];for(let t=0;t<24;t++){const shift=SHA3_ROTL[t];const Th=rotlH(curH,curL,shift);const Tl=rotlL(curH,curL,shift);const PI=SHA3_PI[t];curH=s[PI];curL=s[PI+1];s[PI]=Th;s[PI+1]=Tl}for(let y=0;y<50;y+=10){for(let x=0;x<10;x++)B[x]=s[y+x];for(let x=0;x<10;x++)s[y+x]^=~B[(x+2)%10]&B[(x+4)%10]}s[0]^=SHA3_IOTA_H[round];s[1]^=SHA3_IOTA_L[round]}B.fill(0)}class Keccak extends Hash{constructor(blockLen,suffix,outputLen,enableXOF=false,rounds=24){super();this.blockLen=blockLen;this.suffix=suffix;this.outputLen=outputLen;this.enableXOF=enableXOF;this.rounds=rounds;this.pos=0;this.posOut=0;this.finished=false;this.destroyed=false;number(outputLen);if(0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200);this.state32=u32(this.state)}keccak(){keccakP(this.state32,this.rounds);this.posOut=0;this.pos=0}update(data){exists(this);const{blockLen,state}=this;data=toBytes(data);const len=data.length;for(let pos=0;pos=blockLen)this.keccak();const take=Math.min(blockLen-this.posOut,len-pos);out.set(bufferOut.subarray(this.posOut,this.posOut+take),pos);this.posOut+=take;pos+=take}return out}xofInto(out){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(out)}xof(bytes){number(bytes);return this.xofInto(new Uint8Array(bytes))}digestInto(out){output(out,this);if(this.finished)throw new Error("digest() was already called");this.writeInto(out);this.destroy();return out}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=true;this.state.fill(0)}_cloneInto(to){const{blockLen,suffix,outputLen,rounds,enableXOF}=this;to||(to=new Keccak(blockLen,suffix,outputLen,enableXOF,rounds));to.state32.set(this.state32);to.pos=this.pos;to.posOut=this.posOut;to.finished=this.finished;to.rounds=rounds;to.suffix=suffix;to.outputLen=outputLen;to.enableXOF=enableXOF;to.destroyed=this.destroyed;return to}}const gen=(suffix,blockLen,outputLen)=>wrapConstructor(()=>new Keccak(blockLen,suffix,outputLen));const keccak_256=gen(1,136,256/8);let locked=false;const _keccak256=function(data){return keccak_256(data)};let __keccak256=_keccak256;function keccak256(_data){const data=getBytes(_data,"data");return hexlify(__keccak256(data))}keccak256._=_keccak256;keccak256.lock=function(){locked=true};keccak256.register=function(func){if(locked){throw new TypeError("keccak256 is locked")}__keccak256=func};Object.freeze(keccak256);function id(value){return keccak256(toUtf8Bytes(value))}const subsChrs=" !#$%&'()*+,-./<=>?@[]^_`{|}~";const Word=/^[a-z]*$/i;function unfold(words,sep){let initial=97;return words.reduce((accum,word)=>{if(word===sep){initial++}else if(word.match(Word)){accum.push(String.fromCharCode(initial)+word)}else{initial=97;accum.push(word)}return accum},[])}function decode(data,subs){for(let i=subsChrs.length-1;i>=0;i--){data=data.split(subsChrs[i]).join(subs.substring(2*i,2*i+2))}const clumps=[];const leftover=data.replace(/(:|([0-9])|([A-Z][a-z]*))/g,(all,item,semi,word)=>{if(semi){for(let i=parseInt(semi);i>=0;i--){clumps.push(";")}}else{clumps.push(item.toLowerCase())}return""});if(leftover){throw new Error(`leftovers: ${JSON.stringify(leftover)}`)}return unfold(unfold(clumps,";"),":")}function decodeOwl(data){assertArgument(data[0]==="0","unsupported auwl data","data",data);return decode(data.substring(1+2*subsChrs.length),data.substring(1,1+2*subsChrs.length))}class Wordlist{locale;constructor(locale){defineProperties(this,{locale:locale})}split(phrase){return phrase.toLowerCase().split(/\s+/g)}join(words){return words.join(" ")}}class WordlistOwl extends Wordlist{#data;#checksum;constructor(locale,data,checksum){super(locale);this.#data=data;this.#checksum=checksum;this.#words=null}get _data(){return this.#data}_decodeWords(){return decodeOwl(this.#data)}#words;#loadWords(){if(this.#words==null){const words=this._decodeWords();const checksum=id(words.join("\n")+"\n");if(checksum!==this.#checksum){throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`)}this.#words=words}return this.#words}getWord(index){const words=this.#loadWords();assertArgument(index>=0&&index=width){const value=accum>>bits-width;accum&=(1<{const match=accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/);assertArgument(match!==null,"internal error parsing accents","accents",accents);let posOffset=0;const positions=decodeBits(parseInt(match[3]),match[4]);const charCode=parseInt(match[2]);const regex=new RegExp(`([${match[1]}])`,"g");words=words.replace(regex,(all,letter)=>{const rem=--positions[posOffset];if(rem===0){letter=String.fromCharCode(letter.charCodeAt(0),charCode);posOffset++}return letter})});return words.split(",")}class WordlistOwlA extends WordlistOwl{#accent;constructor(locale,data,accent,checksum){super(locale,data,checksum);this.#accent=accent}get _accent(){return this.#accent}_decodeWords(){return decodeOwlA(this._data,this._accent)}}const words$3="0arertoiotadonoaRteirroenaNonaLsolocoiliaralaorrenadaChoN$n0A>Dom,EjaI!#Oga&O'Or#RazoR*Ue=U<0Ab Adem@CeLe%OmoRa!RozUn0DazD$GeLaM,#S,)T^0AlAnceA+EEl]`E`EstruzI.I<2ErU{U'0Af[nArO)Uc Uf_Ul:BaB^|eH@IleJ Lanz/c.LdeMbuN>Nd-oRb(>RnizR+Scu]S#nSu[Tal]T!@T*Tu%UlZ 3BeBid/=S SoSt@3|oEnNgo2An>OqueUsa2ABi`BoCaCi`DaDegaIn//!oLsaMb-{dNi#N}saiRdeRr SqueTeTinVe{Zal2AvoAzoEchaEveIl=In>IsaOcaOmaOnceO)UjaUs>U#2CeoCleE'EyFan{F.HoIt_L#Rbuj(l(+Sc TacaZ.:Bal=BezaBi`B[CaoDav!D,aErFeI{ImanJaJ.LLam Lc$L&Li{dLleLm/^LvoMaMb$Mel=Mi'Mp}c!Nd?Nel-gu+Nic-#N-.ObaOsPazPi%nPo)Pt Puch((b.RcelRe%Rg(i'RneRpe%R+R%SaS>S!oSpaS#rT^ceT_U{lUsaZo3Bol]D!D+Ld/eb_LoAmpuAnc]ApaAr]I>Is)IvoOqueOzaUle%Up 0Cl.EgoE=EnEr#F[G +M->NeN%P_sR>Rue]SneTaU{d2Am^AnA+AseAveI,)ImaInica2B_Cc~|i'Ci`CoDigoDoF_G!He)JinJoL/ch/eg$Lg Lin/l LmoLum`Mba)M!Mi{Mo&Mpr-deNej}g-oc!Nsej}t PaPi(az.Rba%RchoR&nR.(r!S!SmosS%2AneoAt!E Ec!Ei&EmaIaIm,Ip%IsisOmoOnicaOque%U&Uz2Ad+Ar#At+BoBr*| aEl=En#Er{Es%EvaId Lebr/p/#Mb_Mpl*N-e%O%P.Pul( R$Se'Sf[zVaVi'5BleCeL^Ming}N Ra&Rm*RAu%EchaOrO%U*UjoU^2B@CaGa%G.L$Lle#N&Rm(+Rtun(z SaTo2AcaA'AsaAtisAveIe%Il=IpeIsI#OG Gu!aJaMb_Ng}^Nr((mig('St?Yo5E>ElgaEr%ENgl-$Nt Pit!R S#V,?Zg :7Lo5A]:B$C$C[DoD+nG #GrimaGu`I>M!Mi`Mp --ch-gos%NzaPizRgoRvaStimaTaTexT*U_lV Zo3AlCc~|eC#rErG~Gumb_Ja'Ngu-#NaOnOp &S~TalT[VeY,{3B!%dB+C^D!Di EnzoGaG!oMaMi)M.Mp$NceN&Ne-go)N}t!`Qui&SoS%T!aT$T+2AgaAmaAn#AveEg En Ev Or Ov!Uv@2BoC~CoCu[GicaG+MbrizM}jaTe5|aC*G J}-esPaSt+ToZ:Ce%|oD!aD_Du+Est+F@G@GoIzL{dLe%Ll/oMaMboMutN>N&Nej Ng-iquiNj N}Re(f?Rg,Ri&RmolR+nR)sRzoSaSc aSivoT T!@TizTrizXimoY^Z^ca3|aDal]D$Du]J?]J^L,/.M^i-^NsajeN)NuRca&R,gueRi#SS.TaT!To&T+Zc]3E&ElEmb+G/Lag+Lit Ll.M}-!}im}u#OpeR SaS!@S?SmoTadTo5|?aC~DaDe=HoJ LdeL!Li'M,#Mi- c-ed-j-#NoRad(d!Re'R*R+Rs(%lScaStr TivoV!V?Zo5|oD EbleE]Er)Est[G_J!L/e%L%N&Nec(alRoScu=SeoSgoSicaS=:C C~D IpeRanj(izRr SalTalTivoTu[lUseaValVeVi{d3C$Ct G Goc$G+OnRv$ToUt+V V!a3|oDoEb]E#NezNoTi&Vel5Bleza|eMin(i(m()TaTic@Va#Ve]V$5BeCaCleoD?=DoE[EveEzLoM!oTr@:Sis0EC~E[In On!T TicaUes#1Ac~A&rAlBi%CaD,EjaGa'G@Gul=I,)Ig,Il]OQues%Uga0Ad@Cu+Ez'OT[0O'Ro1EjaU=1I&Ige'0En)0O':C#D_El]Gi`GoIsJ oLabr/>Le%Li&Lm/om/p NNalNi>Nt!-ue=PaPelP?]Que)R Rcel(edR*RoRpa&RqueR[foR)S SeoS~SoS%TaT$Tr@UsaU%VoYa<3A#nCa&C!a|oDalD*G IneL L{'Le/ig+LlejoLoLuc--s N.OnOrPi'Que'R(ch(d!Rez(f?Ri>Rl(mizEgun%Em$EnsaE|!oD^Eb=Er%Es#Lg/*Lm.LpoLrNd*N%P #Pet*PoN{PaP!oSaScaSt+T 5BiB^DoE{G*I&In/e%LoMboM^Ptu[TaTi`:Ba&B!B$BleC GazG[&L/&L!oL*Lm.L.Ls/#LudLv Mb-c~Ndi-e Ng_Ni{dN}#PoQueRdin()nSt_TanU`Xof.3Cc~CoC_#C%DGu*IsL=LvaMa`M?l-d-Re'Rg*S#T?:Ba>BiqueB]BuCoC#JoL L>L,#Ll/.Ma'Mb^Ng}quePaPe)P@P.Qu?l(deRe(if(je%RotR+R%TuajeU+ZaZ.3At+|oC]CnicaJa&J!Ji&L/efo'MaM^Mp=NazNd!N!NisNRmi'Rnur(+rSisSo+StigoT!aX#Z3B$Bu+nEmpoEn{Er[EPoR(.TanT!eTu=Za5Al]B?=C Ci'DoG/&M N}#P PeQueRaxR!oRm,%RneoRoRpe&R_RS!Xi>2AbajoAc#rA!Afi>AgoAjeAmoAnceA#AumaAz EbolEguaEin%EnEp EsIbuIgoIpaIs)IunfoOfeoOmpaOn>OpaO)OzoU>Ue'Ufa2B!@BoEr#MbaM^NelNic(bin(ismoR'T^:0Ic 9C!a0B[l0I{dIrIv!b){return 1}return 0}for(let length=3;length<=9;length++){const d=data$2[length-3];for(let offset=0;offset=0&&index=40){code=code+168-40}else if(code>=19){code=code+97-19}return toUtf8String(new Uint8Array([225,(code>>6)+132,(code&63)+128]))}let _wordlist$1=null;function loadWords$1(){if(_wordlist$1!=null){return _wordlist$1}const wordlist=[];data$1.forEach((data,length)=>{length+=4;for(let i=0;i=0&&index>2),128+codes.indexOf(data[i*3+1]),128+codes.indexOf(data[i*3+2])];if(locale==="zh_tw"){const common=s%4;for(let i=common;i<3;i++){bytes[i]=codes.indexOf(deltaData[deltaOffset++])+(i==0?228:128)}}wordlist.push(toUtf8String(new Uint8Array(bytes)))}const checksum=id(wordlist.join("\n")+"\n");if(checksum!==Checks[locale]){throw new Error(`BIP39 Wordlist for ${locale} (Chinese) FAILED`)}_wordlist[locale]=wordlist;return wordlist}const wordlists={};class LangZh extends Wordlist{constructor(dialect){super("zh_"+dialect)}getWord(index){const words=loadWords(this.locale);assertArgument(index>=0&&index