UNPKG

@gemini-wallet/core

Version:

Core SDK for Gemini Wallet integration with popup communication

1,577 lines (1,538 loc) 186 kB
var __create = Object.create; var __getProtoOf = Object.getPrototypeOf; var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __toESM = (mod, isNodeMode, target) => { target = mod != null ? __create(__getProtoOf(mod)) : {}; const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; for (let key of __getOwnPropNames(mod)) if (!__hasOwnProp.call(to, key)) __defProp(to, key, { get: () => mod[key], enumerable: true }); return to; }; var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res); // node_modules/@noble/hashes/esm/_u64.js 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) { const len = lst.length; let Ah = new Uint32Array(len); let Al = new Uint32Array(len); for (let i = 0;i < len; i++) { const { h, l } = fromBig(lst[i], le); [Ah[i], Al[i]] = [h, l]; } return [Ah, Al]; } var U32_MASK64, _32n, rotlSH = (h, l, s) => h << s | l >>> 32 - s, rotlSL = (h, l, s) => l << s | h >>> 32 - s, rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s, rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; var init__u64 = __esm(() => { U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); _32n = /* @__PURE__ */ BigInt(32); }); // node_modules/@noble/hashes/esm/utils.js function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } function anumber(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n); } 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 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; } 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; } 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; } 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; } var isLE, swap32IfBE; var init_utils = __esm(() => { /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); swap32IfBE = isLE ? (u) => u : byteSwap32; }); // node_modules/@noble/hashes/esm/sha3.js 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); } var _0n, _1n, _2n, _7n, _256n, _0x71n, SHA3_PI, SHA3_ROTL, _SHA3_IOTA, IOTAS, SHA3_IOTA_H, SHA3_IOTA_L, rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s), rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s), Keccak, gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen)), keccak_256; var init_sha3 = __esm(() => { init__u64(); init_utils(); _0n = BigInt(0); _1n = BigInt(1); _2n = BigInt(2); _7n = BigInt(7); _256n = BigInt(256); _0x71n = BigInt(113); SHA3_PI = []; SHA3_ROTL = []; _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); } IOTAS = split(_SHA3_IOTA, true); SHA3_IOTA_H = IOTAS[0]; SHA3_IOTA_L = IOTAS[1]; Keccak = class Keccak extends Hash { 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; } }; keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))(); }); // node_modules/fast-safe-stringify/index.js var require_fast_safe_stringify = __commonJS((exports, module) => { module.exports = stringify; stringify.default = stringify; stringify.stable = deterministicStringify; stringify.stableStringify = deterministicStringify; var LIMIT_REPLACE_NODE = "[...]"; var CIRCULAR_REPLACE_NODE = "[Circular]"; var arr = []; var replacerStack = []; function defaultOptions() { return { depthLimit: Number.MAX_SAFE_INTEGER, edgesLimit: Number.MAX_SAFE_INTEGER }; } function stringify(obj, replacer, spacer, options) { if (typeof options === "undefined") { options = defaultOptions(); } decirc(obj, "", 0, [], undefined, 0, options); var res; try { if (replacerStack.length === 0) { res = JSON.stringify(obj, replacer, spacer); } else { res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); } } catch (_) { return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); } finally { while (arr.length !== 0) { var part = arr.pop(); if (part.length === 4) { Object.defineProperty(part[0], part[1], part[3]); } else { part[0][part[1]] = part[2]; } } } return res; } function setReplace(replace, val, k, parent) { var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); if (propertyDescriptor.get !== undefined) { if (propertyDescriptor.configurable) { Object.defineProperty(parent, k, { value: replace }); arr.push([parent, k, val, propertyDescriptor]); } else { replacerStack.push([val, k, replace]); } } else { parent[k] = replace; arr.push([parent, k, val]); } } function decirc(val, k, edgeIndex, stack, parent, depth, options) { depth += 1; var i; if (typeof val === "object" && val !== null) { for (i = 0;i < stack.length; i++) { if (stack[i] === val) { setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); return; } } if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { setReplace(LIMIT_REPLACE_NODE, val, k, parent); return; } if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { setReplace(LIMIT_REPLACE_NODE, val, k, parent); return; } stack.push(val); if (Array.isArray(val)) { for (i = 0;i < val.length; i++) { decirc(val[i], i, i, stack, val, depth, options); } } else { var keys = Object.keys(val); for (i = 0;i < keys.length; i++) { var key = keys[i]; decirc(val[key], key, i, stack, val, depth, options); } } stack.pop(); } } function compareFunction(a, b) { if (a < b) { return -1; } if (a > b) { return 1; } return 0; } function deterministicStringify(obj, replacer, spacer, options) { if (typeof options === "undefined") { options = defaultOptions(); } var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; var res; try { if (replacerStack.length === 0) { res = JSON.stringify(tmp, replacer, spacer); } else { res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); } } catch (_) { return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); } finally { while (arr.length !== 0) { var part = arr.pop(); if (part.length === 4) { Object.defineProperty(part[0], part[1], part[3]); } else { part[0][part[1]] = part[2]; } } } return res; } function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { depth += 1; var i; if (typeof val === "object" && val !== null) { for (i = 0;i < stack.length; i++) { if (stack[i] === val) { setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); return; } } try { if (typeof val.toJSON === "function") { return; } } catch (_) { return; } if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { setReplace(LIMIT_REPLACE_NODE, val, k, parent); return; } if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { setReplace(LIMIT_REPLACE_NODE, val, k, parent); return; } stack.push(val); if (Array.isArray(val)) { for (i = 0;i < val.length; i++) { deterministicDecirc(val[i], i, i, stack, val, depth, options); } } else { var tmp = {}; var keys = Object.keys(val).sort(compareFunction); for (i = 0;i < keys.length; i++) { var key = keys[i]; deterministicDecirc(val[key], key, i, stack, val, depth, options); tmp[key] = val[key]; } if (typeof parent !== "undefined") { arr.push([parent, k, val]); parent[k] = tmp; } else { return tmp; } } stack.pop(); } } function replaceGetterValues(replacer) { replacer = typeof replacer !== "undefined" ? replacer : function(k, v) { return v; }; return function(key, val) { if (replacerStack.length > 0) { for (var i = 0;i < replacerStack.length; i++) { var part = replacerStack[i]; if (part[1] === key && part[0] === val) { val = part[2]; replacerStack.splice(i, 1); break; } } } return replacer.call(this, key, val); }; } }); // node_modules/eventemitter3/index.js var require_eventemitter3 = __commonJS((exports, module) => { var has = Object.prototype.hasOwnProperty; var prefix = "~"; function Events() {} if (Object.create) { Events.prototype = Object.create(null); if (!new Events().__proto__) prefix = false; } function EE(fn, context, once) { this.fn = fn; this.context = context; this.once = once || false; } function addListener(emitter, event, fn, context, once) { if (typeof fn !== "function") { throw new TypeError("The listener must be a function"); } var listener = new EE(fn, context || emitter, once), evt = prefix ? prefix + event : event; if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); else emitter._events[evt] = [emitter._events[evt], listener]; return emitter; } function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events; else delete emitter._events[evt]; } function EventEmitter() { this._events = new Events; this._eventsCount = 0; } EventEmitter.prototype.eventNames = function eventNames() { var names = [], events, name; if (this._eventsCount === 0) return names; for (name in events = this._events) { if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); } if (Object.getOwnPropertySymbols) { return names.concat(Object.getOwnPropertySymbols(events)); } return names; }; EventEmitter.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event, handlers = this._events[evt]; if (!handlers) return []; if (handlers.fn) return [handlers.fn]; for (var i = 0, l = handlers.length, ee = new Array(l);i < l; i++) { ee[i] = handlers[i].fn; } return ee; }; EventEmitter.prototype.listenerCount = function listenerCount(event) { var evt = prefix ? prefix + event : event, listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return false; var listeners = this._events[evt], len = arguments.length, args, i; if (listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; case 3: return listeners.fn.call(listeners.context, a1, a2), true; case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } for (i = 1, args = new Array(len - 1);i < len; i++) { args[i - 1] = arguments[i]; } listeners.fn.apply(listeners.context, args); } else { var length = listeners.length, j; for (i = 0;i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; default: if (!args) for (j = 1, args = new Array(len - 1);j < len; j++) { args[j - 1] = arguments[j]; } listeners[i].fn.apply(listeners[i].context, args); } } } return true; }; EventEmitter.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; EventEmitter.prototype.once = function once(event, fn, context) { return addListener(this, event, fn, context, true); }; EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length;i < length; i++) { if (listeners[i].fn !== fn || once && !listeners[i].once || context && listeners[i].context !== context) { events.push(listeners[i]); } } if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { var evt; if (event) { evt = prefix ? prefix + event : event; if (this._events[evt]) clearEvent(this, evt); } else { this._events = new Events; this._eventsCount = 0; } return this; }; EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; EventEmitter.prefixed = prefix; EventEmitter.EventEmitter = EventEmitter; if (typeof module !== "undefined") { module.exports = EventEmitter; } }); // node_modules/abitype/dist/esm/regex.js function execTyped(regex, string2) { const match = regex.exec(string2); return match?.groups; } var init_regex = () => {}; // node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js function formatAbiParameter(abiParameter) { let type = abiParameter.type; if (tupleRegex.test(abiParameter.type) && "components" in abiParameter) { type = "("; const length = abiParameter.components.length; for (let i = 0;i < length; i++) { const component = abiParameter.components[i]; type += formatAbiParameter(component); if (i < length - 1) type += ", "; } const result = execTyped(tupleRegex, abiParameter.type); type += `)${result?.array ?? ""}`; return formatAbiParameter({ ...abiParameter, type }); } if ("indexed" in abiParameter && abiParameter.indexed) type = `${type} indexed`; if (abiParameter.name) return `${type} ${abiParameter.name}`; return type; } var tupleRegex; var init_formatAbiParameter = __esm(() => { init_regex(); tupleRegex = /^tuple(?<array>(\[(\d*)\])*)$/; }); // node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js function formatAbiParameters(abiParameters) { let params = ""; const length = abiParameters.length; for (let i = 0;i < length; i++) { const abiParameter = abiParameters[i]; params += formatAbiParameter(abiParameter); if (i !== length - 1) params += ", "; } return params; } var init_formatAbiParameters = __esm(() => { init_formatAbiParameter(); }); // node_modules/abitype/dist/esm/human-readable/formatAbiItem.js function formatAbiItem(abiItem) { if (abiItem.type === "function") return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== "nonpayable" ? ` ${abiItem.stateMutability}` : ""}${abiItem.outputs?.length ? ` returns (${formatAbiParameters(abiItem.outputs)})` : ""}`; if (abiItem.type === "event") return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; if (abiItem.type === "error") return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`; if (abiItem.type === "constructor") return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === "payable" ? " payable" : ""}`; if (abiItem.type === "fallback") return `fallback() external${abiItem.stateMutability === "payable" ? " payable" : ""}`; return "receive() external payable"; } var init_formatAbiItem = __esm(() => { init_formatAbiParameters(); }); // node_modules/abitype/dist/esm/exports/index.js var init_exports = __esm(() => { init_formatAbiItem(); }); // node_modules/viem/_esm/utils/abi/formatAbiItem.js function formatAbiItem2(abiItem, { includeName = false } = {}) { if (abiItem.type !== "function" && abiItem.type !== "event" && abiItem.type !== "error") throw new InvalidDefinitionTypeError(abiItem.type); return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`; } function formatAbiParams(params, { includeName = false } = {}) { if (!params) return ""; return params.map((param) => formatAbiParam(param, { includeName })).join(includeName ? ", " : ","); } function formatAbiParam(param, { includeName }) { if (param.type.startsWith("tuple")) { return `(${formatAbiParams(param.components, { includeName })})${param.type.slice("tuple".length)}`; } return param.type + (includeName && param.name ? ` ${param.name}` : ""); } var init_formatAbiItem2 = __esm(() => { init_abi(); }); // node_modules/viem/_esm/utils/data/isHex.js function isHex(value, { strict = true } = {}) { if (!value) return false; if (typeof value !== "string") return false; return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith("0x"); } // node_modules/viem/_esm/utils/data/size.js function size(value) { if (isHex(value, { strict: false })) return Math.ceil((value.length - 2) / 2); return value.length; } var init_size = () => {}; // node_modules/viem/_esm/errors/version.js var version = "2.33.3"; // node_modules/viem/_esm/errors/base.js function walk(err, fn) { if (fn?.(err)) return err; if (err && typeof err === "object" && "cause" in err && err.cause !== undefined) return walk(err.cause, fn); return fn ? null : err; } var errorConfig, BaseError; var init_base = __esm(() => { errorConfig = { getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : undefined, version: `viem@${version}` }; BaseError = 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 docsPath = (() => { if (args.cause instanceof BaseError) return args.cause.docsPath || args.docsPath; return args.docsPath; })(); const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath }); const message = [ shortMessage || "An error occurred.", "", ...args.metaMessages ? [...args.metaMessages, ""] : [], ...docsUrl ? [`Docs: ${docsUrl}`] : [], ...details ? [`Details: ${details}`] : [], ...errorConfig.version ? [`Version: ${errorConfig.version}`] : [] ].join(` `); super(message, args.cause ? { cause: args.cause } : undefined); Object.defineProperty(this, "details", { enumerable: true, configurable: true, writable: true, value: undefined }); Object.defineProperty(this, "docsPath", { enumerable: true, configurable: true, writable: true, value: undefined }); Object.defineProperty(this, "metaMessages", { enumerable: true, configurable: true, writable: true, value: undefined }); Object.defineProperty(this, "shortMessage", { enumerable: true, configurable: true, writable: true, value: undefined }); Object.defineProperty(this, "version", { enumerable: true, configurable: true, writable: true, value: undefined }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "BaseError" }); this.details = details; this.docsPath = docsPath; this.metaMessages = args.metaMessages; this.name = args.name ?? this.name; this.shortMessage = shortMessage; this.version = version; } walk(fn) { return walk(this, fn); } }; }); // node_modules/viem/_esm/errors/abi.js var AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, AbiFunctionNotFoundError, AbiItemAmbiguityError, BytesSizeMismatchError, InvalidAbiEncodingTypeError, InvalidArrayError, InvalidDefinitionTypeError, UnsupportedPackedAbiType; var init_abi = __esm(() => { init_formatAbiItem2(); init_size(); init_base(); AbiEncodingArrayLengthMismatchError = class AbiEncodingArrayLengthMismatchError extends BaseError { constructor({ expectedLength, givenLength, type }) { super([ `ABI encoding array length mismatch for type ${type}.`, `Expected length: ${expectedLength}`, `Given length: ${givenLength}` ].join(` `), { name: "AbiEncodingArrayLengthMismatchError" }); } }; AbiEncodingBytesSizeMismatchError = class AbiEncodingBytesSizeMismatchError extends BaseError { constructor({ expectedSize, value }) { super(`Size of bytes "${value}" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: "AbiEncodingBytesSizeMismatchError" }); } }; AbiEncodingLengthMismatchError = class AbiEncodingLengthMismatchError extends BaseError { constructor({ expectedLength, givenLength }) { super([ "ABI encoding params/values length mismatch.", `Expected length (params): ${expectedLength}`, `Given length (values): ${givenLength}` ].join(` `), { name: "AbiEncodingLengthMismatchError" }); } }; AbiFunctionNotFoundError = class AbiFunctionNotFoundError extends BaseError { constructor(functionName, { docsPath } = {}) { super([ `Function ${functionName ? `"${functionName}" ` : ""}not found on ABI.`, "Make sure you are using the correct ABI and that the function exists on it." ].join(` `), { docsPath, name: "AbiFunctionNotFoundError" }); } }; AbiItemAmbiguityError = class AbiItemAmbiguityError extends BaseError { constructor(x, y) { super("Found ambiguous types in overloaded ABI items.", { metaMessages: [ `\`${x.type}\` in \`${formatAbiItem2(x.abiItem)}\`, and`, `\`${y.type}\` in \`${formatAbiItem2(y.abiItem)}\``, "", "These types encode differently and cannot be distinguished at runtime.", "Remove one of the ambiguous items in the ABI." ], name: "AbiItemAmbiguityError" }); } }; BytesSizeMismatchError = class BytesSizeMismatchError extends BaseError { constructor({ expectedSize, givenSize }) { super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, { name: "BytesSizeMismatchError" }); } }; InvalidAbiEncodingTypeError = class InvalidAbiEncodingTypeError extends BaseError { constructor(type, { docsPath }) { super([ `Type "${type}" is not a valid encoding type.`, "Please provide a valid ABI type." ].join(` `), { docsPath, name: "InvalidAbiEncodingType" }); } }; InvalidArrayError = class InvalidArrayError extends BaseError { constructor(value) { super([`Value "${value}" is not a valid array.`].join(` `), { name: "InvalidArrayError" }); } }; InvalidDefinitionTypeError = class InvalidDefinitionTypeError extends BaseError { constructor(type) { super([ `"${type}" is not a valid definition type.`, 'Valid types: "function", "event", "error"' ].join(` `), { name: "InvalidDefinitionTypeError" }); } }; UnsupportedPackedAbiType = class UnsupportedPackedAbiType extends BaseError { constructor(type) { super(`Type "${type}" is not supported for packed encoding.`, { name: "UnsupportedPackedAbiType" }); } }; }); // node_modules/viem/_esm/errors/data.js var SliceOffsetOutOfBoundsError, SizeExceedsPaddingSizeError; var init_data = __esm(() => { init_base(); SliceOffsetOutOfBoundsError = class SliceOffsetOutOfBoundsError extends BaseError { constructor({ offset, position, size: size2 }) { super(`Slice ${position === "start" ? "starting" : "ending"} at offset "${offset}" is out-of-bounds (size: ${size2}).`, { name: "SliceOffsetOutOfBoundsError" }); } }; SizeExceedsPaddingSizeError = class SizeExceedsPaddingSizeError extends BaseError { constructor({ size: size2, targetSize, type }) { super(`${type.charAt(0).toUpperCase()}${type.slice(1).toLowerCase()} size (${size2}) exceeds padding size (${targetSize}).`, { name: "SizeExceedsPaddingSizeError" }); } }; }); // node_modules/viem/_esm/utils/data/pad.js function pad(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({ 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({ 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; } var init_pad = __esm(() => { init_data(); }); // node_modules/viem/_esm/errors/encoding.js var IntegerOutOfRangeError, SizeOverflowError; var init_encoding = __esm(() => { init_base(); IntegerOutOfRangeError = class IntegerOutOfRangeError extends BaseError { 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" }); } }; SizeOverflowError = class SizeOverflowError extends BaseError { constructor({ givenSize, maxSize }) { super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); } }; }); // node_modules/viem/_esm/utils/data/trim.js 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; } // node_modules/viem/_esm/utils/encoding/fromHex.js function assertSize(hexOrBytes, { size: size2 }) { if (size(hexOrBytes) > size2) throw new SizeOverflowError({ givenSize: size(hexOrBytes), maxSize: size2 }); } function hexToBigInt(hex, opts = {}) { const { signed } = opts; if (opts.size) assertSize(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 hexToNumber(hex, opts = {}) { return Number(hexToBigInt(hex, opts)); } var init_fromHex = __esm(() => { init_encoding(); init_size(); }); // node_modules/viem/_esm/utils/encoding/toHex.js 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(value, opts); } function boolToHex(value, opts = {}) { const hex = `0x${Number(value)}`; if (typeof opts.size === "number") { assertSize(hex, { size: opts.size }); return pad(hex, { size: opts.size }); } return hex; } function bytesToHex(value, opts = {}) { let string2 = ""; for (let i = 0;i < value.length; i++) { string2 += hexes[value[i]]; } const hex = `0x${string2}`; if (typeof opts.size === "number") { assertSize(hex, { size: opts.size }); return pad(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({ max: maxValue ? `${maxValue}${suffix}` : undefined, 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(hex, { size: size2 }); return hex; } function stringToHex(value_, opts = {}) { const value = encoder.encode(value_); return bytesToHex(value, opts); } var hexes, encoder; var init_toHex = __esm(() => { init_encoding(); init_pad(); init_fromHex(); hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, "0")); encoder = /* @__PURE__ */ new TextEncoder; }); // node_modules/viem/_esm/utils/encoding/toBytes.js function toBytes2(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(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(bytes, { size: opts.size }); return pad(bytes, { size: opts.size }); } return bytes; } 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; } function hexToBytes(hex_, opts = {}) { let hex = hex_; if (opts.size) { assertSize(hex, { size: opts.size }); hex = pad(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 index = 0, j = 0;index < length; index++) { const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++)); const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++)); if (nibbleLeft === undefined || nibbleRight === undefined) { throw new BaseError(`Invalid byte sequence ("${hexString[j - 2]}${hexString[j - 1]}" in "${hexString}").`); } bytes[index] = nibbleLeft * 16 + nibbleRight; } return bytes; } function numberToBytes(value, opts) { const hex = numberToHex(value, opts); return hexToBytes(hex); } function stringToBytes(value, opts = {}) { const bytes = encoder2.encode(value); if (typeof opts.size === "number") { assertSize(bytes, { size: opts.size }); return pad(bytes, { dir: "right", size: opts.size }); } return bytes; } var encoder2, charCodeMap; var init_toBytes = __esm(() => { init_base(); init_pad(); init_fromHex(); init_toHex(); encoder2 = /* @__PURE__ */ new TextEncoder; charCodeMap = { zero: 48, nine: 57, A: 65, F: 70, a: 97, f: 102 }; }); // node_modules/viem/_esm/utils/hash/keccak256.js function keccak256(value, to_) { const to = to_ || "hex"; const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes2(value) : value); if (to === "bytes") return bytes; return toHex(bytes); } var init_keccak256 = __esm(() => { init_sha3(); init_toBytes(); init_toHex(); }); // node_modules/viem/_esm/utils/hash/hashSignature.js function hashSignature(sig) { return hash(sig); } var hash = (value) => keccak256(toBytes2(value)); var init_hashSignature = __esm(() => { init_toBytes(); init_keccak256(); }); // node_modules/viem/_esm/utils/hash/normalizeSignature.js function normalizeSignature(signature) { let active = true; let current = ""; let level = 0; let result = ""; let valid = false; for (let i = 0;i < signature.length; i++) { const char = signature[i]; if (["(", ")", ","].includes(char)) active = true; if (char === "(") level++; if (char === ")") level--; if (!active) continue; if (level === 0) { if (char === " " && ["event", "function", ""].includes(result)) result = ""; else { result += char; if (char === ")") { valid = true; break; } } continue; } if (char === " ") { if (signature[i - 1] !== "," && current !== "," && current !== ",(") { current = ""; active = false; } continue; } result += char; current += char; } if (!valid) throw new BaseError("Unable to normalize signature."); return result; } var init_normalizeSignature = __esm(() => { init_base(); }); // node_modules/viem/_esm/utils/hash/toSignature.js var toSignature = (def) => { const def_ = (() => { if (typeof def === "string") return def; return formatAbiItem(def); })(); return normalizeSignature(def_); }; var init_toSignature = __esm(() => { init_exports(); init_normalizeSignature(); }); // node_modules/viem/_esm/utils/hash/toSignatureHash.js function toSignatureHash(fn) { return hashSignature(toSignature(fn)); } var init_toSignatureHash = __esm(() => { init_hashSignature(); init_toSignature(); }); // node_modules/viem/_esm/utils/hash/toEventSelector.js var toEventSelector; var init_toEventSelector = __esm(() => { init_toSignatureHash(); toEventSelector = toSignatureHash; }); // node_modules/viem/_esm/errors/address.js var InvalidAddressError; var init_address = __esm(() => { init_base(); InvalidAddressError = class InvalidAddressError extends BaseError { 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" }); } }; }); // node_modules/viem/_esm/utils/lru.js var LruMap; var init_lru = __esm(() => { LruMap = class LruMap extends Map { constructor(size2) { super(); Object.defineProperty(this, "maxSize", { enumerable: true, configurable: true, writable: true, value: undefined }); this.maxSize = size2; } get(key) { const value = super.get(key); if (super.has(key) && value !== undefined) { this.delete(key); super.set(key, value); } return value; } set(key, value) { super.set(key, value); if (this.maxSize && this.size > this.maxSize) { const firstKey = this.keys().next().value; if (firstKey) this.delete(firstKey); } return this; } }; }); // node_modules/viem/_esm/utils/address/getAddress.js function checksumAddress(address_, chainId) { if (checksumAddressCache.has(`${address_}.${chainId}`)) return checksumAddressCache.get(`${address_}.${chainId}`); const hexAddress = chainId ? `${chainId}${address_.toLowerCase()}` : address_.substring(2).toLowerCase(); const hash2 = keccak256(stringToBytes(hexAddress), "bytes"); const 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); } var checksumAddressCache; var init_getAddress = __esm(() => { init_address(); init_toBytes(); init_keccak256(); init_lru(); init_isAddress(); checksumAddressCache = /* @__PURE__ */ new LruMap(8192); }); // node_modules/viem/_esm/utils/address/isAddress.js function isAddress(address, options) { const { strict = true } = options ?? {}; const cacheKey = `${address}.${strict}`; if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey); const result = (() => { if (!addressRegex.test(address)) return false; if (address.toLowerCase() === address) return true; if (strict) return checksumAddress(address) === address; return true; })(); isAddressCache.set(cacheKey, result); return result; } var addressRegex, isAddressCache; var init_isAddress = __esm(() => { init_lru(); init_getAddress(); addressRegex = /^0x[a-fA-F0-9]{40}$/; isAddressCache = /* @__PURE__ */ new LruMap(8192); }); // node_modules/viem/_esm/utils/data/concat.js function concat(values) { if (typeof values[0] === "string") return concatHex(values); return concatBytes(values); } function concatBytes(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", ""), "")}`; } // node_modules/viem/_esm/utils/data/slice.js function slice(value, start, end, { strict } = {}) { if (isHex(value, { strict: false })) return sliceHex(value, start, end, { strict }); return sliceBytes(value, start, end, { strict }); } function assertStartOffset(value, start) { if (typeof start === "number" && start > 0 && start > size(value) - 1) throw new SliceOffsetOutOfBoundsError({ offset: start, position: "start", size: size(value) }); } function assertEndOffset(value, start, end) { if (typeof start === "number" && typeof end === "number" && size(value) !== end - start) { throw new SliceOffsetOutOfBoundsError({ offset: end, position: "end", size: size(value) }); } } function sliceBytes(value_, start, end, { strict } = {}) { assertStartOffset(value_, start); const value = value_.slice(start, end); if (strict) assertEndOffset(value, start, end); return value; } function sliceHex(value_, start, end, { strict } = {}) { assertStartOffset(value_, start); const value = `0x${value_.replace("0x", "").slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`; if (strict) assertEndOffset(value, start, end); return value; } var init_slice = __esm(() => { init_data(); init_size(); }); // node_modules/viem/_esm/utils/regex.js var arrayRegex, bytesRegex, integerRegex; var init_regex2 = __esm(() => { arrayRegex = /^(.*)\[([0-9]*)\]$/; bytesRegex = /^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/; integerRegex = /^(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)?$/; }); // node_modules/viem/_esm/utils/abi/encodeAbiParameters.js 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");