UNPKG

coinley-checkout

Version:

A React SDK for Coinley cryptocurrency payment processing with multi-network support

1,512 lines (1,511 loc) 732 kB
import * as React$2 from "react"; import React__default, { useRef as useRef$1, useEffect as useEffect$2, createContext, createElement, useContext, useMemo as useMemo$1, useSyncExternalStore as useSyncExternalStore$3, useState as useState$1, useCallback, forwardRef, useImperativeHandle } from "react"; const styles = ""; const version$4 = "2.33.2"; let errorConfig = { getDocsUrl: ({ docsBaseUrl, docsPath: docsPath2 = "", docsSlug }) => docsPath2 ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath2}${docsSlug ? `#${docsSlug}` : ""}` : void 0, version: `viem@${version$4}` }; let BaseError$4 = class BaseError extends Error { constructor(shortMessage, args = {}) { const details = (() => { if (args.cause instanceof BaseError) return args.cause.details; if (args.cause?.message) return args.cause.message; return args.details; })(); const docsPath2 = (() => { if (args.cause instanceof BaseError) return args.cause.docsPath || args.docsPath; return args.docsPath; })(); const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath: docsPath2 }); const message = [ shortMessage || "An error occurred.", "", ...args.metaMessages ? [...args.metaMessages, ""] : [], ...docsUrl ? [`Docs: ${docsUrl}`] : [], ...details ? [`Details: ${details}`] : [], ...errorConfig.version ? [`Version: ${errorConfig.version}`] : [] ].join("\n"); super(message, args.cause ? { cause: args.cause } : void 0); Object.defineProperty(this, "details", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "docsPath", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "metaMessages", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "shortMessage", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "version", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "BaseError" }); this.details = details; this.docsPath = docsPath2; this.metaMessages = args.metaMessages; this.name = args.name ?? this.name; this.shortMessage = shortMessage; this.version = version$4; } walk(fn) { return walk$1(this, fn); } }; function walk$1(err, fn) { if (fn?.(err)) return err; if (err && typeof err === "object" && "cause" in err && err.cause !== void 0) return walk$1(err.cause, fn); return fn ? null : err; } let IntegerOutOfRangeError$1 = class IntegerOutOfRangeError extends BaseError$4 { constructor({ max, min, signed, size: size2, value }) { super(`Number "${value}" is not in safe ${size2 ? `${size2 * 8}-bit ${signed ? "signed" : "unsigned"} ` : ""}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: "IntegerOutOfRangeError" }); } }; class InvalidBytesBooleanError extends BaseError$4 { constructor(bytes) { super(`Bytes value "${bytes}" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, { name: "InvalidBytesBooleanError" }); } } class InvalidHexBooleanError extends BaseError$4 { constructor(hex) { super(`Hex value "${hex}" is not a valid boolean. The hex value must be "0x0" (false) or "0x1" (true).`, { name: "InvalidHexBooleanError" }); } } let SizeOverflowError$1 = class SizeOverflowError extends BaseError$4 { constructor({ givenSize, maxSize }) { super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); } }; let SliceOffsetOutOfBoundsError$1 = class SliceOffsetOutOfBoundsError extends BaseError$4 { constructor({ offset, position, size: size2 }) { super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" }); } }; let SizeExceedsPaddingSizeError$1 = class SizeExceedsPaddingSizeError extends BaseError$4 { constructor({ size: size2, targetSize, type }) { super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); } }; class InvalidBytesLengthError extends BaseError$4 { constructor({ size: size2, targetSize, type }) { super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size2} ${type} long.`, { name: "InvalidBytesLengthError" }); } } function pad$1(hexOrBytes, { dir, size: size2 = 32 } = {}) { if (typeof hexOrBytes === "string") return padHex(hexOrBytes, { dir, size: size2 }); return padBytes(hexOrBytes, { dir, size: size2 }); } function padHex(hex_, { dir, size: size2 = 32 } = {}) { if (size2 === null) return hex_; const hex = hex_.replace("0x", ""); if (hex.length > size2 * 2) throw new SizeExceedsPaddingSizeError$1({ size: Math.ceil(hex.length / 2), targetSize: size2, type: "hex" }); return `0x${hex[dir === "right" ? "padEnd" : "padStart"](size2 * 2, "0")}`; } function padBytes(bytes, { dir, size: size2 = 32 } = {}) { if (size2 === null) return bytes; if (bytes.length > size2) throw new SizeExceedsPaddingSizeError$1({ size: bytes.length, targetSize: size2, type: "bytes" }); const paddedBytes = new Uint8Array(size2); for (let i = 0; i < size2; i++) { const padEnd = dir === "right"; paddedBytes[padEnd ? i : size2 - i - 1] = bytes[padEnd ? i : bytes.length - i - 1]; } return paddedBytes; } function isHex(value, { strict = true } = {}) { if (!value) return false; if (typeof value !== "string") return false; return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x"); } function size$3(value) { if (isHex(value, { strict: false })) return Math.ceil((value.length - 2) / 2); return value.length; } function trim(hexOrBytes, { dir = "left" } = {}) { let data = typeof hexOrBytes === "string" ? hexOrBytes.replace("0x", "") : hexOrBytes; let sliceLength = 0; for (let i = 0; i < data.length - 1; i++) { if (data[dir === "left" ? i : data.length - i - 1].toString() === "0") sliceLength++; else break; } data = dir === "left" ? data.slice(sliceLength) : data.slice(0, data.length - sliceLength); if (typeof hexOrBytes === "string") { if (data.length === 1 && dir === "right") data = `${data}0`; return `0x${data.length % 2 === 1 ? `0${data}` : data}`; } return data; } const encoder$2 = /* @__PURE__ */ new TextEncoder(); function toBytes$1(value, opts = {}) { if (typeof value === "number" || typeof value === "bigint") return numberToBytes(value, opts); if (typeof value === "boolean") return boolToBytes(value, opts); if (isHex(value)) return hexToBytes$1(value, opts); return stringToBytes(value, opts); } function boolToBytes(value, opts = {}) { const bytes = new Uint8Array(1); bytes[0] = Number(value); if (typeof opts.size === "number") { assertSize$1(bytes, { size: opts.size }); return pad$1(bytes, { size: opts.size }); } return bytes; } const charCodeMap = { zero: 48, nine: 57, A: 65, F: 70, a: 97, f: 102 }; function charCodeToBase16(char) { if (char >= charCodeMap.zero && char <= charCodeMap.nine) return char - charCodeMap.zero; if (char >= charCodeMap.A && char <= charCodeMap.F) return char - (charCodeMap.A - 10); if (char >= charCodeMap.a && char <= charCodeMap.f) return char - (charCodeMap.a - 10); return void 0; } function hexToBytes$1(hex_, opts = {}) { let hex = hex_; if (opts.size) { assertSize$1(hex, { size: opts.size }); hex = pad$1(hex, { dir: "right", size: opts.size }); } let hexString = hex.slice(2); if (hexString.length % 2) hexString = `0${hexString}`; const length = hexString.length / 2; const bytes = new Uint8Array(length); for (let index2 = 0, j = 0; index2 < length; index2++) { const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++)); const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++)); if (nibbleLeft === void 0 || nibbleRight === void 0) { throw new BaseError$4(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`); } bytes[index2] = nibbleLeft * 16 + nibbleRight; } return bytes; } function numberToBytes(value, opts) { const hex = numberToHex(value, opts); return hexToBytes$1(hex); } function stringToBytes(value, opts = {}) { const bytes = encoder$2.encode(value); if (typeof opts.size === "number") { assertSize$1(bytes, { size: opts.size }); return pad$1(bytes, { dir: "right", size: opts.size }); } return bytes; } function assertSize$1(hexOrBytes, { size: size2 }) { if (size$3(hexOrBytes) > size2) throw new SizeOverflowError$1({ givenSize: size$3(hexOrBytes), maxSize: size2 }); } function hexToBigInt(hex, opts = {}) { const { signed } = opts; if (opts.size) assertSize$1(hex, { size: opts.size }); const value = BigInt(hex); if (!signed) return value; const size2 = (hex.length - 2) / 2; const max = (1n << BigInt(size2) * 8n - 1n) - 1n; if (value <= max) return value; return value - BigInt(`0x${"f".padStart(size2 * 2, "f")}`) - 1n; } function hexToBool(hex_, opts = {}) { let hex = hex_; if (opts.size) { assertSize$1(hex, { size: opts.size }); hex = trim(hex); } if (trim(hex) === "0x00") return false; if (trim(hex) === "0x01") return true; throw new InvalidHexBooleanError(hex); } function hexToNumber(hex, opts = {}) { return Number(hexToBigInt(hex, opts)); } function hexToString(hex, opts = {}) { let bytes = hexToBytes$1(hex); if (opts.size) { assertSize$1(bytes, { size: opts.size }); bytes = trim(bytes, { dir: "right" }); } return new TextDecoder().decode(bytes); } const hexes$2 = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); function toHex(value, opts = {}) { if (typeof value === "number" || typeof value === "bigint") return numberToHex(value, opts); if (typeof value === "string") { return stringToHex(value, opts); } if (typeof value === "boolean") return boolToHex(value, opts); return bytesToHex$1(value, opts); } function boolToHex(value, opts = {}) { const hex = `0x${Number(value)}`; if (typeof opts.size === "number") { assertSize$1(hex, { size: opts.size }); return pad$1(hex, { size: opts.size }); } return hex; } function bytesToHex$1(value, opts = {}) { let string = ""; for (let i = 0; i < value.length; i++) { string += hexes$2[value[i]]; } const hex = `0x${string}`; if (typeof opts.size === "number") { assertSize$1(hex, { size: opts.size }); return pad$1(hex, { dir: "right", size: opts.size }); } return hex; } function numberToHex(value_, opts = {}) { const { signed, size: size2 } = opts; const value = BigInt(value_); let maxValue; if (size2) { if (signed) maxValue = (1n << BigInt(size2) * 8n - 1n) - 1n; else maxValue = 2n ** (BigInt(size2) * 8n) - 1n; } else if (typeof value_ === "number") { maxValue = BigInt(Number.MAX_SAFE_INTEGER); } const minValue = typeof maxValue === "bigint" && signed ? -maxValue - 1n : 0; if (maxValue && value > maxValue || value < minValue) { const suffix = typeof value_ === "bigint" ? "n" : ""; throw new IntegerOutOfRangeError$1({ max: maxValue ? `${maxValue}${suffix}` : void 0, min: `${minValue}${suffix}`, signed, size: size2, value: `${value_}${suffix}` }); } const hex = `0x${(signed && value < 0 ? (1n << BigInt(size2 * 8)) + BigInt(value) : value).toString(16)}`; if (size2) return pad$1(hex, { size: size2 }); return hex; } const encoder$1 = /* @__PURE__ */ new TextEncoder(); function stringToHex(value_, opts = {}) { const value = encoder$1.encode(value_); return bytesToHex$1(value, opts); } function formatAbiItem$1(abiItem, { includeName = false } = {}) { if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error") throw new InvalidDefinitionTypeError(abiItem.type); return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`; } function formatAbiParams(params, { includeName = false } = {}) { if (!params) return ""; return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ","); } function formatAbiParam(param, { includeName }) { if (param.type.startsWith("tuple")) { return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`; } return param.type + (includeName && param.name ? ` ${param.name}` : ""); } class AbiConstructorNotFoundError extends BaseError$4 { constructor({ docsPath: docsPath2 }) { super([ "A constructor was not found on the ABI.", "Make sure you are using the correct ABI and that the constructor exists on it." ].join("\n"), { docsPath: docsPath2, name: "AbiConstructorNotFoundError" }); } } class AbiConstructorParamsNotFoundError extends BaseError$4 { constructor({ docsPath: docsPath2 }) { super([ "Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.", "Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists." ].join("\n"), { docsPath: docsPath2, name: "AbiConstructorParamsNotFoundError" }); } } class AbiDecodingDataSizeTooSmallError extends BaseError$4 { constructor({ data, params, size: size2 }) { super([`Data size of ${size2} bytes is too small for given parameters.`].join("\n"), { metaMessages: [ `Params: (${formatAbiParams(params, { includeName: true })})`, `Data: ${data} (${size2} bytes)` ], name: "AbiDecodingDataSizeTooSmallError" }); Object.defineProperty(this, "data", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "params", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "size", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.data = data; this.params = params; this.size = size2; } } class AbiDecodingZeroDataError extends BaseError$4 { constructor() { super('Cannot decode zero data ("0x") with ABI parameters.', { name: "AbiDecodingZeroDataError" }); } } class AbiEncodingArrayLengthMismatchError extends BaseError$4 { constructor({ expectedLength, givenLength, type }) { super([ `ABI encoding array length mismatch for type ${type}.`, `Expected length: ${expectedLength}`, `Given length: ${givenLength}` ].join("\n"), { name: "AbiEncodingArrayLengthMismatchError" }); } } class AbiEncodingBytesSizeMismatchError extends BaseError$4 { constructor({ expectedSize, value }) { super(`Size of bytes "${value}" (bytes${size$3(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); } } class AbiEncodingLengthMismatchError extends BaseError$4 { constructor({ expectedLength, givenLength }) { super([ "ABI encoding params/values length mismatch.", `Expected length (params): ${expectedLength}`, `Given length (values): ${givenLength}` ].join("\n"), { name: "AbiEncodingLengthMismatchError" }); } } class AbiErrorInputsNotFoundError extends BaseError$4 { constructor(errorName, { docsPath: docsPath2 }) { super([ `Arguments (\`args\`) were provided to "${errorName}", but "${errorName}" on the ABI does not contain any parameters (\`inputs\`).`, "Cannot encode error result without knowing what the parameter types are.", "Make sure you are using the correct ABI and that the inputs exist on it." ].join("\n"), { docsPath: docsPath2, name: "AbiErrorInputsNotFoundError" }); } } class AbiErrorNotFoundError extends BaseError$4 { constructor(errorName, { docsPath: docsPath2 } = {}) { super([ `Error ${errorName ? `"${errorName}" ` : ""}not found on ABI.`, "Make sure you are using the correct ABI and that the error exists on it." ].join("\n"), { docsPath: docsPath2, name: "AbiErrorNotFoundError" }); } } class AbiErrorSignatureNotFoundError extends BaseError$4 { constructor(signature, { docsPath: docsPath2 }) { super([ `Encoded error signature "${signature}" not found on ABI.`, "Make sure you are using the correct ABI and that the error exists on it.", `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.` ].join("\n"), { docsPath: docsPath2, name: "AbiErrorSignatureNotFoundError" }); Object.defineProperty(this, "signature", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.signature = signature; } } class AbiEventSignatureEmptyTopicsError extends BaseError$4 { constructor({ docsPath: docsPath2 }) { super("Cannot extract event signature from empty topics.", { docsPath: docsPath2, name: "AbiEventSignatureEmptyTopicsError" }); } } class AbiEventSignatureNotFoundError extends BaseError$4 { constructor(signature, { docsPath: docsPath2 }) { super([ `Encoded event signature "${signature}" not found on ABI.`, "Make sure you are using the correct ABI and that the event exists on it.", `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.` ].join("\n"), { docsPath: docsPath2, name: "AbiEventSignatureNotFoundError" }); } } class AbiEventNotFoundError extends BaseError$4 { constructor(eventName, { docsPath: docsPath2 } = {}) { super([ `Event ${eventName ? `"${eventName}" ` : ""}not found on ABI.`, "Make sure you are using the correct ABI and that the event exists on it." ].join("\n"), { docsPath: docsPath2, name: "AbiEventNotFoundError" }); } } class AbiFunctionNotFoundError extends BaseError$4 { constructor(functionName, { docsPath: docsPath2 } = {}) { super([ `Function ${functionName ? `"${functionName}" ` : ""}not found on ABI.`, "Make sure you are using the correct ABI and that the function exists on it." ].join("\n"), { docsPath: docsPath2, name: "AbiFunctionNotFoundError" }); } } class AbiFunctionOutputsNotFoundError extends BaseError$4 { constructor(functionName, { docsPath: docsPath2 }) { super([ `Function "${functionName}" does not contain any \`outputs\` on ABI.`, "Cannot decode function result without knowing what the parameter types are.", "Make sure you are using the correct ABI and that the function exists on it." ].join("\n"), { docsPath: docsPath2, name: "AbiFunctionOutputsNotFoundError" }); } } class AbiFunctionSignatureNotFoundError extends BaseError$4 { constructor(signature, { docsPath: docsPath2 }) { super([ `Encoded function signature "${signature}" not found on ABI.`, "Make sure you are using the correct ABI and that the function exists on it.", `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.` ].join("\n"), { docsPath: docsPath2, name: "AbiFunctionSignatureNotFoundError" }); } } class AbiItemAmbiguityError extends BaseError$4 { constructor(x, y) { super("Found ambiguous types in overloaded ABI items.", { metaMessages: [ `\`${x.type}\` in \`${formatAbiItem$1(x.abiItem)}\`, and`, `\`${y.type}\` in \`${formatAbiItem$1(y.abiItem)}\``, "", "These types encode differently and cannot be distinguished at runtime.", "Remove one of the ambiguous items in the ABI." ], name: "AbiItemAmbiguityError" }); } } class BytesSizeMismatchError extends BaseError$4 { constructor({ expectedSize, givenSize }) { super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { name: "BytesSizeMismatchError" }); } } class DecodeLogDataMismatch extends BaseError$4 { constructor({ abiItem, data, params, size: size2 }) { super([ `Data size of ${size2} bytes is too small for non-indexed event parameters.` ].join("\n"), { metaMessages: [ `Params: (${formatAbiParams(params, { includeName: true })})`, `Data: ${data} (${size2} bytes)` ], name: "DecodeLogDataMismatch" }); Object.defineProperty(this, "abiItem", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "data", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "params", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "size", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.abiItem = abiItem; this.data = data; this.params = params; this.size = size2; } } class DecodeLogTopicsMismatch extends BaseError$4 { constructor({ abiItem, param }) { super([ `Expected a topic for indexed event parameter${param.name ? ` "${param.name}"` : ""} on event "${formatAbiItem$1(abiItem, { includeName: true })}".` ].join("\n"), { name: "DecodeLogTopicsMismatch" }); Object.defineProperty(this, "abiItem", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.abiItem = abiItem; } } class InvalidAbiEncodingTypeError extends BaseError$4 { constructor(type, { docsPath: docsPath2 }) { super([ `Type "${type}" is not a valid encoding type.`, "Please provide a valid ABI type." ].join("\n"), { docsPath: docsPath2, name: "InvalidAbiEncodingType" }); } } class InvalidAbiDecodingTypeError extends BaseError$4 { constructor(type, { docsPath: docsPath2 }) { super([ `Type "${type}" is not a valid decoding type.`, "Please provide a valid ABI type." ].join("\n"), { docsPath: docsPath2, name: "InvalidAbiDecodingType" }); } } class InvalidArrayError extends BaseError$4 { constructor(value) { super([`Value "${value}" is not a valid array.`].join("\n"), { name: "InvalidArrayError" }); } } class InvalidDefinitionTypeError extends BaseError$4 { constructor(type) { super([ `"${type}" is not a valid definition type.`, 'Valid types: "function", "event", "error"' ].join("\n"), { name: "InvalidDefinitionTypeError" }); } } class UnsupportedPackedAbiType extends BaseError$4 { constructor(type) { super(`Type "${type}" is not supported for packed encoding.`, { name: "UnsupportedPackedAbiType" }); } } function concat$1(values) { if (typeof values[0] === "string") return concatHex(values); return concatBytes$1(values); } function concatBytes$1(values) { let length = 0; for (const arr of values) { length += arr.length; } const result = new Uint8Array(length); let offset = 0; for (const arr of values) { result.set(arr, offset); offset += arr.length; } return result; } function concatHex(values) { return `0x${values.reduce((acc, x) => acc + x.replace("0x", ""), "")}`; } class InvalidAddressError extends BaseError$4 { constructor({ address }) { super(`Address "${address}" is invalid.`, { metaMessages: [ "- Address must be a hex value of 20 bytes (40 hex characters).", "- Address must match its checksum counterpart." ], name: "InvalidAddressError" }); } } class LruMap extends Map { constructor(size2) { super(); Object.defineProperty(this, "maxSize", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.maxSize = size2; } get(key) { const value = super.get(key); if (super.has(key) && value !== void 0) { this.delete(key); super.set(key, value); } return value; } set(key, value) { super.set(key, value); if (this.maxSize && this.size > this.maxSize) { const firstKey = this.keys().next().value; if (firstKey) this.delete(firstKey); } return this; } } const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); const _32n = /* @__PURE__ */ BigInt(32); function fromBig(n2, le = false) { if (le) return { h: Number(n2 & U32_MASK64), l: Number(n2 >> _32n & U32_MASK64) }; return { h: Number(n2 >> _32n & U32_MASK64) | 0, l: Number(n2 & U32_MASK64) | 0 }; } function split(lst, le = false) { const len = lst.length; let Ah = new Uint32Array(len); let Al = new Uint32Array(len); for (let i = 0; i < len; i++) { const { h, l: l2 } = fromBig(lst[i], le); [Ah[i], Al[i]] = [h, l2]; } return [Ah, Al]; } const rotlSH = (h, l2, s) => h << s | l2 >>> 32 - s; const rotlSL = (h, l2, s) => l2 << s | h >>> 32 - s; const rotlBH = (h, l2, s) => l2 << s - 32 | h >>> 64 - s; const rotlBL = (h, l2, s) => h << s - 32 | l2 >>> 64 - s; const crypto = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0; /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } function anumber(n2) { if (!Number.isSafeInteger(n2) || n2 < 0) throw new Error("positive integer expected, got " + n2); } function abytes(b, ...lengths) { if (!isBytes(b)) throw new Error("Uint8Array expected"); if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length); } function ahash(h) { if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash should be wrapped by utils.createHasher"); anumber(h.outputLen); anumber(h.blockLen); } function aexists(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 aoutput(out, instance) { abytes(out); const min = instance.outputLen; if (out.length < min) { throw new Error("digestInto() expects output buffer of length at least " + min); } } function u32(arr) { return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); } function clean(...arrays) { for (let i = 0; i < arrays.length; i++) { arrays[i].fill(0); } } function createView(arr) { return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); } function rotr(word, shift) { return word << 32 - shift | word >>> shift; } const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); function byteSwap(word) { return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; } function byteSwap32(arr) { for (let i = 0; i < arr.length; i++) { arr[i] = byteSwap(arr[i]); } return arr; } const swap32IfBE = isLE ? (u) => u : byteSwap32; const hasHexBuiltin = /* @__PURE__ */ (() => ( // @ts-ignore typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" ))(); const hexes$1 = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); function bytesToHex(bytes) { abytes(bytes); if (hasHexBuiltin) return bytes.toHex(); let hex = ""; for (let i = 0; i < bytes.length; i++) { hex += hexes$1[bytes[i]]; } return hex; } const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; function asciiToBase16(ch) { if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); return; } function hexToBytes(hex) { if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); if (hasHexBuiltin) return Uint8Array.fromHex(hex); const hl = hex.length; const al = hl / 2; if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl); const array = new Uint8Array(al); for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { const n1 = asciiToBase16(hex.charCodeAt(hi)); const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); if (n1 === void 0 || n2 === void 0) { const char = hex[hi] + hex[hi + 1]; throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi); } array[ai] = n1 * 16 + n2; } return array; } function utf8ToBytes(str) { if (typeof str !== "string") throw new Error("string expected"); return new Uint8Array(new TextEncoder().encode(str)); } function toBytes(data) { if (typeof data === "string") data = utf8ToBytes(data); abytes(data); return data; } function concatBytes(...arrays) { let sum = 0; for (let i = 0; i < arrays.length; i++) { const a = arrays[i]; abytes(a); sum += a.length; } const res = new Uint8Array(sum); for (let i = 0, pad2 = 0; i < arrays.length; i++) { const a = arrays[i]; res.set(a, pad2); pad2 += a.length; } return res; } class Hash { } function createHasher(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(bytesLength = 32) { if (crypto && typeof crypto.getRandomValues === "function") { return crypto.getRandomValues(new Uint8Array(bytesLength)); } if (crypto && typeof crypto.randomBytes === "function") { return Uint8Array.from(crypto.randomBytes(bytesLength)); } throw new Error("crypto.getRandomValues must be defined"); } const _0n = BigInt(0); const _1n = BigInt(1); const _2n = BigInt(2); const _7n = BigInt(7); const _256n = BigInt(256); const _0x71n = BigInt(113); const SHA3_PI = []; const SHA3_ROTL = []; const _SHA3_IOTA = []; 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 << /* @__PURE__ */ BigInt(j)) - _1n; } _SHA3_IOTA.push(t); } const IOTAS = split(_SHA3_IOTA, true); const SHA3_IOTA_H = IOTAS[0]; const SHA3_IOTA_L = IOTAS[1]; const rotlH = (h, l2, s) => s > 32 ? rotlBH(h, l2, s) : rotlSH(h, l2, s); const rotlL = (h, l2, s) => s > 32 ? rotlBL(h, l2, s) : rotlSL(h, l2, 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]; } clean(B); } class Keccak extends Hash { // NOTE: we accept arguments in bytes instead of bits here. constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { super(); this.pos = 0; this.posOut = 0; this.finished = false; this.destroyed = false; this.enableXOF = false; this.blockLen = blockLen; this.suffix = suffix; this.outputLen = outputLen; this.enableXOF = enableXOF; this.rounds = rounds; anumber(outputLen); if (!(0 < blockLen && blockLen < 200)) throw new Error("only keccak-f1600 function is supported"); this.state = new Uint8Array(200); this.state32 = u32(this.state); } clone() { return this._cloneInto(); } keccak() { swap32IfBE(this.state32); keccakP(this.state32, this.rounds); swap32IfBE(this.state32); this.posOut = 0; this.pos = 0; } update(data) { aexists(this); data = toBytes(data); abytes(data); const { blockLen, state } = this; 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; state[pos] ^= suffix; if ((suffix & 128) !== 0 && pos === blockLen - 1) this.keccak(); state[blockLen - 1] ^= 128; this.keccak(); } writeInto(out) { aexists(this, false); abytes(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) { if (!this.enableXOF) throw new Error("XOF is not possible for this instance"); return this.writeInto(out); } xof(bytes) { anumber(bytes); return this.xofInto(new Uint8Array(bytes)); } digestInto(out) { aoutput(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; clean(this.state); } _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) => createHasher(() => new Keccak(blockLen, suffix, outputLen)); const keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))(); function keccak256(value, to_) { const to = to_ || "hex"; const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes$1(value) : value); if (to === "bytes") return bytes; return toHex(bytes); } const checksumAddressCache = /* @__PURE__ */ new LruMap(8192); function checksumAddress(address_, chainId) { if (checksumAddressCache.has(`${address_}.${chainId}`)) return checksumAddressCache.get(`${address_}.${chainId}`); const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase(); const hash2 = keccak256(stringToBytes(hexAddress), "bytes"); const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split(""); for (let i = 0; i < 40; i += 2) { if (hash2[i >> 1] >> 4 >= 8 && address[i]) { address[i] = address[i].toUpperCase(); } if ((hash2[i >> 1] & 15) >= 8 && address[i + 1]) { address[i + 1] = address[i + 1].toUpperCase(); } } const result = `0x${address.join("")}`; checksumAddressCache.set(`${address_}.${chainId}`, result); return result; } function getAddress(address, chainId) { if (!isAddress(address, { strict: false })) throw new InvalidAddressError({ address }); return checksumAddress(address, chainId); } const addressRegex = /^0x[a-fA-F0-9]{40}$/; const isAddressCache = /* @__PURE__ */ new LruMap(8192); function isAddress(address, options) { const { strict = true } = options ?? {}; const cacheKey = `${address}.${strict}`; if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey); const result = (() => { if (!addressRegex.test(address)) return false; if (address.toLowerCase() === address) return true; if (strict) return checksumAddress(address) === address; return true; })(); isAddressCache.set(cacheKey, result); return result; } function slice$1(value, start, end, { strict } = {}) { if (isHex(value, { strict: false })) return sliceHex(value, start, end, { strict }); return sliceBytes(value, start, end, { strict }); } function assertStartOffset$1(value, start) { if (typeof start === "number" && start > 0 && start > size$3(value) - 1) throw new SliceOffsetOutOfBoundsError$1({ offset: start, position: "start", size: size$3(value) }); } function assertEndOffset$1(value, start, end) { if (typeof start === "number" && typeof end === "number" && size$3(value) !== end - start) { throw new SliceOffsetOutOfBoundsError$1({ offset: end, position: "end", size: size$3(value) }); } } function sliceBytes(value_, start, end, { strict } = {}) { assertStartOffset$1(value_, start); const value = value_.slice(start, end); if (strict) assertEndOffset$1(value, start, end); return value; } function sliceHex(value_, start, end, { strict } = {}) { assertStartOffset$1(value_, start); const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`; if (strict) assertEndOffset$1(value, start, end); return value; } const arrayRegex = /^(.*)\[([0-9]*)\]$/; const bytesRegex$1 = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; const integerRegex$1 = /^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/; function encodeAbiParameters(params, values) { if (params.length !== values.length) throw new AbiEncodingLengthMismatchError({ expectedLength: params.length, givenLength: values.length }); const preparedParams = prepareParams({ params, values }); const data = encodeParams(preparedParams); if (data.length === 0) return "0x"; return data; } function prepareParams({ params, values }) { const preparedParams = []; for (let i = 0; i < params.length; i++) { preparedParams.push(prepareParam({ param: params[i], value: values[i] })); } return preparedParams; } function prepareParam({ param, value }) { const arrayComponents = getArrayComponents(param.type); if (arrayComponents) { const [length, type] = arrayComponents; return encodeArray(value, { length, param: { ...param, type } }); } if (param.type === "tuple") { return encodeTuple(value, { param }); } if (param.type === "address") { return encodeAddress(value); } if (param.type === "bool") { return encodeBool(value); } if (param.type.startsWith("uint") || param.type.startsWith("int")) { const signed = param.type.startsWith("int"); const [, , size2 = "256"] = integerRegex$1.exec(param.type) ?? []; return encodeNumber(value, { signed, size: Number(size2) }); } if (param.type.startsWith("bytes")) { return encodeBytes(value, { param }); } if (param.type === "string") { return encodeString(value); } throw new InvalidAbiEncodingTypeError(param.type, { docsPath: "/docs/contract/encodeAbiParameters" }); } function encodeParams(preparedParams) { let staticSize = 0; for (let i = 0; i < preparedParams.length; i++) { const { dynamic, encoded } = preparedParams[i]; if (dynamic) staticSize += 32; else staticSize += size$3(encoded); } const staticParams = []; const dynamicParams = []; let dynamicSize = 0; for (let i = 0; i < preparedParams.length; i++) { const { dynamic, encoded } = preparedParams[i]; if (dynamic) { staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 })); dynamicParams.push(encoded); dynamicSize += size$3(encoded); } else { staticParams.push(encoded); } } return concat$1([...staticParams, ...dynamicParams]); } function encodeAddress(value) { if (!isAddress(value)) throw new InvalidAddressError({ address: value }); return { dynamic: false, encoded: padHex(value.toLowerCase()) }; } function encodeArray(value, { length, param }) { const dynamic = length === null; if (!Array.isArray(value)) throw new InvalidArrayError(value); if (!dynamic && value.length !== length) throw new AbiEncodingArrayLengthMismatchError({ expectedLength: length, givenLength: value.length, type: `${param.type}[${length}]` }); let dynamicChild = false; const preparedParams = []; for (let i = 0; i < value.length; i++) { const preparedParam = prepareParam({ param, value: value[i] }); if (preparedParam.dynamic) dynamicChild = true; preparedParams.push(preparedParam); } if (dynamic || dynamicChild) { const data = encodeParams(preparedParams); if (dynamic) { const length2 = numberToHex(preparedParams.length, { size: 32 }); return { dynamic: true, encoded: preparedParams.length > 0 ? concat$1([length2, data]) : length2 }; } if (dynamicChild) return { dynamic: true, encoded: data }; } return { dynamic: false, encoded: concat$1(preparedParams.map(({ encoded }) => encoded)) }; } function encodeBytes(value, { param }) { const [, paramSize] = param.type.split("bytes"); const bytesSize = size$3(value); if (!paramSize) { let value_ = value; if (bytesSize % 32 !== 0) value_ = padHex(value_, { dir: "right", size: Math.ceil((value.length - 2) / 2 / 32) * 32 }); return { dynamic: true, encoded: concat$1([padHex(numberToHex(bytesSize, { size: 32 })), value_]) }; } if (bytesSize !== Number.parseInt(paramSize)) throw new AbiEncodingBytesSizeMismatchError({ expectedSize: Number.parseInt(paramSize), value }); return { dynamic: false, encoded: padHex(value, { dir: "right" }) }; } function encodeBool(value) { if (typeof value !== "boolean") throw new BaseError$4(`Invalid boolean value: "${value}" (type: ${typeof value}). Expected: \`true\` or \`false\`.`); return { dynamic: false, encoded: padHex(boolToHex(value)) }; } function encodeNumber(value, { signed, size: size2 = 256 }) { if (typeof size2 === "number") { const max = 2n ** (BigInt(size2) - (signed ? 1n : 0n)) - 1n; const min = signed ? -max - 1n : 0n; if (value > max || value < min) throw new IntegerOutOfRangeError$1({ max: max.toString(), min: min.toString(), signed, size: size2 / 8, value: value.toString() }); } return { dynamic: false, encoded: numberToHex(value, { size: 32, signed }) }; } function encodeString(value) { const hexValue = stringToHex(value); const partsLength = Math.ceil(size$3(hexValue) / 32); const parts = []; for (let i = 0; i < partsLength; i++) { parts.push(padHex(slice$1(hexValue, i * 32, (i + 1) * 32), { dir: "right" })); } return { dynamic: true, encoded: concat$1([ padHex(numberToHex(size$3(hexValue), { size: 32 })), ...parts ]) }; } function encodeTuple(value, { param }) { let dynamic = false; const preparedParams = []; for (let i = 0; i < param.components.length; i++) { const param_ = param.components[i]; const index2 = Array.isArray(value) ? i : param_.name; const preparedParam = prepareParam({ param: param_, value: value[index2] }); preparedParams.push(preparedParam); if (preparedParam.dynamic) dynamic = true; } return { dynamic, encoded: dynamic ? encodeParams(preparedParams) : concat$1(preparedParams.map(({ encoded }) => encoded)) }; } function getArrayComponents(type) { const matches = type.match(/^(.*)\[(\d+)?\]$/); return matches ? ( // Return `null` if the array is dynamic. [matches[2] ? Number(matches[2]) : null, matches[1]] ) : void 0; } const docsPath$4 = "/docs/contract/encodeDeployData"; function encodeDeployData(parameters) { const { abi, args, bytecode } = parameters; if (!args || args.length === 0) return bytecode; const description = abi.find((x) => "type" in x && x.type === "constructor"); if (!description) throw new AbiConstructorNotFoundError({ docsPath: docsPath$4 }); if (!("inputs" in description)) throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath$4 }); if (!description.inputs || description.inputs.length === 0) throw new AbiConstructorParamsNotFoundError({ docsPath: docsPath$4 }); const data = encodeAbiParameters(description.inputs, args); return concatHex([bytecode, data]); } function parseAccount(account) { if (typeof account === "string") return { address: account, type: "json-rpc" }; return account; } class AccountNotFoundError extends BaseError$4 { constructor({ docsPath: docsPath2 } = {}) { super([ "Could not find an Account to execute with this Action.", "Please provide an Account with the `account` argument on the Action, or by supplying an `account` to the Client." ].join("\n"), { docsPath: docsPath2, docsSlug: "account", name: "AccountNotFoundError" }); } } class AccountTypeNotSupportedError extends BaseError$4 { constructor({ docsPath: docsPath2, metaMessages, type }) { super(`Account type "${type}" is not supported.`, { docsPath: docsPath2, metaMessages, name: "AccountTypeNotSupportedError" }); } } function publicKeyToAddress(publicKey) { const address = keccak256(`0x${publicKey.substring(4)}`).substring(26); return checksumAddress(`0x${address}`); } async function recoverPublicKey({ hash: hash2, signature }) { const hashHex = isHex(hash2) ? hash2 : toHex(hash2); const { secp256k1 } = await import("./secp256k1-2fbdf512.mjs"); const signature_ = (() => { if (typeof signature === "object" && "r" in signature && "s" in signature) { const { r, s, v, yParity } = signature; const yParityOrV2 = Number(yParity ?? v); const recoveryBit2 = toRecoveryBit(yParityOrV2); return new secp256k1.Signature(hexToBigInt(r), hexToBigInt(s)).addRecoveryBit(recoveryBit2); } const signatureHex = isHex(signature) ? signature : toHex(signature); if (size$3(signatureHex) !== 65) throw new Error("invalid signature length"); const yParityOrV = hexToNumber(`0x${signatureHex.slice(130)}`); const recoveryBit = toRecoveryBit(yParityOrV); return secp256k1.Signature.fromCompact(signatureHex.substring(2, 130)).addRecoveryBit(recoveryBit); })(); const publicKey = signature_.recoverPublicKey(hashHex.substring(2)).toHex(false); return `0x${publicKey}`; } function toRecoveryBit(yParityOrV) { if (yParityOrV === 0 || yParityOrV === 1) return yParityOrV; if (yParityOrV === 27) return 0; if (yParityOrV === 28) return 1; throw new Error("Invalid yParityOrV value"); } async function recoverAddress({ hash: hash2, signature }) { return publicKeyToAddress(await recoverPublicKey({ hash: hash2, signature })); } class NegativeOffsetError extends BaseError$4 { constructor({ offset }) { super(`Offset \`${offset}\` cannot be negative.`, { name: "NegativeOffsetError" }); } } class PositionOutOfBoundsError extends BaseError$4 { constructor({ length, position }) { super(`Position \`${position}\` is out of bounds (\`0 < position < ${length}\`).`, { name: "PositionOutOfBoundsError" }); } } class RecursiveReadLimitExceededError extends BaseError$4 { constructor({ count, limit }) { super(`Recursive read limit of \`${limit}\` exceeded (recursive read count: \`${count}\`).`, { name: "RecursiveReadLimitExceededError" }); } } const staticCursor = { bytes: new Uint8Array(), dataView: new DataView(new ArrayBuffer(0)), position: 0, positionReadCount: /* @__PURE__ */ new Map(), recursiveReadCount: 0, recursiveReadLimit: Number.POSITIVE_INFINITY, assertReadLimit() { if (this.recursiveReadCount >= this.recursiveReadLimit) throw new RecursiveReadLimitExceededError({ count: this.recursiveReadCount + 1, limit: this.recursiveReadLimit }); }, assertPosition(position) { if (position < 0 || position > this.bytes.length - 1) throw new PositionOutOfBoundsError({ length: this.bytes.length,