UNPKG

@etherspot/data-utils

Version:
1,604 lines (1,568 loc) 49.1 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __decorateClass = (decorators, target, key, kind) => { var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target; for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result; if (kind && result) __defProp(target, key, result); return result; }; // 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"); } var init_isHex = __esm({ "node_modules/viem/_esm/utils/data/isHex.js"() { } }); // 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 = __esm({ "node_modules/viem/_esm/utils/data/size.js"() { init_isHex(); } }); // node_modules/viem/_esm/errors/version.js var version; var init_version = __esm({ "node_modules/viem/_esm/errors/version.js"() { version = "2.22.19"; } }); // 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 !== void 0) return walk(err.cause, fn); return fn ? null : err; } var errorConfig, BaseError; var init_base = __esm({ "node_modules/viem/_esm/errors/base.js"() { init_version(); errorConfig = { getDocsUrl: ({ docsBaseUrl, docsPath = "", docsSlug }) => docsPath ? `${docsBaseUrl ?? "https://viem.sh"}${docsPath}${docsSlug ? `#${docsSlug}` : ""}` : void 0, 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("\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 = 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/data.js var SizeExceedsPaddingSizeError; var init_data = __esm({ "node_modules/viem/_esm/errors/data.js"() { init_base(); SizeExceedsPaddingSizeError = class 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({ "node_modules/viem/_esm/utils/data/pad.js"() { init_data(); } }); // node_modules/viem/_esm/errors/encoding.js var IntegerOutOfRangeError, SizeOverflowError; var init_encoding = __esm({ "node_modules/viem/_esm/errors/encoding.js"() { init_base(); IntegerOutOfRangeError = class 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 extends BaseError { constructor({ givenSize, maxSize }) { super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: "SizeOverflowError" }); } }; } }); // 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 }); } var init_fromHex = __esm({ "node_modules/viem/_esm/utils/encoding/fromHex.js"() { 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 string = ""; for (let i = 0; i < value.length; i++) { string += hexes[value[i]]; } const hex = `0x${string}`; 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}` : 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(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({ "node_modules/viem/_esm/utils/encoding/toHex.js"() { 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 toBytes(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 void 0; } 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 === void 0 || nibbleRight === void 0) { 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({ "node_modules/viem/_esm/utils/encoding/toBytes.js"() { init_base(); init_isHex(); 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/@noble/hashes/esm/_assert.js function anumber(n) { if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n); } function isBytes(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array"; } 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); } } var init_assert = __esm({ "node_modules/@noble/hashes/esm/_assert.js"() { } }); // 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) { 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]; } var U32_MASK64, _32n, rotlSH, rotlSL, rotlBH, rotlBL; var init_u64 = __esm({ "node_modules/@noble/hashes/esm/_u64.js"() { U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); _32n = /* @__PURE__ */ BigInt(32); 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; } }); // node_modules/@noble/hashes/esm/utils.js function u32(arr) { return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); } 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]); } } function utf8ToBytes(str) { if (typeof str !== "string") throw new Error("utf8ToBytes expected string, got " + typeof str); return new Uint8Array(new TextEncoder().encode(str)); } function toBytes2(data) { if (typeof data === "string") data = utf8ToBytes(data); abytes(data); return data; } function wrapConstructor(hashCons) { const hashC = (msg) => hashCons().update(toBytes2(msg)).digest(); const tmp = hashCons(); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = () => hashCons(); return hashC; } function wrapXOFConstructorWithOpts(hashCons) { const hashC = (msg, opts) => hashCons(opts).update(toBytes2(msg)).digest(); const tmp = hashCons({}); hashC.outputLen = tmp.outputLen; hashC.blockLen = tmp.blockLen; hashC.create = (opts) => hashCons(opts); return hashC; } var isLE, Hash; var init_utils = __esm({ "node_modules/@noble/hashes/esm/utils.js"() { init_assert(); isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); Hash = class { // Safe version that clones internal state clone() { return this._cloneInto(); } }; } }); // 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]; } B.fill(0); } var SHA3_PI, SHA3_ROTL, _SHA3_IOTA, _0n, _1n, _2n, _7n, _256n, _0x71n, SHA3_IOTA_H, SHA3_IOTA_L, rotlH, rotlL, Keccak, gen, sha3_224, sha3_256, sha3_384, sha3_512, keccak_224, keccak_256, keccak_384, keccak_512, genShake, shake128, shake256; var init_sha3 = __esm({ "node_modules/@noble/hashes/esm/sha3.js"() { init_assert(); init_u64(); init_utils(); SHA3_PI = []; SHA3_ROTL = []; _SHA3_IOTA = []; _0n = /* @__PURE__ */ BigInt(0); _1n = /* @__PURE__ */ BigInt(1); _2n = /* @__PURE__ */ BigInt(2); _7n = /* @__PURE__ */ BigInt(7); _256n = /* @__PURE__ */ BigInt(256); _0x71n = /* @__PURE__ */ 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 << /* @__PURE__ */ BigInt(j)) - _1n; } _SHA3_IOTA.push(t); } [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true); 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 = 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; anumber(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() { if (!isLE) byteSwap32(this.state32); keccakP(this.state32, this.rounds); if (!isLE) byteSwap32(this.state32); this.posOut = 0; this.pos = 0; } update(data) { aexists(this); const { blockLen, state } = this; data = toBytes2(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; 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; 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; } }; gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen)); sha3_224 = /* @__PURE__ */ gen(6, 144, 224 / 8); sha3_256 = /* @__PURE__ */ gen(6, 136, 256 / 8); sha3_384 = /* @__PURE__ */ gen(6, 104, 384 / 8); sha3_512 = /* @__PURE__ */ gen(6, 72, 512 / 8); keccak_224 = /* @__PURE__ */ gen(1, 144, 224 / 8); keccak_256 = /* @__PURE__ */ gen(1, 136, 256 / 8); keccak_384 = /* @__PURE__ */ gen(1, 104, 384 / 8); keccak_512 = /* @__PURE__ */ gen(1, 72, 512 / 8); genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === void 0 ? outputLen : opts.dkLen, true)); shake128 = /* @__PURE__ */ genShake(31, 168, 128 / 8); shake256 = /* @__PURE__ */ genShake(31, 136, 256 / 8); } }); // node_modules/viem/_esm/utils/hash/keccak256.js function keccak256(value, to_) { const to = to_ || "hex"; const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value); if (to === "bytes") return bytes; return toHex(bytes); } var init_keccak256 = __esm({ "node_modules/viem/_esm/utils/hash/keccak256.js"() { init_sha3(); init_isHex(); init_toBytes(); init_toHex(); } }); // node_modules/viem/_esm/utils/lru.js var LruMap; var init_lru = __esm({ "node_modules/viem/_esm/utils/lru.js"() { LruMap = class 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; } }; } }); // 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 hash = keccak256(stringToBytes(hexAddress), "bytes"); const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split(""); for (let i = 0; i < 40; i += 2) { if (hash[i >> 1] >> 4 >= 8 && address[i]) { address[i] = address[i].toUpperCase(); } if ((hash[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; } var checksumAddressCache; var init_getAddress = __esm({ "node_modules/viem/_esm/utils/address/getAddress.js"() { init_toBytes(); init_keccak256(); init_lru(); 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({ "node_modules/viem/_esm/utils/address/isAddress.js"() { init_lru(); init_getAddress(); addressRegex = /^0x[a-fA-F0-9]{40}$/; isAddressCache = /* @__PURE__ */ new LruMap(8192); } }); // src/sdk/dto/get-quotes.dto.ts var get_quotes_dto_exports = {}; __export(get_quotes_dto_exports, { GetQuotesDto: () => GetQuotesDto }); module.exports = __toCommonJS(get_quotes_dto_exports); // src/sdk/dto/validators/is-address.validator.ts var import_class_validator = require("class-validator"); // node_modules/viem/_esm/utils/data/isBytes.js function isBytes2(value) { if (!value) return false; if (typeof value !== "object") return false; if (!("BYTES_PER_ELEMENT" in value)) return false; return value.BYTES_PER_ELEMENT === 1 && value.constructor.name === "Uint8Array"; } // node_modules/viem/_esm/index.js init_isAddress(); init_isHex(); // src/sdk/dto/validators/is-address.validator.ts function IsAddress(options = {}) { return (object, propertyName) => { (0, import_class_validator.registerDecorator)({ propertyName, options: { message: `${propertyName} must be an address`, ...options }, name: "isAddress", target: object.constructor, constraints: [], validator: { validate(value) { return isAddress(value); } } }); }; } // src/sdk/common/rxjs/distinct-unique-key.operator.ts var import_operators = require("rxjs/operators"); // src/sdk/common/types/bignumber.ts var import_bn = __toESM(require("bn.js")); // src/sdk/common/types/bignumber-logger.ts var _permanentCensorErrors = false; var _censorErrors = false; var LogLevels = { debug: 1, "default": 2, info: 2, warning: 3, error: 4, off: 5 }; var _logLevel = LogLevels["default"]; var version2 = "logger/5.7.0"; var _globalLogger = null; function _checkNormalize() { try { const missing = []; ["NFD", "NFC", "NFKD", "NFKC"].forEach((form) => { try { if ("test".normalize(form) !== "test") { throw new Error("bad normalize"); } ; } catch (error) { missing.push(form); } }); if (missing.length) { throw new Error("missing " + missing.join(", ")); } if (String.fromCharCode(233).normalize("NFD") !== String.fromCharCode(101, 769)) { throw new Error("broken implementation"); } } catch (error) { return error.message; } return null; } var _normalizeError = _checkNormalize(); var LogLevel = /* @__PURE__ */ ((LogLevel2) => { LogLevel2["DEBUG"] = "DEBUG"; LogLevel2["INFO"] = "INFO"; LogLevel2["WARNING"] = "WARNING"; LogLevel2["ERROR"] = "ERROR"; LogLevel2["OFF"] = "OFF"; return LogLevel2; })(LogLevel || {}); var ErrorCode = /* @__PURE__ */ ((ErrorCode2) => { ErrorCode2["UNKNOWN_ERROR"] = "UNKNOWN_ERROR"; ErrorCode2["NOT_IMPLEMENTED"] = "NOT_IMPLEMENTED"; ErrorCode2["UNSUPPORTED_OPERATION"] = "UNSUPPORTED_OPERATION"; ErrorCode2["NETWORK_ERROR"] = "NETWORK_ERROR"; ErrorCode2["SERVER_ERROR"] = "SERVER_ERROR"; ErrorCode2["TIMEOUT"] = "TIMEOUT"; ErrorCode2["BUFFER_OVERRUN"] = "BUFFER_OVERRUN"; ErrorCode2["NUMERIC_FAULT"] = "NUMERIC_FAULT"; ErrorCode2["MISSING_NEW"] = "MISSING_NEW"; ErrorCode2["INVALID_ARGUMENT"] = "INVALID_ARGUMENT"; ErrorCode2["MISSING_ARGUMENT"] = "MISSING_ARGUMENT"; ErrorCode2["UNEXPECTED_ARGUMENT"] = "UNEXPECTED_ARGUMENT"; ErrorCode2["CALL_EXCEPTION"] = "CALL_EXCEPTION"; ErrorCode2["INSUFFICIENT_FUNDS"] = "INSUFFICIENT_FUNDS"; ErrorCode2["NONCE_EXPIRED"] = "NONCE_EXPIRED"; ErrorCode2["REPLACEMENT_UNDERPRICED"] = "REPLACEMENT_UNDERPRICED"; ErrorCode2["UNPREDICTABLE_GAS_LIMIT"] = "UNPREDICTABLE_GAS_LIMIT"; ErrorCode2["TRANSACTION_REPLACED"] = "TRANSACTION_REPLACED"; ErrorCode2["ACTION_REJECTED"] = "ACTION_REJECTED"; return ErrorCode2; })(ErrorCode || {}); var HEX = "0123456789abcdef"; var Logger = class _Logger { static { this.errors = ErrorCode; } static { this.levels = LogLevel; } constructor(version4) { Object.defineProperty(this, "version", { enumerable: true, value: version4, writable: false }); } _log(logLevel, args) { const level = logLevel.toLowerCase(); if (LogLevels[level] == null) { this.throwArgumentError("invalid log level name", "logLevel", logLevel); } if (_logLevel > LogLevels[level]) { return; } console.log.apply(console, args); } debug(...args) { this._log(_Logger.levels.DEBUG, args); } info(...args) { this._log(_Logger.levels.INFO, args); } warn(...args) { this._log(_Logger.levels.WARNING, args); } makeError(message, code, params) { if (_censorErrors) { return this.makeError("censored error", code, {}); } if (!code) { code = _Logger.errors.UNKNOWN_ERROR; } if (!params) { params = {}; } const messageDetails = []; Object.keys(params).forEach((key) => { const value = params[key]; try { if (value instanceof Uint8Array) { let hex = ""; for (let i = 0; i < value.length; i++) { hex += HEX[value[i] >> 4]; hex += HEX[value[i] & 15]; } messageDetails.push(key + "=Uint8Array(0x" + hex + ")"); } else { messageDetails.push(key + "=" + JSON.stringify(value)); } } catch (error2) { messageDetails.push(key + "=" + JSON.stringify(params[key].toString())); } }); messageDetails.push(`code=${code}`); messageDetails.push(`version=${this.version}`); const reason = message; let url = ""; switch (code) { case "NUMERIC_FAULT" /* NUMERIC_FAULT */: { url = "NUMERIC_FAULT"; const fault = message; switch (fault) { case "overflow": case "underflow": case "division-by-zero": url += "-" + fault; break; case "negative-power": case "negative-width": url += "-unsupported"; break; case "unbound-bitwise-result": url += "-unbound-result"; break; } break; } case "CALL_EXCEPTION" /* CALL_EXCEPTION */: case "INSUFFICIENT_FUNDS" /* INSUFFICIENT_FUNDS */: case "MISSING_NEW" /* MISSING_NEW */: case "NONCE_EXPIRED" /* NONCE_EXPIRED */: case "REPLACEMENT_UNDERPRICED" /* REPLACEMENT_UNDERPRICED */: case "TRANSACTION_REPLACED" /* TRANSACTION_REPLACED */: case "UNPREDICTABLE_GAS_LIMIT" /* UNPREDICTABLE_GAS_LIMIT */: url = code; break; } if (url) { message += " [ See: https://links.ethers.org/v5-errors-" + url + " ]"; } if (messageDetails.length) { message += " (" + messageDetails.join(", ") + ")"; } const error = new Error(message); error.reason = reason; error.code = code; Object.keys(params).forEach(function(key) { error[key] = params[key]; }); return error; } throwError(message, code, params) { throw this.makeError(message, code, params); } throwArgumentError(message, name, value) { return this.throwError(message, _Logger.errors.INVALID_ARGUMENT, { argument: name, value }); } assert(condition, message, code, params) { if (!!condition) { return; } this.throwError(message, code, params); } assertArgument(condition, message, name, value) { if (!!condition) { return; } this.throwArgumentError(message, name, value); } checkNormalize(message) { if (message == null) { message = "platform missing String.prototype.normalize"; } if (_normalizeError) { this.throwError("platform missing String.prototype.normalize", _Logger.errors.UNSUPPORTED_OPERATION, { operation: "String.prototype.normalize", form: _normalizeError }); } } checkSafeUint53(value, message) { if (typeof value !== "number") { return; } if (message == null) { message = "value not safe"; } if (value < 0 || value >= 9007199254740991) { this.throwError(message, _Logger.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "out-of-safe-range", value }); } if (value % 1) { this.throwError(message, _Logger.errors.NUMERIC_FAULT, { operation: "checkSafeInteger", fault: "non-integer", value }); } } checkArgumentCount(count, expectedCount, message) { if (message) { message = ": " + message; } else { message = ""; } if (count < expectedCount) { this.throwError("missing argument" + message, _Logger.errors.MISSING_ARGUMENT, { count, expectedCount }); } if (count > expectedCount) { this.throwError("too many arguments" + message, _Logger.errors.UNEXPECTED_ARGUMENT, { count, expectedCount }); } } checkNew(target, kind) { if (target === Object || target == null) { this.throwError("missing new", _Logger.errors.MISSING_NEW, { name: kind.name }); } } checkAbstract(target, kind) { if (target === kind) { this.throwError( "cannot instantiate abstract class " + JSON.stringify(kind.name) + " directly; use a sub-class", _Logger.errors.UNSUPPORTED_OPERATION, { name: target.name, operation: "new" } ); } else if (target === Object || target == null) { this.throwError("missing new", _Logger.errors.MISSING_NEW, { name: kind.name }); } } static globalLogger() { if (!_globalLogger) { _globalLogger = new _Logger(version2); } return _globalLogger; } static setCensorship(censorship, permanent) { if (!censorship && permanent) { this.globalLogger().throwError("cannot permanently disable censorship", _Logger.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }); } if (_permanentCensorErrors) { if (!censorship) { return; } this.globalLogger().throwError("error censorship permanent", _Logger.errors.UNSUPPORTED_OPERATION, { operation: "setCensorship" }); } _censorErrors = !!censorship; _permanentCensorErrors = !!permanent; } static setLogLevel(logLevel) { const level = LogLevels[logLevel.toLowerCase()]; if (level == null) { _Logger.globalLogger().warn("invalid log level - " + logLevel); return; } _logLevel = level; } static from(version4) { return new _Logger(version4); } }; // src/sdk/common/types/bignumber.ts var BN = import_bn.default.BN; var version3 = "logger/5.7.0"; var logger = new Logger(version3); var _constructorGuard = {}; var MAX_SAFE = 9007199254740991; var _warnedToStringRadix = false; var BigNumber = class _BigNumber { constructor(constructorGuard, hex) { if (constructorGuard !== _constructorGuard) { logger.throwError("cannot call constructor directly; use BigNumber.from", Logger.errors.UNSUPPORTED_OPERATION, { operation: "new (BigNumber)" }); } this._hex = hex; this._isBigNumber = true; Object.freeze(this); } fromTwos(value) { return toBigNumber(toBN(this).fromTwos(value)); } toTwos(value) { return toBigNumber(toBN(this).toTwos(value)); } abs() { if (this._hex[0] === "-") { return _BigNumber.from(this._hex.substring(1)); } return this; } add(other) { return toBigNumber(toBN(this).add(toBN(other))); } sub(other) { return toBigNumber(toBN(this).sub(toBN(other))); } div(other) { const o = _BigNumber.from(other); if (o.isZero()) { throwFault("division-by-zero", "div"); } return toBigNumber(toBN(this).div(toBN(other))); } mul(other) { return toBigNumber(toBN(this).mul(toBN(other))); } mod(other) { const value = toBN(other); if (value.isNeg()) { throwFault("division-by-zero", "mod"); } return toBigNumber(toBN(this).umod(value)); } pow(other) { const value = toBN(other); if (value.isNeg()) { throwFault("negative-power", "pow"); } return toBigNumber(toBN(this).pow(value)); } and(other) { const value = toBN(other); if (this.isNegative() || value.isNeg()) { throwFault("unbound-bitwise-result", "and"); } return toBigNumber(toBN(this).and(value)); } or(other) { const value = toBN(other); if (this.isNegative() || value.isNeg()) { throwFault("unbound-bitwise-result", "or"); } return toBigNumber(toBN(this).or(value)); } xor(other) { const value = toBN(other); if (this.isNegative() || value.isNeg()) { throwFault("unbound-bitwise-result", "xor"); } return toBigNumber(toBN(this).xor(value)); } mask(value) { if (this.isNegative() || value < 0) { throwFault("negative-width", "mask"); } return toBigNumber(toBN(this).maskn(value)); } shl(value) { if (this.isNegative() || value < 0) { throwFault("negative-width", "shl"); } return toBigNumber(toBN(this).shln(value)); } shr(value) { if (this.isNegative() || value < 0) { throwFault("negative-width", "shr"); } return toBigNumber(toBN(this).shrn(value)); } eq(other) { return toBN(this).eq(toBN(other)); } lt(other) { return toBN(this).lt(toBN(other)); } lte(other) { return toBN(this).lte(toBN(other)); } gt(other) { return toBN(this).gt(toBN(other)); } gte(other) { return toBN(this).gte(toBN(other)); } isNegative() { return this._hex[0] === "-"; } isZero() { return toBN(this).isZero(); } toNumber() { try { return toBN(this).toNumber(); } catch (error) { throwFault("overflow", "toNumber", this.toString()); } return null; } toBigInt() { try { return BigInt(this.toString()); } catch (e) { } return logger.throwError("this platform does not support BigInt", Logger.errors.UNSUPPORTED_OPERATION, { value: this.toString() }); } toString() { if (arguments.length > 0) { if (arguments[0] === 10) { if (!_warnedToStringRadix) { _warnedToStringRadix = true; logger.warn("BigNumber.toString does not accept any parameters; base-10 is assumed"); } } else if (arguments[0] === 16) { logger.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", Logger.errors.UNEXPECTED_ARGUMENT, {}); } else { logger.throwError("BigNumber.toString does not accept parameters", Logger.errors.UNEXPECTED_ARGUMENT, {}); } } return toBN(this).toString(10); } toHexString() { return this._hex; } toJSON(key) { return { type: "BigNumber", hex: this.toHexString() }; } static from(value) { if (value instanceof _BigNumber) { return value; } if (typeof value === "string") { if (value.match(/^-?0x[0-9a-f]+$/i)) { return new _BigNumber(_constructorGuard, toHex2(value)); } if (value.match(/^-?[0-9]+$/)) { return new _BigNumber(_constructorGuard, toHex2(new BN(value))); } return logger.throwArgumentError("invalid BigNumber string", "value", value); } if (typeof value === "number") { if (value % 1) { throwFault("underflow", "BigNumber.from", value); } if (value >= MAX_SAFE || value <= -MAX_SAFE) { throwFault("overflow", "BigNumber.from", value); } return _BigNumber.from(String(value)); } const anyValue = value; if (typeof anyValue === "bigint") { return _BigNumber.from(anyValue.toString()); } if (isBytes2(anyValue)) { return _BigNumber.from(hexlifyValue(anyValue)); } if (anyValue) { if (anyValue.toHexString) { const hex = anyValue.toHexString(); if (typeof hex === "string") { return _BigNumber.from(hex); } } else { let hex = anyValue._hex; if (hex == null && anyValue.type === "BigNumber") { hex = anyValue.hex; } if (typeof hex === "string") { if (isHex(hex) || hex[0] === "-" && isHex(hex.substring(1))) { return _BigNumber.from(hex); } } } } return logger.throwArgumentError("invalid BigNumber value", "value", value); } static isBigNumber(value) { return !!(value && value._isBigNumber); } }; function toHex2(value) { if (typeof value !== "string") { return toHex2(value.toString(16)); } if (value[0] === "-") { value = value.substring(1); if (value[0] === "-") { throw new Error(`invalid hex value: ${value}`); } value = toHex2(value); if (value === "0x00") { return value; } return "-" + value; } if (value.substring(0, 2) !== "0x") { value = "0x" + value; } if (value === "0x") { return "0x00"; } if (value.length % 2) { value = "0x0" + value.substring(2); } while (value.length > 4 && value.substring(0, 4) === "0x00") { value = "0x" + value.substring(4); } return value; } function toBigNumber(value) { return BigNumber.from(toHex2(value)); } function toBN(value) { const hex = BigNumber.from(value).toHexString(); if (hex[0] === "-") { return new BN("-" + hex.substring(3), 16); } return new BN(hex.substring(2), 16); } function throwFault(fault, operation, value) { const params = { fault, operation }; if (value != null) { params.value = value; } return logger.throwError(fault, Logger.errors.NUMERIC_FAULT, params); } // src/sdk/common/utils/hexlify.ts function isHexableValue(value) { return !!value.toHexString; } function isInteger(value) { return typeof value === "number" && value == value && value % 1 === 0; } function isBytes3(value) { if (value == null) { return false; } if (value.constructor === Uint8Array) { return true; } if (typeof value === "string") { return false; } if (!isInteger(value.length) || value.length < 0) { return false; } for (let i = 0; i < value.length; i++) { const v = value[i]; if (!isInteger(v) || v < 0 || v >= 256) { return false; } } return true; } function isHexString(value, length) { if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { return false; } if (length && value.length !== 2 + 2 * length) { return false; } return true; } function checkSafeUint53(value, message) { if (typeof value !== "number") { return; } if (message == null) { message = "value not safe"; } if (value < 0 || value >= 9007199254740991) { throw new Error(`Invalid Hexlify value - CheckSafeInteger Failed due to out-of-safe-range value: ${value}`); } if (value % 1) { throw new Error(`Invalid Hexlify value - CCheckSafeInteger Failed due to non-integer value: ${value}`); } } var HexCharacters = "0123456789abcdef"; function hexlifyValue(value, options) { if (!options) { options = {}; } if (typeof value === "number") { checkSafeUint53(value); let hex = ""; while (value) { hex = HexCharacters[value & 15] + hex; value = Math.floor(value / 16); } if (hex.length) { if (hex.length % 2) { hex = "0" + hex; } return "0x" + hex; } return "0x00"; } if (typeof value === "bigint") { value = value.toString(16); if (value.length % 2) { return "0x0" + value; } return "0x" + value; } if (options.allowMissingPrefix && typeof value === "string" && value.substring(0, 2) !== "0x") { value = "0x" + value; } if (isHexableValue(value)) { return value.toHexString(); } if (isHexString(value)) { if (value.length % 2) { if (options.hexPad === "left") { value = "0x0" + value.substring(2); } else if (options.hexPad === "right") { value += "0"; } else { throw new Error(`invalid hexlify value - hex data is odd-length for value: ${value}`); } } return value.toLowerCase(); } if (isBytes3(value)) { let result = "0x"; for (let i = 0; i < value.length; i++) { const v = value[i]; result += HexCharacters[(v & 240) >> 4] + HexCharacters[v & 15]; } return result; } throw new Error(`invalid hexlify value - ${value}`); } // src/sdk/common/rxjs/object.subject.ts var import_rxjs = require("rxjs"); // src/sdk/common/transformers/transform-big-number.ts var import_class_transformer = require("class-transformer"); // src/sdk/dto/validators/is-big-numberish.validator.ts var import_class_validator2 = require("class-validator"); function IsBigNumberish(options = {}, validationOptions = {}) { return (object, propertyName) => { const { positive } = options; (0, import_class_validator2.registerDecorator)({ propertyName, options: { message: `${propertyName} must be ${positive ? "positive " : ""}big numberish`, ...validationOptions }, name: "IsBigNumberish", target: object.constructor, constraints: [], validator: { validate(value) { let result = false; try { const bn = BigNumber.from(value); result = positive ? bn.gt(0) : bn.gte(0); } catch (err) { } return result; } } }); }; } // src/sdk/dto/validators/is-bytes-like.validator.ts var import_class_validator3 = require("class-validator"); // src/sdk/dto/validators/is-hex.validator.ts var import_class_validator4 = require("class-validator"); // src/sdk/dto/validators/is-url.validator.ts var import_class_validator5 = require("class-validator"); // src/sdk/dto/get-quotes.dto.ts var import_class_validator6 = require("class-validator"); var GetQuotesDto = class { }; __decorateClass([ IsAddress() ], GetQuotesDto.prototype, "fromAddress", 2); __decorateClass([ IsAddress() ], GetQuotesDto.prototype, "toAddress", 2); __decorateClass([ IsAddress() ], GetQuotesDto.prototype, "fromToken", 2); __decorateClass([ IsBigNumberish({ positive: true }) ], GetQuotesDto.prototype, "fromAmount", 2); __decorateClass([ (0, import_class_validator6.IsOptional)() ], GetQuotesDto.prototype, "provider", 2); /*! Bundled license information: @noble/hashes/esm/utils.js: (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *) */ //# sourceMappingURL=get-quotes.dto.js.map