From 6bb372677ac5fb95fa85235584607d9e924f6022 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 10:24:50 +0100 Subject: [PATCH 01/29] add support for smart contracts --- deps.ts | 2 +- lib/miner-info.js | 26 + test.js | 8 +- test/spark.js | 107 +- vendor/deno-deps.js | 38609 ++++++++++++++++++++++++++++++++++-------- 5 files changed, 32006 insertions(+), 6746 deletions(-) diff --git a/deps.ts b/deps.ts index f40c4c7..4e8298b 100644 --- a/deps.ts +++ b/deps.ts @@ -9,7 +9,7 @@ export { decodeBase64 } from 'https://deno.land/std@0.203.0/encoding/base64.ts' export { decode as decodeVarint } from 'https://deno.land/x/varint@v2.0.0/varint.ts' export { retry } from 'https://deno.land/std@0.203.0/async/retry.ts'; - +export { ethers } from "https://cdn.skypack.dev/ethers@5.7.2?dts"; // Deno Bundle does not support npm dependencies, we have to load them via CDN export { CarBlockIterator } from 'https://cdn.skypack.dev/@ipld/car@5.3.2/?dts' export { diff --git a/lib/miner-info.js b/lib/miner-info.js index c9cd093..cbfb4f6 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -1,5 +1,6 @@ import { retry } from '../vendor/deno-deps.js' import { RPC_URL, RPC_AUTH } from './constants.js' +import { getMinerPeerIdFromSmartContract } from './smart-contract-client.js' async function getChainHead ({ maxAttempts = 5 } = {}) { try { @@ -29,6 +30,31 @@ async function getChainHead ({ maxAttempts = 5 } = {}) { * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { + // Make a concurrent request to both sources: Lotus API and smart contract + const [onChainPeerId, smartContractPeerId] = await Promise.all([ + getMinerPeerIdFromRpcNode(minerId, { maxAttempts }), + getMinerPeerIdFromSmartContract(minerId) + ]); + // Return the peer ID from the smart contract if it exists and is not empty + if (smartContractPeerId && smartContractPeerId !== "") { + return smartContractPeerId; + } + + // Return the peer ID from the Lotus API if it exists and is not empty + if (onChainPeerId) { + return onChainPeerId; + } + + return null +} + +/** + * @param {string} minerId A miner actor id, e.g. `f0142637` + * @param {object} options + * @param {number} [options.maxAttempts] + * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` + */ +export async function getMinerPeerIdFromRpcNode(minerId,{ maxAttempts = 5 }){ const chainHead = await getChainHead({ maxAttempts }) try { const res = await retry(() => rpc('Filecoin.StateMinerInfo', minerId, chainHead), { diff --git a/test.js b/test.js index 6803285..0e322a3 100644 --- a/test.js +++ b/test.js @@ -1,7 +1 @@ -import './test/http-assertions.test.js' -import './test/ipni-client.test.js' -import './test/miner-info.test.js' -import './test/multiaddr.test.js' - -import './test/integration.js' -import './test/spark.js' +import './test/spark.js' \ No newline at end of file diff --git a/test/spark.js b/test/spark.js index a240e89..51ca1d5 100644 --- a/test/spark.js +++ b/test/spark.js @@ -2,8 +2,11 @@ import Spark, { calculateDelayBeforeNextTask, newStats } from '../lib/spark.js' import { test } from 'zinnia:test' -import { assertInstanceOf, assertEquals, assertArrayIncludes } from 'zinnia:assert' +import { assertInstanceOf, assertEquals, assertArrayIncludes, assertRejects, assert } from 'zinnia:assert' import { SPARK_VERSION } from '../lib/constants.js' +import { getMinerPeerIdFromSmartContract } from "../lib/smart-contract-client.js" +import { RPC_URL } from '../lib/constants.js' +import { getMinerPeerId } from "../lib/miner-info.js" const KNOWN_CID = 'bafkreih25dih6ug3xtj73vswccw423b56ilrwmnos4cbwhrceudopdp5sq' @@ -363,3 +366,105 @@ test('calculateDelayBeforeNextTask() handles one task per round', () => { }) assertEquals(delay, 60_000) }) + +const mockPeerIdResponse = { + peerID: "12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U", + signature: "0x1234567890abcdef" +}; + +const mockEmptyPeerIdResponse = { + peerID: "", + signature: "0x" +}; + +// Mock contract factory +function createMockContract(mockResponses) { + return { + getPeerData: async (minerId) => { + const response = mockResponses[minerId]; + if (!response) { + throw new Error(`Miner ID ${minerId} not found in contract`); + } + return response; + } + }; +} + + +test('smart-contract-client: getMinerPeerIdFromSmartContract returns peer ID for valid miner ID', async () => { + // Create mock contract with predefined responses + const peerId = 12345 + const mockContract = createMockContract({ + [peerId]: mockPeerIdResponse, + }); + + const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { + getSmartContractClientFn: () => mockContract + }); + + assertEquals(actualPeerId, mockPeerIdResponse.peerID); +}); + +test('miner-info: getMinerPeerId integration test with real miner f01234', async () => { + const peerId = await getMinerPeerIdFromSmartContract("f012345",RPC_URL ) + assertEquals(typeof peerId, 'string', "Expected peerId to be a string"); + assert(peerId.length > 0, "Expected peerId to be non-empty"); + assertEquals(peerId, "12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U"); +}); + +test('smart-contract-client: getMinerPeerIdFromSmartContract returns empty string for miner ID with no peer ID', async () => { + // Create mock contract with predefined responses + const peerId = 99999 + const mockContract = createMockContract({ + [peerId]: mockEmptyPeerIdResponse, + }); + + const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { + getSmartContractClientFn: () => mockContract + }); + + assertEquals(actualPeerId, ""); +}); + +test('smart-contract-client: getMinerPeerIdFromSmartContract throws error for non-existent miner ID', async () => { + // Create mock contract with predefined responses (empty to cause error) + const mockContract = createMockContract({}); + + await assertRejects( + async () => { + await getMinerPeerIdFromSmartContract("f055555", { + getSmartContractClientFn: () => mockContract + }); + }, + Error, + "Error fetching peer ID from contract for miner f055555" + ); +}); + +test('smart-contract-client: getMinerPeerIdFromSmartContract properly strips f0 prefix', async () => { + // Create a mock that validates the minerId was correctly converted + let receivedMinerId = null; + + const mockContract = { + getPeerData: async (minerId) => { + receivedMinerId = minerId; + return mockPeerIdResponse; + } + }; + + await getMinerPeerIdFromSmartContract("f0123456", { + getSmartContractClientFn: () => mockContract + }); + + assertEquals(receivedMinerId, 123456); +}); + +test('miner-info: getMinerPeerId integration test with real miner f03303347', async () => { + const peerId = await getMinerPeerId("f03303347"); + + // We don't know what the actual value is, but we can verify it's a non-empty string + // that looks like a valid peer ID + assert(typeof peerId === 'string', "Expected peerId to be a string"); + assert(peerId.length > 0, "Expected peerId to be non-empty"); + assertEquals(peerId, "12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U"); +}); \ No newline at end of file diff --git a/vendor/deno-deps.js b/vendor/deno-deps.js index 2470189..67c55b1 100644 --- a/vendor/deno-deps.js +++ b/vendor/deno-deps.js @@ -113,5592 +113,27575 @@ function _exponentialBackoffWithJitter(cap, base, attempt, multiplier, jitter) { const exp = Math.min(cap, base * multiplier ** attempt); return (1 - jitter * Math.random()) * exp; } -const typeofs = [ - "string", - "number", - "bigint", - "symbol" -]; -const objectTypeNames = [ - "Function", - "Generator", - "AsyncGenerator", - "GeneratorFunction", - "AsyncGeneratorFunction", - "AsyncFunction", - "Observable", - "Array", - "Buffer", - "Object", - "RegExp", - "Date", - "Error", - "Map", - "Set", - "WeakMap", - "WeakSet", - "ArrayBuffer", - "SharedArrayBuffer", - "DataView", - "Promise", - "URL", - "HTMLElement", - "Int8Array", - "Uint8Array", - "Uint8ClampedArray", - "Int16Array", - "Uint16Array", - "Int32Array", - "Uint32Array", - "Float32Array", - "Float64Array", - "BigInt64Array", - "BigUint64Array" -]; -function is(value) { - if (value === null) { - return "null"; - } - if (value === void 0) { - return "undefined"; - } - if (value === true || value === false) { - return "boolean"; - } - const typeOf = typeof value; - if (typeofs.includes(typeOf)) { - return typeOf; - } - if (typeOf === "function") { - return "Function"; - } - if (Array.isArray(value)) { - return "Array"; - } - if (isBuffer(value)) { - return "Buffer"; - } - const objectType = getObjectType(value); - if (objectType) { - return objectType; - } - return "Object"; -} -function isBuffer(value) { - return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value); -} -function getObjectType(value) { - const objectTypeName = Object.prototype.toString.call(value).slice(8, -1); - if (objectTypeNames.includes(objectTypeName)) { - return objectTypeName; - } - return void 0; -} -class Type { - constructor(major, name, terminal){ - this.major = major; - this.majorEncoded = major << 5; - this.name = name; - this.terminal = terminal; - } - toString() { - return `Type[${this.major}].${this.name}`; - } - compare(typ) { - return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0; - } -} -Type.uint = new Type(0, "uint", true); -Type.negint = new Type(1, "negint", true); -Type.bytes = new Type(2, "bytes", true); -Type.string = new Type(3, "string", true); -Type.array = new Type(4, "array", false); -Type.map = new Type(5, "map", false); -Type.tag = new Type(6, "tag", false); -Type.float = new Type(7, "float", true); -Type.false = new Type(7, "false", true); -Type.true = new Type(7, "true", true); -Type.null = new Type(7, "null", true); -Type.undefined = new Type(7, "undefined", true); -Type.break = new Type(7, "break", true); -class Token { - constructor(type, value, encodedLength){ - this.type = type; - this.value = value; - this.encodedLength = encodedLength; - this.encodedBytes = void 0; - this.byteValue = void 0; - } - toString() { - return `Token[${this.type}].${this.value}`; - } +var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; +function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function(path, base) { + return commonjsRequire(path, base === void 0 || base === null ? module.path : base); + } + }, fn(module, module.exports), module.exports; } -const useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === "function"; -const textDecoder1 = new TextDecoder(); -const textEncoder = new TextEncoder(); -function isBuffer$1(buf2) { - return useBuffer && globalThis.Buffer.isBuffer(buf2); +function getDefaultExportFromNamespaceIfNotNamed(n) { + return n && Object.prototype.hasOwnProperty.call(n, "default") && Object.keys(n).length === 1 ? n["default"] : n; } -function asU8A(buf2) { - if (!(buf2 instanceof Uint8Array)) { - return Uint8Array.from(buf2); - } - return isBuffer$1(buf2) ? new Uint8Array(buf2.buffer, buf2.byteOffset, buf2.byteLength) : buf2; +function commonjsRequire() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); } -const toString = useBuffer ? (bytes, start, end)=>{ - return end - start > 64 ? globalThis.Buffer.from(bytes.subarray(start, end)).toString("utf8") : utf8Slice(bytes, start, end); -} : (bytes, start, end)=>{ - return end - start > 64 ? textDecoder1.decode(bytes.subarray(start, end)) : utf8Slice(bytes, start, end); -}; -const fromString = useBuffer ? (string)=>{ - return string.length > 64 ? globalThis.Buffer.from(string) : utf8ToBytes(string); -} : (string)=>{ - return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string); -}; -const fromArray = (arr)=>{ - return Uint8Array.from(arr); -}; -const slice = useBuffer ? (bytes, start, end)=>{ - if (isBuffer$1(bytes)) { - return new Uint8Array(bytes.subarray(start, end)); - } - return bytes.slice(start, end); -} : (bytes, start, end)=>{ - return bytes.slice(start, end); -}; -const concat = useBuffer ? (chunks, length)=>{ - chunks = chunks.map((c)=>c instanceof Uint8Array ? c : globalThis.Buffer.from(c)); - return asU8A(globalThis.Buffer.concat(chunks, length)); -} : (chunks, length)=>{ - const out = new Uint8Array(length); - let off = 0; - for (let b of chunks){ - if (off + b.length > out.length) { - b = b.subarray(0, out.length - off); - } - out.set(b, off); - off += b.length; - } - return out; -}; -const alloc = useBuffer ? (size)=>{ - return globalThis.Buffer.allocUnsafe(size); -} : (size)=>{ - return new Uint8Array(size); -}; -function compare(b1, b2) { - if (isBuffer$1(b1) && isBuffer$1(b2)) { - return b1.compare(b2); - } - for(let i = 0; i < b1.length; i++){ - if (b1[i] === b2[i]) { - continue; +var _nodeResolve_empty = {}; +var _nodeResolve_empty$1 = Object.freeze({ + __proto__: null, + default: _nodeResolve_empty +}); +var require$$0 = getDefaultExportFromNamespaceIfNotNamed(_nodeResolve_empty$1); +var bn = createCommonjsModule(function(module) { + (function(module2, exports) { + function assert(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); + } + function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + function BN2(number, base, endian) { + if (BN2.isBN(number)) { + return number; + } + this.negative = 0; + this.words = null; + this.length = 0; + this.red = null; + if (number !== null) { + if (base === "le" || base === "be") { + endian = base; + base = 10; + } + this._init(number || 0, base || 10, endian || "be"); + } } - return b1[i] < b2[i] ? -1 : 1; - } - return 0; -} -function utf8ToBytes(str) { - const out = []; - let p = 0; - for(let i = 0; i < str.length; i++){ - let c = str.charCodeAt(i); - if (c < 128) { - out[p++] = c; - } else if (c < 2048) { - out[p++] = c >> 6 | 192; - out[p++] = c & 63 | 128; - } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) { - c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023); - out[p++] = c >> 18 | 240; - out[p++] = c >> 12 & 63 | 128; - out[p++] = c >> 6 & 63 | 128; - out[p++] = c & 63 | 128; + if (typeof module2 === "object") { + module2.exports = BN2; } else { - out[p++] = c >> 12 | 224; - out[p++] = c >> 6 & 63 | 128; - out[p++] = c & 63 | 128; + exports.BN = BN2; } - } - return out; -} -function utf8Slice(buf2, offset, end) { - const res = []; - while(offset < end){ - const firstByte = buf2[offset]; - let codePoint = null; - let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (offset + bytesPerSequence <= end) { - let secondByte, thirdByte, fourthByte, tempCodePoint; - switch(bytesPerSequence){ - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf2[offset + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } + BN2.BN = BN2; + BN2.wordSize = 26; + var Buffer; + try { + if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { + Buffer = window.Buffer; + } else { + Buffer = require$$0.Buffer; + } + } catch (e) {} + BN2.isBN = function isBN(num) { + if (num instanceof BN2) { + return true; + } + return num !== null && typeof num === "object" && num.constructor.wordSize === BN2.wordSize && Array.isArray(num.words); + }; + BN2.max = function max(left, right) { + if (left.cmp(right) > 0) return left; + return right; + }; + BN2.min = function min(left, right) { + if (left.cmp(right) < 0) return left; + return right; + }; + BN2.prototype._init = function init(number, base, endian) { + if (typeof number === "number") { + return this._initNumber(number, base, endian); + } + if (typeof number === "object") { + return this._initArray(number, base, endian); + } + if (base === "hex") { + base = 16; + } + assert(base === (base | 0) && base >= 2 && base <= 36); + number = number.toString().replace(/\s+/g, ""); + var start = 0; + if (number[0] === "-") { + start++; + this.negative = 1; + } + if (start < number.length) { + if (base === 16) { + this._parseHex(number, start, endian); + } else { + this._parseBase(number, base, start); + if (endian === "le") { + this._initArray(this.toArray(), base, endian); } - break; - case 3: - secondByte = buf2[offset + 1]; - thirdByte = buf2[offset + 2]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; - if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { - codePoint = tempCodePoint; - } + } + } + }; + BN2.prototype._initNumber = function _initNumber(number, base, endian) { + if (number < 0) { + this.negative = 1; + number = -number; + } + if (number < 67108864) { + this.words = [ + number & 67108863 + ]; + this.length = 1; + } else if (number < 4503599627370496) { + this.words = [ + number & 67108863, + number / 67108864 & 67108863 + ]; + this.length = 2; + } else { + assert(number < 9007199254740992); + this.words = [ + number & 67108863, + number / 67108864 & 67108863, + 1 + ]; + this.length = 3; + } + if (endian !== "le") return; + this._initArray(this.toArray(), base, endian); + }; + BN2.prototype._initArray = function _initArray(number, base, endian) { + assert(typeof number.length === "number"); + if (number.length <= 0) { + this.words = [ + 0 + ]; + this.length = 1; + return this; + } + this.length = Math.ceil(number.length / 3); + this.words = new Array(this.length); + for(var i = 0; i < this.length; i++){ + this.words[i] = 0; + } + var j, w; + var off = 0; + if (endian === "be") { + for(i = number.length - 1, j = 0; i >= 0; i -= 3){ + w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; } - break; - case 4: - secondByte = buf2[offset + 1]; - thirdByte = buf2[offset + 2]; - fourthByte = buf2[offset + 3]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; - if (tempCodePoint > 65535 && tempCodePoint < 1114112) { - codePoint = tempCodePoint; - } + } + } else if (endian === "le") { + for(i = 0, j = 0; i < number.length; i += 3){ + w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; + this.words[j] |= w << off & 67108863; + this.words[j + 1] = w >>> 26 - off & 67108863; + off += 24; + if (off >= 26) { + off -= 26; + j++; } + } + } + return this._strip(); + }; + function parseHex4Bits(string, index) { + var c = string.charCodeAt(index); + if (c >= 48 && c <= 57) { + return c - 48; + } else if (c >= 65 && c <= 70) { + return c - 55; + } else if (c >= 97 && c <= 102) { + return c - 87; + } else { + assert(false, "Invalid character in " + string); } } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - res.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - res.push(codePoint); - offset += bytesPerSequence; - } - return decodeCodePointsArray(res); -} -const MAX_ARGUMENTS_LENGTH = 4096; -function decodeCodePointsArray(codePoints) { - const len = codePoints.length; - if (len <= 4096) { - return String.fromCharCode.apply(String, codePoints); - } - let res = ""; - let i = 0; - while(i < len){ - res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); - } - return res; -} -class Bl { - constructor(chunkSize = 256){ - this.chunkSize = chunkSize; - this.cursor = 0; - this.maxCursor = -1; - this.chunks = []; - this._initReuseChunk = null; - } - reset() { - this.cursor = 0; - this.maxCursor = -1; - if (this.chunks.length) { - this.chunks = []; + function parseHexByte(string, lowerBound, index) { + var r = parseHex4Bits(string, index); + if (index - 1 >= lowerBound) { + r |= parseHex4Bits(string, index - 1) << 4; + } + return r; } - if (this._initReuseChunk !== null) { - this.chunks.push(this._initReuseChunk); - this.maxCursor = this._initReuseChunk.length - 1; + BN2.prototype._parseHex = function _parseHex(number, start, endian) { + this.length = Math.ceil((number.length - start) / 6); + this.words = new Array(this.length); + for(var i = 0; i < this.length; i++){ + this.words[i] = 0; + } + var off = 0; + var j = 0; + var w; + if (endian === "be") { + for(i = number.length - 1; i >= start; i -= 2){ + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } else { + var parseLength = number.length - start; + for(i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2){ + w = parseHexByte(number, start, i) << off; + this.words[j] |= w & 67108863; + if (off >= 18) { + off -= 18; + j += 1; + this.words[j] |= w >>> 26; + } else { + off += 8; + } + } + } + this._strip(); + }; + function parseBase(str, start, end, mul) { + var r = 0; + var b = 0; + var len = Math.min(str.length, end); + for(var i = start; i < len; i++){ + var c = str.charCodeAt(i) - 48; + r *= mul; + if (c >= 49) { + b = c - 49 + 10; + } else if (c >= 17) { + b = c - 17 + 10; + } else { + b = c; + } + assert(c >= 0 && b < mul, "Invalid character"); + r += b; + } + return r; } - } - push(bytes) { - let topChunk = this.chunks[this.chunks.length - 1]; - const newMax = this.cursor + bytes.length; - if (newMax <= this.maxCursor + 1) { - const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1; - topChunk.set(bytes, chunkPos); + BN2.prototype._parseBase = function _parseBase(number, base, start) { + this.words = [ + 0 + ]; + this.length = 1; + for(var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base){ + limbLen++; + } + limbLen--; + limbPow = limbPow / base | 0; + var total = number.length - start; + var mod = total % limbLen; + var end = Math.min(total, total - mod) + start; + var word = 0; + for(var i = start; i < end; i += limbLen){ + word = parseBase(number, i, i + limbLen, base); + this.imuln(limbPow); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + if (mod !== 0) { + var pow = 1; + word = parseBase(number, i, number.length, base); + for(i = 0; i < mod; i++){ + pow *= base; + } + this.imuln(pow); + if (this.words[0] + word < 67108864) { + this.words[0] += word; + } else { + this._iaddn(word); + } + } + this._strip(); + }; + BN2.prototype.copy = function copy(dest) { + dest.words = new Array(this.length); + for(var i = 0; i < this.length; i++){ + dest.words[i] = this.words[i]; + } + dest.length = this.length; + dest.negative = this.negative; + dest.red = this.red; + }; + function move(dest, src) { + dest.words = src.words; + dest.length = src.length; + dest.negative = src.negative; + dest.red = src.red; + } + BN2.prototype._move = function _move(dest) { + move(dest, this); + }; + BN2.prototype.clone = function clone() { + var r = new BN2(null); + this.copy(r); + return r; + }; + BN2.prototype._expand = function _expand(size) { + while(this.length < size){ + this.words[this.length++] = 0; + } + return this; + }; + BN2.prototype._strip = function strip() { + while(this.length > 1 && this.words[this.length - 1] === 0){ + this.length--; + } + return this._normSign(); + }; + BN2.prototype._normSign = function _normSign() { + if (this.length === 1 && this.words[0] === 0) { + this.negative = 0; + } + return this; + }; + if (typeof Symbol !== "undefined" && typeof Symbol.for === "function") { + try { + BN2.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect; + } catch (e) { + BN2.prototype.inspect = inspect; + } } else { - if (topChunk) { - const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1; - if (chunkPos < topChunk.length) { - this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos); - this.maxCursor = this.cursor - 1; + BN2.prototype.inspect = inspect; + } + function inspect() { + return (this.red ? ""; + } + var zeros = [ + "", + "0", + "00", + "000", + "0000", + "00000", + "000000", + "0000000", + "00000000", + "000000000", + "0000000000", + "00000000000", + "000000000000", + "0000000000000", + "00000000000000", + "000000000000000", + "0000000000000000", + "00000000000000000", + "000000000000000000", + "0000000000000000000", + "00000000000000000000", + "000000000000000000000", + "0000000000000000000000", + "00000000000000000000000", + "000000000000000000000000", + "0000000000000000000000000" + ]; + var groupSizes = [ + 0, + 0, + 25, + 16, + 12, + 11, + 10, + 9, + 8, + 8, + 7, + 7, + 7, + 7, + 6, + 6, + 6, + 6, + 6, + 6, + 6, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5, + 5 + ]; + var groupBases = [ + 0, + 0, + 33554432, + 43046721, + 16777216, + 48828125, + 60466176, + 40353607, + 16777216, + 43046721, + 1e7, + 19487171, + 35831808, + 62748517, + 7529536, + 11390625, + 16777216, + 24137569, + 34012224, + 47045881, + 64e6, + 4084101, + 5153632, + 6436343, + 7962624, + 9765625, + 11881376, + 14348907, + 17210368, + 20511149, + 243e5, + 28629151, + 33554432, + 39135393, + 45435424, + 52521875, + 60466176 + ]; + BN2.prototype.toString = function toString(base, padding) { + base = base || 10; + padding = padding | 0 || 1; + var out; + if (base === 16 || base === "hex") { + out = ""; + var off = 0; + var carry = 0; + for(var i = 0; i < this.length; i++){ + var w = this.words[i]; + var word = ((w << off | carry) & 16777215).toString(16); + carry = w >>> 24 - off & 16777215; + off += 2; + if (off >= 26) { + off -= 26; + i--; + } + if (carry !== 0 || i !== this.length - 1) { + out = zeros[6 - word.length] + word + out; + } else { + out = word + out; + } + } + if (carry !== 0) { + out = carry.toString(16) + out; } + while(out.length % padding !== 0){ + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; } - if (bytes.length < 64 && bytes.length < this.chunkSize) { - topChunk = alloc(this.chunkSize); - this.chunks.push(topChunk); - this.maxCursor += topChunk.length; - if (this._initReuseChunk === null) { - this._initReuseChunk = topChunk; + if (base === (base | 0) && base >= 2 && base <= 36) { + var groupSize = groupSizes[base]; + var groupBase = groupBases[base]; + out = ""; + var c = this.clone(); + c.negative = 0; + while(!c.isZero()){ + var r = c.modrn(groupBase).toString(base); + c = c.idivn(groupBase); + if (!c.isZero()) { + out = zeros[groupSize - r.length] + r + out; + } else { + out = r + out; + } } - topChunk.set(bytes, 0); - } else { - this.chunks.push(bytes); - this.maxCursor += bytes.length; + if (this.isZero()) { + out = "0" + out; + } + while(out.length % padding !== 0){ + out = "0" + out; + } + if (this.negative !== 0) { + out = "-" + out; + } + return out; + } + assert(false, "Base should be between 2 and 36"); + }; + BN2.prototype.toNumber = function toNumber() { + var ret = this.words[0]; + if (this.length === 2) { + ret += this.words[1] * 67108864; + } else if (this.length === 3 && this.words[2] === 1) { + ret += 4503599627370496 + this.words[1] * 67108864; + } else if (this.length > 2) { + assert(false, "Number can only safely store up to 53 bits"); } + return this.negative !== 0 ? -ret : ret; + }; + BN2.prototype.toJSON = function toJSON() { + return this.toString(16, 2); + }; + if (Buffer) { + BN2.prototype.toBuffer = function toBuffer(endian, length) { + return this.toArrayLike(Buffer, endian, length); + }; } - this.cursor += bytes.length; - } - toBytes(reset = false) { - let byts; - if (this.chunks.length === 1) { - const chunk = this.chunks[0]; - if (reset && this.cursor > chunk.length / 2) { - byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor); - this._initReuseChunk = null; - this.chunks = []; - } else { - byts = slice(chunk, 0, this.cursor); + BN2.prototype.toArray = function toArray(endian, length) { + return this.toArrayLike(Array, endian, length); + }; + var allocate = function allocate2(ArrayType, size) { + if (ArrayType.allocUnsafe) { + return ArrayType.allocUnsafe(size); + } + return new ArrayType(size); + }; + BN2.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { + this._strip(); + var byteLength = this.byteLength(); + var reqLength = length || Math.max(1, byteLength); + assert(byteLength <= reqLength, "byte array longer than desired length"); + assert(reqLength > 0, "Requested array length <= 0"); + var res = allocate(ArrayType, reqLength); + var postfix = endian === "le" ? "LE" : "BE"; + this["_toArrayLike" + postfix](res, byteLength); + return res; + }; + BN2.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { + var position = 0; + var carry = 0; + for(var i = 0, shift = 0; i < this.length; i++){ + var word = this.words[i] << shift | carry; + res[position++] = word & 255; + if (position < res.length) { + res[position++] = word >> 8 & 255; + } + if (position < res.length) { + res[position++] = word >> 16 & 255; + } + if (shift === 6) { + if (position < res.length) { + res[position++] = word >> 24 & 255; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } + } + if (position < res.length) { + res[position++] = carry; + while(position < res.length){ + res[position++] = 0; + } + } + }; + BN2.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { + var position = res.length - 1; + var carry = 0; + for(var i = 0, shift = 0; i < this.length; i++){ + var word = this.words[i] << shift | carry; + res[position--] = word & 255; + if (position >= 0) { + res[position--] = word >> 8 & 255; + } + if (position >= 0) { + res[position--] = word >> 16 & 255; + } + if (shift === 6) { + if (position >= 0) { + res[position--] = word >> 24 & 255; + } + carry = 0; + shift = 0; + } else { + carry = word >>> 24; + shift += 2; + } } + if (position >= 0) { + res[position--] = carry; + while(position >= 0){ + res[position--] = 0; + } + } + }; + if (Math.clz32) { + BN2.prototype._countBits = function _countBits(w) { + return 32 - Math.clz32(w); + }; } else { - byts = concat(this.chunks, this.cursor); - } - if (reset) { - this.reset(); + BN2.prototype._countBits = function _countBits(w) { + var t = w; + var r = 0; + if (t >= 4096) { + r += 13; + t >>>= 13; + } + if (t >= 64) { + r += 7; + t >>>= 7; + } + if (t >= 8) { + r += 4; + t >>>= 4; + } + if (t >= 2) { + r += 2; + t >>>= 2; + } + return r + t; + }; } - return byts; - } -} -const decodeErrPrefix = "CBOR decode error:"; -const encodeErrPrefix = "CBOR encode error:"; -const uintMinorPrefixBytes = []; -uintMinorPrefixBytes[23] = 1; -uintMinorPrefixBytes[24] = 2; -uintMinorPrefixBytes[25] = 3; -uintMinorPrefixBytes[26] = 5; -uintMinorPrefixBytes[27] = 9; -function assertEnoughData(data, pos, need) { - if (data.length - pos < need) { - throw new Error(`${decodeErrPrefix} not enough data for type`); - } -} -const uintBoundaries = [ - 24, - 256, - 65536, - 4294967296, - BigInt("18446744073709551616") -]; -function readUint8(data, offset, options) { - assertEnoughData(data, offset, 1); - const value = data[offset]; - if (options.strict === true && value < uintBoundaries[0]) { - throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); - } - return value; -} -function readUint16(data, offset, options) { - assertEnoughData(data, offset, 2); - const value = data[offset] << 8 | data[offset + 1]; - if (options.strict === true && value < uintBoundaries[1]) { - throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); - } - return value; -} -function readUint32(data, offset, options) { - assertEnoughData(data, offset, 4); - const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]; - if (options.strict === true && value < uintBoundaries[2]) { - throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); + BN2.prototype._zeroBits = function _zeroBits(w) { + if (w === 0) return 26; + var t = w; + var r = 0; + if ((t & 8191) === 0) { + r += 13; + t >>>= 13; + } + if ((t & 127) === 0) { + r += 7; + t >>>= 7; + } + if ((t & 15) === 0) { + r += 4; + t >>>= 4; + } + if ((t & 3) === 0) { + r += 2; + t >>>= 2; + } + if ((t & 1) === 0) { + r++; + } + return r; + }; + BN2.prototype.bitLength = function bitLength() { + var w = this.words[this.length - 1]; + var hi = this._countBits(w); + return (this.length - 1) * 26 + hi; + }; + function toBitArray(num) { + var w = new Array(num.bitLength()); + for(var bit = 0; bit < w.length; bit++){ + var off = bit / 26 | 0; + var wbit = bit % 26; + w[bit] = num.words[off] >>> wbit & 1; + } + return w; + } + BN2.prototype.zeroBits = function zeroBits() { + if (this.isZero()) return 0; + var r = 0; + for(var i = 0; i < this.length; i++){ + var b = this._zeroBits(this.words[i]); + r += b; + if (b !== 26) break; + } + return r; + }; + BN2.prototype.byteLength = function byteLength() { + return Math.ceil(this.bitLength() / 8); + }; + BN2.prototype.toTwos = function toTwos(width) { + if (this.negative !== 0) { + return this.abs().inotn(width).iaddn(1); + } + return this.clone(); + }; + BN2.prototype.fromTwos = function fromTwos(width) { + if (this.testn(width - 1)) { + return this.notn(width).iaddn(1).ineg(); + } + return this.clone(); + }; + BN2.prototype.isNeg = function isNeg() { + return this.negative !== 0; + }; + BN2.prototype.neg = function neg() { + return this.clone().ineg(); + }; + BN2.prototype.ineg = function ineg() { + if (!this.isZero()) { + this.negative ^= 1; + } + return this; + }; + BN2.prototype.iuor = function iuor(num) { + while(this.length < num.length){ + this.words[this.length++] = 0; + } + for(var i = 0; i < num.length; i++){ + this.words[i] = this.words[i] | num.words[i]; + } + return this._strip(); + }; + BN2.prototype.ior = function ior(num) { + assert((this.negative | num.negative) === 0); + return this.iuor(num); + }; + BN2.prototype.or = function or(num) { + if (this.length > num.length) return this.clone().ior(num); + return num.clone().ior(this); + }; + BN2.prototype.uor = function uor(num) { + if (this.length > num.length) return this.clone().iuor(num); + return num.clone().iuor(this); + }; + BN2.prototype.iuand = function iuand(num) { + var b; + if (this.length > num.length) { + b = num; + } else { + b = this; + } + for(var i = 0; i < b.length; i++){ + this.words[i] = this.words[i] & num.words[i]; + } + this.length = b.length; + return this._strip(); + }; + BN2.prototype.iand = function iand(num) { + assert((this.negative | num.negative) === 0); + return this.iuand(num); + }; + BN2.prototype.and = function and(num) { + if (this.length > num.length) return this.clone().iand(num); + return num.clone().iand(this); + }; + BN2.prototype.uand = function uand(num) { + if (this.length > num.length) return this.clone().iuand(num); + return num.clone().iuand(this); + }; + BN2.prototype.iuxor = function iuxor(num) { + var a; + var b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + for(var i = 0; i < b.length; i++){ + this.words[i] = a.words[i] ^ b.words[i]; + } + if (this !== a) { + for(; i < a.length; i++){ + this.words[i] = a.words[i]; + } + } + this.length = a.length; + return this._strip(); + }; + BN2.prototype.ixor = function ixor(num) { + assert((this.negative | num.negative) === 0); + return this.iuxor(num); + }; + BN2.prototype.xor = function xor(num) { + if (this.length > num.length) return this.clone().ixor(num); + return num.clone().ixor(this); + }; + BN2.prototype.uxor = function uxor(num) { + if (this.length > num.length) return this.clone().iuxor(num); + return num.clone().iuxor(this); + }; + BN2.prototype.inotn = function inotn(width) { + assert(typeof width === "number" && width >= 0); + var bytesNeeded = Math.ceil(width / 26) | 0; + var bitsLeft = width % 26; + this._expand(bytesNeeded); + if (bitsLeft > 0) { + bytesNeeded--; + } + for(var i = 0; i < bytesNeeded; i++){ + this.words[i] = ~this.words[i] & 67108863; + } + if (bitsLeft > 0) { + this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft; + } + return this._strip(); + }; + BN2.prototype.notn = function notn(width) { + return this.clone().inotn(width); + }; + BN2.prototype.setn = function setn(bit, val) { + assert(typeof bit === "number" && bit >= 0); + var off = bit / 26 | 0; + var wbit = bit % 26; + this._expand(off + 1); + if (val) { + this.words[off] = this.words[off] | 1 << wbit; + } else { + this.words[off] = this.words[off] & ~(1 << wbit); + } + return this._strip(); + }; + BN2.prototype.iadd = function iadd(num) { + var r; + if (this.negative !== 0 && num.negative === 0) { + this.negative = 0; + r = this.isub(num); + this.negative ^= 1; + return this._normSign(); + } else if (this.negative === 0 && num.negative !== 0) { + num.negative = 0; + r = this.isub(num); + num.negative = 1; + return r._normSign(); + } + var a, b; + if (this.length > num.length) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for(var i = 0; i < b.length; i++){ + r = (a.words[i] | 0) + (b.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + for(; carry !== 0 && i < a.length; i++){ + r = (a.words[i] | 0) + carry; + this.words[i] = r & 67108863; + carry = r >>> 26; + } + this.length = a.length; + if (carry !== 0) { + this.words[this.length] = carry; + this.length++; + } else if (a !== this) { + for(; i < a.length; i++){ + this.words[i] = a.words[i]; + } + } + return this; + }; + BN2.prototype.add = function add(num) { + var res; + if (num.negative !== 0 && this.negative === 0) { + num.negative = 0; + res = this.sub(num); + num.negative ^= 1; + return res; + } else if (num.negative === 0 && this.negative !== 0) { + this.negative = 0; + res = num.sub(this); + this.negative = 1; + return res; + } + if (this.length > num.length) return this.clone().iadd(num); + return num.clone().iadd(this); + }; + BN2.prototype.isub = function isub(num) { + if (num.negative !== 0) { + num.negative = 0; + var r = this.iadd(num); + num.negative = 1; + return r._normSign(); + } else if (this.negative !== 0) { + this.negative = 0; + this.iadd(num); + this.negative = 1; + return this._normSign(); + } + var cmp = this.cmp(num); + if (cmp === 0) { + this.negative = 0; + this.length = 1; + this.words[0] = 0; + return this; + } + var a, b; + if (cmp > 0) { + a = this; + b = num; + } else { + a = num; + b = this; + } + var carry = 0; + for(var i = 0; i < b.length; i++){ + r = (a.words[i] | 0) - (b.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + for(; carry !== 0 && i < a.length; i++){ + r = (a.words[i] | 0) + carry; + carry = r >> 26; + this.words[i] = r & 67108863; + } + if (carry === 0 && i < a.length && a !== this) { + for(; i < a.length; i++){ + this.words[i] = a.words[i]; + } + } + this.length = Math.max(this.length, i); + if (a !== this) { + this.negative = 1; + } + return this._strip(); + }; + BN2.prototype.sub = function sub(num) { + return this.clone().isub(num); + }; + function smallMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + var len = self2.length + num.length | 0; + out.length = len; + len = len - 1 | 0; + var a = self2.words[0] | 0; + var b = num.words[0] | 0; + var r = a * b; + var lo = r & 67108863; + var carry = r / 67108864 | 0; + out.words[0] = lo; + for(var k = 1; k < len; k++){ + var ncarry = carry >>> 26; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for(var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++){ + var i = k - j | 0; + a = self2.words[i] | 0; + b = num.words[j] | 0; + r = a * b + rword; + ncarry += r / 67108864 | 0; + rword = r & 67108863; + } + out.words[k] = rword | 0; + carry = ncarry | 0; + } + if (carry !== 0) { + out.words[k] = carry | 0; + } else { + out.length--; + } + return out._strip(); + } + var comb10MulTo = function comb10MulTo2(self2, num, out) { + var a = self2.words; + var b = num.words; + var o = out.words; + var c = 0; + var lo; + var mid; + var hi; + var a0 = a[0] | 0; + var al0 = a0 & 8191; + var ah0 = a0 >>> 13; + var a1 = a[1] | 0; + var al1 = a1 & 8191; + var ah1 = a1 >>> 13; + var a2 = a[2] | 0; + var al2 = a2 & 8191; + var ah2 = a2 >>> 13; + var a3 = a[3] | 0; + var al3 = a3 & 8191; + var ah3 = a3 >>> 13; + var a4 = a[4] | 0; + var al4 = a4 & 8191; + var ah4 = a4 >>> 13; + var a5 = a[5] | 0; + var al5 = a5 & 8191; + var ah5 = a5 >>> 13; + var a6 = a[6] | 0; + var al6 = a6 & 8191; + var ah6 = a6 >>> 13; + var a7 = a[7] | 0; + var al7 = a7 & 8191; + var ah7 = a7 >>> 13; + var a8 = a[8] | 0; + var al8 = a8 & 8191; + var ah8 = a8 >>> 13; + var a9 = a[9] | 0; + var al9 = a9 & 8191; + var ah9 = a9 >>> 13; + var b0 = b[0] | 0; + var bl0 = b0 & 8191; + var bh0 = b0 >>> 13; + var b1 = b[1] | 0; + var bl1 = b1 & 8191; + var bh1 = b1 >>> 13; + var b2 = b[2] | 0; + var bl2 = b2 & 8191; + var bh2 = b2 >>> 13; + var b3 = b[3] | 0; + var bl3 = b3 & 8191; + var bh3 = b3 >>> 13; + var b4 = b[4] | 0; + var bl4 = b4 & 8191; + var bh4 = b4 >>> 13; + var b5 = b[5] | 0; + var bl5 = b5 & 8191; + var bh5 = b5 >>> 13; + var b6 = b[6] | 0; + var bl6 = b6 & 8191; + var bh6 = b6 >>> 13; + var b7 = b[7] | 0; + var bl7 = b7 & 8191; + var bh7 = b7 >>> 13; + var b8 = b[8] | 0; + var bl8 = b8 & 8191; + var bh8 = b8 >>> 13; + var b9 = b[9] | 0; + var bl9 = b9 & 8191; + var bh9 = b9 >>> 13; + out.negative = self2.negative ^ num.negative; + out.length = 19; + lo = Math.imul(al0, bl0); + mid = Math.imul(al0, bh0); + mid = mid + Math.imul(ah0, bl0) | 0; + hi = Math.imul(ah0, bh0); + var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; + w0 &= 67108863; + lo = Math.imul(al1, bl0); + mid = Math.imul(al1, bh0); + mid = mid + Math.imul(ah1, bl0) | 0; + hi = Math.imul(ah1, bh0); + lo = lo + Math.imul(al0, bl1) | 0; + mid = mid + Math.imul(al0, bh1) | 0; + mid = mid + Math.imul(ah0, bl1) | 0; + hi = hi + Math.imul(ah0, bh1) | 0; + var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; + w1 &= 67108863; + lo = Math.imul(al2, bl0); + mid = Math.imul(al2, bh0); + mid = mid + Math.imul(ah2, bl0) | 0; + hi = Math.imul(ah2, bh0); + lo = lo + Math.imul(al1, bl1) | 0; + mid = mid + Math.imul(al1, bh1) | 0; + mid = mid + Math.imul(ah1, bl1) | 0; + hi = hi + Math.imul(ah1, bh1) | 0; + lo = lo + Math.imul(al0, bl2) | 0; + mid = mid + Math.imul(al0, bh2) | 0; + mid = mid + Math.imul(ah0, bl2) | 0; + hi = hi + Math.imul(ah0, bh2) | 0; + var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; + w2 &= 67108863; + lo = Math.imul(al3, bl0); + mid = Math.imul(al3, bh0); + mid = mid + Math.imul(ah3, bl0) | 0; + hi = Math.imul(ah3, bh0); + lo = lo + Math.imul(al2, bl1) | 0; + mid = mid + Math.imul(al2, bh1) | 0; + mid = mid + Math.imul(ah2, bl1) | 0; + hi = hi + Math.imul(ah2, bh1) | 0; + lo = lo + Math.imul(al1, bl2) | 0; + mid = mid + Math.imul(al1, bh2) | 0; + mid = mid + Math.imul(ah1, bl2) | 0; + hi = hi + Math.imul(ah1, bh2) | 0; + lo = lo + Math.imul(al0, bl3) | 0; + mid = mid + Math.imul(al0, bh3) | 0; + mid = mid + Math.imul(ah0, bl3) | 0; + hi = hi + Math.imul(ah0, bh3) | 0; + var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; + w3 &= 67108863; + lo = Math.imul(al4, bl0); + mid = Math.imul(al4, bh0); + mid = mid + Math.imul(ah4, bl0) | 0; + hi = Math.imul(ah4, bh0); + lo = lo + Math.imul(al3, bl1) | 0; + mid = mid + Math.imul(al3, bh1) | 0; + mid = mid + Math.imul(ah3, bl1) | 0; + hi = hi + Math.imul(ah3, bh1) | 0; + lo = lo + Math.imul(al2, bl2) | 0; + mid = mid + Math.imul(al2, bh2) | 0; + mid = mid + Math.imul(ah2, bl2) | 0; + hi = hi + Math.imul(ah2, bh2) | 0; + lo = lo + Math.imul(al1, bl3) | 0; + mid = mid + Math.imul(al1, bh3) | 0; + mid = mid + Math.imul(ah1, bl3) | 0; + hi = hi + Math.imul(ah1, bh3) | 0; + lo = lo + Math.imul(al0, bl4) | 0; + mid = mid + Math.imul(al0, bh4) | 0; + mid = mid + Math.imul(ah0, bl4) | 0; + hi = hi + Math.imul(ah0, bh4) | 0; + var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; + w4 &= 67108863; + lo = Math.imul(al5, bl0); + mid = Math.imul(al5, bh0); + mid = mid + Math.imul(ah5, bl0) | 0; + hi = Math.imul(ah5, bh0); + lo = lo + Math.imul(al4, bl1) | 0; + mid = mid + Math.imul(al4, bh1) | 0; + mid = mid + Math.imul(ah4, bl1) | 0; + hi = hi + Math.imul(ah4, bh1) | 0; + lo = lo + Math.imul(al3, bl2) | 0; + mid = mid + Math.imul(al3, bh2) | 0; + mid = mid + Math.imul(ah3, bl2) | 0; + hi = hi + Math.imul(ah3, bh2) | 0; + lo = lo + Math.imul(al2, bl3) | 0; + mid = mid + Math.imul(al2, bh3) | 0; + mid = mid + Math.imul(ah2, bl3) | 0; + hi = hi + Math.imul(ah2, bh3) | 0; + lo = lo + Math.imul(al1, bl4) | 0; + mid = mid + Math.imul(al1, bh4) | 0; + mid = mid + Math.imul(ah1, bl4) | 0; + hi = hi + Math.imul(ah1, bh4) | 0; + lo = lo + Math.imul(al0, bl5) | 0; + mid = mid + Math.imul(al0, bh5) | 0; + mid = mid + Math.imul(ah0, bl5) | 0; + hi = hi + Math.imul(ah0, bh5) | 0; + var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; + w5 &= 67108863; + lo = Math.imul(al6, bl0); + mid = Math.imul(al6, bh0); + mid = mid + Math.imul(ah6, bl0) | 0; + hi = Math.imul(ah6, bh0); + lo = lo + Math.imul(al5, bl1) | 0; + mid = mid + Math.imul(al5, bh1) | 0; + mid = mid + Math.imul(ah5, bl1) | 0; + hi = hi + Math.imul(ah5, bh1) | 0; + lo = lo + Math.imul(al4, bl2) | 0; + mid = mid + Math.imul(al4, bh2) | 0; + mid = mid + Math.imul(ah4, bl2) | 0; + hi = hi + Math.imul(ah4, bh2) | 0; + lo = lo + Math.imul(al3, bl3) | 0; + mid = mid + Math.imul(al3, bh3) | 0; + mid = mid + Math.imul(ah3, bl3) | 0; + hi = hi + Math.imul(ah3, bh3) | 0; + lo = lo + Math.imul(al2, bl4) | 0; + mid = mid + Math.imul(al2, bh4) | 0; + mid = mid + Math.imul(ah2, bl4) | 0; + hi = hi + Math.imul(ah2, bh4) | 0; + lo = lo + Math.imul(al1, bl5) | 0; + mid = mid + Math.imul(al1, bh5) | 0; + mid = mid + Math.imul(ah1, bl5) | 0; + hi = hi + Math.imul(ah1, bh5) | 0; + lo = lo + Math.imul(al0, bl6) | 0; + mid = mid + Math.imul(al0, bh6) | 0; + mid = mid + Math.imul(ah0, bl6) | 0; + hi = hi + Math.imul(ah0, bh6) | 0; + var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; + w6 &= 67108863; + lo = Math.imul(al7, bl0); + mid = Math.imul(al7, bh0); + mid = mid + Math.imul(ah7, bl0) | 0; + hi = Math.imul(ah7, bh0); + lo = lo + Math.imul(al6, bl1) | 0; + mid = mid + Math.imul(al6, bh1) | 0; + mid = mid + Math.imul(ah6, bl1) | 0; + hi = hi + Math.imul(ah6, bh1) | 0; + lo = lo + Math.imul(al5, bl2) | 0; + mid = mid + Math.imul(al5, bh2) | 0; + mid = mid + Math.imul(ah5, bl2) | 0; + hi = hi + Math.imul(ah5, bh2) | 0; + lo = lo + Math.imul(al4, bl3) | 0; + mid = mid + Math.imul(al4, bh3) | 0; + mid = mid + Math.imul(ah4, bl3) | 0; + hi = hi + Math.imul(ah4, bh3) | 0; + lo = lo + Math.imul(al3, bl4) | 0; + mid = mid + Math.imul(al3, bh4) | 0; + mid = mid + Math.imul(ah3, bl4) | 0; + hi = hi + Math.imul(ah3, bh4) | 0; + lo = lo + Math.imul(al2, bl5) | 0; + mid = mid + Math.imul(al2, bh5) | 0; + mid = mid + Math.imul(ah2, bl5) | 0; + hi = hi + Math.imul(ah2, bh5) | 0; + lo = lo + Math.imul(al1, bl6) | 0; + mid = mid + Math.imul(al1, bh6) | 0; + mid = mid + Math.imul(ah1, bl6) | 0; + hi = hi + Math.imul(ah1, bh6) | 0; + lo = lo + Math.imul(al0, bl7) | 0; + mid = mid + Math.imul(al0, bh7) | 0; + mid = mid + Math.imul(ah0, bl7) | 0; + hi = hi + Math.imul(ah0, bh7) | 0; + var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; + w7 &= 67108863; + lo = Math.imul(al8, bl0); + mid = Math.imul(al8, bh0); + mid = mid + Math.imul(ah8, bl0) | 0; + hi = Math.imul(ah8, bh0); + lo = lo + Math.imul(al7, bl1) | 0; + mid = mid + Math.imul(al7, bh1) | 0; + mid = mid + Math.imul(ah7, bl1) | 0; + hi = hi + Math.imul(ah7, bh1) | 0; + lo = lo + Math.imul(al6, bl2) | 0; + mid = mid + Math.imul(al6, bh2) | 0; + mid = mid + Math.imul(ah6, bl2) | 0; + hi = hi + Math.imul(ah6, bh2) | 0; + lo = lo + Math.imul(al5, bl3) | 0; + mid = mid + Math.imul(al5, bh3) | 0; + mid = mid + Math.imul(ah5, bl3) | 0; + hi = hi + Math.imul(ah5, bh3) | 0; + lo = lo + Math.imul(al4, bl4) | 0; + mid = mid + Math.imul(al4, bh4) | 0; + mid = mid + Math.imul(ah4, bl4) | 0; + hi = hi + Math.imul(ah4, bh4) | 0; + lo = lo + Math.imul(al3, bl5) | 0; + mid = mid + Math.imul(al3, bh5) | 0; + mid = mid + Math.imul(ah3, bl5) | 0; + hi = hi + Math.imul(ah3, bh5) | 0; + lo = lo + Math.imul(al2, bl6) | 0; + mid = mid + Math.imul(al2, bh6) | 0; + mid = mid + Math.imul(ah2, bl6) | 0; + hi = hi + Math.imul(ah2, bh6) | 0; + lo = lo + Math.imul(al1, bl7) | 0; + mid = mid + Math.imul(al1, bh7) | 0; + mid = mid + Math.imul(ah1, bl7) | 0; + hi = hi + Math.imul(ah1, bh7) | 0; + lo = lo + Math.imul(al0, bl8) | 0; + mid = mid + Math.imul(al0, bh8) | 0; + mid = mid + Math.imul(ah0, bl8) | 0; + hi = hi + Math.imul(ah0, bh8) | 0; + var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; + w8 &= 67108863; + lo = Math.imul(al9, bl0); + mid = Math.imul(al9, bh0); + mid = mid + Math.imul(ah9, bl0) | 0; + hi = Math.imul(ah9, bh0); + lo = lo + Math.imul(al8, bl1) | 0; + mid = mid + Math.imul(al8, bh1) | 0; + mid = mid + Math.imul(ah8, bl1) | 0; + hi = hi + Math.imul(ah8, bh1) | 0; + lo = lo + Math.imul(al7, bl2) | 0; + mid = mid + Math.imul(al7, bh2) | 0; + mid = mid + Math.imul(ah7, bl2) | 0; + hi = hi + Math.imul(ah7, bh2) | 0; + lo = lo + Math.imul(al6, bl3) | 0; + mid = mid + Math.imul(al6, bh3) | 0; + mid = mid + Math.imul(ah6, bl3) | 0; + hi = hi + Math.imul(ah6, bh3) | 0; + lo = lo + Math.imul(al5, bl4) | 0; + mid = mid + Math.imul(al5, bh4) | 0; + mid = mid + Math.imul(ah5, bl4) | 0; + hi = hi + Math.imul(ah5, bh4) | 0; + lo = lo + Math.imul(al4, bl5) | 0; + mid = mid + Math.imul(al4, bh5) | 0; + mid = mid + Math.imul(ah4, bl5) | 0; + hi = hi + Math.imul(ah4, bh5) | 0; + lo = lo + Math.imul(al3, bl6) | 0; + mid = mid + Math.imul(al3, bh6) | 0; + mid = mid + Math.imul(ah3, bl6) | 0; + hi = hi + Math.imul(ah3, bh6) | 0; + lo = lo + Math.imul(al2, bl7) | 0; + mid = mid + Math.imul(al2, bh7) | 0; + mid = mid + Math.imul(ah2, bl7) | 0; + hi = hi + Math.imul(ah2, bh7) | 0; + lo = lo + Math.imul(al1, bl8) | 0; + mid = mid + Math.imul(al1, bh8) | 0; + mid = mid + Math.imul(ah1, bl8) | 0; + hi = hi + Math.imul(ah1, bh8) | 0; + lo = lo + Math.imul(al0, bl9) | 0; + mid = mid + Math.imul(al0, bh9) | 0; + mid = mid + Math.imul(ah0, bl9) | 0; + hi = hi + Math.imul(ah0, bh9) | 0; + var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; + w9 &= 67108863; + lo = Math.imul(al9, bl1); + mid = Math.imul(al9, bh1); + mid = mid + Math.imul(ah9, bl1) | 0; + hi = Math.imul(ah9, bh1); + lo = lo + Math.imul(al8, bl2) | 0; + mid = mid + Math.imul(al8, bh2) | 0; + mid = mid + Math.imul(ah8, bl2) | 0; + hi = hi + Math.imul(ah8, bh2) | 0; + lo = lo + Math.imul(al7, bl3) | 0; + mid = mid + Math.imul(al7, bh3) | 0; + mid = mid + Math.imul(ah7, bl3) | 0; + hi = hi + Math.imul(ah7, bh3) | 0; + lo = lo + Math.imul(al6, bl4) | 0; + mid = mid + Math.imul(al6, bh4) | 0; + mid = mid + Math.imul(ah6, bl4) | 0; + hi = hi + Math.imul(ah6, bh4) | 0; + lo = lo + Math.imul(al5, bl5) | 0; + mid = mid + Math.imul(al5, bh5) | 0; + mid = mid + Math.imul(ah5, bl5) | 0; + hi = hi + Math.imul(ah5, bh5) | 0; + lo = lo + Math.imul(al4, bl6) | 0; + mid = mid + Math.imul(al4, bh6) | 0; + mid = mid + Math.imul(ah4, bl6) | 0; + hi = hi + Math.imul(ah4, bh6) | 0; + lo = lo + Math.imul(al3, bl7) | 0; + mid = mid + Math.imul(al3, bh7) | 0; + mid = mid + Math.imul(ah3, bl7) | 0; + hi = hi + Math.imul(ah3, bh7) | 0; + lo = lo + Math.imul(al2, bl8) | 0; + mid = mid + Math.imul(al2, bh8) | 0; + mid = mid + Math.imul(ah2, bl8) | 0; + hi = hi + Math.imul(ah2, bh8) | 0; + lo = lo + Math.imul(al1, bl9) | 0; + mid = mid + Math.imul(al1, bh9) | 0; + mid = mid + Math.imul(ah1, bl9) | 0; + hi = hi + Math.imul(ah1, bh9) | 0; + var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; + w10 &= 67108863; + lo = Math.imul(al9, bl2); + mid = Math.imul(al9, bh2); + mid = mid + Math.imul(ah9, bl2) | 0; + hi = Math.imul(ah9, bh2); + lo = lo + Math.imul(al8, bl3) | 0; + mid = mid + Math.imul(al8, bh3) | 0; + mid = mid + Math.imul(ah8, bl3) | 0; + hi = hi + Math.imul(ah8, bh3) | 0; + lo = lo + Math.imul(al7, bl4) | 0; + mid = mid + Math.imul(al7, bh4) | 0; + mid = mid + Math.imul(ah7, bl4) | 0; + hi = hi + Math.imul(ah7, bh4) | 0; + lo = lo + Math.imul(al6, bl5) | 0; + mid = mid + Math.imul(al6, bh5) | 0; + mid = mid + Math.imul(ah6, bl5) | 0; + hi = hi + Math.imul(ah6, bh5) | 0; + lo = lo + Math.imul(al5, bl6) | 0; + mid = mid + Math.imul(al5, bh6) | 0; + mid = mid + Math.imul(ah5, bl6) | 0; + hi = hi + Math.imul(ah5, bh6) | 0; + lo = lo + Math.imul(al4, bl7) | 0; + mid = mid + Math.imul(al4, bh7) | 0; + mid = mid + Math.imul(ah4, bl7) | 0; + hi = hi + Math.imul(ah4, bh7) | 0; + lo = lo + Math.imul(al3, bl8) | 0; + mid = mid + Math.imul(al3, bh8) | 0; + mid = mid + Math.imul(ah3, bl8) | 0; + hi = hi + Math.imul(ah3, bh8) | 0; + lo = lo + Math.imul(al2, bl9) | 0; + mid = mid + Math.imul(al2, bh9) | 0; + mid = mid + Math.imul(ah2, bl9) | 0; + hi = hi + Math.imul(ah2, bh9) | 0; + var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; + w11 &= 67108863; + lo = Math.imul(al9, bl3); + mid = Math.imul(al9, bh3); + mid = mid + Math.imul(ah9, bl3) | 0; + hi = Math.imul(ah9, bh3); + lo = lo + Math.imul(al8, bl4) | 0; + mid = mid + Math.imul(al8, bh4) | 0; + mid = mid + Math.imul(ah8, bl4) | 0; + hi = hi + Math.imul(ah8, bh4) | 0; + lo = lo + Math.imul(al7, bl5) | 0; + mid = mid + Math.imul(al7, bh5) | 0; + mid = mid + Math.imul(ah7, bl5) | 0; + hi = hi + Math.imul(ah7, bh5) | 0; + lo = lo + Math.imul(al6, bl6) | 0; + mid = mid + Math.imul(al6, bh6) | 0; + mid = mid + Math.imul(ah6, bl6) | 0; + hi = hi + Math.imul(ah6, bh6) | 0; + lo = lo + Math.imul(al5, bl7) | 0; + mid = mid + Math.imul(al5, bh7) | 0; + mid = mid + Math.imul(ah5, bl7) | 0; + hi = hi + Math.imul(ah5, bh7) | 0; + lo = lo + Math.imul(al4, bl8) | 0; + mid = mid + Math.imul(al4, bh8) | 0; + mid = mid + Math.imul(ah4, bl8) | 0; + hi = hi + Math.imul(ah4, bh8) | 0; + lo = lo + Math.imul(al3, bl9) | 0; + mid = mid + Math.imul(al3, bh9) | 0; + mid = mid + Math.imul(ah3, bl9) | 0; + hi = hi + Math.imul(ah3, bh9) | 0; + var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; + w12 &= 67108863; + lo = Math.imul(al9, bl4); + mid = Math.imul(al9, bh4); + mid = mid + Math.imul(ah9, bl4) | 0; + hi = Math.imul(ah9, bh4); + lo = lo + Math.imul(al8, bl5) | 0; + mid = mid + Math.imul(al8, bh5) | 0; + mid = mid + Math.imul(ah8, bl5) | 0; + hi = hi + Math.imul(ah8, bh5) | 0; + lo = lo + Math.imul(al7, bl6) | 0; + mid = mid + Math.imul(al7, bh6) | 0; + mid = mid + Math.imul(ah7, bl6) | 0; + hi = hi + Math.imul(ah7, bh6) | 0; + lo = lo + Math.imul(al6, bl7) | 0; + mid = mid + Math.imul(al6, bh7) | 0; + mid = mid + Math.imul(ah6, bl7) | 0; + hi = hi + Math.imul(ah6, bh7) | 0; + lo = lo + Math.imul(al5, bl8) | 0; + mid = mid + Math.imul(al5, bh8) | 0; + mid = mid + Math.imul(ah5, bl8) | 0; + hi = hi + Math.imul(ah5, bh8) | 0; + lo = lo + Math.imul(al4, bl9) | 0; + mid = mid + Math.imul(al4, bh9) | 0; + mid = mid + Math.imul(ah4, bl9) | 0; + hi = hi + Math.imul(ah4, bh9) | 0; + var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; + w13 &= 67108863; + lo = Math.imul(al9, bl5); + mid = Math.imul(al9, bh5); + mid = mid + Math.imul(ah9, bl5) | 0; + hi = Math.imul(ah9, bh5); + lo = lo + Math.imul(al8, bl6) | 0; + mid = mid + Math.imul(al8, bh6) | 0; + mid = mid + Math.imul(ah8, bl6) | 0; + hi = hi + Math.imul(ah8, bh6) | 0; + lo = lo + Math.imul(al7, bl7) | 0; + mid = mid + Math.imul(al7, bh7) | 0; + mid = mid + Math.imul(ah7, bl7) | 0; + hi = hi + Math.imul(ah7, bh7) | 0; + lo = lo + Math.imul(al6, bl8) | 0; + mid = mid + Math.imul(al6, bh8) | 0; + mid = mid + Math.imul(ah6, bl8) | 0; + hi = hi + Math.imul(ah6, bh8) | 0; + lo = lo + Math.imul(al5, bl9) | 0; + mid = mid + Math.imul(al5, bh9) | 0; + mid = mid + Math.imul(ah5, bl9) | 0; + hi = hi + Math.imul(ah5, bh9) | 0; + var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; + w14 &= 67108863; + lo = Math.imul(al9, bl6); + mid = Math.imul(al9, bh6); + mid = mid + Math.imul(ah9, bl6) | 0; + hi = Math.imul(ah9, bh6); + lo = lo + Math.imul(al8, bl7) | 0; + mid = mid + Math.imul(al8, bh7) | 0; + mid = mid + Math.imul(ah8, bl7) | 0; + hi = hi + Math.imul(ah8, bh7) | 0; + lo = lo + Math.imul(al7, bl8) | 0; + mid = mid + Math.imul(al7, bh8) | 0; + mid = mid + Math.imul(ah7, bl8) | 0; + hi = hi + Math.imul(ah7, bh8) | 0; + lo = lo + Math.imul(al6, bl9) | 0; + mid = mid + Math.imul(al6, bh9) | 0; + mid = mid + Math.imul(ah6, bl9) | 0; + hi = hi + Math.imul(ah6, bh9) | 0; + var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; + w15 &= 67108863; + lo = Math.imul(al9, bl7); + mid = Math.imul(al9, bh7); + mid = mid + Math.imul(ah9, bl7) | 0; + hi = Math.imul(ah9, bh7); + lo = lo + Math.imul(al8, bl8) | 0; + mid = mid + Math.imul(al8, bh8) | 0; + mid = mid + Math.imul(ah8, bl8) | 0; + hi = hi + Math.imul(ah8, bh8) | 0; + lo = lo + Math.imul(al7, bl9) | 0; + mid = mid + Math.imul(al7, bh9) | 0; + mid = mid + Math.imul(ah7, bl9) | 0; + hi = hi + Math.imul(ah7, bh9) | 0; + var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; + w16 &= 67108863; + lo = Math.imul(al9, bl8); + mid = Math.imul(al9, bh8); + mid = mid + Math.imul(ah9, bl8) | 0; + hi = Math.imul(ah9, bh8); + lo = lo + Math.imul(al8, bl9) | 0; + mid = mid + Math.imul(al8, bh9) | 0; + mid = mid + Math.imul(ah8, bl9) | 0; + hi = hi + Math.imul(ah8, bh9) | 0; + var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; + w17 &= 67108863; + lo = Math.imul(al9, bl9); + mid = Math.imul(al9, bh9); + mid = mid + Math.imul(ah9, bl9) | 0; + hi = Math.imul(ah9, bh9); + var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0; + c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; + w18 &= 67108863; + o[0] = w0; + o[1] = w1; + o[2] = w2; + o[3] = w3; + o[4] = w4; + o[5] = w5; + o[6] = w6; + o[7] = w7; + o[8] = w8; + o[9] = w9; + o[10] = w10; + o[11] = w11; + o[12] = w12; + o[13] = w13; + o[14] = w14; + o[15] = w15; + o[16] = w16; + o[17] = w17; + o[18] = w18; + if (c !== 0) { + o[19] = c; + out.length++; + } + return out; + }; + if (!Math.imul) { + comb10MulTo = smallMulTo; + } + function bigMulTo(self2, num, out) { + out.negative = num.negative ^ self2.negative; + out.length = self2.length + num.length; + var carry = 0; + var hncarry = 0; + for(var k = 0; k < out.length - 1; k++){ + var ncarry = hncarry; + hncarry = 0; + var rword = carry & 67108863; + var maxJ = Math.min(k, num.length - 1); + for(var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++){ + var i = k - j; + var a = self2.words[i] | 0; + var b = num.words[j] | 0; + var r = a * b; + var lo = r & 67108863; + ncarry = ncarry + (r / 67108864 | 0) | 0; + lo = lo + rword | 0; + rword = lo & 67108863; + ncarry = ncarry + (lo >>> 26) | 0; + hncarry += ncarry >>> 26; + ncarry &= 67108863; + } + out.words[k] = rword; + carry = ncarry; + ncarry = hncarry; + } + if (carry !== 0) { + out.words[k] = carry; + } else { + out.length--; + } + return out._strip(); + } + function jumboMulTo(self2, num, out) { + return bigMulTo(self2, num, out); + } + BN2.prototype.mulTo = function mulTo(num, out) { + var res; + var len = this.length + num.length; + if (this.length === 10 && num.length === 10) { + res = comb10MulTo(this, num, out); + } else if (len < 63) { + res = smallMulTo(this, num, out); + } else if (len < 1024) { + res = bigMulTo(this, num, out); + } else { + res = jumboMulTo(this, num, out); + } + return res; + }; + BN2.prototype.mul = function mul(num) { + var out = new BN2(null); + out.words = new Array(this.length + num.length); + return this.mulTo(num, out); + }; + BN2.prototype.mulf = function mulf(num) { + var out = new BN2(null); + out.words = new Array(this.length + num.length); + return jumboMulTo(this, num, out); + }; + BN2.prototype.imul = function imul(num) { + return this.clone().mulTo(num, this); + }; + BN2.prototype.imuln = function imuln(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert(typeof num === "number"); + assert(num < 67108864); + var carry = 0; + for(var i = 0; i < this.length; i++){ + var w = (this.words[i] | 0) * num; + var lo = (w & 67108863) + (carry & 67108863); + carry >>= 26; + carry += w / 67108864 | 0; + carry += lo >>> 26; + this.words[i] = lo & 67108863; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return isNegNum ? this.ineg() : this; + }; + BN2.prototype.muln = function muln(num) { + return this.clone().imuln(num); + }; + BN2.prototype.sqr = function sqr() { + return this.mul(this); + }; + BN2.prototype.isqr = function isqr() { + return this.imul(this.clone()); + }; + BN2.prototype.pow = function pow(num) { + var w = toBitArray(num); + if (w.length === 0) return new BN2(1); + var res = this; + for(var i = 0; i < w.length; i++, res = res.sqr()){ + if (w[i] !== 0) break; + } + if (++i < w.length) { + for(var q = res.sqr(); i < w.length; i++, q = q.sqr()){ + if (w[i] === 0) continue; + res = res.mul(q); + } + } + return res; + }; + BN2.prototype.iushln = function iushln(bits) { + assert(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + var carryMask = 67108863 >>> 26 - r << 26 - r; + var i; + if (r !== 0) { + var carry = 0; + for(i = 0; i < this.length; i++){ + var newCarry = this.words[i] & carryMask; + var c = (this.words[i] | 0) - newCarry << r; + this.words[i] = c | carry; + carry = newCarry >>> 26 - r; + } + if (carry) { + this.words[i] = carry; + this.length++; + } + } + if (s !== 0) { + for(i = this.length - 1; i >= 0; i--){ + this.words[i + s] = this.words[i]; + } + for(i = 0; i < s; i++){ + this.words[i] = 0; + } + this.length += s; + } + return this._strip(); + }; + BN2.prototype.ishln = function ishln(bits) { + assert(this.negative === 0); + return this.iushln(bits); + }; + BN2.prototype.iushrn = function iushrn(bits, hint, extended) { + assert(typeof bits === "number" && bits >= 0); + var h; + if (hint) { + h = (hint - hint % 26) / 26; + } else { + h = 0; + } + var r = bits % 26; + var s = Math.min((bits - r) / 26, this.length); + var mask = 67108863 ^ 67108863 >>> r << r; + var maskedWords = extended; + h -= s; + h = Math.max(0, h); + if (maskedWords) { + for(var i = 0; i < s; i++){ + maskedWords.words[i] = this.words[i]; + } + maskedWords.length = s; + } + if (s === 0) ; + else if (this.length > s) { + this.length -= s; + for(i = 0; i < this.length; i++){ + this.words[i] = this.words[i + s]; + } + } else { + this.words[0] = 0; + this.length = 1; + } + var carry = 0; + for(i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--){ + var word = this.words[i] | 0; + this.words[i] = carry << 26 - r | word >>> r; + carry = word & mask; + } + if (maskedWords && carry !== 0) { + maskedWords.words[maskedWords.length++] = carry; + } + if (this.length === 0) { + this.words[0] = 0; + this.length = 1; + } + return this._strip(); + }; + BN2.prototype.ishrn = function ishrn(bits, hint, extended) { + assert(this.negative === 0); + return this.iushrn(bits, hint, extended); + }; + BN2.prototype.shln = function shln(bits) { + return this.clone().ishln(bits); + }; + BN2.prototype.ushln = function ushln(bits) { + return this.clone().iushln(bits); + }; + BN2.prototype.shrn = function shrn(bits) { + return this.clone().ishrn(bits); + }; + BN2.prototype.ushrn = function ushrn(bits) { + return this.clone().iushrn(bits); + }; + BN2.prototype.testn = function testn(bit) { + assert(typeof bit === "number" && bit >= 0); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) return false; + var w = this.words[s]; + return !!(w & q); + }; + BN2.prototype.imaskn = function imaskn(bits) { + assert(typeof bits === "number" && bits >= 0); + var r = bits % 26; + var s = (bits - r) / 26; + assert(this.negative === 0, "imaskn works only with positive numbers"); + if (this.length <= s) { + return this; + } + if (r !== 0) { + s++; + } + this.length = Math.min(s, this.length); + if (r !== 0) { + var mask = 67108863 ^ 67108863 >>> r << r; + this.words[this.length - 1] &= mask; + } + return this._strip(); + }; + BN2.prototype.maskn = function maskn(bits) { + return this.clone().imaskn(bits); + }; + BN2.prototype.iaddn = function iaddn(num) { + assert(typeof num === "number"); + assert(num < 67108864); + if (num < 0) return this.isubn(-num); + if (this.negative !== 0) { + if (this.length === 1 && (this.words[0] | 0) <= num) { + this.words[0] = num - (this.words[0] | 0); + this.negative = 0; + return this; + } + this.negative = 0; + this.isubn(num); + this.negative = 1; + return this; + } + return this._iaddn(num); + }; + BN2.prototype._iaddn = function _iaddn(num) { + this.words[0] += num; + for(var i = 0; i < this.length && this.words[i] >= 67108864; i++){ + this.words[i] -= 67108864; + if (i === this.length - 1) { + this.words[i + 1] = 1; + } else { + this.words[i + 1]++; + } + } + this.length = Math.max(this.length, i + 1); + return this; + }; + BN2.prototype.isubn = function isubn(num) { + assert(typeof num === "number"); + assert(num < 67108864); + if (num < 0) return this.iaddn(-num); + if (this.negative !== 0) { + this.negative = 0; + this.iaddn(num); + this.negative = 1; + return this; + } + this.words[0] -= num; + if (this.length === 1 && this.words[0] < 0) { + this.words[0] = -this.words[0]; + this.negative = 1; + } else { + for(var i = 0; i < this.length && this.words[i] < 0; i++){ + this.words[i] += 67108864; + this.words[i + 1] -= 1; + } + } + return this._strip(); + }; + BN2.prototype.addn = function addn(num) { + return this.clone().iaddn(num); + }; + BN2.prototype.subn = function subn(num) { + return this.clone().isubn(num); + }; + BN2.prototype.iabs = function iabs() { + this.negative = 0; + return this; + }; + BN2.prototype.abs = function abs() { + return this.clone().iabs(); + }; + BN2.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { + var len = num.length + shift; + var i; + this._expand(len); + var w; + var carry = 0; + for(i = 0; i < num.length; i++){ + w = (this.words[i + shift] | 0) + carry; + var right = (num.words[i] | 0) * mul; + w -= right & 67108863; + carry = (w >> 26) - (right / 67108864 | 0); + this.words[i + shift] = w & 67108863; + } + for(; i < this.length - shift; i++){ + w = (this.words[i + shift] | 0) + carry; + carry = w >> 26; + this.words[i + shift] = w & 67108863; + } + if (carry === 0) return this._strip(); + assert(carry === -1); + carry = 0; + for(i = 0; i < this.length; i++){ + w = -(this.words[i] | 0) + carry; + carry = w >> 26; + this.words[i] = w & 67108863; + } + this.negative = 1; + return this._strip(); + }; + BN2.prototype._wordDiv = function _wordDiv(num, mode) { + var shift = this.length - num.length; + var a = this.clone(); + var b = num; + var bhi = b.words[b.length - 1] | 0; + var bhiBits = this._countBits(bhi); + shift = 26 - bhiBits; + if (shift !== 0) { + b = b.ushln(shift); + a.iushln(shift); + bhi = b.words[b.length - 1] | 0; + } + var m = a.length - b.length; + var q; + if (mode !== "mod") { + q = new BN2(null); + q.length = m + 1; + q.words = new Array(q.length); + for(var i = 0; i < q.length; i++){ + q.words[i] = 0; + } + } + var diff = a.clone()._ishlnsubmul(b, 1, m); + if (diff.negative === 0) { + a = diff; + if (q) { + q.words[m] = 1; + } + } + for(var j = m - 1; j >= 0; j--){ + var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); + qj = Math.min(qj / bhi | 0, 67108863); + a._ishlnsubmul(b, qj, j); + while(a.negative !== 0){ + qj--; + a.negative = 0; + a._ishlnsubmul(b, 1, j); + if (!a.isZero()) { + a.negative ^= 1; + } + } + if (q) { + q.words[j] = qj; + } + } + if (q) { + q._strip(); + } + a._strip(); + if (mode !== "div" && shift !== 0) { + a.iushrn(shift); + } + return { + div: q || null, + mod: a + }; + }; + BN2.prototype.divmod = function divmod(num, mode, positive) { + assert(!num.isZero()); + if (this.isZero()) { + return { + div: new BN2(0), + mod: new BN2(0) + }; + } + var div, mod, res; + if (this.negative !== 0 && num.negative === 0) { + res = this.neg().divmod(num, mode); + if (mode !== "mod") { + div = res.div.neg(); + } + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.iadd(num); + } + } + return { + div, + mod + }; + } + if (this.negative === 0 && num.negative !== 0) { + res = this.divmod(num.neg(), mode); + if (mode !== "mod") { + div = res.div.neg(); + } + return { + div, + mod: res.mod + }; + } + if ((this.negative & num.negative) !== 0) { + res = this.neg().divmod(num.neg(), mode); + if (mode !== "div") { + mod = res.mod.neg(); + if (positive && mod.negative !== 0) { + mod.isub(num); + } + } + return { + div: res.div, + mod + }; + } + if (num.length > this.length || this.cmp(num) < 0) { + return { + div: new BN2(0), + mod: this + }; + } + if (num.length === 1) { + if (mode === "div") { + return { + div: this.divn(num.words[0]), + mod: null + }; + } + if (mode === "mod") { + return { + div: null, + mod: new BN2(this.modrn(num.words[0])) + }; + } + return { + div: this.divn(num.words[0]), + mod: new BN2(this.modrn(num.words[0])) + }; + } + return this._wordDiv(num, mode); + }; + BN2.prototype.div = function div(num) { + return this.divmod(num, "div", false).div; + }; + BN2.prototype.mod = function mod(num) { + return this.divmod(num, "mod", false).mod; + }; + BN2.prototype.umod = function umod(num) { + return this.divmod(num, "mod", true).mod; + }; + BN2.prototype.divRound = function divRound(num) { + var dm = this.divmod(num); + if (dm.mod.isZero()) return dm.div; + var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; + var half = num.ushrn(1); + var r2 = num.andln(1); + var cmp = mod.cmp(half); + if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; + return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); + }; + BN2.prototype.modrn = function modrn(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert(num <= 67108863); + var p = (1 << 26) % num; + var acc = 0; + for(var i = this.length - 1; i >= 0; i--){ + acc = (p * acc + (this.words[i] | 0)) % num; + } + return isNegNum ? -acc : acc; + }; + BN2.prototype.modn = function modn(num) { + return this.modrn(num); + }; + BN2.prototype.idivn = function idivn(num) { + var isNegNum = num < 0; + if (isNegNum) num = -num; + assert(num <= 67108863); + var carry = 0; + for(var i = this.length - 1; i >= 0; i--){ + var w = (this.words[i] | 0) + carry * 67108864; + this.words[i] = w / num | 0; + carry = w % num; + } + this._strip(); + return isNegNum ? this.ineg() : this; + }; + BN2.prototype.divn = function divn(num) { + return this.clone().idivn(num); + }; + BN2.prototype.egcd = function egcd(p) { + assert(p.negative === 0); + assert(!p.isZero()); + var x = this; + var y = p.clone(); + if (x.negative !== 0) { + x = x.umod(p); + } else { + x = x.clone(); + } + var A = new BN2(1); + var B = new BN2(0); + var C = new BN2(0); + var D = new BN2(1); + var g = 0; + while(x.isEven() && y.isEven()){ + x.iushrn(1); + y.iushrn(1); + ++g; + } + var yp = y.clone(); + var xp = x.clone(); + while(!x.isZero()){ + for(var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + x.iushrn(i); + while(i-- > 0){ + if (A.isOdd() || B.isOdd()) { + A.iadd(yp); + B.isub(xp); + } + A.iushrn(1); + B.iushrn(1); + } + } + for(var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + y.iushrn(j); + while(j-- > 0){ + if (C.isOdd() || D.isOdd()) { + C.iadd(yp); + D.isub(xp); + } + C.iushrn(1); + D.iushrn(1); + } + } + if (x.cmp(y) >= 0) { + x.isub(y); + A.isub(C); + B.isub(D); + } else { + y.isub(x); + C.isub(A); + D.isub(B); + } + } + return { + a: C, + b: D, + gcd: y.iushln(g) + }; + }; + BN2.prototype._invmp = function _invmp(p) { + assert(p.negative === 0); + assert(!p.isZero()); + var a = this; + var b = p.clone(); + if (a.negative !== 0) { + a = a.umod(p); + } else { + a = a.clone(); + } + var x1 = new BN2(1); + var x2 = new BN2(0); + var delta = b.clone(); + while(a.cmpn(1) > 0 && b.cmpn(1) > 0){ + for(var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); + if (i > 0) { + a.iushrn(i); + while(i-- > 0){ + if (x1.isOdd()) { + x1.iadd(delta); + } + x1.iushrn(1); + } + } + for(var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); + if (j > 0) { + b.iushrn(j); + while(j-- > 0){ + if (x2.isOdd()) { + x2.iadd(delta); + } + x2.iushrn(1); + } + } + if (a.cmp(b) >= 0) { + a.isub(b); + x1.isub(x2); + } else { + b.isub(a); + x2.isub(x1); + } + } + var res; + if (a.cmpn(1) === 0) { + res = x1; + } else { + res = x2; + } + if (res.cmpn(0) < 0) { + res.iadd(p); + } + return res; + }; + BN2.prototype.gcd = function gcd(num) { + if (this.isZero()) return num.abs(); + if (num.isZero()) return this.abs(); + var a = this.clone(); + var b = num.clone(); + a.negative = 0; + b.negative = 0; + for(var shift = 0; a.isEven() && b.isEven(); shift++){ + a.iushrn(1); + b.iushrn(1); + } + do { + while(a.isEven()){ + a.iushrn(1); + } + while(b.isEven()){ + b.iushrn(1); + } + var r = a.cmp(b); + if (r < 0) { + var t = a; + a = b; + b = t; + } else if (r === 0 || b.cmpn(1) === 0) { + break; + } + a.isub(b); + }while (true) + return b.iushln(shift); + }; + BN2.prototype.invm = function invm(num) { + return this.egcd(num).a.umod(num); + }; + BN2.prototype.isEven = function isEven() { + return (this.words[0] & 1) === 0; + }; + BN2.prototype.isOdd = function isOdd() { + return (this.words[0] & 1) === 1; + }; + BN2.prototype.andln = function andln(num) { + return this.words[0] & num; + }; + BN2.prototype.bincn = function bincn(bit) { + assert(typeof bit === "number"); + var r = bit % 26; + var s = (bit - r) / 26; + var q = 1 << r; + if (this.length <= s) { + this._expand(s + 1); + this.words[s] |= q; + return this; + } + var carry = q; + for(var i = s; carry !== 0 && i < this.length; i++){ + var w = this.words[i] | 0; + w += carry; + carry = w >>> 26; + w &= 67108863; + this.words[i] = w; + } + if (carry !== 0) { + this.words[i] = carry; + this.length++; + } + return this; + }; + BN2.prototype.isZero = function isZero() { + return this.length === 1 && this.words[0] === 0; + }; + BN2.prototype.cmpn = function cmpn(num) { + var negative = num < 0; + if (this.negative !== 0 && !negative) return -1; + if (this.negative === 0 && negative) return 1; + this._strip(); + var res; + if (this.length > 1) { + res = 1; + } else { + if (negative) { + num = -num; + } + assert(num <= 67108863, "Number is too big"); + var w = this.words[0] | 0; + res = w === num ? 0 : w < num ? -1 : 1; + } + if (this.negative !== 0) return -res | 0; + return res; + }; + BN2.prototype.cmp = function cmp(num) { + if (this.negative !== 0 && num.negative === 0) return -1; + if (this.negative === 0 && num.negative !== 0) return 1; + var res = this.ucmp(num); + if (this.negative !== 0) return -res | 0; + return res; + }; + BN2.prototype.ucmp = function ucmp(num) { + if (this.length > num.length) return 1; + if (this.length < num.length) return -1; + var res = 0; + for(var i = this.length - 1; i >= 0; i--){ + var a = this.words[i] | 0; + var b = num.words[i] | 0; + if (a === b) continue; + if (a < b) { + res = -1; + } else if (a > b) { + res = 1; + } + break; + } + return res; + }; + BN2.prototype.gtn = function gtn(num) { + return this.cmpn(num) === 1; + }; + BN2.prototype.gt = function gt(num) { + return this.cmp(num) === 1; + }; + BN2.prototype.gten = function gten(num) { + return this.cmpn(num) >= 0; + }; + BN2.prototype.gte = function gte(num) { + return this.cmp(num) >= 0; + }; + BN2.prototype.ltn = function ltn(num) { + return this.cmpn(num) === -1; + }; + BN2.prototype.lt = function lt(num) { + return this.cmp(num) === -1; + }; + BN2.prototype.lten = function lten(num) { + return this.cmpn(num) <= 0; + }; + BN2.prototype.lte = function lte(num) { + return this.cmp(num) <= 0; + }; + BN2.prototype.eqn = function eqn(num) { + return this.cmpn(num) === 0; + }; + BN2.prototype.eq = function eq(num) { + return this.cmp(num) === 0; + }; + BN2.red = function red(num) { + return new Red(num); + }; + BN2.prototype.toRed = function toRed(ctx) { + assert(!this.red, "Already a number in reduction context"); + assert(this.negative === 0, "red works only with positives"); + return ctx.convertTo(this)._forceRed(ctx); + }; + BN2.prototype.fromRed = function fromRed() { + assert(this.red, "fromRed works only with numbers in reduction context"); + return this.red.convertFrom(this); + }; + BN2.prototype._forceRed = function _forceRed(ctx) { + this.red = ctx; + return this; + }; + BN2.prototype.forceRed = function forceRed(ctx) { + assert(!this.red, "Already a number in reduction context"); + return this._forceRed(ctx); + }; + BN2.prototype.redAdd = function redAdd(num) { + assert(this.red, "redAdd works only with red numbers"); + return this.red.add(this, num); + }; + BN2.prototype.redIAdd = function redIAdd(num) { + assert(this.red, "redIAdd works only with red numbers"); + return this.red.iadd(this, num); + }; + BN2.prototype.redSub = function redSub(num) { + assert(this.red, "redSub works only with red numbers"); + return this.red.sub(this, num); + }; + BN2.prototype.redISub = function redISub(num) { + assert(this.red, "redISub works only with red numbers"); + return this.red.isub(this, num); + }; + BN2.prototype.redShl = function redShl(num) { + assert(this.red, "redShl works only with red numbers"); + return this.red.shl(this, num); + }; + BN2.prototype.redMul = function redMul(num) { + assert(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.mul(this, num); + }; + BN2.prototype.redIMul = function redIMul(num) { + assert(this.red, "redMul works only with red numbers"); + this.red._verify2(this, num); + return this.red.imul(this, num); + }; + BN2.prototype.redSqr = function redSqr() { + assert(this.red, "redSqr works only with red numbers"); + this.red._verify1(this); + return this.red.sqr(this); + }; + BN2.prototype.redISqr = function redISqr() { + assert(this.red, "redISqr works only with red numbers"); + this.red._verify1(this); + return this.red.isqr(this); + }; + BN2.prototype.redSqrt = function redSqrt() { + assert(this.red, "redSqrt works only with red numbers"); + this.red._verify1(this); + return this.red.sqrt(this); + }; + BN2.prototype.redInvm = function redInvm() { + assert(this.red, "redInvm works only with red numbers"); + this.red._verify1(this); + return this.red.invm(this); + }; + BN2.prototype.redNeg = function redNeg() { + assert(this.red, "redNeg works only with red numbers"); + this.red._verify1(this); + return this.red.neg(this); + }; + BN2.prototype.redPow = function redPow(num) { + assert(this.red && !num.red, "redPow(normalNum)"); + this.red._verify1(this); + return this.red.pow(this, num); + }; + var primes = { + k256: null, + p224: null, + p192: null, + p25519: null + }; + function MPrime(name, p) { + this.name = name; + this.p = new BN2(p, 16); + this.n = this.p.bitLength(); + this.k = new BN2(1).iushln(this.n).isub(this.p); + this.tmp = this._tmp(); + } + MPrime.prototype._tmp = function _tmp() { + var tmp = new BN2(null); + tmp.words = new Array(Math.ceil(this.n / 13)); + return tmp; + }; + MPrime.prototype.ireduce = function ireduce(num) { + var r = num; + var rlen; + do { + this.split(r, this.tmp); + r = this.imulK(r); + r = r.iadd(this.tmp); + rlen = r.bitLength(); + }while (rlen > this.n) + var cmp = rlen < this.n ? -1 : r.ucmp(this.p); + if (cmp === 0) { + r.words[0] = 0; + r.length = 1; + } else if (cmp > 0) { + r.isub(this.p); + } else { + if (r.strip !== void 0) { + r.strip(); + } else { + r._strip(); + } + } + return r; + }; + MPrime.prototype.split = function split(input, out) { + input.iushrn(this.n, 0, out); + }; + MPrime.prototype.imulK = function imulK(num) { + return num.imul(this.k); + }; + function K256() { + MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); + } + inherits(K256, MPrime); + K256.prototype.split = function split(input, output) { + var mask = 4194303; + var outLen = Math.min(input.length, 9); + for(var i = 0; i < outLen; i++){ + output.words[i] = input.words[i]; + } + output.length = outLen; + if (input.length <= 9) { + input.words[0] = 0; + input.length = 1; + return; + } + var prev = input.words[9]; + output.words[output.length++] = prev & mask; + for(i = 10; i < input.length; i++){ + var next = input.words[i] | 0; + input.words[i - 10] = (next & mask) << 4 | prev >>> 22; + prev = next; + } + prev >>>= 22; + input.words[i - 10] = prev; + if (prev === 0 && input.length > 10) { + input.length -= 10; + } else { + input.length -= 9; + } + }; + K256.prototype.imulK = function imulK(num) { + num.words[num.length] = 0; + num.words[num.length + 1] = 0; + num.length += 2; + var lo = 0; + for(var i = 0; i < num.length; i++){ + var w = num.words[i] | 0; + lo += w * 977; + num.words[i] = lo & 67108863; + lo = w * 64 + (lo / 67108864 | 0); + } + if (num.words[num.length - 1] === 0) { + num.length--; + if (num.words[num.length - 1] === 0) { + num.length--; + } + } + return num; + }; + function P224() { + MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); + } + inherits(P224, MPrime); + function P192() { + MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); + } + inherits(P192, MPrime); + function P25519() { + MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); + } + inherits(P25519, MPrime); + P25519.prototype.imulK = function imulK(num) { + var carry = 0; + for(var i = 0; i < num.length; i++){ + var hi = (num.words[i] | 0) * 19 + carry; + var lo = hi & 67108863; + hi >>>= 26; + num.words[i] = lo; + carry = hi; + } + if (carry !== 0) { + num.words[num.length++] = carry; + } + return num; + }; + BN2._prime = function prime(name) { + if (primes[name]) return primes[name]; + var prime2; + if (name === "k256") { + prime2 = new K256(); + } else if (name === "p224") { + prime2 = new P224(); + } else if (name === "p192") { + prime2 = new P192(); + } else if (name === "p25519") { + prime2 = new P25519(); + } else { + throw new Error("Unknown prime " + name); + } + primes[name] = prime2; + return prime2; + }; + function Red(m) { + if (typeof m === "string") { + var prime = BN2._prime(m); + this.m = prime.p; + this.prime = prime; + } else { + assert(m.gtn(1), "modulus must be greater than 1"); + this.m = m; + this.prime = null; + } + } + Red.prototype._verify1 = function _verify1(a) { + assert(a.negative === 0, "red works only with positives"); + assert(a.red, "red works only with red numbers"); + }; + Red.prototype._verify2 = function _verify2(a, b) { + assert((a.negative | b.negative) === 0, "red works only with positives"); + assert(a.red && a.red === b.red, "red works only with red numbers"); + }; + Red.prototype.imod = function imod(a) { + if (this.prime) return this.prime.ireduce(a)._forceRed(this); + move(a, a.umod(this.m)._forceRed(this)); + return a; + }; + Red.prototype.neg = function neg(a) { + if (a.isZero()) { + return a.clone(); + } + return this.m.sub(a)._forceRed(this); + }; + Red.prototype.add = function add(a, b) { + this._verify2(a, b); + var res = a.add(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res._forceRed(this); + }; + Red.prototype.iadd = function iadd(a, b) { + this._verify2(a, b); + var res = a.iadd(b); + if (res.cmp(this.m) >= 0) { + res.isub(this.m); + } + return res; + }; + Red.prototype.sub = function sub(a, b) { + this._verify2(a, b); + var res = a.sub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res._forceRed(this); + }; + Red.prototype.isub = function isub(a, b) { + this._verify2(a, b); + var res = a.isub(b); + if (res.cmpn(0) < 0) { + res.iadd(this.m); + } + return res; + }; + Red.prototype.shl = function shl(a, num) { + this._verify1(a); + return this.imod(a.ushln(num)); + }; + Red.prototype.imul = function imul(a, b) { + this._verify2(a, b); + return this.imod(a.imul(b)); + }; + Red.prototype.mul = function mul(a, b) { + this._verify2(a, b); + return this.imod(a.mul(b)); + }; + Red.prototype.isqr = function isqr(a) { + return this.imul(a, a.clone()); + }; + Red.prototype.sqr = function sqr(a) { + return this.mul(a, a); + }; + Red.prototype.sqrt = function sqrt(a) { + if (a.isZero()) return a.clone(); + var mod3 = this.m.andln(3); + assert(mod3 % 2 === 1); + if (mod3 === 3) { + var pow = this.m.add(new BN2(1)).iushrn(2); + return this.pow(a, pow); + } + var q = this.m.subn(1); + var s = 0; + while(!q.isZero() && q.andln(1) === 0){ + s++; + q.iushrn(1); + } + assert(!q.isZero()); + var one = new BN2(1).toRed(this); + var nOne = one.redNeg(); + var lpow = this.m.subn(1).iushrn(1); + var z = this.m.bitLength(); + z = new BN2(2 * z * z).toRed(this); + while(this.pow(z, lpow).cmp(nOne) !== 0){ + z.redIAdd(nOne); + } + var c = this.pow(z, q); + var r = this.pow(a, q.addn(1).iushrn(1)); + var t = this.pow(a, q); + var m = s; + while(t.cmp(one) !== 0){ + var tmp = t; + for(var i = 0; tmp.cmp(one) !== 0; i++){ + tmp = tmp.redSqr(); + } + assert(i < m); + var b = this.pow(c, new BN2(1).iushln(m - i - 1)); + r = r.redMul(b); + c = b.redSqr(); + t = t.redMul(c); + m = i; + } + return r; + }; + Red.prototype.invm = function invm(a) { + var inv = a._invmp(this.m); + if (inv.negative !== 0) { + inv.negative = 0; + return this.imod(inv).redNeg(); + } else { + return this.imod(inv); + } + }; + Red.prototype.pow = function pow(a, num) { + if (num.isZero()) return new BN2(1).toRed(this); + if (num.cmpn(1) === 0) return a.clone(); + var windowSize = 4; + var wnd = new Array(1 << windowSize); + wnd[0] = new BN2(1).toRed(this); + wnd[1] = a; + for(var i = 2; i < wnd.length; i++){ + wnd[i] = this.mul(wnd[i - 1], a); + } + var res = wnd[0]; + var current = 0; + var currentLen = 0; + var start = num.bitLength() % 26; + if (start === 0) { + start = 26; + } + for(i = num.length - 1; i >= 0; i--){ + var word = num.words[i]; + for(var j = start - 1; j >= 0; j--){ + var bit = word >> j & 1; + if (res !== wnd[0]) { + res = this.sqr(res); + } + if (bit === 0 && current === 0) { + currentLen = 0; + continue; + } + current <<= 1; + current |= bit; + currentLen++; + if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; + res = this.mul(res, wnd[current]); + currentLen = 0; + current = 0; + } + start = 26; + } + return res; + }; + Red.prototype.convertTo = function convertTo(num) { + var r = num.umod(this.m); + return r === num ? r.clone() : r; + }; + Red.prototype.convertFrom = function convertFrom(num) { + var res = num.clone(); + res.red = null; + return res; + }; + BN2.mont = function mont(num) { + return new Mont(num); + }; + function Mont(m) { + Red.call(this, m); + this.shift = this.m.bitLength(); + if (this.shift % 26 !== 0) { + this.shift += 26 - this.shift % 26; + } + this.r = new BN2(1).iushln(this.shift); + this.r2 = this.imod(this.r.sqr()); + this.rinv = this.r._invmp(this.m); + this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); + this.minv = this.minv.umod(this.r); + this.minv = this.r.sub(this.minv); + } + inherits(Mont, Red); + Mont.prototype.convertTo = function convertTo(num) { + return this.imod(num.ushln(this.shift)); + }; + Mont.prototype.convertFrom = function convertFrom(num) { + var r = this.imod(num.mul(this.rinv)); + r.red = null; + return r; + }; + Mont.prototype.imul = function imul(a, b) { + if (a.isZero() || b.isZero()) { + a.words[0] = 0; + a.length = 1; + return a; + } + var t = a.imul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.mul = function mul(a, b) { + if (a.isZero() || b.isZero()) return new BN2(0)._forceRed(this); + var t = a.mul(b); + var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); + var u = t.isub(c).iushrn(this.shift); + var res = u; + if (u.cmp(this.m) >= 0) { + res = u.isub(this.m); + } else if (u.cmpn(0) < 0) { + res = u.iadd(this.m); + } + return res._forceRed(this); + }; + Mont.prototype.invm = function invm(a) { + var res = this.imod(a._invmp(this.m).mul(this.r2)); + return res._forceRed(this); + }; + })(module, commonjsGlobal); +}); +bn.BN; +const version = "logger/5.7.0"; +let _permanentCensorErrors = false; +let _censorErrors = false; +const LogLevels = { + debug: 1, + default: 2, + info: 2, + warning: 3, + error: 4, + off: 5 +}; +let _logLevel = LogLevels["default"]; +let _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; +} +const _normalizeError = _checkNormalize(); +var LogLevel; +(function(LogLevel2) { + LogLevel2["DEBUG"] = "DEBUG"; + LogLevel2["INFO"] = "INFO"; + LogLevel2["WARNING"] = "WARNING"; + LogLevel2["ERROR"] = "ERROR"; + LogLevel2["OFF"] = "OFF"; +})(LogLevel || (LogLevel = {})); +var ErrorCode; +(function(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"; +})(ErrorCode || (ErrorCode = {})); +const HEX = "0123456789abcdef"; +class Logger { + constructor(version2){ + Object.defineProperty(this, "version", { + enumerable: true, + value: version2, + 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 ErrorCode.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 ErrorCode.CALL_EXCEPTION: + case ErrorCode.INSUFFICIENT_FUNDS: + case ErrorCode.MISSING_NEW: + case ErrorCode.NONCE_EXPIRED: + case ErrorCode.REPLACEMENT_UNDERPRICED: + case ErrorCode.TRANSACTION_REPLACED: + case ErrorCode.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 (_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(version); + } + 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(version2) { + return new Logger(version2); + } +} +Logger.errors = ErrorCode; +Logger.levels = LogLevel; +const version1 = "bytes/5.7.0"; +const logger2 = new Logger(version1); +function isHexable(value) { + return !!value.toHexString; +} +function addSlice(array) { + if (array.slice) { + return array; + } + array.slice = function() { + const args = Array.prototype.slice.call(arguments); + return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args))); + }; + return array; +} +function isBytesLike(value) { + return isHexString(value) && !(value.length % 2) || isBytes(value); +} +function isInteger(value) { + return typeof value === "number" && value == value && value % 1 === 0; +} +function isBytes(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 arrayify(value, options) { + if (!options) { + options = {}; + } + if (typeof value === "number") { + logger2.checkSafeUint53(value, "invalid arrayify value"); + const result = []; + while(value){ + result.unshift(value & 255); + value = parseInt(String(value / 256)); + } + if (result.length === 0) { + result.push(0); + } + return addSlice(new Uint8Array(result)); + } + if (options.allowMissingPrefix && typeof value === "string" && value.substring(0, 2) !== "0x") { + value = "0x" + value; + } + if (isHexable(value)) { + value = value.toHexString(); + } + if (isHexString(value)) { + let hex = value.substring(2); + if (hex.length % 2) { + if (options.hexPad === "left") { + hex = "0" + hex; + } else if (options.hexPad === "right") { + hex += "0"; + } else { + logger2.throwArgumentError("hex data is odd-length", "value", value); + } + } + const result = []; + for(let i = 0; i < hex.length; i += 2){ + result.push(parseInt(hex.substring(i, i + 2), 16)); + } + return addSlice(new Uint8Array(result)); + } + if (isBytes(value)) { + return addSlice(new Uint8Array(value)); + } + return logger2.throwArgumentError("invalid arrayify value", "value", value); +} +function concat(items) { + const objects = items.map((item)=>arrayify(item)); + const length = objects.reduce((accum, item)=>accum + item.length, 0); + const result = new Uint8Array(length); + objects.reduce((offset, object)=>{ + result.set(object, offset); + return offset + object.length; + }, 0); + return addSlice(result); +} +function stripZeros(value) { + let result = arrayify(value); + if (result.length === 0) { + return result; + } + let start = 0; + while(start < result.length && result[start] === 0){ + start++; + } + if (start) { + result = result.slice(start); + } + return result; +} +function zeroPad(value, length) { + value = arrayify(value); + if (value.length > length) { + logger2.throwArgumentError("value out of range", "value", arguments[0]); + } + const result = new Uint8Array(length); + result.set(value, length - value.length); + return addSlice(result); +} +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; +} +const HexCharacters = "0123456789abcdef"; +function hexlify(value, options) { + if (!options) { + options = {}; + } + if (typeof value === "number") { + logger2.checkSafeUint53(value, "invalid hexlify 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 (isHexable(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 { + logger2.throwArgumentError("hex data is odd-length", "value", value); + } + } + return value.toLowerCase(); + } + if (isBytes(value)) { + let result = "0x"; + for(let i = 0; i < value.length; i++){ + let v = value[i]; + result += HexCharacters[(v & 240) >> 4] + HexCharacters[v & 15]; + } + return result; + } + return logger2.throwArgumentError("invalid hexlify value", "value", value); +} +function hexDataLength(data) { + if (typeof data !== "string") { + data = hexlify(data); + } else if (!isHexString(data) || data.length % 2) { + return null; + } + return (data.length - 2) / 2; +} +function hexDataSlice(data, offset, endOffset) { + if (typeof data !== "string") { + data = hexlify(data); + } else if (!isHexString(data) || data.length % 2) { + logger2.throwArgumentError("invalid hexData", "value", data); + } + offset = 2 + 2 * offset; + if (endOffset != null) { + return "0x" + data.substring(offset, 2 + 2 * endOffset); + } + return "0x" + data.substring(offset); +} +function hexConcat(items) { + let result = "0x"; + items.forEach((item)=>{ + result += hexlify(item).substring(2); + }); + return result; +} +function hexValue(value) { + const trimmed = hexStripZeros(hexlify(value, { + hexPad: "left" + })); + if (trimmed === "0x") { + return "0x0"; + } + return trimmed; +} +function hexStripZeros(value) { + if (typeof value !== "string") { + value = hexlify(value); + } + if (!isHexString(value)) { + logger2.throwArgumentError("invalid hex string", "value", value); + } + value = value.substring(2); + let offset = 0; + while(offset < value.length && value[offset] === "0"){ + offset++; + } + return "0x" + value.substring(offset); +} +function hexZeroPad(value, length) { + if (typeof value !== "string") { + value = hexlify(value); + } else if (!isHexString(value)) { + logger2.throwArgumentError("invalid hex string", "value", value); + } + if (value.length > 2 * length + 2) { + logger2.throwArgumentError("value out of range", "value", arguments[1]); + } + while(value.length < 2 * length + 2){ + value = "0x0" + value.substring(2); + } + return value; +} +function splitSignature(signature) { + const result = { + r: "0x", + s: "0x", + _vs: "0x", + recoveryParam: 0, + v: 0, + yParityAndS: "0x", + compact: "0x" + }; + if (isBytesLike(signature)) { + let bytes = arrayify(signature); + if (bytes.length === 64) { + result.v = 27 + (bytes[32] >> 7); + bytes[32] &= 127; + result.r = hexlify(bytes.slice(0, 32)); + result.s = hexlify(bytes.slice(32, 64)); + } else if (bytes.length === 65) { + result.r = hexlify(bytes.slice(0, 32)); + result.s = hexlify(bytes.slice(32, 64)); + result.v = bytes[64]; + } else { + logger2.throwArgumentError("invalid signature string", "signature", signature); + } + if (result.v < 27) { + if (result.v === 0 || result.v === 1) { + result.v += 27; + } else { + logger2.throwArgumentError("signature invalid v byte", "signature", signature); + } + } + result.recoveryParam = 1 - result.v % 2; + if (result.recoveryParam) { + bytes[32] |= 128; + } + result._vs = hexlify(bytes.slice(32, 64)); + } else { + result.r = signature.r; + result.s = signature.s; + result.v = signature.v; + result.recoveryParam = signature.recoveryParam; + result._vs = signature._vs; + if (result._vs != null) { + const vs2 = zeroPad(arrayify(result._vs), 32); + result._vs = hexlify(vs2); + const recoveryParam = vs2[0] >= 128 ? 1 : 0; + if (result.recoveryParam == null) { + result.recoveryParam = recoveryParam; + } else if (result.recoveryParam !== recoveryParam) { + logger2.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature); + } + vs2[0] &= 127; + const s = hexlify(vs2); + if (result.s == null) { + result.s = s; + } else if (result.s !== s) { + logger2.throwArgumentError("signature v mismatch _vs", "signature", signature); + } + } + if (result.recoveryParam == null) { + if (result.v == null) { + logger2.throwArgumentError("signature missing v and recoveryParam", "signature", signature); + } else if (result.v === 0 || result.v === 1) { + result.recoveryParam = result.v; + } else { + result.recoveryParam = 1 - result.v % 2; + } + } else { + if (result.v == null) { + result.v = 27 + result.recoveryParam; + } else { + const recId = result.v === 0 || result.v === 1 ? result.v : 1 - result.v % 2; + if (result.recoveryParam !== recId) { + logger2.throwArgumentError("signature recoveryParam mismatch v", "signature", signature); + } + } + } + if (result.r == null || !isHexString(result.r)) { + logger2.throwArgumentError("signature missing or invalid r", "signature", signature); + } else { + result.r = hexZeroPad(result.r, 32); + } + if (result.s == null || !isHexString(result.s)) { + logger2.throwArgumentError("signature missing or invalid s", "signature", signature); + } else { + result.s = hexZeroPad(result.s, 32); + } + const vs = arrayify(result.s); + if (vs[0] >= 128) { + logger2.throwArgumentError("signature s out of range", "signature", signature); + } + if (result.recoveryParam) { + vs[0] |= 128; + } + const _vs = hexlify(vs); + if (result._vs) { + if (!isHexString(result._vs)) { + logger2.throwArgumentError("signature invalid _vs", "signature", signature); + } + result._vs = hexZeroPad(result._vs, 32); + } + if (result._vs == null) { + result._vs = _vs; + } else if (result._vs !== _vs) { + logger2.throwArgumentError("signature _vs mismatch v and s", "signature", signature); + } + } + result.yParityAndS = result._vs; + result.compact = result.r + result.yParityAndS.substring(2); + return result; +} +function joinSignature(signature) { + signature = splitSignature(signature); + return hexlify(concat([ + signature.r, + signature.s, + signature.recoveryParam ? "0x1c" : "0x1b" + ])); +} +const version2 = "bignumber/5.7.0"; +var BN = bn.BN; +const logger21 = new Logger(version2); +const _constructorGuard = {}; +function isBigNumberish(value) { + return value != null && (BigNumber.isBigNumber(value) || typeof value === "number" && value % 1 === 0 || typeof value === "string" && !!value.match(/^-?[0-9]+$/) || isHexString(value) || typeof value === "bigint" || isBytes(value)); +} +let _warnedToStringRadix = false; +class BigNumber { + constructor(constructorGuard, hex){ + if (constructorGuard !== _constructorGuard) { + logger21.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 logger21.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; + logger21.warn("BigNumber.toString does not accept any parameters; base-10 is assumed"); + } + } else if (arguments[0] === 16) { + logger21.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", Logger.errors.UNEXPECTED_ARGUMENT, {}); + } else { + logger21.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, toHex(value)); + } + if (value.match(/^-?[0-9]+$/)) { + return new BigNumber(_constructorGuard, toHex(new BN(value))); + } + return logger21.throwArgumentError("invalid BigNumber string", "value", value); + } + if (typeof value === "number") { + if (value % 1) { + throwFault("underflow", "BigNumber.from", value); + } + if (value >= 9007199254740991 || value <= -9007199254740991) { + throwFault("overflow", "BigNumber.from", value); + } + return BigNumber.from(String(value)); + } + const anyValue = value; + if (typeof anyValue === "bigint") { + return BigNumber.from(anyValue.toString()); + } + if (isBytes(anyValue)) { + return BigNumber.from(hexlify(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 (isHexString(hex) || hex[0] === "-" && isHexString(hex.substring(1))) { + return BigNumber.from(hex); + } + } + } + } + return logger21.throwArgumentError("invalid BigNumber value", "value", value); + } + static isBigNumber(value) { + return !!(value && value._isBigNumber); + } +} +function toHex(value) { + if (typeof value !== "string") { + return toHex(value.toString(16)); + } + if (value[0] === "-") { + value = value.substring(1); + if (value[0] === "-") { + logger21.throwArgumentError("invalid hex", "value", value); + } + value = toHex(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(toHex(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 logger21.throwError(fault, Logger.errors.NUMERIC_FAULT, params); +} +function _base36To16(value) { + return new BN(value, 36).toString(16); +} +function _base16To36(value) { + return new BN(value, 16).toString(36); +} +const logger$1 = new Logger(version2); +const _constructorGuard$1 = {}; +const Zero = BigNumber.from(0); +const NegativeOne = BigNumber.from(-1); +function throwFault$1(message, fault, operation, value) { + const params = { + fault, + operation + }; + if (value !== void 0) { + params.value = value; + } + return logger$1.throwError(message, Logger.errors.NUMERIC_FAULT, params); +} +let zeros = "0"; +while(zeros.length < 256){ + zeros += zeros; +} +function getMultiplier(decimals) { + if (typeof decimals !== "number") { + try { + decimals = BigNumber.from(decimals).toNumber(); + } catch (e) {} + } + if (typeof decimals === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) { + return "1" + zeros.substring(0, decimals); + } + return logger$1.throwArgumentError("invalid decimal size", "decimals", decimals); +} +function formatFixed(value, decimals) { + if (decimals == null) { + decimals = 0; + } + const multiplier = getMultiplier(decimals); + value = BigNumber.from(value); + const negative = value.lt(Zero); + if (negative) { + value = value.mul(NegativeOne); + } + let fraction = value.mod(multiplier).toString(); + while(fraction.length < multiplier.length - 1){ + fraction = "0" + fraction; + } + fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; + const whole = value.div(multiplier).toString(); + if (multiplier.length === 1) { + value = whole; + } else { + value = whole + "." + fraction; + } + if (negative) { + value = "-" + value; + } + return value; +} +function parseFixed(value, decimals) { + if (decimals == null) { + decimals = 0; + } + const multiplier = getMultiplier(decimals); + if (typeof value !== "string" || !value.match(/^-?[0-9.]+$/)) { + logger$1.throwArgumentError("invalid decimal value", "value", value); + } + const negative = value.substring(0, 1) === "-"; + if (negative) { + value = value.substring(1); + } + if (value === ".") { + logger$1.throwArgumentError("missing value", "value", value); + } + const comps = value.split("."); + if (comps.length > 2) { + logger$1.throwArgumentError("too many decimal points", "value", value); + } + let whole = comps[0], fraction = comps[1]; + if (!whole) { + whole = "0"; + } + if (!fraction) { + fraction = "0"; + } + while(fraction[fraction.length - 1] === "0"){ + fraction = fraction.substring(0, fraction.length - 1); + } + if (fraction.length > multiplier.length - 1) { + throwFault$1("fractional component exceeds decimals", "underflow", "parseFixed"); + } + if (fraction === "") { + fraction = "0"; + } + while(fraction.length < multiplier.length - 1){ + fraction += "0"; + } + const wholeValue = BigNumber.from(whole); + const fractionValue = BigNumber.from(fraction); + let wei = wholeValue.mul(multiplier).add(fractionValue); + if (negative) { + wei = wei.mul(NegativeOne); + } + return wei; +} +class FixedFormat { + constructor(constructorGuard, signed, width, decimals){ + if (constructorGuard !== _constructorGuard$1) { + logger$1.throwError("cannot use FixedFormat constructor; use FixedFormat.from", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "new FixedFormat" + }); + } + this.signed = signed; + this.width = width; + this.decimals = decimals; + this.name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); + this._multiplier = getMultiplier(decimals); + Object.freeze(this); + } + static from(value) { + if (value instanceof FixedFormat) { + return value; + } + if (typeof value === "number") { + value = `fixed128x${value}`; + } + let signed = true; + let width = 128; + let decimals = 18; + if (typeof value === "string") { + if (value === "fixed") ; + else if (value === "ufixed") { + signed = false; + } else { + const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); + if (!match) { + logger$1.throwArgumentError("invalid fixed format", "format", value); + } + signed = match[1] !== "u"; + width = parseInt(match[2]); + decimals = parseInt(match[3]); + } + } else if (value) { + const check = (key, type, defaultValue)=>{ + if (value[key] == null) { + return defaultValue; + } + if (typeof value[key] !== type) { + logger$1.throwArgumentError("invalid fixed format (" + key + " not " + type + ")", "format." + key, value[key]); + } + return value[key]; + }; + signed = check("signed", "boolean", signed); + width = check("width", "number", width); + decimals = check("decimals", "number", decimals); + } + if (width % 8) { + logger$1.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width); + } + if (decimals > 80) { + logger$1.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals); + } + return new FixedFormat(_constructorGuard$1, signed, width, decimals); + } +} +class FixedNumber { + constructor(constructorGuard, hex, value, format){ + if (constructorGuard !== _constructorGuard$1) { + logger$1.throwError("cannot use FixedNumber constructor; use FixedNumber.from", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "new FixedFormat" + }); + } + this.format = format; + this._hex = hex; + this._value = value; + this._isFixedNumber = true; + Object.freeze(this); + } + _checkFormat(other) { + if (this.format.name !== other.format.name) { + logger$1.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other); + } + } + addUnsafe(other) { + this._checkFormat(other); + const a = parseFixed(this._value, this.format.decimals); + const b = parseFixed(other._value, other.format.decimals); + return FixedNumber.fromValue(a.add(b), this.format.decimals, this.format); + } + subUnsafe(other) { + this._checkFormat(other); + const a = parseFixed(this._value, this.format.decimals); + const b = parseFixed(other._value, other.format.decimals); + return FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format); + } + mulUnsafe(other) { + this._checkFormat(other); + const a = parseFixed(this._value, this.format.decimals); + const b = parseFixed(other._value, other.format.decimals); + return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format); + } + divUnsafe(other) { + this._checkFormat(other); + const a = parseFixed(this._value, this.format.decimals); + const b = parseFixed(other._value, other.format.decimals); + return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format); + } + floor() { + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + let result = FixedNumber.from(comps[0], this.format); + const hasFraction = !comps[1].match(/^(0*)$/); + if (this.isNegative() && hasFraction) { + result = result.subUnsafe(ONE.toFormat(result.format)); + } + return result; + } + ceiling() { + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + let result = FixedNumber.from(comps[0], this.format); + const hasFraction = !comps[1].match(/^(0*)$/); + if (!this.isNegative() && hasFraction) { + result = result.addUnsafe(ONE.toFormat(result.format)); + } + return result; + } + round(decimals) { + if (decimals == null) { + decimals = 0; + } + const comps = this.toString().split("."); + if (comps.length === 1) { + comps.push("0"); + } + if (decimals < 0 || decimals > 80 || decimals % 1) { + logger$1.throwArgumentError("invalid decimal count", "decimals", decimals); + } + if (comps[1].length <= decimals) { + return this; + } + const factor = FixedNumber.from("1" + zeros.substring(0, decimals), this.format); + const bump = BUMP.toFormat(this.format); + return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor); + } + isZero() { + return this._value === "0.0" || this._value === "0"; + } + isNegative() { + return this._value[0] === "-"; + } + toString() { + return this._value; + } + toHexString(width) { + if (width == null) { + return this._hex; + } + if (width % 8) { + logger$1.throwArgumentError("invalid byte width", "width", width); + } + const hex = BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString(); + return hexZeroPad(hex, width / 8); + } + toUnsafeFloat() { + return parseFloat(this.toString()); + } + toFormat(format) { + return FixedNumber.fromString(this._value, format); + } + static fromValue(value, decimals, format) { + if (format == null && decimals != null && !isBigNumberish(decimals)) { + format = decimals; + decimals = null; + } + if (decimals == null) { + decimals = 0; + } + if (format == null) { + format = "fixed"; + } + return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format)); + } + static fromString(value, format) { + if (format == null) { + format = "fixed"; + } + const fixedFormat = FixedFormat.from(format); + const numeric = parseFixed(value, fixedFormat.decimals); + if (!fixedFormat.signed && numeric.lt(Zero)) { + throwFault$1("unsigned value cannot be negative", "overflow", "value", value); + } + let hex = null; + if (fixedFormat.signed) { + hex = numeric.toTwos(fixedFormat.width).toHexString(); + } else { + hex = numeric.toHexString(); + hex = hexZeroPad(hex, fixedFormat.width / 8); + } + const decimal = formatFixed(numeric, fixedFormat.decimals); + return new FixedNumber(_constructorGuard$1, hex, decimal, fixedFormat); + } + static fromBytes(value, format) { + if (format == null) { + format = "fixed"; + } + const fixedFormat = FixedFormat.from(format); + if (arrayify(value).length > fixedFormat.width / 8) { + throw new Error("overflow"); + } + let numeric = BigNumber.from(value); + if (fixedFormat.signed) { + numeric = numeric.fromTwos(fixedFormat.width); + } + const hex = numeric.toTwos((fixedFormat.signed ? 0 : 1) + fixedFormat.width).toHexString(); + const decimal = formatFixed(numeric, fixedFormat.decimals); + return new FixedNumber(_constructorGuard$1, hex, decimal, fixedFormat); + } + static from(value, format) { + if (typeof value === "string") { + return FixedNumber.fromString(value, format); + } + if (isBytes(value)) { + return FixedNumber.fromBytes(value, format); + } + try { + return FixedNumber.fromValue(value, 0, format); + } catch (error) { + if (error.code !== Logger.errors.INVALID_ARGUMENT) { + throw error; + } + } + return logger$1.throwArgumentError("invalid FixedNumber value", "value", value); + } + static isFixedNumber(value) { + return !!(value && value._isFixedNumber); + } +} +const ONE = FixedNumber.from(1); +const BUMP = FixedNumber.from("0.5"); +const version3 = "properties/5.7.0"; +var __awaiter = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger22 = new Logger(version3); +function defineReadOnly(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true, + value, + writable: false + }); +} +function getStatic(ctor, key) { + for(let i = 0; i < 32; i++){ + if (ctor[key]) { + return ctor[key]; + } + if (!ctor.prototype || typeof ctor.prototype !== "object") { + break; + } + ctor = Object.getPrototypeOf(ctor.prototype).constructor; + } + return null; +} +function resolveProperties(object) { + return __awaiter(this, void 0, void 0, function*() { + const promises = Object.keys(object).map((key)=>{ + const value = object[key]; + return Promise.resolve(value).then((v)=>({ + key, + value: v + })); + }); + const results = yield Promise.all(promises); + return results.reduce((accum, result)=>{ + accum[result.key] = result.value; + return accum; + }, {}); + }); +} +function checkProperties(object, properties) { + if (!object || typeof object !== "object") { + logger22.throwArgumentError("invalid object", "object", object); + } + Object.keys(object).forEach((key)=>{ + if (!properties[key]) { + logger22.throwArgumentError("invalid object key - " + key, "transaction:" + key, object); + } + }); +} +function shallowCopy(object) { + const result = {}; + for(const key in object){ + result[key] = object[key]; + } + return result; +} +const opaque = { + bigint: true, + boolean: true, + function: true, + number: true, + string: true +}; +function _isFrozen(object) { + if (object === void 0 || object === null || opaque[typeof object]) { + return true; + } + if (Array.isArray(object) || typeof object === "object") { + if (!Object.isFrozen(object)) { + return false; + } + const keys = Object.keys(object); + for(let i = 0; i < keys.length; i++){ + let value = null; + try { + value = object[keys[i]]; + } catch (error) { + continue; + } + if (!_isFrozen(value)) { + return false; + } + } + return true; + } + return logger22.throwArgumentError(`Cannot deepCopy ${typeof object}`, "object", object); +} +function _deepCopy(object) { + if (_isFrozen(object)) { + return object; + } + if (Array.isArray(object)) { + return Object.freeze(object.map((item)=>deepCopy(item))); + } + if (typeof object === "object") { + const result = {}; + for(const key in object){ + const value = object[key]; + if (value === void 0) { + continue; + } + defineReadOnly(result, key, deepCopy(value)); + } + return result; + } + return logger22.throwArgumentError(`Cannot deepCopy ${typeof object}`, "object", object); +} +function deepCopy(object) { + return _deepCopy(object); +} +class Description { + constructor(info){ + for(const key in info){ + this[key] = deepCopy(info[key]); + } + } +} +function defaultSetTimout() { + throw new Error("setTimeout has not been defined"); +} +function defaultClearTimeout() { + throw new Error("clearTimeout has not been defined"); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +var globalContext; +if (typeof window !== "undefined") { + globalContext = window; +} else if (typeof self !== "undefined") { + globalContext = self; +} else { + globalContext = {}; +} +if (typeof globalContext.setTimeout === "function") { + cachedSetTimeout = setTimeout; +} +if (typeof globalContext.clearTimeout === "function") { + cachedClearTimeout = clearTimeout; +} +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + return setTimeout(fun, 0); + } + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + return cachedSetTimeout.call(null, fun, 0); + } catch (e2) { + return cachedSetTimeout.call(this, fun, 0); + } + } +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + return clearTimeout(marker); + } + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + return cachedClearTimeout(marker); + } catch (e) { + try { + return cachedClearTimeout.call(null, marker); + } catch (e2) { + return cachedClearTimeout.call(this, marker); + } + } +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while(len){ + currentQueue = queue; + queue = []; + while(++queueIndex < len){ + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for(var i = 1; i < arguments.length; i++){ + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function() { + this.fun.apply(null, this.array); +}; +var title = "browser"; +var platform = "browser"; +var browser = true; +var argv = []; +var version4 = ""; +var versions = {}; +var release = {}; +var config = {}; +function noop() {} +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; +function binding(name) { + throw new Error("process.binding is not supported"); +} +function cwd() { + return "/"; +} +function chdir(dir) { + throw new Error("process.chdir is not supported"); +} +function umask() { + return 0; +} +var performance = globalContext.performance || {}; +var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function() { + return new Date().getTime(); +}; +function hrtime(previousTimestamp) { + var clocktime = performanceNow.call(performance) * 1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor(clocktime % 1 * 1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds < 0) { + seconds--; + nanoseconds += 1e9; + } + } + return [ + seconds, + nanoseconds + ]; +} +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1e3; +} +var process = { + nextTick, + title, + browser, + env: { + NODE_ENV: "production" + }, + argv, + version: version4, + versions, + on, + addListener, + once, + off, + removeListener, + removeAllListeners, + emit, + binding, + cwd, + chdir, + umask, + hrtime, + platform, + release, + config, + uptime +}; +var commonjsGlobal1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; +function createCommonjsModule1(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function(path, base) { + return commonjsRequire1(path, base === void 0 || base === null ? module.path : base); + } + }, fn(module, module.exports), module.exports; +} +function commonjsRequire1() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); +} +var sha3 = createCommonjsModule1(function(module) { + (function() { + var INPUT_ERROR = "input is invalid type"; + var FINALIZE_ERROR = "finalize already called"; + var WINDOW = typeof window === "object"; + var root = WINDOW ? window : {}; + if (root.JS_SHA3_NO_WINDOW) { + WINDOW = false; + } + var WEB_WORKER = !WINDOW && typeof self === "object"; + var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node; + if (NODE_JS) { + root = commonjsGlobal1; + } else if (WEB_WORKER) { + root = self; + } + var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && true && module.exports; + var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined"; + var HEX_CHARS = "0123456789abcdef".split(""); + var SHAKE_PADDING = [ + 31, + 7936, + 2031616, + 520093696 + ]; + var CSHAKE_PADDING = [ + 4, + 1024, + 262144, + 67108864 + ]; + var KECCAK_PADDING = [ + 1, + 256, + 65536, + 16777216 + ]; + var PADDING = [ + 6, + 1536, + 393216, + 100663296 + ]; + var SHIFT = [ + 0, + 8, + 16, + 24 + ]; + var RC = [ + 1, + 0, + 32898, + 0, + 32906, + 2147483648, + 2147516416, + 2147483648, + 32907, + 0, + 2147483649, + 0, + 2147516545, + 2147483648, + 32777, + 2147483648, + 138, + 0, + 136, + 0, + 2147516425, + 0, + 2147483658, + 0, + 2147516555, + 0, + 139, + 2147483648, + 32905, + 2147483648, + 32771, + 2147483648, + 32770, + 2147483648, + 128, + 2147483648, + 32778, + 0, + 2147483658, + 2147483648, + 2147516545, + 2147483648, + 32896, + 2147483648, + 2147483649, + 0, + 2147516424, + 2147483648 + ]; + var BITS = [ + 224, + 256, + 384, + 512 + ]; + var SHAKE_BITS = [ + 128, + 256 + ]; + var OUTPUT_TYPES = [ + "hex", + "buffer", + "arrayBuffer", + "array", + "digest" + ]; + var CSHAKE_BYTEPAD = { + "128": 168, + "256": 136 + }; + if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { + Array.isArray = function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + } + if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { + ArrayBuffer.isView = function(obj) { + return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer; + }; + } + var createOutputMethod = function(bits2, padding, outputType) { + return function(message) { + return new Keccak(bits2, padding, bits2).update(message)[outputType](); + }; + }; + var createShakeOutputMethod = function(bits2, padding, outputType) { + return function(message, outputBits) { + return new Keccak(bits2, padding, outputBits).update(message)[outputType](); + }; + }; + var createCshakeOutputMethod = function(bits2, padding, outputType) { + return function(message, outputBits, n, s) { + return methods["cshake" + bits2].update(message, outputBits, n, s)[outputType](); + }; + }; + var createKmacOutputMethod = function(bits2, padding, outputType) { + return function(key, message, outputBits, s) { + return methods["kmac" + bits2].update(key, message, outputBits, s)[outputType](); + }; + }; + var createOutputMethods = function(method, createMethod2, bits2, padding) { + for(var i2 = 0; i2 < OUTPUT_TYPES.length; ++i2){ + var type = OUTPUT_TYPES[i2]; + method[type] = createMethod2(bits2, padding, type); + } + return method; + }; + var createMethod = function(bits2, padding) { + var method = createOutputMethod(bits2, padding, "hex"); + method.create = function() { + return new Keccak(bits2, padding, bits2); + }; + method.update = function(message) { + return method.create().update(message); + }; + return createOutputMethods(method, createOutputMethod, bits2, padding); + }; + var createShakeMethod = function(bits2, padding) { + var method = createShakeOutputMethod(bits2, padding, "hex"); + method.create = function(outputBits) { + return new Keccak(bits2, padding, outputBits); + }; + method.update = function(message, outputBits) { + return method.create(outputBits).update(message); + }; + return createOutputMethods(method, createShakeOutputMethod, bits2, padding); + }; + var createCshakeMethod = function(bits2, padding) { + var w = CSHAKE_BYTEPAD[bits2]; + var method = createCshakeOutputMethod(bits2, padding, "hex"); + method.create = function(outputBits, n, s) { + if (!n && !s) { + return methods["shake" + bits2].create(outputBits); + } else { + return new Keccak(bits2, padding, outputBits).bytepad([ + n, + s + ], w); + } + }; + method.update = function(message, outputBits, n, s) { + return method.create(outputBits, n, s).update(message); + }; + return createOutputMethods(method, createCshakeOutputMethod, bits2, padding); + }; + var createKmacMethod = function(bits2, padding) { + var w = CSHAKE_BYTEPAD[bits2]; + var method = createKmacOutputMethod(bits2, padding, "hex"); + method.create = function(key, outputBits, s) { + return new Kmac(bits2, padding, outputBits).bytepad([ + "KMAC", + s + ], w).bytepad([ + key + ], w); + }; + method.update = function(key, message, outputBits, s) { + return method.create(key, outputBits, s).update(message); + }; + return createOutputMethods(method, createKmacOutputMethod, bits2, padding); + }; + var algorithms = [ + { + name: "keccak", + padding: KECCAK_PADDING, + bits: BITS, + createMethod + }, + { + name: "sha3", + padding: PADDING, + bits: BITS, + createMethod + }, + { + name: "shake", + padding: SHAKE_PADDING, + bits: SHAKE_BITS, + createMethod: createShakeMethod + }, + { + name: "cshake", + padding: CSHAKE_PADDING, + bits: SHAKE_BITS, + createMethod: createCshakeMethod + }, + { + name: "kmac", + padding: CSHAKE_PADDING, + bits: SHAKE_BITS, + createMethod: createKmacMethod + } + ]; + var methods = {}, methodNames = []; + for(var i = 0; i < algorithms.length; ++i){ + var algorithm = algorithms[i]; + var bits = algorithm.bits; + for(var j = 0; j < bits.length; ++j){ + var methodName = algorithm.name + "_" + bits[j]; + methodNames.push(methodName); + methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); + if (algorithm.name !== "sha3") { + var newMethodName = algorithm.name + bits[j]; + methodNames.push(newMethodName); + methods[newMethodName] = methods[methodName]; + } + } + } + function Keccak(bits2, padding, outputBits) { + this.blocks = []; + this.s = []; + this.padding = padding; + this.outputBits = outputBits; + this.reset = true; + this.finalized = false; + this.block = 0; + this.start = 0; + this.blockCount = 1600 - (bits2 << 1) >> 5; + this.byteCount = this.blockCount << 2; + this.outputBlocks = outputBits >> 5; + this.extraBytes = (outputBits & 31) >> 3; + for(var i2 = 0; i2 < 50; ++i2){ + this.s[i2] = 0; + } + } + Keccak.prototype.update = function(message) { + if (this.finalized) { + throw new Error(FINALIZE_ERROR); + } + var notString, type = typeof message; + if (type !== "string") { + if (type === "object") { + if (message === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var blocks = this.blocks, byteCount = this.byteCount, length = message.length, blockCount = this.blockCount, index = 0, s = this.s, i2, code; + while(index < length){ + if (this.reset) { + this.reset = false; + blocks[0] = this.block; + for(i2 = 1; i2 < blockCount + 1; ++i2){ + blocks[i2] = 0; + } + } + if (notString) { + for(i2 = this.start; index < length && i2 < byteCount; ++index){ + blocks[i2 >> 2] |= message[index] << SHIFT[i2++ & 3]; + } + } else { + for(i2 = this.start; index < length && i2 < byteCount; ++index){ + code = message.charCodeAt(index); + if (code < 128) { + blocks[i2 >> 2] |= code << SHIFT[i2++ & 3]; + } else if (code < 2048) { + blocks[i2 >> 2] |= (192 | code >> 6) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; + } else if (code < 55296 || code >= 57344) { + blocks[i2 >> 2] |= (224 | code >> 12) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; + } else { + code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); + blocks[i2 >> 2] |= (240 | code >> 18) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code >> 12 & 63) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; + } + } + } + this.lastByteIndex = i2; + if (i2 >= byteCount) { + this.start = i2 - byteCount; + this.block = blocks[blockCount]; + for(i2 = 0; i2 < blockCount; ++i2){ + s[i2] ^= blocks[i2]; + } + f(s); + this.reset = true; + } else { + this.start = i2; + } + } + return this; + }; + Keccak.prototype.encode = function(x, right) { + var o = x & 255, n = 1; + var bytes = [ + o + ]; + x = x >> 8; + o = x & 255; + while(o > 0){ + bytes.unshift(o); + x = x >> 8; + o = x & 255; + ++n; + } + if (right) { + bytes.push(n); + } else { + bytes.unshift(n); + } + this.update(bytes); + return bytes.length; + }; + Keccak.prototype.encodeString = function(str) { + var notString, type = typeof str; + if (type !== "string") { + if (type === "object") { + if (str === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) { + str = new Uint8Array(str); + } else if (!Array.isArray(str)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var bytes = 0, length = str.length; + if (notString) { + bytes = length; + } else { + for(var i2 = 0; i2 < str.length; ++i2){ + var code = str.charCodeAt(i2); + if (code < 128) { + bytes += 1; + } else if (code < 2048) { + bytes += 2; + } else if (code < 55296 || code >= 57344) { + bytes += 3; + } else { + code = 65536 + ((code & 1023) << 10 | str.charCodeAt(++i2) & 1023); + bytes += 4; + } + } + } + bytes += this.encode(bytes * 8); + this.update(str); + return bytes; + }; + Keccak.prototype.bytepad = function(strs, w) { + var bytes = this.encode(w); + for(var i2 = 0; i2 < strs.length; ++i2){ + bytes += this.encodeString(strs[i2]); + } + var paddingBytes = w - bytes % w; + var zeros = []; + zeros.length = paddingBytes; + this.update(zeros); + return this; + }; + Keccak.prototype.finalize = function() { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i2 = this.lastByteIndex, blockCount = this.blockCount, s = this.s; + blocks[i2 >> 2] |= this.padding[i2 & 3]; + if (this.lastByteIndex === this.byteCount) { + blocks[0] = blocks[blockCount]; + for(i2 = 1; i2 < blockCount + 1; ++i2){ + blocks[i2] = 0; + } + } + blocks[blockCount - 1] |= 2147483648; + for(i2 = 0; i2 < blockCount; ++i2){ + s[i2] ^= blocks[i2]; + } + f(s); + }; + Keccak.prototype.toString = Keccak.prototype.hex = function() { + this.finalize(); + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; + var hex = "", block; + while(j2 < outputBlocks){ + for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ + block = s[i2]; + hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15] + HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15] + HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15] + HEX_CHARS[block >> 28 & 15] + HEX_CHARS[block >> 24 & 15]; + } + if (j2 % blockCount === 0) { + f(s); + i2 = 0; + } + } + if (extraBytes) { + block = s[i2]; + hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15]; + if (extraBytes > 1) { + hex += HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15]; + } + if (extraBytes > 2) { + hex += HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15]; + } + } + return hex; + }; + Keccak.prototype.arrayBuffer = function() { + this.finalize(); + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; + var bytes = this.outputBits >> 3; + var buffer; + if (extraBytes) { + buffer = new ArrayBuffer(outputBlocks + 1 << 2); + } else { + buffer = new ArrayBuffer(bytes); + } + var array = new Uint32Array(buffer); + while(j2 < outputBlocks){ + for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ + array[j2] = s[i2]; + } + if (j2 % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + array[i2] = s[i2]; + buffer = buffer.slice(0, bytes); + } + return buffer; + }; + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; + Keccak.prototype.digest = Keccak.prototype.array = function() { + this.finalize(); + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; + var array = [], offset, block; + while(j2 < outputBlocks){ + for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ + offset = j2 << 2; + block = s[i2]; + array[offset] = block & 255; + array[offset + 1] = block >> 8 & 255; + array[offset + 2] = block >> 16 & 255; + array[offset + 3] = block >> 24 & 255; + } + if (j2 % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + offset = j2 << 2; + block = s[i2]; + array[offset] = block & 255; + if (extraBytes > 1) { + array[offset + 1] = block >> 8 & 255; + } + if (extraBytes > 2) { + array[offset + 2] = block >> 16 & 255; + } + } + return array; + }; + function Kmac(bits2, padding, outputBits) { + Keccak.call(this, bits2, padding, outputBits); + } + Kmac.prototype = new Keccak(); + Kmac.prototype.finalize = function() { + this.encode(this.outputBits, true); + return Keccak.prototype.finalize.call(this); + }; + var f = function(s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + for(n = 0; n < 48; n += 2){ + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + h = c8 ^ (c2 << 1 | c3 >>> 31); + l = c9 ^ (c3 << 1 | c2 >>> 31); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ (c4 << 1 | c5 >>> 31); + l = c1 ^ (c5 << 1 | c4 >>> 31); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ (c6 << 1 | c7 >>> 31); + l = c3 ^ (c7 << 1 | c6 >>> 31); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ (c8 << 1 | c9 >>> 31); + l = c5 ^ (c9 << 1 | c8 >>> 31); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ (c0 << 1 | c1 >>> 31); + l = c7 ^ (c1 << 1 | c0 >>> 31); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + b0 = s[0]; + b1 = s[1]; + b32 = s[11] << 4 | s[10] >>> 28; + b33 = s[10] << 4 | s[11] >>> 28; + b14 = s[20] << 3 | s[21] >>> 29; + b15 = s[21] << 3 | s[20] >>> 29; + b46 = s[31] << 9 | s[30] >>> 23; + b47 = s[30] << 9 | s[31] >>> 23; + b28 = s[40] << 18 | s[41] >>> 14; + b29 = s[41] << 18 | s[40] >>> 14; + b20 = s[2] << 1 | s[3] >>> 31; + b21 = s[3] << 1 | s[2] >>> 31; + b2 = s[13] << 12 | s[12] >>> 20; + b3 = s[12] << 12 | s[13] >>> 20; + b34 = s[22] << 10 | s[23] >>> 22; + b35 = s[23] << 10 | s[22] >>> 22; + b16 = s[33] << 13 | s[32] >>> 19; + b17 = s[32] << 13 | s[33] >>> 19; + b48 = s[42] << 2 | s[43] >>> 30; + b49 = s[43] << 2 | s[42] >>> 30; + b40 = s[5] << 30 | s[4] >>> 2; + b41 = s[4] << 30 | s[5] >>> 2; + b22 = s[14] << 6 | s[15] >>> 26; + b23 = s[15] << 6 | s[14] >>> 26; + b4 = s[25] << 11 | s[24] >>> 21; + b5 = s[24] << 11 | s[25] >>> 21; + b36 = s[34] << 15 | s[35] >>> 17; + b37 = s[35] << 15 | s[34] >>> 17; + b18 = s[45] << 29 | s[44] >>> 3; + b19 = s[44] << 29 | s[45] >>> 3; + b10 = s[6] << 28 | s[7] >>> 4; + b11 = s[7] << 28 | s[6] >>> 4; + b42 = s[17] << 23 | s[16] >>> 9; + b43 = s[16] << 23 | s[17] >>> 9; + b24 = s[26] << 25 | s[27] >>> 7; + b25 = s[27] << 25 | s[26] >>> 7; + b6 = s[36] << 21 | s[37] >>> 11; + b7 = s[37] << 21 | s[36] >>> 11; + b38 = s[47] << 24 | s[46] >>> 8; + b39 = s[46] << 24 | s[47] >>> 8; + b30 = s[8] << 27 | s[9] >>> 5; + b31 = s[9] << 27 | s[8] >>> 5; + b12 = s[18] << 20 | s[19] >>> 12; + b13 = s[19] << 20 | s[18] >>> 12; + b44 = s[29] << 7 | s[28] >>> 25; + b45 = s[28] << 7 | s[29] >>> 25; + b26 = s[38] << 8 | s[39] >>> 24; + b27 = s[39] << 8 | s[38] >>> 24; + b8 = s[48] << 14 | s[49] >>> 18; + b9 = s[49] << 14 | s[48] >>> 18; + s[0] = b0 ^ ~b2 & b4; + s[1] = b1 ^ ~b3 & b5; + s[10] = b10 ^ ~b12 & b14; + s[11] = b11 ^ ~b13 & b15; + s[20] = b20 ^ ~b22 & b24; + s[21] = b21 ^ ~b23 & b25; + s[30] = b30 ^ ~b32 & b34; + s[31] = b31 ^ ~b33 & b35; + s[40] = b40 ^ ~b42 & b44; + s[41] = b41 ^ ~b43 & b45; + s[2] = b2 ^ ~b4 & b6; + s[3] = b3 ^ ~b5 & b7; + s[12] = b12 ^ ~b14 & b16; + s[13] = b13 ^ ~b15 & b17; + s[22] = b22 ^ ~b24 & b26; + s[23] = b23 ^ ~b25 & b27; + s[32] = b32 ^ ~b34 & b36; + s[33] = b33 ^ ~b35 & b37; + s[42] = b42 ^ ~b44 & b46; + s[43] = b43 ^ ~b45 & b47; + s[4] = b4 ^ ~b6 & b8; + s[5] = b5 ^ ~b7 & b9; + s[14] = b14 ^ ~b16 & b18; + s[15] = b15 ^ ~b17 & b19; + s[24] = b24 ^ ~b26 & b28; + s[25] = b25 ^ ~b27 & b29; + s[34] = b34 ^ ~b36 & b38; + s[35] = b35 ^ ~b37 & b39; + s[44] = b44 ^ ~b46 & b48; + s[45] = b45 ^ ~b47 & b49; + s[6] = b6 ^ ~b8 & b0; + s[7] = b7 ^ ~b9 & b1; + s[16] = b16 ^ ~b18 & b10; + s[17] = b17 ^ ~b19 & b11; + s[26] = b26 ^ ~b28 & b20; + s[27] = b27 ^ ~b29 & b21; + s[36] = b36 ^ ~b38 & b30; + s[37] = b37 ^ ~b39 & b31; + s[46] = b46 ^ ~b48 & b40; + s[47] = b47 ^ ~b49 & b41; + s[8] = b8 ^ ~b0 & b2; + s[9] = b9 ^ ~b1 & b3; + s[18] = b18 ^ ~b10 & b12; + s[19] = b19 ^ ~b11 & b13; + s[28] = b28 ^ ~b20 & b22; + s[29] = b29 ^ ~b21 & b23; + s[38] = b38 ^ ~b30 & b32; + s[39] = b39 ^ ~b31 & b33; + s[48] = b48 ^ ~b40 & b42; + s[49] = b49 ^ ~b41 & b43; + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + if (COMMON_JS) { + module.exports = methods; + } else { + for(i = 0; i < methodNames.length; ++i){ + root[methodNames[i]] = methods[methodNames[i]]; + } + } + })(); +}); +sha3.cshake128; +sha3.cshake256; +sha3.cshake_128; +sha3.cshake_256; +sha3.keccak224; +sha3.keccak256; +sha3.keccak384; +sha3.keccak512; +sha3.keccak_224; +sha3.keccak_256; +sha3.keccak_384; +sha3.keccak_512; +sha3.kmac128; +sha3.kmac256; +sha3.kmac_128; +sha3.kmac_256; +sha3.sha3_224; +sha3.sha3_256; +sha3.sha3_384; +sha3.sha3_512; +sha3.shake128; +sha3.shake256; +sha3.shake_128; +sha3.shake_256; +function keccak256(data) { + return "0x" + sha3.keccak_256(arrayify(data)); +} +const version5 = "rlp/5.7.0"; +const logger23 = new Logger(version5); +function arrayifyInteger(value) { + const result = []; + while(value){ + result.unshift(value & 255); + value >>= 8; + } + return result; +} +function unarrayifyInteger(data, offset, length) { + let result = 0; + for(let i = 0; i < length; i++){ + result = result * 256 + data[offset + i]; + } + return result; +} +function _encode(object) { + if (Array.isArray(object)) { + let payload = []; + object.forEach(function(child) { + payload = payload.concat(_encode(child)); + }); + if (payload.length <= 55) { + payload.unshift(192 + payload.length); + return payload; + } + const length2 = arrayifyInteger(payload.length); + length2.unshift(247 + length2.length); + return length2.concat(payload); + } + if (!isBytesLike(object)) { + logger23.throwArgumentError("RLP object must be BytesLike", "object", object); + } + const data = Array.prototype.slice.call(arrayify(object)); + if (data.length === 1 && data[0] <= 127) { + return data; + } else if (data.length <= 55) { + data.unshift(128 + data.length); + return data; + } + const length = arrayifyInteger(data.length); + length.unshift(183 + length.length); + return length.concat(data); +} +function encode(object) { + return hexlify(_encode(object)); +} +function _decodeChildren(data, offset, childOffset, length) { + const result = []; + while(childOffset < offset + 1 + length){ + const decoded = _decode(data, childOffset); + result.push(decoded.result); + childOffset += decoded.consumed; + if (childOffset > offset + 1 + length) { + logger23.throwError("child data too short", Logger.errors.BUFFER_OVERRUN, {}); + } + } + return { + consumed: 1 + length, + result + }; +} +function _decode(data, offset) { + if (data.length === 0) { + logger23.throwError("data too short", Logger.errors.BUFFER_OVERRUN, {}); + } + if (data[offset] >= 248) { + const lengthLength = data[offset] - 247; + if (offset + 1 + lengthLength > data.length) { + logger23.throwError("data short segment too short", Logger.errors.BUFFER_OVERRUN, {}); + } + const length = unarrayifyInteger(data, offset + 1, lengthLength); + if (offset + 1 + lengthLength + length > data.length) { + logger23.throwError("data long segment too short", Logger.errors.BUFFER_OVERRUN, {}); + } + return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); + } else if (data[offset] >= 192) { + const length = data[offset] - 192; + if (offset + 1 + length > data.length) { + logger23.throwError("data array too short", Logger.errors.BUFFER_OVERRUN, {}); + } + return _decodeChildren(data, offset, offset + 1, length); + } else if (data[offset] >= 184) { + const lengthLength = data[offset] - 183; + if (offset + 1 + lengthLength > data.length) { + logger23.throwError("data array too short", Logger.errors.BUFFER_OVERRUN, {}); + } + const length = unarrayifyInteger(data, offset + 1, lengthLength); + if (offset + 1 + lengthLength + length > data.length) { + logger23.throwError("data array too short", Logger.errors.BUFFER_OVERRUN, {}); + } + const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); + return { + consumed: 1 + lengthLength + length, + result + }; + } else if (data[offset] >= 128) { + const length = data[offset] - 128; + if (offset + 1 + length > data.length) { + logger23.throwError("data too short", Logger.errors.BUFFER_OVERRUN, {}); + } + const result = hexlify(data.slice(offset + 1, offset + 1 + length)); + return { + consumed: 1 + length, + result + }; + } + return { + consumed: 1, + result: hexlify(data[offset]) + }; +} +function decode1(data) { + const bytes2 = arrayify(data); + const decoded = _decode(bytes2, 0); + if (decoded.consumed !== bytes2.length) { + logger23.throwArgumentError("invalid rlp data", "data", data); + } + return decoded.result; +} +const mod = function() { + return { + decode: decode1, + encode: encode, + default: null + }; +}(); +const version6 = "address/5.7.0"; +const logger24 = new Logger(version6); +function getChecksumAddress(address) { + if (!isHexString(address, 20)) { + logger24.throwArgumentError("invalid address", "address", address); + } + address = address.toLowerCase(); + const chars = address.substring(2).split(""); + const expanded = new Uint8Array(40); + for(let i = 0; i < 40; i++){ + expanded[i] = chars[i].charCodeAt(0); + } + const hashed = arrayify(keccak256(expanded)); + for(let i = 0; i < 40; i += 2){ + if (hashed[i >> 1] >> 4 >= 8) { + chars[i] = chars[i].toUpperCase(); + } + if ((hashed[i >> 1] & 15) >= 8) { + chars[i + 1] = chars[i + 1].toUpperCase(); + } + } + return "0x" + chars.join(""); +} +function log10(x) { + if (Math.log10) { + return Math.log10(x); + } + return Math.log(x) / Math.LN10; +} +const ibanLookup = {}; +for(let i = 0; i < 10; i++){ + ibanLookup[String(i)] = String(i); +} +for(let i = 0; i < 26; i++){ + ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); +} +const safeDigits = Math.floor(log10(9007199254740991)); +function ibanChecksum(address) { + address = address.toUpperCase(); + address = address.substring(4) + address.substring(0, 2) + "00"; + let expanded = address.split("").map((c)=>{ + return ibanLookup[c]; + }).join(""); + while(expanded.length >= safeDigits){ + let block = expanded.substring(0, safeDigits); + expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); + } + let checksum = String(98 - parseInt(expanded, 10) % 97); + while(checksum.length < 2){ + checksum = "0" + checksum; + } + return checksum; +} +function getAddress(address) { + let result = null; + if (typeof address !== "string") { + logger24.throwArgumentError("invalid address", "address", address); + } + if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { + if (address.substring(0, 2) !== "0x") { + address = "0x" + address; + } + result = getChecksumAddress(address); + if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { + logger24.throwArgumentError("bad address checksum", "address", address); + } + } else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + if (address.substring(2, 4) !== ibanChecksum(address)) { + logger24.throwArgumentError("bad icap checksum", "address", address); + } + result = _base36To16(address.substring(4)); + while(result.length < 40){ + result = "0" + result; + } + result = getChecksumAddress("0x" + result); + } else { + logger24.throwArgumentError("invalid address", "address", address); + } + return result; +} +function isAddress(address) { + try { + getAddress(address); + return true; + } catch (error) {} + return false; +} +function getIcapAddress(address) { + let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase(); + while(base36.length < 30){ + base36 = "0" + base36; + } + return "XE" + ibanChecksum("XE00" + base36) + base36; +} +function getContractAddress(transaction) { + let from = null; + try { + from = getAddress(transaction.from); + } catch (error) { + logger24.throwArgumentError("missing from address", "transaction", transaction); + } + const nonce = stripZeros(arrayify(BigNumber.from(transaction.nonce).toHexString())); + return getAddress(hexDataSlice(keccak256(encode([ + from, + nonce + ])), 12)); +} +function getCreate2Address(from, salt, initCodeHash) { + if (hexDataLength(salt) !== 32) { + logger24.throwArgumentError("salt must be 32 bytes", "salt", salt); + } + if (hexDataLength(initCodeHash) !== 32) { + logger24.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", initCodeHash); + } + return getAddress(hexDataSlice(keccak256(concat([ + "0xff", + getAddress(from), + salt, + initCodeHash + ])), 12)); +} +const AddressZero = "0x0000000000000000000000000000000000000000"; +const NegativeOne1 = BigNumber.from(-1); +const Zero1 = BigNumber.from(0); +const One = BigNumber.from(1); +const Two = BigNumber.from(2); +const WeiPerEther = BigNumber.from("1000000000000000000"); +const MaxUint256 = BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const MinInt256 = BigNumber.from("-0x8000000000000000000000000000000000000000000000000000000000000000"); +const MaxInt256 = BigNumber.from("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const HashZero = "0x0000000000000000000000000000000000000000000000000000000000000000"; +const EtherSymbol = "\u039E"; +const mod1 = function() { + return { + AddressZero: AddressZero, + EtherSymbol: EtherSymbol, + HashZero: HashZero, + MaxInt256: MaxInt256, + MaxUint256: MaxUint256, + MinInt256: MinInt256, + NegativeOne: NegativeOne1, + One: One, + Two: Two, + WeiPerEther: WeiPerEther, + Zero: Zero1, + default: null + }; +}(); +const version7 = "strings/5.7.0"; +const logger25 = new Logger(version7); +var UnicodeNormalizationForm; +(function(UnicodeNormalizationForm2) { + UnicodeNormalizationForm2["current"] = ""; + UnicodeNormalizationForm2["NFC"] = "NFC"; + UnicodeNormalizationForm2["NFD"] = "NFD"; + UnicodeNormalizationForm2["NFKC"] = "NFKC"; + UnicodeNormalizationForm2["NFKD"] = "NFKD"; +})(UnicodeNormalizationForm || (UnicodeNormalizationForm = {})); +var Utf8ErrorReason; +(function(Utf8ErrorReason2) { + Utf8ErrorReason2["UNEXPECTED_CONTINUE"] = "unexpected continuation byte"; + Utf8ErrorReason2["BAD_PREFIX"] = "bad codepoint prefix"; + Utf8ErrorReason2["OVERRUN"] = "string overrun"; + Utf8ErrorReason2["MISSING_CONTINUE"] = "missing continuation byte"; + Utf8ErrorReason2["OUT_OF_RANGE"] = "out of UTF-8 range"; + Utf8ErrorReason2["UTF16_SURROGATE"] = "UTF-16 surrogate"; + Utf8ErrorReason2["OVERLONG"] = "overlong representation"; +})(Utf8ErrorReason || (Utf8ErrorReason = {})); +function errorFunc(reason, offset, bytes3, output, badCodepoint) { + return logger25.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes3); +} +function ignoreFunc(reason, offset, bytes3, output, badCodepoint) { + if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) { + let i = 0; + for(let o = offset + 1; o < bytes3.length; o++){ + if (bytes3[o] >> 6 !== 2) { + break; + } + i++; + } + return i; + } + if (reason === Utf8ErrorReason.OVERRUN) { + return bytes3.length - offset - 1; + } + return 0; +} +function replaceFunc(reason, offset, bytes3, output, badCodepoint) { + if (reason === Utf8ErrorReason.OVERLONG) { + output.push(badCodepoint); + return 0; + } + output.push(65533); + return ignoreFunc(reason, offset, bytes3); +} +const Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +function getUtf8CodePoints(bytes3, onError) { + if (onError == null) { + onError = Utf8ErrorFuncs.error; + } + bytes3 = arrayify(bytes3); + const result = []; + let i = 0; + while(i < bytes3.length){ + const c = bytes3[i++]; + if (c >> 7 === 0) { + result.push(c); + continue; + } + let extraLength = null; + let overlongMask = null; + if ((c & 224) === 192) { + extraLength = 1; + overlongMask = 127; + } else if ((c & 240) === 224) { + extraLength = 2; + overlongMask = 2047; + } else if ((c & 248) === 240) { + extraLength = 3; + overlongMask = 65535; + } else { + if ((c & 192) === 128) { + i += onError(Utf8ErrorReason.UNEXPECTED_CONTINUE, i - 1, bytes3, result); + } else { + i += onError(Utf8ErrorReason.BAD_PREFIX, i - 1, bytes3, result); + } + continue; + } + if (i - 1 + extraLength >= bytes3.length) { + i += onError(Utf8ErrorReason.OVERRUN, i - 1, bytes3, result); + continue; + } + let res = c & (1 << 8 - extraLength - 1) - 1; + for(let j = 0; j < extraLength; j++){ + let nextChar = bytes3[i]; + if ((nextChar & 192) != 128) { + i += onError(Utf8ErrorReason.MISSING_CONTINUE, i, bytes3, result); + res = null; + break; + } + res = res << 6 | nextChar & 63; + i++; + } + if (res === null) { + continue; + } + if (res > 1114111) { + i += onError(Utf8ErrorReason.OUT_OF_RANGE, i - 1 - extraLength, bytes3, result, res); + continue; + } + if (res >= 55296 && res <= 57343) { + i += onError(Utf8ErrorReason.UTF16_SURROGATE, i - 1 - extraLength, bytes3, result, res); + continue; + } + if (res <= overlongMask) { + i += onError(Utf8ErrorReason.OVERLONG, i - 1 - extraLength, bytes3, result, res); + continue; + } + result.push(res); + } + return result; +} +function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) { + if (form != UnicodeNormalizationForm.current) { + logger25.checkNormalize(); + str = str.normalize(form); + } + let result = []; + for(let i = 0; i < str.length; i++){ + const c = str.charCodeAt(i); + if (c < 128) { + result.push(c); + } else if (c < 2048) { + result.push(c >> 6 | 192); + result.push(c & 63 | 128); + } else if ((c & 64512) == 55296) { + i++; + const c2 = str.charCodeAt(i); + if (i >= str.length || (c2 & 64512) !== 56320) { + throw new Error("invalid utf-8 string"); + } + const pair = 65536 + ((c & 1023) << 10) + (c2 & 1023); + result.push(pair >> 18 | 240); + result.push(pair >> 12 & 63 | 128); + result.push(pair >> 6 & 63 | 128); + result.push(pair & 63 | 128); + } else { + result.push(c >> 12 | 224); + result.push(c >> 6 & 63 | 128); + result.push(c & 63 | 128); + } + } + return arrayify(result); +} +function escapeChar(value) { + const hex = "0000" + value.toString(16); + return "\\u" + hex.substring(hex.length - 4); +} +function _toEscapedUtf8String(bytes3, onError) { + return '"' + getUtf8CodePoints(bytes3, onError).map((codePoint)=>{ + if (codePoint < 256) { + switch(codePoint){ + case 8: + return "\\b"; + case 9: + return "\\t"; + case 10: + return "\\n"; + case 13: + return "\\r"; + case 34: + return '\\"'; + case 92: + return "\\\\"; + } + if (codePoint >= 32 && codePoint < 127) { + return String.fromCharCode(codePoint); + } + } + if (codePoint <= 65535) { + return escapeChar(codePoint); + } + codePoint -= 65536; + return escapeChar((codePoint >> 10 & 1023) + 55296) + escapeChar((codePoint & 1023) + 56320); + }).join("") + '"'; +} +function _toUtf8String(codePoints) { + return codePoints.map((codePoint)=>{ + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + codePoint -= 65536; + return String.fromCharCode((codePoint >> 10 & 1023) + 55296, (codePoint & 1023) + 56320); + }).join(""); +} +function toUtf8String(bytes3, onError) { + return _toUtf8String(getUtf8CodePoints(bytes3, onError)); +} +function toUtf8CodePoints(str, form = UnicodeNormalizationForm.current) { + return getUtf8CodePoints(toUtf8Bytes(str, form)); +} +function formatBytes32String(text) { + const bytes3 = toUtf8Bytes(text); + if (bytes3.length > 31) { + throw new Error("bytes32 string must be less than 32 bytes"); + } + return hexlify(concat([ + bytes3, + HashZero + ]).slice(0, 32)); +} +function parseBytes32String(bytes3) { + const data = arrayify(bytes3); + if (data.length !== 32) { + throw new Error("invalid bytes32 - not 32 bytes long"); + } + if (data[31] !== 0) { + throw new Error("invalid bytes32 string - no null terminator"); + } + let length = 31; + while(data[length - 1] === 0){ + length--; + } + return toUtf8String(data.slice(0, length)); +} +function bytes2(data) { + if (data.length % 4 !== 0) { + throw new Error("bad data"); + } + let result = []; + for(let i = 0; i < data.length; i += 4){ + result.push(parseInt(data.substring(i, i + 4), 16)); + } + return result; +} +function createTable(data, func) { + if (!func) { + func = function(value) { + return [ + parseInt(value, 16) + ]; + }; + } + let lo = 0; + let result = {}; + data.split(",").forEach((pair)=>{ + let comps = pair.split(":"); + lo += parseInt(comps[0], 16); + result[lo] = func(comps[1]); + }); + return result; +} +function createRangeTable(data) { + let hi = 0; + return data.split(",").map((v)=>{ + let comps = v.split("-"); + if (comps.length === 1) { + comps[1] = "0"; + } else if (comps[1] === "") { + comps[1] = "1"; + } + let lo = hi + parseInt(comps[0], 16); + hi = parseInt(comps[1], 16); + return { + l: lo, + h: hi + }; + }); +} +function matchMap(value, ranges) { + let lo = 0; + for(let i = 0; i < ranges.length; i++){ + let range = ranges[i]; + lo += range.l; + if (value >= lo && value <= lo + range.h && (value - lo) % (range.d || 1) === 0) { + if (range.e && range.e.indexOf(value - lo) !== -1) { + continue; + } + return range; + } + } + return null; +} +const Table_A_1_ranges = createRangeTable("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"); +const Table_B_1_flags = "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((v)=>parseInt(v, 16)); +const Table_B_2_ranges = [ + { + h: 25, + s: 32, + l: 65 + }, + { + h: 30, + s: 32, + e: [ + 23 + ], + l: 127 + }, + { + h: 54, + s: 1, + e: [ + 48 + ], + l: 64, + d: 2 + }, + { + h: 14, + s: 1, + l: 57, + d: 2 + }, + { + h: 44, + s: 1, + l: 17, + d: 2 + }, + { + h: 10, + s: 1, + e: [ + 2, + 6, + 8 + ], + l: 61, + d: 2 + }, + { + h: 16, + s: 1, + l: 68, + d: 2 + }, + { + h: 84, + s: 1, + e: [ + 18, + 24, + 66 + ], + l: 19, + d: 2 + }, + { + h: 26, + s: 32, + e: [ + 17 + ], + l: 435 + }, + { + h: 22, + s: 1, + l: 71, + d: 2 + }, + { + h: 15, + s: 80, + l: 40 + }, + { + h: 31, + s: 32, + l: 16 + }, + { + h: 32, + s: 1, + l: 80, + d: 2 + }, + { + h: 52, + s: 1, + l: 42, + d: 2 + }, + { + h: 12, + s: 1, + l: 55, + d: 2 + }, + { + h: 40, + s: 1, + e: [ + 38 + ], + l: 15, + d: 2 + }, + { + h: 14, + s: 1, + l: 48, + d: 2 + }, + { + h: 37, + s: 48, + l: 49 + }, + { + h: 148, + s: 1, + l: 6351, + d: 2 + }, + { + h: 88, + s: 1, + l: 160, + d: 2 + }, + { + h: 15, + s: 16, + l: 704 + }, + { + h: 25, + s: 26, + l: 854 + }, + { + h: 25, + s: 32, + l: 55915 + }, + { + h: 37, + s: 40, + l: 1247 + }, + { + h: 25, + s: -119711, + l: 53248 + }, + { + h: 25, + s: -119763, + l: 52 + }, + { + h: 25, + s: -119815, + l: 52 + }, + { + h: 25, + s: -119867, + e: [ + 1, + 4, + 5, + 7, + 8, + 11, + 12, + 17 + ], + l: 52 + }, + { + h: 25, + s: -119919, + l: 52 + }, + { + h: 24, + s: -119971, + e: [ + 2, + 7, + 8, + 17 + ], + l: 52 + }, + { + h: 24, + s: -120023, + e: [ + 2, + 7, + 13, + 15, + 16, + 17 + ], + l: 52 + }, + { + h: 25, + s: -120075, + l: 52 + }, + { + h: 25, + s: -120127, + l: 52 + }, + { + h: 25, + s: -120179, + l: 52 + }, + { + h: 25, + s: -120231, + l: 52 + }, + { + h: 25, + s: -120283, + l: 52 + }, + { + h: 25, + s: -120335, + l: 52 + }, + { + h: 24, + s: -119543, + e: [ + 17 + ], + l: 56 + }, + { + h: 24, + s: -119601, + e: [ + 17 + ], + l: 58 + }, + { + h: 24, + s: -119659, + e: [ + 17 + ], + l: 58 + }, + { + h: 24, + s: -119717, + e: [ + 17 + ], + l: 58 + }, + { + h: 24, + s: -119775, + e: [ + 17 + ], + l: 58 + } +]; +const Table_B_2_lut_abs = createTable("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"); +const Table_B_2_lut_rel = createTable("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"); +const Table_B_2_complex = createTable("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", bytes2); +const Table_C_ranges = createRangeTable("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001"); +function flatten(values) { + return values.reduce((accum, value)=>{ + value.forEach((value2)=>{ + accum.push(value2); + }); + return accum; + }, []); +} +function _nameprepTableA1(codepoint) { + return !!matchMap(codepoint, Table_A_1_ranges); +} +function _nameprepTableB2(codepoint) { + let range = matchMap(codepoint, Table_B_2_ranges); + if (range) { + return [ + codepoint + range.s + ]; + } + let codes = Table_B_2_lut_abs[codepoint]; + if (codes) { + return codes; + } + let shift = Table_B_2_lut_rel[codepoint]; + if (shift) { + return [ + codepoint + shift[0] + ]; + } + let complex = Table_B_2_complex[codepoint]; + if (complex) { + return complex; + } + return null; +} +function _nameprepTableC(codepoint) { + return !!matchMap(codepoint, Table_C_ranges); +} +function nameprep(value) { + if (value.match(/^[a-z0-9-]*$/i) && value.length <= 59) { + return value.toLowerCase(); + } + let codes = toUtf8CodePoints(value); + codes = flatten(codes.map((code)=>{ + if (Table_B_1_flags.indexOf(code) >= 0) { + return []; + } + if (code >= 65024 && code <= 65039) { + return []; + } + let codesTableB2 = _nameprepTableB2(code); + if (codesTableB2) { + return codesTableB2; + } + return [ + code + ]; + })); + codes = toUtf8CodePoints(_toUtf8String(codes), UnicodeNormalizationForm.NFKC); + codes.forEach((code)=>{ + if (_nameprepTableC(code)) { + throw new Error("STRINGPREP_CONTAINS_PROHIBITED"); + } + }); + codes.forEach((code)=>{ + if (_nameprepTableA1(code)) { + throw new Error("STRINGPREP_CONTAINS_UNASSIGNED"); + } + }); + let name = _toUtf8String(codes); + if (name.substring(0, 1) === "-" || name.substring(2, 4) === "--" || name.substring(name.length - 1) === "-") { + throw new Error("invalid hyphen"); + } + return name; +} +function decode2(textData) { + textData = atob(textData); + const data = []; + for(let i = 0; i < textData.length; i++){ + data.push(textData.charCodeAt(i)); + } + return arrayify(data); +} +function encode1(data) { + data = arrayify(data); + let textData = ""; + for(let i = 0; i < data.length; i++){ + textData += String.fromCharCode(data[i]); + } + return btoa(textData); +} +const mod2 = function() { + return { + decode: decode2, + encode: encode1, + default: null + }; +}(); +function id(text) { + return keccak256(toUtf8Bytes(text)); +} +const version8 = "hash/5.7.0"; +function flat(array, depth) { + if (depth == null) { + depth = 1; + } + const result = []; + const forEach = result.forEach; + const flatDeep = function(arr, depth2) { + forEach.call(arr, function(val) { + if (depth2 > 0 && Array.isArray(val)) { + flatDeep(val, depth2 - 1); + } else { + result.push(val); + } + }); + }; + flatDeep(array, depth); + return result; +} +function fromEntries(array) { + const result = {}; + for(let i = 0; i < array.length; i++){ + const value = array[i]; + result[value[0]] = value[1]; + } + return result; +} +function decode_arithmetic(bytes2) { + let pos = 0; + function u16() { + return bytes2[pos++] << 8 | bytes2[pos++]; + } + let symbol_count = u16(); + let total = 1; + let acc = [ + 0, + 1 + ]; + for(let i = 1; i < symbol_count; i++){ + acc.push(total += u16()); + } + let skip = u16(); + let pos_payload = pos; + pos += skip; + let read_width = 0; + let read_buffer = 0; + function read_bit() { + if (read_width == 0) { + read_buffer = read_buffer << 8 | bytes2[pos++]; + read_width = 8; + } + return read_buffer >> --read_width & 1; + } + const FULL = Math.pow(2, 31); + const HALF = FULL >>> 1; + const QRTR = HALF >> 1; + const MASK = FULL - 1; + let register = 0; + for(let i = 0; i < 31; i++)register = register << 1 | read_bit(); + let symbols = []; + let low = 0; + let range = FULL; + while(true){ + let value = Math.floor(((register - low + 1) * total - 1) / range); + let start = 0; + let end = symbol_count; + while(end - start > 1){ + let mid = start + end >>> 1; + if (value < acc[mid]) { + end = mid; + } else { + start = mid; + } + } + if (start == 0) break; + symbols.push(start); + let a = low + Math.floor(range * acc[start] / total); + let b = low + Math.floor(range * acc[start + 1] / total) - 1; + while(((a ^ b) & HALF) == 0){ + register = register << 1 & MASK | read_bit(); + a = a << 1 & MASK; + b = b << 1 & MASK | 1; + } + while(a & ~b & QRTR){ + register = register & HALF | register << 1 & MASK >>> 1 | read_bit(); + a = a << 1 ^ HALF; + b = (b ^ HALF) << 1 | HALF | 1; + } + low = a; + range = 1 + b - a; + } + let offset = symbol_count - 4; + return symbols.map((x)=>{ + switch(x - offset){ + case 3: + return offset + 65792 + (bytes2[pos_payload++] << 16 | bytes2[pos_payload++] << 8 | bytes2[pos_payload++]); + case 2: + return offset + 256 + (bytes2[pos_payload++] << 8 | bytes2[pos_payload++]); + case 1: + return offset + bytes2[pos_payload++]; + default: + return x - 1; + } + }); +} +function read_payload(v) { + let pos = 0; + return ()=>v[pos++]; +} +function read_compressed_payload(bytes2) { + return read_payload(decode_arithmetic(bytes2)); +} +function signed(i) { + return i & 1 ? ~i >> 1 : i >> 1; +} +function read_counts(n, next) { + let v = Array(n); + for(let i = 0; i < n; i++)v[i] = 1 + next(); + return v; +} +function read_ascending(n, next) { + let v = Array(n); + for(let i = 0, x = -1; i < n; i++)v[i] = x += 1 + next(); + return v; +} +function read_deltas(n, next) { + let v = Array(n); + for(let i = 0, x = 0; i < n; i++)v[i] = x += signed(next()); + return v; +} +function read_member_array(next, lookup) { + let v = read_ascending(next(), next); + let n = next(); + let vX = read_ascending(n, next); + let vN = read_counts(n, next); + for(let i = 0; i < n; i++){ + for(let j = 0; j < vN[i]; j++){ + v.push(vX[i] + j); + } + } + return lookup ? v.map((x)=>lookup[x]) : v; +} +function read_mapped_map(next) { + let ret = []; + while(true){ + let w = next(); + if (w == 0) break; + ret.push(read_linear_table(w, next)); + } + while(true){ + let w = next() - 1; + if (w < 0) break; + ret.push(read_replacement_table(w, next)); + } + return fromEntries(flat(ret)); +} +function read_zero_terminated_array(next) { + let v = []; + while(true){ + let i = next(); + if (i == 0) break; + v.push(i); + } + return v; +} +function read_transposed(n, w, next) { + let m = Array(n).fill(void 0).map(()=>[]); + for(let i = 0; i < w; i++){ + read_deltas(n, next).forEach((x, j)=>m[j].push(x)); + } + return m; +} +function read_linear_table(w, next) { + let dx = 1 + next(); + let dy = next(); + let vN = read_zero_terminated_array(next); + let m = read_transposed(vN.length, 1 + w, next); + return flat(m.map((v, i)=>{ + const x = v[0], ys = v.slice(1); + return Array(vN[i]).fill(void 0).map((_, j)=>{ + let j_dy = j * dy; + return [ + x + j * dx, + ys.map((y)=>y + j_dy) + ]; + }); + })); +} +function read_replacement_table(w, next) { + let n = 1 + next(); + let m = read_transposed(n, 1 + w, next); + return m.map((v)=>[ + v[0], + v.slice(1) + ]); +} +function read_emoji_trie(next) { + let sorted = read_member_array(next).sort((a, b)=>a - b); + return read(); + function read() { + let branches = []; + while(true){ + let keys = read_member_array(next, sorted); + if (keys.length == 0) break; + branches.push({ + set: new Set(keys), + node: read() + }); + } + branches.sort((a, b)=>b.set.size - a.set.size); + let temp = next(); + let valid = temp % 3; + temp = temp / 3 | 0; + let fe0f = !!(temp & 1); + temp >>= 1; + let save = temp == 1; + let check = temp == 2; + return { + branches, + valid, + fe0f, + save, + check + }; + } +} +function getData() { + return read_compressed_payload(decode2("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA==")); +} +const r = getData(); +const VALID = new Set(read_member_array(r)); +const IGNORED = new Set(read_member_array(r)); +const MAPPED = read_mapped_map(r); +const EMOJI_ROOT = read_emoji_trie(r); +function explode_cp(name) { + return toUtf8CodePoints(name); +} +function filter_fe0f(cps) { + return cps.filter((cp)=>cp != 65039); +} +function ens_normalize_post_check(name) { + for (let label of name.split(".")){ + let cps = explode_cp(label); + try { + for(let i = cps.lastIndexOf(95) - 1; i >= 0; i--){ + if (cps[i] !== 95) { + throw new Error(`underscore only allowed at start`); + } + } + if (cps.length >= 4 && cps.every((cp)=>cp < 128) && cps[2] === 45 && cps[3] === 45) { + throw new Error(`invalid label extension`); + } + } catch (err) { + throw new Error(`Invalid label "${label}": ${err.message}`); + } + } + return name; +} +function ens_normalize(name) { + return ens_normalize_post_check(normalize(name, filter_fe0f)); +} +function normalize(name, emoji_filter) { + let input = explode_cp(name).reverse(); + let output = []; + while(input.length){ + let emoji = consume_emoji_reversed(input); + if (emoji) { + output.push(...emoji_filter(emoji)); + continue; + } + let cp = input.pop(); + if (VALID.has(cp)) { + output.push(cp); + continue; + } + if (IGNORED.has(cp)) { + continue; + } + let cps = MAPPED[cp]; + if (cps) { + output.push(...cps); + continue; + } + throw new Error(`Disallowed codepoint: 0x${cp.toString(16).toUpperCase()}`); + } + return ens_normalize_post_check(nfc(String.fromCodePoint(...output))); +} +function nfc(s) { + return s.normalize("NFC"); +} +function consume_emoji_reversed(cps, eaten) { + var _a; + let node = EMOJI_ROOT; + let emoji; + let saved; + let stack = []; + let pos = cps.length; + if (eaten) eaten.length = 0; + while(pos){ + let cp = cps[--pos]; + node = (_a = node.branches.find((x)=>x.set.has(cp))) === null || _a === void 0 ? void 0 : _a.node; + if (!node) break; + if (node.save) { + saved = cp; + } else if (node.check) { + if (cp === saved) break; + } + stack.push(cp); + if (node.fe0f) { + stack.push(65039); + if (pos > 0 && cps[pos - 1] == 65039) pos--; + } + if (node.valid) { + emoji = stack.slice(); + if (node.valid == 2) emoji.splice(1, 1); + if (eaten) eaten.push(...cps.slice(pos).reverse()); + cps.length = pos; + } + } + return emoji; +} +const logger26 = new Logger(version8); +const Zeros = new Uint8Array(32); +Zeros.fill(0); +function checkComponent(comp) { + if (comp.length === 0) { + throw new Error("invalid ENS name; empty component"); + } + return comp; +} +function ensNameSplit(name) { + const bytes2 = toUtf8Bytes(ens_normalize(name)); + const comps = []; + if (name.length === 0) { + return comps; + } + let last = 0; + for(let i = 0; i < bytes2.length; i++){ + const d = bytes2[i]; + if (d === 46) { + comps.push(checkComponent(bytes2.slice(last, i))); + last = i + 1; + } + } + if (last >= bytes2.length) { + throw new Error("invalid ENS name; empty component"); + } + comps.push(checkComponent(bytes2.slice(last))); + return comps; +} +function isValidName(name) { + try { + return ensNameSplit(name).length !== 0; + } catch (error) {} + return false; +} +function namehash(name) { + if (typeof name !== "string") { + logger26.throwArgumentError("invalid ENS name; not a string", "name", name); + } + let result = Zeros; + const comps = ensNameSplit(name); + while(comps.length){ + result = keccak256(concat([ + result, + keccak256(comps.pop()) + ])); + } + return hexlify(result); +} +function dnsEncode(name) { + return hexlify(concat(ensNameSplit(name).map((comp)=>{ + if (comp.length > 63) { + throw new Error("invalid DNS encoded entry; length exceeds 63 bytes"); + } + const bytes2 = new Uint8Array(comp.length + 1); + bytes2.set(comp, 1); + bytes2[0] = bytes2.length - 1; + return bytes2; + }))) + "00"; +} +const messagePrefix = "Ethereum Signed Message:\n"; +function hashMessage(message) { + if (typeof message === "string") { + message = toUtf8Bytes(message); + } + return keccak256(concat([ + toUtf8Bytes(messagePrefix), + toUtf8Bytes(String(message.length)), + message + ])); +} +var __awaiter1 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger$11 = new Logger(version8); +const padding = new Uint8Array(32); +padding.fill(0); +const NegativeOne2 = BigNumber.from(-1); +const Zero2 = BigNumber.from(0); +const One1 = BigNumber.from(1); +const MaxUint2561 = BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +function hexPadRight(value) { + const bytes2 = arrayify(value); + const padOffset = bytes2.length % 32; + if (padOffset) { + return hexConcat([ + bytes2, + padding.slice(padOffset) + ]); + } + return hexlify(bytes2); +} +const hexTrue = hexZeroPad(One1.toHexString(), 32); +const hexFalse = hexZeroPad(Zero2.toHexString(), 32); +const domainFieldTypes = { + name: "string", + version: "string", + chainId: "uint256", + verifyingContract: "address", + salt: "bytes32" +}; +const domainFieldNames = [ + "name", + "version", + "chainId", + "verifyingContract", + "salt" +]; +function checkString(key) { + return function(value) { + if (typeof value !== "string") { + logger$11.throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); + } + return value; + }; +} +const domainChecks = { + name: checkString("name"), + version: checkString("version"), + chainId: function(value) { + try { + return BigNumber.from(value).toString(); + } catch (error) {} + return logger$11.throwArgumentError(`invalid domain value for "chainId"`, "domain.chainId", value); + }, + verifyingContract: function(value) { + try { + return getAddress(value).toLowerCase(); + } catch (error) {} + return logger$11.throwArgumentError(`invalid domain value "verifyingContract"`, "domain.verifyingContract", value); + }, + salt: function(value) { + try { + const bytes2 = arrayify(value); + if (bytes2.length !== 32) { + throw new Error("bad length"); + } + return hexlify(bytes2); + } catch (error) {} + return logger$11.throwArgumentError(`invalid domain value "salt"`, "domain.salt", value); + } +}; +function getBaseEncoder(type) { + { + const match = type.match(/^(u?)int(\d*)$/); + if (match) { + const signed2 = match[1] === ""; + const width = parseInt(match[2] || "256"); + if (width % 8 !== 0 || width > 256 || match[2] && match[2] !== String(width)) { + logger$11.throwArgumentError("invalid numeric width", "type", type); + } + const boundsUpper = MaxUint2561.mask(signed2 ? width - 1 : width); + const boundsLower = signed2 ? boundsUpper.add(One1).mul(NegativeOne2) : Zero2; + return function(value) { + const v = BigNumber.from(value); + if (v.lt(boundsLower) || v.gt(boundsUpper)) { + logger$11.throwArgumentError(`value out-of-bounds for ${type}`, "value", value); + } + return hexZeroPad(v.toTwos(256).toHexString(), 32); + }; + } + } + { + const match = type.match(/^bytes(\d+)$/); + if (match) { + const width = parseInt(match[1]); + if (width === 0 || width > 32 || match[1] !== String(width)) { + logger$11.throwArgumentError("invalid bytes width", "type", type); + } + return function(value) { + const bytes2 = arrayify(value); + if (bytes2.length !== width) { + logger$11.throwArgumentError(`invalid length for ${type}`, "value", value); + } + return hexPadRight(value); + }; + } + } + switch(type){ + case "address": + return function(value) { + return hexZeroPad(getAddress(value), 32); + }; + case "bool": + return function(value) { + return !value ? hexFalse : hexTrue; + }; + case "bytes": + return function(value) { + return keccak256(value); + }; + case "string": + return function(value) { + return id(value); + }; + } + return null; +} +function encodeType(name, fields) { + return `${name}(${fields.map(({ name: name2, type })=>type + " " + name2).join(",")})`; +} +class TypedDataEncoder { + constructor(types){ + defineReadOnly(this, "types", Object.freeze(deepCopy(types))); + defineReadOnly(this, "_encoderCache", {}); + defineReadOnly(this, "_types", {}); + const links = {}; + const parents = {}; + const subtypes = {}; + Object.keys(types).forEach((type)=>{ + links[type] = {}; + parents[type] = []; + subtypes[type] = {}; + }); + for(const name in types){ + const uniqueNames = {}; + types[name].forEach((field)=>{ + if (uniqueNames[field.name]) { + logger$11.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", types); + } + uniqueNames[field.name] = true; + const baseType = field.type.match(/^([^\x5b]*)(\x5b|$)/)[1]; + if (baseType === name) { + logger$11.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`, "types", types); + } + const encoder = getBaseEncoder(baseType); + if (encoder) { + return; + } + if (!parents[baseType]) { + logger$11.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`, "types", types); + } + parents[baseType].push(name); + links[name][baseType] = true; + }); + } + const primaryTypes = Object.keys(parents).filter((n)=>parents[n].length === 0); + if (primaryTypes.length === 0) { + logger$11.throwArgumentError("missing primary type", "types", types); + } else if (primaryTypes.length > 1) { + logger$11.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map((t)=>JSON.stringify(t)).join(", ")}`, "types", types); + } + defineReadOnly(this, "primaryType", primaryTypes[0]); + function checkCircular(type, found) { + if (found[type]) { + logger$11.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, "types", types); + } + found[type] = true; + Object.keys(links[type]).forEach((child)=>{ + if (!parents[child]) { + return; + } + checkCircular(child, found); + Object.keys(found).forEach((subtype)=>{ + subtypes[subtype][child] = true; + }); + }); + delete found[type]; + } + checkCircular(this.primaryType, {}); + for(const name in subtypes){ + const st = Object.keys(subtypes[name]); + st.sort(); + this._types[name] = encodeType(name, types[name]) + st.map((t)=>encodeType(t, types[t])).join(""); + } + } + getEncoder(type) { + let encoder = this._encoderCache[type]; + if (!encoder) { + encoder = this._encoderCache[type] = this._getEncoder(type); + } + return encoder; + } + _getEncoder(type) { + { + const encoder = getBaseEncoder(type); + if (encoder) { + return encoder; + } + } + const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); + if (match) { + const subtype = match[1]; + const subEncoder = this.getEncoder(subtype); + const length = parseInt(match[3]); + return (value)=>{ + if (length >= 0 && value.length !== length) { + logger$11.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); + } + let result = value.map(subEncoder); + if (this._types[subtype]) { + result = result.map(keccak256); + } + return keccak256(hexConcat(result)); + }; + } + const fields = this.types[type]; + if (fields) { + const encodedType = id(this._types[type]); + return (value)=>{ + const values = fields.map(({ name, type: type2 })=>{ + const result = this.getEncoder(type2)(value[name]); + if (this._types[type2]) { + return keccak256(result); + } + return result; + }); + values.unshift(encodedType); + return hexConcat(values); + }; + } + return logger$11.throwArgumentError(`unknown type: ${type}`, "type", type); + } + encodeType(name) { + const result = this._types[name]; + if (!result) { + logger$11.throwArgumentError(`unknown type: ${JSON.stringify(name)}`, "name", name); + } + return result; + } + encodeData(type, value) { + return this.getEncoder(type)(value); + } + hashStruct(name, value) { + return keccak256(this.encodeData(name, value)); + } + encode(value) { + return this.encodeData(this.primaryType, value); + } + hash(value) { + return this.hashStruct(this.primaryType, value); + } + _visit(type, value, callback) { + { + const encoder = getBaseEncoder(type); + if (encoder) { + return callback(type, value); + } + } + const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); + if (match) { + const subtype = match[1]; + const length = parseInt(match[3]); + if (length >= 0 && value.length !== length) { + logger$11.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); + } + return value.map((v)=>this._visit(subtype, v, callback)); + } + const fields = this.types[type]; + if (fields) { + return fields.reduce((accum, { name, type: type2 })=>{ + accum[name] = this._visit(type2, value[name], callback); + return accum; + }, {}); + } + return logger$11.throwArgumentError(`unknown type: ${type}`, "type", type); + } + visit(value, callback) { + return this._visit(this.primaryType, value, callback); + } + static from(types) { + return new TypedDataEncoder(types); + } + static getPrimaryType(types) { + return TypedDataEncoder.from(types).primaryType; + } + static hashStruct(name, types, value) { + return TypedDataEncoder.from(types).hashStruct(name, value); + } + static hashDomain(domain) { + const domainFields = []; + for(const name in domain){ + const type = domainFieldTypes[name]; + if (!type) { + logger$11.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain); + } + domainFields.push({ + name, + type + }); + } + domainFields.sort((a, b)=>{ + return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); + }); + return TypedDataEncoder.hashStruct("EIP712Domain", { + EIP712Domain: domainFields + }, domain); + } + static encode(domain, types, value) { + return hexConcat([ + "0x1901", + TypedDataEncoder.hashDomain(domain), + TypedDataEncoder.from(types).hash(value) + ]); + } + static hash(domain, types, value) { + return keccak256(TypedDataEncoder.encode(domain, types, value)); + } + static resolveNames(domain, types, value, resolveName) { + return __awaiter1(this, void 0, void 0, function*() { + domain = shallowCopy(domain); + const ensCache = {}; + if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) { + ensCache[domain.verifyingContract] = "0x"; + } + const encoder = TypedDataEncoder.from(types); + encoder.visit(value, (type, value2)=>{ + if (type === "address" && !isHexString(value2, 20)) { + ensCache[value2] = "0x"; + } + return value2; + }); + for(const name in ensCache){ + ensCache[name] = yield resolveName(name); + } + if (domain.verifyingContract && ensCache[domain.verifyingContract]) { + domain.verifyingContract = ensCache[domain.verifyingContract]; + } + value = encoder.visit(value, (type, value2)=>{ + if (type === "address" && ensCache[value2]) { + return ensCache[value2]; + } + return value2; + }); + return { + domain, + value + }; + }); + } + static getPayload(domain, types, value) { + TypedDataEncoder.hashDomain(domain); + const domainValues = {}; + const domainTypes = []; + domainFieldNames.forEach((name)=>{ + const value2 = domain[name]; + if (value2 == null) { + return; + } + domainValues[name] = domainChecks[name](value2); + domainTypes.push({ + name, + type: domainFieldTypes[name] + }); + }); + const encoder = TypedDataEncoder.from(types); + const typesWithDomain = shallowCopy(types); + if (typesWithDomain.EIP712Domain) { + logger$11.throwArgumentError("types must not contain EIP712Domain type", "types.EIP712Domain", types); + } else { + typesWithDomain.EIP712Domain = domainTypes; + } + encoder.encode(value); + return { + types: typesWithDomain, + domain: domainValues, + primaryType: encoder.primaryType, + message: encoder.visit(value, (type, value2)=>{ + if (type.match(/^bytes(\d*)/)) { + return hexlify(arrayify(value2)); + } + if (type.match(/^u?int/)) { + return BigNumber.from(value2).toString(); + } + switch(type){ + case "address": + return value2.toLowerCase(); + case "bool": + return !!value2; + case "string": + if (typeof value2 !== "string") { + logger$11.throwArgumentError(`invalid string`, "value", value2); + } + return value2; + } + return logger$11.throwArgumentError("unsupported type", "type", type); + }) + }; } - return value; } -function readUint64(data, offset, options) { - assertEnoughData(data, offset, 8); - const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]; - const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]; - const value = (BigInt(hi) << BigInt(32)) + BigInt(lo); - if (options.strict === true && value < uintBoundaries[3]) { - throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); +const version9 = "abi/5.7.0"; +const logger27 = new Logger(version9); +const _constructorGuard1 = {}; +let ModifiersBytes = { + calldata: true, + memory: true, + storage: true +}; +let ModifiersNest = { + calldata: true, + memory: true +}; +function checkModifier(type, name) { + if (type === "bytes" || type === "string") { + if (ModifiersBytes[name]) { + return true; + } + } else if (type === "address") { + if (name === "payable") { + return true; + } + } else if (type.indexOf("[") >= 0 || type === "tuple") { + if (ModifiersNest[name]) { + return true; + } } - if (value <= Number.MAX_SAFE_INTEGER) { - return Number(value); + if (ModifiersBytes[name] || name === "payable") { + logger27.throwArgumentError("invalid modifier", "name", name); } - if (options.allowBigInt === true) { - return value; + return false; +} +function parseParamType(param, allowIndexed) { + let originalParam = param; + function throwError(i) { + logger27.throwArgumentError(`unexpected character at position ${i}`, "param", param); } - throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`); + param = param.replace(/\s/g, " "); + function newNode(parent2) { + let node2 = { + type: "", + name: "", + parent: parent2, + state: { + allowType: true + } + }; + if (allowIndexed) { + node2.indexed = false; + } + return node2; + } + let parent = { + type: "", + name: "", + state: { + allowType: true + } + }; + let node = parent; + for(let i = 0; i < param.length; i++){ + let c = param[i]; + switch(c){ + case "(": + if (node.state.allowType && node.type === "") { + node.type = "tuple"; + } else if (!node.state.allowParams) { + throwError(i); + } + node.state.allowType = false; + node.type = verifyType(node.type); + node.components = [ + newNode(node) + ]; + node = node.components[0]; + break; + case ")": + delete node.state; + if (node.name === "indexed") { + if (!allowIndexed) { + throwError(i); + } + node.indexed = true; + node.name = ""; + } + if (checkModifier(node.type, node.name)) { + node.name = ""; + } + node.type = verifyType(node.type); + let child = node; + node = node.parent; + if (!node) { + throwError(i); + } + delete child.parent; + node.state.allowParams = false; + node.state.allowName = true; + node.state.allowArray = true; + break; + case ",": + delete node.state; + if (node.name === "indexed") { + if (!allowIndexed) { + throwError(i); + } + node.indexed = true; + node.name = ""; + } + if (checkModifier(node.type, node.name)) { + node.name = ""; + } + node.type = verifyType(node.type); + let sibling = newNode(node.parent); + node.parent.components.push(sibling); + delete node.parent; + node = sibling; + break; + case " ": + if (node.state.allowType) { + if (node.type !== "") { + node.type = verifyType(node.type); + delete node.state.allowType; + node.state.allowName = true; + node.state.allowParams = true; + } + } + if (node.state.allowName) { + if (node.name !== "") { + if (node.name === "indexed") { + if (!allowIndexed) { + throwError(i); + } + if (node.indexed) { + throwError(i); + } + node.indexed = true; + node.name = ""; + } else if (checkModifier(node.type, node.name)) { + node.name = ""; + } else { + node.state.allowName = false; + } + } + } + break; + case "[": + if (!node.state.allowArray) { + throwError(i); + } + node.type += c; + node.state.allowArray = false; + node.state.allowName = false; + node.state.readArray = true; + break; + case "]": + if (!node.state.readArray) { + throwError(i); + } + node.type += c; + node.state.readArray = false; + node.state.allowArray = true; + node.state.allowName = true; + break; + default: + if (node.state.allowType) { + node.type += c; + node.state.allowParams = true; + node.state.allowArray = true; + } else if (node.state.allowName) { + node.name += c; + delete node.state.allowArray; + } else if (node.state.readArray) { + node.type += c; + } else { + throwError(i); + } + } + } + if (node.parent) { + logger27.throwArgumentError("unexpected eof", "param", param); + } + delete parent.state; + if (node.name === "indexed") { + if (!allowIndexed) { + throwError(originalParam.length - 7); + } + if (node.indexed) { + throwError(originalParam.length - 7); + } + node.indexed = true; + node.name = ""; + } else if (checkModifier(node.type, node.name)) { + node.name = ""; + } + parent.type = verifyType(parent.type); + return parent; } -function decodeUint8(data, pos, _minor, options) { - return new Token(Type.uint, readUint8(data, pos + 1, options), 2); +function populate(object, params) { + for(let key in params){ + defineReadOnly(object, key, params[key]); + } } -function decodeUint16(data, pos, _minor, options) { - return new Token(Type.uint, readUint16(data, pos + 1, options), 3); +const FormatTypes = Object.freeze({ + sighash: "sighash", + minimal: "minimal", + full: "full", + json: "json" +}); +const paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/); +class ParamType { + constructor(constructorGuard, params){ + if (constructorGuard !== _constructorGuard1) { + logger27.throwError("use fromString", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "new ParamType()" + }); + } + populate(this, params); + let match = this.type.match(paramTypeArray); + if (match) { + populate(this, { + arrayLength: parseInt(match[2] || "-1"), + arrayChildren: ParamType.fromObject({ + type: match[1], + components: this.components + }), + baseType: "array" + }); + } else { + populate(this, { + arrayLength: null, + arrayChildren: null, + baseType: this.components != null ? "tuple" : this.type + }); + } + this._isParamType = true; + Object.freeze(this); + } + format(format) { + if (!format) { + format = FormatTypes.sighash; + } + if (!FormatTypes[format]) { + logger27.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatTypes.json) { + let result2 = { + type: this.baseType === "tuple" ? "tuple" : this.type, + name: this.name || void 0 + }; + if (typeof this.indexed === "boolean") { + result2.indexed = this.indexed; + } + if (this.components) { + result2.components = this.components.map((comp)=>JSON.parse(comp.format(format))); + } + return JSON.stringify(result2); + } + let result = ""; + if (this.baseType === "array") { + result += this.arrayChildren.format(format); + result += "[" + (this.arrayLength < 0 ? "" : String(this.arrayLength)) + "]"; + } else { + if (this.baseType === "tuple") { + if (format !== FormatTypes.sighash) { + result += this.type; + } + result += "(" + this.components.map((comp)=>comp.format(format)).join(format === FormatTypes.full ? ", " : ",") + ")"; + } else { + result += this.type; + } + } + if (format !== FormatTypes.sighash) { + if (this.indexed === true) { + result += " indexed"; + } + if (format === FormatTypes.full && this.name) { + result += " " + this.name; + } + } + return result; + } + static from(value, allowIndexed) { + if (typeof value === "string") { + return ParamType.fromString(value, allowIndexed); + } + return ParamType.fromObject(value); + } + static fromObject(value) { + if (ParamType.isParamType(value)) { + return value; + } + return new ParamType(_constructorGuard1, { + name: value.name || null, + type: verifyType(value.type), + indexed: value.indexed == null ? null : !!value.indexed, + components: value.components ? value.components.map(ParamType.fromObject) : null + }); + } + static fromString(value, allowIndexed) { + function ParamTypify(node) { + return ParamType.fromObject({ + name: node.name, + type: node.type, + indexed: node.indexed, + components: node.components + }); + } + return ParamTypify(parseParamType(value, !!allowIndexed)); + } + static isParamType(value) { + return !!(value != null && value._isParamType); + } } -function decodeUint32(data, pos, _minor, options) { - return new Token(Type.uint, readUint32(data, pos + 1, options), 5); +function parseParams(value, allowIndex) { + return splitNesting(value).map((param)=>ParamType.fromString(param, allowIndex)); } -function decodeUint64(data, pos, _minor, options) { - return new Token(Type.uint, readUint64(data, pos + 1, options), 9); +class Fragment { + constructor(constructorGuard, params){ + if (constructorGuard !== _constructorGuard1) { + logger27.throwError("use a static from method", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "new Fragment()" + }); + } + populate(this, params); + this._isFragment = true; + Object.freeze(this); + } + static from(value) { + if (Fragment.isFragment(value)) { + return value; + } + if (typeof value === "string") { + return Fragment.fromString(value); + } + return Fragment.fromObject(value); + } + static fromObject(value) { + if (Fragment.isFragment(value)) { + return value; + } + switch(value.type){ + case "function": + return FunctionFragment.fromObject(value); + case "event": + return EventFragment.fromObject(value); + case "constructor": + return ConstructorFragment.fromObject(value); + case "error": + return ErrorFragment.fromObject(value); + case "fallback": + case "receive": + return null; + } + return logger27.throwArgumentError("invalid fragment object", "value", value); + } + static fromString(value) { + value = value.replace(/\s/g, " "); + value = value.replace(/\(/g, " (").replace(/\)/g, ") ").replace(/\s+/g, " "); + value = value.trim(); + if (value.split(" ")[0] === "event") { + return EventFragment.fromString(value.substring(5).trim()); + } else if (value.split(" ")[0] === "function") { + return FunctionFragment.fromString(value.substring(8).trim()); + } else if (value.split("(")[0].trim() === "constructor") { + return ConstructorFragment.fromString(value.trim()); + } else if (value.split(" ")[0] === "error") { + return ErrorFragment.fromString(value.substring(5).trim()); + } + return logger27.throwArgumentError("unsupported fragment", "value", value); + } + static isFragment(value) { + return !!(value && value._isFragment); + } +} +class EventFragment extends Fragment { + format(format) { + if (!format) { + format = FormatTypes.sighash; + } + if (!FormatTypes[format]) { + logger27.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatTypes.json) { + return JSON.stringify({ + type: "event", + anonymous: this.anonymous, + name: this.name, + inputs: this.inputs.map((input)=>JSON.parse(input.format(format))) + }); + } + let result = ""; + if (format !== FormatTypes.sighash) { + result += "event "; + } + result += this.name + "(" + this.inputs.map((input)=>input.format(format)).join(format === FormatTypes.full ? ", " : ",") + ") "; + if (format !== FormatTypes.sighash) { + if (this.anonymous) { + result += "anonymous "; + } + } + return result.trim(); + } + static from(value) { + if (typeof value === "string") { + return EventFragment.fromString(value); + } + return EventFragment.fromObject(value); + } + static fromObject(value) { + if (EventFragment.isEventFragment(value)) { + return value; + } + if (value.type !== "event") { + logger27.throwArgumentError("invalid event object", "value", value); + } + const params = { + name: verifyIdentifier(value.name), + anonymous: value.anonymous, + inputs: value.inputs ? value.inputs.map(ParamType.fromObject) : [], + type: "event" + }; + return new EventFragment(_constructorGuard1, params); + } + static fromString(value) { + let match = value.match(regexParen); + if (!match) { + logger27.throwArgumentError("invalid event string", "value", value); + } + let anonymous = false; + match[3].split(" ").forEach((modifier)=>{ + switch(modifier.trim()){ + case "anonymous": + anonymous = true; + break; + case "": + break; + default: + logger27.warn("unknown modifier: " + modifier); + } + }); + return EventFragment.fromObject({ + name: match[1].trim(), + anonymous, + inputs: parseParams(match[2], true), + type: "event" + }); + } + static isEventFragment(value) { + return value && value._isFragment && value.type === "event"; + } } -function encodeUint(buf2, token) { - return encodeUintValue(buf2, 0, token.value); +function parseGas(value, params) { + params.gas = null; + let comps = value.split("@"); + if (comps.length !== 1) { + if (comps.length > 2) { + logger27.throwArgumentError("invalid human-readable ABI signature", "value", value); + } + if (!comps[1].match(/^[0-9]+$/)) { + logger27.throwArgumentError("invalid human-readable ABI signature gas", "value", value); + } + params.gas = BigNumber.from(comps[1]); + return comps[0]; + } + return value; } -function encodeUintValue(buf2, major, uint) { - if (uint < uintBoundaries[0]) { - const nuint = Number(uint); - buf2.push([ - major | nuint - ]); - } else if (uint < uintBoundaries[1]) { - const nuint = Number(uint); - buf2.push([ - major | 24, - nuint - ]); - } else if (uint < uintBoundaries[2]) { - const nuint = Number(uint); - buf2.push([ - major | 25, - nuint >>> 8, - nuint & 255 - ]); - } else if (uint < uintBoundaries[3]) { - const nuint = Number(uint); - buf2.push([ - major | 26, - nuint >>> 24 & 255, - nuint >>> 16 & 255, - nuint >>> 8 & 255, - nuint & 255 - ]); - } else { - const buint = BigInt(uint); - if (buint < uintBoundaries[4]) { - const set = [ - major | 27, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - let lo = Number(buint & BigInt(4294967295)); - let hi = Number(buint >> BigInt(32) & BigInt(4294967295)); - set[8] = lo & 255; - lo = lo >> 8; - set[7] = lo & 255; - lo = lo >> 8; - set[6] = lo & 255; - lo = lo >> 8; - set[5] = lo & 255; - set[4] = hi & 255; - hi = hi >> 8; - set[3] = hi & 255; - hi = hi >> 8; - set[2] = hi & 255; - hi = hi >> 8; - set[1] = hi & 255; - buf2.push(set); +function parseModifiers(value, params) { + params.constant = false; + params.payable = false; + params.stateMutability = "nonpayable"; + value.split(" ").forEach((modifier)=>{ + switch(modifier.trim()){ + case "constant": + params.constant = true; + break; + case "payable": + params.payable = true; + params.stateMutability = "payable"; + break; + case "nonpayable": + params.payable = false; + params.stateMutability = "nonpayable"; + break; + case "pure": + params.constant = true; + params.stateMutability = "pure"; + break; + case "view": + params.constant = true; + params.stateMutability = "view"; + break; + case "external": + case "public": + case "": + break; + default: + console.log("unknown modifier: " + modifier); + } + }); +} +function verifyState(value) { + let result = { + constant: false, + payable: true, + stateMutability: "payable" + }; + if (value.stateMutability != null) { + result.stateMutability = value.stateMutability; + result.constant = result.stateMutability === "view" || result.stateMutability === "pure"; + if (value.constant != null) { + if (!!value.constant !== result.constant) { + logger27.throwArgumentError("cannot have constant function with mutability " + result.stateMutability, "value", value); + } + } + result.payable = result.stateMutability === "payable"; + if (value.payable != null) { + if (!!value.payable !== result.payable) { + logger27.throwArgumentError("cannot have payable function with mutability " + result.stateMutability, "value", value); + } + } + } else if (value.payable != null) { + result.payable = !!value.payable; + if (value.constant == null && !result.payable && value.type !== "constructor") { + logger27.throwArgumentError("unable to determine stateMutability", "value", value); + } + result.constant = !!value.constant; + if (result.constant) { + result.stateMutability = "view"; } else { - throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`); + result.stateMutability = result.payable ? "payable" : "nonpayable"; + } + if (result.payable && result.constant) { + logger27.throwArgumentError("cannot have constant payable function", "value", value); + } + } else if (value.constant != null) { + result.constant = !!value.constant; + result.payable = !result.constant; + result.stateMutability = result.constant ? "view" : "payable"; + } else if (value.type !== "constructor") { + logger27.throwArgumentError("unable to determine stateMutability", "value", value); + } + return result; +} +class ConstructorFragment extends Fragment { + format(format) { + if (!format) { + format = FormatTypes.sighash; + } + if (!FormatTypes[format]) { + logger27.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatTypes.json) { + return JSON.stringify({ + type: "constructor", + stateMutability: this.stateMutability !== "nonpayable" ? this.stateMutability : void 0, + payable: this.payable, + gas: this.gas ? this.gas.toNumber() : void 0, + inputs: this.inputs.map((input)=>JSON.parse(input.format(format))) + }); + } + if (format === FormatTypes.sighash) { + logger27.throwError("cannot format a constructor for sighash", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "format(sighash)" + }); + } + let result = "constructor(" + this.inputs.map((input)=>input.format(format)).join(format === FormatTypes.full ? ", " : ",") + ") "; + if (this.stateMutability && this.stateMutability !== "nonpayable") { + result += this.stateMutability + " "; + } + return result.trim(); + } + static from(value) { + if (typeof value === "string") { + return ConstructorFragment.fromString(value); } + return ConstructorFragment.fromObject(value); } -} -encodeUint.encodedSize = function encodedSize(token) { - return encodeUintValue.encodedSize(token.value); -}; -encodeUintValue.encodedSize = function encodedSize2(uint) { - if (uint < uintBoundaries[0]) { - return 1; + static fromObject(value) { + if (ConstructorFragment.isConstructorFragment(value)) { + return value; + } + if (value.type !== "constructor") { + logger27.throwArgumentError("invalid constructor object", "value", value); + } + let state = verifyState(value); + if (state.constant) { + logger27.throwArgumentError("constructor cannot be constant", "value", value); + } + const params = { + name: null, + type: value.type, + inputs: value.inputs ? value.inputs.map(ParamType.fromObject) : [], + payable: state.payable, + stateMutability: state.stateMutability, + gas: value.gas ? BigNumber.from(value.gas) : null + }; + return new ConstructorFragment(_constructorGuard1, params); } - if (uint < uintBoundaries[1]) { - return 2; + static fromString(value) { + let params = { + type: "constructor" + }; + value = parseGas(value, params); + let parens = value.match(regexParen); + if (!parens || parens[1].trim() !== "constructor") { + logger27.throwArgumentError("invalid constructor string", "value", value); + } + params.inputs = parseParams(parens[2].trim(), false); + parseModifiers(parens[3].trim(), params); + return ConstructorFragment.fromObject(params); + } + static isConstructorFragment(value) { + return value && value._isFragment && value.type === "constructor"; + } +} +class FunctionFragment extends ConstructorFragment { + format(format) { + if (!format) { + format = FormatTypes.sighash; + } + if (!FormatTypes[format]) { + logger27.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatTypes.json) { + return JSON.stringify({ + type: "function", + name: this.name, + constant: this.constant, + stateMutability: this.stateMutability !== "nonpayable" ? this.stateMutability : void 0, + payable: this.payable, + gas: this.gas ? this.gas.toNumber() : void 0, + inputs: this.inputs.map((input)=>JSON.parse(input.format(format))), + outputs: this.outputs.map((output)=>JSON.parse(output.format(format))) + }); + } + let result = ""; + if (format !== FormatTypes.sighash) { + result += "function "; + } + result += this.name + "(" + this.inputs.map((input)=>input.format(format)).join(format === FormatTypes.full ? ", " : ",") + ") "; + if (format !== FormatTypes.sighash) { + if (this.stateMutability) { + if (this.stateMutability !== "nonpayable") { + result += this.stateMutability + " "; + } + } else if (this.constant) { + result += "view "; + } + if (this.outputs && this.outputs.length) { + result += "returns (" + this.outputs.map((output)=>output.format(format)).join(", ") + ") "; + } + if (this.gas != null) { + result += "@" + this.gas.toString() + " "; + } + } + return result.trim(); } - if (uint < uintBoundaries[2]) { - return 3; + static from(value) { + if (typeof value === "string") { + return FunctionFragment.fromString(value); + } + return FunctionFragment.fromObject(value); } - if (uint < uintBoundaries[3]) { - return 5; + static fromObject(value) { + if (FunctionFragment.isFunctionFragment(value)) { + return value; + } + if (value.type !== "function") { + logger27.throwArgumentError("invalid function object", "value", value); + } + let state = verifyState(value); + const params = { + type: value.type, + name: verifyIdentifier(value.name), + constant: state.constant, + inputs: value.inputs ? value.inputs.map(ParamType.fromObject) : [], + outputs: value.outputs ? value.outputs.map(ParamType.fromObject) : [], + payable: state.payable, + stateMutability: state.stateMutability, + gas: value.gas ? BigNumber.from(value.gas) : null + }; + return new FunctionFragment(_constructorGuard1, params); } - return 9; -}; -encodeUint.compareTokens = function compareTokens(tok1, tok2) { - return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0; -}; -function decodeNegint8(data, pos, _minor, options) { - return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2); -} -function decodeNegint16(data, pos, _minor, options) { - return new Token(Type.negint, -1 - readUint16(data, pos + 1, options), 3); -} -function decodeNegint32(data, pos, _minor, options) { - return new Token(Type.negint, -1 - readUint32(data, pos + 1, options), 5); -} -const neg1b = BigInt(-1); -const pos1b = BigInt(1); -function decodeNegint64(data, pos, _minor, options) { - const __int = readUint64(data, pos + 1, options); - if (typeof __int !== "bigint") { - const value = -1 - __int; - if (value >= Number.MIN_SAFE_INTEGER) { - return new Token(Type.negint, value, 9); + static fromString(value) { + let params = { + type: "function" + }; + value = parseGas(value, params); + let comps = value.split(" returns "); + if (comps.length > 2) { + logger27.throwArgumentError("invalid function string", "value", value); + } + let parens = comps[0].match(regexParen); + if (!parens) { + logger27.throwArgumentError("invalid function signature", "value", value); + } + params.name = parens[1].trim(); + if (params.name) { + verifyIdentifier(params.name); + } + params.inputs = parseParams(parens[2], false); + parseModifiers(parens[3].trim(), params); + if (comps.length > 1) { + let returns = comps[1].match(regexParen); + if (returns[1].trim() != "" || returns[3].trim() != "") { + logger27.throwArgumentError("unexpected tokens", "value", value); + } + params.outputs = parseParams(returns[2], false); + } else { + params.outputs = []; } + return FunctionFragment.fromObject(params); } - if (options.allowBigInt !== true) { - throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`); + static isFunctionFragment(value) { + return value && value._isFragment && value.type === "function"; } - return new Token(Type.negint, neg1b - BigInt(__int), 9); } -function encodeNegint(buf2, token) { - const negint = token.value; - const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1; - encodeUintValue(buf2, token.type.majorEncoded, unsigned); +function checkForbidden(fragment) { + const sig = fragment.format(); + if (sig === "Error(string)" || sig === "Panic(uint256)") { + logger27.throwArgumentError(`cannot specify user defined ${sig} error`, "fragment", fragment); + } + return fragment; } -encodeNegint.encodedSize = function encodedSize3(token) { - const negint = token.value; - const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1; - if (unsigned < uintBoundaries[0]) { - return 1; +class ErrorFragment extends Fragment { + format(format) { + if (!format) { + format = FormatTypes.sighash; + } + if (!FormatTypes[format]) { + logger27.throwArgumentError("invalid format type", "format", format); + } + if (format === FormatTypes.json) { + return JSON.stringify({ + type: "error", + name: this.name, + inputs: this.inputs.map((input)=>JSON.parse(input.format(format))) + }); + } + let result = ""; + if (format !== FormatTypes.sighash) { + result += "error "; + } + result += this.name + "(" + this.inputs.map((input)=>input.format(format)).join(format === FormatTypes.full ? ", " : ",") + ") "; + return result.trim(); } - if (unsigned < uintBoundaries[1]) { - return 2; + static from(value) { + if (typeof value === "string") { + return ErrorFragment.fromString(value); + } + return ErrorFragment.fromObject(value); } - if (unsigned < uintBoundaries[2]) { - return 3; + static fromObject(value) { + if (ErrorFragment.isErrorFragment(value)) { + return value; + } + if (value.type !== "error") { + logger27.throwArgumentError("invalid error object", "value", value); + } + const params = { + type: value.type, + name: verifyIdentifier(value.name), + inputs: value.inputs ? value.inputs.map(ParamType.fromObject) : [] + }; + return checkForbidden(new ErrorFragment(_constructorGuard1, params)); } - if (unsigned < uintBoundaries[3]) { - return 5; + static fromString(value) { + let params = { + type: "error" + }; + let parens = value.match(regexParen); + if (!parens) { + logger27.throwArgumentError("invalid error signature", "value", value); + } + params.name = parens[1].trim(); + if (params.name) { + verifyIdentifier(params.name); + } + params.inputs = parseParams(parens[2], false); + return checkForbidden(ErrorFragment.fromObject(params)); } - return 9; -}; -encodeNegint.compareTokens = function compareTokens2(tok1, tok2) { - return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0; -}; -function toToken(data, pos, prefix, length) { - assertEnoughData(data, pos, prefix + length); - const buf2 = slice(data, pos + prefix, pos + prefix + length); - return new Token(Type.bytes, buf2, prefix + length); -} -function decodeBytesCompact(data, pos, minor, _options) { - return toToken(data, pos, 1, minor); -} -function decodeBytes8(data, pos, _minor, options) { - return toToken(data, pos, 2, readUint8(data, pos + 1, options)); -} -function decodeBytes16(data, pos, _minor, options) { - return toToken(data, pos, 3, readUint16(data, pos + 1, options)); -} -function decodeBytes32(data, pos, _minor, options) { - return toToken(data, pos, 5, readUint32(data, pos + 1, options)); -} -function decodeBytes64(data, pos, _minor, options) { - const l = readUint64(data, pos + 1, options); - if (typeof l === "bigint") { - throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`); + static isErrorFragment(value) { + return value && value._isFragment && value.type === "error"; } - return toToken(data, pos, 9, l); } -function tokenBytes(token) { - if (token.encodedBytes === void 0) { - token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value; +function verifyType(type) { + if (type.match(/^uint($|[^1-9])/)) { + type = "uint256" + type.substring(4); + } else if (type.match(/^int($|[^1-9])/)) { + type = "int256" + type.substring(3); } - return token.encodedBytes; -} -function encodeBytes(buf2, token) { - const bytes = tokenBytes(token); - encodeUintValue(buf2, token.type.majorEncoded, bytes.length); - buf2.push(bytes); -} -encodeBytes.encodedSize = function encodedSize4(token) { - const bytes = tokenBytes(token); - return encodeUintValue.encodedSize(bytes.length) + bytes.length; -}; -encodeBytes.compareTokens = function compareTokens3(tok1, tok2) { - return compareBytes(tokenBytes(tok1), tokenBytes(tok2)); -}; -function compareBytes(b1, b2) { - return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2); + return type; } -function toToken$1(data, pos, prefix, length, options) { - const totLength = prefix + length; - assertEnoughData(data, pos, totLength); - const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength); - if (options.retainStringBytes === true) { - tok.byteValue = slice(data, pos + prefix, pos + totLength); +const regexIdentifier = new RegExp("^[a-zA-Z$_][a-zA-Z0-9$_]*$"); +function verifyIdentifier(value) { + if (!value || !value.match(regexIdentifier)) { + logger27.throwArgumentError(`invalid identifier "${value}"`, "value", value); } - return tok; -} -function decodeStringCompact(data, pos, minor, options) { - return toToken$1(data, pos, 1, minor, options); -} -function decodeString8(data, pos, _minor, options) { - return toToken$1(data, pos, 2, readUint8(data, pos + 1, options), options); + return value; } -function decodeString16(data, pos, _minor, options) { - return toToken$1(data, pos, 3, readUint16(data, pos + 1, options), options); +const regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"); +function splitNesting(value) { + value = value.trim(); + let result = []; + let accum = ""; + let depth = 0; + for(let offset = 0; offset < value.length; offset++){ + let c = value[offset]; + if (c === "," && depth === 0) { + result.push(accum); + accum = ""; + } else { + accum += c; + if (c === "(") { + depth++; + } else if (c === ")") { + depth--; + if (depth === -1) { + logger27.throwArgumentError("unbalanced parenthesis", "value", value); + } + } + } + } + if (accum) { + result.push(accum); + } + return result; } -function decodeString32(data, pos, _minor, options) { - return toToken$1(data, pos, 5, readUint32(data, pos + 1, options), options); +const logger$12 = new Logger(version9); +function checkResultErrors(result) { + const errors = []; + const checkErrors = function(path, object) { + if (!Array.isArray(object)) { + return; + } + for(let key in object){ + const childPath = path.slice(); + childPath.push(key); + try { + checkErrors(childPath, object[key]); + } catch (error) { + errors.push({ + path: childPath, + error + }); + } + } + }; + checkErrors([], result); + return errors; } -function decodeString64(data, pos, _minor, options) { - const l = readUint64(data, pos + 1, options); - if (typeof l === "bigint") { - throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`); +class Coder { + constructor(name, type, localName, dynamic){ + this.name = name; + this.type = type; + this.localName = localName; + this.dynamic = dynamic; + } + _throwError(message, value) { + logger$12.throwArgumentError(message, this.localName, value); } - return toToken$1(data, pos, 9, l, options); -} -const encodeString = encodeBytes; -function toToken$2(_data, _pos, prefix, length) { - return new Token(Type.array, length, prefix); } -function decodeArrayCompact(data, pos, minor, _options) { - return toToken$2(data, pos, 1, minor); +class Writer { + constructor(wordSize){ + defineReadOnly(this, "wordSize", wordSize || 32); + this._data = []; + this._dataLength = 0; + this._padding = new Uint8Array(wordSize); + } + get data() { + return hexConcat(this._data); + } + get length() { + return this._dataLength; + } + _writeData(data) { + this._data.push(data); + this._dataLength += data.length; + return data.length; + } + appendWriter(writer) { + return this._writeData(concat(writer._data)); + } + writeBytes(value) { + let bytes2 = arrayify(value); + const paddingOffset = bytes2.length % this.wordSize; + if (paddingOffset) { + bytes2 = concat([ + bytes2, + this._padding.slice(paddingOffset) + ]); + } + return this._writeData(bytes2); + } + _getValue(value) { + let bytes2 = arrayify(BigNumber.from(value)); + if (bytes2.length > this.wordSize) { + logger$12.throwError("value out-of-bounds", Logger.errors.BUFFER_OVERRUN, { + length: this.wordSize, + offset: bytes2.length + }); + } + if (bytes2.length % this.wordSize) { + bytes2 = concat([ + this._padding.slice(bytes2.length % this.wordSize), + bytes2 + ]); + } + return bytes2; + } + writeValue(value) { + return this._writeData(this._getValue(value)); + } + writeUpdatableValue() { + const offset = this._data.length; + this._data.push(this._padding); + this._dataLength += this.wordSize; + return (value)=>{ + this._data[offset] = this._getValue(value); + }; + } } -function decodeArray8(data, pos, _minor, options) { - return toToken$2(data, pos, 2, readUint8(data, pos + 1, options)); +class Reader { + constructor(data, wordSize, coerceFunc, allowLoose){ + defineReadOnly(this, "_data", arrayify(data)); + defineReadOnly(this, "wordSize", wordSize || 32); + defineReadOnly(this, "_coerceFunc", coerceFunc); + defineReadOnly(this, "allowLoose", allowLoose); + this._offset = 0; + } + get data() { + return hexlify(this._data); + } + get consumed() { + return this._offset; + } + static coerce(name, value) { + let match = name.match("^u?int([0-9]+)$"); + if (match && parseInt(match[1]) <= 48) { + value = value.toNumber(); + } + return value; + } + coerce(name, value) { + if (this._coerceFunc) { + return this._coerceFunc(name, value); + } + return Reader.coerce(name, value); + } + _peekBytes(offset, length, loose) { + let alignedLength = Math.ceil(length / this.wordSize) * this.wordSize; + if (this._offset + alignedLength > this._data.length) { + if (this.allowLoose && loose && this._offset + length <= this._data.length) { + alignedLength = length; + } else { + logger$12.throwError("data out-of-bounds", Logger.errors.BUFFER_OVERRUN, { + length: this._data.length, + offset: this._offset + alignedLength + }); + } + } + return this._data.slice(this._offset, this._offset + alignedLength); + } + subReader(offset) { + return new Reader(this._data.slice(this._offset + offset), this.wordSize, this._coerceFunc, this.allowLoose); + } + readBytes(length, loose) { + let bytes2 = this._peekBytes(0, length, !!loose); + this._offset += bytes2.length; + return bytes2.slice(0, length); + } + readValue() { + return BigNumber.from(this.readBytes(this.wordSize)); + } } -function decodeArray16(data, pos, _minor, options) { - return toToken$2(data, pos, 3, readUint16(data, pos + 1, options)); +class AddressCoder extends Coder { + constructor(localName){ + super("address", "address", localName, false); + } + defaultValue() { + return "0x0000000000000000000000000000000000000000"; + } + encode(writer, value) { + try { + value = getAddress(value); + } catch (error) { + this._throwError(error.message, value); + } + return writer.writeValue(value); + } + decode(reader) { + return getAddress(hexZeroPad(reader.readValue().toHexString(), 20)); + } } -function decodeArray32(data, pos, _minor, options) { - return toToken$2(data, pos, 5, readUint32(data, pos + 1, options)); +class AnonymousCoder extends Coder { + constructor(coder){ + super(coder.name, coder.type, void 0, coder.dynamic); + this.coder = coder; + } + defaultValue() { + return this.coder.defaultValue(); + } + encode(writer, value) { + return this.coder.encode(writer, value); + } + decode(reader) { + return this.coder.decode(reader); + } } -function decodeArray64(data, pos, _minor, options) { - const l = readUint64(data, pos + 1, options); - if (typeof l === "bigint") { - throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`); +const logger$2 = new Logger(version9); +function pack(writer, coders, values) { + let arrayValues = null; + if (Array.isArray(values)) { + arrayValues = values; + } else if (values && typeof values === "object") { + let unique = {}; + arrayValues = coders.map((coder)=>{ + const name = coder.localName; + if (!name) { + logger$2.throwError("cannot encode object for signature with missing names", Logger.errors.INVALID_ARGUMENT, { + argument: "values", + coder, + value: values + }); + } + if (unique[name]) { + logger$2.throwError("cannot encode object for signature with duplicate names", Logger.errors.INVALID_ARGUMENT, { + argument: "values", + coder, + value: values + }); + } + unique[name] = true; + return values[name]; + }); + } else { + logger$2.throwArgumentError("invalid tuple value", "tuple", values); + } + if (coders.length !== arrayValues.length) { + logger$2.throwArgumentError("types/value length mismatch", "tuple", values); + } + let staticWriter = new Writer(writer.wordSize); + let dynamicWriter = new Writer(writer.wordSize); + let updateFuncs = []; + coders.forEach((coder, index)=>{ + let value = arrayValues[index]; + if (coder.dynamic) { + let dynamicOffset = dynamicWriter.length; + coder.encode(dynamicWriter, value); + let updateFunc = staticWriter.writeUpdatableValue(); + updateFuncs.push((baseOffset)=>{ + updateFunc(baseOffset + dynamicOffset); + }); + } else { + coder.encode(staticWriter, value); + } + }); + updateFuncs.forEach((func)=>{ + func(staticWriter.length); + }); + let length = writer.appendWriter(staticWriter); + length += writer.appendWriter(dynamicWriter); + return length; +} +function unpack(reader, coders) { + let values = []; + let baseReader = reader.subReader(0); + coders.forEach((coder)=>{ + let value = null; + if (coder.dynamic) { + let offset = reader.readValue(); + let offsetReader = baseReader.subReader(offset.toNumber()); + try { + value = coder.decode(offsetReader); + } catch (error) { + if (error.code === Logger.errors.BUFFER_OVERRUN) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } else { + try { + value = coder.decode(reader); + } catch (error) { + if (error.code === Logger.errors.BUFFER_OVERRUN) { + throw error; + } + value = error; + value.baseType = coder.name; + value.name = coder.localName; + value.type = coder.type; + } + } + if (value != void 0) { + values.push(value); + } + }); + const uniqueNames = coders.reduce((accum, coder)=>{ + const name = coder.localName; + if (name) { + if (!accum[name]) { + accum[name] = 0; + } + accum[name]++; + } + return accum; + }, {}); + coders.forEach((coder, index)=>{ + let name = coder.localName; + if (!name || uniqueNames[name] !== 1) { + return; + } + if (name === "length") { + name = "_length"; + } + if (values[name] != null) { + return; + } + const value = values[index]; + if (value instanceof Error) { + Object.defineProperty(values, name, { + enumerable: true, + get: ()=>{ + throw value; + } + }); + } else { + values[name] = value; + } + }); + for(let i = 0; i < values.length; i++){ + const value = values[i]; + if (value instanceof Error) { + Object.defineProperty(values, i, { + enumerable: true, + get: ()=>{ + throw value; + } + }); + } } - return toToken$2(data, pos, 9, l); -} -function decodeArrayIndefinite(data, pos, _minor, options) { - if (options.allowIndefinite === false) { - throw new Error(`${decodeErrPrefix} indefinite length items not allowed`); + return Object.freeze(values); +} +class ArrayCoder extends Coder { + constructor(coder, length, localName){ + const type = coder.type + "[" + (length >= 0 ? length : "") + "]"; + const dynamic = length === -1 || coder.dynamic; + super("array", type, localName, dynamic); + this.coder = coder; + this.length = length; + } + defaultValue() { + const defaultChild = this.coder.defaultValue(); + const result = []; + for(let i = 0; i < this.length; i++){ + result.push(defaultChild); + } + return result; + } + encode(writer, value) { + if (!Array.isArray(value)) { + this._throwError("expected array value", value); + } + let count = this.length; + if (count === -1) { + count = value.length; + writer.writeValue(value.length); + } + logger$2.checkArgumentCount(value.length, count, "coder array" + (this.localName ? " " + this.localName : "")); + let coders = []; + for(let i = 0; i < value.length; i++){ + coders.push(this.coder); + } + return pack(writer, coders, value); + } + decode(reader) { + let count = this.length; + if (count === -1) { + count = reader.readValue().toNumber(); + if (count * 32 > reader._data.length) { + logger$2.throwError("insufficient data length", Logger.errors.BUFFER_OVERRUN, { + length: reader._data.length, + count + }); + } + } + let coders = []; + for(let i = 0; i < count; i++){ + coders.push(new AnonymousCoder(this.coder)); + } + return reader.coerce(this.name, unpack(reader, coders)); } - return toToken$2(data, pos, 1, Infinity); -} -function encodeArray(buf2, token) { - encodeUintValue(buf2, Type.array.majorEncoded, token.value); -} -encodeArray.compareTokens = encodeUint.compareTokens; -encodeArray.encodedSize = function encodedSize5(token) { - return encodeUintValue.encodedSize(token.value); -}; -function toToken$3(_data, _pos, prefix, length) { - return new Token(Type.map, length, prefix); } -function decodeMapCompact(data, pos, minor, _options) { - return toToken$3(data, pos, 1, minor); -} -function decodeMap8(data, pos, _minor, options) { - return toToken$3(data, pos, 2, readUint8(data, pos + 1, options)); +class BooleanCoder extends Coder { + constructor(localName){ + super("bool", "bool", localName, false); + } + defaultValue() { + return false; + } + encode(writer, value) { + return writer.writeValue(value ? 1 : 0); + } + decode(reader) { + return reader.coerce(this.type, !reader.readValue().isZero()); + } } -function decodeMap16(data, pos, _minor, options) { - return toToken$3(data, pos, 3, readUint16(data, pos + 1, options)); +class DynamicBytesCoder extends Coder { + constructor(type, localName){ + super(type, type, localName, true); + } + defaultValue() { + return "0x"; + } + encode(writer, value) { + value = arrayify(value); + let length = writer.writeValue(value.length); + length += writer.writeBytes(value); + return length; + } + decode(reader) { + return reader.readBytes(reader.readValue().toNumber(), true); + } } -function decodeMap32(data, pos, _minor, options) { - return toToken$3(data, pos, 5, readUint32(data, pos + 1, options)); +class BytesCoder extends DynamicBytesCoder { + constructor(localName){ + super("bytes", localName); + } + decode(reader) { + return reader.coerce(this.name, hexlify(super.decode(reader))); + } } -function decodeMap64(data, pos, _minor, options) { - const l = readUint64(data, pos + 1, options); - if (typeof l === "bigint") { - throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`); +class FixedBytesCoder extends Coder { + constructor(size, localName){ + let name = "bytes" + String(size); + super(name, name, localName, false); + this.size = size; + } + defaultValue() { + return "0x0000000000000000000000000000000000000000000000000000000000000000".substring(0, 2 + this.size * 2); + } + encode(writer, value) { + let data = arrayify(value); + if (data.length !== this.size) { + this._throwError("incorrect data length", value); + } + return writer.writeBytes(data); + } + decode(reader) { + return reader.coerce(this.name, hexlify(reader.readBytes(this.size))); } - return toToken$3(data, pos, 9, l); } -function decodeMapIndefinite(data, pos, _minor, options) { - if (options.allowIndefinite === false) { - throw new Error(`${decodeErrPrefix} indefinite length items not allowed`); +class NullCoder extends Coder { + constructor(localName){ + super("null", "", localName, false); + } + defaultValue() { + return null; + } + encode(writer, value) { + if (value != null) { + this._throwError("not null", value); + } + return writer.writeBytes([]); + } + decode(reader) { + reader.readBytes(0); + return reader.coerce(this.name, null); } - return toToken$3(data, pos, 1, Infinity); } -function encodeMap(buf2, token) { - encodeUintValue(buf2, Type.map.majorEncoded, token.value); +class NumberCoder extends Coder { + constructor(size, signed, localName){ + const name = (signed ? "int" : "uint") + size * 8; + super(name, name, localName, false); + this.size = size; + this.signed = signed; + } + defaultValue() { + return 0; + } + encode(writer, value) { + let v = BigNumber.from(value); + let maxUintValue = MaxUint256.mask(writer.wordSize * 8); + if (this.signed) { + let bounds = maxUintValue.mask(this.size * 8 - 1); + if (v.gt(bounds) || v.lt(bounds.add(One).mul(NegativeOne1))) { + this._throwError("value out-of-bounds", value); + } + } else if (v.lt(Zero1) || v.gt(maxUintValue.mask(this.size * 8))) { + this._throwError("value out-of-bounds", value); + } + v = v.toTwos(this.size * 8).mask(this.size * 8); + if (this.signed) { + v = v.fromTwos(this.size * 8).toTwos(8 * writer.wordSize); + } + return writer.writeValue(v); + } + decode(reader) { + let value = reader.readValue().mask(this.size * 8); + if (this.signed) { + value = value.fromTwos(this.size * 8); + } + return reader.coerce(this.name, value); + } } -encodeMap.compareTokens = encodeUint.compareTokens; -encodeMap.encodedSize = function encodedSize6(token) { - return encodeUintValue.encodedSize(token.value); -}; -function decodeTagCompact(_data, _pos, minor, _options) { - return new Token(Type.tag, minor, 1); +class StringCoder extends DynamicBytesCoder { + constructor(localName){ + super("string", localName); + } + defaultValue() { + return ""; + } + encode(writer, value) { + return super.encode(writer, toUtf8Bytes(value)); + } + decode(reader) { + return toUtf8String(super.decode(reader)); + } } -function decodeTag8(data, pos, _minor, options) { - return new Token(Type.tag, readUint8(data, pos + 1, options), 2); +class TupleCoder extends Coder { + constructor(coders, localName){ + let dynamic = false; + const types = []; + coders.forEach((coder)=>{ + if (coder.dynamic) { + dynamic = true; + } + types.push(coder.type); + }); + const type = "tuple(" + types.join(",") + ")"; + super("tuple", type, localName, dynamic); + this.coders = coders; + } + defaultValue() { + const values = []; + this.coders.forEach((coder)=>{ + values.push(coder.defaultValue()); + }); + const uniqueNames = this.coders.reduce((accum, coder)=>{ + const name = coder.localName; + if (name) { + if (!accum[name]) { + accum[name] = 0; + } + accum[name]++; + } + return accum; + }, {}); + this.coders.forEach((coder, index)=>{ + let name = coder.localName; + if (!name || uniqueNames[name] !== 1) { + return; + } + if (name === "length") { + name = "_length"; + } + if (values[name] != null) { + return; + } + values[name] = values[index]; + }); + return Object.freeze(values); + } + encode(writer, value) { + return pack(writer, this.coders, value); + } + decode(reader) { + return reader.coerce(this.name, unpack(reader, this.coders)); + } +} +const logger$3 = new Logger(version9); +const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); +const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); +class AbiCoder { + constructor(coerceFunc){ + defineReadOnly(this, "coerceFunc", coerceFunc || null); + } + _getCoder(param) { + switch(param.baseType){ + case "address": + return new AddressCoder(param.name); + case "bool": + return new BooleanCoder(param.name); + case "string": + return new StringCoder(param.name); + case "bytes": + return new BytesCoder(param.name); + case "array": + return new ArrayCoder(this._getCoder(param.arrayChildren), param.arrayLength, param.name); + case "tuple": + return new TupleCoder((param.components || []).map((component)=>{ + return this._getCoder(component); + }), param.name); + case "": + return new NullCoder(param.name); + } + let match = param.type.match(paramTypeNumber); + if (match) { + let size = parseInt(match[2] || "256"); + if (size === 0 || size > 256 || size % 8 !== 0) { + logger$3.throwArgumentError("invalid " + match[1] + " bit length", "param", param); + } + return new NumberCoder(size / 8, match[1] === "int", param.name); + } + match = param.type.match(paramTypeBytes); + if (match) { + let size = parseInt(match[1]); + if (size === 0 || size > 32) { + logger$3.throwArgumentError("invalid bytes length", "param", param); + } + return new FixedBytesCoder(size, param.name); + } + return logger$3.throwArgumentError("invalid type", "type", param.type); + } + _getWordSize() { + return 32; + } + _getReader(data, allowLoose) { + return new Reader(data, this._getWordSize(), this.coerceFunc, allowLoose); + } + _getWriter() { + return new Writer(this._getWordSize()); + } + getDefaultValue(types) { + const coders = types.map((type)=>this._getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.defaultValue(); + } + encode(types, values) { + if (types.length !== values.length) { + logger$3.throwError("types/values length mismatch", Logger.errors.INVALID_ARGUMENT, { + count: { + types: types.length, + values: values.length + }, + value: { + types, + values + } + }); + } + const coders = types.map((type)=>this._getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + const writer = this._getWriter(); + coder.encode(writer, values); + return writer.data; + } + decode(types, data, loose) { + const coders = types.map((type)=>this._getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.decode(this._getReader(arrayify(data), loose)); + } } -function decodeTag16(data, pos, _minor, options) { - return new Token(Type.tag, readUint16(data, pos + 1, options), 3); +const defaultAbiCoder = new AbiCoder(); +const logger$4 = new Logger(version9); +class LogDescription extends Description { } -function decodeTag32(data, pos, _minor, options) { - return new Token(Type.tag, readUint32(data, pos + 1, options), 5); +class TransactionDescription extends Description { } -function decodeTag64(data, pos, _minor, options) { - return new Token(Type.tag, readUint64(data, pos + 1, options), 9); +class ErrorDescription extends Description { } -function encodeTag(buf2, token) { - encodeUintValue(buf2, Type.tag.majorEncoded, token.value); +class Indexed extends Description { + static isIndexed(value) { + return !!(value && value._isIndexed); + } } -encodeTag.compareTokens = encodeUint.compareTokens; -encodeTag.encodedSize = function encodedSize7(token) { - return encodeUintValue.encodedSize(token.value); +const BuiltinErrors = { + "0x08c379a0": { + signature: "Error(string)", + name: "Error", + inputs: [ + "string" + ], + reason: true + }, + "0x4e487b71": { + signature: "Panic(uint256)", + name: "Panic", + inputs: [ + "uint256" + ] + } }; -function decodeUndefined(_data, _pos, _minor, options) { - if (options.allowUndefined === false) { - throw new Error(`${decodeErrPrefix} undefined values are not supported`); - } else if (options.coerceUndefinedToNull === true) { - return new Token(Type.null, null, 1); +function wrapAccessError(property, error) { + const wrap = new Error(`deferred error during ABI decoding triggered accessing ${property}`); + wrap.error = error; + return wrap; +} +class Interface { + constructor(fragments){ + let abi = []; + if (typeof fragments === "string") { + abi = JSON.parse(fragments); + } else { + abi = fragments; + } + defineReadOnly(this, "fragments", abi.map((fragment)=>{ + return Fragment.from(fragment); + }).filter((fragment)=>fragment != null)); + defineReadOnly(this, "_abiCoder", getStatic(new.target, "getAbiCoder")()); + defineReadOnly(this, "functions", {}); + defineReadOnly(this, "errors", {}); + defineReadOnly(this, "events", {}); + defineReadOnly(this, "structs", {}); + this.fragments.forEach((fragment)=>{ + let bucket = null; + switch(fragment.type){ + case "constructor": + if (this.deploy) { + logger$4.warn("duplicate definition - constructor"); + return; + } + defineReadOnly(this, "deploy", fragment); + return; + case "function": + bucket = this.functions; + break; + case "event": + bucket = this.events; + break; + case "error": + bucket = this.errors; + break; + default: + return; + } + let signature = fragment.format(); + if (bucket[signature]) { + logger$4.warn("duplicate definition - " + signature); + return; + } + bucket[signature] = fragment; + }); + if (!this.deploy) { + defineReadOnly(this, "deploy", ConstructorFragment.from({ + payable: false, + type: "constructor" + })); + } + defineReadOnly(this, "_isInterface", true); + } + format(format) { + if (!format) { + format = FormatTypes.full; + } + if (format === FormatTypes.sighash) { + logger$4.throwArgumentError("interface does not support formatting sighash", "format", format); + } + const abi = this.fragments.map((fragment)=>fragment.format(format)); + if (format === FormatTypes.json) { + return JSON.stringify(abi.map((j)=>JSON.parse(j))); + } + return abi; + } + static getAbiCoder() { + return defaultAbiCoder; + } + static getAddress(address2) { + return getAddress(address2); + } + static getSighash(fragment) { + return hexDataSlice(id(fragment.format()), 0, 4); + } + static getEventTopic(eventFragment) { + return id(eventFragment.format()); + } + getFunction(nameOrSignatureOrSighash) { + if (isHexString(nameOrSignatureOrSighash)) { + for(const name in this.functions){ + if (nameOrSignatureOrSighash === this.getSighash(name)) { + return this.functions[name]; + } + } + logger$4.throwArgumentError("no matching function", "sighash", nameOrSignatureOrSighash); + } + if (nameOrSignatureOrSighash.indexOf("(") === -1) { + const name = nameOrSignatureOrSighash.trim(); + const matching = Object.keys(this.functions).filter((f)=>f.split("(")[0] === name); + if (matching.length === 0) { + logger$4.throwArgumentError("no matching function", "name", name); + } else if (matching.length > 1) { + logger$4.throwArgumentError("multiple matching functions", "name", name); + } + return this.functions[matching[0]]; + } + const result = this.functions[FunctionFragment.fromString(nameOrSignatureOrSighash).format()]; + if (!result) { + logger$4.throwArgumentError("no matching function", "signature", nameOrSignatureOrSighash); + } + return result; + } + getEvent(nameOrSignatureOrTopic) { + if (isHexString(nameOrSignatureOrTopic)) { + const topichash = nameOrSignatureOrTopic.toLowerCase(); + for(const name in this.events){ + if (topichash === this.getEventTopic(name)) { + return this.events[name]; + } + } + logger$4.throwArgumentError("no matching event", "topichash", topichash); + } + if (nameOrSignatureOrTopic.indexOf("(") === -1) { + const name = nameOrSignatureOrTopic.trim(); + const matching = Object.keys(this.events).filter((f)=>f.split("(")[0] === name); + if (matching.length === 0) { + logger$4.throwArgumentError("no matching event", "name", name); + } else if (matching.length > 1) { + logger$4.throwArgumentError("multiple matching events", "name", name); + } + return this.events[matching[0]]; + } + const result = this.events[EventFragment.fromString(nameOrSignatureOrTopic).format()]; + if (!result) { + logger$4.throwArgumentError("no matching event", "signature", nameOrSignatureOrTopic); + } + return result; + } + getError(nameOrSignatureOrSighash) { + if (isHexString(nameOrSignatureOrSighash)) { + const getSighash = getStatic(this.constructor, "getSighash"); + for(const name in this.errors){ + const error = this.errors[name]; + if (nameOrSignatureOrSighash === getSighash(error)) { + return this.errors[name]; + } + } + logger$4.throwArgumentError("no matching error", "sighash", nameOrSignatureOrSighash); + } + if (nameOrSignatureOrSighash.indexOf("(") === -1) { + const name = nameOrSignatureOrSighash.trim(); + const matching = Object.keys(this.errors).filter((f)=>f.split("(")[0] === name); + if (matching.length === 0) { + logger$4.throwArgumentError("no matching error", "name", name); + } else if (matching.length > 1) { + logger$4.throwArgumentError("multiple matching errors", "name", name); + } + return this.errors[matching[0]]; + } + const result = this.errors[FunctionFragment.fromString(nameOrSignatureOrSighash).format()]; + if (!result) { + logger$4.throwArgumentError("no matching error", "signature", nameOrSignatureOrSighash); + } + return result; + } + getSighash(fragment) { + if (typeof fragment === "string") { + try { + fragment = this.getFunction(fragment); + } catch (error) { + try { + fragment = this.getError(fragment); + } catch (_) { + throw error; + } + } + } + return getStatic(this.constructor, "getSighash")(fragment); + } + getEventTopic(eventFragment) { + if (typeof eventFragment === "string") { + eventFragment = this.getEvent(eventFragment); + } + return getStatic(this.constructor, "getEventTopic")(eventFragment); + } + _decodeParams(params, data) { + return this._abiCoder.decode(params, data); + } + _encodeParams(params, values) { + return this._abiCoder.encode(params, values); + } + encodeDeploy(values) { + return this._encodeParams(this.deploy.inputs, values || []); + } + decodeErrorResult(fragment, data) { + if (typeof fragment === "string") { + fragment = this.getError(fragment); + } + const bytes2 = arrayify(data); + if (hexlify(bytes2.slice(0, 4)) !== this.getSighash(fragment)) { + logger$4.throwArgumentError(`data signature does not match error ${fragment.name}.`, "data", hexlify(bytes2)); + } + return this._decodeParams(fragment.inputs, bytes2.slice(4)); + } + encodeErrorResult(fragment, values) { + if (typeof fragment === "string") { + fragment = this.getError(fragment); + } + return hexlify(concat([ + this.getSighash(fragment), + this._encodeParams(fragment.inputs, values || []) + ])); + } + decodeFunctionData(functionFragment, data) { + if (typeof functionFragment === "string") { + functionFragment = this.getFunction(functionFragment); + } + const bytes2 = arrayify(data); + if (hexlify(bytes2.slice(0, 4)) !== this.getSighash(functionFragment)) { + logger$4.throwArgumentError(`data signature does not match function ${functionFragment.name}.`, "data", hexlify(bytes2)); + } + return this._decodeParams(functionFragment.inputs, bytes2.slice(4)); + } + encodeFunctionData(functionFragment, values) { + if (typeof functionFragment === "string") { + functionFragment = this.getFunction(functionFragment); + } + return hexlify(concat([ + this.getSighash(functionFragment), + this._encodeParams(functionFragment.inputs, values || []) + ])); + } + decodeFunctionResult(functionFragment, data) { + if (typeof functionFragment === "string") { + functionFragment = this.getFunction(functionFragment); + } + let bytes2 = arrayify(data); + let reason = null; + let message = ""; + let errorArgs = null; + let errorName = null; + let errorSignature = null; + switch(bytes2.length % this._abiCoder._getWordSize()){ + case 0: + try { + return this._abiCoder.decode(functionFragment.outputs, bytes2); + } catch (error) {} + break; + case 4: + { + const selector = hexlify(bytes2.slice(0, 4)); + const builtin = BuiltinErrors[selector]; + if (builtin) { + errorArgs = this._abiCoder.decode(builtin.inputs, bytes2.slice(4)); + errorName = builtin.name; + errorSignature = builtin.signature; + if (builtin.reason) { + reason = errorArgs[0]; + } + if (errorName === "Error") { + message = `; VM Exception while processing transaction: reverted with reason string ${JSON.stringify(errorArgs[0])}`; + } else if (errorName === "Panic") { + message = `; VM Exception while processing transaction: reverted with panic code ${errorArgs[0]}`; + } + } else { + try { + const error = this.getError(selector); + errorArgs = this._abiCoder.decode(error.inputs, bytes2.slice(4)); + errorName = error.name; + errorSignature = error.format(); + } catch (error) {} + } + break; + } + } + return logger$4.throwError("call revert exception" + message, Logger.errors.CALL_EXCEPTION, { + method: functionFragment.format(), + data: hexlify(data), + errorArgs, + errorName, + errorSignature, + reason + }); + } + encodeFunctionResult(functionFragment, values) { + if (typeof functionFragment === "string") { + functionFragment = this.getFunction(functionFragment); + } + return hexlify(this._abiCoder.encode(functionFragment.outputs, values || [])); + } + encodeFilterTopics(eventFragment, values) { + if (typeof eventFragment === "string") { + eventFragment = this.getEvent(eventFragment); + } + if (values.length > eventFragment.inputs.length) { + logger$4.throwError("too many arguments for " + eventFragment.format(), Logger.errors.UNEXPECTED_ARGUMENT, { + argument: "values", + value: values + }); + } + let topics = []; + if (!eventFragment.anonymous) { + topics.push(this.getEventTopic(eventFragment)); + } + const encodeTopic = (param, value)=>{ + if (param.type === "string") { + return id(value); + } else if (param.type === "bytes") { + return keccak256(hexlify(value)); + } + if (param.type === "bool" && typeof value === "boolean") { + value = value ? "0x01" : "0x00"; + } + if (param.type.match(/^u?int/)) { + value = BigNumber.from(value).toHexString(); + } + if (param.type === "address") { + this._abiCoder.encode([ + "address" + ], [ + value + ]); + } + return hexZeroPad(hexlify(value), 32); + }; + values.forEach((value, index)=>{ + let param = eventFragment.inputs[index]; + if (!param.indexed) { + if (value != null) { + logger$4.throwArgumentError("cannot filter non-indexed parameters; must be null", "contract." + param.name, value); + } + return; + } + if (value == null) { + topics.push(null); + } else if (param.baseType === "array" || param.baseType === "tuple") { + logger$4.throwArgumentError("filtering with tuples or arrays not supported", "contract." + param.name, value); + } else if (Array.isArray(value)) { + topics.push(value.map((value2)=>encodeTopic(param, value2))); + } else { + topics.push(encodeTopic(param, value)); + } + }); + while(topics.length && topics[topics.length - 1] === null){ + topics.pop(); + } + return topics; + } + encodeEventLog(eventFragment, values) { + if (typeof eventFragment === "string") { + eventFragment = this.getEvent(eventFragment); + } + const topics = []; + const dataTypes = []; + const dataValues = []; + if (!eventFragment.anonymous) { + topics.push(this.getEventTopic(eventFragment)); + } + if (values.length !== eventFragment.inputs.length) { + logger$4.throwArgumentError("event arguments/values mismatch", "values", values); + } + eventFragment.inputs.forEach((param, index)=>{ + const value = values[index]; + if (param.indexed) { + if (param.type === "string") { + topics.push(id(value)); + } else if (param.type === "bytes") { + topics.push(keccak256(value)); + } else if (param.baseType === "tuple" || param.baseType === "array") { + throw new Error("not implemented"); + } else { + topics.push(this._abiCoder.encode([ + param.type + ], [ + value + ])); + } + } else { + dataTypes.push(param); + dataValues.push(value); + } + }); + return { + data: this._abiCoder.encode(dataTypes, dataValues), + topics + }; + } + decodeEventLog(eventFragment, data, topics) { + if (typeof eventFragment === "string") { + eventFragment = this.getEvent(eventFragment); + } + if (topics != null && !eventFragment.anonymous) { + let topicHash = this.getEventTopic(eventFragment); + if (!isHexString(topics[0], 32) || topics[0].toLowerCase() !== topicHash) { + logger$4.throwError("fragment/topic mismatch", Logger.errors.INVALID_ARGUMENT, { + argument: "topics[0]", + expected: topicHash, + value: topics[0] + }); + } + topics = topics.slice(1); + } + let indexed = []; + let nonIndexed = []; + let dynamic = []; + eventFragment.inputs.forEach((param, index)=>{ + if (param.indexed) { + if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") { + indexed.push(ParamType.fromObject({ + type: "bytes32", + name: param.name + })); + dynamic.push(true); + } else { + indexed.push(param); + dynamic.push(false); + } + } else { + nonIndexed.push(param); + dynamic.push(false); + } + }); + let resultIndexed = topics != null ? this._abiCoder.decode(indexed, concat(topics)) : null; + let resultNonIndexed = this._abiCoder.decode(nonIndexed, data, true); + let result = []; + let nonIndexedIndex = 0, indexedIndex = 0; + eventFragment.inputs.forEach((param, index)=>{ + if (param.indexed) { + if (resultIndexed == null) { + result[index] = new Indexed({ + _isIndexed: true, + hash: null + }); + } else if (dynamic[index]) { + result[index] = new Indexed({ + _isIndexed: true, + hash: resultIndexed[indexedIndex++] + }); + } else { + try { + result[index] = resultIndexed[indexedIndex++]; + } catch (error) { + result[index] = error; + } + } + } else { + try { + result[index] = resultNonIndexed[nonIndexedIndex++]; + } catch (error) { + result[index] = error; + } + } + if (param.name && result[param.name] == null) { + const value = result[index]; + if (value instanceof Error) { + Object.defineProperty(result, param.name, { + enumerable: true, + get: ()=>{ + throw wrapAccessError(`property ${JSON.stringify(param.name)}`, value); + } + }); + } else { + result[param.name] = value; + } + } + }); + for(let i = 0; i < result.length; i++){ + const value = result[i]; + if (value instanceof Error) { + Object.defineProperty(result, i, { + enumerable: true, + get: ()=>{ + throw wrapAccessError(`index ${i}`, value); + } + }); + } + } + return Object.freeze(result); + } + parseTransaction(tx) { + let fragment = this.getFunction(tx.data.substring(0, 10).toLowerCase()); + if (!fragment) { + return null; + } + return new TransactionDescription({ + args: this._abiCoder.decode(fragment.inputs, "0x" + tx.data.substring(10)), + functionFragment: fragment, + name: fragment.name, + signature: fragment.format(), + sighash: this.getSighash(fragment), + value: BigNumber.from(tx.value || "0") + }); + } + parseLog(log) { + let fragment = this.getEvent(log.topics[0]); + if (!fragment || fragment.anonymous) { + return null; + } + return new LogDescription({ + eventFragment: fragment, + name: fragment.name, + signature: fragment.format(), + topic: this.getEventTopic(fragment), + args: this.decodeEventLog(fragment, log.data, log.topics) + }); } - return new Token(Type.undefined, void 0, 1); -} -function decodeBreak(_data, _pos, _minor, options) { - if (options.allowIndefinite === false) { - throw new Error(`${decodeErrPrefix} indefinite length items not allowed`); + parseError(data) { + const hexData = hexlify(data); + let fragment = this.getError(hexData.substring(0, 10).toLowerCase()); + if (!fragment) { + return null; + } + return new ErrorDescription({ + args: this._abiCoder.decode(fragment.inputs, "0x" + hexData.substring(10)), + errorFragment: fragment, + name: fragment.name, + signature: fragment.format(), + sighash: this.getSighash(fragment) + }); + } + static isInterface(value) { + return !!(value && value._isInterface); } - return new Token(Type.break, void 0, 1); } -function createToken(value, bytes, options) { - if (options) { - if (options.allowNaN === false && Number.isNaN(value)) { - throw new Error(`${decodeErrPrefix} NaN values are not supported`); +const version10 = "abstract-provider/5.7.0"; +var __awaiter2 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) { - throw new Error(`${decodeErrPrefix} Infinity values are not supported`); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger28 = new Logger(version10); +class ForkEvent extends Description { + static isForkEvent(value) { + return !!(value && value._isForkEvent); } - return new Token(Type.float, value, bytes); -} -function decodeFloat16(data, pos, _minor, options) { - return createToken(readFloat16(data, pos + 1), 3, options); -} -function decodeFloat32(data, pos, _minor, options) { - return createToken(readFloat32(data, pos + 1), 5, options); } -function decodeFloat64(data, pos, _minor, options) { - return createToken(readFloat64(data, pos + 1), 9, options); +class Provider { + constructor(){ + logger28.checkAbstract(new.target, Provider); + defineReadOnly(this, "_isProvider", true); + } + getFeeData() { + return __awaiter2(this, void 0, void 0, function*() { + const { block, gasPrice } = yield resolveProperties({ + block: this.getBlock("latest"), + gasPrice: this.getGasPrice().catch((error)=>{ + return null; + }) + }); + let lastBaseFeePerGas = null, maxFeePerGas = null, maxPriorityFeePerGas = null; + if (block && block.baseFeePerGas) { + lastBaseFeePerGas = block.baseFeePerGas; + maxPriorityFeePerGas = BigNumber.from("1500000000"); + maxFeePerGas = block.baseFeePerGas.mul(2).add(maxPriorityFeePerGas); + } + return { + lastBaseFeePerGas, + maxFeePerGas, + maxPriorityFeePerGas, + gasPrice + }; + }); + } + addListener(eventName, listener) { + return this.on(eventName, listener); + } + removeListener(eventName, listener) { + return this.off(eventName, listener); + } + static isProvider(value) { + return !!(value && value._isProvider); + } } -function encodeFloat(buf2, token, options) { - const __float = token.value; - if (__float === false) { - buf2.push([ - Type.float.majorEncoded | 20 - ]); - } else if (__float === true) { - buf2.push([ - Type.float.majorEncoded | 21 - ]); - } else if (__float === null) { - buf2.push([ - Type.float.majorEncoded | 22 - ]); - } else if (__float === void 0) { - buf2.push([ - Type.float.majorEncoded | 23 - ]); - } else { - let decoded; - let success = false; - if (!options || options.float64 !== true) { - encodeFloat16(__float); - decoded = readFloat16(ui8a, 1); - if (__float === decoded || Number.isNaN(__float)) { - ui8a[0] = 249; - buf2.push(ui8a.slice(0, 3)); - success = true; - } else { - encodeFloat32(__float); - decoded = readFloat32(ui8a, 1); - if (__float === decoded) { - ui8a[0] = 250; - buf2.push(ui8a.slice(0, 5)); - success = true; - } +const version11 = "abstract-signer/5.7.0"; +var __awaiter3 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); } } - if (!success) { - encodeFloat64(__float); - decoded = readFloat64(ui8a, 1); - ui8a[0] = 251; - buf2.push(ui8a.slice(0, 9)); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger29 = new Logger(version11); +const allowedTransactionKeys = [ + "accessList", + "ccipReadEnabled", + "chainId", + "customData", + "data", + "from", + "gasLimit", + "gasPrice", + "maxFeePerGas", + "maxPriorityFeePerGas", + "nonce", + "to", + "type", + "value" +]; +const forwardErrors = [ + Logger.errors.INSUFFICIENT_FUNDS, + Logger.errors.NONCE_EXPIRED, + Logger.errors.REPLACEMENT_UNDERPRICED +]; +class Signer { + constructor(){ + logger29.checkAbstract(new.target, Signer); + defineReadOnly(this, "_isSigner", true); } -} -encodeFloat.encodedSize = function encodedSize8(token, options) { - const __float = token.value; - if (__float === false || __float === true || __float === null || __float === void 0) { - return 1; + getBalance(blockTag) { + return __awaiter3(this, void 0, void 0, function*() { + this._checkProvider("getBalance"); + return yield this.provider.getBalance(this.getAddress(), blockTag); + }); } - if (!options || options.float64 !== true) { - encodeFloat16(__float); - let decoded = readFloat16(ui8a, 1); - if (__float === decoded || Number.isNaN(__float)) { - return 3; + getTransactionCount(blockTag) { + return __awaiter3(this, void 0, void 0, function*() { + this._checkProvider("getTransactionCount"); + return yield this.provider.getTransactionCount(this.getAddress(), blockTag); + }); + } + estimateGas(transaction) { + return __awaiter3(this, void 0, void 0, function*() { + this._checkProvider("estimateGas"); + const tx = yield resolveProperties(this.checkTransaction(transaction)); + return yield this.provider.estimateGas(tx); + }); + } + call(transaction, blockTag) { + return __awaiter3(this, void 0, void 0, function*() { + this._checkProvider("call"); + const tx = yield resolveProperties(this.checkTransaction(transaction)); + return yield this.provider.call(tx, blockTag); + }); + } + sendTransaction(transaction) { + return __awaiter3(this, void 0, void 0, function*() { + this._checkProvider("sendTransaction"); + const tx = yield this.populateTransaction(transaction); + const signedTx = yield this.signTransaction(tx); + return yield this.provider.sendTransaction(signedTx); + }); + } + getChainId() { + return __awaiter3(this, void 0, void 0, function*() { + this._checkProvider("getChainId"); + const network = yield this.provider.getNetwork(); + return network.chainId; + }); + } + getGasPrice() { + return __awaiter3(this, void 0, void 0, function*() { + this._checkProvider("getGasPrice"); + return yield this.provider.getGasPrice(); + }); + } + getFeeData() { + return __awaiter3(this, void 0, void 0, function*() { + this._checkProvider("getFeeData"); + return yield this.provider.getFeeData(); + }); + } + resolveName(name) { + return __awaiter3(this, void 0, void 0, function*() { + this._checkProvider("resolveName"); + return yield this.provider.resolveName(name); + }); + } + checkTransaction(transaction) { + for(const key in transaction){ + if (allowedTransactionKeys.indexOf(key) === -1) { + logger29.throwArgumentError("invalid transaction key: " + key, "transaction", transaction); + } } - encodeFloat32(__float); - decoded = readFloat32(ui8a, 1); - if (__float === decoded) { - return 5; + const tx = shallowCopy(transaction); + if (tx.from == null) { + tx.from = this.getAddress(); + } else { + tx.from = Promise.all([ + Promise.resolve(tx.from), + this.getAddress() + ]).then((result)=>{ + if (result[0].toLowerCase() !== result[1].toLowerCase()) { + logger29.throwArgumentError("from address mismatch", "transaction", transaction); + } + return result[0]; + }); } + return tx; } - return 9; -}; -const buffer = new ArrayBuffer(9); -const dataView = new DataView(buffer, 1); -const ui8a = new Uint8Array(buffer, 0); -function encodeFloat16(inp) { - if (inp === Infinity) { - dataView.setUint16(0, 31744, false); - } else if (inp === -Infinity) { - dataView.setUint16(0, 64512, false); - } else if (Number.isNaN(inp)) { - dataView.setUint16(0, 32256, false); - } else { - dataView.setFloat32(0, inp); - const valu32 = dataView.getUint32(0); - const exponent = (valu32 & 2139095040) >> 23; - const mantissa = valu32 & 8388607; - if (exponent === 255) { - dataView.setUint16(0, 31744, false); - } else if (exponent === 0) { - dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false); - } else { - const logicalExponent = exponent - 127; - if (logicalExponent < -24) { - dataView.setUint16(0, 0); - } else if (logicalExponent < -14) { - dataView.setUint16(0, (valu32 & 2147483648) >> 16 | 1 << 24 + logicalExponent, false); + populateTransaction(transaction) { + return __awaiter3(this, void 0, void 0, function*() { + const tx = yield resolveProperties(this.checkTransaction(transaction)); + if (tx.to != null) { + tx.to = Promise.resolve(tx.to).then((to)=>__awaiter3(this, void 0, void 0, function*() { + if (to == null) { + return null; + } + const address = yield this.resolveName(to); + if (address == null) { + logger29.throwArgumentError("provided ENS name resolves to null", "tx.to", to); + } + return address; + })); + tx.to.catch((error)=>{}); + } + const hasEip1559 = tx.maxFeePerGas != null || tx.maxPriorityFeePerGas != null; + if (tx.gasPrice != null && (tx.type === 2 || hasEip1559)) { + logger29.throwArgumentError("eip-1559 transaction do not support gasPrice", "transaction", transaction); + } else if ((tx.type === 0 || tx.type === 1) && hasEip1559) { + logger29.throwArgumentError("pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "transaction", transaction); + } + if ((tx.type === 2 || tx.type == null) && tx.maxFeePerGas != null && tx.maxPriorityFeePerGas != null) { + tx.type = 2; + } else if (tx.type === 0 || tx.type === 1) { + if (tx.gasPrice == null) { + tx.gasPrice = this.getGasPrice(); + } } else { - dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false); + const feeData = yield this.getFeeData(); + if (tx.type == null) { + if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) { + tx.type = 2; + if (tx.gasPrice != null) { + const gasPrice = tx.gasPrice; + delete tx.gasPrice; + tx.maxFeePerGas = gasPrice; + tx.maxPriorityFeePerGas = gasPrice; + } else { + if (tx.maxFeePerGas == null) { + tx.maxFeePerGas = feeData.maxFeePerGas; + } + if (tx.maxPriorityFeePerGas == null) { + tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + } + } + } else if (feeData.gasPrice != null) { + if (hasEip1559) { + logger29.throwError("network does not support EIP-1559", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "populateTransaction" + }); + } + if (tx.gasPrice == null) { + tx.gasPrice = feeData.gasPrice; + } + tx.type = 0; + } else { + logger29.throwError("failed to get consistent fee data", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "signer.getFeeData" + }); + } + } else if (tx.type === 2) { + if (tx.maxFeePerGas == null) { + tx.maxFeePerGas = feeData.maxFeePerGas; + } + if (tx.maxPriorityFeePerGas == null) { + tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; + } + } + } + if (tx.nonce == null) { + tx.nonce = this.getTransactionCount("pending"); } + if (tx.gasLimit == null) { + tx.gasLimit = this.estimateGas(tx).catch((error)=>{ + if (forwardErrors.indexOf(error.code) >= 0) { + throw error; + } + return logger29.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, { + error, + tx + }); + }); + } + if (tx.chainId == null) { + tx.chainId = this.getChainId(); + } else { + tx.chainId = Promise.all([ + Promise.resolve(tx.chainId), + this.getChainId() + ]).then((results)=>{ + if (results[1] !== 0 && results[0] !== results[1]) { + logger29.throwArgumentError("chainId address mismatch", "transaction", transaction); + } + return results[0]; + }); + } + return yield resolveProperties(tx); + }); + } + _checkProvider(operation) { + if (!this.provider) { + logger29.throwError("missing provider", Logger.errors.UNSUPPORTED_OPERATION, { + operation: operation || "_checkProvider" + }); } } + static isSigner(value) { + return !!(value && value._isSigner); + } } -function readFloat16(ui8a2, pos) { - if (ui8a2.length - pos < 2) { - throw new Error(`${decodeErrPrefix} not enough data for float16`); +class VoidSigner extends Signer { + constructor(address, provider){ + super(); + defineReadOnly(this, "address", address); + defineReadOnly(this, "provider", provider || null); } - const half = (ui8a2[pos] << 8) + ui8a2[pos + 1]; - if (half === 31744) { - return Infinity; + getAddress() { + return Promise.resolve(this.address); } - if (half === 64512) { - return -Infinity; + _fail(message, operation) { + return Promise.resolve().then(()=>{ + logger29.throwError(message, Logger.errors.UNSUPPORTED_OPERATION, { + operation + }); + }); } - if (half === 32256) { - return NaN; + signMessage(message) { + return this._fail("VoidSigner cannot sign messages", "signMessage"); } - const exp = half >> 10 & 31; - const mant = half & 1023; - let val; - if (exp === 0) { - val = mant * 2 ** -24; - } else if (exp !== 31) { - val = (mant + 1024) * 2 ** (exp - 25); - } else { - val = mant === 0 ? Infinity : NaN; + signTransaction(transaction) { + return this._fail("VoidSigner cannot sign transactions", "signTransaction"); + } + _signTypedData(domain, types, value) { + return this._fail("VoidSigner cannot sign typed data", "signTypedData"); + } + connect(provider) { + return new VoidSigner(this.address, provider); } - return half & 32768 ? -val : val; } -function encodeFloat32(inp) { - dataView.setFloat32(0, inp, false); +var minimalisticAssert = assert1; +function assert1(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); } -function readFloat32(ui8a2, pos) { - if (ui8a2.length - pos < 4) { - throw new Error(`${decodeErrPrefix} not enough data for float32`); - } - const offset = (ui8a2.byteOffset || 0) + pos; - return new DataView(ui8a2.buffer, offset, 4).getFloat32(0, false); +assert1.equal = function assertEqual(l, r, msg) { + if (l != r) throw new Error(msg || "Assertion failed: " + l + " != " + r); +}; +minimalisticAssert.equal; +function createCommonjsModule2(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function(path, base) { + return commonjsRequire2(path, base === void 0 || base === null ? module.path : base); + } + }, fn(module, module.exports), module.exports; } -function encodeFloat64(inp) { - dataView.setFloat64(0, inp, false); +function commonjsRequire2() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); } -function readFloat64(ui8a2, pos) { - if (ui8a2.length - pos < 8) { - throw new Error(`${decodeErrPrefix} not enough data for float64`); +var inherits_browser = createCommonjsModule2(function(module) { + if (typeof Object.create === "function") { + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + } + }; } - const offset = (ui8a2.byteOffset || 0) + pos; - return new DataView(ui8a2.buffer, offset, 8).getFloat64(0, false); +}); +function createCommonjsModule3(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function(path, base) { + return commonjsRequire3(path, base === void 0 || base === null ? module.path : base); + } + }, fn(module, module.exports), module.exports; } -encodeFloat.compareTokens = encodeUint.compareTokens; -function invalidMinor(data, pos, minor) { - throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`); +function commonjsRequire3() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); } -function errorer(msg) { - return ()=>{ - throw new Error(`${decodeErrPrefix} ${msg}`); - }; +var inherits_1 = inherits_browser; +function isSurrogatePair(msg, i) { + if ((msg.charCodeAt(i) & 64512) !== 55296) { + return false; + } + if (i < 0 || i + 1 >= msg.length) { + return false; + } + return (msg.charCodeAt(i + 1) & 64512) === 56320; +} +function toArray(msg, enc) { + if (Array.isArray(msg)) return msg.slice(); + if (!msg) return []; + var res = []; + if (typeof msg === "string") { + if (!enc) { + var p = 0; + for(var i = 0; i < msg.length; i++){ + var c = msg.charCodeAt(i); + if (c < 128) { + res[p++] = c; + } else if (c < 2048) { + res[p++] = c >> 6 | 192; + res[p++] = c & 63 | 128; + } else if (isSurrogatePair(msg, i)) { + c = 65536 + ((c & 1023) << 10) + (msg.charCodeAt(++i) & 1023); + res[p++] = c >> 18 | 240; + res[p++] = c >> 12 & 63 | 128; + res[p++] = c >> 6 & 63 | 128; + res[p++] = c & 63 | 128; + } else { + res[p++] = c >> 12 | 224; + res[p++] = c >> 6 & 63 | 128; + res[p++] = c & 63 | 128; + } + } + } else if (enc === "hex") { + msg = msg.replace(/[^a-z0-9]+/ig, ""); + if (msg.length % 2 !== 0) msg = "0" + msg; + for(i = 0; i < msg.length; i += 2)res.push(parseInt(msg[i] + msg[i + 1], 16)); + } + } else { + for(i = 0; i < msg.length; i++)res[i] = msg[i] | 0; + } + return res; } -const jump = []; -for(let i = 0; i <= 23; i++){ - jump[i] = invalidMinor; +var toArray_1 = toArray; +function toHex1(msg) { + var res = ""; + for(var i = 0; i < msg.length; i++)res += zero2(msg[i].toString(16)); + return res; } -jump[24] = decodeUint8; -jump[25] = decodeUint16; -jump[26] = decodeUint32; -jump[27] = decodeUint64; -jump[28] = invalidMinor; -jump[29] = invalidMinor; -jump[30] = invalidMinor; -jump[31] = invalidMinor; -for(let i = 32; i <= 55; i++){ - jump[i] = invalidMinor; +var toHex_1 = toHex1; +function htonl(w) { + var res = w >>> 24 | w >>> 8 & 65280 | w << 8 & 16711680 | (w & 255) << 24; + return res >>> 0; } -jump[56] = decodeNegint8; -jump[57] = decodeNegint16; -jump[58] = decodeNegint32; -jump[59] = decodeNegint64; -jump[60] = invalidMinor; -jump[61] = invalidMinor; -jump[62] = invalidMinor; -jump[63] = invalidMinor; -for(let i = 64; i <= 87; i++){ - jump[i] = decodeBytesCompact; +var htonl_1 = htonl; +function toHex32(msg, endian) { + var res = ""; + for(var i = 0; i < msg.length; i++){ + var w = msg[i]; + if (endian === "little") w = htonl(w); + res += zero8(w.toString(16)); + } + return res; } -jump[88] = decodeBytes8; -jump[89] = decodeBytes16; -jump[90] = decodeBytes32; -jump[91] = decodeBytes64; -jump[92] = invalidMinor; -jump[93] = invalidMinor; -jump[94] = invalidMinor; -jump[95] = errorer("indefinite length bytes/strings are not supported"); -for(let i = 96; i <= 119; i++){ - jump[i] = decodeStringCompact; +var toHex32_1 = toHex32; +function zero2(word) { + if (word.length === 1) return "0" + word; + else return word; +} +var zero2_1 = zero2; +function zero8(word) { + if (word.length === 7) return "0" + word; + else if (word.length === 6) return "00" + word; + else if (word.length === 5) return "000" + word; + else if (word.length === 4) return "0000" + word; + else if (word.length === 3) return "00000" + word; + else if (word.length === 2) return "000000" + word; + else if (word.length === 1) return "0000000" + word; + else return word; +} +var zero8_1 = zero8; +function join32(msg, start, end, endian) { + var len = end - start; + minimalisticAssert(len % 4 === 0); + var res = new Array(len / 4); + for(var i = 0, k = start; i < res.length; i++, k += 4){ + var w; + if (endian === "big") w = msg[k] << 24 | msg[k + 1] << 16 | msg[k + 2] << 8 | msg[k + 3]; + else w = msg[k + 3] << 24 | msg[k + 2] << 16 | msg[k + 1] << 8 | msg[k]; + res[i] = w >>> 0; + } + return res; } -jump[120] = decodeString8; -jump[121] = decodeString16; -jump[122] = decodeString32; -jump[123] = decodeString64; -jump[124] = invalidMinor; -jump[125] = invalidMinor; -jump[126] = invalidMinor; -jump[127] = errorer("indefinite length bytes/strings are not supported"); -for(let i = 128; i <= 151; i++){ - jump[i] = decodeArrayCompact; +var join32_1 = join32; +function split32(msg, endian) { + var res = new Array(msg.length * 4); + for(var i = 0, k = 0; i < msg.length; i++, k += 4){ + var m = msg[i]; + if (endian === "big") { + res[k] = m >>> 24; + res[k + 1] = m >>> 16 & 255; + res[k + 2] = m >>> 8 & 255; + res[k + 3] = m & 255; + } else { + res[k + 3] = m >>> 24; + res[k + 2] = m >>> 16 & 255; + res[k + 1] = m >>> 8 & 255; + res[k] = m & 255; + } + } + return res; } -jump[152] = decodeArray8; -jump[153] = decodeArray16; -jump[154] = decodeArray32; -jump[155] = decodeArray64; -jump[156] = invalidMinor; -jump[157] = invalidMinor; -jump[158] = invalidMinor; -jump[159] = decodeArrayIndefinite; -for(let i = 160; i <= 183; i++){ - jump[i] = decodeMapCompact; +var split32_1 = split32; +function rotr32(w, b) { + return w >>> b | w << 32 - b; +} +var rotr32_1 = rotr32; +function rotl32(w, b) { + return w << b | w >>> 32 - b; +} +var rotl32_1 = rotl32; +function sum32(a, b) { + return a + b >>> 0; +} +var sum32_1 = sum32; +function sum32_3(a, b, c) { + return a + b + c >>> 0; +} +var sum32_3_1 = sum32_3; +function sum32_4(a, b, c, d) { + return a + b + c + d >>> 0; +} +var sum32_4_1 = sum32_4; +function sum32_5(a, b, c, d, e) { + return a + b + c + d + e >>> 0; +} +var sum32_5_1 = sum32_5; +function sum64(buf, pos, ah, al) { + var bh = buf[pos]; + var bl = buf[pos + 1]; + var lo = al + bl >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + buf[pos] = hi >>> 0; + buf[pos + 1] = lo; +} +var sum64_1 = sum64; +function sum64_hi(ah, al, bh, bl) { + var lo = al + bl >>> 0; + var hi = (lo < al ? 1 : 0) + ah + bh; + return hi >>> 0; +} +var sum64_hi_1 = sum64_hi; +function sum64_lo(ah, al, bh, bl) { + var lo = al + bl; + return lo >>> 0; +} +var sum64_lo_1 = sum64_lo; +function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { + var carry = 0; + var lo = al; + lo = lo + bl >>> 0; + carry += lo < al ? 1 : 0; + lo = lo + cl >>> 0; + carry += lo < cl ? 1 : 0; + lo = lo + dl >>> 0; + carry += lo < dl ? 1 : 0; + var hi = ah + bh + ch + dh + carry; + return hi >>> 0; +} +var sum64_4_hi_1 = sum64_4_hi; +function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { + var lo = al + bl + cl + dl; + return lo >>> 0; +} +var sum64_4_lo_1 = sum64_4_lo; +function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var carry = 0; + var lo = al; + lo = lo + bl >>> 0; + carry += lo < al ? 1 : 0; + lo = lo + cl >>> 0; + carry += lo < cl ? 1 : 0; + lo = lo + dl >>> 0; + carry += lo < dl ? 1 : 0; + lo = lo + el >>> 0; + carry += lo < el ? 1 : 0; + var hi = ah + bh + ch + dh + eh + carry; + return hi >>> 0; +} +var sum64_5_hi_1 = sum64_5_hi; +function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { + var lo = al + bl + cl + dl + el; + return lo >>> 0; +} +var sum64_5_lo_1 = sum64_5_lo; +function rotr64_hi(ah, al, num) { + var r2 = al << 32 - num | ah >>> num; + return r2 >>> 0; +} +var rotr64_hi_1 = rotr64_hi; +function rotr64_lo(ah, al, num) { + var r2 = ah << 32 - num | al >>> num; + return r2 >>> 0; +} +var rotr64_lo_1 = rotr64_lo; +function shr64_hi(ah, al, num) { + return ah >>> num; +} +var shr64_hi_1 = shr64_hi; +function shr64_lo(ah, al, num) { + var r2 = ah << 32 - num | al >>> num; + return r2 >>> 0; +} +var shr64_lo_1 = shr64_lo; +var utils = { + inherits: inherits_1, + toArray: toArray_1, + toHex: toHex_1, + htonl: htonl_1, + toHex32: toHex32_1, + zero2: zero2_1, + zero8: zero8_1, + join32: join32_1, + split32: split32_1, + rotr32: rotr32_1, + rotl32: rotl32_1, + sum32: sum32_1, + sum32_3: sum32_3_1, + sum32_4: sum32_4_1, + sum32_5: sum32_5_1, + sum64: sum64_1, + sum64_hi: sum64_hi_1, + sum64_lo: sum64_lo_1, + sum64_4_hi: sum64_4_hi_1, + sum64_4_lo: sum64_4_lo_1, + sum64_5_hi: sum64_5_hi_1, + sum64_5_lo: sum64_5_lo_1, + rotr64_hi: rotr64_hi_1, + rotr64_lo: rotr64_lo_1, + shr64_hi: shr64_hi_1, + shr64_lo: shr64_lo_1 +}; +function BlockHash() { + this.pending = null; + this.pendingTotal = 0; + this.blockSize = this.constructor.blockSize; + this.outSize = this.constructor.outSize; + this.hmacStrength = this.constructor.hmacStrength; + this.padLength = this.constructor.padLength / 8; + this.endian = "big"; + this._delta8 = this.blockSize / 8; + this._delta32 = this.blockSize / 32; +} +var BlockHash_1 = BlockHash; +BlockHash.prototype.update = function update(msg, enc) { + msg = utils.toArray(msg, enc); + if (!this.pending) this.pending = msg; + else this.pending = this.pending.concat(msg); + this.pendingTotal += msg.length; + if (this.pending.length >= this._delta8) { + msg = this.pending; + var r2 = msg.length % this._delta8; + this.pending = msg.slice(msg.length - r2, msg.length); + if (this.pending.length === 0) this.pending = null; + msg = utils.join32(msg, 0, msg.length - r2, this.endian); + for(var i = 0; i < msg.length; i += this._delta32)this._update(msg, i, i + this._delta32); + } + return this; +}; +BlockHash.prototype.digest = function digest(enc) { + this.update(this._pad()); + minimalisticAssert(this.pending === null); + return this._digest(enc); +}; +BlockHash.prototype._pad = function pad() { + var len = this.pendingTotal; + var bytes = this._delta8; + var k = bytes - (len + this.padLength) % bytes; + var res = new Array(k + this.padLength); + res[0] = 128; + for(var i = 1; i < k; i++)res[i] = 0; + len <<= 3; + if (this.endian === "big") { + for(var t = 8; t < this.padLength; t++)res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = len >>> 24 & 255; + res[i++] = len >>> 16 & 255; + res[i++] = len >>> 8 & 255; + res[i++] = len & 255; + } else { + res[i++] = len & 255; + res[i++] = len >>> 8 & 255; + res[i++] = len >>> 16 & 255; + res[i++] = len >>> 24 & 255; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + res[i++] = 0; + for(t = 8; t < this.padLength; t++)res[i++] = 0; + } + return res; +}; +var common = { + BlockHash: BlockHash_1 +}; +var rotr32$1 = utils.rotr32; +function ft_1(s2, x, y, z) { + if (s2 === 0) return ch32(x, y, z); + if (s2 === 1 || s2 === 3) return p32(x, y, z); + if (s2 === 2) return maj32(x, y, z); +} +var ft_1_1 = ft_1; +function ch32(x, y, z) { + return x & y ^ ~x & z; +} +var ch32_1 = ch32; +function maj32(x, y, z) { + return x & y ^ x & z ^ y & z; +} +var maj32_1 = maj32; +function p32(x, y, z) { + return x ^ y ^ z; +} +var p32_1 = p32; +function s0_256(x) { + return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22); +} +var s0_256_1 = s0_256; +function s1_256(x) { + return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25); +} +var s1_256_1 = s1_256; +function g0_256(x) { + return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ x >>> 3; +} +var g0_256_1 = g0_256; +function g1_256(x) { + return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ x >>> 10; +} +var g1_256_1 = g1_256; +var common$1 = { + ft_1: ft_1_1, + ch32: ch32_1, + maj32: maj32_1, + p32: p32_1, + s0_256: s0_256_1, + s1_256: s1_256_1, + g0_256: g0_256_1, + g1_256: g1_256_1 +}; +var rotl32$1 = utils.rotl32; +var sum32$1 = utils.sum32; +var sum32_5$1 = utils.sum32_5; +var ft_1$1 = common$1.ft_1; +var BlockHash$1 = common.BlockHash; +var sha1_K = [ + 1518500249, + 1859775393, + 2400959708, + 3395469782 +]; +function SHA1() { + if (!(this instanceof SHA1)) return new SHA1(); + BlockHash$1.call(this); + this.h = [ + 1732584193, + 4023233417, + 2562383102, + 271733878, + 3285377520 + ]; + this.W = new Array(80); +} +utils.inherits(SHA1, BlockHash$1); +var _1 = SHA1; +SHA1.blockSize = 512; +SHA1.outSize = 160; +SHA1.hmacStrength = 80; +SHA1.padLength = 64; +SHA1.prototype._update = function _update(msg, start) { + var W = this.W; + for(var i = 0; i < 16; i++)W[i] = msg[start + i]; + for(; i < W.length; i++)W[i] = rotl32$1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + for(i = 0; i < W.length; i++){ + var s2 = ~~(i / 20); + var t = sum32_5$1(rotl32$1(a, 5), ft_1$1(s2, b, c, d), e, W[i], sha1_K[s2]); + e = d; + d = c; + c = rotl32$1(b, 30); + b = a; + a = t; + } + this.h[0] = sum32$1(this.h[0], a); + this.h[1] = sum32$1(this.h[1], b); + this.h[2] = sum32$1(this.h[2], c); + this.h[3] = sum32$1(this.h[3], d); + this.h[4] = sum32$1(this.h[4], e); +}; +SHA1.prototype._digest = function digest2(enc) { + if (enc === "hex") return utils.toHex32(this.h, "big"); + else return utils.split32(this.h, "big"); +}; +var sum32$2 = utils.sum32; +var sum32_4$1 = utils.sum32_4; +var sum32_5$2 = utils.sum32_5; +var ch32$1 = common$1.ch32; +var maj32$1 = common$1.maj32; +var s0_256$1 = common$1.s0_256; +var s1_256$1 = common$1.s1_256; +var g0_256$1 = common$1.g0_256; +var g1_256$1 = common$1.g1_256; +var BlockHash$2 = common.BlockHash; +var sha256_K = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]; +function SHA256() { + if (!(this instanceof SHA256)) return new SHA256(); + BlockHash$2.call(this); + this.h = [ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 + ]; + this.k = sha256_K; + this.W = new Array(64); +} +utils.inherits(SHA256, BlockHash$2); +var _256 = SHA256; +SHA256.blockSize = 512; +SHA256.outSize = 256; +SHA256.hmacStrength = 192; +SHA256.padLength = 64; +SHA256.prototype._update = function _update2(msg, start) { + var W = this.W; + for(var i = 0; i < 16; i++)W[i] = msg[start + i]; + for(; i < W.length; i++)W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]); + var a = this.h[0]; + var b = this.h[1]; + var c = this.h[2]; + var d = this.h[3]; + var e = this.h[4]; + var f2 = this.h[5]; + var g = this.h[6]; + var h = this.h[7]; + minimalisticAssert(this.k.length === W.length); + for(i = 0; i < W.length; i++){ + var T1 = sum32_5$2(h, s1_256$1(e), ch32$1(e, f2, g), this.k[i], W[i]); + var T2 = sum32$2(s0_256$1(a), maj32$1(a, b, c)); + h = g; + g = f2; + f2 = e; + e = sum32$2(d, T1); + d = c; + c = b; + b = a; + a = sum32$2(T1, T2); + } + this.h[0] = sum32$2(this.h[0], a); + this.h[1] = sum32$2(this.h[1], b); + this.h[2] = sum32$2(this.h[2], c); + this.h[3] = sum32$2(this.h[3], d); + this.h[4] = sum32$2(this.h[4], e); + this.h[5] = sum32$2(this.h[5], f2); + this.h[6] = sum32$2(this.h[6], g); + this.h[7] = sum32$2(this.h[7], h); +}; +SHA256.prototype._digest = function digest3(enc) { + if (enc === "hex") return utils.toHex32(this.h, "big"); + else return utils.split32(this.h, "big"); +}; +function SHA224() { + if (!(this instanceof SHA224)) return new SHA224(); + _256.call(this); + this.h = [ + 3238371032, + 914150663, + 812702999, + 4144912697, + 4290775857, + 1750603025, + 1694076839, + 3204075428 + ]; } -jump[184] = decodeMap8; -jump[185] = decodeMap16; -jump[186] = decodeMap32; -jump[187] = decodeMap64; -jump[188] = invalidMinor; -jump[189] = invalidMinor; -jump[190] = invalidMinor; -jump[191] = decodeMapIndefinite; -for(let i = 192; i <= 215; i++){ - jump[i] = decodeTagCompact; +utils.inherits(SHA224, _256); +var _224 = SHA224; +SHA224.blockSize = 512; +SHA224.outSize = 224; +SHA224.hmacStrength = 192; +SHA224.padLength = 64; +SHA224.prototype._digest = function digest4(enc) { + if (enc === "hex") return utils.toHex32(this.h.slice(0, 7), "big"); + else return utils.split32(this.h.slice(0, 7), "big"); +}; +var rotr64_hi$1 = utils.rotr64_hi; +var rotr64_lo$1 = utils.rotr64_lo; +var shr64_hi$1 = utils.shr64_hi; +var shr64_lo$1 = utils.shr64_lo; +var sum64$1 = utils.sum64; +var sum64_hi$1 = utils.sum64_hi; +var sum64_lo$1 = utils.sum64_lo; +var sum64_4_hi$1 = utils.sum64_4_hi; +var sum64_4_lo$1 = utils.sum64_4_lo; +var sum64_5_hi$1 = utils.sum64_5_hi; +var sum64_5_lo$1 = utils.sum64_5_lo; +var BlockHash$3 = common.BlockHash; +var sha512_K = [ + 1116352408, + 3609767458, + 1899447441, + 602891725, + 3049323471, + 3964484399, + 3921009573, + 2173295548, + 961987163, + 4081628472, + 1508970993, + 3053834265, + 2453635748, + 2937671579, + 2870763221, + 3664609560, + 3624381080, + 2734883394, + 310598401, + 1164996542, + 607225278, + 1323610764, + 1426881987, + 3590304994, + 1925078388, + 4068182383, + 2162078206, + 991336113, + 2614888103, + 633803317, + 3248222580, + 3479774868, + 3835390401, + 2666613458, + 4022224774, + 944711139, + 264347078, + 2341262773, + 604807628, + 2007800933, + 770255983, + 1495990901, + 1249150122, + 1856431235, + 1555081692, + 3175218132, + 1996064986, + 2198950837, + 2554220882, + 3999719339, + 2821834349, + 766784016, + 2952996808, + 2566594879, + 3210313671, + 3203337956, + 3336571891, + 1034457026, + 3584528711, + 2466948901, + 113926993, + 3758326383, + 338241895, + 168717936, + 666307205, + 1188179964, + 773529912, + 1546045734, + 1294757372, + 1522805485, + 1396182291, + 2643833823, + 1695183700, + 2343527390, + 1986661051, + 1014477480, + 2177026350, + 1206759142, + 2456956037, + 344077627, + 2730485921, + 1290863460, + 2820302411, + 3158454273, + 3259730800, + 3505952657, + 3345764771, + 106217008, + 3516065817, + 3606008344, + 3600352804, + 1432725776, + 4094571909, + 1467031594, + 275423344, + 851169720, + 430227734, + 3100823752, + 506948616, + 1363258195, + 659060556, + 3750685593, + 883997877, + 3785050280, + 958139571, + 3318307427, + 1322822218, + 3812723403, + 1537002063, + 2003034995, + 1747873779, + 3602036899, + 1955562222, + 1575990012, + 2024104815, + 1125592928, + 2227730452, + 2716904306, + 2361852424, + 442776044, + 2428436474, + 593698344, + 2756734187, + 3733110249, + 3204031479, + 2999351573, + 3329325298, + 3815920427, + 3391569614, + 3928383900, + 3515267271, + 566280711, + 3940187606, + 3454069534, + 4118630271, + 4000239992, + 116418474, + 1914138554, + 174292421, + 2731055270, + 289380356, + 3203993006, + 460393269, + 320620315, + 685471733, + 587496836, + 852142971, + 1086792851, + 1017036298, + 365543100, + 1126000580, + 2618297676, + 1288033470, + 3409855158, + 1501505948, + 4234509866, + 1607167915, + 987167468, + 1816402316, + 1246189591 +]; +function SHA512() { + if (!(this instanceof SHA512)) return new SHA512(); + BlockHash$3.call(this); + this.h = [ + 1779033703, + 4089235720, + 3144134277, + 2227873595, + 1013904242, + 4271175723, + 2773480762, + 1595750129, + 1359893119, + 2917565137, + 2600822924, + 725511199, + 528734635, + 4215389547, + 1541459225, + 327033209 + ]; + this.k = sha512_K; + this.W = new Array(160); +} +utils.inherits(SHA512, BlockHash$3); +var _512 = SHA512; +SHA512.blockSize = 1024; +SHA512.outSize = 512; +SHA512.hmacStrength = 192; +SHA512.padLength = 128; +SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { + var W = this.W; + for(var i = 0; i < 32; i++)W[i] = msg[start + i]; + for(; i < W.length; i += 2){ + var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); + var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); + var c1_hi = W[i - 14]; + var c1_lo = W[i - 13]; + var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); + var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); + var c3_hi = W[i - 32]; + var c3_lo = W[i - 31]; + W[i] = sum64_4_hi$1(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); + W[i + 1] = sum64_4_lo$1(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); + } +}; +SHA512.prototype._update = function _update3(msg, start) { + this._prepareBlock(msg, start); + var W = this.W; + var ah = this.h[0]; + var al = this.h[1]; + var bh = this.h[2]; + var bl = this.h[3]; + var ch = this.h[4]; + var cl = this.h[5]; + var dh = this.h[6]; + var dl = this.h[7]; + var eh = this.h[8]; + var el = this.h[9]; + var fh = this.h[10]; + var fl = this.h[11]; + var gh = this.h[12]; + var gl = this.h[13]; + var hh = this.h[14]; + var hl = this.h[15]; + minimalisticAssert(this.k.length === W.length); + for(var i = 0; i < W.length; i += 2){ + var c0_hi = hh; + var c0_lo = hl; + var c1_hi = s1_512_hi(eh, el); + var c1_lo = s1_512_lo(eh, el); + var c2_hi = ch64_hi(eh, el, fh, fl, gh); + var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); + var c3_hi = this.k[i]; + var c3_lo = this.k[i + 1]; + var c4_hi = W[i]; + var c4_lo = W[i + 1]; + var T1_hi = sum64_5_hi$1(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); + var T1_lo = sum64_5_lo$1(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); + c0_hi = s0_512_hi(ah, al); + c0_lo = s0_512_lo(ah, al); + c1_hi = maj64_hi(ah, al, bh, bl, ch); + c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); + var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo); + var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo); + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; + eh = sum64_hi$1(dh, dl, T1_hi, T1_lo); + el = sum64_lo$1(dl, dl, T1_hi, T1_lo); + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; + ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo); + al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo); + } + sum64$1(this.h, 0, ah, al); + sum64$1(this.h, 2, bh, bl); + sum64$1(this.h, 4, ch, cl); + sum64$1(this.h, 6, dh, dl); + sum64$1(this.h, 8, eh, el); + sum64$1(this.h, 10, fh, fl); + sum64$1(this.h, 12, gh, gl); + sum64$1(this.h, 14, hh, hl); +}; +SHA512.prototype._digest = function digest5(enc) { + if (enc === "hex") return utils.toHex32(this.h, "big"); + else return utils.split32(this.h, "big"); +}; +function ch64_hi(xh, xl, yh, yl, zh) { + var r2 = xh & yh ^ ~xh & zh; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function ch64_lo(xh, xl, yh, yl, zh, zl) { + var r2 = xl & yl ^ ~xl & zl; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function maj64_hi(xh, xl, yh, yl, zh) { + var r2 = xh & yh ^ xh & zh ^ yh & zh; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function maj64_lo(xh, xl, yh, yl, zh, zl) { + var r2 = xl & yl ^ xl & zl ^ yl & zl; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function s0_512_hi(xh, xl) { + var c0_hi = rotr64_hi$1(xh, xl, 28); + var c1_hi = rotr64_hi$1(xl, xh, 2); + var c2_hi = rotr64_hi$1(xl, xh, 7); + var r2 = c0_hi ^ c1_hi ^ c2_hi; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function s0_512_lo(xh, xl) { + var c0_lo = rotr64_lo$1(xh, xl, 28); + var c1_lo = rotr64_lo$1(xl, xh, 2); + var c2_lo = rotr64_lo$1(xl, xh, 7); + var r2 = c0_lo ^ c1_lo ^ c2_lo; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function s1_512_hi(xh, xl) { + var c0_hi = rotr64_hi$1(xh, xl, 14); + var c1_hi = rotr64_hi$1(xh, xl, 18); + var c2_hi = rotr64_hi$1(xl, xh, 9); + var r2 = c0_hi ^ c1_hi ^ c2_hi; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function s1_512_lo(xh, xl) { + var c0_lo = rotr64_lo$1(xh, xl, 14); + var c1_lo = rotr64_lo$1(xh, xl, 18); + var c2_lo = rotr64_lo$1(xl, xh, 9); + var r2 = c0_lo ^ c1_lo ^ c2_lo; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function g0_512_hi(xh, xl) { + var c0_hi = rotr64_hi$1(xh, xl, 1); + var c1_hi = rotr64_hi$1(xh, xl, 8); + var c2_hi = shr64_hi$1(xh, xl, 7); + var r2 = c0_hi ^ c1_hi ^ c2_hi; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function g0_512_lo(xh, xl) { + var c0_lo = rotr64_lo$1(xh, xl, 1); + var c1_lo = rotr64_lo$1(xh, xl, 8); + var c2_lo = shr64_lo$1(xh, xl, 7); + var r2 = c0_lo ^ c1_lo ^ c2_lo; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function g1_512_hi(xh, xl) { + var c0_hi = rotr64_hi$1(xh, xl, 19); + var c1_hi = rotr64_hi$1(xl, xh, 29); + var c2_hi = shr64_hi$1(xh, xl, 6); + var r2 = c0_hi ^ c1_hi ^ c2_hi; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function g1_512_lo(xh, xl) { + var c0_lo = rotr64_lo$1(xh, xl, 19); + var c1_lo = rotr64_lo$1(xl, xh, 29); + var c2_lo = shr64_lo$1(xh, xl, 6); + var r2 = c0_lo ^ c1_lo ^ c2_lo; + if (r2 < 0) r2 += 4294967296; + return r2; +} +function SHA384() { + if (!(this instanceof SHA384)) return new SHA384(); + _512.call(this); + this.h = [ + 3418070365, + 3238371032, + 1654270250, + 914150663, + 2438529370, + 812702999, + 355462360, + 4144912697, + 1731405415, + 4290775857, + 2394180231, + 1750603025, + 3675008525, + 1694076839, + 1203062813, + 3204075428 + ]; } -jump[216] = decodeTag8; -jump[217] = decodeTag16; -jump[218] = decodeTag32; -jump[219] = decodeTag64; -jump[220] = invalidMinor; -jump[221] = invalidMinor; -jump[222] = invalidMinor; -jump[223] = invalidMinor; -for(let i = 224; i <= 243; i++){ - jump[i] = errorer("simple values are not supported"); +utils.inherits(SHA384, _512); +var _384 = SHA384; +SHA384.blockSize = 1024; +SHA384.outSize = 384; +SHA384.hmacStrength = 192; +SHA384.padLength = 128; +SHA384.prototype._digest = function digest6(enc) { + if (enc === "hex") return utils.toHex32(this.h.slice(0, 12), "big"); + else return utils.split32(this.h.slice(0, 12), "big"); +}; +var sha1 = _1; +var sha224 = _224; +var sha256 = _256; +var sha384 = _384; +var sha512 = _512; +var sha = { + sha1, + sha224, + sha256, + sha384, + sha512 +}; +var rotl32$2 = utils.rotl32; +var sum32$3 = utils.sum32; +var sum32_3$1 = utils.sum32_3; +var sum32_4$2 = utils.sum32_4; +var BlockHash$4 = common.BlockHash; +function RIPEMD160() { + if (!(this instanceof RIPEMD160)) return new RIPEMD160(); + BlockHash$4.call(this); + this.h = [ + 1732584193, + 4023233417, + 2562383102, + 271733878, + 3285377520 + ]; + this.endian = "little"; +} +utils.inherits(RIPEMD160, BlockHash$4); +var ripemd160 = RIPEMD160; +RIPEMD160.blockSize = 512; +RIPEMD160.outSize = 160; +RIPEMD160.hmacStrength = 192; +RIPEMD160.padLength = 64; +RIPEMD160.prototype._update = function update2(msg, start) { + var A = this.h[0]; + var B = this.h[1]; + var C = this.h[2]; + var D = this.h[3]; + var E = this.h[4]; + var Ah = A; + var Bh = B; + var Ch = C; + var Dh = D; + var Eh = E; + for(var j = 0; j < 80; j++){ + var T = sum32$3(rotl32$2(sum32_4$2(A, f(j, B, C, D), msg[r1[j] + start], K(j)), s[j]), E); + A = E; + E = D; + D = rotl32$2(C, 10); + C = B; + B = T; + T = sum32$3(rotl32$2(sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh); + Ah = Eh; + Eh = Dh; + Dh = rotl32$2(Ch, 10); + Ch = Bh; + Bh = T; + } + T = sum32_3$1(this.h[1], C, Dh); + this.h[1] = sum32_3$1(this.h[2], D, Eh); + this.h[2] = sum32_3$1(this.h[3], E, Ah); + this.h[3] = sum32_3$1(this.h[4], A, Bh); + this.h[4] = sum32_3$1(this.h[0], B, Ch); + this.h[0] = T; +}; +RIPEMD160.prototype._digest = function digest7(enc) { + if (enc === "hex") return utils.toHex32(this.h, "little"); + else return utils.split32(this.h, "little"); +}; +function f(j, x, y, z) { + if (j <= 15) return x ^ y ^ z; + else if (j <= 31) return x & y | ~x & z; + else if (j <= 47) return (x | ~y) ^ z; + else if (j <= 63) return x & z | y & ~z; + else return x ^ (y | ~z); +} +function K(j) { + if (j <= 15) return 0; + else if (j <= 31) return 1518500249; + else if (j <= 47) return 1859775393; + else if (j <= 63) return 2400959708; + else return 2840853838; +} +function Kh(j) { + if (j <= 15) return 1352829926; + else if (j <= 31) return 1548603684; + else if (j <= 47) return 1836072691; + else if (j <= 63) return 2053994217; + else return 0; +} +var r1 = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 7, + 4, + 13, + 1, + 10, + 6, + 15, + 3, + 12, + 0, + 9, + 5, + 2, + 14, + 11, + 8, + 3, + 10, + 14, + 4, + 9, + 15, + 8, + 1, + 2, + 7, + 0, + 6, + 13, + 11, + 5, + 12, + 1, + 9, + 11, + 10, + 0, + 8, + 12, + 4, + 13, + 3, + 7, + 15, + 14, + 5, + 6, + 2, + 4, + 0, + 5, + 9, + 7, + 12, + 2, + 10, + 14, + 1, + 3, + 8, + 11, + 6, + 15, + 13 +]; +var rh = [ + 5, + 14, + 7, + 0, + 9, + 2, + 11, + 4, + 13, + 6, + 15, + 8, + 1, + 10, + 3, + 12, + 6, + 11, + 3, + 7, + 0, + 13, + 5, + 10, + 14, + 15, + 8, + 12, + 4, + 9, + 1, + 2, + 15, + 5, + 1, + 3, + 7, + 14, + 6, + 9, + 11, + 8, + 12, + 2, + 10, + 0, + 4, + 13, + 8, + 6, + 4, + 1, + 3, + 11, + 15, + 0, + 5, + 12, + 2, + 13, + 9, + 7, + 10, + 14, + 12, + 15, + 10, + 4, + 1, + 5, + 8, + 7, + 6, + 2, + 13, + 14, + 0, + 3, + 9, + 11 +]; +var s = [ + 11, + 14, + 15, + 12, + 5, + 8, + 7, + 9, + 11, + 13, + 14, + 15, + 6, + 7, + 9, + 8, + 7, + 6, + 8, + 13, + 11, + 9, + 7, + 15, + 7, + 12, + 15, + 9, + 11, + 7, + 13, + 12, + 11, + 13, + 6, + 7, + 14, + 9, + 13, + 15, + 14, + 8, + 13, + 6, + 5, + 12, + 7, + 5, + 11, + 12, + 14, + 15, + 14, + 15, + 9, + 8, + 9, + 14, + 5, + 6, + 8, + 6, + 5, + 12, + 9, + 15, + 5, + 11, + 6, + 8, + 13, + 12, + 5, + 12, + 13, + 14, + 11, + 8, + 5, + 6 +]; +var sh = [ + 8, + 9, + 9, + 11, + 13, + 15, + 15, + 5, + 7, + 7, + 8, + 11, + 14, + 14, + 12, + 6, + 9, + 13, + 15, + 7, + 12, + 8, + 9, + 11, + 7, + 7, + 12, + 7, + 6, + 15, + 13, + 11, + 9, + 7, + 15, + 11, + 8, + 6, + 6, + 14, + 12, + 13, + 5, + 14, + 13, + 13, + 7, + 5, + 15, + 5, + 8, + 11, + 14, + 14, + 6, + 14, + 6, + 9, + 12, + 9, + 12, + 5, + 15, + 8, + 8, + 5, + 12, + 9, + 12, + 5, + 14, + 6, + 8, + 13, + 6, + 5, + 15, + 13, + 11, + 11 +]; +var ripemd = { + ripemd160 +}; +function Hmac(hash, key, enc) { + if (!(this instanceof Hmac)) return new Hmac(hash, key, enc); + this.Hash = hash; + this.blockSize = hash.blockSize / 8; + this.outSize = hash.outSize / 8; + this.inner = null; + this.outer = null; + this._init(utils.toArray(key, enc)); +} +var hmac = Hmac; +Hmac.prototype._init = function init(key) { + if (key.length > this.blockSize) key = new this.Hash().update(key).digest(); + minimalisticAssert(key.length <= this.blockSize); + for(var i = key.length; i < this.blockSize; i++)key.push(0); + for(i = 0; i < key.length; i++)key[i] ^= 54; + this.inner = new this.Hash().update(key); + for(i = 0; i < key.length; i++)key[i] ^= 106; + this.outer = new this.Hash().update(key); +}; +Hmac.prototype.update = function update3(msg, enc) { + this.inner.update(msg, enc); + return this; +}; +Hmac.prototype.digest = function digest8(enc) { + this.outer.update(this.inner.digest()); + return this.outer.digest(enc); +}; +var hash_1 = createCommonjsModule3(function(module, exports) { + var hash = exports; + hash.utils = utils; + hash.common = common; + hash.sha = sha; + hash.ripemd = ripemd; + hash.hmac = hmac; + hash.sha1 = hash.sha.sha1; + hash.sha256 = hash.sha.sha256; + hash.sha224 = hash.sha.sha224; + hash.sha384 = hash.sha.sha384; + hash.sha512 = hash.sha.sha512; + hash.ripemd160 = hash.ripemd.ripemd160; +}); +function createCommonjsModule4(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function(path, base2) { + return commonjsRequire4(path, base2 === void 0 || base2 === null ? module.path : base2); + } + }, fn(module, module.exports), module.exports; } -jump[244] = invalidMinor; -jump[245] = invalidMinor; -jump[246] = invalidMinor; -jump[247] = decodeUndefined; -jump[248] = errorer("simple values are not supported"); -jump[249] = decodeFloat16; -jump[250] = decodeFloat32; -jump[251] = decodeFloat64; -jump[252] = invalidMinor; -jump[253] = invalidMinor; -jump[254] = invalidMinor; -jump[255] = decodeBreak; -const quick = []; -for(let i = 0; i < 24; i++){ - quick[i] = new Token(Type.uint, i, 1); +function commonjsRequire4() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); } -for(let i = -1; i >= -24; i--){ - quick[31 - i] = new Token(Type.negint, i, 1); +var minimalisticAssert1 = assert2; +function assert2(val, msg) { + if (!val) throw new Error(msg || "Assertion failed"); } -quick[64] = new Token(Type.bytes, new Uint8Array(0), 1); -quick[96] = new Token(Type.string, "", 1); -quick[128] = new Token(Type.array, 0, 1); -quick[160] = new Token(Type.map, 0, 1); -quick[244] = new Token(Type.false, false, 1); -quick[245] = new Token(Type.true, true, 1); -quick[246] = new Token(Type.null, null, 1); -function quickEncodeToken(token) { - switch(token.type){ - case Type.false: - return fromArray([ - 244 - ]); - case Type.true: - return fromArray([ - 245 - ]); - case Type.null: - return fromArray([ - 246 - ]); - case Type.bytes: - if (!token.value.length) { - return fromArray([ - 64 - ]); +assert2.equal = function assertEqual(l, r, msg) { + if (l != r) throw new Error(msg || "Assertion failed: " + l + " != " + r); +}; +var utils_1 = createCommonjsModule4(function(module, exports) { + var utils = exports; + function toArray(msg, enc) { + if (Array.isArray(msg)) return msg.slice(); + if (!msg) return []; + var res = []; + if (typeof msg !== "string") { + for(var i = 0; i < msg.length; i++)res[i] = msg[i] | 0; + return res; + } + if (enc === "hex") { + msg = msg.replace(/[^a-z0-9]+/ig, ""); + if (msg.length % 2 !== 0) msg = "0" + msg; + for(var i = 0; i < msg.length; i += 2)res.push(parseInt(msg[i] + msg[i + 1], 16)); + } else { + for(var i = 0; i < msg.length; i++){ + var c = msg.charCodeAt(i); + var hi = c >> 8; + var lo = c & 255; + if (hi) res.push(hi, lo); + else res.push(lo); } - return; - case Type.string: - if (token.value === "") { - return fromArray([ - 96 - ]); + } + return res; + } + utils.toArray = toArray; + function zero2(word) { + if (word.length === 1) return "0" + word; + else return word; + } + utils.zero2 = zero2; + function toHex(msg) { + var res = ""; + for(var i = 0; i < msg.length; i++)res += zero2(msg[i].toString(16)); + return res; + } + utils.toHex = toHex; + utils.encode = function encode2(arr, enc) { + if (enc === "hex") return toHex(arr); + else return arr; + }; +}); +var utils_1$1 = createCommonjsModule4(function(module, exports) { + var utils = exports; + utils.assert = minimalisticAssert1; + utils.toArray = utils_1.toArray; + utils.zero2 = utils_1.zero2; + utils.toHex = utils_1.toHex; + utils.encode = utils_1.encode; + function getNAF2(num, w, bits) { + var naf = new Array(Math.max(num.bitLength(), bits) + 1); + naf.fill(0); + var ws = 1 << w + 1; + var k = num.clone(); + for(var i = 0; i < naf.length; i++){ + var z; + var mod = k.andln(ws - 1); + if (k.isOdd()) { + if (mod > (ws >> 1) - 1) z = (ws >> 1) - mod; + else z = mod; + k.isubn(z); + } else { + z = 0; } - return; - case Type.array: - if (token.value === 0) { - return fromArray([ - 128 - ]); + naf[i] = z; + k.iushrn(1); + } + return naf; + } + utils.getNAF = getNAF2; + function getJSF2(k1, k2) { + var jsf = [ + [], + [] + ]; + k1 = k1.clone(); + k2 = k2.clone(); + var d1 = 0; + var d2 = 0; + var m8; + while(k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0){ + var m14 = k1.andln(3) + d1 & 3; + var m24 = k2.andln(3) + d2 & 3; + if (m14 === 3) m14 = -1; + if (m24 === 3) m24 = -1; + var u1; + if ((m14 & 1) === 0) { + u1 = 0; + } else { + m8 = k1.andln(7) + d1 & 7; + if ((m8 === 3 || m8 === 5) && m24 === 2) u1 = -m14; + else u1 = m14; } - return; - case Type.map: - if (token.value === 0) { - return fromArray([ - 160 - ]); + jsf[0].push(u1); + var u2; + if ((m24 & 1) === 0) { + u2 = 0; + } else { + m8 = k2.andln(7) + d2 & 7; + if ((m8 === 3 || m8 === 5) && m14 === 2) u2 = -m24; + else u2 = m24; } - return; - case Type.uint: - if (token.value < 24) { - return fromArray([ - Number(token.value) - ]); + jsf[1].push(u2); + if (2 * d1 === u1 + 1) d1 = 1 - d1; + if (2 * d2 === u2 + 1) d2 = 1 - d2; + k1.iushrn(1); + k2.iushrn(1); + } + return jsf; + } + utils.getJSF = getJSF2; + function cachedProperty(obj, name, computer) { + var key2 = "_" + name; + obj.prototype[name] = function cachedProperty2() { + return this[key2] !== void 0 ? this[key2] : this[key2] = computer.call(this); + }; + } + utils.cachedProperty = cachedProperty; + function parseBytes(bytes2) { + return typeof bytes2 === "string" ? utils.toArray(bytes2, "hex") : bytes2; + } + utils.parseBytes = parseBytes; + function intFromLE(bytes2) { + return new bn(bytes2, "hex", "le"); + } + utils.intFromLE = intFromLE; +}); +var getNAF = utils_1$1.getNAF; +var getJSF = utils_1$1.getJSF; +var assert$1 = utils_1$1.assert; +function BaseCurve(type, conf) { + this.type = type; + this.p = new bn(conf.p, 16); + this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p); + this.zero = new bn(0).toRed(this.red); + this.one = new bn(1).toRed(this.red); + this.two = new bn(2).toRed(this.red); + this.n = conf.n && new bn(conf.n, 16); + this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); + this._wnafT1 = new Array(4); + this._wnafT2 = new Array(4); + this._wnafT3 = new Array(4); + this._wnafT4 = new Array(4); + this._bitLength = this.n ? this.n.bitLength() : 0; + var adjustCount = this.n && this.p.div(this.n); + if (!adjustCount || adjustCount.cmpn(100) > 0) { + this.redN = null; + } else { + this._maxwellTrick = true; + this.redN = this.n.toRed(this.red); + } +} +var base = BaseCurve; +BaseCurve.prototype.point = function point() { + throw new Error("Not implemented"); +}; +BaseCurve.prototype.validate = function validate() { + throw new Error("Not implemented"); +}; +BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { + assert$1(p.precomputed); + var doubles = p._getDoubles(); + var naf = getNAF(k, 1, this._bitLength); + var I = (1 << doubles.step + 1) - (doubles.step % 2 === 0 ? 2 : 1); + I /= 3; + var repr = []; + var j; + var nafW; + for(j = 0; j < naf.length; j += doubles.step){ + nafW = 0; + for(var l = j + doubles.step - 1; l >= j; l--)nafW = (nafW << 1) + naf[l]; + repr.push(nafW); + } + var a = this.jpoint(null, null, null); + var b = this.jpoint(null, null, null); + for(var i = I; i > 0; i--){ + for(j = 0; j < repr.length; j++){ + nafW = repr[j]; + if (nafW === i) b = b.mixedAdd(doubles.points[j]); + else if (nafW === -i) b = b.mixedAdd(doubles.points[j].neg()); + } + a = a.add(b); + } + return a.toP(); +}; +BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { + var w = 4; + var nafPoints = p._getNAFPoints(w); + w = nafPoints.wnd; + var wnd = nafPoints.points; + var naf = getNAF(k, w, this._bitLength); + var acc = this.jpoint(null, null, null); + for(var i = naf.length - 1; i >= 0; i--){ + for(var l = 0; i >= 0 && naf[i] === 0; i--)l++; + if (i >= 0) l++; + acc = acc.dblp(l); + if (i < 0) break; + var z = naf[i]; + assert$1(z !== 0); + if (p.type === "affine") { + if (z > 0) acc = acc.mixedAdd(wnd[z - 1 >> 1]); + else acc = acc.mixedAdd(wnd[-z - 1 >> 1].neg()); + } else { + if (z > 0) acc = acc.add(wnd[z - 1 >> 1]); + else acc = acc.add(wnd[-z - 1 >> 1].neg()); + } + } + return p.type === "affine" ? acc.toP() : acc; +}; +BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) { + var wndWidth = this._wnafT1; + var wnd = this._wnafT2; + var naf = this._wnafT3; + var max = 0; + var i; + var j; + var p; + for(i = 0; i < len; i++){ + p = points[i]; + var nafPoints = p._getNAFPoints(defW); + wndWidth[i] = nafPoints.wnd; + wnd[i] = nafPoints.points; + } + for(i = len - 1; i >= 1; i -= 2){ + var a = i - 1; + var b = i; + if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { + naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength); + naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength); + max = Math.max(naf[a].length, max); + max = Math.max(naf[b].length, max); + continue; + } + var comb = [ + points[a], + null, + null, + points[b] + ]; + if (points[a].y.cmp(points[b].y) === 0) { + comb[1] = points[a].add(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].add(points[b].neg()); + } else { + comb[1] = points[a].toJ().mixedAdd(points[b]); + comb[2] = points[a].toJ().mixedAdd(points[b].neg()); + } + var index = [ + -3, + -1, + -5, + -7, + 0, + 7, + 5, + 1, + 3 + ]; + var jsf = getJSF(coeffs[a], coeffs[b]); + max = Math.max(jsf[0].length, max); + naf[a] = new Array(max); + naf[b] = new Array(max); + for(j = 0; j < max; j++){ + var ja = jsf[0][j] | 0; + var jb = jsf[1][j] | 0; + naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; + naf[b][j] = 0; + wnd[a] = comb; + } + } + var acc = this.jpoint(null, null, null); + var tmp = this._wnafT4; + for(i = max; i >= 0; i--){ + var k = 0; + while(i >= 0){ + var zero = true; + for(j = 0; j < len; j++){ + tmp[j] = naf[j][i] | 0; + if (tmp[j] !== 0) zero = false; } - return; - case Type.negint: - if (token.value >= -24) { - return fromArray([ - 31 - Number(token.value) - ]); + if (!zero) break; + k++; + i--; + } + if (i >= 0) k++; + acc = acc.dblp(k); + if (i < 0) break; + for(j = 0; j < len; j++){ + var z = tmp[j]; + if (z === 0) continue; + else if (z > 0) p = wnd[j][z - 1 >> 1]; + else if (z < 0) p = wnd[j][-z - 1 >> 1].neg(); + if (p.type === "affine") acc = acc.mixedAdd(p); + else acc = acc.add(p); + } + } + for(i = 0; i < len; i++)wnd[i] = null; + if (jacobianResult) return acc; + else return acc.toP(); +}; +function BasePoint(curve, type) { + this.curve = curve; + this.type = type; + this.precomputed = null; +} +BaseCurve.BasePoint = BasePoint; +BasePoint.prototype.eq = function eq() { + throw new Error("Not implemented"); +}; +BasePoint.prototype.validate = function validate2() { + return this.curve.validate(this); +}; +BaseCurve.prototype.decodePoint = function decodePoint(bytes2, enc) { + bytes2 = utils_1$1.toArray(bytes2, enc); + var len = this.p.byteLength(); + if ((bytes2[0] === 4 || bytes2[0] === 6 || bytes2[0] === 7) && bytes2.length - 1 === 2 * len) { + if (bytes2[0] === 6) assert$1(bytes2[bytes2.length - 1] % 2 === 0); + else if (bytes2[0] === 7) assert$1(bytes2[bytes2.length - 1] % 2 === 1); + var res = this.point(bytes2.slice(1, 1 + len), bytes2.slice(1 + len, 1 + 2 * len)); + return res; + } else if ((bytes2[0] === 2 || bytes2[0] === 3) && bytes2.length - 1 === len) { + return this.pointFromX(bytes2.slice(1, 1 + len), bytes2[0] === 3); + } + throw new Error("Unknown point format"); +}; +BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { + return this.encode(enc, true); +}; +BasePoint.prototype._encode = function _encode(compact) { + var len = this.curve.p.byteLength(); + var x = this.getX().toArray("be", len); + if (compact) return [ + this.getY().isEven() ? 2 : 3 + ].concat(x); + return [ + 4 + ].concat(x, this.getY().toArray("be", len)); +}; +BasePoint.prototype.encode = function encode(enc, compact) { + return utils_1$1.encode(this._encode(compact), enc); +}; +BasePoint.prototype.precompute = function precompute(power) { + if (this.precomputed) return this; + var precomputed = { + doubles: null, + naf: null, + beta: null + }; + precomputed.naf = this._getNAFPoints(8); + precomputed.doubles = this._getDoubles(4, power); + precomputed.beta = this._getBeta(); + this.precomputed = precomputed; + return this; +}; +BasePoint.prototype._hasDoubles = function _hasDoubles(k) { + if (!this.precomputed) return false; + var doubles = this.precomputed.doubles; + if (!doubles) return false; + return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); +}; +BasePoint.prototype._getDoubles = function _getDoubles(step, power) { + if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; + var doubles = [ + this + ]; + var acc = this; + for(var i = 0; i < power; i += step){ + for(var j = 0; j < step; j++)acc = acc.dbl(); + doubles.push(acc); + } + return { + step, + points: doubles + }; +}; +BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { + if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; + var res = [ + this + ]; + var max = (1 << wnd) - 1; + var dbl3 = max === 1 ? null : this.dbl(); + for(var i = 1; i < max; i++)res[i] = res[i - 1].add(dbl3); + return { + wnd, + points: res + }; +}; +BasePoint.prototype._getBeta = function _getBeta() { + return null; +}; +BasePoint.prototype.dblp = function dblp(k) { + var r = this; + for(var i = 0; i < k; i++)r = r.dbl(); + return r; +}; +var inherits_browser1 = createCommonjsModule4(function(module) { + if (typeof Object.create === "function") { + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + } + }; + } else { + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor; + var TempCtor = function() {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; } + }; } -} -const defaultEncodeOptions = { - float64: false, - mapSorter, - quickEncodeToken +}); +var assert$2 = utils_1$1.assert; +function ShortCurve(conf) { + base.call(this, "short", conf); + this.a = new bn(conf.a, 16).toRed(this.red); + this.b = new bn(conf.b, 16).toRed(this.red); + this.tinv = this.two.redInvm(); + this.zeroA = this.a.fromRed().cmpn(0) === 0; + this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; + this.endo = this._getEndomorphism(conf); + this._endoWnafT1 = new Array(4); + this._endoWnafT2 = new Array(4); +} +inherits_browser1(ShortCurve, base); +var short_1 = ShortCurve; +ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { + if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) return; + var beta; + var lambda; + if (conf.beta) { + beta = new bn(conf.beta, 16).toRed(this.red); + } else { + var betas = this._getEndoRoots(this.p); + beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; + beta = beta.toRed(this.red); + } + if (conf.lambda) { + lambda = new bn(conf.lambda, 16); + } else { + var lambdas = this._getEndoRoots(this.n); + if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { + lambda = lambdas[0]; + } else { + lambda = lambdas[1]; + assert$2(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); + } + } + var basis; + if (conf.basis) { + basis = conf.basis.map(function(vec) { + return { + a: new bn(vec.a, 16), + b: new bn(vec.b, 16) + }; + }); + } else { + basis = this._getEndoBasis(lambda); + } + return { + beta, + lambda, + basis + }; }; -function makeCborEncoders() { - const encoders = []; - encoders[Type.uint.major] = encodeUint; - encoders[Type.negint.major] = encodeNegint; - encoders[Type.bytes.major] = encodeBytes; - encoders[Type.string.major] = encodeString; - encoders[Type.array.major] = encodeArray; - encoders[Type.map.major] = encodeMap; - encoders[Type.tag.major] = encodeTag; - encoders[Type.float.major] = encodeFloat; - return encoders; -} -const cborEncoders = makeCborEncoders(); -const buf = new Bl(); -class Ref { - constructor(obj, parent){ - this.obj = obj; - this.parent = parent; +ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { + var red = num === this.p ? this.red : bn.mont(num); + var tinv = new bn(2).toRed(red).redInvm(); + var ntinv = tinv.redNeg(); + var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); + var l1 = ntinv.redAdd(s).fromRed(); + var l2 = ntinv.redSub(s).fromRed(); + return [ + l1, + l2 + ]; +}; +ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { + var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); + var u = lambda; + var v = this.n.clone(); + var x1 = new bn(1); + var y1 = new bn(0); + var x2 = new bn(0); + var y2 = new bn(1); + var a0; + var b0; + var a1; + var b1; + var a2; + var b2; + var prevR; + var i = 0; + var r; + var x; + while(u.cmpn(0) !== 0){ + var q = v.div(u); + r = v.sub(q.mul(u)); + x = x2.sub(q.mul(x1)); + var y = y2.sub(q.mul(y1)); + if (!a1 && r.cmp(aprxSqrt) < 0) { + a0 = prevR.neg(); + b0 = x1; + a1 = r.neg(); + b1 = x; + } else if (a1 && ++i === 2) { + break; + } + prevR = r; + v = u; + u = r; + x2 = x1; + x1 = x; + y2 = y1; + y1 = y; + } + a2 = r.neg(); + b2 = x; + var len1 = a1.sqr().add(b1.sqr()); + var len2 = a2.sqr().add(b2.sqr()); + if (len2.cmp(len1) >= 0) { + a2 = a0; + b2 = b0; + } + if (a1.negative) { + a1 = a1.neg(); + b1 = b1.neg(); + } + if (a2.negative) { + a2 = a2.neg(); + b2 = b2.neg(); } - includes(obj) { - let p = this; - do { - if (p.obj === obj) { - return true; - } - }while (p = p.parent) - return false; + return [ + { + a: a1, + b: b1 + }, + { + a: a2, + b: b2 + } + ]; +}; +ShortCurve.prototype._endoSplit = function _endoSplit(k) { + var basis = this.endo.basis; + var v1 = basis[0]; + var v2 = basis[1]; + var c1 = v2.b.mul(k).divRound(this.n); + var c2 = v1.b.neg().mul(k).divRound(this.n); + var p1 = c1.mul(v1.a); + var p2 = c2.mul(v2.a); + var q1 = c1.mul(v1.b); + var q2 = c2.mul(v2.b); + var k1 = k.sub(p1).sub(p2); + var k2 = q1.add(q2).neg(); + return { + k1, + k2 + }; +}; +ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { + x = new bn(x, 16); + if (!x.red) x = x.toRed(this.red); + var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); + var y = y2.redSqrt(); + if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error("invalid point"); + var isOdd = y.fromRed().isOdd(); + if (odd && !isOdd || !odd && isOdd) y = y.redNeg(); + return this.point(x, y); +}; +ShortCurve.prototype.validate = function validate3(point3) { + if (point3.inf) return true; + var x = point3.x; + var y = point3.y; + var ax = this.a.redMul(x); + var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); + return y.redSqr().redISub(rhs).cmpn(0) === 0; +}; +ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs, jacobianResult) { + var npoints = this._endoWnafT1; + var ncoeffs = this._endoWnafT2; + for(var i = 0; i < points.length; i++){ + var split = this._endoSplit(coeffs[i]); + var p = points[i]; + var beta = p._getBeta(); + if (split.k1.negative) { + split.k1.ineg(); + p = p.neg(true); + } + if (split.k2.negative) { + split.k2.ineg(); + beta = beta.neg(true); + } + npoints[i * 2] = p; + npoints[i * 2 + 1] = beta; + ncoeffs[i * 2] = split.k1; + ncoeffs[i * 2 + 1] = split.k2; + } + var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); + for(var j = 0; j < i * 2; j++){ + npoints[j] = null; + ncoeffs[j] = null; } - static createCheck(stack, obj) { - if (stack && stack.includes(obj)) { - throw new Error(`${encodeErrPrefix} object contains circular references`); + return res; +}; +function Point(curve, x, y, isRed) { + base.BasePoint.call(this, curve, "affine"); + if (x === null && y === null) { + this.x = null; + this.y = null; + this.inf = true; + } else { + this.x = new bn(x, 16); + this.y = new bn(y, 16); + if (isRed) { + this.x.forceRed(this.curve.red); + this.y.forceRed(this.curve.red); } - return new Ref(obj, stack); + if (!this.x.red) this.x = this.x.toRed(this.curve.red); + if (!this.y.red) this.y = this.y.toRed(this.curve.red); + this.inf = false; } } -const simpleTokens = { - null: new Token(Type.null, null), - undefined: new Token(Type.undefined, void 0), - true: new Token(Type.true, true), - false: new Token(Type.false, false), - emptyArray: new Token(Type.array, 0), - emptyMap: new Token(Type.map, 0) +inherits_browser1(Point, base.BasePoint); +ShortCurve.prototype.point = function point2(x, y, isRed) { + return new Point(this, x, y, isRed); }; -const typeEncoders = { - number (obj, _typ, _options, _refStack) { - if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) { - return new Token(Type.float, obj); - } else if (obj >= 0) { - return new Token(Type.uint, obj); - } else { - return new Token(Type.negint, obj); - } - }, - bigint (obj, _typ, _options, _refStack) { - if (obj >= BigInt(0)) { - return new Token(Type.uint, obj); - } else { - return new Token(Type.negint, obj); - } - }, - Uint8Array (obj, _typ, _options, _refStack) { - return new Token(Type.bytes, obj); - }, - string (obj, _typ, _options, _refStack) { - return new Token(Type.string, obj); - }, - boolean (obj, _typ, _options, _refStack) { - return obj ? simpleTokens.true : simpleTokens.false; - }, - null (_obj, _typ, _options, _refStack) { - return simpleTokens.null; - }, - undefined (_obj, _typ, _options, _refStack) { - return simpleTokens.undefined; - }, - ArrayBuffer (obj, _typ, _options, _refStack) { - return new Token(Type.bytes, new Uint8Array(obj)); - }, - DataView (obj, _typ, _options, _refStack) { - return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)); - }, - Array (obj, _typ, options, refStack) { - if (!obj.length) { - if (options.addBreakTokens === true) { - return [ - simpleTokens.emptyArray, - new Token(Type.break) - ]; +ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { + return Point.fromJSON(this, obj, red); +}; +Point.prototype._getBeta = function _getBeta2() { + if (!this.curve.endo) return; + var pre = this.precomputed; + if (pre && pre.beta) return pre.beta; + var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); + if (pre) { + var curve = this.curve; + var endoMul = function(p) { + return curve.point(p.x.redMul(curve.endo.beta), p.y); + }; + pre.beta = beta; + beta.precomputed = { + beta: null, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(endoMul) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(endoMul) + } + }; + } + return beta; +}; +Point.prototype.toJSON = function toJSON() { + if (!this.precomputed) return [ + this.x, + this.y + ]; + return [ + this.x, + this.y, + this.precomputed && { + doubles: this.precomputed.doubles && { + step: this.precomputed.doubles.step, + points: this.precomputed.doubles.points.slice(1) + }, + naf: this.precomputed.naf && { + wnd: this.precomputed.naf.wnd, + points: this.precomputed.naf.points.slice(1) } - return simpleTokens.emptyArray; - } - refStack = Ref.createCheck(refStack, obj); - const entries = []; - let i = 0; - for (const e of obj){ - entries[i++] = objectToTokens(e, options, refStack); } - if (options.addBreakTokens) { - return [ - new Token(Type.array, obj.length), - entries, - new Token(Type.break) - ]; + ]; +}; +Point.fromJSON = function fromJSON(curve, obj, red) { + if (typeof obj === "string") obj = JSON.parse(obj); + var res = curve.point(obj[0], obj[1], red); + if (!obj[2]) return res; + function obj2point(obj2) { + return curve.point(obj2[0], obj2[1], red); + } + var pre = obj[2]; + res.precomputed = { + beta: null, + doubles: pre.doubles && { + step: pre.doubles.step, + points: [ + res + ].concat(pre.doubles.points.map(obj2point)) + }, + naf: pre.naf && { + wnd: pre.naf.wnd, + points: [ + res + ].concat(pre.naf.points.map(obj2point)) } - return [ - new Token(Type.array, obj.length), - entries - ]; - }, - Object (obj, typ, options, refStack) { - const isMap = typ !== "Object"; - const keys = isMap ? obj.keys() : Object.keys(obj); - const length = isMap ? obj.size : keys.length; - if (!length) { - if (options.addBreakTokens === true) { - return [ - simpleTokens.emptyMap, - new Token(Type.break) - ]; + }; + return res; +}; +Point.prototype.inspect = function inspect() { + if (this.isInfinity()) return ""; + return ""; +}; +Point.prototype.isInfinity = function isInfinity() { + return this.inf; +}; +Point.prototype.add = function add(p) { + if (this.inf) return p; + if (p.inf) return this; + if (this.eq(p)) return this.dbl(); + if (this.neg().eq(p)) return this.curve.point(null, null); + if (this.x.cmp(p.x) === 0) return this.curve.point(null, null); + var c = this.y.redSub(p.y); + if (c.cmpn(0) !== 0) c = c.redMul(this.x.redSub(p.x).redInvm()); + var nx = c.redSqr().redISub(this.x).redISub(p.x); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; +Point.prototype.dbl = function dbl() { + if (this.inf) return this; + var ys1 = this.y.redAdd(this.y); + if (ys1.cmpn(0) === 0) return this.curve.point(null, null); + var a = this.curve.a; + var x2 = this.x.redSqr(); + var dyinv = ys1.redInvm(); + var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); + var nx = c.redSqr().redISub(this.x.redAdd(this.x)); + var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); + return this.curve.point(nx, ny); +}; +Point.prototype.getX = function getX() { + return this.x.fromRed(); +}; +Point.prototype.getY = function getY() { + return this.y.fromRed(); +}; +Point.prototype.mul = function mul(k) { + k = new bn(k, 16); + if (this.isInfinity()) return this; + else if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k); + else if (this.curve.endo) return this.curve._endoWnafMulAdd([ + this + ], [ + k + ]); + else return this.curve._wnafMul(this, k); +}; +Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { + var points = [ + this, + p2 + ]; + var coeffs = [ + k1, + k2 + ]; + if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs); + else return this.curve._wnafMulAdd(1, points, coeffs, 2); +}; +Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { + var points = [ + this, + p2 + ]; + var coeffs = [ + k1, + k2 + ]; + if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs, true); + else return this.curve._wnafMulAdd(1, points, coeffs, 2, true); +}; +Point.prototype.eq = function eq2(p) { + return this === p || this.inf === p.inf && (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); +}; +Point.prototype.neg = function neg(_precompute) { + if (this.inf) return this; + var res = this.curve.point(this.x, this.y.redNeg()); + if (_precompute && this.precomputed) { + var pre = this.precomputed; + var negate = function(p) { + return p.neg(); + }; + res.precomputed = { + naf: pre.naf && { + wnd: pre.naf.wnd, + points: pre.naf.points.map(negate) + }, + doubles: pre.doubles && { + step: pre.doubles.step, + points: pre.doubles.points.map(negate) } - return simpleTokens.emptyMap; - } - refStack = Ref.createCheck(refStack, obj); - const entries = []; - let i = 0; - for (const key of keys){ - entries[i++] = [ - objectToTokens(key, options, refStack), - objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack) - ]; + }; + } + return res; +}; +Point.prototype.toJ = function toJ() { + if (this.inf) return this.curve.jpoint(null, null, null); + var res = this.curve.jpoint(this.x, this.y, this.curve.one); + return res; +}; +function JPoint(curve, x, y, z) { + base.BasePoint.call(this, curve, "jacobian"); + if (x === null && y === null && z === null) { + this.x = this.curve.one; + this.y = this.curve.one; + this.z = new bn(0); + } else { + this.x = new bn(x, 16); + this.y = new bn(y, 16); + this.z = new bn(z, 16); + } + if (!this.x.red) this.x = this.x.toRed(this.curve.red); + if (!this.y.red) this.y = this.y.toRed(this.curve.red); + if (!this.z.red) this.z = this.z.toRed(this.curve.red); + this.zOne = this.z === this.curve.one; +} +inherits_browser1(JPoint, base.BasePoint); +ShortCurve.prototype.jpoint = function jpoint(x, y, z) { + return new JPoint(this, x, y, z); +}; +JPoint.prototype.toP = function toP() { + if (this.isInfinity()) return this.curve.point(null, null); + var zinv = this.z.redInvm(); + var zinv2 = zinv.redSqr(); + var ax = this.x.redMul(zinv2); + var ay = this.y.redMul(zinv2).redMul(zinv); + return this.curve.point(ax, ay); +}; +JPoint.prototype.neg = function neg2() { + return this.curve.jpoint(this.x, this.y.redNeg(), this.z); +}; +JPoint.prototype.add = function add2(p) { + if (this.isInfinity()) return p; + if (p.isInfinity()) return this; + var pz2 = p.z.redSqr(); + var z2 = this.z.redSqr(); + var u1 = this.x.redMul(pz2); + var u2 = p.x.redMul(z2); + var s1 = this.y.redMul(pz2.redMul(p.z)); + var s2 = p.y.redMul(z2.redMul(this.z)); + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); + else return this.dbl(); + } + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(p.z).redMul(h); + return this.curve.jpoint(nx, ny, nz); +}; +JPoint.prototype.mixedAdd = function mixedAdd(p) { + if (this.isInfinity()) return p.toJ(); + if (p.isInfinity()) return this; + var z2 = this.z.redSqr(); + var u1 = this.x; + var u2 = p.x.redMul(z2); + var s1 = this.y; + var s2 = p.y.redMul(z2).redMul(this.z); + var h = u1.redSub(u2); + var r = s1.redSub(s2); + if (h.cmpn(0) === 0) { + if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); + else return this.dbl(); + } + var h2 = h.redSqr(); + var h3 = h2.redMul(h); + var v = u1.redMul(h2); + var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); + var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); + var nz = this.z.redMul(h); + return this.curve.jpoint(nx, ny, nz); +}; +JPoint.prototype.dblp = function dblp2(pow) { + if (pow === 0) return this; + if (this.isInfinity()) return this; + if (!pow) return this.dbl(); + var i; + if (this.curve.zeroA || this.curve.threeA) { + var r = this; + for(i = 0; i < pow; i++)r = r.dbl(); + return r; + } + var a = this.curve.a; + var tinv = this.curve.tinv; + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + var jyd = jy.redAdd(jy); + for(i = 0; i < pow; i++){ + var jx2 = jx.redSqr(); + var jyd2 = jyd.redSqr(); + var jyd4 = jyd2.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + var t1 = jx.redMul(jyd2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var dny = c.redMul(t2); + dny = dny.redIAdd(dny).redISub(jyd4); + var nz = jyd.redMul(jz); + if (i + 1 < pow) jz4 = jz4.redMul(jyd4); + jx = nx; + jz = nz; + jyd = dny; + } + return this.curve.jpoint(jx, jyd.redMul(tinv), jz); +}; +JPoint.prototype.dbl = function dbl2() { + if (this.isInfinity()) return this; + if (this.curve.zeroA) return this._zeroDbl(); + else if (this.curve.threeA) return this._threeDbl(); + else return this._dbl(); +}; +JPoint.prototype._zeroDbl = function _zeroDbl() { + var nx; + var ny; + var nz; + if (this.zOne) { + var xx = this.x.redSqr(); + var yy = this.y.redSqr(); + var yyyy = yy.redSqr(); + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + var m = xx.redAdd(xx).redIAdd(xx); + var t = m.redSqr().redISub(s).redISub(s); + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + nx = t; + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + nz = this.y.redAdd(this.y); + } else { + var a = this.x.redSqr(); + var b = this.y.redSqr(); + var c = b.redSqr(); + var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); + d = d.redIAdd(d); + var e = a.redAdd(a).redIAdd(a); + var f = e.redSqr(); + var c8 = c.redIAdd(c); + c8 = c8.redIAdd(c8); + c8 = c8.redIAdd(c8); + nx = f.redISub(d).redISub(d); + ny = e.redMul(d.redISub(nx)).redISub(c8); + nz = this.y.redMul(this.z); + nz = nz.redIAdd(nz); + } + return this.curve.jpoint(nx, ny, nz); +}; +JPoint.prototype._threeDbl = function _threeDbl() { + var nx; + var ny; + var nz; + if (this.zOne) { + var xx = this.x.redSqr(); + var yy = this.y.redSqr(); + var yyyy = yy.redSqr(); + var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + s = s.redIAdd(s); + var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); + var t = m.redSqr().redISub(s).redISub(s); + nx = t; + var yyyy8 = yyyy.redIAdd(yyyy); + yyyy8 = yyyy8.redIAdd(yyyy8); + yyyy8 = yyyy8.redIAdd(yyyy8); + ny = m.redMul(s.redISub(t)).redISub(yyyy8); + nz = this.y.redAdd(this.y); + } else { + var delta = this.z.redSqr(); + var gamma = this.y.redSqr(); + var beta = this.x.redMul(gamma); + var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); + alpha = alpha.redAdd(alpha).redIAdd(alpha); + var beta4 = beta.redIAdd(beta); + beta4 = beta4.redIAdd(beta4); + var beta8 = beta4.redAdd(beta4); + nx = alpha.redSqr().redISub(beta8); + nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); + var ggamma8 = gamma.redSqr(); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ggamma8 = ggamma8.redIAdd(ggamma8); + ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); + } + return this.curve.jpoint(nx, ny, nz); +}; +JPoint.prototype._dbl = function _dbl() { + var a = this.curve.a; + var jx = this.x; + var jy = this.y; + var jz = this.z; + var jz4 = jz.redSqr().redSqr(); + var jx2 = jx.redSqr(); + var jy2 = jy.redSqr(); + var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); + var jxd4 = jx.redAdd(jx); + jxd4 = jxd4.redIAdd(jxd4); + var t1 = jxd4.redMul(jy2); + var nx = c.redSqr().redISub(t1.redAdd(t1)); + var t2 = t1.redISub(nx); + var jyd8 = jy2.redSqr(); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + jyd8 = jyd8.redIAdd(jyd8); + var ny = c.redMul(t2).redISub(jyd8); + var nz = jy.redAdd(jy).redMul(jz); + return this.curve.jpoint(nx, ny, nz); +}; +JPoint.prototype.trpl = function trpl() { + if (!this.curve.zeroA) return this.dbl().add(this); + var xx = this.x.redSqr(); + var yy = this.y.redSqr(); + var zz = this.z.redSqr(); + var yyyy = yy.redSqr(); + var m = xx.redAdd(xx).redIAdd(xx); + var mm = m.redSqr(); + var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); + e = e.redIAdd(e); + e = e.redAdd(e).redIAdd(e); + e = e.redISub(mm); + var ee = e.redSqr(); + var t = yyyy.redIAdd(yyyy); + t = t.redIAdd(t); + t = t.redIAdd(t); + t = t.redIAdd(t); + var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); + var yyu4 = yy.redMul(u); + yyu4 = yyu4.redIAdd(yyu4); + yyu4 = yyu4.redIAdd(yyu4); + var nx = this.x.redMul(ee).redISub(yyu4); + nx = nx.redIAdd(nx); + nx = nx.redIAdd(nx); + var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + ny = ny.redIAdd(ny); + var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); + return this.curve.jpoint(nx, ny, nz); +}; +JPoint.prototype.mul = function mul2(k, kbase) { + k = new bn(k, kbase); + return this.curve._wnafMul(this, k); +}; +JPoint.prototype.eq = function eq3(p) { + if (p.type === "affine") return this.eq(p.toJ()); + if (this === p) return true; + var z2 = this.z.redSqr(); + var pz2 = p.z.redSqr(); + if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) return false; + var z3 = z2.redMul(this.z); + var pz3 = pz2.redMul(p.z); + return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; +}; +JPoint.prototype.eqXToP = function eqXToP(x) { + var zs = this.z.redSqr(); + var rx = x.toRed(this.curve.red).redMul(zs); + if (this.x.cmp(rx) === 0) return true; + var xc = x.clone(); + var t = this.curve.redN.redMul(zs); + for(;;){ + xc.iadd(this.curve.n); + if (xc.cmp(this.curve.p) >= 0) return false; + rx.redIAdd(t); + if (this.x.cmp(rx) === 0) return true; + } +}; +JPoint.prototype.inspect = function inspect2() { + if (this.isInfinity()) return ""; + return ""; +}; +JPoint.prototype.isInfinity = function isInfinity2() { + return this.z.cmpn(0) === 0; +}; +var curve_1 = createCommonjsModule4(function(module, exports) { + var curve = exports; + curve.base = base; + curve.short = short_1; + curve.mont = null; + curve.edwards = null; +}); +var curves_1 = createCommonjsModule4(function(module, exports) { + var curves = exports; + var assert2 = utils_1$1.assert; + function PresetCurve(options) { + if (options.type === "short") this.curve = new curve_1.short(options); + else if (options.type === "edwards") this.curve = new curve_1.edwards(options); + else this.curve = new curve_1.mont(options); + this.g = this.curve.g; + this.n = this.curve.n; + this.hash = options.hash; + assert2(this.g.validate(), "Invalid curve"); + assert2(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); + } + curves.PresetCurve = PresetCurve; + function defineCurve(name, options) { + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + get: function() { + var curve = new PresetCurve(options); + Object.defineProperty(curves, name, { + configurable: true, + enumerable: true, + value: curve + }); + return curve; + } + }); + } + defineCurve("p192", { + type: "short", + prime: "p192", + p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", + a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", + b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", + n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", + hash: hash_1.sha256, + gRed: false, + g: [ + "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", + "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811" + ] + }); + defineCurve("p224", { + type: "short", + prime: "p224", + p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", + a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", + b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", + n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", + hash: hash_1.sha256, + gRed: false, + g: [ + "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", + "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34" + ] + }); + defineCurve("p256", { + type: "short", + prime: null, + p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", + a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", + b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", + n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", + hash: hash_1.sha256, + gRed: false, + g: [ + "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", + "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5" + ] + }); + defineCurve("p384", { + type: "short", + prime: null, + p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", + a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", + b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", + n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", + hash: hash_1.sha384, + gRed: false, + g: [ + "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", + "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f" + ] + }); + defineCurve("p521", { + type: "short", + prime: null, + p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", + a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", + b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", + n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", + hash: hash_1.sha512, + gRed: false, + g: [ + "000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", + "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650" + ] + }); + defineCurve("curve25519", { + type: "mont", + prime: "p25519", + p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", + a: "76d06", + b: "1", + n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", + hash: hash_1.sha256, + gRed: false, + g: [ + "9" + ] + }); + defineCurve("ed25519", { + type: "edwards", + prime: "p25519", + p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", + a: "-1", + c: "1", + d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", + n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", + hash: hash_1.sha256, + gRed: false, + g: [ + "216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", + "6666666666666666666666666666666666666666666666666666666666666658" + ] + }); + var pre; + try { + pre = null.crash(); + } catch (e) { + pre = void 0; + } + defineCurve("secp256k1", { + type: "short", + prime: "k256", + p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", + a: "0", + b: "7", + n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", + h: "1", + hash: hash_1.sha256, + beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", + lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", + basis: [ + { + a: "3086d221a7d46bcde86c90e49284eb15", + b: "-e4437ed6010e88286f547fa90abfe4c3" + }, + { + a: "114ca50f7a8e2f3f657c1108d9d44cfd8", + b: "3086d221a7d46bcde86c90e49284eb15" + } + ], + gRed: false, + g: [ + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", + pre + ] + }); +}); +function HmacDRBG(options) { + if (!(this instanceof HmacDRBG)) return new HmacDRBG(options); + this.hash = options.hash; + this.predResist = !!options.predResist; + this.outLen = this.hash.outSize; + this.minEntropy = options.minEntropy || this.hash.hmacStrength; + this._reseed = null; + this.reseedInterval = null; + this.K = null; + this.V = null; + var entropy = utils_1.toArray(options.entropy, options.entropyEnc || "hex"); + var nonce = utils_1.toArray(options.nonce, options.nonceEnc || "hex"); + var pers = utils_1.toArray(options.pers, options.persEnc || "hex"); + minimalisticAssert1(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"); + this._init(entropy, nonce, pers); +} +var hmacDrbg = HmacDRBG; +HmacDRBG.prototype._init = function init(entropy, nonce, pers) { + var seed = entropy.concat(nonce).concat(pers); + this.K = new Array(this.outLen / 8); + this.V = new Array(this.outLen / 8); + for(var i = 0; i < this.V.length; i++){ + this.K[i] = 0; + this.V[i] = 1; + } + this._update(seed); + this._reseed = 1; + this.reseedInterval = 281474976710656; +}; +HmacDRBG.prototype._hmac = function hmac() { + return new hash_1.hmac(this.hash, this.K); +}; +HmacDRBG.prototype._update = function update(seed) { + var kmac = this._hmac().update(this.V).update([ + 0 + ]); + if (seed) kmac = kmac.update(seed); + this.K = kmac.digest(); + this.V = this._hmac().update(this.V).digest(); + if (!seed) return; + this.K = this._hmac().update(this.V).update([ + 1 + ]).update(seed).digest(); + this.V = this._hmac().update(this.V).digest(); +}; +HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add3, addEnc) { + if (typeof entropyEnc !== "string") { + addEnc = add3; + add3 = entropyEnc; + entropyEnc = null; + } + entropy = utils_1.toArray(entropy, entropyEnc); + add3 = utils_1.toArray(add3, addEnc); + minimalisticAssert1(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"); + this._update(entropy.concat(add3 || [])); + this._reseed = 1; +}; +HmacDRBG.prototype.generate = function generate(len, enc, add3, addEnc) { + if (this._reseed > this.reseedInterval) throw new Error("Reseed is required"); + if (typeof enc !== "string") { + addEnc = add3; + add3 = enc; + enc = null; + } + if (add3) { + add3 = utils_1.toArray(add3, addEnc || "hex"); + this._update(add3); + } + var temp = []; + while(temp.length < len){ + this.V = this._hmac().update(this.V).digest(); + temp = temp.concat(this.V); + } + var res = temp.slice(0, len); + this._update(add3); + this._reseed++; + return utils_1.encode(res, enc); +}; +var assert$3 = utils_1$1.assert; +function KeyPair(ec2, options) { + this.ec = ec2; + this.priv = null; + this.pub = null; + if (options.priv) this._importPrivate(options.priv, options.privEnc); + if (options.pub) this._importPublic(options.pub, options.pubEnc); +} +var key = KeyPair; +KeyPair.fromPublic = function fromPublic(ec2, pub, enc) { + if (pub instanceof KeyPair) return pub; + return new KeyPair(ec2, { + pub, + pubEnc: enc + }); +}; +KeyPair.fromPrivate = function fromPrivate(ec2, priv, enc) { + if (priv instanceof KeyPair) return priv; + return new KeyPair(ec2, { + priv, + privEnc: enc + }); +}; +KeyPair.prototype.validate = function validate4() { + var pub = this.getPublic(); + if (pub.isInfinity()) return { + result: false, + reason: "Invalid public key" + }; + if (!pub.validate()) return { + result: false, + reason: "Public key is not a point" + }; + if (!pub.mul(this.ec.curve.n).isInfinity()) return { + result: false, + reason: "Public key * N != O" + }; + return { + result: true, + reason: null + }; +}; +KeyPair.prototype.getPublic = function getPublic(compact, enc) { + if (typeof compact === "string") { + enc = compact; + compact = null; + } + if (!this.pub) this.pub = this.ec.g.mul(this.priv); + if (!enc) return this.pub; + return this.pub.encode(enc, compact); +}; +KeyPair.prototype.getPrivate = function getPrivate(enc) { + if (enc === "hex") return this.priv.toString(16, 2); + else return this.priv; +}; +KeyPair.prototype._importPrivate = function _importPrivate(key2, enc) { + this.priv = new bn(key2, enc || 16); + this.priv = this.priv.umod(this.ec.curve.n); +}; +KeyPair.prototype._importPublic = function _importPublic(key2, enc) { + if (key2.x || key2.y) { + if (this.ec.curve.type === "mont") { + assert$3(key2.x, "Need x coordinate"); + } else if (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") { + assert$3(key2.x && key2.y, "Need both x and y coordinate"); + } + this.pub = this.ec.curve.point(key2.x, key2.y); + return; + } + this.pub = this.ec.curve.decodePoint(key2, enc); +}; +KeyPair.prototype.derive = function derive(pub) { + if (!pub.validate()) { + assert$3(pub.validate(), "public point not validated"); + } + return pub.mul(this.priv).getX(); +}; +KeyPair.prototype.sign = function sign(msg, enc, options) { + return this.ec.sign(msg, this, enc, options); +}; +KeyPair.prototype.verify = function verify(msg, signature2) { + return this.ec.verify(msg, signature2, this); +}; +KeyPair.prototype.inspect = function inspect3() { + return ""; +}; +var assert$4 = utils_1$1.assert; +function Signature(options, enc) { + if (options instanceof Signature) return options; + if (this._importDER(options, enc)) return; + assert$4(options.r && options.s, "Signature without r or s"); + this.r = new bn(options.r, 16); + this.s = new bn(options.s, 16); + if (options.recoveryParam === void 0) this.recoveryParam = null; + else this.recoveryParam = options.recoveryParam; +} +var signature = Signature; +function Position() { + this.place = 0; +} +function getLength(buf, p) { + var initial = buf[p.place++]; + if (!(initial & 128)) { + return initial; + } + var octetLen = initial & 15; + if (octetLen === 0 || octetLen > 4) { + return false; + } + var val = 0; + for(var i = 0, off = p.place; i < octetLen; i++, off++){ + val <<= 8; + val |= buf[off]; + val >>>= 0; + } + if (val <= 127) { + return false; + } + p.place = off; + return val; +} +function rmPadding(buf) { + var i = 0; + var len = buf.length - 1; + while(!buf[i] && !(buf[i + 1] & 128) && i < len){ + i++; + } + if (i === 0) { + return buf; + } + return buf.slice(i); +} +Signature.prototype._importDER = function _importDER(data, enc) { + data = utils_1$1.toArray(data, enc); + var p = new Position(); + if (data[p.place++] !== 48) { + return false; + } + var len = getLength(data, p); + if (len === false) { + return false; + } + if (len + p.place !== data.length) { + return false; + } + if (data[p.place++] !== 2) { + return false; + } + var rlen = getLength(data, p); + if (rlen === false) { + return false; + } + var r = data.slice(p.place, rlen + p.place); + p.place += rlen; + if (data[p.place++] !== 2) { + return false; + } + var slen = getLength(data, p); + if (slen === false) { + return false; + } + if (data.length !== slen + p.place) { + return false; + } + var s = data.slice(p.place, slen + p.place); + if (r[0] === 0) { + if (r[1] & 128) { + r = r.slice(1); + } else { + return false; } - sortMapEntries(entries, options); - if (options.addBreakTokens) { - return [ - new Token(Type.map, length), - entries, - new Token(Type.break) - ]; + } + if (s[0] === 0) { + if (s[1] & 128) { + s = s.slice(1); + } else { + return false; } - return [ - new Token(Type.map, length), - entries - ]; } + this.r = new bn(r); + this.s = new bn(s); + this.recoveryParam = null; + return true; }; -typeEncoders.Map = typeEncoders.Object; -typeEncoders.Buffer = typeEncoders.Uint8Array; -for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")){ - typeEncoders[`${typ}Array`] = typeEncoders.DataView; -} -function objectToTokens(obj, options = {}, refStack) { - const typ = is(obj); - const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ]; - if (typeof customTypeEncoder === "function") { - const tokens = customTypeEncoder(obj, typ, options, refStack); - if (tokens != null) { - return tokens; +function constructLength(arr, len) { + if (len < 128) { + arr.push(len); + return; + } + var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); + arr.push(octets | 128); + while(--octets){ + arr.push(len >>> (octets << 3) & 255); + } + arr.push(len); +} +Signature.prototype.toDER = function toDER(enc) { + var r = this.r.toArray(); + var s = this.s.toArray(); + if (r[0] & 128) r = [ + 0 + ].concat(r); + if (s[0] & 128) s = [ + 0 + ].concat(s); + r = rmPadding(r); + s = rmPadding(s); + while(!s[0] && !(s[1] & 128)){ + s = s.slice(1); + } + var arr = [ + 2 + ]; + constructLength(arr, r.length); + arr = arr.concat(r); + arr.push(2); + constructLength(arr, s.length); + var backHalf = arr.concat(s); + var res = [ + 48 + ]; + constructLength(res, backHalf.length); + res = res.concat(backHalf); + return utils_1$1.encode(res, enc); +}; +var rand = function() { + throw new Error("unsupported"); +}; +var assert$5 = utils_1$1.assert; +function EC(options) { + if (!(this instanceof EC)) return new EC(options); + if (typeof options === "string") { + assert$5(Object.prototype.hasOwnProperty.call(curves_1, options), "Unknown curve " + options); + options = curves_1[options]; + } + if (options instanceof curves_1.PresetCurve) options = { + curve: options + }; + this.curve = options.curve.curve; + this.n = this.curve.n; + this.nh = this.n.ushrn(1); + this.g = this.curve.g; + this.g = options.curve.g; + this.g.precompute(options.curve.n.bitLength() + 1); + this.hash = options.hash || options.curve.hash; +} +var ec = EC; +EC.prototype.keyPair = function keyPair(options) { + return new key(this, options); +}; +EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { + return key.fromPrivate(this, priv, enc); +}; +EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { + return key.fromPublic(this, pub, enc); +}; +EC.prototype.genKeyPair = function genKeyPair(options) { + if (!options) options = {}; + var drbg = new hmacDrbg({ + hash: this.hash, + pers: options.pers, + persEnc: options.persEnc || "utf8", + entropy: options.entropy || rand(this.hash.hmacStrength), + entropyEnc: options.entropy && options.entropyEnc || "utf8", + nonce: this.n.toArray() + }); + var bytes2 = this.n.byteLength(); + var ns2 = this.n.sub(new bn(2)); + for(;;){ + var priv = new bn(drbg.generate(bytes2)); + if (priv.cmp(ns2) > 0) continue; + priv.iaddn(1); + return this.keyFromPrivate(priv); + } +}; +EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) { + var delta = msg.byteLength() * 8 - this.n.bitLength(); + if (delta > 0) msg = msg.ushrn(delta); + if (!truncOnly && msg.cmp(this.n) >= 0) return msg.sub(this.n); + else return msg; +}; +EC.prototype.sign = function sign2(msg, key2, enc, options) { + if (typeof enc === "object") { + options = enc; + enc = null; + } + if (!options) options = {}; + key2 = this.keyFromPrivate(key2, enc); + msg = this._truncateToN(new bn(msg, 16)); + var bytes2 = this.n.byteLength(); + var bkey = key2.getPrivate().toArray("be", bytes2); + var nonce = msg.toArray("be", bytes2); + var drbg = new hmacDrbg({ + hash: this.hash, + entropy: bkey, + nonce, + pers: options.pers, + persEnc: options.persEnc || "utf8" + }); + var ns1 = this.n.sub(new bn(1)); + for(var iter = 0;; iter++){ + var k = options.k ? options.k(iter) : new bn(drbg.generate(this.n.byteLength())); + k = this._truncateToN(k, true); + if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) continue; + var kp = this.g.mul(k); + if (kp.isInfinity()) continue; + var kpX = kp.getX(); + var r = kpX.umod(this.n); + if (r.cmpn(0) === 0) continue; + var s = k.invm(this.n).mul(r.mul(key2.getPrivate()).iadd(msg)); + s = s.umod(this.n); + if (s.cmpn(0) === 0) continue; + var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r) !== 0 ? 2 : 0); + if (options.canonical && s.cmp(this.nh) > 0) { + s = this.n.sub(s); + recoveryParam ^= 1; + } + return new signature({ + r, + s, + recoveryParam + }); + } +}; +EC.prototype.verify = function verify2(msg, signature$1, key2, enc) { + msg = this._truncateToN(new bn(msg, 16)); + key2 = this.keyFromPublic(key2, enc); + signature$1 = new signature(signature$1, "hex"); + var r = signature$1.r; + var s = signature$1.s; + if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) return false; + if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) return false; + var sinv = s.invm(this.n); + var u1 = sinv.mul(msg).umod(this.n); + var u2 = sinv.mul(r).umod(this.n); + var p; + if (!this.curve._maxwellTrick) { + p = this.g.mulAdd(u1, key2.getPublic(), u2); + if (p.isInfinity()) return false; + return p.getX().umod(this.n).cmp(r) === 0; + } + p = this.g.jmulAdd(u1, key2.getPublic(), u2); + if (p.isInfinity()) return false; + return p.eqXToP(r); +}; +EC.prototype.recoverPubKey = function(msg, signature$1, j, enc) { + assert$5((3 & j) === j, "The recovery param is more than two bits"); + signature$1 = new signature(signature$1, enc); + var n = this.n; + var e = new bn(msg); + var r = signature$1.r; + var s = signature$1.s; + var isYOdd = j & 1; + var isSecondKey = j >> 1; + if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) throw new Error("Unable to find sencond key candinate"); + if (isSecondKey) r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); + else r = this.curve.pointFromX(r, isYOdd); + var rInv = signature$1.r.invm(n); + var s1 = n.sub(e).mul(rInv).umod(n); + var s2 = s.mul(rInv).umod(n); + return this.g.mulAdd(s1, r, s2); +}; +EC.prototype.getKeyRecoveryParam = function(e, signature$1, Q, enc) { + signature$1 = new signature(signature$1, enc); + if (signature$1.recoveryParam !== null) return signature$1.recoveryParam; + for(var i = 0; i < 4; i++){ + var Qprime; + try { + Qprime = this.recoverPubKey(e, signature$1, i); + } catch (e2) { + continue; } + if (Qprime.eq(Q)) return i; } - const typeEncoder = typeEncoders[typ]; - if (!typeEncoder) { - throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`); + throw new Error("Unable to find valid recovery factor"); +}; +var elliptic_1 = createCommonjsModule4(function(module, exports) { + var elliptic = exports; + elliptic.version = ({ + version: "6.5.4" + }).version; + elliptic.utils = utils_1$1; + elliptic.rand = function() { + throw new Error("unsupported"); + }; + elliptic.curve = curve_1; + elliptic.curves = curves_1; + elliptic.ec = ec; + elliptic.eddsa = null; +}); +var EC$1 = elliptic_1.ec; +const version12 = "signing-key/5.7.0"; +const logger210 = new Logger(version12); +let _curve = null; +function getCurve() { + if (!_curve) { + _curve = new EC$1("secp256k1"); + } + return _curve; +} +class SigningKey { + constructor(privateKey){ + defineReadOnly(this, "curve", "secp256k1"); + defineReadOnly(this, "privateKey", hexlify(privateKey)); + if (hexDataLength(this.privateKey) !== 32) { + logger210.throwArgumentError("invalid private key", "privateKey", "[[ REDACTED ]]"); + } + const keyPair2 = getCurve().keyFromPrivate(arrayify(this.privateKey)); + defineReadOnly(this, "publicKey", "0x" + keyPair2.getPublic(false, "hex")); + defineReadOnly(this, "compressedPublicKey", "0x" + keyPair2.getPublic(true, "hex")); + defineReadOnly(this, "_isSigningKey", true); + } + _addPoint(other) { + const p0 = getCurve().keyFromPublic(arrayify(this.publicKey)); + const p1 = getCurve().keyFromPublic(arrayify(other)); + return "0x" + p0.pub.add(p1.pub).encodeCompressed("hex"); + } + signDigest(digest) { + const keyPair2 = getCurve().keyFromPrivate(arrayify(this.privateKey)); + const digestBytes = arrayify(digest); + if (digestBytes.length !== 32) { + logger210.throwArgumentError("bad digest length", "digest", digest); + } + const signature2 = keyPair2.sign(digestBytes, { + canonical: true + }); + return splitSignature({ + recoveryParam: signature2.recoveryParam, + r: hexZeroPad("0x" + signature2.r.toString(16), 32), + s: hexZeroPad("0x" + signature2.s.toString(16), 32) + }); + } + computeSharedSecret(otherKey) { + const keyPair2 = getCurve().keyFromPrivate(arrayify(this.privateKey)); + const otherKeyPair = getCurve().keyFromPublic(arrayify(computePublicKey(otherKey))); + return hexZeroPad("0x" + keyPair2.derive(otherKeyPair.getPublic()).toString(16), 32); + } + static isSigningKey(value) { + return !!(value && value._isSigningKey); } - return typeEncoder(obj, typ, options, refStack); } -function sortMapEntries(entries, options) { - if (options.mapSorter) { - entries.sort(options.mapSorter); +function recoverPublicKey(digest, signature2) { + const sig = splitSignature(signature2); + const rs = { + r: arrayify(sig.r), + s: arrayify(sig.s) + }; + return "0x" + getCurve().recoverPubKey(arrayify(digest), rs, sig.recoveryParam).encode("hex", false); +} +function computePublicKey(key2, compressed) { + const bytes2 = arrayify(key2); + if (bytes2.length === 32) { + const signingKey = new SigningKey(bytes2); + if (compressed) { + return "0x" + getCurve().keyFromPrivate(bytes2).getPublic(true, "hex"); + } + return signingKey.publicKey; + } else if (bytes2.length === 33) { + if (compressed) { + return hexlify(bytes2); + } + return "0x" + getCurve().keyFromPublic(bytes2).getPublic(false, "hex"); + } else if (bytes2.length === 65) { + if (!compressed) { + return hexlify(bytes2); + } + return "0x" + getCurve().keyFromPublic(bytes2).getPublic(true, "hex"); + } + return logger210.throwArgumentError("invalid public or private key", "key", "[REDACTED]"); +} +const version13 = "transactions/5.7.0"; +const logger211 = new Logger(version13); +var TransactionTypes; +(function(TransactionTypes2) { + TransactionTypes2[TransactionTypes2["legacy"] = 0] = "legacy"; + TransactionTypes2[TransactionTypes2["eip2930"] = 1] = "eip2930"; + TransactionTypes2[TransactionTypes2["eip1559"] = 2] = "eip1559"; +})(TransactionTypes || (TransactionTypes = {})); +function handleAddress(value) { + if (value === "0x") { + return null; } + return getAddress(value); } -function mapSorter(e1, e2) { - const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]; - const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]; - if (keyToken1.type !== keyToken2.type) { - return keyToken1.type.compare(keyToken2.type); +function handleNumber(value) { + if (value === "0x") { + return Zero1; } - const major = keyToken1.type.major; - const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2); - if (tcmp === 0) { - console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"); + return BigNumber.from(value); +} +const transactionFields = [ + { + name: "nonce", + maxLength: 32, + numeric: true + }, + { + name: "gasPrice", + maxLength: 32, + numeric: true + }, + { + name: "gasLimit", + maxLength: 32, + numeric: true + }, + { + name: "to", + length: 20 + }, + { + name: "value", + maxLength: 32, + numeric: true + }, + { + name: "data" } - return tcmp; +]; +const allowedTransactionKeys1 = { + chainId: true, + data: true, + gasLimit: true, + gasPrice: true, + nonce: true, + to: true, + type: true, + value: true +}; +function computeAddress(key) { + const publicKey = computePublicKey(key); + return getAddress(hexDataSlice(keccak256(hexDataSlice(publicKey, 1)), 12)); } -function tokensToEncoded(buf2, tokens, encoders, options) { - if (Array.isArray(tokens)) { - for (const token of tokens){ - tokensToEncoded(buf2, token, encoders, options); +function recoverAddress(digest, signature) { + return computeAddress(recoverPublicKey(arrayify(digest), signature)); +} +function formatNumber(value, name) { + const result = stripZeros(BigNumber.from(value).toHexString()); + if (result.length > 32) { + logger211.throwArgumentError("invalid length for " + name, "transaction:" + name, value); + } + return result; +} +function accessSetify(addr, storageKeys) { + return { + address: getAddress(addr), + storageKeys: (storageKeys || []).map((storageKey, index)=>{ + if (hexDataLength(storageKey) !== 32) { + logger211.throwArgumentError("invalid access list storageKey", `accessList[${addr}:${index}]`, storageKey); + } + return storageKey.toLowerCase(); + }) + }; +} +function accessListify(value) { + if (Array.isArray(value)) { + return value.map((set, index)=>{ + if (Array.isArray(set)) { + if (set.length > 2) { + logger211.throwArgumentError("access list expected to be [ address, storageKeys[] ]", `value[${index}]`, set); + } + return accessSetify(set[0], set[1]); + } + return accessSetify(set.address, set.storageKeys); + }); + } + const result = Object.keys(value).map((addr)=>{ + const storageKeys = value[addr].reduce((accum, storageKey)=>{ + accum[storageKey] = true; + return accum; + }, {}); + return accessSetify(addr, Object.keys(storageKeys).sort()); + }); + result.sort((a, b)=>a.address.localeCompare(b.address)); + return result; +} +function formatAccessList(value) { + return accessListify(value).map((set)=>[ + set.address, + set.storageKeys + ]); +} +function _serializeEip1559(transaction, signature) { + if (transaction.gasPrice != null) { + const gasPrice = BigNumber.from(transaction.gasPrice); + const maxFeePerGas = BigNumber.from(transaction.maxFeePerGas || 0); + if (!gasPrice.eq(maxFeePerGas)) { + logger211.throwArgumentError("mismatch EIP-1559 gasPrice != maxFeePerGas", "tx", { + gasPrice, + maxFeePerGas + }); } + } + const fields = [ + formatNumber(transaction.chainId || 0, "chainId"), + formatNumber(transaction.nonce || 0, "nonce"), + formatNumber(transaction.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(transaction.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(transaction.gasLimit || 0, "gasLimit"), + transaction.to != null ? getAddress(transaction.to) : "0x", + formatNumber(transaction.value || 0, "value"), + transaction.data || "0x", + formatAccessList(transaction.accessList || []) + ]; + if (signature) { + const sig = splitSignature(signature); + fields.push(formatNumber(sig.recoveryParam, "recoveryParam")); + fields.push(stripZeros(sig.r)); + fields.push(stripZeros(sig.s)); + } + return hexConcat([ + "0x02", + encode(fields) + ]); +} +function _serializeEip2930(transaction, signature) { + const fields = [ + formatNumber(transaction.chainId || 0, "chainId"), + formatNumber(transaction.nonce || 0, "nonce"), + formatNumber(transaction.gasPrice || 0, "gasPrice"), + formatNumber(transaction.gasLimit || 0, "gasLimit"), + transaction.to != null ? getAddress(transaction.to) : "0x", + formatNumber(transaction.value || 0, "value"), + transaction.data || "0x", + formatAccessList(transaction.accessList || []) + ]; + if (signature) { + const sig = splitSignature(signature); + fields.push(formatNumber(sig.recoveryParam, "recoveryParam")); + fields.push(stripZeros(sig.r)); + fields.push(stripZeros(sig.s)); + } + return hexConcat([ + "0x01", + encode(fields) + ]); +} +function _serialize(transaction, signature) { + checkProperties(transaction, allowedTransactionKeys1); + const raw = []; + transactionFields.forEach(function(fieldInfo) { + let value = transaction[fieldInfo.name] || []; + const options = {}; + if (fieldInfo.numeric) { + options.hexPad = "left"; + } + value = arrayify(hexlify(value, options)); + if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) { + logger211.throwArgumentError("invalid length for " + fieldInfo.name, "transaction:" + fieldInfo.name, value); + } + if (fieldInfo.maxLength) { + value = stripZeros(value); + if (value.length > fieldInfo.maxLength) { + logger211.throwArgumentError("invalid length for " + fieldInfo.name, "transaction:" + fieldInfo.name, value); + } + } + raw.push(hexlify(value)); + }); + let chainId = 0; + if (transaction.chainId != null) { + chainId = transaction.chainId; + if (typeof chainId !== "number") { + logger211.throwArgumentError("invalid transaction.chainId", "transaction", transaction); + } + } else if (signature && !isBytesLike(signature) && signature.v > 28) { + chainId = Math.floor((signature.v - 35) / 2); + } + if (chainId !== 0) { + raw.push(hexlify(chainId)); + raw.push("0x"); + raw.push("0x"); + } + if (!signature) { + return encode(raw); + } + const sig = splitSignature(signature); + let v = 27 + sig.recoveryParam; + if (chainId !== 0) { + raw.pop(); + raw.pop(); + raw.pop(); + v += chainId * 2 + 8; + if (sig.v > 28 && sig.v !== v) { + logger211.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature); + } + } else if (sig.v !== v) { + logger211.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature); + } + raw.push(hexlify(v)); + raw.push(stripZeros(arrayify(sig.r))); + raw.push(stripZeros(arrayify(sig.s))); + return encode(raw); +} +function serialize(transaction, signature) { + if (transaction.type == null || transaction.type === 0) { + if (transaction.accessList != null) { + logger211.throwArgumentError("untyped transactions do not support accessList; include type: 1", "transaction", transaction); + } + return _serialize(transaction, signature); + } + switch(transaction.type){ + case 1: + return _serializeEip2930(transaction, signature); + case 2: + return _serializeEip1559(transaction, signature); + } + return logger211.throwError(`unsupported transaction type: ${transaction.type}`, Logger.errors.UNSUPPORTED_OPERATION, { + operation: "serializeTransaction", + transactionType: transaction.type + }); +} +function _parseEipSignature(tx, fields, serialize2) { + try { + const recid = handleNumber(fields[0]).toNumber(); + if (recid !== 0 && recid !== 1) { + throw new Error("bad recid"); + } + tx.v = recid; + } catch (error) { + logger211.throwArgumentError("invalid v for transaction type: 1", "v", fields[0]); + } + tx.r = hexZeroPad(fields[1], 32); + tx.s = hexZeroPad(fields[2], 32); + try { + const digest = keccak256(serialize2(tx)); + tx.from = recoverAddress(digest, { + r: tx.r, + s: tx.s, + recoveryParam: tx.v + }); + } catch (error) {} +} +function _parseEip1559(payload) { + const transaction = decode1(payload.slice(1)); + if (transaction.length !== 9 && transaction.length !== 12) { + logger211.throwArgumentError("invalid component count for transaction type: 2", "payload", hexlify(payload)); + } + const maxPriorityFeePerGas = handleNumber(transaction[2]); + const maxFeePerGas = handleNumber(transaction[3]); + const tx = { + type: 2, + chainId: handleNumber(transaction[0]).toNumber(), + nonce: handleNumber(transaction[1]).toNumber(), + maxPriorityFeePerGas, + maxFeePerGas, + gasPrice: null, + gasLimit: handleNumber(transaction[4]), + to: handleAddress(transaction[5]), + value: handleNumber(transaction[6]), + data: transaction[7], + accessList: accessListify(transaction[8]) + }; + if (transaction.length === 9) { + return tx; + } + tx.hash = keccak256(payload); + _parseEipSignature(tx, transaction.slice(9), _serializeEip1559); + return tx; +} +function _parseEip2930(payload) { + const transaction = decode1(payload.slice(1)); + if (transaction.length !== 8 && transaction.length !== 11) { + logger211.throwArgumentError("invalid component count for transaction type: 1", "payload", hexlify(payload)); + } + const tx = { + type: 1, + chainId: handleNumber(transaction[0]).toNumber(), + nonce: handleNumber(transaction[1]).toNumber(), + gasPrice: handleNumber(transaction[2]), + gasLimit: handleNumber(transaction[3]), + to: handleAddress(transaction[4]), + value: handleNumber(transaction[5]), + data: transaction[6], + accessList: accessListify(transaction[7]) + }; + if (transaction.length === 8) { + return tx; + } + tx.hash = keccak256(payload); + _parseEipSignature(tx, transaction.slice(8), _serializeEip2930); + return tx; +} +function _parse(rawTransaction) { + const transaction = decode1(rawTransaction); + if (transaction.length !== 9 && transaction.length !== 6) { + logger211.throwArgumentError("invalid raw transaction", "rawTransaction", rawTransaction); + } + const tx = { + nonce: handleNumber(transaction[0]).toNumber(), + gasPrice: handleNumber(transaction[1]), + gasLimit: handleNumber(transaction[2]), + to: handleAddress(transaction[3]), + value: handleNumber(transaction[4]), + data: transaction[5], + chainId: 0 + }; + if (transaction.length === 6) { + return tx; + } + try { + tx.v = BigNumber.from(transaction[6]).toNumber(); + } catch (error) { + return tx; + } + tx.r = hexZeroPad(transaction[7], 32); + tx.s = hexZeroPad(transaction[8], 32); + if (BigNumber.from(tx.r).isZero() && BigNumber.from(tx.s).isZero()) { + tx.chainId = tx.v; + tx.v = 0; } else { - encoders[tokens.type.major](buf2, tokens, options); + tx.chainId = Math.floor((tx.v - 35) / 2); + if (tx.chainId < 0) { + tx.chainId = 0; + } + let recoveryParam = tx.v - 27; + const raw = transaction.slice(0, 6); + if (tx.chainId !== 0) { + raw.push(hexlify(tx.chainId)); + raw.push("0x"); + raw.push("0x"); + recoveryParam -= tx.chainId * 2 + 8; + } + const digest = keccak256(encode(raw)); + try { + tx.from = recoverAddress(digest, { + r: hexlify(tx.r), + s: hexlify(tx.s), + recoveryParam + }); + } catch (error) {} + tx.hash = keccak256(rawTransaction); + } + tx.type = null; + return tx; +} +function parse(rawTransaction) { + const payload = arrayify(rawTransaction); + if (payload[0] > 127) { + return _parse(payload); + } + switch(payload[0]){ + case 1: + return _parseEip2930(payload); + case 2: + return _parseEip1559(payload); + } + return logger211.throwError(`unsupported transaction type: ${payload[0]}`, Logger.errors.UNSUPPORTED_OPERATION, { + operation: "parseTransaction", + transactionType: payload[0] + }); +} +const version14 = "contracts/5.7.0"; +var __awaiter4 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger212 = new Logger(version14); +const allowedTransactionKeys2 = { + chainId: true, + data: true, + from: true, + gasLimit: true, + gasPrice: true, + nonce: true, + to: true, + value: true, + type: true, + accessList: true, + maxFeePerGas: true, + maxPriorityFeePerGas: true, + customData: true, + ccipReadEnabled: true +}; +function resolveName(resolver, nameOrPromise) { + return __awaiter4(this, void 0, void 0, function*() { + const name = yield nameOrPromise; + if (typeof name !== "string") { + logger212.throwArgumentError("invalid address or ENS name", "name", name); + } + try { + return getAddress(name); + } catch (error) {} + if (!resolver) { + logger212.throwError("a provider or signer is needed to resolve ENS names", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "resolveName" + }); + } + const address2 = yield resolver.resolveName(name); + if (address2 == null) { + logger212.throwArgumentError("resolver or addr is not configured for ENS name", "name", name); + } + return address2; + }); } -function encodeCustom(data, encoders, options) { - const tokens = objectToTokens(data, options); - if (!Array.isArray(tokens) && options.quickEncodeToken) { - const quickBytes = options.quickEncodeToken(tokens); - if (quickBytes) { - return quickBytes; +function resolveAddresses(resolver, value, paramType) { + return __awaiter4(this, void 0, void 0, function*() { + if (Array.isArray(paramType)) { + return yield Promise.all(paramType.map((paramType2, index)=>{ + return resolveAddresses(resolver, Array.isArray(value) ? value[index] : value[paramType2.name], paramType2); + })); + } + if (paramType.type === "address") { + return yield resolveName(resolver, value); + } + if (paramType.type === "tuple") { + return yield resolveAddresses(resolver, value, paramType.components); + } + if (paramType.baseType === "array") { + if (!Array.isArray(value)) { + return Promise.reject(logger212.makeError("invalid value for array", Logger.errors.INVALID_ARGUMENT, { + argument: "value", + value + })); + } + return yield Promise.all(value.map((v)=>resolveAddresses(resolver, v, paramType.arrayChildren))); } - const encoder = encoders[tokens.type.major]; - if (encoder.encodedSize) { - const size = encoder.encodedSize(tokens, options); - const buf2 = new Bl(size); - encoder(buf2, tokens, options); - if (buf2.chunks.length !== 1) { - throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`); + return value; + }); +} +function populateTransaction(contract, fragment, args) { + return __awaiter4(this, void 0, void 0, function*() { + let overrides = {}; + if (args.length === fragment.inputs.length + 1 && typeof args[args.length - 1] === "object") { + overrides = shallowCopy(args.pop()); + } + logger212.checkArgumentCount(args.length, fragment.inputs.length, "passed to contract"); + if (contract.signer) { + if (overrides.from) { + overrides.from = resolveProperties({ + override: resolveName(contract.signer, overrides.from), + signer: contract.signer.getAddress() + }).then((check)=>__awaiter4(this, void 0, void 0, function*() { + if (getAddress(check.signer) !== check.override) { + logger212.throwError("Contract with a Signer cannot override from", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "overrides.from" + }); + } + return check.override; + })); + } else { + overrides.from = contract.signer.getAddress(); } - return asU8A(buf2.chunks[0]); + } else if (overrides.from) { + overrides.from = resolveName(contract.provider, overrides.from); + } + const resolved = yield resolveProperties({ + args: resolveAddresses(contract.signer || contract.provider, args, fragment.inputs), + address: contract.resolvedAddress, + overrides: resolveProperties(overrides) || {} + }); + const data = contract.interface.encodeFunctionData(fragment, resolved.args); + const tx = { + data, + to: resolved.address + }; + const ro = resolved.overrides; + if (ro.nonce != null) { + tx.nonce = BigNumber.from(ro.nonce).toNumber(); + } + if (ro.gasLimit != null) { + tx.gasLimit = BigNumber.from(ro.gasLimit); + } + if (ro.gasPrice != null) { + tx.gasPrice = BigNumber.from(ro.gasPrice); + } + if (ro.maxFeePerGas != null) { + tx.maxFeePerGas = BigNumber.from(ro.maxFeePerGas); + } + if (ro.maxPriorityFeePerGas != null) { + tx.maxPriorityFeePerGas = BigNumber.from(ro.maxPriorityFeePerGas); + } + if (ro.from != null) { + tx.from = ro.from; + } + if (ro.type != null) { + tx.type = ro.type; + } + if (ro.accessList != null) { + tx.accessList = accessListify(ro.accessList); + } + if (tx.gasLimit == null && fragment.gas != null) { + let intrinsic = 21e3; + const bytes2 = arrayify(data); + for(let i = 0; i < bytes2.length; i++){ + intrinsic += 4; + if (bytes2[i]) { + intrinsic += 64; + } + } + tx.gasLimit = BigNumber.from(fragment.gas).add(intrinsic); + } + if (ro.value) { + const roValue = BigNumber.from(ro.value); + if (!roValue.isZero() && !fragment.payable) { + logger212.throwError("non-payable method cannot override value", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "overrides.value", + value: overrides.value + }); + } + tx.value = roValue; + } + if (ro.customData) { + tx.customData = shallowCopy(ro.customData); + } + if (ro.ccipReadEnabled) { + tx.ccipReadEnabled = !!ro.ccipReadEnabled; + } + delete overrides.nonce; + delete overrides.gasLimit; + delete overrides.gasPrice; + delete overrides.from; + delete overrides.value; + delete overrides.type; + delete overrides.accessList; + delete overrides.maxFeePerGas; + delete overrides.maxPriorityFeePerGas; + delete overrides.customData; + delete overrides.ccipReadEnabled; + const leftovers = Object.keys(overrides).filter((key)=>overrides[key] != null); + if (leftovers.length) { + logger212.throwError(`cannot override ${leftovers.map((l)=>JSON.stringify(l)).join(",")}`, Logger.errors.UNSUPPORTED_OPERATION, { + operation: "overrides", + overrides: leftovers + }); } + return tx; + }); +} +function buildPopulate(contract, fragment) { + return function(...args) { + return populateTransaction(contract, fragment, args); + }; +} +function buildEstimate(contract, fragment) { + const signerOrProvider = contract.signer || contract.provider; + return function(...args) { + return __awaiter4(this, void 0, void 0, function*() { + if (!signerOrProvider) { + logger212.throwError("estimate require a provider or signer", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "estimateGas" + }); + } + const tx = yield populateTransaction(contract, fragment, args); + return yield signerOrProvider.estimateGas(tx); + }); + }; +} +function addContractWait(contract, tx) { + const wait = tx.wait.bind(tx); + tx.wait = (confirmations)=>{ + return wait(confirmations).then((receipt)=>{ + receipt.events = receipt.logs.map((log)=>{ + let event = deepCopy(log); + let parsed = null; + try { + parsed = contract.interface.parseLog(log); + } catch (e) {} + if (parsed) { + event.args = parsed.args; + event.decode = (data, topics)=>{ + return contract.interface.decodeEventLog(parsed.eventFragment, data, topics); + }; + event.event = parsed.name; + event.eventSignature = parsed.signature; + } + event.removeListener = ()=>{ + return contract.provider; + }; + event.getBlock = ()=>{ + return contract.provider.getBlock(receipt.blockHash); + }; + event.getTransaction = ()=>{ + return contract.provider.getTransaction(receipt.transactionHash); + }; + event.getTransactionReceipt = ()=>{ + return Promise.resolve(receipt); + }; + return event; + }); + return receipt; + }); + }; +} +function buildCall(contract, fragment, collapseSimple) { + const signerOrProvider = contract.signer || contract.provider; + return function(...args) { + return __awaiter4(this, void 0, void 0, function*() { + let blockTag = void 0; + if (args.length === fragment.inputs.length + 1 && typeof args[args.length - 1] === "object") { + const overrides = shallowCopy(args.pop()); + if (overrides.blockTag != null) { + blockTag = yield overrides.blockTag; + } + delete overrides.blockTag; + args.push(overrides); + } + if (contract.deployTransaction != null) { + yield contract._deployed(blockTag); + } + const tx = yield populateTransaction(contract, fragment, args); + const result = yield signerOrProvider.call(tx, blockTag); + try { + let value = contract.interface.decodeFunctionResult(fragment, result); + if (collapseSimple && fragment.outputs.length === 1) { + value = value[0]; + } + return value; + } catch (error) { + if (error.code === Logger.errors.CALL_EXCEPTION) { + error.address = contract.address; + error.args = args; + error.transaction = tx; + } + throw error; + } + }); + }; +} +function buildSend(contract, fragment) { + return function(...args) { + return __awaiter4(this, void 0, void 0, function*() { + if (!contract.signer) { + logger212.throwError("sending a transaction requires a signer", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "sendTransaction" + }); + } + if (contract.deployTransaction != null) { + yield contract._deployed(); + } + const txRequest = yield populateTransaction(contract, fragment, args); + const tx = yield contract.signer.sendTransaction(txRequest); + addContractWait(contract, tx); + return tx; + }); + }; +} +function buildDefault(contract, fragment, collapseSimple) { + if (fragment.constant) { + return buildCall(contract, fragment, collapseSimple); } - buf.reset(); - tokensToEncoded(buf, tokens, encoders, options); - return buf.toBytes(true); + return buildSend(contract, fragment); } -function encode(data, options) { - options = Object.assign({}, defaultEncodeOptions, options); - return encodeCustom(data, cborEncoders, options); +function getEventTag(filter) { + if (filter.address && (filter.topics == null || filter.topics.length === 0)) { + return "*"; + } + return (filter.address || "*") + "@" + (filter.topics ? filter.topics.map((topic)=>{ + if (Array.isArray(topic)) { + return topic.join("|"); + } + return topic; + }).join(":") : ""); } -const defaultDecodeOptions = { - strict: false, - allowIndefinite: true, - allowUndefined: true, - allowBigInt: true -}; -class Tokeniser { - constructor(data, options = {}){ - this._pos = 0; - this.data = data; - this.options = options; +class RunningEvent { + constructor(tag, filter){ + defineReadOnly(this, "tag", tag); + defineReadOnly(this, "filter", filter); + this._listeners = []; } - pos() { - return this._pos; + addListener(listener, once) { + this._listeners.push({ + listener, + once + }); + } + removeListener(listener) { + let done = false; + this._listeners = this._listeners.filter((item)=>{ + if (done || item.listener !== listener) { + return true; + } + done = true; + return false; + }); + } + removeAllListeners() { + this._listeners = []; + } + listeners() { + return this._listeners.map((i)=>i.listener); + } + listenerCount() { + return this._listeners.length; } - done() { - return this._pos >= this.data.length; + run(args) { + const listenerCount = this.listenerCount(); + this._listeners = this._listeners.filter((item)=>{ + const argsCopy = args.slice(); + setTimeout(()=>{ + item.listener.apply(this, argsCopy); + }, 0); + return !item.once; + }); + return listenerCount; } - next() { - const byt = this.data[this._pos]; - let token = quick[byt]; - if (token === void 0) { - const decoder = jump[byt]; - if (!decoder) { - throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, "0")})`); - } - const minor = byt & 31; - token = decoder(this.data, this._pos, minor, this.options); - } - this._pos += token.encodedLength; - return token; + prepareEvent(event) {} + getEmit(event) { + return [ + event + ]; } } -const DONE = Symbol.for("DONE"); -const BREAK = Symbol.for("BREAK"); -function tokenToArray(token, tokeniser, options) { - const arr = []; - for(let i = 0; i < token.value; i++){ - const value = tokensToObject(tokeniser, options); - if (value === BREAK) { - if (token.value === Infinity) { - break; +class ErrorRunningEvent extends RunningEvent { + constructor(){ + super("error", null); + } +} +class FragmentRunningEvent extends RunningEvent { + constructor(address2, contractInterface, fragment, topics){ + const filter = { + address: address2 + }; + let topic = contractInterface.getEventTopic(fragment); + if (topics) { + if (topic !== topics[0]) { + logger212.throwArgumentError("topic mismatch", "topics", topics); } - throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`); + filter.topics = topics.slice(); + } else { + filter.topics = [ + topic + ]; } - if (value === DONE) { - throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`); + super(getEventTag(filter), filter); + defineReadOnly(this, "address", address2); + defineReadOnly(this, "interface", contractInterface); + defineReadOnly(this, "fragment", fragment); + } + prepareEvent(event) { + super.prepareEvent(event); + event.event = this.fragment.name; + event.eventSignature = this.fragment.format(); + event.decode = (data, topics)=>{ + return this.interface.decodeEventLog(this.fragment, data, topics); + }; + try { + event.args = this.interface.decodeEventLog(this.fragment, event.data, event.topics); + } catch (error) { + event.args = null; + event.decodeError = error; } - arr[i] = value; } - return arr; + getEmit(event) { + const errors = checkResultErrors(event.args); + if (errors.length) { + throw errors[0].error; + } + const args = (event.args || []).slice(); + args.push(event); + return args; + } } -function tokenToMap(token, tokeniser, options) { - const useMaps = options.useMaps === true; - const obj = useMaps ? void 0 : {}; - const m = useMaps ? new Map() : void 0; - for(let i = 0; i < token.value; i++){ - const key = tokensToObject(tokeniser, options); - if (key === BREAK) { - if (token.value === Infinity) { - break; - } - throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`); +class WildcardRunningEvent extends RunningEvent { + constructor(address2, contractInterface){ + super("*", { + address: address2 + }); + defineReadOnly(this, "address", address2); + defineReadOnly(this, "interface", contractInterface); + } + prepareEvent(event) { + super.prepareEvent(event); + try { + const parsed = this.interface.parseLog(event); + event.event = parsed.name; + event.eventSignature = parsed.signature; + event.decode = (data, topics)=>{ + return this.interface.decodeEventLog(parsed.eventFragment, data, topics); + }; + event.args = parsed.args; + } catch (error) {} + } +} +class BaseContract { + constructor(addressOrName, contractInterface, signerOrProvider){ + defineReadOnly(this, "interface", getStatic(new.target, "getInterface")(contractInterface)); + if (signerOrProvider == null) { + defineReadOnly(this, "provider", null); + defineReadOnly(this, "signer", null); + } else if (Signer.isSigner(signerOrProvider)) { + defineReadOnly(this, "provider", signerOrProvider.provider || null); + defineReadOnly(this, "signer", signerOrProvider); + } else if (Provider.isProvider(signerOrProvider)) { + defineReadOnly(this, "provider", signerOrProvider); + defineReadOnly(this, "signer", null); + } else { + logger212.throwArgumentError("invalid signer or provider", "signerOrProvider", signerOrProvider); } - if (key === DONE) { - throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`); + defineReadOnly(this, "callStatic", {}); + defineReadOnly(this, "estimateGas", {}); + defineReadOnly(this, "functions", {}); + defineReadOnly(this, "populateTransaction", {}); + defineReadOnly(this, "filters", {}); + { + const uniqueFilters = {}; + Object.keys(this.interface.events).forEach((eventSignature)=>{ + const event = this.interface.events[eventSignature]; + defineReadOnly(this.filters, eventSignature, (...args)=>{ + return { + address: this.address, + topics: this.interface.encodeFilterTopics(event, args) + }; + }); + if (!uniqueFilters[event.name]) { + uniqueFilters[event.name] = []; + } + uniqueFilters[event.name].push(eventSignature); + }); + Object.keys(uniqueFilters).forEach((name)=>{ + const filters = uniqueFilters[name]; + if (filters.length === 1) { + defineReadOnly(this.filters, name, this.filters[filters[0]]); + } else { + logger212.warn(`Duplicate definition of ${name} (${filters.join(", ")})`); + } + }); } - if (useMaps !== true && typeof key !== "string") { - throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`); + defineReadOnly(this, "_runningEvents", {}); + defineReadOnly(this, "_wrappedEmits", {}); + if (addressOrName == null) { + logger212.throwArgumentError("invalid contract address or ENS name", "addressOrName", addressOrName); } - if (options.rejectDuplicateMapKeys === true) { - if (useMaps && m.has(key) || !useMaps && key in obj) { - throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`); + defineReadOnly(this, "address", addressOrName); + if (this.provider) { + defineReadOnly(this, "resolvedAddress", resolveName(this.provider, addressOrName)); + } else { + try { + defineReadOnly(this, "resolvedAddress", Promise.resolve(getAddress(addressOrName))); + } catch (error) { + logger212.throwError("provider is required to use ENS name as contract address", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "new Contract" + }); } } - const value = tokensToObject(tokeniser, options); - if (value === DONE) { - throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`); + this.resolvedAddress.catch((e)=>{}); + const uniqueNames = {}; + const uniqueSignatures = {}; + Object.keys(this.interface.functions).forEach((signature)=>{ + const fragment = this.interface.functions[signature]; + if (uniqueSignatures[signature]) { + logger212.warn(`Duplicate ABI entry for ${JSON.stringify(signature)}`); + return; + } + uniqueSignatures[signature] = true; + { + const name = fragment.name; + if (!uniqueNames[`%${name}`]) { + uniqueNames[`%${name}`] = []; + } + uniqueNames[`%${name}`].push(signature); + } + if (this[signature] == null) { + defineReadOnly(this, signature, buildDefault(this, fragment, true)); + } + if (this.functions[signature] == null) { + defineReadOnly(this.functions, signature, buildDefault(this, fragment, false)); + } + if (this.callStatic[signature] == null) { + defineReadOnly(this.callStatic, signature, buildCall(this, fragment, true)); + } + if (this.populateTransaction[signature] == null) { + defineReadOnly(this.populateTransaction, signature, buildPopulate(this, fragment)); + } + if (this.estimateGas[signature] == null) { + defineReadOnly(this.estimateGas, signature, buildEstimate(this, fragment)); + } + }); + Object.keys(uniqueNames).forEach((name)=>{ + const signatures = uniqueNames[name]; + if (signatures.length > 1) { + return; + } + name = name.substring(1); + const signature = signatures[0]; + try { + if (this[name] == null) { + defineReadOnly(this, name, this[signature]); + } + } catch (e) {} + if (this.functions[name] == null) { + defineReadOnly(this.functions, name, this.functions[signature]); + } + if (this.callStatic[name] == null) { + defineReadOnly(this.callStatic, name, this.callStatic[signature]); + } + if (this.populateTransaction[name] == null) { + defineReadOnly(this.populateTransaction, name, this.populateTransaction[signature]); + } + if (this.estimateGas[name] == null) { + defineReadOnly(this.estimateGas, name, this.estimateGas[signature]); + } + }); + } + static getContractAddress(transaction) { + return getContractAddress(transaction); + } + static getInterface(contractInterface) { + if (Interface.isInterface(contractInterface)) { + return contractInterface; } - if (useMaps) { - m.set(key, value); - } else { - obj[key] = value; + return new Interface(contractInterface); + } + deployed() { + return this._deployed(); + } + _deployed(blockTag) { + if (!this._deployedPromise) { + if (this.deployTransaction) { + this._deployedPromise = this.deployTransaction.wait().then(()=>{ + return this; + }); + } else { + this._deployedPromise = this.provider.getCode(this.address, blockTag).then((code)=>{ + if (code === "0x") { + logger212.throwError("contract not deployed", Logger.errors.UNSUPPORTED_OPERATION, { + contractAddress: this.address, + operation: "getDeployed" + }); + } + return this; + }); + } } + return this._deployedPromise; } - return useMaps ? m : obj; -} -function tokensToObject(tokeniser, options) { - if (tokeniser.done()) { - return DONE; + fallback(overrides) { + if (!this.signer) { + logger212.throwError("sending a transactions require a signer", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "sendTransaction(fallback)" + }); + } + const tx = shallowCopy(overrides || {}); + [ + "from", + "to" + ].forEach(function(key) { + if (tx[key] == null) { + return; + } + logger212.throwError("cannot override " + key, Logger.errors.UNSUPPORTED_OPERATION, { + operation: key + }); + }); + tx.to = this.resolvedAddress; + return this.deployed().then(()=>{ + return this.signer.sendTransaction(tx); + }); } - const token = tokeniser.next(); - if (token.type === Type.break) { - return BREAK; + connect(signerOrProvider) { + if (typeof signerOrProvider === "string") { + signerOrProvider = new VoidSigner(signerOrProvider, this.provider); + } + const contract = new this.constructor(this.address, this.interface, signerOrProvider); + if (this.deployTransaction) { + defineReadOnly(contract, "deployTransaction", this.deployTransaction); + } + return contract; } - if (token.type.terminal) { - return token.value; + attach(addressOrName) { + return new this.constructor(addressOrName, this.interface, this.signer || this.provider); } - if (token.type === Type.array) { - return tokenToArray(token, tokeniser, options); + static isIndexed(value) { + return Indexed.isIndexed(value); } - if (token.type === Type.map) { - return tokenToMap(token, tokeniser, options); + _normalizeRunningEvent(runningEvent) { + if (this._runningEvents[runningEvent.tag]) { + return this._runningEvents[runningEvent.tag]; + } + return runningEvent; } - if (token.type === Type.tag) { - if (options.tags && typeof options.tags[token.value] === "function") { - const tagged = tokensToObject(tokeniser, options); - return options.tags[token.value](tagged); + _getRunningEvent(eventName) { + if (typeof eventName === "string") { + if (eventName === "error") { + return this._normalizeRunningEvent(new ErrorRunningEvent()); + } + if (eventName === "event") { + return this._normalizeRunningEvent(new RunningEvent("event", null)); + } + if (eventName === "*") { + return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface)); + } + const fragment = this.interface.getEvent(eventName); + return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment)); } - throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`); + if (eventName.topics && eventName.topics.length > 0) { + try { + const topic = eventName.topics[0]; + if (typeof topic !== "string") { + throw new Error("invalid topic"); + } + const fragment = this.interface.getEvent(topic); + return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment, eventName.topics)); + } catch (error) {} + const filter = { + address: this.address, + topics: eventName.topics + }; + return this._normalizeRunningEvent(new RunningEvent(getEventTag(filter), filter)); + } + return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface)); } - throw new Error("unsupported"); -} -function decodeFirst(data, options) { - if (!(data instanceof Uint8Array)) { - throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`); + _checkRunningEvents(runningEvent) { + if (runningEvent.listenerCount() === 0) { + delete this._runningEvents[runningEvent.tag]; + const emit = this._wrappedEmits[runningEvent.tag]; + if (emit && runningEvent.filter) { + this.provider.off(runningEvent.filter, emit); + delete this._wrappedEmits[runningEvent.tag]; + } + } } - options = Object.assign({}, defaultDecodeOptions, options); - const tokeniser = options.tokenizer || new Tokeniser(data, options); - const decoded = tokensToObject(tokeniser, options); - if (decoded === DONE) { - throw new Error(`${decodeErrPrefix} did not find any content to decode`); + _wrapEvent(runningEvent, log, listener) { + const event = deepCopy(log); + event.removeListener = ()=>{ + if (!listener) { + return; + } + runningEvent.removeListener(listener); + this._checkRunningEvents(runningEvent); + }; + event.getBlock = ()=>{ + return this.provider.getBlock(log.blockHash); + }; + event.getTransaction = ()=>{ + return this.provider.getTransaction(log.transactionHash); + }; + event.getTransactionReceipt = ()=>{ + return this.provider.getTransactionReceipt(log.transactionHash); + }; + runningEvent.prepareEvent(event); + return event; } - if (decoded === BREAK) { - throw new Error(`${decodeErrPrefix} got unexpected break`); + _addEventListener(runningEvent, listener, once) { + if (!this.provider) { + logger212.throwError("events require a provider or a signer with a provider", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "once" + }); + } + runningEvent.addListener(listener, once); + this._runningEvents[runningEvent.tag] = runningEvent; + if (!this._wrappedEmits[runningEvent.tag]) { + const wrappedEmit = (log)=>{ + let event = this._wrapEvent(runningEvent, log, listener); + if (event.decodeError == null) { + try { + const args = runningEvent.getEmit(event); + this.emit(runningEvent.filter, ...args); + } catch (error) { + event.decodeError = error.error; + } + } + if (runningEvent.filter != null) { + this.emit("event", event); + } + if (event.decodeError != null) { + this.emit("error", event.decodeError, event); + } + }; + this._wrappedEmits[runningEvent.tag] = wrappedEmit; + if (runningEvent.filter != null) { + this.provider.on(runningEvent.filter, wrappedEmit); + } + } } - return [ - decoded, - data.subarray(tokeniser.pos()) - ]; -} -function decode1(data, options) { - const [decoded, remainder] = decodeFirst(data, options); - if (remainder.length > 0) { - throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`); + queryFilter(event, fromBlockOrBlockhash, toBlock) { + const runningEvent = this._getRunningEvent(event); + const filter = shallowCopy(runningEvent.filter); + if (typeof fromBlockOrBlockhash === "string" && isHexString(fromBlockOrBlockhash, 32)) { + if (toBlock != null) { + logger212.throwArgumentError("cannot specify toBlock with blockhash", "toBlock", toBlock); + } + filter.blockHash = fromBlockOrBlockhash; + } else { + filter.fromBlock = fromBlockOrBlockhash != null ? fromBlockOrBlockhash : 0; + filter.toBlock = toBlock != null ? toBlock : "latest"; + } + return this.provider.getLogs(filter).then((logs)=>{ + return logs.map((log)=>this._wrapEvent(runningEvent, log, null)); + }); } - return decoded; -} -const empty = new Uint8Array(0); -function toHex(d) { - return d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); -} -function fromHex(hex) { - const hexes = hex.match(/../g); - return hexes != null ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty; -} -function equals(aa, bb) { - if (aa === bb) return true; - if (aa.byteLength !== bb.byteLength) { - return false; + on(event, listener) { + this._addEventListener(this._getRunningEvent(event), listener, false); + return this; } - for(let ii = 0; ii < aa.byteLength; ii++){ - if (aa[ii] !== bb[ii]) { + once(event, listener) { + this._addEventListener(this._getRunningEvent(event), listener, true); + return this; + } + emit(eventName, ...args) { + if (!this.provider) { return false; } + const runningEvent = this._getRunningEvent(eventName); + const result = runningEvent.run(args) > 0; + this._checkRunningEvents(runningEvent); + return result; } - return true; -} -function coerce(o) { - if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") return o; - if (o instanceof ArrayBuffer) return new Uint8Array(o); - if (ArrayBuffer.isView(o)) { - return new Uint8Array(o.buffer, o.byteOffset, o.byteLength); - } - throw new Error("Unknown type, must be binary type"); -} -function isBinary(o) { - return o instanceof ArrayBuffer || ArrayBuffer.isView(o); -} -function fromString1(str) { - return new TextEncoder().encode(str); -} -function toString1(b) { - return new TextDecoder().decode(b); -} -Object.freeze({ - __proto__: null, - empty, - toHex, - fromHex, - equals, - coerce, - isBinary, - fromString: fromString1, - toString: toString1 -}); -var __defProp = Object.defineProperty; -var __publicField = (obj, key, value)=>{ - if (typeof key !== "symbol") key += ""; - if (key in obj) return __defProp(obj, key, { - enumerable: true, - configurable: true, - writable: true, - value - }); - return obj[key] = value; -}; -function base(ALPHABET, name) { - if (ALPHABET.length >= 255) { - throw new TypeError("Alphabet too long"); + listenerCount(eventName) { + if (!this.provider) { + return 0; + } + if (eventName == null) { + return Object.keys(this._runningEvents).reduce((accum, key)=>{ + return accum + this._runningEvents[key].listenerCount(); + }, 0); + } + return this._getRunningEvent(eventName).listenerCount(); } - var BASE_MAP = new Uint8Array(256); - for(var j = 0; j < BASE_MAP.length; j++){ - BASE_MAP[j] = 255; + listeners(eventName) { + if (!this.provider) { + return []; + } + if (eventName == null) { + const result = []; + for(let tag in this._runningEvents){ + this._runningEvents[tag].listeners().forEach((listener)=>{ + result.push(listener); + }); + } + return result; + } + return this._getRunningEvent(eventName).listeners(); } - for(var i = 0; i < ALPHABET.length; i++){ - var x = ALPHABET.charAt(i); - var xc = x.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { - throw new TypeError(x + " is ambiguous"); + removeAllListeners(eventName) { + if (!this.provider) { + return this; } - BASE_MAP[xc] = i; + if (eventName == null) { + for(const tag in this._runningEvents){ + const runningEvent2 = this._runningEvents[tag]; + runningEvent2.removeAllListeners(); + this._checkRunningEvents(runningEvent2); + } + return this; + } + const runningEvent = this._getRunningEvent(eventName); + runningEvent.removeAllListeners(); + this._checkRunningEvents(runningEvent); + return this; } - var BASE = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE) / Math.log(256); - var iFACTOR = Math.log(256) / Math.log(BASE); - function encode2(source) { - if (source instanceof Uint8Array) ; - else if (ArrayBuffer.isView(source)) { - source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); - } else if (Array.isArray(source)) { - source = Uint8Array.from(source); + off(eventName, listener) { + if (!this.provider) { + return this; } - if (!(source instanceof Uint8Array)) { - throw new TypeError("Expected Uint8Array"); + const runningEvent = this._getRunningEvent(eventName); + runningEvent.removeListener(listener); + this._checkRunningEvents(runningEvent); + return this; + } + removeListener(eventName, listener) { + return this.off(eventName, listener); + } +} +class Contract extends BaseContract { +} +class ContractFactory { + constructor(contractInterface, bytecode, signer){ + let bytecodeHex = null; + if (typeof bytecode === "string") { + bytecodeHex = bytecode; + } else if (isBytes(bytecode)) { + bytecodeHex = hexlify(bytecode); + } else if (bytecode && typeof bytecode.object === "string") { + bytecodeHex = bytecode.object; + } else { + bytecodeHex = "!"; } - if (source.length === 0) { - return ""; + if (bytecodeHex.substring(0, 2) !== "0x") { + bytecodeHex = "0x" + bytecodeHex; } - var zeroes = 0; - var length = 0; - var pbegin = 0; - var pend = source.length; - while(pbegin !== pend && source[pbegin] === 0){ - pbegin++; - zeroes++; + if (!isHexString(bytecodeHex) || bytecodeHex.length % 2) { + logger212.throwArgumentError("invalid bytecode", "bytecode", bytecode); } - var size = (pend - pbegin) * iFACTOR + 1 >>> 0; - var b58 = new Uint8Array(size); - while(pbegin !== pend){ - var carry = source[pbegin]; - var i2 = 0; - for(var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++){ - carry += 256 * b58[it1] >>> 0; - b58[it1] = carry % BASE >>> 0; - carry = carry / BASE >>> 0; + if (signer && !Signer.isSigner(signer)) { + logger212.throwArgumentError("invalid signer", "signer", signer); + } + defineReadOnly(this, "bytecode", bytecodeHex); + defineReadOnly(this, "interface", getStatic(new.target, "getInterface")(contractInterface)); + defineReadOnly(this, "signer", signer || null); + } + getDeployTransaction(...args) { + let tx = {}; + if (args.length === this.interface.deploy.inputs.length + 1 && typeof args[args.length - 1] === "object") { + tx = shallowCopy(args.pop()); + for(const key in tx){ + if (!allowedTransactionKeys2[key]) { + throw new Error("unknown transaction override " + key); + } } - if (carry !== 0) { - throw new Error("Non-zero carry"); + } + [ + "data", + "from", + "to" + ].forEach((key)=>{ + if (tx[key] == null) { + return; + } + logger212.throwError("cannot override " + key, Logger.errors.UNSUPPORTED_OPERATION, { + operation: key + }); + }); + if (tx.value) { + const value = BigNumber.from(tx.value); + if (!value.isZero() && !this.interface.deploy.payable) { + logger212.throwError("non-payable constructor cannot override value", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "overrides.value", + value: tx.value + }); } - length = i2; - pbegin++; } - var it2 = size - length; - while(it2 !== size && b58[it2] === 0){ - it2++; + logger212.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor"); + tx.data = hexlify(concat([ + this.bytecode, + this.interface.encodeDeploy(args) + ])); + return tx; + } + deploy(...args) { + return __awaiter4(this, void 0, void 0, function*() { + let overrides = {}; + if (args.length === this.interface.deploy.inputs.length + 1) { + overrides = args.pop(); + } + logger212.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor"); + const params = yield resolveAddresses(this.signer, args, this.interface.deploy.inputs); + params.push(overrides); + const unsignedTx = this.getDeployTransaction(...params); + const tx = yield this.signer.sendTransaction(unsignedTx); + const address2 = getStatic(this.constructor, "getContractAddress")(tx); + const contract = getStatic(this.constructor, "getContract")(address2, this.interface, this.signer); + addContractWait(contract, tx); + defineReadOnly(contract, "deployTransaction", tx); + return contract; + }); + } + attach(address2) { + return this.constructor.getContract(address2, this.interface, this.signer); + } + connect(signer) { + return new this.constructor(this.interface, this.bytecode, signer); + } + static fromSolidity(compilerOutput, signer) { + if (compilerOutput == null) { + logger212.throwError("missing compiler output", Logger.errors.MISSING_ARGUMENT, { + argument: "compilerOutput" + }); } - var str = LEADER.repeat(zeroes); - for(; it2 < size; ++it2){ - str += ALPHABET.charAt(b58[it2]); + if (typeof compilerOutput === "string") { + compilerOutput = JSON.parse(compilerOutput); } - return str; + const abi2 = compilerOutput.abi; + let bytecode = null; + if (compilerOutput.bytecode) { + bytecode = compilerOutput.bytecode; + } else if (compilerOutput.evm && compilerOutput.evm.bytecode) { + bytecode = compilerOutput.evm.bytecode; + } + return new this(abi2, bytecode, signer); } - function decodeUnsafe(source) { - if (typeof source !== "string") { - throw new TypeError("Expected String"); + static getInterface(contractInterface) { + return Contract.getInterface(contractInterface); + } + static getContractAddress(tx) { + return getContractAddress(tx); + } + static getContract(address2, contractInterface, signer) { + return new Contract(address2, contractInterface, signer); + } +} +class BaseX { + constructor(alphabet){ + defineReadOnly(this, "alphabet", alphabet); + defineReadOnly(this, "base", alphabet.length); + defineReadOnly(this, "_alphabetMap", {}); + defineReadOnly(this, "_leader", alphabet.charAt(0)); + for(let i = 0; i < alphabet.length; i++){ + this._alphabetMap[alphabet.charAt(i)] = i; } + } + encode(value) { + let source = arrayify(value); if (source.length === 0) { - return new Uint8Array(); + return ""; } - var psz = 0; - if (source[psz] === " ") { - return; + let digits = [ + 0 + ]; + for(let i = 0; i < source.length; ++i){ + let carry = source[i]; + for(let j = 0; j < digits.length; ++j){ + carry += digits[j] << 8; + digits[j] = carry % this.base; + carry = carry / this.base | 0; + } + while(carry > 0){ + digits.push(carry % this.base); + carry = carry / this.base | 0; + } } - var zeroes = 0; - var length = 0; - while(source[psz] === LEADER){ - zeroes++; - psz++; + let string = ""; + for(let k = 0; source[k] === 0 && k < source.length - 1; ++k){ + string += this._leader; } - var size = (source.length - psz) * FACTOR + 1 >>> 0; - var b256 = new Uint8Array(size); - while(source[psz]){ - var carry = BASE_MAP[source.charCodeAt(psz)]; - if (carry === 255) { - return; + for(let q = digits.length - 1; q >= 0; --q){ + string += this.alphabet[digits[q]]; + } + return string; + } + decode(value) { + if (typeof value !== "string") { + throw new TypeError("Expected String"); + } + let bytes2 = []; + if (value.length === 0) { + return new Uint8Array(bytes2); + } + bytes2.push(0); + for(let i = 0; i < value.length; i++){ + let __byte = this._alphabetMap[value[i]]; + if (__byte === void 0) { + throw new Error("Non-base" + this.base + " character"); } - var i2 = 0; - for(var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++){ - carry += BASE * b256[it3] >>> 0; - b256[it3] = carry % 256 >>> 0; - carry = carry / 256 >>> 0; + let carry = __byte; + for(let j = 0; j < bytes2.length; ++j){ + carry += bytes2[j] * this.base; + bytes2[j] = carry & 255; + carry >>= 8; } - if (carry !== 0) { - throw new Error("Non-zero carry"); + while(carry > 0){ + bytes2.push(carry & 255); + carry >>= 8; } - length = i2; - psz++; } - if (source[psz] === " ") { - return; - } - var it4 = size - length; - while(it4 !== size && b256[it4] === 0){ - it4++; + for(let k = 0; value[k] === this._leader && k < value.length - 1; ++k){ + bytes2.push(0); } - var vch = new Uint8Array(zeroes + (size - it4)); - var j2 = zeroes; - while(it4 !== size){ - vch[j2++] = b256[it4++]; + return arrayify(new Uint8Array(bytes2.reverse())); + } +} +new BaseX("abcdefghijklmnopqrstuvwxyz234567"); +const Base58 = new BaseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); +var SupportedAlgorithm; +(function(SupportedAlgorithm2) { + SupportedAlgorithm2["sha256"] = "sha256"; + SupportedAlgorithm2["sha512"] = "sha512"; +})(SupportedAlgorithm || (SupportedAlgorithm = {})); +const version15 = "sha2/5.7.0"; +const logger213 = new Logger(version15); +function ripemd1601(data) { + return "0x" + hash_1.ripemd160().update(arrayify(data)).digest("hex"); +} +function sha2561(data) { + return "0x" + hash_1.sha256().update(arrayify(data)).digest("hex"); +} +function sha5121(data) { + return "0x" + hash_1.sha512().update(arrayify(data)).digest("hex"); +} +function computeHmac(algorithm, key, data) { + if (!SupportedAlgorithm[algorithm]) { + logger213.throwError("unsupported algorithm " + algorithm, Logger.errors.UNSUPPORTED_OPERATION, { + operation: "hmac", + algorithm + }); + } + return "0x" + hash_1.hmac(hash_1[algorithm], arrayify(key)).update(arrayify(data)).digest("hex"); +} +function pbkdf2(password, salt, iterations, keylen, hashAlgorithm) { + password = arrayify(password); + salt = arrayify(salt); + let hLen; + let l = 1; + const DK = new Uint8Array(keylen); + const block1 = new Uint8Array(salt.length + 4); + block1.set(salt); + let r; + let T; + for(let i = 1; i <= l; i++){ + block1[salt.length] = i >> 24 & 255; + block1[salt.length + 1] = i >> 16 & 255; + block1[salt.length + 2] = i >> 8 & 255; + block1[salt.length + 3] = i & 255; + let U = arrayify(computeHmac(hashAlgorithm, password, block1)); + if (!hLen) { + hLen = U.length; + T = new Uint8Array(hLen); + l = Math.ceil(keylen / hLen); + r = keylen - (l - 1) * hLen; + } + T.set(U); + for(let j = 1; j < iterations; j++){ + U = arrayify(computeHmac(hashAlgorithm, password, U)); + for(let k = 0; k < hLen; k++)T[k] ^= U[k]; + } + const destPos = (i - 1) * hLen; + const len = i === l ? r : hLen; + DK.set(arrayify(T).slice(0, len), destPos); + } + return hexlify(DK); +} +const version16 = "wordlists/5.7.0"; +const logger214 = new Logger(version16); +class Wordlist { + constructor(locale){ + logger214.checkAbstract(new.target, Wordlist); + defineReadOnly(this, "locale", locale); + } + split(mnemonic) { + return mnemonic.toLowerCase().split(/ +/g); + } + join(words2) { + return words2.join(" "); + } + static check(wordlist2) { + const words2 = []; + for(let i = 0; i < 2048; i++){ + const word = wordlist2.getWord(i); + if (i !== wordlist2.getWordIndex(word)) { + return "0x"; + } + words2.push(word); } - return vch; + return id(words2.join("\n") + "\n"); } - function decode2(string) { - var buffer = decodeUnsafe(string); - if (buffer) { - return buffer; + static register(lang, name) { + if (!name) { + name = lang.locale; } - throw new Error(`Non-${name} character`); } - return { - encode: encode2, - decodeUnsafe, - decode: decode2 - }; } -var src = base; -var _brrp__multiformats_scope_baseX = src; -class Encoder { - constructor(name, prefix, baseEncode){ - __publicField(this, "name"); - __publicField(this, "prefix"); - __publicField(this, "baseEncode"); - this.name = name; - this.prefix = prefix; - this.baseEncode = baseEncode; +const words = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo"; +let wordlist = null; +function loadWords(lang) { + if (wordlist != null) { + return; } - encode(bytes) { - if (bytes instanceof Uint8Array) { - return `${this.prefix}${this.baseEncode(bytes)}`; - } else { - throw Error("Unknown type, must be binary type"); - } + wordlist = words.replace(/([A-Z])/g, " $1").toLowerCase().substring(1).split(" "); + if (Wordlist.check(lang) !== "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60") { + wordlist = null; + throw new Error("BIP39 Wordlist for en (English) FAILED"); } } -class Decoder { - constructor(name, prefix, baseDecode){ - __publicField(this, "name"); - __publicField(this, "prefix"); - __publicField(this, "baseDecode"); - __publicField(this, "prefixCodePoint"); - this.name = name; - this.prefix = prefix; - if (prefix.codePointAt(0) === void 0) { - throw new Error("Invalid prefix character"); +class LangEn extends Wordlist { + constructor(){ + super("en"); + } + getWord(index) { + loadWords(this); + return wordlist[index]; + } + getWordIndex(word) { + loadWords(this); + return wordlist.indexOf(word); + } +} +const langEn = new LangEn(); +Wordlist.register(langEn); +const wordlists = { + en: langEn +}; +const version17 = "hdnode/5.7.0"; +const logger215 = new Logger(version17); +const N = BigNumber.from("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const MasterSecret = toUtf8Bytes("Bitcoin seed"); +const HardenedBit = 2147483648; +function getUpperMask(bits) { + return (1 << bits) - 1 << 8 - bits; +} +function getLowerMask(bits) { + return (1 << bits) - 1; +} +function bytes32(value) { + return hexZeroPad(hexlify(value), 32); +} +function base58check(data) { + return Base58.encode(concat([ + data, + hexDataSlice(sha2561(sha2561(data)), 0, 4) + ])); +} +function getWordlist(wordlist) { + if (wordlist == null) { + return wordlists["en"]; + } + if (typeof wordlist === "string") { + const words = wordlists[wordlist]; + if (words == null) { + logger215.throwArgumentError("unknown locale", "wordlist", wordlist); } - this.prefixCodePoint = prefix.codePointAt(0); - this.baseDecode = baseDecode; + return words; } - decode(text) { - if (typeof text === "string") { - if (text.codePointAt(0) !== this.prefixCodePoint) { - throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); + return wordlist; +} +const _constructorGuard2 = {}; +const defaultPath = "m/44'/60'/0'/0/0"; +class HDNode { + constructor(constructorGuard, privateKey, publicKey, parentFingerprint, chainCode, index, depth, mnemonicOrPath){ + if (constructorGuard !== _constructorGuard2) { + throw new Error("HDNode constructor cannot be called directly"); + } + if (privateKey) { + const signingKey = new SigningKey(privateKey); + defineReadOnly(this, "privateKey", signingKey.privateKey); + defineReadOnly(this, "publicKey", signingKey.compressedPublicKey); + } else { + defineReadOnly(this, "privateKey", null); + defineReadOnly(this, "publicKey", hexlify(publicKey)); + } + defineReadOnly(this, "parentFingerprint", parentFingerprint); + defineReadOnly(this, "fingerprint", hexDataSlice(ripemd1601(sha2561(this.publicKey)), 0, 4)); + defineReadOnly(this, "address", computeAddress(this.publicKey)); + defineReadOnly(this, "chainCode", chainCode); + defineReadOnly(this, "index", index); + defineReadOnly(this, "depth", depth); + if (mnemonicOrPath == null) { + defineReadOnly(this, "mnemonic", null); + defineReadOnly(this, "path", null); + } else if (typeof mnemonicOrPath === "string") { + defineReadOnly(this, "mnemonic", null); + defineReadOnly(this, "path", mnemonicOrPath); + } else { + defineReadOnly(this, "mnemonic", mnemonicOrPath); + defineReadOnly(this, "path", mnemonicOrPath.path); + } + } + get extendedKey() { + if (this.depth >= 256) { + throw new Error("Depth too large!"); + } + return base58check(concat([ + this.privateKey != null ? "0x0488ADE4" : "0x0488B21E", + hexlify(this.depth), + this.parentFingerprint, + hexZeroPad(hexlify(this.index), 4), + this.chainCode, + this.privateKey != null ? concat([ + "0x00", + this.privateKey + ]) : this.publicKey + ])); + } + neuter() { + return new HDNode(_constructorGuard2, null, this.publicKey, this.parentFingerprint, this.chainCode, this.index, this.depth, this.path); + } + _derive(index) { + if (index > 4294967295) { + throw new Error("invalid index - " + String(index)); + } + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + } + const data = new Uint8Array(37); + if (index & 2147483648) { + if (!this.privateKey) { + throw new Error("cannot derive child of neutered node"); + } + data.set(arrayify(this.privateKey), 1); + if (path) { + path += "'"; } - return this.baseDecode(text.slice(this.prefix.length)); } else { - throw Error("Can only multibase decode strings"); + data.set(arrayify(this.publicKey)); + } + for(let i = 24; i >= 0; i -= 8){ + data[33 + (i >> 3)] = index >> 24 - i & 255; + } + const I = arrayify(computeHmac(SupportedAlgorithm.sha512, this.chainCode, data)); + const IL = I.slice(0, 32); + const IR = I.slice(32); + let ki = null; + let Ki = null; + if (this.privateKey) { + ki = bytes32(BigNumber.from(IL).add(this.privateKey).mod(N)); + } else { + const ek = new SigningKey(hexlify(IL)); + Ki = ek._addPoint(this.publicKey); + } + let mnemonicOrPath = path; + const srcMnemonic = this.mnemonic; + if (srcMnemonic) { + mnemonicOrPath = Object.freeze({ + phrase: srcMnemonic.phrase, + path, + locale: srcMnemonic.locale || "en" + }); } + return new HDNode(_constructorGuard2, ki, Ki, this.fingerprint, bytes32(IR), index, this.depth + 1, mnemonicOrPath); } - or(decoder) { - return or(this, decoder); + derivePath(path) { + const components = path.split("/"); + if (components.length === 0 || components[0] === "m" && this.depth !== 0) { + throw new Error("invalid path - " + path); + } + if (components[0] === "m") { + components.shift(); + } + let result = this; + for(let i = 0; i < components.length; i++){ + const component = components[i]; + if (component.match(/^[0-9]+'$/)) { + const index = parseInt(component.substring(0, component.length - 1)); + if (index >= 2147483648) { + throw new Error("invalid path index - " + component); + } + result = result._derive(HardenedBit + index); + } else if (component.match(/^[0-9]+$/)) { + const index = parseInt(component); + if (index >= 2147483648) { + throw new Error("invalid path index - " + component); + } + result = result._derive(index); + } else { + throw new Error("invalid path component - " + component); + } + } + return result; } -} -class ComposedDecoder { - constructor(decoders){ - __publicField(this, "decoders"); - this.decoders = decoders; + static _fromSeed(seed, mnemonic) { + const seedArray = arrayify(seed); + if (seedArray.length < 16 || seedArray.length > 64) { + throw new Error("invalid seed"); + } + const I = arrayify(computeHmac(SupportedAlgorithm.sha512, MasterSecret, seedArray)); + return new HDNode(_constructorGuard2, bytes32(I.slice(0, 32)), null, "0x00000000", bytes32(I.slice(32)), 0, 0, mnemonic); } - or(decoder) { - return or(this, decoder); + static fromMnemonic(mnemonic, password, wordlist) { + wordlist = getWordlist(wordlist); + mnemonic = entropyToMnemonic(mnemonicToEntropy(mnemonic, wordlist), wordlist); + return HDNode._fromSeed(mnemonicToSeed(mnemonic, password), { + phrase: mnemonic, + path: "m", + locale: wordlist.locale + }); } - decode(input) { - const prefix = input[0]; - const decoder = this.decoders[prefix]; - if (decoder != null) { - return decoder.decode(input); - } else { - throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); + static fromSeed(seed) { + return HDNode._fromSeed(seed, null); + } + static fromExtendedKey(extendedKey) { + const bytes2 = Base58.decode(extendedKey); + if (bytes2.length !== 82 || base58check(bytes2.slice(0, 78)) !== extendedKey) { + logger215.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]"); + } + const depth = bytes2[4]; + const parentFingerprint = hexlify(bytes2.slice(5, 9)); + const index = parseInt(hexlify(bytes2.slice(9, 13)).substring(2), 16); + const chainCode = hexlify(bytes2.slice(13, 45)); + const key = bytes2.slice(45, 78); + switch(hexlify(bytes2.slice(0, 4))){ + case "0x0488b21e": + case "0x043587cf": + return new HDNode(_constructorGuard2, null, hexlify(key), parentFingerprint, chainCode, index, depth, null); + case "0x0488ade4": + case "0x04358394 ": + if (key[0] !== 0) { + break; + } + return new HDNode(_constructorGuard2, hexlify(key.slice(1)), null, parentFingerprint, chainCode, index, depth, null); } + return logger215.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]"); } -} -function or(left, right) { - var _a, _b; - return new ComposedDecoder({ - ...(_a = left.decoders) != null ? _a : { - [left.prefix]: left - }, - ...(_b = right.decoders) != null ? _b : { - [right.prefix]: right - } - }); -} -class Codec { - constructor(name, prefix, baseEncode, baseDecode){ - __publicField(this, "name"); - __publicField(this, "prefix"); - __publicField(this, "baseEncode"); - __publicField(this, "baseDecode"); - __publicField(this, "encoder"); - __publicField(this, "decoder"); - this.name = name; - this.prefix = prefix; - this.baseEncode = baseEncode; - this.baseDecode = baseDecode; - this.encoder = new Encoder(name, prefix, baseEncode); - this.decoder = new Decoder(name, prefix, baseDecode); +} +function mnemonicToSeed(mnemonic, password) { + if (!password) { + password = ""; } - encode(input) { - return this.encoder.encode(input); + const salt = toUtf8Bytes("mnemonic" + password, UnicodeNormalizationForm.NFKD); + return pbkdf2(toUtf8Bytes(mnemonic, UnicodeNormalizationForm.NFKD), salt, 2048, 64, "sha512"); +} +function mnemonicToEntropy(mnemonic, wordlist) { + wordlist = getWordlist(wordlist); + logger215.checkNormalize(); + const words = wordlist.split(mnemonic); + if (words.length % 3 !== 0) { + throw new Error("invalid mnemonic"); } - decode(input) { - return this.decoder.decode(input); + const entropy = arrayify(new Uint8Array(Math.ceil(11 * words.length / 8))); + let offset = 0; + for(let i = 0; i < words.length; i++){ + let index = wordlist.getWordIndex(words[i].normalize("NFKD")); + if (index === -1) { + throw new Error("invalid mnemonic"); + } + for(let bit = 0; bit < 11; bit++){ + if (index & 1 << 10 - bit) { + entropy[offset >> 3] |= 1 << 7 - offset % 8; + } + offset++; + } + } + const entropyBits = 32 * words.length / 3; + const checksumBits = words.length / 3; + const checksumMask = getUpperMask(checksumBits); + const checksum = arrayify(sha2561(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; + if (checksum !== (entropy[entropy.length - 1] & checksumMask)) { + throw new Error("invalid checksum"); } + return hexlify(entropy.slice(0, entropyBits / 8)); } -function from({ name, prefix, encode: encode2, decode: decode2 }) { - return new Codec(name, prefix, encode2, decode2); +function entropyToMnemonic(entropy, wordlist) { + wordlist = getWordlist(wordlist); + entropy = arrayify(entropy); + if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) { + throw new Error("invalid entropy"); + } + const indices = [ + 0 + ]; + let remainingBits = 11; + for(let i = 0; i < entropy.length; i++){ + if (remainingBits > 8) { + indices[indices.length - 1] <<= 8; + indices[indices.length - 1] |= entropy[i]; + remainingBits -= 8; + } else { + indices[indices.length - 1] <<= remainingBits; + indices[indices.length - 1] |= entropy[i] >> 8 - remainingBits; + indices.push(entropy[i] & getLowerMask(8 - remainingBits)); + remainingBits += 3; + } + } + const checksumBits = entropy.length / 4; + const checksum = arrayify(sha2561(entropy))[0] & getUpperMask(checksumBits); + indices[indices.length - 1] <<= checksumBits; + indices[indices.length - 1] |= checksum >> 8 - checksumBits; + return wordlist.join(indices.map((index)=>wordlist.getWord(index))); } -function baseX({ name, prefix, alphabet }) { - const { encode: encode2, decode: decode2 } = _brrp__multiformats_scope_baseX(alphabet, name); - return from({ - prefix, - name, - encode: encode2, - decode: (text)=>coerce(decode2(text)) - }); +function isValidMnemonic(mnemonic, wordlist) { + try { + mnemonicToEntropy(mnemonic, wordlist); + return true; + } catch (error) {} + return false; +} +function getAccountPath(index) { + if (typeof index !== "number" || index < 0 || index >= 2147483648 || index % 1) { + logger215.throwArgumentError("invalid account index", "index", index); + } + return `m/44'/60'/${index}'/0/0`; +} +var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; +const version18 = "random/5.7.0"; +const logger216 = new Logger(version18); +function getGlobal() { + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global$1 !== "undefined") { + return global$1; + } + throw new Error("unable to locate global object"); +} +const anyGlobal = getGlobal(); +let crypto1 = anyGlobal.crypto || anyGlobal.msCrypto; +if (!crypto1 || !crypto1.getRandomValues) { + logger216.warn("WARNING: Missing strong random number source"); + crypto1 = { + getRandomValues: function(buffer) { + return logger216.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "crypto.getRandomValues" + }); + } + }; } -function decode2(string, alphabet, bitsPerChar, name) { - const codes = {}; - for(let i = 0; i < alphabet.length; ++i){ - codes[alphabet[i]] = i; +function randomBytes(length) { + if (length <= 0 || length > 1024 || length % 1 || length != length) { + logger216.throwArgumentError("invalid length", "length", length); } - let end = string.length; - while(string[end - 1] === "="){ - --end; + const result = new Uint8Array(length); + crypto1.getRandomValues(result); + return arrayify(result); +} +function shuffled(array) { + array = array.slice(); + for(let i = array.length - 1; i > 0; i--){ + const j = Math.floor(Math.random() * (i + 1)); + const tmp = array[i]; + array[i] = array[j]; + array[j] = tmp; } - const out = new Uint8Array(end * bitsPerChar / 8 | 0); - let bits = 0; - let buffer = 0; - let written = 0; - for(let i = 0; i < end; ++i){ - const value = codes[string[i]]; - if (value === void 0) { - throw new SyntaxError(`Non-${name} character`); + return array; +} +function createCommonjsModule5(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function(path, base) { + return commonjsRequire5(path, base === void 0 || base === null ? module.path : base); + } + }, fn(module, module.exports), module.exports; +} +function commonjsRequire5() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); +} +var aesJs = createCommonjsModule5(function(module, exports) { + (function(root) { + function checkInt(value) { + return parseInt(value) === value; + } + function checkInts(arrayish) { + if (!checkInt(arrayish.length)) { + return false; + } + for(var i = 0; i < arrayish.length; i++){ + if (!checkInt(arrayish[i]) || arrayish[i] < 0 || arrayish[i] > 255) { + return false; + } + } + return true; + } + function coerceArray(arg, copy) { + if (arg.buffer && ArrayBuffer.isView(arg) && arg.name === "Uint8Array") { + if (copy) { + if (arg.slice) { + arg = arg.slice(); + } else { + arg = Array.prototype.slice.call(arg); + } + } + return arg; + } + if (Array.isArray(arg)) { + if (!checkInts(arg)) { + throw new Error("Array contains invalid value: " + arg); + } + return new Uint8Array(arg); + } + if (checkInt(arg.length) && checkInts(arg)) { + return new Uint8Array(arg); + } + throw new Error("unsupported array-like object"); + } + function createArray(length) { + return new Uint8Array(length); + } + function copyArray(sourceArray, targetArray, targetStart, sourceStart, sourceEnd) { + if (sourceStart != null || sourceEnd != null) { + if (sourceArray.slice) { + sourceArray = sourceArray.slice(sourceStart, sourceEnd); + } else { + sourceArray = Array.prototype.slice.call(sourceArray, sourceStart, sourceEnd); + } + } + targetArray.set(sourceArray, targetStart); + } + var convertUtf8 = function() { + function toBytes(text) { + var result = [], i = 0; + text = encodeURI(text); + while(i < text.length){ + var c = text.charCodeAt(i++); + if (c === 37) { + result.push(parseInt(text.substr(i, 2), 16)); + i += 2; + } else { + result.push(c); + } + } + return coerceArray(result); + } + function fromBytes(bytes) { + var result = [], i = 0; + while(i < bytes.length){ + var c = bytes[i]; + if (c < 128) { + result.push(String.fromCharCode(c)); + i++; + } else if (c > 191 && c < 224) { + result.push(String.fromCharCode((c & 31) << 6 | bytes[i + 1] & 63)); + i += 2; + } else { + result.push(String.fromCharCode((c & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63)); + i += 3; + } + } + return result.join(""); + } + return { + toBytes, + fromBytes + }; + }(); + var convertHex = function() { + function toBytes(text) { + var result = []; + for(var i = 0; i < text.length; i += 2){ + result.push(parseInt(text.substr(i, 2), 16)); + } + return result; + } + var Hex = "0123456789abcdef"; + function fromBytes(bytes) { + var result = []; + for(var i = 0; i < bytes.length; i++){ + var v = bytes[i]; + result.push(Hex[(v & 240) >> 4] + Hex[v & 15]); + } + return result.join(""); + } + return { + toBytes, + fromBytes + }; + }(); + var numberOfRounds = { + 16: 10, + 24: 12, + 32: 14 + }; + var rcon = [ + 1, + 2, + 4, + 8, + 16, + 32, + 64, + 128, + 27, + 54, + 108, + 216, + 171, + 77, + 154, + 47, + 94, + 188, + 99, + 198, + 151, + 53, + 106, + 212, + 179, + 125, + 250, + 239, + 197, + 145 + ]; + var S = [ + 99, + 124, + 119, + 123, + 242, + 107, + 111, + 197, + 48, + 1, + 103, + 43, + 254, + 215, + 171, + 118, + 202, + 130, + 201, + 125, + 250, + 89, + 71, + 240, + 173, + 212, + 162, + 175, + 156, + 164, + 114, + 192, + 183, + 253, + 147, + 38, + 54, + 63, + 247, + 204, + 52, + 165, + 229, + 241, + 113, + 216, + 49, + 21, + 4, + 199, + 35, + 195, + 24, + 150, + 5, + 154, + 7, + 18, + 128, + 226, + 235, + 39, + 178, + 117, + 9, + 131, + 44, + 26, + 27, + 110, + 90, + 160, + 82, + 59, + 214, + 179, + 41, + 227, + 47, + 132, + 83, + 209, + 0, + 237, + 32, + 252, + 177, + 91, + 106, + 203, + 190, + 57, + 74, + 76, + 88, + 207, + 208, + 239, + 170, + 251, + 67, + 77, + 51, + 133, + 69, + 249, + 2, + 127, + 80, + 60, + 159, + 168, + 81, + 163, + 64, + 143, + 146, + 157, + 56, + 245, + 188, + 182, + 218, + 33, + 16, + 255, + 243, + 210, + 205, + 12, + 19, + 236, + 95, + 151, + 68, + 23, + 196, + 167, + 126, + 61, + 100, + 93, + 25, + 115, + 96, + 129, + 79, + 220, + 34, + 42, + 144, + 136, + 70, + 238, + 184, + 20, + 222, + 94, + 11, + 219, + 224, + 50, + 58, + 10, + 73, + 6, + 36, + 92, + 194, + 211, + 172, + 98, + 145, + 149, + 228, + 121, + 231, + 200, + 55, + 109, + 141, + 213, + 78, + 169, + 108, + 86, + 244, + 234, + 101, + 122, + 174, + 8, + 186, + 120, + 37, + 46, + 28, + 166, + 180, + 198, + 232, + 221, + 116, + 31, + 75, + 189, + 139, + 138, + 112, + 62, + 181, + 102, + 72, + 3, + 246, + 14, + 97, + 53, + 87, + 185, + 134, + 193, + 29, + 158, + 225, + 248, + 152, + 17, + 105, + 217, + 142, + 148, + 155, + 30, + 135, + 233, + 206, + 85, + 40, + 223, + 140, + 161, + 137, + 13, + 191, + 230, + 66, + 104, + 65, + 153, + 45, + 15, + 176, + 84, + 187, + 22 + ]; + var Si = [ + 82, + 9, + 106, + 213, + 48, + 54, + 165, + 56, + 191, + 64, + 163, + 158, + 129, + 243, + 215, + 251, + 124, + 227, + 57, + 130, + 155, + 47, + 255, + 135, + 52, + 142, + 67, + 68, + 196, + 222, + 233, + 203, + 84, + 123, + 148, + 50, + 166, + 194, + 35, + 61, + 238, + 76, + 149, + 11, + 66, + 250, + 195, + 78, + 8, + 46, + 161, + 102, + 40, + 217, + 36, + 178, + 118, + 91, + 162, + 73, + 109, + 139, + 209, + 37, + 114, + 248, + 246, + 100, + 134, + 104, + 152, + 22, + 212, + 164, + 92, + 204, + 93, + 101, + 182, + 146, + 108, + 112, + 72, + 80, + 253, + 237, + 185, + 218, + 94, + 21, + 70, + 87, + 167, + 141, + 157, + 132, + 144, + 216, + 171, + 0, + 140, + 188, + 211, + 10, + 247, + 228, + 88, + 5, + 184, + 179, + 69, + 6, + 208, + 44, + 30, + 143, + 202, + 63, + 15, + 2, + 193, + 175, + 189, + 3, + 1, + 19, + 138, + 107, + 58, + 145, + 17, + 65, + 79, + 103, + 220, + 234, + 151, + 242, + 207, + 206, + 240, + 180, + 230, + 115, + 150, + 172, + 116, + 34, + 231, + 173, + 53, + 133, + 226, + 249, + 55, + 232, + 28, + 117, + 223, + 110, + 71, + 241, + 26, + 113, + 29, + 41, + 197, + 137, + 111, + 183, + 98, + 14, + 170, + 24, + 190, + 27, + 252, + 86, + 62, + 75, + 198, + 210, + 121, + 32, + 154, + 219, + 192, + 254, + 120, + 205, + 90, + 244, + 31, + 221, + 168, + 51, + 136, + 7, + 199, + 49, + 177, + 18, + 16, + 89, + 39, + 128, + 236, + 95, + 96, + 81, + 127, + 169, + 25, + 181, + 74, + 13, + 45, + 229, + 122, + 159, + 147, + 201, + 156, + 239, + 160, + 224, + 59, + 77, + 174, + 42, + 245, + 176, + 200, + 235, + 187, + 60, + 131, + 83, + 153, + 97, + 23, + 43, + 4, + 126, + 186, + 119, + 214, + 38, + 225, + 105, + 20, + 99, + 85, + 33, + 12, + 125 + ]; + var T1 = [ + 3328402341, + 4168907908, + 4000806809, + 4135287693, + 4294111757, + 3597364157, + 3731845041, + 2445657428, + 1613770832, + 33620227, + 3462883241, + 1445669757, + 3892248089, + 3050821474, + 1303096294, + 3967186586, + 2412431941, + 528646813, + 2311702848, + 4202528135, + 4026202645, + 2992200171, + 2387036105, + 4226871307, + 1101901292, + 3017069671, + 1604494077, + 1169141738, + 597466303, + 1403299063, + 3832705686, + 2613100635, + 1974974402, + 3791519004, + 1033081774, + 1277568618, + 1815492186, + 2118074177, + 4126668546, + 2211236943, + 1748251740, + 1369810420, + 3521504564, + 4193382664, + 3799085459, + 2883115123, + 1647391059, + 706024767, + 134480908, + 2512897874, + 1176707941, + 2646852446, + 806885416, + 932615841, + 168101135, + 798661301, + 235341577, + 605164086, + 461406363, + 3756188221, + 3454790438, + 1311188841, + 2142417613, + 3933566367, + 302582043, + 495158174, + 1479289972, + 874125870, + 907746093, + 3698224818, + 3025820398, + 1537253627, + 2756858614, + 1983593293, + 3084310113, + 2108928974, + 1378429307, + 3722699582, + 1580150641, + 327451799, + 2790478837, + 3117535592, + 0, + 3253595436, + 1075847264, + 3825007647, + 2041688520, + 3059440621, + 3563743934, + 2378943302, + 1740553945, + 1916352843, + 2487896798, + 2555137236, + 2958579944, + 2244988746, + 3151024235, + 3320835882, + 1336584933, + 3992714006, + 2252555205, + 2588757463, + 1714631509, + 293963156, + 2319795663, + 3925473552, + 67240454, + 4269768577, + 2689618160, + 2017213508, + 631218106, + 1269344483, + 2723238387, + 1571005438, + 2151694528, + 93294474, + 1066570413, + 563977660, + 1882732616, + 4059428100, + 1673313503, + 2008463041, + 2950355573, + 1109467491, + 537923632, + 3858759450, + 4260623118, + 3218264685, + 2177748300, + 403442708, + 638784309, + 3287084079, + 3193921505, + 899127202, + 2286175436, + 773265209, + 2479146071, + 1437050866, + 4236148354, + 2050833735, + 3362022572, + 3126681063, + 840505643, + 3866325909, + 3227541664, + 427917720, + 2655997905, + 2749160575, + 1143087718, + 1412049534, + 999329963, + 193497219, + 2353415882, + 3354324521, + 1807268051, + 672404540, + 2816401017, + 3160301282, + 369822493, + 2916866934, + 3688947771, + 1681011286, + 1949973070, + 336202270, + 2454276571, + 201721354, + 1210328172, + 3093060836, + 2680341085, + 3184776046, + 1135389935, + 3294782118, + 965841320, + 831886756, + 3554993207, + 4068047243, + 3588745010, + 2345191491, + 1849112409, + 3664604599, + 26054028, + 2983581028, + 2622377682, + 1235855840, + 3630984372, + 2891339514, + 4092916743, + 3488279077, + 3395642799, + 4101667470, + 1202630377, + 268961816, + 1874508501, + 4034427016, + 1243948399, + 1546530418, + 941366308, + 1470539505, + 1941222599, + 2546386513, + 3421038627, + 2715671932, + 3899946140, + 1042226977, + 2521517021, + 1639824860, + 227249030, + 260737669, + 3765465232, + 2084453954, + 1907733956, + 3429263018, + 2420656344, + 100860677, + 4160157185, + 470683154, + 3261161891, + 1781871967, + 2924959737, + 1773779408, + 394692241, + 2579611992, + 974986535, + 664706745, + 3655459128, + 3958962195, + 731420851, + 571543859, + 3530123707, + 2849626480, + 126783113, + 865375399, + 765172662, + 1008606754, + 361203602, + 3387549984, + 2278477385, + 2857719295, + 1344809080, + 2782912378, + 59542671, + 1503764984, + 160008576, + 437062935, + 1707065306, + 3622233649, + 2218934982, + 3496503480, + 2185314755, + 697932208, + 1512910199, + 504303377, + 2075177163, + 2824099068, + 1841019862, + 739644986 + ]; + var T2 = [ + 2781242211, + 2230877308, + 2582542199, + 2381740923, + 234877682, + 3184946027, + 2984144751, + 1418839493, + 1348481072, + 50462977, + 2848876391, + 2102799147, + 434634494, + 1656084439, + 3863849899, + 2599188086, + 1167051466, + 2636087938, + 1082771913, + 2281340285, + 368048890, + 3954334041, + 3381544775, + 201060592, + 3963727277, + 1739838676, + 4250903202, + 3930435503, + 3206782108, + 4149453988, + 2531553906, + 1536934080, + 3262494647, + 484572669, + 2923271059, + 1783375398, + 1517041206, + 1098792767, + 49674231, + 1334037708, + 1550332980, + 4098991525, + 886171109, + 150598129, + 2481090929, + 1940642008, + 1398944049, + 1059722517, + 201851908, + 1385547719, + 1699095331, + 1587397571, + 674240536, + 2704774806, + 252314885, + 3039795866, + 151914247, + 908333586, + 2602270848, + 1038082786, + 651029483, + 1766729511, + 3447698098, + 2682942837, + 454166793, + 2652734339, + 1951935532, + 775166490, + 758520603, + 3000790638, + 4004797018, + 4217086112, + 4137964114, + 1299594043, + 1639438038, + 3464344499, + 2068982057, + 1054729187, + 1901997871, + 2534638724, + 4121318227, + 1757008337, + 0, + 750906861, + 1614815264, + 535035132, + 3363418545, + 3988151131, + 3201591914, + 1183697867, + 3647454910, + 1265776953, + 3734260298, + 3566750796, + 3903871064, + 1250283471, + 1807470800, + 717615087, + 3847203498, + 384695291, + 3313910595, + 3617213773, + 1432761139, + 2484176261, + 3481945413, + 283769337, + 100925954, + 2180939647, + 4037038160, + 1148730428, + 3123027871, + 3813386408, + 4087501137, + 4267549603, + 3229630528, + 2315620239, + 2906624658, + 3156319645, + 1215313976, + 82966005, + 3747855548, + 3245848246, + 1974459098, + 1665278241, + 807407632, + 451280895, + 251524083, + 1841287890, + 1283575245, + 337120268, + 891687699, + 801369324, + 3787349855, + 2721421207, + 3431482436, + 959321879, + 1469301956, + 4065699751, + 2197585534, + 1199193405, + 2898814052, + 3887750493, + 724703513, + 2514908019, + 2696962144, + 2551808385, + 3516813135, + 2141445340, + 1715741218, + 2119445034, + 2872807568, + 2198571144, + 3398190662, + 700968686, + 3547052216, + 1009259540, + 2041044702, + 3803995742, + 487983883, + 1991105499, + 1004265696, + 1449407026, + 1316239930, + 504629770, + 3683797321, + 168560134, + 1816667172, + 3837287516, + 1570751170, + 1857934291, + 4014189740, + 2797888098, + 2822345105, + 2754712981, + 936633572, + 2347923833, + 852879335, + 1133234376, + 1500395319, + 3084545389, + 2348912013, + 1689376213, + 3533459022, + 3762923945, + 3034082412, + 4205598294, + 133428468, + 634383082, + 2949277029, + 2398386810, + 3913789102, + 403703816, + 3580869306, + 2297460856, + 1867130149, + 1918643758, + 607656988, + 4049053350, + 3346248884, + 1368901318, + 600565992, + 2090982877, + 2632479860, + 557719327, + 3717614411, + 3697393085, + 2249034635, + 2232388234, + 2430627952, + 1115438654, + 3295786421, + 2865522278, + 3633334344, + 84280067, + 33027830, + 303828494, + 2747425121, + 1600795957, + 4188952407, + 3496589753, + 2434238086, + 1486471617, + 658119965, + 3106381470, + 953803233, + 334231800, + 3005978776, + 857870609, + 3151128937, + 1890179545, + 2298973838, + 2805175444, + 3056442267, + 574365214, + 2450884487, + 550103529, + 1233637070, + 4289353045, + 2018519080, + 2057691103, + 2399374476, + 4166623649, + 2148108681, + 387583245, + 3664101311, + 836232934, + 3330556482, + 3100665960, + 3280093505, + 2955516313, + 2002398509, + 287182607, + 3413881008, + 4238890068, + 3597515707, + 975967766 + ]; + var T3 = [ + 1671808611, + 2089089148, + 2006576759, + 2072901243, + 4061003762, + 1807603307, + 1873927791, + 3310653893, + 810573872, + 16974337, + 1739181671, + 729634347, + 4263110654, + 3613570519, + 2883997099, + 1989864566, + 3393556426, + 2191335298, + 3376449993, + 2106063485, + 4195741690, + 1508618841, + 1204391495, + 4027317232, + 2917941677, + 3563566036, + 2734514082, + 2951366063, + 2629772188, + 2767672228, + 1922491506, + 3227229120, + 3082974647, + 4246528509, + 2477669779, + 644500518, + 911895606, + 1061256767, + 4144166391, + 3427763148, + 878471220, + 2784252325, + 3845444069, + 4043897329, + 1905517169, + 3631459288, + 827548209, + 356461077, + 67897348, + 3344078279, + 593839651, + 3277757891, + 405286936, + 2527147926, + 84871685, + 2595565466, + 118033927, + 305538066, + 2157648768, + 3795705826, + 3945188843, + 661212711, + 2999812018, + 1973414517, + 152769033, + 2208177539, + 745822252, + 439235610, + 455947803, + 1857215598, + 1525593178, + 2700827552, + 1391895634, + 994932283, + 3596728278, + 3016654259, + 695947817, + 3812548067, + 795958831, + 2224493444, + 1408607827, + 3513301457, + 0, + 3979133421, + 543178784, + 4229948412, + 2982705585, + 1542305371, + 1790891114, + 3410398667, + 3201918910, + 961245753, + 1256100938, + 1289001036, + 1491644504, + 3477767631, + 3496721360, + 4012557807, + 2867154858, + 4212583931, + 1137018435, + 1305975373, + 861234739, + 2241073541, + 1171229253, + 4178635257, + 33948674, + 2139225727, + 1357946960, + 1011120188, + 2679776671, + 2833468328, + 1374921297, + 2751356323, + 1086357568, + 2408187279, + 2460827538, + 2646352285, + 944271416, + 4110742005, + 3168756668, + 3066132406, + 3665145818, + 560153121, + 271589392, + 4279952895, + 4077846003, + 3530407890, + 3444343245, + 202643468, + 322250259, + 3962553324, + 1608629855, + 2543990167, + 1154254916, + 389623319, + 3294073796, + 2817676711, + 2122513534, + 1028094525, + 1689045092, + 1575467613, + 422261273, + 1939203699, + 1621147744, + 2174228865, + 1339137615, + 3699352540, + 577127458, + 712922154, + 2427141008, + 2290289544, + 1187679302, + 3995715566, + 3100863416, + 339486740, + 3732514782, + 1591917662, + 186455563, + 3681988059, + 3762019296, + 844522546, + 978220090, + 169743370, + 1239126601, + 101321734, + 611076132, + 1558493276, + 3260915650, + 3547250131, + 2901361580, + 1655096418, + 2443721105, + 2510565781, + 3828863972, + 2039214713, + 3878868455, + 3359869896, + 928607799, + 1840765549, + 2374762893, + 3580146133, + 1322425422, + 2850048425, + 1823791212, + 1459268694, + 4094161908, + 3928346602, + 1706019429, + 2056189050, + 2934523822, + 135794696, + 3134549946, + 2022240376, + 628050469, + 779246638, + 472135708, + 2800834470, + 3032970164, + 3327236038, + 3894660072, + 3715932637, + 1956440180, + 522272287, + 1272813131, + 3185336765, + 2340818315, + 2323976074, + 1888542832, + 1044544574, + 3049550261, + 1722469478, + 1222152264, + 50660867, + 4127324150, + 236067854, + 1638122081, + 895445557, + 1475980887, + 3117443513, + 2257655686, + 3243809217, + 489110045, + 2662934430, + 3778599393, + 4162055160, + 2561878936, + 288563729, + 1773916777, + 3648039385, + 2391345038, + 2493985684, + 2612407707, + 505560094, + 2274497927, + 3911240169, + 3460925390, + 1442818645, + 678973480, + 3749357023, + 2358182796, + 2717407649, + 2306869641, + 219617805, + 3218761151, + 3862026214, + 1120306242, + 1756942440, + 1103331905, + 2578459033, + 762796589, + 252780047, + 2966125488, + 1425844308, + 3151392187, + 372911126 + ]; + var T4 = [ + 1667474886, + 2088535288, + 2004326894, + 2071694838, + 4075949567, + 1802223062, + 1869591006, + 3318043793, + 808472672, + 16843522, + 1734846926, + 724270422, + 4278065639, + 3621216949, + 2880169549, + 1987484396, + 3402253711, + 2189597983, + 3385409673, + 2105378810, + 4210693615, + 1499065266, + 1195886990, + 4042263547, + 2913856577, + 3570689971, + 2728590687, + 2947541573, + 2627518243, + 2762274643, + 1920112356, + 3233831835, + 3082273397, + 4261223649, + 2475929149, + 640051788, + 909531756, + 1061110142, + 4160160501, + 3435941763, + 875846760, + 2779116625, + 3857003729, + 4059105529, + 1903268834, + 3638064043, + 825316194, + 353713962, + 67374088, + 3351728789, + 589522246, + 3284360861, + 404236336, + 2526454071, + 84217610, + 2593830191, + 117901582, + 303183396, + 2155911963, + 3806477791, + 3958056653, + 656894286, + 2998062463, + 1970642922, + 151591698, + 2206440989, + 741110872, + 437923380, + 454765878, + 1852748508, + 1515908788, + 2694904667, + 1381168804, + 993742198, + 3604373943, + 3014905469, + 690584402, + 3823320797, + 791638366, + 2223281939, + 1398011302, + 3520161977, + 0, + 3991743681, + 538992704, + 4244381667, + 2981218425, + 1532751286, + 1785380564, + 3419096717, + 3200178535, + 960056178, + 1246420628, + 1280103576, + 1482221744, + 3486468741, + 3503319995, + 4025428677, + 2863326543, + 4227536621, + 1128514950, + 1296947098, + 859002214, + 2240123921, + 1162203018, + 4193849577, + 33687044, + 2139062782, + 1347481760, + 1010582648, + 2678045221, + 2829640523, + 1364325282, + 2745433693, + 1077985408, + 2408548869, + 2459086143, + 2644360225, + 943212656, + 4126475505, + 3166494563, + 3065430391, + 3671750063, + 555836226, + 269496352, + 4294908645, + 4092792573, + 3537006015, + 3452783745, + 202118168, + 320025894, + 3974901699, + 1600119230, + 2543297077, + 1145359496, + 387397934, + 3301201811, + 2812801621, + 2122220284, + 1027426170, + 1684319432, + 1566435258, + 421079858, + 1936954854, + 1616945344, + 2172753945, + 1330631070, + 3705438115, + 572679748, + 707427924, + 2425400123, + 2290647819, + 1179044492, + 4008585671, + 3099120491, + 336870440, + 3739122087, + 1583276732, + 185277718, + 3688593069, + 3772791771, + 842159716, + 976899700, + 168435220, + 1229577106, + 101059084, + 606366792, + 1549591736, + 3267517855, + 3553849021, + 2897014595, + 1650632388, + 2442242105, + 2509612081, + 3840161747, + 2038008818, + 3890688725, + 3368567691, + 926374254, + 1835907034, + 2374863873, + 3587531953, + 1313788572, + 2846482505, + 1819063512, + 1448540844, + 4109633523, + 3941213647, + 1701162954, + 2054852340, + 2930698567, + 134748176, + 3132806511, + 2021165296, + 623210314, + 774795868, + 471606328, + 2795958615, + 3031746419, + 3334885783, + 3907527627, + 3722280097, + 1953799400, + 522133822, + 1263263126, + 3183336545, + 2341176845, + 2324333839, + 1886425312, + 1044267644, + 3048588401, + 1718004428, + 1212733584, + 50529542, + 4143317495, + 235803164, + 1633788866, + 892690282, + 1465383342, + 3115962473, + 2256965911, + 3250673817, + 488449850, + 2661202215, + 3789633753, + 4177007595, + 2560144171, + 286339874, + 1768537042, + 3654906025, + 2391705863, + 2492770099, + 2610673197, + 505291324, + 2273808917, + 3924369609, + 3469625735, + 1431699370, + 673740880, + 3755965093, + 2358021891, + 2711746649, + 2307489801, + 218961690, + 3217021541, + 3873845719, + 1111672452, + 1751693520, + 1094828930, + 2576986153, + 757954394, + 252645662, + 2964376443, + 1414855848, + 3149649517, + 370555436 + ]; + var T5 = [ + 1374988112, + 2118214995, + 437757123, + 975658646, + 1001089995, + 530400753, + 2902087851, + 1273168787, + 540080725, + 2910219766, + 2295101073, + 4110568485, + 1340463100, + 3307916247, + 641025152, + 3043140495, + 3736164937, + 632953703, + 1172967064, + 1576976609, + 3274667266, + 2169303058, + 2370213795, + 1809054150, + 59727847, + 361929877, + 3211623147, + 2505202138, + 3569255213, + 1484005843, + 1239443753, + 2395588676, + 1975683434, + 4102977912, + 2572697195, + 666464733, + 3202437046, + 4035489047, + 3374361702, + 2110667444, + 1675577880, + 3843699074, + 2538681184, + 1649639237, + 2976151520, + 3144396420, + 4269907996, + 4178062228, + 1883793496, + 2403728665, + 2497604743, + 1383856311, + 2876494627, + 1917518562, + 3810496343, + 1716890410, + 3001755655, + 800440835, + 2261089178, + 3543599269, + 807962610, + 599762354, + 33778362, + 3977675356, + 2328828971, + 2809771154, + 4077384432, + 1315562145, + 1708848333, + 101039829, + 3509871135, + 3299278474, + 875451293, + 2733856160, + 92987698, + 2767645557, + 193195065, + 1080094634, + 1584504582, + 3178106961, + 1042385657, + 2531067453, + 3711829422, + 1306967366, + 2438237621, + 1908694277, + 67556463, + 1615861247, + 429456164, + 3602770327, + 2302690252, + 1742315127, + 2968011453, + 126454664, + 3877198648, + 2043211483, + 2709260871, + 2084704233, + 4169408201, + 0, + 159417987, + 841739592, + 504459436, + 1817866830, + 4245618683, + 260388950, + 1034867998, + 908933415, + 168810852, + 1750902305, + 2606453969, + 607530554, + 202008497, + 2472011535, + 3035535058, + 463180190, + 2160117071, + 1641816226, + 1517767529, + 470948374, + 3801332234, + 3231722213, + 1008918595, + 303765277, + 235474187, + 4069246893, + 766945465, + 337553864, + 1475418501, + 2943682380, + 4003061179, + 2743034109, + 4144047775, + 1551037884, + 1147550661, + 1543208500, + 2336434550, + 3408119516, + 3069049960, + 3102011747, + 3610369226, + 1113818384, + 328671808, + 2227573024, + 2236228733, + 3535486456, + 2935566865, + 3341394285, + 496906059, + 3702665459, + 226906860, + 2009195472, + 733156972, + 2842737049, + 294930682, + 1206477858, + 2835123396, + 2700099354, + 1451044056, + 573804783, + 2269728455, + 3644379585, + 2362090238, + 2564033334, + 2801107407, + 2776292904, + 3669462566, + 1068351396, + 742039012, + 1350078989, + 1784663195, + 1417561698, + 4136440770, + 2430122216, + 775550814, + 2193862645, + 2673705150, + 1775276924, + 1876241833, + 3475313331, + 3366754619, + 270040487, + 3902563182, + 3678124923, + 3441850377, + 1851332852, + 3969562369, + 2203032232, + 3868552805, + 2868897406, + 566021896, + 4011190502, + 3135740889, + 1248802510, + 3936291284, + 699432150, + 832877231, + 708780849, + 3332740144, + 899835584, + 1951317047, + 4236429990, + 3767586992, + 866637845, + 4043610186, + 1106041591, + 2144161806, + 395441711, + 1984812685, + 1139781709, + 3433712980, + 3835036895, + 2664543715, + 1282050075, + 3240894392, + 1181045119, + 2640243204, + 25965917, + 4203181171, + 4211818798, + 3009879386, + 2463879762, + 3910161971, + 1842759443, + 2597806476, + 933301370, + 1509430414, + 3943906441, + 3467192302, + 3076639029, + 3776767469, + 2051518780, + 2631065433, + 1441952575, + 404016761, + 1942435775, + 1408749034, + 1610459739, + 3745345300, + 2017778566, + 3400528769, + 3110650942, + 941896748, + 3265478751, + 371049330, + 3168937228, + 675039627, + 4279080257, + 967311729, + 135050206, + 3635733660, + 1683407248, + 2076935265, + 3576870512, + 1215061108, + 3501741890 + ]; + var T6 = [ + 1347548327, + 1400783205, + 3273267108, + 2520393566, + 3409685355, + 4045380933, + 2880240216, + 2471224067, + 1428173050, + 4138563181, + 2441661558, + 636813900, + 4233094615, + 3620022987, + 2149987652, + 2411029155, + 1239331162, + 1730525723, + 2554718734, + 3781033664, + 46346101, + 310463728, + 2743944855, + 3328955385, + 3875770207, + 2501218972, + 3955191162, + 3667219033, + 768917123, + 3545789473, + 692707433, + 1150208456, + 1786102409, + 2029293177, + 1805211710, + 3710368113, + 3065962831, + 401639597, + 1724457132, + 3028143674, + 409198410, + 2196052529, + 1620529459, + 1164071807, + 3769721975, + 2226875310, + 486441376, + 2499348523, + 1483753576, + 428819965, + 2274680428, + 3075636216, + 598438867, + 3799141122, + 1474502543, + 711349675, + 129166120, + 53458370, + 2592523643, + 2782082824, + 4063242375, + 2988687269, + 3120694122, + 1559041666, + 730517276, + 2460449204, + 4042459122, + 2706270690, + 3446004468, + 3573941694, + 533804130, + 2328143614, + 2637442643, + 2695033685, + 839224033, + 1973745387, + 957055980, + 2856345839, + 106852767, + 1371368976, + 4181598602, + 1033297158, + 2933734917, + 1179510461, + 3046200461, + 91341917, + 1862534868, + 4284502037, + 605657339, + 2547432937, + 3431546947, + 2003294622, + 3182487618, + 2282195339, + 954669403, + 3682191598, + 1201765386, + 3917234703, + 3388507166, + 0, + 2198438022, + 1211247597, + 2887651696, + 1315723890, + 4227665663, + 1443857720, + 507358933, + 657861945, + 1678381017, + 560487590, + 3516619604, + 975451694, + 2970356327, + 261314535, + 3535072918, + 2652609425, + 1333838021, + 2724322336, + 1767536459, + 370938394, + 182621114, + 3854606378, + 1128014560, + 487725847, + 185469197, + 2918353863, + 3106780840, + 3356761769, + 2237133081, + 1286567175, + 3152976349, + 4255350624, + 2683765030, + 3160175349, + 3309594171, + 878443390, + 1988838185, + 3704300486, + 1756818940, + 1673061617, + 3403100636, + 272786309, + 1075025698, + 545572369, + 2105887268, + 4174560061, + 296679730, + 1841768865, + 1260232239, + 4091327024, + 3960309330, + 3497509347, + 1814803222, + 2578018489, + 4195456072, + 575138148, + 3299409036, + 446754879, + 3629546796, + 4011996048, + 3347532110, + 3252238545, + 4270639778, + 915985419, + 3483825537, + 681933534, + 651868046, + 2755636671, + 3828103837, + 223377554, + 2607439820, + 1649704518, + 3270937875, + 3901806776, + 1580087799, + 4118987695, + 3198115200, + 2087309459, + 2842678573, + 3016697106, + 1003007129, + 2802849917, + 1860738147, + 2077965243, + 164439672, + 4100872472, + 32283319, + 2827177882, + 1709610350, + 2125135846, + 136428751, + 3874428392, + 3652904859, + 3460984630, + 3572145929, + 3593056380, + 2939266226, + 824852259, + 818324884, + 3224740454, + 930369212, + 2801566410, + 2967507152, + 355706840, + 1257309336, + 4148292826, + 243256656, + 790073846, + 2373340630, + 1296297904, + 1422699085, + 3756299780, + 3818836405, + 457992840, + 3099667487, + 2135319889, + 77422314, + 1560382517, + 1945798516, + 788204353, + 1521706781, + 1385356242, + 870912086, + 325965383, + 2358957921, + 2050466060, + 2388260884, + 2313884476, + 4006521127, + 901210569, + 3990953189, + 1014646705, + 1503449823, + 1062597235, + 2031621326, + 3212035895, + 3931371469, + 1533017514, + 350174575, + 2256028891, + 2177544179, + 1052338372, + 741876788, + 1606591296, + 1914052035, + 213705253, + 2334669897, + 1107234197, + 1899603969, + 3725069491, + 2631447780, + 2422494913, + 1635502980, + 1893020342, + 1950903388, + 1120974935 + ]; + var T7 = [ + 2807058932, + 1699970625, + 2764249623, + 1586903591, + 1808481195, + 1173430173, + 1487645946, + 59984867, + 4199882800, + 1844882806, + 1989249228, + 1277555970, + 3623636965, + 3419915562, + 1149249077, + 2744104290, + 1514790577, + 459744698, + 244860394, + 3235995134, + 1963115311, + 4027744588, + 2544078150, + 4190530515, + 1608975247, + 2627016082, + 2062270317, + 1507497298, + 2200818878, + 567498868, + 1764313568, + 3359936201, + 2305455554, + 2037970062, + 1047239e3, + 1910319033, + 1337376481, + 2904027272, + 2892417312, + 984907214, + 1243112415, + 830661914, + 861968209, + 2135253587, + 2011214180, + 2927934315, + 2686254721, + 731183368, + 1750626376, + 4246310725, + 1820824798, + 4172763771, + 3542330227, + 48394827, + 2404901663, + 2871682645, + 671593195, + 3254988725, + 2073724613, + 145085239, + 2280796200, + 2779915199, + 1790575107, + 2187128086, + 472615631, + 3029510009, + 4075877127, + 3802222185, + 4107101658, + 3201631749, + 1646252340, + 4270507174, + 1402811438, + 1436590835, + 3778151818, + 3950355702, + 3963161475, + 4020912224, + 2667994737, + 273792366, + 2331590177, + 104699613, + 95345982, + 3175501286, + 2377486676, + 1560637892, + 3564045318, + 369057872, + 4213447064, + 3919042237, + 1137477952, + 2658625497, + 1119727848, + 2340947849, + 1530455833, + 4007360968, + 172466556, + 266959938, + 516552836, + 0, + 2256734592, + 3980931627, + 1890328081, + 1917742170, + 4294704398, + 945164165, + 3575528878, + 958871085, + 3647212047, + 2787207260, + 1423022939, + 775562294, + 1739656202, + 3876557655, + 2530391278, + 2443058075, + 3310321856, + 547512796, + 1265195639, + 437656594, + 3121275539, + 719700128, + 3762502690, + 387781147, + 218828297, + 3350065803, + 2830708150, + 2848461854, + 428169201, + 122466165, + 3720081049, + 1627235199, + 648017665, + 4122762354, + 1002783846, + 2117360635, + 695634755, + 3336358691, + 4234721005, + 4049844452, + 3704280881, + 2232435299, + 574624663, + 287343814, + 612205898, + 1039717051, + 840019705, + 2708326185, + 793451934, + 821288114, + 1391201670, + 3822090177, + 376187827, + 3113855344, + 1224348052, + 1679968233, + 2361698556, + 1058709744, + 752375421, + 2431590963, + 1321699145, + 3519142200, + 2734591178, + 188127444, + 2177869557, + 3727205754, + 2384911031, + 3215212461, + 2648976442, + 2450346104, + 3432737375, + 1180849278, + 331544205, + 3102249176, + 4150144569, + 2952102595, + 2159976285, + 2474404304, + 766078933, + 313773861, + 2570832044, + 2108100632, + 1668212892, + 3145456443, + 2013908262, + 418672217, + 3070356634, + 2594734927, + 1852171925, + 3867060991, + 3473416636, + 3907448597, + 2614737639, + 919489135, + 164948639, + 2094410160, + 2997825956, + 590424639, + 2486224549, + 1723872674, + 3157750862, + 3399941250, + 3501252752, + 3625268135, + 2555048196, + 3673637356, + 1343127501, + 4130281361, + 3599595085, + 2957853679, + 1297403050, + 81781910, + 3051593425, + 2283490410, + 532201772, + 1367295589, + 3926170974, + 895287692, + 1953757831, + 1093597963, + 492483431, + 3528626907, + 1446242576, + 1192455638, + 1636604631, + 209336225, + 344873464, + 1015671571, + 669961897, + 3375740769, + 3857572124, + 2973530695, + 3747192018, + 1933530610, + 3464042516, + 935293895, + 3454686199, + 2858115069, + 1863638845, + 3683022916, + 4085369519, + 3292445032, + 875313188, + 1080017571, + 3279033885, + 621591778, + 1233856572, + 2504130317, + 24197544, + 3017672716, + 3835484340, + 3247465558, + 2220981195, + 3060847922, + 1551124588, + 1463996600 + ]; + var T8 = [ + 4104605777, + 1097159550, + 396673818, + 660510266, + 2875968315, + 2638606623, + 4200115116, + 3808662347, + 821712160, + 1986918061, + 3430322568, + 38544885, + 3856137295, + 718002117, + 893681702, + 1654886325, + 2975484382, + 3122358053, + 3926825029, + 4274053469, + 796197571, + 1290801793, + 1184342925, + 3556361835, + 2405426947, + 2459735317, + 1836772287, + 1381620373, + 3196267988, + 1948373848, + 3764988233, + 3385345166, + 3263785589, + 2390325492, + 1480485785, + 3111247143, + 3780097726, + 2293045232, + 548169417, + 3459953789, + 3746175075, + 439452389, + 1362321559, + 1400849762, + 1685577905, + 1806599355, + 2174754046, + 137073913, + 1214797936, + 1174215055, + 3731654548, + 2079897426, + 1943217067, + 1258480242, + 529487843, + 1437280870, + 3945269170, + 3049390895, + 3313212038, + 923313619, + 679998e3, + 3215307299, + 57326082, + 377642221, + 3474729866, + 2041877159, + 133361907, + 1776460110, + 3673476453, + 96392454, + 878845905, + 2801699524, + 777231668, + 4082475170, + 2330014213, + 4142626212, + 2213296395, + 1626319424, + 1906247262, + 1846563261, + 562755902, + 3708173718, + 1040559837, + 3871163981, + 1418573201, + 3294430577, + 114585348, + 1343618912, + 2566595609, + 3186202582, + 1078185097, + 3651041127, + 3896688048, + 2307622919, + 425408743, + 3371096953, + 2081048481, + 1108339068, + 2216610296, + 0, + 2156299017, + 736970802, + 292596766, + 1517440620, + 251657213, + 2235061775, + 2933202493, + 758720310, + 265905162, + 1554391400, + 1532285339, + 908999204, + 174567692, + 1474760595, + 4002861748, + 2610011675, + 3234156416, + 3693126241, + 2001430874, + 303699484, + 2478443234, + 2687165888, + 585122620, + 454499602, + 151849742, + 2345119218, + 3064510765, + 514443284, + 4044981591, + 1963412655, + 2581445614, + 2137062819, + 19308535, + 1928707164, + 1715193156, + 4219352155, + 1126790795, + 600235211, + 3992742070, + 3841024952, + 836553431, + 1669664834, + 2535604243, + 3323011204, + 1243905413, + 3141400786, + 4180808110, + 698445255, + 2653899549, + 2989552604, + 2253581325, + 3252932727, + 3004591147, + 1891211689, + 2487810577, + 3915653703, + 4237083816, + 4030667424, + 2100090966, + 865136418, + 1229899655, + 953270745, + 3399679628, + 3557504664, + 4118925222, + 2061379749, + 3079546586, + 2915017791, + 983426092, + 2022837584, + 1607244650, + 2118541908, + 2366882550, + 3635996816, + 972512814, + 3283088770, + 1568718495, + 3499326569, + 3576539503, + 621982671, + 2895723464, + 410887952, + 2623762152, + 1002142683, + 645401037, + 1494807662, + 2595684844, + 1335535747, + 2507040230, + 4293295786, + 3167684641, + 367585007, + 3885750714, + 1865862730, + 2668221674, + 2960971305, + 2763173681, + 1059270954, + 2777952454, + 2724642869, + 1320957812, + 2194319100, + 2429595872, + 2815956275, + 77089521, + 3973773121, + 3444575871, + 2448830231, + 1305906550, + 4021308739, + 2857194700, + 2516901860, + 3518358430, + 1787304780, + 740276417, + 1699839814, + 1592394909, + 2352307457, + 2272556026, + 188821243, + 1729977011, + 3687994002, + 274084841, + 3594982253, + 3613494426, + 2701949495, + 4162096729, + 322734571, + 2837966542, + 1640576439, + 484830689, + 1202797690, + 3537852828, + 4067639125, + 349075736, + 3342319475, + 4157467219, + 4255800159, + 1030690015, + 1155237496, + 2951971274, + 1757691577, + 607398968, + 2738905026, + 499347990, + 3794078908, + 1011452712, + 227885567, + 2818666809, + 213114376, + 3034881240, + 1455525988, + 3414450555, + 850817237, + 1817998408, + 3092726480 + ]; + var U1 = [ + 0, + 235474187, + 470948374, + 303765277, + 941896748, + 908933415, + 607530554, + 708780849, + 1883793496, + 2118214995, + 1817866830, + 1649639237, + 1215061108, + 1181045119, + 1417561698, + 1517767529, + 3767586992, + 4003061179, + 4236429990, + 4069246893, + 3635733660, + 3602770327, + 3299278474, + 3400528769, + 2430122216, + 2664543715, + 2362090238, + 2193862645, + 2835123396, + 2801107407, + 3035535058, + 3135740889, + 3678124923, + 3576870512, + 3341394285, + 3374361702, + 3810496343, + 3977675356, + 4279080257, + 4043610186, + 2876494627, + 2776292904, + 3076639029, + 3110650942, + 2472011535, + 2640243204, + 2403728665, + 2169303058, + 1001089995, + 899835584, + 666464733, + 699432150, + 59727847, + 226906860, + 530400753, + 294930682, + 1273168787, + 1172967064, + 1475418501, + 1509430414, + 1942435775, + 2110667444, + 1876241833, + 1641816226, + 2910219766, + 2743034109, + 2976151520, + 3211623147, + 2505202138, + 2606453969, + 2302690252, + 2269728455, + 3711829422, + 3543599269, + 3240894392, + 3475313331, + 3843699074, + 3943906441, + 4178062228, + 4144047775, + 1306967366, + 1139781709, + 1374988112, + 1610459739, + 1975683434, + 2076935265, + 1775276924, + 1742315127, + 1034867998, + 866637845, + 566021896, + 800440835, + 92987698, + 193195065, + 429456164, + 395441711, + 1984812685, + 2017778566, + 1784663195, + 1683407248, + 1315562145, + 1080094634, + 1383856311, + 1551037884, + 101039829, + 135050206, + 437757123, + 337553864, + 1042385657, + 807962610, + 573804783, + 742039012, + 2531067453, + 2564033334, + 2328828971, + 2227573024, + 2935566865, + 2700099354, + 3001755655, + 3168937228, + 3868552805, + 3902563182, + 4203181171, + 4102977912, + 3736164937, + 3501741890, + 3265478751, + 3433712980, + 1106041591, + 1340463100, + 1576976609, + 1408749034, + 2043211483, + 2009195472, + 1708848333, + 1809054150, + 832877231, + 1068351396, + 766945465, + 599762354, + 159417987, + 126454664, + 361929877, + 463180190, + 2709260871, + 2943682380, + 3178106961, + 3009879386, + 2572697195, + 2538681184, + 2236228733, + 2336434550, + 3509871135, + 3745345300, + 3441850377, + 3274667266, + 3910161971, + 3877198648, + 4110568485, + 4211818798, + 2597806476, + 2497604743, + 2261089178, + 2295101073, + 2733856160, + 2902087851, + 3202437046, + 2968011453, + 3936291284, + 3835036895, + 4136440770, + 4169408201, + 3535486456, + 3702665459, + 3467192302, + 3231722213, + 2051518780, + 1951317047, + 1716890410, + 1750902305, + 1113818384, + 1282050075, + 1584504582, + 1350078989, + 168810852, + 67556463, + 371049330, + 404016761, + 841739592, + 1008918595, + 775550814, + 540080725, + 3969562369, + 3801332234, + 4035489047, + 4269907996, + 3569255213, + 3669462566, + 3366754619, + 3332740144, + 2631065433, + 2463879762, + 2160117071, + 2395588676, + 2767645557, + 2868897406, + 3102011747, + 3069049960, + 202008497, + 33778362, + 270040487, + 504459436, + 875451293, + 975658646, + 675039627, + 641025152, + 2084704233, + 1917518562, + 1615861247, + 1851332852, + 1147550661, + 1248802510, + 1484005843, + 1451044056, + 933301370, + 967311729, + 733156972, + 632953703, + 260388950, + 25965917, + 328671808, + 496906059, + 1206477858, + 1239443753, + 1543208500, + 1441952575, + 2144161806, + 1908694277, + 1675577880, + 1842759443, + 3610369226, + 3644379585, + 3408119516, + 3307916247, + 4011190502, + 3776767469, + 4077384432, + 4245618683, + 2809771154, + 2842737049, + 3144396420, + 3043140495, + 2673705150, + 2438237621, + 2203032232, + 2370213795 + ]; + var U2 = [ + 0, + 185469197, + 370938394, + 487725847, + 741876788, + 657861945, + 975451694, + 824852259, + 1483753576, + 1400783205, + 1315723890, + 1164071807, + 1950903388, + 2135319889, + 1649704518, + 1767536459, + 2967507152, + 3152976349, + 2801566410, + 2918353863, + 2631447780, + 2547432937, + 2328143614, + 2177544179, + 3901806776, + 3818836405, + 4270639778, + 4118987695, + 3299409036, + 3483825537, + 3535072918, + 3652904859, + 2077965243, + 1893020342, + 1841768865, + 1724457132, + 1474502543, + 1559041666, + 1107234197, + 1257309336, + 598438867, + 681933534, + 901210569, + 1052338372, + 261314535, + 77422314, + 428819965, + 310463728, + 3409685355, + 3224740454, + 3710368113, + 3593056380, + 3875770207, + 3960309330, + 4045380933, + 4195456072, + 2471224067, + 2554718734, + 2237133081, + 2388260884, + 3212035895, + 3028143674, + 2842678573, + 2724322336, + 4138563181, + 4255350624, + 3769721975, + 3955191162, + 3667219033, + 3516619604, + 3431546947, + 3347532110, + 2933734917, + 2782082824, + 3099667487, + 3016697106, + 2196052529, + 2313884476, + 2499348523, + 2683765030, + 1179510461, + 1296297904, + 1347548327, + 1533017514, + 1786102409, + 1635502980, + 2087309459, + 2003294622, + 507358933, + 355706840, + 136428751, + 53458370, + 839224033, + 957055980, + 605657339, + 790073846, + 2373340630, + 2256028891, + 2607439820, + 2422494913, + 2706270690, + 2856345839, + 3075636216, + 3160175349, + 3573941694, + 3725069491, + 3273267108, + 3356761769, + 4181598602, + 4063242375, + 4011996048, + 3828103837, + 1033297158, + 915985419, + 730517276, + 545572369, + 296679730, + 446754879, + 129166120, + 213705253, + 1709610350, + 1860738147, + 1945798516, + 2029293177, + 1239331162, + 1120974935, + 1606591296, + 1422699085, + 4148292826, + 4233094615, + 3781033664, + 3931371469, + 3682191598, + 3497509347, + 3446004468, + 3328955385, + 2939266226, + 2755636671, + 3106780840, + 2988687269, + 2198438022, + 2282195339, + 2501218972, + 2652609425, + 1201765386, + 1286567175, + 1371368976, + 1521706781, + 1805211710, + 1620529459, + 2105887268, + 1988838185, + 533804130, + 350174575, + 164439672, + 46346101, + 870912086, + 954669403, + 636813900, + 788204353, + 2358957921, + 2274680428, + 2592523643, + 2441661558, + 2695033685, + 2880240216, + 3065962831, + 3182487618, + 3572145929, + 3756299780, + 3270937875, + 3388507166, + 4174560061, + 4091327024, + 4006521127, + 3854606378, + 1014646705, + 930369212, + 711349675, + 560487590, + 272786309, + 457992840, + 106852767, + 223377554, + 1678381017, + 1862534868, + 1914052035, + 2031621326, + 1211247597, + 1128014560, + 1580087799, + 1428173050, + 32283319, + 182621114, + 401639597, + 486441376, + 768917123, + 651868046, + 1003007129, + 818324884, + 1503449823, + 1385356242, + 1333838021, + 1150208456, + 1973745387, + 2125135846, + 1673061617, + 1756818940, + 2970356327, + 3120694122, + 2802849917, + 2887651696, + 2637442643, + 2520393566, + 2334669897, + 2149987652, + 3917234703, + 3799141122, + 4284502037, + 4100872472, + 3309594171, + 3460984630, + 3545789473, + 3629546796, + 2050466060, + 1899603969, + 1814803222, + 1730525723, + 1443857720, + 1560382517, + 1075025698, + 1260232239, + 575138148, + 692707433, + 878443390, + 1062597235, + 243256656, + 91341917, + 409198410, + 325965383, + 3403100636, + 3252238545, + 3704300486, + 3620022987, + 3874428392, + 3990953189, + 4042459122, + 4227665663, + 2460449204, + 2578018489, + 2226875310, + 2411029155, + 3198115200, + 3046200461, + 2827177882, + 2743944855 + ]; + var U3 = [ + 0, + 218828297, + 437656594, + 387781147, + 875313188, + 958871085, + 775562294, + 590424639, + 1750626376, + 1699970625, + 1917742170, + 2135253587, + 1551124588, + 1367295589, + 1180849278, + 1265195639, + 3501252752, + 3720081049, + 3399941250, + 3350065803, + 3835484340, + 3919042237, + 4270507174, + 4085369519, + 3102249176, + 3051593425, + 2734591178, + 2952102595, + 2361698556, + 2177869557, + 2530391278, + 2614737639, + 3145456443, + 3060847922, + 2708326185, + 2892417312, + 2404901663, + 2187128086, + 2504130317, + 2555048196, + 3542330227, + 3727205754, + 3375740769, + 3292445032, + 3876557655, + 3926170974, + 4246310725, + 4027744588, + 1808481195, + 1723872674, + 1910319033, + 2094410160, + 1608975247, + 1391201670, + 1173430173, + 1224348052, + 59984867, + 244860394, + 428169201, + 344873464, + 935293895, + 984907214, + 766078933, + 547512796, + 1844882806, + 1627235199, + 2011214180, + 2062270317, + 1507497298, + 1423022939, + 1137477952, + 1321699145, + 95345982, + 145085239, + 532201772, + 313773861, + 830661914, + 1015671571, + 731183368, + 648017665, + 3175501286, + 2957853679, + 2807058932, + 2858115069, + 2305455554, + 2220981195, + 2474404304, + 2658625497, + 3575528878, + 3625268135, + 3473416636, + 3254988725, + 3778151818, + 3963161475, + 4213447064, + 4130281361, + 3599595085, + 3683022916, + 3432737375, + 3247465558, + 3802222185, + 4020912224, + 4172763771, + 4122762354, + 3201631749, + 3017672716, + 2764249623, + 2848461854, + 2331590177, + 2280796200, + 2431590963, + 2648976442, + 104699613, + 188127444, + 472615631, + 287343814, + 840019705, + 1058709744, + 671593195, + 621591778, + 1852171925, + 1668212892, + 1953757831, + 2037970062, + 1514790577, + 1463996600, + 1080017571, + 1297403050, + 3673637356, + 3623636965, + 3235995134, + 3454686199, + 4007360968, + 3822090177, + 4107101658, + 4190530515, + 2997825956, + 3215212461, + 2830708150, + 2779915199, + 2256734592, + 2340947849, + 2627016082, + 2443058075, + 172466556, + 122466165, + 273792366, + 492483431, + 1047239e3, + 861968209, + 612205898, + 695634755, + 1646252340, + 1863638845, + 2013908262, + 1963115311, + 1446242576, + 1530455833, + 1277555970, + 1093597963, + 1636604631, + 1820824798, + 2073724613, + 1989249228, + 1436590835, + 1487645946, + 1337376481, + 1119727848, + 164948639, + 81781910, + 331544205, + 516552836, + 1039717051, + 821288114, + 669961897, + 719700128, + 2973530695, + 3157750862, + 2871682645, + 2787207260, + 2232435299, + 2283490410, + 2667994737, + 2450346104, + 3647212047, + 3564045318, + 3279033885, + 3464042516, + 3980931627, + 3762502690, + 4150144569, + 4199882800, + 3070356634, + 3121275539, + 2904027272, + 2686254721, + 2200818878, + 2384911031, + 2570832044, + 2486224549, + 3747192018, + 3528626907, + 3310321856, + 3359936201, + 3950355702, + 3867060991, + 4049844452, + 4234721005, + 1739656202, + 1790575107, + 2108100632, + 1890328081, + 1402811438, + 1586903591, + 1233856572, + 1149249077, + 266959938, + 48394827, + 369057872, + 418672217, + 1002783846, + 919489135, + 567498868, + 752375421, + 209336225, + 24197544, + 376187827, + 459744698, + 945164165, + 895287692, + 574624663, + 793451934, + 1679968233, + 1764313568, + 2117360635, + 1933530610, + 1343127501, + 1560637892, + 1243112415, + 1192455638, + 3704280881, + 3519142200, + 3336358691, + 3419915562, + 3907448597, + 3857572124, + 4075877127, + 4294704398, + 3029510009, + 3113855344, + 2927934315, + 2744104290, + 2159976285, + 2377486676, + 2594734927, + 2544078150 + ]; + var U4 = [ + 0, + 151849742, + 303699484, + 454499602, + 607398968, + 758720310, + 908999204, + 1059270954, + 1214797936, + 1097159550, + 1517440620, + 1400849762, + 1817998408, + 1699839814, + 2118541908, + 2001430874, + 2429595872, + 2581445614, + 2194319100, + 2345119218, + 3034881240, + 3186202582, + 2801699524, + 2951971274, + 3635996816, + 3518358430, + 3399679628, + 3283088770, + 4237083816, + 4118925222, + 4002861748, + 3885750714, + 1002142683, + 850817237, + 698445255, + 548169417, + 529487843, + 377642221, + 227885567, + 77089521, + 1943217067, + 2061379749, + 1640576439, + 1757691577, + 1474760595, + 1592394909, + 1174215055, + 1290801793, + 2875968315, + 2724642869, + 3111247143, + 2960971305, + 2405426947, + 2253581325, + 2638606623, + 2487810577, + 3808662347, + 3926825029, + 4044981591, + 4162096729, + 3342319475, + 3459953789, + 3576539503, + 3693126241, + 1986918061, + 2137062819, + 1685577905, + 1836772287, + 1381620373, + 1532285339, + 1078185097, + 1229899655, + 1040559837, + 923313619, + 740276417, + 621982671, + 439452389, + 322734571, + 137073913, + 19308535, + 3871163981, + 4021308739, + 4104605777, + 4255800159, + 3263785589, + 3414450555, + 3499326569, + 3651041127, + 2933202493, + 2815956275, + 3167684641, + 3049390895, + 2330014213, + 2213296395, + 2566595609, + 2448830231, + 1305906550, + 1155237496, + 1607244650, + 1455525988, + 1776460110, + 1626319424, + 2079897426, + 1928707164, + 96392454, + 213114376, + 396673818, + 514443284, + 562755902, + 679998e3, + 865136418, + 983426092, + 3708173718, + 3557504664, + 3474729866, + 3323011204, + 4180808110, + 4030667424, + 3945269170, + 3794078908, + 2507040230, + 2623762152, + 2272556026, + 2390325492, + 2975484382, + 3092726480, + 2738905026, + 2857194700, + 3973773121, + 3856137295, + 4274053469, + 4157467219, + 3371096953, + 3252932727, + 3673476453, + 3556361835, + 2763173681, + 2915017791, + 3064510765, + 3215307299, + 2156299017, + 2307622919, + 2459735317, + 2610011675, + 2081048481, + 1963412655, + 1846563261, + 1729977011, + 1480485785, + 1362321559, + 1243905413, + 1126790795, + 878845905, + 1030690015, + 645401037, + 796197571, + 274084841, + 425408743, + 38544885, + 188821243, + 3613494426, + 3731654548, + 3313212038, + 3430322568, + 4082475170, + 4200115116, + 3780097726, + 3896688048, + 2668221674, + 2516901860, + 2366882550, + 2216610296, + 3141400786, + 2989552604, + 2837966542, + 2687165888, + 1202797690, + 1320957812, + 1437280870, + 1554391400, + 1669664834, + 1787304780, + 1906247262, + 2022837584, + 265905162, + 114585348, + 499347990, + 349075736, + 736970802, + 585122620, + 972512814, + 821712160, + 2595684844, + 2478443234, + 2293045232, + 2174754046, + 3196267988, + 3079546586, + 2895723464, + 2777952454, + 3537852828, + 3687994002, + 3234156416, + 3385345166, + 4142626212, + 4293295786, + 3841024952, + 3992742070, + 174567692, + 57326082, + 410887952, + 292596766, + 777231668, + 660510266, + 1011452712, + 893681702, + 1108339068, + 1258480242, + 1343618912, + 1494807662, + 1715193156, + 1865862730, + 1948373848, + 2100090966, + 2701949495, + 2818666809, + 3004591147, + 3122358053, + 2235061775, + 2352307457, + 2535604243, + 2653899549, + 3915653703, + 3764988233, + 4219352155, + 4067639125, + 3444575871, + 3294430577, + 3746175075, + 3594982253, + 836553431, + 953270745, + 600235211, + 718002117, + 367585007, + 484830689, + 133361907, + 251657213, + 2041877159, + 1891211689, + 1806599355, + 1654886325, + 1568718495, + 1418573201, + 1335535747, + 1184342925 + ]; + function convertToInt32(bytes) { + var result = []; + for(var i = 0; i < bytes.length; i += 4){ + result.push(bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]); + } + return result; + } + var AES2 = function(key) { + if (!(this instanceof AES2)) { + throw Error("AES must be instanitated with `new`"); + } + Object.defineProperty(this, "key", { + value: coerceArray(key, true) + }); + this._prepare(); + }; + AES2.prototype._prepare = function() { + var rounds = numberOfRounds[this.key.length]; + if (rounds == null) { + throw new Error("invalid key size (must be 16, 24 or 32 bytes)"); + } + this._Ke = []; + this._Kd = []; + for(var i = 0; i <= rounds; i++){ + this._Ke.push([ + 0, + 0, + 0, + 0 + ]); + this._Kd.push([ + 0, + 0, + 0, + 0 + ]); + } + var roundKeyCount = (rounds + 1) * 4; + var KC = this.key.length / 4; + var tk = convertToInt32(this.key); + var index; + for(var i = 0; i < KC; i++){ + index = i >> 2; + this._Ke[index][i % 4] = tk[i]; + this._Kd[rounds - index][i % 4] = tk[i]; + } + var rconpointer = 0; + var t = KC, tt; + while(t < roundKeyCount){ + tt = tk[KC - 1]; + tk[0] ^= S[tt >> 16 & 255] << 24 ^ S[tt >> 8 & 255] << 16 ^ S[tt & 255] << 8 ^ S[tt >> 24 & 255] ^ rcon[rconpointer] << 24; + rconpointer += 1; + if (KC != 8) { + for(var i = 1; i < KC; i++){ + tk[i] ^= tk[i - 1]; + } + } else { + for(var i = 1; i < KC / 2; i++){ + tk[i] ^= tk[i - 1]; + } + tt = tk[KC / 2 - 1]; + tk[KC / 2] ^= S[tt & 255] ^ S[tt >> 8 & 255] << 8 ^ S[tt >> 16 & 255] << 16 ^ S[tt >> 24 & 255] << 24; + for(var i = KC / 2 + 1; i < KC; i++){ + tk[i] ^= tk[i - 1]; + } + } + var i = 0, r, c; + while(i < KC && t < roundKeyCount){ + r = t >> 2; + c = t % 4; + this._Ke[r][c] = tk[i]; + this._Kd[rounds - r][c] = tk[i++]; + t++; + } + } + for(var r = 1; r < rounds; r++){ + for(var c = 0; c < 4; c++){ + tt = this._Kd[r][c]; + this._Kd[r][c] = U1[tt >> 24 & 255] ^ U2[tt >> 16 & 255] ^ U3[tt >> 8 & 255] ^ U4[tt & 255]; + } + } + }; + AES2.prototype.encrypt = function(plaintext) { + if (plaintext.length != 16) { + throw new Error("invalid plaintext size (must be 16 bytes)"); + } + var rounds = this._Ke.length - 1; + var a = [ + 0, + 0, + 0, + 0 + ]; + var t = convertToInt32(plaintext); + for(var i = 0; i < 4; i++){ + t[i] ^= this._Ke[0][i]; + } + for(var r = 1; r < rounds; r++){ + for(var i = 0; i < 4; i++){ + a[i] = T1[t[i] >> 24 & 255] ^ T2[t[(i + 1) % 4] >> 16 & 255] ^ T3[t[(i + 2) % 4] >> 8 & 255] ^ T4[t[(i + 3) % 4] & 255] ^ this._Ke[r][i]; + } + t = a.slice(); + } + var result = createArray(16), tt; + for(var i = 0; i < 4; i++){ + tt = this._Ke[rounds][i]; + result[4 * i] = (S[t[i] >> 24 & 255] ^ tt >> 24) & 255; + result[4 * i + 1] = (S[t[(i + 1) % 4] >> 16 & 255] ^ tt >> 16) & 255; + result[4 * i + 2] = (S[t[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; + result[4 * i + 3] = (S[t[(i + 3) % 4] & 255] ^ tt) & 255; + } + return result; + }; + AES2.prototype.decrypt = function(ciphertext) { + if (ciphertext.length != 16) { + throw new Error("invalid ciphertext size (must be 16 bytes)"); + } + var rounds = this._Kd.length - 1; + var a = [ + 0, + 0, + 0, + 0 + ]; + var t = convertToInt32(ciphertext); + for(var i = 0; i < 4; i++){ + t[i] ^= this._Kd[0][i]; + } + for(var r = 1; r < rounds; r++){ + for(var i = 0; i < 4; i++){ + a[i] = T5[t[i] >> 24 & 255] ^ T6[t[(i + 3) % 4] >> 16 & 255] ^ T7[t[(i + 2) % 4] >> 8 & 255] ^ T8[t[(i + 1) % 4] & 255] ^ this._Kd[r][i]; + } + t = a.slice(); + } + var result = createArray(16), tt; + for(var i = 0; i < 4; i++){ + tt = this._Kd[rounds][i]; + result[4 * i] = (Si[t[i] >> 24 & 255] ^ tt >> 24) & 255; + result[4 * i + 1] = (Si[t[(i + 3) % 4] >> 16 & 255] ^ tt >> 16) & 255; + result[4 * i + 2] = (Si[t[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; + result[4 * i + 3] = (Si[t[(i + 1) % 4] & 255] ^ tt) & 255; + } + return result; + }; + var ModeOfOperationECB = function(key) { + if (!(this instanceof ModeOfOperationECB)) { + throw Error("AES must be instanitated with `new`"); + } + this.description = "Electronic Code Block"; + this.name = "ecb"; + this._aes = new AES2(key); + }; + ModeOfOperationECB.prototype.encrypt = function(plaintext) { + plaintext = coerceArray(plaintext); + if (plaintext.length % 16 !== 0) { + throw new Error("invalid plaintext size (must be multiple of 16 bytes)"); + } + var ciphertext = createArray(plaintext.length); + var block = createArray(16); + for(var i = 0; i < plaintext.length; i += 16){ + copyArray(plaintext, block, 0, i, i + 16); + block = this._aes.encrypt(block); + copyArray(block, ciphertext, i); + } + return ciphertext; + }; + ModeOfOperationECB.prototype.decrypt = function(ciphertext) { + ciphertext = coerceArray(ciphertext); + if (ciphertext.length % 16 !== 0) { + throw new Error("invalid ciphertext size (must be multiple of 16 bytes)"); + } + var plaintext = createArray(ciphertext.length); + var block = createArray(16); + for(var i = 0; i < ciphertext.length; i += 16){ + copyArray(ciphertext, block, 0, i, i + 16); + block = this._aes.decrypt(block); + copyArray(block, plaintext, i); + } + return plaintext; + }; + var ModeOfOperationCBC = function(key, iv) { + if (!(this instanceof ModeOfOperationCBC)) { + throw Error("AES must be instanitated with `new`"); + } + this.description = "Cipher Block Chaining"; + this.name = "cbc"; + if (!iv) { + iv = createArray(16); + } else if (iv.length != 16) { + throw new Error("invalid initialation vector size (must be 16 bytes)"); + } + this._lastCipherblock = coerceArray(iv, true); + this._aes = new AES2(key); + }; + ModeOfOperationCBC.prototype.encrypt = function(plaintext) { + plaintext = coerceArray(plaintext); + if (plaintext.length % 16 !== 0) { + throw new Error("invalid plaintext size (must be multiple of 16 bytes)"); + } + var ciphertext = createArray(plaintext.length); + var block = createArray(16); + for(var i = 0; i < plaintext.length; i += 16){ + copyArray(plaintext, block, 0, i, i + 16); + for(var j = 0; j < 16; j++){ + block[j] ^= this._lastCipherblock[j]; + } + this._lastCipherblock = this._aes.encrypt(block); + copyArray(this._lastCipherblock, ciphertext, i); + } + return ciphertext; + }; + ModeOfOperationCBC.prototype.decrypt = function(ciphertext) { + ciphertext = coerceArray(ciphertext); + if (ciphertext.length % 16 !== 0) { + throw new Error("invalid ciphertext size (must be multiple of 16 bytes)"); + } + var plaintext = createArray(ciphertext.length); + var block = createArray(16); + for(var i = 0; i < ciphertext.length; i += 16){ + copyArray(ciphertext, block, 0, i, i + 16); + block = this._aes.decrypt(block); + for(var j = 0; j < 16; j++){ + plaintext[i + j] = block[j] ^ this._lastCipherblock[j]; + } + copyArray(ciphertext, this._lastCipherblock, 0, i, i + 16); + } + return plaintext; + }; + var ModeOfOperationCFB = function(key, iv, segmentSize) { + if (!(this instanceof ModeOfOperationCFB)) { + throw Error("AES must be instanitated with `new`"); + } + this.description = "Cipher Feedback"; + this.name = "cfb"; + if (!iv) { + iv = createArray(16); + } else if (iv.length != 16) { + throw new Error("invalid initialation vector size (must be 16 size)"); + } + if (!segmentSize) { + segmentSize = 1; + } + this.segmentSize = segmentSize; + this._shiftRegister = coerceArray(iv, true); + this._aes = new AES2(key); + }; + ModeOfOperationCFB.prototype.encrypt = function(plaintext) { + if (plaintext.length % this.segmentSize != 0) { + throw new Error("invalid plaintext size (must be segmentSize bytes)"); + } + var encrypted = coerceArray(plaintext, true); + var xorSegment; + for(var i = 0; i < encrypted.length; i += this.segmentSize){ + xorSegment = this._aes.encrypt(this._shiftRegister); + for(var j = 0; j < this.segmentSize; j++){ + encrypted[i + j] ^= xorSegment[j]; + } + copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize); + copyArray(encrypted, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize); + } + return encrypted; + }; + ModeOfOperationCFB.prototype.decrypt = function(ciphertext) { + if (ciphertext.length % this.segmentSize != 0) { + throw new Error("invalid ciphertext size (must be segmentSize bytes)"); + } + var plaintext = coerceArray(ciphertext, true); + var xorSegment; + for(var i = 0; i < plaintext.length; i += this.segmentSize){ + xorSegment = this._aes.encrypt(this._shiftRegister); + for(var j = 0; j < this.segmentSize; j++){ + plaintext[i + j] ^= xorSegment[j]; + } + copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize); + copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize); + } + return plaintext; + }; + var ModeOfOperationOFB = function(key, iv) { + if (!(this instanceof ModeOfOperationOFB)) { + throw Error("AES must be instanitated with `new`"); + } + this.description = "Output Feedback"; + this.name = "ofb"; + if (!iv) { + iv = createArray(16); + } else if (iv.length != 16) { + throw new Error("invalid initialation vector size (must be 16 bytes)"); + } + this._lastPrecipher = coerceArray(iv, true); + this._lastPrecipherIndex = 16; + this._aes = new AES2(key); + }; + ModeOfOperationOFB.prototype.encrypt = function(plaintext) { + var encrypted = coerceArray(plaintext, true); + for(var i = 0; i < encrypted.length; i++){ + if (this._lastPrecipherIndex === 16) { + this._lastPrecipher = this._aes.encrypt(this._lastPrecipher); + this._lastPrecipherIndex = 0; + } + encrypted[i] ^= this._lastPrecipher[this._lastPrecipherIndex++]; + } + return encrypted; + }; + ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt; + var Counter2 = function(initialValue) { + if (!(this instanceof Counter2)) { + throw Error("Counter must be instanitated with `new`"); + } + if (initialValue !== 0 && !initialValue) { + initialValue = 1; + } + if (typeof initialValue === "number") { + this._counter = createArray(16); + this.setValue(initialValue); + } else { + this.setBytes(initialValue); + } + }; + Counter2.prototype.setValue = function(value) { + if (typeof value !== "number" || parseInt(value) != value) { + throw new Error("invalid counter value (must be an integer)"); + } + for(var index = 15; index >= 0; --index){ + this._counter[index] = value % 256; + value = value >> 8; + } + }; + Counter2.prototype.setBytes = function(bytes) { + bytes = coerceArray(bytes, true); + if (bytes.length != 16) { + throw new Error("invalid counter bytes size (must be 16 bytes)"); + } + this._counter = bytes; + }; + Counter2.prototype.increment = function() { + for(var i = 15; i >= 0; i--){ + if (this._counter[i] === 255) { + this._counter[i] = 0; + } else { + this._counter[i]++; + break; + } + } + }; + var ModeOfOperationCTR = function(key, counter) { + if (!(this instanceof ModeOfOperationCTR)) { + throw Error("AES must be instanitated with `new`"); + } + this.description = "Counter"; + this.name = "ctr"; + if (!(counter instanceof Counter2)) { + counter = new Counter2(counter); + } + this._counter = counter; + this._remainingCounter = null; + this._remainingCounterIndex = 16; + this._aes = new AES2(key); + }; + ModeOfOperationCTR.prototype.encrypt = function(plaintext) { + var encrypted = coerceArray(plaintext, true); + for(var i = 0; i < encrypted.length; i++){ + if (this._remainingCounterIndex === 16) { + this._remainingCounter = this._aes.encrypt(this._counter._counter); + this._remainingCounterIndex = 0; + this._counter.increment(); + } + encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++]; + } + return encrypted; + }; + ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt; + function pkcs7pad(data) { + data = coerceArray(data, true); + var padder = 16 - data.length % 16; + var result = createArray(data.length + padder); + copyArray(data, result); + for(var i = data.length; i < result.length; i++){ + result[i] = padder; + } + return result; } - buffer = buffer << bitsPerChar | value; - bits += bitsPerChar; - if (bits >= 8) { - bits -= 8; - out[written++] = 255 & buffer >> bits; + function pkcs7strip(data) { + data = coerceArray(data, true); + if (data.length < 16) { + throw new Error("PKCS#7 invalid length"); + } + var padder = data[data.length - 1]; + if (padder > 16) { + throw new Error("PKCS#7 padding byte out of range"); + } + var length = data.length - padder; + for(var i = 0; i < padder; i++){ + if (data[length + i] !== padder) { + throw new Error("PKCS#7 invalid padding byte"); + } + } + var result = createArray(length); + copyArray(data, result, 0, 0, length); + return result; + } + var aesjs = { + AES: AES2, + Counter: Counter2, + ModeOfOperation: { + ecb: ModeOfOperationECB, + cbc: ModeOfOperationCBC, + cfb: ModeOfOperationCFB, + ofb: ModeOfOperationOFB, + ctr: ModeOfOperationCTR + }, + utils: { + hex: convertHex, + utf8: convertUtf8 + }, + padding: { + pkcs7: { + pad: pkcs7pad, + strip: pkcs7strip + } + }, + _arrayTest: { + coerceArray, + createArray, + copyArray + } + }; + { + module.exports = aesjs; } - } - if (bits >= bitsPerChar || (255 & buffer << 8 - bits) !== 0) { - throw new SyntaxError("Unexpected end of data"); - } - return out; + })(); +}); +aesJs.AES; +aesJs.Counter; +aesJs.ModeOfOperation; +aesJs._arrayTest; +aesJs.padding; +aesJs.utils; +function createCommonjsModule6(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function(path, base) { + return commonjsRequire6(path, base === void 0 || base === null ? module.path : base); + } + }, fn(module, module.exports), module.exports; } -function encode1(data, alphabet, bitsPerChar) { - const pad = alphabet[alphabet.length - 1] === "="; - const mask = (1 << bitsPerChar) - 1; - let out = ""; - let bits = 0; - let buffer = 0; - for(let i = 0; i < data.length; ++i){ - buffer = buffer << 8 | data[i]; - bits += 8; - while(bits > bitsPerChar){ - bits -= bitsPerChar; - out += alphabet[mask & buffer >> bits]; +function commonjsRequire6() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); +} +var scrypt = createCommonjsModule6(function(module, exports) { + (function(root) { + function SHA256(m) { + const K = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 + ]); + let h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762; + let h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225; + const w = new Uint32Array(64); + function blocks(p2) { + let off = 0, len = p2.length; + while(len >= 64){ + let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7, u, i2, j, t1, t2; + for(i2 = 0; i2 < 16; i2++){ + j = off + i2 * 4; + w[i2] = (p2[j] & 255) << 24 | (p2[j + 1] & 255) << 16 | (p2[j + 2] & 255) << 8 | p2[j + 3] & 255; + } + for(i2 = 16; i2 < 64; i2++){ + u = w[i2 - 2]; + t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10; + u = w[i2 - 15]; + t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3; + w[i2] = (t1 + w[i2 - 7] | 0) + (t2 + w[i2 - 16] | 0) | 0; + } + for(i2 = 0; i2 < 64; i2++){ + t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g) | 0) + (h + (K[i2] + w[i2] | 0) | 0) | 0; + t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c ^ b & c) | 0; + h = g; + g = f; + f = e; + e = d + t1 | 0; + d = c; + c = b; + b = a; + a = t1 + t2 | 0; + } + h0 = h0 + a | 0; + h1 = h1 + b | 0; + h2 = h2 + c | 0; + h3 = h3 + d | 0; + h4 = h4 + e | 0; + h5 = h5 + f | 0; + h6 = h6 + g | 0; + h7 = h7 + h | 0; + off += 64; + len -= 64; + } + } + blocks(m); + let i, bytesLeft = m.length % 64, bitLenHi = m.length / 536870912 | 0, bitLenLo = m.length << 3, numZeros = bytesLeft < 56 ? 56 : 120, p = m.slice(m.length - bytesLeft, m.length); + p.push(128); + for(i = bytesLeft + 1; i < numZeros; i++){ + p.push(0); + } + p.push(bitLenHi >>> 24 & 255); + p.push(bitLenHi >>> 16 & 255); + p.push(bitLenHi >>> 8 & 255); + p.push(bitLenHi >>> 0 & 255); + p.push(bitLenLo >>> 24 & 255); + p.push(bitLenLo >>> 16 & 255); + p.push(bitLenLo >>> 8 & 255); + p.push(bitLenLo >>> 0 & 255); + blocks(p); + return [ + h0 >>> 24 & 255, + h0 >>> 16 & 255, + h0 >>> 8 & 255, + h0 >>> 0 & 255, + h1 >>> 24 & 255, + h1 >>> 16 & 255, + h1 >>> 8 & 255, + h1 >>> 0 & 255, + h2 >>> 24 & 255, + h2 >>> 16 & 255, + h2 >>> 8 & 255, + h2 >>> 0 & 255, + h3 >>> 24 & 255, + h3 >>> 16 & 255, + h3 >>> 8 & 255, + h3 >>> 0 & 255, + h4 >>> 24 & 255, + h4 >>> 16 & 255, + h4 >>> 8 & 255, + h4 >>> 0 & 255, + h5 >>> 24 & 255, + h5 >>> 16 & 255, + h5 >>> 8 & 255, + h5 >>> 0 & 255, + h6 >>> 24 & 255, + h6 >>> 16 & 255, + h6 >>> 8 & 255, + h6 >>> 0 & 255, + h7 >>> 24 & 255, + h7 >>> 16 & 255, + h7 >>> 8 & 255, + h7 >>> 0 & 255 + ]; } - } - if (bits !== 0) { - out += alphabet[mask & buffer << bitsPerChar - bits]; - } - if (pad) { - while((out.length * bitsPerChar & 7) !== 0){ - out += "="; + function PBKDF2_HMAC_SHA256_OneIter(password, salt, dkLen) { + password = password.length <= 64 ? password : SHA256(password); + const innerLen = 64 + salt.length + 4; + const inner = new Array(innerLen); + const outerKey = new Array(64); + let i; + let dk = []; + for(i = 0; i < 64; i++){ + inner[i] = 54; + } + for(i = 0; i < password.length; i++){ + inner[i] ^= password[i]; + } + for(i = 0; i < salt.length; i++){ + inner[64 + i] = salt[i]; + } + for(i = innerLen - 4; i < innerLen; i++){ + inner[i] = 0; + } + for(i = 0; i < 64; i++)outerKey[i] = 92; + for(i = 0; i < password.length; i++)outerKey[i] ^= password[i]; + function incrementCounter() { + for(let i2 = innerLen - 1; i2 >= innerLen - 4; i2--){ + inner[i2]++; + if (inner[i2] <= 255) return; + inner[i2] = 0; + } + } + while(dkLen >= 32){ + incrementCounter(); + dk = dk.concat(SHA256(outerKey.concat(SHA256(inner)))); + dkLen -= 32; + } + if (dkLen > 0) { + incrementCounter(); + dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))).slice(0, dkLen)); + } + return dk; + } + function blockmix_salsa8(BY, Yi, r, x, _X) { + let i; + arraycopy(BY, (2 * r - 1) * 16, _X, 0, 16); + for(i = 0; i < 2 * r; i++){ + blockxor(BY, i * 16, _X, 16); + salsa20_8(_X, x); + arraycopy(_X, 0, BY, Yi + i * 16, 16); + } + for(i = 0; i < r; i++){ + arraycopy(BY, Yi + i * 2 * 16, BY, i * 16, 16); + } + for(i = 0; i < r; i++){ + arraycopy(BY, Yi + (i * 2 + 1) * 16, BY, (i + r) * 16, 16); + } } - } - return out; -} -function rfc4648({ name, prefix, bitsPerChar, alphabet }) { - return from({ - prefix, - name, - encode (input) { - return encode1(input, alphabet, bitsPerChar); - }, - decode (input) { - return decode2(input, alphabet, bitsPerChar, name); + function R(a, b) { + return a << b | a >>> 32 - b; + } + function salsa20_8(B, x) { + arraycopy(B, 0, x, 0, 16); + for(let i = 8; i > 0; i -= 2){ + x[4] ^= R(x[0] + x[12], 7); + x[8] ^= R(x[4] + x[0], 9); + x[12] ^= R(x[8] + x[4], 13); + x[0] ^= R(x[12] + x[8], 18); + x[9] ^= R(x[5] + x[1], 7); + x[13] ^= R(x[9] + x[5], 9); + x[1] ^= R(x[13] + x[9], 13); + x[5] ^= R(x[1] + x[13], 18); + x[14] ^= R(x[10] + x[6], 7); + x[2] ^= R(x[14] + x[10], 9); + x[6] ^= R(x[2] + x[14], 13); + x[10] ^= R(x[6] + x[2], 18); + x[3] ^= R(x[15] + x[11], 7); + x[7] ^= R(x[3] + x[15], 9); + x[11] ^= R(x[7] + x[3], 13); + x[15] ^= R(x[11] + x[7], 18); + x[1] ^= R(x[0] + x[3], 7); + x[2] ^= R(x[1] + x[0], 9); + x[3] ^= R(x[2] + x[1], 13); + x[0] ^= R(x[3] + x[2], 18); + x[6] ^= R(x[5] + x[4], 7); + x[7] ^= R(x[6] + x[5], 9); + x[4] ^= R(x[7] + x[6], 13); + x[5] ^= R(x[4] + x[7], 18); + x[11] ^= R(x[10] + x[9], 7); + x[8] ^= R(x[11] + x[10], 9); + x[9] ^= R(x[8] + x[11], 13); + x[10] ^= R(x[9] + x[8], 18); + x[12] ^= R(x[15] + x[14], 7); + x[13] ^= R(x[12] + x[15], 9); + x[14] ^= R(x[13] + x[12], 13); + x[15] ^= R(x[14] + x[13], 18); + } + for(let i = 0; i < 16; ++i){ + B[i] += x[i]; + } } - }); -} -const base32 = rfc4648({ - prefix: "b", - name: "base32", - alphabet: "abcdefghijklmnopqrstuvwxyz234567", - bitsPerChar: 5 -}); -const base32upper = rfc4648({ - prefix: "B", - name: "base32upper", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", - bitsPerChar: 5 -}); -const base32pad = rfc4648({ - prefix: "c", - name: "base32pad", - alphabet: "abcdefghijklmnopqrstuvwxyz234567=", - bitsPerChar: 5 -}); -const base32padupper = rfc4648({ - prefix: "C", - name: "base32padupper", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", - bitsPerChar: 5 -}); -const base32hex = rfc4648({ - prefix: "v", - name: "base32hex", - alphabet: "0123456789abcdefghijklmnopqrstuv", - bitsPerChar: 5 -}); -const base32hexupper = rfc4648({ - prefix: "V", - name: "base32hexupper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", - bitsPerChar: 5 -}); -const base32hexpad = rfc4648({ - prefix: "t", - name: "base32hexpad", - alphabet: "0123456789abcdefghijklmnopqrstuv=", - bitsPerChar: 5 -}); -const base32hexpadupper = rfc4648({ - prefix: "T", - name: "base32hexpadupper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", - bitsPerChar: 5 -}); -const base32z = rfc4648({ - prefix: "h", - name: "base32z", - alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", - bitsPerChar: 5 -}); -Object.freeze({ - __proto__: null, - base32, - base32upper, - base32pad, - base32padupper, - base32hex, - base32hexupper, - base32hexpad, - base32hexpadupper, - base32z -}); -const base58btc = baseX({ - name: "base58btc", - prefix: "z", - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" -}); -const base58flickr = baseX({ - name: "base58flickr", - prefix: "Z", - alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" -}); -Object.freeze({ - __proto__: null, - base58btc, - base58flickr -}); -var __defProp1 = Object.defineProperty; -var __publicField1 = (obj, key, value)=>{ - if (typeof key !== "symbol") key += ""; - if (key in obj) return __defProp1(obj, key, { - enumerable: true, - configurable: true, - writable: true, - value - }); - return obj[key] = value; -}; -var encode_1 = encode2; -var MSB = 128, REST1 = 127, MSBALL = ~REST1, INT = Math.pow(2, 31); -function encode2(num, out, offset) { - out = out || []; - offset = offset || 0; - var oldOffset = offset; - while(num >= INT){ - out[offset++] = num & 255 | MSB; - num /= 128; - } - while(num & MSBALL){ - out[offset++] = num & 255 | MSB; - num >>>= 7; - } - out[offset] = num | 0; - encode2.bytes = offset - oldOffset + 1; - return out; -} -var decode3 = read; -var MSB$1 = 128, REST$1 = 127; -function read(buf, offset) { - var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; - do { - if (counter >= l) { - read.bytes = 0; - throw new RangeError("Could not decode varint"); + function blockxor(S, Si, D, len) { + for(let i = 0; i < len; i++){ + D[i] ^= S[Si + i]; + } } - b = buf[counter++]; - res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift); - shift += 7; - }while (b >= MSB$1) - read.bytes = counter - offset; - return res; + function arraycopy(src, srcPos, dest, destPos, length) { + while(length--){ + dest[destPos++] = src[srcPos++]; + } + } + function checkBufferish(o) { + if (!o || typeof o.length !== "number") { + return false; + } + for(let i = 0; i < o.length; i++){ + const v = o[i]; + if (typeof v !== "number" || v % 1 || v < 0 || v >= 256) { + return false; + } + } + return true; + } + function ensureInteger(value, name) { + if (typeof value !== "number" || value % 1) { + throw new Error("invalid " + name); + } + return value; + } + function _scrypt(password, salt, N, r, p, dkLen, callback) { + N = ensureInteger(N, "N"); + r = ensureInteger(r, "r"); + p = ensureInteger(p, "p"); + dkLen = ensureInteger(dkLen, "dkLen"); + if (N === 0 || (N & N - 1) !== 0) { + throw new Error("N must be power of 2"); + } + if (N > 2147483647 / 128 / r) { + throw new Error("N too large"); + } + if (r > 2147483647 / 128 / p) { + throw new Error("r too large"); + } + if (!checkBufferish(password)) { + throw new Error("password must be an array or buffer"); + } + password = Array.prototype.slice.call(password); + if (!checkBufferish(salt)) { + throw new Error("salt must be an array or buffer"); + } + salt = Array.prototype.slice.call(salt); + let b = PBKDF2_HMAC_SHA256_OneIter(password, salt, p * 128 * r); + const B = new Uint32Array(p * 32 * r); + for(let i = 0; i < B.length; i++){ + const j = i * 4; + B[i] = (b[j + 3] & 255) << 24 | (b[j + 2] & 255) << 16 | (b[j + 1] & 255) << 8 | (b[j + 0] & 255) << 0; + } + const XY = new Uint32Array(64 * r); + const V = new Uint32Array(32 * r * N); + const Yi = 32 * r; + const x = new Uint32Array(16); + const _X = new Uint32Array(16); + const totalOps = p * N * 2; + let currentOp = 0; + let lastPercent10 = null; + let stop = false; + let state = 0; + let i0 = 0, i1; + let Bi; + const limit = callback ? parseInt(1e3 / r) : 4294967295; + const nextTick = typeof setImmediate !== "undefined" ? setImmediate : setTimeout; + const incrementalSMix = function() { + if (stop) { + return callback(new Error("cancelled"), currentOp / totalOps); + } + let steps; + switch(state){ + case 0: + Bi = i0 * 32 * r; + arraycopy(B, Bi, XY, 0, Yi); + state = 1; + i1 = 0; + case 1: + steps = N - i1; + if (steps > limit) { + steps = limit; + } + for(let i = 0; i < steps; i++){ + arraycopy(XY, 0, V, (i1 + i) * Yi, Yi); + blockmix_salsa8(XY, Yi, r, x, _X); + } + i1 += steps; + currentOp += steps; + if (callback) { + const percent10 = parseInt(1e3 * currentOp / totalOps); + if (percent10 !== lastPercent10) { + stop = callback(null, currentOp / totalOps); + if (stop) { + break; + } + lastPercent10 = percent10; + } + } + if (i1 < N) { + break; + } + i1 = 0; + state = 2; + case 2: + steps = N - i1; + if (steps > limit) { + steps = limit; + } + for(let i = 0; i < steps; i++){ + const offset = (2 * r - 1) * 16; + const j = XY[offset] & N - 1; + blockxor(V, j * Yi, XY, Yi); + blockmix_salsa8(XY, Yi, r, x, _X); + } + i1 += steps; + currentOp += steps; + if (callback) { + const percent10 = parseInt(1e3 * currentOp / totalOps); + if (percent10 !== lastPercent10) { + stop = callback(null, currentOp / totalOps); + if (stop) { + break; + } + lastPercent10 = percent10; + } + } + if (i1 < N) { + break; + } + arraycopy(XY, 0, B, Bi, Yi); + i0++; + if (i0 < p) { + state = 0; + break; + } + b = []; + for(let i = 0; i < B.length; i++){ + b.push(B[i] >> 0 & 255); + b.push(B[i] >> 8 & 255); + b.push(B[i] >> 16 & 255); + b.push(B[i] >> 24 & 255); + } + const derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen); + if (callback) { + callback(null, 1, derivedKey); + } + return derivedKey; + } + if (callback) { + nextTick(incrementalSMix); + } + }; + if (!callback) { + while(true){ + const derivedKey = incrementalSMix(); + if (derivedKey != void 0) { + return derivedKey; + } + } + } + incrementalSMix(); + } + const lib = { + scrypt: function(password, salt, N, r, p, dkLen, progressCallback) { + return new Promise(function(resolve, reject) { + let lastProgress = 0; + if (progressCallback) { + progressCallback(0); + } + _scrypt(password, salt, N, r, p, dkLen, function(error, progress, key) { + if (error) { + reject(error); + } else if (key) { + if (progressCallback && lastProgress !== 1) { + progressCallback(1); + } + resolve(new Uint8Array(key)); + } else if (progressCallback && progress !== lastProgress) { + lastProgress = progress; + return progressCallback(progress); + } + }); + }); + }, + syncScrypt: function(password, salt, N, r, p, dkLen) { + return new Uint8Array(_scrypt(password, salt, N, r, p, dkLen)); + } + }; + { + module.exports = lib; + } + })(); +}); +scrypt.scrypt; +scrypt.syncScrypt; +const version19 = "json-wallets/5.7.0"; +function looseArrayify(hexString) { + if (typeof hexString === "string" && hexString.substring(0, 2) !== "0x") { + hexString = "0x" + hexString; + } + return arrayify(hexString); } -var N1 = Math.pow(2, 7); -var N2 = Math.pow(2, 14); -var N3 = Math.pow(2, 21); -var N4 = Math.pow(2, 28); -var N5 = Math.pow(2, 35); -var N6 = Math.pow(2, 42); -var N7 = Math.pow(2, 49); -var N8 = Math.pow(2, 56); -var N9 = Math.pow(2, 63); -var length = function(value) { - return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10; -}; -var varint = { - encode: encode_1, - decode: decode3, - encodingLength: length -}; -var _brrp_varint = varint; -function decode$1(data, offset = 0) { - const code = _brrp_varint.decode(data, offset); - return [ - code, - _brrp_varint.decode.bytes - ]; +function zpad(value, length) { + value = String(value); + while(value.length < length){ + value = "0" + value; + } + return value; } -function encodeTo(__int, target, offset = 0) { - _brrp_varint.encode(__int, target, offset); - return target; +function getPassword(password) { + if (typeof password === "string") { + return toUtf8Bytes(password, UnicodeNormalizationForm.NFKC); + } + return arrayify(password); } -function encodingLength(__int) { - return _brrp_varint.encodingLength(__int); +function searchPath(object, path) { + let currentChild = object; + const comps = path.toLowerCase().split("/"); + for(let i = 0; i < comps.length; i++){ + let matchingChild = null; + for(const key in currentChild){ + if (key.toLowerCase() === comps[i]) { + matchingChild = currentChild[key]; + break; + } + } + if (matchingChild === null) { + return null; + } + currentChild = matchingChild; + } + return currentChild; } -Object.freeze({ - __proto__: null, - decode: decode$1, - encodeTo, - encodingLength -}); -function create(code, digest2) { - const size = digest2.byteLength; - const sizeOffset = encodingLength(code); - const digestOffset = sizeOffset + encodingLength(size); - const bytes = new Uint8Array(digestOffset + size); - encodeTo(code, bytes, 0); - encodeTo(size, bytes, sizeOffset); - bytes.set(digest2, digestOffset); - return new Digest(code, size, digest2, bytes); +function uuidV4(randomBytes2) { + const bytes2 = arrayify(randomBytes2); + bytes2[6] = bytes2[6] & 15 | 64; + bytes2[8] = bytes2[8] & 63 | 128; + const value = hexlify(bytes2); + return [ + value.substring(2, 10), + value.substring(10, 14), + value.substring(14, 18), + value.substring(18, 22), + value.substring(22, 34) + ].join("-"); +} +const logger217 = new Logger(version19); +class CrowdsaleAccount extends Description { + isCrowdsaleAccount(value) { + return !!(value && value._isCrowdsaleAccount); + } +} +function decrypt(json, password) { + const data = JSON.parse(json); + password = getPassword(password); + const ethaddr = getAddress(searchPath(data, "ethaddr")); + const encseed = looseArrayify(searchPath(data, "encseed")); + if (!encseed || encseed.length % 16 !== 0) { + logger217.throwArgumentError("invalid encseed", "json", json); + } + const key = arrayify(pbkdf2(password, password, 2e3, 32, "sha256")).slice(0, 16); + const iv = encseed.slice(0, 16); + const encryptedSeed = encseed.slice(16); + const aesCbc = new aesJs.ModeOfOperation.cbc(key, iv); + const seed = aesJs.padding.pkcs7.strip(arrayify(aesCbc.decrypt(encryptedSeed))); + let seedHex = ""; + for(let i = 0; i < seed.length; i++){ + seedHex += String.fromCharCode(seed[i]); + } + const seedHexBytes = toUtf8Bytes(seedHex); + const privateKey = keccak256(seedHexBytes); + return new CrowdsaleAccount({ + _isCrowdsaleAccount: true, + address: ethaddr, + privateKey + }); } -function decode$2(multihash) { - const bytes = coerce(multihash); - const [code, sizeOffset] = decode$1(bytes); - const [size, digestOffset] = decode$1(bytes.subarray(sizeOffset)); - const digest2 = bytes.subarray(sizeOffset + digestOffset); - if (digest2.byteLength !== size) { - throw new Error("Incorrect length"); +function isCrowdsaleWallet(json) { + let data = null; + try { + data = JSON.parse(json); + } catch (error) { + return false; } - return new Digest(code, size, digest2, bytes); + return data.encseed && data.ethaddr; } -function equals1(a, b) { - if (a === b) { - return true; - } else { - const data = b; - return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes); +function isKeystoreWallet(json) { + let data = null; + try { + data = JSON.parse(json); + } catch (error) { + return false; + } + if (!data.version || parseInt(data.version) !== data.version || parseInt(data.version) !== 3) { + return false; } + return true; } -class Digest { - constructor(code, size, digest2, bytes){ - __publicField1(this, "code"); - __publicField1(this, "size"); - __publicField1(this, "digest"); - __publicField1(this, "bytes"); - this.code = code; - this.size = size; - this.digest = digest2; - this.bytes = bytes; +function getJsonWalletAddress(json) { + if (isCrowdsaleWallet(json)) { + try { + return getAddress(JSON.parse(json).ethaddr); + } catch (error) { + return null; + } + } + if (isKeystoreWallet(json)) { + try { + return getAddress(JSON.parse(json).address); + } catch (error) { + return null; + } } + return null; } -Object.freeze({ - __proto__: null, - create, - decode: decode$2, - equals: equals1, - Digest -}); -var __defProp2 = Object.defineProperty; -var __publicField2 = (obj, key, value)=>{ - if (typeof key !== "symbol") key += ""; - if (key in obj) return __defProp2(obj, key, { - enumerable: true, - configurable: true, - writable: true, - value +var __awaiter5 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - return obj[key] = value; }; -var _a; -function format(link, base) { - const { bytes, version } = link; - switch(version){ - case 0: - return toStringV0(bytes, baseCache(link), base != null ? base : base58btc.encoder); - default: - return toStringV1(bytes, baseCache(link), base != null ? base : base32.encoder); +const logger$13 = new Logger(version19); +function hasMnemonic(value) { + return value != null && value.mnemonic && value.mnemonic.phrase; +} +class KeystoreAccount extends Description { + isKeystoreAccount(value) { + return !!(value && value._isKeystoreAccount); } } -const cache = new WeakMap(); -function baseCache(cid) { - const baseCache2 = cache.get(cid); - if (baseCache2 == null) { - const baseCache3 = new Map(); - cache.set(cid, baseCache3); - return baseCache3; +function _decrypt(data, key, ciphertext) { + const cipher = searchPath(data, "crypto/cipher"); + if (cipher === "aes-128-ctr") { + const iv = looseArrayify(searchPath(data, "crypto/cipherparams/iv")); + const counter = new aesJs.Counter(iv); + const aesCtr = new aesJs.ModeOfOperation.ctr(key, counter); + return arrayify(aesCtr.decrypt(ciphertext)); } - return baseCache2; + return null; } -class CID { - constructor(version, code, multihash, bytes){ - __publicField2(this, "code"); - __publicField2(this, "version"); - __publicField2(this, "multihash"); - __publicField2(this, "bytes"); - __publicField2(this, "/"); - __publicField2(this, _a, "CID"); - this.code = code; - this.version = version; - this.multihash = multihash; - this.bytes = bytes; - this["/"] = bytes; +function _getAccount(data, key) { + const ciphertext = looseArrayify(searchPath(data, "crypto/ciphertext")); + const computedMAC = hexlify(keccak256(concat([ + key.slice(16, 32), + ciphertext + ]))).substring(2); + if (computedMAC !== searchPath(data, "crypto/mac").toLowerCase()) { + throw new Error("invalid password"); + } + const privateKey = _decrypt(data, key.slice(0, 16), ciphertext); + if (!privateKey) { + logger$13.throwError("unsupported cipher", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "decrypt" + }); } - get asCID() { - return this; + const mnemonicKey = key.slice(32, 64); + const address2 = computeAddress(privateKey); + if (data.address) { + let check = data.address.toLowerCase(); + if (check.substring(0, 2) !== "0x") { + check = "0x" + check; + } + if (getAddress(check) !== address2) { + throw new Error("address mismatch"); + } } - get byteOffset() { - return this.bytes.byteOffset; + const account = { + _isKeystoreAccount: true, + address: address2, + privateKey: hexlify(privateKey) + }; + if (searchPath(data, "x-ethers/version") === "0.1") { + const mnemonicCiphertext = looseArrayify(searchPath(data, "x-ethers/mnemonicCiphertext")); + const mnemonicIv = looseArrayify(searchPath(data, "x-ethers/mnemonicCounter")); + const mnemonicCounter = new aesJs.Counter(mnemonicIv); + const mnemonicAesCtr = new aesJs.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter); + const path = searchPath(data, "x-ethers/path") || defaultPath; + const locale = searchPath(data, "x-ethers/locale") || "en"; + const entropy = arrayify(mnemonicAesCtr.decrypt(mnemonicCiphertext)); + try { + const mnemonic = entropyToMnemonic(entropy, locale); + const node = HDNode.fromMnemonic(mnemonic, null, locale).derivePath(path); + if (node.privateKey != account.privateKey) { + throw new Error("mnemonic mismatch"); + } + account.mnemonic = node.mnemonic; + } catch (error) { + if (error.code !== Logger.errors.INVALID_ARGUMENT || error.argument !== "wordlist") { + throw error; + } + } } - get byteLength() { - return this.bytes.byteLength; + return new KeystoreAccount(account); +} +function pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc) { + return arrayify(pbkdf2(passwordBytes, salt, count, dkLen, prfFunc)); +} +function pbkdf22(passwordBytes, salt, count, dkLen, prfFunc) { + return Promise.resolve(pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc)); +} +function _computeKdfKey(data, password, pbkdf2Func, scryptFunc, progressCallback) { + const passwordBytes = getPassword(password); + const kdf = searchPath(data, "crypto/kdf"); + if (kdf && typeof kdf === "string") { + const throwError = function(name, value) { + return logger$13.throwArgumentError("invalid key-derivation function parameters", name, value); + }; + if (kdf.toLowerCase() === "scrypt") { + const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt")); + const N = parseInt(searchPath(data, "crypto/kdfparams/n")); + const r = parseInt(searchPath(data, "crypto/kdfparams/r")); + const p = parseInt(searchPath(data, "crypto/kdfparams/p")); + if (!N || !r || !p) { + throwError("kdf", kdf); + } + if ((N & N - 1) !== 0) { + throwError("N", N); + } + const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen")); + if (dkLen !== 32) { + throwError("dklen", dkLen); + } + return scryptFunc(passwordBytes, salt, N, r, p, 64, progressCallback); + } else if (kdf.toLowerCase() === "pbkdf2") { + const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt")); + let prfFunc = null; + const prf = searchPath(data, "crypto/kdfparams/prf"); + if (prf === "hmac-sha256") { + prfFunc = "sha256"; + } else if (prf === "hmac-sha512") { + prfFunc = "sha512"; + } else { + throwError("prf", prf); + } + const count = parseInt(searchPath(data, "crypto/kdfparams/c")); + const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen")); + if (dkLen !== 32) { + throwError("dklen", dkLen); + } + return pbkdf2Func(passwordBytes, salt, count, dkLen, prfFunc); + } } - toV0() { - switch(this.version){ - case 0: - { - return this; - } - case 1: - { - const { code, multihash } = this; - if (code !== DAG_PB_CODE) { - throw new Error("Cannot convert a non dag-pb CID to CIDv0"); - } - if (multihash.code !== SHA_256_CODE) { - throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); - } - return CID.createV0(multihash); - } - default: - { - throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); - } + return logger$13.throwArgumentError("unsupported key-derivation function", "kdf", kdf); +} +function decryptSync(json, password) { + const data = JSON.parse(json); + const key = _computeKdfKey(data, password, pbkdf2Sync, scrypt.syncScrypt); + return _getAccount(data, key); +} +function decrypt$1(json, password, progressCallback) { + return __awaiter5(this, void 0, void 0, function*() { + const data = JSON.parse(json); + const key = yield _computeKdfKey(data, password, pbkdf22, scrypt.scrypt, progressCallback); + return _getAccount(data, key); + }); +} +function encrypt(account, password, options, progressCallback) { + try { + if (getAddress(account.address) !== computeAddress(account.privateKey)) { + throw new Error("address/privateKey mismatch"); + } + if (hasMnemonic(account)) { + const mnemonic = account.mnemonic; + const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path || defaultPath); + if (node.privateKey != account.privateKey) { + throw new Error("mnemonic mismatch"); + } + } + } catch (e) { + return Promise.reject(e); + } + if (typeof options === "function" && !progressCallback) { + progressCallback = options; + options = {}; + } + if (!options) { + options = {}; + } + const privateKey = arrayify(account.privateKey); + const passwordBytes = getPassword(password); + let entropy = null; + let path = null; + let locale = null; + if (hasMnemonic(account)) { + const srcMnemonic = account.mnemonic; + entropy = arrayify(mnemonicToEntropy(srcMnemonic.phrase, srcMnemonic.locale || "en")); + path = srcMnemonic.path || defaultPath; + locale = srcMnemonic.locale || "en"; + } + let client = options.client; + if (!client) { + client = "ethers.js"; + } + let salt = null; + if (options.salt) { + salt = arrayify(options.salt); + } else { + salt = randomBytes(32); + } + let iv = null; + if (options.iv) { + iv = arrayify(options.iv); + if (iv.length !== 16) { + throw new Error("invalid iv"); } + } else { + iv = randomBytes(16); } - toV1() { - switch(this.version){ - case 0: - { - const { code, digest: digest$1 } = this.multihash; - const multihash = create(code, digest$1); - return CID.createV1(this.code, multihash); + let uuidRandom = null; + if (options.uuid) { + uuidRandom = arrayify(options.uuid); + if (uuidRandom.length !== 16) { + throw new Error("invalid uuid"); + } + } else { + uuidRandom = randomBytes(16); + } + let N = 1 << 17, r = 8, p = 1; + if (options.scrypt) { + if (options.scrypt.N) { + N = options.scrypt.N; + } + if (options.scrypt.r) { + r = options.scrypt.r; + } + if (options.scrypt.p) { + p = options.scrypt.p; + } + } + return scrypt.scrypt(passwordBytes, salt, N, r, p, 64, progressCallback).then((key)=>{ + key = arrayify(key); + const derivedKey = key.slice(0, 16); + const macPrefix = key.slice(16, 32); + const mnemonicKey = key.slice(32, 64); + const counter = new aesJs.Counter(iv); + const aesCtr = new aesJs.ModeOfOperation.ctr(derivedKey, counter); + const ciphertext = arrayify(aesCtr.encrypt(privateKey)); + const mac = keccak256(concat([ + macPrefix, + ciphertext + ])); + const data = { + address: account.address.substring(2).toLowerCase(), + id: uuidV4(uuidRandom), + version: 3, + crypto: { + cipher: "aes-128-ctr", + cipherparams: { + iv: hexlify(iv).substring(2) + }, + ciphertext: hexlify(ciphertext).substring(2), + kdf: "scrypt", + kdfparams: { + salt: hexlify(salt).substring(2), + n: N, + dklen: 32, + p, + r + }, + mac: mac.substring(2) + } + }; + if (entropy) { + const mnemonicIv = randomBytes(16); + const mnemonicCounter = new aesJs.Counter(mnemonicIv); + const mnemonicAesCtr = new aesJs.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter); + const mnemonicCiphertext = arrayify(mnemonicAesCtr.encrypt(entropy)); + const now = new Date(); + const timestamp = now.getUTCFullYear() + "-" + zpad(now.getUTCMonth() + 1, 2) + "-" + zpad(now.getUTCDate(), 2) + "T" + zpad(now.getUTCHours(), 2) + "-" + zpad(now.getUTCMinutes(), 2) + "-" + zpad(now.getUTCSeconds(), 2) + ".0Z"; + data["x-ethers"] = { + client, + gethFilename: "UTC--" + timestamp + "--" + data.address, + mnemonicCounter: hexlify(mnemonicIv).substring(2), + mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2), + path, + locale, + version: "0.1" + }; + } + return JSON.stringify(data); + }); +} +function decryptJsonWallet(json, password, progressCallback) { + if (isCrowdsaleWallet(json)) { + if (progressCallback) { + progressCallback(0); + } + const account = decrypt(json, password); + if (progressCallback) { + progressCallback(1); + } + return Promise.resolve(account); + } + if (isKeystoreWallet(json)) { + return decrypt$1(json, password, progressCallback); + } + return Promise.reject(new Error("invalid JSON wallet")); +} +function decryptJsonWalletSync(json, password) { + if (isCrowdsaleWallet(json)) { + return decrypt(json, password); + } + if (isKeystoreWallet(json)) { + return decryptSync(json, password); + } + throw new Error("invalid JSON wallet"); +} +const version20 = "wallet/5.7.0"; +var __awaiter6 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger218 = new Logger(version20); +function isAccount(value) { + return value != null && isHexString(value.privateKey, 32) && value.address != null; +} +function hasMnemonic1(value) { + const mnemonic = value.mnemonic; + return mnemonic && mnemonic.phrase; +} +class Wallet extends Signer { + constructor(privateKey, provider){ + super(); + if (isAccount(privateKey)) { + const signingKey = new SigningKey(privateKey.privateKey); + defineReadOnly(this, "_signingKey", ()=>signingKey); + defineReadOnly(this, "address", computeAddress(this.publicKey)); + if (this.address !== getAddress(privateKey.address)) { + logger218.throwArgumentError("privateKey/address mismatch", "privateKey", "[REDACTED]"); + } + if (hasMnemonic1(privateKey)) { + const srcMnemonic = privateKey.mnemonic; + defineReadOnly(this, "_mnemonic", ()=>({ + phrase: srcMnemonic.phrase, + path: srcMnemonic.path || defaultPath, + locale: srcMnemonic.locale || "en" + })); + const mnemonic = this.mnemonic; + const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path); + if (computeAddress(node.privateKey) !== this.address) { + logger218.throwArgumentError("mnemonic/address mismatch", "privateKey", "[REDACTED]"); } - case 1: - { - return this; + } else { + defineReadOnly(this, "_mnemonic", ()=>null); + } + } else { + if (SigningKey.isSigningKey(privateKey)) { + if (privateKey.curve !== "secp256k1") { + logger218.throwArgumentError("unsupported curve; must be secp256k1", "privateKey", "[REDACTED]"); } - default: - { - throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`); + defineReadOnly(this, "_signingKey", ()=>privateKey); + } else { + if (typeof privateKey === "string") { + if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) { + privateKey = "0x" + privateKey; + } } + const signingKey = new SigningKey(privateKey); + defineReadOnly(this, "_signingKey", ()=>signingKey); + } + defineReadOnly(this, "_mnemonic", ()=>null); + defineReadOnly(this, "address", computeAddress(this.publicKey)); } + if (provider && !Provider.isProvider(provider)) { + logger218.throwArgumentError("invalid provider", "provider", provider); + } + defineReadOnly(this, "provider", provider || null); } - equals(other) { - return CID.equals(this, other); + get mnemonic() { + return this._mnemonic(); } - static equals(self1, other) { - const unknown = other; - return unknown != null && self1.code === unknown.code && self1.version === unknown.version && equals1(self1.multihash, unknown.multihash); + get privateKey() { + return this._signingKey().privateKey; } - toString(base) { - return format(this, base); + get publicKey() { + return this._signingKey().publicKey; } - toJSON() { - return { - "/": format(this) - }; + getAddress() { + return Promise.resolve(this.address); } - link() { - return this; + connect(provider) { + return new Wallet(this, provider); } - [(_a = Symbol.toStringTag, Symbol.for("nodejs.util.inspect.custom"))]() { - return `CID(${this.toString()})`; + signTransaction(transaction) { + return resolveProperties(transaction).then((tx)=>{ + if (tx.from != null) { + if (getAddress(tx.from) !== this.address) { + logger218.throwArgumentError("transaction from address mismatch", "transaction.from", transaction.from); + } + delete tx.from; + } + const signature = this._signingKey().signDigest(keccak256(serialize(tx))); + return serialize(tx, signature); + }); } - static asCID(input) { - if (input == null) { - return null; + signMessage(message) { + return __awaiter6(this, void 0, void 0, function*() { + return joinSignature(this._signingKey().signDigest(hashMessage(message))); + }); + } + _signTypedData(domain, types, value) { + return __awaiter6(this, void 0, void 0, function*() { + const populated = yield TypedDataEncoder.resolveNames(domain, types, value, (name)=>{ + if (this.provider == null) { + logger218.throwError("cannot resolve ENS names without a provider", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "resolveName", + value: name + }); + } + return this.provider.resolveName(name); + }); + return joinSignature(this._signingKey().signDigest(TypedDataEncoder.hash(populated.domain, types, populated.value))); + }); + } + encrypt(password, options, progressCallback) { + if (typeof options === "function" && !progressCallback) { + progressCallback = options; + options = {}; } - const value = input; - if (value instanceof CID) { - return value; - } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) { - const { version, code, multihash, bytes } = value; - return new CID(version, code, multihash, bytes != null ? bytes : encodeCID(version, code, multihash.bytes)); - } else if (value[cidSymbol] === true) { - const { version, multihash, code } = value; - const digest$1 = decode$2(multihash); - return CID.create(version, code, digest$1); - } else { - return null; + if (progressCallback && typeof progressCallback !== "function") { + throw new Error("invalid callback"); } - } - static create(version, code, digest) { - if (typeof code !== "number") { - throw new Error("String codecs are no longer supported"); + if (!options) { + options = {}; } - if (!(digest.bytes instanceof Uint8Array)) { - throw new Error("Invalid digest"); + return encrypt(this, password, options, progressCallback); + } + static createRandom(options) { + let entropy = randomBytes(16); + if (!options) { + options = {}; } - switch(version){ - case 0: - { - if (code !== DAG_PB_CODE) { - throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`); - } else { - return new CID(version, code, digest, digest.bytes); - } - } - case 1: - { - const bytes = encodeCID(version, code, digest.bytes); - return new CID(version, code, digest, bytes); - } - default: - { - throw new Error("Invalid version"); - } + if (options.extraEntropy) { + entropy = arrayify(hexDataSlice(keccak256(concat([ + entropy, + options.extraEntropy + ])), 0, 16)); } + const mnemonic = entropyToMnemonic(entropy, options.locale); + return Wallet.fromMnemonic(mnemonic, options.path, options.locale); } - static createV0(digest) { - return CID.create(0, DAG_PB_CODE, digest); + static fromEncryptedJson(json, password, progressCallback) { + return decryptJsonWallet(json, password, progressCallback).then((account)=>{ + return new Wallet(account); + }); } - static createV1(code, digest) { - return CID.create(1, code, digest); + static fromEncryptedJsonSync(json, password) { + return new Wallet(decryptJsonWalletSync(json, password)); } - static decode(bytes) { - const [cid, remainder] = CID.decodeFirst(bytes); - if (remainder.length !== 0) { - throw new Error("Incorrect length"); + static fromMnemonic(mnemonic, path, wordlist) { + if (!path) { + path = defaultPath; } - return cid; + return new Wallet(HDNode.fromMnemonic(mnemonic, null, wordlist).derivePath(path)); } - static decodeFirst(bytes) { - const specs = CID.inspectBytes(bytes); - const prefixSize = specs.size - specs.multihashSize; - const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); - if (multihashBytes.byteLength !== specs.multihashSize) { - throw new Error("Incorrect length"); +} +function verifyMessage(message, signature) { + return recoverAddress(hashMessage(message), signature); +} +function verifyTypedData(domain, types, value, signature) { + return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature); +} +const version21 = "networks/5.7.1"; +const logger219 = new Logger(version21); +function isRenetworkable(value) { + return value && typeof value.renetwork === "function"; +} +function ethDefaultProvider(network) { + const func = function(providers, options) { + if (options == null) { + options = {}; } - const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); - const digest$1 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); - const cid = specs.version === 0 ? CID.createV0(digest$1) : CID.createV1(specs.codec, digest$1); - return [ - cid, - bytes.subarray(specs.size) - ]; - } - static inspectBytes(initialBytes) { - let offset = 0; - const next = ()=>{ - const [i, length] = decode$1(initialBytes.subarray(offset)); - offset += length; - return i; - }; - let version = next(); - let codec = DAG_PB_CODE; - if (version === 18) { - version = 0; - offset = 0; - } else { - codec = next(); + const providerList = []; + if (providers.InfuraProvider && options.infura !== "-") { + try { + providerList.push(new providers.InfuraProvider(network, options.infura)); + } catch (error) {} } - if (version !== 0 && version !== 1) { - throw new RangeError(`Invalid CID version ${version}`); + if (providers.EtherscanProvider && options.etherscan !== "-") { + try { + providerList.push(new providers.EtherscanProvider(network, options.etherscan)); + } catch (error) {} } - const prefixSize = offset; - const multihashCode = next(); - const digestSize = next(); - const size = offset + digestSize; - const multihashSize = size - prefixSize; - return { - version, - codec, - multihashCode, - digestSize, - multihashSize, - size - }; - } - static parse(source, base) { - const [prefix, bytes] = parseCIDtoBytes(source, base); - const cid = CID.decode(bytes); - if (cid.version === 0 && source[0] !== "Q") { - throw Error("Version 0 CID string must not include multibase prefix"); + if (providers.AlchemyProvider && options.alchemy !== "-") { + try { + providerList.push(new providers.AlchemyProvider(network, options.alchemy)); + } catch (error) {} + } + if (providers.PocketProvider && options.pocket !== "-") { + const skip = [ + "goerli", + "ropsten", + "rinkeby", + "sepolia" + ]; + try { + const provider = new providers.PocketProvider(network, options.pocket); + if (provider.network && skip.indexOf(provider.network.name) === -1) { + providerList.push(provider); + } + } catch (error) {} } - baseCache(cid).set(prefix, source); - return cid; - } -} -function parseCIDtoBytes(source, base) { - switch(source[0]){ - case "Q": - { - const decoder = base != null ? base : base58btc; - return [ - base58btc.prefix, - decoder.decode(`${base58btc.prefix}${source}`) - ]; - } - case base58btc.prefix: - { - const decoder = base != null ? base : base58btc; - return [ - base58btc.prefix, - decoder.decode(source) - ]; - } - case base32.prefix: - { - const decoder = base != null ? base : base32; - return [ - base32.prefix, - decoder.decode(source) + if (providers.CloudflareProvider && options.cloudflare !== "-") { + try { + providerList.push(new providers.CloudflareProvider(network)); + } catch (error) {} + } + if (providers.AnkrProvider && options.ankr !== "-") { + try { + const skip = [ + "ropsten" ]; - } - default: - { - if (base == null) { - throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided"); + const provider = new providers.AnkrProvider(network, options.ankr); + if (provider.network && skip.indexOf(provider.network.name) === -1) { + providerList.push(provider); } - return [ - source[0], - base.decode(source) - ]; + } catch (error) {} + } + if (providerList.length === 0) { + return null; + } + if (providers.FallbackProvider) { + let quorum = 1; + if (options.quorum != null) { + quorum = options.quorum; + } else if (network === "homestead") { + quorum = 2; } - } -} -function toStringV0(bytes, cache2, base) { - const { prefix } = base; - if (prefix !== base58btc.prefix) { - throw Error(`Cannot string encode V0 in ${base.name} encoding`); - } - const cid = cache2.get(prefix); - if (cid == null) { - const cid2 = base.encode(bytes).slice(1); - cache2.set(prefix, cid2); - return cid2; - } else { - return cid; - } -} -function toStringV1(bytes, cache2, base) { - const { prefix } = base; - const cid = cache2.get(prefix); - if (cid == null) { - const cid2 = base.encode(bytes); - cache2.set(prefix, cid2); - return cid2; - } else { - return cid; - } -} -const DAG_PB_CODE = 112; -const SHA_256_CODE = 18; -function encodeCID(version, code, multihash) { - const codeOffset = encodingLength(version); - const hashOffset = codeOffset + encodingLength(code); - const bytes = new Uint8Array(hashOffset + multihash.byteLength); - encodeTo(version, bytes, 0); - encodeTo(code, bytes, codeOffset); - bytes.set(multihash, hashOffset); - return bytes; -} -const cidSymbol = Symbol.for("@ipld/js-cid/CID"); -const CID_CBOR_TAG = 42; -function toByteView(buf) { - if (buf instanceof ArrayBuffer) { - return new Uint8Array(buf, 0, buf.byteLength); - } - return buf; + return new providers.FallbackProvider(providerList, quorum); + } + return providerList[0]; + }; + func.renetwork = function(network2) { + return ethDefaultProvider(network2); + }; + return func; } -function cidEncoder(obj) { - if (obj.asCID !== obj && obj["/"] !== obj.bytes) { +function etcDefaultProvider(url, network) { + const func = function(providers, options) { + if (providers.JsonRpcProvider) { + return new providers.JsonRpcProvider(url, network); + } return null; + }; + func.renetwork = function(network2) { + return etcDefaultProvider(url, network2); + }; + return func; +} +const homestead = { + chainId: 1, + ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + name: "homestead", + _defaultProvider: ethDefaultProvider("homestead") +}; +const ropsten = { + chainId: 3, + ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + name: "ropsten", + _defaultProvider: ethDefaultProvider("ropsten") +}; +const classicMordor = { + chainId: 63, + name: "classicMordor", + _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/mordor", "classicMordor") +}; +const networks = { + unspecified: { + chainId: 0, + name: "unspecified" + }, + homestead, + mainnet: homestead, + morden: { + chainId: 2, + name: "morden" + }, + ropsten, + testnet: ropsten, + rinkeby: { + chainId: 4, + ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + name: "rinkeby", + _defaultProvider: ethDefaultProvider("rinkeby") + }, + kovan: { + chainId: 42, + name: "kovan", + _defaultProvider: ethDefaultProvider("kovan") + }, + goerli: { + chainId: 5, + ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", + name: "goerli", + _defaultProvider: ethDefaultProvider("goerli") + }, + kintsugi: { + chainId: 1337702, + name: "kintsugi" + }, + sepolia: { + chainId: 11155111, + name: "sepolia", + _defaultProvider: ethDefaultProvider("sepolia") + }, + classic: { + chainId: 61, + name: "classic", + _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/etc", "classic") + }, + classicMorden: { + chainId: 62, + name: "classicMorden" + }, + classicMordor, + classicTestnet: classicMordor, + classicKotti: { + chainId: 6, + name: "classicKotti", + _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/kotti", "classicKotti") + }, + xdai: { + chainId: 100, + name: "xdai" + }, + matic: { + chainId: 137, + name: "matic", + _defaultProvider: ethDefaultProvider("matic") + }, + maticmum: { + chainId: 80001, + name: "maticmum" + }, + optimism: { + chainId: 10, + name: "optimism", + _defaultProvider: ethDefaultProvider("optimism") + }, + "optimism-kovan": { + chainId: 69, + name: "optimism-kovan" + }, + "optimism-goerli": { + chainId: 420, + name: "optimism-goerli" + }, + arbitrum: { + chainId: 42161, + name: "arbitrum" + }, + "arbitrum-rinkeby": { + chainId: 421611, + name: "arbitrum-rinkeby" + }, + "arbitrum-goerli": { + chainId: 421613, + name: "arbitrum-goerli" + }, + bnb: { + chainId: 56, + name: "bnb" + }, + bnbt: { + chainId: 97, + name: "bnbt" } - const cid2 = CID.asCID(obj); - if (!cid2) { +}; +function getNetwork(network) { + if (network == null) { return null; } - const bytes = new Uint8Array(cid2.bytes.byteLength + 1); - bytes.set(cid2.bytes, 1); - return [ - new Token(Type.tag, 42), - new Token(Type.bytes, bytes) - ]; -} -function undefinedEncoder() { - throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded"); -} -function numberEncoder(num) { - if (Number.isNaN(num)) { - throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded"); + if (typeof network === "number") { + for(const name in networks){ + const standard2 = networks[name]; + if (standard2.chainId === network) { + return { + name: standard2.name, + chainId: standard2.chainId, + ensAddress: standard2.ensAddress || null, + _defaultProvider: standard2._defaultProvider || null + }; + } + } + return { + chainId: network, + name: "unknown" + }; } - if (num === Infinity || num === -Infinity) { - throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded"); + if (typeof network === "string") { + const standard2 = networks[network]; + if (standard2 == null) { + return null; + } + return { + name: standard2.name, + chainId: standard2.chainId, + ensAddress: standard2.ensAddress, + _defaultProvider: standard2._defaultProvider || null + }; } - return null; -} -const _encodeOptions = { - float64: true, - typeEncoders: { - Object: cidEncoder, - undefined: undefinedEncoder, - number: numberEncoder + const standard = networks[network.name]; + if (!standard) { + if (typeof network.chainId !== "number") { + logger219.throwArgumentError("invalid network chainId", "network", network); + } + return network; } -}; -({ - ..._encodeOptions, - typeEncoders: { - ..._encodeOptions.typeEncoders + if (network.chainId !== 0 && network.chainId !== standard.chainId) { + logger219.throwArgumentError("network chainId mismatch", "network", network); } -}); -function cidDecoder(bytes) { - if (bytes[0] !== 0) { - throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00"); + let defaultProvider = network._defaultProvider || null; + if (defaultProvider == null && standard._defaultProvider) { + if (isRenetworkable(standard._defaultProvider)) { + defaultProvider = standard._defaultProvider.renetwork(network); + } else { + defaultProvider = standard._defaultProvider; + } } - return CID.decode(bytes.subarray(1)); + return { + name: network.name, + chainId: standard.chainId, + ensAddress: network.ensAddress || standard.ensAddress || null, + _defaultProvider: defaultProvider + }; } -const _decodeOptions = { - allowIndefinite: false, - coerceUndefinedToNull: true, - allowNaN: false, - allowInfinity: false, - allowBigInt: true, - strict: true, - useMaps: false, - rejectDuplicateMapKeys: true, - tags: [] +const version22 = "web/5.7.1"; +var __awaiter7 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; -_decodeOptions.tags[CID_CBOR_TAG] = cidDecoder; -({ - ..._decodeOptions, - tags: _decodeOptions.tags.slice() -}); -const encode3 = (node)=>encode(node, _encodeOptions); -const decode4 = (data)=>decode1(toByteView(data), _decodeOptions); -var encode_11 = encode4; -var MSB1 = 128, REST2 = 127, MSBALL1 = ~REST2, INT1 = Math.pow(2, 31); -function encode4(num, out, offset) { - if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) { - encode4.bytes = 0; - throw new RangeError("Could not encode varint"); +function getUrl(href, options) { + return __awaiter7(this, void 0, void 0, function*() { + if (options == null) { + options = {}; + } + const request = { + method: options.method || "GET", + headers: options.headers || {}, + body: options.body || void 0 + }; + if (options.skipFetchSetup !== true) { + request.mode = "cors"; + request.cache = "no-cache"; + request.credentials = "same-origin"; + request.redirect = "follow"; + request.referrer = "client"; + } + if (options.fetchOptions != null) { + const opts = options.fetchOptions; + if (opts.mode) { + request.mode = opts.mode; + } + if (opts.cache) { + request.cache = opts.cache; + } + if (opts.credentials) { + request.credentials = opts.credentials; + } + if (opts.redirect) { + request.redirect = opts.redirect; + } + if (opts.referrer) { + request.referrer = opts.referrer; + } + } + const response = yield fetch(href, request); + const body = yield response.arrayBuffer(); + const headers = {}; + if (response.headers.forEach) { + response.headers.forEach((value, key)=>{ + headers[key.toLowerCase()] = value; + }); + } else { + response.headers.keys().forEach((key)=>{ + headers[key.toLowerCase()] = response.headers.get(key); + }); + } + return { + headers, + statusCode: response.status, + statusMessage: response.statusText, + body: arrayify(new Uint8Array(body)) + }; + }); +} +var __awaiter$1 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); } - out = out || []; - offset = offset || 0; - var oldOffset = offset; - while(num >= INT1){ - out[offset++] = num & 255 | MSB1; - num /= 128; + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger220 = new Logger(version22); +function staller(duration) { + return new Promise((resolve)=>{ + setTimeout(resolve, duration); + }); +} +function bodyify(value, type) { + if (value == null) { + return null; } - while(num & MSBALL1){ - out[offset++] = num & 255 | MSB1; - num >>>= 7; + if (typeof value === "string") { + return value; } - out[offset] = num | 0; - encode4.bytes = offset - oldOffset + 1; - return out; -} -var decode5 = read1; -var MSB$11 = 128, REST$11 = 127; -function read1(buf, offset) { - var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; - do { - if (counter >= l || shift > 49) { - read1.bytes = 0; - throw new RangeError("Could not decode varint"); + if (isBytesLike(value)) { + if (type && (type.split("/")[0] === "text" || type.split(";")[0].trim() === "application/json")) { + try { + return toUtf8String(value); + } catch (error) {} } - b = buf[counter++]; - res += shift < 28 ? (b & REST$11) << shift : (b & REST$11) * Math.pow(2, shift); - shift += 7; - }while (b >= MSB$11) - read1.bytes = counter - offset; - return res; -} -var N11 = Math.pow(2, 7); -var N21 = Math.pow(2, 14); -var N31 = Math.pow(2, 21); -var N41 = Math.pow(2, 28); -var N51 = Math.pow(2, 35); -var N61 = Math.pow(2, 42); -var N71 = Math.pow(2, 49); -var N81 = Math.pow(2, 56); -var N91 = Math.pow(2, 63); -var length1 = function(value) { - return value < N11 ? 1 : value < N21 ? 2 : value < N31 ? 3 : value < N41 ? 4 : value < N51 ? 5 : value < N61 ? 6 : value < N71 ? 7 : value < N81 ? 8 : value < N91 ? 9 : 10; -}; -var varint1 = { - encode: encode_11, - decode: decode5, - encodingLength: length1 -}; -varint1.encode; -const CIDV0_BYTES = { - SHA2_256: 18, - LENGTH: 32, - DAG_PB: 112 -}; -const V2_HEADER_LENGTH = 16 + 8 + 8 + 8; -function decodeVarint(bytes, seeker) { - if (!bytes.length) { - throw new Error("Unexpected end of data"); + return hexlify(value); } - const i = varint1.decode(bytes); - seeker.seek(varint1.decode.bytes); - return i; -} -function decodeV2Header(bytes) { - const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - let offset = 0; - const header = { - version: 2, - characteristics: [ - dv.getBigUint64(offset, true), - dv.getBigUint64(offset += 8, true) - ], - dataOffset: Number(dv.getBigUint64(offset += 8, true)), - dataSize: Number(dv.getBigUint64(offset += 8, true)), - indexOffset: Number(dv.getBigUint64(offset += 8, true)) - }; - return header; + return value; } -function getMultihashLength(bytes) { - varint1.decode(bytes); - const codeLength = varint1.decode.bytes; - const length = varint1.decode(bytes.subarray(varint1.decode.bytes)); - const lengthLength = varint1.decode.bytes; - const mhLength = codeLength + lengthLength + length; - return mhLength; +function unpercent(value) { + return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code)=>{ + return String.fromCharCode(parseInt(code, 16)); + })); } -const Kinds = { - Null: (obj)=>obj === null ? obj : void 0, - Int: (obj)=>Number.isInteger(obj) ? obj : void 0, - Float: (obj)=>typeof obj === "number" && Number.isFinite(obj) ? obj : void 0, - String: (obj)=>typeof obj === "string" ? obj : void 0, - Bool: (obj)=>typeof obj === "boolean" ? obj : void 0, - Bytes: (obj)=>obj instanceof Uint8Array ? obj : void 0, - Link: (obj)=>obj !== null && typeof obj === "object" && obj.asCID === obj ? obj : void 0, - List: (obj)=>Array.isArray(obj) ? obj : void 0, - Map: (obj)=>obj !== null && typeof obj === "object" && obj.asCID !== obj && !Array.isArray(obj) && !(obj instanceof Uint8Array) ? obj : void 0 -}; -const Types = { - "CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)": Kinds.Link, - "CarV1HeaderOrV2Pragma > roots (anon)": (obj)=>{ - if (Kinds.List(obj) === void 0) { - return void 0; - } - for(let i = 0; i < obj.length; i++){ - let v = obj[i]; - v = Types["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v); - if (v === void 0) { - return void 0; - } - if (v !== obj[i]) { - const ret = obj.slice(0, i); - for(let j = i; j < obj.length; j++){ - let v2 = obj[j]; - v2 = Types["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v2); - if (v2 === void 0) { - return void 0; - } - ret.push(v2); +function _fetchData(connection, body, processFunc) { + const attemptLimit = typeof connection === "object" && connection.throttleLimit != null ? connection.throttleLimit : 12; + logger220.assertArgument(attemptLimit > 0 && attemptLimit % 1 === 0, "invalid connection throttle limit", "connection.throttleLimit", attemptLimit); + const throttleCallback = typeof connection === "object" ? connection.throttleCallback : null; + const throttleSlotInterval = typeof connection === "object" && typeof connection.throttleSlotInterval === "number" ? connection.throttleSlotInterval : 100; + logger220.assertArgument(throttleSlotInterval > 0 && throttleSlotInterval % 1 === 0, "invalid connection throttle slot interval", "connection.throttleSlotInterval", throttleSlotInterval); + const errorPassThrough = typeof connection === "object" ? !!connection.errorPassThrough : false; + const headers = {}; + let url = null; + const options = { + method: "GET" + }; + let allow304 = false; + let timeout = 2 * 60 * 1e3; + if (typeof connection === "string") { + url = connection; + } else if (typeof connection === "object") { + if (connection == null || connection.url == null) { + logger220.throwArgumentError("missing URL", "connection.url", connection); + } + url = connection.url; + if (typeof connection.timeout === "number" && connection.timeout > 0) { + timeout = connection.timeout; + } + if (connection.headers) { + for(const key in connection.headers){ + headers[key.toLowerCase()] = { + key, + value: String(connection.headers[key]) + }; + if ([ + "if-none-match", + "if-modified-since" + ].indexOf(key.toLowerCase()) >= 0) { + allow304 = true; } - return ret; } } - return obj; - }, - Int: Kinds.Int, - CarV1HeaderOrV2Pragma: (obj)=>{ - if (Kinds.Map(obj) === void 0) { - return void 0; + options.allowGzip = !!connection.allowGzip; + if (connection.user != null && connection.password != null) { + if (url.substring(0, 6) !== "https:" && connection.allowInsecureAuthentication !== true) { + logger220.throwError("basic authentication requires a secure https url", Logger.errors.INVALID_ARGUMENT, { + argument: "url", + url, + user: connection.user, + password: "[REDACTED]" + }); + } + const authorization = connection.user + ":" + connection.password; + headers["authorization"] = { + key: "Authorization", + value: "Basic " + encode1(toUtf8Bytes(authorization)) + }; } - const entries = Object.entries(obj); - let ret = obj; - let requiredCount = 1; - for(let i = 0; i < entries.length; i++){ - const [key, value] = entries[i]; - switch(key){ - case "roots": - { - const v = Types["CarV1HeaderOrV2Pragma > roots (anon)"](obj[key]); - if (v === void 0) { - return void 0; - } - if (v !== value || ret !== obj) { - if (ret === obj) { - ret = {}; - for(let j = 0; j < i; j++){ - ret[entries[j][0]] = entries[j][1]; + if (connection.skipFetchSetup != null) { + options.skipFetchSetup = !!connection.skipFetchSetup; + } + if (connection.fetchOptions != null) { + options.fetchOptions = shallowCopy(connection.fetchOptions); + } + } + const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); + const dataMatch = url ? url.match(reData) : null; + if (dataMatch) { + try { + const response = { + statusCode: 200, + statusMessage: "OK", + headers: { + "content-type": dataMatch[1] || "text/plain" + }, + body: dataMatch[2] ? decode2(dataMatch[3]) : unpercent(dataMatch[3]) + }; + let result = response.body; + if (processFunc) { + result = processFunc(response.body, response); + } + return Promise.resolve(result); + } catch (error) { + logger220.throwError("processing response error", Logger.errors.SERVER_ERROR, { + body: bodyify(dataMatch[1], dataMatch[2]), + error, + requestBody: null, + requestMethod: "GET", + url + }); + } + } + if (body) { + options.method = "POST"; + options.body = body; + if (headers["content-type"] == null) { + headers["content-type"] = { + key: "Content-Type", + value: "application/octet-stream" + }; + } + if (headers["content-length"] == null) { + headers["content-length"] = { + key: "Content-Length", + value: String(body.length) + }; + } + } + const flatHeaders = {}; + Object.keys(headers).forEach((key)=>{ + const header = headers[key]; + flatHeaders[header.key] = header.value; + }); + options.headers = flatHeaders; + const runningTimeout = function() { + let timer = null; + const promise = new Promise(function(resolve, reject) { + if (timeout) { + timer = setTimeout(()=>{ + if (timer == null) { + return; + } + timer = null; + reject(logger220.makeError("timeout", Logger.errors.TIMEOUT, { + requestBody: bodyify(options.body, flatHeaders["content-type"]), + requestMethod: options.method, + timeout, + url + })); + }, timeout); + } + }); + const cancel = function() { + if (timer == null) { + return; + } + clearTimeout(timer); + timer = null; + }; + return { + promise, + cancel + }; + }(); + const runningFetch = function() { + return __awaiter$1(this, void 0, void 0, function*() { + for(let attempt = 0; attempt < attemptLimit; attempt++){ + let response = null; + try { + response = yield getUrl(url, options); + if (attempt < attemptLimit) { + if (response.statusCode === 301 || response.statusCode === 302) { + const location = response.headers.location || ""; + if (options.method === "GET" && location.match(/^https:/)) { + url = response.headers.location; + continue; + } + } else if (response.statusCode === 429) { + let tryAgain = true; + if (throttleCallback) { + tryAgain = yield throttleCallback(attempt, url); + } + if (tryAgain) { + let stall = 0; + const retryAfter = response.headers["retry-after"]; + if (typeof retryAfter === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { + stall = parseInt(retryAfter) * 1e3; + } else { + stall = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt))); } + yield staller(stall); + continue; } - ret.roots = v; } } - break; - case "version": - { - requiredCount--; - const v = Types.Int(obj[key]); - if (v === void 0) { - return void 0; - } - if (v !== value || ret !== obj) { - if (ret === obj) { - ret = {}; - for(let j = 0; j < i; j++){ - ret[entries[j][0]] = entries[j][1]; - } + } catch (error) { + response = error.response; + if (response == null) { + runningTimeout.cancel(); + logger220.throwError("missing response", Logger.errors.SERVER_ERROR, { + requestBody: bodyify(options.body, flatHeaders["content-type"]), + requestMethod: options.method, + serverError: error, + url + }); + } + } + let body2 = response.body; + if (allow304 && response.statusCode === 304) { + body2 = null; + } else if (!errorPassThrough && (response.statusCode < 200 || response.statusCode >= 300)) { + runningTimeout.cancel(); + logger220.throwError("bad response", Logger.errors.SERVER_ERROR, { + status: response.statusCode, + headers: response.headers, + body: bodyify(body2, response.headers ? response.headers["content-type"] : null), + requestBody: bodyify(options.body, flatHeaders["content-type"]), + requestMethod: options.method, + url + }); + } + if (processFunc) { + try { + const result = yield processFunc(body2, response); + runningTimeout.cancel(); + return result; + } catch (error) { + if (error.throttleRetry && attempt < attemptLimit) { + let tryAgain = true; + if (throttleCallback) { + tryAgain = yield throttleCallback(attempt, url); + } + if (tryAgain) { + const timeout2 = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt))); + yield staller(timeout2); + continue; } - ret.version = v; } + runningTimeout.cancel(); + logger220.throwError("processing response error", Logger.errors.SERVER_ERROR, { + body: bodyify(body2, response.headers ? response.headers["content-type"] : null), + error, + requestBody: bodyify(options.body, flatHeaders["content-type"]), + requestMethod: options.method, + url + }); } - break; - default: - return void 0; + } + runningTimeout.cancel(); + return body2; + } + return logger220.throwError("failed response", Logger.errors.SERVER_ERROR, { + requestBody: bodyify(options.body, flatHeaders["content-type"]), + requestMethod: options.method, + url + }); + }); + }(); + return Promise.race([ + runningTimeout.promise, + runningFetch + ]); +} +function fetchJson(connection, json, processFunc) { + let processJsonFunc = (value, response)=>{ + let result = null; + if (value != null) { + try { + result = JSON.parse(toUtf8String(value)); + } catch (error) { + logger220.throwError("invalid JSON", Logger.errors.SERVER_ERROR, { + body: value, + error + }); } } - if (requiredCount > 0) { - return void 0; + if (processFunc) { + result = processFunc(result, response); } - return ret; - } -}; -const Reprs = { - "CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)": Kinds.Link, - "CarV1HeaderOrV2Pragma > roots (anon)": (obj)=>{ - if (Kinds.List(obj) === void 0) { - return void 0; + return result; + }; + let body = null; + if (json != null) { + body = toUtf8Bytes(json); + const updated = typeof connection === "string" ? { + url: connection + } : shallowCopy(connection); + if (updated.headers) { + const hasContentType = Object.keys(updated.headers).filter((k)=>k.toLowerCase() === "content-type").length !== 0; + if (!hasContentType) { + updated.headers = shallowCopy(updated.headers); + updated.headers["content-type"] = "application/json"; + } + } else { + updated.headers = { + "content-type": "application/json" + }; } - for(let i = 0; i < obj.length; i++){ - let v = obj[i]; - v = Reprs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v); - if (v === void 0) { - return void 0; + connection = updated; + } + return _fetchData(connection, body, processJsonFunc); +} +function poll(func, options) { + if (!options) { + options = {}; + } + options = shallowCopy(options); + if (options.floor == null) { + options.floor = 0; + } + if (options.ceiling == null) { + options.ceiling = 1e4; + } + if (options.interval == null) { + options.interval = 250; + } + return new Promise(function(resolve, reject) { + let timer = null; + let done = false; + const cancel = ()=>{ + if (done) { + return false; } - if (v !== obj[i]) { - const ret = obj.slice(0, i); - for(let j = i; j < obj.length; j++){ - let v2 = obj[j]; - v2 = Reprs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v2); - if (v2 === void 0) { - return void 0; + done = true; + if (timer) { + clearTimeout(timer); + } + return true; + }; + if (options.timeout) { + timer = setTimeout(()=>{ + if (cancel()) { + reject(new Error("timeout")); + } + }, options.timeout); + } + const retryLimit = options.retryLimit; + let attempt = 0; + function check() { + return func().then(function(result) { + if (result !== void 0) { + if (cancel()) { + resolve(result); } - ret.push(v2); + } else if (options.oncePoll) { + options.oncePoll.once("poll", check); + } else if (options.onceBlock) { + options.onceBlock.once("block", check); + } else if (!done) { + attempt++; + if (attempt > retryLimit) { + if (cancel()) { + reject(new Error("retry limit reached")); + } + return; + } + let timeout = options.interval * parseInt(String(Math.random() * Math.pow(2, attempt))); + if (timeout < options.floor) { + timeout = options.floor; + } + if (timeout > options.ceiling) { + timeout = options.ceiling; + } + setTimeout(check, timeout); } - return ret; + return null; + }, function(error) { + if (cancel()) { + reject(error); + } + }); + } + check(); + }); +} +var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; +var ALPHABET_MAP = {}; +for(var z = 0; z < ALPHABET.length; z++){ + var x = ALPHABET.charAt(z); + if (ALPHABET_MAP[x] !== void 0) throw new TypeError(x + " is ambiguous"); + ALPHABET_MAP[x] = z; +} +function polymodStep(pre) { + var b = pre >> 25; + return (pre & 33554431) << 5 ^ -(b >> 0 & 1) & 996825010 ^ -(b >> 1 & 1) & 642813549 ^ -(b >> 2 & 1) & 513874426 ^ -(b >> 3 & 1) & 1027748829 ^ -(b >> 4 & 1) & 705979059; +} +function prefixChk(prefix) { + var chk = 1; + for(var i = 0; i < prefix.length; ++i){ + var c = prefix.charCodeAt(i); + if (c < 33 || c > 126) return "Invalid prefix (" + prefix + ")"; + chk = polymodStep(chk) ^ c >> 5; + } + chk = polymodStep(chk); + for(i = 0; i < prefix.length; ++i){ + var v = prefix.charCodeAt(i); + chk = polymodStep(chk) ^ v & 31; + } + return chk; +} +function encode2(prefix, words, LIMIT) { + LIMIT = LIMIT || 90; + if (prefix.length + 7 + words.length > LIMIT) throw new TypeError("Exceeds length limit"); + prefix = prefix.toLowerCase(); + var chk = prefixChk(prefix); + if (typeof chk === "string") throw new Error(chk); + var result = prefix + "1"; + for(var i = 0; i < words.length; ++i){ + var x = words[i]; + if (x >> 5 !== 0) throw new Error("Non 5-bit word"); + chk = polymodStep(chk) ^ x; + result += ALPHABET.charAt(x); + } + for(i = 0; i < 6; ++i){ + chk = polymodStep(chk); + } + chk ^= 1; + for(i = 0; i < 6; ++i){ + var v = chk >> (5 - i) * 5 & 31; + result += ALPHABET.charAt(v); + } + return result; +} +function __decode(str, LIMIT) { + LIMIT = LIMIT || 90; + if (str.length < 8) return str + " too short"; + if (str.length > LIMIT) return "Exceeds length limit"; + var lowered = str.toLowerCase(); + var uppered = str.toUpperCase(); + if (str !== lowered && str !== uppered) return "Mixed-case string " + str; + str = lowered; + var split = str.lastIndexOf("1"); + if (split === -1) return "No separator character for " + str; + if (split === 0) return "Missing prefix for " + str; + var prefix = str.slice(0, split); + var wordChars = str.slice(split + 1); + if (wordChars.length < 6) return "Data too short"; + var chk = prefixChk(prefix); + if (typeof chk === "string") return chk; + var words = []; + for(var i = 0; i < wordChars.length; ++i){ + var c = wordChars.charAt(i); + var v = ALPHABET_MAP[c]; + if (v === void 0) return "Unknown character " + c; + chk = polymodStep(chk) ^ v; + if (i + 6 >= wordChars.length) continue; + words.push(v); + } + if (chk !== 1) return "Invalid checksum for " + str; + return { + prefix, + words + }; +} +function decodeUnsafe() { + var res = __decode.apply(null, arguments); + if (typeof res === "object") return res; +} +function decode3(str) { + var res = __decode.apply(null, arguments); + if (typeof res === "object") return res; + throw new Error(res); +} +function convert(data, inBits, outBits, pad) { + var value = 0; + var bits = 0; + var maxV = (1 << outBits) - 1; + var result = []; + for(var i = 0; i < data.length; ++i){ + value = value << inBits | data[i]; + bits += inBits; + while(bits >= outBits){ + bits -= outBits; + result.push(value >> bits & maxV); + } + } + if (pad) { + if (bits > 0) { + result.push(value << outBits - bits & maxV); + } + } else { + if (bits >= inBits) return "Excess padding"; + if (value << outBits - bits & maxV) return "Non-zero padding"; + } + return result; +} +function toWordsUnsafe(bytes) { + var res = convert(bytes, 8, 5, true); + if (Array.isArray(res)) return res; +} +function toWords(bytes) { + var res = convert(bytes, 8, 5, true); + if (Array.isArray(res)) return res; + throw new Error(res); +} +function fromWordsUnsafe(words) { + var res = convert(words, 5, 8, false); + if (Array.isArray(res)) return res; +} +function fromWords(words) { + var res = convert(words, 5, 8, false); + if (Array.isArray(res)) return res; + throw new Error(res); +} +var bech32 = { + decodeUnsafe, + decode: decode3, + encode: encode2, + toWordsUnsafe, + toWords, + fromWordsUnsafe, + fromWords +}; +bech32.decode; +bech32.decodeUnsafe; +bech32.encode; +bech32.fromWords; +bech32.fromWordsUnsafe; +bech32.toWords; +bech32.toWordsUnsafe; +const version23 = "providers/5.7.2"; +const logger221 = new Logger(version23); +class Formatter { + constructor(){ + this.formats = this.getDefaultFormats(); + } + getDefaultFormats() { + const formats = {}; + const address2 = this.address.bind(this); + const bigNumber = this.bigNumber.bind(this); + const blockTag = this.blockTag.bind(this); + const data = this.data.bind(this); + const hash2 = this.hash.bind(this); + const hex = this.hex.bind(this); + const number = this.number.bind(this); + const type = this.type.bind(this); + const strictData = (v)=>{ + return this.data(v, true); + }; + formats.transaction = { + hash: hash2, + type, + accessList: Formatter.allowNull(this.accessList.bind(this), null), + blockHash: Formatter.allowNull(hash2, null), + blockNumber: Formatter.allowNull(number, null), + transactionIndex: Formatter.allowNull(number, null), + confirmations: Formatter.allowNull(number, null), + from: address2, + gasPrice: Formatter.allowNull(bigNumber), + maxPriorityFeePerGas: Formatter.allowNull(bigNumber), + maxFeePerGas: Formatter.allowNull(bigNumber), + gasLimit: bigNumber, + to: Formatter.allowNull(address2, null), + value: bigNumber, + nonce: number, + data, + r: Formatter.allowNull(this.uint256), + s: Formatter.allowNull(this.uint256), + v: Formatter.allowNull(number), + creates: Formatter.allowNull(address2, null), + raw: Formatter.allowNull(data) + }; + formats.transactionRequest = { + from: Formatter.allowNull(address2), + nonce: Formatter.allowNull(number), + gasLimit: Formatter.allowNull(bigNumber), + gasPrice: Formatter.allowNull(bigNumber), + maxPriorityFeePerGas: Formatter.allowNull(bigNumber), + maxFeePerGas: Formatter.allowNull(bigNumber), + to: Formatter.allowNull(address2), + value: Formatter.allowNull(bigNumber), + data: Formatter.allowNull(strictData), + type: Formatter.allowNull(number), + accessList: Formatter.allowNull(this.accessList.bind(this), null) + }; + formats.receiptLog = { + transactionIndex: number, + blockNumber: number, + transactionHash: hash2, + address: address2, + topics: Formatter.arrayOf(hash2), + data, + logIndex: number, + blockHash: hash2 + }; + formats.receipt = { + to: Formatter.allowNull(this.address, null), + from: Formatter.allowNull(this.address, null), + contractAddress: Formatter.allowNull(address2, null), + transactionIndex: number, + root: Formatter.allowNull(hex), + gasUsed: bigNumber, + logsBloom: Formatter.allowNull(data), + blockHash: hash2, + transactionHash: hash2, + logs: Formatter.arrayOf(this.receiptLog.bind(this)), + blockNumber: number, + confirmations: Formatter.allowNull(number, null), + cumulativeGasUsed: bigNumber, + effectiveGasPrice: Formatter.allowNull(bigNumber), + status: Formatter.allowNull(number), + type + }; + formats.block = { + hash: Formatter.allowNull(hash2), + parentHash: hash2, + number, + timestamp: number, + nonce: Formatter.allowNull(hex), + difficulty: this.difficulty.bind(this), + gasLimit: bigNumber, + gasUsed: bigNumber, + miner: Formatter.allowNull(address2), + extraData: data, + transactions: Formatter.allowNull(Formatter.arrayOf(hash2)), + baseFeePerGas: Formatter.allowNull(bigNumber) + }; + formats.blockWithTransactions = shallowCopy(formats.block); + formats.blockWithTransactions.transactions = Formatter.allowNull(Formatter.arrayOf(this.transactionResponse.bind(this))); + formats.filter = { + fromBlock: Formatter.allowNull(blockTag, void 0), + toBlock: Formatter.allowNull(blockTag, void 0), + blockHash: Formatter.allowNull(hash2, void 0), + address: Formatter.allowNull(address2, void 0), + topics: Formatter.allowNull(this.topics.bind(this), void 0) + }; + formats.filterLog = { + blockNumber: Formatter.allowNull(number), + blockHash: Formatter.allowNull(hash2), + transactionIndex: number, + removed: Formatter.allowNull(this.boolean.bind(this)), + address: address2, + data: Formatter.allowFalsish(data, "0x"), + topics: Formatter.arrayOf(hash2), + transactionHash: hash2, + logIndex: number + }; + return formats; + } + accessList(accessList) { + return accessListify(accessList || []); + } + number(number) { + if (number === "0x") { + return 0; + } + return BigNumber.from(number).toNumber(); + } + type(number) { + if (number === "0x" || number == null) { + return 0; + } + return BigNumber.from(number).toNumber(); + } + bigNumber(value) { + return BigNumber.from(value); + } + boolean(value) { + if (typeof value === "boolean") { + return value; + } + if (typeof value === "string") { + value = value.toLowerCase(); + if (value === "true") { + return true; + } + if (value === "false") { + return false; } } - return obj; - }, - Int: Kinds.Int, - CarV1HeaderOrV2Pragma: (obj)=>{ - if (Kinds.Map(obj) === void 0) { - return void 0; + throw new Error("invalid boolean - " + value); + } + hex(value, strict) { + if (typeof value === "string") { + if (!strict && value.substring(0, 2) !== "0x") { + value = "0x" + value; + } + if (isHexString(value)) { + return value.toLowerCase(); + } } - const entries = Object.entries(obj); - let ret = obj; - let requiredCount = 1; - for(let i = 0; i < entries.length; i++){ - const [key, value] = entries[i]; - switch(key){ - case "roots": - { - const v = Reprs["CarV1HeaderOrV2Pragma > roots (anon)"](value); - if (v === void 0) { - return void 0; - } - if (v !== value || ret !== obj) { - if (ret === obj) { - ret = {}; - for(let j = 0; j < i; j++){ - ret[entries[j][0]] = entries[j][1]; - } - } - ret.roots = v; - } - } - break; - case "version": - { - requiredCount--; - const v = Reprs.Int(value); - if (v === void 0) { - return void 0; - } - if (v !== value || ret !== obj) { - if (ret === obj) { - ret = {}; - for(let j = 0; j < i; j++){ - ret[entries[j][0]] = entries[j][1]; - } - } - ret.version = v; - } + return logger221.throwArgumentError("invalid hash", "value", value); + } + data(value, strict) { + const result = this.hex(value, strict); + if (result.length % 2 !== 0) { + throw new Error("invalid data; odd-length - " + value); + } + return result; + } + address(value) { + return getAddress(value); + } + callAddress(value) { + if (!isHexString(value, 32)) { + return null; + } + const address2 = getAddress(hexDataSlice(value, 12)); + return address2 === AddressZero ? null : address2; + } + contractAddress(value) { + return getContractAddress(value); + } + blockTag(blockTag) { + if (blockTag == null) { + return "latest"; + } + if (blockTag === "earliest") { + return "0x0"; + } + switch(blockTag){ + case "earliest": + return "0x0"; + case "latest": + case "pending": + case "safe": + case "finalized": + return blockTag; + } + if (typeof blockTag === "number" || isHexString(blockTag)) { + return hexValue(blockTag); + } + throw new Error("invalid blockTag"); + } + hash(value, strict) { + const result = this.hex(value, strict); + if (hexDataLength(result) !== 32) { + return logger221.throwArgumentError("invalid hash", "value", value); + } + return result; + } + difficulty(value) { + if (value == null) { + return null; + } + const v = BigNumber.from(value); + try { + return v.toNumber(); + } catch (error) {} + return null; + } + uint256(value) { + if (!isHexString(value)) { + throw new Error("invalid uint256"); + } + return hexZeroPad(value, 32); + } + _block(value, format) { + if (value.author != null && value.miner == null) { + value.miner = value.author; + } + const difficulty = value._difficulty != null ? value._difficulty : value.difficulty; + const result = Formatter.check(format, value); + result._difficulty = difficulty == null ? null : BigNumber.from(difficulty); + return result; + } + block(value) { + return this._block(value, this.formats.block); + } + blockWithTransactions(value) { + return this._block(value, this.formats.blockWithTransactions); + } + transactionRequest(value) { + return Formatter.check(this.formats.transactionRequest, value); + } + transactionResponse(transaction) { + if (transaction.gas != null && transaction.gasLimit == null) { + transaction.gasLimit = transaction.gas; + } + if (transaction.to && BigNumber.from(transaction.to).isZero()) { + transaction.to = "0x0000000000000000000000000000000000000000"; + } + if (transaction.input != null && transaction.data == null) { + transaction.data = transaction.input; + } + if (transaction.to == null && transaction.creates == null) { + transaction.creates = this.contractAddress(transaction); + } + if ((transaction.type === 1 || transaction.type === 2) && transaction.accessList == null) { + transaction.accessList = []; + } + const result = Formatter.check(this.formats.transaction, transaction); + if (transaction.chainId != null) { + let chainId = transaction.chainId; + if (isHexString(chainId)) { + chainId = BigNumber.from(chainId).toNumber(); + } + result.chainId = chainId; + } else { + let chainId = transaction.networkId; + if (chainId == null && result.v == null) { + chainId = transaction.chainId; + } + if (isHexString(chainId)) { + chainId = BigNumber.from(chainId).toNumber(); + } + if (typeof chainId !== "number" && result.v != null) { + chainId = (result.v - 35) / 2; + if (chainId < 0) { + chainId = 0; + } + chainId = parseInt(chainId); + } + if (typeof chainId !== "number") { + chainId = 0; + } + result.chainId = chainId; + } + if (result.blockHash && result.blockHash.replace(/0/g, "") === "x") { + result.blockHash = null; + } + return result; + } + transaction(value) { + return parse(value); + } + receiptLog(value) { + return Formatter.check(this.formats.receiptLog, value); + } + receipt(value) { + const result = Formatter.check(this.formats.receipt, value); + if (result.root != null) { + if (result.root.length <= 4) { + const value2 = BigNumber.from(result.root).toNumber(); + if (value2 === 0 || value2 === 1) { + if (result.status != null && result.status !== value2) { + logger221.throwArgumentError("alt-root-status/status mismatch", "value", { + root: result.root, + status: result.status + }); } - break; - default: - return void 0; + result.status = value2; + delete result.root; + } else { + logger221.throwArgumentError("invalid alt-root-status", "value.root", result.root); + } + } else if (result.root.length !== 66) { + logger221.throwArgumentError("invalid root hash", "value.root", result.root); } } - if (requiredCount > 0) { - return void 0; + if (result.status != null) { + result.byzantium = true; } - return ret; + return result; } -}; -const CarV1HeaderOrV2Pragma = { - toTyped: Types.CarV1HeaderOrV2Pragma, - toRepresentation: Reprs.CarV1HeaderOrV2Pragma -}; -const cborEncoders1 = makeCborEncoders(); -const defaultEncodeOptions1 = { - float64: false, - quickEncodeToken -}; -function tokensToLength(tokens, encoders = cborEncoders1, options = defaultEncodeOptions1) { - if (Array.isArray(tokens)) { - let len = 0; - for (const token of tokens){ - len += tokensToLength(token, encoders, options); + topics(value) { + if (Array.isArray(value)) { + return value.map((v)=>this.topics(v)); + } else if (value != null) { + return this.hash(value, true); } - return len; - } else { - const encoder = encoders[tokens.type.major]; - if (encoder.encodedSize === void 0 || typeof encoder.encodedSize !== "function") { - throw new Error(`Encoder for ${tokens.type.name} does not have an encodedSize()`); + return null; + } + filter(value) { + return Formatter.check(this.formats.filter, value); + } + filterLog(value) { + return Formatter.check(this.formats.filterLog, value); + } + static check(format, object) { + const result = {}; + for(const key in format){ + try { + const value = format[key](object[key]); + if (value !== void 0) { + result[key] = value; + } + } catch (error) { + error.checkKey = key; + error.checkValue = object[key]; + throw error; + } } - return encoder.encodedSize(tokens, options); + return result; } -} -async function readHeader(reader, strictVersion) { - const length = decodeVarint(await reader.upTo(8), reader); - if (length === 0) { - throw new Error("Invalid CAR header (zero length)"); + static allowNull(format, nullValue) { + return function(value) { + if (value == null) { + return nullValue; + } + return format(value); + }; } - const header = await reader.exactly(length, true); - const block = decode4(header); - if (CarV1HeaderOrV2Pragma.toTyped(block) === void 0) { - throw new Error("Invalid CAR header format"); + static allowFalsish(format, replaceValue) { + return function(value) { + if (!value) { + return replaceValue; + } + return format(value); + }; } - if (block.version !== 1 && block.version !== 2 || strictVersion !== void 0 && block.version !== strictVersion) { - throw new Error(`Invalid CAR version: ${block.version}${strictVersion !== void 0 ? ` (expected ${strictVersion})` : ""}`); + static arrayOf(format) { + return function(array) { + if (!Array.isArray(array)) { + throw new Error("not an array"); + } + const result = []; + array.forEach(function(value) { + result.push(format(value)); + }); + return result; + }; } - if (block.version === 1) { - if (!Array.isArray(block.roots)) { - throw new Error("Invalid CAR header format"); +} +function isCommunityResourcable(value) { + return value && typeof value.isCommunityResource === "function"; +} +function isCommunityResource(value) { + return isCommunityResourcable(value) && value.isCommunityResource(); +} +let throttleMessage = false; +function showThrottleMessage() { + if (throttleMessage) { + return; + } + throttleMessage = true; + console.log("========= NOTICE ========="); + console.log("Request-Rate Exceeded (this message will not be repeated)"); + console.log(""); + console.log("The default API keys for each service are provided as a highly-throttled,"); + console.log("community resource for low-traffic projects and early prototyping."); + console.log(""); + console.log("While your application will continue to function, we highly recommended"); + console.log("signing up for your own API keys to improve performance, increase your"); + console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."); + console.log(""); + console.log("For more details: https://docs.ethers.io/api-keys/"); + console.log("=========================="); +} +var __awaiter8 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - return block; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger$14 = new Logger(version23); +function checkTopic(topic) { + if (topic == null) { + return "null"; } - if (block.roots !== void 0) { - throw new Error("Invalid CAR header format"); + if (hexDataLength(topic) !== 32) { + logger$14.throwArgumentError("invalid topic", "topic", topic); } - const v2Header = decodeV2Header(await reader.exactly(V2_HEADER_LENGTH, true)); - reader.seek(v2Header.dataOffset - reader.pos); - const v1Header = await readHeader(reader, 1); - return Object.assign(v1Header, v2Header); + return topic.toLowerCase(); } -async function readCid(reader) { - const first = await reader.exactly(2, false); - if (first[0] === CIDV0_BYTES.SHA2_256 && first[1] === CIDV0_BYTES.LENGTH) { - const bytes2 = await reader.exactly(34, true); - const multihash2 = decode$2(bytes2); - return CID.create(0, CIDV0_BYTES.DAG_PB, multihash2); +function serializeTopics(topics) { + topics = topics.slice(); + while(topics.length > 0 && topics[topics.length - 1] == null){ + topics.pop(); } - const version = decodeVarint(await reader.upTo(8), reader); - if (version !== 1) { - throw new Error(`Unexpected CID version (${version})`); + return topics.map((topic)=>{ + if (Array.isArray(topic)) { + const unique = {}; + topic.forEach((topic2)=>{ + unique[checkTopic(topic2)] = true; + }); + const sorted = Object.keys(unique); + sorted.sort(); + return sorted.join("|"); + } else { + return checkTopic(topic); + } + }).join("&"); +} +function deserializeTopics(data) { + if (data === "") { + return []; } - const codec = decodeVarint(await reader.upTo(8), reader); - const bytes = await reader.exactly(getMultihashLength(await reader.upTo(8)), true); - const multihash = decode$2(bytes); - return CID.create(version, codec, multihash); + return data.split(/&/g).map((topic)=>{ + if (topic === "") { + return []; + } + const comps = topic.split("|").map((topic2)=>{ + return topic2 === "null" ? null : topic2; + }); + return comps.length === 1 ? comps[0] : comps; + }); } -async function readBlockHead(reader) { - const start = reader.pos; - let length = decodeVarint(await reader.upTo(8), reader); - if (length === 0) { - throw new Error("Invalid CAR section (zero length)"); +function getEventTag1(eventName) { + if (typeof eventName === "string") { + eventName = eventName.toLowerCase(); + if (hexDataLength(eventName) === 32) { + return "tx:" + eventName; + } + if (eventName.indexOf(":") === -1) { + return eventName; + } + } else if (Array.isArray(eventName)) { + return "filter:*:" + serializeTopics(eventName); + } else if (ForkEvent.isForkEvent(eventName)) { + logger$14.warn("not implemented"); + throw new Error("not implemented"); + } else if (eventName && typeof eventName === "object") { + return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []); } - length += reader.pos - start; - const cid2 = await readCid(reader); - const blockLength = length - Number(reader.pos - start); - return { - cid: cid2, - length, - blockLength - }; + throw new Error("invalid event - " + eventName); } -async function readBlock(reader) { - const { cid: cid2, blockLength } = await readBlockHead(reader); - const bytes = await reader.exactly(blockLength, true); - return { - bytes, - cid: cid2 - }; +function getTime() { + return new Date().getTime(); } -async function readBlockIndex(reader) { - const offset = reader.pos; - const { cid: cid2, length, blockLength } = await readBlockHead(reader); - const index = { - cid: cid2, - length, - blockLength, - offset, - blockOffset: reader.pos - }; - reader.seek(index.blockLength); - return index; +function stall(duration) { + return new Promise((resolve)=>{ + setTimeout(resolve, duration); + }); } -function createDecoder(reader) { - const headerPromise = (async ()=>{ - const header = await readHeader(reader); - if (header.version === 2) { - const v1length = reader.pos - header.dataOffset; - reader = limitReader(reader, header.dataSize - v1length); +const PollableEvents = [ + "block", + "network", + "pending", + "poll" +]; +class Event { + constructor(tag, listener, once){ + defineReadOnly(this, "tag", tag); + defineReadOnly(this, "listener", listener); + defineReadOnly(this, "once", once); + this._lastBlockNumber = -2; + this._inflight = false; + } + get event() { + switch(this.type){ + case "tx": + return this.hash; + case "filter": + return this.filter; + } + return this.tag; + } + get type() { + return this.tag.split(":")[0]; + } + get hash() { + const comps = this.tag.split(":"); + if (comps[0] !== "tx") { + return null; } - return header; - })(); - return { - header: ()=>headerPromise, - async *blocks () { - await headerPromise; - while((await reader.upTo(8)).length > 0){ - yield await readBlock(reader); - } - }, - async *blocksIndex () { - await headerPromise; - while((await reader.upTo(8)).length > 0){ - yield await readBlockIndex(reader); - } + return comps[1]; + } + get filter() { + const comps = this.tag.split(":"); + if (comps[0] !== "filter") { + return null; } - }; -} -function bytesReader(bytes) { - let pos = 0; - return { - async upTo (length) { - const out = bytes.subarray(pos, pos + Math.min(length, bytes.length - pos)); - return out; - }, - async exactly (length, seek = false) { - if (length > bytes.length - pos) { - throw new Error("Unexpected end of data"); - } - const out = bytes.subarray(pos, pos + length); - if (seek) { - pos += length; - } - return out; - }, - seek (length) { - pos += length; - }, - get pos () { - return pos; + const address2 = comps[1]; + const topics = deserializeTopics(comps[2]); + const filter = {}; + if (topics.length > 0) { + filter.topics = topics; } - }; + if (address2 && address2 !== "*") { + filter.address = address2; + } + return filter; + } + pollable() { + return this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0; + } } -function chunkReader(readChunk) { - let pos = 0; - let have = 0; - let offset = 0; - let currentChunk = new Uint8Array(0); - const read = async (length)=>{ - have = currentChunk.length - offset; - const bufa = [ - currentChunk.subarray(offset) - ]; - while(have < length){ - const chunk = await readChunk(); - if (chunk == null) { - break; - } - if (have < 0) { - if (chunk.length > have) { - bufa.push(chunk.subarray(-have)); +const coinInfos = { + "0": { + symbol: "btc", + p2pkh: 0, + p2sh: 5, + prefix: "bc" + }, + "2": { + symbol: "ltc", + p2pkh: 48, + p2sh: 50, + prefix: "ltc" + }, + "3": { + symbol: "doge", + p2pkh: 30, + p2sh: 22 + }, + "60": { + symbol: "eth", + ilk: "eth" + }, + "61": { + symbol: "etc", + ilk: "eth" + }, + "700": { + symbol: "xdai", + ilk: "eth" + } +}; +function bytes32ify(value) { + return hexZeroPad(BigNumber.from(value).toHexString(), 32); +} +function base58Encode(data) { + return Base58.encode(concat([ + data, + hexDataSlice(sha2561(sha2561(data)), 0, 4) + ])); +} +const matcherIpfs = new RegExp("^(ipfs)://(.*)$", "i"); +const matchers = [ + new RegExp("^(https)://(.*)$", "i"), + new RegExp("^(data):(.*)$", "i"), + matcherIpfs, + new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i") +]; +function _parseString(result, start) { + try { + return toUtf8String(_parseBytes(result, start)); + } catch (error) {} + return null; +} +function _parseBytes(result, start) { + if (result === "0x") { + return null; + } + const offset = BigNumber.from(hexDataSlice(result, start, start + 32)).toNumber(); + const length = BigNumber.from(hexDataSlice(result, offset, offset + 32)).toNumber(); + return hexDataSlice(result, offset + 32, offset + 32 + length); +} +function getIpfsLink(link) { + if (link.match(/^ipfs:\/\/ipfs\//i)) { + link = link.substring(12); + } else if (link.match(/^ipfs:\/\//i)) { + link = link.substring(7); + } else { + logger$14.throwArgumentError("unsupported IPFS format", "link", link); + } + return `https://gateway.ipfs.io/ipfs/${link}`; +} +function numPad(value) { + const result = arrayify(value); + if (result.length > 32) { + throw new Error("internal; should not happen"); + } + const padded = new Uint8Array(32); + padded.set(result, 32 - result.length); + return padded; +} +function bytesPad(value) { + if (value.length % 32 === 0) { + return value; + } + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; +} +function encodeBytes(datas) { + const result = []; + let byteCount = 0; + for(let i = 0; i < datas.length; i++){ + result.push(null); + byteCount += 32; + } + for(let i = 0; i < datas.length; i++){ + const data = arrayify(datas[i]); + result[i] = numPad(byteCount); + result.push(numPad(data.length)); + result.push(bytesPad(data)); + byteCount += 32 + Math.ceil(data.length / 32) * 32; + } + return hexConcat(result); +} +class Resolver { + constructor(provider, address2, name, resolvedAddress){ + defineReadOnly(this, "provider", provider); + defineReadOnly(this, "name", name); + defineReadOnly(this, "address", provider.formatter.address(address2)); + defineReadOnly(this, "_resolvedAddress", resolvedAddress); + } + supportsWildcard() { + if (!this._supportsEip2544) { + this._supportsEip2544 = this.provider.call({ + to: this.address, + data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000" + }).then((result)=>{ + return BigNumber.from(result).eq(1); + }).catch((error)=>{ + if (error.code === Logger.errors.CALL_EXCEPTION) { + return false; } - } else { - bufa.push(chunk); - } - have += chunk.length; - } - currentChunk = new Uint8Array(bufa.reduce((p, c)=>p + c.length, 0)); - let off = 0; - for (const b of bufa){ - currentChunk.set(b, off); - off += b.length; + this._supportsEip2544 = null; + throw error; + }); } - offset = 0; - }; - return { - async upTo (length) { - if (currentChunk.length - offset < length) { - await read(length); - } - return currentChunk.subarray(offset, offset + Math.min(currentChunk.length - offset, length)); - }, - async exactly (length, seek = false) { - if (currentChunk.length - offset < length) { - await read(length); - } - if (currentChunk.length - offset < length) { - throw new Error("Unexpected end of data"); + return this._supportsEip2544; + } + _fetch(selector, parameters) { + return __awaiter8(this, void 0, void 0, function*() { + const tx = { + to: this.address, + ccipReadEnabled: true, + data: hexConcat([ + selector, + namehash(this.name), + parameters || "0x" + ]) + }; + let parseBytes = false; + if (yield this.supportsWildcard()) { + parseBytes = true; + tx.data = hexConcat([ + "0x9061b923", + encodeBytes([ + dnsEncode(this.name), + tx.data + ]) + ]); } - const out = currentChunk.subarray(offset, offset + length); - if (seek) { - pos += length; - offset += length; + try { + let result = yield this.provider.call(tx); + if (arrayify(result).length % 32 === 4) { + logger$14.throwError("resolver threw error", Logger.errors.CALL_EXCEPTION, { + transaction: tx, + data: result + }); + } + if (parseBytes) { + result = _parseBytes(result, 0); + } + return result; + } catch (error) { + if (error.code === Logger.errors.CALL_EXCEPTION) { + return null; + } + throw error; + } + }); + } + _fetchBytes(selector, parameters) { + return __awaiter8(this, void 0, void 0, function*() { + const result = yield this._fetch(selector, parameters); + if (result != null) { + return _parseBytes(result, 0); } - return out; - }, - seek (length) { - pos += length; - offset += length; - }, - get pos () { - return pos; - } - }; -} -function asyncIterableReader(asyncIterable) { - const iterator = asyncIterable[Symbol.asyncIterator](); - async function readChunk() { - const next = await iterator.next(); - if (next.done) { return null; - } - return next.value; + }); } - return chunkReader(readChunk); -} -function limitReader(reader, byteLimit) { - let bytesRead = 0; - return { - async upTo (length) { - let bytes = await reader.upTo(length); - if (bytes.length + bytesRead > byteLimit) { - bytes = bytes.subarray(0, byteLimit - bytesRead); + _getAddress(coinType, hexBytes) { + const coinInfo = coinInfos[String(coinType)]; + if (coinInfo == null) { + logger$14.throwError(`unsupported coin type: ${coinType}`, Logger.errors.UNSUPPORTED_OPERATION, { + operation: `getAddress(${coinType})` + }); + } + if (coinInfo.ilk === "eth") { + return this.provider.formatter.address(hexBytes); + } + const bytes2 = arrayify(hexBytes); + if (coinInfo.p2pkh != null) { + const p2pkh = hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/); + if (p2pkh) { + const length = parseInt(p2pkh[1], 16); + if (p2pkh[2].length === length * 2 && length >= 1 && length <= 75) { + return base58Encode(concat([ + [ + coinInfo.p2pkh + ], + "0x" + p2pkh[2] + ])); + } } - return bytes; - }, - async exactly (length, seek = false) { - const bytes = await reader.exactly(length, seek); - if (bytes.length + bytesRead > byteLimit) { - throw new Error("Unexpected end of data"); + } + if (coinInfo.p2sh != null) { + const p2sh = hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/); + if (p2sh) { + const length = parseInt(p2sh[1], 16); + if (p2sh[2].length === length * 2 && length >= 1 && length <= 75) { + return base58Encode(concat([ + [ + coinInfo.p2sh + ], + "0x" + p2sh[2] + ])); + } } - if (seek) { - bytesRead += length; + } + if (coinInfo.prefix != null) { + const length = bytes2[1]; + let version2 = bytes2[0]; + if (version2 === 0) { + if (length !== 20 && length !== 32) { + version2 = -1; + } + } else { + version2 = -1; + } + if (version2 >= 0 && bytes2.length === 2 + length && length >= 1 && length <= 75) { + const words = bech32.toWords(bytes2.slice(2)); + words.unshift(version2); + return bech32.encode(coinInfo.prefix, words); } - return bytes; - }, - seek (length) { - bytesRead += length; - reader.seek(length); - }, - get pos () { - return reader.pos; } - }; -} -class CarBufferWriter { - constructor(bytes, headerSize){ - this.bytes = bytes; - this.byteOffset = headerSize; - this.roots = []; - this.headerSize = headerSize; + return null; } - addRoot(root, options) { - addRoot(this, root, options); - return this; + getAddress(coinType) { + return __awaiter8(this, void 0, void 0, function*() { + if (coinType == null) { + coinType = 60; + } + if (coinType === 60) { + try { + const result = yield this._fetch("0x3b3b57de"); + if (result === "0x" || result === HashZero) { + return null; + } + return this.provider.formatter.callAddress(result); + } catch (error) { + if (error.code === Logger.errors.CALL_EXCEPTION) { + return null; + } + throw error; + } + } + const hexBytes = yield this._fetchBytes("0xf1cb7e06", bytes32ify(coinType)); + if (hexBytes == null || hexBytes === "0x") { + return null; + } + const address2 = this._getAddress(coinType, hexBytes); + if (address2 == null) { + logger$14.throwError(`invalid or unsupported coin data`, Logger.errors.UNSUPPORTED_OPERATION, { + operation: `getAddress(${coinType})`, + coinType, + data: hexBytes + }); + } + return address2; + }); } - write(block) { - addBlock(this, block); - return this; + getAvatar() { + return __awaiter8(this, void 0, void 0, function*() { + const linkage = [ + { + type: "name", + content: this.name + } + ]; + try { + const avatar = yield this.getText("avatar"); + if (avatar == null) { + return null; + } + for(let i = 0; i < matchers.length; i++){ + const match = avatar.match(matchers[i]); + if (match == null) { + continue; + } + const scheme = match[1].toLowerCase(); + switch(scheme){ + case "https": + linkage.push({ + type: "url", + content: avatar + }); + return { + linkage, + url: avatar + }; + case "data": + linkage.push({ + type: "data", + content: avatar + }); + return { + linkage, + url: avatar + }; + case "ipfs": + linkage.push({ + type: "ipfs", + content: avatar + }); + return { + linkage, + url: getIpfsLink(avatar) + }; + case "erc721": + case "erc1155": + { + const selector = scheme === "erc721" ? "0xc87b56dd" : "0x0e89341c"; + linkage.push({ + type: scheme, + content: avatar + }); + const owner = this._resolvedAddress || (yield this.getAddress()); + const comps = (match[2] || "").split("/"); + if (comps.length !== 2) { + return null; + } + const addr = yield this.provider.formatter.address(comps[0]); + const tokenId = hexZeroPad(BigNumber.from(comps[1]).toHexString(), 32); + if (scheme === "erc721") { + const tokenOwner = this.provider.formatter.callAddress((yield this.provider.call({ + to: addr, + data: hexConcat([ + "0x6352211e", + tokenId + ]) + }))); + if (owner !== tokenOwner) { + return null; + } + linkage.push({ + type: "owner", + content: tokenOwner + }); + } else if (scheme === "erc1155") { + const balance = BigNumber.from((yield this.provider.call({ + to: addr, + data: hexConcat([ + "0x00fdd58e", + hexZeroPad(owner, 32), + tokenId + ]) + }))); + if (balance.isZero()) { + return null; + } + linkage.push({ + type: "balance", + content: balance.toString() + }); + } + const tx = { + to: this.provider.formatter.address(comps[0]), + data: hexConcat([ + selector, + tokenId + ]) + }; + let metadataUrl = _parseString((yield this.provider.call(tx)), 0); + if (metadataUrl == null) { + return null; + } + linkage.push({ + type: "metadata-url-base", + content: metadataUrl + }); + if (scheme === "erc1155") { + metadataUrl = metadataUrl.replace("{id}", tokenId.substring(2)); + linkage.push({ + type: "metadata-url-expanded", + content: metadataUrl + }); + } + if (metadataUrl.match(/^ipfs:/i)) { + metadataUrl = getIpfsLink(metadataUrl); + } + linkage.push({ + type: "metadata-url", + content: metadataUrl + }); + const metadata = yield fetchJson(metadataUrl); + if (!metadata) { + return null; + } + linkage.push({ + type: "metadata", + content: JSON.stringify(metadata) + }); + let imageUrl = metadata.image; + if (typeof imageUrl !== "string") { + return null; + } + if (imageUrl.match(/^(https:\/\/|data:)/i)) {} else { + const ipfs = imageUrl.match(matcherIpfs); + if (ipfs == null) { + return null; + } + linkage.push({ + type: "url-ipfs", + content: imageUrl + }); + imageUrl = getIpfsLink(imageUrl); + } + linkage.push({ + type: "url", + content: imageUrl + }); + return { + linkage, + url: imageUrl + }; + } + } + } + } catch (error) {} + return null; + }); } - close(options) { - return close(this, options); + getContentHash() { + return __awaiter8(this, void 0, void 0, function*() { + const hexBytes = yield this._fetchBytes("0xbc1c58d1"); + if (hexBytes == null || hexBytes === "0x") { + return null; + } + const ipfs = hexBytes.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); + if (ipfs) { + const length = parseInt(ipfs[3], 16); + if (ipfs[4].length === length * 2) { + return "ipfs://" + Base58.encode("0x" + ipfs[1]); + } + } + const ipns = hexBytes.match(/^0xe5010172(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); + if (ipns) { + const length = parseInt(ipns[3], 16); + if (ipns[4].length === length * 2) { + return "ipns://" + Base58.encode("0x" + ipns[1]); + } + } + const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/); + if (swarm) { + if (swarm[1].length === 32 * 2) { + return "bzz://" + swarm[1]; + } + } + const skynet = hexBytes.match(/^0x90b2c605([0-9a-f]*)$/); + if (skynet) { + if (skynet[1].length === 34 * 2) { + const urlSafe = { + "=": "", + "+": "-", + "/": "_" + }; + const hash2 = encode1("0x" + skynet[1]).replace(/[=+\/]/g, (a)=>urlSafe[a]); + return "sia://" + hash2; + } + } + return logger$14.throwError(`invalid or unsupported content hash data`, Logger.errors.UNSUPPORTED_OPERATION, { + operation: "getContentHash()", + data: hexBytes + }); + }); + } + getText(key) { + return __awaiter8(this, void 0, void 0, function*() { + let keyBytes = toUtf8Bytes(key); + keyBytes = concat([ + bytes32ify(64), + bytes32ify(keyBytes.length), + keyBytes + ]); + if (keyBytes.length % 32 !== 0) { + keyBytes = concat([ + keyBytes, + hexZeroPad("0x", 32 - key.length % 32) + ]); + } + const hexBytes = yield this._fetchBytes("0x59d1d43c", hexlify(keyBytes)); + if (hexBytes == null || hexBytes === "0x") { + return null; + } + return toUtf8String(hexBytes); + }); } } -const addRoot = (writer, root, options = {})=>{ - const { resize = false } = options; - const { bytes, headerSize, byteOffset, roots } = writer; - writer.roots.push(root); - const size = headerLength(writer); - if (size > headerSize) { - if (size - headerSize + byteOffset < bytes.byteLength) { - if (resize) { - resizeHeader(writer, size); +let defaultFormatter = null; +let nextPollId = 1; +class BaseProvider extends Provider { + constructor(network){ + super(); + this._events = []; + this._emitted = { + block: -2 + }; + this.disableCcipRead = false; + this.formatter = new.target.getFormatter(); + defineReadOnly(this, "anyNetwork", network === "any"); + if (this.anyNetwork) { + network = this.detectNetwork(); + } + if (network instanceof Promise) { + this._networkPromise = network; + network.catch((error)=>{}); + this._ready().catch((error)=>{}); + } else { + const knownNetwork = getStatic(new.target, "getNetwork")(network); + if (knownNetwork) { + defineReadOnly(this, "_network", knownNetwork); + this.emit("network", knownNetwork, null); } else { - roots.pop(); - throw new RangeError(`Header of size ${headerSize} has no capacity for new root ${root}. - However there is a space in the buffer and you could call addRoot(root, { resize: root }) to resize header to make a space for this root.`); + logger$14.throwArgumentError("invalid network", "network", network); } - } else { - roots.pop(); - throw new RangeError(`Buffer has no capacity for a new root ${root}`); } + this._maxInternalBlockNumber = -1024; + this._lastBlockNumber = -2; + this._maxFilterBlockRange = 10; + this._pollingInterval = 4e3; + this._fastQueryDate = 0; + } + _ready() { + return __awaiter8(this, void 0, void 0, function*() { + if (this._network == null) { + let network = null; + if (this._networkPromise) { + try { + network = yield this._networkPromise; + } catch (error) {} + } + if (network == null) { + network = yield this.detectNetwork(); + } + if (!network) { + logger$14.throwError("no network detected", Logger.errors.UNKNOWN_ERROR, {}); + } + if (this._network == null) { + if (this.anyNetwork) { + this._network = network; + } else { + defineReadOnly(this, "_network", network); + } + this.emit("network", network, null); + } + } + return this._network; + }); } -}; -const blockLength = ({ cid, bytes })=>{ - const size = cid.bytes.byteLength + bytes.byteLength; - return varint1.encodingLength(size) + size; -}; -const addBlock = (writer, { cid, bytes })=>{ - const byteLength = cid.bytes.byteLength + bytes.byteLength; - const size = varint1.encode(byteLength); - if (writer.byteOffset + size.length + byteLength > writer.bytes.byteLength) { - throw new RangeError("Buffer has no capacity for this block"); - } else { - writeBytes(writer, size); - writeBytes(writer, cid.bytes); - writeBytes(writer, bytes); + get ready() { + return poll(()=>{ + return this._ready().then((network)=>{ + return network; + }, (error)=>{ + if (error.code === Logger.errors.NETWORK_ERROR && error.event === "noNetwork") { + return void 0; + } + throw error; + }); + }); } -}; -const close = (writer, options = {})=>{ - const { resize = false } = options; - const { roots, bytes, byteOffset, headerSize } = writer; - const headerBytes = encode3({ - version: 1, - roots - }); - const varintBytes = varint1.encode(headerBytes.length); - const size = varintBytes.length + headerBytes.byteLength; - const offset = headerSize - size; - if (offset === 0) { - writeHeader(writer, varintBytes, headerBytes); - return bytes.subarray(0, byteOffset); - } else if (resize) { - resizeHeader(writer, size); - writeHeader(writer, varintBytes, headerBytes); - return bytes.subarray(0, writer.byteOffset); - } else { - throw new RangeError(`Header size was overestimated. -You can use close({ resize: true }) to resize header`); + static getFormatter() { + if (defaultFormatter == null) { + defaultFormatter = new Formatter(); + } + return defaultFormatter; } -}; -const resizeHeader = (writer, byteLength)=>{ - const { bytes, headerSize } = writer; - bytes.set(bytes.subarray(headerSize, writer.byteOffset), byteLength); - writer.byteOffset += byteLength - headerSize; - writer.headerSize = byteLength; -}; -const writeBytes = (writer, bytes)=>{ - writer.bytes.set(bytes, writer.byteOffset); - writer.byteOffset += bytes.length; -}; -const writeHeader = ({ bytes }, varint3, header)=>{ - bytes.set(varint3); - bytes.set(header, varint3.length); -}; -const headerPreludeTokens = [ - new Token(Type.map, 2), - new Token(Type.string, "version"), - new Token(Type.uint, 1), - new Token(Type.string, "roots") -]; -const CID_TAG = new Token(Type.tag, 42); -const calculateHeaderLength = (rootLengths)=>{ - const tokens = [ - ...headerPreludeTokens - ]; - tokens.push(new Token(Type.array, rootLengths.length)); - for (const rootLength of rootLengths){ - tokens.push(CID_TAG); - tokens.push(new Token(Type.bytes, { - length: rootLength + 1 - })); + static getNetwork(network) { + return getNetwork(network == null ? "homestead" : network); } - const length2 = tokensToLength(tokens); - return varint1.encodingLength(length2) + length2; -}; -const headerLength = ({ roots })=>calculateHeaderLength(roots.map((cid)=>cid.bytes.byteLength)); -const estimateHeaderLength = (rootCount, rootByteLength = 36)=>calculateHeaderLength(new Array(rootCount).fill(rootByteLength)); -const createWriter = (buffer, options = {})=>{ - const { roots = [], byteOffset = 0, byteLength = buffer.byteLength, headerSize = headerLength({ - roots - }) } = options; - const bytes = new Uint8Array(buffer, byteOffset, byteLength); - const writer = new CarBufferWriter(bytes, headerSize); - for (const root of roots){ - writer.addRoot(root); + ccipReadFetch(tx, calldata, urls) { + return __awaiter8(this, void 0, void 0, function*() { + if (this.disableCcipRead || urls.length === 0) { + return null; + } + const sender = tx.to.toLowerCase(); + const data = calldata.toLowerCase(); + const errorMessages = []; + for(let i = 0; i < urls.length; i++){ + const url = urls[i]; + const href = url.replace("{sender}", sender).replace("{data}", data); + const json = url.indexOf("{data}") >= 0 ? null : JSON.stringify({ + data, + sender + }); + const result = yield fetchJson({ + url: href, + errorPassThrough: true + }, json, (value, response)=>{ + value.status = response.statusCode; + return value; + }); + if (result.data) { + return result.data; + } + const errorMessage = result.message || "unknown error"; + if (result.status >= 400 && result.status < 500) { + return logger$14.throwError(`response not found during CCIP fetch: ${errorMessage}`, Logger.errors.SERVER_ERROR, { + url, + errorMessage + }); + } + errorMessages.push(errorMessage); + } + return logger$14.throwError(`error encountered during CCIP fetch: ${errorMessages.map((m)=>JSON.stringify(m)).join(", ")}`, Logger.errors.SERVER_ERROR, { + urls, + errorMessages + }); + }); } - return writer; -}; -Object.freeze({ - __proto__: null, - addRoot, - blockLength, - addBlock, - close, - resizeHeader, - calculateHeaderLength, - headerLength, - estimateHeaderLength, - createWriter -}); -class CarIndexer { - constructor(version, roots, iterator){ - this._version = version; - this._roots = roots; - this._iterator = iterator; + _getInternalBlockNumber(maxAge) { + return __awaiter8(this, void 0, void 0, function*() { + yield this._ready(); + if (maxAge > 0) { + while(this._internalBlockNumber){ + const internalBlockNumber = this._internalBlockNumber; + try { + const result = yield internalBlockNumber; + if (getTime() - result.respTime <= maxAge) { + return result.blockNumber; + } + break; + } catch (error) { + if (this._internalBlockNumber === internalBlockNumber) { + break; + } + } + } + } + const reqTime = getTime(); + const checkInternalBlockNumber = resolveProperties({ + blockNumber: this.perform("getBlockNumber", {}), + networkError: this.getNetwork().then((network)=>null, (error)=>error) + }).then(({ blockNumber, networkError })=>{ + if (networkError) { + if (this._internalBlockNumber === checkInternalBlockNumber) { + this._internalBlockNumber = null; + } + throw networkError; + } + const respTime = getTime(); + blockNumber = BigNumber.from(blockNumber).toNumber(); + if (blockNumber < this._maxInternalBlockNumber) { + blockNumber = this._maxInternalBlockNumber; + } + this._maxInternalBlockNumber = blockNumber; + this._setFastBlockNumber(blockNumber); + return { + blockNumber, + reqTime, + respTime + }; + }); + this._internalBlockNumber = checkInternalBlockNumber; + checkInternalBlockNumber.catch((error)=>{ + if (this._internalBlockNumber === checkInternalBlockNumber) { + this._internalBlockNumber = null; + } + }); + return (yield checkInternalBlockNumber).blockNumber; + }); + } + poll() { + return __awaiter8(this, void 0, void 0, function*() { + const pollId = nextPollId++; + const runners = []; + let blockNumber = null; + try { + blockNumber = yield this._getInternalBlockNumber(100 + this.pollingInterval / 2); + } catch (error) { + this.emit("error", error); + return; + } + this._setFastBlockNumber(blockNumber); + this.emit("poll", pollId, blockNumber); + if (blockNumber === this._lastBlockNumber) { + this.emit("didPoll", pollId); + return; + } + if (this._emitted.block === -2) { + this._emitted.block = blockNumber - 1; + } + if (Math.abs(this._emitted.block - blockNumber) > 1e3) { + logger$14.warn(`network block skew detected; skipping block events (emitted=${this._emitted.block} blockNumber${blockNumber})`); + this.emit("error", logger$14.makeError("network block skew detected", Logger.errors.NETWORK_ERROR, { + blockNumber, + event: "blockSkew", + previousBlockNumber: this._emitted.block + })); + this.emit("block", blockNumber); + } else { + for(let i = this._emitted.block + 1; i <= blockNumber; i++){ + this.emit("block", i); + } + } + if (this._emitted.block !== blockNumber) { + this._emitted.block = blockNumber; + Object.keys(this._emitted).forEach((key)=>{ + if (key === "block") { + return; + } + const eventBlockNumber = this._emitted[key]; + if (eventBlockNumber === "pending") { + return; + } + if (blockNumber - eventBlockNumber > 12) { + delete this._emitted[key]; + } + }); + } + if (this._lastBlockNumber === -2) { + this._lastBlockNumber = blockNumber - 1; + } + this._events.forEach((event)=>{ + switch(event.type){ + case "tx": + { + const hash2 = event.hash; + let runner = this.getTransactionReceipt(hash2).then((receipt)=>{ + if (!receipt || receipt.blockNumber == null) { + return null; + } + this._emitted["t:" + hash2] = receipt.blockNumber; + this.emit(hash2, receipt); + return null; + }).catch((error)=>{ + this.emit("error", error); + }); + runners.push(runner); + break; + } + case "filter": + { + if (!event._inflight) { + event._inflight = true; + if (event._lastBlockNumber === -2) { + event._lastBlockNumber = blockNumber - 1; + } + const filter = event.filter; + filter.fromBlock = event._lastBlockNumber + 1; + filter.toBlock = blockNumber; + const minFromBlock = filter.toBlock - this._maxFilterBlockRange; + if (minFromBlock > filter.fromBlock) { + filter.fromBlock = minFromBlock; + } + if (filter.fromBlock < 0) { + filter.fromBlock = 0; + } + const runner = this.getLogs(filter).then((logs)=>{ + event._inflight = false; + if (logs.length === 0) { + return; + } + logs.forEach((log)=>{ + if (log.blockNumber > event._lastBlockNumber) { + event._lastBlockNumber = log.blockNumber; + } + this._emitted["b:" + log.blockHash] = log.blockNumber; + this._emitted["t:" + log.transactionHash] = log.blockNumber; + this.emit(filter, log); + }); + }).catch((error)=>{ + this.emit("error", error); + event._inflight = false; + }); + runners.push(runner); + } + break; + } + } + }); + this._lastBlockNumber = blockNumber; + Promise.all(runners).then(()=>{ + this.emit("didPoll", pollId); + }).catch((error)=>{ + this.emit("error", error); + }); + return; + }); } - get version() { - return this._version; + resetEventsBlock(blockNumber) { + this._lastBlockNumber = blockNumber - 1; + if (this.polling) { + this.poll(); + } } - async getRoots() { - return this._roots; + get network() { + return this._network; } - [Symbol.asyncIterator]() { - return this._iterator; + detectNetwork() { + return __awaiter8(this, void 0, void 0, function*() { + return logger$14.throwError("provider does not support network detection", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "provider.detectNetwork" + }); + }); } - static async fromBytes(bytes) { - if (!(bytes instanceof Uint8Array)) { - throw new TypeError("fromBytes() requires a Uint8Array"); - } - return decodeIndexerComplete(bytesReader(bytes)); + getNetwork() { + return __awaiter8(this, void 0, void 0, function*() { + const network = yield this._ready(); + const currentNetwork = yield this.detectNetwork(); + if (network.chainId !== currentNetwork.chainId) { + if (this.anyNetwork) { + this._network = currentNetwork; + this._lastBlockNumber = -2; + this._fastBlockNumber = null; + this._fastBlockNumberPromise = null; + this._fastQueryDate = 0; + this._emitted.block = -2; + this._maxInternalBlockNumber = -1024; + this._internalBlockNumber = null; + this.emit("network", currentNetwork, network); + yield stall(0); + return this._network; + } + const error = logger$14.makeError("underlying network changed", Logger.errors.NETWORK_ERROR, { + event: "changed", + network, + detectedNetwork: currentNetwork + }); + this.emit("error", error); + throw error; + } + return network; + }); } - static async fromIterable(asyncIterable) { - if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === "function")) { - throw new TypeError("fromIterable() requires an async iterable"); + get blockNumber() { + this._getInternalBlockNumber(100 + this.pollingInterval / 2).then((blockNumber)=>{ + this._setFastBlockNumber(blockNumber); + }, (error)=>{}); + return this._fastBlockNumber != null ? this._fastBlockNumber : -1; + } + get polling() { + return this._poller != null; + } + set polling(value) { + if (value && !this._poller) { + this._poller = setInterval(()=>{ + this.poll(); + }, this.pollingInterval); + if (!this._bootstrapPoll) { + this._bootstrapPoll = setTimeout(()=>{ + this.poll(); + this._bootstrapPoll = setTimeout(()=>{ + if (!this._poller) { + this.poll(); + } + this._bootstrapPoll = null; + }, this.pollingInterval); + }, 0); + } + } else if (!value && this._poller) { + clearInterval(this._poller); + this._poller = null; } - return decodeIndexerComplete(asyncIterableReader(asyncIterable)); } -} -class CarIteratorBase { - constructor(version, roots, iterable){ - this._version = version; - this._roots = roots; - this._iterable = iterable; - this._decoded = false; + get pollingInterval() { + return this._pollingInterval; } - get version() { - return this._version; + set pollingInterval(value) { + if (typeof value !== "number" || value <= 0 || parseInt(String(value)) != value) { + throw new Error("invalid polling interval"); + } + this._pollingInterval = value; + if (this._poller) { + clearInterval(this._poller); + this._poller = setInterval(()=>{ + this.poll(); + }, this._pollingInterval); + } } - async getRoots() { - return this._roots; + _getFastBlockNumber() { + const now2 = getTime(); + if (now2 - this._fastQueryDate > 2 * this._pollingInterval) { + this._fastQueryDate = now2; + this._fastBlockNumberPromise = this.getBlockNumber().then((blockNumber)=>{ + if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) { + this._fastBlockNumber = blockNumber; + } + return this._fastBlockNumber; + }); + } + return this._fastBlockNumberPromise; } -} -class CarBlockIterator extends CarIteratorBase { - [Symbol.asyncIterator]() { - if (this._decoded) { - throw new Error("Cannot decode more than once"); + _setFastBlockNumber(blockNumber) { + if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) { + return; } - if (!this._iterable) { - throw new Error("Block iterable not found"); + this._fastQueryDate = getTime(); + if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) { + this._fastBlockNumber = blockNumber; + this._fastBlockNumberPromise = Promise.resolve(blockNumber); } - this._decoded = true; - return this._iterable[Symbol.asyncIterator](); } - static async fromBytes(bytes) { - const { version, roots, iterator } = await fromBytes(bytes); - return new CarBlockIterator(version, roots, iterator); + waitForTransaction(transactionHash, confirmations, timeout) { + return __awaiter8(this, void 0, void 0, function*() { + return this._waitForTransaction(transactionHash, confirmations == null ? 1 : confirmations, timeout || 0, null); + }); } - static async fromIterable(asyncIterable) { - const { version, roots, iterator } = await fromIterable(asyncIterable); - return new CarBlockIterator(version, roots, iterator); + _waitForTransaction(transactionHash, confirmations, timeout, replaceable) { + return __awaiter8(this, void 0, void 0, function*() { + const receipt = yield this.getTransactionReceipt(transactionHash); + if ((receipt ? receipt.confirmations : 0) >= confirmations) { + return receipt; + } + return new Promise((resolve, reject)=>{ + const cancelFuncs = []; + let done = false; + const alreadyDone = function() { + if (done) { + return true; + } + done = true; + cancelFuncs.forEach((func)=>{ + func(); + }); + return false; + }; + const minedHandler = (receipt2)=>{ + if (receipt2.confirmations < confirmations) { + return; + } + if (alreadyDone()) { + return; + } + resolve(receipt2); + }; + this.on(transactionHash, minedHandler); + cancelFuncs.push(()=>{ + this.removeListener(transactionHash, minedHandler); + }); + if (replaceable) { + let lastBlockNumber = replaceable.startBlock; + let scannedBlock = null; + const replaceHandler = (blockNumber)=>__awaiter8(this, void 0, void 0, function*() { + if (done) { + return; + } + yield stall(1e3); + this.getTransactionCount(replaceable.from).then((nonce)=>__awaiter8(this, void 0, void 0, function*() { + if (done) { + return; + } + if (nonce <= replaceable.nonce) { + lastBlockNumber = blockNumber; + } else { + { + const mined = yield this.getTransaction(transactionHash); + if (mined && mined.blockNumber != null) { + return; + } + } + if (scannedBlock == null) { + scannedBlock = lastBlockNumber - 3; + if (scannedBlock < replaceable.startBlock) { + scannedBlock = replaceable.startBlock; + } + } + while(scannedBlock <= blockNumber){ + if (done) { + return; + } + const block = yield this.getBlockWithTransactions(scannedBlock); + for(let ti = 0; ti < block.transactions.length; ti++){ + const tx = block.transactions[ti]; + if (tx.hash === transactionHash) { + return; + } + if (tx.from === replaceable.from && tx.nonce === replaceable.nonce) { + if (done) { + return; + } + const receipt2 = yield this.waitForTransaction(tx.hash, confirmations); + if (alreadyDone()) { + return; + } + let reason = "replaced"; + if (tx.data === replaceable.data && tx.to === replaceable.to && tx.value.eq(replaceable.value)) { + reason = "repriced"; + } else if (tx.data === "0x" && tx.from === tx.to && tx.value.isZero()) { + reason = "cancelled"; + } + reject(logger$14.makeError("transaction was replaced", Logger.errors.TRANSACTION_REPLACED, { + cancelled: reason === "replaced" || reason === "cancelled", + reason, + replacement: this._wrapTransaction(tx), + hash: transactionHash, + receipt: receipt2 + })); + return; + } + } + scannedBlock++; + } + } + if (done) { + return; + } + this.once("block", replaceHandler); + }), (error)=>{ + if (done) { + return; + } + this.once("block", replaceHandler); + }); + }); + if (done) { + return; + } + this.once("block", replaceHandler); + cancelFuncs.push(()=>{ + this.removeListener("block", replaceHandler); + }); + } + if (typeof timeout === "number" && timeout > 0) { + const timer2 = setTimeout(()=>{ + if (alreadyDone()) { + return; + } + reject(logger$14.makeError("timeout exceeded", Logger.errors.TIMEOUT, { + timeout + })); + }, timeout); + if (timer2.unref) { + timer2.unref(); + } + cancelFuncs.push(()=>{ + clearTimeout(timer2); + }); + } + }); + }); } -} -class CarCIDIterator extends CarIteratorBase { - [Symbol.asyncIterator]() { - if (this._decoded) { - throw new Error("Cannot decode more than once"); + getBlockNumber() { + return __awaiter8(this, void 0, void 0, function*() { + return this._getInternalBlockNumber(0); + }); + } + getGasPrice() { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + const result = yield this.perform("getGasPrice", {}); + try { + return BigNumber.from(result); + } catch (error) { + return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { + method: "getGasPrice", + result, + error + }); + } + }); + } + getBalance(addressOrName, blockTag) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + const params = yield resolveProperties({ + address: this._getAddress(addressOrName), + blockTag: this._getBlockTag(blockTag) + }); + const result = yield this.perform("getBalance", params); + try { + return BigNumber.from(result); + } catch (error) { + return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { + method: "getBalance", + params, + result, + error + }); + } + }); + } + getTransactionCount(addressOrName, blockTag) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + const params = yield resolveProperties({ + address: this._getAddress(addressOrName), + blockTag: this._getBlockTag(blockTag) + }); + const result = yield this.perform("getTransactionCount", params); + try { + return BigNumber.from(result).toNumber(); + } catch (error) { + return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { + method: "getTransactionCount", + params, + result, + error + }); + } + }); + } + getCode(addressOrName, blockTag) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + const params = yield resolveProperties({ + address: this._getAddress(addressOrName), + blockTag: this._getBlockTag(blockTag) + }); + const result = yield this.perform("getCode", params); + try { + return hexlify(result); + } catch (error) { + return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { + method: "getCode", + params, + result, + error + }); + } + }); + } + getStorageAt(addressOrName, position, blockTag) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + const params = yield resolveProperties({ + address: this._getAddress(addressOrName), + blockTag: this._getBlockTag(blockTag), + position: Promise.resolve(position).then((p)=>hexValue(p)) + }); + const result = yield this.perform("getStorageAt", params); + try { + return hexlify(result); + } catch (error) { + return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { + method: "getStorageAt", + params, + result, + error + }); + } + }); + } + _wrapTransaction(tx, hash2, startBlock) { + if (hash2 != null && hexDataLength(hash2) !== 32) { + throw new Error("invalid response - sendTransaction"); } - if (!this._iterable) { - throw new Error("Block iterable not found"); + const result = tx; + if (hash2 != null && tx.hash !== hash2) { + logger$14.throwError("Transaction hash mismatch from Provider.sendTransaction.", Logger.errors.UNKNOWN_ERROR, { + expectedHash: tx.hash, + returnedHash: hash2 + }); } - this._decoded = true; - const iterable = this._iterable[Symbol.asyncIterator](); - return { - async next () { - const next = await iterable.next(); - if (next.done) { - return next; + result.wait = (confirms, timeout)=>__awaiter8(this, void 0, void 0, function*() { + if (confirms == null) { + confirms = 1; } - return { - done: false, - value: next.value.cid - }; + if (timeout == null) { + timeout = 0; + } + let replacement = void 0; + if (confirms !== 0 && startBlock != null) { + replacement = { + data: tx.data, + from: tx.from, + nonce: tx.nonce, + to: tx.to, + value: tx.value, + startBlock + }; + } + const receipt = yield this._waitForTransaction(tx.hash, confirms, timeout, replacement); + if (receipt == null && confirms === 0) { + return null; + } + this._emitted["t:" + tx.hash] = receipt.blockNumber; + if (receipt.status === 0) { + logger$14.throwError("transaction failed", Logger.errors.CALL_EXCEPTION, { + transactionHash: tx.hash, + transaction: tx, + receipt + }); + } + return receipt; + }); + return result; + } + sendTransaction(signedTransaction) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + const hexTx = yield Promise.resolve(signedTransaction).then((t)=>hexlify(t)); + const tx = this.formatter.transaction(signedTransaction); + if (tx.confirmations == null) { + tx.confirmations = 0; } - }; + const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); + try { + const hash2 = yield this.perform("sendTransaction", { + signedTransaction: hexTx + }); + return this._wrapTransaction(tx, hash2, blockNumber); + } catch (error) { + error.transaction = tx; + error.transactionHash = tx.hash; + throw error; + } + }); } - static async fromBytes(bytes) { - const { version, roots, iterator } = await fromBytes(bytes); - return new CarCIDIterator(version, roots, iterator); + _getTransactionRequest(transaction) { + return __awaiter8(this, void 0, void 0, function*() { + const values = yield transaction; + const tx = {}; + [ + "from", + "to" + ].forEach((key)=>{ + if (values[key] == null) { + return; + } + tx[key] = Promise.resolve(values[key]).then((v)=>v ? this._getAddress(v) : null); + }); + [ + "gasLimit", + "gasPrice", + "maxFeePerGas", + "maxPriorityFeePerGas", + "value" + ].forEach((key)=>{ + if (values[key] == null) { + return; + } + tx[key] = Promise.resolve(values[key]).then((v)=>v ? BigNumber.from(v) : null); + }); + [ + "type" + ].forEach((key)=>{ + if (values[key] == null) { + return; + } + tx[key] = Promise.resolve(values[key]).then((v)=>v != null ? v : null); + }); + if (values.accessList) { + tx.accessList = this.formatter.accessList(values.accessList); + } + [ + "data" + ].forEach((key)=>{ + if (values[key] == null) { + return; + } + tx[key] = Promise.resolve(values[key]).then((v)=>v ? hexlify(v) : null); + }); + return this.formatter.transactionRequest((yield resolveProperties(tx))); + }); } - static async fromIterable(asyncIterable) { - const { version, roots, iterator } = await fromIterable(asyncIterable); - return new CarCIDIterator(version, roots, iterator); + _getFilter(filter) { + return __awaiter8(this, void 0, void 0, function*() { + filter = yield filter; + const result = {}; + if (filter.address != null) { + result.address = this._getAddress(filter.address); + } + [ + "blockHash", + "topics" + ].forEach((key)=>{ + if (filter[key] == null) { + return; + } + result[key] = filter[key]; + }); + [ + "fromBlock", + "toBlock" + ].forEach((key)=>{ + if (filter[key] == null) { + return; + } + result[key] = this._getBlockTag(filter[key]); + }); + return this.formatter.filter((yield resolveProperties(result))); + }); } -} -async function fromBytes(bytes) { - if (!(bytes instanceof Uint8Array)) { - throw new TypeError("fromBytes() requires a Uint8Array"); + _call(transaction, blockTag, attempt) { + return __awaiter8(this, void 0, void 0, function*() { + if (attempt >= 10) { + logger$14.throwError("CCIP read exceeded maximum redirections", Logger.errors.SERVER_ERROR, { + redirects: attempt, + transaction + }); + } + const txSender = transaction.to; + const result = yield this.perform("call", { + transaction, + blockTag + }); + if (attempt >= 0 && blockTag === "latest" && txSender != null && result.substring(0, 10) === "0x556f1830" && hexDataLength(result) % 32 === 4) { + try { + const data = hexDataSlice(result, 4); + const sender = hexDataSlice(data, 0, 32); + if (!BigNumber.from(sender).eq(txSender)) { + logger$14.throwError("CCIP Read sender did not match", Logger.errors.CALL_EXCEPTION, { + name: "OffchainLookup", + signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + transaction, + data: result + }); + } + const urls = []; + const urlsOffset = BigNumber.from(hexDataSlice(data, 32, 64)).toNumber(); + const urlsLength = BigNumber.from(hexDataSlice(data, urlsOffset, urlsOffset + 32)).toNumber(); + const urlsData = hexDataSlice(data, urlsOffset + 32); + for(let u = 0; u < urlsLength; u++){ + const url = _parseString(urlsData, u * 32); + if (url == null) { + logger$14.throwError("CCIP Read contained corrupt URL string", Logger.errors.CALL_EXCEPTION, { + name: "OffchainLookup", + signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + transaction, + data: result + }); + } + urls.push(url); + } + const calldata = _parseBytes(data, 64); + if (!BigNumber.from(hexDataSlice(data, 100, 128)).isZero()) { + logger$14.throwError("CCIP Read callback selector included junk", Logger.errors.CALL_EXCEPTION, { + name: "OffchainLookup", + signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + transaction, + data: result + }); + } + const callbackSelector = hexDataSlice(data, 96, 100); + const extraData = _parseBytes(data, 128); + const ccipResult = yield this.ccipReadFetch(transaction, calldata, urls); + if (ccipResult == null) { + logger$14.throwError("CCIP Read disabled or provided no URLs", Logger.errors.CALL_EXCEPTION, { + name: "OffchainLookup", + signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + transaction, + data: result + }); + } + const tx = { + to: txSender, + data: hexConcat([ + callbackSelector, + encodeBytes([ + ccipResult, + extraData + ]) + ]) + }; + return this._call(tx, blockTag, attempt + 1); + } catch (error) { + if (error.code === Logger.errors.SERVER_ERROR) { + throw error; + } + } + } + try { + return hexlify(result); + } catch (error) { + return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { + method: "call", + params: { + transaction, + blockTag + }, + result, + error + }); + } + }); + } + call(transaction, blockTag) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + const resolved = yield resolveProperties({ + transaction: this._getTransactionRequest(transaction), + blockTag: this._getBlockTag(blockTag), + ccipReadEnabled: Promise.resolve(transaction.ccipReadEnabled) + }); + return this._call(resolved.transaction, resolved.blockTag, resolved.ccipReadEnabled ? 0 : -1); + }); + } + estimateGas(transaction) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + const params = yield resolveProperties({ + transaction: this._getTransactionRequest(transaction) + }); + const result = yield this.perform("estimateGas", params); + try { + return BigNumber.from(result); + } catch (error) { + return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { + method: "estimateGas", + params, + result, + error + }); + } + }); + } + _getAddress(addressOrName) { + return __awaiter8(this, void 0, void 0, function*() { + addressOrName = yield addressOrName; + if (typeof addressOrName !== "string") { + logger$14.throwArgumentError("invalid address or ENS name", "name", addressOrName); + } + const address2 = yield this.resolveName(addressOrName); + if (address2 == null) { + logger$14.throwError("ENS name not configured", Logger.errors.UNSUPPORTED_OPERATION, { + operation: `resolveName(${JSON.stringify(addressOrName)})` + }); + } + return address2; + }); + } + _getBlock(blockHashOrBlockTag, includeTransactions) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + blockHashOrBlockTag = yield blockHashOrBlockTag; + let blockNumber = -128; + const params = { + includeTransactions: !!includeTransactions + }; + if (isHexString(blockHashOrBlockTag, 32)) { + params.blockHash = blockHashOrBlockTag; + } else { + try { + params.blockTag = yield this._getBlockTag(blockHashOrBlockTag); + if (isHexString(params.blockTag)) { + blockNumber = parseInt(params.blockTag.substring(2), 16); + } + } catch (error) { + logger$14.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag); + } + } + return poll(()=>__awaiter8(this, void 0, void 0, function*() { + const block = yield this.perform("getBlock", params); + if (block == null) { + if (params.blockHash != null) { + if (this._emitted["b:" + params.blockHash] == null) { + return null; + } + } + if (params.blockTag != null) { + if (blockNumber > this._emitted.block) { + return null; + } + } + return void 0; + } + if (includeTransactions) { + let blockNumber2 = null; + for(let i = 0; i < block.transactions.length; i++){ + const tx = block.transactions[i]; + if (tx.blockNumber == null) { + tx.confirmations = 0; + } else if (tx.confirmations == null) { + if (blockNumber2 == null) { + blockNumber2 = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); + } + let confirmations = blockNumber2 - tx.blockNumber + 1; + if (confirmations <= 0) { + confirmations = 1; + } + tx.confirmations = confirmations; + } + } + const blockWithTxs = this.formatter.blockWithTransactions(block); + blockWithTxs.transactions = blockWithTxs.transactions.map((tx)=>this._wrapTransaction(tx)); + return blockWithTxs; + } + return this.formatter.block(block); + }), { + oncePoll: this + }); + }); + } + getBlock(blockHashOrBlockTag) { + return this._getBlock(blockHashOrBlockTag, false); + } + getBlockWithTransactions(blockHashOrBlockTag) { + return this._getBlock(blockHashOrBlockTag, true); + } + getTransaction(transactionHash) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + transactionHash = yield transactionHash; + const params = { + transactionHash: this.formatter.hash(transactionHash, true) + }; + return poll(()=>__awaiter8(this, void 0, void 0, function*() { + const result = yield this.perform("getTransaction", params); + if (result == null) { + if (this._emitted["t:" + transactionHash] == null) { + return null; + } + return void 0; + } + const tx = this.formatter.transactionResponse(result); + if (tx.blockNumber == null) { + tx.confirmations = 0; + } else if (tx.confirmations == null) { + const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); + let confirmations = blockNumber - tx.blockNumber + 1; + if (confirmations <= 0) { + confirmations = 1; + } + tx.confirmations = confirmations; + } + return this._wrapTransaction(tx); + }), { + oncePoll: this + }); + }); + } + getTransactionReceipt(transactionHash) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + transactionHash = yield transactionHash; + const params = { + transactionHash: this.formatter.hash(transactionHash, true) + }; + return poll(()=>__awaiter8(this, void 0, void 0, function*() { + const result = yield this.perform("getTransactionReceipt", params); + if (result == null) { + if (this._emitted["t:" + transactionHash] == null) { + return null; + } + return void 0; + } + if (result.blockHash == null) { + return void 0; + } + const receipt = this.formatter.receipt(result); + if (receipt.blockNumber == null) { + receipt.confirmations = 0; + } else if (receipt.confirmations == null) { + const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); + let confirmations = blockNumber - receipt.blockNumber + 1; + if (confirmations <= 0) { + confirmations = 1; + } + receipt.confirmations = confirmations; + } + return receipt; + }), { + oncePoll: this + }); + }); + } + getLogs(filter) { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + const params = yield resolveProperties({ + filter: this._getFilter(filter) + }); + const logs = yield this.perform("getLogs", params); + logs.forEach((log)=>{ + if (log.removed == null) { + log.removed = false; + } + }); + return Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs); + }); } - return decodeIterator(bytesReader(bytes)); -} -async function fromIterable(asyncIterable) { - if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === "function")) { - throw new TypeError("fromIterable() requires an async iterable"); + getEtherPrice() { + return __awaiter8(this, void 0, void 0, function*() { + yield this.getNetwork(); + return this.perform("getEtherPrice", {}); + }); } - return decodeIterator(asyncIterableReader(asyncIterable)); -} -async function decodeIterator(reader) { - const decoder2 = createDecoder(reader); - const { version, roots } = await decoder2.header(); - return { - version, - roots, - iterator: decoder2.blocks() - }; -} -class CarWriterOut { - constructor(iterator){ - this._iterator = iterator; + _getBlockTag(blockTag) { + return __awaiter8(this, void 0, void 0, function*() { + blockTag = yield blockTag; + if (typeof blockTag === "number" && blockTag < 0) { + if (blockTag % 1) { + logger$14.throwArgumentError("invalid BlockTag", "blockTag", blockTag); + } + let blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); + blockNumber += blockTag; + if (blockNumber < 0) { + blockNumber = 0; + } + return this.formatter.blockTag(blockNumber); + } + return this.formatter.blockTag(blockTag); + }); } - [Symbol.asyncIterator]() { - if (this._iterating) { - throw new Error("Multiple iterator not supported"); - } - this._iterating = true; - return this._iterator; + getResolver(name) { + return __awaiter8(this, void 0, void 0, function*() { + let currentName = name; + while(true){ + if (currentName === "" || currentName === ".") { + return null; + } + if (name !== "eth" && currentName === "eth") { + return null; + } + const addr = yield this._getResolver(currentName, "getResolver"); + if (addr != null) { + const resolver = new Resolver(this, addr, name); + if (currentName !== name && !(yield resolver.supportsWildcard())) { + return null; + } + return resolver; + } + currentName = currentName.split(".").slice(1).join("."); + } + }); } -} -const empty1 = new Uint8Array(0); -const toHex1 = (d)=>d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); -const fromHex1 = (hex)=>{ - const hexes = hex.match(/../g); - return hexes ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty1; -}; -const equals2 = (aa, bb)=>{ - if (aa === bb) return true; - if (aa.byteLength !== bb.byteLength) { - return false; + _getResolver(name, operation) { + return __awaiter8(this, void 0, void 0, function*() { + if (operation == null) { + operation = "ENS"; + } + const network = yield this.getNetwork(); + if (!network.ensAddress) { + logger$14.throwError("network does not support ENS", Logger.errors.UNSUPPORTED_OPERATION, { + operation, + network: network.name + }); + } + try { + const addrData = yield this.call({ + to: network.ensAddress, + data: "0x0178b8bf" + namehash(name).substring(2) + }); + return this.formatter.callAddress(addrData); + } catch (error) {} + return null; + }); } - for(let ii = 0; ii < aa.byteLength; ii++){ - if (aa[ii] !== bb[ii]) { - return false; - } + resolveName(name) { + return __awaiter8(this, void 0, void 0, function*() { + name = yield name; + try { + return Promise.resolve(this.formatter.address(name)); + } catch (error) { + if (isHexString(name)) { + throw error; + } + } + if (typeof name !== "string") { + logger$14.throwArgumentError("invalid ENS name", "name", name); + } + const resolver = yield this.getResolver(name); + if (!resolver) { + return null; + } + return yield resolver.getAddress(); + }); } - return true; -}; -const coerce1 = (o)=>{ - if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") return o; - if (o instanceof ArrayBuffer) return new Uint8Array(o); - if (ArrayBuffer.isView(o)) { - return new Uint8Array(o.buffer, o.byteOffset, o.byteLength); + lookupAddress(address2) { + return __awaiter8(this, void 0, void 0, function*() { + address2 = yield address2; + address2 = this.formatter.address(address2); + const node = address2.substring(2).toLowerCase() + ".addr.reverse"; + const resolverAddr = yield this._getResolver(node, "lookupAddress"); + if (resolverAddr == null) { + return null; + } + const name = _parseString((yield this.call({ + to: resolverAddr, + data: "0x691f3431" + namehash(node).substring(2) + })), 0); + const addr = yield this.resolveName(name); + if (addr != address2) { + return null; + } + return name; + }); } - throw new Error("Unknown type, must be binary type"); -}; -const isBinary1 = (o)=>o instanceof ArrayBuffer || ArrayBuffer.isView(o); -const fromString2 = (str)=>new TextEncoder().encode(str); -const toString2 = (b)=>new TextDecoder().decode(b); -var bytes = Object.freeze({ - __proto__: null, - equals: equals2, - coerce: coerce1, - isBinary: isBinary1, - fromHex: fromHex1, - toHex: toHex1, - fromString: fromString2, - toString: toString2, - empty: empty1 -}); -var encode_12 = encode5; -var MSB2 = 128, REST3 = 127, MSBALL2 = ~REST3, INT2 = Math.pow(2, 31); -function encode5(num, out, offset) { - out = out || []; - offset = offset || 0; - var oldOffset = offset; - while(num >= INT2){ - out[offset++] = num & 255 | MSB2; - num /= 128; + getAvatar(nameOrAddress) { + return __awaiter8(this, void 0, void 0, function*() { + let resolver = null; + if (isHexString(nameOrAddress)) { + const address2 = this.formatter.address(nameOrAddress); + const node = address2.substring(2).toLowerCase() + ".addr.reverse"; + const resolverAddress = yield this._getResolver(node, "getAvatar"); + if (!resolverAddress) { + return null; + } + resolver = new Resolver(this, resolverAddress, node); + try { + const avatar2 = yield resolver.getAvatar(); + if (avatar2) { + return avatar2.url; + } + } catch (error) { + if (error.code !== Logger.errors.CALL_EXCEPTION) { + throw error; + } + } + try { + const name = _parseString((yield this.call({ + to: resolverAddress, + data: "0x691f3431" + namehash(node).substring(2) + })), 0); + resolver = yield this.getResolver(name); + } catch (error) { + if (error.code !== Logger.errors.CALL_EXCEPTION) { + throw error; + } + return null; + } + } else { + resolver = yield this.getResolver(nameOrAddress); + if (!resolver) { + return null; + } + } + const avatar = yield resolver.getAvatar(); + if (avatar == null) { + return null; + } + return avatar.url; + }); } - while(num & MSBALL2){ - out[offset++] = num & 255 | MSB2; - num >>>= 7; + perform(method, params) { + return logger$14.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { + operation: method + }); } - out[offset] = num | 0; - encode5.bytes = offset - oldOffset + 1; - return out; -} -var decode6 = read2; -var MSB$12 = 128, REST$12 = 127; -function read2(buf, offset) { - var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; - do { - if (counter >= l) { - read2.bytes = 0; - throw new RangeError("Could not decode varint"); - } - b = buf[counter++]; - res += shift < 28 ? (b & REST$12) << shift : (b & REST$12) * Math.pow(2, shift); - shift += 7; - }while (b >= MSB$12) - read2.bytes = counter - offset; - return res; -} -var N12 = Math.pow(2, 7); -var N22 = Math.pow(2, 14); -var N32 = Math.pow(2, 21); -var N42 = Math.pow(2, 28); -var N52 = Math.pow(2, 35); -var N62 = Math.pow(2, 42); -var N72 = Math.pow(2, 49); -var N82 = Math.pow(2, 56); -var N92 = Math.pow(2, 63); -var length2 = function(value) { - return value < N12 ? 1 : value < N22 ? 2 : value < N32 ? 3 : value < N42 ? 4 : value < N52 ? 5 : value < N62 ? 6 : value < N72 ? 7 : value < N82 ? 8 : value < N92 ? 9 : 10; -}; -var varint2 = { - encode: encode_12, - decode: decode6, - encodingLength: length2 -}; -var _brrp_varint1 = varint2; -const decode$11 = (data, offset = 0)=>{ - const code = _brrp_varint1.decode(data, offset); - return [ - code, - _brrp_varint1.decode.bytes - ]; -}; -const encodeTo1 = (__int, target, offset = 0)=>{ - _brrp_varint1.encode(__int, target, offset); - return target; -}; -const encodingLength1 = (__int)=>{ - return _brrp_varint1.encodingLength(__int); -}; -Object.freeze({ - __proto__: null, - decode: decode$11, - encodeTo: encodeTo1, - encodingLength: encodingLength1 -}); -const create1 = (code, digest2)=>{ - const size = digest2.byteLength; - const sizeOffset = encodingLength1(code); - const digestOffset = sizeOffset + encodingLength1(size); - const bytes = new Uint8Array(digestOffset + size); - encodeTo1(code, bytes, 0); - encodeTo1(size, bytes, sizeOffset); - bytes.set(digest2, digestOffset); - return new Digest1(code, size, digest2, bytes); -}; -const decode$21 = (multihash)=>{ - const bytes = coerce1(multihash); - const [code, sizeOffset] = decode$11(bytes); - const [size, digestOffset] = decode$11(bytes.subarray(sizeOffset)); - const digest2 = bytes.subarray(sizeOffset + digestOffset); - if (digest2.byteLength !== size) { - throw new Error("Incorrect length"); + _startEvent(event) { + this.polling = this._events.filter((e)=>e.pollable()).length > 0; } - return new Digest1(code, size, digest2, bytes); -}; -const equals3 = (a, b)=>{ - if (a === b) { - return true; - } else { - return a.code === b.code && a.size === b.size && equals2(a.bytes, b.bytes); + _stopEvent(event) { + this.polling = this._events.filter((e)=>e.pollable()).length > 0; } -}; -class Digest1 { - constructor(code, size, digest2, bytes){ - this.code = code; - this.size = size; - this.digest = digest2; - this.bytes = bytes; + _addEventListener(eventName, listener, once) { + const event = new Event(getEventTag1(eventName), listener, once); + this._events.push(event); + this._startEvent(event); + return this; } -} -Object.freeze({ - __proto__: null, - create: create1, - decode: decode$21, - equals: equals3, - Digest: Digest1 -}); -const from1 = ({ name, code, encode })=>new Hasher(name, code, encode); -class Hasher { - constructor(name, code, encode){ - this.name = name; - this.code = code; - this.encode = encode; + on(eventName, listener) { + return this._addEventListener(eventName, listener, false); } - digest(input) { - if (input instanceof Uint8Array) { - const result = this.encode(input); - return result instanceof Uint8Array ? create1(this.code, result) : result.then((digest$1)=>create1(this.code, digest$1)); - } else { - throw Error("Unknown type, must be binary type"); - } + once(eventName, listener) { + return this._addEventListener(eventName, listener, true); } -} -Object.freeze({ - __proto__: null, - from: from1, - Hasher -}); -const sha = (name)=>async (data)=>new Uint8Array(await crypto.subtle.digest(name, data)); -const sha256 = from1({ - name: "sha2-256", - code: 18, - encode: sha("SHA-256") -}); -const sha512 = from1({ - name: "sha2-512", - code: 19, - encode: sha("SHA-512") -}); -var sha2 = Object.freeze({ - __proto__: null, - sha256, - sha512 -}); -const empty2 = new Uint8Array(0); -const toHex2 = (d)=>d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); -const fromHex2 = (hex)=>{ - const hexes = hex.match(/../g); - return hexes ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty2; -}; -const equals4 = (aa, bb)=>{ - if (aa === bb) return true; - if (aa.byteLength !== bb.byteLength) { - return false; + emit(eventName, ...args) { + let result = false; + let stopped = []; + let eventTag = getEventTag1(eventName); + this._events = this._events.filter((event)=>{ + if (event.tag !== eventTag) { + return true; + } + setTimeout(()=>{ + event.listener.apply(this, args); + }, 0); + result = true; + if (event.once) { + stopped.push(event); + return false; + } + return true; + }); + stopped.forEach((event)=>{ + this._stopEvent(event); + }); + return result; } - for(let ii = 0; ii < aa.byteLength; ii++){ - if (aa[ii] !== bb[ii]) { + listenerCount(eventName) { + if (!eventName) { + return this._events.length; + } + let eventTag = getEventTag1(eventName); + return this._events.filter((event)=>{ + return event.tag === eventTag; + }).length; + } + listeners(eventName) { + if (eventName == null) { + return this._events.map((event)=>event.listener); + } + let eventTag = getEventTag1(eventName); + return this._events.filter((event)=>event.tag === eventTag).map((event)=>event.listener); + } + off(eventName, listener) { + if (listener == null) { + return this.removeAllListeners(eventName); + } + const stopped = []; + let found = false; + let eventTag = getEventTag1(eventName); + this._events = this._events.filter((event)=>{ + if (event.tag !== eventTag || event.listener != listener) { + return true; + } + if (found) { + return true; + } + found = true; + stopped.push(event); return false; + }); + stopped.forEach((event)=>{ + this._stopEvent(event); + }); + return this; + } + removeAllListeners(eventName) { + let stopped = []; + if (eventName == null) { + stopped = this._events; + this._events = []; + } else { + const eventTag = getEventTag1(eventName); + this._events = this._events.filter((event)=>{ + if (event.tag !== eventTag) { + return true; + } + stopped.push(event); + return false; + }); } + stopped.forEach((event)=>{ + this._stopEvent(event); + }); + return this; } - return true; -}; -const coerce2 = (o)=>{ - if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") return o; - if (o instanceof ArrayBuffer) return new Uint8Array(o); - if (ArrayBuffer.isView(o)) { - return new Uint8Array(o.buffer, o.byteOffset, o.byteLength); +} +var __awaiter$11 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); } - throw new Error("Unknown type, must be binary type"); + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); }; -const isBinary2 = (o)=>o instanceof ArrayBuffer || ArrayBuffer.isView(o); -const fromString3 = (str)=>new TextEncoder().encode(str); -const toString3 = (b)=>new TextDecoder().decode(b); -var bytes1 = Object.freeze({ - __proto__: null, - equals: equals4, - coerce: coerce2, - isBinary: isBinary2, - fromHex: fromHex2, - toHex: toHex2, - fromString: fromString3, - toString: toString3, - empty: empty2 -}); -var encode_13 = encode6; -var MSB3 = 128, REST4 = 127, MSBALL3 = ~REST4, INT3 = Math.pow(2, 31); -function encode6(num, out, offset) { - out = out || []; - offset = offset || 0; - var oldOffset = offset; - while(num >= INT3){ - out[offset++] = num & 255 | MSB3; - num /= 128; +const logger$21 = new Logger(version23); +const errorGas = [ + "call", + "estimateGas" +]; +function spelunk(value, requireData) { + if (value == null) { + return null; } - while(num & MSBALL3){ - out[offset++] = num & 255 | MSB3; - num >>>= 7; + if (typeof value.message === "string" && value.message.match("reverted")) { + const data = isHexString(value.data) ? value.data : null; + if (!requireData || data) { + return { + message: value.message, + data + }; + } } - out[offset] = num | 0; - encode6.bytes = offset - oldOffset + 1; - return out; -} -var decode7 = read3; -var MSB$13 = 128, REST$13 = 127; -function read3(buf, offset) { - var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; - do { - if (counter >= l) { - read3.bytes = 0; - throw new RangeError("Could not decode varint"); + if (typeof value === "object") { + for(const key in value){ + const result = spelunk(value[key], requireData); + if (result) { + return result; + } } - b = buf[counter++]; - res += shift < 28 ? (b & REST$13) << shift : (b & REST$13) * Math.pow(2, shift); - shift += 7; - }while (b >= MSB$13) - read3.bytes = counter - offset; - return res; + return null; + } + if (typeof value === "string") { + try { + return spelunk(JSON.parse(value), requireData); + } catch (error) {} + } + return null; } -var N13 = Math.pow(2, 7); -var N23 = Math.pow(2, 14); -var N33 = Math.pow(2, 21); -var N43 = Math.pow(2, 28); -var N53 = Math.pow(2, 35); -var N63 = Math.pow(2, 42); -var N73 = Math.pow(2, 49); -var N83 = Math.pow(2, 56); -var N93 = Math.pow(2, 63); -var length3 = function(value) { - return value < N13 ? 1 : value < N23 ? 2 : value < N33 ? 3 : value < N43 ? 4 : value < N53 ? 5 : value < N63 ? 6 : value < N73 ? 7 : value < N83 ? 8 : value < N93 ? 9 : 10; -}; -var varint3 = { - encode: encode_13, - decode: decode7, - encodingLength: length3 -}; -var _brrp_varint2 = varint3; -const decode$12 = (data)=>{ - const code = _brrp_varint2.decode(data); - return [ - code, - _brrp_varint2.decode.bytes - ]; -}; -const encodeTo2 = (__int, target, offset = 0)=>{ - _brrp_varint2.encode(__int, target, offset); - return target; -}; -const encodingLength2 = (__int)=>{ - return _brrp_varint2.encodingLength(__int); -}; -Object.freeze({ - __proto__: null, - decode: decode$12, - encodeTo: encodeTo2, - encodingLength: encodingLength2 -}); -const create2 = (code, digest2)=>{ - const size = digest2.byteLength; - const sizeOffset = encodingLength2(code); - const digestOffset = sizeOffset + encodingLength2(size); - const bytes = new Uint8Array(digestOffset + size); - encodeTo2(code, bytes, 0); - encodeTo2(size, bytes, sizeOffset); - bytes.set(digest2, digestOffset); - return new Digest2(code, size, digest2, bytes); -}; -const decode$22 = (multihash)=>{ - const bytes = coerce2(multihash); - const [code, sizeOffset] = decode$12(bytes); - const [size, digestOffset] = decode$12(bytes.subarray(sizeOffset)); - const digest2 = bytes.subarray(sizeOffset + digestOffset); - if (digest2.byteLength !== size) { - throw new Error("Incorrect length"); +function checkError(method, error, params) { + const transaction = params.transaction || params.signedTransaction; + if (method === "call") { + const result = spelunk(error, true); + if (result) { + return result.data; + } + logger$21.throwError("missing revert data in call exception; Transaction reverted without a reason string", Logger.errors.CALL_EXCEPTION, { + data: "0x", + transaction, + error + }); } - return new Digest2(code, size, digest2, bytes); -}; -const equals5 = (a, b)=>{ - if (a === b) { - return true; - } else { - return a.code === b.code && a.size === b.size && equals4(a.bytes, b.bytes); + if (method === "estimateGas") { + let result = spelunk(error.body, false); + if (result == null) { + result = spelunk(error, false); + } + if (result) { + logger$21.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, { + reason: result.message, + method, + transaction, + error + }); + } } -}; -class Digest2 { - constructor(code, size, digest2, bytes){ - this.code = code; - this.size = size; - this.digest = digest2; - this.bytes = bytes; + let message = error.message; + if (error.code === Logger.errors.SERVER_ERROR && error.error && typeof error.error.message === "string") { + message = error.error.message; + } else if (typeof error.body === "string") { + message = error.body; + } else if (typeof error.responseText === "string") { + message = error.responseText; + } + message = (message || "").toLowerCase(); + if (message.match(/insufficient funds|base fee exceeds gas limit|InsufficientFunds/i)) { + logger$21.throwError("insufficient funds for intrinsic transaction cost", Logger.errors.INSUFFICIENT_FUNDS, { + error, + method, + transaction + }); + } + if (message.match(/nonce (is )?too low/i)) { + logger$21.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, { + error, + method, + transaction + }); + } + if (message.match(/replacement transaction underpriced|transaction gas price.*too low/i)) { + logger$21.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, { + error, + method, + transaction + }); + } + if (message.match(/only replay-protected/i)) { + logger$21.throwError("legacy pre-eip-155 transactions not supported", Logger.errors.UNSUPPORTED_OPERATION, { + error, + method, + transaction + }); + } + if (errorGas.indexOf(method) >= 0 && message.match(/gas required exceeds allowance|always failing transaction|execution reverted|revert/)) { + logger$21.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, { + error, + method, + transaction + }); } + throw error; } -Object.freeze({ - __proto__: null, - create: create2, - decode: decode$22, - equals: equals5, - Digest: Digest2 -}); -const from2 = ({ name, code, encode })=>new Hasher1(name, code, encode); -class Hasher1 { - constructor(name, code, encode){ - this.name = name; - this.code = code; - this.encode = encode; +function timer(timeout) { + return new Promise(function(resolve) { + setTimeout(resolve, timeout); + }); +} +function getResult(payload) { + if (payload.error) { + const error = new Error(payload.error.message); + error.code = payload.error.code; + error.data = payload.error.data; + throw error; } - digest(input) { - if (input instanceof Uint8Array) { - const result = this.encode(input); - return result instanceof Uint8Array ? create2(this.code, result) : result.then((digest$1)=>create2(this.code, digest$1)); + return payload.result; +} +function getLowerCase(value) { + if (value) { + return value.toLowerCase(); + } + return value; +} +const _constructorGuard3 = {}; +class JsonRpcSigner extends Signer { + constructor(constructorGuard, provider, addressOrIndex){ + super(); + if (constructorGuard !== _constructorGuard3) { + throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner"); + } + defineReadOnly(this, "provider", provider); + if (addressOrIndex == null) { + addressOrIndex = 0; + } + if (typeof addressOrIndex === "string") { + defineReadOnly(this, "_address", this.provider.formatter.address(addressOrIndex)); + defineReadOnly(this, "_index", null); + } else if (typeof addressOrIndex === "number") { + defineReadOnly(this, "_index", addressOrIndex); + defineReadOnly(this, "_address", null); } else { - throw Error("Unknown type, must be binary type"); + logger$21.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex); } } -} -Object.freeze({ - __proto__: null, - from: from2, - Hasher: Hasher1 -}); -function base1(ALPHABET, name) { - if (ALPHABET.length >= 255) { - throw new TypeError("Alphabet too long"); + connect(provider) { + return logger$21.throwError("cannot alter JSON-RPC Signer connection", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "connect" + }); } - var BASE_MAP = new Uint8Array(256); - for(var j = 0; j < BASE_MAP.length; j++){ - BASE_MAP[j] = 255; + connectUnchecked() { + return new UncheckedJsonRpcSigner(_constructorGuard3, this.provider, this._address || this._index); + } + getAddress() { + if (this._address) { + return Promise.resolve(this._address); + } + return this.provider.send("eth_accounts", []).then((accounts)=>{ + if (accounts.length <= this._index) { + logger$21.throwError("unknown account #" + this._index, Logger.errors.UNSUPPORTED_OPERATION, { + operation: "getAddress" + }); + } + return this.provider.formatter.address(accounts[this._index]); + }); + } + sendUncheckedTransaction(transaction) { + transaction = shallowCopy(transaction); + const fromAddress = this.getAddress().then((address2)=>{ + if (address2) { + address2 = address2.toLowerCase(); + } + return address2; + }); + if (transaction.gasLimit == null) { + const estimate = shallowCopy(transaction); + estimate.from = fromAddress; + transaction.gasLimit = this.provider.estimateGas(estimate); + } + if (transaction.to != null) { + transaction.to = Promise.resolve(transaction.to).then((to)=>__awaiter$11(this, void 0, void 0, function*() { + if (to == null) { + return null; + } + const address2 = yield this.provider.resolveName(to); + if (address2 == null) { + logger$21.throwArgumentError("provided ENS name resolves to null", "tx.to", to); + } + return address2; + })); + } + return resolveProperties({ + tx: resolveProperties(transaction), + sender: fromAddress + }).then(({ tx, sender })=>{ + if (tx.from != null) { + if (tx.from.toLowerCase() !== sender) { + logger$21.throwArgumentError("from address mismatch", "transaction", transaction); + } + } else { + tx.from = sender; + } + const hexTx = this.provider.constructor.hexlifyTransaction(tx, { + from: true + }); + return this.provider.send("eth_sendTransaction", [ + hexTx + ]).then((hash2)=>{ + return hash2; + }, (error)=>{ + if (typeof error.message === "string" && error.message.match(/user denied/i)) { + logger$21.throwError("user rejected transaction", Logger.errors.ACTION_REJECTED, { + action: "sendTransaction", + transaction: tx + }); + } + return checkError("sendTransaction", error, hexTx); + }); + }); + } + signTransaction(transaction) { + return logger$21.throwError("signing transactions is unsupported", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "signTransaction" + }); + } + sendTransaction(transaction) { + return __awaiter$11(this, void 0, void 0, function*() { + const blockNumber = yield this.provider._getInternalBlockNumber(100 + 2 * this.provider.pollingInterval); + const hash2 = yield this.sendUncheckedTransaction(transaction); + try { + return yield poll(()=>__awaiter$11(this, void 0, void 0, function*() { + const tx = yield this.provider.getTransaction(hash2); + if (tx === null) { + return void 0; + } + return this.provider._wrapTransaction(tx, hash2, blockNumber); + }), { + oncePoll: this.provider + }); + } catch (error) { + error.transactionHash = hash2; + throw error; + } + }); + } + signMessage(message) { + return __awaiter$11(this, void 0, void 0, function*() { + const data = typeof message === "string" ? toUtf8Bytes(message) : message; + const address2 = yield this.getAddress(); + try { + return yield this.provider.send("personal_sign", [ + hexlify(data), + address2.toLowerCase() + ]); + } catch (error) { + if (typeof error.message === "string" && error.message.match(/user denied/i)) { + logger$21.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, { + action: "signMessage", + from: address2, + messageData: message + }); + } + throw error; + } + }); + } + _legacySignMessage(message) { + return __awaiter$11(this, void 0, void 0, function*() { + const data = typeof message === "string" ? toUtf8Bytes(message) : message; + const address2 = yield this.getAddress(); + try { + return yield this.provider.send("eth_sign", [ + address2.toLowerCase(), + hexlify(data) + ]); + } catch (error) { + if (typeof error.message === "string" && error.message.match(/user denied/i)) { + logger$21.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, { + action: "_legacySignMessage", + from: address2, + messageData: message + }); + } + throw error; + } + }); + } + _signTypedData(domain, types, value) { + return __awaiter$11(this, void 0, void 0, function*() { + const populated = yield TypedDataEncoder.resolveNames(domain, types, value, (name)=>{ + return this.provider.resolveName(name); + }); + const address2 = yield this.getAddress(); + try { + return yield this.provider.send("eth_signTypedData_v4", [ + address2.toLowerCase(), + JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types, populated.value)) + ]); + } catch (error) { + if (typeof error.message === "string" && error.message.match(/user denied/i)) { + logger$21.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, { + action: "_signTypedData", + from: address2, + messageData: { + domain: populated.domain, + types, + value: populated.value + } + }); + } + throw error; + } + }); + } + unlock(password) { + return __awaiter$11(this, void 0, void 0, function*() { + const provider = this.provider; + const address2 = yield this.getAddress(); + return provider.send("personal_unlockAccount", [ + address2.toLowerCase(), + password, + null + ]); + }); } - for(var i = 0; i < ALPHABET.length; i++){ - var x = ALPHABET.charAt(i); - var xc = x.charCodeAt(0); - if (BASE_MAP[xc] !== 255) { - throw new TypeError(x + " is ambiguous"); - } - BASE_MAP[xc] = i; +} +class UncheckedJsonRpcSigner extends JsonRpcSigner { + sendTransaction(transaction) { + return this.sendUncheckedTransaction(transaction).then((hash2)=>{ + return { + hash: hash2, + nonce: null, + gasLimit: null, + gasPrice: null, + data: null, + value: null, + chainId: null, + confirmations: 0, + from: null, + wait: (confirmations)=>{ + return this.provider.waitForTransaction(hash2, confirmations); + } + }; + }); } - var BASE = ALPHABET.length; - var LEADER = ALPHABET.charAt(0); - var FACTOR = Math.log(BASE) / Math.log(256); - var iFACTOR = Math.log(256) / Math.log(BASE); - function encode2(source) { - if (source instanceof Uint8Array) ; - else if (ArrayBuffer.isView(source)) { - source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); - } else if (Array.isArray(source)) { - source = Uint8Array.from(source); +} +const allowedTransactionKeys3 = { + chainId: true, + data: true, + gasLimit: true, + gasPrice: true, + nonce: true, + to: true, + value: true, + type: true, + accessList: true, + maxFeePerGas: true, + maxPriorityFeePerGas: true +}; +class JsonRpcProvider extends BaseProvider { + constructor(url, network){ + let networkOrReady = network; + if (networkOrReady == null) { + networkOrReady = new Promise((resolve, reject)=>{ + setTimeout(()=>{ + this.detectNetwork().then((network2)=>{ + resolve(network2); + }, (error)=>{ + reject(error); + }); + }, 0); + }); } - if (!(source instanceof Uint8Array)) { - throw new TypeError("Expected Uint8Array"); + super(networkOrReady); + if (!url) { + url = getStatic(this.constructor, "defaultUrl")(); } - if (source.length === 0) { - return ""; + if (typeof url === "string") { + defineReadOnly(this, "connection", Object.freeze({ + url + })); + } else { + defineReadOnly(this, "connection", Object.freeze(shallowCopy(url))); } - var zeroes = 0; - var length = 0; - var pbegin = 0; - var pend = source.length; - while(pbegin !== pend && source[pbegin] === 0){ - pbegin++; - zeroes++; + this._nextId = 42; + } + get _cache() { + if (this._eventLoopCache == null) { + this._eventLoopCache = {}; } - var size = (pend - pbegin) * iFACTOR + 1 >>> 0; - var b58 = new Uint8Array(size); - while(pbegin !== pend){ - var carry = source[pbegin]; - var i2 = 0; - for(var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++){ - carry += 256 * b58[it1] >>> 0; - b58[it1] = carry % BASE >>> 0; - carry = carry / BASE >>> 0; + return this._eventLoopCache; + } + static defaultUrl() { + return "http://localhost:8545"; + } + detectNetwork() { + if (!this._cache["detectNetwork"]) { + this._cache["detectNetwork"] = this._uncachedDetectNetwork(); + setTimeout(()=>{ + this._cache["detectNetwork"] = null; + }, 0); + } + return this._cache["detectNetwork"]; + } + _uncachedDetectNetwork() { + return __awaiter$11(this, void 0, void 0, function*() { + yield timer(0); + let chainId = null; + try { + chainId = yield this.send("eth_chainId", []); + } catch (error) { + try { + chainId = yield this.send("net_version", []); + } catch (error2) {} } - if (carry !== 0) { - throw new Error("Non-zero carry"); + if (chainId != null) { + const getNetwork3 = getStatic(this.constructor, "getNetwork"); + try { + return getNetwork3(BigNumber.from(chainId).toNumber()); + } catch (error) { + return logger$21.throwError("could not detect network", Logger.errors.NETWORK_ERROR, { + chainId, + event: "invalidNetwork", + serverError: error + }); + } } - length = i2; - pbegin++; - } - var it2 = size - length; - while(it2 !== size && b58[it2] === 0){ - it2++; - } - var str = LEADER.repeat(zeroes); - for(; it2 < size; ++it2){ - str += ALPHABET.charAt(b58[it2]); + return logger$21.throwError("could not detect network", Logger.errors.NETWORK_ERROR, { + event: "noNetwork" + }); + }); + } + getSigner(addressOrIndex) { + return new JsonRpcSigner(_constructorGuard3, this, addressOrIndex); + } + getUncheckedSigner(addressOrIndex) { + return this.getSigner(addressOrIndex).connectUnchecked(); + } + listAccounts() { + return this.send("eth_accounts", []).then((accounts)=>{ + return accounts.map((a)=>this.formatter.address(a)); + }); + } + send(method, params) { + const request = { + method, + params, + id: this._nextId++, + jsonrpc: "2.0" + }; + this.emit("debug", { + action: "request", + request: deepCopy(request), + provider: this + }); + const cache = [ + "eth_chainId", + "eth_blockNumber" + ].indexOf(method) >= 0; + if (cache && this._cache[method]) { + return this._cache[method]; + } + const result = fetchJson(this.connection, JSON.stringify(request), getResult).then((result2)=>{ + this.emit("debug", { + action: "response", + request, + response: result2, + provider: this + }); + return result2; + }, (error)=>{ + this.emit("debug", { + action: "response", + error, + request, + provider: this + }); + throw error; + }); + if (cache) { + this._cache[method] = result; + setTimeout(()=>{ + this._cache[method] = null; + }, 0); } - return str; + return result; } - function decodeUnsafe(source) { - if (typeof source !== "string") { - throw new TypeError("Expected String"); + prepareRequest(method, params) { + switch(method){ + case "getBlockNumber": + return [ + "eth_blockNumber", + [] + ]; + case "getGasPrice": + return [ + "eth_gasPrice", + [] + ]; + case "getBalance": + return [ + "eth_getBalance", + [ + getLowerCase(params.address), + params.blockTag + ] + ]; + case "getTransactionCount": + return [ + "eth_getTransactionCount", + [ + getLowerCase(params.address), + params.blockTag + ] + ]; + case "getCode": + return [ + "eth_getCode", + [ + getLowerCase(params.address), + params.blockTag + ] + ]; + case "getStorageAt": + return [ + "eth_getStorageAt", + [ + getLowerCase(params.address), + hexZeroPad(params.position, 32), + params.blockTag + ] + ]; + case "sendTransaction": + return [ + "eth_sendRawTransaction", + [ + params.signedTransaction + ] + ]; + case "getBlock": + if (params.blockTag) { + return [ + "eth_getBlockByNumber", + [ + params.blockTag, + !!params.includeTransactions + ] + ]; + } else if (params.blockHash) { + return [ + "eth_getBlockByHash", + [ + params.blockHash, + !!params.includeTransactions + ] + ]; + } + return null; + case "getTransaction": + return [ + "eth_getTransactionByHash", + [ + params.transactionHash + ] + ]; + case "getTransactionReceipt": + return [ + "eth_getTransactionReceipt", + [ + params.transactionHash + ] + ]; + case "call": + { + const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction"); + return [ + "eth_call", + [ + hexlifyTransaction(params.transaction, { + from: true + }), + params.blockTag + ] + ]; + } + case "estimateGas": + { + const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction"); + return [ + "eth_estimateGas", + [ + hexlifyTransaction(params.transaction, { + from: true + }) + ] + ]; + } + case "getLogs": + if (params.filter && params.filter.address != null) { + params.filter.address = getLowerCase(params.filter.address); + } + return [ + "eth_getLogs", + [ + params.filter + ] + ]; } - if (source.length === 0) { - return new Uint8Array(); + return null; + } + perform(method, params) { + return __awaiter$11(this, void 0, void 0, function*() { + if (method === "call" || method === "estimateGas") { + const tx = params.transaction; + if (tx && tx.type != null && BigNumber.from(tx.type).isZero()) { + if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { + const feeData = yield this.getFeeData(); + if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { + params = shallowCopy(params); + params.transaction = shallowCopy(tx); + delete params.transaction.type; + } + } + } + } + const args = this.prepareRequest(method, params); + if (args == null) { + logger$21.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { + operation: method + }); + } + try { + return yield this.send(args[0], args[1]); + } catch (error) { + return checkError(method, error, params); + } + }); + } + _startEvent(event) { + if (event.tag === "pending") { + this._startPending(); } - var psz = 0; - if (source[psz] === " ") { + super._startEvent(event); + } + _startPending() { + if (this._pendingFilter != null) { return; } - var zeroes = 0; - var length = 0; - while(source[psz] === LEADER){ - zeroes++; - psz++; + const self1 = this; + const pendingFilter = this.send("eth_newPendingTransactionFilter", []); + this._pendingFilter = pendingFilter; + pendingFilter.then(function(filterId) { + function poll2() { + self1.send("eth_getFilterChanges", [ + filterId + ]).then(function(hashes) { + if (self1._pendingFilter != pendingFilter) { + return null; + } + let seq = Promise.resolve(); + hashes.forEach(function(hash2) { + self1._emitted["t:" + hash2.toLowerCase()] = "pending"; + seq = seq.then(function() { + return self1.getTransaction(hash2).then(function(tx) { + self1.emit("pending", tx); + return null; + }); + }); + }); + return seq.then(function() { + return timer(1e3); + }); + }).then(function() { + if (self1._pendingFilter != pendingFilter) { + self1.send("eth_uninstallFilter", [ + filterId + ]); + return; + } + setTimeout(function() { + poll2(); + }, 0); + return null; + }).catch((error)=>{}); + } + poll2(); + return filterId; + }).catch((error)=>{}); + } + _stopEvent(event) { + if (event.tag === "pending" && this.listenerCount("pending") === 0) { + this._pendingFilter = null; + } + super._stopEvent(event); + } + static hexlifyTransaction(transaction, allowExtra) { + const allowed = shallowCopy(allowedTransactionKeys3); + if (allowExtra) { + for(const key in allowExtra){ + if (allowExtra[key]) { + allowed[key] = true; + } + } } - var size = (source.length - psz) * FACTOR + 1 >>> 0; - var b256 = new Uint8Array(size); - while(source[psz]){ - var carry = BASE_MAP[source.charCodeAt(psz)]; - if (carry === 255) { + checkProperties(transaction, allowed); + const result = {}; + [ + "chainId", + "gasLimit", + "gasPrice", + "type", + "maxFeePerGas", + "maxPriorityFeePerGas", + "nonce", + "value" + ].forEach(function(key) { + if (transaction[key] == null) { return; } - var i2 = 0; - for(var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++){ - carry += BASE * b256[it3] >>> 0; - b256[it3] = carry % 256 >>> 0; - carry = carry / 256 >>> 0; + const value = hexValue(BigNumber.from(transaction[key])); + if (key === "gasLimit") { + key = "gas"; } - if (carry !== 0) { - throw new Error("Non-zero carry"); + result[key] = value; + }); + [ + "from", + "to", + "data" + ].forEach(function(key) { + if (transaction[key] == null) { + return; } - length = i2; - psz++; + result[key] = hexlify(transaction[key]); + }); + if (transaction.accessList) { + result["accessList"] = accessListify(transaction.accessList); } - if (source[psz] === " ") { - return; + return result; + } +} +let WS = null; +try { + WS = WebSocket; + if (WS == null) { + throw new Error("inject please"); + } +} catch (error) { + const logger3 = new Logger(version23); + WS = function() { + logger3.throwError("WebSockets not supported in this environment", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "new WebSocket()" + }); + }; +} +var __awaiter$2 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - var it4 = size - length; - while(it4 !== size && b256[it4] === 0){ - it4++; + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - var vch = new Uint8Array(zeroes + (size - it4)); - var j2 = zeroes; - while(it4 !== size){ - vch[j2++] = b256[it4++]; + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger$31 = new Logger(version23); +let NextId = 1; +class WebSocketProvider extends JsonRpcProvider { + constructor(url, network){ + if (network === "any") { + logger$31.throwError("WebSocketProvider does not support 'any' network yet", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "network:any" + }); + } + if (typeof url === "string") { + super(url, network); + } else { + super("_websocket", network); + } + this._pollingInterval = -1; + this._wsReady = false; + if (typeof url === "string") { + defineReadOnly(this, "_websocket", new WS(this.connection.url)); + } else { + defineReadOnly(this, "_websocket", url); + } + defineReadOnly(this, "_requests", {}); + defineReadOnly(this, "_subs", {}); + defineReadOnly(this, "_subIds", {}); + defineReadOnly(this, "_detectNetwork", super.detectNetwork()); + this.websocket.onopen = ()=>{ + this._wsReady = true; + Object.keys(this._requests).forEach((id)=>{ + this.websocket.send(this._requests[id].payload); + }); + }; + this.websocket.onmessage = (messageEvent)=>{ + const data = messageEvent.data; + const result = JSON.parse(data); + if (result.id != null) { + const id = String(result.id); + const request = this._requests[id]; + delete this._requests[id]; + if (result.result !== void 0) { + request.callback(null, result.result); + this.emit("debug", { + action: "response", + request: JSON.parse(request.payload), + response: result.result, + provider: this + }); + } else { + let error = null; + if (result.error) { + error = new Error(result.error.message || "unknown error"); + defineReadOnly(error, "code", result.error.code || null); + defineReadOnly(error, "response", data); + } else { + error = new Error("unknown error"); + } + request.callback(error, void 0); + this.emit("debug", { + action: "response", + error, + request: JSON.parse(request.payload), + provider: this + }); + } + } else if (result.method === "eth_subscription") { + const sub = this._subs[result.params.subscription]; + if (sub) { + sub.processFunc(result.params.result); + } + } else { + console.warn("this should not happen"); + } + }; + const fauxPoll = setInterval(()=>{ + this.emit("poll"); + }, 1e3); + if (fauxPoll.unref) { + fauxPoll.unref(); } - return vch; } - function decode2(string) { - var buffer = decodeUnsafe(string); - if (buffer) { - return buffer; + get websocket() { + return this._websocket; + } + detectNetwork() { + return this._detectNetwork; + } + get pollingInterval() { + return 0; + } + resetEventsBlock(blockNumber) { + logger$31.throwError("cannot reset events block on WebSocketProvider", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "resetEventBlock" + }); + } + set pollingInterval(value) { + logger$31.throwError("cannot set polling interval on WebSocketProvider", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "setPollingInterval" + }); + } + poll() { + return __awaiter$2(this, void 0, void 0, function*() { + return null; + }); + } + set polling(value) { + if (!value) { + return; } - throw new Error(`Non-${name} character`); + logger$31.throwError("cannot set polling on WebSocketProvider", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "setPolling" + }); } - return { - encode: encode2, - decodeUnsafe, - decode: decode2 - }; -} -var src1 = base1; -var _brrp__multiformats_scope_baseX1 = src1; -class Encoder1 { - constructor(name, prefix, baseEncode){ - this.name = name; - this.prefix = prefix; - this.baseEncode = baseEncode; + send(method, params) { + const rid = NextId++; + return new Promise((resolve, reject)=>{ + function callback(error, result) { + if (error) { + return reject(error); + } + return resolve(result); + } + const payload = JSON.stringify({ + method, + params, + id: rid, + jsonrpc: "2.0" + }); + this.emit("debug", { + action: "request", + request: JSON.parse(payload), + provider: this + }); + this._requests[String(rid)] = { + callback, + payload + }; + if (this._wsReady) { + this.websocket.send(payload); + } + }); } - encode(bytes) { - if (bytes instanceof Uint8Array) { - return `${this.prefix}${this.baseEncode(bytes)}`; - } else { - throw Error("Unknown type, must be binary type"); + static defaultUrl() { + return "ws://localhost:8546"; + } + _subscribe(tag, param, processFunc) { + return __awaiter$2(this, void 0, void 0, function*() { + let subIdPromise = this._subIds[tag]; + if (subIdPromise == null) { + subIdPromise = Promise.all(param).then((param2)=>{ + return this.send("eth_subscribe", param2); + }); + this._subIds[tag] = subIdPromise; + } + const subId = yield subIdPromise; + this._subs[subId] = { + tag, + processFunc + }; + }); + } + _startEvent(event) { + switch(event.type){ + case "block": + this._subscribe("block", [ + "newHeads" + ], (result)=>{ + const blockNumber = BigNumber.from(result.number).toNumber(); + this._emitted.block = blockNumber; + this.emit("block", blockNumber); + }); + break; + case "pending": + this._subscribe("pending", [ + "newPendingTransactions" + ], (result)=>{ + this.emit("pending", result); + }); + break; + case "filter": + this._subscribe(event.tag, [ + "logs", + this._getFilter(event.filter) + ], (result)=>{ + if (result.removed == null) { + result.removed = false; + } + this.emit(event.filter, this.formatter.filterLog(result)); + }); + break; + case "tx": + { + const emitReceipt = (event2)=>{ + const hash2 = event2.hash; + this.getTransactionReceipt(hash2).then((receipt)=>{ + if (!receipt) { + return; + } + this.emit(hash2, receipt); + }); + }; + emitReceipt(event); + this._subscribe("tx", [ + "newHeads" + ], (result)=>{ + this._events.filter((e)=>e.type === "tx").forEach(emitReceipt); + }); + break; + } + case "debug": + case "poll": + case "willPoll": + case "didPoll": + case "error": + break; + default: + console.log("unhandled:", event); + break; } } -} -class Decoder1 { - constructor(name, prefix, baseDecode){ - this.name = name; - this.prefix = prefix; - this.baseDecode = baseDecode; - } - decode(text) { - if (typeof text === "string") { - switch(text[0]){ - case this.prefix: - { - return this.baseDecode(text.slice(1)); - } - default: - { - throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); - } + _stopEvent(event) { + let tag = event.tag; + if (event.type === "tx") { + if (this._events.filter((e)=>e.type === "tx").length) { + return; } - } else { - throw Error("Can only multibase decode strings"); + tag = "tx"; + } else if (this.listenerCount(event.event)) { + return; + } + const subId = this._subIds[tag]; + if (!subId) { + return; } + delete this._subIds[tag]; + subId.then((subId2)=>{ + if (!this._subs[subId2]) { + return; + } + delete this._subs[subId2]; + this.send("eth_unsubscribe", [ + subId2 + ]); + }); } - or(decoder) { - return or1(this, decoder); + destroy() { + return __awaiter$2(this, void 0, void 0, function*() { + if (this.websocket.readyState === WS.CONNECTING) { + yield new Promise((resolve)=>{ + this.websocket.onopen = function() { + resolve(true); + }; + this.websocket.onerror = function() { + resolve(false); + }; + }); + } + this.websocket.close(1e3); + }); } } -class ComposedDecoder1 { - constructor(decoders){ - this.decoders = decoders; - } - or(decoder) { - return or1(this, decoder); +var __awaiter$3 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); } - decode(input) { - const prefix = input[0]; - const decoder = this.decoders[prefix]; - if (decoder) { - return decoder.decode(input); - } else { - throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger$41 = new Logger(version23); +class StaticJsonRpcProvider extends JsonRpcProvider { + detectNetwork() { + const _super = Object.create(null, { + detectNetwork: { + get: ()=>super.detectNetwork + } + }); + return __awaiter$3(this, void 0, void 0, function*() { + let network = this.network; + if (network == null) { + network = yield _super.detectNetwork.call(this); + if (!network) { + logger$41.throwError("no network detected", Logger.errors.UNKNOWN_ERROR, {}); + } + if (this._network == null) { + defineReadOnly(this, "_network", network); + this.emit("network", network, null); + } + } + return network; + }); } } -const or1 = (left, right)=>new ComposedDecoder1({ - ...left.decoders || { - [left.prefix]: left - }, - ...right.decoders || { - [right.prefix]: right +class UrlJsonRpcProvider extends StaticJsonRpcProvider { + constructor(network, apiKey){ + logger$41.checkAbstract(new.target, UrlJsonRpcProvider); + network = getStatic(new.target, "getNetwork")(network); + apiKey = getStatic(new.target, "getApiKey")(apiKey); + const connection = getStatic(new.target, "getUrl")(network, apiKey); + super(connection, network); + if (typeof apiKey === "string") { + defineReadOnly(this, "apiKey", apiKey); + } else if (apiKey != null) { + Object.keys(apiKey).forEach((key)=>{ + defineReadOnly(this, key, apiKey[key]); + }); } - }); -class Codec1 { - constructor(name, prefix, baseEncode, baseDecode){ - this.name = name; - this.prefix = prefix; - this.baseEncode = baseEncode; - this.baseDecode = baseDecode; - this.encoder = new Encoder1(name, prefix, baseEncode); - this.decoder = new Decoder1(name, prefix, baseDecode); } - encode(input) { - return this.encoder.encode(input); + _startPending() { + logger$41.warn("WARNING: API provider does not support pending filters"); } - decode(input) { - return this.decoder.decode(input); + isCommunityResource() { + return false; } -} -const from3 = ({ name, prefix, encode: encode2, decode: decode2 })=>new Codec1(name, prefix, encode2, decode2); -const baseX1 = ({ prefix, name, alphabet })=>{ - const { encode: encode2, decode: decode2 } = _brrp__multiformats_scope_baseX1(alphabet, name); - return from3({ - prefix, - name, - encode: encode2, - decode: (text)=>coerce2(decode2(text)) - }); -}; -const decode8 = (string, alphabet, bitsPerChar, name)=>{ - const codes = {}; - for(let i = 0; i < alphabet.length; ++i){ - codes[alphabet[i]] = i; + getSigner(address2) { + return logger$41.throwError("API provider does not support signing", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "getSigner" + }); } - let end = string.length; - while(string[end - 1] === "="){ - --end; + listAccounts() { + return Promise.resolve([]); } - const out = new Uint8Array(end * bitsPerChar / 8 | 0); - let bits = 0; - let buffer = 0; - let written = 0; - for(let i = 0; i < end; ++i){ - const value = codes[string[i]]; - if (value === void 0) { - throw new SyntaxError(`Non-${name} character`); - } - buffer = buffer << bitsPerChar | value; - bits += bitsPerChar; - if (bits >= 8) { - bits -= 8; - out[written++] = 255 & buffer >> bits; - } + static getApiKey(apiKey) { + return apiKey; } - if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { - throw new SyntaxError("Unexpected end of data"); + static getUrl(network, apiKey) { + return logger$41.throwError("not implemented; sub-classes must override getUrl", Logger.errors.NOT_IMPLEMENTED, { + operation: "getUrl" + }); } - return out; -}; -const encode7 = (data, alphabet, bitsPerChar)=>{ - const pad = alphabet[alphabet.length - 1] === "="; - const mask = (1 << bitsPerChar) - 1; - let out = ""; - let bits = 0; - let buffer = 0; - for(let i = 0; i < data.length; ++i){ - buffer = buffer << 8 | data[i]; - bits += 8; - while(bits > bitsPerChar){ - bits -= bitsPerChar; - out += alphabet[mask & buffer >> bits]; - } +} +const logger$5 = new Logger(version23); +const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC"; +class AlchemyWebSocketProvider extends WebSocketProvider { + constructor(network, apiKey){ + const provider = new AlchemyProvider(network, apiKey); + const url = provider.connection.url.replace(/^http/i, "ws").replace(".alchemyapi.", ".ws.alchemyapi."); + super(url, provider.network); + defineReadOnly(this, "apiKey", provider.apiKey); } - if (bits) { - out += alphabet[mask & buffer << bitsPerChar - bits]; + isCommunityResource() { + return this.apiKey === defaultApiKey; } - if (pad) { - while(out.length * bitsPerChar & 7){ - out += "="; - } +} +class AlchemyProvider extends UrlJsonRpcProvider { + static getWebSocketProvider(network, apiKey) { + return new AlchemyWebSocketProvider(network, apiKey); } - return out; -}; -const rfc46481 = ({ name, prefix, bitsPerChar, alphabet })=>{ - return from3({ - prefix, - name, - encode (input) { - return encode7(input, alphabet, bitsPerChar); - }, - decode (input) { - return decode8(input, alphabet, bitsPerChar, name); + static getApiKey(apiKey) { + if (apiKey == null) { + return defaultApiKey; } - }); -}; -const base58btc1 = baseX1({ - name: "base58btc", - prefix: "z", - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" -}); -const base58flickr1 = baseX1({ - name: "base58flickr", - prefix: "Z", - alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" -}); -Object.freeze({ - __proto__: null, - base58btc: base58btc1, - base58flickr: base58flickr1 -}); -const base321 = rfc46481({ - prefix: "b", - name: "base32", - alphabet: "abcdefghijklmnopqrstuvwxyz234567", - bitsPerChar: 5 -}); -const base32upper1 = rfc46481({ - prefix: "B", - name: "base32upper", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", - bitsPerChar: 5 -}); -const base32pad1 = rfc46481({ - prefix: "c", - name: "base32pad", - alphabet: "abcdefghijklmnopqrstuvwxyz234567=", - bitsPerChar: 5 -}); -const base32padupper1 = rfc46481({ - prefix: "C", - name: "base32padupper", - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", - bitsPerChar: 5 -}); -const base32hex1 = rfc46481({ - prefix: "v", - name: "base32hex", - alphabet: "0123456789abcdefghijklmnopqrstuv", - bitsPerChar: 5 -}); -const base32hexupper1 = rfc46481({ - prefix: "V", - name: "base32hexupper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", - bitsPerChar: 5 -}); -const base32hexpad1 = rfc46481({ - prefix: "t", - name: "base32hexpad", - alphabet: "0123456789abcdefghijklmnopqrstuv=", - bitsPerChar: 5 -}); -const base32hexpadupper1 = rfc46481({ - prefix: "T", - name: "base32hexpadupper", - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", - bitsPerChar: 5 -}); -const base32z1 = rfc46481({ - prefix: "h", - name: "base32z", - alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", - bitsPerChar: 5 -}); -Object.freeze({ - __proto__: null, - base32: base321, - base32upper: base32upper1, - base32pad: base32pad1, - base32padupper: base32padupper1, - base32hex: base32hex1, - base32hexupper: base32hexupper1, - base32hexpad: base32hexpad1, - base32hexpadupper: base32hexpadupper1, - base32z: base32z1 -}); -class CID1 { - constructor(version2, code, multihash, bytes){ - this.code = code; - this.version = version2; - this.multihash = multihash; - this.bytes = bytes; - this.byteOffset = bytes.byteOffset; - this.byteLength = bytes.byteLength; - this.asCID = this; - this._baseCache = new Map(); - Object.defineProperties(this, { - byteOffset: hidden, - byteLength: hidden, - code: readonly, - version: readonly, - multihash: readonly, - bytes: readonly, - _baseCache: hidden, - asCID: hidden - }); + if (apiKey && typeof apiKey !== "string") { + logger$5.throwArgumentError("invalid apiKey", "apiKey", apiKey); + } + return apiKey; } - toV0() { - switch(this.version){ - case 0: - { - return this; - } + static getUrl(network, apiKey) { + let host = null; + switch(network.name){ + case "homestead": + host = "eth-mainnet.alchemyapi.io/v2/"; + break; + case "goerli": + host = "eth-goerli.g.alchemy.com/v2/"; + break; + case "matic": + host = "polygon-mainnet.g.alchemy.com/v2/"; + break; + case "maticmum": + host = "polygon-mumbai.g.alchemy.com/v2/"; + break; + case "arbitrum": + host = "arb-mainnet.g.alchemy.com/v2/"; + break; + case "arbitrum-goerli": + host = "arb-goerli.g.alchemy.com/v2/"; + break; + case "optimism": + host = "opt-mainnet.g.alchemy.com/v2/"; + break; + case "optimism-goerli": + host = "opt-goerli.g.alchemy.com/v2/"; + break; default: - { - const { code, multihash } = this; - if (code !== DAG_PB_CODE1) { - throw new Error("Cannot convert a non dag-pb CID to CIDv0"); - } - if (multihash.code !== SHA_256_CODE1) { - throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); - } - return CID1.createV0(multihash); - } + logger$5.throwArgumentError("unsupported network", "network", arguments[0]); } - } - toV1() { - switch(this.version){ - case 0: - { - const { code, digest: digest$1 } = this.multihash; - const multihash = create2(code, digest$1); - return CID1.createV1(this.code, multihash); - } - case 1: - { - return this; + return { + allowGzip: true, + url: "https://" + host + apiKey, + throttleCallback: (attempt, url)=>{ + if (apiKey === defaultApiKey) { + showThrottleMessage(); } - default: - { - throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); + return Promise.resolve(true); + } + }; + } + isCommunityResource() { + return this.apiKey === defaultApiKey; + } +} +const logger$6 = new Logger(version23); +const defaultApiKey$1 = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972"; +function getHost(name) { + switch(name){ + case "homestead": + return "rpc.ankr.com/eth/"; + case "ropsten": + return "rpc.ankr.com/eth_ropsten/"; + case "rinkeby": + return "rpc.ankr.com/eth_rinkeby/"; + case "goerli": + return "rpc.ankr.com/eth_goerli/"; + case "matic": + return "rpc.ankr.com/polygon/"; + case "arbitrum": + return "rpc.ankr.com/arbitrum/"; + } + return logger$6.throwArgumentError("unsupported network", "name", name); +} +class AnkrProvider extends UrlJsonRpcProvider { + isCommunityResource() { + return this.apiKey === defaultApiKey$1; + } + static getApiKey(apiKey) { + if (apiKey == null) { + return defaultApiKey$1; + } + return apiKey; + } + static getUrl(network, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey$1; + } + const connection = { + allowGzip: true, + url: "https://" + getHost(network.name) + apiKey, + throttleCallback: (attempt, url)=>{ + if (apiKey.apiKey === defaultApiKey$1) { + showThrottleMessage(); } + return Promise.resolve(true); + } + }; + if (apiKey.projectSecret != null) { + connection.user = ""; + connection.password = apiKey.projectSecret; } + return connection; } - equals(other) { - return other && this.code === other.code && this.version === other.version && equals5(this.multihash, other.multihash); +} +var __awaiter$4 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); } - toString(base) { - const { bytes, version: version2, _baseCache } = this; - switch(version2){ - case 0: - return toStringV01(bytes, _baseCache, base || base58btc1.encoder); + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger$7 = new Logger(version23); +class CloudflareProvider extends UrlJsonRpcProvider { + static getApiKey(apiKey) { + if (apiKey != null) { + logger$7.throwArgumentError("apiKey not supported for cloudflare", "apiKey", apiKey); + } + return null; + } + static getUrl(network, apiKey) { + let host = null; + switch(network.name){ + case "homestead": + host = "https://cloudflare-eth.com/"; + break; default: - return toStringV11(bytes, _baseCache, base || base321.encoder); + logger$7.throwArgumentError("unsupported network", "network", arguments[0]); } + return host; } - toJSON() { - return { - code: this.code, - version: this.version, - hash: this.multihash.bytes - }; + perform(method, params) { + const _super = Object.create(null, { + perform: { + get: ()=>super.perform + } + }); + return __awaiter$4(this, void 0, void 0, function*() { + if (method === "getBlockNumber") { + const block = yield _super.perform.call(this, "getBlock", { + blockTag: "latest" + }); + return block.number; + } + return _super.perform.call(this, method, params); + }); } - get [Symbol.toStringTag]() { - return "CID"; +} +var __awaiter$5 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); } - [Symbol.for("nodejs.util.inspect.custom")]() { - return "CID(" + this.toString() + ")"; + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger$8 = new Logger(version23); +function getTransactionPostData(transaction) { + const result = {}; + for(let key in transaction){ + if (transaction[key] == null) { + continue; + } + let value = transaction[key]; + if (key === "type" && value === 0) { + continue; + } + if (({ + type: true, + gasLimit: true, + gasPrice: true, + maxFeePerGs: true, + maxPriorityFeePerGas: true, + nonce: true, + value: true + })[key]) { + value = hexValue(hexlify(value)); + } else if (key === "accessList") { + value = "[" + accessListify(value).map((set)=>{ + return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`; + }).join(",") + "]"; + } else { + value = hexlify(value); + } + result[key] = value; } - static isCID(value) { - deprecate(/^0\.0/, IS_CID_DEPRECATION); - return !!(value && (value[cidSymbol1] || value.asCID === value)); + return result; +} +function getResult$1(result) { + if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) { + return result.result; } - get toBaseEncodedString() { - throw new Error("Deprecated, use .toString()"); + if (result.status != 1 || typeof result.message !== "string" || !result.message.match(/^OK/)) { + const error = new Error("invalid response"); + error.result = JSON.stringify(result); + if ((result.result || "").toLowerCase().indexOf("rate limit") >= 0) { + error.throttleRetry = true; + } + throw error; } - get codec() { - throw new Error('"codec" property is deprecated, use integer "code" property instead'); + return result.result; +} +function getJsonResult(result) { + if (result && result.status == 0 && result.message == "NOTOK" && (result.result || "").toLowerCase().indexOf("rate limit") >= 0) { + const error = new Error("throttled response"); + error.result = JSON.stringify(result); + error.throttleRetry = true; + throw error; } - get buffer() { - throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead"); + if (result.jsonrpc != "2.0") { + const error = new Error("invalid response"); + error.result = JSON.stringify(result); + throw error; } - get multibaseName() { - throw new Error('"multibaseName" property is deprecated'); + if (result.error) { + const error = new Error(result.error.message || "unknown error"); + if (result.error.code) { + error.code = result.error.code; + } + if (result.error.data) { + error.data = result.error.data; + } + throw error; } - get prefix() { - throw new Error('"prefix" property is deprecated'); + return result.result; +} +function checkLogTag(blockTag) { + if (blockTag === "pending") { + throw new Error("pending not supported"); } - static asCID(value) { - if (value instanceof CID1) { - return value; - } else if (value != null && value.asCID === value) { - const { version: version2, code, multihash, bytes } = value; - return new CID1(version2, code, multihash, bytes || encodeCID1(version2, code, multihash.bytes)); - } else if (value != null && value[cidSymbol1] === true) { - const { version: version2, multihash, code } = value; - const digest$1 = decode$22(multihash); - return CID1.create(version2, code, digest$1); - } else { - return null; + if (blockTag === "latest") { + return blockTag; + } + return parseInt(blockTag.substring(2), 16); +} +function checkError$1(method, error, transaction) { + if (method === "call" && error.code === Logger.errors.SERVER_ERROR) { + const e = error.error; + if (e && (e.message.match(/reverted/i) || e.message.match(/VM execution error/i))) { + let data = e.data; + if (data) { + data = "0x" + data.replace(/^.*0x/i, ""); + } + if (isHexString(data)) { + return data; + } + logger$8.throwError("missing revert data in call exception", Logger.errors.CALL_EXCEPTION, { + error, + data: "0x" + }); } } - static create(version2, code, digest) { - if (typeof code !== "number") { - throw new Error("String codecs are no longer supported"); + let message = error.message; + if (error.code === Logger.errors.SERVER_ERROR) { + if (error.error && typeof error.error.message === "string") { + message = error.error.message; + } else if (typeof error.body === "string") { + message = error.body; + } else if (typeof error.responseText === "string") { + message = error.responseText; } - switch(version2){ - case 0: - { - if (code !== DAG_PB_CODE1) { - throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE1}) block encoding`); - } else { - return new CID1(version2, code, digest, digest.bytes); + } + message = (message || "").toLowerCase(); + if (message.match(/insufficient funds/)) { + logger$8.throwError("insufficient funds for intrinsic transaction cost", Logger.errors.INSUFFICIENT_FUNDS, { + error, + method, + transaction + }); + } + if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) { + logger$8.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, { + error, + method, + transaction + }); + } + if (message.match(/another transaction with same nonce/)) { + logger$8.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, { + error, + method, + transaction + }); + } + if (message.match(/execution failed due to an exception|execution reverted/)) { + logger$8.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, { + error, + method, + transaction + }); + } + throw error; +} +class EtherscanProvider extends BaseProvider { + constructor(network, apiKey){ + super(network); + defineReadOnly(this, "baseUrl", this.getBaseUrl()); + defineReadOnly(this, "apiKey", apiKey || null); + } + getBaseUrl() { + switch(this.network ? this.network.name : "invalid"){ + case "homestead": + return "https://api.etherscan.io"; + case "goerli": + return "https://api-goerli.etherscan.io"; + case "sepolia": + return "https://api-sepolia.etherscan.io"; + case "matic": + return "https://api.polygonscan.com"; + case "maticmum": + return "https://api-testnet.polygonscan.com"; + case "arbitrum": + return "https://api.arbiscan.io"; + case "arbitrum-goerli": + return "https://api-goerli.arbiscan.io"; + case "optimism": + return "https://api-optimistic.etherscan.io"; + case "optimism-goerli": + return "https://api-goerli-optimistic.etherscan.io"; + } + return logger$8.throwArgumentError("unsupported network", "network", this.network.name); + } + getUrl(module, params) { + const query = Object.keys(params).reduce((accum, key)=>{ + const value = params[key]; + if (value != null) { + accum += `&${key}=${value}`; + } + return accum; + }, ""); + const apiKey = this.apiKey ? `&apikey=${this.apiKey}` : ""; + return `${this.baseUrl}/api?module=${module}${query}${apiKey}`; + } + getPostUrl() { + return `${this.baseUrl}/api`; + } + getPostData(module, params) { + params.module = module; + params.apikey = this.apiKey; + return params; + } + fetch(module, params, post) { + return __awaiter$5(this, void 0, void 0, function*() { + const url = post ? this.getPostUrl() : this.getUrl(module, params); + const payload = post ? this.getPostData(module, params) : null; + const procFunc = module === "proxy" ? getJsonResult : getResult$1; + this.emit("debug", { + action: "request", + request: url, + provider: this + }); + const connection = { + url, + throttleSlotInterval: 1e3, + throttleCallback: (attempt, url2)=>{ + if (this.isCommunityResource()) { + showThrottleMessage(); } + return Promise.resolve(true); } - case 1: - { - const bytes = encodeCID1(version2, code, digest.bytes); - return new CID1(version2, code, digest, bytes); + }; + let payloadStr = null; + if (payload) { + connection.headers = { + "content-type": "application/x-www-form-urlencoded; charset=UTF-8" + }; + payloadStr = Object.keys(payload).map((key)=>{ + return `${key}=${payload[key]}`; + }).join("&"); + } + const result = yield fetchJson(connection, payloadStr, procFunc || getJsonResult); + this.emit("debug", { + action: "response", + request: url, + response: deepCopy(result), + provider: this + }); + return result; + }); + } + detectNetwork() { + return __awaiter$5(this, void 0, void 0, function*() { + return this.network; + }); + } + perform(method, params) { + const _super = Object.create(null, { + perform: { + get: ()=>super.perform + } + }); + return __awaiter$5(this, void 0, void 0, function*() { + switch(method){ + case "getBlockNumber": + return this.fetch("proxy", { + action: "eth_blockNumber" + }); + case "getGasPrice": + return this.fetch("proxy", { + action: "eth_gasPrice" + }); + case "getBalance": + return this.fetch("account", { + action: "balance", + address: params.address, + tag: params.blockTag + }); + case "getTransactionCount": + return this.fetch("proxy", { + action: "eth_getTransactionCount", + address: params.address, + tag: params.blockTag + }); + case "getCode": + return this.fetch("proxy", { + action: "eth_getCode", + address: params.address, + tag: params.blockTag + }); + case "getStorageAt": + return this.fetch("proxy", { + action: "eth_getStorageAt", + address: params.address, + position: params.position, + tag: params.blockTag + }); + case "sendTransaction": + return this.fetch("proxy", { + action: "eth_sendRawTransaction", + hex: params.signedTransaction + }, true).catch((error)=>{ + return checkError$1("sendTransaction", error, params.signedTransaction); + }); + case "getBlock": + if (params.blockTag) { + return this.fetch("proxy", { + action: "eth_getBlockByNumber", + tag: params.blockTag, + boolean: params.includeTransactions ? "true" : "false" + }); + } + throw new Error("getBlock by blockHash not implemented"); + case "getTransaction": + return this.fetch("proxy", { + action: "eth_getTransactionByHash", + txhash: params.transactionHash + }); + case "getTransactionReceipt": + return this.fetch("proxy", { + action: "eth_getTransactionReceipt", + txhash: params.transactionHash + }); + case "call": + { + if (params.blockTag !== "latest") { + throw new Error("EtherscanProvider does not support blockTag for call"); + } + const postData = getTransactionPostData(params.transaction); + postData.module = "proxy"; + postData.action = "eth_call"; + try { + return yield this.fetch("proxy", postData, true); + } catch (error) { + return checkError$1("call", error, params.transaction); + } + } + case "estimateGas": + { + const postData = getTransactionPostData(params.transaction); + postData.module = "proxy"; + postData.action = "eth_estimateGas"; + try { + return yield this.fetch("proxy", postData, true); + } catch (error) { + return checkError$1("estimateGas", error, params.transaction); + } + } + case "getLogs": + { + const args = { + action: "getLogs" + }; + if (params.filter.fromBlock) { + args.fromBlock = checkLogTag(params.filter.fromBlock); + } + if (params.filter.toBlock) { + args.toBlock = checkLogTag(params.filter.toBlock); + } + if (params.filter.address) { + args.address = params.filter.address; + } + if (params.filter.topics && params.filter.topics.length > 0) { + if (params.filter.topics.length > 1) { + logger$8.throwError("unsupported topic count", Logger.errors.UNSUPPORTED_OPERATION, { + topics: params.filter.topics + }); + } + if (params.filter.topics.length === 1) { + const topic0 = params.filter.topics[0]; + if (typeof topic0 !== "string" || topic0.length !== 66) { + logger$8.throwError("unsupported topic format", Logger.errors.UNSUPPORTED_OPERATION, { + topic0 + }); + } + args.topic0 = topic0; + } + } + const logs = yield this.fetch("logs", args); + let blocks = {}; + for(let i = 0; i < logs.length; i++){ + const log = logs[i]; + if (log.blockHash != null) { + continue; + } + if (blocks[log.blockNumber] == null) { + const block = yield this.getBlock(log.blockNumber); + if (block) { + blocks[log.blockNumber] = block.hash; + } + } + log.blockHash = blocks[log.blockNumber]; + } + return logs; + } + case "getEtherPrice": + if (this.network.name !== "homestead") { + return 0; + } + return parseFloat((yield this.fetch("stats", { + action: "ethprice" + })).ethusd); + } + return _super.perform.call(this, method, params); + }); + } + getHistory(addressOrName, startBlock, endBlock) { + return __awaiter$5(this, void 0, void 0, function*() { + const params = { + action: "txlist", + address: yield this.resolveName(addressOrName), + startblock: startBlock == null ? 0 : startBlock, + endblock: endBlock == null ? 99999999 : endBlock, + sort: "asc" + }; + const result = yield this.fetch("account", params); + return result.map((tx)=>{ + [ + "contractAddress", + "to" + ].forEach(function(key) { + if (tx[key] == "") { + delete tx[key]; + } + }); + if (tx.creates == null && tx.contractAddress != null) { + tx.creates = tx.contractAddress; } - default: - { - throw new Error("Invalid version"); + const item = this.formatter.transactionResponse(tx); + if (tx.timeStamp) { + item.timestamp = parseInt(tx.timeStamp); } - } + return item; + }); + }); } - static createV0(digest) { - return CID1.create(0, DAG_PB_CODE1, digest); + isCommunityResource() { + return this.apiKey == null; } - static createV1(code, digest) { - return CID1.create(1, code, digest); +} +var __awaiter$6 = function(thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function(resolve) { + resolve(value); + }); } - static decode(bytes) { - const [cid, remainder] = CID1.decodeFirst(bytes); - if (remainder.length) { - throw new Error("Incorrect length"); + return new (P || (P = Promise))(function(resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } } - return cid; - } - static decodeFirst(bytes) { - const specs = CID1.inspectBytes(bytes); - const prefixSize = specs.size - specs.multihashSize; - const multihashBytes = coerce2(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); - if (multihashBytes.byteLength !== specs.multihashSize) { - throw new Error("Incorrect length"); + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } } - const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); - const digest$1 = new Digest2(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); - const cid = specs.version === 0 ? CID1.createV0(digest$1) : CID1.createV1(specs.codec, digest$1); - return [ - cid, - bytes.subarray(specs.size) - ]; - } - static inspectBytes(initialBytes) { - let offset = 0; - const next = ()=>{ - const [i, length] = decode$12(initialBytes.subarray(offset)); - offset += length; - return i; - }; - let version2 = next(); - let codec = DAG_PB_CODE1; - if (version2 === 18) { - version2 = 0; - offset = 0; - } else if (version2 === 1) { - codec = next(); + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - if (version2 !== 0 && version2 !== 1) { - throw new RangeError(`Invalid CID version ${version2}`); + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +const logger$9 = new Logger(version23); +function now() { + return new Date().getTime(); +} +function checkNetworks(networks3) { + let result = null; + for(let i = 0; i < networks3.length; i++){ + const network = networks3[i]; + if (network == null) { + return null; } - const prefixSize = offset; - const multihashCode = next(); - const digestSize = next(); - const size = offset + digestSize; - const multihashSize = size - prefixSize; - return { - version: version2, - codec, - multihashCode, - digestSize, - multihashSize, - size + if (result) { + if (!(result.name === network.name && result.chainId === network.chainId && (result.ensAddress === network.ensAddress || result.ensAddress == null && network.ensAddress == null))) { + logger$9.throwArgumentError("provider mismatch", "networks", networks3); + } + } else { + result = network; + } + } + return result; +} +function median(values, maxDelta) { + values = values.slice().sort(); + const middle = Math.floor(values.length / 2); + if (values.length % 2) { + return values[middle]; + } + const a = values[middle - 1], b = values[middle]; + if (maxDelta != null && Math.abs(a - b) > maxDelta) { + return null; + } + return (a + b) / 2; +} +function serialize1(value) { + if (value === null) { + return "null"; + } else if (typeof value === "number" || typeof value === "boolean") { + return JSON.stringify(value); + } else if (typeof value === "string") { + return value; + } else if (BigNumber.isBigNumber(value)) { + return value.toString(); + } else if (Array.isArray(value)) { + return JSON.stringify(value.map((i)=>serialize1(i))); + } else if (typeof value === "object") { + const keys = Object.keys(value); + keys.sort(); + return "{" + keys.map((key)=>{ + let v = value[key]; + if (typeof v === "function") { + v = "[function]"; + } else { + v = serialize1(v); + } + return JSON.stringify(key) + ":" + v; + }).join(",") + "}"; + } + throw new Error("unknown value type: " + typeof value); +} +let nextRid = 1; +function stall$1(duration) { + let cancel = null; + let timer2 = null; + let promise = new Promise((resolve)=>{ + cancel = function() { + if (timer2) { + clearTimeout(timer2); + timer2 = null; + } + resolve(); }; + timer2 = setTimeout(cancel, duration); + }); + const wait = (func)=>{ + promise = promise.then(func); + return promise; + }; + function getPromise() { + return promise; } - static parse(source, base) { - const [prefix, bytes] = parseCIDtoBytes1(source, base); - const cid = CID1.decode(bytes); - cid._baseCache.set(prefix, source); - return cid; + return { + cancel, + getPromise, + wait + }; +} +const ForwardErrors = [ + Logger.errors.CALL_EXCEPTION, + Logger.errors.INSUFFICIENT_FUNDS, + Logger.errors.NONCE_EXPIRED, + Logger.errors.REPLACEMENT_UNDERPRICED, + Logger.errors.UNPREDICTABLE_GAS_LIMIT +]; +const ForwardProperties = [ + "address", + "args", + "errorArgs", + "errorSignature", + "method", + "transaction" +]; +function exposeDebugConfig(config, now2) { + const result = { + weight: config.weight + }; + Object.defineProperty(result, "provider", { + get: ()=>config.provider + }); + if (config.start) { + result.start = config.start; + } + if (now2) { + result.duration = now2 - config.start; + } + if (config.done) { + if (config.error) { + result.error = config.error; + } else { + result.result = config.result || null; + } } + return result; } -const parseCIDtoBytes1 = (source, base)=>{ - switch(source[0]){ - case "Q": - { - const decoder = base || base58btc1; - return [ - base58btc1.prefix, - decoder.decode(`${base58btc1.prefix}${source}`) - ]; +function normalizedTally(normalize, quorum) { + return function(configs) { + const tally = {}; + configs.forEach((c)=>{ + const value = normalize(c.result); + if (!tally[value]) { + tally[value] = { + count: 0, + result: c.result + }; } - case base58btc1.prefix: - { - const decoder = base || base58btc1; - return [ - base58btc1.prefix, - decoder.decode(source) - ]; + tally[value].count++; + }); + const keys = Object.keys(tally); + for(let i = 0; i < keys.length; i++){ + const check = tally[keys[i]]; + if (check.count >= quorum) { + return check.result; } - case base321.prefix: - { - const decoder = base || base321; - return [ - base321.prefix, - decoder.decode(source) - ]; + } + return void 0; + }; +} +function getProcessFunc(provider, method, params) { + let normalize = serialize1; + switch(method){ + case "getBlockNumber": + return function(configs) { + const values = configs.map((c)=>c.result); + let blockNumber = median(configs.map((c)=>c.result), 2); + if (blockNumber == null) { + return void 0; + } + blockNumber = Math.ceil(blockNumber); + if (values.indexOf(blockNumber + 1) >= 0) { + blockNumber++; + } + if (blockNumber >= provider._highestBlockNumber) { + provider._highestBlockNumber = blockNumber; + } + return provider._highestBlockNumber; + }; + case "getGasPrice": + return function(configs) { + const values = configs.map((c)=>c.result); + values.sort(); + return values[Math.floor(values.length / 2)]; + }; + case "getEtherPrice": + return function(configs) { + return median(configs.map((c)=>c.result)); + }; + case "getBalance": + case "getTransactionCount": + case "getCode": + case "getStorageAt": + case "call": + case "estimateGas": + case "getLogs": + break; + case "getTransaction": + case "getTransactionReceipt": + normalize = function(tx) { + if (tx == null) { + return null; + } + tx = shallowCopy(tx); + tx.confirmations = -1; + return serialize1(tx); + }; + break; + case "getBlock": + if (params.includeTransactions) { + normalize = function(block) { + if (block == null) { + return null; + } + block = shallowCopy(block); + block.transactions = block.transactions.map((tx)=>{ + tx = shallowCopy(tx); + tx.confirmations = -1; + return tx; + }); + return serialize1(block); + }; + } else { + normalize = function(block) { + if (block == null) { + return null; + } + return serialize1(block); + }; } + break; default: - { - if (base == null) { - throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided"); + throw new Error("unknown method: " + method); + } + return normalizedTally(normalize, provider.quorum); +} +function waitForSync(config, blockNumber) { + return __awaiter$6(this, void 0, void 0, function*() { + const provider = config.provider; + if (provider.blockNumber != null && provider.blockNumber >= blockNumber || blockNumber === -1) { + return provider; + } + return poll(()=>{ + return new Promise((resolve, reject)=>{ + setTimeout(function() { + if (provider.blockNumber >= blockNumber) { + return resolve(provider); + } + if (config.cancelled) { + return resolve(null); + } + return resolve(void 0); + }, 0); + }); + }, { + oncePoll: provider + }); + }); +} +function getRunner(config, currentBlockNumber, method, params) { + return __awaiter$6(this, void 0, void 0, function*() { + let provider = config.provider; + switch(method){ + case "getBlockNumber": + case "getGasPrice": + return provider[method](); + case "getEtherPrice": + if (provider.getEtherPrice) { + return provider.getEtherPrice(); } - return [ - source[0], - base.decode(source) - ]; + break; + case "getBalance": + case "getTransactionCount": + case "getCode": + if (params.blockTag && isHexString(params.blockTag)) { + provider = yield waitForSync(config, currentBlockNumber); + } + return provider[method](params.address, params.blockTag || "latest"); + case "getStorageAt": + if (params.blockTag && isHexString(params.blockTag)) { + provider = yield waitForSync(config, currentBlockNumber); + } + return provider.getStorageAt(params.address, params.position, params.blockTag || "latest"); + case "getBlock": + if (params.blockTag && isHexString(params.blockTag)) { + provider = yield waitForSync(config, currentBlockNumber); + } + return provider[params.includeTransactions ? "getBlockWithTransactions" : "getBlock"](params.blockTag || params.blockHash); + case "call": + case "estimateGas": + if (params.blockTag && isHexString(params.blockTag)) { + provider = yield waitForSync(config, currentBlockNumber); + } + if (method === "call" && params.blockTag) { + return provider[method](params.transaction, params.blockTag); + } + return provider[method](params.transaction); + case "getTransaction": + case "getTransactionReceipt": + return provider[method](params.transactionHash); + case "getLogs": + { + let filter = params.filter; + if (filter.fromBlock && isHexString(filter.fromBlock) || filter.toBlock && isHexString(filter.toBlock)) { + provider = yield waitForSync(config, currentBlockNumber); + } + return provider.getLogs(filter); + } + } + return logger$9.throwError("unknown method error", Logger.errors.UNKNOWN_ERROR, { + method, + params + }); + }); +} +class FallbackProvider extends BaseProvider { + constructor(providers, quorum){ + if (providers.length === 0) { + logger$9.throwArgumentError("missing providers", "providers", providers); + } + const providerConfigs = providers.map((configOrProvider, index)=>{ + if (Provider.isProvider(configOrProvider)) { + const stallTimeout = isCommunityResource(configOrProvider) ? 2e3 : 750; + return Object.freeze({ + provider: configOrProvider, + weight: 1, + stallTimeout, + priority: 1 + }); } + const config = shallowCopy(configOrProvider); + if (config.priority == null) { + config.priority = 1; + } + if (config.stallTimeout == null) { + config.stallTimeout = isCommunityResource(configOrProvider) ? 2e3 : 750; + } + if (config.weight == null) { + config.weight = 1; + } + const weight = config.weight; + if (weight % 1 || weight > 512 || weight < 1) { + logger$9.throwArgumentError("invalid weight; must be integer in [1, 512]", `providers[${index}].weight`, weight); + } + return Object.freeze(config); + }); + const total = providerConfigs.reduce((accum, c)=>accum + c.weight, 0); + if (quorum == null) { + quorum = total / 2; + } else if (quorum > total) { + logger$9.throwArgumentError("quorum will always fail; larger than total weight", "quorum", quorum); + } + let networkOrReady = checkNetworks(providerConfigs.map((c)=>c.provider.network)); + if (networkOrReady == null) { + networkOrReady = new Promise((resolve, reject)=>{ + setTimeout(()=>{ + this.detectNetwork().then(resolve, reject); + }, 0); + }); + } + super(networkOrReady); + defineReadOnly(this, "providerConfigs", Object.freeze(providerConfigs)); + defineReadOnly(this, "quorum", quorum); + this._highestBlockNumber = -1; } -}; -const toStringV01 = (bytes, cache, base)=>{ - const { prefix } = base; - if (prefix !== base58btc1.prefix) { - throw Error(`Cannot string encode V0 in ${base.name} encoding`); - } - const cid = cache.get(prefix); - if (cid == null) { - const cid2 = base.encode(bytes).slice(1); - cache.set(prefix, cid2); - return cid2; - } else { - return cid; - } -}; -const toStringV11 = (bytes, cache, base)=>{ - const { prefix } = base; - const cid = cache.get(prefix); - if (cid == null) { - const cid2 = base.encode(bytes); - cache.set(prefix, cid2); - return cid2; - } else { - return cid; + detectNetwork() { + return __awaiter$6(this, void 0, void 0, function*() { + const networks3 = yield Promise.all(this.providerConfigs.map((c)=>c.provider.getNetwork())); + return checkNetworks(networks3); + }); } -}; -const DAG_PB_CODE1 = 112; -const SHA_256_CODE1 = 18; -const encodeCID1 = (version2, code, multihash)=>{ - const codeOffset = encodingLength2(version2); - const hashOffset = codeOffset + encodingLength2(code); - const bytes = new Uint8Array(hashOffset + multihash.byteLength); - encodeTo2(version2, bytes, 0); - encodeTo2(code, bytes, codeOffset); - bytes.set(multihash, hashOffset); - return bytes; -}; -const cidSymbol1 = Symbol.for("@ipld/js-cid/CID"); -const readonly = { - writable: false, - configurable: false, - enumerable: true -}; -const hidden = { - writable: false, - enumerable: false, - configurable: false -}; -const version = "0.0.0-dev"; -const deprecate = (range, message)=>{ - if (range.test(version)) { - console.warn(message); - } else { - throw new Error(message); + perform(method, params) { + return __awaiter$6(this, void 0, void 0, function*() { + if (method === "sendTransaction") { + const results = yield Promise.all(this.providerConfigs.map((c)=>{ + return c.provider.sendTransaction(params.signedTransaction).then((result)=>{ + return result.hash; + }, (error)=>{ + return error; + }); + })); + for(let i2 = 0; i2 < results.length; i2++){ + const result = results[i2]; + if (typeof result === "string") { + return result; + } + } + throw results[0]; + } + if (this._highestBlockNumber === -1 && method !== "getBlockNumber") { + yield this.getBlockNumber(); + } + const processFunc = getProcessFunc(this, method, params); + const configs = shuffled(this.providerConfigs.map(shallowCopy)); + configs.sort((a, b)=>a.priority - b.priority); + const currentBlockNumber = this._highestBlockNumber; + let i = 0; + let first = true; + while(true){ + const t0 = now(); + let inflightWeight = configs.filter((c)=>c.runner && t0 - c.start < c.stallTimeout).reduce((accum, c)=>accum + c.weight, 0); + while(inflightWeight < this.quorum && i < configs.length){ + const config = configs[i++]; + const rid = nextRid++; + config.start = now(); + config.staller = stall$1(config.stallTimeout); + config.staller.wait(()=>{ + config.staller = null; + }); + config.runner = getRunner(config, currentBlockNumber, method, params).then((result)=>{ + config.done = true; + config.result = result; + if (this.listenerCount("debug")) { + this.emit("debug", { + action: "request", + rid, + backend: exposeDebugConfig(config, now()), + request: { + method, + params: deepCopy(params) + }, + provider: this + }); + } + }, (error)=>{ + config.done = true; + config.error = error; + if (this.listenerCount("debug")) { + this.emit("debug", { + action: "request", + rid, + backend: exposeDebugConfig(config, now()), + request: { + method, + params: deepCopy(params) + }, + provider: this + }); + } + }); + if (this.listenerCount("debug")) { + this.emit("debug", { + action: "request", + rid, + backend: exposeDebugConfig(config, null), + request: { + method, + params: deepCopy(params) + }, + provider: this + }); + } + inflightWeight += config.weight; + } + const waiting = []; + configs.forEach((c)=>{ + if (c.done || !c.runner) { + return; + } + waiting.push(c.runner); + if (c.staller) { + waiting.push(c.staller.getPromise()); + } + }); + if (waiting.length) { + yield Promise.race(waiting); + } + const results = configs.filter((c)=>c.done && c.error == null); + if (results.length >= this.quorum) { + const result = processFunc(results); + if (result !== void 0) { + configs.forEach((c)=>{ + if (c.staller) { + c.staller.cancel(); + } + c.cancelled = true; + }); + return result; + } + if (!first) { + yield stall$1(100).getPromise(); + } + first = false; + } + const errors = configs.reduce((accum, c)=>{ + if (!c.done || c.error == null) { + return accum; + } + const code = c.error.code; + if (ForwardErrors.indexOf(code) >= 0) { + if (!accum[code]) { + accum[code] = { + error: c.error, + weight: 0 + }; + } + accum[code].weight += c.weight; + } + return accum; + }, {}); + Object.keys(errors).forEach((errorCode)=>{ + const tally = errors[errorCode]; + if (tally.weight < this.quorum) { + return; + } + configs.forEach((c)=>{ + if (c.staller) { + c.staller.cancel(); + } + c.cancelled = true; + }); + const e = tally.error; + const props = {}; + ForwardProperties.forEach((name)=>{ + if (e[name] == null) { + return; + } + props[name] = e[name]; + }); + logger$9.throwError(e.reason || e.message, errorCode, props); + }); + if (configs.filter((c)=>!c.done).length === 0) { + break; + } + } + configs.forEach((c)=>{ + if (c.staller) { + c.staller.cancel(); + } + c.cancelled = true; + }); + return logger$9.throwError("failed to meet quorum", Logger.errors.SERVER_ERROR, { + method, + params, + results: configs.map((c)=>exposeDebugConfig(c)), + provider: this + }); + }); } -}; -const IS_CID_DEPRECATION = `CID.isCID(v) is deprecated and will be removed in the next major release. -Following code pattern: - -if (CID.isCID(value)) { - doSomethingWithCID(value) -} - -Is replaced with: - -const cid = CID.asCID(value) -if (cid) { - // Make sure to use cid instead of value - doSomethingWithCID(cid) } -`; -function createCommonjsModule(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function(path, base) { - return commonjsRequire(path, base === void 0 || base === null ? module.path : base); +const logger$a = new Logger(version23); +const defaultProjectId = "84842078b09946638c03157f83405213"; +class InfuraWebSocketProvider extends WebSocketProvider { + constructor(network, apiKey){ + const provider = new InfuraProvider(network, apiKey); + const connection = provider.connection; + if (connection.password) { + logger$a.throwError("INFURA WebSocket project secrets unsupported", Logger.errors.UNSUPPORTED_OPERATION, { + operation: "InfuraProvider.getWebSocketProvider()" + }); } - }, fn(module, module.exports), module.exports; -} -function commonjsRequire() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); + const url = connection.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/"); + super(url, network); + defineReadOnly(this, "apiKey", provider.projectId); + defineReadOnly(this, "projectId", provider.projectId); + defineReadOnly(this, "projectSecret", provider.projectSecret); + } + isCommunityResource() { + return this.projectId === defaultProjectId; + } } -var murmurHash3js = createCommonjsModule(function(module, exports) { - (function(root, undefined$1) { - var library = { - version: "3.0.0", - x86: {}, - x64: {}, - inputValidation: true +class InfuraProvider extends UrlJsonRpcProvider { + static getWebSocketProvider(network, apiKey) { + return new InfuraWebSocketProvider(network, apiKey); + } + static getApiKey(apiKey) { + const apiKeyObj = { + apiKey: defaultProjectId, + projectId: defaultProjectId, + projectSecret: null }; - function _validBytes(bytes) { - if (!Array.isArray(bytes) && !ArrayBuffer.isView(bytes)) { - return false; - } - for(var i = 0; i < bytes.length; i++){ - if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) { - return false; + if (apiKey == null) { + return apiKeyObj; + } + if (typeof apiKey === "string") { + apiKeyObj.projectId = apiKey; + } else if (apiKey.projectSecret != null) { + logger$a.assertArgument(typeof apiKey.projectId === "string", "projectSecret requires a projectId", "projectId", apiKey.projectId); + logger$a.assertArgument(typeof apiKey.projectSecret === "string", "invalid projectSecret", "projectSecret", "[REDACTED]"); + apiKeyObj.projectId = apiKey.projectId; + apiKeyObj.projectSecret = apiKey.projectSecret; + } else if (apiKey.projectId) { + apiKeyObj.projectId = apiKey.projectId; + } + apiKeyObj.apiKey = apiKeyObj.projectId; + return apiKeyObj; + } + static getUrl(network, apiKey) { + let host = null; + switch(network ? network.name : "unknown"){ + case "homestead": + host = "mainnet.infura.io"; + break; + case "goerli": + host = "goerli.infura.io"; + break; + case "sepolia": + host = "sepolia.infura.io"; + break; + case "matic": + host = "polygon-mainnet.infura.io"; + break; + case "maticmum": + host = "polygon-mumbai.infura.io"; + break; + case "optimism": + host = "optimism-mainnet.infura.io"; + break; + case "optimism-goerli": + host = "optimism-goerli.infura.io"; + break; + case "arbitrum": + host = "arbitrum-mainnet.infura.io"; + break; + case "arbitrum-goerli": + host = "arbitrum-goerli.infura.io"; + break; + default: + logger$a.throwError("unsupported network", Logger.errors.INVALID_ARGUMENT, { + argument: "network", + value: network + }); + } + const connection = { + allowGzip: true, + url: "https://" + host + "/v3/" + apiKey.projectId, + throttleCallback: (attempt, url)=>{ + if (apiKey.projectId === defaultProjectId) { + showThrottleMessage(); } + return Promise.resolve(true); } - return true; - } - function _x86Multiply(m, n) { - return (m & 65535) * n + (((m >>> 16) * n & 65535) << 16); - } - function _x86Rotl(m, n) { - return m << n | m >>> 32 - n; + }; + if (apiKey.projectSecret != null) { + connection.user = ""; + connection.password = apiKey.projectSecret; } - function _x86Fmix(h) { - h ^= h >>> 16; - h = _x86Multiply(h, 2246822507); - h ^= h >>> 13; - h = _x86Multiply(h, 3266489909); - h ^= h >>> 16; - return h; + return connection; + } + isCommunityResource() { + return this.projectId === defaultProjectId; + } +} +class JsonRpcBatchProvider extends JsonRpcProvider { + send(method, params) { + const request = { + method, + params, + id: this._nextId++, + jsonrpc: "2.0" + }; + if (this._pendingBatch == null) { + this._pendingBatch = []; } - function _x64Add(m, n) { - m = [ - m[0] >>> 16, - m[0] & 65535, - m[1] >>> 16, - m[1] & 65535 - ]; - n = [ - n[0] >>> 16, - n[0] & 65535, - n[1] >>> 16, - n[1] & 65535 - ]; - var o = [ - 0, - 0, - 0, - 0 - ]; - o[3] += m[3] + n[3]; - o[2] += o[3] >>> 16; - o[3] &= 65535; - o[2] += m[2] + n[2]; - o[1] += o[2] >>> 16; - o[2] &= 65535; - o[1] += m[1] + n[1]; - o[0] += o[1] >>> 16; - o[1] &= 65535; - o[0] += m[0] + n[0]; - o[0] &= 65535; - return [ - o[0] << 16 | o[1], - o[2] << 16 | o[3] - ]; + const inflightRequest = { + request, + resolve: null, + reject: null + }; + const promise = new Promise((resolve, reject)=>{ + inflightRequest.resolve = resolve; + inflightRequest.reject = reject; + }); + this._pendingBatch.push(inflightRequest); + if (!this._pendingBatchAggregator) { + this._pendingBatchAggregator = setTimeout(()=>{ + const batch = this._pendingBatch; + this._pendingBatch = null; + this._pendingBatchAggregator = null; + const request2 = batch.map((inflight)=>inflight.request); + this.emit("debug", { + action: "requestBatch", + request: deepCopy(request2), + provider: this + }); + return fetchJson(this.connection, JSON.stringify(request2)).then((result)=>{ + this.emit("debug", { + action: "response", + request: request2, + response: result, + provider: this + }); + batch.forEach((inflightRequest2, index)=>{ + const payload = result[index]; + if (payload.error) { + const error = new Error(payload.error.message); + error.code = payload.error.code; + error.data = payload.error.data; + inflightRequest2.reject(error); + } else { + inflightRequest2.resolve(payload.result); + } + }); + }, (error)=>{ + this.emit("debug", { + action: "response", + error, + request: request2, + provider: this + }); + batch.forEach((inflightRequest2)=>{ + inflightRequest2.reject(error); + }); + }); + }, 10); } - function _x64Multiply(m, n) { - m = [ - m[0] >>> 16, - m[0] & 65535, - m[1] >>> 16, - m[1] & 65535 - ]; - n = [ - n[0] >>> 16, - n[0] & 65535, - n[1] >>> 16, - n[1] & 65535 - ]; - var o = [ - 0, - 0, - 0, - 0 - ]; - o[3] += m[3] * n[3]; - o[2] += o[3] >>> 16; - o[3] &= 65535; - o[2] += m[2] * n[3]; - o[1] += o[2] >>> 16; - o[2] &= 65535; - o[2] += m[3] * n[2]; - o[1] += o[2] >>> 16; - o[2] &= 65535; - o[1] += m[1] * n[3]; - o[0] += o[1] >>> 16; - o[1] &= 65535; - o[1] += m[2] * n[2]; - o[0] += o[1] >>> 16; - o[1] &= 65535; - o[1] += m[3] * n[1]; - o[0] += o[1] >>> 16; - o[1] &= 65535; - o[0] += m[0] * n[3] + m[1] * n[2] + m[2] * n[1] + m[3] * n[0]; - o[0] &= 65535; - return [ - o[0] << 16 | o[1], - o[2] << 16 | o[3] - ]; + return promise; + } +} +const logger$b = new Logger(version23); +const defaultApiKey$2 = "ETHERS_JS_SHARED"; +class NodesmithProvider extends UrlJsonRpcProvider { + static getApiKey(apiKey) { + if (apiKey && typeof apiKey !== "string") { + logger$b.throwArgumentError("invalid apiKey", "apiKey", apiKey); } - function _x64Rotl(m, n) { - n %= 64; - if (n === 32) { - return [ - m[1], - m[0] - ]; - } else if (n < 32) { - return [ - m[0] << n | m[1] >>> 32 - n, - m[1] << n | m[0] >>> 32 - n - ]; - } else { - n -= 32; - return [ - m[1] << n | m[0] >>> 32 - n, - m[0] << n | m[1] >>> 32 - n - ]; - } + return apiKey || defaultApiKey$2; + } + static getUrl(network, apiKey) { + logger$b.warn("NodeSmith will be discontinued on 2019-12-20; please migrate to another platform."); + let host = null; + switch(network.name){ + case "homestead": + host = "https://ethereum.api.nodesmith.io/v1/mainnet/jsonrpc"; + break; + case "ropsten": + host = "https://ethereum.api.nodesmith.io/v1/ropsten/jsonrpc"; + break; + case "rinkeby": + host = "https://ethereum.api.nodesmith.io/v1/rinkeby/jsonrpc"; + break; + case "goerli": + host = "https://ethereum.api.nodesmith.io/v1/goerli/jsonrpc"; + break; + case "kovan": + host = "https://ethereum.api.nodesmith.io/v1/kovan/jsonrpc"; + break; + default: + logger$b.throwArgumentError("unsupported network", "network", arguments[0]); } - function _x64LeftShift(m, n) { - n %= 64; - if (n === 0) { - return m; - } else if (n < 32) { - return [ - m[0] << n | m[1] >>> 32 - n, - m[1] << n - ]; - } else { - return [ - m[1] << n - 32, - 0 - ]; - } + return host + "?apiKey=" + apiKey; + } +} +const logger$c = new Logger(version23); +const defaultApplicationId = "62e1ad51b37b8e00394bda3b"; +class PocketProvider extends UrlJsonRpcProvider { + static getApiKey(apiKey) { + const apiKeyObj = { + applicationId: null, + loadBalancer: true, + applicationSecretKey: null + }; + if (apiKey == null) { + apiKeyObj.applicationId = defaultApplicationId; + } else if (typeof apiKey === "string") { + apiKeyObj.applicationId = apiKey; + } else if (apiKey.applicationSecretKey != null) { + apiKeyObj.applicationId = apiKey.applicationId; + apiKeyObj.applicationSecretKey = apiKey.applicationSecretKey; + } else if (apiKey.applicationId) { + apiKeyObj.applicationId = apiKey.applicationId; + } else { + logger$c.throwArgumentError("unsupported PocketProvider apiKey", "apiKey", apiKey); } - function _x64Xor(m, n) { - return [ - m[0] ^ n[0], - m[1] ^ n[1] - ]; + return apiKeyObj; + } + static getUrl(network, apiKey) { + let host = null; + switch(network ? network.name : "unknown"){ + case "goerli": + host = "eth-goerli.gateway.pokt.network"; + break; + case "homestead": + host = "eth-mainnet.gateway.pokt.network"; + break; + case "kovan": + host = "poa-kovan.gateway.pokt.network"; + break; + case "matic": + host = "poly-mainnet.gateway.pokt.network"; + break; + case "maticmum": + host = "polygon-mumbai-rpc.gateway.pokt.network"; + break; + case "rinkeby": + host = "eth-rinkeby.gateway.pokt.network"; + break; + case "ropsten": + host = "eth-ropsten.gateway.pokt.network"; + break; + default: + logger$c.throwError("unsupported network", Logger.errors.INVALID_ARGUMENT, { + argument: "network", + value: network + }); } - function _x64Fmix(h) { - h = _x64Xor(h, [ - 0, - h[0] >>> 1 - ]); - h = _x64Multiply(h, [ - 4283543511, - 3981806797 - ]); - h = _x64Xor(h, [ - 0, - h[0] >>> 1 - ]); - h = _x64Multiply(h, [ - 3301882366, - 444984403 - ]); - h = _x64Xor(h, [ - 0, - h[0] >>> 1 - ]); - return h; + const url = `https://${host}/v1/lb/${apiKey.applicationId}`; + const connection = { + headers: {}, + url + }; + if (apiKey.applicationSecretKey != null) { + connection.user = ""; + connection.password = apiKey.applicationSecretKey; + } + return connection; + } + isCommunityResource() { + return this.applicationId === defaultApplicationId; + } +} +const logger$d = new Logger(version23); +let _nextId = 1; +function buildWeb3LegacyFetcher(provider, sendFunc) { + const fetcher = "Web3LegacyFetcher"; + return function(method, params) { + const request = { + method, + params, + id: _nextId++, + jsonrpc: "2.0" + }; + return new Promise((resolve, reject)=>{ + this.emit("debug", { + action: "request", + fetcher, + request: deepCopy(request), + provider: this + }); + sendFunc(request, (error, response)=>{ + if (error) { + this.emit("debug", { + action: "response", + fetcher, + error, + request, + provider: this + }); + return reject(error); + } + this.emit("debug", { + action: "response", + fetcher, + request, + response, + provider: this + }); + if (response.error) { + const error2 = new Error(response.error.message); + error2.code = response.error.code; + error2.data = response.error.data; + return reject(error2); + } + resolve(response.result); + }); + }); + }; +} +function buildEip1193Fetcher(provider) { + return function(method, params) { + if (params == null) { + params = []; } - library.x86.hash32 = function(bytes, seed) { - if (library.inputValidation && !_validBytes(bytes)) { - return undefined$1; + const request = { + method, + params + }; + this.emit("debug", { + action: "request", + fetcher: "Eip1193Fetcher", + request: deepCopy(request), + provider: this + }); + return provider.request(request).then((response)=>{ + this.emit("debug", { + action: "response", + fetcher: "Eip1193Fetcher", + request, + response, + provider: this + }); + return response; + }, (error)=>{ + this.emit("debug", { + action: "response", + fetcher: "Eip1193Fetcher", + request, + error, + provider: this + }); + throw error; + }); + }; +} +class Web3Provider extends JsonRpcProvider { + constructor(provider, network){ + if (provider == null) { + logger$d.throwArgumentError("missing provider", "provider", provider); + } + let path = null; + let jsonRpcFetchFunc = null; + let subprovider = null; + if (typeof provider === "function") { + path = "unknown:"; + jsonRpcFetchFunc = provider; + } else { + path = provider.host || provider.path || ""; + if (!path && provider.isMetaMask) { + path = "metamask"; } - seed = seed || 0; - var remainder = bytes.length % 4; - var blocks = bytes.length - remainder; - var h1 = seed; - var k1 = 0; - var c1 = 3432918353; - var c2 = 461845907; - for(var i = 0; i < blocks; i = i + 4){ - k1 = bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24; - k1 = _x86Multiply(k1, c1); - k1 = _x86Rotl(k1, 15); - k1 = _x86Multiply(k1, c2); - h1 ^= k1; - h1 = _x86Rotl(h1, 13); - h1 = _x86Multiply(h1, 5) + 3864292196; + subprovider = provider; + if (provider.request) { + if (path === "") { + path = "eip-1193:"; + } + jsonRpcFetchFunc = buildEip1193Fetcher(provider); + } else if (provider.sendAsync) { + jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.sendAsync.bind(provider)); + } else if (provider.send) { + jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.send.bind(provider)); + } else { + logger$d.throwArgumentError("unsupported provider", "provider", provider); } - k1 = 0; - switch(remainder){ - case 3: - k1 ^= bytes[i + 2] << 16; - case 2: - k1 ^= bytes[i + 1] << 8; - case 1: - k1 ^= bytes[i]; - k1 = _x86Multiply(k1, c1); - k1 = _x86Rotl(k1, 15); - k1 = _x86Multiply(k1, c2); - h1 ^= k1; + if (!path) { + path = "unknown:"; } - h1 ^= bytes.length; - h1 = _x86Fmix(h1); - return h1 >>> 0; - }; - library.x86.hash128 = function(bytes, seed) { - if (library.inputValidation && !_validBytes(bytes)) { - return undefined$1; + } + super(path, network); + defineReadOnly(this, "jsonRpcFetchFunc", jsonRpcFetchFunc); + defineReadOnly(this, "provider", subprovider); + } + send(method, params) { + return this.jsonRpcFetchFunc(method, params); + } +} +const logger$e = new Logger(version23); +function getDefaultProvider(network, options) { + if (network == null) { + network = "homestead"; + } + if (typeof network === "string") { + const match = network.match(/^(ws|http)s?:/i); + if (match) { + switch(match[1].toLowerCase()){ + case "http": + case "https": + return new JsonRpcProvider(network); + case "ws": + case "wss": + return new WebSocketProvider(network); + default: + logger$e.throwArgumentError("unsupported URL scheme", "network", network); + } + } + } + const n = getNetwork(network); + if (!n || !n._defaultProvider) { + logger$e.throwError("unsupported getDefaultProvider network", Logger.errors.NETWORK_ERROR, { + operation: "getDefaultProvider", + network + }); + } + return n._defaultProvider({ + FallbackProvider, + AlchemyProvider, + AnkrProvider, + CloudflareProvider, + EtherscanProvider, + InfuraProvider, + JsonRpcProvider, + NodesmithProvider, + PocketProvider, + Web3Provider, + IpcProvider: null + }, options); +} +const mod3 = function() { + return { + Provider: Provider, + getNetwork: getNetwork, + AlchemyProvider: AlchemyProvider, + AlchemyWebSocketProvider: AlchemyWebSocketProvider, + AnkrProvider: AnkrProvider, + BaseProvider: BaseProvider, + CloudflareProvider: CloudflareProvider, + EtherscanProvider: EtherscanProvider, + FallbackProvider: FallbackProvider, + Formatter: Formatter, + InfuraProvider: InfuraProvider, + InfuraWebSocketProvider: InfuraWebSocketProvider, + IpcProvider: null, + JsonRpcBatchProvider: JsonRpcBatchProvider, + JsonRpcProvider: JsonRpcProvider, + JsonRpcSigner: JsonRpcSigner, + NodesmithProvider: NodesmithProvider, + PocketProvider: PocketProvider, + Resolver: Resolver, + StaticJsonRpcProvider: StaticJsonRpcProvider, + UrlJsonRpcProvider: UrlJsonRpcProvider, + Web3Provider: Web3Provider, + WebSocketProvider: WebSocketProvider, + getDefaultProvider: getDefaultProvider, + isCommunityResourcable: isCommunityResourcable, + isCommunityResource: isCommunityResource, + showThrottleMessage: showThrottleMessage, + default: null + }; +}(); +const version24 = "solidity/5.7.0"; +const regexBytes = new RegExp("^bytes([0-9]+)$"); +const regexNumber = new RegExp("^(u?int)([0-9]*)$"); +const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$"); +const Zeros1 = "0000000000000000000000000000000000000000000000000000000000000000"; +const logger222 = new Logger(version24); +function _pack(type, value, isArray) { + switch(type){ + case "address": + if (isArray) { + return zeroPad(value, 32); } - seed = seed || 0; - var remainder = bytes.length % 16; - var blocks = bytes.length - remainder; - var h1 = seed; - var h2 = seed; - var h3 = seed; - var h4 = seed; - var k1 = 0; - var k2 = 0; - var k3 = 0; - var k4 = 0; - var c1 = 597399067; - var c2 = 2869860233; - var c3 = 951274213; - var c4 = 2716044179; - for(var i = 0; i < blocks; i = i + 16){ - k1 = bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24; - k2 = bytes[i + 4] | bytes[i + 5] << 8 | bytes[i + 6] << 16 | bytes[i + 7] << 24; - k3 = bytes[i + 8] | bytes[i + 9] << 8 | bytes[i + 10] << 16 | bytes[i + 11] << 24; - k4 = bytes[i + 12] | bytes[i + 13] << 8 | bytes[i + 14] << 16 | bytes[i + 15] << 24; - k1 = _x86Multiply(k1, c1); - k1 = _x86Rotl(k1, 15); - k1 = _x86Multiply(k1, c2); - h1 ^= k1; - h1 = _x86Rotl(h1, 19); - h1 += h2; - h1 = _x86Multiply(h1, 5) + 1444728091; - k2 = _x86Multiply(k2, c2); - k2 = _x86Rotl(k2, 16); - k2 = _x86Multiply(k2, c3); - h2 ^= k2; - h2 = _x86Rotl(h2, 17); - h2 += h3; - h2 = _x86Multiply(h2, 5) + 197830471; - k3 = _x86Multiply(k3, c3); - k3 = _x86Rotl(k3, 17); - k3 = _x86Multiply(k3, c4); - h3 ^= k3; - h3 = _x86Rotl(h3, 15); - h3 += h4; - h3 = _x86Multiply(h3, 5) + 2530024501; - k4 = _x86Multiply(k4, c4); - k4 = _x86Rotl(k4, 18); - k4 = _x86Multiply(k4, c1); - h4 ^= k4; - h4 = _x86Rotl(h4, 13); - h4 += h1; - h4 = _x86Multiply(h4, 5) + 850148119; + return arrayify(value); + case "string": + return toUtf8Bytes(value); + case "bytes": + return arrayify(value); + case "bool": + value = value ? "0x01" : "0x00"; + if (isArray) { + return zeroPad(value, 32); } - k1 = 0; - k2 = 0; - k3 = 0; - k4 = 0; - switch(remainder){ - case 15: - k4 ^= bytes[i + 14] << 16; - case 14: - k4 ^= bytes[i + 13] << 8; - case 13: - k4 ^= bytes[i + 12]; - k4 = _x86Multiply(k4, c4); - k4 = _x86Rotl(k4, 18); - k4 = _x86Multiply(k4, c1); - h4 ^= k4; - case 12: - k3 ^= bytes[i + 11] << 24; - case 11: - k3 ^= bytes[i + 10] << 16; - case 10: - k3 ^= bytes[i + 9] << 8; - case 9: - k3 ^= bytes[i + 8]; - k3 = _x86Multiply(k3, c3); - k3 = _x86Rotl(k3, 17); - k3 = _x86Multiply(k3, c4); - h3 ^= k3; - case 8: - k2 ^= bytes[i + 7] << 24; - case 7: - k2 ^= bytes[i + 6] << 16; - case 6: - k2 ^= bytes[i + 5] << 8; - case 5: - k2 ^= bytes[i + 4]; - k2 = _x86Multiply(k2, c2); - k2 = _x86Rotl(k2, 16); - k2 = _x86Multiply(k2, c3); - h2 ^= k2; - case 4: - k1 ^= bytes[i + 3] << 24; - case 3: - k1 ^= bytes[i + 2] << 16; - case 2: - k1 ^= bytes[i + 1] << 8; + return arrayify(value); + } + let match = type.match(regexNumber); + if (match) { + let size = parseInt(match[2] || "256"); + if (match[2] && String(size) !== match[2] || size % 8 !== 0 || size === 0 || size > 256) { + logger222.throwArgumentError("invalid number type", "type", type); + } + if (isArray) { + size = 256; + } + value = BigNumber.from(value).toTwos(size); + return zeroPad(value, size / 8); + } + match = type.match(regexBytes); + if (match) { + const size = parseInt(match[1]); + if (String(size) !== match[1] || size === 0 || size > 32) { + logger222.throwArgumentError("invalid bytes type", "type", type); + } + if (arrayify(value).byteLength !== size) { + logger222.throwArgumentError(`invalid value for ${type}`, "value", value); + } + if (isArray) { + return arrayify((value + Zeros1).substring(0, 66)); + } + return value; + } + match = type.match(regexArray); + if (match && Array.isArray(value)) { + const baseType = match[1]; + const count = parseInt(match[2] || String(value.length)); + if (count != value.length) { + logger222.throwArgumentError(`invalid array length for ${type}`, "value", value); + } + const result = []; + value.forEach(function(value2) { + result.push(_pack(baseType, value2, true)); + }); + return concat(result); + } + return logger222.throwArgumentError("invalid type", "type", type); +} +function pack1(types, values) { + if (types.length != values.length) { + logger222.throwArgumentError("wrong number of values; expected ${ types.length }", "values", values); + } + const tight = []; + types.forEach(function(type, index) { + tight.push(_pack(type, values[index])); + }); + return hexlify(concat(tight)); +} +function keccak2562(types, values) { + return keccak256(pack1(types, values)); +} +function sha2562(types, values) { + return sha2561(pack1(types, values)); +} +const version25 = "units/5.7.0"; +const logger223 = new Logger(version25); +const names = [ + "wei", + "kwei", + "mwei", + "gwei", + "szabo", + "finney", + "ether" +]; +function commify(value) { + const comps = String(value).split("."); + if (comps.length > 2 || !comps[0].match(/^-?[0-9]*$/) || comps[1] && !comps[1].match(/^[0-9]*$/) || value === "." || value === "-.") { + logger223.throwArgumentError("invalid value", "value", value); + } + let whole = comps[0]; + let negative = ""; + if (whole.substring(0, 1) === "-") { + negative = "-"; + whole = whole.substring(1); + } + while(whole.substring(0, 1) === "0"){ + whole = whole.substring(1); + } + if (whole === "") { + whole = "0"; + } + let suffix = ""; + if (comps.length === 2) { + suffix = "." + (comps[1] || "0"); + } + while(suffix.length > 2 && suffix[suffix.length - 1] === "0"){ + suffix = suffix.substring(0, suffix.length - 1); + } + const formatted = []; + while(whole.length){ + if (whole.length <= 3) { + formatted.unshift(whole); + break; + } else { + const index = whole.length - 3; + formatted.unshift(whole.substring(index)); + whole = whole.substring(0, index); + } + } + return negative + formatted.join(",") + suffix; +} +function formatUnits(value, unitName) { + if (typeof unitName === "string") { + const index = names.indexOf(unitName); + if (index !== -1) { + unitName = 3 * index; + } + } + return formatFixed(value, unitName != null ? unitName : 18); +} +function parseUnits(value, unitName) { + if (typeof value !== "string") { + logger223.throwArgumentError("value must be a string", "value", value); + } + if (typeof unitName === "string") { + const index = names.indexOf(unitName); + if (index !== -1) { + unitName = 3 * index; + } + } + return parseFixed(value, unitName != null ? unitName : 18); +} +function formatEther(wei) { + return formatUnits(wei, 18); +} +function parseEther(ether) { + return parseUnits(ether, 18); +} +var utils1 = Object.freeze({ + __proto__: null, + AbiCoder, + defaultAbiCoder, + Fragment, + ConstructorFragment, + ErrorFragment, + EventFragment, + FunctionFragment, + ParamType, + FormatTypes, + checkResultErrors, + Logger, + RLP: mod, + _fetchData, + fetchJson, + poll, + checkProperties, + deepCopy, + defineReadOnly, + getStatic, + resolveProperties, + shallowCopy, + arrayify, + concat, + stripZeros, + zeroPad, + isBytes, + isBytesLike, + defaultPath, + HDNode, + SigningKey, + Interface, + LogDescription, + TransactionDescription, + base58: Base58, + base64: mod2, + hexlify, + isHexString, + hexConcat, + hexStripZeros, + hexValue, + hexZeroPad, + hexDataLength, + hexDataSlice, + nameprep, + _toEscapedUtf8String, + toUtf8Bytes, + toUtf8CodePoints, + toUtf8String, + Utf8ErrorFuncs, + formatBytes32String, + parseBytes32String, + dnsEncode, + hashMessage, + namehash, + isValidName, + id, + _TypedDataEncoder: TypedDataEncoder, + getAddress, + getIcapAddress, + getContractAddress, + getCreate2Address, + isAddress, + formatEther, + parseEther, + formatUnits, + parseUnits, + commify, + computeHmac, + keccak256: keccak256, + ripemd160: ripemd1601, + sha256: sha2561, + sha512: sha5121, + randomBytes, + shuffled, + solidityPack: pack1, + solidityKeccak256: keccak2562, + soliditySha256: sha2562, + splitSignature, + joinSignature, + accessListify, + parseTransaction: parse, + serializeTransaction: serialize, + TransactionTypes, + getJsonWalletAddress, + computeAddress, + recoverAddress, + computePublicKey, + recoverPublicKey, + verifyMessage, + verifyTypedData, + getAccountPath, + mnemonicToEntropy, + entropyToMnemonic, + isValidMnemonic, + mnemonicToSeed, + SupportedAlgorithm, + UnicodeNormalizationForm, + Utf8ErrorReason, + Indexed +}); +const version26 = "ethers/5.7.2"; +const logger3 = new Logger(version26); +var ethers = Object.freeze({ + __proto__: null, + Signer, + Wallet, + VoidSigner, + getDefaultProvider, + providers: mod3, + BaseContract, + Contract, + ContractFactory, + BigNumber, + FixedNumber, + constants: mod1, + errors: ErrorCode, + logger: logger3, + utils: utils1, + wordlists: wordlists, + version: version26, + Wordlist +}); +try { + const anyGlobal = window; + if (anyGlobal._ethers == null) { + anyGlobal._ethers = ethers; + } +} catch (error) {} +const typeofs = [ + "string", + "number", + "bigint", + "symbol" +]; +const objectTypeNames = [ + "Function", + "Generator", + "AsyncGenerator", + "GeneratorFunction", + "AsyncGeneratorFunction", + "AsyncFunction", + "Observable", + "Array", + "Buffer", + "Object", + "RegExp", + "Date", + "Error", + "Map", + "Set", + "WeakMap", + "WeakSet", + "ArrayBuffer", + "SharedArrayBuffer", + "DataView", + "Promise", + "URL", + "HTMLElement", + "Int8Array", + "Uint8Array", + "Uint8ClampedArray", + "Int16Array", + "Uint16Array", + "Int32Array", + "Uint32Array", + "Float32Array", + "Float64Array", + "BigInt64Array", + "BigUint64Array" +]; +function is(value) { + if (value === null) { + return "null"; + } + if (value === void 0) { + return "undefined"; + } + if (value === true || value === false) { + return "boolean"; + } + const typeOf = typeof value; + if (typeofs.includes(typeOf)) { + return typeOf; + } + if (typeOf === "function") { + return "Function"; + } + if (Array.isArray(value)) { + return "Array"; + } + if (isBuffer(value)) { + return "Buffer"; + } + const objectType = getObjectType(value); + if (objectType) { + return objectType; + } + return "Object"; +} +function isBuffer(value) { + return value && value.constructor && value.constructor.isBuffer && value.constructor.isBuffer.call(null, value); +} +function getObjectType(value) { + const objectTypeName = Object.prototype.toString.call(value).slice(8, -1); + if (objectTypeNames.includes(objectTypeName)) { + return objectTypeName; + } + return void 0; +} +class Type { + constructor(major, name, terminal){ + this.major = major; + this.majorEncoded = major << 5; + this.name = name; + this.terminal = terminal; + } + toString() { + return `Type[${this.major}].${this.name}`; + } + compare(typ) { + return this.major < typ.major ? -1 : this.major > typ.major ? 1 : 0; + } +} +Type.uint = new Type(0, "uint", true); +Type.negint = new Type(1, "negint", true); +Type.bytes = new Type(2, "bytes", true); +Type.string = new Type(3, "string", true); +Type.array = new Type(4, "array", false); +Type.map = new Type(5, "map", false); +Type.tag = new Type(6, "tag", false); +Type.float = new Type(7, "float", true); +Type.false = new Type(7, "false", true); +Type.true = new Type(7, "true", true); +Type.null = new Type(7, "null", true); +Type.undefined = new Type(7, "undefined", true); +Type.break = new Type(7, "break", true); +class Token { + constructor(type, value, encodedLength){ + this.type = type; + this.value = value; + this.encodedLength = encodedLength; + this.encodedBytes = void 0; + this.byteValue = void 0; + } + toString() { + return `Token[${this.type}].${this.value}`; + } +} +const useBuffer = globalThis.process && !globalThis.process.browser && globalThis.Buffer && typeof globalThis.Buffer.isBuffer === "function"; +const textDecoder1 = new TextDecoder(); +const textEncoder = new TextEncoder(); +function isBuffer$1(buf2) { + return useBuffer && globalThis.Buffer.isBuffer(buf2); +} +function asU8A(buf2) { + if (!(buf2 instanceof Uint8Array)) { + return Uint8Array.from(buf2); + } + return isBuffer$1(buf2) ? new Uint8Array(buf2.buffer, buf2.byteOffset, buf2.byteLength) : buf2; +} +const toString = useBuffer ? (bytes, start, end)=>{ + return end - start > 64 ? globalThis.Buffer.from(bytes.subarray(start, end)).toString("utf8") : utf8Slice(bytes, start, end); +} : (bytes, start, end)=>{ + return end - start > 64 ? textDecoder1.decode(bytes.subarray(start, end)) : utf8Slice(bytes, start, end); +}; +const fromString = useBuffer ? (string)=>{ + return string.length > 64 ? globalThis.Buffer.from(string) : utf8ToBytes(string); +} : (string)=>{ + return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string); +}; +const fromArray = (arr)=>{ + return Uint8Array.from(arr); +}; +const slice = useBuffer ? (bytes, start, end)=>{ + if (isBuffer$1(bytes)) { + return new Uint8Array(bytes.subarray(start, end)); + } + return bytes.slice(start, end); +} : (bytes, start, end)=>{ + return bytes.slice(start, end); +}; +const concat1 = useBuffer ? (chunks, length)=>{ + chunks = chunks.map((c)=>c instanceof Uint8Array ? c : globalThis.Buffer.from(c)); + return asU8A(globalThis.Buffer.concat(chunks, length)); +} : (chunks, length)=>{ + const out = new Uint8Array(length); + let off = 0; + for (let b of chunks){ + if (off + b.length > out.length) { + b = b.subarray(0, out.length - off); + } + out.set(b, off); + off += b.length; + } + return out; +}; +const alloc = useBuffer ? (size)=>{ + return globalThis.Buffer.allocUnsafe(size); +} : (size)=>{ + return new Uint8Array(size); +}; +function compare(b1, b2) { + if (isBuffer$1(b1) && isBuffer$1(b2)) { + return b1.compare(b2); + } + for(let i = 0; i < b1.length; i++){ + if (b1[i] === b2[i]) { + continue; + } + return b1[i] < b2[i] ? -1 : 1; + } + return 0; +} +function utf8ToBytes(str) { + const out = []; + let p = 0; + for(let i = 0; i < str.length; i++){ + let c = str.charCodeAt(i); + if (c < 128) { + out[p++] = c; + } else if (c < 2048) { + out[p++] = c >> 6 | 192; + out[p++] = c & 63 | 128; + } else if ((c & 64512) === 55296 && i + 1 < str.length && (str.charCodeAt(i + 1) & 64512) === 56320) { + c = 65536 + ((c & 1023) << 10) + (str.charCodeAt(++i) & 1023); + out[p++] = c >> 18 | 240; + out[p++] = c >> 12 & 63 | 128; + out[p++] = c >> 6 & 63 | 128; + out[p++] = c & 63 | 128; + } else { + out[p++] = c >> 12 | 224; + out[p++] = c >> 6 & 63 | 128; + out[p++] = c & 63 | 128; + } + } + return out; +} +function utf8Slice(buf2, offset, end) { + const res = []; + while(offset < end){ + const firstByte = buf2[offset]; + let codePoint = null; + let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (offset + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + switch(bytesPerSequence){ case 1: - k1 ^= bytes[i]; - k1 = _x86Multiply(k1, c1); - k1 = _x86Rotl(k1, 15); - k1 = _x86Multiply(k1, c2); - h1 ^= k1; - } - h1 ^= bytes.length; - h2 ^= bytes.length; - h3 ^= bytes.length; - h4 ^= bytes.length; - h1 += h2; - h1 += h3; - h1 += h4; - h2 += h1; - h3 += h1; - h4 += h1; - h1 = _x86Fmix(h1); - h2 = _x86Fmix(h2); - h3 = _x86Fmix(h3); - h4 = _x86Fmix(h4); - h1 += h2; - h1 += h3; - h1 += h4; - h2 += h1; - h3 += h1; - h4 += h1; - return ("00000000" + (h1 >>> 0).toString(16)).slice(-8) + ("00000000" + (h2 >>> 0).toString(16)).slice(-8) + ("00000000" + (h3 >>> 0).toString(16)).slice(-8) + ("00000000" + (h4 >>> 0).toString(16)).slice(-8); - }; - library.x64.hash128 = function(bytes, seed) { - if (library.inputValidation && !_validBytes(bytes)) { - return undefined$1; + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf2[offset + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf2[offset + 1]; + thirdByte = buf2[offset + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf2[offset + 1]; + thirdByte = buf2[offset + 2]; + fourthByte = buf2[offset + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } } - seed = seed || 0; - var remainder = bytes.length % 16; - var blocks = bytes.length - remainder; - var h1 = [ - 0, - seed - ]; - var h2 = [ - 0, - seed - ]; - var k1 = [ - 0, - 0 - ]; - var k2 = [ - 0, - 0 - ]; - var c1 = [ - 2277735313, - 289559509 - ]; - var c2 = [ - 1291169091, - 658871167 - ]; - for(var i = 0; i < blocks; i = i + 16){ - k1 = [ - bytes[i + 4] | bytes[i + 5] << 8 | bytes[i + 6] << 16 | bytes[i + 7] << 24, - bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24 - ]; - k2 = [ - bytes[i + 12] | bytes[i + 13] << 8 | bytes[i + 14] << 16 | bytes[i + 15] << 24, - bytes[i + 8] | bytes[i + 9] << 8 | bytes[i + 10] << 16 | bytes[i + 11] << 24 - ]; - k1 = _x64Multiply(k1, c1); - k1 = _x64Rotl(k1, 31); - k1 = _x64Multiply(k1, c2); - h1 = _x64Xor(h1, k1); - h1 = _x64Rotl(h1, 27); - h1 = _x64Add(h1, h2); - h1 = _x64Add(_x64Multiply(h1, [ - 0, - 5 - ]), [ - 0, - 1390208809 - ]); - k2 = _x64Multiply(k2, c2); - k2 = _x64Rotl(k2, 33); - k2 = _x64Multiply(k2, c1); - h2 = _x64Xor(h2, k2); - h2 = _x64Rotl(h2, 31); - h2 = _x64Add(h2, h1); - h2 = _x64Add(_x64Multiply(h2, [ - 0, - 5 - ]), [ - 0, - 944331445 - ]); + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + offset += bytesPerSequence; + } + return decodeCodePointsArray(res); +} +const MAX_ARGUMENTS_LENGTH = 4096; +function decodeCodePointsArray(codePoints) { + const len = codePoints.length; + if (len <= 4096) { + return String.fromCharCode.apply(String, codePoints); + } + let res = ""; + let i = 0; + while(i < len){ + res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); + } + return res; +} +class Bl { + constructor(chunkSize = 256){ + this.chunkSize = chunkSize; + this.cursor = 0; + this.maxCursor = -1; + this.chunks = []; + this._initReuseChunk = null; + } + reset() { + this.cursor = 0; + this.maxCursor = -1; + if (this.chunks.length) { + this.chunks = []; + } + if (this._initReuseChunk !== null) { + this.chunks.push(this._initReuseChunk); + this.maxCursor = this._initReuseChunk.length - 1; + } + } + push(bytes) { + let topChunk = this.chunks[this.chunks.length - 1]; + const newMax = this.cursor + bytes.length; + if (newMax <= this.maxCursor + 1) { + const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1; + topChunk.set(bytes, chunkPos); + } else { + if (topChunk) { + const chunkPos = topChunk.length - (this.maxCursor - this.cursor) - 1; + if (chunkPos < topChunk.length) { + this.chunks[this.chunks.length - 1] = topChunk.subarray(0, chunkPos); + this.maxCursor = this.cursor - 1; + } } - k1 = [ + if (bytes.length < 64 && bytes.length < this.chunkSize) { + topChunk = alloc(this.chunkSize); + this.chunks.push(topChunk); + this.maxCursor += topChunk.length; + if (this._initReuseChunk === null) { + this._initReuseChunk = topChunk; + } + topChunk.set(bytes, 0); + } else { + this.chunks.push(bytes); + this.maxCursor += bytes.length; + } + } + this.cursor += bytes.length; + } + toBytes(reset = false) { + let byts; + if (this.chunks.length === 1) { + const chunk = this.chunks[0]; + if (reset && this.cursor > chunk.length / 2) { + byts = this.cursor === chunk.length ? chunk : chunk.subarray(0, this.cursor); + this._initReuseChunk = null; + this.chunks = []; + } else { + byts = slice(chunk, 0, this.cursor); + } + } else { + byts = concat1(this.chunks, this.cursor); + } + if (reset) { + this.reset(); + } + return byts; + } +} +const decodeErrPrefix = "CBOR decode error:"; +const encodeErrPrefix = "CBOR encode error:"; +const uintMinorPrefixBytes = []; +uintMinorPrefixBytes[23] = 1; +uintMinorPrefixBytes[24] = 2; +uintMinorPrefixBytes[25] = 3; +uintMinorPrefixBytes[26] = 5; +uintMinorPrefixBytes[27] = 9; +function assertEnoughData(data, pos, need) { + if (data.length - pos < need) { + throw new Error(`${decodeErrPrefix} not enough data for type`); + } +} +const uintBoundaries = [ + 24, + 256, + 65536, + 4294967296, + BigInt("18446744073709551616") +]; +function readUint8(data, offset, options) { + assertEnoughData(data, offset, 1); + const value = data[offset]; + if (options.strict === true && value < uintBoundaries[0]) { + throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); + } + return value; +} +function readUint16(data, offset, options) { + assertEnoughData(data, offset, 2); + const value = data[offset] << 8 | data[offset + 1]; + if (options.strict === true && value < uintBoundaries[1]) { + throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); + } + return value; +} +function readUint32(data, offset, options) { + assertEnoughData(data, offset, 4); + const value = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]; + if (options.strict === true && value < uintBoundaries[2]) { + throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); + } + return value; +} +function readUint64(data, offset, options) { + assertEnoughData(data, offset, 8); + const hi = data[offset] * 16777216 + (data[offset + 1] << 16) + (data[offset + 2] << 8) + data[offset + 3]; + const lo = data[offset + 4] * 16777216 + (data[offset + 5] << 16) + (data[offset + 6] << 8) + data[offset + 7]; + const value = (BigInt(hi) << BigInt(32)) + BigInt(lo); + if (options.strict === true && value < uintBoundaries[3]) { + throw new Error(`${decodeErrPrefix} integer encoded in more bytes than necessary (strict decode)`); + } + if (value <= Number.MAX_SAFE_INTEGER) { + return Number(value); + } + if (options.allowBigInt === true) { + return value; + } + throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`); +} +function decodeUint8(data, pos, _minor, options) { + return new Token(Type.uint, readUint8(data, pos + 1, options), 2); +} +function decodeUint16(data, pos, _minor, options) { + return new Token(Type.uint, readUint16(data, pos + 1, options), 3); +} +function decodeUint32(data, pos, _minor, options) { + return new Token(Type.uint, readUint32(data, pos + 1, options), 5); +} +function decodeUint64(data, pos, _minor, options) { + return new Token(Type.uint, readUint64(data, pos + 1, options), 9); +} +function encodeUint(buf2, token) { + return encodeUintValue(buf2, 0, token.value); +} +function encodeUintValue(buf2, major, uint) { + if (uint < uintBoundaries[0]) { + const nuint = Number(uint); + buf2.push([ + major | nuint + ]); + } else if (uint < uintBoundaries[1]) { + const nuint = Number(uint); + buf2.push([ + major | 24, + nuint + ]); + } else if (uint < uintBoundaries[2]) { + const nuint = Number(uint); + buf2.push([ + major | 25, + nuint >>> 8, + nuint & 255 + ]); + } else if (uint < uintBoundaries[3]) { + const nuint = Number(uint); + buf2.push([ + major | 26, + nuint >>> 24 & 255, + nuint >>> 16 & 255, + nuint >>> 8 & 255, + nuint & 255 + ]); + } else { + const buint = BigInt(uint); + if (buint < uintBoundaries[4]) { + const set = [ + major | 27, 0, - 0 - ]; - k2 = [ 0, - 0 - ]; - switch(remainder){ - case 15: - k2 = _x64Xor(k2, _x64LeftShift([ - 0, - bytes[i + 14] - ], 48)); - case 14: - k2 = _x64Xor(k2, _x64LeftShift([ - 0, - bytes[i + 13] - ], 40)); - case 13: - k2 = _x64Xor(k2, _x64LeftShift([ - 0, - bytes[i + 12] - ], 32)); - case 12: - k2 = _x64Xor(k2, _x64LeftShift([ - 0, - bytes[i + 11] - ], 24)); - case 11: - k2 = _x64Xor(k2, _x64LeftShift([ - 0, - bytes[i + 10] - ], 16)); - case 10: - k2 = _x64Xor(k2, _x64LeftShift([ - 0, - bytes[i + 9] - ], 8)); - case 9: - k2 = _x64Xor(k2, [ - 0, - bytes[i + 8] - ]); - k2 = _x64Multiply(k2, c2); - k2 = _x64Rotl(k2, 33); - k2 = _x64Multiply(k2, c1); - h2 = _x64Xor(h2, k2); - case 8: - k1 = _x64Xor(k1, _x64LeftShift([ - 0, - bytes[i + 7] - ], 56)); - case 7: - k1 = _x64Xor(k1, _x64LeftShift([ - 0, - bytes[i + 6] - ], 48)); - case 6: - k1 = _x64Xor(k1, _x64LeftShift([ - 0, - bytes[i + 5] - ], 40)); - case 5: - k1 = _x64Xor(k1, _x64LeftShift([ - 0, - bytes[i + 4] - ], 32)); - case 4: - k1 = _x64Xor(k1, _x64LeftShift([ - 0, - bytes[i + 3] - ], 24)); - case 3: - k1 = _x64Xor(k1, _x64LeftShift([ - 0, - bytes[i + 2] - ], 16)); - case 2: - k1 = _x64Xor(k1, _x64LeftShift([ - 0, - bytes[i + 1] - ], 8)); - case 1: - k1 = _x64Xor(k1, [ - 0, - bytes[i] - ]); - k1 = _x64Multiply(k1, c1); - k1 = _x64Rotl(k1, 31); - k1 = _x64Multiply(k1, c2); - h1 = _x64Xor(h1, k1); - } - h1 = _x64Xor(h1, [ 0, - bytes.length - ]); - h2 = _x64Xor(h2, [ 0, - bytes.length - ]); - h1 = _x64Add(h1, h2); - h2 = _x64Add(h2, h1); - h1 = _x64Fmix(h1); - h2 = _x64Fmix(h2); - h1 = _x64Add(h1, h2); - h2 = _x64Add(h2, h1); - return ("00000000" + (h1[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h1[1] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[1] >>> 0).toString(16)).slice(-8); - }; - { - if (module.exports) { - exports = module.exports = library; - } - exports.murmurHash3 = library; + 0, + 0, + 0 + ]; + let lo = Number(buint & BigInt(4294967295)); + let hi = Number(buint >> BigInt(32) & BigInt(4294967295)); + set[8] = lo & 255; + lo = lo >> 8; + set[7] = lo & 255; + lo = lo >> 8; + set[6] = lo & 255; + lo = lo >> 8; + set[5] = lo & 255; + set[4] = hi & 255; + hi = hi >> 8; + set[3] = hi & 255; + hi = hi >> 8; + set[2] = hi & 255; + hi = hi >> 8; + set[1] = hi & 255; + buf2.push(set); + } else { + throw new Error(`${decodeErrPrefix} encountered BigInt larger than allowable range`); } - })(); -}); -var murmurhash3jsRevisited = murmurHash3js; -murmurhash3jsRevisited.murmurHash3; -function fromNumberTo32BitBuf(number) { - const bytes2 = new Array(4); - for(let i = 0; i < 4; i++){ - bytes2[i] = number & 255; - number = number >> 8; } - return new Uint8Array(bytes2); } -const murmur332 = from2({ - name: "murmur3-32", - code: 35, - encode: (input)=>fromNumberTo32BitBuf(murmurhash3jsRevisited.x86.hash32(input)) -}); -const murmur3128 = from2({ - name: "murmur3-128", - code: 34, - encode: (input)=>bytes1.fromHex(murmurhash3jsRevisited.x64.hash128(input)) -}); -const ERROR_MSG_INPUT = "Input must be an string, Buffer or Uint8Array"; -function normalizeInput(input) { - let ret; - if (input instanceof Uint8Array) { - ret = input; - } else if (typeof input === "string") { - const encoder = new TextEncoder(); - ret = encoder.encode(input); - } else { - throw new Error(ERROR_MSG_INPUT); +encodeUint.encodedSize = function encodedSize(token) { + return encodeUintValue.encodedSize(token.value); +}; +encodeUintValue.encodedSize = function encodedSize2(uint) { + if (uint < uintBoundaries[0]) { + return 1; } - return ret; + if (uint < uintBoundaries[1]) { + return 2; + } + if (uint < uintBoundaries[2]) { + return 3; + } + if (uint < uintBoundaries[3]) { + return 5; + } + return 9; +}; +encodeUint.compareTokens = function compareTokens(tok1, tok2) { + return tok1.value < tok2.value ? -1 : tok1.value > tok2.value ? 1 : 0; +}; +function decodeNegint8(data, pos, _minor, options) { + return new Token(Type.negint, -1 - readUint8(data, pos + 1, options), 2); } -function toHex3(bytes) { - return Array.prototype.map.call(bytes, function(n) { - return (n < 16 ? "0" : "") + n.toString(16); - }).join(""); +function decodeNegint16(data, pos, _minor, options) { + return new Token(Type.negint, -1 - readUint16(data, pos + 1, options), 3); } -function uint32ToHex(val) { - return (4294967296 + val).toString(16).substring(1); +function decodeNegint32(data, pos, _minor, options) { + return new Token(Type.negint, -1 - readUint32(data, pos + 1, options), 5); } -function debugPrint(label, arr, size) { - let msg = "\n" + label + " = "; - for(let i = 0; i < arr.length; i += 2){ - if (size === 32) { - msg += uint32ToHex(arr[i]).toUpperCase(); - msg += " "; - msg += uint32ToHex(arr[i + 1]).toUpperCase(); - } else if (size === 64) { - msg += uint32ToHex(arr[i + 1]).toUpperCase(); - msg += uint32ToHex(arr[i]).toUpperCase(); - } else throw new Error("Invalid size " + size); - if (i % 6 === 4) { - msg += "\n" + new Array(label.length + 4).join(" "); - } else if (i < arr.length - 2) { - msg += " "; +const neg1b = BigInt(-1); +const pos1b = BigInt(1); +function decodeNegint64(data, pos, _minor, options) { + const __int = readUint64(data, pos + 1, options); + if (typeof __int !== "bigint") { + const value = -1 - __int; + if (value >= Number.MIN_SAFE_INTEGER) { + return new Token(Type.negint, value, 9); } } - console.log(msg); + if (options.allowBigInt !== true) { + throw new Error(`${decodeErrPrefix} integers outside of the safe integer range are not supported`); + } + return new Token(Type.negint, neg1b - BigInt(__int), 9); } -function testSpeed(hashFn, N, M) { - let startMs = new Date().getTime(); - const input = new Uint8Array(N); - for(let i = 0; i < N; i++){ - input[i] = i % 256; +function encodeNegint(buf2, token) { + const negint = token.value; + const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1; + encodeUintValue(buf2, token.type.majorEncoded, unsigned); +} +encodeNegint.encodedSize = function encodedSize3(token) { + const negint = token.value; + const unsigned = typeof negint === "bigint" ? negint * neg1b - pos1b : negint * -1 - 1; + if (unsigned < uintBoundaries[0]) { + return 1; } - const genMs = new Date().getTime(); - console.log("Generated random input in " + (genMs - startMs) + "ms"); - startMs = genMs; - for(let i = 0; i < M; i++){ - const hashHex = hashFn(input); - const hashMs = new Date().getTime(); - const ms = hashMs - startMs; - startMs = hashMs; - console.log("Hashed in " + ms + "ms: " + hashHex.substring(0, 20) + "..."); - console.log(Math.round(N / (1 << 20) / (ms / 1e3) * 100) / 100 + " MB PER SECOND"); + if (unsigned < uintBoundaries[1]) { + return 2; } -} -var util = { - normalizeInput, - toHex: toHex3, - debugPrint, - testSpeed + if (unsigned < uintBoundaries[2]) { + return 3; + } + if (unsigned < uintBoundaries[3]) { + return 5; + } + return 9; }; -function ADD64AA(v2, a, b) { - const o0 = v2[a] + v2[b]; - let o1 = v2[a + 1] + v2[b + 1]; - if (o0 >= 4294967296) { - o1++; +encodeNegint.compareTokens = function compareTokens2(tok1, tok2) { + return tok1.value < tok2.value ? 1 : tok1.value > tok2.value ? -1 : 0; +}; +function toToken(data, pos, prefix, length) { + assertEnoughData(data, pos, prefix + length); + const buf2 = slice(data, pos + prefix, pos + prefix + length); + return new Token(Type.bytes, buf2, prefix + length); +} +function decodeBytesCompact(data, pos, minor, _options) { + return toToken(data, pos, 1, minor); +} +function decodeBytes8(data, pos, _minor, options) { + return toToken(data, pos, 2, readUint8(data, pos + 1, options)); +} +function decodeBytes16(data, pos, _minor, options) { + return toToken(data, pos, 3, readUint16(data, pos + 1, options)); +} +function decodeBytes32(data, pos, _minor, options) { + return toToken(data, pos, 5, readUint32(data, pos + 1, options)); +} +function decodeBytes64(data, pos, _minor, options) { + const l = readUint64(data, pos + 1, options); + if (typeof l === "bigint") { + throw new Error(`${decodeErrPrefix} 64-bit integer bytes lengths not supported`); } - v2[a] = o0; - v2[a + 1] = o1; + return toToken(data, pos, 9, l); } -function ADD64AC(v2, a, b0, b1) { - let o0 = v2[a] + b0; - if (b0 < 0) { - o0 += 4294967296; +function tokenBytes(token) { + if (token.encodedBytes === void 0) { + token.encodedBytes = token.type === Type.string ? fromString(token.value) : token.value; } - let o1 = v2[a + 1] + b1; - if (o0 >= 4294967296) { - o1++; + return token.encodedBytes; +} +function encodeBytes1(buf2, token) { + const bytes = tokenBytes(token); + encodeUintValue(buf2, token.type.majorEncoded, bytes.length); + buf2.push(bytes); +} +encodeBytes1.encodedSize = function encodedSize4(token) { + const bytes = tokenBytes(token); + return encodeUintValue.encodedSize(bytes.length) + bytes.length; +}; +encodeBytes1.compareTokens = function compareTokens3(tok1, tok2) { + return compareBytes(tokenBytes(tok1), tokenBytes(tok2)); +}; +function compareBytes(b1, b2) { + return b1.length < b2.length ? -1 : b1.length > b2.length ? 1 : compare(b1, b2); +} +function toToken$1(data, pos, prefix, length, options) { + const totLength = prefix + length; + assertEnoughData(data, pos, totLength); + const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength); + if (options.retainStringBytes === true) { + tok.byteValue = slice(data, pos + prefix, pos + totLength); } - v2[a] = o0; - v2[a + 1] = o1; + return tok; } -function B2B_GET32(arr, i) { - return arr[i] ^ arr[i + 1] << 8 ^ arr[i + 2] << 16 ^ arr[i + 3] << 24; +function decodeStringCompact(data, pos, minor, options) { + return toToken$1(data, pos, 1, minor, options); +} +function decodeString8(data, pos, _minor, options) { + return toToken$1(data, pos, 2, readUint8(data, pos + 1, options), options); +} +function decodeString16(data, pos, _minor, options) { + return toToken$1(data, pos, 3, readUint16(data, pos + 1, options), options); +} +function decodeString32(data, pos, _minor, options) { + return toToken$1(data, pos, 5, readUint32(data, pos + 1, options), options); +} +function decodeString64(data, pos, _minor, options) { + const l = readUint64(data, pos + 1, options); + if (typeof l === "bigint") { + throw new Error(`${decodeErrPrefix} 64-bit integer string lengths not supported`); + } + return toToken$1(data, pos, 9, l, options); } -function B2B_G(a, b, c, d, ix, iy) { - const x0 = m[ix]; - const x1 = m[ix + 1]; - const y0 = m[iy]; - const y1 = m[iy + 1]; - ADD64AA(v, a, b); - ADD64AC(v, a, x0, x1); - let xor0 = v[d] ^ v[a]; - let xor1 = v[d + 1] ^ v[a + 1]; - v[d] = xor1; - v[d + 1] = xor0; - ADD64AA(v, c, d); - xor0 = v[b] ^ v[c]; - xor1 = v[b + 1] ^ v[c + 1]; - v[b] = xor0 >>> 24 ^ xor1 << 8; - v[b + 1] = xor1 >>> 24 ^ xor0 << 8; - ADD64AA(v, a, b); - ADD64AC(v, a, y0, y1); - xor0 = v[d] ^ v[a]; - xor1 = v[d + 1] ^ v[a + 1]; - v[d] = xor0 >>> 16 ^ xor1 << 16; - v[d + 1] = xor1 >>> 16 ^ xor0 << 16; - ADD64AA(v, c, d); - xor0 = v[b] ^ v[c]; - xor1 = v[b + 1] ^ v[c + 1]; - v[b] = xor1 >>> 31 ^ xor0 << 1; - v[b + 1] = xor0 >>> 31 ^ xor1 << 1; +const encodeString = encodeBytes1; +function toToken$2(_data, _pos, prefix, length) { + return new Token(Type.array, length, prefix); } -const BLAKE2B_IV32 = new Uint32Array([ - 4089235720, - 1779033703, - 2227873595, - 3144134277, - 4271175723, - 1013904242, - 1595750129, - 2773480762, - 2917565137, - 1359893119, - 725511199, - 2600822924, - 4215389547, - 528734635, - 327033209, - 1541459225 -]); -const SIGMA8 = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3, - 11, - 8, - 12, - 0, - 5, - 2, - 15, - 13, - 10, - 14, - 3, - 6, - 7, - 1, - 9, - 4, - 7, - 9, - 3, - 1, - 13, - 12, - 11, - 14, - 2, - 6, - 5, - 10, - 4, - 0, - 15, - 8, - 9, - 0, - 5, - 7, - 2, - 4, - 10, - 15, - 14, - 1, - 11, - 12, - 6, - 8, - 3, - 13, - 2, - 12, - 6, - 10, - 0, - 11, - 8, - 3, - 4, - 13, - 7, - 5, - 15, - 14, - 1, - 9, - 12, - 5, - 1, - 15, - 14, - 13, - 4, - 10, - 0, - 7, - 6, - 3, - 9, - 2, - 8, - 11, - 13, - 11, - 7, - 14, - 12, - 1, - 3, - 9, - 5, - 0, - 15, - 4, - 8, - 6, - 2, - 10, - 6, - 15, - 14, - 9, - 11, - 3, - 0, - 8, - 12, - 2, - 13, - 7, - 1, - 4, - 10, - 5, - 10, - 2, - 8, - 4, - 7, - 6, - 1, - 5, - 15, - 11, - 9, - 14, - 3, - 12, - 13, - 0, - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3 -]; -const SIGMA82 = new Uint8Array(SIGMA8.map(function(x) { - return x * 2; -})); -const v = new Uint32Array(32); -const m = new Uint32Array(32); -function blake2bCompress(ctx, last) { - let i = 0; - for(i = 0; i < 16; i++){ - v[i] = ctx.h[i]; - v[i + 16] = BLAKE2B_IV32[i]; +function decodeArrayCompact(data, pos, minor, _options) { + return toToken$2(data, pos, 1, minor); +} +function decodeArray8(data, pos, _minor, options) { + return toToken$2(data, pos, 2, readUint8(data, pos + 1, options)); +} +function decodeArray16(data, pos, _minor, options) { + return toToken$2(data, pos, 3, readUint16(data, pos + 1, options)); +} +function decodeArray32(data, pos, _minor, options) { + return toToken$2(data, pos, 5, readUint32(data, pos + 1, options)); +} +function decodeArray64(data, pos, _minor, options) { + const l = readUint64(data, pos + 1, options); + if (typeof l === "bigint") { + throw new Error(`${decodeErrPrefix} 64-bit integer array lengths not supported`); } - v[24] = v[24] ^ ctx.t; - v[25] = v[25] ^ ctx.t / 4294967296; - if (last) { - v[28] = ~v[28]; - v[29] = ~v[29]; + return toToken$2(data, pos, 9, l); +} +function decodeArrayIndefinite(data, pos, _minor, options) { + if (options.allowIndefinite === false) { + throw new Error(`${decodeErrPrefix} indefinite length items not allowed`); } - for(i = 0; i < 32; i++){ - m[i] = B2B_GET32(ctx.b, 4 * i); + return toToken$2(data, pos, 1, Infinity); +} +function encodeArray(buf2, token) { + encodeUintValue(buf2, Type.array.majorEncoded, token.value); +} +encodeArray.compareTokens = encodeUint.compareTokens; +encodeArray.encodedSize = function encodedSize5(token) { + return encodeUintValue.encodedSize(token.value); +}; +function toToken$3(_data, _pos, prefix, length) { + return new Token(Type.map, length, prefix); +} +function decodeMapCompact(data, pos, minor, _options) { + return toToken$3(data, pos, 1, minor); +} +function decodeMap8(data, pos, _minor, options) { + return toToken$3(data, pos, 2, readUint8(data, pos + 1, options)); +} +function decodeMap16(data, pos, _minor, options) { + return toToken$3(data, pos, 3, readUint16(data, pos + 1, options)); +} +function decodeMap32(data, pos, _minor, options) { + return toToken$3(data, pos, 5, readUint32(data, pos + 1, options)); +} +function decodeMap64(data, pos, _minor, options) { + const l = readUint64(data, pos + 1, options); + if (typeof l === "bigint") { + throw new Error(`${decodeErrPrefix} 64-bit integer map lengths not supported`); } - for(i = 0; i < 12; i++){ - B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]); - B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]); - B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]); - B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]); - B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]); - B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]); - B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]); - B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]); + return toToken$3(data, pos, 9, l); +} +function decodeMapIndefinite(data, pos, _minor, options) { + if (options.allowIndefinite === false) { + throw new Error(`${decodeErrPrefix} indefinite length items not allowed`); } - for(i = 0; i < 16; i++){ - ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16]; + return toToken$3(data, pos, 1, Infinity); +} +function encodeMap(buf2, token) { + encodeUintValue(buf2, Type.map.majorEncoded, token.value); +} +encodeMap.compareTokens = encodeUint.compareTokens; +encodeMap.encodedSize = function encodedSize6(token) { + return encodeUintValue.encodedSize(token.value); +}; +function decodeTagCompact(_data, _pos, minor, _options) { + return new Token(Type.tag, minor, 1); +} +function decodeTag8(data, pos, _minor, options) { + return new Token(Type.tag, readUint8(data, pos + 1, options), 2); +} +function decodeTag16(data, pos, _minor, options) { + return new Token(Type.tag, readUint16(data, pos + 1, options), 3); +} +function decodeTag32(data, pos, _minor, options) { + return new Token(Type.tag, readUint32(data, pos + 1, options), 5); +} +function decodeTag64(data, pos, _minor, options) { + return new Token(Type.tag, readUint64(data, pos + 1, options), 9); +} +function encodeTag(buf2, token) { + encodeUintValue(buf2, Type.tag.majorEncoded, token.value); +} +encodeTag.compareTokens = encodeUint.compareTokens; +encodeTag.encodedSize = function encodedSize7(token) { + return encodeUintValue.encodedSize(token.value); +}; +function decodeUndefined(_data, _pos, _minor, options) { + if (options.allowUndefined === false) { + throw new Error(`${decodeErrPrefix} undefined values are not supported`); + } else if (options.coerceUndefinedToNull === true) { + return new Token(Type.null, null, 1); + } + return new Token(Type.undefined, void 0, 1); +} +function decodeBreak(_data, _pos, _minor, options) { + if (options.allowIndefinite === false) { + throw new Error(`${decodeErrPrefix} indefinite length items not allowed`); + } + return new Token(Type.break, void 0, 1); +} +function createToken(value, bytes, options) { + if (options) { + if (options.allowNaN === false && Number.isNaN(value)) { + throw new Error(`${decodeErrPrefix} NaN values are not supported`); + } + if (options.allowInfinity === false && (value === Infinity || value === -Infinity)) { + throw new Error(`${decodeErrPrefix} Infinity values are not supported`); + } + } + return new Token(Type.float, value, bytes); +} +function decodeFloat16(data, pos, _minor, options) { + return createToken(readFloat16(data, pos + 1), 3, options); +} +function decodeFloat32(data, pos, _minor, options) { + return createToken(readFloat32(data, pos + 1), 5, options); +} +function decodeFloat64(data, pos, _minor, options) { + return createToken(readFloat64(data, pos + 1), 9, options); +} +function encodeFloat(buf2, token, options) { + const __float = token.value; + if (__float === false) { + buf2.push([ + Type.float.majorEncoded | 20 + ]); + } else if (__float === true) { + buf2.push([ + Type.float.majorEncoded | 21 + ]); + } else if (__float === null) { + buf2.push([ + Type.float.majorEncoded | 22 + ]); + } else if (__float === void 0) { + buf2.push([ + Type.float.majorEncoded | 23 + ]); + } else { + let decoded; + let success = false; + if (!options || options.float64 !== true) { + encodeFloat16(__float); + decoded = readFloat16(ui8a, 1); + if (__float === decoded || Number.isNaN(__float)) { + ui8a[0] = 249; + buf2.push(ui8a.slice(0, 3)); + success = true; + } else { + encodeFloat32(__float); + decoded = readFloat32(ui8a, 1); + if (__float === decoded) { + ui8a[0] = 250; + buf2.push(ui8a.slice(0, 5)); + success = true; + } + } + } + if (!success) { + encodeFloat64(__float); + decoded = readFloat64(ui8a, 1); + ui8a[0] = 251; + buf2.push(ui8a.slice(0, 9)); + } + } +} +encodeFloat.encodedSize = function encodedSize8(token, options) { + const __float = token.value; + if (__float === false || __float === true || __float === null || __float === void 0) { + return 1; + } + if (!options || options.float64 !== true) { + encodeFloat16(__float); + let decoded = readFloat16(ui8a, 1); + if (__float === decoded || Number.isNaN(__float)) { + return 3; + } + encodeFloat32(__float); + decoded = readFloat32(ui8a, 1); + if (__float === decoded) { + return 5; + } + } + return 9; +}; +const buffer = new ArrayBuffer(9); +const dataView = new DataView(buffer, 1); +const ui8a = new Uint8Array(buffer, 0); +function encodeFloat16(inp) { + if (inp === Infinity) { + dataView.setUint16(0, 31744, false); + } else if (inp === -Infinity) { + dataView.setUint16(0, 64512, false); + } else if (Number.isNaN(inp)) { + dataView.setUint16(0, 32256, false); + } else { + dataView.setFloat32(0, inp); + const valu32 = dataView.getUint32(0); + const exponent = (valu32 & 2139095040) >> 23; + const mantissa = valu32 & 8388607; + if (exponent === 255) { + dataView.setUint16(0, 31744, false); + } else if (exponent === 0) { + dataView.setUint16(0, (inp & 2147483648) >> 16 | mantissa >> 13, false); + } else { + const logicalExponent = exponent - 127; + if (logicalExponent < -24) { + dataView.setUint16(0, 0); + } else if (logicalExponent < -14) { + dataView.setUint16(0, (valu32 & 2147483648) >> 16 | 1 << 24 + logicalExponent, false); + } else { + dataView.setUint16(0, (valu32 & 2147483648) >> 16 | logicalExponent + 15 << 10 | mantissa >> 13, false); + } + } + } +} +function readFloat16(ui8a2, pos) { + if (ui8a2.length - pos < 2) { + throw new Error(`${decodeErrPrefix} not enough data for float16`); + } + const half = (ui8a2[pos] << 8) + ui8a2[pos + 1]; + if (half === 31744) { + return Infinity; + } + if (half === 64512) { + return -Infinity; + } + if (half === 32256) { + return NaN; + } + const exp = half >> 10 & 31; + const mant = half & 1023; + let val; + if (exp === 0) { + val = mant * 2 ** -24; + } else if (exp !== 31) { + val = (mant + 1024) * 2 ** (exp - 25); + } else { + val = mant === 0 ? Infinity : NaN; + } + return half & 32768 ? -val : val; +} +function encodeFloat32(inp) { + dataView.setFloat32(0, inp, false); +} +function readFloat32(ui8a2, pos) { + if (ui8a2.length - pos < 4) { + throw new Error(`${decodeErrPrefix} not enough data for float32`); } + const offset = (ui8a2.byteOffset || 0) + pos; + return new DataView(ui8a2.buffer, offset, 4).getFloat32(0, false); } -const parameterBlock = new Uint8Array([ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 -]); -function blake2bInit(outlen, key, salt, personal) { - if (outlen === 0 || outlen > 64) { - throw new Error("Illegal output length, expected 0 < length <= 64"); +function encodeFloat64(inp) { + dataView.setFloat64(0, inp, false); +} +function readFloat64(ui8a2, pos) { + if (ui8a2.length - pos < 8) { + throw new Error(`${decodeErrPrefix} not enough data for float64`); } - if (key && key.length > 64) { - throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64"); + const offset = (ui8a2.byteOffset || 0) + pos; + return new DataView(ui8a2.buffer, offset, 8).getFloat64(0, false); +} +encodeFloat.compareTokens = encodeUint.compareTokens; +function invalidMinor(data, pos, minor) { + throw new Error(`${decodeErrPrefix} encountered invalid minor (${minor}) for major ${data[pos] >>> 5}`); +} +function errorer(msg) { + return ()=>{ + throw new Error(`${decodeErrPrefix} ${msg}`); + }; +} +const jump = []; +for(let i = 0; i <= 23; i++){ + jump[i] = invalidMinor; +} +jump[24] = decodeUint8; +jump[25] = decodeUint16; +jump[26] = decodeUint32; +jump[27] = decodeUint64; +jump[28] = invalidMinor; +jump[29] = invalidMinor; +jump[30] = invalidMinor; +jump[31] = invalidMinor; +for(let i = 32; i <= 55; i++){ + jump[i] = invalidMinor; +} +jump[56] = decodeNegint8; +jump[57] = decodeNegint16; +jump[58] = decodeNegint32; +jump[59] = decodeNegint64; +jump[60] = invalidMinor; +jump[61] = invalidMinor; +jump[62] = invalidMinor; +jump[63] = invalidMinor; +for(let i = 64; i <= 87; i++){ + jump[i] = decodeBytesCompact; +} +jump[88] = decodeBytes8; +jump[89] = decodeBytes16; +jump[90] = decodeBytes32; +jump[91] = decodeBytes64; +jump[92] = invalidMinor; +jump[93] = invalidMinor; +jump[94] = invalidMinor; +jump[95] = errorer("indefinite length bytes/strings are not supported"); +for(let i = 96; i <= 119; i++){ + jump[i] = decodeStringCompact; +} +jump[120] = decodeString8; +jump[121] = decodeString16; +jump[122] = decodeString32; +jump[123] = decodeString64; +jump[124] = invalidMinor; +jump[125] = invalidMinor; +jump[126] = invalidMinor; +jump[127] = errorer("indefinite length bytes/strings are not supported"); +for(let i = 128; i <= 151; i++){ + jump[i] = decodeArrayCompact; +} +jump[152] = decodeArray8; +jump[153] = decodeArray16; +jump[154] = decodeArray32; +jump[155] = decodeArray64; +jump[156] = invalidMinor; +jump[157] = invalidMinor; +jump[158] = invalidMinor; +jump[159] = decodeArrayIndefinite; +for(let i = 160; i <= 183; i++){ + jump[i] = decodeMapCompact; +} +jump[184] = decodeMap8; +jump[185] = decodeMap16; +jump[186] = decodeMap32; +jump[187] = decodeMap64; +jump[188] = invalidMinor; +jump[189] = invalidMinor; +jump[190] = invalidMinor; +jump[191] = decodeMapIndefinite; +for(let i = 192; i <= 215; i++){ + jump[i] = decodeTagCompact; +} +jump[216] = decodeTag8; +jump[217] = decodeTag16; +jump[218] = decodeTag32; +jump[219] = decodeTag64; +jump[220] = invalidMinor; +jump[221] = invalidMinor; +jump[222] = invalidMinor; +jump[223] = invalidMinor; +for(let i = 224; i <= 243; i++){ + jump[i] = errorer("simple values are not supported"); +} +jump[244] = invalidMinor; +jump[245] = invalidMinor; +jump[246] = invalidMinor; +jump[247] = decodeUndefined; +jump[248] = errorer("simple values are not supported"); +jump[249] = decodeFloat16; +jump[250] = decodeFloat32; +jump[251] = decodeFloat64; +jump[252] = invalidMinor; +jump[253] = invalidMinor; +jump[254] = invalidMinor; +jump[255] = decodeBreak; +const quick = []; +for(let i = 0; i < 24; i++){ + quick[i] = new Token(Type.uint, i, 1); +} +for(let i = -1; i >= -24; i--){ + quick[31 - i] = new Token(Type.negint, i, 1); +} +quick[64] = new Token(Type.bytes, new Uint8Array(0), 1); +quick[96] = new Token(Type.string, "", 1); +quick[128] = new Token(Type.array, 0, 1); +quick[160] = new Token(Type.map, 0, 1); +quick[244] = new Token(Type.false, false, 1); +quick[245] = new Token(Type.true, true, 1); +quick[246] = new Token(Type.null, null, 1); +function quickEncodeToken(token) { + switch(token.type){ + case Type.false: + return fromArray([ + 244 + ]); + case Type.true: + return fromArray([ + 245 + ]); + case Type.null: + return fromArray([ + 246 + ]); + case Type.bytes: + if (!token.value.length) { + return fromArray([ + 64 + ]); + } + return; + case Type.string: + if (token.value === "") { + return fromArray([ + 96 + ]); + } + return; + case Type.array: + if (token.value === 0) { + return fromArray([ + 128 + ]); + } + return; + case Type.map: + if (token.value === 0) { + return fromArray([ + 160 + ]); + } + return; + case Type.uint: + if (token.value < 24) { + return fromArray([ + Number(token.value) + ]); + } + return; + case Type.negint: + if (token.value >= -24) { + return fromArray([ + 31 - Number(token.value) + ]); + } } - if (salt && salt.length !== 16) { - throw new Error("Illegal salt, expected Uint8Array with length is 16"); +} +const defaultEncodeOptions = { + float64: false, + mapSorter, + quickEncodeToken +}; +function makeCborEncoders() { + const encoders = []; + encoders[Type.uint.major] = encodeUint; + encoders[Type.negint.major] = encodeNegint; + encoders[Type.bytes.major] = encodeBytes1; + encoders[Type.string.major] = encodeString; + encoders[Type.array.major] = encodeArray; + encoders[Type.map.major] = encodeMap; + encoders[Type.tag.major] = encodeTag; + encoders[Type.float.major] = encodeFloat; + return encoders; +} +const cborEncoders = makeCborEncoders(); +const buf = new Bl(); +class Ref { + constructor(obj, parent){ + this.obj = obj; + this.parent = parent; } - if (personal && personal.length !== 16) { - throw new Error("Illegal personal, expected Uint8Array with length is 16"); + includes(obj) { + let p = this; + do { + if (p.obj === obj) { + return true; + } + }while (p = p.parent) + return false; } - const ctx = { - b: new Uint8Array(128), - h: new Uint32Array(16), - t: 0, - c: 0, - outlen - }; - parameterBlock.fill(0); - parameterBlock[0] = outlen; - if (key) parameterBlock[1] = key.length; - parameterBlock[2] = 1; - parameterBlock[3] = 1; - if (salt) parameterBlock.set(salt, 32); - if (personal) parameterBlock.set(personal, 48); - for(let i = 0; i < 16; i++){ - ctx.h[i] = BLAKE2B_IV32[i] ^ B2B_GET32(parameterBlock, i * 4); + static createCheck(stack, obj) { + if (stack && stack.includes(obj)) { + throw new Error(`${encodeErrPrefix} object contains circular references`); + } + return new Ref(obj, stack); } - if (key) { - blake2bUpdate(ctx, key); - ctx.c = 128; +} +const simpleTokens = { + null: new Token(Type.null, null), + undefined: new Token(Type.undefined, void 0), + true: new Token(Type.true, true), + false: new Token(Type.false, false), + emptyArray: new Token(Type.array, 0), + emptyMap: new Token(Type.map, 0) +}; +const typeEncoders = { + number (obj, _typ, _options, _refStack) { + if (!Number.isInteger(obj) || !Number.isSafeInteger(obj)) { + return new Token(Type.float, obj); + } else if (obj >= 0) { + return new Token(Type.uint, obj); + } else { + return new Token(Type.negint, obj); + } + }, + bigint (obj, _typ, _options, _refStack) { + if (obj >= BigInt(0)) { + return new Token(Type.uint, obj); + } else { + return new Token(Type.negint, obj); + } + }, + Uint8Array (obj, _typ, _options, _refStack) { + return new Token(Type.bytes, obj); + }, + string (obj, _typ, _options, _refStack) { + return new Token(Type.string, obj); + }, + boolean (obj, _typ, _options, _refStack) { + return obj ? simpleTokens.true : simpleTokens.false; + }, + null (_obj, _typ, _options, _refStack) { + return simpleTokens.null; + }, + undefined (_obj, _typ, _options, _refStack) { + return simpleTokens.undefined; + }, + ArrayBuffer (obj, _typ, _options, _refStack) { + return new Token(Type.bytes, new Uint8Array(obj)); + }, + DataView (obj, _typ, _options, _refStack) { + return new Token(Type.bytes, new Uint8Array(obj.buffer, obj.byteOffset, obj.byteLength)); + }, + Array (obj, _typ, options, refStack) { + if (!obj.length) { + if (options.addBreakTokens === true) { + return [ + simpleTokens.emptyArray, + new Token(Type.break) + ]; + } + return simpleTokens.emptyArray; + } + refStack = Ref.createCheck(refStack, obj); + const entries = []; + let i = 0; + for (const e of obj){ + entries[i++] = objectToTokens(e, options, refStack); + } + if (options.addBreakTokens) { + return [ + new Token(Type.array, obj.length), + entries, + new Token(Type.break) + ]; + } + return [ + new Token(Type.array, obj.length), + entries + ]; + }, + Object (obj, typ, options, refStack) { + const isMap = typ !== "Object"; + const keys = isMap ? obj.keys() : Object.keys(obj); + const length = isMap ? obj.size : keys.length; + if (!length) { + if (options.addBreakTokens === true) { + return [ + simpleTokens.emptyMap, + new Token(Type.break) + ]; + } + return simpleTokens.emptyMap; + } + refStack = Ref.createCheck(refStack, obj); + const entries = []; + let i = 0; + for (const key of keys){ + entries[i++] = [ + objectToTokens(key, options, refStack), + objectToTokens(isMap ? obj.get(key) : obj[key], options, refStack) + ]; + } + sortMapEntries(entries, options); + if (options.addBreakTokens) { + return [ + new Token(Type.map, length), + entries, + new Token(Type.break) + ]; + } + return [ + new Token(Type.map, length), + entries + ]; } - return ctx; +}; +typeEncoders.Map = typeEncoders.Object; +typeEncoders.Buffer = typeEncoders.Uint8Array; +for (const typ of "Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")){ + typeEncoders[`${typ}Array`] = typeEncoders.DataView; } -function blake2bUpdate(ctx, input) { - for(let i = 0; i < input.length; i++){ - if (ctx.c === 128) { - ctx.t += ctx.c; - blake2bCompress(ctx, false); - ctx.c = 0; +function objectToTokens(obj, options = {}, refStack) { + const typ = is(obj); + const customTypeEncoder = options && options.typeEncoders && options.typeEncoders[typ] || typeEncoders[typ]; + if (typeof customTypeEncoder === "function") { + const tokens = customTypeEncoder(obj, typ, options, refStack); + if (tokens != null) { + return tokens; } - ctx.b[ctx.c++] = input[i]; } + const typeEncoder = typeEncoders[typ]; + if (!typeEncoder) { + throw new Error(`${encodeErrPrefix} unsupported type: ${typ}`); + } + return typeEncoder(obj, typ, options, refStack); } -function blake2bFinal(ctx) { - ctx.t += ctx.c; - while(ctx.c < 128){ - ctx.b[ctx.c++] = 0; +function sortMapEntries(entries, options) { + if (options.mapSorter) { + entries.sort(options.mapSorter); } - blake2bCompress(ctx, true); - const out = new Uint8Array(ctx.outlen); - for(let i = 0; i < ctx.outlen; i++){ - out[i] = ctx.h[i >> 2] >> 8 * (i & 3); +} +function mapSorter(e1, e2) { + const keyToken1 = Array.isArray(e1[0]) ? e1[0][0] : e1[0]; + const keyToken2 = Array.isArray(e2[0]) ? e2[0][0] : e2[0]; + if (keyToken1.type !== keyToken2.type) { + return keyToken1.type.compare(keyToken2.type); } - return out; + const major = keyToken1.type.major; + const tcmp = cborEncoders[major].compareTokens(keyToken1, keyToken2); + if (tcmp === 0) { + console.warn("WARNING: complex key types used, CBOR key sorting guarantees are gone"); + } + return tcmp; } -function blake2b(input, key, outlen, salt, personal) { - outlen = outlen || 64; - input = util.normalizeInput(input); - if (salt) { - salt = util.normalizeInput(salt); +function tokensToEncoded(buf2, tokens, encoders, options) { + if (Array.isArray(tokens)) { + for (const token of tokens){ + tokensToEncoded(buf2, token, encoders, options); + } + } else { + encoders[tokens.type.major](buf2, tokens, options); } - if (personal) { - personal = util.normalizeInput(personal); +} +function encodeCustom(data, encoders, options) { + const tokens = objectToTokens(data, options); + if (!Array.isArray(tokens) && options.quickEncodeToken) { + const quickBytes = options.quickEncodeToken(tokens); + if (quickBytes) { + return quickBytes; + } + const encoder = encoders[tokens.type.major]; + if (encoder.encodedSize) { + const size = encoder.encodedSize(tokens, options); + const buf2 = new Bl(size); + encoder(buf2, tokens, options); + if (buf2.chunks.length !== 1) { + throw new Error(`Unexpected error: pre-calculated length for ${tokens} was wrong`); + } + return asU8A(buf2.chunks[0]); + } } - const ctx = blake2bInit(outlen, key, salt, personal); - blake2bUpdate(ctx, input); - return blake2bFinal(ctx); + buf.reset(); + tokensToEncoded(buf, tokens, encoders, options); + return buf.toBytes(true); } -function blake2bHex(input, key, outlen, salt, personal) { - const output = blake2b(input, key, outlen, salt, personal); - return util.toHex(output); +function encode3(data, options) { + options = Object.assign({}, defaultEncodeOptions, options); + return encodeCustom(data, cborEncoders, options); } -var blake2b_1 = { - blake2b, - blake2bHex, - blake2bInit, - blake2bUpdate, - blake2bFinal +const defaultDecodeOptions = { + strict: false, + allowIndefinite: true, + allowUndefined: true, + allowBigInt: true }; -function B2S_GET32(v2, i) { - return v2[i] ^ v2[i + 1] << 8 ^ v2[i + 2] << 16 ^ v2[i + 3] << 24; -} -function B2S_G(a, b, c, d, x, y) { - v$1[a] = v$1[a] + v$1[b] + x; - v$1[d] = ROTR32(v$1[d] ^ v$1[a], 16); - v$1[c] = v$1[c] + v$1[d]; - v$1[b] = ROTR32(v$1[b] ^ v$1[c], 12); - v$1[a] = v$1[a] + v$1[b] + y; - v$1[d] = ROTR32(v$1[d] ^ v$1[a], 8); - v$1[c] = v$1[c] + v$1[d]; - v$1[b] = ROTR32(v$1[b] ^ v$1[c], 7); +class Tokeniser { + constructor(data, options = {}){ + this._pos = 0; + this.data = data; + this.options = options; + } + pos() { + return this._pos; + } + done() { + return this._pos >= this.data.length; + } + next() { + const byt = this.data[this._pos]; + let token = quick[byt]; + if (token === void 0) { + const decoder = jump[byt]; + if (!decoder) { + throw new Error(`${decodeErrPrefix} no decoder for major type ${byt >>> 5} (byte 0x${byt.toString(16).padStart(2, "0")})`); + } + const minor = byt & 31; + token = decoder(this.data, this._pos, minor, this.options); + } + this._pos += token.encodedLength; + return token; + } } -function ROTR32(x, y) { - return x >>> y ^ x << 32 - y; +const DONE = Symbol.for("DONE"); +const BREAK = Symbol.for("BREAK"); +function tokenToArray(token, tokeniser, options) { + const arr = []; + for(let i = 0; i < token.value; i++){ + const value = tokensToObject(tokeniser, options); + if (value === BREAK) { + if (token.value === Infinity) { + break; + } + throw new Error(`${decodeErrPrefix} got unexpected break to lengthed array`); + } + if (value === DONE) { + throw new Error(`${decodeErrPrefix} found array but not enough entries (got ${i}, expected ${token.value})`); + } + arr[i] = value; + } + return arr; } -const BLAKE2S_IV = new Uint32Array([ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 -]); -const SIGMA = new Uint8Array([ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 14, - 10, - 4, - 8, - 9, - 15, - 13, - 6, - 1, - 12, - 0, - 2, - 11, - 7, - 5, - 3, - 11, - 8, - 12, - 0, - 5, - 2, - 15, - 13, - 10, - 14, - 3, - 6, - 7, - 1, - 9, - 4, - 7, - 9, - 3, - 1, - 13, - 12, - 11, - 14, - 2, - 6, - 5, - 10, - 4, - 0, - 15, - 8, - 9, - 0, - 5, - 7, - 2, - 4, - 10, - 15, - 14, - 1, - 11, - 12, - 6, - 8, - 3, - 13, - 2, - 12, - 6, - 10, - 0, - 11, - 8, - 3, - 4, - 13, - 7, - 5, - 15, - 14, - 1, - 9, - 12, - 5, - 1, - 15, - 14, - 13, - 4, - 10, - 0, - 7, - 6, - 3, - 9, - 2, - 8, - 11, - 13, - 11, - 7, - 14, - 12, - 1, - 3, - 9, - 5, - 0, - 15, - 4, - 8, - 6, - 2, - 10, - 6, - 15, - 14, - 9, - 11, - 3, - 0, - 8, - 12, - 2, - 13, - 7, - 1, - 4, - 10, - 5, - 10, - 2, - 8, - 4, - 7, - 6, - 1, - 5, - 15, - 11, - 9, - 14, - 3, - 12, - 13, - 0 -]); -const v$1 = new Uint32Array(16); -const m$1 = new Uint32Array(16); -function blake2sCompress(ctx, last) { - let i = 0; - for(i = 0; i < 8; i++){ - v$1[i] = ctx.h[i]; - v$1[i + 8] = BLAKE2S_IV[i]; +function tokenToMap(token, tokeniser, options) { + const useMaps = options.useMaps === true; + const obj = useMaps ? void 0 : {}; + const m = useMaps ? new Map() : void 0; + for(let i = 0; i < token.value; i++){ + const key = tokensToObject(tokeniser, options); + if (key === BREAK) { + if (token.value === Infinity) { + break; + } + throw new Error(`${decodeErrPrefix} got unexpected break to lengthed map`); + } + if (key === DONE) { + throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no key], expected ${token.value})`); + } + if (useMaps !== true && typeof key !== "string") { + throw new Error(`${decodeErrPrefix} non-string keys not supported (got ${typeof key})`); + } + if (options.rejectDuplicateMapKeys === true) { + if (useMaps && m.has(key) || !useMaps && key in obj) { + throw new Error(`${decodeErrPrefix} found repeat map key "${key}"`); + } + } + const value = tokensToObject(tokeniser, options); + if (value === DONE) { + throw new Error(`${decodeErrPrefix} found map but not enough entries (got ${i} [no value], expected ${token.value})`); + } + if (useMaps) { + m.set(key, value); + } else { + obj[key] = value; + } } - v$1[12] ^= ctx.t; - v$1[13] ^= ctx.t / 4294967296; - if (last) { - v$1[14] = ~v$1[14]; + return useMaps ? m : obj; +} +function tokensToObject(tokeniser, options) { + if (tokeniser.done()) { + return DONE; } - for(i = 0; i < 16; i++){ - m$1[i] = B2S_GET32(ctx.b, 4 * i); + const token = tokeniser.next(); + if (token.type === Type.break) { + return BREAK; } - for(i = 0; i < 10; i++){ - B2S_G(0, 4, 8, 12, m$1[SIGMA[i * 16 + 0]], m$1[SIGMA[i * 16 + 1]]); - B2S_G(1, 5, 9, 13, m$1[SIGMA[i * 16 + 2]], m$1[SIGMA[i * 16 + 3]]); - B2S_G(2, 6, 10, 14, m$1[SIGMA[i * 16 + 4]], m$1[SIGMA[i * 16 + 5]]); - B2S_G(3, 7, 11, 15, m$1[SIGMA[i * 16 + 6]], m$1[SIGMA[i * 16 + 7]]); - B2S_G(0, 5, 10, 15, m$1[SIGMA[i * 16 + 8]], m$1[SIGMA[i * 16 + 9]]); - B2S_G(1, 6, 11, 12, m$1[SIGMA[i * 16 + 10]], m$1[SIGMA[i * 16 + 11]]); - B2S_G(2, 7, 8, 13, m$1[SIGMA[i * 16 + 12]], m$1[SIGMA[i * 16 + 13]]); - B2S_G(3, 4, 9, 14, m$1[SIGMA[i * 16 + 14]], m$1[SIGMA[i * 16 + 15]]); + if (token.type.terminal) { + return token.value; } - for(i = 0; i < 8; i++){ - ctx.h[i] ^= v$1[i] ^ v$1[i + 8]; + if (token.type === Type.array) { + return tokenToArray(token, tokeniser, options); + } + if (token.type === Type.map) { + return tokenToMap(token, tokeniser, options); + } + if (token.type === Type.tag) { + if (options.tags && typeof options.tags[token.value] === "function") { + const tagged = tokensToObject(tokeniser, options); + return options.tags[token.value](tagged); + } + throw new Error(`${decodeErrPrefix} tag not supported (${token.value})`); } + throw new Error("unsupported"); } -function blake2sInit(outlen, key) { - if (!(outlen > 0 && outlen <= 32)) { - throw new Error("Incorrect output length, should be in [1, 32]"); +function decodeFirst(data, options) { + if (!(data instanceof Uint8Array)) { + throw new Error(`${decodeErrPrefix} data to decode must be a Uint8Array`); } - const keylen = key ? key.length : 0; - if (key && !(keylen > 0 && keylen <= 32)) { - throw new Error("Incorrect key length, should be in [1, 32]"); + options = Object.assign({}, defaultDecodeOptions, options); + const tokeniser = options.tokenizer || new Tokeniser(data, options); + const decoded = tokensToObject(tokeniser, options); + if (decoded === DONE) { + throw new Error(`${decodeErrPrefix} did not find any content to decode`); } - const ctx = { - h: new Uint32Array(BLAKE2S_IV), - b: new Uint8Array(64), - c: 0, - t: 0, - outlen - }; - ctx.h[0] ^= 16842752 ^ keylen << 8 ^ outlen; - if (keylen > 0) { - blake2sUpdate(ctx, key); - ctx.c = 64; + if (decoded === BREAK) { + throw new Error(`${decodeErrPrefix} got unexpected break`); } - return ctx; + return [ + decoded, + data.subarray(tokeniser.pos()) + ]; } -function blake2sUpdate(ctx, input) { - for(let i = 0; i < input.length; i++){ - if (ctx.c === 64) { - ctx.t += ctx.c; - blake2sCompress(ctx, false); - ctx.c = 0; - } - ctx.b[ctx.c++] = input[i]; +function decode4(data, options) { + const [decoded, remainder] = decodeFirst(data, options); + if (remainder.length > 0) { + throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`); } + return decoded; } -function blake2sFinal(ctx) { - ctx.t += ctx.c; - while(ctx.c < 64){ - ctx.b[ctx.c++] = 0; +const empty = new Uint8Array(0); +function toHex2(d) { + return d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); +} +function fromHex(hex) { + const hexes = hex.match(/../g); + return hexes != null ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty; +} +function equals(aa, bb) { + if (aa === bb) return true; + if (aa.byteLength !== bb.byteLength) { + return false; } - blake2sCompress(ctx, true); - const out = new Uint8Array(ctx.outlen); - for(let i = 0; i < ctx.outlen; i++){ - out[i] = ctx.h[i >> 2] >> 8 * (i & 3) & 255; + for(let ii = 0; ii < aa.byteLength; ii++){ + if (aa[ii] !== bb[ii]) { + return false; + } } - return out; + return true; } -function blake2s(input, key, outlen) { - outlen = outlen || 32; - input = util.normalizeInput(input); - const ctx = blake2sInit(outlen, key); - blake2sUpdate(ctx, input); - return blake2sFinal(ctx); +function coerce(o) { + if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") return o; + if (o instanceof ArrayBuffer) return new Uint8Array(o); + if (ArrayBuffer.isView(o)) { + return new Uint8Array(o.buffer, o.byteOffset, o.byteLength); + } + throw new Error("Unknown type, must be binary type"); } -function blake2sHex(input, key, outlen) { - const output = blake2s(input, key, outlen); - return util.toHex(output); +function isBinary(o) { + return o instanceof ArrayBuffer || ArrayBuffer.isView(o); } -var blake2s_1 = { - blake2s, - blake2sHex, - blake2sInit, - blake2sUpdate, - blake2sFinal -}; -var blakejs = { - blake2b: blake2b_1.blake2b, - blake2bHex: blake2b_1.blake2bHex, - blake2bInit: blake2b_1.blake2bInit, - blake2bUpdate: blake2b_1.blake2bUpdate, - blake2bFinal: blake2b_1.blake2bFinal, - blake2s: blake2s_1.blake2s, - blake2sHex: blake2s_1.blake2sHex, - blake2sInit: blake2s_1.blake2sInit, - blake2sUpdate: blake2s_1.blake2sUpdate, - blake2sFinal: blake2s_1.blake2sFinal +function fromString1(str) { + return new TextEncoder().encode(str); +} +function toString1(b) { + return new TextDecoder().decode(b); +} +Object.freeze({ + __proto__: null, + empty, + toHex: toHex2, + fromHex, + equals, + coerce, + isBinary, + fromString: fromString1, + toString: toString1 +}); +var __defProp = Object.defineProperty; +var __publicField = (obj, key, value)=>{ + if (typeof key !== "symbol") key += ""; + if (key in obj) return __defProp(obj, key, { + enumerable: true, + configurable: true, + writable: true, + value + }); + return obj[key] = value; }; -blakejs.blake2b; -function base2(ALPHABET, name) { +function base1(ALPHABET, name) { if (ALPHABET.length >= 255) { throw new TypeError("Alphabet too long"); } @@ -5828,10 +27811,13 @@ function base2(ALPHABET, name) { decode: decode2 }; } -var src2 = base2; -var _brrp__multiformats_scope_baseX2 = src2; -class Encoder2 { +var src = base1; +var _brrp__multiformats_scope_baseX = src; +class Encoder { constructor(name, prefix, baseEncode){ + __publicField(this, "name"); + __publicField(this, "prefix"); + __publicField(this, "baseEncode"); this.name = name; this.prefix = prefix; this.baseEncode = baseEncode; @@ -5844,8 +27830,12 @@ class Encoder2 { } } } -class Decoder2 { +class Decoder { constructor(name, prefix, baseDecode){ + __publicField(this, "name"); + __publicField(this, "prefix"); + __publicField(this, "baseDecode"); + __publicField(this, "prefixCodePoint"); this.name = name; this.prefix = prefix; if (prefix.codePointAt(0) === void 0) { @@ -5865,42 +27855,52 @@ class Decoder2 { } } or(decoder) { - return or2(this, decoder); + return or(this, decoder); } } -class ComposedDecoder2 { +class ComposedDecoder { constructor(decoders){ + __publicField(this, "decoders"); this.decoders = decoders; } or(decoder) { - return or2(this, decoder); + return or(this, decoder); } decode(input) { const prefix = input[0]; const decoder = this.decoders[prefix]; - if (decoder) { + if (decoder != null) { return decoder.decode(input); } else { throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); } } } -const or2 = (left, right)=>new ComposedDecoder2({ - ...left.decoders || { +function or(left, right) { + var _a, _b; + return new ComposedDecoder({ + ...(_a = left.decoders) != null ? _a : { [left.prefix]: left }, - ...right.decoders || { + ...(_b = right.decoders) != null ? _b : { [right.prefix]: right } }); -class Codec2 { +} +class Codec { constructor(name, prefix, baseEncode, baseDecode){ + __publicField(this, "name"); + __publicField(this, "prefix"); + __publicField(this, "baseEncode"); + __publicField(this, "baseDecode"); + __publicField(this, "encoder"); + __publicField(this, "decoder"); this.name = name; this.prefix = prefix; this.baseEncode = baseEncode; this.baseDecode = baseDecode; - this.encoder = new Encoder2(name, prefix, baseEncode); - this.decoder = new Decoder2(name, prefix, baseDecode); + this.encoder = new Encoder(name, prefix, baseEncode); + this.decoder = new Decoder(name, prefix, baseDecode); } encode(input) { return this.encoder.encode(input); @@ -5909,17 +27909,19 @@ class Codec2 { return this.decoder.decode(input); } } -const from4 = ({ name, prefix, encode: encode2, decode: decode2 })=>new Codec2(name, prefix, encode2, decode2); -const baseX2 = ({ prefix, name, alphabet })=>{ - const { encode: encode2, decode: decode2 } = _brrp__multiformats_scope_baseX2(alphabet, name); - return from4({ +function from({ name, prefix, encode: encode2, decode: decode2 }) { + return new Codec(name, prefix, encode2, decode2); +} +function baseX({ name, prefix, alphabet }) { + const { encode: encode2, decode: decode2 } = _brrp__multiformats_scope_baseX(alphabet, name); + return from({ prefix, name, encode: encode2, - decode: (text)=>coerce1(decode2(text)) + decode: (text)=>coerce(decode2(text)) }); -}; -const decode9 = (string, alphabet, bitsPerChar, name)=>{ +} +function decode5(string, alphabet, bitsPerChar, name) { const codes = {}; for(let i = 0; i < alphabet.length; ++i){ codes[alphabet[i]] = i; @@ -5944,12 +27946,12 @@ const decode9 = (string, alphabet, bitsPerChar, name)=>{ out[written++] = 255 & buffer >> bits; } } - if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { + if (bits >= bitsPerChar || (255 & buffer << 8 - bits) !== 0) { throw new SyntaxError("Unexpected end of data"); } return out; -}; -const encode8 = (data, alphabet, bitsPerChar)=>{ +} +function encode4(data, alphabet, bitsPerChar) { const pad = alphabet[alphabet.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; @@ -5963,129 +27965,292 @@ const encode8 = (data, alphabet, bitsPerChar)=>{ out += alphabet[mask & buffer >> bits]; } } - if (bits) { + if (bits !== 0) { out += alphabet[mask & buffer << bitsPerChar - bits]; } if (pad) { - while(out.length * bitsPerChar & 7){ + while((out.length * bitsPerChar & 7) !== 0){ out += "="; } } return out; -}; -const rfc46482 = ({ name, prefix, bitsPerChar, alphabet })=>{ - return from4({ +} +function rfc4648({ name, prefix, bitsPerChar, alphabet }) { + return from({ prefix, name, encode (input) { - return encode8(input, alphabet, bitsPerChar); + return encode4(input, alphabet, bitsPerChar); }, decode (input) { - return decode9(input, alphabet, bitsPerChar, name); + return decode5(input, alphabet, bitsPerChar, name); } }); -}; -const base58btc2 = baseX2({ - name: "base58btc", - prefix: "z", - alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" -}); -const base58flickr2 = baseX2({ - name: "base58flickr", - prefix: "Z", - alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" -}); -var base58 = Object.freeze({ - __proto__: null, - base58btc: base58btc2, - base58flickr: base58flickr2 -}); -const base322 = rfc46482({ +} +const base32 = rfc4648({ prefix: "b", name: "base32", alphabet: "abcdefghijklmnopqrstuvwxyz234567", bitsPerChar: 5 }); -const base32upper2 = rfc46482({ +const base32upper = rfc4648({ prefix: "B", name: "base32upper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", bitsPerChar: 5 }); -const base32pad2 = rfc46482({ +const base32pad = rfc4648({ prefix: "c", name: "base32pad", alphabet: "abcdefghijklmnopqrstuvwxyz234567=", bitsPerChar: 5 }); -const base32padupper2 = rfc46482({ +const base32padupper = rfc4648({ prefix: "C", name: "base32padupper", alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", bitsPerChar: 5 }); -const base32hex2 = rfc46482({ +const base32hex = rfc4648({ prefix: "v", name: "base32hex", alphabet: "0123456789abcdefghijklmnopqrstuv", bitsPerChar: 5 }); -const base32hexupper2 = rfc46482({ +const base32hexupper = rfc4648({ prefix: "V", name: "base32hexupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", bitsPerChar: 5 }); -const base32hexpad2 = rfc46482({ +const base32hexpad = rfc4648({ prefix: "t", name: "base32hexpad", alphabet: "0123456789abcdefghijklmnopqrstuv=", bitsPerChar: 5 }); -const base32hexpadupper2 = rfc46482({ +const base32hexpadupper = rfc4648({ prefix: "T", name: "base32hexpadupper", alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", bitsPerChar: 5 }); -const base32z2 = rfc46482({ +const base32z = rfc4648({ prefix: "h", name: "base32z", alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", bitsPerChar: 5 }); -var base32$1 = Object.freeze({ +Object.freeze({ __proto__: null, - base32: base322, - base32upper: base32upper2, - base32pad: base32pad2, - base32padupper: base32padupper2, - base32hex: base32hex2, - base32hexupper: base32hexupper2, - base32hexpad: base32hexpad2, - base32hexpadupper: base32hexpadupper2, - base32z: base32z2 + base32, + base32upper, + base32pad, + base32padupper, + base32hex, + base32hexupper, + base32hexpad, + base32hexpadupper, + base32z }); -class CID2 { - constructor(version2, code, multihash, bytes){ +const base58btc = baseX({ + name: "base58btc", + prefix: "z", + alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" +}); +const base58flickr = baseX({ + name: "base58flickr", + prefix: "Z", + alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" +}); +Object.freeze({ + __proto__: null, + base58btc, + base58flickr +}); +var __defProp1 = Object.defineProperty; +var __publicField1 = (obj, key, value)=>{ + if (typeof key !== "symbol") key += ""; + if (key in obj) return __defProp1(obj, key, { + enumerable: true, + configurable: true, + writable: true, + value + }); + return obj[key] = value; +}; +var encode_1 = encode5; +var MSB = 128, REST1 = 127, MSBALL = ~REST1, INT = Math.pow(2, 31); +function encode5(num, out, offset) { + out = out || []; + offset = offset || 0; + var oldOffset = offset; + while(num >= INT){ + out[offset++] = num & 255 | MSB; + num /= 128; + } + while(num & MSBALL){ + out[offset++] = num & 255 | MSB; + num >>>= 7; + } + out[offset] = num | 0; + encode5.bytes = offset - oldOffset + 1; + return out; +} +var decode6 = read; +var MSB$1 = 128, REST$1 = 127; +function read(buf, offset) { + var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; + do { + if (counter >= l) { + read.bytes = 0; + throw new RangeError("Could not decode varint"); + } + b = buf[counter++]; + res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift); + shift += 7; + }while (b >= MSB$1) + read.bytes = counter - offset; + return res; +} +var N1 = Math.pow(2, 7); +var N2 = Math.pow(2, 14); +var N3 = Math.pow(2, 21); +var N4 = Math.pow(2, 28); +var N5 = Math.pow(2, 35); +var N6 = Math.pow(2, 42); +var N7 = Math.pow(2, 49); +var N8 = Math.pow(2, 56); +var N9 = Math.pow(2, 63); +var length = function(value) { + return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10; +}; +var varint = { + encode: encode_1, + decode: decode6, + encodingLength: length +}; +var _brrp_varint = varint; +function decode$1(data, offset = 0) { + const code = _brrp_varint.decode(data, offset); + return [ + code, + _brrp_varint.decode.bytes + ]; +} +function encodeTo(__int, target, offset = 0) { + _brrp_varint.encode(__int, target, offset); + return target; +} +function encodingLength(__int) { + return _brrp_varint.encodingLength(__int); +} +Object.freeze({ + __proto__: null, + decode: decode$1, + encodeTo, + encodingLength +}); +function create(code, digest2) { + const size = digest2.byteLength; + const sizeOffset = encodingLength(code); + const digestOffset = sizeOffset + encodingLength(size); + const bytes = new Uint8Array(digestOffset + size); + encodeTo(code, bytes, 0); + encodeTo(size, bytes, sizeOffset); + bytes.set(digest2, digestOffset); + return new Digest(code, size, digest2, bytes); +} +function decode$2(multihash) { + const bytes = coerce(multihash); + const [code, sizeOffset] = decode$1(bytes); + const [size, digestOffset] = decode$1(bytes.subarray(sizeOffset)); + const digest2 = bytes.subarray(sizeOffset + digestOffset); + if (digest2.byteLength !== size) { + throw new Error("Incorrect length"); + } + return new Digest(code, size, digest2, bytes); +} +function equals1(a, b) { + if (a === b) { + return true; + } else { + const data = b; + return a.code === data.code && a.size === data.size && data.bytes instanceof Uint8Array && equals(a.bytes, data.bytes); + } +} +class Digest { + constructor(code, size, digest2, bytes){ + __publicField1(this, "code"); + __publicField1(this, "size"); + __publicField1(this, "digest"); + __publicField1(this, "bytes"); + this.code = code; + this.size = size; + this.digest = digest2; + this.bytes = bytes; + } +} +Object.freeze({ + __proto__: null, + create, + decode: decode$2, + equals: equals1, + Digest +}); +var __defProp2 = Object.defineProperty; +var __publicField2 = (obj, key, value)=>{ + if (typeof key !== "symbol") key += ""; + if (key in obj) return __defProp2(obj, key, { + enumerable: true, + configurable: true, + writable: true, + value + }); + return obj[key] = value; +}; +var _a; +function format(link, base) { + const { bytes, version } = link; + switch(version){ + case 0: + return toStringV0(bytes, baseCache(link), base != null ? base : base58btc.encoder); + default: + return toStringV1(bytes, baseCache(link), base != null ? base : base32.encoder); + } +} +const cache = new WeakMap(); +function baseCache(cid) { + const baseCache2 = cache.get(cid); + if (baseCache2 == null) { + const baseCache3 = new Map(); + cache.set(cid, baseCache3); + return baseCache3; + } + return baseCache2; +} +class CID { + constructor(version, code, multihash, bytes){ + __publicField2(this, "code"); + __publicField2(this, "version"); + __publicField2(this, "multihash"); + __publicField2(this, "bytes"); + __publicField2(this, "/"); + __publicField2(this, _a, "CID"); this.code = code; - this.version = version2; + this.version = version; this.multihash = multihash; this.bytes = bytes; - this.byteOffset = bytes.byteOffset; - this.byteLength = bytes.byteLength; - this.asCID = this; - this._baseCache = new Map(); - Object.defineProperties(this, { - byteOffset: hidden1, - byteLength: hidden1, - code: readonly1, - version: readonly1, - multihash: readonly1, - bytes: readonly1, - _baseCache: hidden1, - asCID: hidden1 - }); + this["/"] = bytes; + } + get asCID() { + return this; + } + get byteOffset() { + return this.bytes.byteOffset; + } + get byteLength() { + return this.bytes.byteLength; } toV0() { switch(this.version){ @@ -6093,16 +28258,20 @@ class CID2 { { return this; } - default: + case 1: { const { code, multihash } = this; - if (code !== DAG_PB_CODE2) { + if (code !== DAG_PB_CODE) { throw new Error("Cannot convert a non dag-pb CID to CIDv0"); } - if (multihash.code !== SHA_256_CODE2) { + if (multihash.code !== SHA_256_CODE) { throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); } - return CID2.createV0(multihash); + return CID.createV0(multihash); + } + default: + { + throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); } } } @@ -6111,8 +28280,8 @@ class CID2 { case 0: { const { code, digest: digest$1 } = this.multihash; - const multihash = create1(code, digest$1); - return CID2.createV1(this.code, multihash); + const multihash = create(code, digest$1); + return CID.createV1(this.code, multihash); } case 1: { @@ -6120,85 +28289,69 @@ class CID2 { } default: { - throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); + throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`); } } } equals(other) { - return other && this.code === other.code && this.version === other.version && equals3(this.multihash, other.multihash); + return CID.equals(this, other); + } + static equals(self1, other) { + const unknown = other; + return unknown != null && self1.code === unknown.code && self1.version === unknown.version && equals1(self1.multihash, unknown.multihash); } toString(base) { - const { bytes, version: version2, _baseCache } = this; - switch(version2){ - case 0: - return toStringV02(bytes, _baseCache, base || base58btc2.encoder); - default: - return toStringV12(bytes, _baseCache, base || base322.encoder); - } + return format(this, base); } toJSON() { return { - code: this.code, - version: this.version, - hash: this.multihash.bytes + "/": format(this) }; } - get [Symbol.toStringTag]() { - return "CID"; - } - [Symbol.for("nodejs.util.inspect.custom")]() { - return "CID(" + this.toString() + ")"; - } - static isCID(value) { - deprecate1(/^0\.0/, IS_CID_DEPRECATION1); - return !!(value && (value[cidSymbol2] || value.asCID === value)); - } - get toBaseEncodedString() { - throw new Error("Deprecated, use .toString()"); - } - get codec() { - throw new Error('"codec" property is deprecated, use integer "code" property instead'); - } - get buffer() { - throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead"); - } - get multibaseName() { - throw new Error('"multibaseName" property is deprecated'); + link() { + return this; } - get prefix() { - throw new Error('"prefix" property is deprecated'); + [(_a = Symbol.toStringTag, Symbol.for("nodejs.util.inspect.custom"))]() { + return `CID(${this.toString()})`; } - static asCID(value) { - if (value instanceof CID2) { + static asCID(input) { + if (input == null) { + return null; + } + const value = input; + if (value instanceof CID) { return value; - } else if (value != null && value.asCID === value) { - const { version: version2, code, multihash, bytes } = value; - return new CID2(version2, code, multihash, bytes || encodeCID2(version2, code, multihash.bytes)); - } else if (value != null && value[cidSymbol2] === true) { - const { version: version2, multihash, code } = value; - const digest$1 = decode$21(multihash); - return CID2.create(version2, code, digest$1); + } else if (value["/"] != null && value["/"] === value.bytes || value.asCID === value) { + const { version, code, multihash, bytes } = value; + return new CID(version, code, multihash, bytes != null ? bytes : encodeCID(version, code, multihash.bytes)); + } else if (value[cidSymbol] === true) { + const { version, multihash, code } = value; + const digest$1 = decode$2(multihash); + return CID.create(version, code, digest$1); } else { return null; } } - static create(version2, code, digest) { + static create(version, code, digest) { if (typeof code !== "number") { throw new Error("String codecs are no longer supported"); } - switch(version2){ + if (!(digest.bytes instanceof Uint8Array)) { + throw new Error("Invalid digest"); + } + switch(version){ case 0: { - if (code !== DAG_PB_CODE2) { - throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE2}) block encoding`); + if (code !== DAG_PB_CODE) { + throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`); } else { - return new CID2(version2, code, digest, digest.bytes); + return new CID(version, code, digest, digest.bytes); } } case 1: { - const bytes = encodeCID2(version2, code, digest.bytes); - return new CID2(version2, code, digest, bytes); + const bytes = encodeCID(version, code, digest.bytes); + return new CID(version, code, digest, bytes); } default: { @@ -6207,28 +28360,28 @@ class CID2 { } } static createV0(digest) { - return CID2.create(0, DAG_PB_CODE2, digest); + return CID.create(0, DAG_PB_CODE, digest); } static createV1(code, digest) { - return CID2.create(1, code, digest); + return CID.create(1, code, digest); } static decode(bytes) { - const [cid, remainder] = CID2.decodeFirst(bytes); - if (remainder.length) { + const [cid, remainder] = CID.decodeFirst(bytes); + if (remainder.length !== 0) { throw new Error("Incorrect length"); } return cid; } static decodeFirst(bytes) { - const specs = CID2.inspectBytes(bytes); + const specs = CID.inspectBytes(bytes); const prefixSize = specs.size - specs.multihashSize; - const multihashBytes = coerce1(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); + const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); if (multihashBytes.byteLength !== specs.multihashSize) { throw new Error("Incorrect length"); } const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); - const digest$1 = new Digest1(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); - const cid = specs.version === 0 ? CID2.createV0(digest$1) : CID2.createV1(specs.codec, digest$1); + const digest$1 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); + const cid = specs.version === 0 ? CID.createV0(digest$1) : CID.createV1(specs.codec, digest$1); return [ cid, bytes.subarray(specs.size) @@ -6237,20 +28390,20 @@ class CID2 { static inspectBytes(initialBytes) { let offset = 0; const next = ()=>{ - const [i, length] = decode$11(initialBytes.subarray(offset)); + const [i, length] = decode$1(initialBytes.subarray(offset)); offset += length; return i; }; - let version2 = next(); - let codec = DAG_PB_CODE2; - if (version2 === 18) { - version2 = 0; + let version = next(); + let codec = DAG_PB_CODE; + if (version === 18) { + version = 0; offset = 0; - } else if (version2 === 1) { + } else { codec = next(); } - if (version2 !== 0 && version2 !== 1) { - throw new RangeError(`Invalid CID version ${version2}`); + if (version !== 0 && version !== 1) { + throw new RangeError(`Invalid CID version ${version}`); } const prefixSize = offset; const multihashCode = next(); @@ -6258,7 +28411,7 @@ class CID2 { const size = offset + digestSize; const multihashSize = size - prefixSize; return { - version: version2, + version, codec, multihashCode, digestSize, @@ -6267,35 +28420,38 @@ class CID2 { }; } static parse(source, base) { - const [prefix, bytes] = parseCIDtoBytes2(source, base); - const cid = CID2.decode(bytes); - cid._baseCache.set(prefix, source); + const [prefix, bytes] = parseCIDtoBytes(source, base); + const cid = CID.decode(bytes); + if (cid.version === 0 && source[0] !== "Q") { + throw Error("Version 0 CID string must not include multibase prefix"); + } + baseCache(cid).set(prefix, source); return cid; } } -const parseCIDtoBytes2 = (source, base)=>{ +function parseCIDtoBytes(source, base) { switch(source[0]){ case "Q": { - const decoder = base || base58btc2; + const decoder = base != null ? base : base58btc; return [ - base58btc2.prefix, - decoder.decode(`${base58btc2.prefix}${source}`) + base58btc.prefix, + decoder.decode(`${base58btc.prefix}${source}`) ]; } - case base58btc2.prefix: + case base58btc.prefix: { - const decoder = base || base58btc2; + const decoder = base != null ? base : base58btc; return [ - base58btc2.prefix, + base58btc.prefix, decoder.decode(source) ]; } - case base322.prefix: + case base32.prefix: { - const decoder = base || base322; + const decoder = base != null ? base : base32; return [ - base322.prefix, + base32.prefix, decoder.decode(source) ]; } @@ -6310,1609 +28466,4582 @@ const parseCIDtoBytes2 = (source, base)=>{ ]; } } -}; -const toStringV02 = (bytes, cache, base)=>{ +} +function toStringV0(bytes, cache2, base) { const { prefix } = base; - if (prefix !== base58btc2.prefix) { + if (prefix !== base58btc.prefix) { throw Error(`Cannot string encode V0 in ${base.name} encoding`); } - const cid = cache.get(prefix); + const cid = cache2.get(prefix); if (cid == null) { const cid2 = base.encode(bytes).slice(1); - cache.set(prefix, cid2); - return cid2; - } else { - return cid; - } -}; -const toStringV12 = (bytes, cache, base)=>{ - const { prefix } = base; - const cid = cache.get(prefix); - if (cid == null) { - const cid2 = base.encode(bytes); - cache.set(prefix, cid2); + cache2.set(prefix, cid2); return cid2; } else { return cid; } -}; -const DAG_PB_CODE2 = 112; -const SHA_256_CODE2 = 18; -const encodeCID2 = (version2, code, multihash)=>{ - const codeOffset = encodingLength1(version2); - const hashOffset = codeOffset + encodingLength1(code); - const bytes = new Uint8Array(hashOffset + multihash.byteLength); - encodeTo1(version2, bytes, 0); - encodeTo1(code, bytes, codeOffset); - bytes.set(multihash, hashOffset); - return bytes; -}; -const cidSymbol2 = Symbol.for("@ipld/js-cid/CID"); -const readonly1 = { - writable: false, - configurable: false, - enumerable: true -}; -const hidden1 = { - writable: false, - enumerable: false, - configurable: false -}; -const version1 = "0.0.0-dev"; -const deprecate1 = (range, message)=>{ - if (range.test(version1)) { - console.warn(message); - } else { - throw new Error(message); - } -}; -const IS_CID_DEPRECATION1 = `CID.isCID(v) is deprecated and will be removed in the next major release. -Following code pattern: - -if (CID.isCID(value)) { - doSomethingWithCID(value) -} - -Is replaced with: - -const cid = CID.asCID(value) -if (cid) { - // Make sure to use cid instead of value - doSomethingWithCID(cid) } -`; -const { blake2b: blake2b1 } = blakejs; -const blake2b8 = from1({ - name: "blake2b-8", - code: 45569, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 1)) -}); -const blake2b16 = from1({ - name: "blake2b-16", - code: 45570, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 2)) -}); -const blake2b24 = from1({ - name: "blake2b-24", - code: 45571, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 3)) -}); -const blake2b32 = from1({ - name: "blake2b-32", - code: 45572, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 4)) -}); -const blake2b40 = from1({ - name: "blake2b-40", - code: 45573, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 5)) -}); -const blake2b48 = from1({ - name: "blake2b-48", - code: 45574, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 6)) -}); -const blake2b56 = from1({ - name: "blake2b-56", - code: 45575, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 7)) -}); -const blake2b64 = from1({ - name: "blake2b-64", - code: 45576, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 8)) -}); -const blake2b72 = from1({ - name: "blake2b-72", - code: 45577, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 9)) -}); -const blake2b80 = from1({ - name: "blake2b-80", - code: 45578, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 10)) -}); -const blake2b88 = from1({ - name: "blake2b-88", - code: 45579, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 11)) -}); -const blake2b96 = from1({ - name: "blake2b-96", - code: 45580, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 12)) -}); -const blake2b104 = from1({ - name: "blake2b-104", - code: 45581, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 13)) -}); -const blake2b112 = from1({ - name: "blake2b-112", - code: 45582, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 14)) -}); -const blake2b120 = from1({ - name: "blake2b-120", - code: 45583, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 15)) -}); -const blake2b128 = from1({ - name: "blake2b-128", - code: 45584, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 16)) -}); -const blake2b136 = from1({ - name: "blake2b-136", - code: 45585, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 17)) -}); -const blake2b144 = from1({ - name: "blake2b-144", - code: 45586, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 18)) -}); -const blake2b152 = from1({ - name: "blake2b-152", - code: 45587, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 19)) -}); -const blake2b160 = from1({ - name: "blake2b-160", - code: 45588, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 20)) -}); -const blake2b168 = from1({ - name: "blake2b-168", - code: 45589, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 21)) -}); -const blake2b176 = from1({ - name: "blake2b-176", - code: 45590, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 22)) -}); -const blake2b184 = from1({ - name: "blake2b-184", - code: 45591, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 23)) -}); -const blake2b192 = from1({ - name: "blake2b-192", - code: 45592, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 24)) -}); -const blake2b200 = from1({ - name: "blake2b-200", - code: 45593, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 25)) -}); -const blake2b208 = from1({ - name: "blake2b-208", - code: 45594, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 26)) -}); -const blake2b216 = from1({ - name: "blake2b-216", - code: 45595, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 27)) -}); -const blake2b224 = from1({ - name: "blake2b-224", - code: 45596, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 28)) -}); -const blake2b232 = from1({ - name: "blake2b-232", - code: 45597, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 29)) -}); -const blake2b240 = from1({ - name: "blake2b-240", - code: 45598, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 30)) -}); -const blake2b248 = from1({ - name: "blake2b-248", - code: 45599, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 31)) -}); -const blake2b256 = from1({ - name: "blake2b-256", - code: 45600, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 32)) -}); -const blake2b264 = from1({ - name: "blake2b-264", - code: 45601, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 33)) -}); -const blake2b272 = from1({ - name: "blake2b-272", - code: 45602, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 34)) -}); -const blake2b280 = from1({ - name: "blake2b-280", - code: 45603, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 35)) -}); -const blake2b288 = from1({ - name: "blake2b-288", - code: 45604, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 36)) -}); -const blake2b296 = from1({ - name: "blake2b-296", - code: 45605, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 37)) -}); -const blake2b304 = from1({ - name: "blake2b-304", - code: 45606, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 38)) -}); -const blake2b312 = from1({ - name: "blake2b-312", - code: 45607, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 39)) -}); -const blake2b320 = from1({ - name: "blake2b-320", - code: 45608, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 40)) -}); -const blake2b328 = from1({ - name: "blake2b-328", - code: 45609, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 41)) -}); -const blake2b336 = from1({ - name: "blake2b-336", - code: 45610, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 42)) -}); -const blake2b344 = from1({ - name: "blake2b-344", - code: 45611, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 43)) -}); -const blake2b352 = from1({ - name: "blake2b-352", - code: 45612, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 44)) -}); -const blake2b360 = from1({ - name: "blake2b-360", - code: 45613, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 45)) -}); -const blake2b368 = from1({ - name: "blake2b-368", - code: 45614, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 46)) -}); -const blake2b376 = from1({ - name: "blake2b-376", - code: 45615, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 47)) -}); -const blake2b384 = from1({ - name: "blake2b-384", - code: 45616, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 48)) -}); -const blake2b392 = from1({ - name: "blake2b-392", - code: 45617, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 49)) +function toStringV1(bytes, cache2, base) { + const { prefix } = base; + const cid = cache2.get(prefix); + if (cid == null) { + const cid2 = base.encode(bytes); + cache2.set(prefix, cid2); + return cid2; + } else { + return cid; + } +} +const DAG_PB_CODE = 112; +const SHA_256_CODE = 18; +function encodeCID(version, code, multihash) { + const codeOffset = encodingLength(version); + const hashOffset = codeOffset + encodingLength(code); + const bytes = new Uint8Array(hashOffset + multihash.byteLength); + encodeTo(version, bytes, 0); + encodeTo(code, bytes, codeOffset); + bytes.set(multihash, hashOffset); + return bytes; +} +const cidSymbol = Symbol.for("@ipld/js-cid/CID"); +const CID_CBOR_TAG = 42; +function toByteView(buf) { + if (buf instanceof ArrayBuffer) { + return new Uint8Array(buf, 0, buf.byteLength); + } + return buf; +} +function cidEncoder(obj) { + if (obj.asCID !== obj && obj["/"] !== obj.bytes) { + return null; + } + const cid2 = CID.asCID(obj); + if (!cid2) { + return null; + } + const bytes = new Uint8Array(cid2.bytes.byteLength + 1); + bytes.set(cid2.bytes, 1); + return [ + new Token(Type.tag, 42), + new Token(Type.bytes, bytes) + ]; +} +function undefinedEncoder() { + throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded"); +} +function numberEncoder(num) { + if (Number.isNaN(num)) { + throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded"); + } + if (num === Infinity || num === -Infinity) { + throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded"); + } + return null; +} +const _encodeOptions = { + float64: true, + typeEncoders: { + Object: cidEncoder, + undefined: undefinedEncoder, + number: numberEncoder + } +}; +({ + ..._encodeOptions, + typeEncoders: { + ..._encodeOptions.typeEncoders + } }); -const blake2b400 = from1({ - name: "blake2b-400", - code: 45618, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 50)) +function cidDecoder(bytes) { + if (bytes[0] !== 0) { + throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00"); + } + return CID.decode(bytes.subarray(1)); +} +const _decodeOptions = { + allowIndefinite: false, + coerceUndefinedToNull: true, + allowNaN: false, + allowInfinity: false, + allowBigInt: true, + strict: true, + useMaps: false, + rejectDuplicateMapKeys: true, + tags: [] +}; +_decodeOptions.tags[CID_CBOR_TAG] = cidDecoder; +({ + ..._decodeOptions, + tags: _decodeOptions.tags.slice() }); -const blake2b408 = from1({ - name: "blake2b-408", - code: 45619, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 51)) +const encode6 = (node)=>encode3(node, _encodeOptions); +const decode7 = (data)=>decode4(toByteView(data), _decodeOptions); +var encode_11 = encode7; +var MSB1 = 128, REST2 = 127, MSBALL1 = ~REST2, INT1 = Math.pow(2, 31); +function encode7(num, out, offset) { + if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) { + encode7.bytes = 0; + throw new RangeError("Could not encode varint"); + } + out = out || []; + offset = offset || 0; + var oldOffset = offset; + while(num >= INT1){ + out[offset++] = num & 255 | MSB1; + num /= 128; + } + while(num & MSBALL1){ + out[offset++] = num & 255 | MSB1; + num >>>= 7; + } + out[offset] = num | 0; + encode7.bytes = offset - oldOffset + 1; + return out; +} +var decode8 = read1; +var MSB$11 = 128, REST$11 = 127; +function read1(buf, offset) { + var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; + do { + if (counter >= l || shift > 49) { + read1.bytes = 0; + throw new RangeError("Could not decode varint"); + } + b = buf[counter++]; + res += shift < 28 ? (b & REST$11) << shift : (b & REST$11) * Math.pow(2, shift); + shift += 7; + }while (b >= MSB$11) + read1.bytes = counter - offset; + return res; +} +var N11 = Math.pow(2, 7); +var N21 = Math.pow(2, 14); +var N31 = Math.pow(2, 21); +var N41 = Math.pow(2, 28); +var N51 = Math.pow(2, 35); +var N61 = Math.pow(2, 42); +var N71 = Math.pow(2, 49); +var N81 = Math.pow(2, 56); +var N91 = Math.pow(2, 63); +var length1 = function(value) { + return value < N11 ? 1 : value < N21 ? 2 : value < N31 ? 3 : value < N41 ? 4 : value < N51 ? 5 : value < N61 ? 6 : value < N71 ? 7 : value < N81 ? 8 : value < N91 ? 9 : 10; +}; +var varint1 = { + encode: encode_11, + decode: decode8, + encodingLength: length1 +}; +varint1.encode; +const CIDV0_BYTES = { + SHA2_256: 18, + LENGTH: 32, + DAG_PB: 112 +}; +const V2_HEADER_LENGTH = 16 + 8 + 8 + 8; +function decodeVarint(bytes, seeker) { + if (!bytes.length) { + throw new Error("Unexpected end of data"); + } + const i = varint1.decode(bytes); + seeker.seek(varint1.decode.bytes); + return i; +} +function decodeV2Header(bytes) { + const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let offset = 0; + const header = { + version: 2, + characteristics: [ + dv.getBigUint64(offset, true), + dv.getBigUint64(offset += 8, true) + ], + dataOffset: Number(dv.getBigUint64(offset += 8, true)), + dataSize: Number(dv.getBigUint64(offset += 8, true)), + indexOffset: Number(dv.getBigUint64(offset += 8, true)) + }; + return header; +} +function getMultihashLength(bytes) { + varint1.decode(bytes); + const codeLength = varint1.decode.bytes; + const length = varint1.decode(bytes.subarray(varint1.decode.bytes)); + const lengthLength = varint1.decode.bytes; + const mhLength = codeLength + lengthLength + length; + return mhLength; +} +const Kinds = { + Null: (obj)=>obj === null ? obj : void 0, + Int: (obj)=>Number.isInteger(obj) ? obj : void 0, + Float: (obj)=>typeof obj === "number" && Number.isFinite(obj) ? obj : void 0, + String: (obj)=>typeof obj === "string" ? obj : void 0, + Bool: (obj)=>typeof obj === "boolean" ? obj : void 0, + Bytes: (obj)=>obj instanceof Uint8Array ? obj : void 0, + Link: (obj)=>obj !== null && typeof obj === "object" && obj.asCID === obj ? obj : void 0, + List: (obj)=>Array.isArray(obj) ? obj : void 0, + Map: (obj)=>obj !== null && typeof obj === "object" && obj.asCID !== obj && !Array.isArray(obj) && !(obj instanceof Uint8Array) ? obj : void 0 +}; +const Types = { + "CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)": Kinds.Link, + "CarV1HeaderOrV2Pragma > roots (anon)": (obj)=>{ + if (Kinds.List(obj) === void 0) { + return void 0; + } + for(let i = 0; i < obj.length; i++){ + let v = obj[i]; + v = Types["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v); + if (v === void 0) { + return void 0; + } + if (v !== obj[i]) { + const ret = obj.slice(0, i); + for(let j = i; j < obj.length; j++){ + let v2 = obj[j]; + v2 = Types["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v2); + if (v2 === void 0) { + return void 0; + } + ret.push(v2); + } + return ret; + } + } + return obj; + }, + Int: Kinds.Int, + CarV1HeaderOrV2Pragma: (obj)=>{ + if (Kinds.Map(obj) === void 0) { + return void 0; + } + const entries = Object.entries(obj); + let ret = obj; + let requiredCount = 1; + for(let i = 0; i < entries.length; i++){ + const [key, value] = entries[i]; + switch(key){ + case "roots": + { + const v = Types["CarV1HeaderOrV2Pragma > roots (anon)"](obj[key]); + if (v === void 0) { + return void 0; + } + if (v !== value || ret !== obj) { + if (ret === obj) { + ret = {}; + for(let j = 0; j < i; j++){ + ret[entries[j][0]] = entries[j][1]; + } + } + ret.roots = v; + } + } + break; + case "version": + { + requiredCount--; + const v = Types.Int(obj[key]); + if (v === void 0) { + return void 0; + } + if (v !== value || ret !== obj) { + if (ret === obj) { + ret = {}; + for(let j = 0; j < i; j++){ + ret[entries[j][0]] = entries[j][1]; + } + } + ret.version = v; + } + } + break; + default: + return void 0; + } + } + if (requiredCount > 0) { + return void 0; + } + return ret; + } +}; +const Reprs = { + "CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)": Kinds.Link, + "CarV1HeaderOrV2Pragma > roots (anon)": (obj)=>{ + if (Kinds.List(obj) === void 0) { + return void 0; + } + for(let i = 0; i < obj.length; i++){ + let v = obj[i]; + v = Reprs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v); + if (v === void 0) { + return void 0; + } + if (v !== obj[i]) { + const ret = obj.slice(0, i); + for(let j = i; j < obj.length; j++){ + let v2 = obj[j]; + v2 = Reprs["CarV1HeaderOrV2Pragma > roots (anon) > valueType (anon)"](v2); + if (v2 === void 0) { + return void 0; + } + ret.push(v2); + } + return ret; + } + } + return obj; + }, + Int: Kinds.Int, + CarV1HeaderOrV2Pragma: (obj)=>{ + if (Kinds.Map(obj) === void 0) { + return void 0; + } + const entries = Object.entries(obj); + let ret = obj; + let requiredCount = 1; + for(let i = 0; i < entries.length; i++){ + const [key, value] = entries[i]; + switch(key){ + case "roots": + { + const v = Reprs["CarV1HeaderOrV2Pragma > roots (anon)"](value); + if (v === void 0) { + return void 0; + } + if (v !== value || ret !== obj) { + if (ret === obj) { + ret = {}; + for(let j = 0; j < i; j++){ + ret[entries[j][0]] = entries[j][1]; + } + } + ret.roots = v; + } + } + break; + case "version": + { + requiredCount--; + const v = Reprs.Int(value); + if (v === void 0) { + return void 0; + } + if (v !== value || ret !== obj) { + if (ret === obj) { + ret = {}; + for(let j = 0; j < i; j++){ + ret[entries[j][0]] = entries[j][1]; + } + } + ret.version = v; + } + } + break; + default: + return void 0; + } + } + if (requiredCount > 0) { + return void 0; + } + return ret; + } +}; +const CarV1HeaderOrV2Pragma = { + toTyped: Types.CarV1HeaderOrV2Pragma, + toRepresentation: Reprs.CarV1HeaderOrV2Pragma +}; +const cborEncoders1 = makeCborEncoders(); +const defaultEncodeOptions1 = { + float64: false, + quickEncodeToken +}; +function tokensToLength(tokens, encoders = cborEncoders1, options = defaultEncodeOptions1) { + if (Array.isArray(tokens)) { + let len = 0; + for (const token of tokens){ + len += tokensToLength(token, encoders, options); + } + return len; + } else { + const encoder = encoders[tokens.type.major]; + if (encoder.encodedSize === void 0 || typeof encoder.encodedSize !== "function") { + throw new Error(`Encoder for ${tokens.type.name} does not have an encodedSize()`); + } + return encoder.encodedSize(tokens, options); + } +} +async function readHeader(reader, strictVersion) { + const length = decodeVarint(await reader.upTo(8), reader); + if (length === 0) { + throw new Error("Invalid CAR header (zero length)"); + } + const header = await reader.exactly(length, true); + const block = decode7(header); + if (CarV1HeaderOrV2Pragma.toTyped(block) === void 0) { + throw new Error("Invalid CAR header format"); + } + if (block.version !== 1 && block.version !== 2 || strictVersion !== void 0 && block.version !== strictVersion) { + throw new Error(`Invalid CAR version: ${block.version}${strictVersion !== void 0 ? ` (expected ${strictVersion})` : ""}`); + } + if (block.version === 1) { + if (!Array.isArray(block.roots)) { + throw new Error("Invalid CAR header format"); + } + return block; + } + if (block.roots !== void 0) { + throw new Error("Invalid CAR header format"); + } + const v2Header = decodeV2Header(await reader.exactly(V2_HEADER_LENGTH, true)); + reader.seek(v2Header.dataOffset - reader.pos); + const v1Header = await readHeader(reader, 1); + return Object.assign(v1Header, v2Header); +} +async function readCid(reader) { + const first = await reader.exactly(2, false); + if (first[0] === CIDV0_BYTES.SHA2_256 && first[1] === CIDV0_BYTES.LENGTH) { + const bytes2 = await reader.exactly(34, true); + const multihash2 = decode$2(bytes2); + return CID.create(0, CIDV0_BYTES.DAG_PB, multihash2); + } + const version = decodeVarint(await reader.upTo(8), reader); + if (version !== 1) { + throw new Error(`Unexpected CID version (${version})`); + } + const codec = decodeVarint(await reader.upTo(8), reader); + const bytes = await reader.exactly(getMultihashLength(await reader.upTo(8)), true); + const multihash = decode$2(bytes); + return CID.create(version, codec, multihash); +} +async function readBlockHead(reader) { + const start = reader.pos; + let length = decodeVarint(await reader.upTo(8), reader); + if (length === 0) { + throw new Error("Invalid CAR section (zero length)"); + } + length += reader.pos - start; + const cid2 = await readCid(reader); + const blockLength = length - Number(reader.pos - start); + return { + cid: cid2, + length, + blockLength + }; +} +async function readBlock(reader) { + const { cid: cid2, blockLength } = await readBlockHead(reader); + const bytes = await reader.exactly(blockLength, true); + return { + bytes, + cid: cid2 + }; +} +async function readBlockIndex(reader) { + const offset = reader.pos; + const { cid: cid2, length, blockLength } = await readBlockHead(reader); + const index = { + cid: cid2, + length, + blockLength, + offset, + blockOffset: reader.pos + }; + reader.seek(index.blockLength); + return index; +} +function createDecoder(reader) { + const headerPromise = (async ()=>{ + const header = await readHeader(reader); + if (header.version === 2) { + const v1length = reader.pos - header.dataOffset; + reader = limitReader(reader, header.dataSize - v1length); + } + return header; + })(); + return { + header: ()=>headerPromise, + async *blocks () { + await headerPromise; + while((await reader.upTo(8)).length > 0){ + yield await readBlock(reader); + } + }, + async *blocksIndex () { + await headerPromise; + while((await reader.upTo(8)).length > 0){ + yield await readBlockIndex(reader); + } + } + }; +} +function bytesReader(bytes) { + let pos = 0; + return { + async upTo (length) { + const out = bytes.subarray(pos, pos + Math.min(length, bytes.length - pos)); + return out; + }, + async exactly (length, seek = false) { + if (length > bytes.length - pos) { + throw new Error("Unexpected end of data"); + } + const out = bytes.subarray(pos, pos + length); + if (seek) { + pos += length; + } + return out; + }, + seek (length) { + pos += length; + }, + get pos () { + return pos; + } + }; +} +function chunkReader(readChunk) { + let pos = 0; + let have = 0; + let offset = 0; + let currentChunk = new Uint8Array(0); + const read = async (length)=>{ + have = currentChunk.length - offset; + const bufa = [ + currentChunk.subarray(offset) + ]; + while(have < length){ + const chunk = await readChunk(); + if (chunk == null) { + break; + } + if (have < 0) { + if (chunk.length > have) { + bufa.push(chunk.subarray(-have)); + } + } else { + bufa.push(chunk); + } + have += chunk.length; + } + currentChunk = new Uint8Array(bufa.reduce((p, c)=>p + c.length, 0)); + let off = 0; + for (const b of bufa){ + currentChunk.set(b, off); + off += b.length; + } + offset = 0; + }; + return { + async upTo (length) { + if (currentChunk.length - offset < length) { + await read(length); + } + return currentChunk.subarray(offset, offset + Math.min(currentChunk.length - offset, length)); + }, + async exactly (length, seek = false) { + if (currentChunk.length - offset < length) { + await read(length); + } + if (currentChunk.length - offset < length) { + throw new Error("Unexpected end of data"); + } + const out = currentChunk.subarray(offset, offset + length); + if (seek) { + pos += length; + offset += length; + } + return out; + }, + seek (length) { + pos += length; + offset += length; + }, + get pos () { + return pos; + } + }; +} +function asyncIterableReader(asyncIterable) { + const iterator = asyncIterable[Symbol.asyncIterator](); + async function readChunk() { + const next = await iterator.next(); + if (next.done) { + return null; + } + return next.value; + } + return chunkReader(readChunk); +} +function limitReader(reader, byteLimit) { + let bytesRead = 0; + return { + async upTo (length) { + let bytes = await reader.upTo(length); + if (bytes.length + bytesRead > byteLimit) { + bytes = bytes.subarray(0, byteLimit - bytesRead); + } + return bytes; + }, + async exactly (length, seek = false) { + const bytes = await reader.exactly(length, seek); + if (bytes.length + bytesRead > byteLimit) { + throw new Error("Unexpected end of data"); + } + if (seek) { + bytesRead += length; + } + return bytes; + }, + seek (length) { + bytesRead += length; + reader.seek(length); + }, + get pos () { + return reader.pos; + } + }; +} +class CarBufferWriter { + constructor(bytes, headerSize){ + this.bytes = bytes; + this.byteOffset = headerSize; + this.roots = []; + this.headerSize = headerSize; + } + addRoot(root, options) { + addRoot(this, root, options); + return this; + } + write(block) { + addBlock(this, block); + return this; + } + close(options) { + return close(this, options); + } +} +const addRoot = (writer, root, options = {})=>{ + const { resize = false } = options; + const { bytes, headerSize, byteOffset, roots } = writer; + writer.roots.push(root); + const size = headerLength(writer); + if (size > headerSize) { + if (size - headerSize + byteOffset < bytes.byteLength) { + if (resize) { + resizeHeader(writer, size); + } else { + roots.pop(); + throw new RangeError(`Header of size ${headerSize} has no capacity for new root ${root}. + However there is a space in the buffer and you could call addRoot(root, { resize: root }) to resize header to make a space for this root.`); + } + } else { + roots.pop(); + throw new RangeError(`Buffer has no capacity for a new root ${root}`); + } + } +}; +const blockLength = ({ cid, bytes })=>{ + const size = cid.bytes.byteLength + bytes.byteLength; + return varint1.encodingLength(size) + size; +}; +const addBlock = (writer, { cid, bytes })=>{ + const byteLength = cid.bytes.byteLength + bytes.byteLength; + const size = varint1.encode(byteLength); + if (writer.byteOffset + size.length + byteLength > writer.bytes.byteLength) { + throw new RangeError("Buffer has no capacity for this block"); + } else { + writeBytes(writer, size); + writeBytes(writer, cid.bytes); + writeBytes(writer, bytes); + } +}; +const close = (writer, options = {})=>{ + const { resize = false } = options; + const { roots, bytes, byteOffset, headerSize } = writer; + const headerBytes = encode6({ + version: 1, + roots + }); + const varintBytes = varint1.encode(headerBytes.length); + const size = varintBytes.length + headerBytes.byteLength; + const offset = headerSize - size; + if (offset === 0) { + writeHeader(writer, varintBytes, headerBytes); + return bytes.subarray(0, byteOffset); + } else if (resize) { + resizeHeader(writer, size); + writeHeader(writer, varintBytes, headerBytes); + return bytes.subarray(0, writer.byteOffset); + } else { + throw new RangeError(`Header size was overestimated. +You can use close({ resize: true }) to resize header`); + } +}; +const resizeHeader = (writer, byteLength)=>{ + const { bytes, headerSize } = writer; + bytes.set(bytes.subarray(headerSize, writer.byteOffset), byteLength); + writer.byteOffset += byteLength - headerSize; + writer.headerSize = byteLength; +}; +const writeBytes = (writer, bytes)=>{ + writer.bytes.set(bytes, writer.byteOffset); + writer.byteOffset += bytes.length; +}; +const writeHeader = ({ bytes }, varint3, header)=>{ + bytes.set(varint3); + bytes.set(header, varint3.length); +}; +const headerPreludeTokens = [ + new Token(Type.map, 2), + new Token(Type.string, "version"), + new Token(Type.uint, 1), + new Token(Type.string, "roots") +]; +const CID_TAG = new Token(Type.tag, 42); +const calculateHeaderLength = (rootLengths)=>{ + const tokens = [ + ...headerPreludeTokens + ]; + tokens.push(new Token(Type.array, rootLengths.length)); + for (const rootLength of rootLengths){ + tokens.push(CID_TAG); + tokens.push(new Token(Type.bytes, { + length: rootLength + 1 + })); + } + const length2 = tokensToLength(tokens); + return varint1.encodingLength(length2) + length2; +}; +const headerLength = ({ roots })=>calculateHeaderLength(roots.map((cid)=>cid.bytes.byteLength)); +const estimateHeaderLength = (rootCount, rootByteLength = 36)=>calculateHeaderLength(new Array(rootCount).fill(rootByteLength)); +const createWriter = (buffer, options = {})=>{ + const { roots = [], byteOffset = 0, byteLength = buffer.byteLength, headerSize = headerLength({ + roots + }) } = options; + const bytes = new Uint8Array(buffer, byteOffset, byteLength); + const writer = new CarBufferWriter(bytes, headerSize); + for (const root of roots){ + writer.addRoot(root); + } + return writer; +}; +Object.freeze({ + __proto__: null, + addRoot, + blockLength, + addBlock, + close, + resizeHeader, + calculateHeaderLength, + headerLength, + estimateHeaderLength, + createWriter }); -const blake2b416 = from1({ - name: "blake2b-416", - code: 45620, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 52)) +class CarIndexer { + constructor(version, roots, iterator){ + this._version = version; + this._roots = roots; + this._iterator = iterator; + } + get version() { + return this._version; + } + async getRoots() { + return this._roots; + } + [Symbol.asyncIterator]() { + return this._iterator; + } + static async fromBytes(bytes) { + if (!(bytes instanceof Uint8Array)) { + throw new TypeError("fromBytes() requires a Uint8Array"); + } + return decodeIndexerComplete(bytesReader(bytes)); + } + static async fromIterable(asyncIterable) { + if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === "function")) { + throw new TypeError("fromIterable() requires an async iterable"); + } + return decodeIndexerComplete(asyncIterableReader(asyncIterable)); + } +} +class CarIteratorBase { + constructor(version, roots, iterable){ + this._version = version; + this._roots = roots; + this._iterable = iterable; + this._decoded = false; + } + get version() { + return this._version; + } + async getRoots() { + return this._roots; + } +} +class CarBlockIterator extends CarIteratorBase { + [Symbol.asyncIterator]() { + if (this._decoded) { + throw new Error("Cannot decode more than once"); + } + if (!this._iterable) { + throw new Error("Block iterable not found"); + } + this._decoded = true; + return this._iterable[Symbol.asyncIterator](); + } + static async fromBytes(bytes) { + const { version, roots, iterator } = await fromBytes(bytes); + return new CarBlockIterator(version, roots, iterator); + } + static async fromIterable(asyncIterable) { + const { version, roots, iterator } = await fromIterable(asyncIterable); + return new CarBlockIterator(version, roots, iterator); + } +} +class CarCIDIterator extends CarIteratorBase { + [Symbol.asyncIterator]() { + if (this._decoded) { + throw new Error("Cannot decode more than once"); + } + if (!this._iterable) { + throw new Error("Block iterable not found"); + } + this._decoded = true; + const iterable = this._iterable[Symbol.asyncIterator](); + return { + async next () { + const next = await iterable.next(); + if (next.done) { + return next; + } + return { + done: false, + value: next.value.cid + }; + } + }; + } + static async fromBytes(bytes) { + const { version, roots, iterator } = await fromBytes(bytes); + return new CarCIDIterator(version, roots, iterator); + } + static async fromIterable(asyncIterable) { + const { version, roots, iterator } = await fromIterable(asyncIterable); + return new CarCIDIterator(version, roots, iterator); + } +} +async function fromBytes(bytes) { + if (!(bytes instanceof Uint8Array)) { + throw new TypeError("fromBytes() requires a Uint8Array"); + } + return decodeIterator(bytesReader(bytes)); +} +async function fromIterable(asyncIterable) { + if (!asyncIterable || !(typeof asyncIterable[Symbol.asyncIterator] === "function")) { + throw new TypeError("fromIterable() requires an async iterable"); + } + return decodeIterator(asyncIterableReader(asyncIterable)); +} +async function decodeIterator(reader) { + const decoder2 = createDecoder(reader); + const { version, roots } = await decoder2.header(); + return { + version, + roots, + iterator: decoder2.blocks() + }; +} +class CarWriterOut { + constructor(iterator){ + this._iterator = iterator; + } + [Symbol.asyncIterator]() { + if (this._iterating) { + throw new Error("Multiple iterator not supported"); + } + this._iterating = true; + return this._iterator; + } +} +const empty1 = new Uint8Array(0); +const toHex3 = (d)=>d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); +const fromHex1 = (hex)=>{ + const hexes = hex.match(/../g); + return hexes ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty1; +}; +const equals2 = (aa, bb)=>{ + if (aa === bb) return true; + if (aa.byteLength !== bb.byteLength) { + return false; + } + for(let ii = 0; ii < aa.byteLength; ii++){ + if (aa[ii] !== bb[ii]) { + return false; + } + } + return true; +}; +const coerce1 = (o)=>{ + if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") return o; + if (o instanceof ArrayBuffer) return new Uint8Array(o); + if (ArrayBuffer.isView(o)) { + return new Uint8Array(o.buffer, o.byteOffset, o.byteLength); + } + throw new Error("Unknown type, must be binary type"); +}; +const isBinary1 = (o)=>o instanceof ArrayBuffer || ArrayBuffer.isView(o); +const fromString2 = (str)=>new TextEncoder().encode(str); +const toString2 = (b)=>new TextDecoder().decode(b); +var bytes = Object.freeze({ + __proto__: null, + equals: equals2, + coerce: coerce1, + isBinary: isBinary1, + fromHex: fromHex1, + toHex: toHex3, + fromString: fromString2, + toString: toString2, + empty: empty1 }); -const blake2b424 = from1({ - name: "blake2b-424", - code: 45621, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 53)) +var encode_12 = encode8; +var MSB2 = 128, REST3 = 127, MSBALL2 = ~REST3, INT2 = Math.pow(2, 31); +function encode8(num, out, offset) { + out = out || []; + offset = offset || 0; + var oldOffset = offset; + while(num >= INT2){ + out[offset++] = num & 255 | MSB2; + num /= 128; + } + while(num & MSBALL2){ + out[offset++] = num & 255 | MSB2; + num >>>= 7; + } + out[offset] = num | 0; + encode8.bytes = offset - oldOffset + 1; + return out; +} +var decode9 = read2; +var MSB$12 = 128, REST$12 = 127; +function read2(buf, offset) { + var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; + do { + if (counter >= l) { + read2.bytes = 0; + throw new RangeError("Could not decode varint"); + } + b = buf[counter++]; + res += shift < 28 ? (b & REST$12) << shift : (b & REST$12) * Math.pow(2, shift); + shift += 7; + }while (b >= MSB$12) + read2.bytes = counter - offset; + return res; +} +var N12 = Math.pow(2, 7); +var N22 = Math.pow(2, 14); +var N32 = Math.pow(2, 21); +var N42 = Math.pow(2, 28); +var N52 = Math.pow(2, 35); +var N62 = Math.pow(2, 42); +var N72 = Math.pow(2, 49); +var N82 = Math.pow(2, 56); +var N92 = Math.pow(2, 63); +var length2 = function(value) { + return value < N12 ? 1 : value < N22 ? 2 : value < N32 ? 3 : value < N42 ? 4 : value < N52 ? 5 : value < N62 ? 6 : value < N72 ? 7 : value < N82 ? 8 : value < N92 ? 9 : 10; +}; +var varint2 = { + encode: encode_12, + decode: decode9, + encodingLength: length2 +}; +var _brrp_varint1 = varint2; +const decode$11 = (data, offset = 0)=>{ + const code = _brrp_varint1.decode(data, offset); + return [ + code, + _brrp_varint1.decode.bytes + ]; +}; +const encodeTo1 = (__int, target, offset = 0)=>{ + _brrp_varint1.encode(__int, target, offset); + return target; +}; +const encodingLength1 = (__int)=>{ + return _brrp_varint1.encodingLength(__int); +}; +Object.freeze({ + __proto__: null, + decode: decode$11, + encodeTo: encodeTo1, + encodingLength: encodingLength1 }); -const blake2b432 = from1({ - name: "blake2b-432", - code: 45622, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 54)) +const create1 = (code, digest2)=>{ + const size = digest2.byteLength; + const sizeOffset = encodingLength1(code); + const digestOffset = sizeOffset + encodingLength1(size); + const bytes = new Uint8Array(digestOffset + size); + encodeTo1(code, bytes, 0); + encodeTo1(size, bytes, sizeOffset); + bytes.set(digest2, digestOffset); + return new Digest1(code, size, digest2, bytes); +}; +const decode$21 = (multihash)=>{ + const bytes = coerce1(multihash); + const [code, sizeOffset] = decode$11(bytes); + const [size, digestOffset] = decode$11(bytes.subarray(sizeOffset)); + const digest2 = bytes.subarray(sizeOffset + digestOffset); + if (digest2.byteLength !== size) { + throw new Error("Incorrect length"); + } + return new Digest1(code, size, digest2, bytes); +}; +const equals3 = (a, b)=>{ + if (a === b) { + return true; + } else { + return a.code === b.code && a.size === b.size && equals2(a.bytes, b.bytes); + } +}; +class Digest1 { + constructor(code, size, digest2, bytes){ + this.code = code; + this.size = size; + this.digest = digest2; + this.bytes = bytes; + } +} +Object.freeze({ + __proto__: null, + create: create1, + decode: decode$21, + equals: equals3, + Digest: Digest1 }); -const blake2b440 = from1({ - name: "blake2b-440", - code: 45623, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 55)) +const from1 = ({ name, code, encode })=>new Hasher(name, code, encode); +class Hasher { + constructor(name, code, encode){ + this.name = name; + this.code = code; + this.encode = encode; + } + digest(input) { + if (input instanceof Uint8Array) { + const result = this.encode(input); + return result instanceof Uint8Array ? create1(this.code, result) : result.then((digest$1)=>create1(this.code, digest$1)); + } else { + throw Error("Unknown type, must be binary type"); + } + } +} +Object.freeze({ + __proto__: null, + from: from1, + Hasher }); -const blake2b448 = from1({ - name: "blake2b-448", - code: 45624, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 56)) +const sha2 = (name)=>async (data)=>new Uint8Array(await crypto.subtle.digest(name, data)); +const sha2563 = from1({ + name: "sha2-256", + code: 18, + encode: sha2("SHA-256") }); -const blake2b456 = from1({ - name: "blake2b-456", - code: 45625, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 57)) +const sha5122 = from1({ + name: "sha2-512", + code: 19, + encode: sha2("SHA-512") }); -const blake2b464 = from1({ - name: "blake2b-464", - code: 45626, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 58)) +var sha21 = Object.freeze({ + __proto__: null, + sha256: sha2563, + sha512: sha5122 }); -const blake2b472 = from1({ - name: "blake2b-472", - code: 45627, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 59)) +const empty2 = new Uint8Array(0); +const toHex4 = (d)=>d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); +const fromHex2 = (hex)=>{ + const hexes = hex.match(/../g); + return hexes ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty2; +}; +const equals4 = (aa, bb)=>{ + if (aa === bb) return true; + if (aa.byteLength !== bb.byteLength) { + return false; + } + for(let ii = 0; ii < aa.byteLength; ii++){ + if (aa[ii] !== bb[ii]) { + return false; + } + } + return true; +}; +const coerce2 = (o)=>{ + if (o instanceof Uint8Array && o.constructor.name === "Uint8Array") return o; + if (o instanceof ArrayBuffer) return new Uint8Array(o); + if (ArrayBuffer.isView(o)) { + return new Uint8Array(o.buffer, o.byteOffset, o.byteLength); + } + throw new Error("Unknown type, must be binary type"); +}; +const isBinary2 = (o)=>o instanceof ArrayBuffer || ArrayBuffer.isView(o); +const fromString3 = (str)=>new TextEncoder().encode(str); +const toString3 = (b)=>new TextDecoder().decode(b); +var bytes1 = Object.freeze({ + __proto__: null, + equals: equals4, + coerce: coerce2, + isBinary: isBinary2, + fromHex: fromHex2, + toHex: toHex4, + fromString: fromString3, + toString: toString3, + empty: empty2 }); -const blake2b480 = from1({ - name: "blake2b-480", - code: 45628, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 60)) +var encode_13 = encode9; +var MSB3 = 128, REST4 = 127, MSBALL3 = ~REST4, INT3 = Math.pow(2, 31); +function encode9(num, out, offset) { + out = out || []; + offset = offset || 0; + var oldOffset = offset; + while(num >= INT3){ + out[offset++] = num & 255 | MSB3; + num /= 128; + } + while(num & MSBALL3){ + out[offset++] = num & 255 | MSB3; + num >>>= 7; + } + out[offset] = num | 0; + encode9.bytes = offset - oldOffset + 1; + return out; +} +var decode10 = read3; +var MSB$13 = 128, REST$13 = 127; +function read3(buf, offset) { + var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; + do { + if (counter >= l) { + read3.bytes = 0; + throw new RangeError("Could not decode varint"); + } + b = buf[counter++]; + res += shift < 28 ? (b & REST$13) << shift : (b & REST$13) * Math.pow(2, shift); + shift += 7; + }while (b >= MSB$13) + read3.bytes = counter - offset; + return res; +} +var N13 = Math.pow(2, 7); +var N23 = Math.pow(2, 14); +var N33 = Math.pow(2, 21); +var N43 = Math.pow(2, 28); +var N53 = Math.pow(2, 35); +var N63 = Math.pow(2, 42); +var N73 = Math.pow(2, 49); +var N83 = Math.pow(2, 56); +var N93 = Math.pow(2, 63); +var length3 = function(value) { + return value < N13 ? 1 : value < N23 ? 2 : value < N33 ? 3 : value < N43 ? 4 : value < N53 ? 5 : value < N63 ? 6 : value < N73 ? 7 : value < N83 ? 8 : value < N93 ? 9 : 10; +}; +var varint3 = { + encode: encode_13, + decode: decode10, + encodingLength: length3 +}; +var _brrp_varint2 = varint3; +const decode$12 = (data)=>{ + const code = _brrp_varint2.decode(data); + return [ + code, + _brrp_varint2.decode.bytes + ]; +}; +const encodeTo2 = (__int, target, offset = 0)=>{ + _brrp_varint2.encode(__int, target, offset); + return target; +}; +const encodingLength2 = (__int)=>{ + return _brrp_varint2.encodingLength(__int); +}; +Object.freeze({ + __proto__: null, + decode: decode$12, + encodeTo: encodeTo2, + encodingLength: encodingLength2 }); -const blake2b488 = from1({ - name: "blake2b-488", - code: 45629, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 61)) +const create2 = (code, digest2)=>{ + const size = digest2.byteLength; + const sizeOffset = encodingLength2(code); + const digestOffset = sizeOffset + encodingLength2(size); + const bytes = new Uint8Array(digestOffset + size); + encodeTo2(code, bytes, 0); + encodeTo2(size, bytes, sizeOffset); + bytes.set(digest2, digestOffset); + return new Digest2(code, size, digest2, bytes); +}; +const decode$22 = (multihash)=>{ + const bytes = coerce2(multihash); + const [code, sizeOffset] = decode$12(bytes); + const [size, digestOffset] = decode$12(bytes.subarray(sizeOffset)); + const digest2 = bytes.subarray(sizeOffset + digestOffset); + if (digest2.byteLength !== size) { + throw new Error("Incorrect length"); + } + return new Digest2(code, size, digest2, bytes); +}; +const equals5 = (a, b)=>{ + if (a === b) { + return true; + } else { + return a.code === b.code && a.size === b.size && equals4(a.bytes, b.bytes); + } +}; +class Digest2 { + constructor(code, size, digest2, bytes){ + this.code = code; + this.size = size; + this.digest = digest2; + this.bytes = bytes; + } +} +Object.freeze({ + __proto__: null, + create: create2, + decode: decode$22, + equals: equals5, + Digest: Digest2 }); -const blake2b496 = from1({ - name: "blake2b-496", - code: 45630, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 62)) +const from2 = ({ name, code, encode })=>new Hasher1(name, code, encode); +class Hasher1 { + constructor(name, code, encode){ + this.name = name; + this.code = code; + this.encode = encode; + } + digest(input) { + if (input instanceof Uint8Array) { + const result = this.encode(input); + return result instanceof Uint8Array ? create2(this.code, result) : result.then((digest$1)=>create2(this.code, digest$1)); + } else { + throw Error("Unknown type, must be binary type"); + } + } +} +Object.freeze({ + __proto__: null, + from: from2, + Hasher: Hasher1 }); -const blake2b504 = from1({ - name: "blake2b-504", - code: 45631, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 63)) +function base2(ALPHABET, name) { + if (ALPHABET.length >= 255) { + throw new TypeError("Alphabet too long"); + } + var BASE_MAP = new Uint8Array(256); + for(var j = 0; j < BASE_MAP.length; j++){ + BASE_MAP[j] = 255; + } + for(var i = 0; i < ALPHABET.length; i++){ + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { + throw new TypeError(x + " is ambiguous"); + } + BASE_MAP[xc] = i; + } + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); + var iFACTOR = Math.log(256) / Math.log(BASE); + function encode2(source) { + if (source instanceof Uint8Array) ; + else if (ArrayBuffer.isView(source)) { + source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); + } else if (Array.isArray(source)) { + source = Uint8Array.from(source); + } + if (!(source instanceof Uint8Array)) { + throw new TypeError("Expected Uint8Array"); + } + if (source.length === 0) { + return ""; + } + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; + while(pbegin !== pend && source[pbegin] === 0){ + pbegin++; + zeroes++; + } + var size = (pend - pbegin) * iFACTOR + 1 >>> 0; + var b58 = new Uint8Array(size); + while(pbegin !== pend){ + var carry = source[pbegin]; + var i2 = 0; + for(var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++){ + carry += 256 * b58[it1] >>> 0; + b58[it1] = carry % BASE >>> 0; + carry = carry / BASE >>> 0; + } + if (carry !== 0) { + throw new Error("Non-zero carry"); + } + length = i2; + pbegin++; + } + var it2 = size - length; + while(it2 !== size && b58[it2] === 0){ + it2++; + } + var str = LEADER.repeat(zeroes); + for(; it2 < size; ++it2){ + str += ALPHABET.charAt(b58[it2]); + } + return str; + } + function decodeUnsafe(source) { + if (typeof source !== "string") { + throw new TypeError("Expected String"); + } + if (source.length === 0) { + return new Uint8Array(); + } + var psz = 0; + if (source[psz] === " ") { + return; + } + var zeroes = 0; + var length = 0; + while(source[psz] === LEADER){ + zeroes++; + psz++; + } + var size = (source.length - psz) * FACTOR + 1 >>> 0; + var b256 = new Uint8Array(size); + while(source[psz]){ + var carry = BASE_MAP[source.charCodeAt(psz)]; + if (carry === 255) { + return; + } + var i2 = 0; + for(var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++){ + carry += BASE * b256[it3] >>> 0; + b256[it3] = carry % 256 >>> 0; + carry = carry / 256 >>> 0; + } + if (carry !== 0) { + throw new Error("Non-zero carry"); + } + length = i2; + psz++; + } + if (source[psz] === " ") { + return; + } + var it4 = size - length; + while(it4 !== size && b256[it4] === 0){ + it4++; + } + var vch = new Uint8Array(zeroes + (size - it4)); + var j2 = zeroes; + while(it4 !== size){ + vch[j2++] = b256[it4++]; + } + return vch; + } + function decode2(string) { + var buffer = decodeUnsafe(string); + if (buffer) { + return buffer; + } + throw new Error(`Non-${name} character`); + } + return { + encode: encode2, + decodeUnsafe, + decode: decode2 + }; +} +var src1 = base2; +var _brrp__multiformats_scope_baseX1 = src1; +class Encoder1 { + constructor(name, prefix, baseEncode){ + this.name = name; + this.prefix = prefix; + this.baseEncode = baseEncode; + } + encode(bytes) { + if (bytes instanceof Uint8Array) { + return `${this.prefix}${this.baseEncode(bytes)}`; + } else { + throw Error("Unknown type, must be binary type"); + } + } +} +class Decoder1 { + constructor(name, prefix, baseDecode){ + this.name = name; + this.prefix = prefix; + this.baseDecode = baseDecode; + } + decode(text) { + if (typeof text === "string") { + switch(text[0]){ + case this.prefix: + { + return this.baseDecode(text.slice(1)); + } + default: + { + throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); + } + } + } else { + throw Error("Can only multibase decode strings"); + } + } + or(decoder) { + return or1(this, decoder); + } +} +class ComposedDecoder1 { + constructor(decoders){ + this.decoders = decoders; + } + or(decoder) { + return or1(this, decoder); + } + decode(input) { + const prefix = input[0]; + const decoder = this.decoders[prefix]; + if (decoder) { + return decoder.decode(input); + } else { + throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); + } + } +} +const or1 = (left, right)=>new ComposedDecoder1({ + ...left.decoders || { + [left.prefix]: left + }, + ...right.decoders || { + [right.prefix]: right + } + }); +class Codec1 { + constructor(name, prefix, baseEncode, baseDecode){ + this.name = name; + this.prefix = prefix; + this.baseEncode = baseEncode; + this.baseDecode = baseDecode; + this.encoder = new Encoder1(name, prefix, baseEncode); + this.decoder = new Decoder1(name, prefix, baseDecode); + } + encode(input) { + return this.encoder.encode(input); + } + decode(input) { + return this.decoder.decode(input); + } +} +const from3 = ({ name, prefix, encode: encode2, decode: decode2 })=>new Codec1(name, prefix, encode2, decode2); +const baseX1 = ({ prefix, name, alphabet })=>{ + const { encode: encode2, decode: decode2 } = _brrp__multiformats_scope_baseX1(alphabet, name); + return from3({ + prefix, + name, + encode: encode2, + decode: (text)=>coerce2(decode2(text)) + }); +}; +const decode11 = (string, alphabet, bitsPerChar, name)=>{ + const codes = {}; + for(let i = 0; i < alphabet.length; ++i){ + codes[alphabet[i]] = i; + } + let end = string.length; + while(string[end - 1] === "="){ + --end; + } + const out = new Uint8Array(end * bitsPerChar / 8 | 0); + let bits = 0; + let buffer = 0; + let written = 0; + for(let i = 0; i < end; ++i){ + const value = codes[string[i]]; + if (value === void 0) { + throw new SyntaxError(`Non-${name} character`); + } + buffer = buffer << bitsPerChar | value; + bits += bitsPerChar; + if (bits >= 8) { + bits -= 8; + out[written++] = 255 & buffer >> bits; + } + } + if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { + throw new SyntaxError("Unexpected end of data"); + } + return out; +}; +const encode10 = (data, alphabet, bitsPerChar)=>{ + const pad = alphabet[alphabet.length - 1] === "="; + const mask = (1 << bitsPerChar) - 1; + let out = ""; + let bits = 0; + let buffer = 0; + for(let i = 0; i < data.length; ++i){ + buffer = buffer << 8 | data[i]; + bits += 8; + while(bits > bitsPerChar){ + bits -= bitsPerChar; + out += alphabet[mask & buffer >> bits]; + } + } + if (bits) { + out += alphabet[mask & buffer << bitsPerChar - bits]; + } + if (pad) { + while(out.length * bitsPerChar & 7){ + out += "="; + } + } + return out; +}; +const rfc46481 = ({ name, prefix, bitsPerChar, alphabet })=>{ + return from3({ + prefix, + name, + encode (input) { + return encode10(input, alphabet, bitsPerChar); + }, + decode (input) { + return decode11(input, alphabet, bitsPerChar, name); + } + }); +}; +const base58btc1 = baseX1({ + name: "base58btc", + prefix: "z", + alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" }); -const blake2b512 = from1({ - name: "blake2b-512", - code: 45632, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 64)) +const base58flickr1 = baseX1({ + name: "base58flickr", + prefix: "Z", + alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" }); Object.freeze({ __proto__: null, - blake2b8, - blake2b16, - blake2b24, - blake2b32, - blake2b40, - blake2b48, - blake2b56, - blake2b64, - blake2b72, - blake2b80, - blake2b88, - blake2b96, - blake2b104, - blake2b112, - blake2b120, - blake2b128, - blake2b136, - blake2b144, - blake2b152, - blake2b160, - blake2b168, - blake2b176, - blake2b184, - blake2b192, - blake2b200, - blake2b208, - blake2b216, - blake2b224, - blake2b232, - blake2b240, - blake2b248, - blake2b256, - blake2b264, - blake2b272, - blake2b280, - blake2b288, - blake2b296, - blake2b304, - blake2b312, - blake2b320, - blake2b328, - blake2b336, - blake2b344, - blake2b352, - blake2b360, - blake2b368, - blake2b376, - blake2b384, - blake2b392, - blake2b400, - blake2b408, - blake2b416, - blake2b424, - blake2b432, - blake2b440, - blake2b448, - blake2b456, - blake2b464, - blake2b472, - blake2b480, - blake2b488, - blake2b496, - blake2b504, - blake2b512 -}); -const { blake2s: blake2s1 } = blakejs; -const blake2s8 = from1({ - name: "blake2s-8", - code: 45633, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 1)) -}); -const blake2s16 = from1({ - name: "blake2s-16", - code: 45634, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 2)) -}); -const blake2s24 = from1({ - name: "blake2s-24", - code: 45635, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 3)) -}); -const blake2s32 = from1({ - name: "blake2s-32", - code: 45636, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 4)) -}); -const blake2s40 = from1({ - name: "blake2s-40", - code: 45637, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 5)) -}); -const blake2s48 = from1({ - name: "blake2s-48", - code: 45638, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 6)) -}); -const blake2s56 = from1({ - name: "blake2s-56", - code: 45639, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 7)) -}); -const blake2s64 = from1({ - name: "blake2s-64", - code: 45640, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 8)) -}); -const blake2s72 = from1({ - name: "blake2s-72", - code: 45641, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 9)) -}); -const blake2s80 = from1({ - name: "blake2s-80", - code: 45642, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 10)) -}); -const blake2s88 = from1({ - name: "blake2s-88", - code: 45643, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 11)) -}); -const blake2s96 = from1({ - name: "blake2s-96", - code: 45644, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 12)) -}); -const blake2s104 = from1({ - name: "blake2s-104", - code: 45645, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 13)) -}); -const blake2s112 = from1({ - name: "blake2s-112", - code: 45646, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 14)) -}); -const blake2s120 = from1({ - name: "blake2s-120", - code: 45647, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 15)) -}); -const blake2s128 = from1({ - name: "blake2s-128", - code: 45648, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 16)) -}); -const blake2s136 = from1({ - name: "blake2s-136", - code: 45649, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 17)) -}); -const blake2s144 = from1({ - name: "blake2s-144", - code: 45650, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 18)) -}); -const blake2s152 = from1({ - name: "blake2s-152", - code: 45651, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 19)) -}); -const blake2s160 = from1({ - name: "blake2s-160", - code: 45652, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 20)) + base58btc: base58btc1, + base58flickr: base58flickr1 }); -const blake2s168 = from1({ - name: "blake2s-168", - code: 45653, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 21)) +const base321 = rfc46481({ + prefix: "b", + name: "base32", + alphabet: "abcdefghijklmnopqrstuvwxyz234567", + bitsPerChar: 5 }); -const blake2s176 = from1({ - name: "blake2s-176", - code: 45654, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 22)) +const base32upper1 = rfc46481({ + prefix: "B", + name: "base32upper", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + bitsPerChar: 5 }); -const blake2s184 = from1({ - name: "blake2s-184", - code: 45655, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 23)) +const base32pad1 = rfc46481({ + prefix: "c", + name: "base32pad", + alphabet: "abcdefghijklmnopqrstuvwxyz234567=", + bitsPerChar: 5 }); -const blake2s192 = from1({ - name: "blake2s-192", - code: 45656, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 24)) +const base32padupper1 = rfc46481({ + prefix: "C", + name: "base32padupper", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", + bitsPerChar: 5 }); -const blake2s200 = from1({ - name: "blake2s-200", - code: 45657, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 25)) +const base32hex1 = rfc46481({ + prefix: "v", + name: "base32hex", + alphabet: "0123456789abcdefghijklmnopqrstuv", + bitsPerChar: 5 }); -const blake2s208 = from1({ - name: "blake2s-208", - code: 45658, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 26)) +const base32hexupper1 = rfc46481({ + prefix: "V", + name: "base32hexupper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + bitsPerChar: 5 }); -const blake2s216 = from1({ - name: "blake2s-216", - code: 45659, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 27)) +const base32hexpad1 = rfc46481({ + prefix: "t", + name: "base32hexpad", + alphabet: "0123456789abcdefghijklmnopqrstuv=", + bitsPerChar: 5 }); -const blake2s224 = from1({ - name: "blake2s-224", - code: 45660, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 28)) +const base32hexpadupper1 = rfc46481({ + prefix: "T", + name: "base32hexpadupper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", + bitsPerChar: 5 }); -const blake2s232 = from1({ - name: "blake2s-232", - code: 45661, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 29)) +const base32z1 = rfc46481({ + prefix: "h", + name: "base32z", + alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", + bitsPerChar: 5 }); -const blake2s240 = from1({ - name: "blake2s-240", - code: 45662, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 30)) +Object.freeze({ + __proto__: null, + base32: base321, + base32upper: base32upper1, + base32pad: base32pad1, + base32padupper: base32padupper1, + base32hex: base32hex1, + base32hexupper: base32hexupper1, + base32hexpad: base32hexpad1, + base32hexpadupper: base32hexpadupper1, + base32z: base32z1 }); -const blake2s248 = from1({ - name: "blake2s-248", - code: 45663, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 31)) +class CID1 { + constructor(version2, code, multihash, bytes){ + this.code = code; + this.version = version2; + this.multihash = multihash; + this.bytes = bytes; + this.byteOffset = bytes.byteOffset; + this.byteLength = bytes.byteLength; + this.asCID = this; + this._baseCache = new Map(); + Object.defineProperties(this, { + byteOffset: hidden, + byteLength: hidden, + code: readonly, + version: readonly, + multihash: readonly, + bytes: readonly, + _baseCache: hidden, + asCID: hidden + }); + } + toV0() { + switch(this.version){ + case 0: + { + return this; + } + default: + { + const { code, multihash } = this; + if (code !== DAG_PB_CODE1) { + throw new Error("Cannot convert a non dag-pb CID to CIDv0"); + } + if (multihash.code !== SHA_256_CODE1) { + throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); + } + return CID1.createV0(multihash); + } + } + } + toV1() { + switch(this.version){ + case 0: + { + const { code, digest: digest$1 } = this.multihash; + const multihash = create2(code, digest$1); + return CID1.createV1(this.code, multihash); + } + case 1: + { + return this; + } + default: + { + throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); + } + } + } + equals(other) { + return other && this.code === other.code && this.version === other.version && equals5(this.multihash, other.multihash); + } + toString(base) { + const { bytes, version: version2, _baseCache } = this; + switch(version2){ + case 0: + return toStringV01(bytes, _baseCache, base || base58btc1.encoder); + default: + return toStringV11(bytes, _baseCache, base || base321.encoder); + } + } + toJSON() { + return { + code: this.code, + version: this.version, + hash: this.multihash.bytes + }; + } + get [Symbol.toStringTag]() { + return "CID"; + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return "CID(" + this.toString() + ")"; + } + static isCID(value) { + deprecate(/^0\.0/, IS_CID_DEPRECATION); + return !!(value && (value[cidSymbol1] || value.asCID === value)); + } + get toBaseEncodedString() { + throw new Error("Deprecated, use .toString()"); + } + get codec() { + throw new Error('"codec" property is deprecated, use integer "code" property instead'); + } + get buffer() { + throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead"); + } + get multibaseName() { + throw new Error('"multibaseName" property is deprecated'); + } + get prefix() { + throw new Error('"prefix" property is deprecated'); + } + static asCID(value) { + if (value instanceof CID1) { + return value; + } else if (value != null && value.asCID === value) { + const { version: version2, code, multihash, bytes } = value; + return new CID1(version2, code, multihash, bytes || encodeCID1(version2, code, multihash.bytes)); + } else if (value != null && value[cidSymbol1] === true) { + const { version: version2, multihash, code } = value; + const digest$1 = decode$22(multihash); + return CID1.create(version2, code, digest$1); + } else { + return null; + } + } + static create(version2, code, digest) { + if (typeof code !== "number") { + throw new Error("String codecs are no longer supported"); + } + switch(version2){ + case 0: + { + if (code !== DAG_PB_CODE1) { + throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE1}) block encoding`); + } else { + return new CID1(version2, code, digest, digest.bytes); + } + } + case 1: + { + const bytes = encodeCID1(version2, code, digest.bytes); + return new CID1(version2, code, digest, bytes); + } + default: + { + throw new Error("Invalid version"); + } + } + } + static createV0(digest) { + return CID1.create(0, DAG_PB_CODE1, digest); + } + static createV1(code, digest) { + return CID1.create(1, code, digest); + } + static decode(bytes) { + const [cid, remainder] = CID1.decodeFirst(bytes); + if (remainder.length) { + throw new Error("Incorrect length"); + } + return cid; + } + static decodeFirst(bytes) { + const specs = CID1.inspectBytes(bytes); + const prefixSize = specs.size - specs.multihashSize; + const multihashBytes = coerce2(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); + if (multihashBytes.byteLength !== specs.multihashSize) { + throw new Error("Incorrect length"); + } + const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); + const digest$1 = new Digest2(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); + const cid = specs.version === 0 ? CID1.createV0(digest$1) : CID1.createV1(specs.codec, digest$1); + return [ + cid, + bytes.subarray(specs.size) + ]; + } + static inspectBytes(initialBytes) { + let offset = 0; + const next = ()=>{ + const [i, length] = decode$12(initialBytes.subarray(offset)); + offset += length; + return i; + }; + let version2 = next(); + let codec = DAG_PB_CODE1; + if (version2 === 18) { + version2 = 0; + offset = 0; + } else if (version2 === 1) { + codec = next(); + } + if (version2 !== 0 && version2 !== 1) { + throw new RangeError(`Invalid CID version ${version2}`); + } + const prefixSize = offset; + const multihashCode = next(); + const digestSize = next(); + const size = offset + digestSize; + const multihashSize = size - prefixSize; + return { + version: version2, + codec, + multihashCode, + digestSize, + multihashSize, + size + }; + } + static parse(source, base) { + const [prefix, bytes] = parseCIDtoBytes1(source, base); + const cid = CID1.decode(bytes); + cid._baseCache.set(prefix, source); + return cid; + } +} +const parseCIDtoBytes1 = (source, base)=>{ + switch(source[0]){ + case "Q": + { + const decoder = base || base58btc1; + return [ + base58btc1.prefix, + decoder.decode(`${base58btc1.prefix}${source}`) + ]; + } + case base58btc1.prefix: + { + const decoder = base || base58btc1; + return [ + base58btc1.prefix, + decoder.decode(source) + ]; + } + case base321.prefix: + { + const decoder = base || base321; + return [ + base321.prefix, + decoder.decode(source) + ]; + } + default: + { + if (base == null) { + throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided"); + } + return [ + source[0], + base.decode(source) + ]; + } + } +}; +const toStringV01 = (bytes, cache, base)=>{ + const { prefix } = base; + if (prefix !== base58btc1.prefix) { + throw Error(`Cannot string encode V0 in ${base.name} encoding`); + } + const cid = cache.get(prefix); + if (cid == null) { + const cid2 = base.encode(bytes).slice(1); + cache.set(prefix, cid2); + return cid2; + } else { + return cid; + } +}; +const toStringV11 = (bytes, cache, base)=>{ + const { prefix } = base; + const cid = cache.get(prefix); + if (cid == null) { + const cid2 = base.encode(bytes); + cache.set(prefix, cid2); + return cid2; + } else { + return cid; + } +}; +const DAG_PB_CODE1 = 112; +const SHA_256_CODE1 = 18; +const encodeCID1 = (version2, code, multihash)=>{ + const codeOffset = encodingLength2(version2); + const hashOffset = codeOffset + encodingLength2(code); + const bytes = new Uint8Array(hashOffset + multihash.byteLength); + encodeTo2(version2, bytes, 0); + encodeTo2(code, bytes, codeOffset); + bytes.set(multihash, hashOffset); + return bytes; +}; +const cidSymbol1 = Symbol.for("@ipld/js-cid/CID"); +const readonly = { + writable: false, + configurable: false, + enumerable: true +}; +const hidden = { + writable: false, + enumerable: false, + configurable: false +}; +const version27 = "0.0.0-dev"; +const deprecate = (range, message)=>{ + if (range.test(version27)) { + console.warn(message); + } else { + throw new Error(message); + } +}; +const IS_CID_DEPRECATION = `CID.isCID(v) is deprecated and will be removed in the next major release. +Following code pattern: + +if (CID.isCID(value)) { + doSomethingWithCID(value) +} + +Is replaced with: + +const cid = CID.asCID(value) +if (cid) { + // Make sure to use cid instead of value + doSomethingWithCID(cid) +} +`; +function createCommonjsModule7(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function(path, base) { + return commonjsRequire7(path, base === void 0 || base === null ? module.path : base); + } + }, fn(module, module.exports), module.exports; +} +function commonjsRequire7() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); +} +var murmurHash3js = createCommonjsModule7(function(module, exports) { + (function(root, undefined$1) { + var library = { + version: "3.0.0", + x86: {}, + x64: {}, + inputValidation: true + }; + function _validBytes(bytes) { + if (!Array.isArray(bytes) && !ArrayBuffer.isView(bytes)) { + return false; + } + for(var i = 0; i < bytes.length; i++){ + if (!Number.isInteger(bytes[i]) || bytes[i] < 0 || bytes[i] > 255) { + return false; + } + } + return true; + } + function _x86Multiply(m, n) { + return (m & 65535) * n + (((m >>> 16) * n & 65535) << 16); + } + function _x86Rotl(m, n) { + return m << n | m >>> 32 - n; + } + function _x86Fmix(h) { + h ^= h >>> 16; + h = _x86Multiply(h, 2246822507); + h ^= h >>> 13; + h = _x86Multiply(h, 3266489909); + h ^= h >>> 16; + return h; + } + function _x64Add(m, n) { + m = [ + m[0] >>> 16, + m[0] & 65535, + m[1] >>> 16, + m[1] & 65535 + ]; + n = [ + n[0] >>> 16, + n[0] & 65535, + n[1] >>> 16, + n[1] & 65535 + ]; + var o = [ + 0, + 0, + 0, + 0 + ]; + o[3] += m[3] + n[3]; + o[2] += o[3] >>> 16; + o[3] &= 65535; + o[2] += m[2] + n[2]; + o[1] += o[2] >>> 16; + o[2] &= 65535; + o[1] += m[1] + n[1]; + o[0] += o[1] >>> 16; + o[1] &= 65535; + o[0] += m[0] + n[0]; + o[0] &= 65535; + return [ + o[0] << 16 | o[1], + o[2] << 16 | o[3] + ]; + } + function _x64Multiply(m, n) { + m = [ + m[0] >>> 16, + m[0] & 65535, + m[1] >>> 16, + m[1] & 65535 + ]; + n = [ + n[0] >>> 16, + n[0] & 65535, + n[1] >>> 16, + n[1] & 65535 + ]; + var o = [ + 0, + 0, + 0, + 0 + ]; + o[3] += m[3] * n[3]; + o[2] += o[3] >>> 16; + o[3] &= 65535; + o[2] += m[2] * n[3]; + o[1] += o[2] >>> 16; + o[2] &= 65535; + o[2] += m[3] * n[2]; + o[1] += o[2] >>> 16; + o[2] &= 65535; + o[1] += m[1] * n[3]; + o[0] += o[1] >>> 16; + o[1] &= 65535; + o[1] += m[2] * n[2]; + o[0] += o[1] >>> 16; + o[1] &= 65535; + o[1] += m[3] * n[1]; + o[0] += o[1] >>> 16; + o[1] &= 65535; + o[0] += m[0] * n[3] + m[1] * n[2] + m[2] * n[1] + m[3] * n[0]; + o[0] &= 65535; + return [ + o[0] << 16 | o[1], + o[2] << 16 | o[3] + ]; + } + function _x64Rotl(m, n) { + n %= 64; + if (n === 32) { + return [ + m[1], + m[0] + ]; + } else if (n < 32) { + return [ + m[0] << n | m[1] >>> 32 - n, + m[1] << n | m[0] >>> 32 - n + ]; + } else { + n -= 32; + return [ + m[1] << n | m[0] >>> 32 - n, + m[0] << n | m[1] >>> 32 - n + ]; + } + } + function _x64LeftShift(m, n) { + n %= 64; + if (n === 0) { + return m; + } else if (n < 32) { + return [ + m[0] << n | m[1] >>> 32 - n, + m[1] << n + ]; + } else { + return [ + m[1] << n - 32, + 0 + ]; + } + } + function _x64Xor(m, n) { + return [ + m[0] ^ n[0], + m[1] ^ n[1] + ]; + } + function _x64Fmix(h) { + h = _x64Xor(h, [ + 0, + h[0] >>> 1 + ]); + h = _x64Multiply(h, [ + 4283543511, + 3981806797 + ]); + h = _x64Xor(h, [ + 0, + h[0] >>> 1 + ]); + h = _x64Multiply(h, [ + 3301882366, + 444984403 + ]); + h = _x64Xor(h, [ + 0, + h[0] >>> 1 + ]); + return h; + } + library.x86.hash32 = function(bytes, seed) { + if (library.inputValidation && !_validBytes(bytes)) { + return undefined$1; + } + seed = seed || 0; + var remainder = bytes.length % 4; + var blocks = bytes.length - remainder; + var h1 = seed; + var k1 = 0; + var c1 = 3432918353; + var c2 = 461845907; + for(var i = 0; i < blocks; i = i + 4){ + k1 = bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24; + k1 = _x86Multiply(k1, c1); + k1 = _x86Rotl(k1, 15); + k1 = _x86Multiply(k1, c2); + h1 ^= k1; + h1 = _x86Rotl(h1, 13); + h1 = _x86Multiply(h1, 5) + 3864292196; + } + k1 = 0; + switch(remainder){ + case 3: + k1 ^= bytes[i + 2] << 16; + case 2: + k1 ^= bytes[i + 1] << 8; + case 1: + k1 ^= bytes[i]; + k1 = _x86Multiply(k1, c1); + k1 = _x86Rotl(k1, 15); + k1 = _x86Multiply(k1, c2); + h1 ^= k1; + } + h1 ^= bytes.length; + h1 = _x86Fmix(h1); + return h1 >>> 0; + }; + library.x86.hash128 = function(bytes, seed) { + if (library.inputValidation && !_validBytes(bytes)) { + return undefined$1; + } + seed = seed || 0; + var remainder = bytes.length % 16; + var blocks = bytes.length - remainder; + var h1 = seed; + var h2 = seed; + var h3 = seed; + var h4 = seed; + var k1 = 0; + var k2 = 0; + var k3 = 0; + var k4 = 0; + var c1 = 597399067; + var c2 = 2869860233; + var c3 = 951274213; + var c4 = 2716044179; + for(var i = 0; i < blocks; i = i + 16){ + k1 = bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24; + k2 = bytes[i + 4] | bytes[i + 5] << 8 | bytes[i + 6] << 16 | bytes[i + 7] << 24; + k3 = bytes[i + 8] | bytes[i + 9] << 8 | bytes[i + 10] << 16 | bytes[i + 11] << 24; + k4 = bytes[i + 12] | bytes[i + 13] << 8 | bytes[i + 14] << 16 | bytes[i + 15] << 24; + k1 = _x86Multiply(k1, c1); + k1 = _x86Rotl(k1, 15); + k1 = _x86Multiply(k1, c2); + h1 ^= k1; + h1 = _x86Rotl(h1, 19); + h1 += h2; + h1 = _x86Multiply(h1, 5) + 1444728091; + k2 = _x86Multiply(k2, c2); + k2 = _x86Rotl(k2, 16); + k2 = _x86Multiply(k2, c3); + h2 ^= k2; + h2 = _x86Rotl(h2, 17); + h2 += h3; + h2 = _x86Multiply(h2, 5) + 197830471; + k3 = _x86Multiply(k3, c3); + k3 = _x86Rotl(k3, 17); + k3 = _x86Multiply(k3, c4); + h3 ^= k3; + h3 = _x86Rotl(h3, 15); + h3 += h4; + h3 = _x86Multiply(h3, 5) + 2530024501; + k4 = _x86Multiply(k4, c4); + k4 = _x86Rotl(k4, 18); + k4 = _x86Multiply(k4, c1); + h4 ^= k4; + h4 = _x86Rotl(h4, 13); + h4 += h1; + h4 = _x86Multiply(h4, 5) + 850148119; + } + k1 = 0; + k2 = 0; + k3 = 0; + k4 = 0; + switch(remainder){ + case 15: + k4 ^= bytes[i + 14] << 16; + case 14: + k4 ^= bytes[i + 13] << 8; + case 13: + k4 ^= bytes[i + 12]; + k4 = _x86Multiply(k4, c4); + k4 = _x86Rotl(k4, 18); + k4 = _x86Multiply(k4, c1); + h4 ^= k4; + case 12: + k3 ^= bytes[i + 11] << 24; + case 11: + k3 ^= bytes[i + 10] << 16; + case 10: + k3 ^= bytes[i + 9] << 8; + case 9: + k3 ^= bytes[i + 8]; + k3 = _x86Multiply(k3, c3); + k3 = _x86Rotl(k3, 17); + k3 = _x86Multiply(k3, c4); + h3 ^= k3; + case 8: + k2 ^= bytes[i + 7] << 24; + case 7: + k2 ^= bytes[i + 6] << 16; + case 6: + k2 ^= bytes[i + 5] << 8; + case 5: + k2 ^= bytes[i + 4]; + k2 = _x86Multiply(k2, c2); + k2 = _x86Rotl(k2, 16); + k2 = _x86Multiply(k2, c3); + h2 ^= k2; + case 4: + k1 ^= bytes[i + 3] << 24; + case 3: + k1 ^= bytes[i + 2] << 16; + case 2: + k1 ^= bytes[i + 1] << 8; + case 1: + k1 ^= bytes[i]; + k1 = _x86Multiply(k1, c1); + k1 = _x86Rotl(k1, 15); + k1 = _x86Multiply(k1, c2); + h1 ^= k1; + } + h1 ^= bytes.length; + h2 ^= bytes.length; + h3 ^= bytes.length; + h4 ^= bytes.length; + h1 += h2; + h1 += h3; + h1 += h4; + h2 += h1; + h3 += h1; + h4 += h1; + h1 = _x86Fmix(h1); + h2 = _x86Fmix(h2); + h3 = _x86Fmix(h3); + h4 = _x86Fmix(h4); + h1 += h2; + h1 += h3; + h1 += h4; + h2 += h1; + h3 += h1; + h4 += h1; + return ("00000000" + (h1 >>> 0).toString(16)).slice(-8) + ("00000000" + (h2 >>> 0).toString(16)).slice(-8) + ("00000000" + (h3 >>> 0).toString(16)).slice(-8) + ("00000000" + (h4 >>> 0).toString(16)).slice(-8); + }; + library.x64.hash128 = function(bytes, seed) { + if (library.inputValidation && !_validBytes(bytes)) { + return undefined$1; + } + seed = seed || 0; + var remainder = bytes.length % 16; + var blocks = bytes.length - remainder; + var h1 = [ + 0, + seed + ]; + var h2 = [ + 0, + seed + ]; + var k1 = [ + 0, + 0 + ]; + var k2 = [ + 0, + 0 + ]; + var c1 = [ + 2277735313, + 289559509 + ]; + var c2 = [ + 1291169091, + 658871167 + ]; + for(var i = 0; i < blocks; i = i + 16){ + k1 = [ + bytes[i + 4] | bytes[i + 5] << 8 | bytes[i + 6] << 16 | bytes[i + 7] << 24, + bytes[i] | bytes[i + 1] << 8 | bytes[i + 2] << 16 | bytes[i + 3] << 24 + ]; + k2 = [ + bytes[i + 12] | bytes[i + 13] << 8 | bytes[i + 14] << 16 | bytes[i + 15] << 24, + bytes[i + 8] | bytes[i + 9] << 8 | bytes[i + 10] << 16 | bytes[i + 11] << 24 + ]; + k1 = _x64Multiply(k1, c1); + k1 = _x64Rotl(k1, 31); + k1 = _x64Multiply(k1, c2); + h1 = _x64Xor(h1, k1); + h1 = _x64Rotl(h1, 27); + h1 = _x64Add(h1, h2); + h1 = _x64Add(_x64Multiply(h1, [ + 0, + 5 + ]), [ + 0, + 1390208809 + ]); + k2 = _x64Multiply(k2, c2); + k2 = _x64Rotl(k2, 33); + k2 = _x64Multiply(k2, c1); + h2 = _x64Xor(h2, k2); + h2 = _x64Rotl(h2, 31); + h2 = _x64Add(h2, h1); + h2 = _x64Add(_x64Multiply(h2, [ + 0, + 5 + ]), [ + 0, + 944331445 + ]); + } + k1 = [ + 0, + 0 + ]; + k2 = [ + 0, + 0 + ]; + switch(remainder){ + case 15: + k2 = _x64Xor(k2, _x64LeftShift([ + 0, + bytes[i + 14] + ], 48)); + case 14: + k2 = _x64Xor(k2, _x64LeftShift([ + 0, + bytes[i + 13] + ], 40)); + case 13: + k2 = _x64Xor(k2, _x64LeftShift([ + 0, + bytes[i + 12] + ], 32)); + case 12: + k2 = _x64Xor(k2, _x64LeftShift([ + 0, + bytes[i + 11] + ], 24)); + case 11: + k2 = _x64Xor(k2, _x64LeftShift([ + 0, + bytes[i + 10] + ], 16)); + case 10: + k2 = _x64Xor(k2, _x64LeftShift([ + 0, + bytes[i + 9] + ], 8)); + case 9: + k2 = _x64Xor(k2, [ + 0, + bytes[i + 8] + ]); + k2 = _x64Multiply(k2, c2); + k2 = _x64Rotl(k2, 33); + k2 = _x64Multiply(k2, c1); + h2 = _x64Xor(h2, k2); + case 8: + k1 = _x64Xor(k1, _x64LeftShift([ + 0, + bytes[i + 7] + ], 56)); + case 7: + k1 = _x64Xor(k1, _x64LeftShift([ + 0, + bytes[i + 6] + ], 48)); + case 6: + k1 = _x64Xor(k1, _x64LeftShift([ + 0, + bytes[i + 5] + ], 40)); + case 5: + k1 = _x64Xor(k1, _x64LeftShift([ + 0, + bytes[i + 4] + ], 32)); + case 4: + k1 = _x64Xor(k1, _x64LeftShift([ + 0, + bytes[i + 3] + ], 24)); + case 3: + k1 = _x64Xor(k1, _x64LeftShift([ + 0, + bytes[i + 2] + ], 16)); + case 2: + k1 = _x64Xor(k1, _x64LeftShift([ + 0, + bytes[i + 1] + ], 8)); + case 1: + k1 = _x64Xor(k1, [ + 0, + bytes[i] + ]); + k1 = _x64Multiply(k1, c1); + k1 = _x64Rotl(k1, 31); + k1 = _x64Multiply(k1, c2); + h1 = _x64Xor(h1, k1); + } + h1 = _x64Xor(h1, [ + 0, + bytes.length + ]); + h2 = _x64Xor(h2, [ + 0, + bytes.length + ]); + h1 = _x64Add(h1, h2); + h2 = _x64Add(h2, h1); + h1 = _x64Fmix(h1); + h2 = _x64Fmix(h2); + h1 = _x64Add(h1, h2); + h2 = _x64Add(h2, h1); + return ("00000000" + (h1[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h1[1] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[0] >>> 0).toString(16)).slice(-8) + ("00000000" + (h2[1] >>> 0).toString(16)).slice(-8); + }; + { + if (module.exports) { + exports = module.exports = library; + } + exports.murmurHash3 = library; + } + })(); }); -const blake2s256 = from1({ - name: "blake2s-256", - code: 45664, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 32)) +var murmurhash3jsRevisited = murmurHash3js; +murmurhash3jsRevisited.murmurHash3; +function fromNumberTo32BitBuf(number) { + const bytes2 = new Array(4); + for(let i = 0; i < 4; i++){ + bytes2[i] = number & 255; + number = number >> 8; + } + return new Uint8Array(bytes2); +} +const murmur332 = from2({ + name: "murmur3-32", + code: 35, + encode: (input)=>fromNumberTo32BitBuf(murmurhash3jsRevisited.x86.hash32(input)) }); -Object.freeze({ - __proto__: null, - blake2s8, - blake2s16, - blake2s24, - blake2s32, - blake2s40, - blake2s48, - blake2s56, - blake2s64, - blake2s72, - blake2s80, - blake2s88, - blake2s96, - blake2s104, - blake2s112, - blake2s120, - blake2s128, - blake2s136, - blake2s144, - blake2s152, - blake2s160, - blake2s168, - blake2s176, - blake2s184, - blake2s192, - blake2s200, - blake2s208, - blake2s216, - blake2s224, - blake2s232, - blake2s240, - blake2s248, - blake2s256 +const murmur3128 = from2({ + name: "murmur3-128", + code: 34, + encode: (input)=>bytes1.fromHex(murmurhash3jsRevisited.x64.hash128(input)) }); -function defaultSetTimout() { - throw new Error("setTimeout has not been defined"); +const ERROR_MSG_INPUT = "Input must be an string, Buffer or Uint8Array"; +function normalizeInput(input) { + let ret; + if (input instanceof Uint8Array) { + ret = input; + } else if (typeof input === "string") { + const encoder = new TextEncoder(); + ret = encoder.encode(input); + } else { + throw new Error(ERROR_MSG_INPUT); + } + return ret; +} +function toHex5(bytes) { + return Array.prototype.map.call(bytes, function(n) { + return (n < 16 ? "0" : "") + n.toString(16); + }).join(""); +} +function uint32ToHex(val) { + return (4294967296 + val).toString(16).substring(1); +} +function debugPrint(label, arr, size) { + let msg = "\n" + label + " = "; + for(let i = 0; i < arr.length; i += 2){ + if (size === 32) { + msg += uint32ToHex(arr[i]).toUpperCase(); + msg += " "; + msg += uint32ToHex(arr[i + 1]).toUpperCase(); + } else if (size === 64) { + msg += uint32ToHex(arr[i + 1]).toUpperCase(); + msg += uint32ToHex(arr[i]).toUpperCase(); + } else throw new Error("Invalid size " + size); + if (i % 6 === 4) { + msg += "\n" + new Array(label.length + 4).join(" "); + } else if (i < arr.length - 2) { + msg += " "; + } + } + console.log(msg); +} +function testSpeed(hashFn, N, M) { + let startMs = new Date().getTime(); + const input = new Uint8Array(N); + for(let i = 0; i < N; i++){ + input[i] = i % 256; + } + const genMs = new Date().getTime(); + console.log("Generated random input in " + (genMs - startMs) + "ms"); + startMs = genMs; + for(let i = 0; i < M; i++){ + const hashHex = hashFn(input); + const hashMs = new Date().getTime(); + const ms = hashMs - startMs; + startMs = hashMs; + console.log("Hashed in " + ms + "ms: " + hashHex.substring(0, 20) + "..."); + console.log(Math.round(N / (1 << 20) / (ms / 1e3) * 100) / 100 + " MB PER SECOND"); + } +} +var util = { + normalizeInput, + toHex: toHex5, + debugPrint, + testSpeed +}; +function ADD64AA(v2, a, b) { + const o0 = v2[a] + v2[b]; + let o1 = v2[a + 1] + v2[b + 1]; + if (o0 >= 4294967296) { + o1++; + } + v2[a] = o0; + v2[a + 1] = o1; +} +function ADD64AC(v2, a, b0, b1) { + let o0 = v2[a] + b0; + if (b0 < 0) { + o0 += 4294967296; + } + let o1 = v2[a + 1] + b1; + if (o0 >= 4294967296) { + o1++; + } + v2[a] = o0; + v2[a + 1] = o1; +} +function B2B_GET32(arr, i) { + return arr[i] ^ arr[i + 1] << 8 ^ arr[i + 2] << 16 ^ arr[i + 3] << 24; +} +function B2B_G(a, b, c, d, ix, iy) { + const x0 = m[ix]; + const x1 = m[ix + 1]; + const y0 = m[iy]; + const y1 = m[iy + 1]; + ADD64AA(v, a, b); + ADD64AC(v, a, x0, x1); + let xor0 = v[d] ^ v[a]; + let xor1 = v[d + 1] ^ v[a + 1]; + v[d] = xor1; + v[d + 1] = xor0; + ADD64AA(v, c, d); + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = xor0 >>> 24 ^ xor1 << 8; + v[b + 1] = xor1 >>> 24 ^ xor0 << 8; + ADD64AA(v, a, b); + ADD64AC(v, a, y0, y1); + xor0 = v[d] ^ v[a]; + xor1 = v[d + 1] ^ v[a + 1]; + v[d] = xor0 >>> 16 ^ xor1 << 16; + v[d + 1] = xor1 >>> 16 ^ xor0 << 16; + ADD64AA(v, c, d); + xor0 = v[b] ^ v[c]; + xor1 = v[b + 1] ^ v[c + 1]; + v[b] = xor1 >>> 31 ^ xor0 << 1; + v[b + 1] = xor0 >>> 31 ^ xor1 << 1; } -function defaultClearTimeout() { - throw new Error("clearTimeout has not been defined"); +const BLAKE2B_IV32 = new Uint32Array([ + 4089235720, + 1779033703, + 2227873595, + 3144134277, + 4271175723, + 1013904242, + 1595750129, + 2773480762, + 2917565137, + 1359893119, + 725511199, + 2600822924, + 4215389547, + 528734635, + 327033209, + 1541459225 +]); +const SIGMA8 = [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3, + 11, + 8, + 12, + 0, + 5, + 2, + 15, + 13, + 10, + 14, + 3, + 6, + 7, + 1, + 9, + 4, + 7, + 9, + 3, + 1, + 13, + 12, + 11, + 14, + 2, + 6, + 5, + 10, + 4, + 0, + 15, + 8, + 9, + 0, + 5, + 7, + 2, + 4, + 10, + 15, + 14, + 1, + 11, + 12, + 6, + 8, + 3, + 13, + 2, + 12, + 6, + 10, + 0, + 11, + 8, + 3, + 4, + 13, + 7, + 5, + 15, + 14, + 1, + 9, + 12, + 5, + 1, + 15, + 14, + 13, + 4, + 10, + 0, + 7, + 6, + 3, + 9, + 2, + 8, + 11, + 13, + 11, + 7, + 14, + 12, + 1, + 3, + 9, + 5, + 0, + 15, + 4, + 8, + 6, + 2, + 10, + 6, + 15, + 14, + 9, + 11, + 3, + 0, + 8, + 12, + 2, + 13, + 7, + 1, + 4, + 10, + 5, + 10, + 2, + 8, + 4, + 7, + 6, + 1, + 5, + 15, + 11, + 9, + 14, + 3, + 12, + 13, + 0, + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3 +]; +const SIGMA82 = new Uint8Array(SIGMA8.map(function(x) { + return x * 2; +})); +const v = new Uint32Array(32); +const m = new Uint32Array(32); +function blake2bCompress(ctx, last) { + let i = 0; + for(i = 0; i < 16; i++){ + v[i] = ctx.h[i]; + v[i + 16] = BLAKE2B_IV32[i]; + } + v[24] = v[24] ^ ctx.t; + v[25] = v[25] ^ ctx.t / 4294967296; + if (last) { + v[28] = ~v[28]; + v[29] = ~v[29]; + } + for(i = 0; i < 32; i++){ + m[i] = B2B_GET32(ctx.b, 4 * i); + } + for(i = 0; i < 12; i++){ + B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]); + B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]); + B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]); + B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]); + B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]); + B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]); + B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]); + B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]); + } + for(i = 0; i < 16; i++){ + ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16]; + } } -var cachedSetTimeout = defaultSetTimout; -var cachedClearTimeout = defaultClearTimeout; -var globalContext; -if (typeof window !== "undefined") { - globalContext = window; -} else if (typeof self !== "undefined") { - globalContext = self; -} else { - globalContext = {}; +const parameterBlock = new Uint8Array([ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 +]); +function blake2bInit(outlen, key, salt, personal) { + if (outlen === 0 || outlen > 64) { + throw new Error("Illegal output length, expected 0 < length <= 64"); + } + if (key && key.length > 64) { + throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64"); + } + if (salt && salt.length !== 16) { + throw new Error("Illegal salt, expected Uint8Array with length is 16"); + } + if (personal && personal.length !== 16) { + throw new Error("Illegal personal, expected Uint8Array with length is 16"); + } + const ctx = { + b: new Uint8Array(128), + h: new Uint32Array(16), + t: 0, + c: 0, + outlen + }; + parameterBlock.fill(0); + parameterBlock[0] = outlen; + if (key) parameterBlock[1] = key.length; + parameterBlock[2] = 1; + parameterBlock[3] = 1; + if (salt) parameterBlock.set(salt, 32); + if (personal) parameterBlock.set(personal, 48); + for(let i = 0; i < 16; i++){ + ctx.h[i] = BLAKE2B_IV32[i] ^ B2B_GET32(parameterBlock, i * 4); + } + if (key) { + blake2bUpdate(ctx, key); + ctx.c = 128; + } + return ctx; } -if (typeof globalContext.setTimeout === "function") { - cachedSetTimeout = setTimeout; +function blake2bUpdate(ctx, input) { + for(let i = 0; i < input.length; i++){ + if (ctx.c === 128) { + ctx.t += ctx.c; + blake2bCompress(ctx, false); + ctx.c = 0; + } + ctx.b[ctx.c++] = input[i]; + } } -if (typeof globalContext.clearTimeout === "function") { - cachedClearTimeout = clearTimeout; +function blake2bFinal(ctx) { + ctx.t += ctx.c; + while(ctx.c < 128){ + ctx.b[ctx.c++] = 0; + } + blake2bCompress(ctx, true); + const out = new Uint8Array(ctx.outlen); + for(let i = 0; i < ctx.outlen; i++){ + out[i] = ctx.h[i >> 2] >> 8 * (i & 3); + } + return out; } -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - return setTimeout(fun, 0); +function blake2b(input, key, outlen, salt, personal) { + outlen = outlen || 64; + input = util.normalizeInput(input); + if (salt) { + salt = util.normalizeInput(salt); } - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); + if (personal) { + personal = util.normalizeInput(personal); + } + const ctx = blake2bInit(outlen, key, salt, personal); + blake2bUpdate(ctx, input); + return blake2bFinal(ctx); +} +function blake2bHex(input, key, outlen, salt, personal) { + const output = blake2b(input, key, outlen, salt, personal); + return util.toHex(output); +} +var blake2b_1 = { + blake2b, + blake2bHex, + blake2bInit, + blake2bUpdate, + blake2bFinal +}; +function B2S_GET32(v2, i) { + return v2[i] ^ v2[i + 1] << 8 ^ v2[i + 2] << 16 ^ v2[i + 3] << 24; +} +function B2S_G(a, b, c, d, x, y) { + v$1[a] = v$1[a] + v$1[b] + x; + v$1[d] = ROTR32(v$1[d] ^ v$1[a], 16); + v$1[c] = v$1[c] + v$1[d]; + v$1[b] = ROTR32(v$1[b] ^ v$1[c], 12); + v$1[a] = v$1[a] + v$1[b] + y; + v$1[d] = ROTR32(v$1[d] ^ v$1[a], 8); + v$1[c] = v$1[c] + v$1[d]; + v$1[b] = ROTR32(v$1[b] ^ v$1[c], 7); +} +function ROTR32(x, y) { + return x >>> y ^ x << 32 - y; +} +const BLAKE2S_IV = new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +const SIGMA = new Uint8Array([ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 14, + 10, + 4, + 8, + 9, + 15, + 13, + 6, + 1, + 12, + 0, + 2, + 11, + 7, + 5, + 3, + 11, + 8, + 12, + 0, + 5, + 2, + 15, + 13, + 10, + 14, + 3, + 6, + 7, + 1, + 9, + 4, + 7, + 9, + 3, + 1, + 13, + 12, + 11, + 14, + 2, + 6, + 5, + 10, + 4, + 0, + 15, + 8, + 9, + 0, + 5, + 7, + 2, + 4, + 10, + 15, + 14, + 1, + 11, + 12, + 6, + 8, + 3, + 13, + 2, + 12, + 6, + 10, + 0, + 11, + 8, + 3, + 4, + 13, + 7, + 5, + 15, + 14, + 1, + 9, + 12, + 5, + 1, + 15, + 14, + 13, + 4, + 10, + 0, + 7, + 6, + 3, + 9, + 2, + 8, + 11, + 13, + 11, + 7, + 14, + 12, + 1, + 3, + 9, + 5, + 0, + 15, + 4, + 8, + 6, + 2, + 10, + 6, + 15, + 14, + 9, + 11, + 3, + 0, + 8, + 12, + 2, + 13, + 7, + 1, + 4, + 10, + 5, + 10, + 2, + 8, + 4, + 7, + 6, + 1, + 5, + 15, + 11, + 9, + 14, + 3, + 12, + 13, + 0 +]); +const v$1 = new Uint32Array(16); +const m$1 = new Uint32Array(16); +function blake2sCompress(ctx, last) { + let i = 0; + for(i = 0; i < 8; i++){ + v$1[i] = ctx.h[i]; + v$1[i + 8] = BLAKE2S_IV[i]; } - try { - return cachedSetTimeout(fun, 0); - } catch (e) { - try { - return cachedSetTimeout.call(null, fun, 0); - } catch (e2) { - return cachedSetTimeout.call(this, fun, 0); - } + v$1[12] ^= ctx.t; + v$1[13] ^= ctx.t / 4294967296; + if (last) { + v$1[14] = ~v$1[14]; } -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - return clearTimeout(marker); + for(i = 0; i < 16; i++){ + m$1[i] = B2S_GET32(ctx.b, 4 * i); } - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); + for(i = 0; i < 10; i++){ + B2S_G(0, 4, 8, 12, m$1[SIGMA[i * 16 + 0]], m$1[SIGMA[i * 16 + 1]]); + B2S_G(1, 5, 9, 13, m$1[SIGMA[i * 16 + 2]], m$1[SIGMA[i * 16 + 3]]); + B2S_G(2, 6, 10, 14, m$1[SIGMA[i * 16 + 4]], m$1[SIGMA[i * 16 + 5]]); + B2S_G(3, 7, 11, 15, m$1[SIGMA[i * 16 + 6]], m$1[SIGMA[i * 16 + 7]]); + B2S_G(0, 5, 10, 15, m$1[SIGMA[i * 16 + 8]], m$1[SIGMA[i * 16 + 9]]); + B2S_G(1, 6, 11, 12, m$1[SIGMA[i * 16 + 10]], m$1[SIGMA[i * 16 + 11]]); + B2S_G(2, 7, 8, 13, m$1[SIGMA[i * 16 + 12]], m$1[SIGMA[i * 16 + 13]]); + B2S_G(3, 4, 9, 14, m$1[SIGMA[i * 16 + 14]], m$1[SIGMA[i * 16 + 15]]); } - try { - return cachedClearTimeout(marker); - } catch (e) { - try { - return cachedClearTimeout.call(null, marker); - } catch (e2) { - return cachedClearTimeout.call(this, marker); - } + for(i = 0; i < 8; i++){ + ctx.h[i] ^= v$1[i] ^ v$1[i + 8]; } } -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; +function blake2sInit(outlen, key) { + if (!(outlen > 0 && outlen <= 32)) { + throw new Error("Incorrect output length, should be in [1, 32]"); } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; + const keylen = key ? key.length : 0; + if (key && !(keylen > 0 && keylen <= 32)) { + throw new Error("Incorrect key length, should be in [1, 32]"); } - if (queue.length) { - drainQueue(); + const ctx = { + h: new Uint32Array(BLAKE2S_IV), + b: new Uint8Array(64), + c: 0, + t: 0, + outlen + }; + ctx.h[0] ^= 16842752 ^ keylen << 8 ^ outlen; + if (keylen > 0) { + blake2sUpdate(ctx, key); + ctx.c = 64; } + return ctx; } -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while(len){ - currentQueue = queue; - queue = []; - while(++queueIndex < len){ - if (currentQueue) { - currentQueue[queueIndex].run(); - } +function blake2sUpdate(ctx, input) { + for(let i = 0; i < input.length; i++){ + if (ctx.c === 64) { + ctx.t += ctx.c; + blake2sCompress(ctx, false); + ctx.c = 0; } - queueIndex = -1; - len = queue.length; + ctx.b[ctx.c++] = input[i]; } - currentQueue = null; - draining = false; - runClearTimeout(timeout); } -function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for(var i = 1; i < arguments.length; i++){ - args[i - 1] = arguments[i]; - } +function blake2sFinal(ctx) { + ctx.t += ctx.c; + while(ctx.c < 64){ + ctx.b[ctx.c++] = 0; } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); + blake2sCompress(ctx, true); + const out = new Uint8Array(ctx.outlen); + for(let i = 0; i < ctx.outlen; i++){ + out[i] = ctx.h[i >> 2] >> 8 * (i & 3) & 255; } + return out; } -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function() { - this.fun.apply(null, this.array); -}; -var title = "browser"; -var platform = "browser"; -var browser = true; -var argv = []; -var version2 = ""; -var versions = {}; -var release = {}; -var config = {}; -function noop() {} -var on = noop; -var addListener = noop; -var once = noop; -var off = noop; -var removeListener = noop; -var removeAllListeners = noop; -var emit = noop; -function binding(name) { - throw new Error("process.binding is not supported"); -} -function cwd() { - return "/"; -} -function chdir(dir) { - throw new Error("process.chdir is not supported"); +function blake2s(input, key, outlen) { + outlen = outlen || 32; + input = util.normalizeInput(input); + const ctx = blake2sInit(outlen, key); + blake2sUpdate(ctx, input); + return blake2sFinal(ctx); } -function umask() { - return 0; +function blake2sHex(input, key, outlen) { + const output = blake2s(input, key, outlen); + return util.toHex(output); } -var performance = globalContext.performance || {}; -var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function() { - return new Date().getTime(); +var blake2s_1 = { + blake2s, + blake2sHex, + blake2sInit, + blake2sUpdate, + blake2sFinal }; -function hrtime(previousTimestamp) { - var clocktime = performanceNow.call(performance) * 1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor(clocktime % 1 * 1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds < 0) { - seconds--; - nanoseconds += 1e9; +var blakejs = { + blake2b: blake2b_1.blake2b, + blake2bHex: blake2b_1.blake2bHex, + blake2bInit: blake2b_1.blake2bInit, + blake2bUpdate: blake2b_1.blake2bUpdate, + blake2bFinal: blake2b_1.blake2bFinal, + blake2s: blake2s_1.blake2s, + blake2sHex: blake2s_1.blake2sHex, + blake2sInit: blake2s_1.blake2sInit, + blake2sUpdate: blake2s_1.blake2sUpdate, + blake2sFinal: blake2s_1.blake2sFinal +}; +blakejs.blake2b; +function base3(ALPHABET, name) { + if (ALPHABET.length >= 255) { + throw new TypeError("Alphabet too long"); + } + var BASE_MAP = new Uint8Array(256); + for(var j = 0; j < BASE_MAP.length; j++){ + BASE_MAP[j] = 255; + } + for(var i = 0; i < ALPHABET.length; i++){ + var x = ALPHABET.charAt(i); + var xc = x.charCodeAt(0); + if (BASE_MAP[xc] !== 255) { + throw new TypeError(x + " is ambiguous"); } + BASE_MAP[xc] = i; } - return [ - seconds, - nanoseconds - ]; -} -var startTime = new Date(); -function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1e3; -} -var process = { - nextTick, - title, - browser, - env: { - NODE_ENV: "production" - }, - argv, - version: version2, - versions, - on, - addListener, - once, - off, - removeListener, - removeAllListeners, - emit, - binding, - cwd, - chdir, - umask, - hrtime, - platform, - release, - config, - uptime -}; -var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; -function createCommonjsModule1(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function(path, base) { - return commonjsRequire1(path, base === void 0 || base === null ? module.path : base); + var BASE = ALPHABET.length; + var LEADER = ALPHABET.charAt(0); + var FACTOR = Math.log(BASE) / Math.log(256); + var iFACTOR = Math.log(256) / Math.log(BASE); + function encode2(source) { + if (source instanceof Uint8Array) ; + else if (ArrayBuffer.isView(source)) { + source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength); + } else if (Array.isArray(source)) { + source = Uint8Array.from(source); } - }, fn(module, module.exports), module.exports; -} -function commonjsRequire1() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); -} -var sha3 = createCommonjsModule1(function(module) { - (function() { - var INPUT_ERROR = "input is invalid type"; - var FINALIZE_ERROR = "finalize already called"; - var WINDOW = typeof window === "object"; - var root = WINDOW ? window : {}; - if (root.JS_SHA3_NO_WINDOW) { - WINDOW = false; + if (!(source instanceof Uint8Array)) { + throw new TypeError("Expected Uint8Array"); } - var WEB_WORKER = !WINDOW && typeof self === "object"; - var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node; - if (NODE_JS) { - root = commonjsGlobal; - } else if (WEB_WORKER) { - root = self; + if (source.length === 0) { + return ""; } - var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && true && module.exports; - var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined"; - var HEX_CHARS = "0123456789abcdef".split(""); - var SHAKE_PADDING = [ - 31, - 7936, - 2031616, - 520093696 - ]; - var CSHAKE_PADDING = [ - 4, - 1024, - 262144, - 67108864 - ]; - var KECCAK_PADDING = [ - 1, - 256, - 65536, - 16777216 - ]; - var PADDING = [ - 6, - 1536, - 393216, - 100663296 - ]; - var SHIFT = [ - 0, - 8, - 16, - 24 - ]; - var RC = [ - 1, - 0, - 32898, - 0, - 32906, - 2147483648, - 2147516416, - 2147483648, - 32907, - 0, - 2147483649, - 0, - 2147516545, - 2147483648, - 32777, - 2147483648, - 138, - 0, - 136, - 0, - 2147516425, - 0, - 2147483658, - 0, - 2147516555, - 0, - 139, - 2147483648, - 32905, - 2147483648, - 32771, - 2147483648, - 32770, - 2147483648, - 128, - 2147483648, - 32778, - 0, - 2147483658, - 2147483648, - 2147516545, - 2147483648, - 32896, - 2147483648, - 2147483649, - 0, - 2147516424, - 2147483648 - ]; - var BITS = [ - 224, - 256, - 384, - 512 - ]; - var SHAKE_BITS = [ - 128, - 256 - ]; - var OUTPUT_TYPES = [ - "hex", - "buffer", - "arrayBuffer", - "array", - "digest" - ]; - var CSHAKE_BYTEPAD = { - "128": 168, - "256": 136 - }; - if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { - Array.isArray = function(obj) { - return Object.prototype.toString.call(obj) === "[object Array]"; - }; + var zeroes = 0; + var length = 0; + var pbegin = 0; + var pend = source.length; + while(pbegin !== pend && source[pbegin] === 0){ + pbegin++; + zeroes++; + } + var size = (pend - pbegin) * iFACTOR + 1 >>> 0; + var b58 = new Uint8Array(size); + while(pbegin !== pend){ + var carry = source[pbegin]; + var i2 = 0; + for(var it1 = size - 1; (carry !== 0 || i2 < length) && it1 !== -1; it1--, i2++){ + carry += 256 * b58[it1] >>> 0; + b58[it1] = carry % BASE >>> 0; + carry = carry / BASE >>> 0; + } + if (carry !== 0) { + throw new Error("Non-zero carry"); + } + length = i2; + pbegin++; } - if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { - ArrayBuffer.isView = function(obj) { - return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer; - }; + var it2 = size - length; + while(it2 !== size && b58[it2] === 0){ + it2++; } - var createOutputMethod = function(bits2, padding, outputType) { - return function(message) { - return new Keccak(bits2, padding, bits2).update(message)[outputType](); - }; - }; - var createShakeOutputMethod = function(bits2, padding, outputType) { - return function(message, outputBits) { - return new Keccak(bits2, padding, outputBits).update(message)[outputType](); - }; - }; - var createCshakeOutputMethod = function(bits2, padding, outputType) { - return function(message, outputBits, n, s) { - return methods["cshake" + bits2].update(message, outputBits, n, s)[outputType](); - }; - }; - var createKmacOutputMethod = function(bits2, padding, outputType) { - return function(key, message, outputBits, s) { - return methods["kmac" + bits2].update(key, message, outputBits, s)[outputType](); - }; - }; - var createOutputMethods = function(method, createMethod2, bits2, padding) { - for(var i2 = 0; i2 < OUTPUT_TYPES.length; ++i2){ - var type = OUTPUT_TYPES[i2]; - method[type] = createMethod2(bits2, padding, type); + var str = LEADER.repeat(zeroes); + for(; it2 < size; ++it2){ + str += ALPHABET.charAt(b58[it2]); + } + return str; + } + function decodeUnsafe(source) { + if (typeof source !== "string") { + throw new TypeError("Expected String"); + } + if (source.length === 0) { + return new Uint8Array(); + } + var psz = 0; + if (source[psz] === " ") { + return; + } + var zeroes = 0; + var length = 0; + while(source[psz] === LEADER){ + zeroes++; + psz++; + } + var size = (source.length - psz) * FACTOR + 1 >>> 0; + var b256 = new Uint8Array(size); + while(source[psz]){ + var carry = BASE_MAP[source.charCodeAt(psz)]; + if (carry === 255) { + return; } - return method; - }; - var createMethod = function(bits2, padding) { - var method = createOutputMethod(bits2, padding, "hex"); - method.create = function() { - return new Keccak(bits2, padding, bits2); - }; - method.update = function(message) { - return method.create().update(message); - }; - return createOutputMethods(method, createOutputMethod, bits2, padding); - }; - var createShakeMethod = function(bits2, padding) { - var method = createShakeOutputMethod(bits2, padding, "hex"); - method.create = function(outputBits) { - return new Keccak(bits2, padding, outputBits); - }; - method.update = function(message, outputBits) { - return method.create(outputBits).update(message); - }; - return createOutputMethods(method, createShakeOutputMethod, bits2, padding); - }; - var createCshakeMethod = function(bits2, padding) { - var w = CSHAKE_BYTEPAD[bits2]; - var method = createCshakeOutputMethod(bits2, padding, "hex"); - method.create = function(outputBits, n, s) { - if (!n && !s) { - return methods["shake" + bits2].create(outputBits); - } else { - return new Keccak(bits2, padding, outputBits).bytepad([ - n, - s - ], w); - } - }; - method.update = function(message, outputBits, n, s) { - return method.create(outputBits, n, s).update(message); - }; - return createOutputMethods(method, createCshakeOutputMethod, bits2, padding); - }; - var createKmacMethod = function(bits2, padding) { - var w = CSHAKE_BYTEPAD[bits2]; - var method = createKmacOutputMethod(bits2, padding, "hex"); - method.create = function(key, outputBits, s) { - return new Kmac(bits2, padding, outputBits).bytepad([ - "KMAC", - s - ], w).bytepad([ - key - ], w); - }; - method.update = function(key, message, outputBits, s) { - return method.create(key, outputBits, s).update(message); - }; - return createOutputMethods(method, createKmacOutputMethod, bits2, padding); - }; - var algorithms = [ - { - name: "keccak", - padding: KECCAK_PADDING, - bits: BITS, - createMethod - }, - { - name: "sha3", - padding: PADDING, - bits: BITS, - createMethod - }, - { - name: "shake", - padding: SHAKE_PADDING, - bits: SHAKE_BITS, - createMethod: createShakeMethod - }, - { - name: "cshake", - padding: CSHAKE_PADDING, - bits: SHAKE_BITS, - createMethod: createCshakeMethod - }, - { - name: "kmac", - padding: CSHAKE_PADDING, - bits: SHAKE_BITS, - createMethod: createKmacMethod + var i2 = 0; + for(var it3 = size - 1; (carry !== 0 || i2 < length) && it3 !== -1; it3--, i2++){ + carry += BASE * b256[it3] >>> 0; + b256[it3] = carry % 256 >>> 0; + carry = carry / 256 >>> 0; } - ]; - var methods = {}, methodNames = []; - for(var i = 0; i < algorithms.length; ++i){ - var algorithm = algorithms[i]; - var bits = algorithm.bits; - for(var j = 0; j < bits.length; ++j){ - var methodName = algorithm.name + "_" + bits[j]; - methodNames.push(methodName); - methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); - if (algorithm.name !== "sha3") { - var newMethodName = algorithm.name + bits[j]; - methodNames.push(newMethodName); - methods[newMethodName] = methods[methodName]; - } + if (carry !== 0) { + throw new Error("Non-zero carry"); + } + length = i2; + psz++; + } + if (source[psz] === " ") { + return; + } + var it4 = size - length; + while(it4 !== size && b256[it4] === 0){ + it4++; + } + var vch = new Uint8Array(zeroes + (size - it4)); + var j2 = zeroes; + while(it4 !== size){ + vch[j2++] = b256[it4++]; + } + return vch; + } + function decode2(string) { + var buffer = decodeUnsafe(string); + if (buffer) { + return buffer; + } + throw new Error(`Non-${name} character`); + } + return { + encode: encode2, + decodeUnsafe, + decode: decode2 + }; +} +var src2 = base3; +var _brrp__multiformats_scope_baseX2 = src2; +class Encoder2 { + constructor(name, prefix, baseEncode){ + this.name = name; + this.prefix = prefix; + this.baseEncode = baseEncode; + } + encode(bytes) { + if (bytes instanceof Uint8Array) { + return `${this.prefix}${this.baseEncode(bytes)}`; + } else { + throw Error("Unknown type, must be binary type"); + } + } +} +class Decoder2 { + constructor(name, prefix, baseDecode){ + this.name = name; + this.prefix = prefix; + if (prefix.codePointAt(0) === void 0) { + throw new Error("Invalid prefix character"); + } + this.prefixCodePoint = prefix.codePointAt(0); + this.baseDecode = baseDecode; + } + decode(text) { + if (typeof text === "string") { + if (text.codePointAt(0) !== this.prefixCodePoint) { + throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`); } + return this.baseDecode(text.slice(this.prefix.length)); + } else { + throw Error("Can only multibase decode strings"); + } + } + or(decoder) { + return or2(this, decoder); + } +} +class ComposedDecoder2 { + constructor(decoders){ + this.decoders = decoders; + } + or(decoder) { + return or2(this, decoder); + } + decode(input) { + const prefix = input[0]; + const decoder = this.decoders[prefix]; + if (decoder) { + return decoder.decode(input); + } else { + throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`); + } + } +} +const or2 = (left, right)=>new ComposedDecoder2({ + ...left.decoders || { + [left.prefix]: left + }, + ...right.decoders || { + [right.prefix]: right } - function Keccak(bits2, padding, outputBits) { - this.blocks = []; - this.s = []; - this.padding = padding; - this.outputBits = outputBits; - this.reset = true; - this.finalized = false; - this.block = 0; - this.start = 0; - this.blockCount = 1600 - (bits2 << 1) >> 5; - this.byteCount = this.blockCount << 2; - this.outputBlocks = outputBits >> 5; - this.extraBytes = (outputBits & 31) >> 3; - for(var i2 = 0; i2 < 50; ++i2){ - this.s[i2] = 0; - } + }); +class Codec2 { + constructor(name, prefix, baseEncode, baseDecode){ + this.name = name; + this.prefix = prefix; + this.baseEncode = baseEncode; + this.baseDecode = baseDecode; + this.encoder = new Encoder2(name, prefix, baseEncode); + this.decoder = new Decoder2(name, prefix, baseDecode); + } + encode(input) { + return this.encoder.encode(input); + } + decode(input) { + return this.decoder.decode(input); + } +} +const from4 = ({ name, prefix, encode: encode2, decode: decode2 })=>new Codec2(name, prefix, encode2, decode2); +const baseX2 = ({ prefix, name, alphabet })=>{ + const { encode: encode2, decode: decode2 } = _brrp__multiformats_scope_baseX2(alphabet, name); + return from4({ + prefix, + name, + encode: encode2, + decode: (text)=>coerce1(decode2(text)) + }); +}; +const decode12 = (string, alphabet, bitsPerChar, name)=>{ + const codes = {}; + for(let i = 0; i < alphabet.length; ++i){ + codes[alphabet[i]] = i; + } + let end = string.length; + while(string[end - 1] === "="){ + --end; + } + const out = new Uint8Array(end * bitsPerChar / 8 | 0); + let bits = 0; + let buffer = 0; + let written = 0; + for(let i = 0; i < end; ++i){ + const value = codes[string[i]]; + if (value === void 0) { + throw new SyntaxError(`Non-${name} character`); } - Keccak.prototype.update = function(message) { - if (this.finalized) { - throw new Error(FINALIZE_ERROR); - } - var notString, type = typeof message; - if (type !== "string") { - if (type === "object") { - if (message === null) { - throw new Error(INPUT_ERROR); - } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { - message = new Uint8Array(message); - } else if (!Array.isArray(message)) { - if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { - throw new Error(INPUT_ERROR); - } - } - } else { - throw new Error(INPUT_ERROR); - } - notString = true; - } - var blocks = this.blocks, byteCount = this.byteCount, length = message.length, blockCount = this.blockCount, index = 0, s = this.s, i2, code; - while(index < length){ - if (this.reset) { - this.reset = false; - blocks[0] = this.block; - for(i2 = 1; i2 < blockCount + 1; ++i2){ - blocks[i2] = 0; - } - } - if (notString) { - for(i2 = this.start; index < length && i2 < byteCount; ++index){ - blocks[i2 >> 2] |= message[index] << SHIFT[i2++ & 3]; - } - } else { - for(i2 = this.start; index < length && i2 < byteCount; ++index){ - code = message.charCodeAt(index); - if (code < 128) { - blocks[i2 >> 2] |= code << SHIFT[i2++ & 3]; - } else if (code < 2048) { - blocks[i2 >> 2] |= (192 | code >> 6) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; - } else if (code < 55296 || code >= 57344) { - blocks[i2 >> 2] |= (224 | code >> 12) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; - } else { - code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); - blocks[i2 >> 2] |= (240 | code >> 18) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code >> 12 & 63) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; - } - } - } - this.lastByteIndex = i2; - if (i2 >= byteCount) { - this.start = i2 - byteCount; - this.block = blocks[blockCount]; - for(i2 = 0; i2 < blockCount; ++i2){ - s[i2] ^= blocks[i2]; - } - f(s); - this.reset = true; - } else { - this.start = i2; + buffer = buffer << bitsPerChar | value; + bits += bitsPerChar; + if (bits >= 8) { + bits -= 8; + out[written++] = 255 & buffer >> bits; + } + } + if (bits >= bitsPerChar || 255 & buffer << 8 - bits) { + throw new SyntaxError("Unexpected end of data"); + } + return out; +}; +const encode11 = (data, alphabet, bitsPerChar)=>{ + const pad = alphabet[alphabet.length - 1] === "="; + const mask = (1 << bitsPerChar) - 1; + let out = ""; + let bits = 0; + let buffer = 0; + for(let i = 0; i < data.length; ++i){ + buffer = buffer << 8 | data[i]; + bits += 8; + while(bits > bitsPerChar){ + bits -= bitsPerChar; + out += alphabet[mask & buffer >> bits]; + } + } + if (bits) { + out += alphabet[mask & buffer << bitsPerChar - bits]; + } + if (pad) { + while(out.length * bitsPerChar & 7){ + out += "="; + } + } + return out; +}; +const rfc46482 = ({ name, prefix, bitsPerChar, alphabet })=>{ + return from4({ + prefix, + name, + encode (input) { + return encode11(input, alphabet, bitsPerChar); + }, + decode (input) { + return decode12(input, alphabet, bitsPerChar, name); + } + }); +}; +const base58btc2 = baseX2({ + name: "base58btc", + prefix: "z", + alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" +}); +const base58flickr2 = baseX2({ + name: "base58flickr", + prefix: "Z", + alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ" +}); +var base58 = Object.freeze({ + __proto__: null, + base58btc: base58btc2, + base58flickr: base58flickr2 +}); +const base322 = rfc46482({ + prefix: "b", + name: "base32", + alphabet: "abcdefghijklmnopqrstuvwxyz234567", + bitsPerChar: 5 +}); +const base32upper2 = rfc46482({ + prefix: "B", + name: "base32upper", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", + bitsPerChar: 5 +}); +const base32pad2 = rfc46482({ + prefix: "c", + name: "base32pad", + alphabet: "abcdefghijklmnopqrstuvwxyz234567=", + bitsPerChar: 5 +}); +const base32padupper2 = rfc46482({ + prefix: "C", + name: "base32padupper", + alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=", + bitsPerChar: 5 +}); +const base32hex2 = rfc46482({ + prefix: "v", + name: "base32hex", + alphabet: "0123456789abcdefghijklmnopqrstuv", + bitsPerChar: 5 +}); +const base32hexupper2 = rfc46482({ + prefix: "V", + name: "base32hexupper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", + bitsPerChar: 5 +}); +const base32hexpad2 = rfc46482({ + prefix: "t", + name: "base32hexpad", + alphabet: "0123456789abcdefghijklmnopqrstuv=", + bitsPerChar: 5 +}); +const base32hexpadupper2 = rfc46482({ + prefix: "T", + name: "base32hexpadupper", + alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=", + bitsPerChar: 5 +}); +const base32z2 = rfc46482({ + prefix: "h", + name: "base32z", + alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769", + bitsPerChar: 5 +}); +var base32$1 = Object.freeze({ + __proto__: null, + base32: base322, + base32upper: base32upper2, + base32pad: base32pad2, + base32padupper: base32padupper2, + base32hex: base32hex2, + base32hexupper: base32hexupper2, + base32hexpad: base32hexpad2, + base32hexpadupper: base32hexpadupper2, + base32z: base32z2 +}); +class CID2 { + constructor(version2, code, multihash, bytes){ + this.code = code; + this.version = version2; + this.multihash = multihash; + this.bytes = bytes; + this.byteOffset = bytes.byteOffset; + this.byteLength = bytes.byteLength; + this.asCID = this; + this._baseCache = new Map(); + Object.defineProperties(this, { + byteOffset: hidden1, + byteLength: hidden1, + code: readonly1, + version: readonly1, + multihash: readonly1, + bytes: readonly1, + _baseCache: hidden1, + asCID: hidden1 + }); + } + toV0() { + switch(this.version){ + case 0: + { + return this; } - } - return this; - }; - Keccak.prototype.encode = function(x, right) { - var o = x & 255, n = 1; - var bytes = [ - o - ]; - x = x >> 8; - o = x & 255; - while(o > 0){ - bytes.unshift(o); - x = x >> 8; - o = x & 255; - ++n; - } - if (right) { - bytes.push(n); - } else { - bytes.unshift(n); - } - this.update(bytes); - return bytes.length; - }; - Keccak.prototype.encodeString = function(str) { - var notString, type = typeof str; - if (type !== "string") { - if (type === "object") { - if (str === null) { - throw new Error(INPUT_ERROR); - } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) { - str = new Uint8Array(str); - } else if (!Array.isArray(str)) { - if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) { - throw new Error(INPUT_ERROR); - } + default: + { + const { code, multihash } = this; + if (code !== DAG_PB_CODE2) { + throw new Error("Cannot convert a non dag-pb CID to CIDv0"); } - } else { - throw new Error(INPUT_ERROR); - } - notString = true; - } - var bytes = 0, length = str.length; - if (notString) { - bytes = length; - } else { - for(var i2 = 0; i2 < str.length; ++i2){ - var code = str.charCodeAt(i2); - if (code < 128) { - bytes += 1; - } else if (code < 2048) { - bytes += 2; - } else if (code < 55296 || code >= 57344) { - bytes += 3; - } else { - code = 65536 + ((code & 1023) << 10 | str.charCodeAt(++i2) & 1023); - bytes += 4; + if (multihash.code !== SHA_256_CODE2) { + throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0"); } + return CID2.createV0(multihash); } - } - bytes += this.encode(bytes * 8); - this.update(str); - return bytes; - }; - Keccak.prototype.bytepad = function(strs, w) { - var bytes = this.encode(w); - for(var i2 = 0; i2 < strs.length; ++i2){ - bytes += this.encodeString(strs[i2]); - } - var paddingBytes = w - bytes % w; - var zeros = []; - zeros.length = paddingBytes; - this.update(zeros); - return this; - }; - Keccak.prototype.finalize = function() { - if (this.finalized) { - return; - } - this.finalized = true; - var blocks = this.blocks, i2 = this.lastByteIndex, blockCount = this.blockCount, s = this.s; - blocks[i2 >> 2] |= this.padding[i2 & 3]; - if (this.lastByteIndex === this.byteCount) { - blocks[0] = blocks[blockCount]; - for(i2 = 1; i2 < blockCount + 1; ++i2){ - blocks[i2] = 0; - } - } - blocks[blockCount - 1] |= 2147483648; - for(i2 = 0; i2 < blockCount; ++i2){ - s[i2] ^= blocks[i2]; - } - f(s); - }; - Keccak.prototype.toString = Keccak.prototype.hex = function() { - this.finalize(); - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; - var hex = "", block; - while(j2 < outputBlocks){ - for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ - block = s[i2]; - hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15] + HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15] + HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15] + HEX_CHARS[block >> 28 & 15] + HEX_CHARS[block >> 24 & 15]; - } - if (j2 % blockCount === 0) { - f(s); - i2 = 0; - } - } - if (extraBytes) { - block = s[i2]; - hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15]; - if (extraBytes > 1) { - hex += HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15]; - } - if (extraBytes > 2) { - hex += HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15]; + } + } + toV1() { + switch(this.version){ + case 0: + { + const { code, digest: digest$1 } = this.multihash; + const multihash = create1(code, digest$1); + return CID2.createV1(this.code, multihash); } - } - return hex; - }; - Keccak.prototype.arrayBuffer = function() { - this.finalize(); - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; - var bytes = this.outputBits >> 3; - var buffer; - if (extraBytes) { - buffer = new ArrayBuffer(outputBlocks + 1 << 2); - } else { - buffer = new ArrayBuffer(bytes); - } - var array = new Uint32Array(buffer); - while(j2 < outputBlocks){ - for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ - array[j2] = s[i2]; + case 1: + { + return this; } - if (j2 % blockCount === 0) { - f(s); + default: + { + throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`); } - } - if (extraBytes) { - array[i2] = s[i2]; - buffer = buffer.slice(0, bytes); - } - return buffer; + } + } + equals(other) { + return other && this.code === other.code && this.version === other.version && equals3(this.multihash, other.multihash); + } + toString(base) { + const { bytes, version: version2, _baseCache } = this; + switch(version2){ + case 0: + return toStringV02(bytes, _baseCache, base || base58btc2.encoder); + default: + return toStringV12(bytes, _baseCache, base || base322.encoder); + } + } + toJSON() { + return { + code: this.code, + version: this.version, + hash: this.multihash.bytes }; - Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; - Keccak.prototype.digest = Keccak.prototype.array = function() { - this.finalize(); - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; - var array = [], offset, block; - while(j2 < outputBlocks){ - for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ - offset = j2 << 2; - block = s[i2]; - array[offset] = block & 255; - array[offset + 1] = block >> 8 & 255; - array[offset + 2] = block >> 16 & 255; - array[offset + 3] = block >> 24 & 255; - } - if (j2 % blockCount === 0) { - f(s); + } + get [Symbol.toStringTag]() { + return "CID"; + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return "CID(" + this.toString() + ")"; + } + static isCID(value) { + deprecate1(/^0\.0/, IS_CID_DEPRECATION1); + return !!(value && (value[cidSymbol2] || value.asCID === value)); + } + get toBaseEncodedString() { + throw new Error("Deprecated, use .toString()"); + } + get codec() { + throw new Error('"codec" property is deprecated, use integer "code" property instead'); + } + get buffer() { + throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead"); + } + get multibaseName() { + throw new Error('"multibaseName" property is deprecated'); + } + get prefix() { + throw new Error('"prefix" property is deprecated'); + } + static asCID(value) { + if (value instanceof CID2) { + return value; + } else if (value != null && value.asCID === value) { + const { version: version2, code, multihash, bytes } = value; + return new CID2(version2, code, multihash, bytes || encodeCID2(version2, code, multihash.bytes)); + } else if (value != null && value[cidSymbol2] === true) { + const { version: version2, multihash, code } = value; + const digest$1 = decode$21(multihash); + return CID2.create(version2, code, digest$1); + } else { + return null; + } + } + static create(version2, code, digest) { + if (typeof code !== "number") { + throw new Error("String codecs are no longer supported"); + } + switch(version2){ + case 0: + { + if (code !== DAG_PB_CODE2) { + throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE2}) block encoding`); + } else { + return new CID2(version2, code, digest, digest.bytes); + } } - } - if (extraBytes) { - offset = j2 << 2; - block = s[i2]; - array[offset] = block & 255; - if (extraBytes > 1) { - array[offset + 1] = block >> 8 & 255; + case 1: + { + const bytes = encodeCID2(version2, code, digest.bytes); + return new CID2(version2, code, digest, bytes); } - if (extraBytes > 2) { - array[offset + 2] = block >> 16 & 255; + default: + { + throw new Error("Invalid version"); } - } - return array; - }; - function Kmac(bits2, padding, outputBits) { - Keccak.call(this, bits2, padding, outputBits); } - Kmac.prototype = new Keccak(); - Kmac.prototype.finalize = function() { - this.encode(this.outputBits, true); - return Keccak.prototype.finalize.call(this); + } + static createV0(digest) { + return CID2.create(0, DAG_PB_CODE2, digest); + } + static createV1(code, digest) { + return CID2.create(1, code, digest); + } + static decode(bytes) { + const [cid, remainder] = CID2.decodeFirst(bytes); + if (remainder.length) { + throw new Error("Incorrect length"); + } + return cid; + } + static decodeFirst(bytes) { + const specs = CID2.inspectBytes(bytes); + const prefixSize = specs.size - specs.multihashSize; + const multihashBytes = coerce1(bytes.subarray(prefixSize, prefixSize + specs.multihashSize)); + if (multihashBytes.byteLength !== specs.multihashSize) { + throw new Error("Incorrect length"); + } + const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize); + const digest$1 = new Digest1(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes); + const cid = specs.version === 0 ? CID2.createV0(digest$1) : CID2.createV1(specs.codec, digest$1); + return [ + cid, + bytes.subarray(specs.size) + ]; + } + static inspectBytes(initialBytes) { + let offset = 0; + const next = ()=>{ + const [i, length] = decode$11(initialBytes.subarray(offset)); + offset += length; + return i; }; - var f = function(s) { - var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; - for(n = 0; n < 48; n += 2){ - c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; - c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; - c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; - c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; - c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; - c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; - c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; - c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; - c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; - c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; - h = c8 ^ (c2 << 1 | c3 >>> 31); - l = c9 ^ (c3 << 1 | c2 >>> 31); - s[0] ^= h; - s[1] ^= l; - s[10] ^= h; - s[11] ^= l; - s[20] ^= h; - s[21] ^= l; - s[30] ^= h; - s[31] ^= l; - s[40] ^= h; - s[41] ^= l; - h = c0 ^ (c4 << 1 | c5 >>> 31); - l = c1 ^ (c5 << 1 | c4 >>> 31); - s[2] ^= h; - s[3] ^= l; - s[12] ^= h; - s[13] ^= l; - s[22] ^= h; - s[23] ^= l; - s[32] ^= h; - s[33] ^= l; - s[42] ^= h; - s[43] ^= l; - h = c2 ^ (c6 << 1 | c7 >>> 31); - l = c3 ^ (c7 << 1 | c6 >>> 31); - s[4] ^= h; - s[5] ^= l; - s[14] ^= h; - s[15] ^= l; - s[24] ^= h; - s[25] ^= l; - s[34] ^= h; - s[35] ^= l; - s[44] ^= h; - s[45] ^= l; - h = c4 ^ (c8 << 1 | c9 >>> 31); - l = c5 ^ (c9 << 1 | c8 >>> 31); - s[6] ^= h; - s[7] ^= l; - s[16] ^= h; - s[17] ^= l; - s[26] ^= h; - s[27] ^= l; - s[36] ^= h; - s[37] ^= l; - s[46] ^= h; - s[47] ^= l; - h = c6 ^ (c0 << 1 | c1 >>> 31); - l = c7 ^ (c1 << 1 | c0 >>> 31); - s[8] ^= h; - s[9] ^= l; - s[18] ^= h; - s[19] ^= l; - s[28] ^= h; - s[29] ^= l; - s[38] ^= h; - s[39] ^= l; - s[48] ^= h; - s[49] ^= l; - b0 = s[0]; - b1 = s[1]; - b32 = s[11] << 4 | s[10] >>> 28; - b33 = s[10] << 4 | s[11] >>> 28; - b14 = s[20] << 3 | s[21] >>> 29; - b15 = s[21] << 3 | s[20] >>> 29; - b46 = s[31] << 9 | s[30] >>> 23; - b47 = s[30] << 9 | s[31] >>> 23; - b28 = s[40] << 18 | s[41] >>> 14; - b29 = s[41] << 18 | s[40] >>> 14; - b20 = s[2] << 1 | s[3] >>> 31; - b21 = s[3] << 1 | s[2] >>> 31; - b2 = s[13] << 12 | s[12] >>> 20; - b3 = s[12] << 12 | s[13] >>> 20; - b34 = s[22] << 10 | s[23] >>> 22; - b35 = s[23] << 10 | s[22] >>> 22; - b16 = s[33] << 13 | s[32] >>> 19; - b17 = s[32] << 13 | s[33] >>> 19; - b48 = s[42] << 2 | s[43] >>> 30; - b49 = s[43] << 2 | s[42] >>> 30; - b40 = s[5] << 30 | s[4] >>> 2; - b41 = s[4] << 30 | s[5] >>> 2; - b22 = s[14] << 6 | s[15] >>> 26; - b23 = s[15] << 6 | s[14] >>> 26; - b4 = s[25] << 11 | s[24] >>> 21; - b5 = s[24] << 11 | s[25] >>> 21; - b36 = s[34] << 15 | s[35] >>> 17; - b37 = s[35] << 15 | s[34] >>> 17; - b18 = s[45] << 29 | s[44] >>> 3; - b19 = s[44] << 29 | s[45] >>> 3; - b10 = s[6] << 28 | s[7] >>> 4; - b11 = s[7] << 28 | s[6] >>> 4; - b42 = s[17] << 23 | s[16] >>> 9; - b43 = s[16] << 23 | s[17] >>> 9; - b24 = s[26] << 25 | s[27] >>> 7; - b25 = s[27] << 25 | s[26] >>> 7; - b6 = s[36] << 21 | s[37] >>> 11; - b7 = s[37] << 21 | s[36] >>> 11; - b38 = s[47] << 24 | s[46] >>> 8; - b39 = s[46] << 24 | s[47] >>> 8; - b30 = s[8] << 27 | s[9] >>> 5; - b31 = s[9] << 27 | s[8] >>> 5; - b12 = s[18] << 20 | s[19] >>> 12; - b13 = s[19] << 20 | s[18] >>> 12; - b44 = s[29] << 7 | s[28] >>> 25; - b45 = s[28] << 7 | s[29] >>> 25; - b26 = s[38] << 8 | s[39] >>> 24; - b27 = s[39] << 8 | s[38] >>> 24; - b8 = s[48] << 14 | s[49] >>> 18; - b9 = s[49] << 14 | s[48] >>> 18; - s[0] = b0 ^ ~b2 & b4; - s[1] = b1 ^ ~b3 & b5; - s[10] = b10 ^ ~b12 & b14; - s[11] = b11 ^ ~b13 & b15; - s[20] = b20 ^ ~b22 & b24; - s[21] = b21 ^ ~b23 & b25; - s[30] = b30 ^ ~b32 & b34; - s[31] = b31 ^ ~b33 & b35; - s[40] = b40 ^ ~b42 & b44; - s[41] = b41 ^ ~b43 & b45; - s[2] = b2 ^ ~b4 & b6; - s[3] = b3 ^ ~b5 & b7; - s[12] = b12 ^ ~b14 & b16; - s[13] = b13 ^ ~b15 & b17; - s[22] = b22 ^ ~b24 & b26; - s[23] = b23 ^ ~b25 & b27; - s[32] = b32 ^ ~b34 & b36; - s[33] = b33 ^ ~b35 & b37; - s[42] = b42 ^ ~b44 & b46; - s[43] = b43 ^ ~b45 & b47; - s[4] = b4 ^ ~b6 & b8; - s[5] = b5 ^ ~b7 & b9; - s[14] = b14 ^ ~b16 & b18; - s[15] = b15 ^ ~b17 & b19; - s[24] = b24 ^ ~b26 & b28; - s[25] = b25 ^ ~b27 & b29; - s[34] = b34 ^ ~b36 & b38; - s[35] = b35 ^ ~b37 & b39; - s[44] = b44 ^ ~b46 & b48; - s[45] = b45 ^ ~b47 & b49; - s[6] = b6 ^ ~b8 & b0; - s[7] = b7 ^ ~b9 & b1; - s[16] = b16 ^ ~b18 & b10; - s[17] = b17 ^ ~b19 & b11; - s[26] = b26 ^ ~b28 & b20; - s[27] = b27 ^ ~b29 & b21; - s[36] = b36 ^ ~b38 & b30; - s[37] = b37 ^ ~b39 & b31; - s[46] = b46 ^ ~b48 & b40; - s[47] = b47 ^ ~b49 & b41; - s[8] = b8 ^ ~b0 & b2; - s[9] = b9 ^ ~b1 & b3; - s[18] = b18 ^ ~b10 & b12; - s[19] = b19 ^ ~b11 & b13; - s[28] = b28 ^ ~b20 & b22; - s[29] = b29 ^ ~b21 & b23; - s[38] = b38 ^ ~b30 & b32; - s[39] = b39 ^ ~b31 & b33; - s[48] = b48 ^ ~b40 & b42; - s[49] = b49 ^ ~b41 & b43; - s[0] ^= RC[n]; - s[1] ^= RC[n + 1]; - } + let version2 = next(); + let codec = DAG_PB_CODE2; + if (version2 === 18) { + version2 = 0; + offset = 0; + } else if (version2 === 1) { + codec = next(); + } + if (version2 !== 0 && version2 !== 1) { + throw new RangeError(`Invalid CID version ${version2}`); + } + const prefixSize = offset; + const multihashCode = next(); + const digestSize = next(); + const size = offset + digestSize; + const multihashSize = size - prefixSize; + return { + version: version2, + codec, + multihashCode, + digestSize, + multihashSize, + size }; - if (COMMON_JS) { - module.exports = methods; - } else { - for(i = 0; i < methodNames.length; ++i){ - root[methodNames[i]] = methods[methodNames[i]]; + } + static parse(source, base) { + const [prefix, bytes] = parseCIDtoBytes2(source, base); + const cid = CID2.decode(bytes); + cid._baseCache.set(prefix, source); + return cid; + } +} +const parseCIDtoBytes2 = (source, base)=>{ + switch(source[0]){ + case "Q": + { + const decoder = base || base58btc2; + return [ + base58btc2.prefix, + decoder.decode(`${base58btc2.prefix}${source}`) + ]; } - } - })(); + case base58btc2.prefix: + { + const decoder = base || base58btc2; + return [ + base58btc2.prefix, + decoder.decode(source) + ]; + } + case base322.prefix: + { + const decoder = base || base322; + return [ + base322.prefix, + decoder.decode(source) + ]; + } + default: + { + if (base == null) { + throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided"); + } + return [ + source[0], + base.decode(source) + ]; + } + } +}; +const toStringV02 = (bytes, cache, base)=>{ + const { prefix } = base; + if (prefix !== base58btc2.prefix) { + throw Error(`Cannot string encode V0 in ${base.name} encoding`); + } + const cid = cache.get(prefix); + if (cid == null) { + const cid2 = base.encode(bytes).slice(1); + cache.set(prefix, cid2); + return cid2; + } else { + return cid; + } +}; +const toStringV12 = (bytes, cache, base)=>{ + const { prefix } = base; + const cid = cache.get(prefix); + if (cid == null) { + const cid2 = base.encode(bytes); + cache.set(prefix, cid2); + return cid2; + } else { + return cid; + } +}; +const DAG_PB_CODE2 = 112; +const SHA_256_CODE2 = 18; +const encodeCID2 = (version2, code, multihash)=>{ + const codeOffset = encodingLength1(version2); + const hashOffset = codeOffset + encodingLength1(code); + const bytes = new Uint8Array(hashOffset + multihash.byteLength); + encodeTo1(version2, bytes, 0); + encodeTo1(code, bytes, codeOffset); + bytes.set(multihash, hashOffset); + return bytes; +}; +const cidSymbol2 = Symbol.for("@ipld/js-cid/CID"); +const readonly1 = { + writable: false, + configurable: false, + enumerable: true +}; +const hidden1 = { + writable: false, + enumerable: false, + configurable: false +}; +const version28 = "0.0.0-dev"; +const deprecate1 = (range, message)=>{ + if (range.test(version28)) { + console.warn(message); + } else { + throw new Error(message); + } +}; +const IS_CID_DEPRECATION1 = `CID.isCID(v) is deprecated and will be removed in the next major release. +Following code pattern: + +if (CID.isCID(value)) { + doSomethingWithCID(value) +} + +Is replaced with: + +const cid = CID.asCID(value) +if (cid) { + // Make sure to use cid instead of value + doSomethingWithCID(cid) +} +`; +const { blake2b: blake2b1 } = blakejs; +const blake2b8 = from1({ + name: "blake2b-8", + code: 45569, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 1)) +}); +const blake2b16 = from1({ + name: "blake2b-16", + code: 45570, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 2)) +}); +const blake2b24 = from1({ + name: "blake2b-24", + code: 45571, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 3)) +}); +const blake2b32 = from1({ + name: "blake2b-32", + code: 45572, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 4)) +}); +const blake2b40 = from1({ + name: "blake2b-40", + code: 45573, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 5)) +}); +const blake2b48 = from1({ + name: "blake2b-48", + code: 45574, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 6)) +}); +const blake2b56 = from1({ + name: "blake2b-56", + code: 45575, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 7)) +}); +const blake2b64 = from1({ + name: "blake2b-64", + code: 45576, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 8)) +}); +const blake2b72 = from1({ + name: "blake2b-72", + code: 45577, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 9)) +}); +const blake2b80 = from1({ + name: "blake2b-80", + code: 45578, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 10)) +}); +const blake2b88 = from1({ + name: "blake2b-88", + code: 45579, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 11)) +}); +const blake2b96 = from1({ + name: "blake2b-96", + code: 45580, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 12)) +}); +const blake2b104 = from1({ + name: "blake2b-104", + code: 45581, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 13)) +}); +const blake2b112 = from1({ + name: "blake2b-112", + code: 45582, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 14)) +}); +const blake2b120 = from1({ + name: "blake2b-120", + code: 45583, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 15)) +}); +const blake2b128 = from1({ + name: "blake2b-128", + code: 45584, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 16)) +}); +const blake2b136 = from1({ + name: "blake2b-136", + code: 45585, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 17)) +}); +const blake2b144 = from1({ + name: "blake2b-144", + code: 45586, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 18)) +}); +const blake2b152 = from1({ + name: "blake2b-152", + code: 45587, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 19)) +}); +const blake2b160 = from1({ + name: "blake2b-160", + code: 45588, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 20)) +}); +const blake2b168 = from1({ + name: "blake2b-168", + code: 45589, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 21)) +}); +const blake2b176 = from1({ + name: "blake2b-176", + code: 45590, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 22)) +}); +const blake2b184 = from1({ + name: "blake2b-184", + code: 45591, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 23)) +}); +const blake2b192 = from1({ + name: "blake2b-192", + code: 45592, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 24)) +}); +const blake2b200 = from1({ + name: "blake2b-200", + code: 45593, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 25)) +}); +const blake2b208 = from1({ + name: "blake2b-208", + code: 45594, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 26)) +}); +const blake2b216 = from1({ + name: "blake2b-216", + code: 45595, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 27)) +}); +const blake2b224 = from1({ + name: "blake2b-224", + code: 45596, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 28)) +}); +const blake2b232 = from1({ + name: "blake2b-232", + code: 45597, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 29)) +}); +const blake2b240 = from1({ + name: "blake2b-240", + code: 45598, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 30)) +}); +const blake2b248 = from1({ + name: "blake2b-248", + code: 45599, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 31)) +}); +const blake2b256 = from1({ + name: "blake2b-256", + code: 45600, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 32)) +}); +const blake2b264 = from1({ + name: "blake2b-264", + code: 45601, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 33)) +}); +const blake2b272 = from1({ + name: "blake2b-272", + code: 45602, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 34)) +}); +const blake2b280 = from1({ + name: "blake2b-280", + code: 45603, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 35)) +}); +const blake2b288 = from1({ + name: "blake2b-288", + code: 45604, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 36)) +}); +const blake2b296 = from1({ + name: "blake2b-296", + code: 45605, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 37)) +}); +const blake2b304 = from1({ + name: "blake2b-304", + code: 45606, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 38)) +}); +const blake2b312 = from1({ + name: "blake2b-312", + code: 45607, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 39)) +}); +const blake2b320 = from1({ + name: "blake2b-320", + code: 45608, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 40)) +}); +const blake2b328 = from1({ + name: "blake2b-328", + code: 45609, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 41)) +}); +const blake2b336 = from1({ + name: "blake2b-336", + code: 45610, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 42)) +}); +const blake2b344 = from1({ + name: "blake2b-344", + code: 45611, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 43)) +}); +const blake2b352 = from1({ + name: "blake2b-352", + code: 45612, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 44)) +}); +const blake2b360 = from1({ + name: "blake2b-360", + code: 45613, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 45)) +}); +const blake2b368 = from1({ + name: "blake2b-368", + code: 45614, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 46)) +}); +const blake2b376 = from1({ + name: "blake2b-376", + code: 45615, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 47)) +}); +const blake2b384 = from1({ + name: "blake2b-384", + code: 45616, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 48)) +}); +const blake2b392 = from1({ + name: "blake2b-392", + code: 45617, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 49)) +}); +const blake2b400 = from1({ + name: "blake2b-400", + code: 45618, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 50)) +}); +const blake2b408 = from1({ + name: "blake2b-408", + code: 45619, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 51)) +}); +const blake2b416 = from1({ + name: "blake2b-416", + code: 45620, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 52)) +}); +const blake2b424 = from1({ + name: "blake2b-424", + code: 45621, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 53)) +}); +const blake2b432 = from1({ + name: "blake2b-432", + code: 45622, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 54)) +}); +const blake2b440 = from1({ + name: "blake2b-440", + code: 45623, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 55)) +}); +const blake2b448 = from1({ + name: "blake2b-448", + code: 45624, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 56)) +}); +const blake2b456 = from1({ + name: "blake2b-456", + code: 45625, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 57)) +}); +const blake2b464 = from1({ + name: "blake2b-464", + code: 45626, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 58)) +}); +const blake2b472 = from1({ + name: "blake2b-472", + code: 45627, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 59)) +}); +const blake2b480 = from1({ + name: "blake2b-480", + code: 45628, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 60)) +}); +const blake2b488 = from1({ + name: "blake2b-488", + code: 45629, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 61)) +}); +const blake2b496 = from1({ + name: "blake2b-496", + code: 45630, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 62)) +}); +const blake2b504 = from1({ + name: "blake2b-504", + code: 45631, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 63)) +}); +const blake2b512 = from1({ + name: "blake2b-512", + code: 45632, + encode: (input)=>bytes.coerce(blake2b1(input, void 0, 64)) +}); +Object.freeze({ + __proto__: null, + blake2b8, + blake2b16, + blake2b24, + blake2b32, + blake2b40, + blake2b48, + blake2b56, + blake2b64, + blake2b72, + blake2b80, + blake2b88, + blake2b96, + blake2b104, + blake2b112, + blake2b120, + blake2b128, + blake2b136, + blake2b144, + blake2b152, + blake2b160, + blake2b168, + blake2b176, + blake2b184, + blake2b192, + blake2b200, + blake2b208, + blake2b216, + blake2b224, + blake2b232, + blake2b240, + blake2b248, + blake2b256, + blake2b264, + blake2b272, + blake2b280, + blake2b288, + blake2b296, + blake2b304, + blake2b312, + blake2b320, + blake2b328, + blake2b336, + blake2b344, + blake2b352, + blake2b360, + blake2b368, + blake2b376, + blake2b384, + blake2b392, + blake2b400, + blake2b408, + blake2b416, + blake2b424, + blake2b432, + blake2b440, + blake2b448, + blake2b456, + blake2b464, + blake2b472, + blake2b480, + blake2b488, + blake2b496, + blake2b504, + blake2b512 +}); +const { blake2s: blake2s1 } = blakejs; +const blake2s8 = from1({ + name: "blake2s-8", + code: 45633, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 1)) +}); +const blake2s16 = from1({ + name: "blake2s-16", + code: 45634, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 2)) +}); +const blake2s24 = from1({ + name: "blake2s-24", + code: 45635, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 3)) +}); +const blake2s32 = from1({ + name: "blake2s-32", + code: 45636, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 4)) +}); +const blake2s40 = from1({ + name: "blake2s-40", + code: 45637, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 5)) +}); +const blake2s48 = from1({ + name: "blake2s-48", + code: 45638, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 6)) +}); +const blake2s56 = from1({ + name: "blake2s-56", + code: 45639, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 7)) +}); +const blake2s64 = from1({ + name: "blake2s-64", + code: 45640, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 8)) +}); +const blake2s72 = from1({ + name: "blake2s-72", + code: 45641, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 9)) +}); +const blake2s80 = from1({ + name: "blake2s-80", + code: 45642, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 10)) +}); +const blake2s88 = from1({ + name: "blake2s-88", + code: 45643, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 11)) +}); +const blake2s96 = from1({ + name: "blake2s-96", + code: 45644, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 12)) +}); +const blake2s104 = from1({ + name: "blake2s-104", + code: 45645, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 13)) +}); +const blake2s112 = from1({ + name: "blake2s-112", + code: 45646, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 14)) +}); +const blake2s120 = from1({ + name: "blake2s-120", + code: 45647, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 15)) +}); +const blake2s128 = from1({ + name: "blake2s-128", + code: 45648, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 16)) +}); +const blake2s136 = from1({ + name: "blake2s-136", + code: 45649, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 17)) +}); +const blake2s144 = from1({ + name: "blake2s-144", + code: 45650, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 18)) +}); +const blake2s152 = from1({ + name: "blake2s-152", + code: 45651, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 19)) +}); +const blake2s160 = from1({ + name: "blake2s-160", + code: 45652, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 20)) +}); +const blake2s168 = from1({ + name: "blake2s-168", + code: 45653, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 21)) +}); +const blake2s176 = from1({ + name: "blake2s-176", + code: 45654, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 22)) +}); +const blake2s184 = from1({ + name: "blake2s-184", + code: 45655, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 23)) +}); +const blake2s192 = from1({ + name: "blake2s-192", + code: 45656, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 24)) +}); +const blake2s200 = from1({ + name: "blake2s-200", + code: 45657, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 25)) +}); +const blake2s208 = from1({ + name: "blake2s-208", + code: 45658, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 26)) +}); +const blake2s216 = from1({ + name: "blake2s-216", + code: 45659, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 27)) +}); +const blake2s224 = from1({ + name: "blake2s-224", + code: 45660, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 28)) +}); +const blake2s232 = from1({ + name: "blake2s-232", + code: 45661, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 29)) +}); +const blake2s240 = from1({ + name: "blake2s-240", + code: 45662, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 30)) +}); +const blake2s248 = from1({ + name: "blake2s-248", + code: 45663, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 31)) +}); +const blake2s256 = from1({ + name: "blake2s-256", + code: 45664, + encode: (input)=>bytes.coerce(blake2s1(input, void 0, 32)) +}); +Object.freeze({ + __proto__: null, + blake2s8, + blake2s16, + blake2s24, + blake2s32, + blake2s40, + blake2s48, + blake2s56, + blake2s64, + blake2s72, + blake2s80, + blake2s88, + blake2s96, + blake2s104, + blake2s112, + blake2s120, + blake2s128, + blake2s136, + blake2s144, + blake2s152, + blake2s160, + blake2s168, + blake2s176, + blake2s184, + blake2s192, + blake2s200, + blake2s208, + blake2s216, + blake2s224, + blake2s232, + blake2s240, + blake2s248, + blake2s256 }); -sha3.cshake128; -sha3.cshake256; -sha3.cshake_128; -sha3.cshake_256; -sha3.keccak224; -sha3.keccak256; -sha3.keccak384; -sha3.keccak512; -sha3.keccak_224; -sha3.keccak_256; -sha3.keccak_384; -sha3.keccak_512; -sha3.kmac128; -sha3.kmac256; -sha3.kmac_128; -sha3.kmac_256; -sha3.sha3_224; -sha3.sha3_256; -sha3.sha3_384; -sha3.sha3_512; -sha3.shake128; -sha3.shake256; -sha3.shake_128; -sha3.shake_256; function encoder1(fn) { return (b)=>new Uint8Array(fn.array(b)); } @@ -7951,7 +33080,7 @@ const keccak224 = from1({ name: "keccak-224", encode: encoder1(sha3.keccak224) }); -const keccak256 = from1({ +const keccak2561 = from1({ code: 27, name: "keccak-256", encode: encoder1(sha3.keccak256) @@ -8089,13 +33218,13 @@ const alphabetCharsToBytes = alphabet.reduce((p, c, i)=>{ p[c.codePointAt(0)] = i; return p; }, []); -function encode9(data) { +function encode12(data) { return data.reduce((p, c)=>{ p += alphabetBytesToChars[c]; return p; }, ""); } -function decode10(str) { +function decode13(str) { const byts = []; for (const __char of str){ const byt = alphabetCharsToBytes[__char.codePointAt(0)]; @@ -8109,8 +33238,8 @@ function decode10(str) { const base256emoji = from4({ prefix: "\u{1F680}", name: "base256emoji", - encode: encode9, - decode: decode10 + encode: encode12, + decode: decode13 }); var base256emoji$1 = Object.freeze({ __proto__: null, @@ -8129,26 +33258,26 @@ var identity$1 = Object.freeze({ identity: identity1 }); const name1 = "raw"; -const encode10 = (node)=>coerce1(node); -const decode11 = (data)=>coerce1(data); +const encode13 = (node)=>coerce1(node); +const decode14 = (data)=>coerce1(data); Object.freeze({ __proto__: null, name: name1, code: 85, - encode: encode10, - decode: decode11 + encode: encode13, + decode: decode14 }); const textEncoder1 = new TextEncoder(); const textDecoder2 = new TextDecoder(); const name2 = "json"; -const encode11 = (node)=>textEncoder1.encode(JSON.stringify(node)); -const decode12 = (data)=>JSON.parse(textDecoder2.decode(data)); +const encode14 = (node)=>textEncoder1.encode(JSON.stringify(node)); +const decode15 = (data)=>JSON.parse(textDecoder2.decode(data)); Object.freeze({ __proto__: null, name: name2, code: 512, - encode: encode11, - decode: decode12 + encode: encode14, + decode: decode15 }); const bases = { ...identityBase, @@ -8163,7 +33292,7 @@ const bases = { ...base256emoji$1 }; ({ - ...sha2, + ...sha21, ...identity$1 }); function createCodec(name, prefix, encode, decode) { @@ -8225,8 +33354,8 @@ function equals6(a, b) { return true; } const hashMap = new Map([ - sha256, - sha512, + sha2563, + sha5122, murmur3128, murmur332, blake2b256, @@ -8238,7 +33367,7 @@ const hashMap = new Map([ shake128, shake256, keccak224, - keccak256, + keccak2561, keccak384, keccak512 ].map((hash)=>[ @@ -8281,7 +33410,7 @@ function e(t, e = !0) { if (t.destroyed) throw new Error("Hash instance has been destroyed"); if (e && t.finished) throw new Error("Hash#digest() has already been called"); } -const s = (t)=>new DataView(t.buffer, t.byteOffset, t.byteLength), n = (t, e)=>t << 32 - e | t >>> e; +const s1 = (t)=>new DataView(t.buffer, t.byteOffset, t.byteLength), n = (t, e)=>t << 32 - e | t >>> e; function i(e) { return "string" == typeof e && (e = function(t) { if ("string" != typeof t) throw new Error("utf8ToBytes expected string, got " + typeof t); @@ -8291,7 +33420,7 @@ function i(e) { new Uint8Array(new Uint32Array([ 287454020 ]).buffer)[0]; -class r { +class r2 { clone() { return this._cloneInto(); } @@ -8301,9 +33430,9 @@ function o1(t) { return e.outputLen = s.outputLen, e.blockLen = s.blockLen, e.create = ()=>t(), e; } const h = (t, e, s)=>t & e ^ t & s ^ e & s; -class f extends r { +class f1 extends r2 { constructor(t, e, n, i){ - super(), this.blockLen = t, this.outputLen = e, this.padOffset = n, this.isLE = i, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(t), this.view = s(this.buffer); + super(), this.blockLen = t, this.outputLen = e, this.padOffset = n, this.isLE = i, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(t), this.view = s1(this.buffer); } update(t) { e(this); @@ -8312,7 +33441,7 @@ class f extends r { const i = Math.min(o - this.pos, h - e); if (i !== o) r.set(t.subarray(e, e + i), this.pos), this.pos += i, e += i, this.pos === o && (this.process(n, 0), this.pos = 0); else { - const n = s(t); + const n = s1(t); for(; o <= h - e; e += o)this.process(n, e); } } @@ -8333,7 +33462,7 @@ class f extends r { const i = BigInt(32), r = BigInt(4294967295), o = Number(s >> i & r), h = Number(s & r), f = n ? 4 : 0, u = n ? 0 : 4; t.setUint32(e + f, o, n), t.setUint32(e + u, h, n); }(r, o - 8, BigInt(8 * this.length), h), this.process(r, 0); - const u = s(n), c = this.outputLen; + const u = s1(n), c = this.outputLen; if (c % 4) throw new Error("_sha2: outputLen should be aligned to 32bit"); const l = c / 4, a = this.get(); if (l > a.length) throw new Error("_sha2: outputLen bigger than state"); @@ -8426,7 +33555,7 @@ const u = new Uint32Array([ 528734635, 1541459225 ]), l = new Uint32Array(64); -class a extends f { +class a extends f1 { constructor(){ super(64, 32, 8, !1), this.A = 0 | c[0], this.B = 0 | c[1], this.C = 0 | c[2], this.D = 0 | c[3], this.E = 0 | c[4], this.F = 0 | c[5], this.G = 0 | c[6], this.H = 0 | c[7]; } @@ -8483,12 +33612,12 @@ function O(e = 32) { if (o && "function" == typeof o.getRandomValues) return o.getRandomValues(new Uint8Array(e)); throw new Error("crypto.getRandomValues must be defined"); } -const c1 = BigInt(0), a1 = BigInt(1), f1 = BigInt(2); -function r1(e) { +const c1 = BigInt(0), a1 = BigInt(1), f2 = BigInt(2); +function r3(e) { return e instanceof Uint8Array || null != e && "object" == typeof e && "Uint8Array" === e.constructor.name; } function n1(e) { - if (!r1(e)) throw new Error("Uint8Array expected"); + if (!r3(e)) throw new Error("Uint8Array expected"); } const d1 = Array.from({ length: 256 @@ -8511,7 +33640,7 @@ const b = { _a: 97, _f: 102 }; -function s1(e) { +function s2(e) { return e >= b._0 && e <= b._9 ? e - b._0 : e >= b._A && e <= b._F ? e - (b._A - 10) : e >= b._a && e <= b._f ? e - (b._a - 10) : void 0; } function u1(e) { @@ -8520,7 +33649,7 @@ function u1(e) { if (t % 2) throw new Error("padded hex string expected, got unpadded hex of length " + t); const a = new Uint8Array(c); for(let t = 0, f = 0; t < c; t++, f += 2){ - const c = s1(e.charCodeAt(f)), r = s1(e.charCodeAt(f + 1)); + const c = s2(e.charCodeAt(f)), r = s2(e.charCodeAt(f + 1)); if (void 0 === c || void 0 === r) { const t = e[f] + e[f + 1]; throw new Error('hex string expected, got non-hex character "' + t + '" at index ' + f); @@ -8549,7 +33678,7 @@ function y(e, t, c) { throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${c}`); } else { - if (!r1(t)) throw new Error(`${e} must be hex string or Uint8Array`); + if (!r3(t)) throw new Error(`${e} must be hex string or Uint8Array`); a = Uint8Array.from(t); } const f = a.length; @@ -8569,7 +33698,7 @@ function B(...e) { } return c; } -function x(e) { +function x1(e) { if ("string" != typeof e) throw new Error("utf8ToBytes expected string, got " + typeof e); return new Uint8Array((new TextEncoder).encode(e)); } @@ -8581,12 +33710,12 @@ function E(e) { function h1(e, t) { return e >> BigInt(t) & a1; } -const w = (e)=>(f1 << BigInt(e - 1)) - a1, v1 = { +const w = (e)=>(f2 << BigInt(e - 1)) - a1, v1 = { bigint: (e)=>"bigint" == typeof e, function: (e)=>"function" == typeof e, boolean: (e)=>"boolean" == typeof e, string: (e)=>"string" == typeof e, - stringOrUint8Array: (e)=>"string" == typeof e || r1(e), + stringOrUint8Array: (e)=>"string" == typeof e || r3(e), isSafeInteger: (e)=>Number.isSafeInteger(e), array: (e)=>Array.isArray(e), field: (e, t)=>t.Fp.isValid(e), @@ -8604,7 +33733,7 @@ function I(e, t, c = {}) { return e; } const O1 = BigInt(0), S = BigInt(1), R = BigInt(2), q = BigInt(3), P = BigInt(4), T = BigInt(5), A = BigInt(8); -function N(e, t) { +function N10(e, t) { const c = e % t; return c >= O1 ? c : t + c; } @@ -8617,13 +33746,13 @@ function Z(e, t, c) { } function _(e, t) { if (e === O1 || t <= O1) throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`); - let c = N(e, t), a = t, f = O1, r = S; + let c = N10(e, t), a = t, f = O1, r = S; for(; c !== O1;){ const e = a % c, t = f - r * (a / c); a = c, c = e, f = r, r = t; } if (a !== S) throw new Error("invert: does not exist"); - return N(f, t); + return N10(f, t); } function j(e) { if (e % P === q) { @@ -8728,21 +33857,21 @@ function U(e, t, c = !1, a = {}) { MASK: w(f), ZERO: O1, ONE: S, - create: (t)=>N(t, e), + create: (t)=>N10(t, e), isValid: (t)=>{ if ("bigint" != typeof t) throw new Error("Invalid field element: expected bigint, got " + typeof t); return O1 <= t && t < e; }, is0: (e)=>e === O1, isOdd: (e)=>(e & S) === S, - neg: (t)=>N(-t, e), + neg: (t)=>N10(-t, e), eql: (e, t)=>e === t, - sqr: (t)=>N(t * t, e), - add: (t, c)=>N(t + c, e), - sub: (t, c)=>N(t - c, e), - mul: (t, c)=>N(t * c, e), + sqr: (t)=>N10(t * t, e), + add: (t, c)=>N10(t + c, e), + sub: (t, c)=>N10(t - c, e), + mul: (t, c)=>N10(t * c, e), pow: (e, t)=>D(d, e, t), - div: (t, c)=>N(t * _(c, e), e), + div: (t, c)=>N10(t * _(c, e), e), sqrN: (e)=>e * e, addN: (e, t)=>e + t, subN: (e, t)=>e - t, @@ -8777,12 +33906,12 @@ function $(e, t) { for(let a = t - 1; a >= 0; a--)c[a] = 255 & e, e >>>= 8; return new Uint8Array(c); } -function z(e, t) { +function z1(e, t) { const c = new Uint8Array(e.length); for(let a = 0; a < e.length; a++)c[a] = e[a] ^ t[a]; return c; } -function K(e) { +function K1(e) { if (!Number.isSafeInteger(e)) throw new Error("number expected"); } function k(e, t, c) { @@ -8794,18 +33923,18 @@ function k(e, t, c) { hash: "hash" }); const { p: a, k: f, m: r, hash: d, expand: i, DST: o } = c; - n1(e), K(t); - const b = "string" == typeof o ? x(o) : o, s = a.toString(2).length, u = Math.ceil((s + f) / 8), l = t * r * u; + n1(e), K1(t); + const b = "string" == typeof o ? x1(o) : o, s = a.toString(2).length, u = Math.ceil((s + f) / 8), l = t * r * u; let m; if ("xmd" === i) m = function(e, t, c, a) { - n1(e), n1(t), K(c), t.length > 255 && (t = a(B(x("H2C-OVERSIZE-DST-"), t))); + n1(e), n1(t), K1(c), t.length > 255 && (t = a(B(x1("H2C-OVERSIZE-DST-"), t))); const { outputLen: f, blockLen: r } = a, d = Math.ceil(c / f); if (d > 255) throw new Error("Invalid xmd length"); const i = B(t, $(t.length, 1)), o = $(0, r), b = $(c, 2), s = new Array(d), u = a(B(o, e, b, $(0, 1), i)); s[0] = a(B(u, $(1, 1), i)); for(let e = 1; e <= d; e++){ const t = [ - z(u, s[e - 1]), + z1(u, s[e - 1]), $(e + 1, 1), i ]; @@ -8814,11 +33943,11 @@ function k(e, t, c) { return B(...s).slice(0, c); }(e, b, l, d); else if ("xof" === i) m = function(e, t, c, a, f) { - if (n1(e), n1(t), K(c), t.length > 255) { + if (n1(e), n1(t), K1(c), t.length > 255) { const e = Math.ceil(2 * a / 8); t = f.create({ dkLen: e - }).update(x("H2C-OVERSIZE-DST-")).update(t).digest(); + }).update(x1("H2C-OVERSIZE-DST-")).update(t).digest(); } if (c > 65535 || t.length > 255) throw new Error("expand_message_xof: invalid lenInBytes"); return f.create({ @@ -8834,7 +33963,7 @@ function k(e, t, c) { const t = new Array(r); for(let c = 0; c < r; c++){ const f = u * (c + e * r), n = m.subarray(f, f + u); - t[c] = N(L(n), a); + t[c] = N10(L(n), a); } p[e] = t; } @@ -8943,7 +34072,7 @@ function re(e) { function b(e) { const { allowedPrivateKeyLengths: c, nByteLength: a, wrapPrivateKey: f, n: n } = t; if (c && "bigint" != typeof e) { - if (r1(e) && (e = i1(e)), "string" != typeof e || !c.includes(e.length)) throw new Error("Invalid key"); + if (r3(e) && (e = i1(e)), "string" != typeof e || !c.includes(e.length)) throw new Error("Invalid key"); e = e.padStart(2 * a, "0"); } let d; @@ -8952,7 +34081,7 @@ function re(e) { } catch (t) { throw new Error(`private key must be ${a} bytes, hex or bigint, not ${typeof e}`); } - return f && (d = N(d, n)), o(d), d; + return f && (d = N10(d, n)), o(d), d; } const s = new Map; function u(e) { @@ -10006,7 +35135,7 @@ const it = function(e) { return function(e, t, c = !1) { const a = e.length, f = C(t), r = Y(t); if (a < 16 || a < r || a > 1024) throw new Error(`expected ${r}-1024 bytes of input, got ${a}`); - const n = N(c ? l1(e) : m1(e), t - S) + S; + const n = N10(c ? l1(e) : m1(e), t - S) + S; return c ? g1(n, f) : p1(n, f); }(e.randomBytes(t), c.ORDER); }, @@ -10356,26 +35485,29 @@ const it = function(e) { hash: d, randomBytes: O }); +"object" == typeof globalThis && "crypto" in globalThis ? globalThis.crypto : void 0; function t1(t11, ...e) { - if (!((s = t11) instanceof Uint8Array || null != s && "object" == typeof s && "Uint8Array" === s.constructor.name)) throw new Error("Uint8Array expected"); + if (!((s = t11) instanceof Uint8Array || ArrayBuffer.isView(s) && "Uint8Array" === s.constructor.name)) throw new Error("Uint8Array expected"); var s; - if (e.length > 0 && !e.includes(t11.length)) throw new Error(`Uint8Array expected of length ${e}, not of length=${t11.length}`); + if (e.length > 0 && !e.includes(t11.length)) throw new Error("Uint8Array expected of length " + e + ", got length=" + t11.length); } function e1(t, e = !0) { if (t.destroyed) throw new Error("Hash instance has been destroyed"); if (e && t.finished) throw new Error("Hash#digest() has already been called"); } -const s2 = (t)=>new DataView(t.buffer, t.byteOffset, t.byteLength), n2 = (t, e)=>t << 32 - e | t >>> e; +function s3(t) { + return new DataView(t.buffer, t.byteOffset, t.byteLength); +} +function n2(t, e) { + return t << 32 - e | t >>> e; +} function i2(e) { return "string" == typeof e && (e = function(t) { if ("string" != typeof t) throw new Error("utf8ToBytes expected string, got " + typeof t); return new Uint8Array((new TextEncoder).encode(t)); }(e)), t1(e), e; } -new Uint8Array(new Uint32Array([ - 287454020 -]).buffer)[0]; -class r2 { +class r4 { clone() { return this._cloneInto(); } @@ -10384,10 +35516,12 @@ function o3(t) { const e = (e)=>t().update(i2(e)).digest(), s = t(); return e.outputLen = s.outputLen, e.blockLen = s.blockLen, e.create = ()=>t(), e; } -const h2 = (t, e, s)=>t & e ^ t & s ^ e & s; -class f2 extends r2 { +function h2(t, e, s) { + return t & e ^ t & s ^ e & s; +} +class u2 extends r4 { constructor(t, e, n, i){ - super(), this.blockLen = t, this.outputLen = e, this.padOffset = n, this.isLE = i, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(t), this.view = s2(this.buffer); + super(), this.blockLen = t, this.outputLen = e, this.padOffset = n, this.isLE = i, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(t), this.view = s3(this.buffer); } update(t) { e1(this); @@ -10396,7 +35530,7 @@ class f2 extends r2 { const i = Math.min(o - this.pos, h - e); if (i !== o) r.set(t.subarray(e, e + i), this.pos), this.pos += i, e += i, this.pos === o && (this.process(n, 0), this.pos = 0); else { - const n = s2(t); + const n = s3(t); for(; o <= h - e; e += o)this.process(n, e); } } @@ -10406,22 +35540,22 @@ class f2 extends r2 { e1(this), function(e, s) { t1(e); const n = s.outputLen; - if (e.length < n) throw new Error(`digestInto() expects output buffer of length at least ${n}`); + if (e.length < n) throw new Error("digestInto() expects output buffer of length at least " + n); }(n, this), this.finished = !0; const { buffer: i, view: r, blockLen: o, isLE: h } = this; - let { pos: f } = this; - i[f++] = 128, this.buffer.subarray(f).fill(0), this.padOffset > o - f && (this.process(r, 0), f = 0); - for(let t = f; t < o; t++)i[t] = 0; + let { pos: u } = this; + i[u++] = 128, this.buffer.subarray(u).fill(0), this.padOffset > o - u && (this.process(r, 0), u = 0); + for(let t = u; t < o; t++)i[t] = 0; !function(t, e, s, n) { if ("function" == typeof t.setBigUint64) return t.setBigUint64(e, s, n); - const i = BigInt(32), r = BigInt(4294967295), o = Number(s >> i & r), h = Number(s & r), f = n ? 4 : 0, u = n ? 0 : 4; - t.setUint32(e + f, o, n), t.setUint32(e + u, h, n); + const i = BigInt(32), r = BigInt(4294967295), o = Number(s >> i & r), h = Number(s & r), u = n ? 4 : 0, f = n ? 0 : 4; + t.setUint32(e + u, o, n), t.setUint32(e + f, h, n); }(r, o - 8, BigInt(8 * this.length), h), this.process(r, 0); - const u = s2(n), c = this.outputLen; + const f = s3(n), c = this.outputLen; if (c % 4) throw new Error("_sha2: outputLen should be aligned to 32bit"); const l = c / 4, a = this.get(); if (l > a.length) throw new Error("_sha2: outputLen bigger than state"); - for(let t = 0; t < l; t++)u.setUint32(4 * t, a[t], h); + for(let t = 0; t < l; t++)f.setUint32(4 * t, a[t], h); } digest() { const { buffer: t, outputLen: e } = this; @@ -10435,7 +35569,7 @@ class f2 extends r2 { return t.length = n, t.pos = o, t.finished = i, t.destroyed = r, n % e && t.buffer.set(s), t; } } -const u2 = new Uint32Array([ +const f3 = new Uint32Array([ 1116352408, 1899447441, 3049323471, @@ -10510,7 +35644,7 @@ const u2 = new Uint32Array([ 528734635, 1541459225 ]), l2 = new Uint32Array(64); -class a2 extends f2 { +class a2 extends u2 { constructor(){ super(64, 32, 8, !1), this.A = 0 | c2[0], this.B = 0 | c2[1], this.C = 0 | c2[2], this.D = 0 | c2[3], this.E = 0 | c2[4], this.F = 0 | c2[5], this.G = 0 | c2[6], this.H = 0 | c2[7]; } @@ -10536,13 +35670,13 @@ class a2 extends f2 { const e = l2[t - 15], s = l2[t - 2], i = n2(e, 7) ^ n2(e, 18) ^ e >>> 3, r = n2(s, 17) ^ n2(s, 19) ^ s >>> 10; l2[t] = r + l2[t - 7] + i + l2[t - 16] | 0; } - let { A: s, B: i, C: r, D: o, E: f, F: c, G: a, H: p } = this; + let { A: s, B: i, C: r, D: o, E: u, F: c, G: a, H: p } = this; for(let t = 0; t < 64; t++){ - const e = p + (n2(f, 6) ^ n2(f, 11) ^ n2(f, 25)) + ((d = f) & c ^ ~d & a) + u2[t] + l2[t] | 0, g = (n2(s, 2) ^ n2(s, 13) ^ n2(s, 22)) + h2(s, i, r) | 0; - p = a, a = c, c = f, f = o + e | 0, o = r, r = i, i = s, s = e + g | 0; + const e = p + (n2(u, 6) ^ n2(u, 11) ^ n2(u, 25)) + ((d = u) & c ^ ~d & a) + f3[t] + l2[t] | 0, g = (n2(s, 2) ^ n2(s, 13) ^ n2(s, 22)) + h2(s, i, r) | 0; + p = a, a = c, c = u, u = o + e | 0, o = r, r = i, i = s, s = e + g | 0; } var d; - s = s + this.A | 0, i = i + this.B | 0, r = r + this.C | 0, o = o + this.D | 0, f = f + this.E | 0, c = c + this.F | 0, a = a + this.G | 0, p = p + this.H | 0, this.set(s, i, r, o, f, c, a, p); + s = s + this.A | 0, i = i + this.B | 0, r = r + this.C | 0, o = o + this.D | 0, u = u + this.E | 0, c = c + this.F | 0, a = a + this.G | 0, p = p + this.H | 0, this.set(s, i, r, o, u, c, a, p); } roundClean() { l2.fill(0); @@ -10561,11 +35695,11 @@ BigInt(0), BigInt(1), BigInt(2); Array.from({ length: 256 }, (t, n)=>n.toString(16).padStart(2, "0")); -var r3 = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {}; +var r5 = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {}; function i3(t) { return t && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t; } -var o4 = {}, a3 = {}, s3 = {}, u3 = {}; +var o4 = {}, a3 = {}, s4 = {}, u3 = {}; Object.defineProperty(u3, "__esModule", { value: !0 }), u3.LIB_VERSION = void 0, u3.LIB_VERSION = "1.2.6", function(t) { @@ -10604,15 +35738,15 @@ Object.defineProperty(u3, "__esModule", { return t(e, n - 1); } }; -}(s3), Object.defineProperty(a3, "__esModule", { +}(s4), Object.defineProperty(a3, "__esModule", { value: !0 }), a3.HttpChain = void 0; -const f3 = o4, c3 = s3; +const f4 = o4, c3 = s4; class h3 { baseUrl; options; httpOptions; - constructor(t, e = f3.defaultChainOptions, n = {}){ + constructor(t, e = f4.defaultChainOptions, n = {}){ this.baseUrl = t, this.options = e, this.httpOptions = n; } async info() { @@ -10629,7 +35763,7 @@ a3.default = class { options; chain; cachedInfo; - constructor(t, e = f3.defaultChainOptions){ + constructor(t, e = f4.defaultChainOptions){ this.baseUrl = t, this.options = e, this.chain = new h3(t, e); } async info() { @@ -10640,7 +35774,7 @@ var l3 = {}; Object.defineProperty(l3, "__esModule", { value: !0 }); -const d2 = o4, p3 = s3; +const d2 = o4, p3 = s4; function b1(t, e) { return e.noCache ? `${t}?${Date.now()}` : t; } @@ -10663,10 +35797,10 @@ l3.default = class { return this.someChain; } }; -var g2 = {}, _1 = {}; -Object.defineProperty(_1, "__esModule", { +var g2 = {}, _2 = {}; +Object.defineProperty(_2, "__esModule", { value: !0 -}), _1.createSpeedTest = void 0, _1.createSpeedTest = function(t, e, n = 5) { +}), _2.createSpeedTest = void 0, _2.createSpeedTest = function(t, e, n = 5) { let r = new y1(n), i = null; const o = async ()=>{ const e = Date.now(); @@ -10703,7 +35837,7 @@ class y1 { return this.values; } } -var w1 = r3 && r3.__createBinding || (Object.create ? function(t, e, n, r) { +var w1 = r5 && r5.__createBinding || (Object.create ? function(t, e, n, r) { void 0 === r && (r = n); var i = Object.getOwnPropertyDescriptor(e, n); i && !("get" in i ? !e.__esModule : i.writable || i.configurable) || (i = { @@ -10714,19 +35848,19 @@ var w1 = r3 && r3.__createBinding || (Object.create ? function(t, e, n, r) { }), Object.defineProperty(t, r, i); } : function(t, e, n, r) { void 0 === r && (r = n), t[r] = e[n]; -}), E1 = r3 && r3.__setModuleDefault || (Object.create ? function(t, e) { +}), E1 = r5 && r5.__setModuleDefault || (Object.create ? function(t, e) { Object.defineProperty(t, "default", { enumerable: !0, value: e }); } : function(t, e) { t.default = e; -}), v2 = r3 && r3.__importStar || function(t) { +}), v2 = r5 && r5.__importStar || function(t) { if (t && t.__esModule) return t; var e = {}; if (null != t) for(var n in t)"default" !== n && Object.prototype.hasOwnProperty.call(t, n) && w1(e, t, n); return E1(e, t), e; -}, T1 = r3 && r3.__importDefault || function(t) { +}, T1 = r5 && r5.__importDefault || function(t) { return t && t.__esModule ? t : { default: t }; @@ -10734,7 +35868,7 @@ var w1 = r3 && r3.__createBinding || (Object.create ? function(t, e, n, r) { Object.defineProperty(g2, "__esModule", { value: !0 }); -const m2 = o4, A1 = v2(a3), C1 = _1, I1 = T1(l3); +const m2 = o4, A1 = v2(a3), C1 = _2, I1 = T1(l3); g2.default = class { baseUrls; options; @@ -10776,16 +35910,16 @@ g2.default = class { this.speedTests.forEach((t)=>t.test.stop()), this.speedTests = []; } }; -var N10 = {}, U1 = r3 && r3.__importDefault || function(t) { +var N14 = {}, U1 = r5 && r5.__importDefault || function(t) { return t && t.__esModule ? t : { default: t }; }; -Object.defineProperty(N10, "__esModule", { +Object.defineProperty(N14, "__esModule", { value: !0 }); -const O2 = o4, R1 = U1(a3), P1 = s3; -N10.default = class { +const O2 = o4, R1 = U1(a3), P1 = s4; +N14.default = class { baseUrl; options; constructor(t, e = O2.defaultChainOptions){ @@ -10838,13 +35972,13 @@ function k1(t, e, n, r, i) { } return (d ? -1 : 1) * a * Math.pow(2, o - r); } -function x1(t, e, n, r, i, o) { +function x2(t, e, n, r, i, o) { var a, s, u, f = 8 * o - i - 1, c = (1 << f) - 1, h = c >> 1, l = 23 === i ? Math.pow(2, -24) - Math.pow(2, -77) : 0, d = r ? 0 : o - 1, p = r ? 1 : -1, b = e < 0 || 0 === e && 1 / e < 0 ? 1 : 0; for(e = Math.abs(e), isNaN(e) || e === 1 / 0 ? (s = isNaN(e) ? 1 : 0, a = c) : (a = Math.floor(Math.log(e) / Math.LN2), e * (u = Math.pow(2, -a)) < 1 && (a--, u *= 2), (e += a + h >= 1 ? l / u : l * Math.pow(2, 1 - h)) * u >= 2 && (a++, u /= 2), a + h >= c ? (s = 0, a = c) : a + h >= 1 ? (s = (e * u - 1) * Math.pow(2, i), a += h) : (s = e * Math.pow(2, h - 1) * Math.pow(2, i), a = 0)); i >= 8; t[n + d] = 255 & s, d += p, s /= 256, i -= 8); for(a = a << i | s, f += i; f > 0; t[n + d] = 255 & a, d += p, a /= 256, f -= 8); t[n + d - p] |= 128 * b; } -var G1 = {}.toString, K1 = Array.isArray || function(t) { +var G1 = {}.toString, K2 = Array.isArray || function(t) { return "[object Array]" == G1.call(t); }; q1.TYPED_ARRAY_SUPPORT = void 0 === S1.TYPED_ARRAY_SUPPORT || S1.TYPED_ARRAY_SUPPORT; @@ -10862,9 +35996,9 @@ function q1(t, e, n) { if ("string" == typeof e) throw new Error("If encoding is specified then the first argument must be a string"); return W1(this, t); } - return z1(this, t, e, n); + return z2(this, t, e, n); } -function z1(t, e, n, r) { +function z2(t, e, n, r) { if ("number" == typeof e) throw new TypeError('"value" argument must not be a number'); return "undefined" != typeof ArrayBuffer && e instanceof ArrayBuffer ? function(t, e, n, r) { if (e.byteLength, n < 0 || e.byteLength < n) throw new RangeError("'offset' is out of bounds"); @@ -10887,7 +36021,7 @@ function z1(t, e, n, r) { } if (e) { if ("undefined" != typeof ArrayBuffer && e.buffer instanceof ArrayBuffer || "length" in e) return "number" != typeof e.length || (r = e.length) != r ? V1(t, 0) : J1(t, e); - if ("Buffer" === e.type && K1(e.data)) return J1(t, e.data); + if ("Buffer" === e.type && K2(e.data)) return J1(t, e.data); } var r; throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."); @@ -11084,7 +36218,7 @@ function pt(t, e, n) { q1.poolSize = 8192, q1._augment = function(t) { return t.__proto__ = q1.prototype, t; }, q1.from = function(t, e, n) { - return z1(null, t, e, n); + return z2(null, t, e, n); }, q1.TYPED_ARRAY_SUPPORT && (q1.prototype.__proto__ = Uint8Array.prototype, q1.__proto__ = Uint8Array, "undefined" != typeof Symbol && Symbol.species && q1[Symbol.species]), q1.alloc = function(t, e, n) { return function(t, e, n, r) { return X1(e), e <= 0 ? V1(t, e) : void 0 !== n ? "string" == typeof r ? V1(t, e).fill(n, r) : V1(t, e).fill(n) : V1(t, e); @@ -11119,7 +36253,7 @@ q1.poolSize = 8192, q1._augment = function(t) { return !1; } }, q1.concat = function(t, e) { - if (!K1(t)) throw new TypeError('"list" argument must be an Array of Buffers'); + if (!K2(t)) throw new TypeError('"list" argument must be an Array of Buffers'); if (0 === t.length) return q1.alloc(0); var n; if (void 0 === e) for(e = 0, n = 0; n < t.length; ++n)e += t[n].length; @@ -11255,10 +36389,10 @@ function At(t, e, n, r, i, o) { if (n < 0) throw new RangeError("Index out of range"); } function Ct(t, e, n, r, i) { - return i || At(t, 0, n, 4), x1(t, e, n, r, 23, 4), n + 4; + return i || At(t, 0, n, 4), x2(t, e, n, r, 23, 4), n + 4; } function It(t, e, n, r, i) { - return i || At(t, 0, n, 8), x1(t, e, n, r, 52, 8), n + 8; + return i || At(t, 0, n, 8), x2(t, e, n, r, 52, 8), n + 8; } q1.prototype.slice = function(t, e) { var n, r = this.length; @@ -11532,7 +36666,7 @@ B1.verifyBeacon = async function(t, e, n) { }, B1.verifySigOnG1 = kt, B1.roundBuffer = Kt; var Qt = {}; !function(t) { - var e = r3 && r3.__importDefault || function(t) { + var e = r5 && r5.__importDefault || function(t) { return t && t.__esModule ? t : { default: t }; @@ -11638,7 +36772,7 @@ var Qt = {}; return new i.default(r, e); }; }(Qt), function(t) { - var e = r3 && r3.__importDefault || function(t) { + var e = r5 && r5.__importDefault || function(t) { return t && t.__esModule ? t : { default: t }; @@ -11659,9 +36793,9 @@ var Qt = {}; t.HttpChainClient = o.default; const u = e(g2); t.FastestNodeClient = u.default; - const f = e(N10); + const f = e(N14); t.MultiBeaconNode = f.default; - const c = s3; + const c = s4; Object.defineProperty(t, "roundAt", { enumerable: !0, get: function() { @@ -11744,6 +36878,7 @@ export { encodeHex as encodeHex }; export { decodeBase64 as decodeBase64 }; export { decode as decodeVarint }; export { retry as retry }; +export { ethers as ethers }; export { CarBlockIterator as CarBlockIterator }; export { UnsupportedHashError as UnsupportedHashError, HashMismatchError as HashMismatchError, validateBlock as validateBlock }; export { ne1 as fetchBeaconByTime, zt as HttpChainClient, Vt as HttpCachingChain }; From 68359b60b626527566528a421fd3b17107d598e8 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 10:25:16 +0100 Subject: [PATCH 02/29] fmt --- lib/miner-info.js | 16 +++---- test.js | 2 +- test/spark.js | 114 +++++++++++++++++++++++----------------------- 3 files changed, 65 insertions(+), 67 deletions(-) diff --git a/lib/miner-info.js b/lib/miner-info.js index cbfb4f6..ebaaa99 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -30,21 +30,21 @@ async function getChainHead ({ maxAttempts = 5 } = {}) { * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { - // Make a concurrent request to both sources: Lotus API and smart contract - const [onChainPeerId, smartContractPeerId] = await Promise.all([ + // Make a concurrent request to both sources: Lotus API and smart contract + const [onChainPeerId, smartContractPeerId] = await Promise.all([ getMinerPeerIdFromRpcNode(minerId, { maxAttempts }), getMinerPeerIdFromSmartContract(minerId) - ]); + ]) // Return the peer ID from the smart contract if it exists and is not empty - if (smartContractPeerId && smartContractPeerId !== "") { - return smartContractPeerId; + if (smartContractPeerId && smartContractPeerId !== '') { + return smartContractPeerId } // Return the peer ID from the Lotus API if it exists and is not empty if (onChainPeerId) { - return onChainPeerId; + return onChainPeerId } - + return null } @@ -54,7 +54,7 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { * @param {number} [options.maxAttempts] * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ -export async function getMinerPeerIdFromRpcNode(minerId,{ maxAttempts = 5 }){ +export async function getMinerPeerIdFromRpcNode (minerId, { maxAttempts = 5 }) { const chainHead = await getChainHead({ maxAttempts }) try { const res = await retry(() => rpc('Filecoin.StateMinerInfo', minerId, chainHead), { diff --git a/test.js b/test.js index 0e322a3..6669873 100644 --- a/test.js +++ b/test.js @@ -1 +1 @@ -import './test/spark.js' \ No newline at end of file +import './test/spark.js' diff --git a/test/spark.js b/test/spark.js index 51ca1d5..997885b 100644 --- a/test/spark.js +++ b/test/spark.js @@ -3,10 +3,9 @@ import Spark, { calculateDelayBeforeNextTask, newStats } from '../lib/spark.js' import { test } from 'zinnia:test' import { assertInstanceOf, assertEquals, assertArrayIncludes, assertRejects, assert } from 'zinnia:assert' -import { SPARK_VERSION } from '../lib/constants.js' -import { getMinerPeerIdFromSmartContract } from "../lib/smart-contract-client.js" -import { RPC_URL } from '../lib/constants.js' -import { getMinerPeerId } from "../lib/miner-info.js" +import { SPARK_VERSION, RPC_URL } from '../lib/constants.js' +import { getMinerPeerIdFromSmartContract } from '../lib/smart-contract-client.js' +import { getMinerPeerId } from '../lib/miner-info.js' const KNOWN_CID = 'bafkreih25dih6ug3xtj73vswccw423b56ilrwmnos4cbwhrceudopdp5sq' @@ -368,103 +367,102 @@ test('calculateDelayBeforeNextTask() handles one task per round', () => { }) const mockPeerIdResponse = { - peerID: "12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U", - signature: "0x1234567890abcdef" -}; + peerID: '12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U', + signature: '0x1234567890abcdef' +} const mockEmptyPeerIdResponse = { - peerID: "", - signature: "0x" -}; + peerID: '', + signature: '0x' +} // Mock contract factory -function createMockContract(mockResponses) { +function createMockContract (mockResponses) { return { getPeerData: async (minerId) => { - const response = mockResponses[minerId]; + const response = mockResponses[minerId] if (!response) { - throw new Error(`Miner ID ${minerId} not found in contract`); + throw new Error(`Miner ID ${minerId} not found in contract`) } - return response; + return response } - }; + } } - test('smart-contract-client: getMinerPeerIdFromSmartContract returns peer ID for valid miner ID', async () => { // Create mock contract with predefined responses const peerId = 12345 const mockContract = createMockContract({ - [peerId]: mockPeerIdResponse, - }); - + [peerId]: mockPeerIdResponse + }) + const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { getSmartContractClientFn: () => mockContract - }); - - assertEquals(actualPeerId, mockPeerIdResponse.peerID); -}); + }) + + assertEquals(actualPeerId, mockPeerIdResponse.peerID) +}) test('miner-info: getMinerPeerId integration test with real miner f01234', async () => { - const peerId = await getMinerPeerIdFromSmartContract("f012345",RPC_URL ) - assertEquals(typeof peerId, 'string', "Expected peerId to be a string"); - assert(peerId.length > 0, "Expected peerId to be non-empty"); - assertEquals(peerId, "12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U"); -}); + const peerId = await getMinerPeerIdFromSmartContract('f012345', RPC_URL) + assertEquals(typeof peerId, 'string', 'Expected peerId to be a string') + assert(peerId.length > 0, 'Expected peerId to be non-empty') + assertEquals(peerId, '12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U') +}) test('smart-contract-client: getMinerPeerIdFromSmartContract returns empty string for miner ID with no peer ID', async () => { // Create mock contract with predefined responses const peerId = 99999 const mockContract = createMockContract({ - [peerId]: mockEmptyPeerIdResponse, - }); - + [peerId]: mockEmptyPeerIdResponse + }) + const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { getSmartContractClientFn: () => mockContract - }); - - assertEquals(actualPeerId, ""); -}); + }) + + assertEquals(actualPeerId, '') +}) test('smart-contract-client: getMinerPeerIdFromSmartContract throws error for non-existent miner ID', async () => { // Create mock contract with predefined responses (empty to cause error) - const mockContract = createMockContract({}); + const mockContract = createMockContract({}) await assertRejects( async () => { - await getMinerPeerIdFromSmartContract("f055555", { + await getMinerPeerIdFromSmartContract('f055555', { getSmartContractClientFn: () => mockContract - }); + }) }, Error, - "Error fetching peer ID from contract for miner f055555" - ); -}); + 'Error fetching peer ID from contract for miner f055555' + ) +}) test('smart-contract-client: getMinerPeerIdFromSmartContract properly strips f0 prefix', async () => { // Create a mock that validates the minerId was correctly converted - let receivedMinerId = null; - + let receivedMinerId = null + const mockContract = { getPeerData: async (minerId) => { - receivedMinerId = minerId; - return mockPeerIdResponse; + receivedMinerId = minerId + return mockPeerIdResponse } - }; - - await getMinerPeerIdFromSmartContract("f0123456", { + } + + await getMinerPeerIdFromSmartContract('f0123456', { getSmartContractClientFn: () => mockContract - }); - - assertEquals(receivedMinerId, 123456); -}); + }) + + assertEquals(receivedMinerId, 123456) +}) test('miner-info: getMinerPeerId integration test with real miner f03303347', async () => { - const peerId = await getMinerPeerId("f03303347"); - + const peerId = await getMinerPeerId('f03303347') + // We don't know what the actual value is, but we can verify it's a non-empty string // that looks like a valid peer ID - assert(typeof peerId === 'string', "Expected peerId to be a string"); - assert(peerId.length > 0, "Expected peerId to be non-empty"); - assertEquals(peerId, "12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U"); -}); \ No newline at end of file + assert(typeof peerId === 'string', 'Expected peerId to be a string') + assert(peerId.length > 0, 'Expected peerId to be non-empty') + assertEquals(peerId, '12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U') +}) From 62be1e61fb8a5a22107711db47ecdcf678f5fdd3 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 10:26:17 +0100 Subject: [PATCH 03/29] reanbled tests --- test.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test.js b/test.js index 6669873..6803285 100644 --- a/test.js +++ b/test.js @@ -1 +1,7 @@ +import './test/http-assertions.test.js' +import './test/ipni-client.test.js' +import './test/miner-info.test.js' +import './test/multiaddr.test.js' + +import './test/integration.js' import './test/spark.js' From 2bbbeca300431461a0cc75aef2bfe0b668278dbe Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 11:34:32 +0100 Subject: [PATCH 04/29] add client file --- lib/smart-contract-client.js | 77 ++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 lib/smart-contract-client.js diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js new file mode 100644 index 0000000..1fcc495 --- /dev/null +++ b/lib/smart-contract-client.js @@ -0,0 +1,77 @@ +import { ethers } from '../vendor/deno-deps.js' +import { assert } from 'zinnia:assert' +import { RPC_URL } from './constants.js' + +// ABI for the MinerPeerIDMapping contract (minimal ABI with just the method we need) +const contractABI = [ + { + inputs: [ + { + internalType: 'uint64', + name: 'minerID', + type: 'uint64' + } + ], + name: 'getPeerData', + outputs: [ + { + components: [ + { + internalType: 'string', + name: 'peerID', + type: 'string' + }, + { + internalType: 'bytes', + name: 'signature', + type: 'bytes' + } + ], + internalType: 'struct MinerPeerIDMapping.PeerData', + name: '', + type: 'tuple' + } + ], + stateMutability: 'view', + type: 'function' + } +] + +// Contract address on the Filecoin EVM +const CONTRACT_ADDRESS = '0x14183aD016Ddc83D638425D6328009aa390339Ce' +let smartContract +// Initialize provider and contract +async function getSmartContractClient (rpcUrl) { + const provider = new ethers.providers.JsonRpcProvider(rpcUrl) + return new ethers.Contract(CONTRACT_ADDRESS, contractABI, provider) +} + +/** + * Query the smart contract for the peer ID mapping + * @param {string} minerID - The miner ID (as string, will be converted to uint64) + * @param {object} [options] + * @param {function} [options.getSmartContractClientFn] - Function to get the smart contract client + * @returns {Promise} The peer ID from the contract or empty string if not found + */ +export async function getMinerPeerIdFromSmartContract ( + minerID, + { getSmartContractClientFn } = {} +) { + try { + if (!smartContract || getSmartContractClientFn) { + smartContract = await ( + getSmartContractClientFn ?? getSmartContractClient + )(RPC_URL) + } + assert(smartContract, 'smartContract must be initialized') + // Convert minerID string (like 'f01234') to numeric ID + const numericID = parseInt(minerID.replace('f0', '')) + const peerData = await smartContract.getPeerData(numericID) + // TODO: Check if peerData.signature is valid + return peerData?.peerID ?? null + } catch (error) { + throw Error(`Error fetching peer ID from contract for miner ${minerID}.`, { + cause: error + }) + } +} From 9697f26421b6d6af08cd208ed240ddb6dc4d0585 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 11:49:53 +0100 Subject: [PATCH 05/29] fmt --- lib/miner-info.js | 19 ++++++++++--------- lib/smart-contract-client.js | 1 + test/spark.js | 2 -- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/lib/miner-info.js b/lib/miner-info.js index ebaaa99..37b18fe 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -30,22 +30,23 @@ async function getChainHead ({ maxAttempts = 5 } = {}) { * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { - // Make a concurrent request to both sources: Lotus API and smart contract - const [onChainPeerId, smartContractPeerId] = await Promise.all([ + // Make a concurrent request to both sources: RPC node and smart contract + const [onChainResult, contractResult] = await Promise.allSettled([ getMinerPeerIdFromRpcNode(minerId, { maxAttempts }), getMinerPeerIdFromSmartContract(minerId) ]) - // Return the peer ID from the smart contract if it exists and is not empty - if (smartContractPeerId && smartContractPeerId !== '') { - return smartContractPeerId + // Check contract result first + if (contractResult.status === 'fulfilled' && contractResult.value) { + return contractResult.value } - // Return the peer ID from the Lotus API if it exists and is not empty - if (onChainPeerId) { - return onChainPeerId + // Fall back to on-chain result + if (onChainResult.status === 'fulfilled' && onChainResult.value) { + return onChainResult.value } - return null + // Handle the case where both failed + throw new Error(`Failed to resolve PeerID from any source: ${contractResult.reason}, ${onChainResult.reason}`) } /** diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index 1fcc495..5c68c05 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -39,6 +39,7 @@ const contractABI = [ // Contract address on the Filecoin EVM const CONTRACT_ADDRESS = '0x14183aD016Ddc83D638425D6328009aa390339Ce' +// Singleton instance of the smart contract client let smartContract // Initialize provider and contract async function getSmartContractClient (rpcUrl) { diff --git a/test/spark.js b/test/spark.js index 997885b..009030e 100644 --- a/test/spark.js +++ b/test/spark.js @@ -460,8 +460,6 @@ test('smart-contract-client: getMinerPeerIdFromSmartContract properly strips f0 test('miner-info: getMinerPeerId integration test with real miner f03303347', async () => { const peerId = await getMinerPeerId('f03303347') - // We don't know what the actual value is, but we can verify it's a non-empty string - // that looks like a valid peer ID assert(typeof peerId === 'string', 'Expected peerId to be a string') assert(peerId.length > 0, 'Expected peerId to be non-empty') assertEquals(peerId, '12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U') From 12623277547a2231a3b4c98e9d13efce21841c4d Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 11:50:58 +0100 Subject: [PATCH 06/29] comments --- lib/miner-info.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/miner-info.js b/lib/miner-info.js index 37b18fe..02cf350 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -31,7 +31,7 @@ async function getChainHead ({ maxAttempts = 5 } = {}) { */ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { // Make a concurrent request to both sources: RPC node and smart contract - const [onChainResult, contractResult] = await Promise.allSettled([ + const [rpcNodeResult, contractResult] = await Promise.allSettled([ getMinerPeerIdFromRpcNode(minerId, { maxAttempts }), getMinerPeerIdFromSmartContract(minerId) ]) @@ -40,13 +40,13 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { return contractResult.value } - // Fall back to on-chain result - if (onChainResult.status === 'fulfilled' && onChainResult.value) { - return onChainResult.value + // Fall back to rpc-Node result + if (rpcNodeResult.status === 'fulfilled' && rpcNodeResult.value) { + return rpcNodeResult.value } // Handle the case where both failed - throw new Error(`Failed to resolve PeerID from any source: ${contractResult.reason}, ${onChainResult.reason}`) + throw new Error(`Failed to resolve PeerID from any source: ${contractResult.reason}, ${rpcNodeResult.reason}`) } /** From 544d4c48a3d5491cb92c6438c973fa9ae1dd337c Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 11:52:48 +0100 Subject: [PATCH 07/29] comments --- lib/smart-contract-client.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index 5c68c05..e15aa62 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -59,6 +59,8 @@ export async function getMinerPeerIdFromSmartContract ( { getSmartContractClientFn } = {} ) { try { + // Reuse the smart contract if already initialized + // Use a custom initialization function if passed. if (!smartContract || getSmartContractClientFn) { smartContract = await ( getSmartContractClientFn ?? getSmartContractClient From 87e6ec0b548f5443c9146b51470af4778b063288 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl <113891786+NikolasHaimerl@users.noreply.github.com> Date: Mon, 10 Mar 2025 17:22:35 +0100 Subject: [PATCH 08/29] Update lib/miner-info.js MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Miroslav Bajtoš --- lib/miner-info.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/miner-info.js b/lib/miner-info.js index 02cf350..71c8d6f 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -46,7 +46,7 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { } // Handle the case where both failed - throw new Error(`Failed to resolve PeerID from any source: ${contractResult.reason}, ${rpcNodeResult.reason}`) + throw new Error(`Failed to obtain Miner's Index Provider PeerID.\nSmartContract query error: ${contractResult.reason}\nStateMinerInfo query error: ${rpcNodeResult.reason}`) } /** From e16ae0cbca7cbd5778cfccd7b2fb6b572f28cbc9 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl <113891786+NikolasHaimerl@users.noreply.github.com> Date: Mon, 10 Mar 2025 17:32:55 +0100 Subject: [PATCH 09/29] Update lib/miner-info.js MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Miroslav Bajtoš --- lib/miner-info.js | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/miner-info.js b/lib/miner-info.js index 71c8d6f..7cd3258 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -42,6 +42,7 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { // Fall back to rpc-Node result if (rpcNodeResult.status === 'fulfilled' && rpcNodeResult.value) { + console.log('Using PeerID from the MinerInfo state.') return rpcNodeResult.value } From 3a60176172843234a404b43adc8bdb9f82aa494d Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 17:39:16 +0100 Subject: [PATCH 10/29] resolve PR threads --- deps.ts | 1 + lib/miner-info.js | 16 ++--- lib/smart-contract-client.js | 20 ++---- test.js | 1 + test/smart-contract-client.test.js | 101 +++++++++++++++++++++++++++ test/spark.js | 105 +---------------------------- 6 files changed, 120 insertions(+), 124 deletions(-) create mode 100644 test/smart-contract-client.test.js diff --git a/deps.ts b/deps.ts index 4e8298b..c74b125 100644 --- a/deps.ts +++ b/deps.ts @@ -9,6 +9,7 @@ export { decodeBase64 } from 'https://deno.land/std@0.203.0/encoding/base64.ts' export { decode as decodeVarint } from 'https://deno.land/x/varint@v2.0.0/varint.ts' export { retry } from 'https://deno.land/std@0.203.0/async/retry.ts'; + export { ethers } from "https://cdn.skypack.dev/ethers@5.7.2?dts"; // Deno Bundle does not support npm dependencies, we have to load them via CDN export { CarBlockIterator } from 'https://cdn.skypack.dev/@ipld/car@5.3.2/?dts' diff --git a/lib/miner-info.js b/lib/miner-info.js index 02cf350..f5d2092 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -30,9 +30,9 @@ async function getChainHead ({ maxAttempts = 5 } = {}) { * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { - // Make a concurrent request to both sources: RPC node and smart contract - const [rpcNodeResult, contractResult] = await Promise.allSettled([ - getMinerPeerIdFromRpcNode(minerId, { maxAttempts }), + // Make a concurrent request to both sources: FilecoinMinerInfo and smart contract + const [minerInfoResult, contractResult] = await Promise.allSettled([ + getMinerPeerIdFromFilecoinMinerInfo(minerId, { maxAttempts }), getMinerPeerIdFromSmartContract(minerId) ]) // Check contract result first @@ -40,13 +40,13 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { return contractResult.value } - // Fall back to rpc-Node result - if (rpcNodeResult.status === 'fulfilled' && rpcNodeResult.value) { - return rpcNodeResult.value + // Fall back to FilecoinMinerInfo result + if (minerInfoResult.status === 'fulfilled' && minerInfoResult.value) { + return minerInfoResult.value } // Handle the case where both failed - throw new Error(`Failed to resolve PeerID from any source: ${contractResult.reason}, ${rpcNodeResult.reason}`) + throw new Error(`Failed to resolve PeerID from any source: ${contractResult.reason}, ${minerInfoResult.reason}`) } /** @@ -55,7 +55,7 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { * @param {number} [options.maxAttempts] * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ -export async function getMinerPeerIdFromRpcNode (minerId, { maxAttempts = 5 }) { +export async function getMinerPeerIdFromFilecoinMinerInfo (minerId, { maxAttempts = 5 }) { const chainHead = await getChainHead({ maxAttempts }) try { const res = await retry(() => rpc('Filecoin.StateMinerInfo', minerId, chainHead), { diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index e15aa62..f7ad8e9 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -3,6 +3,8 @@ import { assert } from 'zinnia:assert' import { RPC_URL } from './constants.js' // ABI for the MinerPeerIDMapping contract (minimal ABI with just the method we need) +// Docs for smart contract: https://github.com/filecoin-project/curio/blob/395bc47d0f585cbc869fd4671dc05b1b2f4b18c2/market/ipni/spark/sol/README.md +// Reasoning for smart contract: https://docs.curiostorage.org/curio-market/ipni-interplanetary-network-indexer-provider#ipni-provider-identification const contractABI = [ { inputs: [ @@ -39,8 +41,6 @@ const contractABI = [ // Contract address on the Filecoin EVM const CONTRACT_ADDRESS = '0x14183aD016Ddc83D638425D6328009aa390339Ce' -// Singleton instance of the smart contract client -let smartContract // Initialize provider and contract async function getSmartContractClient (rpcUrl) { const provider = new ethers.providers.JsonRpcProvider(rpcUrl) @@ -51,25 +51,19 @@ async function getSmartContractClient (rpcUrl) { * Query the smart contract for the peer ID mapping * @param {string} minerID - The miner ID (as string, will be converted to uint64) * @param {object} [options] - * @param {function} [options.getSmartContractClientFn] - Function to get the smart contract client + * @param {function} [options.smartContract] - Function to get the smart contract client * @returns {Promise} The peer ID from the contract or empty string if not found */ export async function getMinerPeerIdFromSmartContract ( minerID, - { getSmartContractClientFn } = {} + { smartContract } = {} ) { try { - // Reuse the smart contract if already initialized - // Use a custom initialization function if passed. - if (!smartContract || getSmartContractClientFn) { - smartContract = await ( - getSmartContractClientFn ?? getSmartContractClient - )(RPC_URL) - } - assert(smartContract, 'smartContract must be initialized') + const contractClient = smartContract ?? (await getSmartContractClient(RPC_URL)) + assert(contractClient, 'smartContract must be initialized') // Convert minerID string (like 'f01234') to numeric ID const numericID = parseInt(minerID.replace('f0', '')) - const peerData = await smartContract.getPeerData(numericID) + const peerData = await contractClient.getPeerData(numericID) // TODO: Check if peerData.signature is valid return peerData?.peerID ?? null } catch (error) { diff --git a/test.js b/test.js index 6803285..67921f1 100644 --- a/test.js +++ b/test.js @@ -5,3 +5,4 @@ import './test/multiaddr.test.js' import './test/integration.js' import './test/spark.js' +import './test/smart-contract-client.test.js' diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js new file mode 100644 index 0000000..caac235 --- /dev/null +++ b/test/smart-contract-client.test.js @@ -0,0 +1,101 @@ +import { assertEquals, assertRejects, assert } from 'zinnia:assert' +import { getMinerPeerIdFromSmartContract } from '../lib/smart-contract-client.js' +import { getMinerPeerId } from '../lib/miner-info.js' +import { test } from 'zinnia:test' + +const mockPeerIdResponse = { + peerID: '12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U', + signature: '0x1234567890abcdef' +} + +const mockEmptyPeerIdResponse = { + peerID: '', + signature: '0x' +} + +// Mock contract factory +function createMockContract (mockResponses) { + return { + getPeerData: async (minerId) => { + const response = mockResponses[minerId] + if (!response) { + throw new Error(`Miner ID ${minerId} not found in contract`) + } + return response + } + } +} + +test('getMinerPeerIdFromSmartContract returns peer ID for valid miner ID', async () => { + // Create mock contract with predefined responses + const peerId = 12345 + const mockContract = createMockContract({ + [peerId]: mockPeerIdResponse + }) + + const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { + smartContract: mockContract + }) + + assertEquals(actualPeerId, mockPeerIdResponse.peerID) +}) + +test('getMinerPeerId returns correct peer id for miner f03303347', async () => { + const peerId = await getMinerPeerIdFromSmartContract('f03303347') + assertEquals(typeof peerId, 'string', 'Expected peerId to be a string') + assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') +}) + +test('getMinerPeerIdFromSmartContract returns empty string for miner ID with no peer ID', async () => { + // Create mock contract with predefined responses + const peerId = 99999 + const mockContract = createMockContract({ + [peerId]: mockEmptyPeerIdResponse + }) + + const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { + smartContract: mockContract + }) + + assertEquals(actualPeerId, '') +}) + +test('getMinerPeerIdFromSmartContract throws error for non-existent miner ID', async () => { + // Create mock contract with predefined responses (empty to cause error) + const mockContract = createMockContract({}) + + await assertRejects( + async () => { + await getMinerPeerIdFromSmartContract('f055555', { + smartContract: mockContract + }) + }, + Error, + 'Error fetching peer ID from contract for miner f055555' + ) +}) + +test('getMinerPeerIdFromSmartContract properly strips f0 prefix', async () => { + // Create a mock that validates the minerId was correctly converted + let receivedMinerId = null + + const mockContract = { + getPeerData: async (minerId) => { + receivedMinerId = minerId + return mockPeerIdResponse + } + } + + await getMinerPeerIdFromSmartContract('f0123456', { + smartContract: mockContract + }) + + assertEquals(receivedMinerId, 123456) +}) + +test('getMinerPeerId returns correct peer id for miner f03303347', async () => { + const peerId = await getMinerPeerId('f03303347') + + assert(typeof peerId === 'string', 'Expected peerId to be a string') + assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') +}) diff --git a/test/spark.js b/test/spark.js index 009030e..a240e89 100644 --- a/test/spark.js +++ b/test/spark.js @@ -2,10 +2,8 @@ import Spark, { calculateDelayBeforeNextTask, newStats } from '../lib/spark.js' import { test } from 'zinnia:test' -import { assertInstanceOf, assertEquals, assertArrayIncludes, assertRejects, assert } from 'zinnia:assert' -import { SPARK_VERSION, RPC_URL } from '../lib/constants.js' -import { getMinerPeerIdFromSmartContract } from '../lib/smart-contract-client.js' -import { getMinerPeerId } from '../lib/miner-info.js' +import { assertInstanceOf, assertEquals, assertArrayIncludes } from 'zinnia:assert' +import { SPARK_VERSION } from '../lib/constants.js' const KNOWN_CID = 'bafkreih25dih6ug3xtj73vswccw423b56ilrwmnos4cbwhrceudopdp5sq' @@ -365,102 +363,3 @@ test('calculateDelayBeforeNextTask() handles one task per round', () => { }) assertEquals(delay, 60_000) }) - -const mockPeerIdResponse = { - peerID: '12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U', - signature: '0x1234567890abcdef' -} - -const mockEmptyPeerIdResponse = { - peerID: '', - signature: '0x' -} - -// Mock contract factory -function createMockContract (mockResponses) { - return { - getPeerData: async (minerId) => { - const response = mockResponses[minerId] - if (!response) { - throw new Error(`Miner ID ${minerId} not found in contract`) - } - return response - } - } -} - -test('smart-contract-client: getMinerPeerIdFromSmartContract returns peer ID for valid miner ID', async () => { - // Create mock contract with predefined responses - const peerId = 12345 - const mockContract = createMockContract({ - [peerId]: mockPeerIdResponse - }) - - const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { - getSmartContractClientFn: () => mockContract - }) - - assertEquals(actualPeerId, mockPeerIdResponse.peerID) -}) - -test('miner-info: getMinerPeerId integration test with real miner f01234', async () => { - const peerId = await getMinerPeerIdFromSmartContract('f012345', RPC_URL) - assertEquals(typeof peerId, 'string', 'Expected peerId to be a string') - assert(peerId.length > 0, 'Expected peerId to be non-empty') - assertEquals(peerId, '12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U') -}) - -test('smart-contract-client: getMinerPeerIdFromSmartContract returns empty string for miner ID with no peer ID', async () => { - // Create mock contract with predefined responses - const peerId = 99999 - const mockContract = createMockContract({ - [peerId]: mockEmptyPeerIdResponse - }) - - const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { - getSmartContractClientFn: () => mockContract - }) - - assertEquals(actualPeerId, '') -}) - -test('smart-contract-client: getMinerPeerIdFromSmartContract throws error for non-existent miner ID', async () => { - // Create mock contract with predefined responses (empty to cause error) - const mockContract = createMockContract({}) - - await assertRejects( - async () => { - await getMinerPeerIdFromSmartContract('f055555', { - getSmartContractClientFn: () => mockContract - }) - }, - Error, - 'Error fetching peer ID from contract for miner f055555' - ) -}) - -test('smart-contract-client: getMinerPeerIdFromSmartContract properly strips f0 prefix', async () => { - // Create a mock that validates the minerId was correctly converted - let receivedMinerId = null - - const mockContract = { - getPeerData: async (minerId) => { - receivedMinerId = minerId - return mockPeerIdResponse - } - } - - await getMinerPeerIdFromSmartContract('f0123456', { - getSmartContractClientFn: () => mockContract - }) - - assertEquals(receivedMinerId, 123456) -}) - -test('miner-info: getMinerPeerId integration test with real miner f03303347', async () => { - const peerId = await getMinerPeerId('f03303347') - - assert(typeof peerId === 'string', 'Expected peerId to be a string') - assert(peerId.length > 0, 'Expected peerId to be non-empty') - assertEquals(peerId, '12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U') -}) From 66a2d4a493d8f49562b2cf51da8ccdb22003818e Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 17:45:10 +0100 Subject: [PATCH 11/29] resolve PR threads --- lib/miner-info.js | 2 ++ lib/smart-contract-client.js | 4 +++- test/smart-contract-client.test.js | 2 +- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/lib/miner-info.js b/lib/miner-info.js index 6849187..f5cdd7d 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -37,11 +37,13 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { ]) // Check contract result first if (contractResult.status === 'fulfilled' && contractResult.value) { + console.log('Using PeerID from the smart contract.') return contractResult.value } // Fall back to FilecoinMinerInfo result if (minerInfoResult.status === 'fulfilled' && minerInfoResult.value) { + console.log('Using PeerID from FilecoinMinerInfo.') return minerInfoResult.value } diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index f7ad8e9..4cc3e8d 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -43,7 +43,9 @@ const contractABI = [ const CONTRACT_ADDRESS = '0x14183aD016Ddc83D638425D6328009aa390339Ce' // Initialize provider and contract async function getSmartContractClient (rpcUrl) { - const provider = new ethers.providers.JsonRpcProvider(rpcUrl) + const fetchRequest = new ethers.FetchRequest(rpcUrl) + fetchRequest.setHeader('Authorization', `Bearer ${GLIF_TOKEN}`) + const provider = new ethers.JsonRpcProvider(fetchRequest) return new ethers.Contract(CONTRACT_ADDRESS, contractABI, provider) } diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index caac235..ece9715 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -97,5 +97,5 @@ test('getMinerPeerId returns correct peer id for miner f03303347', async () => { const peerId = await getMinerPeerId('f03303347') assert(typeof peerId === 'string', 'Expected peerId to be a string') - assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') + assertEquals(peerId, '12D3KooWCtiN7tAjeLKL4mashteXdH4htUrzWu8bWN9kDU3qbKjQ') }) From 3eb9effe19a5f91fb3b68d2028bbc056a64b5b02 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Mon, 10 Mar 2025 17:47:48 +0100 Subject: [PATCH 12/29] auth --- lib/miner-info.js | 2 +- lib/smart-contract-client.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/miner-info.js b/lib/miner-info.js index f5cdd7d..314e6d2 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -48,7 +48,7 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { } // Handle the case where both failed - throw new Error(`Failed to obtain Miner's Index Provider PeerID.\nSmartContract query error: ${contractResult.reason}\nStateMinerInfo query error: ${rpcNodeResult.reason}`) + throw new Error(`Failed to obtain Miner's Index Provider PeerID.\nSmartContract query error: ${contractResult.reason}\nStateMinerInfo query error: ${minerInfoResult.reason}`) } /** diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index 4cc3e8d..cf4a800 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -1,6 +1,6 @@ import { ethers } from '../vendor/deno-deps.js' import { assert } from 'zinnia:assert' -import { RPC_URL } from './constants.js' +import { RPC_URL, RPC_AUTH } from './constants.js' // ABI for the MinerPeerIDMapping contract (minimal ABI with just the method we need) // Docs for smart contract: https://github.com/filecoin-project/curio/blob/395bc47d0f585cbc869fd4671dc05b1b2f4b18c2/market/ipni/spark/sol/README.md @@ -44,7 +44,7 @@ const CONTRACT_ADDRESS = '0x14183aD016Ddc83D638425D6328009aa390339Ce' // Initialize provider and contract async function getSmartContractClient (rpcUrl) { const fetchRequest = new ethers.FetchRequest(rpcUrl) - fetchRequest.setHeader('Authorization', `Bearer ${GLIF_TOKEN}`) + fetchRequest.setHeader('Authorization', `Bearer ${RPC_AUTH}`) const provider = new ethers.JsonRpcProvider(fetchRequest) return new ethers.Contract(CONTRACT_ADDRESS, contractABI, provider) } From 3e827ce9614feae681e9885c51683e5cff106964 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Tue, 11 Mar 2025 05:53:10 +0100 Subject: [PATCH 13/29] fix ethers import --- deps.ts | 2 +- vendor/deno-deps.js | 47542 ++++++++++++++++++++---------------------- 2 files changed, 22959 insertions(+), 24585 deletions(-) diff --git a/deps.ts b/deps.ts index c74b125..b2432ad 100644 --- a/deps.ts +++ b/deps.ts @@ -10,8 +10,8 @@ export { decode as decodeVarint } from 'https://deno.land/x/varint@v2.0.0/varint export { retry } from 'https://deno.land/std@0.203.0/async/retry.ts'; -export { ethers } from "https://cdn.skypack.dev/ethers@5.7.2?dts"; // Deno Bundle does not support npm dependencies, we have to load them via CDN +export { ethers } from "https://cdn.jsdelivr.net/npm/ethers@6.13.5/dist/ethers.min.js"; export { CarBlockIterator } from 'https://cdn.skypack.dev/@ipld/car@5.3.2/?dts' export { UnsupportedHashError, diff --git a/vendor/deno-deps.js b/vendor/deno-deps.js index 67c55b1..b90a6fb 100644 --- a/vendor/deno-deps.js +++ b/vendor/deno-deps.js @@ -113,5266 +113,5380 @@ function _exponentialBackoffWithJitter(cap, base, attempt, multiplier, jitter) { const exp = Math.min(cap, base * multiplier ** attempt); return (1 - jitter * Math.random()) * exp; } -var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; -function createCommonjsModule(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function(path, base) { - return commonjsRequire(path, base === void 0 || base === null ? module.path : base); +const __$G = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; +const version = "6.13.5"; +function checkType(value, type, name) { + const types = type.split("|").map((t)=>t.trim()); + for(let i = 0; i < types.length; i++){ + switch(type){ + case "any": + return; + case "bigint": + case "boolean": + case "number": + case "string": + if (typeof value === type) { + return; + } } - }, fn(module, module.exports), module.exports; -} -function getDefaultExportFromNamespaceIfNotNamed(n) { - return n && Object.prototype.hasOwnProperty.call(n, "default") && Object.keys(n).length === 1 ? n["default"] : n; + } + const error = new Error(`invalid value for type ${type}`); + error.code = "INVALID_ARGUMENT"; + error.argument = `value.${name}`; + error.value = value; + throw error; } -function commonjsRequire() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); +async function resolveProperties(value) { + const keys = Object.keys(value); + const results = await Promise.all(keys.map((k)=>Promise.resolve(value[k]))); + return results.reduce((accum, v, index)=>{ + accum[keys[index]] = v; + return accum; + }, {}); } -var _nodeResolve_empty = {}; -var _nodeResolve_empty$1 = Object.freeze({ - __proto__: null, - default: _nodeResolve_empty -}); -var require$$0 = getDefaultExportFromNamespaceIfNotNamed(_nodeResolve_empty$1); -var bn = createCommonjsModule(function(module) { - (function(module2, exports) { - function assert(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); - } - function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function() {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - function BN2(number, base, endian) { - if (BN2.isBN(number)) { - return number; - } - this.negative = 0; - this.words = null; - this.length = 0; - this.red = null; - if (number !== null) { - if (base === "le" || base === "be") { - endian = base; - base = 10; - } - this._init(number || 0, base || 10, endian || "be"); - } +function defineProperties(target, values, types) { + for(let key in values){ + let value = values[key]; + const type = types ? types[key] : null; + if (type) { + checkType(value, type, key); } - if (typeof module2 === "object") { - module2.exports = BN2; - } else { - exports.BN = BN2; + Object.defineProperty(target, key, { + enumerable: true, + value: value, + writable: false + }); + } +} +function stringify$1(value) { + if (value == null) { + return "null"; + } + if (Array.isArray(value)) { + return "[ " + value.map(stringify$1).join(", ") + " ]"; + } + if (value instanceof Uint8Array) { + const HEX = "0123456789abcdef"; + let result = "0x"; + for(let i = 0; i < value.length; i++){ + result += HEX[value[i] >> 4]; + result += HEX[value[i] & 15]; } - BN2.BN = BN2; - BN2.wordSize = 26; - var Buffer; - try { - if (typeof window !== "undefined" && typeof window.Buffer !== "undefined") { - Buffer = window.Buffer; - } else { - Buffer = require$$0.Buffer; - } - } catch (e) {} - BN2.isBN = function isBN(num) { - if (num instanceof BN2) { - return true; - } - return num !== null && typeof num === "object" && num.constructor.wordSize === BN2.wordSize && Array.isArray(num.words); - }; - BN2.max = function max(left, right) { - if (left.cmp(right) > 0) return left; - return right; - }; - BN2.min = function min(left, right) { - if (left.cmp(right) < 0) return left; - return right; - }; - BN2.prototype._init = function init(number, base, endian) { - if (typeof number === "number") { - return this._initNumber(number, base, endian); - } - if (typeof number === "object") { - return this._initArray(number, base, endian); - } - if (base === "hex") { - base = 16; - } - assert(base === (base | 0) && base >= 2 && base <= 36); - number = number.toString().replace(/\s+/g, ""); - var start = 0; - if (number[0] === "-") { - start++; - this.negative = 1; - } - if (start < number.length) { - if (base === 16) { - this._parseHex(number, start, endian); - } else { - this._parseBase(number, base, start); - if (endian === "le") { - this._initArray(this.toArray(), base, endian); - } - } - } - }; - BN2.prototype._initNumber = function _initNumber(number, base, endian) { - if (number < 0) { - this.negative = 1; - number = -number; - } - if (number < 67108864) { - this.words = [ - number & 67108863 - ]; - this.length = 1; - } else if (number < 4503599627370496) { - this.words = [ - number & 67108863, - number / 67108864 & 67108863 - ]; - this.length = 2; - } else { - assert(number < 9007199254740992); - this.words = [ - number & 67108863, - number / 67108864 & 67108863, - 1 - ]; - this.length = 3; - } - if (endian !== "le") return; - this._initArray(this.toArray(), base, endian); - }; - BN2.prototype._initArray = function _initArray(number, base, endian) { - assert(typeof number.length === "number"); - if (number.length <= 0) { - this.words = [ - 0 - ]; - this.length = 1; - return this; - } - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for(var i = 0; i < this.length; i++){ - this.words[i] = 0; - } - var j, w; - var off = 0; - if (endian === "be") { - for(i = number.length - 1, j = 0; i >= 0; i -= 3){ - w = number[i] | number[i - 1] << 8 | number[i - 2] << 16; - this.words[j] |= w << off & 67108863; - this.words[j + 1] = w >>> 26 - off & 67108863; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === "le") { - for(i = 0, j = 0; i < number.length; i += 3){ - w = number[i] | number[i + 1] << 8 | number[i + 2] << 16; - this.words[j] |= w << off & 67108863; - this.words[j + 1] = w >>> 26 - off & 67108863; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } + return result; + } + if (typeof value === "object" && typeof value.toJSON === "function") { + return stringify$1(value.toJSON()); + } + switch(typeof value){ + case "boolean": + case "symbol": + return value.toString(); + case "bigint": + return BigInt(value).toString(); + case "number": + return value.toString(); + case "string": + return JSON.stringify(value); + case "object": + { + const keys = Object.keys(value); + keys.sort(); + return "{ " + keys.map((k)=>`${stringify$1(k)}: ${stringify$1(value[k])}`).join(", ") + " }"; } - return this._strip(); - }; - function parseHex4Bits(string, index) { - var c = string.charCodeAt(index); - if (c >= 48 && c <= 57) { - return c - 48; - } else if (c >= 65 && c <= 70) { - return c - 55; - } else if (c >= 97 && c <= 102) { - return c - 87; - } else { - assert(false, "Invalid character in " + string); - } - } - function parseHexByte(string, lowerBound, index) { - var r = parseHex4Bits(string, index); - if (index - 1 >= lowerBound) { - r |= parseHex4Bits(string, index - 1) << 4; - } - return r; - } - BN2.prototype._parseHex = function _parseHex(number, start, endian) { - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for(var i = 0; i < this.length; i++){ - this.words[i] = 0; - } - var off = 0; - var j = 0; - var w; - if (endian === "be") { - for(i = number.length - 1; i >= start; i -= 2){ - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 67108863; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } - } else { - var parseLength = number.length - start; - for(i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2){ - w = parseHexByte(number, start, i) << off; - this.words[j] |= w & 67108863; - if (off >= 18) { - off -= 18; - j += 1; - this.words[j] |= w >>> 26; - } else { - off += 8; - } - } + } + return `[ COULD NOT SERIALIZE ]`; +} +function isError(error, code) { + return error && error.code === code; +} +function isCallException(error) { + return isError(error, "CALL_EXCEPTION"); +} +function makeError(message, code, info) { + let shortMessage = message; + { + const details = []; + if (info) { + if ("message" in info || "code" in info || "name" in info) { + throw new Error(`value will overwrite populated values: ${stringify$1(info)}`); } - this._strip(); - }; - function parseBase(str, start, end, mul) { - var r = 0; - var b = 0; - var len = Math.min(str.length, end); - for(var i = start; i < len; i++){ - var c = str.charCodeAt(i) - 48; - r *= mul; - if (c >= 49) { - b = c - 49 + 10; - } else if (c >= 17) { - b = c - 17 + 10; - } else { - b = c; + for(const key in info){ + if (key === "shortMessage") { + continue; } - assert(c >= 0 && b < mul, "Invalid character"); - r += b; + const value = info[key]; + details.push(key + "=" + stringify$1(value)); } - return r; } - BN2.prototype._parseBase = function _parseBase(number, base, start) { - this.words = [ - 0 - ]; - this.length = 1; - for(var limbLen = 0, limbPow = 1; limbPow <= 67108863; limbPow *= base){ - limbLen++; - } - limbLen--; - limbPow = limbPow / base | 0; - var total = number.length - start; - var mod = total % limbLen; - var end = Math.min(total, total - mod) + start; - var word = 0; - for(var i = start; i < end; i += limbLen){ - word = parseBase(number, i, i + limbLen, base); - this.imuln(limbPow); - if (this.words[0] + word < 67108864) { - this.words[0] += word; - } else { - this._iaddn(word); - } + details.push(`code=${code}`); + details.push(`version=${version}`); + if (details.length) { + message += " (" + details.join(", ") + ")"; + } + } + let error; + switch(code){ + case "INVALID_ARGUMENT": + error = new TypeError(message); + break; + case "NUMERIC_FAULT": + case "BUFFER_OVERRUN": + error = new RangeError(message); + break; + default: + error = new Error(message); + } + defineProperties(error, { + code: code + }); + if (info) { + Object.assign(error, info); + } + if (error.shortMessage == null) { + defineProperties(error, { + shortMessage: shortMessage + }); + } + return error; +} +function assert1(check, message, code, info) { + if (!check) { + throw makeError(message, code, info); + } +} +function assertArgument(check, message, name, value) { + assert1(check, message, "INVALID_ARGUMENT", { + argument: name, + value: value + }); +} +function assertArgumentCount(count, expectedCount, message) { + if (message == null) { + message = ""; + } + if (message) { + message = ": " + message; + } + assert1(count >= expectedCount, "missing argument" + message, "MISSING_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); + assert1(count <= expectedCount, "too many arguments" + message, "UNEXPECTED_ARGUMENT", { + count: count, + expectedCount: expectedCount + }); +} +const _normalizeForms = [ + "NFD", + "NFC", + "NFKD", + "NFKC" +].reduce((accum, form)=>{ + try { + if ("test".normalize(form) !== "test") { + throw new Error("bad"); + } + if (form === "NFD") { + const check = String.fromCharCode(233).normalize("NFD"); + const expected = String.fromCharCode(101, 769); + if (check !== expected) { + throw new Error("broken"); } - if (mod !== 0) { - var pow = 1; - word = parseBase(number, i, number.length, base); - for(i = 0; i < mod; i++){ - pow *= base; + } + accum.push(form); + } catch (error) {} + return accum; +}, []); +function assertNormalize(form) { + assert1(_normalizeForms.indexOf(form) >= 0, "platform missing String.prototype.normalize", "UNSUPPORTED_OPERATION", { + operation: "String.prototype.normalize", + info: { + form: form + } + }); +} +function assertPrivate(givenGuard, guard, className) { + if (className == null) { + className = ""; + } + if (givenGuard !== guard) { + let method = className, operation = "new"; + if (className) { + method += "."; + operation += " " + className; + } + assert1(false, `private constructor; use ${method}from* methods`, "UNSUPPORTED_OPERATION", { + operation: operation + }); + } +} +function _getBytes(value, name, copy) { + if (value instanceof Uint8Array) { + if (copy) { + return new Uint8Array(value); + } + return value; + } + if (typeof value === "string" && value.match(/^0x(?:[0-9a-f][0-9a-f])*$/i)) { + const result = new Uint8Array((value.length - 2) / 2); + let offset = 2; + for(let i = 0; i < result.length; i++){ + result[i] = parseInt(value.substring(offset, offset + 2), 16); + offset += 2; + } + return result; + } + assertArgument(false, "invalid BytesLike value", name || "value", value); +} +function getBytes(value, name) { + return _getBytes(value, name, false); +} +function getBytesCopy(value, name) { + return _getBytes(value, name, true); +} +function isHexString(value, length) { + if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { + return false; + } + if (typeof length === "number" && value.length !== 2 + 2 * length) { + return false; + } + if (length === true && value.length % 2 !== 0) { + return false; + } + return true; +} +function isBytesLike(value) { + return isHexString(value, true) || value instanceof Uint8Array; +} +const HexCharacters = "0123456789abcdef"; +function hexlify(data) { + const bytes = getBytes(data); + let result = "0x"; + for(let i = 0; i < bytes.length; i++){ + const v = bytes[i]; + result += HexCharacters[(v & 240) >> 4] + HexCharacters[v & 15]; + } + return result; +} +function concat(datas) { + return "0x" + datas.map((d)=>hexlify(d).substring(2)).join(""); +} +function dataLength(data) { + if (isHexString(data, true)) { + return (data.length - 2) / 2; + } + return getBytes(data).length; +} +function dataSlice(data, start, end) { + const bytes = getBytes(data); + if (end != null && end > bytes.length) { + assert1(false, "cannot slice beyond data bounds", "BUFFER_OVERRUN", { + buffer: bytes, + length: bytes.length, + offset: end + }); + } + return hexlify(bytes.slice(start == null ? 0 : start, end == null ? bytes.length : end)); +} +function stripZerosLeft(data) { + let bytes = hexlify(data).substring(2); + while(bytes.startsWith("00")){ + bytes = bytes.substring(2); + } + return "0x" + bytes; +} +function zeroPad(data, length, left) { + const bytes = getBytes(data); + assert1(length >= bytes.length, "padding exceeds data length", "BUFFER_OVERRUN", { + buffer: new Uint8Array(bytes), + length: length, + offset: length + 1 + }); + const result = new Uint8Array(length); + result.fill(0); + if (left) { + result.set(bytes, length - bytes.length); + } else { + result.set(bytes, 0); + } + return hexlify(result); +} +function zeroPadValue(data, length) { + return zeroPad(data, length, true); +} +function zeroPadBytes(data, length) { + return zeroPad(data, length, false); +} +const BN_0$a = BigInt(0); +const BN_1$5 = BigInt(1); +function fromTwos(_value, _width) { + const value = getUint(_value, "value"); + const width = BigInt(getNumber(_width, "width")); + assert1(value >> width === BN_0$a, "overflow", "NUMERIC_FAULT", { + operation: "fromTwos", + fault: "overflow", + value: _value + }); + if (value >> width - BN_1$5) { + const mask = (BN_1$5 << width) - BN_1$5; + return -((~value & mask) + BN_1$5); + } + return value; +} +function toTwos(_value, _width) { + let value = getBigInt(_value, "value"); + const width = BigInt(getNumber(_width, "width")); + const limit = BN_1$5 << width - BN_1$5; + if (value < BN_0$a) { + value = -value; + assert1(value <= limit, "too low", "NUMERIC_FAULT", { + operation: "toTwos", + fault: "overflow", + value: _value + }); + const mask = (BN_1$5 << width) - BN_1$5; + return (~value & mask) + BN_1$5; + } else { + assert1(value < limit, "too high", "NUMERIC_FAULT", { + operation: "toTwos", + fault: "overflow", + value: _value + }); + } + return value; +} +function mask(_value, _bits) { + const value = getUint(_value, "value"); + const bits = BigInt(getNumber(_bits, "bits")); + return value & (BN_1$5 << bits) - BN_1$5; +} +function getBigInt(value, name) { + switch(typeof value){ + case "bigint": + return value; + case "number": + assertArgument(Number.isInteger(value), "underflow", name || "value", value); + assertArgument(value >= -9007199254740991 && value <= 9007199254740991, "overflow", name || "value", value); + return BigInt(value); + case "string": + try { + if (value === "") { + throw new Error("empty string"); } - this.imuln(pow); - if (this.words[0] + word < 67108864) { - this.words[0] += word; - } else { - this._iaddn(word); + if (value[0] === "-" && value[1] !== "-") { + return -BigInt(value.substring(1)); } - } - this._strip(); - }; - BN2.prototype.copy = function copy(dest) { - dest.words = new Array(this.length); - for(var i = 0; i < this.length; i++){ - dest.words[i] = this.words[i]; - } - dest.length = this.length; - dest.negative = this.negative; - dest.red = this.red; - }; - function move(dest, src) { - dest.words = src.words; - dest.length = src.length; - dest.negative = src.negative; - dest.red = src.red; - } - BN2.prototype._move = function _move(dest) { - move(dest, this); - }; - BN2.prototype.clone = function clone() { - var r = new BN2(null); - this.copy(r); - return r; - }; - BN2.prototype._expand = function _expand(size) { - while(this.length < size){ - this.words[this.length++] = 0; - } - return this; - }; - BN2.prototype._strip = function strip() { - while(this.length > 1 && this.words[this.length - 1] === 0){ - this.length--; - } - return this._normSign(); - }; - BN2.prototype._normSign = function _normSign() { - if (this.length === 1 && this.words[0] === 0) { - this.negative = 0; - } - return this; - }; - if (typeof Symbol !== "undefined" && typeof Symbol.for === "function") { - try { - BN2.prototype[Symbol.for("nodejs.util.inspect.custom")] = inspect; + return BigInt(value); } catch (e) { - BN2.prototype.inspect = inspect; + assertArgument(false, `invalid BigNumberish string: ${e.message}`, name || "value", value); } - } else { - BN2.prototype.inspect = inspect; - } - function inspect() { - return (this.red ? ""; - } - var zeros = [ - "", - "0", - "00", - "000", - "0000", - "00000", - "000000", - "0000000", - "00000000", - "000000000", - "0000000000", - "00000000000", - "000000000000", - "0000000000000", - "00000000000000", - "000000000000000", - "0000000000000000", - "00000000000000000", - "000000000000000000", - "0000000000000000000", - "00000000000000000000", - "000000000000000000000", - "0000000000000000000000", - "00000000000000000000000", - "000000000000000000000000", - "0000000000000000000000000" - ]; - var groupSizes = [ - 0, - 0, - 25, - 16, - 12, - 11, - 10, - 9, - 8, - 8, - 7, - 7, - 7, - 7, - 6, - 6, - 6, - 6, - 6, - 6, - 6, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5, - 5 - ]; - var groupBases = [ - 0, - 0, - 33554432, - 43046721, - 16777216, - 48828125, - 60466176, - 40353607, - 16777216, - 43046721, - 1e7, - 19487171, - 35831808, - 62748517, - 7529536, - 11390625, - 16777216, - 24137569, - 34012224, - 47045881, - 64e6, - 4084101, - 5153632, - 6436343, - 7962624, - 9765625, - 11881376, - 14348907, - 17210368, - 20511149, - 243e5, - 28629151, - 33554432, - 39135393, - 45435424, - 52521875, - 60466176 - ]; - BN2.prototype.toString = function toString(base, padding) { - base = base || 10; - padding = padding | 0 || 1; - var out; - if (base === 16 || base === "hex") { - out = ""; - var off = 0; - var carry = 0; - for(var i = 0; i < this.length; i++){ - var w = this.words[i]; - var word = ((w << off | carry) & 16777215).toString(16); - carry = w >>> 24 - off & 16777215; - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - if (carry !== 0 || i !== this.length - 1) { - out = zeros[6 - word.length] + word + out; - } else { - out = word + out; - } - } - if (carry !== 0) { - out = carry.toString(16) + out; - } - while(out.length % padding !== 0){ - out = "0" + out; - } - if (this.negative !== 0) { - out = "-" + out; - } - return out; - } - if (base === (base | 0) && base >= 2 && base <= 36) { - var groupSize = groupSizes[base]; - var groupBase = groupBases[base]; - out = ""; - var c = this.clone(); - c.negative = 0; - while(!c.isZero()){ - var r = c.modrn(groupBase).toString(base); - c = c.idivn(groupBase); - if (!c.isZero()) { - out = zeros[groupSize - r.length] + r + out; - } else { - out = r + out; - } - } - if (this.isZero()) { - out = "0" + out; - } - while(out.length % padding !== 0){ - out = "0" + out; - } - if (this.negative !== 0) { - out = "-" + out; + } + assertArgument(false, "invalid BigNumberish value", name || "value", value); +} +function getUint(value, name) { + const result = getBigInt(value, name); + assert1(result >= BN_0$a, "unsigned value cannot be negative", "NUMERIC_FAULT", { + fault: "overflow", + operation: "getUint", + value: value + }); + return result; +} +const Nibbles$1 = "0123456789abcdef"; +function toBigInt(value) { + if (value instanceof Uint8Array) { + let result = "0x0"; + for (const v of value){ + result += Nibbles$1[v >> 4]; + result += Nibbles$1[v & 15]; + } + return BigInt(result); + } + return getBigInt(value); +} +function getNumber(value, name) { + switch(typeof value){ + case "bigint": + assertArgument(value >= -9007199254740991 && value <= 9007199254740991, "overflow", name || "value", value); + return Number(value); + case "number": + assertArgument(Number.isInteger(value), "underflow", name || "value", value); + assertArgument(value >= -9007199254740991 && value <= 9007199254740991, "overflow", name || "value", value); + return value; + case "string": + try { + if (value === "") { + throw new Error("empty string"); } - return out; + return getNumber(BigInt(value), name); + } catch (e) { + assertArgument(false, `invalid numeric string: ${e.message}`, name || "value", value); } - assert(false, "Base should be between 2 and 36"); - }; - BN2.prototype.toNumber = function toNumber() { - var ret = this.words[0]; - if (this.length === 2) { - ret += this.words[1] * 67108864; - } else if (this.length === 3 && this.words[2] === 1) { - ret += 4503599627370496 + this.words[1] * 67108864; - } else if (this.length > 2) { - assert(false, "Number can only safely store up to 53 bits"); - } - return this.negative !== 0 ? -ret : ret; - }; - BN2.prototype.toJSON = function toJSON() { - return this.toString(16, 2); - }; - if (Buffer) { - BN2.prototype.toBuffer = function toBuffer(endian, length) { - return this.toArrayLike(Buffer, endian, length); - }; + } + assertArgument(false, "invalid numeric value", name || "value", value); +} +function toNumber(value) { + return getNumber(toBigInt(value)); +} +function toBeHex(_value, _width) { + const value = getUint(_value, "value"); + let result = value.toString(16); + if (_width == null) { + if (result.length % 2) { + result = "0" + result; } - BN2.prototype.toArray = function toArray(endian, length) { - return this.toArrayLike(Array, endian, length); - }; - var allocate = function allocate2(ArrayType, size) { - if (ArrayType.allocUnsafe) { - return ArrayType.allocUnsafe(size); - } - return new ArrayType(size); - }; - BN2.prototype.toArrayLike = function toArrayLike(ArrayType, endian, length) { - this._strip(); - var byteLength = this.byteLength(); - var reqLength = length || Math.max(1, byteLength); - assert(byteLength <= reqLength, "byte array longer than desired length"); - assert(reqLength > 0, "Requested array length <= 0"); - var res = allocate(ArrayType, reqLength); - var postfix = endian === "le" ? "LE" : "BE"; - this["_toArrayLike" + postfix](res, byteLength); - return res; - }; - BN2.prototype._toArrayLikeLE = function _toArrayLikeLE(res, byteLength) { - var position = 0; - var carry = 0; - for(var i = 0, shift = 0; i < this.length; i++){ - var word = this.words[i] << shift | carry; - res[position++] = word & 255; - if (position < res.length) { - res[position++] = word >> 8 & 255; - } - if (position < res.length) { - res[position++] = word >> 16 & 255; - } - if (shift === 6) { - if (position < res.length) { - res[position++] = word >> 24 & 255; - } - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } - if (position < res.length) { - res[position++] = carry; - while(position < res.length){ - res[position++] = 0; - } - } - }; - BN2.prototype._toArrayLikeBE = function _toArrayLikeBE(res, byteLength) { - var position = res.length - 1; - var carry = 0; - for(var i = 0, shift = 0; i < this.length; i++){ - var word = this.words[i] << shift | carry; - res[position--] = word & 255; - if (position >= 0) { - res[position--] = word >> 8 & 255; - } - if (position >= 0) { - res[position--] = word >> 16 & 255; - } - if (shift === 6) { - if (position >= 0) { - res[position--] = word >> 24 & 255; - } - carry = 0; - shift = 0; - } else { - carry = word >>> 24; - shift += 2; - } - } - if (position >= 0) { - res[position--] = carry; - while(position >= 0){ - res[position--] = 0; - } - } - }; - if (Math.clz32) { - BN2.prototype._countBits = function _countBits(w) { - return 32 - Math.clz32(w); - }; - } else { - BN2.prototype._countBits = function _countBits(w) { - var t = w; - var r = 0; - if (t >= 4096) { - r += 13; - t >>>= 13; - } - if (t >= 64) { - r += 7; - t >>>= 7; - } - if (t >= 8) { - r += 4; - t >>>= 4; - } - if (t >= 2) { - r += 2; - t >>>= 2; - } - return r + t; - }; + } else { + const width = getNumber(_width, "width"); + assert1(width * 2 >= result.length, `value exceeds width (${width} bytes)`, "NUMERIC_FAULT", { + operation: "toBeHex", + fault: "overflow", + value: _value + }); + while(result.length < width * 2){ + result = "0" + result; } - BN2.prototype._zeroBits = function _zeroBits(w) { - if (w === 0) return 26; - var t = w; - var r = 0; - if ((t & 8191) === 0) { - r += 13; - t >>>= 13; - } - if ((t & 127) === 0) { - r += 7; - t >>>= 7; - } - if ((t & 15) === 0) { - r += 4; - t >>>= 4; - } - if ((t & 3) === 0) { - r += 2; - t >>>= 2; - } - if ((t & 1) === 0) { - r++; - } - return r; - }; - BN2.prototype.bitLength = function bitLength() { - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; - }; - function toBitArray(num) { - var w = new Array(num.bitLength()); - for(var bit = 0; bit < w.length; bit++){ - var off = bit / 26 | 0; - var wbit = bit % 26; - w[bit] = num.words[off] >>> wbit & 1; - } - return w; - } - BN2.prototype.zeroBits = function zeroBits() { - if (this.isZero()) return 0; - var r = 0; - for(var i = 0; i < this.length; i++){ - var b = this._zeroBits(this.words[i]); - r += b; - if (b !== 26) break; - } - return r; - }; - BN2.prototype.byteLength = function byteLength() { - return Math.ceil(this.bitLength() / 8); - }; - BN2.prototype.toTwos = function toTwos(width) { - if (this.negative !== 0) { - return this.abs().inotn(width).iaddn(1); + } + return "0x" + result; +} +function toBeArray(_value) { + const value = getUint(_value, "value"); + if (value === BN_0$a) { + return new Uint8Array([]); + } + let hex = value.toString(16); + if (hex.length % 2) { + hex = "0" + hex; + } + const result = new Uint8Array(hex.length / 2); + for(let i = 0; i < result.length; i++){ + const offset = i * 2; + result[i] = parseInt(hex.substring(offset, offset + 2), 16); + } + return result; +} +function toQuantity(value) { + let result = hexlify(isBytesLike(value) ? value : toBeArray(value)).substring(2); + while(result.startsWith("0")){ + result = result.substring(1); + } + if (result === "") { + result = "0"; + } + return "0x" + result; +} +const Alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; +let Lookup = null; +function getAlpha(letter) { + if (Lookup == null) { + Lookup = {}; + for(let i = 0; i < Alphabet.length; i++){ + Lookup[Alphabet[i]] = BigInt(i); + } + } + const result = Lookup[letter]; + assertArgument(result != null, `invalid base58 value`, "letter", letter); + return result; +} +const BN_0$9 = BigInt(0); +const BN_58 = BigInt(58); +function encodeBase58(_value) { + const bytes = getBytes(_value); + let value = toBigInt(bytes); + let result = ""; + while(value){ + result = Alphabet[Number(value % BN_58)] + result; + value /= BN_58; + } + for(let i = 0; i < bytes.length; i++){ + if (bytes[i]) { + break; + } + result = Alphabet[0] + result; + } + return result; +} +function decodeBase58(value) { + let result = BN_0$9; + for(let i = 0; i < value.length; i++){ + result *= BN_58; + result += getAlpha(value[i]); + } + return result; +} +function decodeBase641(textData) { + textData = atob(textData); + const data = new Uint8Array(textData.length); + for(let i = 0; i < textData.length; i++){ + data[i] = textData.charCodeAt(i); + } + return getBytes(data); +} +function encodeBase64(_data) { + const data = getBytes(_data); + let textData = ""; + for(let i = 0; i < data.length; i++){ + textData += String.fromCharCode(data[i]); + } + return btoa(textData); +} +class EventPayload { + filter; + emitter; + #listener; + constructor(emitter, listener, filter){ + this.#listener = listener; + defineProperties(this, { + emitter: emitter, + filter: filter + }); + } + async removeListener() { + if (this.#listener == null) { + return; + } + await this.emitter.off(this.filter, this.#listener); + } +} +function errorFunc(reason, offset, bytes, output, badCodepoint) { + assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes); +} +function ignoreFunc(reason, offset, bytes, output, badCodepoint) { + if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") { + let i = 0; + for(let o = offset + 1; o < bytes.length; o++){ + if (bytes[o] >> 6 !== 2) { + break; } - return this.clone(); - }; - BN2.prototype.fromTwos = function fromTwos(width) { - if (this.testn(width - 1)) { - return this.notn(width).iaddn(1).ineg(); + i++; + } + return i; + } + if (reason === "OVERRUN") { + return bytes.length - offset - 1; + } + return 0; +} +function replaceFunc(reason, offset, bytes, output, badCodepoint) { + if (reason === "OVERLONG") { + assertArgument(typeof badCodepoint === "number", "invalid bad code point for replacement", "badCodepoint", badCodepoint); + output.push(badCodepoint); + return 0; + } + output.push(65533); + return ignoreFunc(reason, offset, bytes); +} +const Utf8ErrorFuncs = Object.freeze({ + error: errorFunc, + ignore: ignoreFunc, + replace: replaceFunc +}); +function getUtf8CodePoints(_bytes, onError) { + if (onError == null) { + onError = Utf8ErrorFuncs.error; + } + const bytes = getBytes(_bytes, "bytes"); + const result = []; + let i = 0; + while(i < bytes.length){ + const c = bytes[i++]; + if (c >> 7 === 0) { + result.push(c); + continue; + } + let extraLength = null; + let overlongMask = null; + if ((c & 224) === 192) { + extraLength = 1; + overlongMask = 127; + } else if ((c & 240) === 224) { + extraLength = 2; + overlongMask = 2047; + } else if ((c & 248) === 240) { + extraLength = 3; + overlongMask = 65535; + } else { + if ((c & 192) === 128) { + i += onError("UNEXPECTED_CONTINUE", i - 1, bytes, result); + } else { + i += onError("BAD_PREFIX", i - 1, bytes, result); } - return this.clone(); - }; - BN2.prototype.isNeg = function isNeg() { - return this.negative !== 0; - }; - BN2.prototype.neg = function neg() { - return this.clone().ineg(); - }; - BN2.prototype.ineg = function ineg() { - if (!this.isZero()) { - this.negative ^= 1; + continue; + } + if (i - 1 + extraLength >= bytes.length) { + i += onError("OVERRUN", i - 1, bytes, result); + continue; + } + let res = c & (1 << 8 - extraLength - 1) - 1; + for(let j = 0; j < extraLength; j++){ + let nextChar = bytes[i]; + if ((nextChar & 192) != 128) { + i += onError("MISSING_CONTINUE", i, bytes, result); + res = null; + break; } - return this; + res = res << 6 | nextChar & 63; + i++; + } + if (res === null) { + continue; + } + if (res > 1114111) { + i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes, result, res); + continue; + } + if (res >= 55296 && res <= 57343) { + i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes, result, res); + continue; + } + if (res <= overlongMask) { + i += onError("OVERLONG", i - 1 - extraLength, bytes, result, res); + continue; + } + result.push(res); + } + return result; +} +function toUtf8Bytes(str, form) { + assertArgument(typeof str === "string", "invalid string value", "str", str); + if (form != null) { + assertNormalize(form); + str = str.normalize(form); + } + let result = []; + for(let i = 0; i < str.length; i++){ + const c = str.charCodeAt(i); + if (c < 128) { + result.push(c); + } else if (c < 2048) { + result.push(c >> 6 | 192); + result.push(c & 63 | 128); + } else if ((c & 64512) == 55296) { + i++; + const c2 = str.charCodeAt(i); + assertArgument(i < str.length && (c2 & 64512) === 56320, "invalid surrogate pair", "str", str); + const pair = 65536 + ((c & 1023) << 10) + (c2 & 1023); + result.push(pair >> 18 | 240); + result.push(pair >> 12 & 63 | 128); + result.push(pair >> 6 & 63 | 128); + result.push(pair & 63 | 128); + } else { + result.push(c >> 12 | 224); + result.push(c >> 6 & 63 | 128); + result.push(c & 63 | 128); + } + } + return new Uint8Array(result); +} +function _toUtf8String(codePoints) { + return codePoints.map((codePoint)=>{ + if (codePoint <= 65535) { + return String.fromCharCode(codePoint); + } + codePoint -= 65536; + return String.fromCharCode((codePoint >> 10 & 1023) + 55296, (codePoint & 1023) + 56320); + }).join(""); +} +function toUtf8String(bytes, onError) { + return _toUtf8String(getUtf8CodePoints(bytes, onError)); +} +function toUtf8CodePoints(str, form) { + return getUtf8CodePoints(toUtf8Bytes(str, form)); +} +function createGetUrl(options) { + async function getUrl(req, _signal) { + assert1(_signal == null || !_signal.cancelled, "request cancelled before sending", "CANCELLED"); + const protocol = req.url.split(":")[0].toLowerCase(); + assert1(protocol === "http" || protocol === "https", `unsupported protocol ${protocol}`, "UNSUPPORTED_OPERATION", { + info: { + protocol: protocol + }, + operation: "request" + }); + assert1(protocol === "https" || !req.credentials || req.allowInsecureAuthentication, "insecure authorized connections unsupported", "UNSUPPORTED_OPERATION", { + operation: "request" + }); + let error = null; + const controller = new AbortController; + const timer = setTimeout(()=>{ + error = makeError("request timeout", "TIMEOUT"); + controller.abort(); + }, req.timeout); + if (_signal) { + _signal.addListener(()=>{ + error = makeError("request cancelled", "CANCELLED"); + controller.abort(); + }); + } + const init = { + method: req.method, + headers: new Headers(Array.from(req)), + body: req.body || undefined, + signal: controller.signal }; - BN2.prototype.iuor = function iuor(num) { - while(this.length < num.length){ - this.words[this.length++] = 0; - } - for(var i = 0; i < num.length; i++){ - this.words[i] = this.words[i] | num.words[i]; + let resp; + try { + resp = await fetch(req.url, init); + } catch (_error) { + clearTimeout(timer); + if (error) { + throw error; } - return this._strip(); - }; - BN2.prototype.ior = function ior(num) { - assert((this.negative | num.negative) === 0); - return this.iuor(num); - }; - BN2.prototype.or = function or(num) { - if (this.length > num.length) return this.clone().ior(num); - return num.clone().ior(this); - }; - BN2.prototype.uor = function uor(num) { - if (this.length > num.length) return this.clone().iuor(num); - return num.clone().iuor(this); + throw _error; + } + clearTimeout(timer); + const headers = {}; + resp.headers.forEach((value, key)=>{ + headers[key.toLowerCase()] = value; + }); + const respBody = await resp.arrayBuffer(); + const body = respBody == null ? null : new Uint8Array(respBody); + return { + statusCode: resp.status, + statusMessage: resp.statusText, + headers: headers, + body: body }; - BN2.prototype.iuand = function iuand(num) { - var b; - if (this.length > num.length) { - b = num; - } else { - b = this; - } - for(var i = 0; i < b.length; i++){ - this.words[i] = this.words[i] & num.words[i]; + } + return getUrl; +} +const MAX_ATTEMPTS = 12; +const SLOT_INTERVAL = 250; +let defaultGetUrlFunc = createGetUrl(); +const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); +const reIpfs = new RegExp("^ipfs://(ipfs/)?(.*)$", "i"); +let locked$5 = false; +async function dataGatewayFunc(url, signal) { + try { + const match = url.match(reData); + if (!match) { + throw new Error("invalid data"); + } + return new FetchResponse(200, "OK", { + "content-type": match[1] || "text/plain" + }, match[2] ? decodeBase641(match[3]) : unpercent(match[3])); + } catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid data: URI)", {}, null, new FetchRequest(url)); + } +} +function getIpfsGatewayFunc(baseUrl) { + async function gatewayIpfs(url, signal) { + try { + const match = url.match(reIpfs); + if (!match) { + throw new Error("invalid link"); } - this.length = b.length; - return this._strip(); - }; - BN2.prototype.iand = function iand(num) { - assert((this.negative | num.negative) === 0); - return this.iuand(num); - }; - BN2.prototype.and = function and(num) { - if (this.length > num.length) return this.clone().iand(num); - return num.clone().iand(this); - }; - BN2.prototype.uand = function uand(num) { - if (this.length > num.length) return this.clone().iuand(num); - return num.clone().iuand(this); - }; - BN2.prototype.iuxor = function iuxor(num) { - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; + return new FetchRequest(`${baseUrl}${match[2]}`); + } catch (error) { + return new FetchResponse(599, "BAD REQUEST (invalid IPFS URI)", {}, null, new FetchRequest(url)); + } + } + return gatewayIpfs; +} +const Gateways = { + data: dataGatewayFunc, + ipfs: getIpfsGatewayFunc("https://gateway.ipfs.io/ipfs/") +}; +const fetchSignals = new WeakMap; +class FetchCancelSignal { + #listeners; + #cancelled; + constructor(request){ + this.#listeners = []; + this.#cancelled = false; + fetchSignals.set(request, ()=>{ + if (this.#cancelled) { + return; } - for(var i = 0; i < b.length; i++){ - this.words[i] = a.words[i] ^ b.words[i]; + this.#cancelled = true; + for (const listener of this.#listeners){ + setTimeout(()=>{ + listener(); + }, 0); } - if (this !== a) { - for(; i < a.length; i++){ - this.words[i] = a.words[i]; + this.#listeners = []; + }); + } + addListener(listener) { + assert1(!this.#cancelled, "singal already cancelled", "UNSUPPORTED_OPERATION", { + operation: "fetchCancelSignal.addCancelListener" + }); + this.#listeners.push(listener); + } + get cancelled() { + return this.#cancelled; + } + checkSignal() { + assert1(!this.cancelled, "cancelled", "CANCELLED", {}); + } +} +function checkSignal(signal) { + if (signal == null) { + throw new Error("missing signal; should not happen"); + } + signal.checkSignal(); + return signal; +} +class FetchRequest { + #allowInsecure; + #gzip; + #headers; + #method; + #timeout; + #url; + #body; + #bodyType; + #creds; + #preflight; + #process; + #retry; + #signal; + #throttle; + #getUrlFunc; + get url() { + return this.#url; + } + set url(url) { + this.#url = String(url); + } + get body() { + if (this.#body == null) { + return null; + } + return new Uint8Array(this.#body); + } + set body(body) { + if (body == null) { + this.#body = undefined; + this.#bodyType = undefined; + } else if (typeof body === "string") { + this.#body = toUtf8Bytes(body); + this.#bodyType = "text/plain"; + } else if (body instanceof Uint8Array) { + this.#body = body; + this.#bodyType = "application/octet-stream"; + } else if (typeof body === "object") { + this.#body = toUtf8Bytes(JSON.stringify(body)); + this.#bodyType = "application/json"; + } else { + throw new Error("invalid body"); + } + } + hasBody() { + return this.#body != null; + } + get method() { + if (this.#method) { + return this.#method; + } + if (this.hasBody()) { + return "POST"; + } + return "GET"; + } + set method(method) { + if (method == null) { + method = ""; + } + this.#method = String(method).toUpperCase(); + } + get headers() { + const headers = Object.assign({}, this.#headers); + if (this.#creds) { + headers["authorization"] = `Basic ${encodeBase64(toUtf8Bytes(this.#creds))}`; + } + if (this.allowGzip) { + headers["accept-encoding"] = "gzip"; + } + if (headers["content-type"] == null && this.#bodyType) { + headers["content-type"] = this.#bodyType; + } + if (this.body) { + headers["content-length"] = String(this.body.length); + } + return headers; + } + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + setHeader(key, value) { + this.#headers[String(key).toLowerCase()] = String(value); + } + clearHeaders() { + this.#headers = {}; + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: ()=>{ + if (index < keys.length) { + const key = keys[index++]; + return { + value: [ + key, + headers[key] + ], + done: false + }; } + return { + value: undefined, + done: true + }; } - this.length = a.length; - return this._strip(); - }; - BN2.prototype.ixor = function ixor(num) { - assert((this.negative | num.negative) === 0); - return this.iuxor(num); - }; - BN2.prototype.xor = function xor(num) { - if (this.length > num.length) return this.clone().ixor(num); - return num.clone().ixor(this); - }; - BN2.prototype.uxor = function uxor(num) { - if (this.length > num.length) return this.clone().iuxor(num); - return num.clone().iuxor(this); - }; - BN2.prototype.inotn = function inotn(width) { - assert(typeof width === "number" && width >= 0); - var bytesNeeded = Math.ceil(width / 26) | 0; - var bitsLeft = width % 26; - this._expand(bytesNeeded); - if (bitsLeft > 0) { - bytesNeeded--; - } - for(var i = 0; i < bytesNeeded; i++){ - this.words[i] = ~this.words[i] & 67108863; - } - if (bitsLeft > 0) { - this.words[i] = ~this.words[i] & 67108863 >> 26 - bitsLeft; - } - return this._strip(); - }; - BN2.prototype.notn = function notn(width) { - return this.clone().inotn(width); }; - BN2.prototype.setn = function setn(bit, val) { - assert(typeof bit === "number" && bit >= 0); - var off = bit / 26 | 0; - var wbit = bit % 26; - this._expand(off + 1); - if (val) { - this.words[off] = this.words[off] | 1 << wbit; - } else { - this.words[off] = this.words[off] & ~(1 << wbit); - } - return this._strip(); - }; - BN2.prototype.iadd = function iadd(num) { - var r; - if (this.negative !== 0 && num.negative === 0) { - this.negative = 0; - r = this.isub(num); - this.negative ^= 1; - return this._normSign(); - } else if (this.negative === 0 && num.negative !== 0) { - num.negative = 0; - r = this.isub(num); - num.negative = 1; - return r._normSign(); - } - var a, b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - var carry = 0; - for(var i = 0; i < b.length; i++){ - r = (a.words[i] | 0) + (b.words[i] | 0) + carry; - this.words[i] = r & 67108863; - carry = r >>> 26; - } - for(; carry !== 0 && i < a.length; i++){ - r = (a.words[i] | 0) + carry; - this.words[i] = r & 67108863; - carry = r >>> 26; - } - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - } else if (a !== this) { - for(; i < a.length; i++){ - this.words[i] = a.words[i]; - } - } - return this; - }; - BN2.prototype.add = function add(num) { - var res; - if (num.negative !== 0 && this.negative === 0) { - num.negative = 0; - res = this.sub(num); - num.negative ^= 1; - return res; - } else if (num.negative === 0 && this.negative !== 0) { - this.negative = 0; - res = num.sub(this); - this.negative = 1; - return res; - } - if (this.length > num.length) return this.clone().iadd(num); - return num.clone().iadd(this); - }; - BN2.prototype.isub = function isub(num) { - if (num.negative !== 0) { - num.negative = 0; - var r = this.iadd(num); - num.negative = 1; - return r._normSign(); - } else if (this.negative !== 0) { - this.negative = 0; - this.iadd(num); - this.negative = 1; - return this._normSign(); - } - var cmp = this.cmp(num); - if (cmp === 0) { - this.negative = 0; - this.length = 1; - this.words[0] = 0; - return this; - } - var a, b; - if (cmp > 0) { - a = this; - b = num; - } else { - a = num; - b = this; - } - var carry = 0; - for(var i = 0; i < b.length; i++){ - r = (a.words[i] | 0) - (b.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 67108863; - } - for(; carry !== 0 && i < a.length; i++){ - r = (a.words[i] | 0) + carry; - carry = r >> 26; - this.words[i] = r & 67108863; - } - if (carry === 0 && i < a.length && a !== this) { - for(; i < a.length; i++){ - this.words[i] = a.words[i]; - } - } - this.length = Math.max(this.length, i); - if (a !== this) { - this.negative = 1; - } - return this._strip(); - }; - BN2.prototype.sub = function sub(num) { - return this.clone().isub(num); - }; - function smallMulTo(self2, num, out) { - out.negative = num.negative ^ self2.negative; - var len = self2.length + num.length | 0; - out.length = len; - len = len - 1 | 0; - var a = self2.words[0] | 0; - var b = num.words[0] | 0; - var r = a * b; - var lo = r & 67108863; - var carry = r / 67108864 | 0; - out.words[0] = lo; - for(var k = 1; k < len; k++){ - var ncarry = carry >>> 26; - var rword = carry & 67108863; - var maxJ = Math.min(k, num.length - 1); - for(var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++){ - var i = k - j | 0; - a = self2.words[i] | 0; - b = num.words[j] | 0; - r = a * b + rword; - ncarry += r / 67108864 | 0; - rword = r & 67108863; - } - out.words[k] = rword | 0; - carry = ncarry | 0; - } - if (carry !== 0) { - out.words[k] = carry | 0; - } else { - out.length--; - } - return out._strip(); - } - var comb10MulTo = function comb10MulTo2(self2, num, out) { - var a = self2.words; - var b = num.words; - var o = out.words; - var c = 0; - var lo; - var mid; - var hi; - var a0 = a[0] | 0; - var al0 = a0 & 8191; - var ah0 = a0 >>> 13; - var a1 = a[1] | 0; - var al1 = a1 & 8191; - var ah1 = a1 >>> 13; - var a2 = a[2] | 0; - var al2 = a2 & 8191; - var ah2 = a2 >>> 13; - var a3 = a[3] | 0; - var al3 = a3 & 8191; - var ah3 = a3 >>> 13; - var a4 = a[4] | 0; - var al4 = a4 & 8191; - var ah4 = a4 >>> 13; - var a5 = a[5] | 0; - var al5 = a5 & 8191; - var ah5 = a5 >>> 13; - var a6 = a[6] | 0; - var al6 = a6 & 8191; - var ah6 = a6 >>> 13; - var a7 = a[7] | 0; - var al7 = a7 & 8191; - var ah7 = a7 >>> 13; - var a8 = a[8] | 0; - var al8 = a8 & 8191; - var ah8 = a8 >>> 13; - var a9 = a[9] | 0; - var al9 = a9 & 8191; - var ah9 = a9 >>> 13; - var b0 = b[0] | 0; - var bl0 = b0 & 8191; - var bh0 = b0 >>> 13; - var b1 = b[1] | 0; - var bl1 = b1 & 8191; - var bh1 = b1 >>> 13; - var b2 = b[2] | 0; - var bl2 = b2 & 8191; - var bh2 = b2 >>> 13; - var b3 = b[3] | 0; - var bl3 = b3 & 8191; - var bh3 = b3 >>> 13; - var b4 = b[4] | 0; - var bl4 = b4 & 8191; - var bh4 = b4 >>> 13; - var b5 = b[5] | 0; - var bl5 = b5 & 8191; - var bh5 = b5 >>> 13; - var b6 = b[6] | 0; - var bl6 = b6 & 8191; - var bh6 = b6 >>> 13; - var b7 = b[7] | 0; - var bl7 = b7 & 8191; - var bh7 = b7 >>> 13; - var b8 = b[8] | 0; - var bl8 = b8 & 8191; - var bh8 = b8 >>> 13; - var b9 = b[9] | 0; - var bl9 = b9 & 8191; - var bh9 = b9 >>> 13; - out.negative = self2.negative ^ num.negative; - out.length = 19; - lo = Math.imul(al0, bl0); - mid = Math.imul(al0, bh0); - mid = mid + Math.imul(ah0, bl0) | 0; - hi = Math.imul(ah0, bh0); - var w0 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w0 >>> 26) | 0; - w0 &= 67108863; - lo = Math.imul(al1, bl0); - mid = Math.imul(al1, bh0); - mid = mid + Math.imul(ah1, bl0) | 0; - hi = Math.imul(ah1, bh0); - lo = lo + Math.imul(al0, bl1) | 0; - mid = mid + Math.imul(al0, bh1) | 0; - mid = mid + Math.imul(ah0, bl1) | 0; - hi = hi + Math.imul(ah0, bh1) | 0; - var w1 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w1 >>> 26) | 0; - w1 &= 67108863; - lo = Math.imul(al2, bl0); - mid = Math.imul(al2, bh0); - mid = mid + Math.imul(ah2, bl0) | 0; - hi = Math.imul(ah2, bh0); - lo = lo + Math.imul(al1, bl1) | 0; - mid = mid + Math.imul(al1, bh1) | 0; - mid = mid + Math.imul(ah1, bl1) | 0; - hi = hi + Math.imul(ah1, bh1) | 0; - lo = lo + Math.imul(al0, bl2) | 0; - mid = mid + Math.imul(al0, bh2) | 0; - mid = mid + Math.imul(ah0, bl2) | 0; - hi = hi + Math.imul(ah0, bh2) | 0; - var w2 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w2 >>> 26) | 0; - w2 &= 67108863; - lo = Math.imul(al3, bl0); - mid = Math.imul(al3, bh0); - mid = mid + Math.imul(ah3, bl0) | 0; - hi = Math.imul(ah3, bh0); - lo = lo + Math.imul(al2, bl1) | 0; - mid = mid + Math.imul(al2, bh1) | 0; - mid = mid + Math.imul(ah2, bl1) | 0; - hi = hi + Math.imul(ah2, bh1) | 0; - lo = lo + Math.imul(al1, bl2) | 0; - mid = mid + Math.imul(al1, bh2) | 0; - mid = mid + Math.imul(ah1, bl2) | 0; - hi = hi + Math.imul(ah1, bh2) | 0; - lo = lo + Math.imul(al0, bl3) | 0; - mid = mid + Math.imul(al0, bh3) | 0; - mid = mid + Math.imul(ah0, bl3) | 0; - hi = hi + Math.imul(ah0, bh3) | 0; - var w3 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w3 >>> 26) | 0; - w3 &= 67108863; - lo = Math.imul(al4, bl0); - mid = Math.imul(al4, bh0); - mid = mid + Math.imul(ah4, bl0) | 0; - hi = Math.imul(ah4, bh0); - lo = lo + Math.imul(al3, bl1) | 0; - mid = mid + Math.imul(al3, bh1) | 0; - mid = mid + Math.imul(ah3, bl1) | 0; - hi = hi + Math.imul(ah3, bh1) | 0; - lo = lo + Math.imul(al2, bl2) | 0; - mid = mid + Math.imul(al2, bh2) | 0; - mid = mid + Math.imul(ah2, bl2) | 0; - hi = hi + Math.imul(ah2, bh2) | 0; - lo = lo + Math.imul(al1, bl3) | 0; - mid = mid + Math.imul(al1, bh3) | 0; - mid = mid + Math.imul(ah1, bl3) | 0; - hi = hi + Math.imul(ah1, bh3) | 0; - lo = lo + Math.imul(al0, bl4) | 0; - mid = mid + Math.imul(al0, bh4) | 0; - mid = mid + Math.imul(ah0, bl4) | 0; - hi = hi + Math.imul(ah0, bh4) | 0; - var w4 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w4 >>> 26) | 0; - w4 &= 67108863; - lo = Math.imul(al5, bl0); - mid = Math.imul(al5, bh0); - mid = mid + Math.imul(ah5, bl0) | 0; - hi = Math.imul(ah5, bh0); - lo = lo + Math.imul(al4, bl1) | 0; - mid = mid + Math.imul(al4, bh1) | 0; - mid = mid + Math.imul(ah4, bl1) | 0; - hi = hi + Math.imul(ah4, bh1) | 0; - lo = lo + Math.imul(al3, bl2) | 0; - mid = mid + Math.imul(al3, bh2) | 0; - mid = mid + Math.imul(ah3, bl2) | 0; - hi = hi + Math.imul(ah3, bh2) | 0; - lo = lo + Math.imul(al2, bl3) | 0; - mid = mid + Math.imul(al2, bh3) | 0; - mid = mid + Math.imul(ah2, bl3) | 0; - hi = hi + Math.imul(ah2, bh3) | 0; - lo = lo + Math.imul(al1, bl4) | 0; - mid = mid + Math.imul(al1, bh4) | 0; - mid = mid + Math.imul(ah1, bl4) | 0; - hi = hi + Math.imul(ah1, bh4) | 0; - lo = lo + Math.imul(al0, bl5) | 0; - mid = mid + Math.imul(al0, bh5) | 0; - mid = mid + Math.imul(ah0, bl5) | 0; - hi = hi + Math.imul(ah0, bh5) | 0; - var w5 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w5 >>> 26) | 0; - w5 &= 67108863; - lo = Math.imul(al6, bl0); - mid = Math.imul(al6, bh0); - mid = mid + Math.imul(ah6, bl0) | 0; - hi = Math.imul(ah6, bh0); - lo = lo + Math.imul(al5, bl1) | 0; - mid = mid + Math.imul(al5, bh1) | 0; - mid = mid + Math.imul(ah5, bl1) | 0; - hi = hi + Math.imul(ah5, bh1) | 0; - lo = lo + Math.imul(al4, bl2) | 0; - mid = mid + Math.imul(al4, bh2) | 0; - mid = mid + Math.imul(ah4, bl2) | 0; - hi = hi + Math.imul(ah4, bh2) | 0; - lo = lo + Math.imul(al3, bl3) | 0; - mid = mid + Math.imul(al3, bh3) | 0; - mid = mid + Math.imul(ah3, bl3) | 0; - hi = hi + Math.imul(ah3, bh3) | 0; - lo = lo + Math.imul(al2, bl4) | 0; - mid = mid + Math.imul(al2, bh4) | 0; - mid = mid + Math.imul(ah2, bl4) | 0; - hi = hi + Math.imul(ah2, bh4) | 0; - lo = lo + Math.imul(al1, bl5) | 0; - mid = mid + Math.imul(al1, bh5) | 0; - mid = mid + Math.imul(ah1, bl5) | 0; - hi = hi + Math.imul(ah1, bh5) | 0; - lo = lo + Math.imul(al0, bl6) | 0; - mid = mid + Math.imul(al0, bh6) | 0; - mid = mid + Math.imul(ah0, bl6) | 0; - hi = hi + Math.imul(ah0, bh6) | 0; - var w6 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w6 >>> 26) | 0; - w6 &= 67108863; - lo = Math.imul(al7, bl0); - mid = Math.imul(al7, bh0); - mid = mid + Math.imul(ah7, bl0) | 0; - hi = Math.imul(ah7, bh0); - lo = lo + Math.imul(al6, bl1) | 0; - mid = mid + Math.imul(al6, bh1) | 0; - mid = mid + Math.imul(ah6, bl1) | 0; - hi = hi + Math.imul(ah6, bh1) | 0; - lo = lo + Math.imul(al5, bl2) | 0; - mid = mid + Math.imul(al5, bh2) | 0; - mid = mid + Math.imul(ah5, bl2) | 0; - hi = hi + Math.imul(ah5, bh2) | 0; - lo = lo + Math.imul(al4, bl3) | 0; - mid = mid + Math.imul(al4, bh3) | 0; - mid = mid + Math.imul(ah4, bl3) | 0; - hi = hi + Math.imul(ah4, bh3) | 0; - lo = lo + Math.imul(al3, bl4) | 0; - mid = mid + Math.imul(al3, bh4) | 0; - mid = mid + Math.imul(ah3, bl4) | 0; - hi = hi + Math.imul(ah3, bh4) | 0; - lo = lo + Math.imul(al2, bl5) | 0; - mid = mid + Math.imul(al2, bh5) | 0; - mid = mid + Math.imul(ah2, bl5) | 0; - hi = hi + Math.imul(ah2, bh5) | 0; - lo = lo + Math.imul(al1, bl6) | 0; - mid = mid + Math.imul(al1, bh6) | 0; - mid = mid + Math.imul(ah1, bl6) | 0; - hi = hi + Math.imul(ah1, bh6) | 0; - lo = lo + Math.imul(al0, bl7) | 0; - mid = mid + Math.imul(al0, bh7) | 0; - mid = mid + Math.imul(ah0, bl7) | 0; - hi = hi + Math.imul(ah0, bh7) | 0; - var w7 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w7 >>> 26) | 0; - w7 &= 67108863; - lo = Math.imul(al8, bl0); - mid = Math.imul(al8, bh0); - mid = mid + Math.imul(ah8, bl0) | 0; - hi = Math.imul(ah8, bh0); - lo = lo + Math.imul(al7, bl1) | 0; - mid = mid + Math.imul(al7, bh1) | 0; - mid = mid + Math.imul(ah7, bl1) | 0; - hi = hi + Math.imul(ah7, bh1) | 0; - lo = lo + Math.imul(al6, bl2) | 0; - mid = mid + Math.imul(al6, bh2) | 0; - mid = mid + Math.imul(ah6, bl2) | 0; - hi = hi + Math.imul(ah6, bh2) | 0; - lo = lo + Math.imul(al5, bl3) | 0; - mid = mid + Math.imul(al5, bh3) | 0; - mid = mid + Math.imul(ah5, bl3) | 0; - hi = hi + Math.imul(ah5, bh3) | 0; - lo = lo + Math.imul(al4, bl4) | 0; - mid = mid + Math.imul(al4, bh4) | 0; - mid = mid + Math.imul(ah4, bl4) | 0; - hi = hi + Math.imul(ah4, bh4) | 0; - lo = lo + Math.imul(al3, bl5) | 0; - mid = mid + Math.imul(al3, bh5) | 0; - mid = mid + Math.imul(ah3, bl5) | 0; - hi = hi + Math.imul(ah3, bh5) | 0; - lo = lo + Math.imul(al2, bl6) | 0; - mid = mid + Math.imul(al2, bh6) | 0; - mid = mid + Math.imul(ah2, bl6) | 0; - hi = hi + Math.imul(ah2, bh6) | 0; - lo = lo + Math.imul(al1, bl7) | 0; - mid = mid + Math.imul(al1, bh7) | 0; - mid = mid + Math.imul(ah1, bl7) | 0; - hi = hi + Math.imul(ah1, bh7) | 0; - lo = lo + Math.imul(al0, bl8) | 0; - mid = mid + Math.imul(al0, bh8) | 0; - mid = mid + Math.imul(ah0, bl8) | 0; - hi = hi + Math.imul(ah0, bh8) | 0; - var w8 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w8 >>> 26) | 0; - w8 &= 67108863; - lo = Math.imul(al9, bl0); - mid = Math.imul(al9, bh0); - mid = mid + Math.imul(ah9, bl0) | 0; - hi = Math.imul(ah9, bh0); - lo = lo + Math.imul(al8, bl1) | 0; - mid = mid + Math.imul(al8, bh1) | 0; - mid = mid + Math.imul(ah8, bl1) | 0; - hi = hi + Math.imul(ah8, bh1) | 0; - lo = lo + Math.imul(al7, bl2) | 0; - mid = mid + Math.imul(al7, bh2) | 0; - mid = mid + Math.imul(ah7, bl2) | 0; - hi = hi + Math.imul(ah7, bh2) | 0; - lo = lo + Math.imul(al6, bl3) | 0; - mid = mid + Math.imul(al6, bh3) | 0; - mid = mid + Math.imul(ah6, bl3) | 0; - hi = hi + Math.imul(ah6, bh3) | 0; - lo = lo + Math.imul(al5, bl4) | 0; - mid = mid + Math.imul(al5, bh4) | 0; - mid = mid + Math.imul(ah5, bl4) | 0; - hi = hi + Math.imul(ah5, bh4) | 0; - lo = lo + Math.imul(al4, bl5) | 0; - mid = mid + Math.imul(al4, bh5) | 0; - mid = mid + Math.imul(ah4, bl5) | 0; - hi = hi + Math.imul(ah4, bh5) | 0; - lo = lo + Math.imul(al3, bl6) | 0; - mid = mid + Math.imul(al3, bh6) | 0; - mid = mid + Math.imul(ah3, bl6) | 0; - hi = hi + Math.imul(ah3, bh6) | 0; - lo = lo + Math.imul(al2, bl7) | 0; - mid = mid + Math.imul(al2, bh7) | 0; - mid = mid + Math.imul(ah2, bl7) | 0; - hi = hi + Math.imul(ah2, bh7) | 0; - lo = lo + Math.imul(al1, bl8) | 0; - mid = mid + Math.imul(al1, bh8) | 0; - mid = mid + Math.imul(ah1, bl8) | 0; - hi = hi + Math.imul(ah1, bh8) | 0; - lo = lo + Math.imul(al0, bl9) | 0; - mid = mid + Math.imul(al0, bh9) | 0; - mid = mid + Math.imul(ah0, bl9) | 0; - hi = hi + Math.imul(ah0, bh9) | 0; - var w9 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w9 >>> 26) | 0; - w9 &= 67108863; - lo = Math.imul(al9, bl1); - mid = Math.imul(al9, bh1); - mid = mid + Math.imul(ah9, bl1) | 0; - hi = Math.imul(ah9, bh1); - lo = lo + Math.imul(al8, bl2) | 0; - mid = mid + Math.imul(al8, bh2) | 0; - mid = mid + Math.imul(ah8, bl2) | 0; - hi = hi + Math.imul(ah8, bh2) | 0; - lo = lo + Math.imul(al7, bl3) | 0; - mid = mid + Math.imul(al7, bh3) | 0; - mid = mid + Math.imul(ah7, bl3) | 0; - hi = hi + Math.imul(ah7, bh3) | 0; - lo = lo + Math.imul(al6, bl4) | 0; - mid = mid + Math.imul(al6, bh4) | 0; - mid = mid + Math.imul(ah6, bl4) | 0; - hi = hi + Math.imul(ah6, bh4) | 0; - lo = lo + Math.imul(al5, bl5) | 0; - mid = mid + Math.imul(al5, bh5) | 0; - mid = mid + Math.imul(ah5, bl5) | 0; - hi = hi + Math.imul(ah5, bh5) | 0; - lo = lo + Math.imul(al4, bl6) | 0; - mid = mid + Math.imul(al4, bh6) | 0; - mid = mid + Math.imul(ah4, bl6) | 0; - hi = hi + Math.imul(ah4, bh6) | 0; - lo = lo + Math.imul(al3, bl7) | 0; - mid = mid + Math.imul(al3, bh7) | 0; - mid = mid + Math.imul(ah3, bl7) | 0; - hi = hi + Math.imul(ah3, bh7) | 0; - lo = lo + Math.imul(al2, bl8) | 0; - mid = mid + Math.imul(al2, bh8) | 0; - mid = mid + Math.imul(ah2, bl8) | 0; - hi = hi + Math.imul(ah2, bh8) | 0; - lo = lo + Math.imul(al1, bl9) | 0; - mid = mid + Math.imul(al1, bh9) | 0; - mid = mid + Math.imul(ah1, bl9) | 0; - hi = hi + Math.imul(ah1, bh9) | 0; - var w10 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w10 >>> 26) | 0; - w10 &= 67108863; - lo = Math.imul(al9, bl2); - mid = Math.imul(al9, bh2); - mid = mid + Math.imul(ah9, bl2) | 0; - hi = Math.imul(ah9, bh2); - lo = lo + Math.imul(al8, bl3) | 0; - mid = mid + Math.imul(al8, bh3) | 0; - mid = mid + Math.imul(ah8, bl3) | 0; - hi = hi + Math.imul(ah8, bh3) | 0; - lo = lo + Math.imul(al7, bl4) | 0; - mid = mid + Math.imul(al7, bh4) | 0; - mid = mid + Math.imul(ah7, bl4) | 0; - hi = hi + Math.imul(ah7, bh4) | 0; - lo = lo + Math.imul(al6, bl5) | 0; - mid = mid + Math.imul(al6, bh5) | 0; - mid = mid + Math.imul(ah6, bl5) | 0; - hi = hi + Math.imul(ah6, bh5) | 0; - lo = lo + Math.imul(al5, bl6) | 0; - mid = mid + Math.imul(al5, bh6) | 0; - mid = mid + Math.imul(ah5, bl6) | 0; - hi = hi + Math.imul(ah5, bh6) | 0; - lo = lo + Math.imul(al4, bl7) | 0; - mid = mid + Math.imul(al4, bh7) | 0; - mid = mid + Math.imul(ah4, bl7) | 0; - hi = hi + Math.imul(ah4, bh7) | 0; - lo = lo + Math.imul(al3, bl8) | 0; - mid = mid + Math.imul(al3, bh8) | 0; - mid = mid + Math.imul(ah3, bl8) | 0; - hi = hi + Math.imul(ah3, bh8) | 0; - lo = lo + Math.imul(al2, bl9) | 0; - mid = mid + Math.imul(al2, bh9) | 0; - mid = mid + Math.imul(ah2, bl9) | 0; - hi = hi + Math.imul(ah2, bh9) | 0; - var w11 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w11 >>> 26) | 0; - w11 &= 67108863; - lo = Math.imul(al9, bl3); - mid = Math.imul(al9, bh3); - mid = mid + Math.imul(ah9, bl3) | 0; - hi = Math.imul(ah9, bh3); - lo = lo + Math.imul(al8, bl4) | 0; - mid = mid + Math.imul(al8, bh4) | 0; - mid = mid + Math.imul(ah8, bl4) | 0; - hi = hi + Math.imul(ah8, bh4) | 0; - lo = lo + Math.imul(al7, bl5) | 0; - mid = mid + Math.imul(al7, bh5) | 0; - mid = mid + Math.imul(ah7, bl5) | 0; - hi = hi + Math.imul(ah7, bh5) | 0; - lo = lo + Math.imul(al6, bl6) | 0; - mid = mid + Math.imul(al6, bh6) | 0; - mid = mid + Math.imul(ah6, bl6) | 0; - hi = hi + Math.imul(ah6, bh6) | 0; - lo = lo + Math.imul(al5, bl7) | 0; - mid = mid + Math.imul(al5, bh7) | 0; - mid = mid + Math.imul(ah5, bl7) | 0; - hi = hi + Math.imul(ah5, bh7) | 0; - lo = lo + Math.imul(al4, bl8) | 0; - mid = mid + Math.imul(al4, bh8) | 0; - mid = mid + Math.imul(ah4, bl8) | 0; - hi = hi + Math.imul(ah4, bh8) | 0; - lo = lo + Math.imul(al3, bl9) | 0; - mid = mid + Math.imul(al3, bh9) | 0; - mid = mid + Math.imul(ah3, bl9) | 0; - hi = hi + Math.imul(ah3, bh9) | 0; - var w12 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w12 >>> 26) | 0; - w12 &= 67108863; - lo = Math.imul(al9, bl4); - mid = Math.imul(al9, bh4); - mid = mid + Math.imul(ah9, bl4) | 0; - hi = Math.imul(ah9, bh4); - lo = lo + Math.imul(al8, bl5) | 0; - mid = mid + Math.imul(al8, bh5) | 0; - mid = mid + Math.imul(ah8, bl5) | 0; - hi = hi + Math.imul(ah8, bh5) | 0; - lo = lo + Math.imul(al7, bl6) | 0; - mid = mid + Math.imul(al7, bh6) | 0; - mid = mid + Math.imul(ah7, bl6) | 0; - hi = hi + Math.imul(ah7, bh6) | 0; - lo = lo + Math.imul(al6, bl7) | 0; - mid = mid + Math.imul(al6, bh7) | 0; - mid = mid + Math.imul(ah6, bl7) | 0; - hi = hi + Math.imul(ah6, bh7) | 0; - lo = lo + Math.imul(al5, bl8) | 0; - mid = mid + Math.imul(al5, bh8) | 0; - mid = mid + Math.imul(ah5, bl8) | 0; - hi = hi + Math.imul(ah5, bh8) | 0; - lo = lo + Math.imul(al4, bl9) | 0; - mid = mid + Math.imul(al4, bh9) | 0; - mid = mid + Math.imul(ah4, bl9) | 0; - hi = hi + Math.imul(ah4, bh9) | 0; - var w13 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w13 >>> 26) | 0; - w13 &= 67108863; - lo = Math.imul(al9, bl5); - mid = Math.imul(al9, bh5); - mid = mid + Math.imul(ah9, bl5) | 0; - hi = Math.imul(ah9, bh5); - lo = lo + Math.imul(al8, bl6) | 0; - mid = mid + Math.imul(al8, bh6) | 0; - mid = mid + Math.imul(ah8, bl6) | 0; - hi = hi + Math.imul(ah8, bh6) | 0; - lo = lo + Math.imul(al7, bl7) | 0; - mid = mid + Math.imul(al7, bh7) | 0; - mid = mid + Math.imul(ah7, bl7) | 0; - hi = hi + Math.imul(ah7, bh7) | 0; - lo = lo + Math.imul(al6, bl8) | 0; - mid = mid + Math.imul(al6, bh8) | 0; - mid = mid + Math.imul(ah6, bl8) | 0; - hi = hi + Math.imul(ah6, bh8) | 0; - lo = lo + Math.imul(al5, bl9) | 0; - mid = mid + Math.imul(al5, bh9) | 0; - mid = mid + Math.imul(ah5, bl9) | 0; - hi = hi + Math.imul(ah5, bh9) | 0; - var w14 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w14 >>> 26) | 0; - w14 &= 67108863; - lo = Math.imul(al9, bl6); - mid = Math.imul(al9, bh6); - mid = mid + Math.imul(ah9, bl6) | 0; - hi = Math.imul(ah9, bh6); - lo = lo + Math.imul(al8, bl7) | 0; - mid = mid + Math.imul(al8, bh7) | 0; - mid = mid + Math.imul(ah8, bl7) | 0; - hi = hi + Math.imul(ah8, bh7) | 0; - lo = lo + Math.imul(al7, bl8) | 0; - mid = mid + Math.imul(al7, bh8) | 0; - mid = mid + Math.imul(ah7, bl8) | 0; - hi = hi + Math.imul(ah7, bh8) | 0; - lo = lo + Math.imul(al6, bl9) | 0; - mid = mid + Math.imul(al6, bh9) | 0; - mid = mid + Math.imul(ah6, bl9) | 0; - hi = hi + Math.imul(ah6, bh9) | 0; - var w15 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w15 >>> 26) | 0; - w15 &= 67108863; - lo = Math.imul(al9, bl7); - mid = Math.imul(al9, bh7); - mid = mid + Math.imul(ah9, bl7) | 0; - hi = Math.imul(ah9, bh7); - lo = lo + Math.imul(al8, bl8) | 0; - mid = mid + Math.imul(al8, bh8) | 0; - mid = mid + Math.imul(ah8, bl8) | 0; - hi = hi + Math.imul(ah8, bh8) | 0; - lo = lo + Math.imul(al7, bl9) | 0; - mid = mid + Math.imul(al7, bh9) | 0; - mid = mid + Math.imul(ah7, bl9) | 0; - hi = hi + Math.imul(ah7, bh9) | 0; - var w16 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w16 >>> 26) | 0; - w16 &= 67108863; - lo = Math.imul(al9, bl8); - mid = Math.imul(al9, bh8); - mid = mid + Math.imul(ah9, bl8) | 0; - hi = Math.imul(ah9, bh8); - lo = lo + Math.imul(al8, bl9) | 0; - mid = mid + Math.imul(al8, bh9) | 0; - mid = mid + Math.imul(ah8, bl9) | 0; - hi = hi + Math.imul(ah8, bh9) | 0; - var w17 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w17 >>> 26) | 0; - w17 &= 67108863; - lo = Math.imul(al9, bl9); - mid = Math.imul(al9, bh9); - mid = mid + Math.imul(ah9, bl9) | 0; - hi = Math.imul(ah9, bh9); - var w18 = (c + lo | 0) + ((mid & 8191) << 13) | 0; - c = (hi + (mid >>> 13) | 0) + (w18 >>> 26) | 0; - w18 &= 67108863; - o[0] = w0; - o[1] = w1; - o[2] = w2; - o[3] = w3; - o[4] = w4; - o[5] = w5; - o[6] = w6; - o[7] = w7; - o[8] = w8; - o[9] = w9; - o[10] = w10; - o[11] = w11; - o[12] = w12; - o[13] = w13; - o[14] = w14; - o[15] = w15; - o[16] = w16; - o[17] = w17; - o[18] = w18; - if (c !== 0) { - o[19] = c; - out.length++; - } - return out; - }; - if (!Math.imul) { - comb10MulTo = smallMulTo; - } - function bigMulTo(self2, num, out) { - out.negative = num.negative ^ self2.negative; - out.length = self2.length + num.length; - var carry = 0; - var hncarry = 0; - for(var k = 0; k < out.length - 1; k++){ - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 67108863; - var maxJ = Math.min(k, num.length - 1); - for(var j = Math.max(0, k - self2.length + 1); j <= maxJ; j++){ - var i = k - j; - var a = self2.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - var lo = r & 67108863; - ncarry = ncarry + (r / 67108864 | 0) | 0; - lo = lo + rword | 0; - rword = lo & 67108863; - ncarry = ncarry + (lo >>> 26) | 0; - hncarry += ncarry >>> 26; - ncarry &= 67108863; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - return out._strip(); - } - function jumboMulTo(self2, num, out) { - return bigMulTo(self2, num, out); - } - BN2.prototype.mulTo = function mulTo(num, out) { - var res; - var len = this.length + num.length; - if (this.length === 10 && num.length === 10) { - res = comb10MulTo(this, num, out); - } else if (len < 63) { - res = smallMulTo(this, num, out); - } else if (len < 1024) { - res = bigMulTo(this, num, out); - } else { - res = jumboMulTo(this, num, out); - } - return res; - }; - BN2.prototype.mul = function mul(num) { - var out = new BN2(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); - }; - BN2.prototype.mulf = function mulf(num) { - var out = new BN2(null); - out.words = new Array(this.length + num.length); - return jumboMulTo(this, num, out); - }; - BN2.prototype.imul = function imul(num) { - return this.clone().mulTo(num, this); - }; - BN2.prototype.imuln = function imuln(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - assert(typeof num === "number"); - assert(num < 67108864); - var carry = 0; - for(var i = 0; i < this.length; i++){ - var w = (this.words[i] | 0) * num; - var lo = (w & 67108863) + (carry & 67108863); - carry >>= 26; - carry += w / 67108864 | 0; - carry += lo >>> 26; - this.words[i] = lo & 67108863; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return isNegNum ? this.ineg() : this; - }; - BN2.prototype.muln = function muln(num) { - return this.clone().imuln(num); - }; - BN2.prototype.sqr = function sqr() { - return this.mul(this); - }; - BN2.prototype.isqr = function isqr() { - return this.imul(this.clone()); - }; - BN2.prototype.pow = function pow(num) { - var w = toBitArray(num); - if (w.length === 0) return new BN2(1); - var res = this; - for(var i = 0; i < w.length; i++, res = res.sqr()){ - if (w[i] !== 0) break; - } - if (++i < w.length) { - for(var q = res.sqr(); i < w.length; i++, q = q.sqr()){ - if (w[i] === 0) continue; - res = res.mul(q); - } - } - return res; - }; - BN2.prototype.iushln = function iushln(bits) { - assert(typeof bits === "number" && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = 67108863 >>> 26 - r << 26 - r; - var i; - if (r !== 0) { - var carry = 0; - for(i = 0; i < this.length; i++){ - var newCarry = this.words[i] & carryMask; - var c = (this.words[i] | 0) - newCarry << r; - this.words[i] = c | carry; - carry = newCarry >>> 26 - r; - } - if (carry) { - this.words[i] = carry; - this.length++; - } - } - if (s !== 0) { - for(i = this.length - 1; i >= 0; i--){ - this.words[i + s] = this.words[i]; - } - for(i = 0; i < s; i++){ - this.words[i] = 0; - } - this.length += s; - } - return this._strip(); - }; - BN2.prototype.ishln = function ishln(bits) { - assert(this.negative === 0); - return this.iushln(bits); - }; - BN2.prototype.iushrn = function iushrn(bits, hint, extended) { - assert(typeof bits === "number" && bits >= 0); - var h; - if (hint) { - h = (hint - hint % 26) / 26; - } else { - h = 0; - } - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 67108863 ^ 67108863 >>> r << r; - var maskedWords = extended; - h -= s; - h = Math.max(0, h); - if (maskedWords) { - for(var i = 0; i < s; i++){ - maskedWords.words[i] = this.words[i]; - } - maskedWords.length = s; - } - if (s === 0) ; - else if (this.length > s) { - this.length -= s; - for(i = 0; i < this.length; i++){ - this.words[i] = this.words[i + s]; - } - } else { - this.words[0] = 0; - this.length = 1; - } - var carry = 0; - for(i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--){ - var word = this.words[i] | 0; - this.words[i] = carry << 26 - r | word >>> r; - carry = word & mask; - } - if (maskedWords && carry !== 0) { - maskedWords.words[maskedWords.length++] = carry; - } - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - return this._strip(); - }; - BN2.prototype.ishrn = function ishrn(bits, hint, extended) { - assert(this.negative === 0); - return this.iushrn(bits, hint, extended); - }; - BN2.prototype.shln = function shln(bits) { - return this.clone().ishln(bits); - }; - BN2.prototype.ushln = function ushln(bits) { - return this.clone().iushln(bits); - }; - BN2.prototype.shrn = function shrn(bits) { - return this.clone().ishrn(bits); - }; - BN2.prototype.ushrn = function ushrn(bits) { - return this.clone().iushrn(bits); - }; - BN2.prototype.testn = function testn(bit) { - assert(typeof bit === "number" && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - if (this.length <= s) return false; - var w = this.words[s]; - return !!(w & q); - }; - BN2.prototype.imaskn = function imaskn(bits) { - assert(typeof bits === "number" && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - assert(this.negative === 0, "imaskn works only with positive numbers"); - if (this.length <= s) { - return this; - } - if (r !== 0) { - s++; - } - this.length = Math.min(s, this.length); - if (r !== 0) { - var mask = 67108863 ^ 67108863 >>> r << r; - this.words[this.length - 1] &= mask; - } - return this._strip(); - }; - BN2.prototype.maskn = function maskn(bits) { - return this.clone().imaskn(bits); - }; - BN2.prototype.iaddn = function iaddn(num) { - assert(typeof num === "number"); - assert(num < 67108864); - if (num < 0) return this.isubn(-num); - if (this.negative !== 0) { - if (this.length === 1 && (this.words[0] | 0) <= num) { - this.words[0] = num - (this.words[0] | 0); - this.negative = 0; - return this; - } - this.negative = 0; - this.isubn(num); - this.negative = 1; - return this; - } - return this._iaddn(num); - }; - BN2.prototype._iaddn = function _iaddn(num) { - this.words[0] += num; - for(var i = 0; i < this.length && this.words[i] >= 67108864; i++){ - this.words[i] -= 67108864; - if (i === this.length - 1) { - this.words[i + 1] = 1; - } else { - this.words[i + 1]++; - } - } - this.length = Math.max(this.length, i + 1); - return this; - }; - BN2.prototype.isubn = function isubn(num) { - assert(typeof num === "number"); - assert(num < 67108864); - if (num < 0) return this.iaddn(-num); - if (this.negative !== 0) { - this.negative = 0; - this.iaddn(num); - this.negative = 1; - return this; - } - this.words[0] -= num; - if (this.length === 1 && this.words[0] < 0) { - this.words[0] = -this.words[0]; - this.negative = 1; - } else { - for(var i = 0; i < this.length && this.words[i] < 0; i++){ - this.words[i] += 67108864; - this.words[i + 1] -= 1; - } - } - return this._strip(); - }; - BN2.prototype.addn = function addn(num) { - return this.clone().iaddn(num); - }; - BN2.prototype.subn = function subn(num) { - return this.clone().isubn(num); - }; - BN2.prototype.iabs = function iabs() { - this.negative = 0; - return this; - }; - BN2.prototype.abs = function abs() { - return this.clone().iabs(); - }; - BN2.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) { - var len = num.length + shift; - var i; - this._expand(len); - var w; - var carry = 0; - for(i = 0; i < num.length; i++){ - w = (this.words[i + shift] | 0) + carry; - var right = (num.words[i] | 0) * mul; - w -= right & 67108863; - carry = (w >> 26) - (right / 67108864 | 0); - this.words[i + shift] = w & 67108863; - } - for(; i < this.length - shift; i++){ - w = (this.words[i + shift] | 0) + carry; - carry = w >> 26; - this.words[i + shift] = w & 67108863; - } - if (carry === 0) return this._strip(); - assert(carry === -1); - carry = 0; - for(i = 0; i < this.length; i++){ - w = -(this.words[i] | 0) + carry; - carry = w >> 26; - this.words[i] = w & 67108863; - } - this.negative = 1; - return this._strip(); + } + get credentials() { + return this.#creds || null; + } + setCredentials(username, password) { + assertArgument(!username.match(/:/), "invalid basic authentication username", "username", "[REDACTED]"); + this.#creds = `${username}:${password}`; + } + get allowGzip() { + return this.#gzip; + } + set allowGzip(value) { + this.#gzip = !!value; + } + get allowInsecureAuthentication() { + return !!this.#allowInsecure; + } + set allowInsecureAuthentication(value) { + this.#allowInsecure = !!value; + } + get timeout() { + return this.#timeout; + } + set timeout(timeout) { + assertArgument(timeout >= 0, "timeout must be non-zero", "timeout", timeout); + this.#timeout = timeout; + } + get preflightFunc() { + return this.#preflight || null; + } + set preflightFunc(preflight) { + this.#preflight = preflight; + } + get processFunc() { + return this.#process || null; + } + set processFunc(process) { + this.#process = process; + } + get retryFunc() { + return this.#retry || null; + } + set retryFunc(retry) { + this.#retry = retry; + } + get getUrlFunc() { + return this.#getUrlFunc || defaultGetUrlFunc; + } + set getUrlFunc(value) { + this.#getUrlFunc = value; + } + constructor(url){ + this.#url = String(url); + this.#allowInsecure = false; + this.#gzip = true; + this.#headers = {}; + this.#method = ""; + this.#timeout = 3e5; + this.#throttle = { + slotInterval: SLOT_INTERVAL, + maxAttempts: MAX_ATTEMPTS }; - BN2.prototype._wordDiv = function _wordDiv(num, mode) { - var shift = this.length - num.length; - var a = this.clone(); - var b = num; - var bhi = b.words[b.length - 1] | 0; - var bhiBits = this._countBits(bhi); - shift = 26 - bhiBits; - if (shift !== 0) { - b = b.ushln(shift); - a.iushln(shift); - bhi = b.words[b.length - 1] | 0; - } - var m = a.length - b.length; - var q; - if (mode !== "mod") { - q = new BN2(null); - q.length = m + 1; - q.words = new Array(q.length); - for(var i = 0; i < q.length; i++){ - q.words[i] = 0; - } - } - var diff = a.clone()._ishlnsubmul(b, 1, m); - if (diff.negative === 0) { - a = diff; - if (q) { - q.words[m] = 1; - } - } - for(var j = m - 1; j >= 0; j--){ - var qj = (a.words[b.length + j] | 0) * 67108864 + (a.words[b.length + j - 1] | 0); - qj = Math.min(qj / bhi | 0, 67108863); - a._ishlnsubmul(b, qj, j); - while(a.negative !== 0){ - qj--; - a.negative = 0; - a._ishlnsubmul(b, 1, j); - if (!a.isZero()) { - a.negative ^= 1; + this.#getUrlFunc = null; + } + toString() { + return ``; + } + setThrottleParams(params) { + if (params.slotInterval != null) { + this.#throttle.slotInterval = params.slotInterval; + } + if (params.maxAttempts != null) { + this.#throttle.maxAttempts = params.maxAttempts; + } + } + async #send(attempt, expires, delay, _request, _response) { + if (attempt >= this.#throttle.maxAttempts) { + return _response.makeServerError("exceeded maximum retry limit"); + } + assert1(getTime$2() <= expires, "timeout", "TIMEOUT", { + operation: "request.send", + reason: "timeout", + request: _request + }); + if (delay > 0) { + await wait(delay); + } + let req = this.clone(); + const scheme = (req.url.split(":")[0] || "").toLowerCase(); + if (scheme in Gateways) { + const result = await Gateways[scheme](req.url, checkSignal(_request.#signal)); + if (result instanceof FetchResponse) { + let response = result; + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } catch (error) { + if (error.throttle == null || typeof error.stall !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); + } } } - if (q) { - q.words[j] = qj; - } - } - if (q) { - q._strip(); - } - a._strip(); - if (mode !== "div" && shift !== 0) { - a.iushrn(shift); - } - return { - div: q || null, - mod: a - }; - }; - BN2.prototype.divmod = function divmod(num, mode, positive) { - assert(!num.isZero()); - if (this.isZero()) { - return { - div: new BN2(0), - mod: new BN2(0) - }; + return response; } - var div, mod, res; - if (this.negative !== 0 && num.negative === 0) { - res = this.neg().divmod(num, mode); - if (mode !== "mod") { - div = res.div.neg(); - } - if (mode !== "div") { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.iadd(num); - } + req = result; + } + if (this.preflightFunc) { + req = await this.preflightFunc(req); + } + const resp = await this.getUrlFunc(req, checkSignal(_request.#signal)); + let response = new FetchResponse(resp.statusCode, resp.statusMessage, resp.headers, resp.body, _request); + if (response.statusCode === 301 || response.statusCode === 302) { + try { + const location = response.headers.location || ""; + return req.redirect(location).#send(attempt + 1, expires, 0, _request, response); + } catch (error) {} + return response; + } else if (response.statusCode === 429) { + if (this.retryFunc == null || await this.retryFunc(req, response, attempt)) { + const retryAfter = response.headers["retry-after"]; + let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); + if (typeof retryAfter === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { + delay = parseInt(retryAfter); } - return { - div, - mod - }; + return req.clone().#send(attempt + 1, expires, delay, _request, response); } - if (this.negative === 0 && num.negative !== 0) { - res = this.divmod(num.neg(), mode); - if (mode !== "mod") { - div = res.div.neg(); + } + if (this.processFunc) { + checkSignal(_request.#signal); + try { + response = await this.processFunc(req, response); + } catch (error) { + if (error.throttle == null || typeof error.stall !== "number") { + response.makeServerError("error in post-processing function", error).assertOk(); } - return { - div, - mod: res.mod - }; - } - if ((this.negative & num.negative) !== 0) { - res = this.neg().divmod(num.neg(), mode); - if (mode !== "div") { - mod = res.mod.neg(); - if (positive && mod.negative !== 0) { - mod.isub(num); - } + let delay = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt)); + if (error.stall >= 0) { + delay = error.stall; } - return { - div: res.div, - mod - }; + return req.clone().#send(attempt + 1, expires, delay, _request, response); } - if (num.length > this.length || this.cmp(num) < 0) { - return { - div: new BN2(0), - mod: this - }; - } - if (num.length === 1) { - if (mode === "div") { - return { - div: this.divn(num.words[0]), - mod: null - }; + } + return response; + } + send() { + assert1(this.#signal == null, "request already sent", "UNSUPPORTED_OPERATION", { + operation: "fetchRequest.send" + }); + this.#signal = new FetchCancelSignal(this); + return this.#send(0, getTime$2() + this.timeout, 0, this, new FetchResponse(0, "", {}, null, this)); + } + cancel() { + assert1(this.#signal != null, "request has not been sent", "UNSUPPORTED_OPERATION", { + operation: "fetchRequest.cancel" + }); + const signal = fetchSignals.get(this); + if (!signal) { + throw new Error("missing signal; should not happen"); + } + signal(); + } + redirect(location) { + const current = this.url.split(":")[0].toLowerCase(); + const target = location.split(":")[0].toLowerCase(); + assert1(this.method === "GET" && (current !== "https" || target !== "http") && location.match(/^https?:/), `unsupported redirect`, "UNSUPPORTED_OPERATION", { + operation: `redirect(${this.method} ${JSON.stringify(this.url)} => ${JSON.stringify(location)})` + }); + const req = new FetchRequest(location); + req.method = "GET"; + req.allowGzip = this.allowGzip; + req.timeout = this.timeout; + req.#headers = Object.assign({}, this.#headers); + if (this.#body) { + req.#body = new Uint8Array(this.#body); + } + req.#bodyType = this.#bodyType; + return req; + } + clone() { + const clone = new FetchRequest(this.url); + clone.#method = this.#method; + if (this.#body) { + clone.#body = this.#body; + } + clone.#bodyType = this.#bodyType; + clone.#headers = Object.assign({}, this.#headers); + clone.#creds = this.#creds; + if (this.allowGzip) { + clone.allowGzip = true; + } + clone.timeout = this.timeout; + if (this.allowInsecureAuthentication) { + clone.allowInsecureAuthentication = true; + } + clone.#preflight = this.#preflight; + clone.#process = this.#process; + clone.#retry = this.#retry; + clone.#throttle = Object.assign({}, this.#throttle); + clone.#getUrlFunc = this.#getUrlFunc; + return clone; + } + static lockConfig() { + locked$5 = true; + } + static getGateway(scheme) { + return Gateways[scheme.toLowerCase()] || null; + } + static registerGateway(scheme, func) { + scheme = scheme.toLowerCase(); + if (scheme === "http" || scheme === "https") { + throw new Error(`cannot intercept ${scheme}; use registerGetUrl`); + } + if (locked$5) { + throw new Error("gateways locked"); + } + Gateways[scheme] = func; + } + static registerGetUrl(getUrl) { + if (locked$5) { + throw new Error("gateways locked"); + } + defaultGetUrlFunc = getUrl; + } + static createGetUrlFunc(options) { + return createGetUrl(); + } + static createDataGateway() { + return dataGatewayFunc; + } + static createIpfsGatewayFunc(baseUrl) { + return getIpfsGatewayFunc(baseUrl); + } +} +class FetchResponse { + #statusCode; + #statusMessage; + #headers; + #body; + #request; + #error; + toString() { + return ``; + } + get statusCode() { + return this.#statusCode; + } + get statusMessage() { + return this.#statusMessage; + } + get headers() { + return Object.assign({}, this.#headers); + } + get body() { + return this.#body == null ? null : new Uint8Array(this.#body); + } + get bodyText() { + try { + return this.#body == null ? "" : toUtf8String(this.#body); + } catch (error) { + assert1(false, "response body is not valid UTF-8 data", "UNSUPPORTED_OPERATION", { + operation: "bodyText", + info: { + response: this + } + }); + } + } + get bodyJson() { + try { + return JSON.parse(this.bodyText); + } catch (error) { + assert1(false, "response body is not valid JSON", "UNSUPPORTED_OPERATION", { + operation: "bodyJson", + info: { + response: this } - if (mode === "mod") { + }); + } + } + [Symbol.iterator]() { + const headers = this.headers; + const keys = Object.keys(headers); + let index = 0; + return { + next: ()=>{ + if (index < keys.length) { + const key = keys[index++]; return { - div: null, - mod: new BN2(this.modrn(num.words[0])) + value: [ + key, + headers[key] + ], + done: false }; } return { - div: this.divn(num.words[0]), - mod: new BN2(this.modrn(num.words[0])) + value: undefined, + done: true }; } - return this._wordDiv(num, mode); - }; - BN2.prototype.div = function div(num) { - return this.divmod(num, "div", false).div; - }; - BN2.prototype.mod = function mod(num) { - return this.divmod(num, "mod", false).mod; }; - BN2.prototype.umod = function umod(num) { - return this.divmod(num, "mod", true).mod; - }; - BN2.prototype.divRound = function divRound(num) { - var dm = this.divmod(num); - if (dm.mod.isZero()) return dm.div; - var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; - var half = num.ushrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; - return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); - }; - BN2.prototype.modrn = function modrn(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - assert(num <= 67108863); - var p = (1 << 26) % num; - var acc = 0; - for(var i = this.length - 1; i >= 0; i--){ - acc = (p * acc + (this.words[i] | 0)) % num; - } - return isNegNum ? -acc : acc; - }; - BN2.prototype.modn = function modn(num) { - return this.modrn(num); - }; - BN2.prototype.idivn = function idivn(num) { - var isNegNum = num < 0; - if (isNegNum) num = -num; - assert(num <= 67108863); - var carry = 0; - for(var i = this.length - 1; i >= 0; i--){ - var w = (this.words[i] | 0) + carry * 67108864; - this.words[i] = w / num | 0; - carry = w % num; - } - this._strip(); - return isNegNum ? this.ineg() : this; + } + constructor(statusCode, statusMessage, headers, body, request){ + this.#statusCode = statusCode; + this.#statusMessage = statusMessage; + this.#headers = Object.keys(headers).reduce((accum, k)=>{ + accum[k.toLowerCase()] = String(headers[k]); + return accum; + }, {}); + this.#body = body == null ? null : new Uint8Array(body); + this.#request = request || null; + this.#error = { + message: "" }; - BN2.prototype.divn = function divn(num) { - return this.clone().idivn(num); + } + makeServerError(message, error) { + let statusMessage; + if (!message) { + message = `${this.statusCode} ${this.statusMessage}`; + statusMessage = `CLIENT ESCALATED SERVER ERROR (${message})`; + } else { + statusMessage = `CLIENT ESCALATED SERVER ERROR (${this.statusCode} ${this.statusMessage}; ${message})`; + } + const response = new FetchResponse(599, statusMessage, this.headers, this.body, this.#request || undefined); + response.#error = { + message: message, + error: error }; - BN2.prototype.egcd = function egcd(p) { - assert(p.negative === 0); - assert(!p.isZero()); - var x = this; - var y = p.clone(); - if (x.negative !== 0) { - x = x.umod(p); - } else { - x = x.clone(); - } - var A = new BN2(1); - var B = new BN2(0); - var C = new BN2(0); - var D = new BN2(1); - var g = 0; - while(x.isEven() && y.isEven()){ - x.iushrn(1); - y.iushrn(1); - ++g; - } - var yp = y.clone(); - var xp = x.clone(); - while(!x.isZero()){ - for(var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - x.iushrn(i); - while(i-- > 0){ - if (A.isOdd() || B.isOdd()) { - A.iadd(yp); - B.isub(xp); - } - A.iushrn(1); - B.iushrn(1); - } - } - for(var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - y.iushrn(j); - while(j-- > 0){ - if (C.isOdd() || D.isOdd()) { - C.iadd(yp); - D.isub(xp); - } - C.iushrn(1); - D.iushrn(1); - } - } - if (x.cmp(y) >= 0) { - x.isub(y); - A.isub(C); - B.isub(D); - } else { - y.isub(x); - C.isub(A); - D.isub(B); - } + return response; + } + throwThrottleError(message, stall) { + if (stall == null) { + stall = -1; + } else { + assertArgument(Number.isInteger(stall) && stall >= 0, "invalid stall timeout", "stall", stall); + } + const error = new Error(message || "throttling requests"); + defineProperties(error, { + stall: stall, + throttle: true + }); + throw error; + } + getHeader(key) { + return this.headers[key.toLowerCase()]; + } + hasBody() { + return this.#body != null; + } + get request() { + return this.#request; + } + ok() { + return this.#error.message === "" && this.statusCode >= 200 && this.statusCode < 300; + } + assertOk() { + if (this.ok()) { + return; + } + let { message, error } = this.#error; + if (message === "") { + message = `server response ${this.statusCode} ${this.statusMessage}`; + } + let requestUrl = null; + if (this.request) { + requestUrl = this.request.url; + } + let responseBody = null; + try { + if (this.#body) { + responseBody = toUtf8String(this.#body); } - return { - a: C, - b: D, - gcd: y.iushln(g) - }; - }; - BN2.prototype._invmp = function _invmp(p) { - assert(p.negative === 0); - assert(!p.isZero()); - var a = this; - var b = p.clone(); - if (a.negative !== 0) { - a = a.umod(p); - } else { - a = a.clone(); - } - var x1 = new BN2(1); - var x2 = new BN2(0); - var delta = b.clone(); - while(a.cmpn(1) > 0 && b.cmpn(1) > 0){ - for(var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); - if (i > 0) { - a.iushrn(i); - while(i-- > 0){ - if (x1.isOdd()) { - x1.iadd(delta); - } - x1.iushrn(1); - } - } - for(var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); - if (j > 0) { - b.iushrn(j); - while(j-- > 0){ - if (x2.isOdd()) { - x2.iadd(delta); - } - x2.iushrn(1); - } - } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - var res; - if (a.cmpn(1) === 0) { - res = x1; - } else { - res = x2; - } - if (res.cmpn(0) < 0) { - res.iadd(p); - } - return res; - }; - BN2.prototype.gcd = function gcd(num) { - if (this.isZero()) return num.abs(); - if (num.isZero()) return this.abs(); - var a = this.clone(); - var b = num.clone(); - a.negative = 0; - b.negative = 0; - for(var shift = 0; a.isEven() && b.isEven(); shift++){ - a.iushrn(1); - b.iushrn(1); - } - do { - while(a.isEven()){ - a.iushrn(1); - } - while(b.isEven()){ - b.iushrn(1); - } - var r = a.cmp(b); - if (r < 0) { - var t = a; - a = b; - b = t; - } else if (r === 0 || b.cmpn(1) === 0) { - break; - } - a.isub(b); - }while (true) - return b.iushln(shift); - }; - BN2.prototype.invm = function invm(num) { - return this.egcd(num).a.umod(num); - }; - BN2.prototype.isEven = function isEven() { - return (this.words[0] & 1) === 0; - }; - BN2.prototype.isOdd = function isOdd() { - return (this.words[0] & 1) === 1; - }; - BN2.prototype.andln = function andln(num) { - return this.words[0] & num; - }; - BN2.prototype.bincn = function bincn(bit) { - assert(typeof bit === "number"); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - if (this.length <= s) { - this._expand(s + 1); - this.words[s] |= q; - return this; - } - var carry = q; - for(var i = s; carry !== 0 && i < this.length; i++){ - var w = this.words[i] | 0; - w += carry; - carry = w >>> 26; - w &= 67108863; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; - }; - BN2.prototype.isZero = function isZero() { - return this.length === 1 && this.words[0] === 0; - }; - BN2.prototype.cmpn = function cmpn(num) { - var negative = num < 0; - if (this.negative !== 0 && !negative) return -1; - if (this.negative === 0 && negative) return 1; - this._strip(); - var res; - if (this.length > 1) { - res = 1; - } else { - if (negative) { - num = -num; - } - assert(num <= 67108863, "Number is too big"); - var w = this.words[0] | 0; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.negative !== 0) return -res | 0; - return res; - }; - BN2.prototype.cmp = function cmp(num) { - if (this.negative !== 0 && num.negative === 0) return -1; - if (this.negative === 0 && num.negative !== 0) return 1; - var res = this.ucmp(num); - if (this.negative !== 0) return -res | 0; - return res; - }; - BN2.prototype.ucmp = function ucmp(num) { - if (this.length > num.length) return 1; - if (this.length < num.length) return -1; - var res = 0; - for(var i = this.length - 1; i >= 0; i--){ - var a = this.words[i] | 0; - var b = num.words[i] | 0; - if (a === b) continue; - if (a < b) { - res = -1; - } else if (a > b) { - res = 1; - } - break; - } - return res; - }; - BN2.prototype.gtn = function gtn(num) { - return this.cmpn(num) === 1; - }; - BN2.prototype.gt = function gt(num) { - return this.cmp(num) === 1; - }; - BN2.prototype.gten = function gten(num) { - return this.cmpn(num) >= 0; - }; - BN2.prototype.gte = function gte(num) { - return this.cmp(num) >= 0; - }; - BN2.prototype.ltn = function ltn(num) { - return this.cmpn(num) === -1; - }; - BN2.prototype.lt = function lt(num) { - return this.cmp(num) === -1; - }; - BN2.prototype.lten = function lten(num) { - return this.cmpn(num) <= 0; - }; - BN2.prototype.lte = function lte(num) { - return this.cmp(num) <= 0; - }; - BN2.prototype.eqn = function eqn(num) { - return this.cmpn(num) === 0; - }; - BN2.prototype.eq = function eq(num) { - return this.cmp(num) === 0; - }; - BN2.red = function red(num) { - return new Red(num); - }; - BN2.prototype.toRed = function toRed(ctx) { - assert(!this.red, "Already a number in reduction context"); - assert(this.negative === 0, "red works only with positives"); - return ctx.convertTo(this)._forceRed(ctx); - }; - BN2.prototype.fromRed = function fromRed() { - assert(this.red, "fromRed works only with numbers in reduction context"); - return this.red.convertFrom(this); - }; - BN2.prototype._forceRed = function _forceRed(ctx) { - this.red = ctx; - return this; - }; - BN2.prototype.forceRed = function forceRed(ctx) { - assert(!this.red, "Already a number in reduction context"); - return this._forceRed(ctx); - }; - BN2.prototype.redAdd = function redAdd(num) { - assert(this.red, "redAdd works only with red numbers"); - return this.red.add(this, num); - }; - BN2.prototype.redIAdd = function redIAdd(num) { - assert(this.red, "redIAdd works only with red numbers"); - return this.red.iadd(this, num); - }; - BN2.prototype.redSub = function redSub(num) { - assert(this.red, "redSub works only with red numbers"); - return this.red.sub(this, num); - }; - BN2.prototype.redISub = function redISub(num) { - assert(this.red, "redISub works only with red numbers"); - return this.red.isub(this, num); - }; - BN2.prototype.redShl = function redShl(num) { - assert(this.red, "redShl works only with red numbers"); - return this.red.shl(this, num); - }; - BN2.prototype.redMul = function redMul(num) { - assert(this.red, "redMul works only with red numbers"); - this.red._verify2(this, num); - return this.red.mul(this, num); - }; - BN2.prototype.redIMul = function redIMul(num) { - assert(this.red, "redMul works only with red numbers"); - this.red._verify2(this, num); - return this.red.imul(this, num); - }; - BN2.prototype.redSqr = function redSqr() { - assert(this.red, "redSqr works only with red numbers"); - this.red._verify1(this); - return this.red.sqr(this); - }; - BN2.prototype.redISqr = function redISqr() { - assert(this.red, "redISqr works only with red numbers"); - this.red._verify1(this); - return this.red.isqr(this); - }; - BN2.prototype.redSqrt = function redSqrt() { - assert(this.red, "redSqrt works only with red numbers"); - this.red._verify1(this); - return this.red.sqrt(this); - }; - BN2.prototype.redInvm = function redInvm() { - assert(this.red, "redInvm works only with red numbers"); - this.red._verify1(this); - return this.red.invm(this); - }; - BN2.prototype.redNeg = function redNeg() { - assert(this.red, "redNeg works only with red numbers"); - this.red._verify1(this); - return this.red.neg(this); - }; - BN2.prototype.redPow = function redPow(num) { - assert(this.red && !num.red, "redPow(normalNum)"); - this.red._verify1(this); - return this.red.pow(this, num); - }; - var primes = { - k256: null, - p224: null, - p192: null, - p25519: null - }; - function MPrime(name, p) { - this.name = name; - this.p = new BN2(p, 16); - this.n = this.p.bitLength(); - this.k = new BN2(1).iushln(this.n).isub(this.p); - this.tmp = this._tmp(); - } - MPrime.prototype._tmp = function _tmp() { - var tmp = new BN2(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; - }; - MPrime.prototype.ireduce = function ireduce(num) { - var r = num; - var rlen; - do { - this.split(r, this.tmp); - r = this.imulK(r); - r = r.iadd(this.tmp); - rlen = r.bitLength(); - }while (rlen > this.n) - var cmp = rlen < this.n ? -1 : r.ucmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - if (r.strip !== void 0) { - r.strip(); - } else { - r._strip(); - } - } - return r; - }; - MPrime.prototype.split = function split(input, out) { - input.iushrn(this.n, 0, out); - }; - MPrime.prototype.imulK = function imulK(num) { - return num.imul(this.k); - }; - function K256() { - MPrime.call(this, "k256", "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f"); - } - inherits(K256, MPrime); - K256.prototype.split = function split(input, output) { - var mask = 4194303; - var outLen = Math.min(input.length, 9); - for(var i = 0; i < outLen; i++){ - output.words[i] = input.words[i]; - } - output.length = outLen; - if (input.length <= 9) { - input.words[0] = 0; - input.length = 1; - return; - } - var prev = input.words[9]; - output.words[output.length++] = prev & mask; - for(i = 10; i < input.length; i++){ - var next = input.words[i] | 0; - input.words[i - 10] = (next & mask) << 4 | prev >>> 22; - prev = next; - } - prev >>>= 22; - input.words[i - 10] = prev; - if (prev === 0 && input.length > 10) { - input.length -= 10; - } else { - input.length -= 9; - } - }; - K256.prototype.imulK = function imulK(num) { - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - var lo = 0; - for(var i = 0; i < num.length; i++){ - var w = num.words[i] | 0; - lo += w * 977; - num.words[i] = lo & 67108863; - lo = w * 64 + (lo / 67108864 | 0); - } - if (num.words[num.length - 1] === 0) { - num.length--; - if (num.words[num.length - 1] === 0) { - num.length--; - } - } - return num; - }; - function P224() { - MPrime.call(this, "p224", "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001"); - } - inherits(P224, MPrime); - function P192() { - MPrime.call(this, "p192", "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff"); - } - inherits(P192, MPrime); - function P25519() { - MPrime.call(this, "25519", "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed"); - } - inherits(P25519, MPrime); - P25519.prototype.imulK = function imulK(num) { - var carry = 0; - for(var i = 0; i < num.length; i++){ - var hi = (num.words[i] | 0) * 19 + carry; - var lo = hi & 67108863; - hi >>>= 26; - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) { - num.words[num.length++] = carry; - } - return num; - }; - BN2._prime = function prime(name) { - if (primes[name]) return primes[name]; - var prime2; - if (name === "k256") { - prime2 = new K256(); - } else if (name === "p224") { - prime2 = new P224(); - } else if (name === "p192") { - prime2 = new P192(); - } else if (name === "p25519") { - prime2 = new P25519(); - } else { - throw new Error("Unknown prime " + name); - } - primes[name] = prime2; - return prime2; - }; - function Red(m) { - if (typeof m === "string") { - var prime = BN2._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - assert(m.gtn(1), "modulus must be greater than 1"); - this.m = m; - this.prime = null; - } - } - Red.prototype._verify1 = function _verify1(a) { - assert(a.negative === 0, "red works only with positives"); - assert(a.red, "red works only with red numbers"); - }; - Red.prototype._verify2 = function _verify2(a, b) { - assert((a.negative | b.negative) === 0, "red works only with positives"); - assert(a.red && a.red === b.red, "red works only with red numbers"); - }; - Red.prototype.imod = function imod(a) { - if (this.prime) return this.prime.ireduce(a)._forceRed(this); - move(a, a.umod(this.m)._forceRed(this)); - return a; - }; - Red.prototype.neg = function neg(a) { - if (a.isZero()) { - return a.clone(); - } - return this.m.sub(a)._forceRed(this); - }; - Red.prototype.add = function add(a, b) { - this._verify2(a, b); - var res = a.add(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res._forceRed(this); - }; - Red.prototype.iadd = function iadd(a, b) { - this._verify2(a, b); - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) { - res.isub(this.m); - } - return res; - }; - Red.prototype.sub = function sub(a, b) { - this._verify2(a, b); - var res = a.sub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res._forceRed(this); - }; - Red.prototype.isub = function isub(a, b) { - this._verify2(a, b); - var res = a.isub(b); - if (res.cmpn(0) < 0) { - res.iadd(this.m); - } - return res; - }; - Red.prototype.shl = function shl(a, num) { - this._verify1(a); - return this.imod(a.ushln(num)); - }; - Red.prototype.imul = function imul(a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); - }; - Red.prototype.mul = function mul(a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); - }; - Red.prototype.isqr = function isqr(a) { - return this.imul(a, a.clone()); - }; - Red.prototype.sqr = function sqr(a) { - return this.mul(a, a); - }; - Red.prototype.sqrt = function sqrt(a) { - if (a.isZero()) return a.clone(); - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - if (mod3 === 3) { - var pow = this.m.add(new BN2(1)).iushrn(2); - return this.pow(a, pow); - } - var q = this.m.subn(1); - var s = 0; - while(!q.isZero() && q.andln(1) === 0){ - s++; - q.iushrn(1); - } - assert(!q.isZero()); - var one = new BN2(1).toRed(this); - var nOne = one.redNeg(); - var lpow = this.m.subn(1).iushrn(1); - var z = this.m.bitLength(); - z = new BN2(2 * z * z).toRed(this); - while(this.pow(z, lpow).cmp(nOne) !== 0){ - z.redIAdd(nOne); - } - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).iushrn(1)); - var t = this.pow(a, q); - var m = s; - while(t.cmp(one) !== 0){ - var tmp = t; - for(var i = 0; tmp.cmp(one) !== 0; i++){ - tmp = tmp.redSqr(); - } - assert(i < m); - var b = this.pow(c, new BN2(1).iushln(m - i - 1)); - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - return r; - }; - Red.prototype.invm = function invm(a) { - var inv = a._invmp(this.m); - if (inv.negative !== 0) { - inv.negative = 0; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } - }; - Red.prototype.pow = function pow(a, num) { - if (num.isZero()) return new BN2(1).toRed(this); - if (num.cmpn(1) === 0) return a.clone(); - var windowSize = 4; - var wnd = new Array(1 << windowSize); - wnd[0] = new BN2(1).toRed(this); - wnd[1] = a; - for(var i = 2; i < wnd.length; i++){ - wnd[i] = this.mul(wnd[i - 1], a); - } - var res = wnd[0]; - var current = 0; - var currentLen = 0; - var start = num.bitLength() % 26; - if (start === 0) { - start = 26; - } - for(i = num.length - 1; i >= 0; i--){ - var word = num.words[i]; - for(var j = start - 1; j >= 0; j--){ - var bit = word >> j & 1; - if (res !== wnd[0]) { - res = this.sqr(res); - } - if (bit === 0 && current === 0) { - currentLen = 0; - continue; - } - current <<= 1; - current |= bit; - currentLen++; - if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; - res = this.mul(res, wnd[current]); - currentLen = 0; - current = 0; - } - start = 26; - } - return res; - }; - Red.prototype.convertTo = function convertTo(num) { - var r = num.umod(this.m); - return r === num ? r.clone() : r; - }; - Red.prototype.convertFrom = function convertFrom(num) { - var res = num.clone(); - res.red = null; - return res; - }; - BN2.mont = function mont(num) { - return new Mont(num); - }; - function Mont(m) { - Red.call(this, m); - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) { - this.shift += 26 - this.shift % 26; - } - this.r = new BN2(1).iushln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r._invmp(this.m); - this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); - this.minv = this.minv.umod(this.r); - this.minv = this.r.sub(this.minv); - } - inherits(Mont, Red); - Mont.prototype.convertTo = function convertTo(num) { - return this.imod(num.ushln(this.shift)); - }; - Mont.prototype.convertFrom = function convertFrom(num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; - }; - Mont.prototype.imul = function imul(a, b) { - if (a.isZero() || b.isZero()) { - a.words[0] = 0; - a.length = 1; - return a; - } - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - return res._forceRed(this); - }; - Mont.prototype.mul = function mul(a, b) { - if (a.isZero() || b.isZero()) return new BN2(0)._forceRed(this); - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).iushrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) { - res = u.isub(this.m); - } else if (u.cmpn(0) < 0) { - res = u.iadd(this.m); - } - return res._forceRed(this); - }; - Mont.prototype.invm = function invm(a) { - var res = this.imod(a._invmp(this.m).mul(this.r2)); - return res._forceRed(this); - }; - })(module, commonjsGlobal); -}); -bn.BN; -const version = "logger/5.7.0"; -let _permanentCensorErrors = false; -let _censorErrors = false; -const LogLevels = { - debug: 1, - default: 2, - info: 2, - warning: 3, - error: 4, - off: 5 -}; -let _logLevel = LogLevels["default"]; -let _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); + } catch (e) {} + assert1(false, message, "SERVER_ERROR", { + request: this.request || "unknown request", + response: this, + error: error, + info: { + requestUrl: requestUrl, + responseBody: responseBody, + responseStatus: `${this.statusCode} ${this.statusMessage}` } }); - 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; } -const _normalizeError = _checkNormalize(); -var LogLevel; -(function(LogLevel2) { - LogLevel2["DEBUG"] = "DEBUG"; - LogLevel2["INFO"] = "INFO"; - LogLevel2["WARNING"] = "WARNING"; - LogLevel2["ERROR"] = "ERROR"; - LogLevel2["OFF"] = "OFF"; -})(LogLevel || (LogLevel = {})); -var ErrorCode; -(function(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"; -})(ErrorCode || (ErrorCode = {})); -const HEX = "0123456789abcdef"; -class Logger { - constructor(version2){ - Object.defineProperty(this, "version", { - enumerable: true, - value: version2, - writable: false +function getTime$2() { + return (new Date).getTime(); +} +function unpercent(value) { + return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code)=>{ + return String.fromCharCode(parseInt(code, 16)); + })); +} +function wait(delay) { + return new Promise((resolve)=>setTimeout(resolve, delay)); +} +const BN_N1 = BigInt(-1); +const BN_0$8 = BigInt(0); +const BN_1$4 = BigInt(1); +const BN_5 = BigInt(5); +const _guard$5 = {}; +let Zeros$1 = "0000"; +while(Zeros$1.length < 80){ + Zeros$1 += Zeros$1; +} +function getTens(decimals) { + let result = Zeros$1; + while(result.length < decimals){ + result += result; + } + return BigInt("1" + result.substring(0, decimals)); +} +function checkValue(val, format, safeOp) { + const width = BigInt(format.width); + if (format.signed) { + const limit = BN_1$4 << width - BN_1$4; + assert1(safeOp == null || val >= -limit && val < limit, "overflow", "NUMERIC_FAULT", { + operation: safeOp, + fault: "overflow", + value: val }); - } - _log(logLevel, args) { - const level = logLevel.toLowerCase(); - if (LogLevels[level] == null) { - this.throwArgumentError("invalid log level name", "logLevel", logLevel); - } - if (_logLevel > LogLevels[level]) { - return; + if (val > BN_0$8) { + val = fromTwos(mask(val, width), width); + } else { + val = -fromTwos(mask(-val, width), width); } - console.log.apply(console, args); + } else { + const limit = BN_1$4 << width; + assert1(safeOp == null || val >= 0 && val < limit, "overflow", "NUMERIC_FAULT", { + operation: safeOp, + fault: "overflow", + value: val + }); + val = (val % limit + limit) % limit & limit - BN_1$4; + } + return val; +} +function getFormat(value) { + if (typeof value === "number") { + value = `fixed128x${value}`; } - debug(...args) { - this._log(Logger.levels.DEBUG, args); + let signed = true; + let width = 128; + let decimals = 18; + if (typeof value === "string") { + if (value === "fixed") ; + else if (value === "ufixed") { + signed = false; + } else { + const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); + assertArgument(match, "invalid fixed format", "format", value); + signed = match[1] !== "u"; + width = parseInt(match[2]); + decimals = parseInt(match[3]); + } + } else if (value) { + const v = value; + const check = (key, type, defaultValue)=>{ + if (v[key] == null) { + return defaultValue; + } + assertArgument(typeof v[key] === type, "invalid fixed format (" + key + " not " + type + ")", "format." + key, v[key]); + return v[key]; + }; + signed = check("signed", "boolean", signed); + width = check("width", "number", width); + decimals = check("decimals", "number", decimals); + } + assertArgument(width % 8 === 0, "invalid FixedNumber width (not byte aligned)", "format.width", width); + assertArgument(decimals <= 80, "invalid FixedNumber decimals (too large)", "format.decimals", decimals); + const name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); + return { + signed: signed, + width: width, + decimals: decimals, + name: name + }; +} +function toString(val, decimals) { + let negative = ""; + if (val < BN_0$8) { + negative = "-"; + val *= BN_N1; } - info(...args) { - this._log(Logger.levels.INFO, args); + let str = val.toString(); + if (decimals === 0) { + return negative + str; } - warn(...args) { - this._log(Logger.levels.WARNING, args); + while(str.length <= decimals){ + str = Zeros$1 + str; } - 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 ErrorCode.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 ErrorCode.CALL_EXCEPTION: - case ErrorCode.INSUFFICIENT_FUNDS: - case ErrorCode.MISSING_NEW: - case ErrorCode.NONCE_EXPIRED: - case ErrorCode.REPLACEMENT_UNDERPRICED: - case ErrorCode.TRANSACTION_REPLACED: - case ErrorCode.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; + const index = str.length - decimals; + str = str.substring(0, index) + "." + str.substring(index); + while(str[0] === "0" && str[1] !== "."){ + str = str.substring(1); } - throwError(message, code, params) { - throw this.makeError(message, code, params); + while(str[str.length - 1] === "0" && str[str.length - 2] !== "."){ + str = str.substring(0, str.length - 1); } - throwArgumentError(message, name, value) { - return this.throwError(message, Logger.errors.INVALID_ARGUMENT, { - argument: name, - value + return negative + str; +} +class FixedNumber { + format; + #format; + #val; + #tens; + _value; + constructor(guard, value, format){ + assertPrivate(guard, _guard$5, "FixedNumber"); + this.#val = value; + this.#format = format; + const _value = toString(value, format.decimals); + defineProperties(this, { + format: format.name, + _value: _value }); + this.#tens = getTens(format.decimals); } - assert(condition, message, code, params) { - if (!!condition) { - return; - } - this.throwError(message, code, params); + get signed() { + return this.#format.signed; } - assertArgument(condition, message, name, value) { - if (!!condition) { - return; - } - this.throwArgumentError(message, name, value); + get width() { + return this.#format.width; } - checkNormalize(message) { - if (_normalizeError) { - this.throwError("platform missing String.prototype.normalize", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "String.prototype.normalize", - form: _normalizeError - }); - } + get decimals() { + return this.#format.decimals; } - 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 - }); - } + get value() { + return this.#val; } - 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 - }); - } + #checkFormat(other) { + assertArgument(this.format === other.format, "incompatible format; use fixedNumber.toFormat", "other", other); } - checkNew(target, kind) { - if (target === Object || target == null) { - this.throwError("missing new", Logger.errors.MISSING_NEW, { - name: kind.name - }); - } + #checkValue(val, safeOp) { + val = checkValue(val, this.#format, safeOp); + return new FixedNumber(_guard$5, val, this.#format); } - 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 - }); - } + #add(o, safeOp) { + this.#checkFormat(o); + return this.#checkValue(this.#val + o.#val, safeOp); } - static globalLogger() { - if (!_globalLogger) { - _globalLogger = new Logger(version); - } - return _globalLogger; + addUnsafe(other) { + return this.#add(other); } - 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; + add(other) { + return this.#add(other, "add"); } - static setLogLevel(logLevel) { - const level = LogLevels[logLevel.toLowerCase()]; - if (level == null) { - Logger.globalLogger().warn("invalid log level - " + logLevel); - return; - } - _logLevel = level; + #sub(o, safeOp) { + this.#checkFormat(o); + return this.#checkValue(this.#val - o.#val, safeOp); } - static from(version2) { - return new Logger(version2); + subUnsafe(other) { + return this.#sub(other); } -} -Logger.errors = ErrorCode; -Logger.levels = LogLevel; -const version1 = "bytes/5.7.0"; -const logger2 = new Logger(version1); -function isHexable(value) { - return !!value.toHexString; -} -function addSlice(array) { - if (array.slice) { - return array; + sub(other) { + return this.#sub(other, "sub"); } - array.slice = function() { - const args = Array.prototype.slice.call(arguments); - return addSlice(new Uint8Array(Array.prototype.slice.apply(array, args))); - }; - return array; -} -function isBytesLike(value) { - return isHexString(value) && !(value.length % 2) || isBytes(value); -} -function isInteger(value) { - return typeof value === "number" && value == value && value % 1 === 0; -} -function isBytes(value) { - if (value == null) { - return false; + #mul(o, safeOp) { + this.#checkFormat(o); + return this.#checkValue(this.#val * o.#val / this.#tens, safeOp); } - if (value.constructor === Uint8Array) { - return true; + mulUnsafe(other) { + return this.#mul(other); } - if (typeof value === "string") { - return false; + mul(other) { + return this.#mul(other, "mul"); + } + mulSignal(other) { + this.#checkFormat(other); + const value = this.#val * other.#val; + assert1(value % this.#tens === BN_0$8, "precision lost during signalling mul", "NUMERIC_FAULT", { + operation: "mulSignal", + fault: "underflow", + value: this + }); + return this.#checkValue(value / this.#tens, "mulSignal"); } - if (!isInteger(value.length) || value.length < 0) { - return false; + #div(o, safeOp) { + assert1(o.#val !== BN_0$8, "division by zero", "NUMERIC_FAULT", { + operation: "div", + fault: "divide-by-zero", + value: this + }); + this.#checkFormat(o); + return this.#checkValue(this.#val * this.#tens / o.#val, safeOp); } - for(let i = 0; i < value.length; i++){ - const v = value[i]; - if (!isInteger(v) || v < 0 || v >= 256) { - return false; - } + divUnsafe(other) { + return this.#div(other); } - return true; -} -function arrayify(value, options) { - if (!options) { - options = {}; + div(other) { + return this.#div(other, "div"); } - if (typeof value === "number") { - logger2.checkSafeUint53(value, "invalid arrayify value"); - const result = []; - while(value){ - result.unshift(value & 255); - value = parseInt(String(value / 256)); - } - if (result.length === 0) { - result.push(0); - } - return addSlice(new Uint8Array(result)); - } - if (options.allowMissingPrefix && typeof value === "string" && value.substring(0, 2) !== "0x") { - value = "0x" + value; - } - if (isHexable(value)) { - value = value.toHexString(); + divSignal(other) { + assert1(other.#val !== BN_0$8, "division by zero", "NUMERIC_FAULT", { + operation: "div", + fault: "divide-by-zero", + value: this + }); + this.#checkFormat(other); + const value = this.#val * this.#tens; + assert1(value % other.#val === BN_0$8, "precision lost during signalling div", "NUMERIC_FAULT", { + operation: "divSignal", + fault: "underflow", + value: this + }); + return this.#checkValue(value / other.#val, "divSignal"); } - if (isHexString(value)) { - let hex = value.substring(2); - if (hex.length % 2) { - if (options.hexPad === "left") { - hex = "0" + hex; - } else if (options.hexPad === "right") { - hex += "0"; - } else { - logger2.throwArgumentError("hex data is odd-length", "value", value); - } + cmp(other) { + let a = this.value, b = other.value; + const delta = this.decimals - other.decimals; + if (delta > 0) { + b *= getTens(delta); + } else if (delta < 0) { + a *= getTens(-delta); } - const result = []; - for(let i = 0; i < hex.length; i += 2){ - result.push(parseInt(hex.substring(i, i + 2), 16)); + if (a < b) { + return -1; } - return addSlice(new Uint8Array(result)); - } - if (isBytes(value)) { - return addSlice(new Uint8Array(value)); + if (a > b) { + return 1; + } + return 0; } - return logger2.throwArgumentError("invalid arrayify value", "value", value); -} -function concat(items) { - const objects = items.map((item)=>arrayify(item)); - const length = objects.reduce((accum, item)=>accum + item.length, 0); - const result = new Uint8Array(length); - objects.reduce((offset, object)=>{ - result.set(object, offset); - return offset + object.length; - }, 0); - return addSlice(result); -} -function stripZeros(value) { - let result = arrayify(value); - if (result.length === 0) { - return result; + eq(other) { + return this.cmp(other) === 0; } - let start = 0; - while(start < result.length && result[start] === 0){ - start++; + lt(other) { + return this.cmp(other) < 0; } - if (start) { - result = result.slice(start); + lte(other) { + return this.cmp(other) <= 0; } - return result; -} -function zeroPad(value, length) { - value = arrayify(value); - if (value.length > length) { - logger2.throwArgumentError("value out of range", "value", arguments[0]); + gt(other) { + return this.cmp(other) > 0; } - const result = new Uint8Array(length); - result.set(value, length - value.length); - return addSlice(result); -} -function isHexString(value, length) { - if (typeof value !== "string" || !value.match(/^0x[0-9A-Fa-f]*$/)) { - return false; + gte(other) { + return this.cmp(other) >= 0; } - if (length && value.length !== 2 + 2 * length) { - return false; + floor() { + let val = this.#val; + if (this.#val < BN_0$8) { + val -= this.#tens - BN_1$4; + } + val = this.#val / this.#tens * this.#tens; + return this.#checkValue(val, "floor"); } - return true; -} -const HexCharacters = "0123456789abcdef"; -function hexlify(value, options) { - if (!options) { - options = {}; + ceiling() { + let val = this.#val; + if (this.#val > BN_0$8) { + val += this.#tens - BN_1$4; + } + val = this.#val / this.#tens * this.#tens; + return this.#checkValue(val, "ceiling"); } - if (typeof value === "number") { - logger2.checkSafeUint53(value, "invalid hexlify value"); - let hex = ""; - while(value){ - hex = HexCharacters[value & 15] + hex; - value = Math.floor(value / 16); + round(decimals) { + if (decimals == null) { + decimals = 0; } - if (hex.length) { - if (hex.length % 2) { - hex = "0" + hex; - } - return "0x" + hex; + if (decimals >= this.decimals) { + return this; } - return "0x00"; + const delta = this.decimals - decimals; + const bump = BN_5 * getTens(delta - 1); + let value = this.value + bump; + const tens = getTens(delta); + value = value / tens * tens; + checkValue(value, this.#format, "round"); + return new FixedNumber(_guard$5, value, this.#format); } - if (typeof value === "bigint") { - value = value.toString(16); - if (value.length % 2) { - return "0x0" + value; - } - return "0x" + value; + isZero() { + return this.#val === BN_0$8; + } + isNegative() { + return this.#val < BN_0$8; } - if (options.allowMissingPrefix && typeof value === "string" && value.substring(0, 2) !== "0x") { - value = "0x" + value; + toString() { + return this._value; } - if (isHexable(value)) { - return value.toHexString(); + toUnsafeFloat() { + return parseFloat(this.toString()); } - if (isHexString(value)) { - if (value.length % 2) { - if (options.hexPad === "left") { - value = "0x0" + value.substring(2); - } else if (options.hexPad === "right") { - value += "0"; - } else { - logger2.throwArgumentError("hex data is odd-length", "value", value); - } - } - return value.toLowerCase(); + toFormat(format) { + return FixedNumber.fromString(this.toString(), format); + } + static fromValue(_value, _decimals, _format) { + const decimals = _decimals == null ? 0 : getNumber(_decimals); + const format = getFormat(_format); + let value = getBigInt(_value, "value"); + const delta = decimals - format.decimals; + if (delta > 0) { + const tens = getTens(delta); + assert1(value % tens === BN_0$8, "value loses precision for format", "NUMERIC_FAULT", { + operation: "fromValue", + fault: "underflow", + value: _value + }); + value /= tens; + } else if (delta < 0) { + value *= getTens(-delta); + } + checkValue(value, format, "fromValue"); + return new FixedNumber(_guard$5, value, format); + } + static fromString(_value, _format) { + const match = _value.match(/^(-?)([0-9]*)\.?([0-9]*)$/); + assertArgument(match && match[2].length + match[3].length > 0, "invalid FixedNumber string value", "value", _value); + const format = getFormat(_format); + let whole = match[2] || "0", decimal = match[3] || ""; + while(decimal.length < format.decimals){ + decimal += Zeros$1; + } + assert1(decimal.substring(format.decimals).match(/^0*$/), "too many decimals for format", "NUMERIC_FAULT", { + operation: "fromString", + fault: "underflow", + value: _value + }); + decimal = decimal.substring(0, format.decimals); + const value = BigInt(match[1] + whole + decimal); + checkValue(value, format, "fromString"); + return new FixedNumber(_guard$5, value, format); } - if (isBytes(value)) { - let result = "0x"; - for(let i = 0; i < value.length; i++){ - let v = value[i]; - result += HexCharacters[(v & 240) >> 4] + HexCharacters[v & 15]; + static fromBytes(_value, _format) { + let value = toBigInt(getBytes(_value, "value")); + const format = getFormat(_format); + if (format.signed) { + value = fromTwos(value, format.width); } - return result; + checkValue(value, format, "fromBytes"); + return new FixedNumber(_guard$5, value, format); } - return logger2.throwArgumentError("invalid hexlify value", "value", value); } -function hexDataLength(data) { - if (typeof data !== "string") { - data = hexlify(data); - } else if (!isHexString(data) || data.length % 2) { - return null; +function hexlifyByte(value) { + let result = value.toString(16); + while(result.length < 2){ + result = "0" + result; } - return (data.length - 2) / 2; + return "0x" + result; } -function hexDataSlice(data, offset, endOffset) { - if (typeof data !== "string") { - data = hexlify(data); - } else if (!isHexString(data) || data.length % 2) { - logger2.throwArgumentError("invalid hexData", "value", data); - } - offset = 2 + 2 * offset; - if (endOffset != null) { - return "0x" + data.substring(offset, 2 + 2 * endOffset); +function unarrayifyInteger(data, offset, length) { + let result = 0; + for(let i = 0; i < length; i++){ + result = result * 256 + data[offset + i]; } - return "0x" + data.substring(offset); -} -function hexConcat(items) { - let result = "0x"; - items.forEach((item)=>{ - result += hexlify(item).substring(2); - }); return result; } -function hexValue(value) { - const trimmed = hexStripZeros(hexlify(value, { - hexPad: "left" - })); - if (trimmed === "0x") { - return "0x0"; +function _decodeChildren(data, offset, childOffset, length) { + const result = []; + while(childOffset < offset + 1 + length){ + const decoded = _decode(data, childOffset); + result.push(decoded.result); + childOffset += decoded.consumed; + assert1(childOffset <= offset + 1 + length, "child data too short", "BUFFER_OVERRUN", { + buffer: data, + length: length, + offset: offset + }); } - return trimmed; + return { + consumed: 1 + length, + result: result + }; } -function hexStripZeros(value) { - if (typeof value !== "string") { - value = hexlify(value); - } - if (!isHexString(value)) { - logger2.throwArgumentError("invalid hex string", "value", value); +function _decode(data, offset) { + assert1(data.length !== 0, "data too short", "BUFFER_OVERRUN", { + buffer: data, + length: 0, + offset: 1 + }); + const checkOffset = (offset)=>{ + assert1(offset <= data.length, "data short segment too short", "BUFFER_OVERRUN", { + buffer: data, + length: data.length, + offset: offset + }); + }; + if (data[offset] >= 248) { + const lengthLength = data[offset] - 247; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); + } else if (data[offset] >= 192) { + const length = data[offset] - 192; + checkOffset(offset + 1 + length); + return _decodeChildren(data, offset, offset + 1, length); + } else if (data[offset] >= 184) { + const lengthLength = data[offset] - 183; + checkOffset(offset + 1 + lengthLength); + const length = unarrayifyInteger(data, offset + 1, lengthLength); + checkOffset(offset + 1 + lengthLength + length); + const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); + return { + consumed: 1 + lengthLength + length, + result: result + }; + } else if (data[offset] >= 128) { + const length = data[offset] - 128; + checkOffset(offset + 1 + length); + const result = hexlify(data.slice(offset + 1, offset + 1 + length)); + return { + consumed: 1 + length, + result: result + }; } - value = value.substring(2); - let offset = 0; - while(offset < value.length && value[offset] === "0"){ - offset++; + return { + consumed: 1, + result: hexlifyByte(data[offset]) + }; +} +function decodeRlp(_data) { + const data = getBytes(_data, "data"); + const decoded = _decode(data, 0); + assertArgument(decoded.consumed === data.length, "unexpected junk after rlp payload", "data", _data); + return decoded.result; +} +function arrayifyInteger(value) { + const result = []; + while(value){ + result.unshift(value & 255); + value >>= 8; } - return "0x" + value.substring(offset); + return result; } -function hexZeroPad(value, length) { - if (typeof value !== "string") { - value = hexlify(value); - } else if (!isHexString(value)) { - logger2.throwArgumentError("invalid hex string", "value", value); +function _encode(object) { + if (Array.isArray(object)) { + let payload = []; + object.forEach(function(child) { + payload = payload.concat(_encode(child)); + }); + if (payload.length <= 55) { + payload.unshift(192 + payload.length); + return payload; + } + const length = arrayifyInteger(payload.length); + length.unshift(247 + length.length); + return length.concat(payload); } - if (value.length > 2 * length + 2) { - logger2.throwArgumentError("value out of range", "value", arguments[1]); + const data = Array.prototype.slice.call(getBytes(object, "object")); + if (data.length === 1 && data[0] <= 127) { + return data; + } else if (data.length <= 55) { + data.unshift(128 + data.length); + return data; } - while(value.length < 2 * length + 2){ - value = "0x0" + value.substring(2); + const length = arrayifyInteger(data.length); + length.unshift(183 + length.length); + return length.concat(data); +} +const nibbles = "0123456789abcdef"; +function encodeRlp(object) { + let result = "0x"; + for (const v of _encode(object)){ + result += nibbles[v >> 4]; + result += nibbles[v & 15]; } - return value; + return result; } -function splitSignature(signature) { - const result = { - r: "0x", - s: "0x", - _vs: "0x", - recoveryParam: 0, - v: 0, - yParityAndS: "0x", - compact: "0x" - }; - if (isBytesLike(signature)) { - let bytes = arrayify(signature); - if (bytes.length === 64) { - result.v = 27 + (bytes[32] >> 7); - bytes[32] &= 127; - result.r = hexlify(bytes.slice(0, 32)); - result.s = hexlify(bytes.slice(32, 64)); - } else if (bytes.length === 65) { - result.r = hexlify(bytes.slice(0, 32)); - result.s = hexlify(bytes.slice(32, 64)); - result.v = bytes[64]; - } else { - logger2.throwArgumentError("invalid signature string", "signature", signature); - } - if (result.v < 27) { - if (result.v === 0 || result.v === 1) { - result.v += 27; - } else { - logger2.throwArgumentError("signature invalid v byte", "signature", signature); +const names = [ + "wei", + "kwei", + "mwei", + "gwei", + "szabo", + "finney", + "ether" +]; +function formatUnits(value, unit) { + let decimals = 18; + if (typeof unit === "string") { + const index = names.indexOf(unit); + assertArgument(index >= 0, "invalid unit", "unit", unit); + decimals = 3 * index; + } else if (unit != null) { + decimals = getNumber(unit, "unit"); + } + return FixedNumber.fromValue(value, decimals, { + decimals: decimals, + width: 512 + }).toString(); +} +function parseUnits$1(value, unit) { + assertArgument(typeof value === "string", "value must be a string", "value", value); + let decimals = 18; + if (typeof unit === "string") { + const index = names.indexOf(unit); + assertArgument(index >= 0, "invalid unit", "unit", unit); + decimals = 3 * index; + } else if (unit != null) { + decimals = getNumber(unit, "unit"); + } + return FixedNumber.fromString(value, { + decimals: decimals, + width: 512 + }).value; +} +function formatEther(wei) { + return formatUnits(wei, 18); +} +function parseEther(ether) { + return parseUnits$1(ether, 18); +} +function uuidV4(randomBytes) { + const bytes = getBytes(randomBytes, "randomBytes"); + bytes[6] = bytes[6] & 15 | 64; + bytes[8] = bytes[8] & 63 | 128; + const value = hexlify(bytes); + return [ + value.substring(2, 10), + value.substring(10, 14), + value.substring(14, 18), + value.substring(18, 22), + value.substring(22, 34) + ].join("-"); +} +const WordSize = 32; +const Padding = new Uint8Array(32); +const passProperties$1 = [ + "then" +]; +const _guard$4 = {}; +const resultNames = new WeakMap; +function getNames(result) { + return resultNames.get(result); +} +function setNames(result, names) { + resultNames.set(result, names); +} +function throwError(name, error) { + const wrapped = new Error(`deferred error during ABI decoding triggered accessing ${name}`); + wrapped.error = error; + throw wrapped; +} +function toObject(names, items, deep) { + if (names.indexOf(null) >= 0) { + return items.map((item, index)=>{ + if (item instanceof Result) { + return toObject(getNames(item), item, deep); + } + return item; + }); + } + return names.reduce((accum, name, index)=>{ + let item = items.getValue(name); + if (!(name in accum)) { + if (deep && item instanceof Result) { + item = toObject(getNames(item), item, deep); } + accum[name] = item; } - result.recoveryParam = 1 - result.v % 2; - if (result.recoveryParam) { - bytes[32] |= 128; - } - result._vs = hexlify(bytes.slice(32, 64)); - } else { - result.r = signature.r; - result.s = signature.s; - result.v = signature.v; - result.recoveryParam = signature.recoveryParam; - result._vs = signature._vs; - if (result._vs != null) { - const vs2 = zeroPad(arrayify(result._vs), 32); - result._vs = hexlify(vs2); - const recoveryParam = vs2[0] >= 128 ? 1 : 0; - if (result.recoveryParam == null) { - result.recoveryParam = recoveryParam; - } else if (result.recoveryParam !== recoveryParam) { - logger2.throwArgumentError("signature recoveryParam mismatch _vs", "signature", signature); - } - vs2[0] &= 127; - const s = hexlify(vs2); - if (result.s == null) { - result.s = s; - } else if (result.s !== s) { - logger2.throwArgumentError("signature v mismatch _vs", "signature", signature); - } - } - if (result.recoveryParam == null) { - if (result.v == null) { - logger2.throwArgumentError("signature missing v and recoveryParam", "signature", signature); - } else if (result.v === 0 || result.v === 1) { - result.recoveryParam = result.v; - } else { - result.recoveryParam = 1 - result.v % 2; - } - } else { - if (result.v == null) { - result.v = 27 + result.recoveryParam; - } else { - const recId = result.v === 0 || result.v === 1 ? result.v : 1 - result.v % 2; - if (result.recoveryParam !== recId) { - logger2.throwArgumentError("signature recoveryParam mismatch v", "signature", signature); - } + return accum; + }, {}); +} +class Result extends Array { + #names; + constructor(...args){ + const guard = args[0]; + let items = args[1]; + let names = (args[2] || []).slice(); + let wrap = true; + if (guard !== _guard$4) { + items = args; + names = []; + wrap = false; + } + super(items.length); + items.forEach((item, index)=>{ + this[index] = item; + }); + const nameCounts = names.reduce((accum, name)=>{ + if (typeof name === "string") { + accum.set(name, (accum.get(name) || 0) + 1); } - } - if (result.r == null || !isHexString(result.r)) { - logger2.throwArgumentError("signature missing or invalid r", "signature", signature); - } else { - result.r = hexZeroPad(result.r, 32); - } - if (result.s == null || !isHexString(result.s)) { - logger2.throwArgumentError("signature missing or invalid s", "signature", signature); - } else { - result.s = hexZeroPad(result.s, 32); - } - const vs = arrayify(result.s); - if (vs[0] >= 128) { - logger2.throwArgumentError("signature s out of range", "signature", signature); - } - if (result.recoveryParam) { - vs[0] |= 128; - } - const _vs = hexlify(vs); - if (result._vs) { - if (!isHexString(result._vs)) { - logger2.throwArgumentError("signature invalid _vs", "signature", signature); + return accum; + }, new Map); + setNames(this, Object.freeze(items.map((item, index)=>{ + const name = names[index]; + if (name != null && nameCounts.get(name) === 1) { + return name; } - result._vs = hexZeroPad(result._vs, 32); - } - if (result._vs == null) { - result._vs = _vs; - } else if (result._vs !== _vs) { - logger2.throwArgumentError("signature _vs mismatch v and s", "signature", signature); + return null; + }))); + this.#names = []; + if (this.#names == null) { + void this.#names; } - } - result.yParityAndS = result._vs; - result.compact = result.r + result.yParityAndS.substring(2); - return result; -} -function joinSignature(signature) { - signature = splitSignature(signature); - return hexlify(concat([ - signature.r, - signature.s, - signature.recoveryParam ? "0x1c" : "0x1b" - ])); -} -const version2 = "bignumber/5.7.0"; -var BN = bn.BN; -const logger21 = new Logger(version2); -const _constructorGuard = {}; -function isBigNumberish(value) { - return value != null && (BigNumber.isBigNumber(value) || typeof value === "number" && value % 1 === 0 || typeof value === "string" && !!value.match(/^-?[0-9]+$/) || isHexString(value) || typeof value === "bigint" || isBytes(value)); -} -let _warnedToStringRadix = false; -class BigNumber { - constructor(constructorGuard, hex){ - if (constructorGuard !== _constructorGuard) { - logger21.throwError("cannot call constructor directly; use BigNumber.from", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "new (BigNumber)" - }); + if (!wrap) { + return; } - this._hex = hex; - this._isBigNumber = true; Object.freeze(this); + const proxy = new Proxy(this, { + get: (target, prop, receiver)=>{ + if (typeof prop === "string") { + if (prop.match(/^[0-9]+$/)) { + const index = getNumber(prop, "%index"); + if (index < 0 || index >= this.length) { + throw new RangeError("out of result range"); + } + const item = target[index]; + if (item instanceof Error) { + throwError(`index ${index}`, item); + } + return item; + } + if (passProperties$1.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + const value = target[prop]; + if (value instanceof Function) { + return function(...args) { + return value.apply(this === receiver ? target : this, args); + }; + } else if (!(prop in target)) { + return target.getValue.apply(this === receiver ? target : this, [ + prop + ]); + } + } + return Reflect.get(target, prop, receiver); + } + }); + setNames(proxy, getNames(this)); + return proxy; } - fromTwos(value) { - return toBigNumber(toBN(this).fromTwos(value)); + toArray(deep) { + const result = []; + this.forEach((item, index)=>{ + if (item instanceof Error) { + throwError(`index ${index}`, item); + } + if (deep && item instanceof Result) { + item = item.toArray(deep); + } + result.push(item); + }); + return result; } - toTwos(value) { - return toBigNumber(toBN(this).toTwos(value)); + toObject(deep) { + const names = getNames(this); + return names.reduce((accum, name, index)=>{ + assert1(name != null, `value at index ${index} unnamed`, "UNSUPPORTED_OPERATION", { + operation: "toObject()" + }); + return toObject(names, this, deep); + }, {}); } - abs() { - if (this._hex[0] === "-") { - return BigNumber.from(this._hex.substring(1)); + slice(start, end) { + if (start == null) { + start = 0; } - 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"); + if (start < 0) { + start += this.length; + if (start < 0) { + start = 0; + } } - 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"); + if (end == null) { + end = this.length; } - return toBigNumber(toBN(this).umod(value)); - } - pow(other) { - const value = toBN(other); - if (value.isNeg()) { - throwFault("negative-power", "pow"); + if (end < 0) { + end += this.length; + if (end < 0) { + end = 0; + } } - return toBigNumber(toBN(this).pow(value)); - } - and(other) { - const value = toBN(other); - if (this.isNegative() || value.isNeg()) { - throwFault("unbound-bitwise-result", "and"); + if (end > this.length) { + end = this.length; } - return toBigNumber(toBN(this).and(value)); - } - or(other) { - const value = toBN(other); - if (this.isNegative() || value.isNeg()) { - throwFault("unbound-bitwise-result", "or"); + const _names = getNames(this); + const result = [], names = []; + for(let i = start; i < end; i++){ + result.push(this[i]); + names.push(_names[i]); } - return toBigNumber(toBN(this).or(value)); + return new Result(_guard$4, result, names); } - xor(other) { - const value = toBN(other); - if (this.isNegative() || value.isNeg()) { - throwFault("unbound-bitwise-result", "xor"); + filter(callback, thisArg) { + const _names = getNames(this); + const result = [], names = []; + for(let i = 0; i < this.length; i++){ + const item = this[i]; + if (item instanceof Error) { + throwError(`index ${i}`, item); + } + if (callback.call(thisArg, item, i, this)) { + result.push(item); + names.push(_names[i]); + } } - return toBigNumber(toBN(this).xor(value)); + return new Result(_guard$4, result, names); } - mask(value) { - if (this.isNegative() || value < 0) { - throwFault("negative-width", "mask"); + map(callback, thisArg) { + const result = []; + for(let i = 0; i < this.length; i++){ + const item = this[i]; + if (item instanceof Error) { + throwError(`index ${i}`, item); + } + result.push(callback.call(thisArg, item, i, this)); } - return toBigNumber(toBN(this).maskn(value)); + return result; } - shl(value) { - if (this.isNegative() || value < 0) { - throwFault("negative-width", "shl"); + getValue(name) { + const index = getNames(this).indexOf(name); + if (index === -1) { + return undefined; } - return toBigNumber(toBN(this).shln(value)); - } - shr(value) { - if (this.isNegative() || value < 0) { - throwFault("negative-width", "shr"); + const value = this[index]; + if (value instanceof Error) { + throwError(`property ${JSON.stringify(name)}`, value.error); } - 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)); + return value; } - gte(other) { - return toBN(this).gte(toBN(other)); + static fromItems(items, keys) { + return new Result(_guard$4, items, keys); } - isNegative() { - return this._hex[0] === "-"; - } - isZero() { - return toBN(this).isZero(); - } - toNumber() { - try { - return toBN(this).toNumber(); - } catch (error) { - throwFault("overflow", "toNumber", this.toString()); +} +function checkResultErrors(result) { + const errors = []; + const checkErrors = function(path, object) { + if (!Array.isArray(object)) { + return; } - return null; + for(let key in object){ + const childPath = path.slice(); + childPath.push(key); + try { + checkErrors(childPath, object[key]); + } catch (error) { + errors.push({ + path: childPath, + error: error + }); + } + } + }; + checkErrors([], result); + return errors; +} +function getValue$1(value) { + let bytes = toBeArray(value); + assert1(bytes.length <= 32, "value out-of-bounds", "BUFFER_OVERRUN", { + buffer: bytes, + length: 32, + offset: bytes.length + }); + if (bytes.length !== 32) { + bytes = getBytesCopy(concat([ + Padding.slice(bytes.length % WordSize), + bytes + ])); } - toBigInt() { - try { - return BigInt(this.toString()); - } catch (e) {} - return logger21.throwError("this platform does not support BigInt", Logger.errors.UNSUPPORTED_OPERATION, { - value: this.toString() + return bytes; +} +class Coder { + name; + type; + localName; + dynamic; + constructor(name, type, localName, dynamic){ + defineProperties(this, { + name: name, + type: type, + localName: localName, + dynamic: dynamic + }, { + name: "string", + type: "string", + localName: "string", + dynamic: "boolean" }); } - toString() { - if (arguments.length > 0) { - if (arguments[0] === 10) { - if (!_warnedToStringRadix) { - _warnedToStringRadix = true; - logger21.warn("BigNumber.toString does not accept any parameters; base-10 is assumed"); - } - } else if (arguments[0] === 16) { - logger21.throwError("BigNumber.toString does not accept any parameters; use bigNumber.toHexString()", Logger.errors.UNEXPECTED_ARGUMENT, {}); - } else { - logger21.throwError("BigNumber.toString does not accept parameters", Logger.errors.UNEXPECTED_ARGUMENT, {}); - } - } - return toBN(this).toString(10); + _throwError(message, value) { + assertArgument(false, message, this.localName, value); } - toHexString() { - return this._hex; +} +class Writer { + #data; + #dataLength; + constructor(){ + this.#data = []; + this.#dataLength = 0; } - toJSON(key) { - return { - type: "BigNumber", - hex: this.toHexString() - }; + get data() { + return concat(this.#data); } - 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, toHex(value)); - } - if (value.match(/^-?[0-9]+$/)) { - return new BigNumber(_constructorGuard, toHex(new BN(value))); - } - return logger21.throwArgumentError("invalid BigNumber string", "value", value); - } - if (typeof value === "number") { - if (value % 1) { - throwFault("underflow", "BigNumber.from", value); - } - if (value >= 9007199254740991 || value <= -9007199254740991) { - throwFault("overflow", "BigNumber.from", value); - } - return BigNumber.from(String(value)); - } - const anyValue = value; - if (typeof anyValue === "bigint") { - return BigNumber.from(anyValue.toString()); - } - if (isBytes(anyValue)) { - return BigNumber.from(hexlify(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 (isHexString(hex) || hex[0] === "-" && isHexString(hex.substring(1))) { - return BigNumber.from(hex); - } - } - } + get length() { + return this.#dataLength; + } + #writeData(data) { + this.#data.push(data); + this.#dataLength += data.length; + return data.length; + } + appendWriter(writer) { + return this.#writeData(getBytesCopy(writer.data)); + } + writeBytes(value) { + let bytes = getBytesCopy(value); + const paddingOffset = bytes.length % 32; + if (paddingOffset) { + bytes = getBytesCopy(concat([ + bytes, + Padding.slice(paddingOffset) + ])); } - return logger21.throwArgumentError("invalid BigNumber value", "value", value); + return this.#writeData(bytes); + } + writeValue(value) { + return this.#writeData(getValue$1(value)); } - static isBigNumber(value) { - return !!(value && value._isBigNumber); + writeUpdatableValue() { + const offset = this.#data.length; + this.#data.push(Padding); + this.#dataLength += WordSize; + return (value)=>{ + this.#data[offset] = getValue$1(value); + }; } } -function toHex(value) { - if (typeof value !== "string") { - return toHex(value.toString(16)); +class Reader { + allowLoose; + #data; + #offset; + #bytesRead; + #parent; + #maxInflation; + constructor(data, allowLoose, maxInflation){ + defineProperties(this, { + allowLoose: !!allowLoose + }); + this.#data = getBytesCopy(data); + this.#bytesRead = 0; + this.#parent = null; + this.#maxInflation = maxInflation != null ? maxInflation : 1024; + this.#offset = 0; + } + get data() { + return hexlify(this.#data); + } + get dataLength() { + return this.#data.length; } - if (value[0] === "-") { - value = value.substring(1); - if (value[0] === "-") { - logger21.throwArgumentError("invalid hex", "value", value); + get consumed() { + return this.#offset; + } + get bytes() { + return new Uint8Array(this.#data); + } + #incrementBytesRead(count) { + if (this.#parent) { + return this.#parent.#incrementBytesRead(count); } - value = toHex(value); - if (value === "0x00") { - return value; + this.#bytesRead += count; + assert1(this.#maxInflation < 1 || this.#bytesRead <= this.#maxInflation * this.dataLength, `compressed ABI data exceeds inflation ratio of ${this.#maxInflation} ( see: https:/\/github.com/ethers-io/ethers.js/issues/4537 )`, "BUFFER_OVERRUN", { + buffer: getBytesCopy(this.#data), + offset: this.#offset, + length: count, + info: { + bytesRead: this.#bytesRead, + dataLength: this.dataLength + } + }); + } + #peekBytes(offset, length, loose) { + let alignedLength = Math.ceil(length / 32) * 32; + if (this.#offset + alignedLength > this.#data.length) { + if (this.allowLoose && loose && this.#offset + length <= this.#data.length) { + alignedLength = length; + } else { + assert1(false, "data out-of-bounds", "BUFFER_OVERRUN", { + buffer: getBytesCopy(this.#data), + length: this.#data.length, + offset: this.#offset + alignedLength + }); + } } - return "-" + value; + return this.#data.slice(this.#offset, this.#offset + alignedLength); } - if (value.substring(0, 2) !== "0x") { - value = "0x" + value; + subReader(offset) { + const reader = new Reader(this.#data.slice(this.#offset + offset), this.allowLoose, this.#maxInflation); + reader.#parent = this; + return reader; } - if (value === "0x") { - return "0x00"; + readBytes(length, loose) { + let bytes = this.#peekBytes(0, length, !!loose); + this.#incrementBytesRead(length); + this.#offset += bytes.length; + return bytes.slice(0, length); } - if (value.length % 2) { - value = "0x0" + value.substring(2); + readValue() { + return toBigInt(this.readBytes(32)); } - while(value.length > 4 && value.substring(0, 4) === "0x00"){ - value = "0x" + value.substring(4); + readIndex() { + return toNumber(this.readBytes(32)); } - return value; } -function toBigNumber(value) { - return BigNumber.from(toHex(value)); +function number(n) { + if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`); } -function toBN(value) { - const hex = BigNumber.from(value).toHexString(); - if (hex[0] === "-") { - return new BN("-" + hex.substring(3), 16); +function bytes(b, ...lengths) { + if (!(b instanceof Uint8Array)) throw new Error("Expected Uint8Array"); + if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`); +} +function hash(hash) { + if (typeof hash !== "function" || typeof hash.create !== "function") throw new Error("Hash should be wrapped by utils.wrapConstructor"); + number(hash.outputLen); + number(hash.blockLen); +} +function exists(instance, checkFinished = true) { + if (instance.destroyed) throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called"); +} +function output(out, instance) { + bytes(out); + const min = instance.outputLen; + if (out.length < min) { + throw new Error(`digestInto() expects output buffer of length at least ${min}`); } - return new BN(hex.substring(2), 16); } -function throwFault(fault, operation, value) { - const params = { - fault, - operation - }; - if (value != null) { - params.value = value; +const crypto$1 = typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : undefined; +const u8a$1 = (a)=>a instanceof Uint8Array; +const u32 = (arr)=>new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +const createView = (arr)=>new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +const rotr = (word, shift)=>word << 32 - shift | word >>> shift; +const isLE = new Uint8Array(new Uint32Array([ + 287454020 +]).buffer)[0] === 68; +if (!isLE) throw new Error("Non little-endian hardware is not supported"); +const nextTick = async ()=>{}; +async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for(let i = 0; i < iters; i++){ + cb(i); + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) continue; + await nextTick(); + ts += diff; + } +} +function utf8ToBytes$1(str) { + if (typeof str !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array((new TextEncoder).encode(str)); +} +function toBytes(data) { + if (typeof data === "string") data = utf8ToBytes$1(data); + if (!u8a$1(data)) throw new Error(`expected Uint8Array, got ${typeof data}`); + return data; +} +function concatBytes$1(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a)=>sum + a.length, 0)); + let pad = 0; + arrays.forEach((a)=>{ + if (!u8a$1(a)) throw new Error("Uint8Array expected"); + r.set(a, pad); + pad += a.length; + }); + return r; +} +class Hash { + clone() { + return this._cloneInto(); } - return logger21.throwError(fault, Logger.errors.NUMERIC_FAULT, params); } -function _base36To16(value) { - return new BN(value, 36).toString(16); +const toStr = {}.toString; +function checkOpts(defaults, opts) { + if (opts !== undefined && toStr.call(opts) !== "[object Object]") throw new Error("Options should be object or undefined"); + const merged = Object.assign(defaults, opts); + return merged; } -function _base16To36(value) { - return new BN(value, 16).toString(36); +function wrapConstructor(hashCons) { + const hashC = (msg)=>hashCons().update(toBytes(msg)).digest(); + const tmp = hashCons(); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.create = ()=>hashCons(); + return hashC; } -const logger$1 = new Logger(version2); -const _constructorGuard$1 = {}; -const Zero = BigNumber.from(0); -const NegativeOne = BigNumber.from(-1); -function throwFault$1(message, fault, operation, value) { - const params = { - fault, - operation - }; - if (value !== void 0) { - params.value = value; +function randomBytes$2(bytesLength = 32) { + if (crypto$1 && typeof crypto$1.getRandomValues === "function") { + return crypto$1.getRandomValues(new Uint8Array(bytesLength)); } - return logger$1.throwError(message, Logger.errors.NUMERIC_FAULT, params); -} -let zeros = "0"; -while(zeros.length < 256){ - zeros += zeros; + throw new Error("crypto.getRandomValues must be defined"); } -function getMultiplier(decimals) { - if (typeof decimals !== "number") { - try { - decimals = BigNumber.from(decimals).toNumber(); - } catch (e) {} +class HMAC extends Hash { + constructor(hash$1, _key){ + super(); + this.finished = false; + this.destroyed = false; + hash(hash$1); + const key = toBytes(_key); + this.iHash = hash$1.create(); + if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set(key.length > blockLen ? hash$1.create().update(key).digest() : key); + for(let i = 0; i < pad.length; i++)pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash$1.create(); + for(let i = 0; i < pad.length; i++)pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + pad.fill(0); + } + update(buf) { + exists(this); + this.iHash.update(buf); + return this; } - if (typeof decimals === "number" && decimals >= 0 && decimals <= 256 && !(decimals % 1)) { - return "1" + zeros.substring(0, decimals); + digestInto(out) { + exists(this); + bytes(out, this.outputLen); + this.finished = true; + this.iHash.digestInto(out); + this.oHash.update(out); + this.oHash.digestInto(out); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; } - return logger$1.throwArgumentError("invalid decimal size", "decimals", decimals); + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +const hmac = (hash, key, message)=>new HMAC(hash, key).update(message).digest(); +hmac.create = (hash, key)=>new HMAC(hash, key); +function pbkdf2Init(hash$1, _password, _salt, _opts) { + hash(hash$1); + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10 + }, _opts); + const { c, dkLen, asyncTick } = opts; + number(c); + number(dkLen); + number(asyncTick); + if (c < 1) throw new Error("PBKDF2: iterations (c) should be >= 1"); + const password = toBytes(_password); + const salt = toBytes(_salt); + const DK = new Uint8Array(dkLen); + const PRF = hmac.create(hash$1, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { + c: c, + dkLen: dkLen, + asyncTick: asyncTick, + DK: DK, + PRF: PRF, + PRFSalt: PRFSalt + }; } -function formatFixed(value, decimals) { - if (decimals == null) { - decimals = 0; +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + u.fill(0); + return DK; +} +function pbkdf2$1(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + for(let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen){ + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for(let ui = 1; ui < c; ui++){ + PRF._cloneInto(prfW).update(u).digestInto(u); + for(let i = 0; i < Ti.length; i++)Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +function setBigUint64(view, byteOffset, value, isLE) { + if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE); + const _32n = BigInt(32); + const _u32_max = BigInt(4294967295); + const wh = Number(value >> _32n & _u32_max); + const wl = Number(value & _u32_max); + const h = isLE ? 4 : 0; + const l = isLE ? 0 : 4; + view.setUint32(byteOffset + h, wh, isLE); + view.setUint32(byteOffset + l, wl, isLE); +} +class SHA2 extends Hash { + constructor(blockLen, outputLen, padOffset, isLE){ + super(); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.finished = false; + this.length = 0; + this.pos = 0; + this.destroyed = false; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + exists(this); + const { view, buffer, blockLen } = this; + data = toBytes(data); + const len = data.length; + for(let pos = 0; pos < len;){ + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for(; blockLen <= len - pos; pos += blockLen)this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; } - const multiplier = getMultiplier(decimals); - value = BigNumber.from(value); - const negative = value.lt(Zero); - if (negative) { - value = value.mul(NegativeOne); + digestInto(out) { + exists(this); + output(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + buffer[pos++] = 128; + this.buffer.subarray(pos).fill(0); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for(let i = pos; i < blockLen; i++)buffer[i] = 0; + setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state"); + for(let i = 0; i < outLen; i++)oview.setUint32(4 * i, state[i], isLE); } - let fraction = value.mod(multiplier).toString(); - while(fraction.length < multiplier.length - 1){ - fraction = "0" + fraction; + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; } - fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; - const whole = value.div(multiplier).toString(); - if (multiplier.length === 1) { - value = whole; - } else { - value = whole + "." + fraction; + _cloneInto(to) { + to || (to = new this.constructor); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.length = length; + to.pos = pos; + to.finished = finished; + to.destroyed = destroyed; + if (length % blockLen) to.buffer.set(buffer); + return to; + } +} +const Chi = (a, b, c)=>a & b ^ ~a & c; +const Maj = (a, b, c)=>a & b ^ a & c ^ b & c; +const SHA256_K = new Uint32Array([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +const IV = new Uint32Array([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +const SHA256_W = new Uint32Array(64); +class SHA256 extends SHA2 { + constructor(){ + super(64, 32, 8, false); + this.A = IV[0] | 0; + this.B = IV[1] | 0; + this.C = IV[2] | 0; + this.D = IV[3] | 0; + this.E = IV[4] | 0; + this.F = IV[5] | 0; + this.G = IV[6] | 0; + this.H = IV[7] | 0; } - if (negative) { - value = "-" + value; + get() { + const { A, B, C, D, E, F, G, H } = this; + return [ + A, + B, + C, + D, + E, + F, + G, + H + ]; } - return value; -} -function parseFixed(value, decimals) { - if (decimals == null) { - decimals = 0; + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + for(let i = 0; i < 16; i++, offset += 4)SHA256_W[i] = view.getUint32(offset, false); + for(let i = 16; i < 64; i++){ + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A, B, C, D, E, F, G, H } = this; + for(let i = 0; i < 64; i++){ + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = sigma0 + Maj(A, B, C) | 0; + H = G; + G = F; + F = E; + E = D + T1 | 0; + D = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D = D + this.D | 0; + E = E + this.E | 0; + F = F + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D, E, F, G, H); } - const multiplier = getMultiplier(decimals); - if (typeof value !== "string" || !value.match(/^-?[0-9.]+$/)) { - logger$1.throwArgumentError("invalid decimal value", "value", value); + roundClean() { + SHA256_W.fill(0); } - const negative = value.substring(0, 1) === "-"; - if (negative) { - value = value.substring(1); + destroy() { + this.set(0, 0, 0, 0, 0, 0, 0, 0); + this.buffer.fill(0); } - if (value === ".") { - logger$1.throwArgumentError("missing value", "value", value); +} +const sha256$1 = wrapConstructor(()=>new SHA256); +const U32_MASK64 = BigInt(2 ** 32 - 1); +const _32n = BigInt(32); +function fromBig(n, le = false) { + if (le) return { + h: Number(n & U32_MASK64), + l: Number(n >> _32n & U32_MASK64) + }; + return { + h: Number(n >> _32n & U32_MASK64) | 0, + l: Number(n & U32_MASK64) | 0 + }; +} +function split$1(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 + ]; } - const comps = value.split("."); - if (comps.length > 2) { - logger$1.throwArgumentError("too many decimal points", "value", value); + return [ + Ah, + Al + ]; +} +const toBig = (h, l)=>BigInt(h >>> 0) << _32n | BigInt(l >>> 0); +const shrSH = (h, _l, s)=>h >>> s; +const shrSL = (h, l, s)=>h << 32 - s | l >>> s; +const rotrSH = (h, l, s)=>h >>> s | l << 32 - s; +const rotrSL = (h, l, s)=>h << 32 - s | l >>> s; +const rotrBH = (h, l, s)=>h << 64 - s | l >>> s - 32; +const rotrBL = (h, l, s)=>h >>> s - 32 | l << 64 - s; +const rotr32H = (_h, l)=>l; +const rotr32L = (h, _l)=>h; +const rotlSH = (h, l, s)=>h << s | l >>> 32 - s; +const rotlSL = (h, l, s)=>l << s | h >>> 32 - s; +const rotlBH = (h, l, s)=>l << s - 32 | h >>> 64 - s; +const rotlBL = (h, l, s)=>h << s - 32 | l >>> 64 - s; +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { + h: Ah + Bh + (l / 2 ** 32 | 0) | 0, + l: l | 0 + }; +} +const add3L = (Al, Bl, Cl)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +const add3H = (low, Ah, Bh, Ch)=>Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; +const add4L = (Al, Bl, Cl, Dl)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +const add4H = (low, Ah, Bh, Ch, Dh)=>Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; +const add5L = (Al, Bl, Cl, Dl, El)=>(Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +const add5H = (low, Ah, Bh, Ch, Dh, Eh)=>Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; +const u64 = { + fromBig: fromBig, + split: split$1, + toBig: toBig, + shrSH: shrSH, + shrSL: shrSL, + rotrSH: rotrSH, + rotrSL: rotrSL, + rotrBH: rotrBH, + rotrBL: rotrBL, + rotr32H: rotr32H, + rotr32L: rotr32L, + rotlSH: rotlSH, + rotlSL: rotlSL, + rotlBH: rotlBH, + rotlBL: rotlBL, + add: add, + add3L: add3L, + add3H: add3H, + add4L: add4L, + add4H: add4H, + add5H: add5H, + add5L: add5L +}; +const [SHA512_Kh, SHA512_Kl] = (()=>u64.split([ + "0x428a2f98d728ae22", + "0x7137449123ef65cd", + "0xb5c0fbcfec4d3b2f", + "0xe9b5dba58189dbbc", + "0x3956c25bf348b538", + "0x59f111f1b605d019", + "0x923f82a4af194f9b", + "0xab1c5ed5da6d8118", + "0xd807aa98a3030242", + "0x12835b0145706fbe", + "0x243185be4ee4b28c", + "0x550c7dc3d5ffb4e2", + "0x72be5d74f27b896f", + "0x80deb1fe3b1696b1", + "0x9bdc06a725c71235", + "0xc19bf174cf692694", + "0xe49b69c19ef14ad2", + "0xefbe4786384f25e3", + "0x0fc19dc68b8cd5b5", + "0x240ca1cc77ac9c65", + "0x2de92c6f592b0275", + "0x4a7484aa6ea6e483", + "0x5cb0a9dcbd41fbd4", + "0x76f988da831153b5", + "0x983e5152ee66dfab", + "0xa831c66d2db43210", + "0xb00327c898fb213f", + "0xbf597fc7beef0ee4", + "0xc6e00bf33da88fc2", + "0xd5a79147930aa725", + "0x06ca6351e003826f", + "0x142929670a0e6e70", + "0x27b70a8546d22ffc", + "0x2e1b21385c26c926", + "0x4d2c6dfc5ac42aed", + "0x53380d139d95b3df", + "0x650a73548baf63de", + "0x766a0abb3c77b2a8", + "0x81c2c92e47edaee6", + "0x92722c851482353b", + "0xa2bfe8a14cf10364", + "0xa81a664bbc423001", + "0xc24b8b70d0f89791", + "0xc76c51a30654be30", + "0xd192e819d6ef5218", + "0xd69906245565a910", + "0xf40e35855771202a", + "0x106aa07032bbd1b8", + "0x19a4c116b8d2d0c8", + "0x1e376c085141ab53", + "0x2748774cdf8eeb99", + "0x34b0bcb5e19b48a8", + "0x391c0cb3c5c95a63", + "0x4ed8aa4ae3418acb", + "0x5b9cca4f7763e373", + "0x682e6ff3d6b2b8a3", + "0x748f82ee5defb2fc", + "0x78a5636f43172f60", + "0x84c87814a1f0ab72", + "0x8cc702081a6439ec", + "0x90befffa23631e28", + "0xa4506cebde82bde9", + "0xbef9a3f7b2c67915", + "0xc67178f2e372532b", + "0xca273eceea26619c", + "0xd186b8c721c0c207", + "0xeada7dd6cde0eb1e", + "0xf57d4f7fee6ed178", + "0x06f067aa72176fba", + "0x0a637dc5a2c898a6", + "0x113f9804bef90dae", + "0x1b710b35131c471b", + "0x28db77f523047d84", + "0x32caab7b40c72493", + "0x3c9ebe0a15c9bebc", + "0x431d67c49c100d4c", + "0x4cc5d4becb3e42b6", + "0x597f299cfc657e2a", + "0x5fcb6fab3ad6faec", + "0x6c44198c4a475817" + ].map((n)=>BigInt(n))))(); +const SHA512_W_H = new Uint32Array(80); +const SHA512_W_L = new Uint32Array(80); +class SHA512 extends SHA2 { + constructor(){ + super(128, 64, 16, false); + this.Ah = 1779033703 | 0; + this.Al = 4089235720 | 0; + this.Bh = 3144134277 | 0; + this.Bl = 2227873595 | 0; + this.Ch = 1013904242 | 0; + this.Cl = 4271175723 | 0; + this.Dh = 2773480762 | 0; + this.Dl = 1595750129 | 0; + this.Eh = 1359893119 | 0; + this.El = 2917565137 | 0; + this.Fh = 2600822924 | 0; + this.Fl = 725511199 | 0; + this.Gh = 528734635 | 0; + this.Gl = 4215389547 | 0; + this.Hh = 1541459225 | 0; + this.Hl = 327033209 | 0; } - let whole = comps[0], fraction = comps[1]; - if (!whole) { - whole = "0"; + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [ + Ah, + Al, + Bh, + Bl, + Ch, + Cl, + Dh, + Dl, + Eh, + El, + Fh, + Fl, + Gh, + Gl, + Hh, + Hl + ]; } - if (!fraction) { - fraction = "0"; + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + for(let i = 0; i < 16; i++, offset += 4){ + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32(offset += 4); + } + for(let i = 16; i < 80; i++){ + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + for(let i = 0; i < 80; i++){ + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + const CHIh = Eh & Fh ^ ~Eh & Gh; + const CHIl = El & Fl ^ ~El & Gl; + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; + const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); } - while(fraction[fraction.length - 1] === "0"){ - fraction = fraction.substring(0, fraction.length - 1); + roundClean() { + SHA512_W_H.fill(0); + SHA512_W_L.fill(0); } - if (fraction.length > multiplier.length - 1) { - throwFault$1("fractional component exceeds decimals", "underflow", "parseFixed"); + destroy() { + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); } - if (fraction === "") { - fraction = "0"; +} +const sha512$1 = wrapConstructor(()=>new SHA512); +function getGlobal$1() { + if (typeof self !== "undefined") { + return self; } - while(fraction.length < multiplier.length - 1){ - fraction += "0"; + if (typeof window !== "undefined") { + return window; } - const wholeValue = BigNumber.from(whole); - const fractionValue = BigNumber.from(fraction); - let wei = wholeValue.mul(multiplier).add(fractionValue); - if (negative) { - wei = wei.mul(NegativeOne); + if (typeof global !== "undefined") { + return global; } - return wei; + throw new Error("unable to locate global object"); } -class FixedFormat { - constructor(constructorGuard, signed, width, decimals){ - if (constructorGuard !== _constructorGuard$1) { - logger$1.throwError("cannot use FixedFormat constructor; use FixedFormat.from", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "new FixedFormat" - }); - } - this.signed = signed; - this.width = width; - this.decimals = decimals; - this.name = (signed ? "" : "u") + "fixed" + String(width) + "x" + String(decimals); - this._multiplier = getMultiplier(decimals); - Object.freeze(this); +const anyGlobal = getGlobal$1(); +const crypto1 = anyGlobal.crypto || anyGlobal.msCrypto; +function createHash(algo) { + switch(algo){ + case "sha256": + return sha256$1.create(); + case "sha512": + return sha512$1.create(); + } + assertArgument(false, "invalid hashing algorithm name", "algorithm", algo); +} +function createHmac(_algo, key) { + const algo = { + sha256: sha256$1, + sha512: sha512$1 + }[_algo]; + assertArgument(algo != null, "invalid hmac algorithm", "algorithm", _algo); + return hmac.create(algo, key); +} +function pbkdf2Sync(password, salt, iterations, keylen, _algo) { + const algo = { + sha256: sha256$1, + sha512: sha512$1 + }[_algo]; + assertArgument(algo != null, "invalid pbkdf2 algorithm", "algorithm", _algo); + return pbkdf2$1(algo, password, salt, { + c: iterations, + dkLen: keylen + }); +} +function randomBytes$1(length) { + assert1(crypto1 != null, "platform does not support secure random numbers", "UNSUPPORTED_OPERATION", { + operation: "randomBytes" + }); + assertArgument(Number.isInteger(length) && length > 0 && length <= 1024, "invalid length", "length", length); + const result = new Uint8Array(length); + crypto1.getRandomValues(result); + return result; +} +let locked$4 = false; +const _computeHmac = function(algorithm, key, data) { + return createHmac(algorithm, key).update(data).digest(); +}; +let __computeHmac = _computeHmac; +function computeHmac(algorithm, _key, _data) { + const key = getBytes(_key, "key"); + const data = getBytes(_data, "data"); + return hexlify(__computeHmac(algorithm, key, data)); +} +computeHmac._ = _computeHmac; +computeHmac.lock = function() { + locked$4 = true; +}; +computeHmac.register = function(func) { + if (locked$4) { + throw new Error("computeHmac is locked"); } - static from(value) { - if (value instanceof FixedFormat) { - return value; - } - if (typeof value === "number") { - value = `fixed128x${value}`; - } - let signed = true; - let width = 128; - let decimals = 18; - if (typeof value === "string") { - if (value === "fixed") ; - else if (value === "ufixed") { - signed = false; - } else { - const match = value.match(/^(u?)fixed([0-9]+)x([0-9]+)$/); - if (!match) { - logger$1.throwArgumentError("invalid fixed format", "format", value); - } - signed = match[1] !== "u"; - width = parseInt(match[2]); - decimals = parseInt(match[3]); - } - } else if (value) { - const check = (key, type, defaultValue)=>{ - if (value[key] == null) { - return defaultValue; - } - if (typeof value[key] !== type) { - logger$1.throwArgumentError("invalid fixed format (" + key + " not " + type + ")", "format." + key, value[key]); - } - return value[key]; - }; - signed = check("signed", "boolean", signed); - width = check("width", "number", width); - decimals = check("decimals", "number", decimals); - } - if (width % 8) { - logger$1.throwArgumentError("invalid fixed format width (not byte aligned)", "format.width", width); - } - if (decimals > 80) { - logger$1.throwArgumentError("invalid fixed format (decimals too large)", "format.decimals", decimals); - } - return new FixedFormat(_constructorGuard$1, signed, width, decimals); - } -} -class FixedNumber { - constructor(constructorGuard, hex, value, format){ - if (constructorGuard !== _constructorGuard$1) { - logger$1.throwError("cannot use FixedNumber constructor; use FixedNumber.from", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "new FixedFormat" - }); - } - this.format = format; - this._hex = hex; - this._value = value; - this._isFixedNumber = true; - Object.freeze(this); - } - _checkFormat(other) { - if (this.format.name !== other.format.name) { - logger$1.throwArgumentError("incompatible format; use fixedNumber.toFormat", "other", other); - } - } - addUnsafe(other) { - this._checkFormat(other); - const a = parseFixed(this._value, this.format.decimals); - const b = parseFixed(other._value, other.format.decimals); - return FixedNumber.fromValue(a.add(b), this.format.decimals, this.format); - } - subUnsafe(other) { - this._checkFormat(other); - const a = parseFixed(this._value, this.format.decimals); - const b = parseFixed(other._value, other.format.decimals); - return FixedNumber.fromValue(a.sub(b), this.format.decimals, this.format); - } - mulUnsafe(other) { - this._checkFormat(other); - const a = parseFixed(this._value, this.format.decimals); - const b = parseFixed(other._value, other.format.decimals); - return FixedNumber.fromValue(a.mul(b).div(this.format._multiplier), this.format.decimals, this.format); - } - divUnsafe(other) { - this._checkFormat(other); - const a = parseFixed(this._value, this.format.decimals); - const b = parseFixed(other._value, other.format.decimals); - return FixedNumber.fromValue(a.mul(this.format._multiplier).div(b), this.format.decimals, this.format); - } - floor() { - const comps = this.toString().split("."); - if (comps.length === 1) { - comps.push("0"); - } - let result = FixedNumber.from(comps[0], this.format); - const hasFraction = !comps[1].match(/^(0*)$/); - if (this.isNegative() && hasFraction) { - result = result.subUnsafe(ONE.toFormat(result.format)); - } - return result; - } - ceiling() { - const comps = this.toString().split("."); - if (comps.length === 1) { - comps.push("0"); - } - let result = FixedNumber.from(comps[0], this.format); - const hasFraction = !comps[1].match(/^(0*)$/); - if (!this.isNegative() && hasFraction) { - result = result.addUnsafe(ONE.toFormat(result.format)); - } - return result; - } - round(decimals) { - if (decimals == null) { - decimals = 0; - } - const comps = this.toString().split("."); - if (comps.length === 1) { - comps.push("0"); - } - if (decimals < 0 || decimals > 80 || decimals % 1) { - logger$1.throwArgumentError("invalid decimal count", "decimals", decimals); - } - if (comps[1].length <= decimals) { - return this; + __computeHmac = func; +}; +Object.freeze(computeHmac); +const [SHA3_PI, SHA3_ROTL, _SHA3_IOTA] = [ + [], + [], + [] +]; +const _0n$4 = BigInt(0); +const _1n$5 = BigInt(1); +const _2n$3 = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +const _0x71n = BigInt(113); +for(let round = 0, R = _1n$5, 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$4; + for(let j = 0; j < 7; j++){ + R = (R << _1n$5 ^ (R >> _7n) * _0x71n) % _256n; + if (R & _2n$3) t ^= _1n$5 << (_1n$5 << BigInt(j)) - _1n$5; + } + _SHA3_IOTA.push(t); +} +const [SHA3_IOTA_H, SHA3_IOTA_L] = split$1(_SHA3_IOTA, true); +const rotlH = (h, l, s)=>s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); +const rotlL = (h, l, s)=>s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); +function keccakP(s, rounds = 24) { + const B = new Uint32Array(5 * 2); + for(let round = 24 - rounds; round < 24; round++){ + for(let x = 0; x < 10; x++)B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for(let x = 0; x < 10; x += 2){ + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for(let y = 0; y < 50; y += 10){ + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + let curH = s[2]; + let curL = s[3]; + for(let t = 0; t < 24; t++){ + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + for(let y = 0; y < 50; y += 10){ + for(let x = 0; x < 10; x++)B[x] = s[y + x]; + for(let x = 0; x < 10; x++)s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + } + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + B.fill(0); +} +class Keccak extends Hash { + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24){ + super(); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.rounds = rounds; + this.pos = 0; + this.posOut = 0; + this.finished = false; + this.destroyed = false; + number(outputLen); + if (0 >= this.blockLen || this.blockLen >= 200) throw new Error("Sha3 supports only keccak-f1600 function"); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + keccak() { + keccakP(this.state32, this.rounds); + this.posOut = 0; + this.pos = 0; + } + update(data) { + exists(this); + const { blockLen, state } = this; + data = toBytes(data); + const len = data.length; + for(let pos = 0; pos < 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(); } - const factor = FixedNumber.from("1" + zeros.substring(0, decimals), this.format); - const bump = BUMP.toFormat(this.format); - return this.mulUnsafe(factor).addUnsafe(bump).floor().divUnsafe(factor); + return this; } - isZero() { - return this._value === "0.0" || this._value === "0"; + 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) { + exists(this, false); + bytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for(let pos = 0, len = out.length; pos < len;){ + if (this.posOut >= blockLen) this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes) { + number(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + output(out, this); + if (this.finished) throw new Error("digest() was already called"); + this.writeInto(out); + this.destroy(); + return out; } - isNegative() { - return this._value[0] === "-"; + digest() { + return this.digestInto(new Uint8Array(this.outputLen)); } - toString() { - return this._value; + destroy() { + this.destroyed = true; + this.state.fill(0); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.destroyed = this.destroyed; + return to; + } +} +const gen = (suffix, blockLen, outputLen)=>wrapConstructor(()=>new Keccak(blockLen, suffix, outputLen)); +const keccak_256 = gen(1, 136, 256 / 8); +let locked$3 = false; +const _keccak256 = function(data) { + return keccak_256(data); +}; +let __keccak256 = _keccak256; +function keccak256(_data) { + const data = getBytes(_data, "data"); + return hexlify(__keccak256(data)); +} +keccak256._ = _keccak256; +keccak256.lock = function() { + locked$3 = true; +}; +keccak256.register = function(func) { + if (locked$3) { + throw new TypeError("keccak256 is locked"); } - toHexString(width) { - if (width == null) { - return this._hex; - } - if (width % 8) { - logger$1.throwArgumentError("invalid byte width", "width", width); - } - const hex = BigNumber.from(this._hex).fromTwos(this.format.width).toTwos(width).toHexString(); - return hexZeroPad(hex, width / 8); + __keccak256 = func; +}; +Object.freeze(keccak256); +const Rho = new Uint8Array([ + 7, + 4, + 13, + 1, + 10, + 6, + 15, + 3, + 12, + 0, + 9, + 5, + 2, + 14, + 11, + 8 +]); +const Id = Uint8Array.from({ + length: 16 +}, (_, i)=>i); +const Pi = Id.map((i)=>(9 * i + 5) % 16); +let idxL = [ + Id +]; +let idxR = [ + Pi +]; +for(let i = 0; i < 4; i++)for (let j of [ + idxL, + idxR +])j.push(j[i].map((k)=>Rho[k])); +const shifts = [ + [ + 11, + 14, + 15, + 12, + 5, + 8, + 7, + 9, + 11, + 13, + 14, + 15, + 6, + 7, + 9, + 8 + ], + [ + 12, + 13, + 11, + 15, + 6, + 9, + 9, + 7, + 12, + 15, + 11, + 13, + 7, + 8, + 7, + 7 + ], + [ + 13, + 15, + 14, + 11, + 7, + 7, + 6, + 8, + 13, + 14, + 13, + 12, + 5, + 5, + 6, + 9 + ], + [ + 14, + 11, + 12, + 14, + 8, + 6, + 5, + 5, + 15, + 12, + 15, + 14, + 9, + 9, + 8, + 6 + ], + [ + 15, + 12, + 13, + 13, + 9, + 5, + 8, + 6, + 14, + 11, + 12, + 11, + 8, + 6, + 5, + 5 + ] +].map((i)=>new Uint8Array(i)); +const shiftsL = idxL.map((idx, i)=>idx.map((j)=>shifts[i][j])); +const shiftsR = idxR.map((idx, i)=>idx.map((j)=>shifts[i][j])); +const Kl = new Uint32Array([ + 0, + 1518500249, + 1859775393, + 2400959708, + 2840853838 +]); +const Kr = new Uint32Array([ + 1352829926, + 1548603684, + 1836072691, + 2053994217, + 0 +]); +const rotl$1 = (word, shift)=>word << shift | word >>> 32 - shift; +function f(group, x, y, z) { + if (group === 0) return x ^ y ^ z; + else if (group === 1) return x & y | ~x & z; + else if (group === 2) return (x | ~y) ^ z; + else if (group === 3) return x & z | y & ~z; + else return x ^ (y | ~z); +} +const BUF = new Uint32Array(16); +class RIPEMD160 extends SHA2 { + constructor(){ + super(64, 20, 8, true); + this.h0 = 1732584193 | 0; + this.h1 = 4023233417 | 0; + this.h2 = 2562383102 | 0; + this.h3 = 271733878 | 0; + this.h4 = 3285377520 | 0; } - toUnsafeFloat() { - return parseFloat(this.toString()); + get() { + const { h0, h1, h2, h3, h4 } = this; + return [ + h0, + h1, + h2, + h3, + h4 + ]; } - toFormat(format) { - return FixedNumber.fromString(this._value, format); + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; } - static fromValue(value, decimals, format) { - if (format == null && decimals != null && !isBigNumberish(decimals)) { - format = decimals; - decimals = null; - } - if (decimals == null) { - decimals = 0; - } - if (format == null) { - format = "fixed"; + process(view, offset) { + for(let i = 0; i < 16; i++, offset += 4)BUF[i] = view.getUint32(offset, true); + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + for(let group = 0; group < 5; group++){ + const rGroup = 4 - group; + const hbl = Kl[group], hbr = Kr[group]; + const rl = idxL[group], rr = idxR[group]; + const sl = shiftsL[group], sr = shiftsR[group]; + for(let i = 0; i < 16; i++){ + const tl = rotl$1(al + f(group, bl, cl, dl) + BUF[rl[i]] + hbl, sl[i]) + el | 0; + al = el, el = dl, dl = rotl$1(cl, 10) | 0, cl = bl, bl = tl; + } + for(let i = 0; i < 16; i++){ + const tr = rotl$1(ar + f(rGroup, br, cr, dr) + BUF[rr[i]] + hbr, sr[i]) + er | 0; + ar = er, er = dr, dr = rotl$1(cr, 10) | 0, cr = br, br = tr; + } } - return FixedNumber.fromString(formatFixed(value, decimals), FixedFormat.from(format)); + this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0); } - static fromString(value, format) { - if (format == null) { - format = "fixed"; - } - const fixedFormat = FixedFormat.from(format); - const numeric = parseFixed(value, fixedFormat.decimals); - if (!fixedFormat.signed && numeric.lt(Zero)) { - throwFault$1("unsigned value cannot be negative", "overflow", "value", value); - } - let hex = null; - if (fixedFormat.signed) { - hex = numeric.toTwos(fixedFormat.width).toHexString(); - } else { - hex = numeric.toHexString(); - hex = hexZeroPad(hex, fixedFormat.width / 8); - } - const decimal = formatFixed(numeric, fixedFormat.decimals); - return new FixedNumber(_constructorGuard$1, hex, decimal, fixedFormat); + roundClean() { + BUF.fill(0); } - static fromBytes(value, format) { - if (format == null) { - format = "fixed"; - } - const fixedFormat = FixedFormat.from(format); - if (arrayify(value).length > fixedFormat.width / 8) { - throw new Error("overflow"); - } - let numeric = BigNumber.from(value); - if (fixedFormat.signed) { - numeric = numeric.fromTwos(fixedFormat.width); - } - const hex = numeric.toTwos((fixedFormat.signed ? 0 : 1) + fixedFormat.width).toHexString(); - const decimal = formatFixed(numeric, fixedFormat.decimals); - return new FixedNumber(_constructorGuard$1, hex, decimal, fixedFormat); + destroy() { + this.destroyed = true; + this.buffer.fill(0); + this.set(0, 0, 0, 0, 0); } - static from(value, format) { - if (typeof value === "string") { - return FixedNumber.fromString(value, format); - } - if (isBytes(value)) { - return FixedNumber.fromBytes(value, format); - } - try { - return FixedNumber.fromValue(value, 0, format); - } catch (error) { - if (error.code !== Logger.errors.INVALID_ARGUMENT) { - throw error; - } - } - return logger$1.throwArgumentError("invalid FixedNumber value", "value", value); +} +const ripemd160$1 = wrapConstructor(()=>new RIPEMD160); +let locked$2 = false; +const _ripemd160 = function(data) { + return ripemd160$1(data); +}; +let __ripemd160 = _ripemd160; +function ripemd160(_data) { + const data = getBytes(_data, "data"); + return hexlify(__ripemd160(data)); +} +ripemd160._ = _ripemd160; +ripemd160.lock = function() { + locked$2 = true; +}; +ripemd160.register = function(func) { + if (locked$2) { + throw new TypeError("ripemd160 is locked"); } - static isFixedNumber(value) { - return !!(value && value._isFixedNumber); + __ripemd160 = func; +}; +Object.freeze(ripemd160); +let locked$1 = false; +const _pbkdf2 = function(password, salt, iterations, keylen, algo) { + return pbkdf2Sync(password, salt, iterations, keylen, algo); +}; +let __pbkdf2 = _pbkdf2; +function pbkdf2(_password, _salt, iterations, keylen, algo) { + const password = getBytes(_password, "password"); + const salt = getBytes(_salt, "salt"); + return hexlify(__pbkdf2(password, salt, iterations, keylen, algo)); +} +pbkdf2._ = _pbkdf2; +pbkdf2.lock = function() { + locked$1 = true; +}; +pbkdf2.register = function(func) { + if (locked$1) { + throw new Error("pbkdf2 is locked"); } + __pbkdf2 = func; +}; +Object.freeze(pbkdf2); +let locked = false; +const _randomBytes = function(length) { + return new Uint8Array(randomBytes$1(length)); +}; +let __randomBytes = _randomBytes; +function randomBytes(length) { + return __randomBytes(length); } -const ONE = FixedNumber.from(1); -const BUMP = FixedNumber.from("0.5"); -const version3 = "properties/5.7.0"; -var __awaiter = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); +randomBytes._ = _randomBytes; +randomBytes.lock = function() { + locked = true; +}; +randomBytes.register = function(func) { + if (locked) { + throw new Error("randomBytes is locked"); } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); + __randomBytes = func; }; -const logger22 = new Logger(version3); -function defineReadOnly(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true, - value, - writable: false +Object.freeze(randomBytes); +const rotl = (a, b)=>a << b | a >>> 32 - b; +function XorAndSalsa(prev, pi, input, ii, out, oi) { + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15; + for(let i = 0; i < 8; i += 2){ + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + out[oi++] = y00 + x00 | 0; + out[oi++] = y01 + x01 | 0; + out[oi++] = y02 + x02 | 0; + out[oi++] = y03 + x03 | 0; + out[oi++] = y04 + x04 | 0; + out[oi++] = y05 + x05 | 0; + out[oi++] = y06 + x06 | 0; + out[oi++] = y07 + x07 | 0; + out[oi++] = y08 + x08 | 0; + out[oi++] = y09 + x09 | 0; + out[oi++] = y10 + x10 | 0; + out[oi++] = y11 + x11 | 0; + out[oi++] = y12 + x12 | 0; + out[oi++] = y13 + x13 | 0; + out[oi++] = y14 + x14 | 0; + out[oi++] = y15 + x15 | 0; +} +function BlockMix(input, ii, out, oi, r) { + let head = oi + 0; + let tail = oi + 16 * r; + for(let i = 0; i < 16; i++)out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; + for(let i = 0; i < r; i++, head += 16, ii += 16){ + XorAndSalsa(out, tail, input, ii, out, head); + if (i > 0) tail += 16; + XorAndSalsa(out, head, input, ii += 16, out, tail); + } +} +function scryptInit(password, salt, _opts) { + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024 + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + number(N); + number(r); + number(p); + number(dkLen); + number(asyncTick); + number(maxmem); + if (onProgress !== undefined && typeof onProgress !== "function") throw new Error("progressCb should be function"); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + if (N <= 1 || (N & N - 1) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) { + throw new Error("Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32"); + } + if (p < 0 || p > (2 ** 32 - 1) * 32 / blockSize) { + throw new Error("Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)"); + } + if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) { + throw new Error("Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32"); + } + const memUsed = blockSize * (N + p); + if (memUsed > maxmem) { + throw new Error(`Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`); + } + const B = pbkdf2$1(sha256$1, password, salt, { + c: 1, + dkLen: blockSize * p }); -} -function getStatic(ctor, key) { - for(let i = 0; i < 32; i++){ - if (ctor[key]) { - return ctor[key]; - } - if (!ctor.prototype || typeof ctor.prototype !== "object") { - break; - } - ctor = Object.getPrototypeOf(ctor.prototype).constructor; + const B32 = u32(B); + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = ()=>{}; + if (onProgress) { + const totalBlockMix = 2 * N * p; + const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1); + let blockMixCnt = 0; + blockMixCb = ()=>{ + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) onProgress(blockMixCnt / totalBlockMix); + }; } - return null; -} -function resolveProperties(object) { - return __awaiter(this, void 0, void 0, function*() { - const promises = Object.keys(object).map((key)=>{ - const value = object[key]; - return Promise.resolve(value).then((v)=>({ - key, - value: v - })); - }); - const results = yield Promise.all(promises); - return results.reduce((accum, result)=>{ - accum[result.key] = result.value; - return accum; - }, {}); - }); + return { + N: N, + r: r, + p: p, + dkLen: dkLen, + blockSize32: blockSize32, + V: V, + B32: B32, + B: B, + tmp: tmp, + blockMixCb: blockMixCb, + asyncTick: asyncTick + }; } -function checkProperties(object, properties) { - if (!object || typeof object !== "object") { - logger22.throwArgumentError("invalid object", "object", object); - } - Object.keys(object).forEach((key)=>{ - if (!properties[key]) { - logger22.throwArgumentError("invalid object key - " + key, "transaction:" + key, object); - } +function scryptOutput(password, dkLen, B, V, tmp) { + const res = pbkdf2$1(sha256$1, password, B, { + c: 1, + dkLen: dkLen }); + B.fill(0); + V.fill(0); + tmp.fill(0); + return res; } -function shallowCopy(object) { - const result = {}; - for(const key in object){ - result[key] = object[key]; +function scrypt$1(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + for(let pi = 0; pi < p; pi++){ + const Pi = blockSize32 * pi; + for(let i = 0; i < blockSize32; i++)V[i] = B32[Pi + i]; + for(let i = 0, pos = 0; i < N - 1; i++){ + BlockMix(V, pos, V, pos += blockSize32, r); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); + blockMixCb(); + for(let i = 0; i < N; i++){ + const j = B32[Pi + blockSize32 - 16] % N; + for(let k = 0; k < blockSize32; k++)tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; + BlockMix(tmp, 0, B32, Pi, r); + blockMixCb(); + } + } + return scryptOutput(password, dkLen, B, V, tmp); +} +async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + for(let pi = 0; pi < p; pi++){ + const Pi = blockSize32 * pi; + for(let i = 0; i < blockSize32; i++)V[i] = B32[Pi + i]; + let pos = 0; + await asyncLoop(N - 1, asyncTick, ()=>{ + BlockMix(V, pos, V, pos += blockSize32, r); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); + blockMixCb(); + await asyncLoop(N, asyncTick, ()=>{ + const j = B32[Pi + blockSize32 - 16] % N; + for(let k = 0; k < blockSize32; k++)tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; + BlockMix(tmp, 0, B32, Pi, r); + blockMixCb(); + }); } - return result; + return scryptOutput(password, dkLen, B, V, tmp); } -const opaque = { - bigint: true, - boolean: true, - function: true, - number: true, - string: true +let lockedSync = false, lockedAsync = false; +const _scryptAsync = async function(passwd, salt, N, r, p, dkLen, onProgress) { + return await scryptAsync(passwd, salt, { + N: N, + r: r, + p: p, + dkLen: dkLen, + onProgress: onProgress + }); }; -function _isFrozen(object) { - if (object === void 0 || object === null || opaque[typeof object]) { - return true; +const _scryptSync = function(passwd, salt, N, r, p, dkLen) { + return scrypt$1(passwd, salt, { + N: N, + r: r, + p: p, + dkLen: dkLen + }); +}; +let __scryptAsync = _scryptAsync; +let __scryptSync = _scryptSync; +async function scrypt(_passwd, _salt, N, r, p, dkLen, progress) { + const passwd = getBytes(_passwd, "passwd"); + const salt = getBytes(_salt, "salt"); + return hexlify(await __scryptAsync(passwd, salt, N, r, p, dkLen, progress)); +} +scrypt._ = _scryptAsync; +scrypt.lock = function() { + lockedAsync = true; +}; +scrypt.register = function(func) { + if (lockedAsync) { + throw new Error("scrypt is locked"); } - if (Array.isArray(object) || typeof object === "object") { - if (!Object.isFrozen(object)) { - return false; - } - const keys = Object.keys(object); - for(let i = 0; i < keys.length; i++){ - let value = null; - try { - value = object[keys[i]]; - } catch (error) { - continue; - } - if (!_isFrozen(value)) { - return false; - } - } - return true; + __scryptAsync = func; +}; +Object.freeze(scrypt); +function scryptSync(_passwd, _salt, N, r, p, dkLen) { + const passwd = getBytes(_passwd, "passwd"); + const salt = getBytes(_salt, "salt"); + return hexlify(__scryptSync(passwd, salt, N, r, p, dkLen)); +} +scryptSync._ = _scryptSync; +scryptSync.lock = function() { + lockedSync = true; +}; +scryptSync.register = function(func) { + if (lockedSync) { + throw new Error("scryptSync is locked"); } - return logger22.throwArgumentError(`Cannot deepCopy ${typeof object}`, "object", object); -} -function _deepCopy(object) { - if (_isFrozen(object)) { - return object; + __scryptSync = func; +}; +Object.freeze(scryptSync); +const _sha256 = function(data) { + return createHash("sha256").update(data).digest(); +}; +const _sha512 = function(data) { + return createHash("sha512").update(data).digest(); +}; +let __sha256 = _sha256; +let __sha512 = _sha512; +let locked256 = false, locked512 = false; +function sha256(_data) { + const data = getBytes(_data, "data"); + return hexlify(__sha256(data)); +} +sha256._ = _sha256; +sha256.lock = function() { + locked256 = true; +}; +sha256.register = function(func) { + if (locked256) { + throw new Error("sha256 is locked"); } - if (Array.isArray(object)) { - return Object.freeze(object.map((item)=>deepCopy(item))); + __sha256 = func; +}; +Object.freeze(sha256); +function sha512(_data) { + const data = getBytes(_data, "data"); + return hexlify(__sha512(data)); +} +sha512._ = _sha512; +sha512.lock = function() { + locked512 = true; +}; +sha512.register = function(func) { + if (locked512) { + throw new Error("sha512 is locked"); } - if (typeof object === "object") { - const result = {}; - for(const key in object){ - const value = object[key]; - if (value === void 0) { - continue; - } - defineReadOnly(result, key, deepCopy(value)); - } - return result; + __sha512 = func; +}; +Object.freeze(sha256); +const _0n$3 = BigInt(0); +const _1n$4 = BigInt(1); +const _2n$2 = BigInt(2); +const u8a = (a)=>a instanceof Uint8Array; +const hexes = Array.from({ + length: 256 +}, (_, i)=>i.toString(16).padStart(2, "0")); +function bytesToHex(bytes) { + if (!u8a(bytes)) throw new Error("Uint8Array expected"); + let hex = ""; + for(let i = 0; i < bytes.length; i++){ + hex += hexes[bytes[i]]; + } + return hex; +} +function numberToHexUnpadded(num) { + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; +} +function hexToNumber(hex) { + if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); + return BigInt(hex === "" ? "0" : `0x${hex}`); +} +function hexToBytes(hex) { + if (typeof hex !== "string") throw new Error("hex string expected, got " + typeof hex); + const len = hex.length; + if (len % 2) throw new Error("padded hex string expected, got unpadded hex of length " + len); + const array = new Uint8Array(len / 2); + for(let i = 0; i < array.length; i++){ + const j = i * 2; + const hexByte = hex.slice(j, j + 2); + const __byte = Number.parseInt(hexByte, 16); + if (Number.isNaN(__byte) || __byte < 0) throw new Error("Invalid byte sequence"); + array[i] = __byte; } - return logger22.throwArgumentError(`Cannot deepCopy ${typeof object}`, "object", object); + return array; } -function deepCopy(object) { - return _deepCopy(object); +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); } -class Description { - constructor(info){ - for(const key in info){ - this[key] = deepCopy(info[key]); +function bytesToNumberLE(bytes) { + if (!u8a(bytes)) throw new Error("Uint8Array expected"); + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, "0")); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +function numberToVarBytesBE(n) { + return hexToBytes(numberToHexUnpadded(n)); +} +function ensureBytes(title, hex, expectedLength) { + let res; + if (typeof hex === "string") { + try { + res = hexToBytes(hex); + } catch (e) { + throw new Error(`${title} must be valid hex string, got "${hex}". Cause: ${e}`); } + } else if (u8a(hex)) { + res = Uint8Array.from(hex); + } else { + throw new Error(`${title} must be hex string or Uint8Array`); } + const len = res.length; + if (typeof expectedLength === "number" && len !== expectedLength) throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`); + return res; } -function defaultSetTimout() { - throw new Error("setTimeout has not been defined"); +function concatBytes(...arrays) { + const r = new Uint8Array(arrays.reduce((sum, a)=>sum + a.length, 0)); + let pad = 0; + arrays.forEach((a)=>{ + if (!u8a(a)) throw new Error("Uint8Array expected"); + r.set(a, pad); + pad += a.length; + }); + return r; } -function defaultClearTimeout() { - throw new Error("clearTimeout has not been defined"); +function equalBytes(b1, b2) { + if (b1.length !== b2.length) return false; + for(let i = 0; i < b1.length; i++)if (b1[i] !== b2[i]) return false; + return true; } -var cachedSetTimeout = defaultSetTimout; -var cachedClearTimeout = defaultClearTimeout; -var globalContext; -if (typeof window !== "undefined") { - globalContext = window; -} else if (typeof self !== "undefined") { - globalContext = self; -} else { - globalContext = {}; +function utf8ToBytes(str) { + if (typeof str !== "string") throw new Error(`utf8ToBytes expected string, got ${typeof str}`); + return new Uint8Array((new TextEncoder).encode(str)); } -if (typeof globalContext.setTimeout === "function") { - cachedSetTimeout = setTimeout; +function bitLen(n) { + let len; + for(len = 0; n > _0n$3; n >>= _1n$4, len += 1); + return len; } -if (typeof globalContext.clearTimeout === "function") { - cachedClearTimeout = clearTimeout; +function bitGet(n, pos) { + return n >> BigInt(pos) & _1n$4; } -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - return setTimeout(fun, 0); - } - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - return cachedSetTimeout(fun, 0); - } catch (e) { - try { - return cachedSetTimeout.call(null, fun, 0); - } catch (e2) { - return cachedSetTimeout.call(this, fun, 0); - } +const bitSet = (n, pos, value)=>{ + return n | (value ? _1n$4 : _0n$3) << BigInt(pos); +}; +const bitMask = (n)=>(_2n$2 << BigInt(n - 1)) - _1n$4; +const u8n = (data)=>new Uint8Array(data); +const u8fr = (arr)=>Uint8Array.from(arr); +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + if (typeof hashLen !== "number" || hashLen < 2) throw new Error("hashLen must be a number"); + if (typeof qByteLen !== "number" || qByteLen < 2) throw new Error("qByteLen must be a number"); + if (typeof hmacFn !== "function") throw new Error("hmacFn must be a function"); + let v = u8n(hashLen); + let k = u8n(hashLen); + let i = 0; + const reset = ()=>{ + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...b)=>hmacFn(k, v, ...b); + const reseed = (seed = u8n())=>{ + k = h(u8fr([ + 0 + ]), seed); + v = h(); + if (seed.length === 0) return; + k = h(u8fr([ + 1 + ]), seed); + v = h(); + }; + const gen = ()=>{ + if (i++ >= 1e3) throw new Error("drbg: tried 1000 values"); + let len = 0; + const out = []; + while(len < qByteLen){ + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred)=>{ + reset(); + reseed(seed); + let res = undefined; + while(!(res = pred(gen())))reseed(); + reset(); + return res; + }; + return genUntil; +} +const validatorFns = { + bigint: (val)=>typeof val === "bigint", + function: (val)=>typeof val === "function", + boolean: (val)=>typeof val === "boolean", + string: (val)=>typeof val === "string", + stringOrUint8Array: (val)=>typeof val === "string" || val instanceof Uint8Array, + isSafeInteger: (val)=>Number.isSafeInteger(val), + array: (val)=>Array.isArray(val), + field: (val, object)=>object.Fp.isValid(val), + hash: (val)=>typeof val === "function" && Number.isSafeInteger(val.outputLen) +}; +function validateObject(object, validators, optValidators = {}) { + const checkField = (fieldName, type, isOptional)=>{ + const checkVal = validatorFns[type]; + if (typeof checkVal !== "function") throw new Error(`Invalid validator "${type}", expected function`); + const val = object[fieldName]; + if (isOptional && val === undefined) return; + if (!checkVal(val, object)) { + throw new Error(`Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`); + } + }; + for (const [fieldName, type] of Object.entries(validators))checkField(fieldName, type, false); + for (const [fieldName, type] of Object.entries(optValidators))checkField(fieldName, type, true); + return object; +} +var ut = Object.freeze({ + __proto__: null, + bitGet: bitGet, + bitLen: bitLen, + bitMask: bitMask, + bitSet: bitSet, + bytesToHex: bytesToHex, + bytesToNumberBE: bytesToNumberBE, + bytesToNumberLE: bytesToNumberLE, + concatBytes: concatBytes, + createHmacDrbg: createHmacDrbg, + ensureBytes: ensureBytes, + equalBytes: equalBytes, + hexToBytes: hexToBytes, + hexToNumber: hexToNumber, + numberToBytesBE: numberToBytesBE, + numberToBytesLE: numberToBytesLE, + numberToHexUnpadded: numberToHexUnpadded, + numberToVarBytesBE: numberToVarBytesBE, + utf8ToBytes: utf8ToBytes, + validateObject: validateObject +}); +const _0n$2 = BigInt(0), _1n$3 = BigInt(1), _2n$1 = BigInt(2), _3n$1 = BigInt(3); +const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8); +BigInt(9); +BigInt(16); +function mod(a, b) { + const result = a % b; + return result >= _0n$2 ? result : b + result; +} +function pow(num, power, modulo) { + if (modulo <= _0n$2 || power < _0n$2) throw new Error("Expected power/modulo > 0"); + if (modulo === _1n$3) return _0n$2; + let res = _1n$3; + while(power > _0n$2){ + if (power & _1n$3) res = res * num % modulo; + num = num * num % modulo; + power >>= _1n$3; } + return res; } -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - return clearTimeout(marker); - } - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - return cachedClearTimeout(marker); - } catch (e) { - try { - return cachedClearTimeout.call(null, marker); - } catch (e2) { - return cachedClearTimeout.call(this, marker); - } +function pow2(x, power, modulo) { + let res = x; + while(power-- > _0n$2){ + res *= res; + res %= modulo; } + return res; } -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } +function invert(number, modulo) { + if (number === _0n$2 || modulo <= _0n$2) { + throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`); + } + let a = mod(number, modulo); + let b = modulo; + let x = _0n$2, u = _1n$3; + while(a !== _0n$2){ + const q = b / a; + const r = b % a; + const m = x - u * q; + b = a, a = r, x = u, u = m; + } + const gcd = b; + if (gcd !== _1n$3) throw new Error("invert: does not exist"); + return mod(x, modulo); +} +function tonelliShanks(P) { + const legendreC = (P - _1n$3) / _2n$1; + let Q, S, Z; + for(Q = P - _1n$3, S = 0; Q % _2n$1 === _0n$2; Q /= _2n$1, S++); + for(Z = _2n$1; Z < P && pow(Z, legendreC, P) !== P - _1n$3; Z++); + if (S === 1) { + const p1div4 = (P + _1n$3) / _4n; + return function tonelliFast(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); + return root; + }; + } + const Q1div2 = (Q + _1n$3) / _2n$1; + return function tonelliSlow(Fp, n) { + if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error("Cannot find square root"); + let r = S; + let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); + let x = Fp.pow(n, Q1div2); + let b = Fp.pow(n, Q); + while(!Fp.eql(b, Fp.ONE)){ + if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; + let m = 1; + for(let t2 = Fp.sqr(b); m < r; m++){ + if (Fp.eql(t2, Fp.ONE)) break; + t2 = Fp.sqr(t2); + } + const ge = Fp.pow(g, _1n$3 << BigInt(r - m - 1)); + g = Fp.sqr(ge); + x = Fp.mul(x, ge); + b = Fp.mul(b, g); + r = m; + } + return x; + }; } -function drainQueue() { - if (draining) { - return; +function FpSqrt(P) { + if (P % _4n === _3n$1) { + const p1div4 = (P + _1n$3) / _4n; + return function sqrt3mod4(Fp, n) { + const root = Fp.pow(n, p1div4); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); + return root; + }; } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - while(len){ - currentQueue = queue; - queue = []; - while(++queueIndex < len){ - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; + if (P % _8n === _5n) { + const c1 = (P - _5n) / _8n; + return function sqrt5mod8(Fp, n) { + const n2 = Fp.mul(n, _2n$1); + const v = Fp.pow(n2, c1); + const nv = Fp.mul(n, v); + const i = Fp.mul(Fp.mul(nv, _2n$1), v); + const root = Fp.mul(nv, Fp.sub(i, Fp.ONE)); + if (!Fp.eql(Fp.sqr(root), n)) throw new Error("Cannot find square root"); + return root; + }; } - currentQueue = null; - draining = false; - runClearTimeout(timeout); + return tonelliShanks(P); } -function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for(var i = 1; i < arguments.length; i++){ - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); +const FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" +]; +function validateField(field) { + const initial = { + ORDER: "bigint", + MASK: "bigint", + BYTES: "isSafeInteger", + BITS: "isSafeInteger" + }; + const opts = FIELD_FIELDS.reduce((map, val)=>{ + map[val] = "function"; + return map; + }, initial); + return validateObject(field, opts); +} +function FpPow(f, num, power) { + if (power < _0n$2) throw new Error("Expected power > 0"); + if (power === _0n$2) return f.ONE; + if (power === _1n$3) return num; + let p = f.ONE; + let d = num; + while(power > _0n$2){ + if (power & _1n$3) p = f.mul(p, d); + d = f.sqr(d); + power >>= _1n$3; } + return p; } -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function() { - this.fun.apply(null, this.array); -}; -var title = "browser"; -var platform = "browser"; -var browser = true; -var argv = []; -var version4 = ""; -var versions = {}; -var release = {}; -var config = {}; -function noop() {} -var on = noop; -var addListener = noop; -var once = noop; -var off = noop; -var removeListener = noop; -var removeAllListeners = noop; -var emit = noop; -function binding(name) { - throw new Error("process.binding is not supported"); -} -function cwd() { - return "/"; +function FpInvertBatch(f, nums) { + const tmp = new Array(nums.length); + const lastMultiplied = nums.reduce((acc, num, i)=>{ + if (f.is0(num)) return acc; + tmp[i] = acc; + return f.mul(acc, num); + }, f.ONE); + const inverted = f.inv(lastMultiplied); + nums.reduceRight((acc, num, i)=>{ + if (f.is0(num)) return acc; + tmp[i] = f.mul(acc, tmp[i]); + return f.mul(acc, num); + }, inverted); + return tmp; +} +function nLength(n, nBitLength) { + const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length; + const nByteLength = Math.ceil(_nBitLength / 8); + return { + nBitLength: _nBitLength, + nByteLength: nByteLength + }; } -function chdir(dir) { - throw new Error("process.chdir is not supported"); +function Field(ORDER, bitLen, isLE = false, redef = {}) { + if (ORDER <= _0n$2) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`); + const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen); + if (BYTES > 2048) throw new Error("Field lengths over 2048 bytes are not supported"); + const sqrtP = FpSqrt(ORDER); + const f = Object.freeze({ + ORDER: ORDER, + BITS: BITS, + BYTES: BYTES, + MASK: bitMask(BITS), + ZERO: _0n$2, + ONE: _1n$3, + create: (num)=>mod(num, ORDER), + isValid: (num)=>{ + if (typeof num !== "bigint") throw new Error(`Invalid field element: expected bigint, got ${typeof num}`); + return _0n$2 <= num && num < ORDER; + }, + is0: (num)=>num === _0n$2, + isOdd: (num)=>(num & _1n$3) === _1n$3, + neg: (num)=>mod(-num, ORDER), + eql: (lhs, rhs)=>lhs === rhs, + sqr: (num)=>mod(num * num, ORDER), + add: (lhs, rhs)=>mod(lhs + rhs, ORDER), + sub: (lhs, rhs)=>mod(lhs - rhs, ORDER), + mul: (lhs, rhs)=>mod(lhs * rhs, ORDER), + pow: (num, power)=>FpPow(f, num, power), + div: (lhs, rhs)=>mod(lhs * invert(rhs, ORDER), ORDER), + sqrN: (num)=>num * num, + addN: (lhs, rhs)=>lhs + rhs, + subN: (lhs, rhs)=>lhs - rhs, + mulN: (lhs, rhs)=>lhs * rhs, + inv: (num)=>invert(num, ORDER), + sqrt: redef.sqrt || ((n)=>sqrtP(f, n)), + invertBatch: (lst)=>FpInvertBatch(f, lst), + cmov: (a, b, c)=>c ? b : a, + toBytes: (num)=>isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES), + fromBytes: (bytes)=>{ + if (bytes.length !== BYTES) throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`); + return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + } + }); + return Object.freeze(f); +} +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== "bigint") throw new Error("field order must be bigint"); + const bitLength = fieldOrder.toString(2).length; + return Math.ceil(bitLength / 8); +} +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +function mapHashToField(key, fieldOrder, isLE = false) { + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = getMinHashLength(fieldOrder); + if (len < 16 || len < minLen || len > 1024) throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`); + const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key); + const reduced = mod(num, fieldOrder - _1n$3) + _1n$3; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} +const _0n$1 = BigInt(0); +const _1n$2 = BigInt(1); +function wNAF(c, bits) { + const constTimeNegate = (condition, item)=>{ + const neg = item.negate(); + return condition ? neg : item; + }; + const opts = (W)=>{ + const windows = Math.ceil(bits / W) + 1; + const windowSize = 2 ** (W - 1); + return { + windows: windows, + windowSize: windowSize + }; + }; + return { + constTimeNegate: constTimeNegate, + unsafeLadder (elm, n) { + let p = c.ZERO; + let d = elm; + while(n > _0n$1){ + if (n & _1n$2) p = p.add(d); + d = d.double(); + n >>= _1n$2; + } + return p; + }, + precomputeWindow (elm, W) { + const { windows, windowSize } = opts(W); + const points = []; + let p = elm; + let base = p; + for(let window1 = 0; window1 < windows; window1++){ + base = p; + points.push(base); + for(let i = 1; i < windowSize; i++){ + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + }, + wNAF (W, precomputes, n) { + const { windows, windowSize } = opts(W); + let p = c.ZERO; + let f = c.BASE; + const mask = BigInt(2 ** W - 1); + const maxNumber = 2 ** W; + const shiftBy = BigInt(W); + for(let window1 = 0; window1 < windows; window1++){ + const offset = window1 * windowSize; + let wbits = Number(n & mask); + n >>= shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + n += _1n$2; + } + const offset1 = offset; + const offset2 = offset + Math.abs(wbits) - 1; + const cond1 = window1 % 2 !== 0; + const cond2 = wbits < 0; + if (wbits === 0) { + f = f.add(constTimeNegate(cond1, precomputes[offset1])); + } else { + p = p.add(constTimeNegate(cond2, precomputes[offset2])); + } + } + return { + p: p, + f: f + }; + }, + wNAFCached (P, precomputesMap, n, transform) { + const W = P._WINDOW_SIZE || 1; + let comp = precomputesMap.get(P); + if (!comp) { + comp = this.precomputeWindow(P, W); + if (W !== 1) { + precomputesMap.set(P, transform(comp)); + } + } + return this.wNAF(W, comp, n); + } + }; } -function umask() { - return 0; +function validateBasic(curve) { + validateField(curve.Fp); + validateObject(curve, { + n: "bigint", + h: "bigint", + Gx: "field", + Gy: "field" + }, { + nBitLength: "isSafeInteger", + nByteLength: "isSafeInteger" + }); + return Object.freeze({ + ...nLength(curve.n, curve.nBitLength), + ...curve, + ...{ + p: curve.Fp.ORDER + } + }); } -var performance = globalContext.performance || {}; -var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function() { - return new Date().getTime(); -}; -function hrtime(previousTimestamp) { - var clocktime = performanceNow.call(performance) * 1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor(clocktime % 1 * 1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds < 0) { - seconds--; - nanoseconds += 1e9; +function validatePointOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + a: "field", + b: "field" + }, { + allowedPrivateKeyLengths: "array", + wrapPrivateKey: "boolean", + isTorsionFree: "function", + clearCofactor: "function", + allowInfinityPoint: "boolean", + fromBytes: "function", + toBytes: "function" + }); + const { endo, Fp, a } = opts; + if (endo) { + if (!Fp.eql(a, Fp.ZERO)) { + throw new Error("Endomorphism can only be defined for Koblitz curves that have a=0"); + } + if (typeof endo !== "object" || typeof endo.beta !== "bigint" || typeof endo.splitScalar !== "function") { + throw new Error("Expected endomorphism with beta: bigint and splitScalar: function"); } } - return [ - seconds, - nanoseconds - ]; -} -var startTime = new Date(); -function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1e3; + return Object.freeze({ + ...opts + }); } -var process = { - nextTick, - title, - browser, - env: { - NODE_ENV: "production" +const { bytesToNumberBE: b2n, hexToBytes: h2b } = ut; +const DER = { + Err: class DERErr extends Error { + constructor(m = ""){ + super(m); + } }, - argv, - version: version4, - versions, - on, - addListener, - once, - off, - removeListener, - removeAllListeners, - emit, - binding, - cwd, - chdir, - umask, - hrtime, - platform, - release, - config, - uptime + _parseInt (data) { + const { Err: E } = DER; + if (data.length < 2 || data[0] !== 2) throw new E("Invalid signature integer tag"); + const len = data[1]; + const res = data.subarray(2, len + 2); + if (!len || res.length !== len) throw new E("Invalid signature integer: wrong length"); + if (res[0] & 128) throw new E("Invalid signature integer: negative"); + if (res[0] === 0 && !(res[1] & 128)) throw new E("Invalid signature integer: unnecessary leading zero"); + return { + d: b2n(res), + l: data.subarray(len + 2) + }; + }, + toSig (hex) { + const { Err: E } = DER; + const data = typeof hex === "string" ? h2b(hex) : hex; + if (!(data instanceof Uint8Array)) throw new Error("ui8a expected"); + let l = data.length; + if (l < 2 || data[0] != 48) throw new E("Invalid signature tag"); + if (data[1] !== l - 2) throw new E("Invalid signature: incorrect length"); + const { d: r, l: sBytes } = DER._parseInt(data.subarray(2)); + const { d: s, l: rBytesLeft } = DER._parseInt(sBytes); + if (rBytesLeft.length) throw new E("Invalid signature: left bytes after parsing"); + return { + r: r, + s: s + }; + }, + hexFromSig (sig) { + const slice = (s)=>Number.parseInt(s[0], 16) & 8 ? "00" + s : s; + const h = (num)=>{ + const hex = num.toString(16); + return hex.length & 1 ? `0${hex}` : hex; + }; + const s = slice(h(sig.s)); + const r = slice(h(sig.r)); + const shl = s.length / 2; + const rhl = r.length / 2; + const sl = h(shl); + const rl = h(rhl); + return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`; + } }; -var commonjsGlobal1 = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; -function createCommonjsModule1(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function(path, base) { - return commonjsRequire1(path, base === void 0 || base === null ? module.path : base); +const _0n = BigInt(0), _1n$1 = BigInt(1); +BigInt(2); +const _3n = BigInt(3); +BigInt(4); +function weierstrassPoints(opts) { + const CURVE = validatePointOpts(opts); + const { Fp } = CURVE; + const toBytes = CURVE.toBytes || ((_c, point, _isCompressed)=>{ + const a = point.toAffine(); + return concatBytes(Uint8Array.from([ + 4 + ]), Fp.toBytes(a.x), Fp.toBytes(a.y)); + }); + const fromBytes = CURVE.fromBytes || ((bytes)=>{ + const tail = bytes.subarray(1); + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { + x: x, + y: y + }; + }); + function weierstrassEquation(x) { + const { a, b } = CURVE; + const x2 = Fp.sqr(x); + const x3 = Fp.mul(x2, x); + return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); + } + if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx))) throw new Error("bad generator point: equation left != right"); + function isWithinCurveOrder(num) { + return typeof num === "bigint" && _0n < num && num < CURVE.n; + } + function assertGE(num) { + if (!isWithinCurveOrder(num)) throw new Error("Expected valid bigint: 0 < bigint < curve.n"); + } + function normPrivateKeyToScalar(key) { + const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE; + if (lengths && typeof key !== "bigint") { + if (key instanceof Uint8Array) key = bytesToHex(key); + if (typeof key !== "string" || !lengths.includes(key.length)) throw new Error("Invalid key"); + key = key.padStart(nByteLength * 2, "0"); + } + let num; + try { + num = typeof key === "bigint" ? key : bytesToNumberBE(ensureBytes("private key", key, nByteLength)); + } catch (error) { + throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`); + } + if (wrapPrivateKey) num = mod(num, n); + assertGE(num); + return num; + } + const pointPrecomputes = new Map; + function assertPrjPoint(other) { + if (!(other instanceof Point)) throw new Error("ProjectivePoint expected"); + } + class Point { + constructor(px, py, pz){ + this.px = px; + this.py = py; + this.pz = pz; + if (px == null || !Fp.isValid(px)) throw new Error("x required"); + if (py == null || !Fp.isValid(py)) throw new Error("y required"); + if (pz == null || !Fp.isValid(pz)) throw new Error("z required"); + } + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error("invalid affine point"); + if (p instanceof Point) throw new Error("projective point not allowed"); + const is0 = (i)=>Fp.eql(i, Fp.ZERO); + if (is0(x) && is0(y)) return Point.ZERO; + return new Point(x, y, Fp.ONE); } - }, fn(module, module.exports), module.exports; -} -function commonjsRequire1() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); -} -var sha3 = createCommonjsModule1(function(module) { - (function() { - var INPUT_ERROR = "input is invalid type"; - var FINALIZE_ERROR = "finalize already called"; - var WINDOW = typeof window === "object"; - var root = WINDOW ? window : {}; - if (root.JS_SHA3_NO_WINDOW) { - WINDOW = false; + get x() { + return this.toAffine().x; } - var WEB_WORKER = !WINDOW && typeof self === "object"; - var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node; - if (NODE_JS) { - root = commonjsGlobal1; - } else if (WEB_WORKER) { - root = self; + get y() { + return this.toAffine().y; } - var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && true && module.exports; - var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined"; - var HEX_CHARS = "0123456789abcdef".split(""); - var SHAKE_PADDING = [ - 31, - 7936, - 2031616, - 520093696 - ]; - var CSHAKE_PADDING = [ - 4, - 1024, - 262144, - 67108864 - ]; - var KECCAK_PADDING = [ - 1, - 256, - 65536, - 16777216 - ]; - var PADDING = [ - 6, - 1536, - 393216, - 100663296 - ]; - var SHIFT = [ - 0, - 8, - 16, - 24 - ]; - var RC = [ - 1, - 0, - 32898, - 0, - 32906, - 2147483648, - 2147516416, - 2147483648, - 32907, - 0, - 2147483649, - 0, - 2147516545, - 2147483648, - 32777, - 2147483648, - 138, - 0, - 136, - 0, - 2147516425, - 0, - 2147483658, - 0, - 2147516555, - 0, - 139, - 2147483648, - 32905, - 2147483648, - 32771, - 2147483648, - 32770, - 2147483648, - 128, - 2147483648, - 32778, - 0, - 2147483658, - 2147483648, - 2147516545, - 2147483648, - 32896, - 2147483648, - 2147483649, - 0, - 2147516424, - 2147483648 - ]; - var BITS = [ - 224, - 256, - 384, - 512 - ]; - var SHAKE_BITS = [ - 128, - 256 - ]; - var OUTPUT_TYPES = [ - "hex", - "buffer", - "arrayBuffer", - "array", - "digest" - ]; - var CSHAKE_BYTEPAD = { - "128": 168, - "256": 136 - }; - if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { - Array.isArray = function(obj) { - return Object.prototype.toString.call(obj) === "[object Array]"; - }; + static normalizeZ(points) { + const toInv = Fp.invertBatch(points.map((p)=>p.pz)); + return points.map((p, i)=>p.toAffine(toInv[i])).map(Point.fromAffine); } - if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { - ArrayBuffer.isView = function(obj) { - return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer; - }; + static fromHex(hex) { + const P = Point.fromAffine(fromBytes(ensureBytes("pointHex", hex))); + P.assertValidity(); + return P; } - var createOutputMethod = function(bits2, padding, outputType) { - return function(message) { - return new Keccak(bits2, padding, bits2).update(message)[outputType](); - }; - }; - var createShakeOutputMethod = function(bits2, padding, outputType) { - return function(message, outputBits) { - return new Keccak(bits2, padding, outputBits).update(message)[outputType](); - }; - }; - var createCshakeOutputMethod = function(bits2, padding, outputType) { - return function(message, outputBits, n, s) { - return methods["cshake" + bits2].update(message, outputBits, n, s)[outputType](); + static fromPrivateKey(privateKey) { + return Point.BASE.multiply(normPrivateKeyToScalar(privateKey)); + } + _setWindowSize(windowSize) { + this._WINDOW_SIZE = windowSize; + pointPrecomputes.delete(this); + } + assertValidity() { + if (this.is0()) { + if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) return; + throw new Error("bad point: ZERO"); + } + const { x, y } = this.toAffine(); + if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error("bad point: x or y not FE"); + const left = Fp.sqr(y); + const right = weierstrassEquation(x); + if (!Fp.eql(left, right)) throw new Error("bad point: equation left != right"); + if (!this.isTorsionFree()) throw new Error("bad point: not in prime-order subgroup"); + } + hasEvenY() { + const { y } = this.toAffine(); + if (Fp.isOdd) return !Fp.isOdd(y); + throw new Error("Field doesn't support isOdd"); + } + equals(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + negate() { + return new Point(this.px, Fp.neg(this.py), this.pz); + } + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { px: X1, py: Y1, pz: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; + let t0 = Fp.mul(X1, X1); + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + add(other) { + assertPrjPoint(other); + const { px: X1, py: Y1, pz: Z1 } = this; + const { px: X2, py: Y2, pz: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); + return new Point(X3, Y3, Z3); + } + subtract(other) { + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + wNAF(n) { + return wnaf.wNAFCached(this, pointPrecomputes, n, (comp)=>{ + const toInv = Fp.invertBatch(comp.map((p)=>p.pz)); + return comp.map((p, i)=>p.toAffine(toInv[i])).map(Point.fromAffine); + }); + } + multiplyUnsafe(n) { + const I = Point.ZERO; + if (n === _0n) return I; + assertGE(n); + if (n === _1n$1) return this; + const { endo } = CURVE; + if (!endo) return wnaf.unsafeLadder(this, n); + let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let k1p = I; + let k2p = I; + let d = this; + while(k1 > _0n || k2 > _0n){ + if (k1 & _1n$1) k1p = k1p.add(d); + if (k2 & _1n$1) k2p = k2p.add(d); + d = d.double(); + k1 >>= _1n$1; + k2 >>= _1n$1; + } + if (k1neg) k1p = k1p.negate(); + if (k2neg) k2p = k2p.negate(); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + return k1p.add(k2p); + } + multiply(scalar) { + assertGE(scalar); + let n = scalar; + let point, fake; + const { endo } = CURVE; + if (endo) { + const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n); + let { p: k1p, f: f1p } = this.wNAF(k1); + let { p: k2p, f: f2p } = this.wNAF(k2); + k1p = wnaf.constTimeNegate(k1neg, k1p); + k2p = wnaf.constTimeNegate(k2neg, k2p); + k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz); + point = k1p.add(k2p); + fake = f1p.add(f2p); + } else { + const { p, f } = this.wNAF(n); + point = p; + fake = f; + } + return Point.normalizeZ([ + point, + fake + ])[0]; + } + multiplyAndAddUnsafe(Q, a, b) { + const G = Point.BASE; + const mul = (P, a)=>a === _0n || a === _1n$1 || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a); + const sum = mul(this, a).add(mul(Q, b)); + return sum.is0() ? undefined : sum; + } + toAffine(iz) { + const { px: x, py: y, pz: z } = this; + const is0 = this.is0(); + if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z); + const ax = Fp.mul(x, iz); + const ay = Fp.mul(y, iz); + const zz = Fp.mul(z, iz); + if (is0) return { + x: Fp.ZERO, + y: Fp.ZERO }; - }; - var createKmacOutputMethod = function(bits2, padding, outputType) { - return function(key, message, outputBits, s) { - return methods["kmac" + bits2].update(key, message, outputBits, s)[outputType](); + if (!Fp.eql(zz, Fp.ONE)) throw new Error("invZ was invalid"); + return { + x: ax, + y: ay }; - }; - var createOutputMethods = function(method, createMethod2, bits2, padding) { - for(var i2 = 0; i2 < OUTPUT_TYPES.length; ++i2){ - var type = OUTPUT_TYPES[i2]; - method[type] = createMethod2(bits2, padding, type); + } + isTorsionFree() { + const { h: cofactor, isTorsionFree } = CURVE; + if (cofactor === _1n$1) return true; + if (isTorsionFree) return isTorsionFree(Point, this); + throw new Error("isTorsionFree() has not been declared for the elliptic curve"); + } + clearCofactor() { + const { h: cofactor, clearCofactor } = CURVE; + if (cofactor === _1n$1) return this; + if (clearCofactor) return clearCofactor(Point, this); + return this.multiplyUnsafe(CURVE.h); + } + toRawBytes(isCompressed = true) { + this.assertValidity(); + return toBytes(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return bytesToHex(this.toRawBytes(isCompressed)); + } + } + Point.BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + Point.ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); + const _bits = CURVE.nBitLength; + const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits); + return { + CURVE: CURVE, + ProjectivePoint: Point, + normPrivateKeyToScalar: normPrivateKeyToScalar, + weierstrassEquation: weierstrassEquation, + isWithinCurveOrder: isWithinCurveOrder + }; +} +function validateOpts(curve) { + const opts = validateBasic(curve); + validateObject(opts, { + hash: "hash", + hmac: "function", + randomBytes: "function" + }, { + bits2int: "function", + bits2int_modN: "function", + lowS: "boolean" + }); + return Object.freeze({ + lowS: true, + ...opts + }); +} +function weierstrass(curveDef) { + const CURVE = validateOpts(curveDef); + const { Fp, n: CURVE_ORDER } = CURVE; + const compressedLen = Fp.BYTES + 1; + const uncompressedLen = 2 * Fp.BYTES + 1; + function isValidFieldElement(num) { + return _0n < num && num < Fp.ORDER; + } + function modN(a) { + return mod(a, CURVE_ORDER); + } + function invN(a) { + return invert(a, CURVE_ORDER); + } + const { ProjectivePoint: Point, normPrivateKeyToScalar, weierstrassEquation, isWithinCurveOrder } = weierstrassPoints({ + ...CURVE, + toBytes (_c, point, isCompressed) { + const a = point.toAffine(); + const x = Fp.toBytes(a.x); + const cat = concatBytes; + if (isCompressed) { + return cat(Uint8Array.from([ + point.hasEvenY() ? 2 : 3 + ]), x); + } else { + return cat(Uint8Array.from([ + 4 + ]), x, Fp.toBytes(a.y)); } - return method; + }, + fromBytes (bytes) { + const len = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + if (len === compressedLen && (head === 2 || head === 3)) { + const x = bytesToNumberBE(tail); + if (!isValidFieldElement(x)) throw new Error("Point is not on curve"); + const y2 = weierstrassEquation(x); + let y = Fp.sqrt(y2); + const isYOdd = (y & _1n$1) === _1n$1; + const isHeadOdd = (head & 1) === 1; + if (isHeadOdd !== isYOdd) y = Fp.neg(y); + return { + x: x, + y: y + }; + } else if (len === uncompressedLen && head === 4) { + const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES)); + const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES)); + return { + x: x, + y: y + }; + } else { + throw new Error(`Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`); + } + } + }); + const numToNByteStr = (num)=>bytesToHex(numberToBytesBE(num, CURVE.nByteLength)); + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n$1; + return number > HALF; + } + function normalizeS(s) { + return isBiggerThanHalfOrder(s) ? modN(-s) : s; + } + const slcNum = (b, from, to)=>bytesToNumberBE(b.slice(from, to)); + class Signature { + constructor(r, s, recovery){ + this.r = r; + this.s = s; + this.recovery = recovery; + this.assertValidity(); + } + static fromCompact(hex) { + const l = CURVE.nByteLength; + hex = ensureBytes("compactSignature", hex, l * 2); + return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l)); + } + static fromDER(hex) { + const { r, s } = DER.toSig(ensureBytes("DER", hex)); + return new Signature(r, s); + } + assertValidity() { + if (!isWithinCurveOrder(this.r)) throw new Error("r must be 0 < r < CURVE.n"); + if (!isWithinCurveOrder(this.s)) throw new Error("s must be 0 < s < CURVE.n"); + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + recoverPublicKey(msgHash) { + const { r, s, recovery: rec } = this; + const h = bits2int_modN(ensureBytes("msgHash", msgHash)); + if (rec == null || ![ + 0, + 1, + 2, + 3 + ].includes(rec)) throw new Error("recovery id invalid"); + const radj = rec === 2 || rec === 3 ? r + CURVE.n : r; + if (radj >= Fp.ORDER) throw new Error("recovery id 2 or 3 invalid"); + const prefix = (rec & 1) === 0 ? "02" : "03"; + const R = Point.fromHex(prefix + numToNByteStr(radj)); + const ir = invN(radj); + const u1 = modN(-h * ir); + const u2 = modN(s * ir); + const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); + if (!Q) throw new Error("point at infinify"); + Q.assertValidity(); + return Q; + } + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + normalizeS() { + return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this; + } + toDERRawBytes() { + return hexToBytes(this.toDERHex()); + } + toDERHex() { + return DER.hexFromSig({ + r: this.r, + s: this.s + }); + } + toCompactRawBytes() { + return hexToBytes(this.toCompactHex()); + } + toCompactHex() { + return numToNByteStr(this.r) + numToNByteStr(this.s); + } + } + const utils = { + isValidPrivateKey (privateKey) { + try { + normPrivateKeyToScalar(privateKey); + return true; + } catch (error) { + return false; + } + }, + normPrivateKeyToScalar: normPrivateKeyToScalar, + randomPrivateKey: ()=>{ + const length = getMinHashLength(CURVE.n); + return mapHashToField(CURVE.randomBytes(length), CURVE.n); + }, + precompute (windowSize = 8, point = Point.BASE) { + point._setWindowSize(windowSize); + point.multiply(BigInt(3)); + return point; + } + }; + function getPublicKey(privateKey, isCompressed = true) { + return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed); + } + function isProbPub(item) { + const arr = item instanceof Uint8Array; + const str = typeof item === "string"; + const len = (arr || str) && item.length; + if (arr) return len === compressedLen || len === uncompressedLen; + if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen; + if (item instanceof Point) return true; + return false; + } + function getSharedSecret(privateA, publicB, isCompressed = true) { + if (isProbPub(privateA)) throw new Error("first arg must be private key"); + if (!isProbPub(publicB)) throw new Error("second arg must be public key"); + const b = Point.fromHex(publicB); + return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed); + } + const bits2int = CURVE.bits2int || function(bytes) { + const num = bytesToNumberBE(bytes); + const delta = bytes.length * 8 - CURVE.nBitLength; + return delta > 0 ? num >> BigInt(delta) : num; + }; + const bits2int_modN = CURVE.bits2int_modN || function(bytes) { + return modN(bits2int(bytes)); + }; + const ORDER_MASK = bitMask(CURVE.nBitLength); + function int2octets(num) { + if (typeof num !== "bigint") throw new Error("bigint expected"); + if (!(_0n <= num && num < ORDER_MASK)) throw new Error(`bigint expected < 2^${CURVE.nBitLength}`); + return numberToBytesBE(num, CURVE.nByteLength); + } + function prepSig(msgHash, privateKey, opts = defaultSigOpts) { + if ([ + "recovered", + "canonical" + ].some((k)=>k in opts)) throw new Error("sign() legacy options not supported"); + const { hash, randomBytes } = CURVE; + let { lowS, prehash, extraEntropy: ent } = opts; + if (lowS == null) lowS = true; + msgHash = ensureBytes("msgHash", msgHash); + if (prehash) msgHash = ensureBytes("prehashed msgHash", hash(msgHash)); + const h1int = bits2int_modN(msgHash); + const d = normPrivateKeyToScalar(privateKey); + const seedArgs = [ + int2octets(d), + int2octets(h1int) + ]; + if (ent != null) { + const e = ent === true ? randomBytes(Fp.BYTES) : ent; + seedArgs.push(ensureBytes("extraEntropy", e)); + } + const seed = concatBytes(...seedArgs); + const m = h1int; + function k2sig(kBytes) { + const k = bits2int(kBytes); + if (!isWithinCurveOrder(k)) return; + const ik = invN(k); + const q = Point.BASE.multiply(k).toAffine(); + const r = modN(q.x); + if (r === _0n) return; + const s = modN(ik * modN(m + r * d)); + if (s === _0n) return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n$1); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = normalizeS(s); + recovery ^= 1; + } + return new Signature(r, normS, recovery); + } + return { + seed: seed, + k2sig: k2sig }; - var createMethod = function(bits2, padding) { - var method = createOutputMethod(bits2, padding, "hex"); - method.create = function() { - return new Keccak(bits2, padding, bits2); - }; - method.update = function(message) { - return method.create().update(message); + } + const defaultSigOpts = { + lowS: CURVE.lowS, + prehash: false + }; + const defaultVerOpts = { + lowS: CURVE.lowS, + prehash: false + }; + function sign(msgHash, privKey, opts = defaultSigOpts) { + const { seed, k2sig } = prepSig(msgHash, privKey, opts); + const C = CURVE; + const drbg = createHmacDrbg(C.hash.outputLen, C.nByteLength, C.hmac); + return drbg(seed, k2sig); + } + Point.BASE._setWindowSize(8); + function verify(signature, msgHash, publicKey, opts = defaultVerOpts) { + const sg = signature; + msgHash = ensureBytes("msgHash", msgHash); + publicKey = ensureBytes("publicKey", publicKey); + if ("strict" in opts) throw new Error("options.strict was renamed to lowS"); + const { lowS, prehash } = opts; + let _sig = undefined; + let P; + try { + if (typeof sg === "string" || sg instanceof Uint8Array) { + try { + _sig = Signature.fromDER(sg); + } catch (derError) { + if (!(derError instanceof DER.Err)) throw derError; + _sig = Signature.fromCompact(sg); + } + } else if (typeof sg === "object" && typeof sg.r === "bigint" && typeof sg.s === "bigint") { + const { r, s } = sg; + _sig = new Signature(r, s); + } else { + throw new Error("PARSE"); + } + P = Point.fromHex(publicKey); + } catch (error) { + if (error.message === "PARSE") throw new Error(`signature must be Signature instance, Uint8Array or hex string`); + return false; + } + if (lowS && _sig.hasHighS()) return false; + if (prehash) msgHash = CURVE.hash(msgHash); + const { r, s } = _sig; + const h = bits2int_modN(msgHash); + const is = invN(s); + const u1 = modN(h * is); + const u2 = modN(r * is); + const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); + if (!R) return false; + const v = modN(R.x); + return v === r; + } + return { + CURVE: CURVE, + getPublicKey: getPublicKey, + getSharedSecret: getSharedSecret, + sign: sign, + verify: verify, + ProjectivePoint: Point, + Signature: Signature, + utils: utils + }; +} +function getHash(hash) { + return { + hash: hash, + hmac: (key, ...msgs)=>hmac(hash, key, concatBytes$1(...msgs)), + randomBytes: randomBytes$2 + }; +} +function createCurve(curveDef, defHash) { + const create = (hash)=>weierstrass({ + ...curveDef, + ...getHash(hash) + }); + return Object.freeze({ + ...create(defHash), + create: create + }); +} +const secp256k1P = BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"); +const secp256k1N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const _1n = BigInt(1); +const _2n = BigInt(2); +const divNearest = (a, b)=>(a + b / _2n) / b; +function sqrtMod(y) { + const P = secp256k1P; + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = y * y * y % P; + const b3 = b2 * b2 * y % P; + const b6 = pow2(b3, _3n, P) * b3 % P; + const b9 = pow2(b6, _3n, P) * b3 % P; + const b11 = pow2(b9, _2n, P) * b2 % P; + const b22 = pow2(b11, _11n, P) * b11 % P; + const b44 = pow2(b22, _22n, P) * b22 % P; + const b88 = pow2(b44, _44n, P) * b44 % P; + const b176 = pow2(b88, _88n, P) * b88 % P; + const b220 = pow2(b176, _44n, P) * b44 % P; + const b223 = pow2(b220, _3n, P) * b3 % P; + const t1 = pow2(b223, _23n, P) * b22 % P; + const t2 = pow2(t1, _6n, P) * b2 % P; + const root = pow2(t2, _2n, P); + if (!Fp.eql(Fp.sqr(root), y)) throw new Error("Cannot find square root"); + return root; +} +const Fp = Field(secp256k1P, undefined, undefined, { + sqrt: sqrtMod +}); +const secp256k1 = createCurve({ + a: BigInt(0), + b: BigInt(7), + Fp: Fp, + n: secp256k1N, + Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"), + Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"), + h: BigInt(1), + lowS: true, + endo: { + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + splitScalar: (k)=>{ + const n = secp256k1N; + const a1 = BigInt("0x3086d221a7d46bcde86c90e49284eb15"); + const b1 = -_1n * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"); + const a2 = BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"); + const b2 = a1; + const POW_2_128 = BigInt("0x100000000000000000000000000000000"); + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = mod(k - c1 * a1 - c2 * a2, n); + let k2 = mod(-c1 * b1 - c2 * b2, n); + const k1neg = k1 > POW_2_128; + const k2neg = k2 > POW_2_128; + if (k1neg) k1 = n - k1; + if (k2neg) k2 = n - k2; + if (k1 > POW_2_128 || k2 > POW_2_128) { + throw new Error("splitScalar: Endomorphism failed, k=" + k); + } + return { + k1neg: k1neg, + k1: k1, + k2neg: k2neg, + k2: k2 }; - return createOutputMethods(method, createOutputMethod, bits2, padding); - }; - var createShakeMethod = function(bits2, padding) { - var method = createShakeOutputMethod(bits2, padding, "hex"); - method.create = function(outputBits) { - return new Keccak(bits2, padding, outputBits); - }; - method.update = function(message, outputBits) { - return method.create(outputBits).update(message); - }; - return createOutputMethods(method, createShakeOutputMethod, bits2, padding); - }; - var createCshakeMethod = function(bits2, padding) { - var w = CSHAKE_BYTEPAD[bits2]; - var method = createCshakeOutputMethod(bits2, padding, "hex"); - method.create = function(outputBits, n, s) { - if (!n && !s) { - return methods["shake" + bits2].create(outputBits); - } else { - return new Keccak(bits2, padding, outputBits).bytepad([ - n, - s - ], w); - } - }; - method.update = function(message, outputBits, n, s) { - return method.create(outputBits, n, s).update(message); - }; - return createOutputMethods(method, createCshakeOutputMethod, bits2, padding); - }; - var createKmacMethod = function(bits2, padding) { - var w = CSHAKE_BYTEPAD[bits2]; - var method = createKmacOutputMethod(bits2, padding, "hex"); - method.create = function(key, outputBits, s) { - return new Kmac(bits2, padding, outputBits).bytepad([ - "KMAC", - s - ], w).bytepad([ - key - ], w); - }; - method.update = function(key, message, outputBits, s) { - return method.create(key, outputBits, s).update(message); - }; - return createOutputMethods(method, createKmacOutputMethod, bits2, padding); - }; - var algorithms = [ - { - name: "keccak", - padding: KECCAK_PADDING, - bits: BITS, - createMethod - }, - { - name: "sha3", - padding: PADDING, - bits: BITS, - createMethod - }, - { - name: "shake", - padding: SHAKE_PADDING, - bits: SHAKE_BITS, - createMethod: createShakeMethod - }, - { - name: "cshake", - padding: CSHAKE_PADDING, - bits: SHAKE_BITS, - createMethod: createCshakeMethod - }, - { - name: "kmac", - padding: CSHAKE_PADDING, - bits: SHAKE_BITS, - createMethod: createKmacMethod - } - ]; - var methods = {}, methodNames = []; - for(var i = 0; i < algorithms.length; ++i){ - var algorithm = algorithms[i]; - var bits = algorithm.bits; - for(var j = 0; j < bits.length; ++j){ - var methodName = algorithm.name + "_" + bits[j]; - methodNames.push(methodName); - methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); - if (algorithm.name !== "sha3") { - var newMethodName = algorithm.name + bits[j]; - methodNames.push(newMethodName); - methods[newMethodName] = methods[methodName]; - } - } } - function Keccak(bits2, padding, outputBits) { - this.blocks = []; - this.s = []; - this.padding = padding; - this.outputBits = outputBits; - this.reset = true; - this.finalized = false; - this.block = 0; - this.start = 0; - this.blockCount = 1600 - (bits2 << 1) >> 5; - this.byteCount = this.blockCount << 2; - this.outputBlocks = outputBits >> 5; - this.extraBytes = (outputBits & 31) >> 3; - for(var i2 = 0; i2 < 50; ++i2){ - this.s[i2] = 0; - } + } +}, sha256$1); +BigInt(0); +secp256k1.ProjectivePoint; +const ZeroAddress = "0x0000000000000000000000000000000000000000"; +const ZeroHash = "0x0000000000000000000000000000000000000000000000000000000000000000"; +const N$1 = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const WeiPerEther = BigInt("1000000000000000000"); +const MaxUint256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const MinInt256 = BigInt("0x8000000000000000000000000000000000000000000000000000000000000000") * BigInt(-1); +const MaxInt256 = BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const EtherSymbol = "Ξ"; +const MessagePrefix = "Ethereum Signed Message:\n"; +const BN_0$7 = BigInt(0); +const BN_1$3 = BigInt(1); +const BN_2$3 = BigInt(2); +const BN_27$1 = BigInt(27); +const BN_28$1 = BigInt(28); +const BN_35$1 = BigInt(35); +const _guard$3 = {}; +function toUint256(value) { + return zeroPadValue(toBeArray(value), 32); +} +class Signature { + #r; + #s; + #v; + #networkV; + get r() { + return this.#r; + } + set r(value) { + assertArgument(dataLength(value) === 32, "invalid r", "value", value); + this.#r = hexlify(value); + } + get s() { + return this.#s; + } + set s(_value) { + assertArgument(dataLength(_value) === 32, "invalid s", "value", _value); + const value = hexlify(_value); + assertArgument(parseInt(value.substring(0, 3)) < 8, "non-canonical s", "value", value); + this.#s = value; + } + get v() { + return this.#v; + } + set v(value) { + const v = getNumber(value, "value"); + assertArgument(v === 27 || v === 28, "invalid v", "v", value); + this.#v = v; + } + get networkV() { + return this.#networkV; + } + get legacyChainId() { + const v = this.networkV; + if (v == null) { + return null; } - Keccak.prototype.update = function(message) { - if (this.finalized) { - throw new Error(FINALIZE_ERROR); - } - var notString, type = typeof message; - if (type !== "string") { - if (type === "object") { - if (message === null) { - throw new Error(INPUT_ERROR); - } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { - message = new Uint8Array(message); - } else if (!Array.isArray(message)) { - if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { - throw new Error(INPUT_ERROR); - } - } - } else { - throw new Error(INPUT_ERROR); - } - notString = true; - } - var blocks = this.blocks, byteCount = this.byteCount, length = message.length, blockCount = this.blockCount, index = 0, s = this.s, i2, code; - while(index < length){ - if (this.reset) { - this.reset = false; - blocks[0] = this.block; - for(i2 = 1; i2 < blockCount + 1; ++i2){ - blocks[i2] = 0; - } - } - if (notString) { - for(i2 = this.start; index < length && i2 < byteCount; ++index){ - blocks[i2 >> 2] |= message[index] << SHIFT[i2++ & 3]; - } - } else { - for(i2 = this.start; index < length && i2 < byteCount; ++index){ - code = message.charCodeAt(index); - if (code < 128) { - blocks[i2 >> 2] |= code << SHIFT[i2++ & 3]; - } else if (code < 2048) { - blocks[i2 >> 2] |= (192 | code >> 6) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; - } else if (code < 55296 || code >= 57344) { - blocks[i2 >> 2] |= (224 | code >> 12) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; - } else { - code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); - blocks[i2 >> 2] |= (240 | code >> 18) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code >> 12 & 63) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; - blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; - } - } - } - this.lastByteIndex = i2; - if (i2 >= byteCount) { - this.start = i2 - byteCount; - this.block = blocks[blockCount]; - for(i2 = 0; i2 < blockCount; ++i2){ - s[i2] ^= blocks[i2]; - } - f(s); - this.reset = true; - } else { - this.start = i2; - } - } - return this; - }; - Keccak.prototype.encode = function(x, right) { - var o = x & 255, n = 1; - var bytes = [ - o - ]; - x = x >> 8; - o = x & 255; - while(o > 0){ - bytes.unshift(o); - x = x >> 8; - o = x & 255; - ++n; - } - if (right) { - bytes.push(n); - } else { - bytes.unshift(n); + return Signature.getChainId(v); + } + get yParity() { + return this.v === 27 ? 0 : 1; + } + get yParityAndS() { + const yParityAndS = getBytes(this.s); + if (this.yParity) { + yParityAndS[0] |= 128; + } + return hexlify(yParityAndS); + } + get compactSerialized() { + return concat([ + this.r, + this.yParityAndS + ]); + } + get serialized() { + return concat([ + this.r, + this.s, + this.yParity ? "0x1c" : "0x1b" + ]); + } + constructor(guard, r, s, v){ + assertPrivate(guard, _guard$3, "Signature"); + this.#r = r; + this.#s = s; + this.#v = v; + this.#networkV = null; + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return `Signature { r: "${this.r}", s: "${this.s}", yParity: ${this.yParity}, networkV: ${this.networkV} }`; + } + clone() { + const clone = new Signature(_guard$3, this.r, this.s, this.v); + if (this.networkV) { + clone.#networkV = this.networkV; + } + return clone; + } + toJSON() { + const networkV = this.networkV; + return { + _type: "signature", + networkV: networkV != null ? networkV.toString() : null, + r: this.r, + s: this.s, + v: this.v + }; + } + static getChainId(v) { + const bv = getBigInt(v, "v"); + if (bv == BN_27$1 || bv == BN_28$1) { + return BN_0$7; + } + assertArgument(bv >= BN_35$1, "invalid EIP-155 v", "v", v); + return (bv - BN_35$1) / BN_2$3; + } + static getChainIdV(chainId, v) { + return getBigInt(chainId) * BN_2$3 + BigInt(35 + v - 27); + } + static getNormalizedV(v) { + const bv = getBigInt(v); + if (bv === BN_0$7 || bv === BN_27$1) { + return 27; + } + if (bv === BN_1$3 || bv === BN_28$1) { + return 28; + } + assertArgument(bv >= BN_35$1, "invalid v", "v", v); + return bv & BN_1$3 ? 27 : 28; + } + static from(sig) { + function assertError(check, message) { + assertArgument(check, message, "signature", sig); + } + if (sig == null) { + return new Signature(_guard$3, ZeroHash, ZeroHash, 27); + } + if (typeof sig === "string") { + const bytes = getBytes(sig, "signature"); + if (bytes.length === 64) { + const r = hexlify(bytes.slice(0, 32)); + const s = bytes.slice(32, 64); + const v = s[0] & 128 ? 28 : 27; + s[0] &= 127; + return new Signature(_guard$3, r, hexlify(s), v); + } + if (bytes.length === 65) { + const r = hexlify(bytes.slice(0, 32)); + const s = bytes.slice(32, 64); + assertError((s[0] & 128) === 0, "non-canonical s"); + const v = Signature.getNormalizedV(bytes[64]); + return new Signature(_guard$3, r, hexlify(s), v); + } + assertError(false, "invalid raw signature length"); + } + if (sig instanceof Signature) { + return sig.clone(); + } + const _r = sig.r; + assertError(_r != null, "missing r"); + const r = toUint256(_r); + const s = function(s, yParityAndS) { + if (s != null) { + return toUint256(s); + } + if (yParityAndS != null) { + assertError(isHexString(yParityAndS, 32), "invalid yParityAndS"); + const bytes = getBytes(yParityAndS); + bytes[0] &= 127; + return hexlify(bytes); + } + assertError(false, "missing s"); + }(sig.s, sig.yParityAndS); + assertError((getBytes(s)[0] & 128) == 0, "non-canonical s"); + const { networkV, v } = function(_v, yParityAndS, yParity) { + if (_v != null) { + const v = getBigInt(_v); + return { + networkV: v >= BN_35$1 ? v : undefined, + v: Signature.getNormalizedV(v) + }; } - this.update(bytes); - return bytes.length; - }; - Keccak.prototype.encodeString = function(str) { - var notString, type = typeof str; - if (type !== "string") { - if (type === "object") { - if (str === null) { - throw new Error(INPUT_ERROR); - } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) { - str = new Uint8Array(str); - } else if (!Array.isArray(str)) { - if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) { - throw new Error(INPUT_ERROR); - } - } - } else { - throw new Error(INPUT_ERROR); - } - notString = true; + if (yParityAndS != null) { + assertError(isHexString(yParityAndS, 32), "invalid yParityAndS"); + return { + v: getBytes(yParityAndS)[0] & 128 ? 28 : 27 + }; } - var bytes = 0, length = str.length; - if (notString) { - bytes = length; - } else { - for(var i2 = 0; i2 < str.length; ++i2){ - var code = str.charCodeAt(i2); - if (code < 128) { - bytes += 1; - } else if (code < 2048) { - bytes += 2; - } else if (code < 55296 || code >= 57344) { - bytes += 3; - } else { - code = 65536 + ((code & 1023) << 10 | str.charCodeAt(++i2) & 1023); - bytes += 4; - } + if (yParity != null) { + switch(getNumber(yParity, "sig.yParity")){ + case 0: + return { + v: 27 + }; + case 1: + return { + v: 28 + }; } + assertError(false, "invalid yParity"); } - bytes += this.encode(bytes * 8); - this.update(str); - return bytes; - }; - Keccak.prototype.bytepad = function(strs, w) { - var bytes = this.encode(w); - for(var i2 = 0; i2 < strs.length; ++i2){ - bytes += this.encodeString(strs[i2]); - } - var paddingBytes = w - bytes % w; - var zeros = []; - zeros.length = paddingBytes; - this.update(zeros); - return this; - }; - Keccak.prototype.finalize = function() { - if (this.finalized) { - return; - } - this.finalized = true; - var blocks = this.blocks, i2 = this.lastByteIndex, blockCount = this.blockCount, s = this.s; - blocks[i2 >> 2] |= this.padding[i2 & 3]; - if (this.lastByteIndex === this.byteCount) { - blocks[0] = blocks[blockCount]; - for(i2 = 1; i2 < blockCount + 1; ++i2){ - blocks[i2] = 0; - } - } - blocks[blockCount - 1] |= 2147483648; - for(i2 = 0; i2 < blockCount; ++i2){ - s[i2] ^= blocks[i2]; - } - f(s); - }; - Keccak.prototype.toString = Keccak.prototype.hex = function() { - this.finalize(); - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; - var hex = "", block; - while(j2 < outputBlocks){ - for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ - block = s[i2]; - hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15] + HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15] + HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15] + HEX_CHARS[block >> 28 & 15] + HEX_CHARS[block >> 24 & 15]; - } - if (j2 % blockCount === 0) { - f(s); - i2 = 0; - } - } - if (extraBytes) { - block = s[i2]; - hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15]; - if (extraBytes > 1) { - hex += HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15]; - } - if (extraBytes > 2) { - hex += HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15]; - } - } - return hex; - }; - Keccak.prototype.arrayBuffer = function() { - this.finalize(); - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; - var bytes = this.outputBits >> 3; - var buffer; - if (extraBytes) { - buffer = new ArrayBuffer(outputBlocks + 1 << 2); - } else { - buffer = new ArrayBuffer(bytes); - } - var array = new Uint32Array(buffer); - while(j2 < outputBlocks){ - for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ - array[j2] = s[i2]; - } - if (j2 % blockCount === 0) { - f(s); - } - } - if (extraBytes) { - array[i2] = s[i2]; - buffer = buffer.slice(0, bytes); - } - return buffer; - }; - Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; - Keccak.prototype.digest = Keccak.prototype.array = function() { - this.finalize(); - var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; - var array = [], offset, block; - while(j2 < outputBlocks){ - for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ - offset = j2 << 2; - block = s[i2]; - array[offset] = block & 255; - array[offset + 1] = block >> 8 & 255; - array[offset + 2] = block >> 16 & 255; - array[offset + 3] = block >> 24 & 255; - } - if (j2 % blockCount === 0) { - f(s); - } - } - if (extraBytes) { - offset = j2 << 2; - block = s[i2]; - array[offset] = block & 255; - if (extraBytes > 1) { - array[offset + 1] = block >> 8 & 255; - } - if (extraBytes > 2) { - array[offset + 2] = block >> 16 & 255; - } - } - return array; - }; - function Kmac(bits2, padding, outputBits) { - Keccak.call(this, bits2, padding, outputBits); + assertError(false, "missing v"); + }(sig.v, sig.yParityAndS, sig.yParity); + const result = new Signature(_guard$3, r, s, v); + if (networkV) { + result.#networkV = networkV; } - Kmac.prototype = new Keccak(); - Kmac.prototype.finalize = function() { - this.encode(this.outputBits, true); - return Keccak.prototype.finalize.call(this); - }; - var f = function(s) { - var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; - for(n = 0; n < 48; n += 2){ - c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; - c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; - c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; - c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; - c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; - c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; - c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; - c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; - c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; - c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; - h = c8 ^ (c2 << 1 | c3 >>> 31); - l = c9 ^ (c3 << 1 | c2 >>> 31); - s[0] ^= h; - s[1] ^= l; - s[10] ^= h; - s[11] ^= l; - s[20] ^= h; - s[21] ^= l; - s[30] ^= h; - s[31] ^= l; - s[40] ^= h; - s[41] ^= l; - h = c0 ^ (c4 << 1 | c5 >>> 31); - l = c1 ^ (c5 << 1 | c4 >>> 31); - s[2] ^= h; - s[3] ^= l; - s[12] ^= h; - s[13] ^= l; - s[22] ^= h; - s[23] ^= l; - s[32] ^= h; - s[33] ^= l; - s[42] ^= h; - s[43] ^= l; - h = c2 ^ (c6 << 1 | c7 >>> 31); - l = c3 ^ (c7 << 1 | c6 >>> 31); - s[4] ^= h; - s[5] ^= l; - s[14] ^= h; - s[15] ^= l; - s[24] ^= h; - s[25] ^= l; - s[34] ^= h; - s[35] ^= l; - s[44] ^= h; - s[45] ^= l; - h = c4 ^ (c8 << 1 | c9 >>> 31); - l = c5 ^ (c9 << 1 | c8 >>> 31); - s[6] ^= h; - s[7] ^= l; - s[16] ^= h; - s[17] ^= l; - s[26] ^= h; - s[27] ^= l; - s[36] ^= h; - s[37] ^= l; - s[46] ^= h; - s[47] ^= l; - h = c6 ^ (c0 << 1 | c1 >>> 31); - l = c7 ^ (c1 << 1 | c0 >>> 31); - s[8] ^= h; - s[9] ^= l; - s[18] ^= h; - s[19] ^= l; - s[28] ^= h; - s[29] ^= l; - s[38] ^= h; - s[39] ^= l; - s[48] ^= h; - s[49] ^= l; - b0 = s[0]; - b1 = s[1]; - b32 = s[11] << 4 | s[10] >>> 28; - b33 = s[10] << 4 | s[11] >>> 28; - b14 = s[20] << 3 | s[21] >>> 29; - b15 = s[21] << 3 | s[20] >>> 29; - b46 = s[31] << 9 | s[30] >>> 23; - b47 = s[30] << 9 | s[31] >>> 23; - b28 = s[40] << 18 | s[41] >>> 14; - b29 = s[41] << 18 | s[40] >>> 14; - b20 = s[2] << 1 | s[3] >>> 31; - b21 = s[3] << 1 | s[2] >>> 31; - b2 = s[13] << 12 | s[12] >>> 20; - b3 = s[12] << 12 | s[13] >>> 20; - b34 = s[22] << 10 | s[23] >>> 22; - b35 = s[23] << 10 | s[22] >>> 22; - b16 = s[33] << 13 | s[32] >>> 19; - b17 = s[32] << 13 | s[33] >>> 19; - b48 = s[42] << 2 | s[43] >>> 30; - b49 = s[43] << 2 | s[42] >>> 30; - b40 = s[5] << 30 | s[4] >>> 2; - b41 = s[4] << 30 | s[5] >>> 2; - b22 = s[14] << 6 | s[15] >>> 26; - b23 = s[15] << 6 | s[14] >>> 26; - b4 = s[25] << 11 | s[24] >>> 21; - b5 = s[24] << 11 | s[25] >>> 21; - b36 = s[34] << 15 | s[35] >>> 17; - b37 = s[35] << 15 | s[34] >>> 17; - b18 = s[45] << 29 | s[44] >>> 3; - b19 = s[44] << 29 | s[45] >>> 3; - b10 = s[6] << 28 | s[7] >>> 4; - b11 = s[7] << 28 | s[6] >>> 4; - b42 = s[17] << 23 | s[16] >>> 9; - b43 = s[16] << 23 | s[17] >>> 9; - b24 = s[26] << 25 | s[27] >>> 7; - b25 = s[27] << 25 | s[26] >>> 7; - b6 = s[36] << 21 | s[37] >>> 11; - b7 = s[37] << 21 | s[36] >>> 11; - b38 = s[47] << 24 | s[46] >>> 8; - b39 = s[46] << 24 | s[47] >>> 8; - b30 = s[8] << 27 | s[9] >>> 5; - b31 = s[9] << 27 | s[8] >>> 5; - b12 = s[18] << 20 | s[19] >>> 12; - b13 = s[19] << 20 | s[18] >>> 12; - b44 = s[29] << 7 | s[28] >>> 25; - b45 = s[28] << 7 | s[29] >>> 25; - b26 = s[38] << 8 | s[39] >>> 24; - b27 = s[39] << 8 | s[38] >>> 24; - b8 = s[48] << 14 | s[49] >>> 18; - b9 = s[49] << 14 | s[48] >>> 18; - s[0] = b0 ^ ~b2 & b4; - s[1] = b1 ^ ~b3 & b5; - s[10] = b10 ^ ~b12 & b14; - s[11] = b11 ^ ~b13 & b15; - s[20] = b20 ^ ~b22 & b24; - s[21] = b21 ^ ~b23 & b25; - s[30] = b30 ^ ~b32 & b34; - s[31] = b31 ^ ~b33 & b35; - s[40] = b40 ^ ~b42 & b44; - s[41] = b41 ^ ~b43 & b45; - s[2] = b2 ^ ~b4 & b6; - s[3] = b3 ^ ~b5 & b7; - s[12] = b12 ^ ~b14 & b16; - s[13] = b13 ^ ~b15 & b17; - s[22] = b22 ^ ~b24 & b26; - s[23] = b23 ^ ~b25 & b27; - s[32] = b32 ^ ~b34 & b36; - s[33] = b33 ^ ~b35 & b37; - s[42] = b42 ^ ~b44 & b46; - s[43] = b43 ^ ~b45 & b47; - s[4] = b4 ^ ~b6 & b8; - s[5] = b5 ^ ~b7 & b9; - s[14] = b14 ^ ~b16 & b18; - s[15] = b15 ^ ~b17 & b19; - s[24] = b24 ^ ~b26 & b28; - s[25] = b25 ^ ~b27 & b29; - s[34] = b34 ^ ~b36 & b38; - s[35] = b35 ^ ~b37 & b39; - s[44] = b44 ^ ~b46 & b48; - s[45] = b45 ^ ~b47 & b49; - s[6] = b6 ^ ~b8 & b0; - s[7] = b7 ^ ~b9 & b1; - s[16] = b16 ^ ~b18 & b10; - s[17] = b17 ^ ~b19 & b11; - s[26] = b26 ^ ~b28 & b20; - s[27] = b27 ^ ~b29 & b21; - s[36] = b36 ^ ~b38 & b30; - s[37] = b37 ^ ~b39 & b31; - s[46] = b46 ^ ~b48 & b40; - s[47] = b47 ^ ~b49 & b41; - s[8] = b8 ^ ~b0 & b2; - s[9] = b9 ^ ~b1 & b3; - s[18] = b18 ^ ~b10 & b12; - s[19] = b19 ^ ~b11 & b13; - s[28] = b28 ^ ~b20 & b22; - s[29] = b29 ^ ~b21 & b23; - s[38] = b38 ^ ~b30 & b32; - s[39] = b39 ^ ~b31 & b33; - s[48] = b48 ^ ~b40 & b42; - s[49] = b49 ^ ~b41 & b43; - s[0] ^= RC[n]; - s[1] ^= RC[n + 1]; - } - }; - if (COMMON_JS) { - module.exports = methods; - } else { - for(i = 0; i < methodNames.length; ++i){ - root[methodNames[i]] = methods[methodNames[i]]; - } - } - })(); -}); -sha3.cshake128; -sha3.cshake256; -sha3.cshake_128; -sha3.cshake_256; -sha3.keccak224; -sha3.keccak256; -sha3.keccak384; -sha3.keccak512; -sha3.keccak_224; -sha3.keccak_256; -sha3.keccak_384; -sha3.keccak_512; -sha3.kmac128; -sha3.kmac256; -sha3.kmac_128; -sha3.kmac_256; -sha3.sha3_224; -sha3.sha3_256; -sha3.sha3_384; -sha3.sha3_512; -sha3.shake128; -sha3.shake256; -sha3.shake_128; -sha3.shake_256; -function keccak256(data) { - return "0x" + sha3.keccak_256(arrayify(data)); -} -const version5 = "rlp/5.7.0"; -const logger23 = new Logger(version5); -function arrayifyInteger(value) { - const result = []; - while(value){ - result.unshift(value & 255); - value >>= 8; + assertError(sig.yParity == null || getNumber(sig.yParity, "sig.yParity") === result.yParity, "yParity mismatch"); + assertError(sig.yParityAndS == null || sig.yParityAndS === result.yParityAndS, "yParityAndS mismatch"); + return result; } - return result; } -function unarrayifyInteger(data, offset, length) { - let result = 0; - for(let i = 0; i < length; i++){ - result = result * 256 + data[offset + i]; +class SigningKey { + #privateKey; + constructor(privateKey){ + assertArgument(dataLength(privateKey) === 32, "invalid private key", "privateKey", "[REDACTED]"); + this.#privateKey = hexlify(privateKey); } - return result; -} -function _encode(object) { - if (Array.isArray(object)) { - let payload = []; - object.forEach(function(child) { - payload = payload.concat(_encode(child)); - }); - if (payload.length <= 55) { - payload.unshift(192 + payload.length); - return payload; - } - const length2 = arrayifyInteger(payload.length); - length2.unshift(247 + length2.length); - return length2.concat(payload); + get privateKey() { + return this.#privateKey; } - if (!isBytesLike(object)) { - logger23.throwArgumentError("RLP object must be BytesLike", "object", object); + get publicKey() { + return SigningKey.computePublicKey(this.#privateKey); } - const data = Array.prototype.slice.call(arrayify(object)); - if (data.length === 1 && data[0] <= 127) { - return data; - } else if (data.length <= 55) { - data.unshift(128 + data.length); - return data; + get compressedPublicKey() { + return SigningKey.computePublicKey(this.#privateKey, true); } - const length = arrayifyInteger(data.length); - length.unshift(183 + length.length); - return length.concat(data); -} -function encode(object) { - return hexlify(_encode(object)); -} -function _decodeChildren(data, offset, childOffset, length) { - const result = []; - while(childOffset < offset + 1 + length){ - const decoded = _decode(data, childOffset); - result.push(decoded.result); - childOffset += decoded.consumed; - if (childOffset > offset + 1 + length) { - logger23.throwError("child data too short", Logger.errors.BUFFER_OVERRUN, {}); - } + sign(digest) { + assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest); + const sig = secp256k1.sign(getBytesCopy(digest), getBytesCopy(this.#privateKey), { + lowS: true + }); + return Signature.from({ + r: toBeHex(sig.r, 32), + s: toBeHex(sig.s, 32), + v: sig.recovery ? 28 : 27 + }); } - return { - consumed: 1 + length, - result - }; -} -function _decode(data, offset) { - if (data.length === 0) { - logger23.throwError("data too short", Logger.errors.BUFFER_OVERRUN, {}); + computeSharedSecret(other) { + const pubKey = SigningKey.computePublicKey(other); + return hexlify(secp256k1.getSharedSecret(getBytesCopy(this.#privateKey), getBytes(pubKey), false)); } - if (data[offset] >= 248) { - const lengthLength = data[offset] - 247; - if (offset + 1 + lengthLength > data.length) { - logger23.throwError("data short segment too short", Logger.errors.BUFFER_OVERRUN, {}); - } - const length = unarrayifyInteger(data, offset + 1, lengthLength); - if (offset + 1 + lengthLength + length > data.length) { - logger23.throwError("data long segment too short", Logger.errors.BUFFER_OVERRUN, {}); - } - return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length); - } else if (data[offset] >= 192) { - const length = data[offset] - 192; - if (offset + 1 + length > data.length) { - logger23.throwError("data array too short", Logger.errors.BUFFER_OVERRUN, {}); - } - return _decodeChildren(data, offset, offset + 1, length); - } else if (data[offset] >= 184) { - const lengthLength = data[offset] - 183; - if (offset + 1 + lengthLength > data.length) { - logger23.throwError("data array too short", Logger.errors.BUFFER_OVERRUN, {}); - } - const length = unarrayifyInteger(data, offset + 1, lengthLength); - if (offset + 1 + lengthLength + length > data.length) { - logger23.throwError("data array too short", Logger.errors.BUFFER_OVERRUN, {}); - } - const result = hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length)); - return { - consumed: 1 + lengthLength + length, - result - }; - } else if (data[offset] >= 128) { - const length = data[offset] - 128; - if (offset + 1 + length > data.length) { - logger23.throwError("data too short", Logger.errors.BUFFER_OVERRUN, {}); + static computePublicKey(key, compressed) { + let bytes = getBytes(key, "key"); + if (bytes.length === 32) { + const pubKey = secp256k1.getPublicKey(bytes, !!compressed); + return hexlify(pubKey); } - const result = hexlify(data.slice(offset + 1, offset + 1 + length)); - return { - consumed: 1 + length, - result - }; - } - return { - consumed: 1, - result: hexlify(data[offset]) - }; -} -function decode1(data) { - const bytes2 = arrayify(data); - const decoded = _decode(bytes2, 0); - if (decoded.consumed !== bytes2.length) { - logger23.throwArgumentError("invalid rlp data", "data", data); - } - return decoded.result; -} -const mod = function() { - return { - decode: decode1, - encode: encode, - default: null - }; -}(); -const version6 = "address/5.7.0"; -const logger24 = new Logger(version6); + if (bytes.length === 64) { + const pub = new Uint8Array(65); + pub[0] = 4; + pub.set(bytes, 1); + bytes = pub; + } + const point = secp256k1.ProjectivePoint.fromHex(bytes); + return hexlify(point.toRawBytes(compressed)); + } + static recoverPublicKey(digest, signature) { + assertArgument(dataLength(digest) === 32, "invalid digest length", "digest", digest); + const sig = Signature.from(signature); + let secpSig = secp256k1.Signature.fromCompact(getBytesCopy(concat([ + sig.r, + sig.s + ]))); + secpSig = secpSig.addRecoveryBit(sig.yParity); + const pubKey = secpSig.recoverPublicKey(getBytesCopy(digest)); + assertArgument(pubKey != null, "invalid signautre for digest", "signature", signature); + return "0x" + pubKey.toHex(false); + } + static addPoints(p0, p1, compressed) { + const pub0 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p0).substring(2)); + const pub1 = secp256k1.ProjectivePoint.fromHex(SigningKey.computePublicKey(p1).substring(2)); + return "0x" + pub0.add(pub1).toHex(!!compressed); + } +} +function lock() { + computeHmac.lock(); + keccak256.lock(); + pbkdf2.lock(); + randomBytes.lock(); + ripemd160.lock(); + scrypt.lock(); + scryptSync.lock(); + sha256.lock(); + sha512.lock(); + randomBytes.lock(); +} +const BN_0$6 = BigInt(0); +const BN_36 = BigInt(36); function getChecksumAddress(address) { - if (!isHexString(address, 20)) { - logger24.throwArgumentError("invalid address", "address", address); - } address = address.toLowerCase(); const chars = address.substring(2).split(""); const expanded = new Uint8Array(40); for(let i = 0; i < 40; i++){ expanded[i] = chars[i].charCodeAt(0); } - const hashed = arrayify(keccak256(expanded)); + const hashed = getBytes(keccak256(expanded)); for(let i = 0; i < 40; i += 2){ if (hashed[i >> 1] >> 4 >= 8) { chars[i] = chars[i].toUpperCase(); @@ -5383,12 +5497,6 @@ function getChecksumAddress(address) { } return "0x" + chars.join(""); } -function log10(x) { - if (Math.log10) { - return Math.log10(x); - } - return Math.log(x) / Math.LN10; -} const ibanLookup = {}; for(let i = 0; i < 10; i++){ ibanLookup[String(i)] = String(i); @@ -5396,15 +5504,14 @@ for(let i = 0; i < 10; i++){ for(let i = 0; i < 26; i++){ ibanLookup[String.fromCharCode(65 + i)] = String(10 + i); } -const safeDigits = Math.floor(log10(9007199254740991)); function ibanChecksum(address) { address = address.toUpperCase(); address = address.substring(4) + address.substring(0, 2) + "00"; let expanded = address.split("").map((c)=>{ return ibanLookup[c]; }).join(""); - while(expanded.length >= safeDigits){ - let block = expanded.substring(0, safeDigits); + while(expanded.length >= 15){ + let block = expanded.substring(0, 15); expanded = parseInt(block, 10) % 97 + expanded.substring(block.length); } let checksum = String(98 - parseInt(expanded, 10) % 97); @@ -5413,2640 +5520,594 @@ function ibanChecksum(address) { } return checksum; } -function getAddress(address) { - let result = null; - if (typeof address !== "string") { - logger24.throwArgumentError("invalid address", "address", address); +const Base36 = function() { + const result = {}; + for(let i = 0; i < 36; i++){ + const key = "0123456789abcdefghijklmnopqrstuvwxyz"[i]; + result[key] = BigInt(i); + } + return result; +}(); +function fromBase36(value) { + value = value.toLowerCase(); + let result = BN_0$6; + for(let i = 0; i < value.length; i++){ + result = result * BN_36 + Base36[value[i]]; } + return result; +} +function getAddress(address) { + assertArgument(typeof address === "string", "invalid address", "address", address); if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) { - if (address.substring(0, 2) !== "0x") { + if (!address.startsWith("0x")) { address = "0x" + address; } - result = getChecksumAddress(address); - if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) { - logger24.throwArgumentError("bad address checksum", "address", address); - } - } else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { - if (address.substring(2, 4) !== ibanChecksum(address)) { - logger24.throwArgumentError("bad icap checksum", "address", address); - } - result = _base36To16(address.substring(4)); + const result = getChecksumAddress(address); + assertArgument(!address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) || result === address, "bad address checksum", "address", address); + return result; + } + if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) { + assertArgument(address.substring(2, 4) === ibanChecksum(address), "bad icap checksum", "address", address); + let result = fromBase36(address.substring(4)).toString(16); while(result.length < 40){ result = "0" + result; } - result = getChecksumAddress("0x" + result); - } else { - logger24.throwArgumentError("invalid address", "address", address); + return getChecksumAddress("0x" + result); } - return result; -} -function isAddress(address) { - try { - getAddress(address); - return true; - } catch (error) {} - return false; + assertArgument(false, "invalid address", "address", address); } function getIcapAddress(address) { - let base36 = _base16To36(getAddress(address).substring(2)).toUpperCase(); + let base36 = BigInt(getAddress(address)).toString(36).toUpperCase(); while(base36.length < 30){ base36 = "0" + base36; } return "XE" + ibanChecksum("XE00" + base36) + base36; } -function getContractAddress(transaction) { - let from = null; - try { - from = getAddress(transaction.from); - } catch (error) { - logger24.throwArgumentError("missing from address", "transaction", transaction); +function getCreateAddress(tx) { + const from = getAddress(tx.from); + const nonce = getBigInt(tx.nonce, "tx.nonce"); + let nonceHex = nonce.toString(16); + if (nonceHex === "0") { + nonceHex = "0x"; + } else if (nonceHex.length % 2) { + nonceHex = "0x0" + nonceHex; + } else { + nonceHex = "0x" + nonceHex; } - const nonce = stripZeros(arrayify(BigNumber.from(transaction.nonce).toHexString())); - return getAddress(hexDataSlice(keccak256(encode([ + return getAddress(dataSlice(keccak256(encodeRlp([ from, - nonce + nonceHex ])), 12)); } -function getCreate2Address(from, salt, initCodeHash) { - if (hexDataLength(salt) !== 32) { - logger24.throwArgumentError("salt must be 32 bytes", "salt", salt); - } - if (hexDataLength(initCodeHash) !== 32) { - logger24.throwArgumentError("initCodeHash must be 32 bytes", "initCodeHash", initCodeHash); - } - return getAddress(hexDataSlice(keccak256(concat([ +function getCreate2Address(_from, _salt, _initCodeHash) { + const from = getAddress(_from); + const salt = getBytes(_salt, "salt"); + const initCodeHash = getBytes(_initCodeHash, "initCodeHash"); + assertArgument(salt.length === 32, "salt must be 32 bytes", "salt", _salt); + assertArgument(initCodeHash.length === 32, "initCodeHash must be 32 bytes", "initCodeHash", _initCodeHash); + return getAddress(dataSlice(keccak256(concat([ "0xff", - getAddress(from), + from, salt, initCodeHash ])), 12)); } -const AddressZero = "0x0000000000000000000000000000000000000000"; -const NegativeOne1 = BigNumber.from(-1); -const Zero1 = BigNumber.from(0); -const One = BigNumber.from(1); -const Two = BigNumber.from(2); -const WeiPerEther = BigNumber.from("1000000000000000000"); -const MaxUint256 = BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -const MinInt256 = BigNumber.from("-0x8000000000000000000000000000000000000000000000000000000000000000"); -const MaxInt256 = BigNumber.from("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -const HashZero = "0x0000000000000000000000000000000000000000000000000000000000000000"; -const EtherSymbol = "\u039E"; -const mod1 = function() { - return { - AddressZero: AddressZero, - EtherSymbol: EtherSymbol, - HashZero: HashZero, - MaxInt256: MaxInt256, - MaxUint256: MaxUint256, - MinInt256: MinInt256, - NegativeOne: NegativeOne1, - One: One, - Two: Two, - WeiPerEther: WeiPerEther, - Zero: Zero1, - default: null - }; -}(); -const version7 = "strings/5.7.0"; -const logger25 = new Logger(version7); -var UnicodeNormalizationForm; -(function(UnicodeNormalizationForm2) { - UnicodeNormalizationForm2["current"] = ""; - UnicodeNormalizationForm2["NFC"] = "NFC"; - UnicodeNormalizationForm2["NFD"] = "NFD"; - UnicodeNormalizationForm2["NFKC"] = "NFKC"; - UnicodeNormalizationForm2["NFKD"] = "NFKD"; -})(UnicodeNormalizationForm || (UnicodeNormalizationForm = {})); -var Utf8ErrorReason; -(function(Utf8ErrorReason2) { - Utf8ErrorReason2["UNEXPECTED_CONTINUE"] = "unexpected continuation byte"; - Utf8ErrorReason2["BAD_PREFIX"] = "bad codepoint prefix"; - Utf8ErrorReason2["OVERRUN"] = "string overrun"; - Utf8ErrorReason2["MISSING_CONTINUE"] = "missing continuation byte"; - Utf8ErrorReason2["OUT_OF_RANGE"] = "out of UTF-8 range"; - Utf8ErrorReason2["UTF16_SURROGATE"] = "UTF-16 surrogate"; - Utf8ErrorReason2["OVERLONG"] = "overlong representation"; -})(Utf8ErrorReason || (Utf8ErrorReason = {})); -function errorFunc(reason, offset, bytes3, output, badCodepoint) { - return logger25.throwArgumentError(`invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes3); -} -function ignoreFunc(reason, offset, bytes3, output, badCodepoint) { - if (reason === Utf8ErrorReason.BAD_PREFIX || reason === Utf8ErrorReason.UNEXPECTED_CONTINUE) { - let i = 0; - for(let o = offset + 1; o < bytes3.length; o++){ - if (bytes3[o] >> 6 !== 2) { - break; - } - i++; +function isAddressable(value) { + return value && typeof value.getAddress === "function"; +} +function isAddress(value) { + try { + getAddress(value); + return true; + } catch (error) {} + return false; +} +async function checkAddress(target, promise) { + const result = await promise; + if (result == null || result === "0x0000000000000000000000000000000000000000") { + assert1(typeof target !== "string", "unconfigured name", "UNCONFIGURED_NAME", { + value: target + }); + assertArgument(false, "invalid AddressLike value; did not resolve to a value address", "target", target); + } + return getAddress(result); +} +function resolveAddress(target, resolver) { + if (typeof target === "string") { + if (target.match(/^0x[0-9a-f]{40}$/i)) { + return getAddress(target); } - return i; + assert1(resolver != null, "ENS resolution requires a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName" + }); + return checkAddress(target, resolver.resolveName(target)); + } else if (isAddressable(target)) { + return checkAddress(target, target.getAddress()); + } else if (target && typeof target.then === "function") { + return checkAddress(target, target); + } + assertArgument(false, "unsupported addressable value", "target", target); +} +const _gaurd = {}; +function n(value, width) { + let signed = false; + if (width < 0) { + signed = true; + width *= -1; + } + return new Typed(_gaurd, `${signed ? "" : "u"}int${width}`, value, { + signed: signed, + width: width + }); +} +function b(value, size) { + return new Typed(_gaurd, `bytes${size ? size : ""}`, value, { + size: size + }); +} +const _typedSymbol = Symbol.for("_ethers_typed"); +class Typed { + type; + value; + #options; + _typedSymbol; + constructor(gaurd, type, value, options){ + if (options == null) { + options = null; + } + assertPrivate(_gaurd, gaurd, "Typed"); + defineProperties(this, { + _typedSymbol: _typedSymbol, + type: type, + value: value + }); + this.#options = options; + this.format(); } - if (reason === Utf8ErrorReason.OVERRUN) { - return bytes3.length - offset - 1; + format() { + if (this.type === "array") { + throw new Error(""); + } else if (this.type === "dynamicArray") { + throw new Error(""); + } else if (this.type === "tuple") { + return `tuple(${this.value.map((v)=>v.format()).join(",")})`; + } + return this.type; } - return 0; -} -function replaceFunc(reason, offset, bytes3, output, badCodepoint) { - if (reason === Utf8ErrorReason.OVERLONG) { - output.push(badCodepoint); + defaultValue() { return 0; } - output.push(65533); - return ignoreFunc(reason, offset, bytes3); -} -const Utf8ErrorFuncs = Object.freeze({ - error: errorFunc, - ignore: ignoreFunc, - replace: replaceFunc -}); -function getUtf8CodePoints(bytes3, onError) { - if (onError == null) { - onError = Utf8ErrorFuncs.error; + minValue() { + return 0; } - bytes3 = arrayify(bytes3); - const result = []; - let i = 0; - while(i < bytes3.length){ - const c = bytes3[i++]; - if (c >> 7 === 0) { - result.push(c); - continue; + maxValue() { + return 0; + } + isBigInt() { + return !!this.type.match(/^u?int[0-9]+$/); + } + isData() { + return this.type.startsWith("bytes"); + } + isString() { + return this.type === "string"; + } + get tupleName() { + if (this.type !== "tuple") { + throw TypeError("not a tuple"); } - let extraLength = null; - let overlongMask = null; - if ((c & 224) === 192) { - extraLength = 1; - overlongMask = 127; - } else if ((c & 240) === 224) { - extraLength = 2; - overlongMask = 2047; - } else if ((c & 248) === 240) { - extraLength = 3; - overlongMask = 65535; - } else { - if ((c & 192) === 128) { - i += onError(Utf8ErrorReason.UNEXPECTED_CONTINUE, i - 1, bytes3, result); - } else { - i += onError(Utf8ErrorReason.BAD_PREFIX, i - 1, bytes3, result); - } - continue; - } - if (i - 1 + extraLength >= bytes3.length) { - i += onError(Utf8ErrorReason.OVERRUN, i - 1, bytes3, result); - continue; - } - let res = c & (1 << 8 - extraLength - 1) - 1; - for(let j = 0; j < extraLength; j++){ - let nextChar = bytes3[i]; - if ((nextChar & 192) != 128) { - i += onError(Utf8ErrorReason.MISSING_CONTINUE, i, bytes3, result); - res = null; - break; - } - res = res << 6 | nextChar & 63; - i++; - } - if (res === null) { - continue; - } - if (res > 1114111) { - i += onError(Utf8ErrorReason.OUT_OF_RANGE, i - 1 - extraLength, bytes3, result, res); - continue; + return this.#options; + } + get arrayLength() { + if (this.type !== "array") { + throw TypeError("not an array"); } - if (res >= 55296 && res <= 57343) { - i += onError(Utf8ErrorReason.UTF16_SURROGATE, i - 1 - extraLength, bytes3, result, res); - continue; + if (this.#options === true) { + return -1; } - if (res <= overlongMask) { - i += onError(Utf8ErrorReason.OVERLONG, i - 1 - extraLength, bytes3, result, res); - continue; + if (this.#options === false) { + return this.value.length; } - result.push(res); + return null; } - return result; -} -function toUtf8Bytes(str, form = UnicodeNormalizationForm.current) { - if (form != UnicodeNormalizationForm.current) { - logger25.checkNormalize(); - str = str.normalize(form); + static from(type, value) { + return new Typed(_gaurd, type, value); } - let result = []; - for(let i = 0; i < str.length; i++){ - const c = str.charCodeAt(i); - if (c < 128) { - result.push(c); - } else if (c < 2048) { - result.push(c >> 6 | 192); - result.push(c & 63 | 128); - } else if ((c & 64512) == 55296) { - i++; - const c2 = str.charCodeAt(i); - if (i >= str.length || (c2 & 64512) !== 56320) { - throw new Error("invalid utf-8 string"); - } - const pair = 65536 + ((c & 1023) << 10) + (c2 & 1023); - result.push(pair >> 18 | 240); - result.push(pair >> 12 & 63 | 128); - result.push(pair >> 6 & 63 | 128); - result.push(pair & 63 | 128); - } else { - result.push(c >> 12 | 224); - result.push(c >> 6 & 63 | 128); - result.push(c & 63 | 128); - } + static uint8(v) { + return n(v, 8); } - return arrayify(result); -} -function escapeChar(value) { - const hex = "0000" + value.toString(16); - return "\\u" + hex.substring(hex.length - 4); -} -function _toEscapedUtf8String(bytes3, onError) { - return '"' + getUtf8CodePoints(bytes3, onError).map((codePoint)=>{ - if (codePoint < 256) { - switch(codePoint){ - case 8: - return "\\b"; - case 9: - return "\\t"; - case 10: - return "\\n"; - case 13: - return "\\r"; - case 34: - return '\\"'; - case 92: - return "\\\\"; - } - if (codePoint >= 32 && codePoint < 127) { - return String.fromCharCode(codePoint); - } - } - if (codePoint <= 65535) { - return escapeChar(codePoint); - } - codePoint -= 65536; - return escapeChar((codePoint >> 10 & 1023) + 55296) + escapeChar((codePoint & 1023) + 56320); - }).join("") + '"'; -} -function _toUtf8String(codePoints) { - return codePoints.map((codePoint)=>{ - if (codePoint <= 65535) { - return String.fromCharCode(codePoint); - } - codePoint -= 65536; - return String.fromCharCode((codePoint >> 10 & 1023) + 55296, (codePoint & 1023) + 56320); - }).join(""); -} -function toUtf8String(bytes3, onError) { - return _toUtf8String(getUtf8CodePoints(bytes3, onError)); -} -function toUtf8CodePoints(str, form = UnicodeNormalizationForm.current) { - return getUtf8CodePoints(toUtf8Bytes(str, form)); -} -function formatBytes32String(text) { - const bytes3 = toUtf8Bytes(text); - if (bytes3.length > 31) { - throw new Error("bytes32 string must be less than 32 bytes"); + static uint16(v) { + return n(v, 16); } - return hexlify(concat([ - bytes3, - HashZero - ]).slice(0, 32)); -} -function parseBytes32String(bytes3) { - const data = arrayify(bytes3); - if (data.length !== 32) { - throw new Error("invalid bytes32 - not 32 bytes long"); + static uint24(v) { + return n(v, 24); } - if (data[31] !== 0) { - throw new Error("invalid bytes32 string - no null terminator"); + static uint32(v) { + return n(v, 32); } - let length = 31; - while(data[length - 1] === 0){ - length--; + static uint40(v) { + return n(v, 40); } - return toUtf8String(data.slice(0, length)); -} -function bytes2(data) { - if (data.length % 4 !== 0) { - throw new Error("bad data"); + static uint48(v) { + return n(v, 48); } - let result = []; - for(let i = 0; i < data.length; i += 4){ - result.push(parseInt(data.substring(i, i + 4), 16)); + static uint56(v) { + return n(v, 56); } - return result; -} -function createTable(data, func) { - if (!func) { - func = function(value) { - return [ - parseInt(value, 16) - ]; - }; + static uint64(v) { + return n(v, 64); } - let lo = 0; - let result = {}; - data.split(",").forEach((pair)=>{ - let comps = pair.split(":"); - lo += parseInt(comps[0], 16); - result[lo] = func(comps[1]); - }); - return result; -} -function createRangeTable(data) { - let hi = 0; - return data.split(",").map((v)=>{ - let comps = v.split("-"); - if (comps.length === 1) { - comps[1] = "0"; - } else if (comps[1] === "") { - comps[1] = "1"; - } - let lo = hi + parseInt(comps[0], 16); - hi = parseInt(comps[1], 16); - return { - l: lo, - h: hi - }; - }); -} -function matchMap(value, ranges) { - let lo = 0; - for(let i = 0; i < ranges.length; i++){ - let range = ranges[i]; - lo += range.l; - if (value >= lo && value <= lo + range.h && (value - lo) % (range.d || 1) === 0) { - if (range.e && range.e.indexOf(value - lo) !== -1) { - continue; - } - return range; - } + static uint72(v) { + return n(v, 72); } - return null; -} -const Table_A_1_ranges = createRangeTable("221,13-1b,5f-,40-10,51-f,11-3,3-3,2-2,2-4,8,2,15,2d,28-8,88,48,27-,3-5,11-20,27-,8,28,3-5,12,18,b-a,1c-4,6-16,2-d,2-2,2,1b-4,17-9,8f-,10,f,1f-2,1c-34,33-14e,4,36-,13-,6-2,1a-f,4,9-,3-,17,8,2-2,5-,2,8-,3-,4-8,2-3,3,6-,16-6,2-,7-3,3-,17,8,3,3,3-,2,6-3,3-,4-a,5,2-6,10-b,4,8,2,4,17,8,3,6-,b,4,4-,2-e,2-4,b-10,4,9-,3-,17,8,3-,5-,9-2,3-,4-7,3-3,3,4-3,c-10,3,7-2,4,5-2,3,2,3-2,3-2,4-2,9,4-3,6-2,4,5-8,2-e,d-d,4,9,4,18,b,6-3,8,4,5-6,3-8,3-3,b-11,3,9,4,18,b,6-3,8,4,5-6,3-6,2,3-3,b-11,3,9,4,18,11-3,7-,4,5-8,2-7,3-3,b-11,3,13-2,19,a,2-,8-2,2-3,7,2,9-11,4-b,3b-3,1e-24,3,2-,3,2-,2-5,5,8,4,2,2-,3,e,4-,6,2,7-,b-,3-21,49,23-5,1c-3,9,25,10-,2-2f,23,6,3,8-2,5-5,1b-45,27-9,2a-,2-3,5b-4,45-4,53-5,8,40,2,5-,8,2,5-,28,2,5-,20,2,5-,8,2,5-,8,8,18,20,2,5-,8,28,14-5,1d-22,56-b,277-8,1e-2,52-e,e,8-a,18-8,15-b,e,4,3-b,5e-2,b-15,10,b-5,59-7,2b-555,9d-3,5b-5,17-,7-,27-,7-,9,2,2,2,20-,36,10,f-,7,14-,4,a,54-3,2-6,6-5,9-,1c-10,13-1d,1c-14,3c-,10-6,32-b,240-30,28-18,c-14,a0,115-,3,66-,b-76,5,5-,1d,24,2,5-2,2,8-,35-2,19,f-10,1d-3,311-37f,1b,5a-b,d7-19,d-3,41,57-,68-4,29-3,5f,29-37,2e-2,25-c,2c-2,4e-3,30,78-3,64-,20,19b7-49,51a7-59,48e-2,38-738,2ba5-5b,222f-,3c-94,8-b,6-4,1b,6,2,3,3,6d-20,16e-f,41-,37-7,2e-2,11-f,5-b,18-,b,14,5-3,6,88-,2,bf-2,7-,7-,7-,4-2,8,8-9,8-2ff,20,5-b,1c-b4,27-,27-cbb1,f7-9,28-2,b5-221,56,48,3-,2-,3-,5,d,2,5,3,42,5-,9,8,1d,5,6,2-2,8,153-3,123-3,33-27fd,a6da-5128,21f-5df,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3-fffd,3,2-1d,61-ff7d"); -const Table_B_1_flags = "ad,34f,1806,180b,180c,180d,200b,200c,200d,2060,feff".split(",").map((v)=>parseInt(v, 16)); -const Table_B_2_ranges = [ - { - h: 25, - s: 32, - l: 65 - }, - { - h: 30, - s: 32, - e: [ - 23 - ], - l: 127 - }, - { - h: 54, - s: 1, - e: [ - 48 - ], - l: 64, - d: 2 - }, - { - h: 14, - s: 1, - l: 57, - d: 2 - }, - { - h: 44, - s: 1, - l: 17, - d: 2 - }, - { - h: 10, - s: 1, - e: [ - 2, - 6, - 8 - ], - l: 61, - d: 2 - }, - { - h: 16, - s: 1, - l: 68, - d: 2 - }, - { - h: 84, - s: 1, - e: [ - 18, - 24, - 66 - ], - l: 19, - d: 2 - }, - { - h: 26, - s: 32, - e: [ - 17 - ], - l: 435 - }, - { - h: 22, - s: 1, - l: 71, - d: 2 - }, - { - h: 15, - s: 80, - l: 40 - }, - { - h: 31, - s: 32, - l: 16 - }, - { - h: 32, - s: 1, - l: 80, - d: 2 - }, - { - h: 52, - s: 1, - l: 42, - d: 2 - }, - { - h: 12, - s: 1, - l: 55, - d: 2 - }, - { - h: 40, - s: 1, - e: [ - 38 - ], - l: 15, - d: 2 - }, - { - h: 14, - s: 1, - l: 48, - d: 2 - }, - { - h: 37, - s: 48, - l: 49 - }, - { - h: 148, - s: 1, - l: 6351, - d: 2 - }, - { - h: 88, - s: 1, - l: 160, - d: 2 - }, - { - h: 15, - s: 16, - l: 704 - }, - { - h: 25, - s: 26, - l: 854 - }, - { - h: 25, - s: 32, - l: 55915 - }, - { - h: 37, - s: 40, - l: 1247 - }, - { - h: 25, - s: -119711, - l: 53248 - }, - { - h: 25, - s: -119763, - l: 52 - }, - { - h: 25, - s: -119815, - l: 52 - }, - { - h: 25, - s: -119867, - e: [ - 1, - 4, - 5, - 7, - 8, - 11, - 12, - 17 - ], - l: 52 - }, - { - h: 25, - s: -119919, - l: 52 - }, - { - h: 24, - s: -119971, - e: [ - 2, - 7, - 8, - 17 - ], - l: 52 - }, - { - h: 24, - s: -120023, - e: [ - 2, - 7, - 13, - 15, - 16, - 17 - ], - l: 52 - }, - { - h: 25, - s: -120075, - l: 52 - }, - { - h: 25, - s: -120127, - l: 52 - }, - { - h: 25, - s: -120179, - l: 52 - }, - { - h: 25, - s: -120231, - l: 52 - }, - { - h: 25, - s: -120283, - l: 52 - }, - { - h: 25, - s: -120335, - l: 52 - }, - { - h: 24, - s: -119543, - e: [ - 17 - ], - l: 56 - }, - { - h: 24, - s: -119601, - e: [ - 17 - ], - l: 58 - }, - { - h: 24, - s: -119659, - e: [ - 17 - ], - l: 58 - }, - { - h: 24, - s: -119717, - e: [ - 17 - ], - l: 58 - }, - { - h: 24, - s: -119775, - e: [ - 17 - ], - l: 58 + static uint80(v) { + return n(v, 80); } -]; -const Table_B_2_lut_abs = createTable("b5:3bc,c3:ff,7:73,2:253,5:254,3:256,1:257,5:259,1:25b,3:260,1:263,2:269,1:268,5:26f,1:272,2:275,7:280,3:283,5:288,3:28a,1:28b,5:292,3f:195,1:1bf,29:19e,125:3b9,8b:3b2,1:3b8,1:3c5,3:3c6,1:3c0,1a:3ba,1:3c1,1:3c3,2:3b8,1:3b5,1bc9:3b9,1c:1f76,1:1f77,f:1f7a,1:1f7b,d:1f78,1:1f79,1:1f7c,1:1f7d,107:63,5:25b,4:68,1:68,1:68,3:69,1:69,1:6c,3:6e,4:70,1:71,1:72,1:72,1:72,7:7a,2:3c9,2:7a,2:6b,1:e5,1:62,1:63,3:65,1:66,2:6d,b:3b3,1:3c0,6:64,1b574:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3,20:3b8,1a:3c3"); -const Table_B_2_lut_rel = createTable("179:1,2:1,2:1,5:1,2:1,a:4f,a:1,8:1,2:1,2:1,3:1,5:1,3:1,4:1,2:1,3:1,4:1,8:2,1:1,2:2,1:1,2:2,27:2,195:26,2:25,1:25,1:25,2:40,2:3f,1:3f,33:1,11:-6,1:-9,1ac7:-3a,6d:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,b:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,c:-8,2:-8,2:-8,2:-8,9:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,1:-8,49:-8,1:-8,1:-4a,1:-4a,d:-56,1:-56,1:-56,1:-56,d:-8,1:-8,f:-8,1:-8,3:-7"); -const Table_B_2_complex = createTable("df:00730073,51:00690307,19:02BC006E,a7:006A030C,18a:002003B9,16:03B903080301,20:03C503080301,1d7:05650582,190f:00680331,1:00740308,1:0077030A,1:0079030A,1:006102BE,b6:03C50313,2:03C503130300,2:03C503130301,2:03C503130342,2a:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F0003B9,1:1F0103B9,1:1F0203B9,1:1F0303B9,1:1F0403B9,1:1F0503B9,1:1F0603B9,1:1F0703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F2003B9,1:1F2103B9,1:1F2203B9,1:1F2303B9,1:1F2403B9,1:1F2503B9,1:1F2603B9,1:1F2703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,1:1F6003B9,1:1F6103B9,1:1F6203B9,1:1F6303B9,1:1F6403B9,1:1F6503B9,1:1F6603B9,1:1F6703B9,3:1F7003B9,1:03B103B9,1:03AC03B9,2:03B10342,1:03B1034203B9,5:03B103B9,6:1F7403B9,1:03B703B9,1:03AE03B9,2:03B70342,1:03B7034203B9,5:03B703B9,6:03B903080300,1:03B903080301,3:03B90342,1:03B903080342,b:03C503080300,1:03C503080301,1:03C10313,2:03C50342,1:03C503080342,b:1F7C03B9,1:03C903B9,1:03CE03B9,2:03C90342,1:03C9034203B9,5:03C903B9,ac:00720073,5b:00B00063,6:00B00066,d:006E006F,a:0073006D,1:00740065006C,1:0074006D,124f:006800700061,2:00610075,2:006F0076,b:00700061,1:006E0061,1:03BC0061,1:006D0061,1:006B0061,1:006B0062,1:006D0062,1:00670062,3:00700066,1:006E0066,1:03BC0066,4:0068007A,1:006B0068007A,1:006D0068007A,1:00670068007A,1:00740068007A,15:00700061,1:006B00700061,1:006D00700061,1:006700700061,8:00700076,1:006E0076,1:03BC0076,1:006D0076,1:006B0076,1:006D0076,1:00700077,1:006E0077,1:03BC0077,1:006D0077,1:006B0077,1:006D0077,1:006B03C9,1:006D03C9,2:00620071,3:00632215006B0067,1:0063006F002E,1:00640062,1:00670079,2:00680070,2:006B006B,1:006B006D,9:00700068,2:00700070006D,1:00700072,2:00730076,1:00770062,c723:00660066,1:00660069,1:0066006C,1:006600660069,1:00660066006C,1:00730074,1:00730074,d:05740576,1:05740565,1:0574056B,1:057E0576,1:0574056D", bytes2); -const Table_C_ranges = createRangeTable("80-20,2a0-,39c,32,f71,18e,7f2-f,19-7,30-4,7-5,f81-b,5,a800-20ff,4d1-1f,110,fa-6,d174-7,2e84-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,ffff-,2,1f-5f,ff7f-20001"); -function flatten(values) { - return values.reduce((accum, value)=>{ - value.forEach((value2)=>{ - accum.push(value2); - }); - return accum; - }, []); -} -function _nameprepTableA1(codepoint) { - return !!matchMap(codepoint, Table_A_1_ranges); -} -function _nameprepTableB2(codepoint) { - let range = matchMap(codepoint, Table_B_2_ranges); - if (range) { - return [ - codepoint + range.s - ]; + static uint88(v) { + return n(v, 88); } - let codes = Table_B_2_lut_abs[codepoint]; - if (codes) { - return codes; + static uint96(v) { + return n(v, 96); } - let shift = Table_B_2_lut_rel[codepoint]; - if (shift) { - return [ - codepoint + shift[0] - ]; + static uint104(v) { + return n(v, 104); } - let complex = Table_B_2_complex[codepoint]; - if (complex) { - return complex; + static uint112(v) { + return n(v, 112); } - return null; -} -function _nameprepTableC(codepoint) { - return !!matchMap(codepoint, Table_C_ranges); -} -function nameprep(value) { - if (value.match(/^[a-z0-9-]*$/i) && value.length <= 59) { - return value.toLowerCase(); + static uint120(v) { + return n(v, 120); } - let codes = toUtf8CodePoints(value); - codes = flatten(codes.map((code)=>{ - if (Table_B_1_flags.indexOf(code) >= 0) { - return []; - } - if (code >= 65024 && code <= 65039) { - return []; - } - let codesTableB2 = _nameprepTableB2(code); - if (codesTableB2) { - return codesTableB2; - } - return [ - code - ]; - })); - codes = toUtf8CodePoints(_toUtf8String(codes), UnicodeNormalizationForm.NFKC); - codes.forEach((code)=>{ - if (_nameprepTableC(code)) { - throw new Error("STRINGPREP_CONTAINS_PROHIBITED"); - } - }); - codes.forEach((code)=>{ - if (_nameprepTableA1(code)) { - throw new Error("STRINGPREP_CONTAINS_UNASSIGNED"); - } - }); - let name = _toUtf8String(codes); - if (name.substring(0, 1) === "-" || name.substring(2, 4) === "--" || name.substring(name.length - 1) === "-") { - throw new Error("invalid hyphen"); + static uint128(v) { + return n(v, 128); } - return name; -} -function decode2(textData) { - textData = atob(textData); - const data = []; - for(let i = 0; i < textData.length; i++){ - data.push(textData.charCodeAt(i)); + static uint136(v) { + return n(v, 136); } - return arrayify(data); -} -function encode1(data) { - data = arrayify(data); - let textData = ""; - for(let i = 0; i < data.length; i++){ - textData += String.fromCharCode(data[i]); + static uint144(v) { + return n(v, 144); } - return btoa(textData); -} -const mod2 = function() { - return { - decode: decode2, - encode: encode1, - default: null - }; -}(); -function id(text) { - return keccak256(toUtf8Bytes(text)); -} -const version8 = "hash/5.7.0"; -function flat(array, depth) { - if (depth == null) { - depth = 1; + static uint152(v) { + return n(v, 152); } - const result = []; - const forEach = result.forEach; - const flatDeep = function(arr, depth2) { - forEach.call(arr, function(val) { - if (depth2 > 0 && Array.isArray(val)) { - flatDeep(val, depth2 - 1); - } else { - result.push(val); - } - }); - }; - flatDeep(array, depth); - return result; -} -function fromEntries(array) { - const result = {}; - for(let i = 0; i < array.length; i++){ - const value = array[i]; - result[value[0]] = value[1]; + static uint160(v) { + return n(v, 160); } - return result; -} -function decode_arithmetic(bytes2) { - let pos = 0; - function u16() { - return bytes2[pos++] << 8 | bytes2[pos++]; + static uint168(v) { + return n(v, 168); } - let symbol_count = u16(); - let total = 1; - let acc = [ - 0, - 1 - ]; - for(let i = 1; i < symbol_count; i++){ - acc.push(total += u16()); + static uint176(v) { + return n(v, 176); } - let skip = u16(); - let pos_payload = pos; - pos += skip; - let read_width = 0; - let read_buffer = 0; - function read_bit() { - if (read_width == 0) { - read_buffer = read_buffer << 8 | bytes2[pos++]; - read_width = 8; - } - return read_buffer >> --read_width & 1; + static uint184(v) { + return n(v, 184); } - const FULL = Math.pow(2, 31); - const HALF = FULL >>> 1; - const QRTR = HALF >> 1; - const MASK = FULL - 1; - let register = 0; - for(let i = 0; i < 31; i++)register = register << 1 | read_bit(); - let symbols = []; - let low = 0; - let range = FULL; - while(true){ - let value = Math.floor(((register - low + 1) * total - 1) / range); - let start = 0; - let end = symbol_count; - while(end - start > 1){ - let mid = start + end >>> 1; - if (value < acc[mid]) { - end = mid; - } else { - start = mid; - } - } - if (start == 0) break; - symbols.push(start); - let a = low + Math.floor(range * acc[start] / total); - let b = low + Math.floor(range * acc[start + 1] / total) - 1; - while(((a ^ b) & HALF) == 0){ - register = register << 1 & MASK | read_bit(); - a = a << 1 & MASK; - b = b << 1 & MASK | 1; - } - while(a & ~b & QRTR){ - register = register & HALF | register << 1 & MASK >>> 1 | read_bit(); - a = a << 1 ^ HALF; - b = (b ^ HALF) << 1 | HALF | 1; - } - low = a; - range = 1 + b - a; + static uint192(v) { + return n(v, 192); } - let offset = symbol_count - 4; - return symbols.map((x)=>{ - switch(x - offset){ - case 3: - return offset + 65792 + (bytes2[pos_payload++] << 16 | bytes2[pos_payload++] << 8 | bytes2[pos_payload++]); - case 2: - return offset + 256 + (bytes2[pos_payload++] << 8 | bytes2[pos_payload++]); - case 1: - return offset + bytes2[pos_payload++]; - default: - return x - 1; - } - }); -} -function read_payload(v) { - let pos = 0; - return ()=>v[pos++]; -} -function read_compressed_payload(bytes2) { - return read_payload(decode_arithmetic(bytes2)); -} -function signed(i) { - return i & 1 ? ~i >> 1 : i >> 1; -} -function read_counts(n, next) { - let v = Array(n); - for(let i = 0; i < n; i++)v[i] = 1 + next(); - return v; -} -function read_ascending(n, next) { - let v = Array(n); - for(let i = 0, x = -1; i < n; i++)v[i] = x += 1 + next(); - return v; -} -function read_deltas(n, next) { - let v = Array(n); - for(let i = 0, x = 0; i < n; i++)v[i] = x += signed(next()); - return v; -} -function read_member_array(next, lookup) { - let v = read_ascending(next(), next); - let n = next(); - let vX = read_ascending(n, next); - let vN = read_counts(n, next); - for(let i = 0; i < n; i++){ - for(let j = 0; j < vN[i]; j++){ - v.push(vX[i] + j); - } + static uint200(v) { + return n(v, 200); } - return lookup ? v.map((x)=>lookup[x]) : v; -} -function read_mapped_map(next) { - let ret = []; - while(true){ - let w = next(); - if (w == 0) break; - ret.push(read_linear_table(w, next)); + static uint208(v) { + return n(v, 208); } - while(true){ - let w = next() - 1; - if (w < 0) break; - ret.push(read_replacement_table(w, next)); + static uint216(v) { + return n(v, 216); } - return fromEntries(flat(ret)); -} -function read_zero_terminated_array(next) { - let v = []; - while(true){ - let i = next(); - if (i == 0) break; - v.push(i); + static uint224(v) { + return n(v, 224); } - return v; -} -function read_transposed(n, w, next) { - let m = Array(n).fill(void 0).map(()=>[]); - for(let i = 0; i < w; i++){ - read_deltas(n, next).forEach((x, j)=>m[j].push(x)); + static uint232(v) { + return n(v, 232); } - return m; -} -function read_linear_table(w, next) { - let dx = 1 + next(); - let dy = next(); - let vN = read_zero_terminated_array(next); - let m = read_transposed(vN.length, 1 + w, next); - return flat(m.map((v, i)=>{ - const x = v[0], ys = v.slice(1); - return Array(vN[i]).fill(void 0).map((_, j)=>{ - let j_dy = j * dy; - return [ - x + j * dx, - ys.map((y)=>y + j_dy) - ]; - }); - })); -} -function read_replacement_table(w, next) { - let n = 1 + next(); - let m = read_transposed(n, 1 + w, next); - return m.map((v)=>[ - v[0], - v.slice(1) - ]); -} -function read_emoji_trie(next) { - let sorted = read_member_array(next).sort((a, b)=>a - b); - return read(); - function read() { - let branches = []; - while(true){ - let keys = read_member_array(next, sorted); - if (keys.length == 0) break; - branches.push({ - set: new Set(keys), - node: read() - }); - } - branches.sort((a, b)=>b.set.size - a.set.size); - let temp = next(); - let valid = temp % 3; - temp = temp / 3 | 0; - let fe0f = !!(temp & 1); - temp >>= 1; - let save = temp == 1; - let check = temp == 2; - return { - branches, - valid, - fe0f, - save, - check - }; + static uint240(v) { + return n(v, 240); } -} -function getData() { - return read_compressed_payload(decode2("AEQF2AO2DEsA2wIrAGsBRABxAN8AZwCcAEwAqgA0AGwAUgByADcATAAVAFYAIQAyACEAKAAYAFgAGwAjABQAMAAmADIAFAAfABQAKwATACoADgAbAA8AHQAYABoAGQAxADgALAAoADwAEwA9ABMAGgARAA4ADwAWABMAFgAIAA8AHgQXBYMA5BHJAS8JtAYoAe4AExozi0UAH21tAaMnBT8CrnIyhrMDhRgDygIBUAEHcoFHUPe8AXBjAewCjgDQR8IICIcEcQLwATXCDgzvHwBmBoHNAqsBdBcUAykgDhAMShskMgo8AY8jqAQfAUAfHw8BDw87MioGlCIPBwZCa4ELatMAAMspJVgsDl8AIhckSg8XAHdvTwBcIQEiDT4OPhUqbyECAEoAS34Aej8Ybx83JgT/Xw8gHxZ/7w8RICxPHA9vBw+Pfw8PHwAPFv+fAsAvCc8vEr8ivwD/EQ8Bol8OEBa/A78hrwAPCU8vESNvvwWfHwNfAVoDHr+ZAAED34YaAdJPAK7PLwSEgDLHAGo1Pz8Pvx9fUwMrpb8O/58VTzAPIBoXIyQJNF8hpwIVAT8YGAUADDNBaX3RAMomJCg9EhUeA29MABsZBTMNJipjOhc19gcIDR8bBwQHEggCWi6DIgLuAQYA+BAFCha3A5XiAEsqM7UFFgFLhAMjFTMYE1Klnw74nRVBG/ASCm0BYRN/BrsU3VoWy+S0vV8LQx+vN8gF2AC2AK5EAWwApgYDKmAAroQ0NDQ0AT+OCg7wAAIHRAbpNgVcBV0APTA5BfbPFgMLzcYL/QqqA82eBALKCjQCjqYCht0/k2+OAsXQAoP3ASTKDgDw6ACKAUYCMpIKJpRaAE4A5womABzZvs0REEKiACIQAd5QdAECAj4Ywg/wGqY2AVgAYADYvAoCGAEubA0gvAY2ALAAbpbvqpyEAGAEpgQAJgAG7gAgAEACmghUFwCqAMpAINQIwC4DthRAAPcycKgApoIdABwBfCisABoATwBqASIAvhnSBP8aH/ECeAKXAq40NjgDBTwFYQU6AXs3oABgAD4XNgmcCY1eCl5tIFZeUqGgyoNHABgAEQAaABNwWQAmABMATPMa3T34ADldyprmM1M2XociUQgLzvwAXT3xABgAEQAaABNwIGFAnADD8AAgAD4BBJWzaCcIAIEBFMAWwKoAAdq9BWAF5wLQpALEtQAKUSGkahR4GnJM+gsAwCgeFAiUAECQ0BQuL8AAIAAAADKeIheclvFqQAAETr4iAMxIARMgAMIoHhQIAn0E0pDQFC4HhznoAAAAIAI2C0/4lvFqQAAETgBJJwYCAy4ABgYAFAA8MBKYEH4eRhTkAjYeFcgACAYAeABsOqyQ5gRwDayqugEgaIIAtgoACgDmEABmBAWGme5OBJJA2m4cDeoAmITWAXwrMgOgAGwBCh6CBXYF1Tzg1wKAAFdiuABRAFwAXQBsAG8AdgBrAHYAbwCEAHEwfxQBVE5TEQADVFhTBwBDANILAqcCzgLTApQCrQL6vAAMAL8APLhNBKkE6glGKTAU4Dr4N2EYEwBCkABKk8rHAbYBmwIoAiU4Ajf/Aq4CowCAANIChzgaNBsCsTgeODcFXrgClQKdAqQBiQGYAqsCsjTsNHsfNPA0ixsAWTWiOAMFPDQSNCk2BDZHNow2TTZUNhk28Jk9VzI3QkEoAoICoQKwAqcAQAAxBV4FXbS9BW47YkIXP1ciUqs05DS/FwABUwJW11e6nHuYZmSh/RAYA8oMKvZ8KASoUAJYWAJ6ILAsAZSoqjpgA0ocBIhmDgDWAAawRDQoAAcuAj5iAHABZiR2AIgiHgCaAU68ACxuHAG0ygM8MiZIAlgBdF4GagJqAPZOHAMuBgoATkYAsABiAHgAMLoGDPj0HpKEBAAOJgAuALggTAHWAeAMEDbd20Uege0ADwAWADkAQgA9OHd+2MUQZBBhBgNNDkxxPxUQArEPqwvqERoM1irQ090ANK4H8ANYB/ADWANYB/AH8ANYB/ADWANYA1gDWBwP8B/YxRBkD00EcgWTBZAE2wiIJk4RhgctCNdUEnQjHEwDSgEBIypJITuYMxAlR0wRTQgIATZHbKx9PQNMMbBU+pCnA9AyVDlxBgMedhKlAC8PeCE1uk6DekxxpQpQT7NX9wBFBgASqwAS5gBJDSgAUCwGPQBI4zTYABNGAE2bAE3KAExdGABKaAbgAFBXAFCOAFBJABI2SWdObALDOq0//QomCZhvwHdTBkIQHCemEPgMNAG2ATwN7kvZBPIGPATKH34ZGg/OlZ0Ipi3eDO4m5C6igFsj9iqEBe5L9TzeC05RaQ9aC2YJ5DpkgU8DIgEOIowK3g06CG4Q9ArKbA3mEUYHOgPWSZsApgcCCxIdNhW2JhFirQsKOXgG/Br3C5AmsBMqev0F1BoiBk4BKhsAANAu6IWxWjJcHU9gBgQLJiPIFKlQIQ0mQLh4SRocBxYlqgKSQ3FKiFE3HpQh9zw+DWcuFFF9B/Y8BhlQC4I8n0asRQ8R0z6OPUkiSkwtBDaALDAnjAnQD4YMunxzAVoJIgmyDHITMhEYN8YIOgcaLpclJxYIIkaWYJsE+KAD9BPSAwwFQAlCBxQDthwuEy8VKgUOgSXYAvQ21i60ApBWgQEYBcwPJh/gEFFH4Q7qCJwCZgOEJewALhUiABginAhEZABgj9lTBi7MCMhqbSN1A2gU6GIRdAeSDlgHqBw0FcAc4nDJXgyGCSiksAlcAXYJmgFgBOQICjVcjKEgQmdUi1kYnCBiQUBd/QIyDGYVoES+h3kCjA9sEhwBNgF0BzoNAgJ4Ee4RbBCWCOyGBTW2M/k6JgRQIYQgEgooA1BszwsoJvoM+WoBpBJjAw00PnfvZ6xgtyUX/gcaMsZBYSHyC5NPzgydGsIYQ1QvGeUHwAP0GvQn60FYBgADpAQUOk4z7wS+C2oIjAlAAEoOpBgH2BhrCnKM0QEyjAG4mgNYkoQCcJAGOAcMAGgMiAV65gAeAqgIpAAGANADWAA6Aq4HngAaAIZCAT4DKDABIuYCkAOUCDLMAZYwAfQqBBzEDBYA+DhuSwLDsgKAa2ajBd5ZAo8CSjYBTiYEBk9IUgOwcuIA3ABMBhTgSAEWrEvMG+REAeBwLADIAPwABjYHBkIBzgH0bgC4AWALMgmjtLYBTuoqAIQAFmwB2AKKAN4ANgCA8gFUAE4FWvoF1AJQSgESMhksWGIBvAMgATQBDgB6BsyOpsoIIARuB9QCEBwV4gLvLwe2AgMi4BPOQsYCvd9WADIXUu5eZwqoCqdeaAC0YTQHMnM9UQAPH6k+yAdy/BZIiQImSwBQ5gBQQzSaNTFWSTYBpwGqKQK38AFtqwBI/wK37gK3rQK3sAK6280C0gK33AK3zxAAUEIAUD9SklKDArekArw5AEQAzAHCO147WTteO1k7XjtZO147WTteO1kDmChYI03AVU0oJqkKbV9GYewMpw3VRMk6ShPcYFJgMxPJLbgUwhXPJVcZPhq9JwYl5VUKDwUt1GYxCC00dhe9AEApaYNCY4ceMQpMHOhTklT5LRwAskujM7ANrRsWREEFSHXuYisWDwojAmSCAmJDXE6wXDchAqH4AmiZAmYKAp+FOBwMAmY8AmYnBG8EgAN/FAN+kzkHOXgYOYM6JCQCbB4CMjc4CwJtyAJtr/CLADRoRiwBaADfAOIASwYHmQyOAP8MwwAOtgJ3MAJ2o0ACeUxEAni7Hl3cRa9G9AJ8QAJ6yQJ9CgJ88UgBSH5kJQAsFklZSlwWGErNAtECAtDNSygDiFADh+dExpEzAvKiXQQDA69Lz0wuJgTQTU1NsAKLQAKK2cIcCB5EaAa4Ao44Ao5dQZiCAo7aAo5deVG1UzYLUtVUhgKT/AKTDQDqAB1VH1WwVdEHLBwplocy4nhnRTw6ApegAu+zWCKpAFomApaQApZ9nQCqWa1aCoJOADwClrYClk9cRVzSApnMApllXMtdCBoCnJw5wzqeApwXAp+cAp65iwAeEDIrEAKd8gKekwC2PmE1YfACntQCoG8BqgKeoCACnk+mY8lkKCYsAiewAiZ/AqD8AqBN2AKmMAKlzwKoAAB+AqfzaH1osgAESmodatICrOQCrK8CrWgCrQMCVx4CVd0CseLYAx9PbJgCsr4OArLpGGzhbWRtSWADJc4Ctl08QG6RAylGArhfArlIFgK5K3hwN3DiAr0aAy2zAzISAr6JcgMDM3ICvhtzI3NQAsPMAsMFc4N0TDZGdOEDPKgDPJsDPcACxX0CxkgCxhGKAshqUgLIRQLJUALJLwJkngLd03h6YniveSZL0QMYpGcDAmH1GfSVJXsMXpNevBICz2wCz20wTFTT9BSgAMeuAs90ASrrA04TfkwGAtwoAtuLAtJQA1JdA1NgAQIDVY2AikABzBfuYUZ2AILPg44C2sgC2d+EEYRKpz0DhqYAMANkD4ZyWvoAVgLfZgLeuXR4AuIw7RUB8zEoAfScAfLTiALr9ALpcXoAAur6AurlAPpIAboC7ooC652Wq5cEAu5AA4XhmHpw4XGiAvMEAGoDjheZlAL3FAORbwOSiAL3mQL52gL4Z5odmqy8OJsfA52EAv77ARwAOp8dn7QDBY4DpmsDptoA0sYDBmuhiaIGCgMMSgFgASACtgNGAJwEgLpoBgC8BGzAEowcggCEDC6kdjoAJAM0C5IKRoABZCgiAIzw3AYBLACkfng9ogigkgNmWAN6AEQCvrkEVqTGAwCsBRbAA+4iQkMCHR072jI2PTbUNsk2RjY5NvA23TZKNiU3EDcZN5I+RTxDRTBCJkK5VBYKFhZfwQCWygU3AJBRHpu+OytgNxa61A40GMsYjsn7BVwFXQVcBV0FaAVdBVwFXQVcBV0FXAVdBVwFXUsaCNyKAK4AAQUHBwKU7oICoW1e7jAEzgPxA+YDwgCkBFDAwADABKzAAOxFLhitA1UFTDeyPkM+bj51QkRCuwTQWWQ8X+0AWBYzsACNA8xwzAGm7EZ/QisoCTAbLDs6fnLfb8H2GccsbgFw13M1HAVkBW/Jxsm9CNRO8E8FDD0FBQw9FkcClOYCoMFegpDfADgcMiA2AJQACB8AsigKAIzIEAJKeBIApY5yPZQIAKQiHb4fvj5BKSRPQrZCOz0oXyxgOywfKAnGbgMClQaCAkILXgdeCD9IIGUgQj5fPoY+dT52Ao5CM0dAX9BTVG9SDzFwWTQAbxBzJF/lOEIQQglCCkKJIAls5AcClQICoKPMODEFxhi6KSAbiyfIRrMjtCgdWCAkPlFBIitCsEJRzAbMAV/OEyQzDg0OAQQEJ36i328/Mk9AybDJsQlq3tDRApUKAkFzXf1d/j9uALYP6hCoFgCTGD8kPsFKQiobrm0+zj0KSD8kPnVCRBwMDyJRTHFgMTJa5rwXQiQ2YfI/JD7BMEJEHGINTw4TOFlIRzwJO0icMQpyPyQ+wzJCRBv6DVgnKB01NgUKj2bwYzMqCoBkznBgEF+zYDIocwRIX+NgHj4HICNfh2C4CwdwFWpTG/lgUhYGAwRfv2Ts8mAaXzVgml/XYIJfuWC4HI1gUF9pYJZgMR6ilQHMAOwLAlDRefC0in4AXAEJA6PjCwc0IamOANMMCAECRQDFNRTZBgd+CwQlRA+r6+gLBDEFBnwUBXgKATIArwAGRAAHA3cDdAN2A3kDdwN9A3oDdQN7A30DfAN4A3oDfQAYEAAlAtYASwMAUAFsAHcKAHcAmgB3AHUAdQB2AHVu8UgAygDAAHcAdQB1AHYAdQALCgB3AAsAmgB3AAsCOwB3AAtu8UgAygDAAHgKAJoAdwB3AHUAdQB2AHUAeAB1AHUAdgB1bvFIAMoAwAALCgCaAHcACwB3AAsCOwB3AAtu8UgAygDAAH4ACwGgALcBpwC6AahdAu0COwLtbvFIAMoAwAALCgCaAu0ACwLtAAsCOwLtAAtu8UgAygDAA24ACwNvAAu0VsQAAzsAABCkjUIpAAsAUIusOggWcgMeBxVsGwL67U/2HlzmWOEeOgALASvuAAseAfpKUpnpGgYJDCIZM6YyARUE9ThqAD5iXQgnAJYJPnOzw0ZAEZxEKsIAkA4DhAHnTAIDxxUDK0lxCQlPYgIvIQVYJQBVqE1GakUAKGYiDToSBA1EtAYAXQJYAIF8GgMHRyAAIAjOe9YncekRAA0KACUrjwE7Ayc6AAYWAqaiKG4McEcqANoN3+Mg9TwCBhIkuCny+JwUQ29L008JluRxu3K+oAdqiHOqFH0AG5SUIfUJ5SxCGfxdipRzqTmT4V5Zb+r1Uo4Vm+NqSSEl2mNvR2JhIa8SpYO6ntdwFXHCWTCK8f2+Hxo7uiG3drDycAuKIMP5bhi06ACnqArH1rz4Rqg//lm6SgJGEVbF9xJHISaR6HxqxSnkw6shDnelHKNEfGUXSJRJ1GcsmtJw25xrZMDK9gXSm1/YMkdX4/6NKYOdtk/NQ3/NnDASjTc3fPjIjW/5sVfVObX2oTDWkr1dF9f3kxBsD3/3aQO8hPfRz+e0uEiJqt1161griu7gz8hDDwtpy+F+BWtefnKHZPAxcZoWbnznhJpy0e842j36bcNzGnIEusgGX0a8ZxsnjcSsPDZ09yZ36fCQbriHeQ72JRMILNl6ePPf2HWoVwgWAm1fb3V2sAY0+B6rAXqSwPBgseVmoqsBTSrm91+XasMYYySI8eeRxH3ZvHkMz3BQ5aJ3iUVbYPNM3/7emRtjlsMgv/9VyTsyt/mK+8fgWeT6SoFaclXqn42dAIsvAarF5vNNWHzKSkKQ/8Hfk5ZWK7r9yliOsooyBjRhfkHP4Q2DkWXQi6FG/9r/IwbmkV5T7JSopHKn1pJwm9tb5Ot0oyN1Z2mPpKXHTxx2nlK08fKk1hEYA8WgVVWL5lgx0iTv+KdojJeU23ZDjmiubXOxVXJKKi2Wjuh2HLZOFLiSC7Tls5SMh4f+Pj6xUSrNjFqLGehRNB8lC0QSLNmkJJx/wSG3MnjE9T1CkPwJI0wH2lfzwETIiVqUxg0dfu5q39Gt+hwdcxkhhNvQ4TyrBceof3Mhs/IxFci1HmHr4FMZgXEEczPiGCx0HRwzAqDq2j9AVm1kwN0mRVLWLylgtoPNapF5cY4Y1wJh/e0BBwZj44YgZrDNqvD/9Hv7GFYdUQeDJuQ3EWI4HaKqavU1XjC/n41kT4L79kqGq0kLhdTZvgP3TA3fS0ozVz+5piZsoOtIvBUFoMKbNcmBL6YxxaUAusHB38XrS8dQMnQwJfUUkpRoGr5AUeWicvBTzyK9g77+yCkf5PAysL7r/JjcZgrbvRpMW9iyaxZvKO6ceZN2EwIxKwVFPuvFuiEPGCoagbMo+SpydLrXqBzNCDGFCrO/rkcwa2xhokQZ5CdZ0AsU3JfSqJ6n5I14YA+P/uAgfhPU84Tlw7cEFfp7AEE8ey4sP12PTt4Cods1GRgDOB5xvyiR5m+Bx8O5nBCNctU8BevfV5A08x6RHd5jcwPTMDSZJOedIZ1cGQ704lxbAzqZOP05ZxaOghzSdvFBHYqomATARyAADK4elP8Ly3IrUZKfWh23Xy20uBUmLS4Pfagu9+oyVa2iPgqRP3F2CTUsvJ7+RYnN8fFZbU/HVvxvcFFDKkiTqV5UBZ3Gz54JAKByi9hkKMZJvuGgcSYXFmw08UyoQyVdfTD1/dMkCHXcTGAKeROgArsvmRrQTLUOXioOHGK2QkjHuoYFgXciZoTJd6Fs5q1QX1G+p/e26hYsEf7QZD1nnIyl/SFkNtYYmmBhpBrxl9WbY0YpHWRuw2Ll/tj9mD8P4snVzJl4F9J+1arVeTb9E5r2ILH04qStjxQNwn3m4YNqxmaNbLAqW2TN6LidwuJRqS+NXbtqxoeDXpxeGWmxzSkWxjkyCkX4NQRme6q5SAcC+M7+9ETfA/EwrzQajKakCwYyeunP6ZFlxU2oMEn1Pz31zeStW74G406ZJFCl1wAXIoUKkWotYEpOuXB1uVNxJ63dpJEqfxBeptwIHNrPz8BllZoIcBoXwgfJ+8VAUnVPvRvexnw0Ma/WiGYuJO5y8QTvEYBigFmhUxY5RqzE8OcywN/8m4UYrlaniJO75XQ6KSo9+tWHlu+hMi0UVdiKQp7NelnoZUzNaIyBPVeOwK6GNp+FfHuPOoyhaWuNvTYFkvxscMQWDh+zeFCFkgwbXftiV23ywJ4+uwRqmg9k3KzwIQpzppt8DBBOMbrqwQM5Gb05sEwdKzMiAqOloaA/lr0KA+1pr0/+HiWoiIjHA/wir2nIuS3PeU/ji3O6ZwoxcR1SZ9FhtLC5S0FIzFhbBWcGVP/KpxOPSiUoAdWUpqKH++6Scz507iCcxYI6rdMBICPJZea7OcmeFw5mObJSiqpjg2UoWNIs+cFhyDSt6geV5qgi3FunmwwDoGSMgerFOZGX1m0dMCYo5XOruxO063dwENK9DbnVM9wYFREzh4vyU1WYYJ/LRRp6oxgjqP/X5a8/4Af6p6NWkQferzBmXme0zY/4nwMJm/wd1tIqSwGz+E3xPEAOoZlJit3XddD7/BT1pllzOx+8bmQtANQ/S6fZexc6qi3W+Q2xcmXTUhuS5mpHQRvcxZUN0S5+PL9lXWUAaRZhEH8hTdAcuNMMCuVNKTEGtSUKNi3O6KhSaTzck8csZ2vWRZ+d7mW8c4IKwXIYd25S/zIftPkwPzufjEvOHWVD1m+FjpDVUTV0DGDuHj6QnaEwLu/dEgdLQOg9E1Sro9XHJ8ykLAwtPu+pxqKDuFexqON1sKQm7rwbE1E68UCfA/erovrTCG+DBSNg0l4goDQvZN6uNlbyLpcZAwj2UclycvLpIZMgv4yRlpb3YuMftozorbcGVHt/VeDV3+Fdf1TP0iuaCsPi2G4XeGhsyF1ubVDxkoJhmniQ0/jSg/eYML9KLfnCFgISWkp91eauR3IQvED0nAPXK+6hPCYs+n3+hCZbiskmVMG2da+0EsZPonUeIY8EbfusQXjsK/eFDaosbPjEfQS0RKG7yj5GG69M7MeO1HmiUYocgygJHL6M1qzUDDwUSmr99V7Sdr2F3JjQAJY+F0yH33Iv3+C9M38eML7gTgmNu/r2bUMiPvpYbZ6v1/IaESirBHNa7mPKn4dEmYg7v/+HQgPN1G79jBQ1+soydfDC2r+h2Bl/KIc5KjMK7OH6nb1jLsNf0EHVe2KBiE51ox636uyG6Lho0t3J34L5QY/ilE3mikaF4HKXG1mG1rCevT1Vv6GavltxoQe/bMrpZvRggnBxSEPEeEzkEdOxTnPXHVjUYdw8JYvjB/o7Eegc3Ma+NUxLLnsK0kJlinPmUHzHGtrk5+CAbVzFOBqpyy3QVUnzTDfC/0XD94/okH+OB+i7g9lolhWIjSnfIb+Eq43ZXOWmwvjyV/qqD+t0e+7mTEM74qP/Ozt8nmC7mRpyu63OB4KnUzFc074SqoyPUAgM+/TJGFo6T44EHnQU4X4z6qannVqgw/U7zCpwcmXV1AubIrvOmkKHazJAR55ePjp5tLBsN8vAqs3NAHdcEHOR2xQ0lsNAFzSUuxFQCFYvXLZJdOj9p4fNq6p0HBGUik2YzaI4xySy91KzhQ0+q1hjxvImRwPRf76tChlRkhRCi74NXZ9qUNeIwP+s5p+3m5nwPdNOHgSLD79n7O9m1n1uDHiMntq4nkYwV5OZ1ENbXxFd4PgrlvavZsyUO4MqYlqqn1O8W/I1dEZq5dXhrbETLaZIbC2Kj/Aa/QM+fqUOHdf0tXAQ1huZ3cmWECWSXy/43j35+Mvq9xws7JKseriZ1pEWKc8qlzNrGPUGcVgOa9cPJYIJsGnJTAUsEcDOEVULO5x0rXBijc1lgXEzQQKhROf8zIV82w8eswc78YX11KYLWQRcgHNJElBxfXr72lS2RBSl07qTKorO2uUDZr3sFhYsvnhLZn0A94KRzJ/7DEGIAhW5ZWFpL8gEwu1aLA9MuWZzNwl8Oze9Y+bX+v9gywRVnoB5I/8kXTXU3141yRLYrIOOz6SOnyHNy4SieqzkBXharjfjqq1q6tklaEbA8Qfm2DaIPs7OTq/nvJBjKfO2H9bH2cCMh1+5gspfycu8f/cuuRmtDjyqZ7uCIMyjdV3a+p3fqmXsRx4C8lujezIFHnQiVTXLXuI1XrwN3+siYYj2HHTvESUx8DlOTXpak9qFRK+L3mgJ1WsD7F4cu1aJoFoYQnu+wGDMOjJM3kiBQWHCcvhJ/HRdxodOQp45YZaOTA22Nb4XKCVxqkbwMYFhzYQYIAnCW8FW14uf98jhUG2zrKhQQ0q0CEq0t5nXyvUyvR8DvD69LU+g3i+HFWQMQ8PqZuHD+sNKAV0+M6EJC0szq7rEr7B5bQ8BcNHzvDMc9eqB5ZCQdTf80Obn4uzjwpYU7SISdtV0QGa9D3Wrh2BDQtpBKxaNFV+/Cy2P/Sv+8s7Ud0Fd74X4+o/TNztWgETUapy+majNQ68Lq3ee0ZO48VEbTZYiH1Co4OlfWef82RWeyUXo7woM03PyapGfikTnQinoNq5z5veLpeMV3HCAMTaZmA1oGLAn7XS3XYsz+XK7VMQsc4XKrmDXOLU/pSXVNUq8dIqTba///3x6LiLS6xs1xuCAYSfcQ3+rQgmu7uvf3THKt5Ooo97TqcbRqxx7EASizaQCBQllG/rYxVapMLgtLbZS64w1MDBMXX+PQpBKNwqUKOf2DDRDUXQf9EhOS0Qj4nTmlA8dzSLz/G1d+Ud8MTy/6ghhdiLpeerGY/UlDOfiuqFsMUU5/UYlP+BAmgRLuNpvrUaLlVkrqDievNVEAwF+4CoM1MZTmjxjJMsKJq+u8Zd7tNCUFy6LiyYXRJQ4VyvEQFFaCGKsxIwQkk7EzZ6LTJq2hUuPhvAW+gQnSG6J+MszC+7QCRHcnqDdyNRJ6T9xyS87A6MDutbzKGvGktpbXqtzWtXb9HsfK2cBMomjN9a4y+TaJLnXxAeX/HWzmf4cR4vALt/P4w4qgKY04ml4ZdLOinFYS6cup3G/1ie4+t1eOnpBNlqGqs75ilzkT4+DsZQxNvaSKJ//6zIbbk/M7LOhFmRc/1R+kBtz7JFGdZm/COotIdvQoXpTqP/1uqEUmCb/QWoGLMwO5ANcHzxdY48IGP5+J+zKOTBFZ4Pid+GTM+Wq12MV/H86xEJptBa6T+p3kgpwLedManBHC2GgNrFpoN2xnrMz9WFWX/8/ygSBkavq2Uv7FdCsLEYLu9LLIvAU0bNRDtzYl+/vXmjpIvuJFYjmI0im6QEYqnIeMsNjXG4vIutIGHijeAG/9EDBozKV5cldkHbLxHh25vT+ZEzbhXlqvpzKJwcEgfNwLAKFeo0/pvEE10XDB+EXRTXtSzJozQKFFAJhMxYkVaCW+E9AL7tMeU8acxidHqzb6lX4691UsDpy/LLRmT+epgW56+5Cw8tB4kMUv6s9lh3eRKbyGs+H/4mQMaYzPTf2OOdokEn+zzgvoD3FqNKk8QqGAXVsqcGdXrT62fSPkR2vROFi68A6se86UxRUk4cajfPyCC4G5wDhD+zNq4jodQ4u4n/m37Lr36n4LIAAsVr02dFi9AiwA81MYs2rm4eDlDNmdMRvEKRHfBwW5DdMNp0jPFZMeARqF/wL4XBfd+EMLBfMzpH5GH6NaW+1vrvMdg+VxDzatk3MXgO3ro3P/DpcC6+Mo4MySJhKJhSR01SGGGp5hPWmrrUgrv3lDnP+HhcI3nt3YqBoVAVTBAQT5iuhTg8nvPtd8ZeYj6w1x6RqGUBrSku7+N1+BaasZvjTk64RoIDlL8brpEcJx3OmY7jLoZsswdtmhfC/G21llXhITOwmvRDDeTTPbyASOa16cF5/A1fZAidJpqju3wYAy9avPR1ya6eNp9K8XYrrtuxlqi+bDKwlfrYdR0RRiKRVTLOH85+ZY7XSmzRpfZBJjaTa81VDcJHpZnZnSQLASGYW9l51ZV/h7eVzTi3Hv6hUsgc/51AqJRTkpbFVLXXszoBL8nBX0u/0jBLT8nH+fJePbrwURT58OY+UieRjd1vs04w0VG5VN2U6MoGZkQzKN/ptz0Q366dxoTGmj7i1NQGHi9GgnquXFYdrCfZBmeb7s0T6yrdlZH5cZuwHFyIJ/kAtGsTg0xH5taAAq44BAk1CPk9KVVbqQzrCUiFdF/6gtlPQ8bHHc1G1W92MXGZ5HEHftyLYs8mbD/9xYRUWkHmlM0zC2ilJlnNgV4bfALpQghxOUoZL7VTqtCHIaQSXm+YUMnpkXybnV+A6xlm2CVy8fn0Xlm2XRa0+zzOa21JWWmixfiPMSCZ7qA4rS93VN3pkpF1s5TonQjisHf7iU9ZGvUPOAKZcR1pbeVf/Ul7OhepGCaId9wOtqo7pJ7yLcBZ0pFkOF28y4zEI/kcUNmutBHaQpBdNM8vjCS6HZRokkeo88TBAjGyG7SR+6vUgTcyK9Imalj0kuxz0wmK+byQU11AiJFk/ya5dNduRClcnU64yGu/ieWSeOos1t3ep+RPIWQ2pyTYVbZltTbsb7NiwSi3AV+8KLWk7LxCnfZUetEM8ThnsSoGH38/nyAwFguJp8FjvlHtcWZuU4hPva0rHfr0UhOOJ/F6vS62FW7KzkmRll2HEc7oUq4fyi5T70Vl7YVIfsPHUCdHesf9Lk7WNVWO75JDkYbMI8TOW8JKVtLY9d6UJRITO8oKo0xS+o99Yy04iniGHAaGj88kEWgwv0OrHdY/nr76DOGNS59hXCGXzTKUvDl9iKpLSWYN1lxIeyywdNpTkhay74w2jFT6NS8qkjo5CxA1yfSYwp6AJIZNKIeEK5PJAW7ORgWgwp0VgzYpqovMrWxbu+DGZ6Lhie1RAqpzm8VUzKJOH3mCzWuTOLsN3VT/dv2eeYe9UjbR8YTBsLz7q60VN1sU51k+um1f8JxD5pPhbhSC8rRaB454tmh6YUWrJI3+GWY0qeWioj/tbkYITOkJaeuGt4JrJvHA+l0Gu7kY7XOaa05alMnRWVCXqFgLIwSY4uF59Ue5SU4QKuc/HamDxbr0x6csCetXGoP7Qn1Bk/J9DsynO/UD6iZ1Hyrz+jit0hDCwi/E9OjgKTbB3ZQKQ/0ZOvevfNHG0NK4Aj3Cp7NpRk07RT1i/S0EL93Ag8GRgKI9CfpajKyK6+Jj/PI1KO5/85VAwz2AwzP8FTBb075IxCXv6T9RVvWT2tUaqxDS92zrGUbWzUYk9mSs82pECH+fkqsDt93VW++4YsR/dHCYcQSYTO/KaBMDj9LSD/J/+z20Kq8XvZUAIHtm9hRPP3ItbuAu2Hm5lkPs92pd7kCxgRs0xOVBnZ13ccdA0aunrwv9SdqElJRC3g+oCu+nXyCgmXUs9yMjTMAIHfxZV+aPKcZeUBWt057Xo85Ks1Ir5gzEHCWqZEhrLZMuF11ziGtFQUds/EESajhagzcKsxamcSZxGth4UII+adPhQkUnx2WyN+4YWR+r3f8MnkyGFuR4zjzxJS8WsQYR5PTyRaD9ixa6Mh741nBHbzfjXHskGDq179xaRNrCIB1z1xRfWfjqw2pHc1zk9xlPpL8sQWAIuETZZhbnmL54rceXVNRvUiKrrqIkeogsl0XXb17ylNb0f4GA9Wd44vffEG8FSZGHEL2fbaTGRcSiCeA8PmA/f6Hz8HCS76fXUHwgwkzSwlI71ekZ7Fapmlk/KC+Hs8hUcw3N2LN5LhkVYyizYFl/uPeVP5lsoJHhhfWvvSWruCUW1ZcJOeuTbrDgywJ/qG07gZJplnTvLcYdNaH0KMYOYMGX+rB4NGPFmQsNaIwlWrfCezxre8zXBrsMT+edVLbLqN1BqB76JH4BvZTqUIMfGwPGEn+EnmTV86fPBaYbFL3DFEhjB45CewkXEAtJxk4/Ms2pPXnaRqdky0HOYdcUcE2zcXq4vaIvW2/v0nHFJH2XXe22ueDmq/18XGtELSq85j9X8q0tcNSSKJIX8FTuJF/Pf8j5PhqG2u+osvsLxYrvvfeVJL+4tkcXcr9JV7v0ERmj/X6fM3NC4j6dS1+9Umr2oPavqiAydTZPLMNRGY23LO9zAVDly7jD+70G5TPPLdhRIl4WxcYjLnM+SNcJ26FOrkrISUtPObIz5Zb3AG612krnpy15RMW+1cQjlnWFI6538qky9axd2oJmHIHP08KyP0ubGO+TQNOYuv2uh17yCIvR8VcStw7o1g0NM60sk+8Tq7YfIBJrtp53GkvzXH7OA0p8/n/u1satf/VJhtR1l8Wa6Gmaug7haSpaCaYQax6ta0mkutlb+eAOSG1aobM81D9A4iS1RRlzBBoVX6tU1S6WE2N9ORY6DfeLRC4l9Rvr5h95XDWB2mR1d4WFudpsgVYwiTwT31ljskD8ZyDOlm5DkGh9N/UB/0AI5Xvb8ZBmai2hQ4BWMqFwYnzxwB26YHSOv9WgY3JXnvoN+2R4rqGVh/LLDMtpFP+SpMGJNWvbIl5SOodbCczW2RKleksPoUeGEzrjtKHVdtZA+kfqO+rVx/iclCqwoopepvJpSTDjT+b9GWylGRF8EDbGlw6eUzmJM95Ovoz+kwLX3c2fTjFeYEsE7vUZm3mqdGJuKh2w9/QGSaqRHs99aScGOdDqkFcACoqdbBoQqqjamhH6Q9ng39JCg3lrGJwd50Qk9ovnqBTr8MME7Ps2wiVfygUmPoUBJJfJWX5Nda0nuncbFkA==")); -} -const r = getData(); -const VALID = new Set(read_member_array(r)); -const IGNORED = new Set(read_member_array(r)); -const MAPPED = read_mapped_map(r); -const EMOJI_ROOT = read_emoji_trie(r); -function explode_cp(name) { - return toUtf8CodePoints(name); -} -function filter_fe0f(cps) { - return cps.filter((cp)=>cp != 65039); -} -function ens_normalize_post_check(name) { - for (let label of name.split(".")){ - let cps = explode_cp(label); - try { - for(let i = cps.lastIndexOf(95) - 1; i >= 0; i--){ - if (cps[i] !== 95) { - throw new Error(`underscore only allowed at start`); - } - } - if (cps.length >= 4 && cps.every((cp)=>cp < 128) && cps[2] === 45 && cps[3] === 45) { - throw new Error(`invalid label extension`); - } - } catch (err) { - throw new Error(`Invalid label "${label}": ${err.message}`); - } + static uint248(v) { + return n(v, 248); } - return name; -} -function ens_normalize(name) { - return ens_normalize_post_check(normalize(name, filter_fe0f)); -} -function normalize(name, emoji_filter) { - let input = explode_cp(name).reverse(); - let output = []; - while(input.length){ - let emoji = consume_emoji_reversed(input); - if (emoji) { - output.push(...emoji_filter(emoji)); - continue; - } - let cp = input.pop(); - if (VALID.has(cp)) { - output.push(cp); - continue; - } - if (IGNORED.has(cp)) { - continue; - } - let cps = MAPPED[cp]; - if (cps) { - output.push(...cps); - continue; - } - throw new Error(`Disallowed codepoint: 0x${cp.toString(16).toUpperCase()}`); + static uint256(v) { + return n(v, 256); } - return ens_normalize_post_check(nfc(String.fromCodePoint(...output))); -} -function nfc(s) { - return s.normalize("NFC"); -} -function consume_emoji_reversed(cps, eaten) { - var _a; - let node = EMOJI_ROOT; - let emoji; - let saved; - let stack = []; - let pos = cps.length; - if (eaten) eaten.length = 0; - while(pos){ - let cp = cps[--pos]; - node = (_a = node.branches.find((x)=>x.set.has(cp))) === null || _a === void 0 ? void 0 : _a.node; - if (!node) break; - if (node.save) { - saved = cp; - } else if (node.check) { - if (cp === saved) break; - } - stack.push(cp); - if (node.fe0f) { - stack.push(65039); - if (pos > 0 && cps[pos - 1] == 65039) pos--; - } - if (node.valid) { - emoji = stack.slice(); - if (node.valid == 2) emoji.splice(1, 1); - if (eaten) eaten.push(...cps.slice(pos).reverse()); - cps.length = pos; - } + static uint(v) { + return n(v, 256); } - return emoji; -} -const logger26 = new Logger(version8); -const Zeros = new Uint8Array(32); -Zeros.fill(0); -function checkComponent(comp) { - if (comp.length === 0) { - throw new Error("invalid ENS name; empty component"); + static int8(v) { + return n(v, -8); } - return comp; -} -function ensNameSplit(name) { - const bytes2 = toUtf8Bytes(ens_normalize(name)); - const comps = []; - if (name.length === 0) { - return comps; + static int16(v) { + return n(v, -16); } - let last = 0; - for(let i = 0; i < bytes2.length; i++){ - const d = bytes2[i]; - if (d === 46) { - comps.push(checkComponent(bytes2.slice(last, i))); - last = i + 1; - } + static int24(v) { + return n(v, -24); } - if (last >= bytes2.length) { - throw new Error("invalid ENS name; empty component"); + static int32(v) { + return n(v, -32); } - comps.push(checkComponent(bytes2.slice(last))); - return comps; -} -function isValidName(name) { - try { - return ensNameSplit(name).length !== 0; - } catch (error) {} - return false; -} -function namehash(name) { - if (typeof name !== "string") { - logger26.throwArgumentError("invalid ENS name; not a string", "name", name); + static int40(v) { + return n(v, -40); } - let result = Zeros; - const comps = ensNameSplit(name); - while(comps.length){ - result = keccak256(concat([ - result, - keccak256(comps.pop()) - ])); + static int48(v) { + return n(v, -48); } - return hexlify(result); -} -function dnsEncode(name) { - return hexlify(concat(ensNameSplit(name).map((comp)=>{ - if (comp.length > 63) { - throw new Error("invalid DNS encoded entry; length exceeds 63 bytes"); - } - const bytes2 = new Uint8Array(comp.length + 1); - bytes2.set(comp, 1); - bytes2[0] = bytes2.length - 1; - return bytes2; - }))) + "00"; -} -const messagePrefix = "Ethereum Signed Message:\n"; -function hashMessage(message) { - if (typeof message === "string") { - message = toUtf8Bytes(message); + static int56(v) { + return n(v, -56); } - return keccak256(concat([ - toUtf8Bytes(messagePrefix), - toUtf8Bytes(String(message.length)), - message - ])); -} -var __awaiter1 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); + static int64(v) { + return n(v, -64); } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger$11 = new Logger(version8); -const padding = new Uint8Array(32); -padding.fill(0); -const NegativeOne2 = BigNumber.from(-1); -const Zero2 = BigNumber.from(0); -const One1 = BigNumber.from(1); -const MaxUint2561 = BigNumber.from("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); -function hexPadRight(value) { - const bytes2 = arrayify(value); - const padOffset = bytes2.length % 32; - if (padOffset) { - return hexConcat([ - bytes2, - padding.slice(padOffset) - ]); + static int72(v) { + return n(v, -72); } - return hexlify(bytes2); -} -const hexTrue = hexZeroPad(One1.toHexString(), 32); -const hexFalse = hexZeroPad(Zero2.toHexString(), 32); -const domainFieldTypes = { - name: "string", - version: "string", - chainId: "uint256", - verifyingContract: "address", - salt: "bytes32" -}; -const domainFieldNames = [ - "name", - "version", - "chainId", - "verifyingContract", - "salt" -]; -function checkString(key) { - return function(value) { - if (typeof value !== "string") { - logger$11.throwArgumentError(`invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); - } - return value; - }; -} -const domainChecks = { - name: checkString("name"), - version: checkString("version"), - chainId: function(value) { - try { - return BigNumber.from(value).toString(); - } catch (error) {} - return logger$11.throwArgumentError(`invalid domain value for "chainId"`, "domain.chainId", value); - }, - verifyingContract: function(value) { - try { - return getAddress(value).toLowerCase(); - } catch (error) {} - return logger$11.throwArgumentError(`invalid domain value "verifyingContract"`, "domain.verifyingContract", value); - }, - salt: function(value) { - try { - const bytes2 = arrayify(value); - if (bytes2.length !== 32) { - throw new Error("bad length"); - } - return hexlify(bytes2); - } catch (error) {} - return logger$11.throwArgumentError(`invalid domain value "salt"`, "domain.salt", value); + static int80(v) { + return n(v, -80); } -}; -function getBaseEncoder(type) { - { - const match = type.match(/^(u?)int(\d*)$/); - if (match) { - const signed2 = match[1] === ""; - const width = parseInt(match[2] || "256"); - if (width % 8 !== 0 || width > 256 || match[2] && match[2] !== String(width)) { - logger$11.throwArgumentError("invalid numeric width", "type", type); - } - const boundsUpper = MaxUint2561.mask(signed2 ? width - 1 : width); - const boundsLower = signed2 ? boundsUpper.add(One1).mul(NegativeOne2) : Zero2; - return function(value) { - const v = BigNumber.from(value); - if (v.lt(boundsLower) || v.gt(boundsUpper)) { - logger$11.throwArgumentError(`value out-of-bounds for ${type}`, "value", value); - } - return hexZeroPad(v.toTwos(256).toHexString(), 32); - }; - } + static int88(v) { + return n(v, -88); } - { - const match = type.match(/^bytes(\d+)$/); - if (match) { - const width = parseInt(match[1]); - if (width === 0 || width > 32 || match[1] !== String(width)) { - logger$11.throwArgumentError("invalid bytes width", "type", type); - } - return function(value) { - const bytes2 = arrayify(value); - if (bytes2.length !== width) { - logger$11.throwArgumentError(`invalid length for ${type}`, "value", value); - } - return hexPadRight(value); - }; - } + static int96(v) { + return n(v, -96); } - switch(type){ - case "address": - return function(value) { - return hexZeroPad(getAddress(value), 32); - }; - case "bool": - return function(value) { - return !value ? hexFalse : hexTrue; - }; - case "bytes": - return function(value) { - return keccak256(value); - }; - case "string": - return function(value) { - return id(value); - }; + static int104(v) { + return n(v, -104); } - return null; -} -function encodeType(name, fields) { - return `${name}(${fields.map(({ name: name2, type })=>type + " " + name2).join(",")})`; -} -class TypedDataEncoder { - constructor(types){ - defineReadOnly(this, "types", Object.freeze(deepCopy(types))); - defineReadOnly(this, "_encoderCache", {}); - defineReadOnly(this, "_types", {}); - const links = {}; - const parents = {}; - const subtypes = {}; - Object.keys(types).forEach((type)=>{ - links[type] = {}; - parents[type] = []; - subtypes[type] = {}; - }); - for(const name in types){ - const uniqueNames = {}; - types[name].forEach((field)=>{ - if (uniqueNames[field.name]) { - logger$11.throwArgumentError(`duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", types); - } - uniqueNames[field.name] = true; - const baseType = field.type.match(/^([^\x5b]*)(\x5b|$)/)[1]; - if (baseType === name) { - logger$11.throwArgumentError(`circular type reference to ${JSON.stringify(baseType)}`, "types", types); - } - const encoder = getBaseEncoder(baseType); - if (encoder) { - return; - } - if (!parents[baseType]) { - logger$11.throwArgumentError(`unknown type ${JSON.stringify(baseType)}`, "types", types); - } - parents[baseType].push(name); - links[name][baseType] = true; - }); - } - const primaryTypes = Object.keys(parents).filter((n)=>parents[n].length === 0); - if (primaryTypes.length === 0) { - logger$11.throwArgumentError("missing primary type", "types", types); - } else if (primaryTypes.length > 1) { - logger$11.throwArgumentError(`ambiguous primary types or unused types: ${primaryTypes.map((t)=>JSON.stringify(t)).join(", ")}`, "types", types); - } - defineReadOnly(this, "primaryType", primaryTypes[0]); - function checkCircular(type, found) { - if (found[type]) { - logger$11.throwArgumentError(`circular type reference to ${JSON.stringify(type)}`, "types", types); - } - found[type] = true; - Object.keys(links[type]).forEach((child)=>{ - if (!parents[child]) { - return; - } - checkCircular(child, found); - Object.keys(found).forEach((subtype)=>{ - subtypes[subtype][child] = true; - }); - }); - delete found[type]; - } - checkCircular(this.primaryType, {}); - for(const name in subtypes){ - const st = Object.keys(subtypes[name]); - st.sort(); - this._types[name] = encodeType(name, types[name]) + st.map((t)=>encodeType(t, types[t])).join(""); - } + static int112(v) { + return n(v, -112); } - getEncoder(type) { - let encoder = this._encoderCache[type]; - if (!encoder) { - encoder = this._encoderCache[type] = this._getEncoder(type); - } - return encoder; + static int120(v) { + return n(v, -120); } - _getEncoder(type) { - { - const encoder = getBaseEncoder(type); - if (encoder) { - return encoder; - } - } - const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); - if (match) { - const subtype = match[1]; - const subEncoder = this.getEncoder(subtype); - const length = parseInt(match[3]); - return (value)=>{ - if (length >= 0 && value.length !== length) { - logger$11.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); - } - let result = value.map(subEncoder); - if (this._types[subtype]) { - result = result.map(keccak256); - } - return keccak256(hexConcat(result)); - }; - } - const fields = this.types[type]; - if (fields) { - const encodedType = id(this._types[type]); - return (value)=>{ - const values = fields.map(({ name, type: type2 })=>{ - const result = this.getEncoder(type2)(value[name]); - if (this._types[type2]) { - return keccak256(result); - } - return result; - }); - values.unshift(encodedType); - return hexConcat(values); - }; - } - return logger$11.throwArgumentError(`unknown type: ${type}`, "type", type); + static int128(v) { + return n(v, -128); } - encodeType(name) { - const result = this._types[name]; - if (!result) { - logger$11.throwArgumentError(`unknown type: ${JSON.stringify(name)}`, "name", name); - } - return result; + static int136(v) { + return n(v, -136); } - encodeData(type, value) { - return this.getEncoder(type)(value); + static int144(v) { + return n(v, -144); } - hashStruct(name, value) { - return keccak256(this.encodeData(name, value)); + static int152(v) { + return n(v, -152); } - encode(value) { - return this.encodeData(this.primaryType, value); + static int160(v) { + return n(v, -160); } - hash(value) { - return this.hashStruct(this.primaryType, value); + static int168(v) { + return n(v, -168); } - _visit(type, value, callback) { - { - const encoder = getBaseEncoder(type); - if (encoder) { - return callback(type, value); - } - } - const match = type.match(/^(.*)(\x5b(\d*)\x5d)$/); - if (match) { - const subtype = match[1]; - const length = parseInt(match[3]); - if (length >= 0 && value.length !== length) { - logger$11.throwArgumentError("array length mismatch; expected length ${ arrayLength }", "value", value); - } - return value.map((v)=>this._visit(subtype, v, callback)); - } - const fields = this.types[type]; - if (fields) { - return fields.reduce((accum, { name, type: type2 })=>{ - accum[name] = this._visit(type2, value[name], callback); - return accum; - }, {}); - } - return logger$11.throwArgumentError(`unknown type: ${type}`, "type", type); + static int176(v) { + return n(v, -176); } - visit(value, callback) { - return this._visit(this.primaryType, value, callback); + static int184(v) { + return n(v, -184); } - static from(types) { - return new TypedDataEncoder(types); + static int192(v) { + return n(v, -192); } - static getPrimaryType(types) { - return TypedDataEncoder.from(types).primaryType; + static int200(v) { + return n(v, -200); } - static hashStruct(name, types, value) { - return TypedDataEncoder.from(types).hashStruct(name, value); + static int208(v) { + return n(v, -208); } - static hashDomain(domain) { - const domainFields = []; - for(const name in domain){ - const type = domainFieldTypes[name]; - if (!type) { - logger$11.throwArgumentError(`invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain); - } - domainFields.push({ - name, - type - }); - } - domainFields.sort((a, b)=>{ - return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); - }); - return TypedDataEncoder.hashStruct("EIP712Domain", { - EIP712Domain: domainFields - }, domain); + static int216(v) { + return n(v, -216); } - static encode(domain, types, value) { - return hexConcat([ - "0x1901", - TypedDataEncoder.hashDomain(domain), - TypedDataEncoder.from(types).hash(value) - ]); + static int224(v) { + return n(v, -224); } - static hash(domain, types, value) { - return keccak256(TypedDataEncoder.encode(domain, types, value)); + static int232(v) { + return n(v, -232); } - static resolveNames(domain, types, value, resolveName) { - return __awaiter1(this, void 0, void 0, function*() { - domain = shallowCopy(domain); - const ensCache = {}; - if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) { - ensCache[domain.verifyingContract] = "0x"; - } - const encoder = TypedDataEncoder.from(types); - encoder.visit(value, (type, value2)=>{ - if (type === "address" && !isHexString(value2, 20)) { - ensCache[value2] = "0x"; - } - return value2; - }); - for(const name in ensCache){ - ensCache[name] = yield resolveName(name); - } - if (domain.verifyingContract && ensCache[domain.verifyingContract]) { - domain.verifyingContract = ensCache[domain.verifyingContract]; - } - value = encoder.visit(value, (type, value2)=>{ - if (type === "address" && ensCache[value2]) { - return ensCache[value2]; - } - return value2; - }); - return { - domain, - value - }; - }); + static int240(v) { + return n(v, -240); } - static getPayload(domain, types, value) { - TypedDataEncoder.hashDomain(domain); - const domainValues = {}; - const domainTypes = []; - domainFieldNames.forEach((name)=>{ - const value2 = domain[name]; - if (value2 == null) { - return; - } - domainValues[name] = domainChecks[name](value2); - domainTypes.push({ - name, - type: domainFieldTypes[name] - }); - }); - const encoder = TypedDataEncoder.from(types); - const typesWithDomain = shallowCopy(types); - if (typesWithDomain.EIP712Domain) { - logger$11.throwArgumentError("types must not contain EIP712Domain type", "types.EIP712Domain", types); - } else { - typesWithDomain.EIP712Domain = domainTypes; - } - encoder.encode(value); - return { - types: typesWithDomain, - domain: domainValues, - primaryType: encoder.primaryType, - message: encoder.visit(value, (type, value2)=>{ - if (type.match(/^bytes(\d*)/)) { - return hexlify(arrayify(value2)); - } - if (type.match(/^u?int/)) { - return BigNumber.from(value2).toString(); - } - switch(type){ - case "address": - return value2.toLowerCase(); - case "bool": - return !!value2; - case "string": - if (typeof value2 !== "string") { - logger$11.throwArgumentError(`invalid string`, "value", value2); - } - return value2; - } - return logger$11.throwArgumentError("unsupported type", "type", type); - }) - }; + static int248(v) { + return n(v, -248); } -} -const version9 = "abi/5.7.0"; -const logger27 = new Logger(version9); -const _constructorGuard1 = {}; -let ModifiersBytes = { - calldata: true, - memory: true, - storage: true -}; -let ModifiersNest = { - calldata: true, - memory: true -}; -function checkModifier(type, name) { - if (type === "bytes" || type === "string") { - if (ModifiersBytes[name]) { - return true; - } - } else if (type === "address") { - if (name === "payable") { - return true; - } - } else if (type.indexOf("[") >= 0 || type === "tuple") { - if (ModifiersNest[name]) { - return true; - } + static int256(v) { + return n(v, -256); } - if (ModifiersBytes[name] || name === "payable") { - logger27.throwArgumentError("invalid modifier", "name", name); + static int(v) { + return n(v, -256); } - return false; -} -function parseParamType(param, allowIndexed) { - let originalParam = param; - function throwError(i) { - logger27.throwArgumentError(`unexpected character at position ${i}`, "param", param); + static bytes1(v) { + return b(v, 1); } - param = param.replace(/\s/g, " "); - function newNode(parent2) { - let node2 = { - type: "", - name: "", - parent: parent2, - state: { - allowType: true - } - }; - if (allowIndexed) { - node2.indexed = false; - } - return node2; + static bytes2(v) { + return b(v, 2); } - let parent = { - type: "", - name: "", - state: { - allowType: true - } - }; - let node = parent; - for(let i = 0; i < param.length; i++){ - let c = param[i]; - switch(c){ - case "(": - if (node.state.allowType && node.type === "") { - node.type = "tuple"; - } else if (!node.state.allowParams) { - throwError(i); - } - node.state.allowType = false; - node.type = verifyType(node.type); - node.components = [ - newNode(node) - ]; - node = node.components[0]; - break; - case ")": - delete node.state; - if (node.name === "indexed") { - if (!allowIndexed) { - throwError(i); - } - node.indexed = true; - node.name = ""; - } - if (checkModifier(node.type, node.name)) { - node.name = ""; - } - node.type = verifyType(node.type); - let child = node; - node = node.parent; - if (!node) { - throwError(i); - } - delete child.parent; - node.state.allowParams = false; - node.state.allowName = true; - node.state.allowArray = true; - break; - case ",": - delete node.state; - if (node.name === "indexed") { - if (!allowIndexed) { - throwError(i); - } - node.indexed = true; - node.name = ""; - } - if (checkModifier(node.type, node.name)) { - node.name = ""; - } - node.type = verifyType(node.type); - let sibling = newNode(node.parent); - node.parent.components.push(sibling); - delete node.parent; - node = sibling; - break; - case " ": - if (node.state.allowType) { - if (node.type !== "") { - node.type = verifyType(node.type); - delete node.state.allowType; - node.state.allowName = true; - node.state.allowParams = true; - } - } - if (node.state.allowName) { - if (node.name !== "") { - if (node.name === "indexed") { - if (!allowIndexed) { - throwError(i); - } - if (node.indexed) { - throwError(i); - } - node.indexed = true; - node.name = ""; - } else if (checkModifier(node.type, node.name)) { - node.name = ""; - } else { - node.state.allowName = false; - } - } - } - break; - case "[": - if (!node.state.allowArray) { - throwError(i); - } - node.type += c; - node.state.allowArray = false; - node.state.allowName = false; - node.state.readArray = true; - break; - case "]": - if (!node.state.readArray) { - throwError(i); - } - node.type += c; - node.state.readArray = false; - node.state.allowArray = true; - node.state.allowName = true; - break; - default: - if (node.state.allowType) { - node.type += c; - node.state.allowParams = true; - node.state.allowArray = true; - } else if (node.state.allowName) { - node.name += c; - delete node.state.allowArray; - } else if (node.state.readArray) { - node.type += c; - } else { - throwError(i); - } - } + static bytes3(v) { + return b(v, 3); } - if (node.parent) { - logger27.throwArgumentError("unexpected eof", "param", param); + static bytes4(v) { + return b(v, 4); } - delete parent.state; - if (node.name === "indexed") { - if (!allowIndexed) { - throwError(originalParam.length - 7); - } - if (node.indexed) { - throwError(originalParam.length - 7); - } - node.indexed = true; - node.name = ""; - } else if (checkModifier(node.type, node.name)) { - node.name = ""; + static bytes5(v) { + return b(v, 5); } - parent.type = verifyType(parent.type); - return parent; -} -function populate(object, params) { - for(let key in params){ - defineReadOnly(object, key, params[key]); + static bytes6(v) { + return b(v, 6); } -} -const FormatTypes = Object.freeze({ - sighash: "sighash", - minimal: "minimal", - full: "full", - json: "json" -}); -const paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/); -class ParamType { - constructor(constructorGuard, params){ - if (constructorGuard !== _constructorGuard1) { - logger27.throwError("use fromString", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "new ParamType()" - }); - } - populate(this, params); - let match = this.type.match(paramTypeArray); - if (match) { - populate(this, { - arrayLength: parseInt(match[2] || "-1"), - arrayChildren: ParamType.fromObject({ - type: match[1], - components: this.components - }), - baseType: "array" - }); - } else { - populate(this, { - arrayLength: null, - arrayChildren: null, - baseType: this.components != null ? "tuple" : this.type - }); - } - this._isParamType = true; - Object.freeze(this); - } - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger27.throwArgumentError("invalid format type", "format", format); - } - if (format === FormatTypes.json) { - let result2 = { - type: this.baseType === "tuple" ? "tuple" : this.type, - name: this.name || void 0 - }; - if (typeof this.indexed === "boolean") { - result2.indexed = this.indexed; - } - if (this.components) { - result2.components = this.components.map((comp)=>JSON.parse(comp.format(format))); - } - return JSON.stringify(result2); - } - let result = ""; - if (this.baseType === "array") { - result += this.arrayChildren.format(format); - result += "[" + (this.arrayLength < 0 ? "" : String(this.arrayLength)) + "]"; - } else { - if (this.baseType === "tuple") { - if (format !== FormatTypes.sighash) { - result += this.type; - } - result += "(" + this.components.map((comp)=>comp.format(format)).join(format === FormatTypes.full ? ", " : ",") + ")"; - } else { - result += this.type; - } - } - if (format !== FormatTypes.sighash) { - if (this.indexed === true) { - result += " indexed"; - } - if (format === FormatTypes.full && this.name) { - result += " " + this.name; - } - } - return result; - } - static from(value, allowIndexed) { - if (typeof value === "string") { - return ParamType.fromString(value, allowIndexed); - } - return ParamType.fromObject(value); + static bytes7(v) { + return b(v, 7); } - static fromObject(value) { - if (ParamType.isParamType(value)) { - return value; - } - return new ParamType(_constructorGuard1, { - name: value.name || null, - type: verifyType(value.type), - indexed: value.indexed == null ? null : !!value.indexed, - components: value.components ? value.components.map(ParamType.fromObject) : null - }); + static bytes8(v) { + return b(v, 8); } - static fromString(value, allowIndexed) { - function ParamTypify(node) { - return ParamType.fromObject({ - name: node.name, - type: node.type, - indexed: node.indexed, - components: node.components - }); - } - return ParamTypify(parseParamType(value, !!allowIndexed)); + static bytes9(v) { + return b(v, 9); } - static isParamType(value) { - return !!(value != null && value._isParamType); + static bytes10(v) { + return b(v, 10); } -} -function parseParams(value, allowIndex) { - return splitNesting(value).map((param)=>ParamType.fromString(param, allowIndex)); -} -class Fragment { - constructor(constructorGuard, params){ - if (constructorGuard !== _constructorGuard1) { - logger27.throwError("use a static from method", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "new Fragment()" - }); - } - populate(this, params); - this._isFragment = true; - Object.freeze(this); + static bytes11(v) { + return b(v, 11); } - static from(value) { - if (Fragment.isFragment(value)) { - return value; - } - if (typeof value === "string") { - return Fragment.fromString(value); - } - return Fragment.fromObject(value); + static bytes12(v) { + return b(v, 12); } - static fromObject(value) { - if (Fragment.isFragment(value)) { - return value; - } - switch(value.type){ - case "function": - return FunctionFragment.fromObject(value); - case "event": - return EventFragment.fromObject(value); - case "constructor": - return ConstructorFragment.fromObject(value); - case "error": - return ErrorFragment.fromObject(value); - case "fallback": - case "receive": - return null; - } - return logger27.throwArgumentError("invalid fragment object", "value", value); + static bytes13(v) { + return b(v, 13); } - static fromString(value) { - value = value.replace(/\s/g, " "); - value = value.replace(/\(/g, " (").replace(/\)/g, ") ").replace(/\s+/g, " "); - value = value.trim(); - if (value.split(" ")[0] === "event") { - return EventFragment.fromString(value.substring(5).trim()); - } else if (value.split(" ")[0] === "function") { - return FunctionFragment.fromString(value.substring(8).trim()); - } else if (value.split("(")[0].trim() === "constructor") { - return ConstructorFragment.fromString(value.trim()); - } else if (value.split(" ")[0] === "error") { - return ErrorFragment.fromString(value.substring(5).trim()); - } - return logger27.throwArgumentError("unsupported fragment", "value", value); + static bytes14(v) { + return b(v, 14); } - static isFragment(value) { - return !!(value && value._isFragment); + static bytes15(v) { + return b(v, 15); } -} -class EventFragment extends Fragment { - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger27.throwArgumentError("invalid format type", "format", format); - } - if (format === FormatTypes.json) { - return JSON.stringify({ - type: "event", - anonymous: this.anonymous, - name: this.name, - inputs: this.inputs.map((input)=>JSON.parse(input.format(format))) - }); - } - let result = ""; - if (format !== FormatTypes.sighash) { - result += "event "; - } - result += this.name + "(" + this.inputs.map((input)=>input.format(format)).join(format === FormatTypes.full ? ", " : ",") + ") "; - if (format !== FormatTypes.sighash) { - if (this.anonymous) { - result += "anonymous "; - } - } - return result.trim(); + static bytes16(v) { + return b(v, 16); } - static from(value) { - if (typeof value === "string") { - return EventFragment.fromString(value); - } - return EventFragment.fromObject(value); + static bytes17(v) { + return b(v, 17); } - static fromObject(value) { - if (EventFragment.isEventFragment(value)) { - return value; - } - if (value.type !== "event") { - logger27.throwArgumentError("invalid event object", "value", value); - } - const params = { - name: verifyIdentifier(value.name), - anonymous: value.anonymous, - inputs: value.inputs ? value.inputs.map(ParamType.fromObject) : [], - type: "event" - }; - return new EventFragment(_constructorGuard1, params); + static bytes18(v) { + return b(v, 18); } - static fromString(value) { - let match = value.match(regexParen); - if (!match) { - logger27.throwArgumentError("invalid event string", "value", value); - } - let anonymous = false; - match[3].split(" ").forEach((modifier)=>{ - switch(modifier.trim()){ - case "anonymous": - anonymous = true; - break; - case "": - break; - default: - logger27.warn("unknown modifier: " + modifier); - } - }); - return EventFragment.fromObject({ - name: match[1].trim(), - anonymous, - inputs: parseParams(match[2], true), - type: "event" - }); + static bytes19(v) { + return b(v, 19); } - static isEventFragment(value) { - return value && value._isFragment && value.type === "event"; + static bytes20(v) { + return b(v, 20); } -} -function parseGas(value, params) { - params.gas = null; - let comps = value.split("@"); - if (comps.length !== 1) { - if (comps.length > 2) { - logger27.throwArgumentError("invalid human-readable ABI signature", "value", value); - } - if (!comps[1].match(/^[0-9]+$/)) { - logger27.throwArgumentError("invalid human-readable ABI signature gas", "value", value); - } - params.gas = BigNumber.from(comps[1]); - return comps[0]; + static bytes21(v) { + return b(v, 21); } - return value; -} -function parseModifiers(value, params) { - params.constant = false; - params.payable = false; - params.stateMutability = "nonpayable"; - value.split(" ").forEach((modifier)=>{ - switch(modifier.trim()){ - case "constant": - params.constant = true; - break; - case "payable": - params.payable = true; - params.stateMutability = "payable"; - break; - case "nonpayable": - params.payable = false; - params.stateMutability = "nonpayable"; - break; - case "pure": - params.constant = true; - params.stateMutability = "pure"; - break; - case "view": - params.constant = true; - params.stateMutability = "view"; - break; - case "external": - case "public": - case "": - break; - default: - console.log("unknown modifier: " + modifier); - } - }); -} -function verifyState(value) { - let result = { - constant: false, - payable: true, - stateMutability: "payable" - }; - if (value.stateMutability != null) { - result.stateMutability = value.stateMutability; - result.constant = result.stateMutability === "view" || result.stateMutability === "pure"; - if (value.constant != null) { - if (!!value.constant !== result.constant) { - logger27.throwArgumentError("cannot have constant function with mutability " + result.stateMutability, "value", value); - } - } - result.payable = result.stateMutability === "payable"; - if (value.payable != null) { - if (!!value.payable !== result.payable) { - logger27.throwArgumentError("cannot have payable function with mutability " + result.stateMutability, "value", value); - } - } - } else if (value.payable != null) { - result.payable = !!value.payable; - if (value.constant == null && !result.payable && value.type !== "constructor") { - logger27.throwArgumentError("unable to determine stateMutability", "value", value); - } - result.constant = !!value.constant; - if (result.constant) { - result.stateMutability = "view"; - } else { - result.stateMutability = result.payable ? "payable" : "nonpayable"; - } - if (result.payable && result.constant) { - logger27.throwArgumentError("cannot have constant payable function", "value", value); - } - } else if (value.constant != null) { - result.constant = !!value.constant; - result.payable = !result.constant; - result.stateMutability = result.constant ? "view" : "payable"; - } else if (value.type !== "constructor") { - logger27.throwArgumentError("unable to determine stateMutability", "value", value); + static bytes22(v) { + return b(v, 22); } - return result; -} -class ConstructorFragment extends Fragment { - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger27.throwArgumentError("invalid format type", "format", format); - } - if (format === FormatTypes.json) { - return JSON.stringify({ - type: "constructor", - stateMutability: this.stateMutability !== "nonpayable" ? this.stateMutability : void 0, - payable: this.payable, - gas: this.gas ? this.gas.toNumber() : void 0, - inputs: this.inputs.map((input)=>JSON.parse(input.format(format))) - }); - } - if (format === FormatTypes.sighash) { - logger27.throwError("cannot format a constructor for sighash", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "format(sighash)" - }); - } - let result = "constructor(" + this.inputs.map((input)=>input.format(format)).join(format === FormatTypes.full ? ", " : ",") + ") "; - if (this.stateMutability && this.stateMutability !== "nonpayable") { - result += this.stateMutability + " "; - } - return result.trim(); + static bytes23(v) { + return b(v, 23); } - static from(value) { - if (typeof value === "string") { - return ConstructorFragment.fromString(value); - } - return ConstructorFragment.fromObject(value); + static bytes24(v) { + return b(v, 24); } - static fromObject(value) { - if (ConstructorFragment.isConstructorFragment(value)) { - return value; - } - if (value.type !== "constructor") { - logger27.throwArgumentError("invalid constructor object", "value", value); - } - let state = verifyState(value); - if (state.constant) { - logger27.throwArgumentError("constructor cannot be constant", "value", value); - } - const params = { - name: null, - type: value.type, - inputs: value.inputs ? value.inputs.map(ParamType.fromObject) : [], - payable: state.payable, - stateMutability: state.stateMutability, - gas: value.gas ? BigNumber.from(value.gas) : null - }; - return new ConstructorFragment(_constructorGuard1, params); + static bytes25(v) { + return b(v, 25); } - static fromString(value) { - let params = { - type: "constructor" - }; - value = parseGas(value, params); - let parens = value.match(regexParen); - if (!parens || parens[1].trim() !== "constructor") { - logger27.throwArgumentError("invalid constructor string", "value", value); - } - params.inputs = parseParams(parens[2].trim(), false); - parseModifiers(parens[3].trim(), params); - return ConstructorFragment.fromObject(params); + static bytes26(v) { + return b(v, 26); } - static isConstructorFragment(value) { - return value && value._isFragment && value.type === "constructor"; + static bytes27(v) { + return b(v, 27); } -} -class FunctionFragment extends ConstructorFragment { - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger27.throwArgumentError("invalid format type", "format", format); - } - if (format === FormatTypes.json) { - return JSON.stringify({ - type: "function", - name: this.name, - constant: this.constant, - stateMutability: this.stateMutability !== "nonpayable" ? this.stateMutability : void 0, - payable: this.payable, - gas: this.gas ? this.gas.toNumber() : void 0, - inputs: this.inputs.map((input)=>JSON.parse(input.format(format))), - outputs: this.outputs.map((output)=>JSON.parse(output.format(format))) - }); - } - let result = ""; - if (format !== FormatTypes.sighash) { - result += "function "; - } - result += this.name + "(" + this.inputs.map((input)=>input.format(format)).join(format === FormatTypes.full ? ", " : ",") + ") "; - if (format !== FormatTypes.sighash) { - if (this.stateMutability) { - if (this.stateMutability !== "nonpayable") { - result += this.stateMutability + " "; - } - } else if (this.constant) { - result += "view "; - } - if (this.outputs && this.outputs.length) { - result += "returns (" + this.outputs.map((output)=>output.format(format)).join(", ") + ") "; - } - if (this.gas != null) { - result += "@" + this.gas.toString() + " "; - } - } - return result.trim(); + static bytes28(v) { + return b(v, 28); } - static from(value) { - if (typeof value === "string") { - return FunctionFragment.fromString(value); - } - return FunctionFragment.fromObject(value); + static bytes29(v) { + return b(v, 29); } - static fromObject(value) { - if (FunctionFragment.isFunctionFragment(value)) { - return value; - } - if (value.type !== "function") { - logger27.throwArgumentError("invalid function object", "value", value); - } - let state = verifyState(value); - const params = { - type: value.type, - name: verifyIdentifier(value.name), - constant: state.constant, - inputs: value.inputs ? value.inputs.map(ParamType.fromObject) : [], - outputs: value.outputs ? value.outputs.map(ParamType.fromObject) : [], - payable: state.payable, - stateMutability: state.stateMutability, - gas: value.gas ? BigNumber.from(value.gas) : null - }; - return new FunctionFragment(_constructorGuard1, params); + static bytes30(v) { + return b(v, 30); } - static fromString(value) { - let params = { - type: "function" - }; - value = parseGas(value, params); - let comps = value.split(" returns "); - if (comps.length > 2) { - logger27.throwArgumentError("invalid function string", "value", value); - } - let parens = comps[0].match(regexParen); - if (!parens) { - logger27.throwArgumentError("invalid function signature", "value", value); - } - params.name = parens[1].trim(); - if (params.name) { - verifyIdentifier(params.name); - } - params.inputs = parseParams(parens[2], false); - parseModifiers(parens[3].trim(), params); - if (comps.length > 1) { - let returns = comps[1].match(regexParen); - if (returns[1].trim() != "" || returns[3].trim() != "") { - logger27.throwArgumentError("unexpected tokens", "value", value); - } - params.outputs = parseParams(returns[2], false); - } else { - params.outputs = []; - } - return FunctionFragment.fromObject(params); + static bytes31(v) { + return b(v, 31); } - static isFunctionFragment(value) { - return value && value._isFragment && value.type === "function"; + static bytes32(v) { + return b(v, 32); } -} -function checkForbidden(fragment) { - const sig = fragment.format(); - if (sig === "Error(string)" || sig === "Panic(uint256)") { - logger27.throwArgumentError(`cannot specify user defined ${sig} error`, "fragment", fragment); + static address(v) { + return new Typed(_gaurd, "address", v); } - return fragment; -} -class ErrorFragment extends Fragment { - format(format) { - if (!format) { - format = FormatTypes.sighash; - } - if (!FormatTypes[format]) { - logger27.throwArgumentError("invalid format type", "format", format); - } - if (format === FormatTypes.json) { - return JSON.stringify({ - type: "error", - name: this.name, - inputs: this.inputs.map((input)=>JSON.parse(input.format(format))) - }); - } - let result = ""; - if (format !== FormatTypes.sighash) { - result += "error "; - } - result += this.name + "(" + this.inputs.map((input)=>input.format(format)).join(format === FormatTypes.full ? ", " : ",") + ") "; - return result.trim(); + static bool(v) { + return new Typed(_gaurd, "bool", !!v); } - static from(value) { - if (typeof value === "string") { - return ErrorFragment.fromString(value); - } - return ErrorFragment.fromObject(value); + static bytes(v) { + return new Typed(_gaurd, "bytes", v); } - static fromObject(value) { - if (ErrorFragment.isErrorFragment(value)) { - return value; - } - if (value.type !== "error") { - logger27.throwArgumentError("invalid error object", "value", value); - } - const params = { - type: value.type, - name: verifyIdentifier(value.name), - inputs: value.inputs ? value.inputs.map(ParamType.fromObject) : [] - }; - return checkForbidden(new ErrorFragment(_constructorGuard1, params)); + static string(v) { + return new Typed(_gaurd, "string", v); } - static fromString(value) { - let params = { - type: "error" - }; - let parens = value.match(regexParen); - if (!parens) { - logger27.throwArgumentError("invalid error signature", "value", value); - } - params.name = parens[1].trim(); - if (params.name) { - verifyIdentifier(params.name); - } - params.inputs = parseParams(parens[2], false); - return checkForbidden(ErrorFragment.fromObject(params)); + static array(v, dynamic) { + throw new Error("not implemented yet"); } - static isErrorFragment(value) { - return value && value._isFragment && value.type === "error"; + static tuple(v, name) { + throw new Error("not implemented yet"); } -} -function verifyType(type) { - if (type.match(/^uint($|[^1-9])/)) { - type = "uint256" + type.substring(4); - } else if (type.match(/^int($|[^1-9])/)) { - type = "int256" + type.substring(3); + static overrides(v) { + return new Typed(_gaurd, "overrides", Object.assign({}, v)); } - return type; -} -const regexIdentifier = new RegExp("^[a-zA-Z$_][a-zA-Z0-9$_]*$"); -function verifyIdentifier(value) { - if (!value || !value.match(regexIdentifier)) { - logger27.throwArgumentError(`invalid identifier "${value}"`, "value", value); + static isTyped(value) { + return value && typeof value === "object" && "_typedSymbol" in value && value._typedSymbol === _typedSymbol; } - return value; -} -const regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$"); -function splitNesting(value) { - value = value.trim(); - let result = []; - let accum = ""; - let depth = 0; - for(let offset = 0; offset < value.length; offset++){ - let c = value[offset]; - if (c === "," && depth === 0) { - result.push(accum); - accum = ""; - } else { - accum += c; - if (c === "(") { - depth++; - } else if (c === ")") { - depth--; - if (depth === -1) { - logger27.throwArgumentError("unbalanced parenthesis", "value", value); - } + static dereference(value, type) { + if (Typed.isTyped(value)) { + if (value.type !== type) { + throw new Error(`invalid type: expecetd ${type}, got ${value.type}`); } + return value.value; } + return value; } - if (accum) { - result.push(accum); - } - return result; } -const logger$12 = new Logger(version9); -function checkResultErrors(result) { - const errors = []; - const checkErrors = function(path, object) { - if (!Array.isArray(object)) { - return; - } - for(let key in object){ - const childPath = path.slice(); - childPath.push(key); - try { - checkErrors(childPath, object[key]); - } catch (error) { - errors.push({ - path: childPath, - error - }); - } +class AddressCoder extends Coder { + constructor(localName){ + super("address", "address", localName, false); + } + defaultValue() { + return "0x0000000000000000000000000000000000000000"; + } + encode(writer, _value) { + let value = Typed.dereference(_value, "string"); + try { + value = getAddress(value); + } catch (error) { + return this._throwError(error.message, _value); } - }; - checkErrors([], result); - return errors; -} -class Coder { - constructor(name, type, localName, dynamic){ - this.name = name; - this.type = type; - this.localName = localName; - this.dynamic = dynamic; + return writer.writeValue(value); } - _throwError(message, value) { - logger$12.throwArgumentError(message, this.localName, value); + decode(reader) { + return getAddress(toBeHex(reader.readValue(), 20)); } } -class Writer { - constructor(wordSize){ - defineReadOnly(this, "wordSize", wordSize || 32); - this._data = []; - this._dataLength = 0; - this._padding = new Uint8Array(wordSize); - } - get data() { - return hexConcat(this._data); +class AnonymousCoder extends Coder { + coder; + constructor(coder){ + super(coder.name, coder.type, "_", coder.dynamic); + this.coder = coder; } - get length() { - return this._dataLength; + defaultValue() { + return this.coder.defaultValue(); } - _writeData(data) { - this._data.push(data); - this._dataLength += data.length; - return data.length; + encode(writer, value) { + return this.coder.encode(writer, value); } - appendWriter(writer) { - return this._writeData(concat(writer._data)); - } - writeBytes(value) { - let bytes2 = arrayify(value); - const paddingOffset = bytes2.length % this.wordSize; - if (paddingOffset) { - bytes2 = concat([ - bytes2, - this._padding.slice(paddingOffset) - ]); - } - return this._writeData(bytes2); - } - _getValue(value) { - let bytes2 = arrayify(BigNumber.from(value)); - if (bytes2.length > this.wordSize) { - logger$12.throwError("value out-of-bounds", Logger.errors.BUFFER_OVERRUN, { - length: this.wordSize, - offset: bytes2.length - }); - } - if (bytes2.length % this.wordSize) { - bytes2 = concat([ - this._padding.slice(bytes2.length % this.wordSize), - bytes2 - ]); - } - return bytes2; - } - writeValue(value) { - return this._writeData(this._getValue(value)); - } - writeUpdatableValue() { - const offset = this._data.length; - this._data.push(this._padding); - this._dataLength += this.wordSize; - return (value)=>{ - this._data[offset] = this._getValue(value); - }; - } -} -class Reader { - constructor(data, wordSize, coerceFunc, allowLoose){ - defineReadOnly(this, "_data", arrayify(data)); - defineReadOnly(this, "wordSize", wordSize || 32); - defineReadOnly(this, "_coerceFunc", coerceFunc); - defineReadOnly(this, "allowLoose", allowLoose); - this._offset = 0; - } - get data() { - return hexlify(this._data); - } - get consumed() { - return this._offset; - } - static coerce(name, value) { - let match = name.match("^u?int([0-9]+)$"); - if (match && parseInt(match[1]) <= 48) { - value = value.toNumber(); - } - return value; - } - coerce(name, value) { - if (this._coerceFunc) { - return this._coerceFunc(name, value); - } - return Reader.coerce(name, value); - } - _peekBytes(offset, length, loose) { - let alignedLength = Math.ceil(length / this.wordSize) * this.wordSize; - if (this._offset + alignedLength > this._data.length) { - if (this.allowLoose && loose && this._offset + length <= this._data.length) { - alignedLength = length; - } else { - logger$12.throwError("data out-of-bounds", Logger.errors.BUFFER_OVERRUN, { - length: this._data.length, - offset: this._offset + alignedLength - }); - } - } - return this._data.slice(this._offset, this._offset + alignedLength); - } - subReader(offset) { - return new Reader(this._data.slice(this._offset + offset), this.wordSize, this._coerceFunc, this.allowLoose); - } - readBytes(length, loose) { - let bytes2 = this._peekBytes(0, length, !!loose); - this._offset += bytes2.length; - return bytes2.slice(0, length); - } - readValue() { - return BigNumber.from(this.readBytes(this.wordSize)); - } -} -class AddressCoder extends Coder { - constructor(localName){ - super("address", "address", localName, false); - } - defaultValue() { - return "0x0000000000000000000000000000000000000000"; - } - encode(writer, value) { - try { - value = getAddress(value); - } catch (error) { - this._throwError(error.message, value); - } - return writer.writeValue(value); - } - decode(reader) { - return getAddress(hexZeroPad(reader.readValue().toHexString(), 20)); - } -} -class AnonymousCoder extends Coder { - constructor(coder){ - super(coder.name, coder.type, void 0, coder.dynamic); - this.coder = coder; - } - defaultValue() { - return this.coder.defaultValue(); - } - encode(writer, value) { - return this.coder.encode(writer, value); - } - decode(reader) { - return this.coder.decode(reader); + decode(reader) { + return this.coder.decode(reader); } } -const logger$2 = new Logger(version9); function pack(writer, coders, values) { - let arrayValues = null; + let arrayValues = []; if (Array.isArray(values)) { arrayValues = values; } else if (values && typeof values === "object") { let unique = {}; arrayValues = coders.map((coder)=>{ const name = coder.localName; - if (!name) { - logger$2.throwError("cannot encode object for signature with missing names", Logger.errors.INVALID_ARGUMENT, { - argument: "values", - coder, - value: values - }); - } - if (unique[name]) { - logger$2.throwError("cannot encode object for signature with duplicate names", Logger.errors.INVALID_ARGUMENT, { - argument: "values", - coder, - value: values - }); - } + assert1(name, "cannot encode object for signature with missing names", "INVALID_ARGUMENT", { + argument: "values", + info: { + coder: coder + }, + value: values + }); + assert1(!unique[name], "cannot encode object for signature with duplicate names", "INVALID_ARGUMENT", { + argument: "values", + info: { + coder: coder + }, + value: values + }); unique[name] = true; return values[name]; }); } else { - logger$2.throwArgumentError("invalid tuple value", "tuple", values); + assertArgument(false, "invalid tuple value", "tuple", values); } - if (coders.length !== arrayValues.length) { - logger$2.throwArgumentError("types/value length mismatch", "tuple", values); - } - let staticWriter = new Writer(writer.wordSize); - let dynamicWriter = new Writer(writer.wordSize); + assertArgument(coders.length === arrayValues.length, "types/value length mismatch", "tuple", values); + let staticWriter = new Writer; + let dynamicWriter = new Writer; let updateFuncs = []; coders.forEach((coder, index)=>{ let value = arrayValues[index]; @@ -8070,16 +6131,17 @@ function pack(writer, coders, values) { } function unpack(reader, coders) { let values = []; + let keys = []; let baseReader = reader.subReader(0); coders.forEach((coder)=>{ let value = null; if (coder.dynamic) { - let offset = reader.readValue(); - let offsetReader = baseReader.subReader(offset.toNumber()); + let offset = reader.readIndex(); + let offsetReader = baseReader.subReader(offset); try { value = coder.decode(offsetReader); } catch (error) { - if (error.code === Logger.errors.BUFFER_OVERRUN) { + if (isError(error, "BUFFER_OVERRUN")) { throw error; } value = error; @@ -8091,7 +6153,7 @@ function unpack(reader, coders) { try { value = coder.decode(reader); } catch (error) { - if (error.code === Logger.errors.BUFFER_OVERRUN) { + if (isError(error, "BUFFER_OVERRUN")) { throw error; } value = error; @@ -8100,63 +6162,25 @@ function unpack(reader, coders) { value.type = coder.type; } } - if (value != void 0) { - values.push(value); - } - }); - const uniqueNames = coders.reduce((accum, coder)=>{ - const name = coder.localName; - if (name) { - if (!accum[name]) { - accum[name] = 0; - } - accum[name]++; - } - return accum; - }, {}); - coders.forEach((coder, index)=>{ - let name = coder.localName; - if (!name || uniqueNames[name] !== 1) { - return; - } - if (name === "length") { - name = "_length"; - } - if (values[name] != null) { - return; - } - const value = values[index]; - if (value instanceof Error) { - Object.defineProperty(values, name, { - enumerable: true, - get: ()=>{ - throw value; - } - }); - } else { - values[name] = value; + if (value == undefined) { + throw new Error("investigate"); } + values.push(value); + keys.push(coder.localName || null); }); - for(let i = 0; i < values.length; i++){ - const value = values[i]; - if (value instanceof Error) { - Object.defineProperty(values, i, { - enumerable: true, - get: ()=>{ - throw value; - } - }); - } - } - return Object.freeze(values); + return Result.fromItems(values, keys); } class ArrayCoder extends Coder { + coder; + length; constructor(coder, length, localName){ const type = coder.type + "[" + (length >= 0 ? length : "") + "]"; const dynamic = length === -1 || coder.dynamic; super("array", type, localName, dynamic); - this.coder = coder; - this.length = length; + defineProperties(this, { + coder: coder, + length: length + }); } defaultValue() { const defaultChild = this.coder.defaultValue(); @@ -8166,7 +6190,8 @@ class ArrayCoder extends Coder { } return result; } - encode(writer, value) { + encode(writer, _value) { + const value = Typed.dereference(_value, "array"); if (!Array.isArray(value)) { this._throwError("expected array value", value); } @@ -8175,7 +6200,7 @@ class ArrayCoder extends Coder { count = value.length; writer.writeValue(value.length); } - logger$2.checkArgumentCount(value.length, count, "coder array" + (this.localName ? " " + this.localName : "")); + assertArgumentCount(value.length, count, "coder array" + (this.localName ? " " + this.localName : "")); let coders = []; for(let i = 0; i < value.length; i++){ coders.push(this.coder); @@ -8185,19 +6210,18 @@ class ArrayCoder extends Coder { decode(reader) { let count = this.length; if (count === -1) { - count = reader.readValue().toNumber(); - if (count * 32 > reader._data.length) { - logger$2.throwError("insufficient data length", Logger.errors.BUFFER_OVERRUN, { - length: reader._data.length, - count - }); - } + count = reader.readIndex(); + assert1(count * 32 <= reader.dataLength, "insufficient data length", "BUFFER_OVERRUN", { + buffer: reader.bytes, + offset: count * 32, + length: reader.dataLength + }); } let coders = []; for(let i = 0; i < count; i++){ coders.push(new AnonymousCoder(this.coder)); } - return reader.coerce(this.name, unpack(reader, coders)); + return unpack(reader, coders); } } class BooleanCoder extends Coder { @@ -8207,11 +6231,12 @@ class BooleanCoder extends Coder { defaultValue() { return false; } - encode(writer, value) { + encode(writer, _value) { + const value = Typed.dereference(_value, "bool"); return writer.writeValue(value ? 1 : 0); } decode(reader) { - return reader.coerce(this.type, !reader.readValue().isZero()); + return !!reader.readValue(); } } class DynamicBytesCoder extends Coder { @@ -8222,13 +6247,13 @@ class DynamicBytesCoder extends Coder { return "0x"; } encode(writer, value) { - value = arrayify(value); + value = getBytesCopy(value); let length = writer.writeValue(value.length); length += writer.writeBytes(value); return length; } decode(reader) { - return reader.readBytes(reader.readValue().toNumber(), true); + return reader.readBytes(reader.readIndex(), true); } } class BytesCoder extends DynamicBytesCoder { @@ -8236,29 +6261,35 @@ class BytesCoder extends DynamicBytesCoder { super("bytes", localName); } decode(reader) { - return reader.coerce(this.name, hexlify(super.decode(reader))); + return hexlify(super.decode(reader)); } } class FixedBytesCoder extends Coder { + size; constructor(size, localName){ let name = "bytes" + String(size); super(name, name, localName, false); - this.size = size; + defineProperties(this, { + size: size + }, { + size: "number" + }); } defaultValue() { return "0x0000000000000000000000000000000000000000000000000000000000000000".substring(0, 2 + this.size * 2); } - encode(writer, value) { - let data = arrayify(value); + encode(writer, _value) { + let data = getBytesCopy(Typed.dereference(_value, this.type)); if (data.length !== this.size) { - this._throwError("incorrect data length", value); + this._throwError("incorrect data length", _value); } return writer.writeBytes(data); } decode(reader) { - return reader.coerce(this.name, hexlify(reader.readBytes(this.size))); + return hexlify(reader.readBytes(this.size)); } } +const Empty = new Uint8Array([]); class NullCoder extends Coder { constructor(localName){ super("null", "", localName, false); @@ -8270,46 +6301,53 @@ class NullCoder extends Coder { if (value != null) { this._throwError("not null", value); } - return writer.writeBytes([]); + return writer.writeBytes(Empty); } decode(reader) { reader.readBytes(0); - return reader.coerce(this.name, null); + return null; } } +const BN_0$5 = BigInt(0); +const BN_1$2 = BigInt(1); +const BN_MAX_UINT256$1 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); class NumberCoder extends Coder { + size; + signed; constructor(size, signed, localName){ const name = (signed ? "int" : "uint") + size * 8; super(name, name, localName, false); - this.size = size; - this.signed = signed; + defineProperties(this, { + size: size, + signed: signed + }, { + size: "number", + signed: "boolean" + }); } defaultValue() { return 0; } - encode(writer, value) { - let v = BigNumber.from(value); - let maxUintValue = MaxUint256.mask(writer.wordSize * 8); + encode(writer, _value) { + let value = getBigInt(Typed.dereference(_value, this.type)); + let maxUintValue = mask(BN_MAX_UINT256$1, 32 * 8); if (this.signed) { - let bounds = maxUintValue.mask(this.size * 8 - 1); - if (v.gt(bounds) || v.lt(bounds.add(One).mul(NegativeOne1))) { - this._throwError("value out-of-bounds", value); + let bounds = mask(maxUintValue, this.size * 8 - 1); + if (value > bounds || value < -(bounds + BN_1$2)) { + this._throwError("value out-of-bounds", _value); } - } else if (v.lt(Zero1) || v.gt(maxUintValue.mask(this.size * 8))) { - this._throwError("value out-of-bounds", value); - } - v = v.toTwos(this.size * 8).mask(this.size * 8); - if (this.signed) { - v = v.fromTwos(this.size * 8).toTwos(8 * writer.wordSize); + value = toTwos(value, 8 * WordSize); + } else if (value < BN_0$5 || value > mask(maxUintValue, this.size * 8)) { + this._throwError("value out-of-bounds", _value); } - return writer.writeValue(v); + return writer.writeValue(value); } decode(reader) { - let value = reader.readValue().mask(this.size * 8); + let value = mask(reader.readValue(), this.size * 8); if (this.signed) { - value = value.fromTwos(this.size * 8); + value = fromTwos(value, this.size * 8); } - return reader.coerce(this.name, value); + return value; } } class StringCoder extends DynamicBytesCoder { @@ -8319,14 +6357,15 @@ class StringCoder extends DynamicBytesCoder { defaultValue() { return ""; } - encode(writer, value) { - return super.encode(writer, toUtf8Bytes(value)); + encode(writer, _value) { + return super.encode(writer, toUtf8Bytes(Typed.dereference(_value, "string"))); } decode(reader) { return toUtf8String(super.decode(reader)); } } class TupleCoder extends Coder { + coders; constructor(coders, localName){ let dynamic = false; const types = []; @@ -8338,7 +6377,9 @@ class TupleCoder extends Coder { }); const type = "tuple(" + types.join(",") + ")"; super("tuple", type, localName, dynamic); - this.coders = coders; + defineProperties(this, { + coders: Object.freeze(coders.slice()) + }); } defaultValue() { const values = []; @@ -8370,17826 +6411,17211 @@ class TupleCoder extends Coder { }); return Object.freeze(values); } - encode(writer, value) { + encode(writer, _value) { + const value = Typed.dereference(_value, "tuple"); return pack(writer, this.coders, value); } decode(reader) { - return reader.coerce(this.name, unpack(reader, this.coders)); + return unpack(reader, this.coders); } } -const logger$3 = new Logger(version9); -const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); -const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); -class AbiCoder { - constructor(coerceFunc){ - defineReadOnly(this, "coerceFunc", coerceFunc || null); +function id(value) { + return keccak256(toUtf8Bytes(value)); +} +var COMPRESSED$1 = "AEEUdwmgDS8BxQKKAP4BOgDjATAAngDUAIMAoABoAOAAagCOAEQAhABMAHIAOwA9ACsANgAmAGIAHgAuACgAJwAXAC0AGgAjAB8ALwAUACkAEgAeAAkAGwARABkAFgA5ACgALQArADcAFQApABAAHgAiABAAGgAeABMAGAUhBe8BFxREN8sF2wC5AK5HAW8ArQkDzQCuhzc3NzcBP68NEfMABQdHBuw5BV8FYAA9MzkI9r4ZBg7QyQAWA9CeOwLNCjcCjqkChuA/lm+RAsXTAoP6ASfnEQDytQFJAjWVCkeXAOsA6godAB/cwdAUE0WlBCN/AQUCQRjFD/MRBjHxDQSJbw0jBzUAswBxme+tnIcAYwabAysG8QAjAEMMmxcDqgPKQyDXCMMxA7kUQwD3NXOrAKmFIAAfBC0D3x4BJQDBGdUFAhEgVD8JnwmQJiNWYUzrg0oAGwAUAB0AFnNcACkAFgBP9h3gPfsDOWDKneY2ChglX1UDYD30ABsAFAAdABZzIGRAnwDD8wAjAEEMzRbDqgMB2sAFYwXqAtCnAsS4AwpUJKRtFHsadUz9AMMVbwLpABM1NJEX0ZkCgYMBEyMAxRVvAukAEzUBUFAtmUwSAy4DBTER33EftQHfSwB5MxJ/AjkWKQLzL8E/cwBB6QH9LQDPDtO9ASNriQC5DQANAwCK21EFI91zHwCoL9kBqQcHBwcHKzUDowBvAQohPvU3fAQgHwCyAc8CKQMA5zMSezr7ULgFmDp/LzVQBgEGAi8FYQVgt8AFcTtlQhpCWEmfe5tmZ6IAExsDzQ8t+X8rBKtTAltbAn0jsy8Bl6utPWMDTR8Ei2kRANkDBrNHNysDBzECQWUAcwFpJ3kAiyUhAJ0BUb8AL3EfAbfNAz81KUsFWwF3YQZtAm0A+VEfAzEJDQBRSQCzAQBlAHsAM70GD/v3IZWHBwARKQAxALsjTwHZAeMPEzmXgIHwABIAGQA8AEUAQDt3gdvIEGcQZAkGTRFMdEIVEwK0D64L7REdDNkq09PgADSxB/MDWwfzA1sDWwfzB/MDWwfzA1sDWwNbA1scEvAi28gQZw9QBHUFlgWTBN4IiyZREYkHMAjaVBV0JhxPA00BBCMtSSQ7mzMTJUpMFE0LCAQ2SmyvfUADTzGzVP2QqgPTMlc5dAkGHnkSqAAyD3skNb1OhnpPcagKU0+2tYdJak5vAsY6sEAACikJm2/Dd1YGRRAfJ6kQ+ww3AbkBPw3xS9wE9QY/BM0fgRkdD9GVoAipLeEM8SbnLqWAXiP5KocF8Uv4POELUVFsD10LaQnnOmeBUgMlAREijwrhDT0IcRD3Cs1vDekRSQc9A9lJngCpBwULFR05FbkmFGKwCw05ewb/GvoLkyazEy17AAXXGiUGUQEtGwMA0y7rhbRaNVwgT2MGBwspI8sUrFAkDSlAu3hMGh8HGSWtApVDdEqLUToelyH6PEENai4XUYAH+TwJGVMLhTyiRq9FEhHWPpE9TCJNTDAEOYMsMyePCdMPiQy9fHYBXQklCbUMdRM1ERs3yQg9Bx0xlygnGQglRplgngT7owP3E9UDDwVDCUUHFwO5HDETMhUtBRGBKNsC9zbZLrcCk1aEARsFzw8pH+MQVEfkDu0InwJpA4cl7wAxFSUAGyKfCEdnAGOP3FMJLs8Iy2pwI3gDaxTrZRF3B5UOWwerHDcVwxzlcMxeD4YMKKezCV8BeQmdAWME5wgNNV+MpCBFZ1eLXBifIGVBQ14AAjUMaRWjRMGHfAKPD28SHwE5AXcHPQ0FAnsR8RFvEJkI74YINbkz/DopBFMhhyAVCisDU2zSCysm/Qz8bQGnEmYDEDRBd/Jnr2C6KBgBBx0yyUFkIfULlk/RDKAaxRhGVDIZ6AfDA/ca9yfuQVsGAwOnBxc6UTPyBMELbQiPCUMATQ6nGwfbGG4KdYzUATWPAbudA1uVhwJzkwY7Bw8Aaw+LBX3pACECqwinAAkA0wNbAD0CsQehAB0AiUUBQQMrMwEl6QKTA5cINc8BmTMB9y0EH8cMGQD7O25OAsO1AoBuZqYF4VwCkgJNOQFRKQQJUktVA7N15QDfAE8GF+NLARmvTs8e50cB43MvAMsA/wAJOQcJRQHRAfdxALsBYws1Caa3uQFR7S0AhwAZbwHbAo0A4QA5AIP1AVcAUQVd/QXXAlNNARU1HC9bZQG/AyMBNwERAH0Gz5GpzQsjBHEH1wIQHxXlAu8yB7kFAyLjE9FCyQK94lkAMhoKPAqrCqpgX2Q3CjV2PVQAEh+sPss/UgVVO1c7XDtXO1w7VztcO1c7XDtXO1wDm8Pmw+YKcF9JYe8Mqg3YRMw6TRPfYFVgNhPMLbsUxRXSJVoZQRrAJwkl6FUNDwgt12Y0CDA0eRfAAEMpbINFY4oeNApPHOtTlVT8LR8AtUumM7MNsBsZREQFS3XxYi4WEgomAmSFAmJGX1GzAV83JAKh+wJonAJmDQKfiDgfDwJmPwJmKgRyBIMDfxcDfpY5Cjl7GzmGOicnAmwhAjI6OA4CbcsCbbLzjgM3a0kvAWsA4gDlAE4JB5wMkQECD8YAEbkCdzMCdqZDAnlPRwJ4viFg30WyRvcCfEMCeswCfQ0CfPRIBEiBZygALxlJXEpfGRtK0ALRBQLQ0EsrA4hTA4fqRMmRNgLypV0HAwOyS9JMMSkH001QTbMCi0MCitzFHwshR2sJuwKOOwKOYESbhQKO3QKOYHxRuFM5AQ5S2FSJApP/ApMQAO0AIFUiVbNV1AosHymZijLleGpFPz0Cl6MC77ZYJawAXSkClpMCloCgAK1ZsFoNhVEAPwKWuQKWUlxIXNUCmc8CmWhczl0LHQKcnznGOqECnBoCn58CnryOACETNS4TAp31Ap6WALlBYThh8wKe1wKgcgGtAp6jIwKeUqljzGQrKS8CJ7MCJoICoP8CoFDbAqYzAqXSAqgDAIECp/ZogGi1AAdNaiBq1QKs5wKssgKtawKtBgJXIQJV4AKx5dsDH1JsmwKywRECsuwbbORtZ21MYwMl0QK2YD9DbpQDKUkCuGICuUsZArkue3A6cOUCvR0DLbYDMhUCvoxyBgMzdQK+HnMmc1MCw88CwwhzhnRPOUl05AM8qwEDPJ4DPcMCxYACxksCxhSNAshtVQLISALJUwLJMgJkoQLd1nh9ZXiyeSlL1AMYp2cGAmH4GfeVKHsPXpZevxUCz28Cz3AzT1fW9xejAMqxAs93AS3uA04Wfk8JAtwrAtuOAtJTA1JgA1NjAQUDVZCAjUMEzxrxZEl5A4LSg5EC2ssC2eKEFIRNp0ADhqkAMwNkEoZ1Xf0AWQLfaQLevHd7AuIz7RgB8zQrAfSfAfLWiwLr9wLpdH0DAur9AuroAP1LAb0C7o0C66CWrpcHAu5DA4XkmH1w5HGlAvMHAG0DjhqZlwL3FwORcgOSiwL3nAL53QL4apogmq+/O5siA52HAv7+AR8APZ8gAZ+3AwWRA6ZuA6bdANXJAwZuoYyiCQ0DDE0BEwEjB3EGZb1rCQC/BG/DFY8etxEAG3k9ACcDNxJRA42DAWcrJQCM8wAlAOanC6OVCLsGI6fJBgCvBRnDBvElRUYFFoAFcD9GSDNCKUK8X3kZX8QAls0FOgCQVCGbwTsuYDoZutcONxjOGJHJ/gVfBWAFXwVgBWsFYAVfBWAFXwVgBV8FYAVfBWBOHQjfjW8KCgoKbF7xMwTRA7kGN8PDAMMEr8MA70gxFroFTj5xPnhCR0K+X30/X/AAWBkzswCNBsxzzASm70aCRS4rDDMeLz49fnXfcsH5GcoscQFz13Y4HwVnBXLJycnACNdRYwgICAqEXoWTxgA7P4kACxbZBu21Kw0AjMsTAwkVAOVtJUUsJ1JCuULESUArXy9gPi9AKwnJRQYKTD9LPoA+iT54PnkCkULEUUpDX9NWV3JVEjQAc1w3A3IBE3YnX+g7QiMJb6MKaiszRCUuQrNCxDPMCcwEX9EWJzYREBEEBwIHKn6l33JCNVIfybPJtAltydPUCmhBZw/tEKsZAJOVJU1CLRuxbUHOQAo7P0s+eEJHHA8SJVRPdGM0NVrpvBoKhfUlM0JHHGUQUhEWO1xLSj8MO0ucNAqJIzVCRxv9EFsqKyA4OQgNj2nwZgp5ZNFgE2A1K3YHS2AhQQojJmC7DgpzGG1WYFUZCQYHZO9gHWCdYIVgu2BTYJlwFh8GvRbcXbG8YgtDHrMBwzPVyQonHQgkCyYBgQJ0Ajc4nVqIAwGSCsBPIgDsK3SWEtIVBa5N8gGjAo+kVwVIZwD/AEUSCDweX4ITrRQsJ8K3TwBXFDwEAB0TvzVcAtoTS20RIwDgVgZ9BBImYgA5AL4Coi8LFnezOkCnIQFjAY4KBAPh9RcGsgZSBsEAJctdsWIRu2kTkQstRw7DAcMBKgpPBGIGMDAwKCYnKTQaLg4AKRSVAFwCdl+YUZ0JdicFD3lPAdt1F9ZZKCGxuE3yBxkFVGcA/wBFEgiCBwAOLHQSjxOtQDg1z7deFRMAZ8QTAGtKb1ApIiPHADkAvgKiLy1DFtYCmBiDAlDDWNB0eo7fpaMO/aEVRRv0ATEQZBIODyMEAc8JQhCbDRgzFD4TAEMAu9YBCgCsAOkAm5I3ABwAYxvONnR+MhXJAxgKQyxL2+kkJhMbhQKDBMkSsvF0AD9BNQ6uQC7WqSQHwxEAEEIu1hkhAH2z4iQPwyJPHNWpdyYBRSpnJALzoBAEVPPsH20MxA0CCEQKRgAFyAtFAlMNwwjEDUQJRArELtapMg7DDZgJIw+TGukEIwvDFkMAqAtDEMMMBhioe+QAO3MMRAACrgnEBSPY9Q0FDnbSBoMAB8MSYxkSxAEJAPIJAAB8FWMOFtMc/HcXwxhDAC7DAvOowwAewwJdKDKHAAHDAALrFUQVwwAbwyvzpWMWv8wA/ABpAy++bcYDUKPD0KhDCwKmJ1MAAmMA5+UZwxAagwipBRL/eADfw6fDGOMCGsOjk3l6BwOpo4sAEsMOGxMAA5sAbcMOAAvDp0MJGkMDwgipnNIPAwfIqUMGAOGDAAPzABXDAAcDAAnDAGmTABrDAA7DChjDjnEWAwABYwAOcwAuUyYABsMAF8MIKQANUgC6wy4AA8MADqMq8wCyYgAcIwAB8wqpAAXOCx0V4wAHowBCwwEKAGnDAAuDAB3DAAjDCakABdIAbqcZ3QCZCCkABdIAAAFDAAfjAB2jCCkABqIACYMAGzMAbSMA5sOIAAhjAAhDABTDBAkpAAbSAOOTAAlDC6kOzPtnAAdDAG6kQFAATwAKwwwAA0MACbUDPwAHIwAZgwACE6cDAAojAApDAAoDp/MGwwAJIwADEwAQQwgAFEMAEXMAD5MADfMADcMAGRMOFiMAFUMAbqMWuwHDAMIAE0MLAGkzEgDhUwACQwAEWgAXgwUjAAbYABjDBSYBgzBaAEFNALcQBxUMegAwMngBrA0IZgJ0KxQHBREPd1N0ZzKRJwaIHAZqNT4DqQq8BwngAB4DAwt2AX56T1ocKQNXAh1GATQGC3tOxYNagkgAMQA5CQADAQEAWxLjAIOYNAEzAH7tFRk6TglSAF8NAAlYAQ+S1ACAQwQorQBiAN4dAJ1wPyeTANVzuQDX3AIeEMp9eyMgXiUAEdkBkJizKltbVVAaRMqRAAEAhyQ/SDEz6BmfVwB6ATEsOClKIRcDOF0E/832AFNt5AByAnkCRxGCOs94NjXdAwINGBonDBwPALW2AwICAgAAAAAAAAYDBQMDARrUAwAtAAAAAgEGBgYGBgYFBQUFBQUEBQYHCAkEBQUFBQQAAAICAAAAIgCNAJAAlT0A6gC7ANwApEQAwgCyAK0AqADuAKYA2gCjAOcBCAEDAMcAgQBiANIA1AEDAN4A8gCQAKkBMQDqAN8A3AsBCQ8yO9ra2tq8xuLT1tRJOB0BUgFcNU0BWgFpAWgBWwFMUUlLbhMBUxsNEAs6PhMOACcUKy0vMj5AQENDQ0RFFEYGJFdXV1dZWVhZL1pbXVxcI2NnZ2ZoZypsbnZ1eHh4eHh4enp6enp6enp6enp8fH18e2IARPIASQCaAHgAMgBm+ACOAFcAVwA3AnbvAIsABfj4AGQAk/IAnwBPAGIAZP//sACFAIUAaQBWALEAJAC2AIMCQAJDAPwA5wD+AP4A6AD/AOkA6QDoAOYALwJ7AVEBQAE+AVQBPgE+AT4BOQE4ATgBOAEcAVgXADEQCAEAUx8SHgsdHhYAjgCWAKYAUQBqIAIxAHYAbwCXAxUDJzIDIUlGTzEAkQJPAMcCVwKkAMAClgKWApYClgKWApYCiwKWApYClgKWApYClgKVApUCmAKgApcClgKWApQClAKUApQCkgKVAnUB1AKXAp8ClgKWApUeAIETBQD+DQOfAmECOh8BVBg9AuIZEjMbAU4/G1WZAXusRAFpYQEFA0FPAQYAmTEeIJdyADFoAHEANgCRA5zMk/C2jGINwjMWygIZCaXdfDILBCs5dAE7YnQBugDlhoiHhoiGiYqKhouOjIaNkI6Ij4qQipGGkoaThpSSlYaWhpeKmIaZhpqGm4aci52QnoqfhuIC4XTpAt90AIp0LHSoAIsAdHQEQwRABEIERQRDBEkERgRBBEcESQRIBEQERgRJAJ5udACrA490ALxuAQ10ANFZdHQA13QCFHQA/mJ0AP4BIQD+APwA/AD9APwDhGZ03ASMK23HAP4A/AD8AP0A/CR0dACRYnQA/gCRASEA/gCRAvQA/gCRA4RmdNwEjCttxyR0AP9idAEhAP4A/gD8APwA/QD8AP8A/AD8AP0A/AOEZnTcBIwrbcckdHQAkWJ0ASEA/gCRAP4AkQL0AP4AkQOEZnTcBIwrbcckdAJLAT50AlIBQXQCU8l0dAJfdHQDpgL0A6YDpgOnA6cDpwOnA4RmdNwEjCttxyR0dACRYnQBIQOmAJEDpgCRAvQDpgCRA4RmdNwEjCttxyR0BDh0AJEEOQCRDpU5dSgCADR03gV2CwArdAEFAM5iCnR0AF1iAAYcOgp0dACRCnQAXAEIwWZ0CnRmdHQAkWZ0CnRmdEXgAFF03gp0dEY0tlT2u3SOAQTwscwhjZZKrhYcBSfFp9XNbKiVDOD2b+cpe4/Z17mQnbtzzhaeQtE2GGj0IDNTjRUSyTxxw/RPHW/+vS7d1NfRt9z9QPZg4X7QFfhCnkvgNPIItOsC2eV6hPannZNHlZ9xrwZXIMOlu3jSoQSq78WEjwLjw1ELSlF1aBvfzwk5ZX7AUvQzjPQKbDuQ+sm4wNOp4A6AdVuRS0t1y/DZpg4R6m7FNjM9HgvW7Bi88zaMjOo6lM8wtBBdj8LP4ylv3zCXPhebMKJc066o9sF71oFW/8JXu86HJbwDID5lzw5GWLR/LhT0Qqnp2JQxNZNfcbLIzPy+YypqRm/lBmGmex+82+PisxUumSeJkALIT6rJezxMH+CTJmQtt5uwTVbL3ptmjDUQzlSIvWi8Tl7ng1NpuRn1Ng4n14Qc+3Iil7OwkvNWogLSPkn3pihIFytyIGmMhOe3n1tWsuMy9BdKyqF4Z3v2SgggTL9KVvMXPnCbRe+oOuFFP3HejBG/w9gvmfNYvg6JuWia2lcSSN1uIjBktzoIazOHPJZ7kKHPz8mRWVdW3lA8WGF9dQF6Bm673boov3BUWDU2JNcahR23GtfHKLOz/viZ+rYnZFaIznXO67CYEJ1fXuTRpZhYZkKe54xeoagkNGLs+NTZHE0rX45/XvQ2RGADX6vcAvdxIUBV27wxGm2zjZo4X3ILgAlrOFheuZ6wtsvaIj4yLY7qqawlliaIcrz2G+c3vscAnCkCuMzMmZvMfu9lLwTvfX+3cVSyPdN9ZwgDZhfjRgNJcLiJ67b9xx8JHswprbiE3v9UphotAPIgnXVIN5KmMc0piXhc6cChPnN+MRhG9adtdttQTTwSIpl8I4/j//d3sz1326qTBTpPRM/Hgh3kzqEXs8ZAk4ErQhNO8hzrQ0DLkWMA/N+91tn2MdOJnWC2FCZehkQrwzwbKOjhvZsbM95QoeL9skYyMf4srVPVJSgg7pOLUtr/n9eT99oe9nLtFRpjA9okV2Kj8h9k5HaC0oivRD8VyXkJ81tcd4fHNXPCfloIQasxsuO18/46dR2jgul/UIet2G0kRvnyONMKhHs6J26FEoqSqd+rfYjeEGwHWVDpX1fh1jBBcKGMqRepju9Y00mDVHC+Xdij/j44rKfvfjGinNs1jO/0F3jB83XCDINN/HB84axlP+3E/klktRo+vl3U/aiyMJbIodE1XSsDn6UAzIoMtUObY2+k/4gY/l+AkZJ5Sj2vQrkyLm3FoxjhDX+31UXBFf9XrAH31fFqoBmDEZvhvvpnZ87N+oZEu7U9O/nnk+QWj3x8uyoRbEnf+O5UMr9i0nHP38IF5AvzrBW8YWBUR0mIAzIvndQq9N3v/Jto3aPjPXUPl8ASdPPyAp7jENf8bk7VMM9ol9XGmlBmeDMuGqt+WzuL6CXAxXjIhCPM5vACchgMJ/8XBGLO/D1isVvGhwwHHr1DLaI5mn2Jr/b1pUD90uciDaS8cXNDzCWvNmT/PhQe5e8nTnnnkt8Ds/SIjibcum/fqDhKopxAY8AkSrPn+IGDEKOO+U3XOP6djFs2H5N9+orhOahiQk5KnEUWa+CzkVzhp8bMHRbg81qhjjXuIKbHjSLSIBKWqockGtKinY+z4/RdBUF6pcc3JmnlxVcNgrI4SEzKUZSwcD2QCyxzKve+gAmg6ZuSRkpPFa6mfThu7LJNu3H5K42uCpNvPAsoedolKV/LHe/eJ+BbaG5MG0NaSGVPRUmNFMFFSSpXEcXwbVh7UETOZZtoVNRGOIbbkig3McEtR68cG0RZAoJevWYo7Dg/lZ1CQzblWeUvVHmr8fY4Nqd9JJiH/zEX24mJviH60fAyFr0A3c4bC1j3yZU60VgJxXn8JgJXLUIsiBnmKmMYz+7yBQFBvqb2eYnuW59joZBf56/wXvWIR4R8wTmV80i1mZy+S4+BUES+hzjk0uXpC///z/IlqHZ1monzlXp8aCfhGKMti73FI1KbL1q6IKO4fuBuZ59gagjn5xU79muMpHXg6S+e+gDM/U9BKLHbl9l6o8czQKl4RUkJJiqftQG2i3BMg/TQlUYFkJDYBOOvAugYuzYSDnZbDDd/aSd9x0Oe6F+bJcHfl9+gp6L5/TgA+BdFFovbfCrQ40s5vMPw8866pNX8zyFGeFWdxIpPVp9Rg1UPOVFbFZrvaFq/YAzHQgqMWpahMYfqHpmwXfHL1/kpYmGuHFwT55mQu0dylfNuq2Oq0hTMCPwqfxnuBIPLXfci4Y1ANy+1CUipQxld/izVh16WyG2Q0CQQ9NqtAnx1HCHwDj7sYxOSB0wopZSnOzxQOcExmxrVTF2BkOthVpGfuhaGECfCJpJKpjnihY+xOT2QJxN61+9K6QSqtv2Shr82I3jgJrqBg0wELFZPjvHpvzTtaJnLK6Vb97Yn933koO/saN7fsjwNKzp4l2lJVx2orjCGzC/4ZL4zCver6aQYtC5sdoychuFE6ufOiog+VWi5UDkbmvmtah/3aArEBIi39s5ILUnlFLgilcGuz9CQshEY7fw2ouoILAYPVT/gyAIq3TFAIwVsl+ktkRz/qGfnCDGrm5gsl/l9QdvCWGsjPz3dU7XuqKfdUrr/6XIgjp4rey6AJBmCmUJMjITHVdFb5m1p+dLMCL8t55zD42cmftmLEJC0Da04YiRCVUBLLa8D071/N5UBNBXDh0LFsmhV/5B5ExOB4j3WVG/S3lfK5o+V6ELHvy6RR9n4ac+VsK4VE4yphPvV+kG9FegTBH4ZRXL2HytUHCduJazB/KykjfetYxOXTLws267aGOd+I+JhKP//+VnXmS90OD/jvLcVu0asyqcuYN1mSb6XTlCkqv1vigZPIYwNF/zpWcT1GR/6aEIRjkh0yhg4LXJfaGobYJTY4JI58KiAKgmmgAKWdl5nYCeLqavRJGQNuYuZtZFGx+IkI4w4NS2xwbetNMunOjBu/hmKCI/w7tfiiyUd//4rbTeWt4izBY8YvGIN6vyKYmP/8X8wHKCeN+WRcKM70+tXKNGyevU9H2Dg5BsljnTf8YbsJ1TmMs74Ce2XlHisleguhyeg44rQOHZuw/6HTkhnnurK2d62q6yS7210SsAIaR+jXMQA+svkrLpsUY+F30Uw89uOdGAR6vo4FIME0EfVVeHTu6eKicfhSqOeXJhbftcd08sWEnNUL1C9fnprTgd83IMut8onVUF0hvqzZfHduPjbjwEXIcoYmy+P6tcJZHmeOv6VrvEdkHDJecjHuHeWANe79VG662qTjA/HCvumVv3qL+LrOcpqGps2ZGwQdFJ7PU4iuyRlBrwfO+xnPyr47s2cXVbWzAyznDiBGjCM3ksxjjqM62GE9C8f5U38kB3VjtabKp/nRdvMESPGDG90bWRLAt1Qk5DyLuazRR1YzdC1c+hZXvAWV8xA72S4A8B67vjVhbba3MMop293FeEXpe7zItMWrJG/LOH9ByOXmYnNJfjmfuX9KbrpgLOba4nZ+fl8Gbdv/ihv+6wFGKHCYrVwmhFC0J3V2bn2tIB1wCc1CST3d3X2OyxhguXcs4sm679UngzofuSeBewMFJboIQHbUh/m2JhW2hG9DIvG2t7yZIzKBTz9wBtnNC+2pCRYhSIuQ1j8xsz5VvqnyUIthvuoyyu7fNIrg/KQUVmGQaqkqZk/Vx5b33/gsEs8yX7SC1J+NV4icz6bvIE7C5G6McBaI8rVg56q5QBJWxn/87Q1sPK4+sQa8fLU5gXo4paaq4cOcQ4wR0VBHPGjKh+UlPCbA1nLXyEUX45qZ8J7/Ln4FPJE2TdzD0Z8MLSNQiykMMmSyOCiFfy84Rq60emYB2vD09KjYwsoIpeDcBDTElBbXxND72yhd9pC/1CMid/5HUMvAL27OtcIJDzNKpRPNqPOpyt2aPGz9QWIs9hQ9LiX5s8m9hjTUu/f7MyIatjjd+tSfQ3ufZxPpmJhTaBtZtKLUcfOCUqADuO+QoH8B9v6U+P0HV1GLQmtoNFTb3s74ivZgjES0qfK+8RdGgBbcCMSy8eBvh98+et1KIFqSe1KQPyXULBMTsIYnysIwiZBJYdI20vseV+wuJkcqGemehKjaAb9L57xZm3g2zX0bZ2xk/fU+bCo7TlnbW7JuF1YdURo/2Gw7VclDG1W7LOtas2LX4upifZ/23rzpsnY/ALfRgrcWP5hYmV9VxVOQA1fZvp9F2UNU+7d7xRyVm5wiLp3/0dlV7vdw1PMiZrbDAYzIVqEjRY2YU03sJhPnlwIPcZUG5ltL6S8XCxU1eYS5cjr34veBmXAvy7yN4ZjArIG0dfD/5UpBNlX1ZPoxJOwyqRi3wQWtOzd4oNKh0LkoTm8cwqgIfKhqqGOhwo71I+zXnMemTv2B2AUzABWyFztGgGULjDDzWYwJUVBTjKCn5K2QGMK1CQT7SzziOjo+BhAmqBjzuc3xYym2eedGeOIRJVyTwDw37iCMe4g5Vbnsb5ZBdxOAnMT7HU4DHpxWGuQ7GeiY30Cpbvzss55+5Km1YsbD5ea3NI9QNYIXol5apgSu9dZ8f8xS5dtHpido5BclDuLWY4lhik0tbJa07yJhH0BOyEut/GRbYTS6RfiTYWGMCkNpfSHi7HvdiTglEVHKZXaVhezH4kkXiIvKopYAlPusftpE4a5IZwvw1x/eLvoDIh/zpo9FiQInsTb2SAkKHV42XYBjpJDg4374XiVb3ws4qM0s9eSQ5HzsMU4OZJKuopFjBM+dAZEl8RUMx5uU2N486Kr141tVsGQfGjORYMCJAMsxELeNT4RmWjRcpdTGBwcx6XN9drWqPmJzcrGrH4+DRc7+n1w3kPZwu0BkNr6hQrqgo7JTB9A5kdJ/H7P4cWBMwsmuixAzJB3yrQpnGIq90lxAXLzDCdn1LPibsRt7rHNjgQBklRgPZ8vTbjXdgXrTWQsK5MdrXXQVPp0Rinq3frzZKJ0qD6Qhc40VzAraUXlob1gvkhK3vpmHgI6FRlQZNx6eRqkp0zy4AQlX813fAPtL3jMRaitGFFjo0zmErloC+h+YYdVQ6k4F/epxAoF0BmqEoKNTt6j4vQZNQ2BoqF9Vj53TOIoNmDiu9Xp15RkIgQIGcoLpfoIbenzpGUAtqFJp5W+LLnx38jHeECTJ/navKY1NWfN0sY1T8/pB8kIH3DU3DX+u6W3YwpypBMYOhbSxGjq84RZ84fWJow8pyHqn4S/9J15EcCMsXqrfwyd9mhiu3+rEo9pPpoJkdZqHjra4NvzFwuThNKy6hao/SlLw3ZADUcUp3w3SRVfW2rhl80zOgTYnKE0Hs2qp1J6H3xqPqIkvUDRMFDYyRbsFI3M9MEyovPk8rlw7/0a81cDVLmBsR2ze2pBuKb23fbeZC0uXoIvDppfTwIDxk1Oq2dGesGc+oJXWJLGkOha3CX+DUnzgAp9HGH9RsPZN63Hn4RMA5eSVhPHO+9RcRb/IOgtW31V1Q5IPGtoxPjC+MEJbVlIMYADd9aHYWUIQKopuPOHmoqSkubnAKnzgKHqgIOfW5RdAgotN6BN+O2ZYHkuemLnvQ8U9THVrS1RtLmKbcC7PeeDsYznvqzeg6VCNwmr0Yyx1wnLjyT84BZz3EJyCptD3yeueAyDWIs0L2qs/VQ3HUyqfrja0V1LdDzqAikeWuV4sc7RLIB69jEIBjCkyZedoUHqCrOvShVzyd73OdrJW0hPOuQv2qOoHDc9xVb6Yu6uq3Xqp2ZaH46A7lzevbxQEmfrzvAYSJuZ4WDk1Hz3QX1LVdiUK0EvlAGAYlG3Md30r7dcPN63yqBCIj25prpvZP0nI4+EgWoFG95V596CurXpKRBGRjQlHCvy5Ib/iW8nZJWwrET3mgd6mEhfP4KCuaLjopWs7h+MdXFdIv8dHQJgg1xi1eYqB0uDYjxwVmri0Sv5XKut/onqapC+FQiC2C1lvYJ9MVco6yDYsS3AANUfMtvtbYI2hfwZatiSsnoUeMZd34GVjkMMKA+XnjJpXgRW2SHTZplVowPmJsvXy6w3cfO1AK2dvtZEKTkC/TY9LFiKHCG0DnrMQdGm2lzlBHM9iEYynH2UcVMhUEjsc0oDBTgo2ZSQ1gzkAHeWeBXYFjYLuuf8yzTCy7/RFR81WDjXMbq2BOH5dURnxo6oivmxL3cKzKInlZkD31nvpHB9Kk7GfcfE1t+1V64b9LtgeJGlpRFxQCAqWJ5DoY77ski8gsOEOr2uywZaoO/NGa0X0y1pNQHBi3b2SUGNpcZxDT7rLbBf1FSnQ8guxGW3W+36BW0gBje4DOz6Ba6SVk0xiKgt+q2JOFyr4SYfnu+Ic1QZYIuwHBrgzr6UvOcSCzPTOo7D6IC4ISeS7zkl4h+2VoeHpnG/uWR3+ysNgPcOIXQbv0n4mr3BwQcdKJxgPSeyuP/z1Jjg4e9nUvoXegqQVIE30EHx5GHv+FAVUNTowYDJgyFhf5IvlYmEqRif6+WN1MkEJmDcQITx9FX23a4mxy1AQRsOHO/+eImX9l8EMJI3oPWzVXxSOeHU1dUWYr2uAA7AMb+vAEZSbU3qob9ibCyXeypEMpZ6863o6QPqlqGHZkuWABSTVNd4cOh9hv3qEpSx2Zy/DJMP6cItEmiBJ5PFqQnDEIt3NrA3COlOSgz43D7gpNFNJ5MBh4oFzhDPiglC2ypsNU4ISywY2erkyb1NC3Qh/IfWj0eDgZI4/ln8WPfBsT3meTjq1Uqt1E7Zl/qftqkx6aM9KueMCekSnMrcHj1CqTWWzEzPsZGcDe3Ue4Ws+XFYVxNbOFF8ezkvQGR6ZOtOLU2lQEnMBStx47vE6Pb7AYMBRj2OOfZXfisjJnpTfSNjo6sZ6qSvNxZNmDeS7Gk3yYyCk1HtKN2UnhMIjOXUzAqDv90lx9O/q/AT1ZMnit5XQe9wmQxnE/WSH0CqZ9/2Hy+Sfmpeg8RwsHI5Z8kC8H293m/LHVVM/BA7HaTJYg5Enk7M/xWpq0192ACfBai2LA/qrCjCr6Dh1BIMzMXINBmX96MJ5Hn2nxln/RXPFhwHxUmSV0EV2V0jm86/dxxuYSU1W7sVkEbN9EzkG0QFwPhyHKyb3t+Fj5WoUUTErcazE/N6EW6Lvp0d//SDPj7EV9UdJN+Amnf3Wwk3A0SlJ9Z00yvXZ7n3z70G47Hfsow8Wq1JXcfwnA+Yxa5mFsgV464KKP4T31wqIgzFPd3eCe3j5ory5fBF2hgCFyVFrLzI9eetNXvM7oQqyFgDo4CTp/hDV9NMX9JDHQ/nyHTLvZLNLF6ftn2OxjGm8+PqOwhxnPHWipkE/8wbtyri80Sr7pMNkQGMfo4ZYK9OcCC4ESVFFbLMIvlxSoRqWie0wxqnLfcLSXMSpMMQEJYDVObYsXIQNv4TGNwjq1kvT1UOkicTrG3IaBZ3XdScS3u8sgeZPVpOLkbiF940FjbCeNRINNvDbd01EPBrTCPpm12m43ze1bBB59Ia6Ovhnur/Nvx3IxwSWol+3H2qfCJR8df6aQf4v6WiONxkK+IqT4pKQrZK/LplgDI/PJZbOep8dtbV7oCr6CgfpWa8NczOkPx81iSHbsNhVSJBOtrLIMrL31LK9TqHqAbAHe0RLmmV806kRLDLNEhUEJfm9u0sxpkL93Zgd6rw+tqBfTMi59xqXHLXSHwSbSBl0EK0+loECOPtrl+/nsaFe197di4yUgoe4jKoAJDXc6DGDjrQOoFDWZJ9HXwt8xDrQP+7aRwWKWI1GF8s8O4KzxWBBcwnl3vnl1Oez3oh6Ea1vjR7/z7DDTrFtqU2W/KAEzAuXDNZ7MY73MF216dzdSbWmUp4lcm7keJfWaMHgut9x5C9mj66Z0lJ+yhsjVvyiWrfk1lzPOTdhG15Y7gQlXtacvI7qv/XNSscDwqkgwHT/gUsD5yB7LdRRvJxQGYINn9hTpodKFVSTPrtGvyQw+HlRFXIkodErAGu9Iy1YpfSPc3jkFh5CX3lPxv7aqjE/JAfTIpEjGb/H7MO0e2vsViSW1qa/Lmi4/n4DEI3g7lYrcanspDfEpKkdV1OjSLOy0BCUqVoECaB55vs06rXl4jqmLsPsFM/7vYJ0vrBhDCm/00A/H81l1uekJ/6Lml3Hb9+NKiLqATJmDpyzfYZFHumEjC662L0Bwkxi7E9U4cQA0XMVDuMYAIeLMPgQaMVOd8fmt5SflFIfuBoszeAw7ow5gXPE2Y/yBc/7jExARUf/BxIHQBF5Sn3i61w4z5xJdCyO1F1X3+3ax+JSvMeZ7S6QSKp1Fp/sjYz6Z+VgCZzibGeEoujryfMulH7Rai5kAft9ebcW50DyJr2uo2z97mTWIu45YsSnNSMrrNUuG1XsYBtD9TDYzQffKB87vWbkM4EbPAFgoBV4GQS+vtFDUqOFAoi1nTtmIOvg38N4hT2Sn8r8clmBCXspBlMBYTnrqFJGBT3wZOzAyJDre9dHH7+x7qaaKDOB4UQALD5ecS0DE4obubQEiuJZ0EpBVpLuYcce8Aa4PYd/V4DLDAJBYKQPCWTcrEaZ5HYbJi11Gd6hjGom1ii18VHYnG28NKpkz2UKVPxlhYSp8uZr367iOmoy7zsxehW9wzcy2zG0a80PBMCRQMb32hnaHeOR8fnNDzZhaNYhkOdDsBUZ3loDMa1YP0uS0cjUP3b/6DBlqmZOeNABDsLl5BI5QJups8uxAuWJdkUB/pO6Zax6tsg7fN5mjjDgMGngO+DPcKqiHIDbFIGudxtPTIyDi9SFMKBDcfdGQRv41q1AqmxgkVfJMnP8w/Bc7N9/TR6C7mGObFqFkIEom8sKi2xYqJLTCHK7cxzaZvqODo22c3wisBCP4HeAgcRbNPAsBkNRhSmD48dHupdBRw4mIvtS5oeF6zeT1KMCyhMnmhpkFAGWnGscoNkwvQ8ZM5lE/vgTHFYL99OuNxdFBxTEDd5v2qLR8y9WkXsWgG6kZNndFG+pO/UAkOCipqIhL3hq7cRSdrCq7YhUsTocEcnaFa6nVkhnSeRYUA1YO0z5itF9Sly3VlxYDw239TJJH6f3EUfYO5lb7bcFcz8Bp7Oo8QmnsUHOz/fagVUBtKEw1iT88j+aKkv8cscKNkMxjYr8344D1kFoZ7/td1W6LCNYN594301tUGRmFjAzeRg5vyoM1F6+bJZ/Q54jN/k8SFd3DxPTYaAUsivsBfgTn7Mx8H2SpPt4GOdYRnEJOH6jHM2p6SgB0gzIRq6fHxGMmSmqaPCmlfwxiuloaVIitLGN8wie2CDWhkzLoCJcODh7KIOAqbHEvXdUxaS4TTTs07Clzj/6GmVs9kiZDerMxEnhUB6QQPlcfqkG9882RqHoLiHGBoHfQuXIsAG8GTAtao2KVwRnvvam8jo1e312GQAKWEa4sUVEAMG4G6ckcONDwRcg1e2D3+ohXgY4UAWF8wHKQMrSnzCgfFpsxh+aHXMGtPQroQasRY4U6UdG0rz1Vjbka0MekOGRZQEvqQFlxseFor8zWFgHek3v29+WqN6gaK5gZOTOMZzpQIC1201LkMCXild3vWXSc5UX9xcFYfbRPzGFa1FDcPfPB/jUEq/FeGt419CI3YmBlVoHsa4KdcwQP5ZSwHHhFJ7/Ph/Rap/4vmG91eDwPP0lDfCDRCLszTqfzM71xpmiKi2HwS4WlqvGNwtvwF5Dqpn6KTq8ax00UMPkxDcZrEEEsIvHiUXXEphdb4GB4FymlPwBz4Gperqq5pW7TQ6/yNRhW8VT5NhuP0udlxo4gILq5ZxAZk8ZGh3g4CqxJlPKY7AQxupfUcVpWT5VItp1+30UqoyP4wWsRo3olRRgkWZZ2ZN6VC3OZFeXB8NbnUrSdikNptD1QiGuKkr8EmSR/AK9Rw+FF3s5uwuPbvHGiPeFOViltMK7AUaOsq9+x9cndk3iJEE5LKZRlWJbKOZweROzmPNVPkjE3K/TyA57Rs68TkZ3MR8akKpm7cFjnjPd/DdkWjgYoKHSr5Wu5ssoBYU4acRs5g2DHxUmdq8VXOXRbunD8QN0LhgkssgahcdoYsNvuXGUK/KXD/7oFb+VGdhqIn02veuM5bLudJOc2Ky0GMaG4W/xWBxIJcL7yliJOXOpx0AkBqUgzlDczmLT4iILXDxxtRR1oZa2JWFgiAb43obrJnG/TZC2KSK2wqOzRZTXavZZFMb1f3bXvVaNaK828w9TO610gk8JNf3gMfETzXXsbcvRGCG9JWQZ6+cDPqc4466Yo2RcKH+PILeKOqtnlbInR3MmBeGG3FH10yzkybuqEC2HSQwpA0An7d9+73BkDUTm30bZmoP/RGbgFN+GrCOfADgqr0WbI1a1okpFms8iHYw9hm0zUvlEMivBRxModrbJJ+9/p3jUdQQ9BCtQdxnOGrT5dzRUmw0593/mbRSdBg0nRvRZM5/E16m7ZHmDEtWhwvfdZCZ8J8M12W0yRMszXamWfQTwIZ4ayYktrnscQuWr8idp3PjT2eF/jmtdhIfcpMnb+IfZY2FebW6UY/AK3jP4u3Tu4zE4qlnQgLFbM19EBIsNf7KhjdbqQ/D6yiDb+NlEi2SKD+ivXVUK8ib0oBo366gXkR8ZxGjpJIDcEgZPa9TcYe0TIbiPl/rPUQDu3XBJ9X/GNq3FAUsKsll57DzaGMrjcT+gctp+9MLYXCq+sqP81eVQ0r9lt+gcQfZbACRbEjvlMskztZG8gbC8Qn9tt26Q7y7nDrbZq/LEz7kR6Jc6pg3N9rVX8Y5MJrGlML9p9lU4jbTkKqCveeZUJjHB03m2KRKR2TytoFkTXOLg7keU1s1lrPMQJpoOKLuAAC+y1HlJucU6ysB5hsXhvSPPLq5J7JtnqHKZ4vYjC4Vy8153QY+6780xDuGARsGbOs1WqzH0QS765rnSKEbbKlkO8oI/VDwUd0is13tKpqILu1mDJFNy/iJAWcvDgjxvusIT+PGz3ST/J9r9Mtfd0jpaGeiLYIqXc7DiHSS8TcjFVksi66PEkxW1z6ujbLLUGNNYnzOWpH8BZGK4bCK7iR+MbIv8ncDAz1u4StN3vTTzewr9IQjk9wxFxn+6N1ddKs0vffJiS08N3a4G1SVrlZ97Q/M+8G9fe5AP6d9/Qq4WRnORVhofPIKEdCr3llspUfE0oKIIYoByBRPh+bX1HLS3JWGJRhIvE1aW4NTd8ePi4Z+kXb+Z8snYfSNcqijhAgVsx4RCM54cXUiYkjeBmmC4ajOHrChoELscJJC7+9jjMjw5BagZKlgRMiSNYz7h7vvZIoQqbtQmspc0cUk1G/73iXtSpROl5wtLgQi0mW2Ex8i3WULhcggx6E1LMVHUsdc9GHI1PH3U2Ko0PyGdn9KdVOLm7FPBui0i9a0HpA60MsewVE4z8CAt5d401Gv6zXlIT5Ybit1VIA0FCs7wtvYreru1fUyW3oLAZ/+aTnZrOcYRNVA8spoRtlRoWflsRClFcgzkqiHOrf0/SVw+EpVaFlJ0g4Kxq1MMOmiQdpMNpte8lMMQqm6cIFXlnGbfJllysKDi+0JJMotkqgIxOSQgU9dn/lWkeVf8nUm3iwX2Nl3WDw9i6AUK3vBAbZZrcJpDQ/N64AVwjT07Jef30GSSmtNu2WlW7YoyW2FlWfZFQUwk867EdLYKk9VG6JgEnBiBxkY7LMo4YLQJJlAo9l/oTvJkSARDF/XtyAzM8O2t3eT/iXa6wDN3WewNmQHdPfsxChU/KtLG2Mn8i4ZqKdSlIaBZadxJmRzVS/o4yA65RTSViq60oa395Lqw0pzY4SipwE0SXXsKV+GZraGSkr/RW08wPRvqvSUkYBMA9lPx4m24az+IHmCbXA+0faxTRE9wuGeO06DIXa6QlKJ3puIyiuAVfPr736vzo2pBirS+Vxel3TMm3JKhz9o2ZoRvaFVpIkykb0Hcm4oHFBMcNSNj7/4GJt43ogonY2Vg4nsDQIWxAcorpXACzgBqQPjYsE/VUpXpwNManEru4NwMCFPkXvMoqvoeLN3qyu/N1eWEHttMD65v19l/0kH2mR35iv/FI+yjoHJ9gPMz67af3Mq/BoWXqu3rphiWMXVkmnPSEkpGpUI2h1MThideGFEOK6YZHPwYzMBvpNC7+ZHxPb7epfefGyIB4JzO9DTNEYnDLVVHdQyvOEVefrk6Uv5kTQYVYWWdqrdcIl7yljwwIWdfQ/y+2QB3eR/qxYObuYyB4gTbo2in4PzarU1sO9nETkmj9/AoxDA+JM3GMqQtJR4jtduHtnoCLxd1gQUscHRB/MoRYIEsP2pDZ9KvHgtlk1iTbWWbHhohwFEYX7y51fUV2nuUmnoUcqnWIQAAgl9LTVX+Bc0QGNEhChxHR4YjfE51PUdGfsSFE6ck7BL3/hTf9jLq4G1IafINxOLKeAtO7quulYvH5YOBc+zX7CrMgWnW47/jfRsWnJjYYoE7xMfWV2HN2iyIqLI"; +const FENCED = new Map([ + [ + 8217, + "apostrophe" + ], + [ + 8260, + "fraction slash" + ], + [ + 12539, + "middle dot" + ] +]); +function decode_arithmetic(bytes) { + let pos = 0; + function u16() { + return bytes[pos++] << 8 | bytes[pos++]; } - _getCoder(param) { - switch(param.baseType){ - case "address": - return new AddressCoder(param.name); - case "bool": - return new BooleanCoder(param.name); - case "string": - return new StringCoder(param.name); - case "bytes": - return new BytesCoder(param.name); - case "array": - return new ArrayCoder(this._getCoder(param.arrayChildren), param.arrayLength, param.name); - case "tuple": - return new TupleCoder((param.components || []).map((component)=>{ - return this._getCoder(component); - }), param.name); - case "": - return new NullCoder(param.name); + let symbol_count = u16(); + let total = 1; + let acc = [ + 0, + 1 + ]; + for(let i = 1; i < symbol_count; i++){ + acc.push(total += u16()); + } + let skip = u16(); + let pos_payload = pos; + pos += skip; + let read_width = 0; + let read_buffer = 0; + function read_bit() { + if (read_width == 0) { + read_buffer = read_buffer << 8 | bytes[pos++]; + read_width = 8; } - let match = param.type.match(paramTypeNumber); - if (match) { - let size = parseInt(match[2] || "256"); - if (size === 0 || size > 256 || size % 8 !== 0) { - logger$3.throwArgumentError("invalid " + match[1] + " bit length", "param", param); + return read_buffer >> --read_width & 1; + } + const FULL = 2 ** 31; + const HALF = FULL >>> 1; + const QRTR = HALF >> 1; + const MASK = FULL - 1; + let register = 0; + for(let i = 0; i < 31; i++)register = register << 1 | read_bit(); + let symbols = []; + let low = 0; + let range = FULL; + while(true){ + let value = Math.floor(((register - low + 1) * total - 1) / range); + let start = 0; + let end = symbol_count; + while(end - start > 1){ + let mid = start + end >>> 1; + if (value < acc[mid]) { + end = mid; + } else { + start = mid; } - return new NumberCoder(size / 8, match[1] === "int", param.name); } - match = param.type.match(paramTypeBytes); - if (match) { - let size = parseInt(match[1]); - if (size === 0 || size > 32) { - logger$3.throwArgumentError("invalid bytes length", "param", param); - } - return new FixedBytesCoder(size, param.name); + if (start == 0) break; + symbols.push(start); + let a = low + Math.floor(range * acc[start] / total); + let b = low + Math.floor(range * acc[start + 1] / total) - 1; + while(((a ^ b) & HALF) == 0){ + register = register << 1 & MASK | read_bit(); + a = a << 1 & MASK; + b = b << 1 & MASK | 1; } - return logger$3.throwArgumentError("invalid type", "type", param.type); - } - _getWordSize() { - return 32; - } - _getReader(data, allowLoose) { - return new Reader(data, this._getWordSize(), this.coerceFunc, allowLoose); - } - _getWriter() { - return new Writer(this._getWordSize()); - } - getDefaultValue(types) { - const coders = types.map((type)=>this._getCoder(ParamType.from(type))); - const coder = new TupleCoder(coders, "_"); - return coder.defaultValue(); - } - encode(types, values) { - if (types.length !== values.length) { - logger$3.throwError("types/values length mismatch", Logger.errors.INVALID_ARGUMENT, { - count: { - types: types.length, - values: values.length - }, - value: { - types, - values - } - }); + while(a & ~b & QRTR){ + register = register & HALF | register << 1 & MASK >>> 1 | read_bit(); + a = a << 1 ^ HALF; + b = (b ^ HALF) << 1 | HALF | 1; } - const coders = types.map((type)=>this._getCoder(ParamType.from(type))); - const coder = new TupleCoder(coders, "_"); - const writer = this._getWriter(); - coder.encode(writer, values); - return writer.data; - } - decode(types, data, loose) { - const coders = types.map((type)=>this._getCoder(ParamType.from(type))); - const coder = new TupleCoder(coders, "_"); - return coder.decode(this._getReader(arrayify(data), loose)); + low = a; + range = 1 + b - a; } + let offset = symbol_count - 4; + return symbols.map((x)=>{ + switch(x - offset){ + case 3: + return offset + 65792 + (bytes[pos_payload++] << 16 | bytes[pos_payload++] << 8 | bytes[pos_payload++]); + case 2: + return offset + 256 + (bytes[pos_payload++] << 8 | bytes[pos_payload++]); + case 1: + return offset + bytes[pos_payload++]; + default: + return x - 1; + } + }); } -const defaultAbiCoder = new AbiCoder(); -const logger$4 = new Logger(version9); -class LogDescription extends Description { -} -class TransactionDescription extends Description { +function read_payload(v) { + let pos = 0; + return ()=>v[pos++]; } -class ErrorDescription extends Description { +function read_compressed_payload(s) { + return read_payload(decode_arithmetic(unsafe_atob(s))); } -class Indexed extends Description { - static isIndexed(value) { - return !!(value && value._isIndexed); +function unsafe_atob(s) { + let lookup = []; + [ + ..."ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + ].forEach((c, i)=>lookup[c.charCodeAt(0)] = i); + let n = s.length; + let ret = new Uint8Array(6 * n >> 3); + for(let i = 0, pos = 0, width = 0, carry = 0; i < n; i++){ + carry = carry << 6 | lookup[s.charCodeAt(i)]; + width += 6; + if (width >= 8) { + ret[pos++] = carry >> (width -= 8); + } } + return ret; } -const BuiltinErrors = { - "0x08c379a0": { - signature: "Error(string)", - name: "Error", - inputs: [ - "string" - ], - reason: true - }, - "0x4e487b71": { - signature: "Panic(uint256)", - name: "Panic", - inputs: [ - "uint256" - ] - } -}; -function wrapAccessError(property, error) { - const wrap = new Error(`deferred error during ABI decoding triggered accessing ${property}`); - wrap.error = error; - return wrap; +function signed(i) { + return i & 1 ? ~i >> 1 : i >> 1; } -class Interface { - constructor(fragments){ - let abi = []; - if (typeof fragments === "string") { - abi = JSON.parse(fragments); - } else { - abi = fragments; - } - defineReadOnly(this, "fragments", abi.map((fragment)=>{ - return Fragment.from(fragment); - }).filter((fragment)=>fragment != null)); - defineReadOnly(this, "_abiCoder", getStatic(new.target, "getAbiCoder")()); - defineReadOnly(this, "functions", {}); - defineReadOnly(this, "errors", {}); - defineReadOnly(this, "events", {}); - defineReadOnly(this, "structs", {}); - this.fragments.forEach((fragment)=>{ - let bucket = null; - switch(fragment.type){ - case "constructor": - if (this.deploy) { - logger$4.warn("duplicate definition - constructor"); - return; - } - defineReadOnly(this, "deploy", fragment); - return; - case "function": - bucket = this.functions; - break; - case "event": - bucket = this.events; - break; - case "error": - bucket = this.errors; - break; - default: - return; - } - let signature = fragment.format(); - if (bucket[signature]) { - logger$4.warn("duplicate definition - " + signature); - return; - } - bucket[signature] = fragment; - }); - if (!this.deploy) { - defineReadOnly(this, "deploy", ConstructorFragment.from({ - payable: false, - type: "constructor" - })); +function read_deltas(n, next) { + let v = Array(n); + for(let i = 0, x = 0; i < n; i++)v[i] = x += signed(next()); + return v; +} +function read_sorted(next, prev = 0) { + let ret = []; + while(true){ + let x = next(); + let n = next(); + if (!n) break; + prev += x; + for(let i = 0; i < n; i++){ + ret.push(prev + i); } - defineReadOnly(this, "_isInterface", true); + prev += n + 1; } - format(format) { - if (!format) { - format = FormatTypes.full; - } - if (format === FormatTypes.sighash) { - logger$4.throwArgumentError("interface does not support formatting sighash", "format", format); - } - const abi = this.fragments.map((fragment)=>fragment.format(format)); - if (format === FormatTypes.json) { - return JSON.stringify(abi.map((j)=>JSON.parse(j))); - } - return abi; + return ret; +} +function read_sorted_arrays(next) { + return read_array_while(()=>{ + let v = read_sorted(next); + if (v.length) return v; + }); +} +function read_mapped(next) { + let ret = []; + while(true){ + let w = next(); + if (w == 0) break; + ret.push(read_linear_table(w, next)); } - static getAbiCoder() { - return defaultAbiCoder; + while(true){ + let w = next() - 1; + if (w < 0) break; + ret.push(read_replacement_table(w, next)); } - static getAddress(address2) { - return getAddress(address2); + return ret.flat(); +} +function read_array_while(next) { + let v = []; + while(true){ + let x = next(v.length); + if (!x) break; + v.push(x); } - static getSighash(fragment) { - return hexDataSlice(id(fragment.format()), 0, 4); + return v; +} +function read_transposed(n, w, next) { + let m = Array(n).fill().map(()=>[]); + for(let i = 0; i < w; i++){ + read_deltas(n, next).forEach((x, j)=>m[j].push(x)); } - static getEventTopic(eventFragment) { - return id(eventFragment.format()); + return m; +} +function read_linear_table(w, next) { + let dx = 1 + next(); + let dy = next(); + let vN = read_array_while(next); + let m = read_transposed(vN.length, 1 + w, next); + return m.flatMap((v, i)=>{ + let [x, ...ys] = v; + return Array(vN[i]).fill().map((_, j)=>{ + let j_dy = j * dy; + return [ + x + j * dx, + ys.map((y)=>y + j_dy) + ]; + }); + }); +} +function read_replacement_table(w, next) { + let n = 1 + next(); + let m = read_transposed(n, 1 + w, next); + return m.map((v)=>[ + v[0], + v.slice(1) + ]); +} +function read_trie(next) { + let ret = []; + let sorted = read_sorted(next); + expand(decode([]), []); + return ret; + function decode(Q) { + let S = next(); + let B = read_array_while(()=>{ + let cps = read_sorted(next).map((i)=>sorted[i]); + if (cps.length) return decode(cps); + }); + return { + S: S, + B: B, + Q: Q + }; } - getFunction(nameOrSignatureOrSighash) { - if (isHexString(nameOrSignatureOrSighash)) { - for(const name in this.functions){ - if (nameOrSignatureOrSighash === this.getSighash(name)) { - return this.functions[name]; - } + function expand({ S, B }, cps, saved) { + if (S & 4 && saved === cps[cps.length - 1]) return; + if (S & 2) saved = cps[cps.length - 1]; + if (S & 1) ret.push(cps); + for (let br of B){ + for (let cp of br.Q){ + expand(br, [ + ...cps, + cp + ], saved); } - logger$4.throwArgumentError("no matching function", "sighash", nameOrSignatureOrSighash); } - if (nameOrSignatureOrSighash.indexOf("(") === -1) { - const name = nameOrSignatureOrSighash.trim(); - const matching = Object.keys(this.functions).filter((f)=>f.split("(")[0] === name); - if (matching.length === 0) { - logger$4.throwArgumentError("no matching function", "name", name); - } else if (matching.length > 1) { - logger$4.throwArgumentError("multiple matching functions", "name", name); + } +} +function hex_cp(cp) { + return cp.toString(16).toUpperCase().padStart(2, "0"); +} +function quote_cp(cp) { + return `{${hex_cp(cp)}}`; +} +function explode_cp(s) { + let cps = []; + for(let pos = 0, len = s.length; pos < len;){ + let cp = s.codePointAt(pos); + pos += cp < 65536 ? 1 : 2; + cps.push(cp); + } + return cps; +} +function str_from_cps(cps) { + const chunk = 4096; + let len = cps.length; + if (len < 4096) return String.fromCodePoint(...cps); + let buf = []; + for(let i = 0; i < len;){ + buf.push(String.fromCodePoint(...cps.slice(i, i += chunk))); + } + return buf.join(""); +} +function compare_arrays(a, b) { + let n = a.length; + let c = n - b.length; + for(let i = 0; c == 0 && i < n; i++)c = a[i] - b[i]; + return c; +} +var COMPRESSED = "AEUDTAHBCFQATQDRADAAcgAgADQAFAAsABQAHwAOACQADQARAAoAFwAHABIACAAPAAUACwAFAAwABAAQAAMABwAEAAoABQAIAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACgANAA0AAwAKAAkABAAdAAYAZwDSAdsDJgC0CkMB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSMEEEl5RFVMKvO0XQ8ExDdJMnIgsj26PTQyy8FfEQ8AY8IPAGcEbwRwBHEEcgRzBHQEdQR2BHcEeAR6BHsEfAR+BIAEgfndBQoBYgULAWIFDAFiBNcE2ATZBRAFEQUvBdALFAsVDPcNBw13DYcOMA4xDjMB4BllHI0B2grbAMDpHLkQ7QHVAPRNQQFnGRUEg0yEB2uaJF8AJpIBpob5AERSMAKNoAXqaQLUBMCzEiACnwRZEkkVsS7tANAsBG0RuAQLEPABv9HICTUBXigPZwRBApMDOwAamhtaABqEAY8KvKx3LQ4ArAB8UhwEBAVSagD8AEFZADkBIadVj2UMUgx5Il4ANQC9AxIB1BlbEPMAs30CGxlXAhwZKQIECBc6EbsCoxngzv7UzRQA8M0BawL6ZwkN7wABAD33OQRcsgLJCjMCjqUChtw/km+NAsXPAoP2BT84PwURAK0RAvptb6cApQS/OMMey5HJS84UdxpxTPkCogVFITaTOwERAK5pAvkNBOVyA7q3BKlOJSALAgUIBRcEdASpBXqzABXFSWZOawLCOqw//AolCZdvv3dSBkEQGyelEPcMMwG1ATsN7UvYBPEGOwTJH30ZGQ/NlZwIpS3dDO0m4y6hgFoj9SqDBe1L9DzdC01RaA9ZC2UJ4zpjgU4DIQENIosK3Q05CG0Q8wrJaw3lEUUHOQPVSZoApQcBCxEdNRW1JhBirAsJOXcG+xr2C48mrxMpevwF0xohBk0BKRr/AM8u54WwWjFcHE9fBgMLJSPHFKhQIA0lQLd4SBobBxUlqQKRQ3BKh1E2HpMh9jw9DWYuE1F8B/U8BRlPC4E8nkarRQ4R0j6NPUgiSUwsBDV/LC8niwnPD4UMuXxyAVkJIQmxDHETMREXN8UIOQcZLZckJxUIIUaVYJoE958D8xPRAwsFPwlBBxMDtRwtEy4VKQUNgSTXAvM21S6zAo9WgAEXBcsPJR/fEFBH4A7pCJsCZQODJesALRUhABcimwhDYwBfj9hTBS7LCMdqbCN0A2cU52ERcweRDlcHpxwzFb8c4XDIXguGCCijrwlbAXUJmQFfBOMICTVbjKAgQWdTi1gYmyBhQT9d/AIxDGUVn0S9h3gCiw9rEhsBNQFzBzkNAQJ3Ee0RaxCVCOuGBDW1M/g6JQRPIYMgEQonA09szgsnJvkM+GkBoxJiAww0PXfuZ6tgtiQX/QcZMsVBYCHxC5JPzQycGsEYQlQuGeQHvwPzGvMn6kFXBf8DowMTOk0z7gS9C2kIiwk/AEkOoxcH1xhqCnGM0AExiwG3mQNXkYMCb48GNwcLAGcLhwV55QAdAqcIowAFAM8DVwA5Aq0HnQAZAIVBAT0DJy8BIeUCjwOTCDHLAZUvAfMpBBvDDBUA9zduSgLDsQKAamaiBd1YAo4CSTUBTSUEBU5HUQOvceEA2wBLBhPfRwEVq0rLGuNDAd9vKwDHAPsABTUHBUEBzQHzbQC3AV8LMQmis7UBTekpAIMAFWsB1wKJAN0ANQB/8QFTAE0FWfkF0wJPSQERMRgrV2EBuwMfATMBDQB5BsuNpckHHwRtB9MCEBsV4QLvLge1AQMi3xPNQsUCvd5VoWACZIECYkJbTa9bNyACofcCaJgCZgkCn4Q4GwsCZjsCZiYEbgR/A38TA36SOQY5dxc5gjojIwJsHQIyNjgKAm3HAm2u74ozZ0UrAWcA3gDhAEoFB5gMjQD+C8IADbUCdy8CdqI/AnlLQwJ4uh1c20WuRtcCfD8CesgCfQkCfPAFWQUgSABIfWMkAoFtAoAAAoAFAn+uSVhKWxUXSswC0QEC0MxLJwOITwOH5kTFkTIC8qFdAwMDrkvOTC0lA89NTE2vAos/AorYwRsHHUNnBbcCjjcCjlxAl4ECjtkCjlx4UbRTNQpS1FSFApP7ApMMAOkAHFUeVa9V0AYsGymVhjLheGZFOzkCl58C77JYIagAWSUClo8ClnycAKlZrFoJgU0AOwKWtQKWTlxEXNECmcsCmWRcyl0HGQKcmznCOp0CnBYCn5sCnriKAB0PMSoPAp3xAp6SALU9YTRh7wKe0wKgbgGpAp6fHwKeTqVjyGQnJSsCJ68CJn4CoPsCoEwCot0CocQCpi8Cpc4Cp/8AfQKn8mh8aLEAA0lqHGrRAqzjAqyuAq1nAq0CAlcdAlXcArHh1wMfTmyXArK9DQKy6Bds4G1jbUhfAyXNArZcOz9ukAMpRQK4XgK5RxUCuSp3cDZw4QK9GQK72nCWAzIRAr6IcgIDM3ECvhpzInNPAsPLAsMEc4J0SzVFdOADPKcDPJoDPb8CxXwCxkcCxhCJAshpUQLIRALJTwLJLgJknQLd0nh5YXiueSVL0AMYo2cCAmH0GfOVJHsLXpJeuxECz2sCz2wvS1PS8xOfAMatAs9zASnqA04SfksFAtwnAtuKAtJPA1JcA1NfAQEDVYyAiT8AyxbtYEWCHILTgs6DjQLaxwLZ3oQQhEmnPAOGpQAvA2QOhnFZ+QBVAt9lAt64c3cC4i/tFAHzMCcB9JsB8tKHAuvzAulweQLq+QLq5AD5RwG5Au6JAuuclqqXAwLuPwOF4Jh5cOBxoQLzAwBpA44WmZMC9xMDkW4DkocC95gC+dkC+GaaHJqruzebHgOdgwL++gEbADmfHJ+zAwWNA6ZqA6bZANHFAwZqoYiiBQkDDEkCwAA/AwDhQRdTARHzA2sHl2cFAJMtK7evvdsBiZkUfxEEOQH7KQUhDp0JnwCS/SlXxQL3AZ0AtwW5AG8LbUEuFCaNLgFDAYD8AbUmAHUDDgRtACwCFgyhAAAKAj0CagPdA34EkQEgRQUhfAoABQBEABMANhICdwEABdUDa+8KxQIA9wqfJ7+xt+UBkSFBQgHpFH8RNMCJAAQAGwBaAkUChIsABjpTOpSNbQC4Oo860ACNOME63AClAOgAywE6gTo7Ofw5+Tt2iTpbO56JOm85GAFWATMBbAUvNV01njWtNWY1dTW2NcU1gjWRNdI14TWeNa017jX9NbI1wTYCNhE1xjXVNhY2JzXeNe02LjY9Ni41LSE2OjY9Njw2yTcIBJA8VzY4Nt03IDcPNsogN4k3MAoEsDxnNiQ3GTdsOo03IULUQwdC4EMLHA8PCZsobShRVQYA6X8A6bABFCnXAukBowC9BbcAbwNzBL8MDAMMAQgDAAkKCwsLCQoGBAVVBI/DvwDz9b29kaUCb0QtsRTNLt4eGBcSHAMZFhYZEhYEARAEBUEcQRxBHEEcQRxBHEEaQRxBHEFCSTxBPElISUhBNkM2QTYbNklISVmBVIgBFLWZAu0BhQCjBcEAbykBvwGJAaQcEZ0ePCklMAAhMvAIMAL54gC7Bm8EescjzQMpARQpKgDUABavAj626xQAJP0A3etzuf4NNRA7efy2Z9NQrCnC0OSyANz5BBIbJ5IFDR6miIavYS6tprjjmuKebxm5C74Q225X1pkaYYPb6f1DK4k3xMEBb9S2WMjEibTNWhsRJIA+vwNVEiXTE5iXs/wezV66oFLfp9NZGYW+Gk19J2+bCT6Ye2w6LDYdgzKMUabk595eLBCXANz9HUpWbATq9vqXVx9XDg+Pc9Xp4+bsS005SVM/BJBM4687WUuf+Uj9dEi8aDNaPxtpbDxcG1THTImUMZq4UCaaNYpsVqraNyKLJXDYsFZ/5jl7bLRtO88t7P3xZaAxhb5OdPMXqsSkp1WCieG8jXm1U99+blvLlXzPCS+M93VnJCiK+09LfaSaBAVBomyDgJua8dfUzR7ga34IvR2Nvj+A9heJ6lsl1KG4NkI1032Cnff1m1wof2B9oHJK4bi6JkEdSqeNeiuo6QoZZincoc73/TH9SXF8sCE7XyuYyW8WSgbGFCjPV0ihLKhdPs08Tx82fYAkLLc4I2wdl4apY7GU5lHRFzRWJep7Ww3wbeA3qmd59/86P4xuNaqDpygXt6M85glSBHOCGgJDnt+pN9bK7HApMguX6+06RZNjzVmcZJ+wcUrJ9//bpRNxNuKpNl9uFds+S9tdx7LaM5ZkIrPj6nIU9mnbFtVbs9s/uLgl8MVczAwet+iOEzzBlYW7RCMgE6gyNLeq6+1tIx4dpgZnd0DksJS5f+JNDpwwcPNXaaVspq1fbQajOrJgK0ofKtJ1Ne90L6VO4MOl5S886p7u6xo7OLjG8TGL+HU1JXGJgppg4nNbNJ5nlzSpuPYy21JUEcUA94PoFiZfjZue+QnyQ80ekOuZVkxx4g+cvhJfHgNl4hy1/a6+RKcKlar/J29y//EztlbVPHVUeQ1zX86eQVAjR/M3dA9w4W8LfaXp4EgM85wOWasli837PzVMOnsLzR+k3o75/lRPAJSE1xAKQzEi5v10ke+VBvRt1cwQRMd+U5mLCTGVd6XiZtgBG5cDi0w22GKcVNvHiu5LQbZEDVtz0onn7k5+heuKXVsZtSzilkLRAUmjMXEMB3J9YC50XBxPiz53SC+EhnPl9WsKCv92SM/OFFIMJZYfl0WW8tIO3UxYcwdMAj7FSmgrsZ2aAZO03BOhP1bNNZItyXYQFTpC3SG1VuPDqH9GkiCDmE+JwxyIVSO5siDErAOpEXFgjy6PQtOVDj+s6e1r8heWVvmZnTciuf4EiNZzCAd7SOMhXERIOlsHIMG399i9aLTy3m2hRLZjJVDNLS53iGIK11dPqQt0zBDyg6qc7YqkDm2M5Ve6dCWCaCbTXX2rToaIgz6+zh4lYUi/+6nqcFMAkQJKHYLK0wYk5N9szV6xihDbDDFr45lN1K4aCXBq/FitPSud9gLt5ZVn+ZqGX7cwm2z5EGMgfFpIFyhGGuDPmso6TItTMwny+7uPnLCf4W6goFQFV0oQSsc9VfMmVLcLr6ZetDZbaSFTLqnSO/bIPjA3/zAUoqgGFAEQS4IhuMzEp2I3jJzbzkk/IEmyax+rhZTwd6f+CGtwPixu8IvzACquPWPREu9ZvGkUzpRwvRRuaNN6cr0W1wWits9ICdYJ7ltbgMiSL3sTPeufgNcVqMVWFkCPDH4jG2jA0XcVgQj62Cb29v9f/z/+2KbYvIv/zzjpQAPkliaVDzNrW57TZ/ZOyZD0nlfMmAIBIAGAI0D3k/mdN4xr9v85ZbZbbqfH2jGd5hUqNZWwl5SPfoGmfElmazUIeNL1j/mkF7VNAzTq4jNt8JoQ11NQOcmhprXoxSxfRGJ9LDEOAQ+dmxAQH90iti9e2u/MoeuaGcDTHoC+xsmEeWmxEKefQuIzHbpw5Tc5cEocboAD09oipWQhtTO1wivf/O+DRe2rpl/E9wlrzBorjJsOeG1B/XPW4EaJEFdNlECEZga5ZoGRHXgYouGRuVkm8tDESiEyFNo+3s5M5puSdTyUL2llnINVHEt91XUNW4ewdMgJ4boJfEyt/iY5WXqbA+A2Fkt5Z0lutiWhe9nZIyIUjyXDC3UsaG1t+eNx6z4W/OYoTB7A6x+dNSTOi9AInctbESqm5gvOLww7OWXPrmHwVZasrl4eD113pm+JtT7JVOvnCXqdzzdTRHgJ0PiGTFYW5Gvt9R9LD6Lzfs0v/TZZHSmyVNq7viIHE6DBK7Qp07Iz55EM8SYtQvZf/obBniTWi5C2/ovHfw4VndkE5XYdjOhCMRjDeOEfXeN/CwfGduiUIfsoFeUxXeQXba7c7972XNv8w+dTjjUM0QeNAReW+J014dKAD/McQYXT7c0GQPIkn3Ll6R7gGjuiQoZD0TEeEqQpKoZ15g/0OPQI17QiSv9AUROa/V/TQN3dvLArec3RrsYlvBm1b8LWzltdugsC50lNKYLEp2a+ZZYqPejULRlOJh5zj/LVMyTDvwKhMxxwuDkxJ1QpoNI0OTWLom4Z71SNzI9TV1iXJrIu9Wcnd+MCaAw8o1jSXd94YU/1gnkrC9BUEOtQvEIQ7g0i6h+KL2JKk8Ydl7HruvgWMSAmNe+LshGhV4qnWHhO9/RIPQzY1tHRj2VqOyNsDpK0cww+56AdDC4gsWwY0XxoucIWIqs/GcwnWqlaT0KPr8mbK5U94/301i1WLt4YINTVvCFBrFZbIbY8eycOdeJ2teD5IfPLCRg7jjcFTwlMFNl9zdh/o3E/hHPwj7BWg0MU09pPrBLbrCgm54A6H+I6v27+jL5gkjWg/iYdks9jbfVP5y/n0dlgWEMlKasl7JvFZd56LfybW1eeaVO0gxTfXZwD8G4SI116yx7UKVRgui6Ya1YpixqXeNLc8IxtAwCU5IhwQgn+NqHnRaDv61CxKhOq4pOX7M6pkA+Pmpd4j1vn6ACUALoLLc4vpXci8VidLxzm7qFBe7s+quuJs6ETYmnpgS3LwSZxPIltgBDXz8M1k/W2ySNv2f9/NPhxLGK2D21dkHeSGmenRT3Yqcdl0m/h3OYr8V+lXNYGf8aCCpd4bWjE4QIPj7vUKN4Nrfs7ML6Y2OyS830JCnofg/k7lpFpt4SqZc5HGg1HCOrHvOdC8bP6FGDbE/VV0mX4IakzbdS/op+Kt3G24/8QbBV7y86sGSQ/vZzU8FXs7u6jIvwchsEP2BpIhW3G8uWNwa3HmjfH/ZjhhCWvluAcF+nMf14ClKg5hGgtPLJ98ueNAkc5Hs2WZlk2QHvfreCK1CCGO6nMZVSb99VM/ajr8WHTte9JSmkXq/i/U943HEbdzW6Re/S88dKgg8pGOLlAeNiqrcLkUR3/aClFpMXcOUP3rmETcWSfMXZE3TUOi8i+fqRnTYLflVx/Vb/6GJ7eIRZUA6k3RYR3iFSK9c4iDdNwJuZL2FKz/IK5VimcNWEqdXjSoxSgmF0UPlDoUlNrPcM7ftmA8Y9gKiqKEHuWN+AZRIwtVSxye2Kf8rM3lhJ5XcBXU9n4v0Oy1RU2M+4qM8AQPVwse8ErNSob5oFPWxuqZnVzo1qB/IBxkM3EVUKFUUlO3e51259GgNcJbCmlvrdjtoTW7rChm1wyCKzpCTwozUUEOIcWLneRLgMXh+SjGSFkAllzbGS5HK7LlfCMRNRDSvbQPjcXaenNYxCvu2Qyznz6StuxVj66SgI0T8B6/sfHAJYZaZ78thjOSIFumNWLQbeZixDCCC+v0YBtkxiBB3jefHqZ/dFHU+crbj6OvS1x/JDD7vlm7zOVPwpUC01nhxZuY/63E7g"; +const N_COUNT = 21 * 28; +const S_COUNT = 19 * N_COUNT; +const S1 = 44032 + S_COUNT; +const L1 = 4352 + 19; +const V1 = 4449 + 21; +const T1$1 = 4519 + 28; +function unpack_cc(packed) { + return packed >> 24 & 255; +} +function unpack_cp(packed) { + return packed & 16777215; +} +let SHIFTED_RANK, EXCLUSIONS, DECOMP, RECOMP; +function init$1() { + let r = read_compressed_payload(COMPRESSED); + SHIFTED_RANK = new Map(read_sorted_arrays(r).flatMap((v, i)=>v.map((x)=>[ + x, + i + 1 << 24 + ]))); + EXCLUSIONS = new Set(read_sorted(r)); + DECOMP = new Map; + RECOMP = new Map; + for (let [cp, cps] of read_mapped(r)){ + if (!EXCLUSIONS.has(cp) && cps.length == 2) { + let [a, b] = cps; + let bucket = RECOMP.get(a); + if (!bucket) { + bucket = new Map; + RECOMP.set(a, bucket); + } + bucket.set(b, cp); + } + DECOMP.set(cp, cps.reverse()); + } +} +function is_hangul(cp) { + return cp >= 44032 && cp < S1; +} +function compose_pair(a, b) { + if (a >= 4352 && a < L1 && b >= 4449 && b < V1) { + return 44032 + (a - 4352) * N_COUNT + (b - 4449) * 28; + } else if (is_hangul(a) && b > 4519 && b < T1$1 && (a - 44032) % 28 == 0) { + return a + (b - 4519); + } else { + let recomp = RECOMP.get(a); + if (recomp) { + recomp = recomp.get(b); + if (recomp) { + return recomp; } - return this.functions[matching[0]]; } - const result = this.functions[FunctionFragment.fromString(nameOrSignatureOrSighash).format()]; - if (!result) { - logger$4.throwArgumentError("no matching function", "signature", nameOrSignatureOrSighash); + return -1; + } +} +function decomposed(cps) { + if (!SHIFTED_RANK) init$1(); + let ret = []; + let buf = []; + let check_order = false; + function add(cp) { + let cc = SHIFTED_RANK.get(cp); + if (cc) { + check_order = true; + cp |= cc; } - return result; + ret.push(cp); } - getEvent(nameOrSignatureOrTopic) { - if (isHexString(nameOrSignatureOrTopic)) { - const topichash = nameOrSignatureOrTopic.toLowerCase(); - for(const name in this.events){ - if (topichash === this.getEventTopic(name)) { - return this.events[name]; + for (let cp of cps){ + while(true){ + if (cp < 128) { + ret.push(cp); + } else if (is_hangul(cp)) { + let s_index = cp - 44032; + let l_index = s_index / N_COUNT | 0; + let v_index = s_index % N_COUNT / 28 | 0; + let t_index = s_index % 28; + add(4352 + l_index); + add(4449 + v_index); + if (t_index > 0) add(4519 + t_index); + } else { + let mapped = DECOMP.get(cp); + if (mapped) { + buf.push(...mapped); + } else { + add(cp); } } - logger$4.throwArgumentError("no matching event", "topichash", topichash); + if (!buf.length) break; + cp = buf.pop(); } - if (nameOrSignatureOrTopic.indexOf("(") === -1) { - const name = nameOrSignatureOrTopic.trim(); - const matching = Object.keys(this.events).filter((f)=>f.split("(")[0] === name); - if (matching.length === 0) { - logger$4.throwArgumentError("no matching event", "name", name); - } else if (matching.length > 1) { - logger$4.throwArgumentError("multiple matching events", "name", name); + } + if (check_order && ret.length > 1) { + let prev_cc = unpack_cc(ret[0]); + for(let i = 1; i < ret.length; i++){ + let cc = unpack_cc(ret[i]); + if (cc == 0 || prev_cc <= cc) { + prev_cc = cc; + continue; + } + let j = i - 1; + while(true){ + let tmp = ret[j + 1]; + ret[j + 1] = ret[j]; + ret[j] = tmp; + if (!j) break; + prev_cc = unpack_cc(ret[--j]); + if (prev_cc <= cc) break; } - return this.events[matching[0]]; + prev_cc = unpack_cc(ret[i]); } - const result = this.events[EventFragment.fromString(nameOrSignatureOrTopic).format()]; - if (!result) { - logger$4.throwArgumentError("no matching event", "signature", nameOrSignatureOrTopic); + } + return ret; +} +function composed_from_decomposed(v) { + let ret = []; + let stack = []; + let prev_cp = -1; + let prev_cc = 0; + for (let packed of v){ + let cc = unpack_cc(packed); + let cp = unpack_cp(packed); + if (prev_cp == -1) { + if (cc == 0) { + prev_cp = cp; + } else { + ret.push(cp); + } + } else if (prev_cc > 0 && prev_cc >= cc) { + if (cc == 0) { + ret.push(prev_cp, ...stack); + stack.length = 0; + prev_cp = cp; + } else { + stack.push(cp); + } + prev_cc = cc; + } else { + let composed = compose_pair(prev_cp, cp); + if (composed >= 0) { + prev_cp = composed; + } else if (prev_cc == 0 && cc == 0) { + ret.push(prev_cp); + prev_cp = cp; + } else { + stack.push(cp); + prev_cc = cc; + } } - return result; } - getError(nameOrSignatureOrSighash) { - if (isHexString(nameOrSignatureOrSighash)) { - const getSighash = getStatic(this.constructor, "getSighash"); - for(const name in this.errors){ - const error = this.errors[name]; - if (nameOrSignatureOrSighash === getSighash(error)) { - return this.errors[name]; - } + if (prev_cp >= 0) { + ret.push(prev_cp, ...stack); + } + return ret; +} +function nfd(cps) { + return decomposed(cps).map(unpack_cp); +} +function nfc(cps) { + return composed_from_decomposed(decomposed(cps)); +} +const STOP_CH = "."; +const Array_from = (x)=>Array.from(x); +function group_has_cp(g, cp) { + return g.P.has(cp) || g.Q.has(cp); +} +class Emoji extends Array { + get is_emoji() { + return true; + } +} +let MAPPED, IGNORED, CM, NSM, ESCAPE, GROUPS, WHOLE_VALID, WHOLE_MAP, VALID, EMOJI_LIST, EMOJI_ROOT; +function init() { + if (MAPPED) return; + let r = read_compressed_payload(COMPRESSED$1); + const read_sorted_array = ()=>read_sorted(r); + const read_sorted_set = ()=>new Set(read_sorted_array()); + const set_add_many = (set, v)=>v.forEach((x)=>set.add(x)); + MAPPED = new Map(read_mapped(r)); + IGNORED = read_sorted_set(); + CM = read_sorted_array(); + NSM = new Set(read_sorted_array().map((i)=>CM[i])); + CM = new Set(CM); + ESCAPE = read_sorted_set(); + read_sorted_set(); + let chunks = read_sorted_arrays(r); + let unrestricted = r(); + const read_chunked = ()=>{ + let set = new Set; + read_sorted_array().forEach((i)=>set_add_many(set, chunks[i])); + set_add_many(set, read_sorted_array()); + return set; + }; + GROUPS = read_array_while((i)=>{ + let N = read_array_while(r).map((x)=>x + 96); + if (N.length) { + let R = i >= unrestricted; + N[0] -= 32; + N = str_from_cps(N); + if (R) N = `Restricted[${N}]`; + let P = read_chunked(); + let Q = read_chunked(); + let M = !r(); + return { + N: N, + P: P, + Q: Q, + M: M, + R: R + }; + } + }); + WHOLE_VALID = read_sorted_set(); + WHOLE_MAP = new Map; + let wholes = read_sorted_array().concat(Array_from(WHOLE_VALID)).sort((a, b)=>a - b); + wholes.forEach((cp, i)=>{ + let d = r(); + let w = wholes[i] = d ? wholes[i - d] : { + V: [], + M: new Map + }; + w.V.push(cp); + if (!WHOLE_VALID.has(cp)) { + WHOLE_MAP.set(cp, w); + } + }); + for (let { V, M } of new Set(WHOLE_MAP.values())){ + let recs = []; + for (let cp of V){ + let gs = GROUPS.filter((g)=>group_has_cp(g, cp)); + let rec = recs.find(({ G })=>gs.some((g)=>G.has(g))); + if (!rec) { + rec = { + G: new Set, + V: [] + }; + recs.push(rec); } - logger$4.throwArgumentError("no matching error", "sighash", nameOrSignatureOrSighash); + rec.V.push(cp); + set_add_many(rec.G, gs); } - if (nameOrSignatureOrSighash.indexOf("(") === -1) { - const name = nameOrSignatureOrSighash.trim(); - const matching = Object.keys(this.errors).filter((f)=>f.split("(")[0] === name); - if (matching.length === 0) { - logger$4.throwArgumentError("no matching error", "name", name); - } else if (matching.length > 1) { - logger$4.throwArgumentError("multiple matching errors", "name", name); + let union = recs.flatMap((x)=>Array_from(x.G)); + for (let { G, V } of recs){ + let complement = new Set(union.filter((g)=>!G.has(g))); + for (let cp of V){ + M.set(cp, complement); } - return this.errors[matching[0]]; } - const result = this.errors[FunctionFragment.fromString(nameOrSignatureOrSighash).format()]; - if (!result) { - logger$4.throwArgumentError("no matching error", "signature", nameOrSignatureOrSighash); + } + VALID = new Set; + let multi = new Set; + const add_to_union = (cp)=>VALID.has(cp) ? multi.add(cp) : VALID.add(cp); + for (let g of GROUPS){ + for (let cp of g.P)add_to_union(cp); + for (let cp of g.Q)add_to_union(cp); + } + for (let cp of VALID){ + if (!WHOLE_MAP.has(cp) && !multi.has(cp)) { + WHOLE_MAP.set(cp, 1); } - return result; } - getSighash(fragment) { - if (typeof fragment === "string") { - try { - fragment = this.getFunction(fragment); - } catch (error) { - try { - fragment = this.getError(fragment); - } catch (_) { - throw error; - } + set_add_many(VALID, nfd(VALID)); + EMOJI_LIST = read_trie(r).map((v)=>Emoji.from(v)).sort(compare_arrays); + EMOJI_ROOT = new Map; + for (let cps of EMOJI_LIST){ + let prev = [ + EMOJI_ROOT + ]; + for (let cp of cps){ + let next = prev.map((node)=>{ + let child = node.get(cp); + if (!child) { + child = new Map; + node.set(cp, child); + } + return child; + }); + if (cp === 65039) { + prev.push(...next); + } else { + prev = next; } } - return getStatic(this.constructor, "getSighash")(fragment); + for (let x of prev){ + x.V = cps; + } + } +} +function quoted_cp(cp) { + return (should_escape(cp) ? "" : `${bidi_qq(safe_str_from_cps([ + cp + ]))} `) + quote_cp(cp); +} +function bidi_qq(s) { + return `"${s}"\u200E`; +} +function check_label_extension(cps) { + if (cps.length >= 4 && cps[2] == 45 && cps[3] == 45) { + throw new Error(`invalid label extension: "${str_from_cps(cps.slice(0, 4))}"`); } - getEventTopic(eventFragment) { - if (typeof eventFragment === "string") { - eventFragment = this.getEvent(eventFragment); +} +function check_leading_underscore(cps) { + for(let i = cps.lastIndexOf(95); i > 0;){ + if (cps[--i] !== 95) { + throw new Error("underscore allowed only at start"); } - return getStatic(this.constructor, "getEventTopic")(eventFragment); } - _decodeParams(params, data) { - return this._abiCoder.decode(params, data); +} +function check_fenced(cps) { + let cp = cps[0]; + let prev = FENCED.get(cp); + if (prev) throw error_placement(`leading ${prev}`); + let n = cps.length; + let last = -1; + for(let i = 1; i < n; i++){ + cp = cps[i]; + let match = FENCED.get(cp); + if (match) { + if (last == i) throw error_placement(`${prev} + ${match}`); + last = i + 1; + prev = match; + } } - _encodeParams(params, values) { - return this._abiCoder.encode(params, values); + if (last == n) throw error_placement(`trailing ${prev}`); +} +function safe_str_from_cps(cps, max = Infinity, quoter = quote_cp) { + let buf = []; + if (is_combining_mark(cps[0])) buf.push("◌"); + if (cps.length > max) { + max >>= 1; + cps = [ + ...cps.slice(0, max), + 8230, + ...cps.slice(-max) + ]; } - encodeDeploy(values) { - return this._encodeParams(this.deploy.inputs, values || []); + let prev = 0; + let n = cps.length; + for(let i = 0; i < n; i++){ + let cp = cps[i]; + if (should_escape(cp)) { + buf.push(str_from_cps(cps.slice(prev, i))); + buf.push(quoter(cp)); + prev = i + 1; + } } - decodeErrorResult(fragment, data) { - if (typeof fragment === "string") { - fragment = this.getError(fragment); + buf.push(str_from_cps(cps.slice(prev, n))); + return buf.join(""); +} +function is_combining_mark(cp) { + init(); + return CM.has(cp); +} +function should_escape(cp) { + init(); + return ESCAPE.has(cp); +} +function ens_normalize(name) { + return flatten(split(name, nfc, filter_fe0f)); +} +function split(name, nf, ef) { + if (!name) return []; + init(); + let offset = 0; + return name.split(STOP_CH).map((label)=>{ + let input = explode_cp(label); + let info = { + input: input, + offset: offset + }; + offset += input.length + 1; + try { + let tokens = info.tokens = tokens_from_str(input, nf, ef); + let token_count = tokens.length; + let type; + if (!token_count) { + throw new Error(`empty label`); + } + let norm = info.output = tokens.flat(); + check_leading_underscore(norm); + let emoji = info.emoji = token_count > 1 || tokens[0].is_emoji; + if (!emoji && norm.every((cp)=>cp < 128)) { + check_label_extension(norm); + type = "ASCII"; + } else { + let chars = tokens.flatMap((x)=>x.is_emoji ? [] : x); + if (!chars.length) { + type = "Emoji"; + } else { + if (CM.has(norm[0])) throw error_placement("leading combining mark"); + for(let i = 1; i < token_count; i++){ + let cps = tokens[i]; + if (!cps.is_emoji && CM.has(cps[0])) { + throw error_placement(`emoji + combining mark: "${str_from_cps(tokens[i - 1])} + ${safe_str_from_cps([ + cps[0] + ])}"`); + } + } + check_fenced(norm); + let unique = Array_from(new Set(chars)); + let [g] = determine_group(unique); + check_group(g, chars); + check_whole(g, unique); + type = g.N; + } + } + info.type = type; + } catch (err) { + info.error = err; } - const bytes2 = arrayify(data); - if (hexlify(bytes2.slice(0, 4)) !== this.getSighash(fragment)) { - logger$4.throwArgumentError(`data signature does not match error ${fragment.name}.`, "data", hexlify(bytes2)); + return info; + }); +} +function check_whole(group, unique) { + let maker; + let shared = []; + for (let cp of unique){ + let whole = WHOLE_MAP.get(cp); + if (whole === 1) return; + if (whole) { + let set = whole.M.get(cp); + maker = maker ? maker.filter((g)=>set.has(g)) : Array_from(set); + if (!maker.length) return; + } else { + shared.push(cp); } - return this._decodeParams(fragment.inputs, bytes2.slice(4)); } - encodeErrorResult(fragment, values) { - if (typeof fragment === "string") { - fragment = this.getError(fragment); + if (maker) { + for (let g of maker){ + if (shared.every((cp)=>group_has_cp(g, cp))) { + throw new Error(`whole-script confusable: ${group.N}/${g.N}`); + } } - return hexlify(concat([ - this.getSighash(fragment), - this._encodeParams(fragment.inputs, values || []) - ])); } - decodeFunctionData(functionFragment, data) { - if (typeof functionFragment === "string") { - functionFragment = this.getFunction(functionFragment); - } - const bytes2 = arrayify(data); - if (hexlify(bytes2.slice(0, 4)) !== this.getSighash(functionFragment)) { - logger$4.throwArgumentError(`data signature does not match function ${functionFragment.name}.`, "data", hexlify(bytes2)); +} +function determine_group(unique) { + let groups = GROUPS; + for (let cp of unique){ + let gs = groups.filter((g)=>group_has_cp(g, cp)); + if (!gs.length) { + if (!GROUPS.some((g)=>group_has_cp(g, cp))) { + throw error_disallowed(cp); + } else { + throw error_group_member(groups[0], cp); + } } - return this._decodeParams(functionFragment.inputs, bytes2.slice(4)); + groups = gs; + if (gs.length == 1) break; } - encodeFunctionData(functionFragment, values) { - if (typeof functionFragment === "string") { - functionFragment = this.getFunction(functionFragment); + return groups; +} +function flatten(split) { + return split.map(({ input, error, output })=>{ + if (error) { + let msg = error.message; + throw new Error(split.length == 1 ? msg : `Invalid label ${bidi_qq(safe_str_from_cps(input, 63))}: ${msg}`); } - return hexlify(concat([ - this.getSighash(functionFragment), - this._encodeParams(functionFragment.inputs, values || []) - ])); + return str_from_cps(output); + }).join(STOP_CH); +} +function error_disallowed(cp) { + return new Error(`disallowed character: ${quoted_cp(cp)}`); +} +function error_group_member(g, cp) { + let quoted = quoted_cp(cp); + let gg = GROUPS.find((g)=>g.P.has(cp)); + if (gg) { + quoted = `${gg.N} ${quoted}`; } - decodeFunctionResult(functionFragment, data) { - if (typeof functionFragment === "string") { - functionFragment = this.getFunction(functionFragment); + return new Error(`illegal mixture: ${g.N} + ${quoted}`); +} +function error_placement(where) { + return new Error(`illegal placement: ${where}`); +} +function check_group(g, cps) { + for (let cp of cps){ + if (!group_has_cp(g, cp)) { + throw error_group_member(g, cp); } - let bytes2 = arrayify(data); - let reason = null; - let message = ""; - let errorArgs = null; - let errorName = null; - let errorSignature = null; - switch(bytes2.length % this._abiCoder._getWordSize()){ - case 0: - try { - return this._abiCoder.decode(functionFragment.outputs, bytes2); - } catch (error) {} - break; - case 4: - { - const selector = hexlify(bytes2.slice(0, 4)); - const builtin = BuiltinErrors[selector]; - if (builtin) { - errorArgs = this._abiCoder.decode(builtin.inputs, bytes2.slice(4)); - errorName = builtin.name; - errorSignature = builtin.signature; - if (builtin.reason) { - reason = errorArgs[0]; - } - if (errorName === "Error") { - message = `; VM Exception while processing transaction: reverted with reason string ${JSON.stringify(errorArgs[0])}`; - } else if (errorName === "Panic") { - message = `; VM Exception while processing transaction: reverted with panic code ${errorArgs[0]}`; + } + if (g.M) { + let decomposed = nfd(cps); + for(let i = 1, e = decomposed.length; i < e; i++){ + if (NSM.has(decomposed[i])) { + let j = i + 1; + for(let cp; j < e && NSM.has(cp = decomposed[j]); j++){ + for(let k = i; k < j; k++){ + if (decomposed[k] == cp) { + throw new Error(`duplicate non-spacing marks: ${quoted_cp(cp)}`); } - } else { - try { - const error = this.getError(selector); - errorArgs = this._abiCoder.decode(error.inputs, bytes2.slice(4)); - errorName = error.name; - errorSignature = error.format(); - } catch (error) {} } - break; } + if (j - i > 4) { + throw new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(decomposed.slice(i - 1, j)))} (${j - i}/${4})`); + } + i = j; + } } - return logger$4.throwError("call revert exception" + message, Logger.errors.CALL_EXCEPTION, { - method: functionFragment.format(), - data: hexlify(data), - errorArgs, - errorName, - errorSignature, - reason - }); } - encodeFunctionResult(functionFragment, values) { - if (typeof functionFragment === "string") { - functionFragment = this.getFunction(functionFragment); +} +function tokens_from_str(input, nf, ef) { + let ret = []; + let chars = []; + input = input.slice().reverse(); + while(input.length){ + let emoji = consume_emoji_reversed(input); + if (emoji) { + if (chars.length) { + ret.push(nf(chars)); + chars = []; + } + ret.push(ef(emoji)); + } else { + let cp = input.pop(); + if (VALID.has(cp)) { + chars.push(cp); + } else { + let cps = MAPPED.get(cp); + if (cps) { + chars.push(...cps); + } else if (!IGNORED.has(cp)) { + throw error_disallowed(cp); + } + } } - return hexlify(this._abiCoder.encode(functionFragment.outputs, values || [])); } - encodeFilterTopics(eventFragment, values) { - if (typeof eventFragment === "string") { - eventFragment = this.getEvent(eventFragment); - } - if (values.length > eventFragment.inputs.length) { - logger$4.throwError("too many arguments for " + eventFragment.format(), Logger.errors.UNEXPECTED_ARGUMENT, { - argument: "values", - value: values - }); - } - let topics = []; - if (!eventFragment.anonymous) { - topics.push(this.getEventTopic(eventFragment)); - } - const encodeTopic = (param, value)=>{ - if (param.type === "string") { - return id(value); - } else if (param.type === "bytes") { - return keccak256(hexlify(value)); - } - if (param.type === "bool" && typeof value === "boolean") { - value = value ? "0x01" : "0x00"; - } - if (param.type.match(/^u?int/)) { - value = BigNumber.from(value).toHexString(); - } - if (param.type === "address") { - this._abiCoder.encode([ - "address" - ], [ - value - ]); - } - return hexZeroPad(hexlify(value), 32); - }; - values.forEach((value, index)=>{ - let param = eventFragment.inputs[index]; - if (!param.indexed) { - if (value != null) { - logger$4.throwArgumentError("cannot filter non-indexed parameters; must be null", "contract." + param.name, value); - } - return; - } - if (value == null) { - topics.push(null); - } else if (param.baseType === "array" || param.baseType === "tuple") { - logger$4.throwArgumentError("filtering with tuples or arrays not supported", "contract." + param.name, value); - } else if (Array.isArray(value)) { - topics.push(value.map((value2)=>encodeTopic(param, value2))); - } else { - topics.push(encodeTopic(param, value)); - } - }); - while(topics.length && topics[topics.length - 1] === null){ - topics.pop(); - } - return topics; - } - encodeEventLog(eventFragment, values) { - if (typeof eventFragment === "string") { - eventFragment = this.getEvent(eventFragment); - } - const topics = []; - const dataTypes = []; - const dataValues = []; - if (!eventFragment.anonymous) { - topics.push(this.getEventTopic(eventFragment)); - } - if (values.length !== eventFragment.inputs.length) { - logger$4.throwArgumentError("event arguments/values mismatch", "values", values); - } - eventFragment.inputs.forEach((param, index)=>{ - const value = values[index]; - if (param.indexed) { - if (param.type === "string") { - topics.push(id(value)); - } else if (param.type === "bytes") { - topics.push(keccak256(value)); - } else if (param.baseType === "tuple" || param.baseType === "array") { - throw new Error("not implemented"); - } else { - topics.push(this._abiCoder.encode([ - param.type - ], [ - value - ])); - } - } else { - dataTypes.push(param); - dataValues.push(value); - } - }); - return { - data: this._abiCoder.encode(dataTypes, dataValues), - topics - }; + if (chars.length) { + ret.push(nf(chars)); } - decodeEventLog(eventFragment, data, topics) { - if (typeof eventFragment === "string") { - eventFragment = this.getEvent(eventFragment); - } - if (topics != null && !eventFragment.anonymous) { - let topicHash = this.getEventTopic(eventFragment); - if (!isHexString(topics[0], 32) || topics[0].toLowerCase() !== topicHash) { - logger$4.throwError("fragment/topic mismatch", Logger.errors.INVALID_ARGUMENT, { - argument: "topics[0]", - expected: topicHash, - value: topics[0] - }); - } - topics = topics.slice(1); - } - let indexed = []; - let nonIndexed = []; - let dynamic = []; - eventFragment.inputs.forEach((param, index)=>{ - if (param.indexed) { - if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") { - indexed.push(ParamType.fromObject({ - type: "bytes32", - name: param.name - })); - dynamic.push(true); - } else { - indexed.push(param); - dynamic.push(false); - } - } else { - nonIndexed.push(param); - dynamic.push(false); - } - }); - let resultIndexed = topics != null ? this._abiCoder.decode(indexed, concat(topics)) : null; - let resultNonIndexed = this._abiCoder.decode(nonIndexed, data, true); - let result = []; - let nonIndexedIndex = 0, indexedIndex = 0; - eventFragment.inputs.forEach((param, index)=>{ - if (param.indexed) { - if (resultIndexed == null) { - result[index] = new Indexed({ - _isIndexed: true, - hash: null - }); - } else if (dynamic[index]) { - result[index] = new Indexed({ - _isIndexed: true, - hash: resultIndexed[indexedIndex++] - }); - } else { - try { - result[index] = resultIndexed[indexedIndex++]; - } catch (error) { - result[index] = error; - } - } - } else { - try { - result[index] = resultNonIndexed[nonIndexedIndex++]; - } catch (error) { - result[index] = error; - } - } - if (param.name && result[param.name] == null) { - const value = result[index]; - if (value instanceof Error) { - Object.defineProperty(result, param.name, { - enumerable: true, - get: ()=>{ - throw wrapAccessError(`property ${JSON.stringify(param.name)}`, value); - } - }); - } else { - result[param.name] = value; - } - } - }); - for(let i = 0; i < result.length; i++){ - const value = result[i]; - if (value instanceof Error) { - Object.defineProperty(result, i, { - enumerable: true, - get: ()=>{ - throw wrapAccessError(`index ${i}`, value); - } - }); - } + return ret; +} +function filter_fe0f(cps) { + return cps.filter((cp)=>cp != 65039); +} +function consume_emoji_reversed(cps, eaten) { + let node = EMOJI_ROOT; + let emoji; + let pos = cps.length; + while(pos){ + node = node.get(cps[--pos]); + if (!node) break; + let { V } = node; + if (V) { + emoji = V; + cps.length = pos; } - return Object.freeze(result); } - parseTransaction(tx) { - let fragment = this.getFunction(tx.data.substring(0, 10).toLowerCase()); - if (!fragment) { - return null; - } - return new TransactionDescription({ - args: this._abiCoder.decode(fragment.inputs, "0x" + tx.data.substring(10)), - functionFragment: fragment, - name: fragment.name, - signature: fragment.format(), - sighash: this.getSighash(fragment), - value: BigNumber.from(tx.value || "0") - }); + return emoji; +} +const Zeros = new Uint8Array(32); +Zeros.fill(0); +function checkComponent(comp) { + assertArgument(comp.length !== 0, "invalid ENS name; empty component", "comp", comp); + return comp; +} +function ensNameSplit(name) { + const bytes = toUtf8Bytes(ensNormalize(name)); + const comps = []; + if (name.length === 0) { + return comps; } - parseLog(log) { - let fragment = this.getEvent(log.topics[0]); - if (!fragment || fragment.anonymous) { - return null; + let last = 0; + for(let i = 0; i < bytes.length; i++){ + const d = bytes[i]; + if (d === 46) { + comps.push(checkComponent(bytes.slice(last, i))); + last = i + 1; } - return new LogDescription({ - eventFragment: fragment, - name: fragment.name, - signature: fragment.format(), - topic: this.getEventTopic(fragment), - args: this.decodeEventLog(fragment, log.data, log.topics) - }); } - parseError(data) { - const hexData = hexlify(data); - let fragment = this.getError(hexData.substring(0, 10).toLowerCase()); - if (!fragment) { - return null; + assertArgument(last < bytes.length, "invalid ENS name; empty component", "name", name); + comps.push(checkComponent(bytes.slice(last))); + return comps; +} +function ensNormalize(name) { + try { + if (name.length === 0) { + throw new Error("empty label"); } - return new ErrorDescription({ - args: this._abiCoder.decode(fragment.inputs, "0x" + hexData.substring(10)), - errorFragment: fragment, - name: fragment.name, - signature: fragment.format(), - sighash: this.getSighash(fragment) - }); + return ens_normalize(name); + } catch (error) { + assertArgument(false, `invalid ENS name (${error.message})`, "name", name); } - static isInterface(value) { - return !!(value && value._isInterface); +} +function isValidName(name) { + try { + return ensNameSplit(name).length !== 0; + } catch (error) {} + return false; +} +function namehash(name) { + assertArgument(typeof name === "string", "invalid ENS name; not a string", "name", name); + assertArgument(name.length, `invalid ENS name (empty label)`, "name", name); + let result = Zeros; + const comps = ensNameSplit(name); + while(comps.length){ + result = keccak256(concat([ + result, + keccak256(comps.pop()) + ])); } + return hexlify(result); +} +function dnsEncode(name, _maxLength) { + const length = _maxLength != null ? _maxLength : 63; + assertArgument(length <= 255, "DNS encoded label cannot exceed 255", "length", length); + return hexlify(concat(ensNameSplit(name).map((comp)=>{ + assertArgument(comp.length <= length, `label ${JSON.stringify(name)} exceeds ${length} bytes`, "name", name); + const bytes = new Uint8Array(comp.length + 1); + bytes.set(comp, 1); + bytes[0] = bytes.length - 1; + return bytes; + }))) + "00"; +} +function accessSetify(addr, storageKeys) { + return { + address: getAddress(addr), + storageKeys: storageKeys.map((storageKey, index)=>{ + assertArgument(isHexString(storageKey, 32), "invalid slot", `storageKeys[${index}]`, storageKey); + return storageKey.toLowerCase(); + }) + }; } -const version10 = "abstract-provider/5.7.0"; -var __awaiter2 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); +function accessListify(value) { + if (Array.isArray(value)) { + return value.map((set, index)=>{ + if (Array.isArray(set)) { + assertArgument(set.length === 2, "invalid slot set", `value[${index}]`, set); + return accessSetify(set[0], set[1]); + } + assertArgument(set != null && typeof set === "object", "invalid address-slot set", "value", value); + return accessSetify(set.address, set.storageKeys); }); } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + assertArgument(value != null && typeof value === "object", "invalid access list", "value", value); + const result = Object.keys(value).map((addr)=>{ + const storageKeys = value[addr].reduce((accum, storageKey)=>{ + accum[storageKey] = true; + return accum; + }, {}); + return accessSetify(addr, Object.keys(storageKeys).sort()); }); -}; -const logger28 = new Logger(version10); -class ForkEvent extends Description { - static isForkEvent(value) { - return !!(value && value._isForkEvent); + result.sort((a, b)=>a.address.localeCompare(b.address)); + return result; +} +function computeAddress(key) { + let pubkey; + if (typeof key === "string") { + pubkey = SigningKey.computePublicKey(key, false); + } else { + pubkey = key.publicKey; } + return getAddress(keccak256("0x" + pubkey.substring(4)).substring(26)); } -class Provider { - constructor(){ - logger28.checkAbstract(new.target, Provider); - defineReadOnly(this, "_isProvider", true); - } - getFeeData() { - return __awaiter2(this, void 0, void 0, function*() { - const { block, gasPrice } = yield resolveProperties({ - block: this.getBlock("latest"), - gasPrice: this.getGasPrice().catch((error)=>{ - return null; - }) - }); - let lastBaseFeePerGas = null, maxFeePerGas = null, maxPriorityFeePerGas = null; - if (block && block.baseFeePerGas) { - lastBaseFeePerGas = block.baseFeePerGas; - maxPriorityFeePerGas = BigNumber.from("1500000000"); - maxFeePerGas = block.baseFeePerGas.mul(2).add(maxPriorityFeePerGas); - } - return { - lastBaseFeePerGas, - maxFeePerGas, - maxPriorityFeePerGas, - gasPrice - }; - }); +function recoverAddress(digest, signature) { + return computeAddress(SigningKey.recoverPublicKey(digest, signature)); +} +const BN_0$4 = BigInt(0); +const BN_2$2 = BigInt(2); +const BN_27 = BigInt(27); +const BN_28 = BigInt(28); +const BN_35 = BigInt(35); +const BN_MAX_UINT = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +const BLOB_SIZE = 4096 * 32; +function getVersionedHash(version, hash) { + let versioned = version.toString(16); + while(versioned.length < 2){ + versioned = "0" + versioned; + } + versioned += sha256(hash).substring(4); + return "0x" + versioned; +} +function handleAddress(value) { + if (value === "0x") { + return null; + } + return getAddress(value); +} +function handleAccessList(value, param) { + try { + return accessListify(value); + } catch (error) { + assertArgument(false, error.message, param, value); } - addListener(eventName, listener) { - return this.on(eventName, listener); +} +function handleNumber(_value, param) { + if (_value === "0x") { + return 0; } - removeListener(eventName, listener) { - return this.off(eventName, listener); + return getNumber(_value, param); +} +function handleUint(_value, param) { + if (_value === "0x") { + return BN_0$4; } - static isProvider(value) { - return !!(value && value._isProvider); + const value = getBigInt(_value, param); + assertArgument(value <= BN_MAX_UINT, "value exceeds uint size", param, value); + return value; +} +function formatNumber(_value, name) { + const value = getBigInt(_value, "value"); + const result = toBeArray(value); + assertArgument(result.length <= 32, `value too large`, `tx.${name}`, value); + return result; +} +function formatAccessList(value) { + return accessListify(value).map((set)=>[ + set.address, + set.storageKeys + ]); +} +function formatHashes(value, param) { + assertArgument(Array.isArray(value), `invalid ${param}`, "value", value); + for(let i = 0; i < value.length; i++){ + assertArgument(isHexString(value[i], 32), "invalid ${ param } hash", `value[${i}]`, value[i]); } + return value; } -const version11 = "abstract-signer/5.7.0"; -var __awaiter3 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); +function _parseLegacy(data) { + const fields = decodeRlp(data); + assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 6), "invalid field count for legacy transaction", "data", data); + const tx = { + type: 0, + nonce: handleNumber(fields[0], "nonce"), + gasPrice: handleUint(fields[1], "gasPrice"), + gasLimit: handleUint(fields[2], "gasLimit"), + to: handleAddress(fields[3]), + value: handleUint(fields[4], "value"), + data: hexlify(fields[5]), + chainId: BN_0$4 + }; + if (fields.length === 6) { + return tx; + } + const v = handleUint(fields[6], "v"); + const r = handleUint(fields[7], "r"); + const s = handleUint(fields[8], "s"); + if (r === BN_0$4 && s === BN_0$4) { + tx.chainId = v; + } else { + let chainId = (v - BN_35) / BN_2$2; + if (chainId < BN_0$4) { + chainId = BN_0$4; + } + tx.chainId = chainId; + assertArgument(chainId !== BN_0$4 || v === BN_27 || v === BN_28, "non-canonical legacy v", "v", fields[6]); + tx.signature = Signature.from({ + r: zeroPadValue(fields[7], 32), + s: zeroPadValue(fields[8], 32), + v: v }); } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + return tx; +} +function _serializeLegacy(tx, sig) { + const fields = [ + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit, "gasLimit"), + tx.to || "0x", + formatNumber(tx.value, "value"), + tx.data + ]; + let chainId = BN_0$4; + if (tx.chainId != BN_0$4) { + chainId = getBigInt(tx.chainId, "tx.chainId"); + assertArgument(!sig || sig.networkV == null || sig.legacyChainId === chainId, "tx.chainId/sig.v mismatch", "sig", sig); + } else if (tx.signature) { + const legacy = tx.signature.legacyChainId; + if (legacy != null) { + chainId = legacy; + } + } + if (!sig) { + if (chainId !== BN_0$4) { + fields.push(toBeArray(chainId)); + fields.push("0x"); + fields.push("0x"); + } + return encodeRlp(fields); + } + let v = BigInt(27 + sig.yParity); + if (chainId !== BN_0$4) { + v = Signature.getChainIdV(chainId, sig.v); + } else if (BigInt(sig.v) !== v) { + assertArgument(false, "tx.chainId/sig.v mismatch", "sig", sig); + } + fields.push(toBeArray(v)); + fields.push(toBeArray(sig.r)); + fields.push(toBeArray(sig.s)); + return encodeRlp(fields); +} +function _parseEipSignature(tx, fields) { + let yParity; + try { + yParity = handleNumber(fields[0], "yParity"); + if (yParity !== 0 && yParity !== 1) { + throw new Error("bad yParity"); } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + } catch (error) { + assertArgument(false, "invalid yParity", "yParity", fields[0]); + } + const r = zeroPadValue(fields[1], 32); + const s = zeroPadValue(fields[2], 32); + const signature = Signature.from({ + r: r, + s: s, + yParity: yParity + }); + tx.signature = signature; +} +function _parseEip1559(data) { + const fields = decodeRlp(getBytes(data).slice(1)); + assertArgument(Array.isArray(fields) && (fields.length === 9 || fields.length === 12), "invalid field count for transaction type: 2", "data", hexlify(data)); + const tx = { + type: 2, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"), + maxFeePerGas: handleUint(fields[3], "maxFeePerGas"), + gasPrice: null, + gasLimit: handleUint(fields[4], "gasLimit"), + to: handleAddress(fields[5]), + value: handleUint(fields[6], "value"), + data: hexlify(fields[7]), + accessList: handleAccessList(fields[8], "accessList") + }; + if (fields.length === 9) { + return tx; + } + _parseEipSignature(tx, fields.slice(9)); + return tx; +} +function _serializeEip1559(tx, sig) { + const fields = [ + formatNumber(tx.chainId, "chainId"), + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(tx.gasLimit, "gasLimit"), + tx.to || "0x", + formatNumber(tx.value, "value"), + tx.data, + formatAccessList(tx.accessList || []) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "yParity")); + fields.push(toBeArray(sig.r)); + fields.push(toBeArray(sig.s)); + } + return concat([ + "0x02", + encodeRlp(fields) + ]); +} +function _parseEip2930(data) { + const fields = decodeRlp(getBytes(data).slice(1)); + assertArgument(Array.isArray(fields) && (fields.length === 8 || fields.length === 11), "invalid field count for transaction type: 1", "data", hexlify(data)); + const tx = { + type: 1, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + gasPrice: handleUint(fields[2], "gasPrice"), + gasLimit: handleUint(fields[3], "gasLimit"), + to: handleAddress(fields[4]), + value: handleUint(fields[5], "value"), + data: hexlify(fields[6]), + accessList: handleAccessList(fields[7], "accessList") + }; + if (fields.length === 8) { + return tx; + } + _parseEipSignature(tx, fields.slice(8)); + return tx; +} +function _serializeEip2930(tx, sig) { + const fields = [ + formatNumber(tx.chainId, "chainId"), + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.gasPrice || 0, "gasPrice"), + formatNumber(tx.gasLimit, "gasLimit"), + tx.to || "0x", + formatNumber(tx.value, "value"), + tx.data, + formatAccessList(tx.accessList || []) + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "recoveryParam")); + fields.push(toBeArray(sig.r)); + fields.push(toBeArray(sig.s)); + } + return concat([ + "0x01", + encodeRlp(fields) + ]); +} +function _parseEip4844(data) { + let fields = decodeRlp(getBytes(data).slice(1)); + let typeName = "3"; + let blobs = null; + if (fields.length === 4 && Array.isArray(fields[0])) { + typeName = "3 (network format)"; + const fBlobs = fields[1], fCommits = fields[2], fProofs = fields[3]; + assertArgument(Array.isArray(fBlobs), "invalid network format: blobs not an array", "fields[1]", fBlobs); + assertArgument(Array.isArray(fCommits), "invalid network format: commitments not an array", "fields[2]", fCommits); + assertArgument(Array.isArray(fProofs), "invalid network format: proofs not an array", "fields[3]", fProofs); + assertArgument(fBlobs.length === fCommits.length, "invalid network format: blobs/commitments length mismatch", "fields", fields); + assertArgument(fBlobs.length === fProofs.length, "invalid network format: blobs/proofs length mismatch", "fields", fields); + blobs = []; + for(let i = 0; i < fields[1].length; i++){ + blobs.push({ + data: fBlobs[i], + commitment: fCommits[i], + proof: fProofs[i] + }); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + fields = fields[0]; + } + assertArgument(Array.isArray(fields) && (fields.length === 11 || fields.length === 14), `invalid field count for transaction type: ${typeName}`, "data", hexlify(data)); + const tx = { + type: 3, + chainId: handleUint(fields[0], "chainId"), + nonce: handleNumber(fields[1], "nonce"), + maxPriorityFeePerGas: handleUint(fields[2], "maxPriorityFeePerGas"), + maxFeePerGas: handleUint(fields[3], "maxFeePerGas"), + gasPrice: null, + gasLimit: handleUint(fields[4], "gasLimit"), + to: handleAddress(fields[5]), + value: handleUint(fields[6], "value"), + data: hexlify(fields[7]), + accessList: handleAccessList(fields[8], "accessList"), + maxFeePerBlobGas: handleUint(fields[9], "maxFeePerBlobGas"), + blobVersionedHashes: fields[10] + }; + if (blobs) { + tx.blobs = blobs; + } + assertArgument(tx.to != null, `invalid address for transaction type: ${typeName}`, "data", data); + assertArgument(Array.isArray(tx.blobVersionedHashes), "invalid blobVersionedHashes: must be an array", "data", data); + for(let i = 0; i < tx.blobVersionedHashes.length; i++){ + assertArgument(isHexString(tx.blobVersionedHashes[i], 32), `invalid blobVersionedHash at index ${i}: must be length 32`, "data", data); + } + if (fields.length === 11) { + return tx; + } + _parseEipSignature(tx, fields.slice(11)); + return tx; +} +function _serializeEip4844(tx, sig, blobs) { + const fields = [ + formatNumber(tx.chainId, "chainId"), + formatNumber(tx.nonce, "nonce"), + formatNumber(tx.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), + formatNumber(tx.maxFeePerGas || 0, "maxFeePerGas"), + formatNumber(tx.gasLimit, "gasLimit"), + tx.to || ZeroAddress, + formatNumber(tx.value, "value"), + tx.data, + formatAccessList(tx.accessList || []), + formatNumber(tx.maxFeePerBlobGas || 0, "maxFeePerBlobGas"), + formatHashes(tx.blobVersionedHashes || [], "blobVersionedHashes") + ]; + if (sig) { + fields.push(formatNumber(sig.yParity, "yParity")); + fields.push(toBeArray(sig.r)); + fields.push(toBeArray(sig.s)); + if (blobs) { + return concat([ + "0x03", + encodeRlp([ + fields, + blobs.map((b)=>b.data), + blobs.map((b)=>b.commitment), + blobs.map((b)=>b.proof) + ]) + ]); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger29 = new Logger(version11); -const allowedTransactionKeys = [ - "accessList", - "ccipReadEnabled", - "chainId", - "customData", - "data", - "from", - "gasLimit", - "gasPrice", - "maxFeePerGas", - "maxPriorityFeePerGas", - "nonce", - "to", - "type", - "value" -]; -const forwardErrors = [ - Logger.errors.INSUFFICIENT_FUNDS, - Logger.errors.NONCE_EXPIRED, - Logger.errors.REPLACEMENT_UNDERPRICED -]; -class Signer { - constructor(){ - logger29.checkAbstract(new.target, Signer); - defineReadOnly(this, "_isSigner", true); } - getBalance(blockTag) { - return __awaiter3(this, void 0, void 0, function*() { - this._checkProvider("getBalance"); - return yield this.provider.getBalance(this.getAddress(), blockTag); - }); + return concat([ + "0x03", + encodeRlp(fields) + ]); +} +class Transaction { + #type; + #to; + #data; + #nonce; + #gasLimit; + #gasPrice; + #maxPriorityFeePerGas; + #maxFeePerGas; + #value; + #chainId; + #sig; + #accessList; + #maxFeePerBlobGas; + #blobVersionedHashes; + #kzg; + #blobs; + get type() { + return this.#type; } - getTransactionCount(blockTag) { - return __awaiter3(this, void 0, void 0, function*() { - this._checkProvider("getTransactionCount"); - return yield this.provider.getTransactionCount(this.getAddress(), blockTag); - }); + set type(value) { + switch(value){ + case null: + this.#type = null; + break; + case 0: + case "legacy": + this.#type = 0; + break; + case 1: + case "berlin": + case "eip-2930": + this.#type = 1; + break; + case 2: + case "london": + case "eip-1559": + this.#type = 2; + break; + case 3: + case "cancun": + case "eip-4844": + this.#type = 3; + break; + default: + assertArgument(false, "unsupported transaction type", "type", value); + } } - estimateGas(transaction) { - return __awaiter3(this, void 0, void 0, function*() { - this._checkProvider("estimateGas"); - const tx = yield resolveProperties(this.checkTransaction(transaction)); - return yield this.provider.estimateGas(tx); - }); + get typeName() { + switch(this.type){ + case 0: + return "legacy"; + case 1: + return "eip-2930"; + case 2: + return "eip-1559"; + case 3: + return "eip-4844"; + } + return null; } - call(transaction, blockTag) { - return __awaiter3(this, void 0, void 0, function*() { - this._checkProvider("call"); - const tx = yield resolveProperties(this.checkTransaction(transaction)); - return yield this.provider.call(tx, blockTag); - }); + get to() { + const value = this.#to; + if (value == null && this.type === 3) { + return ZeroAddress; + } + return value; } - sendTransaction(transaction) { - return __awaiter3(this, void 0, void 0, function*() { - this._checkProvider("sendTransaction"); - const tx = yield this.populateTransaction(transaction); - const signedTx = yield this.signTransaction(tx); - return yield this.provider.sendTransaction(signedTx); - }); + set to(value) { + this.#to = value == null ? null : getAddress(value); } - getChainId() { - return __awaiter3(this, void 0, void 0, function*() { - this._checkProvider("getChainId"); - const network = yield this.provider.getNetwork(); - return network.chainId; - }); + get nonce() { + return this.#nonce; } - getGasPrice() { - return __awaiter3(this, void 0, void 0, function*() { - this._checkProvider("getGasPrice"); - return yield this.provider.getGasPrice(); - }); + set nonce(value) { + this.#nonce = getNumber(value, "value"); } - getFeeData() { - return __awaiter3(this, void 0, void 0, function*() { - this._checkProvider("getFeeData"); - return yield this.provider.getFeeData(); - }); + get gasLimit() { + return this.#gasLimit; } - resolveName(name) { - return __awaiter3(this, void 0, void 0, function*() { - this._checkProvider("resolveName"); - return yield this.provider.resolveName(name); - }); + set gasLimit(value) { + this.#gasLimit = getBigInt(value); + } + get gasPrice() { + const value = this.#gasPrice; + if (value == null && (this.type === 0 || this.type === 1)) { + return BN_0$4; + } + return value; } - checkTransaction(transaction) { - for(const key in transaction){ - if (allowedTransactionKeys.indexOf(key) === -1) { - logger29.throwArgumentError("invalid transaction key: " + key, "transaction", transaction); + set gasPrice(value) { + this.#gasPrice = value == null ? null : getBigInt(value, "gasPrice"); + } + get maxPriorityFeePerGas() { + const value = this.#maxPriorityFeePerGas; + if (value == null) { + if (this.type === 2 || this.type === 3) { + return BN_0$4; } + return null; } - const tx = shallowCopy(transaction); - if (tx.from == null) { - tx.from = this.getAddress(); - } else { - tx.from = Promise.all([ - Promise.resolve(tx.from), - this.getAddress() - ]).then((result)=>{ - if (result[0].toLowerCase() !== result[1].toLowerCase()) { - logger29.throwArgumentError("from address mismatch", "transaction", transaction); - } - return result[0]; - }); + return value; + } + set maxPriorityFeePerGas(value) { + this.#maxPriorityFeePerGas = value == null ? null : getBigInt(value, "maxPriorityFeePerGas"); + } + get maxFeePerGas() { + const value = this.#maxFeePerGas; + if (value == null) { + if (this.type === 2 || this.type === 3) { + return BN_0$4; + } + return null; } - return tx; + return value; } - populateTransaction(transaction) { - return __awaiter3(this, void 0, void 0, function*() { - const tx = yield resolveProperties(this.checkTransaction(transaction)); - if (tx.to != null) { - tx.to = Promise.resolve(tx.to).then((to)=>__awaiter3(this, void 0, void 0, function*() { - if (to == null) { - return null; - } - const address = yield this.resolveName(to); - if (address == null) { - logger29.throwArgumentError("provided ENS name resolves to null", "tx.to", to); - } - return address; - })); - tx.to.catch((error)=>{}); - } - const hasEip1559 = tx.maxFeePerGas != null || tx.maxPriorityFeePerGas != null; - if (tx.gasPrice != null && (tx.type === 2 || hasEip1559)) { - logger29.throwArgumentError("eip-1559 transaction do not support gasPrice", "transaction", transaction); - } else if ((tx.type === 0 || tx.type === 1) && hasEip1559) { - logger29.throwArgumentError("pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "transaction", transaction); - } - if ((tx.type === 2 || tx.type == null) && tx.maxFeePerGas != null && tx.maxPriorityFeePerGas != null) { - tx.type = 2; - } else if (tx.type === 0 || tx.type === 1) { - if (tx.gasPrice == null) { - tx.gasPrice = this.getGasPrice(); - } - } else { - const feeData = yield this.getFeeData(); - if (tx.type == null) { - if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) { - tx.type = 2; - if (tx.gasPrice != null) { - const gasPrice = tx.gasPrice; - delete tx.gasPrice; - tx.maxFeePerGas = gasPrice; - tx.maxPriorityFeePerGas = gasPrice; - } else { - if (tx.maxFeePerGas == null) { - tx.maxFeePerGas = feeData.maxFeePerGas; - } - if (tx.maxPriorityFeePerGas == null) { - tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; - } - } - } else if (feeData.gasPrice != null) { - if (hasEip1559) { - logger29.throwError("network does not support EIP-1559", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "populateTransaction" - }); - } - if (tx.gasPrice == null) { - tx.gasPrice = feeData.gasPrice; - } - tx.type = 0; - } else { - logger29.throwError("failed to get consistent fee data", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "signer.getFeeData" - }); - } - } else if (tx.type === 2) { - if (tx.maxFeePerGas == null) { - tx.maxFeePerGas = feeData.maxFeePerGas; - } - if (tx.maxPriorityFeePerGas == null) { - tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; - } - } + set maxFeePerGas(value) { + this.#maxFeePerGas = value == null ? null : getBigInt(value, "maxFeePerGas"); + } + get data() { + return this.#data; + } + set data(value) { + this.#data = hexlify(value); + } + get value() { + return this.#value; + } + set value(value) { + this.#value = getBigInt(value, "value"); + } + get chainId() { + return this.#chainId; + } + set chainId(value) { + this.#chainId = getBigInt(value); + } + get signature() { + return this.#sig || null; + } + set signature(value) { + this.#sig = value == null ? null : Signature.from(value); + } + get accessList() { + const value = this.#accessList || null; + if (value == null) { + if (this.type === 1 || this.type === 2 || this.type === 3) { + return []; } - if (tx.nonce == null) { - tx.nonce = this.getTransactionCount("pending"); + return null; + } + return value; + } + set accessList(value) { + this.#accessList = value == null ? null : accessListify(value); + } + get maxFeePerBlobGas() { + const value = this.#maxFeePerBlobGas; + if (value == null && this.type === 3) { + return BN_0$4; + } + return value; + } + set maxFeePerBlobGas(value) { + this.#maxFeePerBlobGas = value == null ? null : getBigInt(value, "maxFeePerBlobGas"); + } + get blobVersionedHashes() { + let value = this.#blobVersionedHashes; + if (value == null && this.type === 3) { + return []; + } + return value; + } + set blobVersionedHashes(value) { + if (value != null) { + assertArgument(Array.isArray(value), "blobVersionedHashes must be an Array", "value", value); + value = value.slice(); + for(let i = 0; i < value.length; i++){ + assertArgument(isHexString(value[i], 32), "invalid blobVersionedHash", `value[${i}]`, value[i]); } - if (tx.gasLimit == null) { - tx.gasLimit = this.estimateGas(tx).catch((error)=>{ - if (forwardErrors.indexOf(error.code) >= 0) { - throw error; - } - return logger29.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, { - error, - tx - }); + } + this.#blobVersionedHashes = value; + } + get blobs() { + if (this.#blobs == null) { + return null; + } + return this.#blobs.map((b)=>Object.assign({}, b)); + } + set blobs(_blobs) { + if (_blobs == null) { + this.#blobs = null; + return; + } + const blobs = []; + const versionedHashes = []; + for(let i = 0; i < _blobs.length; i++){ + const blob = _blobs[i]; + if (isBytesLike(blob)) { + assert1(this.#kzg, "adding a raw blob requires a KZG library", "UNSUPPORTED_OPERATION", { + operation: "set blobs()" }); - } - if (tx.chainId == null) { - tx.chainId = this.getChainId(); + let data = getBytes(blob); + assertArgument(data.length <= BLOB_SIZE, "blob is too large", `blobs[${i}]`, blob); + if (data.length !== BLOB_SIZE) { + const padded = new Uint8Array(BLOB_SIZE); + padded.set(data); + data = padded; + } + const commit = this.#kzg.blobToKzgCommitment(data); + const proof = hexlify(this.#kzg.computeBlobKzgProof(data, commit)); + blobs.push({ + data: hexlify(data), + commitment: hexlify(commit), + proof: proof + }); + versionedHashes.push(getVersionedHash(1, commit)); } else { - tx.chainId = Promise.all([ - Promise.resolve(tx.chainId), - this.getChainId() - ]).then((results)=>{ - if (results[1] !== 0 && results[0] !== results[1]) { - logger29.throwArgumentError("chainId address mismatch", "transaction", transaction); - } - return results[0]; + const commit = hexlify(blob.commitment); + blobs.push({ + data: hexlify(blob.data), + commitment: commit, + proof: hexlify(blob.proof) }); + versionedHashes.push(getVersionedHash(1, commit)); } - return yield resolveProperties(tx); - }); - } - _checkProvider(operation) { - if (!this.provider) { - logger29.throwError("missing provider", Logger.errors.UNSUPPORTED_OPERATION, { - operation: operation || "_checkProvider" - }); } + this.#blobs = blobs; + this.#blobVersionedHashes = versionedHashes; } - static isSigner(value) { - return !!(value && value._isSigner); + get kzg() { + return this.#kzg; } -} -class VoidSigner extends Signer { - constructor(address, provider){ - super(); - defineReadOnly(this, "address", address); - defineReadOnly(this, "provider", provider || null); + set kzg(kzg) { + this.#kzg = kzg; } - getAddress() { - return Promise.resolve(this.address); + constructor(){ + this.#type = null; + this.#to = null; + this.#nonce = 0; + this.#gasLimit = BN_0$4; + this.#gasPrice = null; + this.#maxPriorityFeePerGas = null; + this.#maxFeePerGas = null; + this.#data = "0x"; + this.#value = BN_0$4; + this.#chainId = BN_0$4; + this.#sig = null; + this.#accessList = null; + this.#maxFeePerBlobGas = null; + this.#blobVersionedHashes = null; + this.#blobs = null; + this.#kzg = null; } - _fail(message, operation) { - return Promise.resolve().then(()=>{ - logger29.throwError(message, Logger.errors.UNSUPPORTED_OPERATION, { - operation - }); - }); + get hash() { + if (this.signature == null) { + return null; + } + return keccak256(this.#getSerialized(true, false)); } - signMessage(message) { - return this._fail("VoidSigner cannot sign messages", "signMessage"); + get unsignedHash() { + return keccak256(this.unsignedSerialized); } - signTransaction(transaction) { - return this._fail("VoidSigner cannot sign transactions", "signTransaction"); + get from() { + if (this.signature == null) { + return null; + } + return recoverAddress(this.unsignedHash, this.signature); } - _signTypedData(domain, types, value) { - return this._fail("VoidSigner cannot sign typed data", "signTypedData"); + get fromPublicKey() { + if (this.signature == null) { + return null; + } + return SigningKey.recoverPublicKey(this.unsignedHash, this.signature); } - connect(provider) { - return new VoidSigner(this.address, provider); + isSigned() { + return this.signature != null; } -} -var minimalisticAssert = assert1; -function assert1(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); -} -assert1.equal = function assertEqual(l, r, msg) { - if (l != r) throw new Error(msg || "Assertion failed: " + l + " != " + r); -}; -minimalisticAssert.equal; -function createCommonjsModule2(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function(path, base) { - return commonjsRequire2(path, base === void 0 || base === null ? module.path : base); + #getSerialized(signed, sidecar) { + assert1(!signed || this.signature != null, "cannot serialize unsigned transaction; maybe you meant .unsignedSerialized", "UNSUPPORTED_OPERATION", { + operation: ".serialized" + }); + const sig = signed ? this.signature : null; + switch(this.inferType()){ + case 0: + return _serializeLegacy(this, sig); + case 1: + return _serializeEip2930(this, sig); + case 2: + return _serializeEip1559(this, sig); + case 3: + return _serializeEip4844(this, sig, sidecar ? this.blobs : null); } - }, fn(module, module.exports), module.exports; -} -function commonjsRequire2() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); -} -var inherits_browser = createCommonjsModule2(function(module) { - if (typeof Object.create === "function") { - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - } - }; - } else { - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - var TempCtor = function() {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } - }; + assert1(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { + operation: ".serialized" + }); } -}); -function createCommonjsModule3(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function(path, base) { - return commonjsRequire3(path, base === void 0 || base === null ? module.path : base); - } - }, fn(module, module.exports), module.exports; -} -function commonjsRequire3() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); -} -var inherits_1 = inherits_browser; -function isSurrogatePair(msg, i) { - if ((msg.charCodeAt(i) & 64512) !== 55296) { - return false; + get serialized() { + return this.#getSerialized(true, true); } - if (i < 0 || i + 1 >= msg.length) { - return false; + get unsignedSerialized() { + return this.#getSerialized(false, false); } - return (msg.charCodeAt(i + 1) & 64512) === 56320; -} -function toArray(msg, enc) { - if (Array.isArray(msg)) return msg.slice(); - if (!msg) return []; - var res = []; - if (typeof msg === "string") { - if (!enc) { - var p = 0; - for(var i = 0; i < msg.length; i++){ - var c = msg.charCodeAt(i); - if (c < 128) { - res[p++] = c; - } else if (c < 2048) { - res[p++] = c >> 6 | 192; - res[p++] = c & 63 | 128; - } else if (isSurrogatePair(msg, i)) { - c = 65536 + ((c & 1023) << 10) + (msg.charCodeAt(++i) & 1023); - res[p++] = c >> 18 | 240; - res[p++] = c >> 12 & 63 | 128; - res[p++] = c >> 6 & 63 | 128; - res[p++] = c & 63 | 128; - } else { - res[p++] = c >> 12 | 224; - res[p++] = c >> 6 & 63 | 128; - res[p++] = c & 63 | 128; - } + inferType() { + const types = this.inferTypes(); + if (types.indexOf(2) >= 0) { + return 2; + } + return types.pop(); + } + inferTypes() { + const hasGasPrice = this.gasPrice != null; + const hasFee = this.maxFeePerGas != null || this.maxPriorityFeePerGas != null; + const hasAccessList = this.accessList != null; + const hasBlob = this.#maxFeePerBlobGas != null || this.#blobVersionedHashes; + if (this.maxFeePerGas != null && this.maxPriorityFeePerGas != null) { + assert1(this.maxFeePerGas >= this.maxPriorityFeePerGas, "priorityFee cannot be more than maxFee", "BAD_DATA", { + value: this + }); + } + assert1(!hasFee || this.type !== 0 && this.type !== 1, "transaction type cannot have maxFeePerGas or maxPriorityFeePerGas", "BAD_DATA", { + value: this + }); + assert1(this.type !== 0 || !hasAccessList, "legacy transaction cannot have accessList", "BAD_DATA", { + value: this + }); + const types = []; + if (this.type != null) { + types.push(this.type); + } else { + if (hasFee) { + types.push(2); + } else if (hasGasPrice) { + types.push(1); + if (!hasAccessList) { + types.push(0); + } + } else if (hasAccessList) { + types.push(1); + types.push(2); + } else if (hasBlob && this.to) { + types.push(3); + } else { + types.push(0); + types.push(1); + types.push(2); + types.push(3); } - } else if (enc === "hex") { - msg = msg.replace(/[^a-z0-9]+/ig, ""); - if (msg.length % 2 !== 0) msg = "0" + msg; - for(i = 0; i < msg.length; i += 2)res.push(parseInt(msg[i] + msg[i + 1], 16)); } - } else { - for(i = 0; i < msg.length; i++)res[i] = msg[i] | 0; + types.sort(); + return types; } - return res; -} -var toArray_1 = toArray; -function toHex1(msg) { - var res = ""; - for(var i = 0; i < msg.length; i++)res += zero2(msg[i].toString(16)); - return res; -} -var toHex_1 = toHex1; -function htonl(w) { - var res = w >>> 24 | w >>> 8 & 65280 | w << 8 & 16711680 | (w & 255) << 24; - return res >>> 0; -} -var htonl_1 = htonl; -function toHex32(msg, endian) { - var res = ""; - for(var i = 0; i < msg.length; i++){ - var w = msg[i]; - if (endian === "little") w = htonl(w); - res += zero8(w.toString(16)); + isLegacy() { + return this.type === 0; } - return res; -} -var toHex32_1 = toHex32; -function zero2(word) { - if (word.length === 1) return "0" + word; - else return word; -} -var zero2_1 = zero2; -function zero8(word) { - if (word.length === 7) return "0" + word; - else if (word.length === 6) return "00" + word; - else if (word.length === 5) return "000" + word; - else if (word.length === 4) return "0000" + word; - else if (word.length === 3) return "00000" + word; - else if (word.length === 2) return "000000" + word; - else if (word.length === 1) return "0000000" + word; - else return word; -} -var zero8_1 = zero8; -function join32(msg, start, end, endian) { - var len = end - start; - minimalisticAssert(len % 4 === 0); - var res = new Array(len / 4); - for(var i = 0, k = start; i < res.length; i++, k += 4){ - var w; - if (endian === "big") w = msg[k] << 24 | msg[k + 1] << 16 | msg[k + 2] << 8 | msg[k + 3]; - else w = msg[k + 3] << 24 | msg[k + 2] << 16 | msg[k + 1] << 8 | msg[k]; - res[i] = w >>> 0; + isBerlin() { + return this.type === 1; } - return res; -} -var join32_1 = join32; -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for(var i = 0, k = 0; i < msg.length; i++, k += 4){ - var m = msg[i]; - if (endian === "big") { - res[k] = m >>> 24; - res[k + 1] = m >>> 16 & 255; - res[k + 2] = m >>> 8 & 255; - res[k + 3] = m & 255; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = m >>> 16 & 255; - res[k + 1] = m >>> 8 & 255; - res[k] = m & 255; - } + isLondon() { + return this.type === 2; } - return res; -} -var split32_1 = split32; -function rotr32(w, b) { - return w >>> b | w << 32 - b; -} -var rotr32_1 = rotr32; -function rotl32(w, b) { - return w << b | w >>> 32 - b; -} -var rotl32_1 = rotl32; -function sum32(a, b) { - return a + b >>> 0; -} -var sum32_1 = sum32; -function sum32_3(a, b, c) { - return a + b + c >>> 0; -} -var sum32_3_1 = sum32_3; -function sum32_4(a, b, c, d) { - return a + b + c + d >>> 0; -} -var sum32_4_1 = sum32_4; -function sum32_5(a, b, c, d, e) { - return a + b + c + d + e >>> 0; -} -var sum32_5_1 = sum32_5; -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; - var lo = al + bl >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; -} -var sum64_1 = sum64; -function sum64_hi(ah, al, bh, bl) { - var lo = al + bl >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -var sum64_hi_1 = sum64_hi; -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -} -var sum64_lo_1 = sum64_lo; -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = lo + bl >>> 0; - carry += lo < al ? 1 : 0; - lo = lo + cl >>> 0; - carry += lo < cl ? 1 : 0; - lo = lo + dl >>> 0; - carry += lo < dl ? 1 : 0; - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -} -var sum64_4_hi_1 = sum64_4_hi; -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -var sum64_4_lo_1 = sum64_4_lo; -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = lo + bl >>> 0; - carry += lo < al ? 1 : 0; - lo = lo + cl >>> 0; - carry += lo < cl ? 1 : 0; - lo = lo + dl >>> 0; - carry += lo < dl ? 1 : 0; - lo = lo + el >>> 0; - carry += lo < el ? 1 : 0; - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; -} -var sum64_5_hi_1 = sum64_5_hi; -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - return lo >>> 0; -} -var sum64_5_lo_1 = sum64_5_lo; -function rotr64_hi(ah, al, num) { - var r2 = al << 32 - num | ah >>> num; - return r2 >>> 0; -} -var rotr64_hi_1 = rotr64_hi; -function rotr64_lo(ah, al, num) { - var r2 = ah << 32 - num | al >>> num; - return r2 >>> 0; -} -var rotr64_lo_1 = rotr64_lo; -function shr64_hi(ah, al, num) { - return ah >>> num; -} -var shr64_hi_1 = shr64_hi; -function shr64_lo(ah, al, num) { - var r2 = ah << 32 - num | al >>> num; - return r2 >>> 0; -} -var shr64_lo_1 = shr64_lo; -var utils = { - inherits: inherits_1, - toArray: toArray_1, - toHex: toHex_1, - htonl: htonl_1, - toHex32: toHex32_1, - zero2: zero2_1, - zero8: zero8_1, - join32: join32_1, - split32: split32_1, - rotr32: rotr32_1, - rotl32: rotl32_1, - sum32: sum32_1, - sum32_3: sum32_3_1, - sum32_4: sum32_4_1, - sum32_5: sum32_5_1, - sum64: sum64_1, - sum64_hi: sum64_hi_1, - sum64_lo: sum64_lo_1, - sum64_4_hi: sum64_4_hi_1, - sum64_4_lo: sum64_4_lo_1, - sum64_5_hi: sum64_5_hi_1, - sum64_5_lo: sum64_5_lo_1, - rotr64_hi: rotr64_hi_1, - rotr64_lo: rotr64_lo_1, - shr64_hi: shr64_hi_1, - shr64_lo: shr64_lo_1 -}; -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = "big"; - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -var BlockHash_1 = BlockHash; -BlockHash.prototype.update = function update(msg, enc) { - msg = utils.toArray(msg, enc); - if (!this.pending) this.pending = msg; - else this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - if (this.pending.length >= this._delta8) { - msg = this.pending; - var r2 = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r2, msg.length); - if (this.pending.length === 0) this.pending = null; - msg = utils.join32(msg, 0, msg.length - r2, this.endian); - for(var i = 0; i < msg.length; i += this._delta32)this._update(msg, i, i + this._delta32); + isCancun() { + return this.type === 3; } - return this; -}; -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - minimalisticAssert(this.pending === null); - return this._digest(enc); -}; -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - (len + this.padLength) % bytes; - var res = new Array(k + this.padLength); - res[0] = 128; - for(var i = 1; i < k; i++)res[i] = 0; - len <<= 3; - if (this.endian === "big") { - for(var t = 8; t < this.padLength; t++)res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = len >>> 24 & 255; - res[i++] = len >>> 16 & 255; - res[i++] = len >>> 8 & 255; - res[i++] = len & 255; - } else { - res[i++] = len & 255; - res[i++] = len >>> 8 & 255; - res[i++] = len >>> 16 & 255; - res[i++] = len >>> 24 & 255; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - for(t = 8; t < this.padLength; t++)res[i++] = 0; + clone() { + return Transaction.from(this); + } + toJSON() { + const s = (v)=>{ + if (v == null) { + return null; + } + return v.toString(); + }; + return { + type: this.type, + to: this.to, + data: this.data, + nonce: this.nonce, + gasLimit: s(this.gasLimit), + gasPrice: s(this.gasPrice), + maxPriorityFeePerGas: s(this.maxPriorityFeePerGas), + maxFeePerGas: s(this.maxFeePerGas), + value: s(this.value), + chainId: s(this.chainId), + sig: this.signature ? this.signature.toJSON() : null, + accessList: this.accessList + }; + } + static from(tx) { + if (tx == null) { + return new Transaction; + } + if (typeof tx === "string") { + const payload = getBytes(tx); + if (payload[0] >= 127) { + return Transaction.from(_parseLegacy(payload)); + } + switch(payload[0]){ + case 1: + return Transaction.from(_parseEip2930(payload)); + case 2: + return Transaction.from(_parseEip1559(payload)); + case 3: + return Transaction.from(_parseEip4844(payload)); + } + assert1(false, "unsupported transaction type", "UNSUPPORTED_OPERATION", { + operation: "from" + }); + } + const result = new Transaction; + if (tx.type != null) { + result.type = tx.type; + } + if (tx.to != null) { + result.to = tx.to; + } + if (tx.nonce != null) { + result.nonce = tx.nonce; + } + if (tx.gasLimit != null) { + result.gasLimit = tx.gasLimit; + } + if (tx.gasPrice != null) { + result.gasPrice = tx.gasPrice; + } + if (tx.maxPriorityFeePerGas != null) { + result.maxPriorityFeePerGas = tx.maxPriorityFeePerGas; + } + if (tx.maxFeePerGas != null) { + result.maxFeePerGas = tx.maxFeePerGas; + } + if (tx.maxFeePerBlobGas != null) { + result.maxFeePerBlobGas = tx.maxFeePerBlobGas; + } + if (tx.data != null) { + result.data = tx.data; + } + if (tx.value != null) { + result.value = tx.value; + } + if (tx.chainId != null) { + result.chainId = tx.chainId; + } + if (tx.signature != null) { + result.signature = Signature.from(tx.signature); + } + if (tx.accessList != null) { + result.accessList = tx.accessList; + } + if (tx.blobVersionedHashes != null) { + result.blobVersionedHashes = tx.blobVersionedHashes; + } + if (tx.kzg != null) { + result.kzg = tx.kzg; + } + if (tx.blobs != null) { + result.blobs = tx.blobs; + } + if (tx.hash != null) { + assertArgument(result.isSigned(), "unsigned transaction cannot define '.hash'", "tx", tx); + assertArgument(result.hash === tx.hash, "hash mismatch", "tx", tx); + } + if (tx.from != null) { + assertArgument(result.isSigned(), "unsigned transaction cannot define '.from'", "tx", tx); + assertArgument(result.from.toLowerCase() === (tx.from || "").toLowerCase(), "from mismatch", "tx", tx); + } + return result; } - return res; -}; -var common = { - BlockHash: BlockHash_1 -}; -var rotr32$1 = utils.rotr32; -function ft_1(s2, x, y, z) { - if (s2 === 0) return ch32(x, y, z); - if (s2 === 1 || s2 === 3) return p32(x, y, z); - if (s2 === 2) return maj32(x, y, z); -} -var ft_1_1 = ft_1; -function ch32(x, y, z) { - return x & y ^ ~x & z; -} -var ch32_1 = ch32; -function maj32(x, y, z) { - return x & y ^ x & z ^ y & z; -} -var maj32_1 = maj32; -function p32(x, y, z) { - return x ^ y ^ z; -} -var p32_1 = p32; -function s0_256(x) { - return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22); -} -var s0_256_1 = s0_256; -function s1_256(x) { - return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25); -} -var s1_256_1 = s1_256; -function g0_256(x) { - return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ x >>> 3; -} -var g0_256_1 = g0_256; -function g1_256(x) { - return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ x >>> 10; -} -var g1_256_1 = g1_256; -var common$1 = { - ft_1: ft_1_1, - ch32: ch32_1, - maj32: maj32_1, - p32: p32_1, - s0_256: s0_256_1, - s1_256: s1_256_1, - g0_256: g0_256_1, - g1_256: g1_256_1 -}; -var rotl32$1 = utils.rotl32; -var sum32$1 = utils.sum32; -var sum32_5$1 = utils.sum32_5; -var ft_1$1 = common$1.ft_1; -var BlockHash$1 = common.BlockHash; -var sha1_K = [ - 1518500249, - 1859775393, - 2400959708, - 3395469782 -]; -function SHA1() { - if (!(this instanceof SHA1)) return new SHA1(); - BlockHash$1.call(this); - this.h = [ - 1732584193, - 4023233417, - 2562383102, - 271733878, - 3285377520 - ]; - this.W = new Array(80); -} -utils.inherits(SHA1, BlockHash$1); -var _1 = SHA1; -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; -SHA1.padLength = 64; -SHA1.prototype._update = function _update(msg, start) { - var W = this.W; - for(var i = 0; i < 16; i++)W[i] = msg[start + i]; - for(; i < W.length; i++)W[i] = rotl32$1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - for(i = 0; i < W.length; i++){ - var s2 = ~~(i / 20); - var t = sum32_5$1(rotl32$1(a, 5), ft_1$1(s2, b, c, d), e, W[i], sha1_K[s2]); - e = d; - d = c; - c = rotl32$1(b, 30); - b = a; - a = t; - } - this.h[0] = sum32$1(this.h[0], a); - this.h[1] = sum32$1(this.h[1], b); - this.h[2] = sum32$1(this.h[2], c); - this.h[3] = sum32$1(this.h[3], d); - this.h[4] = sum32$1(this.h[4], e); -}; -SHA1.prototype._digest = function digest2(enc) { - if (enc === "hex") return utils.toHex32(this.h, "big"); - else return utils.split32(this.h, "big"); -}; -var sum32$2 = utils.sum32; -var sum32_4$1 = utils.sum32_4; -var sum32_5$2 = utils.sum32_5; -var ch32$1 = common$1.ch32; -var maj32$1 = common$1.maj32; -var s0_256$1 = common$1.s0_256; -var s1_256$1 = common$1.s1_256; -var g0_256$1 = common$1.g0_256; -var g1_256$1 = common$1.g1_256; -var BlockHash$2 = common.BlockHash; -var sha256_K = [ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]; -function SHA256() { - if (!(this instanceof SHA256)) return new SHA256(); - BlockHash$2.call(this); - this.h = [ - 1779033703, - 3144134277, - 1013904242, - 2773480762, - 1359893119, - 2600822924, - 528734635, - 1541459225 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash$2); -var _256 = SHA256; -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; -SHA256.prototype._update = function _update2(msg, start) { - var W = this.W; - for(var i = 0; i < 16; i++)W[i] = msg[start + i]; - for(; i < W.length; i++)W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]); - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f2 = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - minimalisticAssert(this.k.length === W.length); - for(i = 0; i < W.length; i++){ - var T1 = sum32_5$2(h, s1_256$1(e), ch32$1(e, f2, g), this.k[i], W[i]); - var T2 = sum32$2(s0_256$1(a), maj32$1(a, b, c)); - h = g; - g = f2; - f2 = e; - e = sum32$2(d, T1); - d = c; - c = b; - b = a; - a = sum32$2(T1, T2); - } - this.h[0] = sum32$2(this.h[0], a); - this.h[1] = sum32$2(this.h[1], b); - this.h[2] = sum32$2(this.h[2], c); - this.h[3] = sum32$2(this.h[3], d); - this.h[4] = sum32$2(this.h[4], e); - this.h[5] = sum32$2(this.h[5], f2); - this.h[6] = sum32$2(this.h[6], g); - this.h[7] = sum32$2(this.h[7], h); -}; -SHA256.prototype._digest = function digest3(enc) { - if (enc === "hex") return utils.toHex32(this.h, "big"); - else return utils.split32(this.h, "big"); -}; -function SHA224() { - if (!(this instanceof SHA224)) return new SHA224(); - _256.call(this); - this.h = [ - 3238371032, - 914150663, - 812702999, - 4144912697, - 4290775857, - 1750603025, - 1694076839, - 3204075428 - ]; } -utils.inherits(SHA224, _256); -var _224 = SHA224; -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; -SHA224.prototype._digest = function digest4(enc) { - if (enc === "hex") return utils.toHex32(this.h.slice(0, 7), "big"); - else return utils.split32(this.h.slice(0, 7), "big"); -}; -var rotr64_hi$1 = utils.rotr64_hi; -var rotr64_lo$1 = utils.rotr64_lo; -var shr64_hi$1 = utils.shr64_hi; -var shr64_lo$1 = utils.shr64_lo; -var sum64$1 = utils.sum64; -var sum64_hi$1 = utils.sum64_hi; -var sum64_lo$1 = utils.sum64_lo; -var sum64_4_hi$1 = utils.sum64_4_hi; -var sum64_4_lo$1 = utils.sum64_4_lo; -var sum64_5_hi$1 = utils.sum64_5_hi; -var sum64_5_lo$1 = utils.sum64_5_lo; -var BlockHash$3 = common.BlockHash; -var sha512_K = [ - 1116352408, - 3609767458, - 1899447441, - 602891725, - 3049323471, - 3964484399, - 3921009573, - 2173295548, - 961987163, - 4081628472, - 1508970993, - 3053834265, - 2453635748, - 2937671579, - 2870763221, - 3664609560, - 3624381080, - 2734883394, - 310598401, - 1164996542, - 607225278, - 1323610764, - 1426881987, - 3590304994, - 1925078388, - 4068182383, - 2162078206, - 991336113, - 2614888103, - 633803317, - 3248222580, - 3479774868, - 3835390401, - 2666613458, - 4022224774, - 944711139, - 264347078, - 2341262773, - 604807628, - 2007800933, - 770255983, - 1495990901, - 1249150122, - 1856431235, - 1555081692, - 3175218132, - 1996064986, - 2198950837, - 2554220882, - 3999719339, - 2821834349, - 766784016, - 2952996808, - 2566594879, - 3210313671, - 3203337956, - 3336571891, - 1034457026, - 3584528711, - 2466948901, - 113926993, - 3758326383, - 338241895, - 168717936, - 666307205, - 1188179964, - 773529912, - 1546045734, - 1294757372, - 1522805485, - 1396182291, - 2643833823, - 1695183700, - 2343527390, - 1986661051, - 1014477480, - 2177026350, - 1206759142, - 2456956037, - 344077627, - 2730485921, - 1290863460, - 2820302411, - 3158454273, - 3259730800, - 3505952657, - 3345764771, - 106217008, - 3516065817, - 3606008344, - 3600352804, - 1432725776, - 4094571909, - 1467031594, - 275423344, - 851169720, - 430227734, - 3100823752, - 506948616, - 1363258195, - 659060556, - 3750685593, - 883997877, - 3785050280, - 958139571, - 3318307427, - 1322822218, - 3812723403, - 1537002063, - 2003034995, - 1747873779, - 3602036899, - 1955562222, - 1575990012, - 2024104815, - 1125592928, - 2227730452, - 2716904306, - 2361852424, - 442776044, - 2428436474, - 593698344, - 2756734187, - 3733110249, - 3204031479, - 2999351573, - 3329325298, - 3815920427, - 3391569614, - 3928383900, - 3515267271, - 566280711, - 3940187606, - 3454069534, - 4118630271, - 4000239992, - 116418474, - 1914138554, - 174292421, - 2731055270, - 289380356, - 3203993006, - 460393269, - 320620315, - 685471733, - 587496836, - 852142971, - 1086792851, - 1017036298, - 365543100, - 1126000580, - 2618297676, - 1288033470, - 3409855158, - 1501505948, - 4234509866, - 1607167915, - 987167468, - 1816402316, - 1246189591 -]; -function SHA512() { - if (!(this instanceof SHA512)) return new SHA512(); - BlockHash$3.call(this); - this.h = [ - 1779033703, - 4089235720, - 3144134277, - 2227873595, - 1013904242, - 4271175723, - 2773480762, - 1595750129, - 1359893119, - 2917565137, - 2600822924, - 725511199, - 528734635, - 4215389547, - 1541459225, - 327033209 - ]; - this.k = sha512_K; - this.W = new Array(160); -} -utils.inherits(SHA512, BlockHash$3); -var _512 = SHA512; -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - for(var i = 0; i < 32; i++)W[i] = msg[start + i]; - for(; i < W.length; i += 2){ - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; - var c3_lo = W[i - 31]; - W[i] = sum64_4_hi$1(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); - W[i + 1] = sum64_4_lo$1(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo); +function hashMessage(message) { + if (typeof message === "string") { + message = toUtf8Bytes(message); } -}; -SHA512.prototype._update = function _update3(msg, start) { - this._prepareBlock(msg, start); - var W = this.W; - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; - minimalisticAssert(this.k.length === W.length); - for(var i = 0; i < W.length; i += 2){ - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; - var T1_hi = sum64_5_hi$1(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); - var T1_lo = sum64_5_lo$1(c0_hi, c0_lo, c1_hi, c1_lo, c2_hi, c2_lo, c3_hi, c3_lo, c4_hi, c4_lo); - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - var T2_hi = sum64_hi$1(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo$1(c0_hi, c0_lo, c1_hi, c1_lo); - hh = gh; - hl = gl; - gh = fh; - gl = fl; - fh = eh; - fl = el; - eh = sum64_hi$1(dh, dl, T1_hi, T1_lo); - el = sum64_lo$1(dl, dl, T1_hi, T1_lo); - dh = ch; - dl = cl; - ch = bh; - cl = bl; - bh = ah; - bl = al; - ah = sum64_hi$1(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo$1(T1_hi, T1_lo, T2_hi, T2_lo); - } - sum64$1(this.h, 0, ah, al); - sum64$1(this.h, 2, bh, bl); - sum64$1(this.h, 4, ch, cl); - sum64$1(this.h, 6, dh, dl); - sum64$1(this.h, 8, eh, el); - sum64$1(this.h, 10, fh, fl); - sum64$1(this.h, 12, gh, gl); - sum64$1(this.h, 14, hh, hl); -}; -SHA512.prototype._digest = function digest5(enc) { - if (enc === "hex") return utils.toHex32(this.h, "big"); - else return utils.split32(this.h, "big"); -}; -function ch64_hi(xh, xl, yh, yl, zh) { - var r2 = xh & yh ^ ~xh & zh; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r2 = xl & yl ^ ~xl & zl; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function maj64_hi(xh, xl, yh, yl, zh) { - var r2 = xh & yh ^ xh & zh ^ yh & zh; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r2 = xl & yl ^ xl & zl ^ yl & zl; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 28); - var c1_hi = rotr64_hi$1(xl, xh, 2); - var c2_hi = rotr64_hi$1(xl, xh, 7); - var r2 = c0_hi ^ c1_hi ^ c2_hi; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 28); - var c1_lo = rotr64_lo$1(xl, xh, 2); - var c2_lo = rotr64_lo$1(xl, xh, 7); - var r2 = c0_lo ^ c1_lo ^ c2_lo; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 14); - var c1_hi = rotr64_hi$1(xh, xl, 18); - var c2_hi = rotr64_hi$1(xl, xh, 9); - var r2 = c0_hi ^ c1_hi ^ c2_hi; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 14); - var c1_lo = rotr64_lo$1(xh, xl, 18); - var c2_lo = rotr64_lo$1(xl, xh, 9); - var r2 = c0_lo ^ c1_lo ^ c2_lo; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 1); - var c1_hi = rotr64_hi$1(xh, xl, 8); - var c2_hi = shr64_hi$1(xh, xl, 7); - var r2 = c0_hi ^ c1_hi ^ c2_hi; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 1); - var c1_lo = rotr64_lo$1(xh, xl, 8); - var c2_lo = shr64_lo$1(xh, xl, 7); - var r2 = c0_lo ^ c1_lo ^ c2_lo; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi$1(xh, xl, 19); - var c1_hi = rotr64_hi$1(xl, xh, 29); - var c2_hi = shr64_hi$1(xh, xl, 6); - var r2 = c0_hi ^ c1_hi ^ c2_hi; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo$1(xh, xl, 19); - var c1_lo = rotr64_lo$1(xl, xh, 29); - var c2_lo = shr64_lo$1(xh, xl, 6); - var r2 = c0_lo ^ c1_lo ^ c2_lo; - if (r2 < 0) r2 += 4294967296; - return r2; -} -function SHA384() { - if (!(this instanceof SHA384)) return new SHA384(); - _512.call(this); - this.h = [ - 3418070365, - 3238371032, - 1654270250, - 914150663, - 2438529370, - 812702999, - 355462360, - 4144912697, - 1731405415, - 4290775857, - 2394180231, - 1750603025, - 3675008525, - 1694076839, - 1203062813, - 3204075428 - ]; + return keccak256(concat([ + toUtf8Bytes(MessagePrefix), + toUtf8Bytes(String(message.length)), + message + ])); } -utils.inherits(SHA384, _512); -var _384 = SHA384; -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; -SHA384.prototype._digest = function digest6(enc) { - if (enc === "hex") return utils.toHex32(this.h.slice(0, 12), "big"); - else return utils.split32(this.h.slice(0, 12), "big"); -}; -var sha1 = _1; -var sha224 = _224; -var sha256 = _256; -var sha384 = _384; -var sha512 = _512; -var sha = { - sha1, - sha224, - sha256, - sha384, - sha512 -}; -var rotl32$2 = utils.rotl32; -var sum32$3 = utils.sum32; -var sum32_3$1 = utils.sum32_3; -var sum32_4$2 = utils.sum32_4; -var BlockHash$4 = common.BlockHash; -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) return new RIPEMD160(); - BlockHash$4.call(this); - this.h = [ - 1732584193, - 4023233417, - 2562383102, - 271733878, - 3285377520 - ]; - this.endian = "little"; -} -utils.inherits(RIPEMD160, BlockHash$4); -var ripemd160 = RIPEMD160; -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; -RIPEMD160.prototype._update = function update2(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for(var j = 0; j < 80; j++){ - var T = sum32$3(rotl32$2(sum32_4$2(A, f(j, B, C, D), msg[r1[j] + start], K(j)), s[j]), E); - A = E; - E = D; - D = rotl32$2(C, 10); - C = B; - B = T; - T = sum32$3(rotl32$2(sum32_4$2(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), sh[j]), Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32$2(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3$1(this.h[1], C, Dh); - this.h[1] = sum32_3$1(this.h[2], D, Eh); - this.h[2] = sum32_3$1(this.h[3], E, Ah); - this.h[3] = sum32_3$1(this.h[4], A, Bh); - this.h[4] = sum32_3$1(this.h[0], B, Ch); - this.h[0] = T; -}; -RIPEMD160.prototype._digest = function digest7(enc) { - if (enc === "hex") return utils.toHex32(this.h, "little"); - else return utils.split32(this.h, "little"); +function verifyMessage(message, sig) { + const digest = hashMessage(message); + return recoverAddress(digest, sig); +} +const regexBytes = new RegExp("^bytes([0-9]+)$"); +const regexNumber = new RegExp("^(u?int)([0-9]*)$"); +const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$"); +function _pack(type, value, isArray) { + switch(type){ + case "address": + if (isArray) { + return getBytes(zeroPadValue(value, 32)); + } + return getBytes(getAddress(value)); + case "string": + return toUtf8Bytes(value); + case "bytes": + return getBytes(value); + case "bool": + value = !!value ? "0x01" : "0x00"; + if (isArray) { + return getBytes(zeroPadValue(value, 32)); + } + return getBytes(value); + } + let match = type.match(regexNumber); + if (match) { + let signed = match[1] === "int"; + let size = parseInt(match[2] || "256"); + assertArgument((!match[2] || match[2] === String(size)) && size % 8 === 0 && size !== 0 && size <= 256, "invalid number type", "type", type); + if (isArray) { + size = 256; + } + if (signed) { + value = toTwos(value, size); + } + return getBytes(zeroPadValue(toBeArray(value), size / 8)); + } + match = type.match(regexBytes); + if (match) { + const size = parseInt(match[1]); + assertArgument(String(size) === match[1] && size !== 0 && size <= 32, "invalid bytes type", "type", type); + assertArgument(dataLength(value) === size, `invalid value for ${type}`, "value", value); + if (isArray) { + return getBytes(zeroPadBytes(value, 32)); + } + return value; + } + match = type.match(regexArray); + if (match && Array.isArray(value)) { + const baseType = match[1]; + const count = parseInt(match[2] || String(value.length)); + assertArgument(count === value.length, `invalid array length for ${type}`, "value", value); + const result = []; + value.forEach(function(value) { + result.push(_pack(baseType, value, true)); + }); + return getBytes(concat(result)); + } + assertArgument(false, "invalid type", "type", type); +} +function solidityPacked(types, values) { + assertArgument(types.length === values.length, "wrong number of values; expected ${ types.length }", "values", values); + const tight = []; + types.forEach(function(type, index) { + tight.push(_pack(type, values[index])); + }); + return hexlify(concat(tight)); +} +function solidityPackedKeccak256(types, values) { + return keccak256(solidityPacked(types, values)); +} +function solidityPackedSha256(types, values) { + return sha256(solidityPacked(types, values)); +} +const padding = new Uint8Array(32); +padding.fill(0); +const BN__1 = BigInt(-1); +const BN_0$3 = BigInt(0); +const BN_1$1 = BigInt(1); +const BN_MAX_UINT256 = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); +function hexPadRight(value) { + const bytes = getBytes(value); + const padOffset = bytes.length % 32; + if (padOffset) { + return concat([ + bytes, + padding.slice(padOffset) + ]); + } + return hexlify(bytes); +} +const hexTrue = toBeHex(BN_1$1, 32); +const hexFalse = toBeHex(BN_0$3, 32); +const domainFieldTypes = { + name: "string", + version: "string", + chainId: "uint256", + verifyingContract: "address", + salt: "bytes32" }; -function f(j, x, y, z) { - if (j <= 15) return x ^ y ^ z; - else if (j <= 31) return x & y | ~x & z; - else if (j <= 47) return (x | ~y) ^ z; - else if (j <= 63) return x & z | y & ~z; - else return x ^ (y | ~z); +const domainFieldNames = [ + "name", + "version", + "chainId", + "verifyingContract", + "salt" +]; +function checkString(key) { + return function(value) { + assertArgument(typeof value === "string", `invalid domain value for ${JSON.stringify(key)}`, `domain.${key}`, value); + return value; + }; } -function K(j) { - if (j <= 15) return 0; - else if (j <= 31) return 1518500249; - else if (j <= 47) return 1859775393; - else if (j <= 63) return 2400959708; - else return 2840853838; -} -function Kh(j) { - if (j <= 15) return 1352829926; - else if (j <= 31) return 1548603684; - else if (j <= 47) return 1836072691; - else if (j <= 63) return 2053994217; - else return 0; -} -var r1 = [ - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 10, - 11, - 12, - 13, - 14, - 15, - 7, - 4, - 13, - 1, - 10, - 6, - 15, - 3, - 12, - 0, - 9, - 5, - 2, - 14, - 11, - 8, - 3, - 10, - 14, - 4, - 9, - 15, - 8, - 1, - 2, - 7, - 0, - 6, - 13, - 11, - 5, - 12, - 1, - 9, - 11, - 10, - 0, - 8, - 12, - 4, - 13, - 3, - 7, - 15, - 14, - 5, - 6, - 2, - 4, - 0, - 5, - 9, - 7, - 12, - 2, - 10, - 14, - 1, - 3, - 8, - 11, - 6, - 15, - 13 -]; -var rh = [ - 5, - 14, - 7, - 0, - 9, - 2, - 11, - 4, - 13, - 6, - 15, - 8, - 1, - 10, - 3, - 12, - 6, - 11, - 3, - 7, - 0, - 13, - 5, - 10, - 14, - 15, - 8, - 12, - 4, - 9, - 1, - 2, - 15, - 5, - 1, - 3, - 7, - 14, - 6, - 9, - 11, - 8, - 12, - 2, - 10, - 0, - 4, - 13, - 8, - 6, - 4, - 1, - 3, - 11, - 15, - 0, - 5, - 12, - 2, - 13, - 9, - 7, - 10, - 14, - 12, - 15, - 10, - 4, - 1, - 5, - 8, - 7, - 6, - 2, - 13, - 14, - 0, - 3, - 9, - 11 -]; -var s = [ - 11, - 14, - 15, - 12, - 5, - 8, - 7, - 9, - 11, - 13, - 14, - 15, - 6, - 7, - 9, - 8, - 7, - 6, - 8, - 13, - 11, - 9, - 7, - 15, - 7, - 12, - 15, - 9, - 11, - 7, - 13, - 12, - 11, - 13, - 6, - 7, - 14, - 9, - 13, - 15, - 14, - 8, - 13, - 6, - 5, - 12, - 7, - 5, - 11, - 12, - 14, - 15, - 14, - 15, - 9, - 8, - 9, - 14, - 5, - 6, - 8, - 6, - 5, - 12, - 9, - 15, - 5, - 11, - 6, - 8, - 13, - 12, - 5, - 12, - 13, - 14, - 11, - 8, - 5, - 6 -]; -var sh = [ - 8, - 9, - 9, - 11, - 13, - 15, - 15, - 5, - 7, - 7, - 8, - 11, - 14, - 14, - 12, - 6, - 9, - 13, - 15, - 7, - 12, - 8, - 9, - 11, - 7, - 7, - 12, - 7, - 6, - 15, - 13, - 11, - 9, - 7, - 15, - 11, - 8, - 6, - 6, - 14, - 12, - 13, - 5, - 14, - 13, - 13, - 7, - 5, - 15, - 5, - 8, - 11, - 14, - 14, - 6, - 14, - 6, - 9, - 12, - 9, - 12, - 5, - 15, - 8, - 8, - 5, - 12, - 9, - 12, - 5, - 14, - 6, - 8, - 13, - 6, - 5, - 15, - 13, - 11, - 11 -]; -var ripemd = { - ripemd160 +const domainChecks = { + name: checkString("name"), + version: checkString("version"), + chainId: function(_value) { + const value = getBigInt(_value, "domain.chainId"); + assertArgument(value >= 0, "invalid chain ID", "domain.chainId", _value); + if (Number.isSafeInteger(value)) { + return Number(value); + } + return toQuantity(value); + }, + verifyingContract: function(value) { + try { + return getAddress(value).toLowerCase(); + } catch (error) {} + assertArgument(false, `invalid domain value "verifyingContract"`, "domain.verifyingContract", value); + }, + salt: function(value) { + const bytes = getBytes(value, "domain.salt"); + assertArgument(bytes.length === 32, `invalid domain value "salt"`, "domain.salt", value); + return hexlify(bytes); + } }; -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - this._init(utils.toArray(key, enc)); -} -var hmac = Hmac; -Hmac.prototype._init = function init(key) { - if (key.length > this.blockSize) key = new this.Hash().update(key).digest(); - minimalisticAssert(key.length <= this.blockSize); - for(var i = key.length; i < this.blockSize; i++)key.push(0); - for(i = 0; i < key.length; i++)key[i] ^= 54; - this.inner = new this.Hash().update(key); - for(i = 0; i < key.length; i++)key[i] ^= 106; - this.outer = new this.Hash().update(key); +function getBaseEncoder(type) { + { + const match = type.match(/^(u?)int(\d+)$/); + if (match) { + const signed = match[1] === ""; + const width = parseInt(match[2]); + assertArgument(width % 8 === 0 && width !== 0 && width <= 256 && match[2] === String(width), "invalid numeric width", "type", type); + const boundsUpper = mask(BN_MAX_UINT256, signed ? width - 1 : width); + const boundsLower = signed ? (boundsUpper + BN_1$1) * BN__1 : BN_0$3; + return function(_value) { + const value = getBigInt(_value, "value"); + assertArgument(value >= boundsLower && value <= boundsUpper, `value out-of-bounds for ${type}`, "value", value); + return toBeHex(signed ? toTwos(value, 256) : value, 32); + }; + } + } + { + const match = type.match(/^bytes(\d+)$/); + if (match) { + const width = parseInt(match[1]); + assertArgument(width !== 0 && width <= 32 && match[1] === String(width), "invalid bytes width", "type", type); + return function(value) { + const bytes = getBytes(value); + assertArgument(bytes.length === width, `invalid length for ${type}`, "value", value); + return hexPadRight(value); + }; + } + } + switch(type){ + case "address": + return function(value) { + return zeroPadValue(getAddress(value), 32); + }; + case "bool": + return function(value) { + return !value ? hexFalse : hexTrue; + }; + case "bytes": + return function(value) { + return keccak256(value); + }; + case "string": + return function(value) { + return id(value); + }; + } + return null; +} +function encodeType(name, fields) { + return `${name}(${fields.map(({ name, type })=>type + " " + name).join(",")})`; +} +function splitArray(type) { + const match = type.match(/^([^\x5b]*)((\x5b\d*\x5d)*)(\x5b(\d*)\x5d)$/); + if (match) { + return { + base: match[1], + index: match[2] + match[4], + array: { + base: match[1], + prefix: match[1] + match[2], + count: match[5] ? parseInt(match[5]) : -1 + } + }; + } + return { + base: type + }; +} +class TypedDataEncoder { + primaryType; + #types; + get types() { + return JSON.parse(this.#types); + } + #fullTypes; + #encoderCache; + constructor(_types){ + this.#fullTypes = new Map; + this.#encoderCache = new Map; + const links = new Map; + const parents = new Map; + const subtypes = new Map; + const types = {}; + Object.keys(_types).forEach((type)=>{ + types[type] = _types[type].map(({ name, type })=>{ + let { base, index } = splitArray(type); + if (base === "int" && !_types["int"]) { + base = "int256"; + } + if (base === "uint" && !_types["uint"]) { + base = "uint256"; + } + return { + name: name, + type: base + (index || "") + }; + }); + links.set(type, new Set); + parents.set(type, []); + subtypes.set(type, new Set); + }); + this.#types = JSON.stringify(types); + for(const name in types){ + const uniqueNames = new Set; + for (const field of types[name]){ + assertArgument(!uniqueNames.has(field.name), `duplicate variable name ${JSON.stringify(field.name)} in ${JSON.stringify(name)}`, "types", _types); + uniqueNames.add(field.name); + const baseType = splitArray(field.type).base; + assertArgument(baseType !== name, `circular type reference to ${JSON.stringify(baseType)}`, "types", _types); + const encoder = getBaseEncoder(baseType); + if (encoder) { + continue; + } + assertArgument(parents.has(baseType), `unknown type ${JSON.stringify(baseType)}`, "types", _types); + parents.get(baseType).push(name); + links.get(name).add(baseType); + } + } + const primaryTypes = Array.from(parents.keys()).filter((n)=>parents.get(n).length === 0); + assertArgument(primaryTypes.length !== 0, "missing primary type", "types", _types); + assertArgument(primaryTypes.length === 1, `ambiguous primary types or unused types: ${primaryTypes.map((t)=>JSON.stringify(t)).join(", ")}`, "types", _types); + defineProperties(this, { + primaryType: primaryTypes[0] + }); + function checkCircular(type, found) { + assertArgument(!found.has(type), `circular type reference to ${JSON.stringify(type)}`, "types", _types); + found.add(type); + for (const child of links.get(type)){ + if (!parents.has(child)) { + continue; + } + checkCircular(child, found); + for (const subtype of found){ + subtypes.get(subtype).add(child); + } + } + found.delete(type); + } + checkCircular(this.primaryType, new Set); + for (const [name, set] of subtypes){ + const st = Array.from(set); + st.sort(); + this.#fullTypes.set(name, encodeType(name, types[name]) + st.map((t)=>encodeType(t, types[t])).join("")); + } + } + getEncoder(type) { + let encoder = this.#encoderCache.get(type); + if (!encoder) { + encoder = this.#getEncoder(type); + this.#encoderCache.set(type, encoder); + } + return encoder; + } + #getEncoder(type) { + { + const encoder = getBaseEncoder(type); + if (encoder) { + return encoder; + } + } + const array = splitArray(type).array; + if (array) { + const subtype = array.prefix; + const subEncoder = this.getEncoder(subtype); + return (value)=>{ + assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value); + let result = value.map(subEncoder); + if (this.#fullTypes.has(subtype)) { + result = result.map(keccak256); + } + return keccak256(concat(result)); + }; + } + const fields = this.types[type]; + if (fields) { + const encodedType = id(this.#fullTypes.get(type)); + return (value)=>{ + const values = fields.map(({ name, type })=>{ + const result = this.getEncoder(type)(value[name]); + if (this.#fullTypes.has(type)) { + return keccak256(result); + } + return result; + }); + values.unshift(encodedType); + return concat(values); + }; + } + assertArgument(false, `unknown type: ${type}`, "type", type); + } + encodeType(name) { + const result = this.#fullTypes.get(name); + assertArgument(result, `unknown type: ${JSON.stringify(name)}`, "name", name); + return result; + } + encodeData(type, value) { + return this.getEncoder(type)(value); + } + hashStruct(name, value) { + return keccak256(this.encodeData(name, value)); + } + encode(value) { + return this.encodeData(this.primaryType, value); + } + hash(value) { + return this.hashStruct(this.primaryType, value); + } + _visit(type, value, callback) { + { + const encoder = getBaseEncoder(type); + if (encoder) { + return callback(type, value); + } + } + const array = splitArray(type).array; + if (array) { + assertArgument(array.count === -1 || array.count === value.length, `array length mismatch; expected length ${array.count}`, "value", value); + return value.map((v)=>this._visit(array.prefix, v, callback)); + } + const fields = this.types[type]; + if (fields) { + return fields.reduce((accum, { name, type })=>{ + accum[name] = this._visit(type, value[name], callback); + return accum; + }, {}); + } + assertArgument(false, `unknown type: ${type}`, "type", type); + } + visit(value, callback) { + return this._visit(this.primaryType, value, callback); + } + static from(types) { + return new TypedDataEncoder(types); + } + static getPrimaryType(types) { + return TypedDataEncoder.from(types).primaryType; + } + static hashStruct(name, types, value) { + return TypedDataEncoder.from(types).hashStruct(name, value); + } + static hashDomain(domain) { + const domainFields = []; + for(const name in domain){ + if (domain[name] == null) { + continue; + } + const type = domainFieldTypes[name]; + assertArgument(type, `invalid typed-data domain key: ${JSON.stringify(name)}`, "domain", domain); + domainFields.push({ + name: name, + type: type + }); + } + domainFields.sort((a, b)=>{ + return domainFieldNames.indexOf(a.name) - domainFieldNames.indexOf(b.name); + }); + return TypedDataEncoder.hashStruct("EIP712Domain", { + EIP712Domain: domainFields + }, domain); + } + static encode(domain, types, value) { + return concat([ + "0x1901", + TypedDataEncoder.hashDomain(domain), + TypedDataEncoder.from(types).hash(value) + ]); + } + static hash(domain, types, value) { + return keccak256(TypedDataEncoder.encode(domain, types, value)); + } + static async resolveNames(domain, types, value, resolveName) { + domain = Object.assign({}, domain); + for(const key in domain){ + if (domain[key] == null) { + delete domain[key]; + } + } + const ensCache = {}; + if (domain.verifyingContract && !isHexString(domain.verifyingContract, 20)) { + ensCache[domain.verifyingContract] = "0x"; + } + const encoder = TypedDataEncoder.from(types); + encoder.visit(value, (type, value)=>{ + if (type === "address" && !isHexString(value, 20)) { + ensCache[value] = "0x"; + } + return value; + }); + for(const name in ensCache){ + ensCache[name] = await resolveName(name); + } + if (domain.verifyingContract && ensCache[domain.verifyingContract]) { + domain.verifyingContract = ensCache[domain.verifyingContract]; + } + value = encoder.visit(value, (type, value)=>{ + if (type === "address" && ensCache[value]) { + return ensCache[value]; + } + return value; + }); + return { + domain: domain, + value: value + }; + } + static getPayload(domain, types, value) { + TypedDataEncoder.hashDomain(domain); + const domainValues = {}; + const domainTypes = []; + domainFieldNames.forEach((name)=>{ + const value = domain[name]; + if (value == null) { + return; + } + domainValues[name] = domainChecks[name](value); + domainTypes.push({ + name: name, + type: domainFieldTypes[name] + }); + }); + const encoder = TypedDataEncoder.from(types); + types = encoder.types; + const typesWithDomain = Object.assign({}, types); + assertArgument(typesWithDomain.EIP712Domain == null, "types must not contain EIP712Domain type", "types.EIP712Domain", types); + typesWithDomain.EIP712Domain = domainTypes; + encoder.encode(value); + return { + types: typesWithDomain, + domain: domainValues, + primaryType: encoder.primaryType, + message: encoder.visit(value, (type, value)=>{ + if (type.match(/^bytes(\d*)/)) { + return hexlify(getBytes(value)); + } + if (type.match(/^u?int/)) { + return getBigInt(value).toString(); + } + switch(type){ + case "address": + return value.toLowerCase(); + case "bool": + return !!value; + case "string": + assertArgument(typeof value === "string", "invalid string", "value", value); + return value; + } + assertArgument(false, "unsupported type", "type", type); + }) + }; + } +} +function verifyTypedData(domain, types, value, signature) { + return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature); +} +function setify(items) { + const result = new Set; + items.forEach((k)=>result.add(k)); + return Object.freeze(result); +} +const _kwVisibDeploy = "external public payable override"; +const KwVisibDeploy = setify(_kwVisibDeploy.split(" ")); +const _kwVisib = "constant external internal payable private public pure view override"; +const KwVisib = setify(_kwVisib.split(" ")); +const _kwTypes = "constructor error event fallback function receive struct"; +const KwTypes = setify(_kwTypes.split(" ")); +const _kwModifiers = "calldata memory storage payable indexed"; +const KwModifiers = setify(_kwModifiers.split(" ")); +const _kwOther = "tuple returns"; +const _keywords = [ + _kwTypes, + _kwModifiers, + _kwOther, + _kwVisib +].join(" "); +const Keywords = setify(_keywords.split(" ")); +const SimpleTokens = { + "(": "OPEN_PAREN", + ")": "CLOSE_PAREN", + "[": "OPEN_BRACKET", + "]": "CLOSE_BRACKET", + ",": "COMMA", + "@": "AT" }; -Hmac.prototype.update = function update3(msg, enc) { - this.inner.update(msg, enc); - return this; +const regexWhitespacePrefix = new RegExp("^(\\s*)"); +const regexNumberPrefix = new RegExp("^([0-9]+)"); +const regexIdPrefix = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)"); +const regexId = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$"); +const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$"); +class TokenString { + #offset; + #tokens; + get offset() { + return this.#offset; + } + get length() { + return this.#tokens.length - this.#offset; + } + constructor(tokens){ + this.#offset = 0; + this.#tokens = tokens.slice(); + } + clone() { + return new TokenString(this.#tokens); + } + reset() { + this.#offset = 0; + } + #subTokenString(from = 0, to = 0) { + return new TokenString(this.#tokens.slice(from, to).map((t)=>{ + return Object.freeze(Object.assign({}, t, { + match: t.match - from, + linkBack: t.linkBack - from, + linkNext: t.linkNext - from + })); + })); + } + popKeyword(allowed) { + const top = this.peek(); + if (top.type !== "KEYWORD" || !allowed.has(top.text)) { + throw new Error(`expected keyword ${top.text}`); + } + return this.pop().text; + } + popType(type) { + if (this.peek().type !== type) { + const top = this.peek(); + throw new Error(`expected ${type}; got ${top.type} ${JSON.stringify(top.text)}`); + } + return this.pop().text; + } + popParen() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = this.#subTokenString(this.#offset + 1, top.match + 1); + this.#offset = top.match + 1; + return result; + } + popParams() { + const top = this.peek(); + if (top.type !== "OPEN_PAREN") { + throw new Error("bad start"); + } + const result = []; + while(this.#offset < top.match - 1){ + const link = this.peek().linkNext; + result.push(this.#subTokenString(this.#offset + 1, link)); + this.#offset = link; + } + this.#offset = top.match + 1; + return result; + } + peek() { + if (this.#offset >= this.#tokens.length) { + throw new Error("out-of-bounds"); + } + return this.#tokens[this.#offset]; + } + peekKeyword(allowed) { + const top = this.peekType("KEYWORD"); + return top != null && allowed.has(top) ? top : null; + } + peekType(type) { + if (this.length === 0) { + return null; + } + const top = this.peek(); + return top.type === type ? top.text : null; + } + pop() { + const result = this.peek(); + this.#offset++; + return result; + } + toString() { + const tokens = []; + for(let i = this.#offset; i < this.#tokens.length; i++){ + const token = this.#tokens[i]; + tokens.push(`${token.type}:${token.text}`); + } + return ``; + } +} +function lex(text) { + const tokens = []; + const throwError = (message)=>{ + const token = offset < text.length ? JSON.stringify(text[offset]) : "$EOI"; + throw new Error(`invalid token ${token} at ${offset}: ${message}`); + }; + let brackets = []; + let commas = []; + let offset = 0; + while(offset < text.length){ + let cur = text.substring(offset); + let match = cur.match(regexWhitespacePrefix); + if (match) { + offset += match[1].length; + cur = text.substring(offset); + } + const token = { + depth: brackets.length, + linkBack: -1, + linkNext: -1, + match: -1, + type: "", + text: "", + offset: offset, + value: -1 + }; + tokens.push(token); + let type = SimpleTokens[cur[0]] || ""; + if (type) { + token.type = type; + token.text = cur[0]; + offset++; + if (type === "OPEN_PAREN") { + brackets.push(tokens.length - 1); + commas.push(tokens.length - 1); + } else if (type == "CLOSE_PAREN") { + if (brackets.length === 0) { + throwError("no matching open bracket"); + } + token.match = brackets.pop(); + tokens[token.match].match = tokens.length - 1; + token.depth--; + token.linkBack = commas.pop(); + tokens[token.linkBack].linkNext = tokens.length - 1; + } else if (type === "COMMA") { + token.linkBack = commas.pop(); + tokens[token.linkBack].linkNext = tokens.length - 1; + commas.push(tokens.length - 1); + } else if (type === "OPEN_BRACKET") { + token.type = "BRACKET"; + } else if (type === "CLOSE_BRACKET") { + let suffix = tokens.pop().text; + if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") { + const value = tokens.pop().text; + suffix = value + suffix; + tokens[tokens.length - 1].value = getNumber(value); + } + if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") { + throw new Error("missing opening bracket"); + } + tokens[tokens.length - 1].text += suffix; + } + continue; + } + match = cur.match(regexIdPrefix); + if (match) { + token.text = match[1]; + offset += token.text.length; + if (Keywords.has(token.text)) { + token.type = "KEYWORD"; + continue; + } + if (token.text.match(regexType)) { + token.type = "TYPE"; + continue; + } + token.type = "ID"; + continue; + } + match = cur.match(regexNumberPrefix); + if (match) { + token.text = match[1]; + token.type = "NUMBER"; + offset += token.text.length; + continue; + } + throw new Error(`unexpected token ${JSON.stringify(cur[0])} at position ${offset}`); + } + return new TokenString(tokens.map((t)=>Object.freeze(t))); +} +function allowSingle(set, allowed) { + let included = []; + for(const key in allowed.keys()){ + if (set.has(key)) { + included.push(key); + } + } + if (included.length > 1) { + throw new Error(`conflicting types: ${included.join(", ")}`); + } +} +function consumeName(type, tokens) { + if (tokens.peekKeyword(KwTypes)) { + const keyword = tokens.pop().text; + if (keyword !== type) { + throw new Error(`expected ${type}, got ${keyword}`); + } + } + return tokens.popType("ID"); +} +function consumeKeywords(tokens, allowed) { + const keywords = new Set; + while(true){ + const keyword = tokens.peekType("KEYWORD"); + if (keyword == null || allowed && !allowed.has(keyword)) { + break; + } + tokens.pop(); + if (keywords.has(keyword)) { + throw new Error(`duplicate keywords: ${JSON.stringify(keyword)}`); + } + keywords.add(keyword); + } + return Object.freeze(keywords); +} +function consumeMutability(tokens) { + let modifiers = consumeKeywords(tokens, KwVisib); + allowSingle(modifiers, setify("constant payable nonpayable".split(" "))); + allowSingle(modifiers, setify("pure view payable nonpayable".split(" "))); + if (modifiers.has("view")) { + return "view"; + } + if (modifiers.has("pure")) { + return "pure"; + } + if (modifiers.has("payable")) { + return "payable"; + } + if (modifiers.has("nonpayable")) { + return "nonpayable"; + } + if (modifiers.has("constant")) { + return "view"; + } + return "nonpayable"; +} +function consumeParams(tokens, allowIndexed) { + return tokens.popParams().map((t)=>ParamType.from(t, allowIndexed)); +} +function consumeGas(tokens) { + if (tokens.peekType("AT")) { + tokens.pop(); + if (tokens.peekType("NUMBER")) { + return getBigInt(tokens.pop().text); + } + throw new Error("invalid gas"); + } + return null; +} +function consumeEoi(tokens) { + if (tokens.length) { + throw new Error(`unexpected tokens at offset ${tokens.offset}: ${tokens.toString()}`); + } +} +const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/); +function verifyBasicType(type) { + const match = type.match(regexType); + assertArgument(match, "invalid type", "type", type); + if (type === "uint") { + return "uint256"; + } + if (type === "int") { + return "int256"; + } + if (match[2]) { + const length = parseInt(match[2]); + assertArgument(length !== 0 && length <= 32, "invalid bytes length", "type", type); + } else if (match[3]) { + const size = parseInt(match[3]); + assertArgument(size !== 0 && size <= 256 && size % 8 === 0, "invalid numeric width", "type", type); + } + return type; +} +const _guard$2 = {}; +const internal$1 = Symbol.for("_ethers_internal"); +const ParamTypeInternal = "_ParamTypeInternal"; +const ErrorFragmentInternal = "_ErrorInternal"; +const EventFragmentInternal = "_EventInternal"; +const ConstructorFragmentInternal = "_ConstructorInternal"; +const FallbackFragmentInternal = "_FallbackInternal"; +const FunctionFragmentInternal = "_FunctionInternal"; +const StructFragmentInternal = "_StructInternal"; +class ParamType { + name; + type; + baseType; + indexed; + components; + arrayLength; + arrayChildren; + constructor(guard, name, type, baseType, indexed, components, arrayLength, arrayChildren){ + assertPrivate(guard, _guard$2, "ParamType"); + Object.defineProperty(this, internal$1, { + value: ParamTypeInternal + }); + if (components) { + components = Object.freeze(components.slice()); + } + if (baseType === "array") { + if (arrayLength == null || arrayChildren == null) { + throw new Error(""); + } + } else if (arrayLength != null || arrayChildren != null) { + throw new Error(""); + } + if (baseType === "tuple") { + if (components == null) { + throw new Error(""); + } + } else if (components != null) { + throw new Error(""); + } + defineProperties(this, { + name: name, + type: type, + baseType: baseType, + indexed: indexed, + components: components, + arrayLength: arrayLength, + arrayChildren: arrayChildren + }); + } + format(format) { + if (format == null) { + format = "sighash"; + } + if (format === "json") { + const name = this.name || ""; + if (this.isArray()) { + const result = JSON.parse(this.arrayChildren.format("json")); + result.name = name; + result.type += `[${this.arrayLength < 0 ? "" : String(this.arrayLength)}]`; + return JSON.stringify(result); + } + const result = { + type: this.baseType === "tuple" ? "tuple" : this.type, + name: name + }; + if (typeof this.indexed === "boolean") { + result.indexed = this.indexed; + } + if (this.isTuple()) { + result.components = this.components.map((c)=>JSON.parse(c.format(format))); + } + return JSON.stringify(result); + } + let result = ""; + if (this.isArray()) { + result += this.arrayChildren.format(format); + result += `[${this.arrayLength < 0 ? "" : String(this.arrayLength)}]`; + } else { + if (this.isTuple()) { + result += "(" + this.components.map((comp)=>comp.format(format)).join(format === "full" ? ", " : ",") + ")"; + } else { + result += this.type; + } + } + if (format !== "sighash") { + if (this.indexed === true) { + result += " indexed"; + } + if (format === "full" && this.name) { + result += " " + this.name; + } + } + return result; + } + isArray() { + return this.baseType === "array"; + } + isTuple() { + return this.baseType === "tuple"; + } + isIndexable() { + return this.indexed != null; + } + walk(value, process) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invalid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + const _this = this; + return value.map((v)=>_this.arrayChildren.walk(v, process)); + } + if (this.isTuple()) { + if (!Array.isArray(value)) { + throw new Error("invalid tuple value"); + } + if (value.length !== this.components.length) { + throw new Error("array is wrong length"); + } + const _this = this; + return value.map((v, i)=>_this.components[i].walk(v, process)); + } + return process(this.type, value); + } + #walkAsync(promises, value, process, setValue) { + if (this.isArray()) { + if (!Array.isArray(value)) { + throw new Error("invalid array value"); + } + if (this.arrayLength !== -1 && value.length !== this.arrayLength) { + throw new Error("array is wrong length"); + } + const childType = this.arrayChildren; + const result = value.slice(); + result.forEach((value, index)=>{ + childType.#walkAsync(promises, value, process, (value)=>{ + result[index] = value; + }); + }); + setValue(result); + return; + } + if (this.isTuple()) { + const components = this.components; + let result; + if (Array.isArray(value)) { + result = value.slice(); + } else { + if (value == null || typeof value !== "object") { + throw new Error("invalid tuple value"); + } + result = components.map((param)=>{ + if (!param.name) { + throw new Error("cannot use object value with unnamed components"); + } + if (!(param.name in value)) { + throw new Error(`missing value for component ${param.name}`); + } + return value[param.name]; + }); + } + if (result.length !== this.components.length) { + throw new Error("array is wrong length"); + } + result.forEach((value, index)=>{ + components[index].#walkAsync(promises, value, process, (value)=>{ + result[index] = value; + }); + }); + setValue(result); + return; + } + const result = process(this.type, value); + if (result.then) { + promises.push(async function() { + setValue(await result); + }()); + } else { + setValue(result); + } + } + async walkAsync(value, process) { + const promises = []; + const result = [ + value + ]; + this.#walkAsync(promises, value, process, (value)=>{ + result[0] = value; + }); + if (promises.length) { + await Promise.all(promises); + } + return result[0]; + } + static from(obj, allowIndexed) { + if (ParamType.isParamType(obj)) { + return obj; + } + if (typeof obj === "string") { + try { + return ParamType.from(lex(obj), allowIndexed); + } catch (error) { + assertArgument(false, "invalid param type", "obj", obj); + } + } else if (obj instanceof TokenString) { + let type = "", baseType = ""; + let comps = null; + if (consumeKeywords(obj, setify([ + "tuple" + ])).has("tuple") || obj.peekType("OPEN_PAREN")) { + baseType = "tuple"; + comps = obj.popParams().map((t)=>ParamType.from(t)); + type = `tuple(${comps.map((c)=>c.format()).join(",")})`; + } else { + type = verifyBasicType(obj.popType("TYPE")); + baseType = type; + } + let arrayChildren = null; + let arrayLength = null; + while(obj.length && obj.peekType("BRACKET")){ + const bracket = obj.pop(); + arrayChildren = new ParamType(_guard$2, "", type, baseType, null, comps, arrayLength, arrayChildren); + arrayLength = bracket.value; + type += bracket.text; + baseType = "array"; + comps = null; + } + let indexed = null; + const keywords = consumeKeywords(obj, KwModifiers); + if (keywords.has("indexed")) { + if (!allowIndexed) { + throw new Error(""); + } + indexed = true; + } + const name = obj.peekType("ID") ? obj.pop().text : ""; + if (obj.length) { + throw new Error("leftover tokens"); + } + return new ParamType(_guard$2, name, type, baseType, indexed, comps, arrayLength, arrayChildren); + } + const name = obj.name; + assertArgument(!name || typeof name === "string" && name.match(regexId), "invalid name", "obj.name", name); + let indexed = obj.indexed; + if (indexed != null) { + assertArgument(allowIndexed, "parameter cannot be indexed", "obj.indexed", obj.indexed); + indexed = !!indexed; + } + let type = obj.type; + let arrayMatch = type.match(regexArrayType); + if (arrayMatch) { + const arrayLength = parseInt(arrayMatch[2] || "-1"); + const arrayChildren = ParamType.from({ + type: arrayMatch[1], + components: obj.components + }); + return new ParamType(_guard$2, name || "", type, "array", indexed, null, arrayLength, arrayChildren); + } + if (type === "tuple" || type.startsWith("tuple(") || type.startsWith("(")) { + const comps = obj.components != null ? obj.components.map((c)=>ParamType.from(c)) : null; + const tuple = new ParamType(_guard$2, name || "", type, "tuple", indexed, comps, null, null); + return tuple; + } + type = verifyBasicType(obj.type); + return new ParamType(_guard$2, name || "", type, type, indexed, null, null, null); + } + static isParamType(value) { + return value && value[internal$1] === ParamTypeInternal; + } +} +class Fragment { + type; + inputs; + constructor(guard, type, inputs){ + assertPrivate(guard, _guard$2, "Fragment"); + inputs = Object.freeze(inputs.slice()); + defineProperties(this, { + type: type, + inputs: inputs + }); + } + static from(obj) { + if (typeof obj === "string") { + try { + Fragment.from(JSON.parse(obj)); + } catch (e) {} + return Fragment.from(lex(obj)); + } + if (obj instanceof TokenString) { + const type = obj.peekKeyword(KwTypes); + switch(type){ + case "constructor": + return ConstructorFragment.from(obj); + case "error": + return ErrorFragment.from(obj); + case "event": + return EventFragment.from(obj); + case "fallback": + case "receive": + return FallbackFragment.from(obj); + case "function": + return FunctionFragment.from(obj); + case "struct": + return StructFragment.from(obj); + } + } else if (typeof obj === "object") { + switch(obj.type){ + case "constructor": + return ConstructorFragment.from(obj); + case "error": + return ErrorFragment.from(obj); + case "event": + return EventFragment.from(obj); + case "fallback": + case "receive": + return FallbackFragment.from(obj); + case "function": + return FunctionFragment.from(obj); + case "struct": + return StructFragment.from(obj); + } + assert1(false, `unsupported type: ${obj.type}`, "UNSUPPORTED_OPERATION", { + operation: "Fragment.from" + }); + } + assertArgument(false, "unsupported frgament object", "obj", obj); + } + static isConstructor(value) { + return ConstructorFragment.isFragment(value); + } + static isError(value) { + return ErrorFragment.isFragment(value); + } + static isEvent(value) { + return EventFragment.isFragment(value); + } + static isFunction(value) { + return FunctionFragment.isFragment(value); + } + static isStruct(value) { + return StructFragment.isFragment(value); + } +} +class NamedFragment extends Fragment { + name; + constructor(guard, type, name, inputs){ + super(guard, type, inputs); + assertArgument(typeof name === "string" && name.match(regexId), "invalid identifier", "name", name); + inputs = Object.freeze(inputs.slice()); + defineProperties(this, { + name: name + }); + } +} +function joinParams(format, params) { + return "(" + params.map((p)=>p.format(format)).join(format === "full" ? ", " : ",") + ")"; +} +class ErrorFragment extends NamedFragment { + constructor(guard, name, inputs){ + super(guard, "error", name, inputs); + Object.defineProperty(this, internal$1, { + value: ErrorFragmentInternal + }); + } + get selector() { + return id(this.format("sighash")).substring(0, 10); + } + format(format) { + if (format == null) { + format = "sighash"; + } + if (format === "json") { + return JSON.stringify({ + type: "error", + name: this.name, + inputs: this.inputs.map((input)=>JSON.parse(input.format(format))) + }); + } + const result = []; + if (format !== "sighash") { + result.push("error"); + } + result.push(this.name + joinParams(format, this.inputs)); + return result.join(" "); + } + static from(obj) { + if (ErrorFragment.isFragment(obj)) { + return obj; + } + if (typeof obj === "string") { + return ErrorFragment.from(lex(obj)); + } else if (obj instanceof TokenString) { + const name = consumeName("error", obj); + const inputs = consumeParams(obj); + consumeEoi(obj); + return new ErrorFragment(_guard$2, name, inputs); + } + return new ErrorFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); + } + static isFragment(value) { + return value && value[internal$1] === ErrorFragmentInternal; + } +} +class EventFragment extends NamedFragment { + anonymous; + constructor(guard, name, inputs, anonymous){ + super(guard, "event", name, inputs); + Object.defineProperty(this, internal$1, { + value: EventFragmentInternal + }); + defineProperties(this, { + anonymous: anonymous + }); + } + get topicHash() { + return id(this.format("sighash")); + } + format(format) { + if (format == null) { + format = "sighash"; + } + if (format === "json") { + return JSON.stringify({ + type: "event", + anonymous: this.anonymous, + name: this.name, + inputs: this.inputs.map((i)=>JSON.parse(i.format(format))) + }); + } + const result = []; + if (format !== "sighash") { + result.push("event"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== "sighash" && this.anonymous) { + result.push("anonymous"); + } + return result.join(" "); + } + static getTopicHash(name, params) { + params = (params || []).map((p)=>ParamType.from(p)); + const fragment = new EventFragment(_guard$2, name, params, false); + return fragment.topicHash; + } + static from(obj) { + if (EventFragment.isFragment(obj)) { + return obj; + } + if (typeof obj === "string") { + try { + return EventFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid event fragment", "obj", obj); + } + } else if (obj instanceof TokenString) { + const name = consumeName("event", obj); + const inputs = consumeParams(obj, true); + const anonymous = !!consumeKeywords(obj, setify([ + "anonymous" + ])).has("anonymous"); + consumeEoi(obj); + return new EventFragment(_guard$2, name, inputs, anonymous); + } + return new EventFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map((p)=>ParamType.from(p, true)) : [], !!obj.anonymous); + } + static isFragment(value) { + return value && value[internal$1] === EventFragmentInternal; + } +} +class ConstructorFragment extends Fragment { + payable; + gas; + constructor(guard, type, inputs, payable, gas){ + super(guard, type, inputs); + Object.defineProperty(this, internal$1, { + value: ConstructorFragmentInternal + }); + defineProperties(this, { + payable: payable, + gas: gas + }); + } + format(format) { + assert1(format != null && format !== "sighash", "cannot format a constructor for sighash", "UNSUPPORTED_OPERATION", { + operation: "format(sighash)" + }); + if (format === "json") { + return JSON.stringify({ + type: "constructor", + stateMutability: this.payable ? "payable" : "undefined", + payable: this.payable, + gas: this.gas != null ? this.gas : undefined, + inputs: this.inputs.map((i)=>JSON.parse(i.format(format))) + }); + } + const result = [ + `constructor${joinParams(format, this.inputs)}` + ]; + if (this.payable) { + result.push("payable"); + } + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + return result.join(" "); + } + static from(obj) { + if (ConstructorFragment.isFragment(obj)) { + return obj; + } + if (typeof obj === "string") { + try { + return ConstructorFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid constuctor fragment", "obj", obj); + } + } else if (obj instanceof TokenString) { + consumeKeywords(obj, setify([ + "constructor" + ])); + const inputs = consumeParams(obj); + const payable = !!consumeKeywords(obj, KwVisibDeploy).has("payable"); + const gas = consumeGas(obj); + consumeEoi(obj); + return new ConstructorFragment(_guard$2, "constructor", inputs, payable, gas); + } + return new ConstructorFragment(_guard$2, "constructor", obj.inputs ? obj.inputs.map(ParamType.from) : [], !!obj.payable, obj.gas != null ? obj.gas : null); + } + static isFragment(value) { + return value && value[internal$1] === ConstructorFragmentInternal; + } +} +class FallbackFragment extends Fragment { + payable; + constructor(guard, inputs, payable){ + super(guard, "fallback", inputs); + Object.defineProperty(this, internal$1, { + value: FallbackFragmentInternal + }); + defineProperties(this, { + payable: payable + }); + } + format(format) { + const type = this.inputs.length === 0 ? "receive" : "fallback"; + if (format === "json") { + const stateMutability = this.payable ? "payable" : "nonpayable"; + return JSON.stringify({ + type: type, + stateMutability: stateMutability + }); + } + return `${type}()${this.payable ? " payable" : ""}`; + } + static from(obj) { + if (FallbackFragment.isFragment(obj)) { + return obj; + } + if (typeof obj === "string") { + try { + return FallbackFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid fallback fragment", "obj", obj); + } + } else if (obj instanceof TokenString) { + const errorObj = obj.toString(); + const topIsValid = obj.peekKeyword(setify([ + "fallback", + "receive" + ])); + assertArgument(topIsValid, "type must be fallback or receive", "obj", errorObj); + const type = obj.popKeyword(setify([ + "fallback", + "receive" + ])); + if (type === "receive") { + const inputs = consumeParams(obj); + assertArgument(inputs.length === 0, `receive cannot have arguments`, "obj.inputs", inputs); + consumeKeywords(obj, setify([ + "payable" + ])); + consumeEoi(obj); + return new FallbackFragment(_guard$2, [], true); + } + let inputs = consumeParams(obj); + if (inputs.length) { + assertArgument(inputs.length === 1 && inputs[0].type === "bytes", "invalid fallback inputs", "obj.inputs", inputs.map((i)=>i.format("minimal")).join(", ")); + } else { + inputs = [ + ParamType.from("bytes") + ]; + } + const mutability = consumeMutability(obj); + assertArgument(mutability === "nonpayable" || mutability === "payable", "fallback cannot be constants", "obj.stateMutability", mutability); + if (consumeKeywords(obj, setify([ + "returns" + ])).has("returns")) { + const outputs = consumeParams(obj); + assertArgument(outputs.length === 1 && outputs[0].type === "bytes", "invalid fallback outputs", "obj.outputs", outputs.map((i)=>i.format("minimal")).join(", ")); + } + consumeEoi(obj); + return new FallbackFragment(_guard$2, inputs, mutability === "payable"); + } + if (obj.type === "receive") { + return new FallbackFragment(_guard$2, [], true); + } + if (obj.type === "fallback") { + const inputs = [ + ParamType.from("bytes") + ]; + const payable = obj.stateMutability === "payable"; + return new FallbackFragment(_guard$2, inputs, payable); + } + assertArgument(false, "invalid fallback description", "obj", obj); + } + static isFragment(value) { + return value && value[internal$1] === FallbackFragmentInternal; + } +} +class FunctionFragment extends NamedFragment { + constant; + outputs; + stateMutability; + payable; + gas; + constructor(guard, name, stateMutability, inputs, outputs, gas){ + super(guard, "function", name, inputs); + Object.defineProperty(this, internal$1, { + value: FunctionFragmentInternal + }); + outputs = Object.freeze(outputs.slice()); + const constant = stateMutability === "view" || stateMutability === "pure"; + const payable = stateMutability === "payable"; + defineProperties(this, { + constant: constant, + gas: gas, + outputs: outputs, + payable: payable, + stateMutability: stateMutability + }); + } + get selector() { + return id(this.format("sighash")).substring(0, 10); + } + format(format) { + if (format == null) { + format = "sighash"; + } + if (format === "json") { + return JSON.stringify({ + type: "function", + name: this.name, + constant: this.constant, + stateMutability: this.stateMutability !== "nonpayable" ? this.stateMutability : undefined, + payable: this.payable, + gas: this.gas != null ? this.gas : undefined, + inputs: this.inputs.map((i)=>JSON.parse(i.format(format))), + outputs: this.outputs.map((o)=>JSON.parse(o.format(format))) + }); + } + const result = []; + if (format !== "sighash") { + result.push("function"); + } + result.push(this.name + joinParams(format, this.inputs)); + if (format !== "sighash") { + if (this.stateMutability !== "nonpayable") { + result.push(this.stateMutability); + } + if (this.outputs && this.outputs.length) { + result.push("returns"); + result.push(joinParams(format, this.outputs)); + } + if (this.gas != null) { + result.push(`@${this.gas.toString()}`); + } + } + return result.join(" "); + } + static getSelector(name, params) { + params = (params || []).map((p)=>ParamType.from(p)); + const fragment = new FunctionFragment(_guard$2, name, "view", params, [], null); + return fragment.selector; + } + static from(obj) { + if (FunctionFragment.isFragment(obj)) { + return obj; + } + if (typeof obj === "string") { + try { + return FunctionFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid function fragment", "obj", obj); + } + } else if (obj instanceof TokenString) { + const name = consumeName("function", obj); + const inputs = consumeParams(obj); + const mutability = consumeMutability(obj); + let outputs = []; + if (consumeKeywords(obj, setify([ + "returns" + ])).has("returns")) { + outputs = consumeParams(obj); + } + const gas = consumeGas(obj); + consumeEoi(obj); + return new FunctionFragment(_guard$2, name, mutability, inputs, outputs, gas); + } + let stateMutability = obj.stateMutability; + if (stateMutability == null) { + stateMutability = "payable"; + if (typeof obj.constant === "boolean") { + stateMutability = "view"; + if (!obj.constant) { + stateMutability = "payable"; + if (typeof obj.payable === "boolean" && !obj.payable) { + stateMutability = "nonpayable"; + } + } + } else if (typeof obj.payable === "boolean" && !obj.payable) { + stateMutability = "nonpayable"; + } + } + return new FunctionFragment(_guard$2, obj.name, stateMutability, obj.inputs ? obj.inputs.map(ParamType.from) : [], obj.outputs ? obj.outputs.map(ParamType.from) : [], obj.gas != null ? obj.gas : null); + } + static isFragment(value) { + return value && value[internal$1] === FunctionFragmentInternal; + } +} +class StructFragment extends NamedFragment { + constructor(guard, name, inputs){ + super(guard, "struct", name, inputs); + Object.defineProperty(this, internal$1, { + value: StructFragmentInternal + }); + } + format() { + throw new Error("@TODO"); + } + static from(obj) { + if (typeof obj === "string") { + try { + return StructFragment.from(lex(obj)); + } catch (error) { + assertArgument(false, "invalid struct fragment", "obj", obj); + } + } else if (obj instanceof TokenString) { + const name = consumeName("struct", obj); + const inputs = consumeParams(obj); + consumeEoi(obj); + return new StructFragment(_guard$2, name, inputs); + } + return new StructFragment(_guard$2, obj.name, obj.inputs ? obj.inputs.map(ParamType.from) : []); + } + static isFragment(value) { + return value && value[internal$1] === StructFragmentInternal; + } +} +const PanicReasons$1 = new Map; +PanicReasons$1.set(0, "GENERIC_PANIC"); +PanicReasons$1.set(1, "ASSERT_FALSE"); +PanicReasons$1.set(17, "OVERFLOW"); +PanicReasons$1.set(18, "DIVIDE_BY_ZERO"); +PanicReasons$1.set(33, "ENUM_RANGE_ERROR"); +PanicReasons$1.set(34, "BAD_STORAGE_DATA"); +PanicReasons$1.set(49, "STACK_UNDERFLOW"); +PanicReasons$1.set(50, "ARRAY_RANGE_ERROR"); +PanicReasons$1.set(65, "OUT_OF_MEMORY"); +PanicReasons$1.set(81, "UNINITIALIZED_FUNCTION_CALL"); +const paramTypeBytes = new RegExp(/^bytes([0-9]*)$/); +const paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/); +let defaultCoder = null; +let defaultMaxInflation = 1024; +function getBuiltinCallException(action, tx, data, abiCoder) { + let message = "missing revert data"; + let reason = null; + let revert = null; + if (data) { + message = "execution reverted"; + const bytes = getBytes(data); + data = hexlify(data); + if (bytes.length === 0) { + message += " (no data present; likely require(false) occurred"; + reason = "require(false)"; + } else if (bytes.length % 32 !== 4) { + message += " (could not decode reason; invalid data length)"; + } else if (hexlify(bytes.slice(0, 4)) === "0x08c379a0") { + try { + reason = abiCoder.decode([ + "string" + ], bytes.slice(4))[0]; + revert = { + signature: "Error(string)", + name: "Error", + args: [ + reason + ] + }; + message += `: ${JSON.stringify(reason)}`; + } catch (error) { + message += " (could not decode reason; invalid string data)"; + } + } else if (hexlify(bytes.slice(0, 4)) === "0x4e487b71") { + try { + const code = Number(abiCoder.decode([ + "uint256" + ], bytes.slice(4))[0]); + revert = { + signature: "Panic(uint256)", + name: "Panic", + args: [ + code + ] + }; + reason = `Panic due to ${PanicReasons$1.get(code) || "UNKNOWN"}(${code})`; + message += `: ${reason}`; + } catch (error) { + message += " (could not decode panic code)"; + } + } else { + message += " (unknown custom error)"; + } + } + const transaction = { + to: tx.to ? getAddress(tx.to) : null, + data: tx.data || "0x" + }; + if (tx.from) { + transaction.from = getAddress(tx.from); + } + return makeError(message, "CALL_EXCEPTION", { + action: action, + data: data, + reason: reason, + transaction: transaction, + invocation: null, + revert: revert + }); +} +class AbiCoder { + #getCoder(param) { + if (param.isArray()) { + return new ArrayCoder(this.#getCoder(param.arrayChildren), param.arrayLength, param.name); + } + if (param.isTuple()) { + return new TupleCoder(param.components.map((c)=>this.#getCoder(c)), param.name); + } + switch(param.baseType){ + case "address": + return new AddressCoder(param.name); + case "bool": + return new BooleanCoder(param.name); + case "string": + return new StringCoder(param.name); + case "bytes": + return new BytesCoder(param.name); + case "": + return new NullCoder(param.name); + } + let match = param.type.match(paramTypeNumber); + if (match) { + let size = parseInt(match[2] || "256"); + assertArgument(size !== 0 && size <= 256 && size % 8 === 0, "invalid " + match[1] + " bit length", "param", param); + return new NumberCoder(size / 8, match[1] === "int", param.name); + } + match = param.type.match(paramTypeBytes); + if (match) { + let size = parseInt(match[1]); + assertArgument(size !== 0 && size <= 32, "invalid bytes length", "param", param); + return new FixedBytesCoder(size, param.name); + } + assertArgument(false, "invalid type", "type", param.type); + } + getDefaultValue(types) { + const coders = types.map((type)=>this.#getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.defaultValue(); + } + encode(types, values) { + assertArgumentCount(values.length, types.length, "types/values length mismatch"); + const coders = types.map((type)=>this.#getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + const writer = new Writer; + coder.encode(writer, values); + return writer.data; + } + decode(types, data, loose) { + const coders = types.map((type)=>this.#getCoder(ParamType.from(type))); + const coder = new TupleCoder(coders, "_"); + return coder.decode(new Reader(data, loose, defaultMaxInflation)); + } + static _setDefaultMaxInflation(value) { + assertArgument(typeof value === "number" && Number.isInteger(value), "invalid defaultMaxInflation factor", "value", value); + defaultMaxInflation = value; + } + static defaultAbiCoder() { + if (defaultCoder == null) { + defaultCoder = new AbiCoder; + } + return defaultCoder; + } + static getBuiltinCallException(action, tx, data) { + return getBuiltinCallException(action, tx, data, AbiCoder.defaultAbiCoder()); + } +} +function encodeBytes32String(text) { + const bytes = toUtf8Bytes(text); + if (bytes.length > 31) { + throw new Error("bytes32 string must be less than 32 bytes"); + } + return zeroPadBytes(bytes, 32); +} +function decodeBytes32String(_bytes) { + const data = getBytes(_bytes, "bytes"); + if (data.length !== 32) { + throw new Error("invalid bytes32 - not 32 bytes long"); + } + if (data[31] !== 0) { + throw new Error("invalid bytes32 string - no null terminator"); + } + let length = 31; + while(data[length - 1] === 0){ + length--; + } + return toUtf8String(data.slice(0, length)); +} +class LogDescription { + fragment; + name; + signature; + topic; + args; + constructor(fragment, topic, args){ + const name = fragment.name, signature = fragment.format(); + defineProperties(this, { + fragment: fragment, + name: name, + signature: signature, + topic: topic, + args: args + }); + } +} +class TransactionDescription { + fragment; + name; + args; + signature; + selector; + value; + constructor(fragment, selector, args, value){ + const name = fragment.name, signature = fragment.format(); + defineProperties(this, { + fragment: fragment, + name: name, + args: args, + signature: signature, + selector: selector, + value: value + }); + } +} +class ErrorDescription { + fragment; + name; + args; + signature; + selector; + constructor(fragment, selector, args){ + const name = fragment.name, signature = fragment.format(); + defineProperties(this, { + fragment: fragment, + name: name, + args: args, + signature: signature, + selector: selector + }); + } +} +class Indexed { + hash; + _isIndexed; + static isIndexed(value) { + return !!(value && value._isIndexed); + } + constructor(hash){ + defineProperties(this, { + hash: hash, + _isIndexed: true + }); + } +} +const PanicReasons = { + 0: "generic panic", + 1: "assert(false)", + 17: "arithmetic overflow", + 18: "division or modulo by zero", + 33: "enum overflow", + 34: "invalid encoded storage byte array accessed", + 49: "out-of-bounds array access; popping on an empty array", + 50: "out-of-bounds access of an array or bytesN", + 65: "out of memory", + 81: "uninitialized function" }; -Hmac.prototype.digest = function digest8(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); +const BuiltinErrors = { + "0x08c379a0": { + signature: "Error(string)", + name: "Error", + inputs: [ + "string" + ], + reason: (message)=>{ + return `reverted with reason string ${JSON.stringify(message)}`; + } + }, + "0x4e487b71": { + signature: "Panic(uint256)", + name: "Panic", + inputs: [ + "uint256" + ], + reason: (code)=>{ + let reason = "unknown panic code"; + if (code >= 0 && code <= 255 && PanicReasons[code.toString()]) { + reason = PanicReasons[code.toString()]; + } + return `reverted with panic code 0x${code.toString(16)} (${reason})`; + } + } }; -var hash_1 = createCommonjsModule3(function(module, exports) { - var hash = exports; - hash.utils = utils; - hash.common = common; - hash.sha = sha; - hash.ripemd = ripemd; - hash.hmac = hmac; - hash.sha1 = hash.sha.sha1; - hash.sha256 = hash.sha.sha256; - hash.sha224 = hash.sha.sha224; - hash.sha384 = hash.sha.sha384; - hash.sha512 = hash.sha.sha512; - hash.ripemd160 = hash.ripemd.ripemd160; -}); -function createCommonjsModule4(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function(path, base2) { - return commonjsRequire4(path, base2 === void 0 || base2 === null ? module.path : base2); +class Interface { + fragments; + deploy; + fallback; + receive; + #errors; + #events; + #functions; + #abiCoder; + constructor(fragments){ + let abi = []; + if (typeof fragments === "string") { + abi = JSON.parse(fragments); + } else { + abi = fragments; + } + this.#functions = new Map; + this.#errors = new Map; + this.#events = new Map; + const frags = []; + for (const a of abi){ + try { + frags.push(Fragment.from(a)); + } catch (error) { + console.log(`[Warning] Invalid Fragment ${JSON.stringify(a)}:`, error.message); + } + } + defineProperties(this, { + fragments: Object.freeze(frags) + }); + let fallback = null; + let receive = false; + this.#abiCoder = this.getAbiCoder(); + this.fragments.forEach((fragment, index)=>{ + let bucket; + switch(fragment.type){ + case "constructor": + if (this.deploy) { + console.log("duplicate definition - constructor"); + return; + } + defineProperties(this, { + deploy: fragment + }); + return; + case "fallback": + if (fragment.inputs.length === 0) { + receive = true; + } else { + assertArgument(!fallback || fragment.payable !== fallback.payable, "conflicting fallback fragments", `fragments[${index}]`, fragment); + fallback = fragment; + receive = fallback.payable; + } + return; + case "function": + bucket = this.#functions; + break; + case "event": + bucket = this.#events; + break; + case "error": + bucket = this.#errors; + break; + default: + return; + } + const signature = fragment.format(); + if (bucket.has(signature)) { + return; + } + bucket.set(signature, fragment); + }); + if (!this.deploy) { + defineProperties(this, { + deploy: ConstructorFragment.from("constructor()") + }); + } + defineProperties(this, { + fallback: fallback, + receive: receive + }); + } + format(minimal) { + const format = minimal ? "minimal" : "full"; + const abi = this.fragments.map((f)=>f.format(format)); + return abi; + } + formatJson() { + const abi = this.fragments.map((f)=>f.format("json")); + return JSON.stringify(abi.map((j)=>JSON.parse(j))); + } + getAbiCoder() { + return AbiCoder.defaultAbiCoder(); + } + #getFunction(key, values, forceUnique) { + if (isHexString(key)) { + const selector = key.toLowerCase(); + for (const fragment of this.#functions.values()){ + if (selector === fragment.selector) { + return fragment; + } + } + return null; + } + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#functions){ + if (name.split("(")[0] === key) { + matching.push(fragment); + } + } + if (values) { + const lastValue = values.length > 0 ? values[values.length - 1] : null; + let valueLength = values.length; + let allowOptions = true; + if (Typed.isTyped(lastValue) && lastValue.type === "overrides") { + allowOptions = false; + valueLength--; + } + for(let i = matching.length - 1; i >= 0; i--){ + const inputs = matching[i].inputs.length; + if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) { + matching.splice(i, 1); + } + } + for(let i = matching.length - 1; i >= 0; i--){ + const inputs = matching[i].inputs; + for(let j = 0; j < values.length; j++){ + if (!Typed.isTyped(values[j])) { + continue; + } + if (j >= inputs.length) { + if (values[j].type === "overrides") { + continue; + } + matching.splice(i, 1); + break; + } + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + if (matching.length === 1 && values && values.length !== matching[0].inputs.length) { + const lastArg = values[values.length - 1]; + if (lastArg == null || Array.isArray(lastArg) || typeof lastArg !== "object") { + matching.splice(0, 1); + } + } + if (matching.length === 0) { + return null; + } + if (matching.length > 1 && forceUnique) { + const matchStr = matching.map((m)=>JSON.stringify(m.format())).join(", "); + assertArgument(false, `ambiguous function description (i.e. matches ${matchStr})`, "key", key); + } + return matching[0]; + } + const result = this.#functions.get(FunctionFragment.from(key).format()); + if (result) { + return result; + } + return null; + } + getFunctionName(key) { + const fragment = this.#getFunction(key, null, false); + assertArgument(fragment, "no matching function", "key", key); + return fragment.name; + } + hasFunction(key) { + return !!this.#getFunction(key, null, false); + } + getFunction(key, values) { + return this.#getFunction(key, values || null, true); + } + forEachFunction(callback) { + const names = Array.from(this.#functions.keys()); + names.sort((a, b)=>a.localeCompare(b)); + for(let i = 0; i < names.length; i++){ + const name = names[i]; + callback(this.#functions.get(name), i); + } + } + #getEvent(key, values, forceUnique) { + if (isHexString(key)) { + const eventTopic = key.toLowerCase(); + for (const fragment of this.#events.values()){ + if (eventTopic === fragment.topicHash) { + return fragment; + } + } + return null; + } + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#events){ + if (name.split("(")[0] === key) { + matching.push(fragment); + } + } + if (values) { + for(let i = matching.length - 1; i >= 0; i--){ + if (matching[i].inputs.length < values.length) { + matching.splice(i, 1); + } + } + for(let i = matching.length - 1; i >= 0; i--){ + const inputs = matching[i].inputs; + for(let j = 0; j < values.length; j++){ + if (!Typed.isTyped(values[j])) { + continue; + } + if (values[j].type !== inputs[j].baseType) { + matching.splice(i, 1); + break; + } + } + } + } + if (matching.length === 0) { + return null; + } + if (matching.length > 1 && forceUnique) { + const matchStr = matching.map((m)=>JSON.stringify(m.format())).join(", "); + assertArgument(false, `ambiguous event description (i.e. matches ${matchStr})`, "key", key); + } + return matching[0]; + } + const result = this.#events.get(EventFragment.from(key).format()); + if (result) { + return result; + } + return null; + } + getEventName(key) { + const fragment = this.#getEvent(key, null, false); + assertArgument(fragment, "no matching event", "key", key); + return fragment.name; + } + hasEvent(key) { + return !!this.#getEvent(key, null, false); + } + getEvent(key, values) { + return this.#getEvent(key, values || null, true); + } + forEachEvent(callback) { + const names = Array.from(this.#events.keys()); + names.sort((a, b)=>a.localeCompare(b)); + for(let i = 0; i < names.length; i++){ + const name = names[i]; + callback(this.#events.get(name), i); + } + } + getError(key, values) { + if (isHexString(key)) { + const selector = key.toLowerCase(); + if (BuiltinErrors[selector]) { + return ErrorFragment.from(BuiltinErrors[selector].signature); + } + for (const fragment of this.#errors.values()){ + if (selector === fragment.selector) { + return fragment; + } + } + return null; + } + if (key.indexOf("(") === -1) { + const matching = []; + for (const [name, fragment] of this.#errors){ + if (name.split("(")[0] === key) { + matching.push(fragment); + } + } + if (matching.length === 0) { + if (key === "Error") { + return ErrorFragment.from("error Error(string)"); + } + if (key === "Panic") { + return ErrorFragment.from("error Panic(uint256)"); + } + return null; + } else if (matching.length > 1) { + const matchStr = matching.map((m)=>JSON.stringify(m.format())).join(", "); + assertArgument(false, `ambiguous error description (i.e. ${matchStr})`, "name", key); + } + return matching[0]; + } + key = ErrorFragment.from(key).format(); + if (key === "Error(string)") { + return ErrorFragment.from("error Error(string)"); + } + if (key === "Panic(uint256)") { + return ErrorFragment.from("error Panic(uint256)"); + } + const result = this.#errors.get(key); + if (result) { + return result; + } + return null; + } + forEachError(callback) { + const names = Array.from(this.#errors.keys()); + names.sort((a, b)=>a.localeCompare(b)); + for(let i = 0; i < names.length; i++){ + const name = names[i]; + callback(this.#errors.get(name), i); + } + } + _decodeParams(params, data) { + return this.#abiCoder.decode(params, data); + } + _encodeParams(params, values) { + return this.#abiCoder.encode(params, values); + } + encodeDeploy(values) { + return this._encodeParams(this.deploy.inputs, values || []); + } + decodeErrorResult(fragment, data) { + if (typeof fragment === "string") { + const f = this.getError(fragment); + assertArgument(f, "unknown error", "fragment", fragment); + fragment = f; } - }, fn(module, module.exports), module.exports; -} -function commonjsRequire4() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); -} -var minimalisticAssert1 = assert2; -function assert2(val, msg) { - if (!val) throw new Error(msg || "Assertion failed"); -} -assert2.equal = function assertEqual(l, r, msg) { - if (l != r) throw new Error(msg || "Assertion failed: " + l + " != " + r); -}; -var utils_1 = createCommonjsModule4(function(module, exports) { - var utils = exports; - function toArray(msg, enc) { - if (Array.isArray(msg)) return msg.slice(); - if (!msg) return []; - var res = []; - if (typeof msg !== "string") { - for(var i = 0; i < msg.length; i++)res[i] = msg[i] | 0; - return res; - } - if (enc === "hex") { - msg = msg.replace(/[^a-z0-9]+/ig, ""); - if (msg.length % 2 !== 0) msg = "0" + msg; - for(var i = 0; i < msg.length; i += 2)res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else { - for(var i = 0; i < msg.length; i++){ - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 255; - if (hi) res.push(hi, lo); - else res.push(lo); + assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match error ${fragment.name}.`, "data", data); + return this._decodeParams(fragment.inputs, dataSlice(data, 4)); + } + encodeErrorResult(fragment, values) { + if (typeof fragment === "string") { + const f = this.getError(fragment); + assertArgument(f, "unknown error", "fragment", fragment); + fragment = f; + } + return concat([ + fragment.selector, + this._encodeParams(fragment.inputs, values || []) + ]); + } + decodeFunctionData(fragment, data) { + if (typeof fragment === "string") { + const f = this.getFunction(fragment); + assertArgument(f, "unknown function", "fragment", fragment); + fragment = f; + } + assertArgument(dataSlice(data, 0, 4) === fragment.selector, `data signature does not match function ${fragment.name}.`, "data", data); + return this._decodeParams(fragment.inputs, dataSlice(data, 4)); + } + encodeFunctionData(fragment, values) { + if (typeof fragment === "string") { + const f = this.getFunction(fragment); + assertArgument(f, "unknown function", "fragment", fragment); + fragment = f; + } + return concat([ + fragment.selector, + this._encodeParams(fragment.inputs, values || []) + ]); + } + decodeFunctionResult(fragment, data) { + if (typeof fragment === "string") { + const f = this.getFunction(fragment); + assertArgument(f, "unknown function", "fragment", fragment); + fragment = f; + } + let message = "invalid length for result data"; + const bytes = getBytesCopy(data); + if (bytes.length % 32 === 0) { + try { + return this.#abiCoder.decode(fragment.outputs, bytes); + } catch (error) { + message = "could not decode result data"; } } - return res; + assert1(false, message, "BAD_DATA", { + value: hexlify(bytes), + info: { + method: fragment.name, + signature: fragment.format() + } + }); } - utils.toArray = toArray; - function zero2(word) { - if (word.length === 1) return "0" + word; - else return word; + makeError(_data, tx) { + const data = getBytes(_data, "data"); + const error = AbiCoder.getBuiltinCallException("call", tx, data); + const customPrefix = "execution reverted (unknown custom error)"; + if (error.message.startsWith(customPrefix)) { + const selector = hexlify(data.slice(0, 4)); + const ef = this.getError(selector); + if (ef) { + try { + const args = this.#abiCoder.decode(ef.inputs, data.slice(4)); + error.revert = { + name: ef.name, + signature: ef.format(), + args: args + }; + error.reason = error.revert.signature; + error.message = `execution reverted: ${error.reason}`; + } catch (e) { + error.message = `execution reverted (coult not decode custom error)`; + } + } + } + const parsed = this.parseTransaction(tx); + if (parsed) { + error.invocation = { + method: parsed.name, + signature: parsed.signature, + args: parsed.args + }; + } + return error; } - utils.zero2 = zero2; - function toHex(msg) { - var res = ""; - for(var i = 0; i < msg.length; i++)res += zero2(msg[i].toString(16)); - return res; + encodeFunctionResult(fragment, values) { + if (typeof fragment === "string") { + const f = this.getFunction(fragment); + assertArgument(f, "unknown function", "fragment", fragment); + fragment = f; + } + return hexlify(this.#abiCoder.encode(fragment.outputs, values || [])); } - utils.toHex = toHex; - utils.encode = function encode2(arr, enc) { - if (enc === "hex") return toHex(arr); - else return arr; - }; -}); -var utils_1$1 = createCommonjsModule4(function(module, exports) { - var utils = exports; - utils.assert = minimalisticAssert1; - utils.toArray = utils_1.toArray; - utils.zero2 = utils_1.zero2; - utils.toHex = utils_1.toHex; - utils.encode = utils_1.encode; - function getNAF2(num, w, bits) { - var naf = new Array(Math.max(num.bitLength(), bits) + 1); - naf.fill(0); - var ws = 1 << w + 1; - var k = num.clone(); - for(var i = 0; i < naf.length; i++){ - var z; - var mod = k.andln(ws - 1); - if (k.isOdd()) { - if (mod > (ws >> 1) - 1) z = (ws >> 1) - mod; - else z = mod; - k.isubn(z); + encodeFilterTopics(fragment, values) { + if (typeof fragment === "string") { + const f = this.getEvent(fragment); + assertArgument(f, "unknown event", "eventFragment", fragment); + fragment = f; + } + assert1(values.length <= fragment.inputs.length, `too many arguments for ${fragment.format()}`, "UNEXPECTED_ARGUMENT", { + count: values.length, + expectedCount: fragment.inputs.length + }); + const topics = []; + if (!fragment.anonymous) { + topics.push(fragment.topicHash); + } + const encodeTopic = (param, value)=>{ + if (param.type === "string") { + return id(value); + } else if (param.type === "bytes") { + return keccak256(hexlify(value)); + } + if (param.type === "bool" && typeof value === "boolean") { + value = value ? "0x01" : "0x00"; + } else if (param.type.match(/^u?int/)) { + value = toBeHex(value); + } else if (param.type.match(/^bytes/)) { + value = zeroPadBytes(value, 32); + } else if (param.type === "address") { + this.#abiCoder.encode([ + "address" + ], [ + value + ]); + } + return zeroPadValue(hexlify(value), 32); + }; + values.forEach((value, index)=>{ + const param = fragment.inputs[index]; + if (!param.indexed) { + assertArgument(value == null, "cannot filter non-indexed parameters; must be null", "contract." + param.name, value); + return; + } + if (value == null) { + topics.push(null); + } else if (param.baseType === "array" || param.baseType === "tuple") { + assertArgument(false, "filtering with tuples or arrays not supported", "contract." + param.name, value); + } else if (Array.isArray(value)) { + topics.push(value.map((value)=>encodeTopic(param, value))); } else { - z = 0; + topics.push(encodeTopic(param, value)); } - naf[i] = z; - k.iushrn(1); + }); + while(topics.length && topics[topics.length - 1] === null){ + topics.pop(); } - return naf; + return topics; } - utils.getNAF = getNAF2; - function getJSF2(k1, k2) { - var jsf = [ - [], - [] - ]; - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - var m8; - while(k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0){ - var m14 = k1.andln(3) + d1 & 3; - var m24 = k2.andln(3) + d2 & 3; - if (m14 === 3) m14 = -1; - if (m24 === 3) m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - m8 = k1.andln(7) + d1 & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) u1 = -m14; - else u1 = m14; - } - jsf[0].push(u1); - var u2; - if ((m24 & 1) === 0) { - u2 = 0; + encodeEventLog(fragment, values) { + if (typeof fragment === "string") { + const f = this.getEvent(fragment); + assertArgument(f, "unknown event", "eventFragment", fragment); + fragment = f; + } + const topics = []; + const dataTypes = []; + const dataValues = []; + if (!fragment.anonymous) { + topics.push(fragment.topicHash); + } + assertArgument(values.length === fragment.inputs.length, "event arguments/values mismatch", "values", values); + fragment.inputs.forEach((param, index)=>{ + const value = values[index]; + if (param.indexed) { + if (param.type === "string") { + topics.push(id(value)); + } else if (param.type === "bytes") { + topics.push(keccak256(value)); + } else if (param.baseType === "tuple" || param.baseType === "array") { + throw new Error("not implemented"); + } else { + topics.push(this.#abiCoder.encode([ + param.type + ], [ + value + ])); + } } else { - m8 = k2.andln(7) + d2 & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) u2 = -m24; - else u2 = m24; - } - jsf[1].push(u2); - if (2 * d1 === u1 + 1) d1 = 1 - d1; - if (2 * d2 === u2 + 1) d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } - return jsf; - } - utils.getJSF = getJSF2; - function cachedProperty(obj, name, computer) { - var key2 = "_" + name; - obj.prototype[name] = function cachedProperty2() { - return this[key2] !== void 0 ? this[key2] : this[key2] = computer.call(this); + dataTypes.push(param); + dataValues.push(value); + } + }); + return { + data: this.#abiCoder.encode(dataTypes, dataValues), + topics: topics }; } - utils.cachedProperty = cachedProperty; - function parseBytes(bytes2) { - return typeof bytes2 === "string" ? utils.toArray(bytes2, "hex") : bytes2; + decodeEventLog(fragment, data, topics) { + if (typeof fragment === "string") { + const f = this.getEvent(fragment); + assertArgument(f, "unknown event", "eventFragment", fragment); + fragment = f; + } + if (topics != null && !fragment.anonymous) { + const eventTopic = fragment.topicHash; + assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic, "fragment/topic mismatch", "topics[0]", topics[0]); + topics = topics.slice(1); + } + const indexed = []; + const nonIndexed = []; + const dynamic = []; + fragment.inputs.forEach((param, index)=>{ + if (param.indexed) { + if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") { + indexed.push(ParamType.from({ + type: "bytes32", + name: param.name + })); + dynamic.push(true); + } else { + indexed.push(param); + dynamic.push(false); + } + } else { + nonIndexed.push(param); + dynamic.push(false); + } + }); + const resultIndexed = topics != null ? this.#abiCoder.decode(indexed, concat(topics)) : null; + const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true); + const values = []; + const keys = []; + let nonIndexedIndex = 0, indexedIndex = 0; + fragment.inputs.forEach((param, index)=>{ + let value = null; + if (param.indexed) { + if (resultIndexed == null) { + value = new Indexed(null); + } else if (dynamic[index]) { + value = new Indexed(resultIndexed[indexedIndex++]); + } else { + try { + value = resultIndexed[indexedIndex++]; + } catch (error) { + value = error; + } + } + } else { + try { + value = resultNonIndexed[nonIndexedIndex++]; + } catch (error) { + value = error; + } + } + values.push(value); + keys.push(param.name || null); + }); + return Result.fromItems(values, keys); + } + parseTransaction(tx) { + const data = getBytes(tx.data, "tx.data"); + const value = getBigInt(tx.value != null ? tx.value : 0, "tx.value"); + const fragment = this.getFunction(hexlify(data.slice(0, 4))); + if (!fragment) { + return null; + } + const args = this.#abiCoder.decode(fragment.inputs, data.slice(4)); + return new TransactionDescription(fragment, fragment.selector, args, value); } - utils.parseBytes = parseBytes; - function intFromLE(bytes2) { - return new bn(bytes2, "hex", "le"); + parseCallResult(data) { + throw new Error("@TODO"); } - utils.intFromLE = intFromLE; -}); -var getNAF = utils_1$1.getNAF; -var getJSF = utils_1$1.getJSF; -var assert$1 = utils_1$1.assert; -function BaseCurve(type, conf) { - this.type = type; - this.p = new bn(conf.p, 16); - this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p); - this.zero = new bn(0).toRed(this.red); - this.one = new bn(1).toRed(this.red); - this.two = new bn(2).toRed(this.red); - this.n = conf.n && new bn(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); - this._bitLength = this.n ? this.n.bitLength() : 0; - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); + parseLog(log) { + const fragment = this.getEvent(log.topics[0]); + if (!fragment || fragment.anonymous) { + return null; + } + return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics)); } -} -var base = BaseCurve; -BaseCurve.prototype.point = function point() { - throw new Error("Not implemented"); -}; -BaseCurve.prototype.validate = function validate() { - throw new Error("Not implemented"); -}; -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert$1(p.precomputed); - var doubles = p._getDoubles(); - var naf = getNAF(k, 1, this._bitLength); - var I = (1 << doubles.step + 1) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - var repr = []; - var j; - var nafW; - for(j = 0; j < naf.length; j += doubles.step){ - nafW = 0; - for(var l = j + doubles.step - 1; l >= j; l--)nafW = (nafW << 1) + naf[l]; - repr.push(nafW); - } - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for(var i = I; i > 0; i--){ - for(j = 0; j < repr.length; j++){ - nafW = repr[j]; - if (nafW === i) b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); -}; -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; - var naf = getNAF(k, w, this._bitLength); - var acc = this.jpoint(null, null, null); - for(var i = naf.length - 1; i >= 0; i--){ - for(var l = 0; i >= 0 && naf[i] === 0; i--)l++; - if (i >= 0) l++; - acc = acc.dblp(l); - if (i < 0) break; - var z = naf[i]; - assert$1(z !== 0); - if (p.type === "affine") { - if (z > 0) acc = acc.mixedAdd(wnd[z - 1 >> 1]); - else acc = acc.mixedAdd(wnd[-z - 1 >> 1].neg()); - } else { - if (z > 0) acc = acc.add(wnd[z - 1 >> 1]); - else acc = acc.add(wnd[-z - 1 >> 1].neg()); + parseError(data) { + const hexData = hexlify(data); + const fragment = this.getError(dataSlice(hexData, 0, 4)); + if (!fragment) { + return null; } + const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4)); + return new ErrorDescription(fragment, fragment.selector, args); } - return p.type === "affine" ? acc.toP() : acc; -}; -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, len, jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - var max = 0; - var i; - var j; - var p; - for(i = 0; i < len; i++){ - p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - for(i = len - 1; i >= 1; i -= 2){ - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength); - naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; + static from(value) { + if (value instanceof Interface) { + return value; } - var comb = [ - points[a], - null, - null, - points[b] - ]; - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - var index = [ - -3, - -1, - -5, - -7, - 0, - 7, - 5, - 1, - 3 - ]; - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for(j = 0; j < max; j++){ - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } - } - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for(i = max; i >= 0; i--){ - var k = 0; - while(i >= 0){ - var zero = true; - for(j = 0; j < len; j++){ - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) zero = false; - } - if (!zero) break; - k++; - i--; - } - if (i >= 0) k++; - acc = acc.dblp(k); - if (i < 0) break; - for(j = 0; j < len; j++){ - var z = tmp[j]; - if (z === 0) continue; - else if (z > 0) p = wnd[j][z - 1 >> 1]; - else if (z < 0) p = wnd[j][-z - 1 >> 1].neg(); - if (p.type === "affine") acc = acc.mixedAdd(p); - else acc = acc.add(p); - } - } - for(i = 0; i < len; i++)wnd[i] = null; - if (jacobianResult) return acc; - else return acc.toP(); -}; -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; -} -BaseCurve.BasePoint = BasePoint; -BasePoint.prototype.eq = function eq() { - throw new Error("Not implemented"); -}; -BasePoint.prototype.validate = function validate2() { - return this.curve.validate(this); -}; -BaseCurve.prototype.decodePoint = function decodePoint(bytes2, enc) { - bytes2 = utils_1$1.toArray(bytes2, enc); - var len = this.p.byteLength(); - if ((bytes2[0] === 4 || bytes2[0] === 6 || bytes2[0] === 7) && bytes2.length - 1 === 2 * len) { - if (bytes2[0] === 6) assert$1(bytes2[bytes2.length - 1] % 2 === 0); - else if (bytes2[0] === 7) assert$1(bytes2[bytes2.length - 1] % 2 === 1); - var res = this.point(bytes2.slice(1, 1 + len), bytes2.slice(1 + len, 1 + 2 * len)); - return res; - } else if ((bytes2[0] === 2 || bytes2[0] === 3) && bytes2.length - 1 === len) { - return this.pointFromX(bytes2.slice(1, 1 + len), bytes2[0] === 3); + if (typeof value === "string") { + return new Interface(JSON.parse(value)); + } + if (typeof value.formatJson === "function") { + return new Interface(value.formatJson()); + } + if (typeof value.format === "function") { + return new Interface(value.format("json")); + } + return new Interface(value); } - throw new Error("Unknown point format"); -}; -BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); -}; -BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray("be", len); - if (compact) return [ - this.getY().isEven() ? 2 : 3 - ].concat(x); - return [ - 4 - ].concat(x, this.getY().toArray("be", len)); -}; -BasePoint.prototype.encode = function encode(enc, compact) { - return utils_1$1.encode(this._encode(compact), enc); -}; -BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) return this; - var precomputed = { - doubles: null, - naf: null, - beta: null - }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - return this; -}; -BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) return false; - var doubles = this.precomputed.doubles; - if (!doubles) return false; - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); -}; -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) return this.precomputed.doubles; - var doubles = [ - this - ]; - var acc = this; - for(var i = 0; i < power; i += step){ - for(var j = 0; j < step; j++)acc = acc.dbl(); - doubles.push(acc); +} +const BN_0$2 = BigInt(0); +function getValue(value) { + if (value == null) { + return null; } - return { - step, - points: doubles - }; -}; -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) return this.precomputed.naf; - var res = [ - this - ]; - var max = (1 << wnd) - 1; - var dbl3 = max === 1 ? null : this.dbl(); - for(var i = 1; i < max; i++)res[i] = res[i - 1].add(dbl3); - return { - wnd, - points: res - }; -}; -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for(var i = 0; i < k; i++)r = r.dbl(); - return r; -}; -var inherits_browser1 = createCommonjsModule4(function(module) { - if (typeof Object.create === "function") { - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - } - }; - } else { - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor; - var TempCtor = function() {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - } + return value; +} +function toJson(value) { + if (value == null) { + return null; + } + return value.toString(); +} +class FeeData { + gasPrice; + maxFeePerGas; + maxPriorityFeePerGas; + constructor(gasPrice, maxFeePerGas, maxPriorityFeePerGas){ + defineProperties(this, { + gasPrice: getValue(gasPrice), + maxFeePerGas: getValue(maxFeePerGas), + maxPriorityFeePerGas: getValue(maxPriorityFeePerGas) + }); + } + toJSON() { + const { gasPrice, maxFeePerGas, maxPriorityFeePerGas } = this; + return { + _type: "FeeData", + gasPrice: toJson(gasPrice), + maxFeePerGas: toJson(maxFeePerGas), + maxPriorityFeePerGas: toJson(maxPriorityFeePerGas) }; } -}); -var assert$2 = utils_1$1.assert; -function ShortCurve(conf) { - base.call(this, "short", conf); - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits_browser1(ShortCurve, base); -var short_1 = ShortCurve; -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) return; - var beta; - var lambda; - if (conf.beta) { - beta = new bn(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); +} +function copyRequest(req) { + const result = {}; + if (req.to) { + result.to = req.to; } - if (conf.lambda) { - lambda = new bn(conf.lambda, 16); - } else { - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; - } else { - lambda = lambdas[1]; - assert$2(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); - } + if (req.from) { + result.from = req.from; } - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new bn(vec.a, 16), - b: new bn(vec.b, 16) - }; - }); - } else { - basis = this._getEndoBasis(lambda); + if (req.data) { + result.data = hexlify(req.data); } - return { - beta, - lambda, - basis - }; -}; -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - var red = num === this.p ? this.red : bn.mont(num); - var tinv = new bn(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ - l1, - l2 - ]; -}; -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - var u = lambda; - var v = this.n.clone(); - var x1 = new bn(1); - var y1 = new bn(0); - var x2 = new bn(0); - var y2 = new bn(1); - var a0; - var b0; - var a1; - var b1; - var a2; - var b2; - var prevR; - var i = 0; - var r; - var x; - while(u.cmpn(0) !== 0){ - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; + const bigIntKeys = "chainId,gasLimit,gasPrice,maxFeePerBlobGas,maxFeePerGas,maxPriorityFeePerGas,value".split(/,/); + for (const key of bigIntKeys){ + if (!(key in req) || req[key] == null) { + continue; } - prevR = r; - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); + result[key] = getBigInt(req[key], `request.${key}`); } - return [ - { - a: a1, - b: b1 - }, - { - a: a2, - b: b2 + const numberKeys = "type,nonce".split(/,/); + for (const key of numberKeys){ + if (!(key in req) || req[key] == null) { + continue; } - ]; -}; -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { - k1, - k2 - }; -}; -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new bn(x, 16); - if (!x.red) x = x.toRed(this.red); - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) throw new Error("invalid point"); - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) y = y.redNeg(); - return this.point(x, y); -}; -ShortCurve.prototype.validate = function validate3(point3) { - if (point3.inf) return true; - var x = point3.x; - var y = point3.y; - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; -ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for(var i = 0; i < points.length; i++){ - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); - for(var j = 0; j < i * 2; j++){ - npoints[j] = null; - ncoeffs[j] = null; + result[key] = getNumber(req[key], `request.${key}`); } - return res; -}; -function Point(curve, x, y, isRed) { - base.BasePoint.call(this, curve, "affine"); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); - } - if (!this.x.red) this.x = this.x.toRed(this.curve.red); - if (!this.y.red) this.y = this.y.toRed(this.curve.red); - this.inf = false; + if (req.accessList) { + result.accessList = accessListify(req.accessList); + } + if ("blockTag" in req) { + result.blockTag = req.blockTag; + } + if ("enableCcipRead" in req) { + result.enableCcipRead = !!req.enableCcipRead; + } + if ("customData" in req) { + result.customData = req.customData; + } + if ("blobVersionedHashes" in req && req.blobVersionedHashes) { + result.blobVersionedHashes = req.blobVersionedHashes.slice(); + } + if ("kzg" in req) { + result.kzg = req.kzg; + } + if ("blobs" in req && req.blobs) { + result.blobs = req.blobs.map((b)=>{ + if (isBytesLike(b)) { + return hexlify(b); + } + return Object.assign({}, b); + }); } + return result; } -inherits_browser1(Point, base.BasePoint); -ShortCurve.prototype.point = function point2(x, y, isRed) { - return new Point(this, x, y, isRed); -}; -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; -Point.prototype._getBeta = function _getBeta2() { - if (!this.curve.endo) return; - var pre = this.precomputed; - if (pre && pre.beta) return pre.beta; - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) +class Block { + provider; + number; + hash; + timestamp; + parentHash; + parentBeaconBlockRoot; + nonce; + difficulty; + gasLimit; + gasUsed; + stateRoot; + receiptsRoot; + blobGasUsed; + excessBlobGas; + miner; + prevRandao; + extraData; + baseFeePerGas; + #transactions; + constructor(block, provider){ + this.#transactions = block.transactions.map((tx)=>{ + if (typeof tx !== "string") { + return new TransactionResponse(tx, provider); } - }; + return tx; + }); + defineProperties(this, { + provider: provider, + hash: getValue(block.hash), + number: block.number, + timestamp: block.timestamp, + parentHash: block.parentHash, + parentBeaconBlockRoot: block.parentBeaconBlockRoot, + nonce: block.nonce, + difficulty: block.difficulty, + gasLimit: block.gasLimit, + gasUsed: block.gasUsed, + blobGasUsed: block.blobGasUsed, + excessBlobGas: block.excessBlobGas, + miner: block.miner, + prevRandao: getValue(block.prevRandao), + extraData: block.extraData, + baseFeePerGas: getValue(block.baseFeePerGas), + stateRoot: block.stateRoot, + receiptsRoot: block.receiptsRoot + }); } - return beta; -}; -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) return [ - this.x, - this.y - ]; - return [ - this.x, - this.y, - this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) + get transactions() { + return this.#transactions.map((tx)=>{ + if (typeof tx === "string") { + return tx; } + return tx.hash; + }); + } + get prefetchedTransactions() { + const txs = this.#transactions.slice(); + if (txs.length === 0) { + return []; } - ]; -}; -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === "string") obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) return res; - function obj2point(obj2) { - return curve.point(obj2[0], obj2[1], red); - } - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ - res - ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ - res - ].concat(pre.naf.points.map(obj2point)) - } - }; - return res; -}; -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) return ""; - return ""; -}; -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; -Point.prototype.add = function add(p) { - if (this.inf) return p; - if (p.inf) return this; - if (this.eq(p)) return this.dbl(); - if (this.neg().eq(p)) return this.curve.point(null, null); - if (this.x.cmp(p.x) === 0) return this.curve.point(null, null); - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; -Point.prototype.dbl = function dbl() { - if (this.inf) return this; - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) return this.curve.point(null, null); - var a = this.curve.a; - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; -Point.prototype.mul = function mul(k) { - k = new bn(k, 16); - if (this.isInfinity()) return this; - else if (this._hasDoubles(k)) return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) return this.curve._endoWnafMulAdd([ - this - ], [ - k - ]); - else return this.curve._wnafMul(this, k); -}; -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ - this, - p2 - ]; - var coeffs = [ - k1, - k2 - ]; - if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs); - else return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; -Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ - this, - p2 - ]; - var coeffs = [ - k1, - k2 - ]; - if (this.curve.endo) return this.curve._endoWnafMulAdd(points, coeffs, true); - else return this.curve._wnafMulAdd(1, points, coeffs, 2, true); -}; -Point.prototype.eq = function eq2(p) { - return this === p || this.inf === p.inf && (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; -Point.prototype.neg = function neg(_precompute) { - if (this.inf) return this; - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) + assert1(typeof txs[0] === "object", "transactions were not prefetched with block request", "UNSUPPORTED_OPERATION", { + operation: "transactionResponses()" + }); + return txs; + } + toJSON() { + const { baseFeePerGas, difficulty, extraData, gasLimit, gasUsed, hash, miner, prevRandao, nonce, number, parentHash, parentBeaconBlockRoot, stateRoot, receiptsRoot, timestamp, transactions } = this; + return { + _type: "Block", + baseFeePerGas: toJson(baseFeePerGas), + difficulty: toJson(difficulty), + extraData: extraData, + gasLimit: toJson(gasLimit), + gasUsed: toJson(gasUsed), + blobGasUsed: toJson(this.blobGasUsed), + excessBlobGas: toJson(this.excessBlobGas), + hash: hash, + miner: miner, + prevRandao: prevRandao, + nonce: nonce, + number: number, + parentHash: parentHash, + timestamp: timestamp, + parentBeaconBlockRoot: parentBeaconBlockRoot, + stateRoot: stateRoot, + receiptsRoot: receiptsRoot, + transactions: transactions + }; + } + [Symbol.iterator]() { + let index = 0; + const txs = this.transactions; + return { + next: ()=>{ + if (index < this.length) { + return { + value: txs[index++], + done: false + }; + } + return { + value: undefined, + done: true + }; } }; } - return res; -}; -Point.prototype.toJ = function toJ() { - if (this.inf) return this.curve.jpoint(null, null, null); - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; -function JPoint(curve, x, y, z) { - base.BasePoint.call(this, curve, "jacobian"); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new bn(0); - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = new bn(z, 16); - } - if (!this.x.red) this.x = this.x.toRed(this.curve.red); - if (!this.y.red) this.y = this.y.toRed(this.curve.red); - if (!this.z.red) this.z = this.z.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; -} -inherits_browser1(JPoint, base.BasePoint); -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) return this.curve.point(null, null); - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - return this.curve.point(ax, ay); -}; -JPoint.prototype.neg = function neg2() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; -JPoint.prototype.add = function add2(p) { - if (this.isInfinity()) return p; - if (p.isInfinity()) return this; - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); - else return this.dbl(); - } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); - return this.curve.jpoint(nx, ny, nz); -}; -JPoint.prototype.mixedAdd = function mixedAdd(p) { - if (this.isInfinity()) return p.toJ(); - if (p.isInfinity()) return this; - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) return this.curve.jpoint(null, null, null); - else return this.dbl(); - } - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); - return this.curve.jpoint(nx, ny, nz); -}; -JPoint.prototype.dblp = function dblp2(pow) { - if (pow === 0) return this; - if (this.isInfinity()) return this; - if (!pow) return this.dbl(); - var i; - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for(i = 0; i < pow; i++)r = r.dbl(); - return r; - } - var a = this.curve.a; - var tinv = this.curve.tinv; - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - var jyd = jy.redAdd(jy); - for(i = 0; i < pow; i++){ - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) jz4 = jz4.redMul(jyd4); - jx = nx; - jz = nz; - jyd = dny; - } - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; -JPoint.prototype.dbl = function dbl2() { - if (this.isInfinity()) return this; - if (this.curve.zeroA) return this._zeroDbl(); - else if (this.curve.threeA) return this._threeDbl(); - else return this._dbl(); -}; -JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - if (this.zOne) { - var xx = this.x.redSqr(); - var yy = this.y.redSqr(); - var yyyy = yy.redSqr(); - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - var m = xx.redAdd(xx).redIAdd(xx); - var t = m.redSqr().redISub(s).redISub(s); - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - nx = t; - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - nz = this.y.redAdd(this.y); - } else { - var a = this.x.redSqr(); - var b = this.y.redSqr(); - var c = b.redSqr(); - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - var e = a.redAdd(a).redIAdd(a); - var f = e.redSqr(); - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - nx = f.redISub(d).redISub(d); - ny = e.redMul(d.redISub(nx)).redISub(c8); - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - return this.curve.jpoint(nx, ny, nz); -}; -JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - if (this.zOne) { - var xx = this.x.redSqr(); - var yy = this.y.redSqr(); - var yyyy = yy.redSqr(); - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - var t = m.redSqr().redISub(s).redISub(s); - nx = t; - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - nz = this.y.redAdd(this.y); - } else { - var delta = this.z.redSqr(); - var gamma = this.y.redSqr(); - var beta = this.x.redMul(gamma); - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - return this.curve.jpoint(nx, ny, nz); -}; -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); - return this.curve.jpoint(nx, ny, nz); -}; -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) return this.dbl().add(this); - var xx = this.x.redSqr(); - var yy = this.y.redSqr(); - var zz = this.z.redSqr(); - var yyyy = yy.redSqr(); - var m = xx.redAdd(xx).redIAdd(xx); - var mm = m.redSqr(); - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - var ee = e.redSqr(); - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - return this.curve.jpoint(nx, ny, nz); -}; -JPoint.prototype.mul = function mul2(k, kbase) { - k = new bn(k, kbase); - return this.curve._wnafMul(this, k); -}; -JPoint.prototype.eq = function eq3(p) { - if (p.type === "affine") return this.eq(p.toJ()); - if (this === p) return true; - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) return false; - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; -JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) return true; - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for(;;){ - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) return false; - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) return true; + get length() { + return this.#transactions.length; } -}; -JPoint.prototype.inspect = function inspect2() { - if (this.isInfinity()) return ""; - return ""; -}; -JPoint.prototype.isInfinity = function isInfinity2() { - return this.z.cmpn(0) === 0; -}; -var curve_1 = createCommonjsModule4(function(module, exports) { - var curve = exports; - curve.base = base; - curve.short = short_1; - curve.mont = null; - curve.edwards = null; -}); -var curves_1 = createCommonjsModule4(function(module, exports) { - var curves = exports; - var assert2 = utils_1$1.assert; - function PresetCurve(options) { - if (options.type === "short") this.curve = new curve_1.short(options); - else if (options.type === "edwards") this.curve = new curve_1.edwards(options); - else this.curve = new curve_1.mont(options); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; - assert2(this.g.validate(), "Invalid curve"); - assert2(this.g.mul(this.n).isInfinity(), "Invalid curve, G*N != O"); - } - curves.PresetCurve = PresetCurve; - function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); + get date() { + if (this.timestamp == null) { + return null; + } + return new Date(this.timestamp * 1e3); } - defineCurve("p192", { - type: "short", - prime: "p192", - p: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff", - a: "ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc", - b: "64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1", - n: "ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831", - hash: hash_1.sha256, - gRed: false, - g: [ - "188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012", - "07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811" - ] - }); - defineCurve("p224", { - type: "short", - prime: "p224", - p: "ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001", - a: "ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe", - b: "b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4", - n: "ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d", - hash: hash_1.sha256, - gRed: false, - g: [ - "b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21", - "bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34" - ] - }); - defineCurve("p256", { - type: "short", - prime: null, - p: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff", - a: "ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc", - b: "5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b", - n: "ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551", - hash: hash_1.sha256, - gRed: false, - g: [ - "6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296", - "4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5" - ] - }); - defineCurve("p384", { - type: "short", - prime: null, - p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 ffffffff", - a: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe ffffffff 00000000 00000000 fffffffc", - b: "b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f 5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef", - n: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 f4372ddf 581a0db2 48b0a77a ecec196a ccc52973", - hash: hash_1.sha384, - gRed: false, - g: [ - "aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 5502f25d bf55296c 3a545e38 72760ab7", - "3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 0a60b1ce 1d7e819d 7a431d7c 90ea0e5f" - ] - }); - defineCurve("p521", { - type: "short", - prime: null, - p: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff", - a: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffc", - b: "00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b 99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd 3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00", - n: "000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409", - hash: hash_1.sha512, - gRed: false, - g: [ - "000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66", - "00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 3fad0761 353c7086 a272c240 88be9476 9fd16650" - ] - }); - defineCurve("curve25519", { - type: "mont", - prime: "p25519", - p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", - a: "76d06", - b: "1", - n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", - hash: hash_1.sha256, - gRed: false, - g: [ - "9" - ] - }); - defineCurve("ed25519", { - type: "edwards", - prime: "p25519", - p: "7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed", - a: "-1", - c: "1", - d: "52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3", - n: "1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed", - hash: hash_1.sha256, - gRed: false, - g: [ - "216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a", - "6666666666666666666666666666666666666666666666666666666666666658" - ] - }); - var pre; - try { - pre = null.crash(); - } catch (e) { - pre = void 0; - } - defineCurve("secp256k1", { - type: "short", - prime: "k256", - p: "ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f", - a: "0", - b: "7", - n: "ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141", - h: "1", - hash: hash_1.sha256, - beta: "7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", - lambda: "5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", - basis: [ - { - a: "3086d221a7d46bcde86c90e49284eb15", - b: "-e4437ed6010e88286f547fa90abfe4c3" - }, - { - a: "114ca50f7a8e2f3f657c1108d9d44cfd8", - b: "3086d221a7d46bcde86c90e49284eb15" + async getTransaction(indexOrHash) { + let tx = undefined; + if (typeof indexOrHash === "number") { + tx = this.#transactions[indexOrHash]; + } else { + const hash = indexOrHash.toLowerCase(); + for (const v of this.#transactions){ + if (typeof v === "string") { + if (v !== hash) { + continue; + } + tx = v; + break; + } else { + if (v.hash !== hash) { + continue; + } + tx = v; + break; + } } - ], - gRed: false, - g: [ - "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", - "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8", - pre - ] - }); -}); -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; - var entropy = utils_1.toArray(options.entropy, options.entropyEnc || "hex"); - var nonce = utils_1.toArray(options.nonce, options.nonceEnc || "hex"); - var pers = utils_1.toArray(options.pers, options.persEnc || "hex"); - minimalisticAssert1(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"); - this._init(entropy, nonce, pers); -} -var hmacDrbg = HmacDRBG; -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for(var i = 0; i < this.V.length; i++){ - this.K[i] = 0; - this.V[i] = 1; - } - this._update(seed); - this._reseed = 1; - this.reseedInterval = 281474976710656; -}; -HmacDRBG.prototype._hmac = function hmac() { - return new hash_1.hmac(this.hash, this.K); -}; -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac().update(this.V).update([ - 0 - ]); - if (seed) kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) return; - this.K = this._hmac().update(this.V).update([ - 1 - ]).update(seed).digest(); - this.V = this._hmac().update(this.V).digest(); -}; -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add3, addEnc) { - if (typeof entropyEnc !== "string") { - addEnc = add3; - add3 = entropyEnc; - entropyEnc = null; - } - entropy = utils_1.toArray(entropy, entropyEnc); - add3 = utils_1.toArray(add3, addEnc); - minimalisticAssert1(entropy.length >= this.minEntropy / 8, "Not enough entropy. Minimum is: " + this.minEntropy + " bits"); - this._update(entropy.concat(add3 || [])); - this._reseed = 1; -}; -HmacDRBG.prototype.generate = function generate(len, enc, add3, addEnc) { - if (this._reseed > this.reseedInterval) throw new Error("Reseed is required"); - if (typeof enc !== "string") { - addEnc = add3; - add3 = enc; - enc = null; - } - if (add3) { - add3 = utils_1.toArray(add3, addEnc || "hex"); - this._update(add3); - } - var temp = []; - while(temp.length < len){ - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } - var res = temp.slice(0, len); - this._update(add3); - this._reseed++; - return utils_1.encode(res, enc); -}; -var assert$3 = utils_1$1.assert; -function KeyPair(ec2, options) { - this.ec = ec2; - this.priv = null; - this.pub = null; - if (options.priv) this._importPrivate(options.priv, options.privEnc); - if (options.pub) this._importPublic(options.pub, options.pubEnc); -} -var key = KeyPair; -KeyPair.fromPublic = function fromPublic(ec2, pub, enc) { - if (pub instanceof KeyPair) return pub; - return new KeyPair(ec2, { - pub, - pubEnc: enc - }); -}; -KeyPair.fromPrivate = function fromPrivate(ec2, priv, enc) { - if (priv instanceof KeyPair) return priv; - return new KeyPair(ec2, { - priv, - privEnc: enc - }); -}; -KeyPair.prototype.validate = function validate4() { - var pub = this.getPublic(); - if (pub.isInfinity()) return { - result: false, - reason: "Invalid public key" - }; - if (!pub.validate()) return { - result: false, - reason: "Public key is not a point" - }; - if (!pub.mul(this.ec.curve.n).isInfinity()) return { - result: false, - reason: "Public key * N != O" - }; - return { - result: true, - reason: null - }; -}; -KeyPair.prototype.getPublic = function getPublic(compact, enc) { - if (typeof compact === "string") { - enc = compact; - compact = null; - } - if (!this.pub) this.pub = this.ec.g.mul(this.priv); - if (!enc) return this.pub; - return this.pub.encode(enc, compact); -}; -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === "hex") return this.priv.toString(16, 2); - else return this.priv; -}; -KeyPair.prototype._importPrivate = function _importPrivate(key2, enc) { - this.priv = new bn(key2, enc || 16); - this.priv = this.priv.umod(this.ec.curve.n); -}; -KeyPair.prototype._importPublic = function _importPublic(key2, enc) { - if (key2.x || key2.y) { - if (this.ec.curve.type === "mont") { - assert$3(key2.x, "Need x coordinate"); - } else if (this.ec.curve.type === "short" || this.ec.curve.type === "edwards") { - assert$3(key2.x && key2.y, "Need both x and y coordinate"); - } - this.pub = this.ec.curve.point(key2.x, key2.y); - return; + } + if (tx == null) { + throw new Error("no such tx"); + } + if (typeof tx === "string") { + return await this.provider.getTransaction(tx); + } else { + return tx; + } } - this.pub = this.ec.curve.decodePoint(key2, enc); -}; -KeyPair.prototype.derive = function derive(pub) { - if (!pub.validate()) { - assert$3(pub.validate(), "public point not validated"); + getPrefetchedTransaction(indexOrHash) { + const txs = this.prefetchedTransactions; + if (typeof indexOrHash === "number") { + return txs[indexOrHash]; + } + indexOrHash = indexOrHash.toLowerCase(); + for (const tx of txs){ + if (tx.hash === indexOrHash) { + return tx; + } + } + assertArgument(false, "no matching transaction", "indexOrHash", indexOrHash); + } + isMined() { + return !!this.hash; + } + isLondon() { + return !!this.baseFeePerGas; + } + orphanedEvent() { + if (!this.isMined()) { + throw new Error(""); + } + return createOrphanedBlockFilter(this); + } +} +class Log { + provider; + transactionHash; + blockHash; + blockNumber; + removed; + address; + data; + topics; + index; + transactionIndex; + constructor(log, provider){ + this.provider = provider; + const topics = Object.freeze(log.topics.slice()); + defineProperties(this, { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + removed: log.removed, + address: log.address, + data: log.data, + topics: topics, + index: log.index, + transactionIndex: log.transactionIndex + }); } - return pub.mul(this.priv).getX(); -}; -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); -}; -KeyPair.prototype.verify = function verify(msg, signature2) { - return this.ec.verify(msg, signature2, this); -}; -KeyPair.prototype.inspect = function inspect3() { - return ""; -}; -var assert$4 = utils_1$1.assert; -function Signature(options, enc) { - if (options instanceof Signature) return options; - if (this._importDER(options, enc)) return; - assert$4(options.r && options.s, "Signature without r or s"); - this.r = new bn(options.r, 16); - this.s = new bn(options.s, 16); - if (options.recoveryParam === void 0) this.recoveryParam = null; - else this.recoveryParam = options.recoveryParam; -} -var signature = Signature; -function Position() { - this.place = 0; -} -function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 128)) { - return initial; - } - var octetLen = initial & 15; - if (octetLen === 0 || octetLen > 4) { - return false; + toJSON() { + const { address, blockHash, blockNumber, data, index, removed, topics, transactionHash, transactionIndex } = this; + return { + _type: "log", + address: address, + blockHash: blockHash, + blockNumber: blockNumber, + data: data, + index: index, + removed: removed, + topics: topics, + transactionHash: transactionHash, + transactionIndex: transactionIndex + }; + } + async getBlock() { + const block = await this.provider.getBlock(this.blockHash); + assert1(!!block, "failed to find transaction", "UNKNOWN_ERROR", {}); + return block; + } + async getTransaction() { + const tx = await this.provider.getTransaction(this.transactionHash); + assert1(!!tx, "failed to find transaction", "UNKNOWN_ERROR", {}); + return tx; } - var val = 0; - for(var i = 0, off = p.place; i < octetLen; i++, off++){ - val <<= 8; - val |= buf[off]; - val >>>= 0; + async getTransactionReceipt() { + const receipt = await this.provider.getTransactionReceipt(this.transactionHash); + assert1(!!receipt, "failed to find transaction receipt", "UNKNOWN_ERROR", {}); + return receipt; + } + removedEvent() { + return createRemovedLogFilter(this); + } +} +class TransactionReceipt { + provider; + to; + from; + contractAddress; + hash; + index; + blockHash; + blockNumber; + logsBloom; + gasUsed; + blobGasUsed; + cumulativeGasUsed; + gasPrice; + blobGasPrice; + type; + status; + root; + #logs; + constructor(tx, provider){ + this.#logs = Object.freeze(tx.logs.map((log)=>{ + return new Log(log, provider); + })); + let gasPrice = BN_0$2; + if (tx.effectiveGasPrice != null) { + gasPrice = tx.effectiveGasPrice; + } else if (tx.gasPrice != null) { + gasPrice = tx.gasPrice; + } + defineProperties(this, { + provider: provider, + to: tx.to, + from: tx.from, + contractAddress: tx.contractAddress, + hash: tx.hash, + index: tx.index, + blockHash: tx.blockHash, + blockNumber: tx.blockNumber, + logsBloom: tx.logsBloom, + gasUsed: tx.gasUsed, + cumulativeGasUsed: tx.cumulativeGasUsed, + blobGasUsed: tx.blobGasUsed, + gasPrice: gasPrice, + blobGasPrice: tx.blobGasPrice, + type: tx.type, + status: tx.status, + root: tx.root + }); } - if (val <= 127) { - return false; + get logs() { + return this.#logs; } - p.place = off; - return val; -} -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while(!buf[i] && !(buf[i + 1] & 128) && i < len){ - i++; + toJSON() { + const { to, from, contractAddress, hash, index, blockHash, blockNumber, logsBloom, logs, status, root } = this; + return { + _type: "TransactionReceipt", + blockHash: blockHash, + blockNumber: blockNumber, + contractAddress: contractAddress, + cumulativeGasUsed: toJson(this.cumulativeGasUsed), + from: from, + gasPrice: toJson(this.gasPrice), + blobGasUsed: toJson(this.blobGasUsed), + blobGasPrice: toJson(this.blobGasPrice), + gasUsed: toJson(this.gasUsed), + hash: hash, + index: index, + logs: logs, + logsBloom: logsBloom, + root: root, + status: status, + to: to + }; } - if (i === 0) { - return buf; + get length() { + return this.logs.length; } - return buf.slice(i); -} -Signature.prototype._importDER = function _importDER(data, enc) { - data = utils_1$1.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 48) { - return false; + [Symbol.iterator]() { + let index = 0; + return { + next: ()=>{ + if (index < this.length) { + return { + value: this.logs[index++], + done: false + }; + } + return { + value: undefined, + done: true + }; + } + }; } - var len = getLength(data, p); - if (len === false) { - return false; + get fee() { + return this.gasUsed * this.gasPrice; } - if (len + p.place !== data.length) { - return false; + async getBlock() { + const block = await this.provider.getBlock(this.blockHash); + if (block == null) { + throw new Error("TODO"); + } + return block; } - if (data[p.place++] !== 2) { - return false; + async getTransaction() { + const tx = await this.provider.getTransaction(this.hash); + if (tx == null) { + throw new Error("TODO"); + } + return tx; } - var rlen = getLength(data, p); - if (rlen === false) { - return false; + async getResult() { + return await this.provider.getTransactionResult(this.hash); } - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 2) { - return false; + async confirmations() { + return await this.provider.getBlockNumber() - this.blockNumber + 1; } - var slen = getLength(data, p); - if (slen === false) { - return false; + removedEvent() { + return createRemovedTransactionFilter(this); } - if (data.length !== slen + p.place) { - return false; + reorderedEvent(other) { + assert1(!other || other.isMined(), "unmined 'other' transction cannot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "reorderedEvent(other)" + }); + return createReorderedTransactionFilter(this, other); + } +} +class TransactionResponse { + provider; + blockNumber; + blockHash; + index; + hash; + type; + to; + from; + nonce; + gasLimit; + gasPrice; + maxPriorityFeePerGas; + maxFeePerGas; + maxFeePerBlobGas; + data; + value; + chainId; + signature; + accessList; + blobVersionedHashes; + #startBlock; + constructor(tx, provider){ + this.provider = provider; + this.blockNumber = tx.blockNumber != null ? tx.blockNumber : null; + this.blockHash = tx.blockHash != null ? tx.blockHash : null; + this.hash = tx.hash; + this.index = tx.index; + this.type = tx.type; + this.from = tx.from; + this.to = tx.to || null; + this.gasLimit = tx.gasLimit; + this.nonce = tx.nonce; + this.data = tx.data; + this.value = tx.value; + this.gasPrice = tx.gasPrice; + this.maxPriorityFeePerGas = tx.maxPriorityFeePerGas != null ? tx.maxPriorityFeePerGas : null; + this.maxFeePerGas = tx.maxFeePerGas != null ? tx.maxFeePerGas : null; + this.maxFeePerBlobGas = tx.maxFeePerBlobGas != null ? tx.maxFeePerBlobGas : null; + this.chainId = tx.chainId; + this.signature = tx.signature; + this.accessList = tx.accessList != null ? tx.accessList : null; + this.blobVersionedHashes = tx.blobVersionedHashes != null ? tx.blobVersionedHashes : null; + this.#startBlock = -1; } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0) { - if (r[1] & 128) { - r = r.slice(1); - } else { - return false; + toJSON() { + const { blockNumber, blockHash, index, hash, type, to, from, nonce, data, signature, accessList, blobVersionedHashes } = this; + return { + _type: "TransactionResponse", + accessList: accessList, + blockNumber: blockNumber, + blockHash: blockHash, + blobVersionedHashes: blobVersionedHashes, + chainId: toJson(this.chainId), + data: data, + from: from, + gasLimit: toJson(this.gasLimit), + gasPrice: toJson(this.gasPrice), + hash: hash, + maxFeePerGas: toJson(this.maxFeePerGas), + maxPriorityFeePerGas: toJson(this.maxPriorityFeePerGas), + maxFeePerBlobGas: toJson(this.maxFeePerBlobGas), + nonce: nonce, + signature: signature, + to: to, + index: index, + type: type, + value: toJson(this.value) + }; + } + async getBlock() { + let blockNumber = this.blockNumber; + if (blockNumber == null) { + const tx = await this.getTransaction(); + if (tx) { + blockNumber = tx.blockNumber; + } + } + if (blockNumber == null) { + return null; + } + const block = this.provider.getBlock(blockNumber); + if (block == null) { + throw new Error("TODO"); } + return block; + } + async getTransaction() { + return this.provider.getTransaction(this.hash); } - if (s[0] === 0) { - if (s[1] & 128) { - s = s.slice(1); + async confirmations() { + if (this.blockNumber == null) { + const { tx, blockNumber } = await resolveProperties({ + tx: this.getTransaction(), + blockNumber: this.provider.getBlockNumber() + }); + if (tx == null || tx.blockNumber == null) { + return 0; + } + return blockNumber - tx.blockNumber + 1; + } + const blockNumber = await this.provider.getBlockNumber(); + return blockNumber - this.blockNumber + 1; + } + async wait(_confirms, _timeout) { + const confirms = _confirms == null ? 1 : _confirms; + const timeout = _timeout == null ? 0 : _timeout; + let startBlock = this.#startBlock; + let nextScan = -1; + let stopScanning = startBlock === -1 ? true : false; + const checkReplacement = async ()=>{ + if (stopScanning) { + return null; + } + const { blockNumber, nonce } = await resolveProperties({ + blockNumber: this.provider.getBlockNumber(), + nonce: this.provider.getTransactionCount(this.from) + }); + if (nonce < this.nonce) { + startBlock = blockNumber; + return; + } + if (stopScanning) { + return null; + } + const mined = await this.getTransaction(); + if (mined && mined.blockNumber != null) { + return; + } + if (nextScan === -1) { + nextScan = startBlock - 3; + if (nextScan < this.#startBlock) { + nextScan = this.#startBlock; + } + } + while(nextScan <= blockNumber){ + if (stopScanning) { + return null; + } + const block = await this.provider.getBlock(nextScan, true); + if (block == null) { + return; + } + for (const hash of block){ + if (hash === this.hash) { + return; + } + } + for(let i = 0; i < block.length; i++){ + const tx = await block.getTransaction(i); + if (tx.from === this.from && tx.nonce === this.nonce) { + if (stopScanning) { + return null; + } + const receipt = await this.provider.getTransactionReceipt(tx.hash); + if (receipt == null) { + return; + } + if (blockNumber - receipt.blockNumber + 1 < confirms) { + return; + } + let reason = "replaced"; + if (tx.data === this.data && tx.to === this.to && tx.value === this.value) { + reason = "repriced"; + } else if (tx.data === "0x" && tx.from === tx.to && tx.value === BN_0$2) { + reason = "cancelled"; + } + assert1(false, "transaction was replaced", "TRANSACTION_REPLACED", { + cancelled: reason === "replaced" || reason === "cancelled", + reason: reason, + replacement: tx.replaceableTransaction(startBlock), + hash: tx.hash, + receipt: receipt + }); + } + } + nextScan++; + } + return; + }; + const checkReceipt = (receipt)=>{ + if (receipt == null || receipt.status !== 0) { + return receipt; + } + assert1(false, "transaction execution reverted", "CALL_EXCEPTION", { + action: "sendTransaction", + data: null, + reason: null, + invocation: null, + revert: null, + transaction: { + to: receipt.to, + from: receipt.from, + data: "" + }, + receipt: receipt + }); + }; + const receipt = await this.provider.getTransactionReceipt(this.hash); + if (confirms === 0) { + return checkReceipt(receipt); + } + if (receipt) { + if (await receipt.confirmations() >= confirms) { + return checkReceipt(receipt); + } } else { - return false; + await checkReplacement(); + if (confirms === 0) { + return null; + } } + const waiter = new Promise((resolve, reject)=>{ + const cancellers = []; + const cancel = ()=>{ + cancellers.forEach((c)=>c()); + }; + cancellers.push(()=>{ + stopScanning = true; + }); + if (timeout > 0) { + const timer = setTimeout(()=>{ + cancel(); + reject(makeError("wait for transaction timeout", "TIMEOUT")); + }, timeout); + cancellers.push(()=>{ + clearTimeout(timer); + }); + } + const txListener = async (receipt)=>{ + if (await receipt.confirmations() >= confirms) { + cancel(); + try { + resolve(checkReceipt(receipt)); + } catch (error) { + reject(error); + } + } + }; + cancellers.push(()=>{ + this.provider.off(this.hash, txListener); + }); + this.provider.on(this.hash, txListener); + if (startBlock >= 0) { + const replaceListener = async ()=>{ + try { + await checkReplacement(); + } catch (error) { + if (isError(error, "TRANSACTION_REPLACED")) { + cancel(); + reject(error); + return; + } + } + if (!stopScanning) { + this.provider.once("block", replaceListener); + } + }; + cancellers.push(()=>{ + this.provider.off("block", replaceListener); + }); + this.provider.once("block", replaceListener); + } + }); + return await waiter; } - this.r = new bn(r); - this.s = new bn(s); - this.recoveryParam = null; - return true; -}; -function constructLength(arr, len) { - if (len < 128) { - arr.push(len); - return; + isMined() { + return this.blockHash != null; } - var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); - arr.push(octets | 128); - while(--octets){ - arr.push(len >>> (octets << 3) & 255); + isLegacy() { + return this.type === 0; } - arr.push(len); -} -Signature.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - if (r[0] & 128) r = [ - 0 - ].concat(r); - if (s[0] & 128) s = [ - 0 - ].concat(s); - r = rmPadding(r); - s = rmPadding(s); - while(!s[0] && !(s[1] & 128)){ - s = s.slice(1); - } - var arr = [ - 2 - ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(2); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ - 48 - ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils_1$1.encode(res, enc); -}; -var rand = function() { - throw new Error("unsupported"); -}; -var assert$5 = utils_1$1.assert; -function EC(options) { - if (!(this instanceof EC)) return new EC(options); - if (typeof options === "string") { - assert$5(Object.prototype.hasOwnProperty.call(curves_1, options), "Unknown curve " + options); - options = curves_1[options]; - } - if (options instanceof curves_1.PresetCurve) options = { - curve: options - }; - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); - this.hash = options.hash || options.curve.hash; -} -var ec = EC; -EC.prototype.keyPair = function keyPair(options) { - return new key(this, options); -}; -EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return key.fromPrivate(this, priv, enc); -}; -EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return key.fromPublic(this, pub, enc); -}; -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) options = {}; - var drbg = new hmacDrbg({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || "utf8", - entropy: options.entropy || rand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || "utf8", - nonce: this.n.toArray() - }); - var bytes2 = this.n.byteLength(); - var ns2 = this.n.sub(new bn(2)); - for(;;){ - var priv = new bn(drbg.generate(bytes2)); - if (priv.cmp(ns2) > 0) continue; - priv.iaddn(1); - return this.keyFromPrivate(priv); + isBerlin() { + return this.type === 1; } -}; -EC.prototype._truncateToN = function _truncateToN(msg, truncOnly) { - var delta = msg.byteLength() * 8 - this.n.bitLength(); - if (delta > 0) msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) return msg.sub(this.n); - else return msg; -}; -EC.prototype.sign = function sign2(msg, key2, enc, options) { - if (typeof enc === "object") { - options = enc; - enc = null; - } - if (!options) options = {}; - key2 = this.keyFromPrivate(key2, enc); - msg = this._truncateToN(new bn(msg, 16)); - var bytes2 = this.n.byteLength(); - var bkey = key2.getPrivate().toArray("be", bytes2); - var nonce = msg.toArray("be", bytes2); - var drbg = new hmacDrbg({ - hash: this.hash, - entropy: bkey, - nonce, - pers: options.pers, - persEnc: options.persEnc || "utf8" - }); - var ns1 = this.n.sub(new bn(1)); - for(var iter = 0;; iter++){ - var k = options.k ? options.k(iter) : new bn(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) continue; - var kp = this.g.mul(k); - if (kp.isInfinity()) continue; - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) continue; - var s = k.invm(this.n).mul(r.mul(key2.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) continue; - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | (kpX.cmp(r) !== 0 ? 2 : 0); - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } - return new signature({ - r, - s, - recoveryParam - }); + isLondon() { + return this.type === 2; } -}; -EC.prototype.verify = function verify2(msg, signature$1, key2, enc) { - msg = this._truncateToN(new bn(msg, 16)); - key2 = this.keyFromPublic(key2, enc); - signature$1 = new signature(signature$1, "hex"); - var r = signature$1.r; - var s = signature$1.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) return false; - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); - var p; - if (!this.curve._maxwellTrick) { - p = this.g.mulAdd(u1, key2.getPublic(), u2); - if (p.isInfinity()) return false; - return p.getX().umod(this.n).cmp(r) === 0; - } - p = this.g.jmulAdd(u1, key2.getPublic(), u2); - if (p.isInfinity()) return false; - return p.eqXToP(r); -}; -EC.prototype.recoverPubKey = function(msg, signature$1, j, enc) { - assert$5((3 & j) === j, "The recovery param is more than two bits"); - signature$1 = new signature(signature$1, enc); - var n = this.n; - var e = new bn(msg); - var r = signature$1.r; - var s = signature$1.s; - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) throw new Error("Unable to find sencond key candinate"); - if (isSecondKey) r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else r = this.curve.pointFromX(r, isYOdd); - var rInv = signature$1.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); - return this.g.mulAdd(s1, r, s2); -}; -EC.prototype.getKeyRecoveryParam = function(e, signature$1, Q, enc) { - signature$1 = new signature(signature$1, enc); - if (signature$1.recoveryParam !== null) return signature$1.recoveryParam; - for(var i = 0; i < 4; i++){ - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature$1, i); - } catch (e2) { - continue; - } - if (Qprime.eq(Q)) return i; + isCancun() { + return this.type === 3; } - throw new Error("Unable to find valid recovery factor"); -}; -var elliptic_1 = createCommonjsModule4(function(module, exports) { - var elliptic = exports; - elliptic.version = ({ - version: "6.5.4" - }).version; - elliptic.utils = utils_1$1; - elliptic.rand = function() { - throw new Error("unsupported"); - }; - elliptic.curve = curve_1; - elliptic.curves = curves_1; - elliptic.ec = ec; - elliptic.eddsa = null; -}); -var EC$1 = elliptic_1.ec; -const version12 = "signing-key/5.7.0"; -const logger210 = new Logger(version12); -let _curve = null; -function getCurve() { - if (!_curve) { - _curve = new EC$1("secp256k1"); + removedEvent() { + assert1(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" + }); + return createRemovedTransactionFilter(this); } - return _curve; -} -class SigningKey { - constructor(privateKey){ - defineReadOnly(this, "curve", "secp256k1"); - defineReadOnly(this, "privateKey", hexlify(privateKey)); - if (hexDataLength(this.privateKey) !== 32) { - logger210.throwArgumentError("invalid private key", "privateKey", "[[ REDACTED ]]"); - } - const keyPair2 = getCurve().keyFromPrivate(arrayify(this.privateKey)); - defineReadOnly(this, "publicKey", "0x" + keyPair2.getPublic(false, "hex")); - defineReadOnly(this, "compressedPublicKey", "0x" + keyPair2.getPublic(true, "hex")); - defineReadOnly(this, "_isSigningKey", true); - } - _addPoint(other) { - const p0 = getCurve().keyFromPublic(arrayify(this.publicKey)); - const p1 = getCurve().keyFromPublic(arrayify(other)); - return "0x" + p0.pub.add(p1.pub).encodeCompressed("hex"); - } - signDigest(digest) { - const keyPair2 = getCurve().keyFromPrivate(arrayify(this.privateKey)); - const digestBytes = arrayify(digest); - if (digestBytes.length !== 32) { - logger210.throwArgumentError("bad digest length", "digest", digest); - } - const signature2 = keyPair2.sign(digestBytes, { - canonical: true + reorderedEvent(other) { + assert1(this.isMined(), "unmined transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" }); - return splitSignature({ - recoveryParam: signature2.recoveryParam, - r: hexZeroPad("0x" + signature2.r.toString(16), 32), - s: hexZeroPad("0x" + signature2.s.toString(16), 32) + assert1(!other || other.isMined(), "unmined 'other' transaction canot be orphaned", "UNSUPPORTED_OPERATION", { + operation: "removeEvent()" }); + return createReorderedTransactionFilter(this, other); } - computeSharedSecret(otherKey) { - const keyPair2 = getCurve().keyFromPrivate(arrayify(this.privateKey)); - const otherKeyPair = getCurve().keyFromPublic(arrayify(computePublicKey(otherKey))); - return hexZeroPad("0x" + keyPair2.derive(otherKeyPair.getPublic()).toString(16), 32); - } - static isSigningKey(value) { - return !!(value && value._isSigningKey); + replaceableTransaction(startBlock) { + assertArgument(Number.isInteger(startBlock) && startBlock >= 0, "invalid startBlock", "startBlock", startBlock); + const tx = new TransactionResponse(this, this.provider); + tx.#startBlock = startBlock; + return tx; } } -function recoverPublicKey(digest, signature2) { - const sig = splitSignature(signature2); - const rs = { - r: arrayify(sig.r), - s: arrayify(sig.s) +function createOrphanedBlockFilter(block) { + return { + orphan: "drop-block", + hash: block.hash, + number: block.number }; - return "0x" + getCurve().recoverPubKey(arrayify(digest), rs, sig.recoveryParam).encode("hex", false); -} -function computePublicKey(key2, compressed) { - const bytes2 = arrayify(key2); - if (bytes2.length === 32) { - const signingKey = new SigningKey(bytes2); - if (compressed) { - return "0x" + getCurve().keyFromPrivate(bytes2).getPublic(true, "hex"); - } - return signingKey.publicKey; - } else if (bytes2.length === 33) { - if (compressed) { - return hexlify(bytes2); - } - return "0x" + getCurve().keyFromPublic(bytes2).getPublic(false, "hex"); - } else if (bytes2.length === 65) { - if (!compressed) { - return hexlify(bytes2); - } - return "0x" + getCurve().keyFromPublic(bytes2).getPublic(true, "hex"); - } - return logger210.throwArgumentError("invalid public or private key", "key", "[REDACTED]"); -} -const version13 = "transactions/5.7.0"; -const logger211 = new Logger(version13); -var TransactionTypes; -(function(TransactionTypes2) { - TransactionTypes2[TransactionTypes2["legacy"] = 0] = "legacy"; - TransactionTypes2[TransactionTypes2["eip2930"] = 1] = "eip2930"; - TransactionTypes2[TransactionTypes2["eip1559"] = 2] = "eip1559"; -})(TransactionTypes || (TransactionTypes = {})); -function handleAddress(value) { - if (value === "0x") { - return null; - } - return getAddress(value); -} -function handleNumber(value) { - if (value === "0x") { - return Zero1; - } - return BigNumber.from(value); -} -const transactionFields = [ - { - name: "nonce", - maxLength: 32, - numeric: true - }, - { - name: "gasPrice", - maxLength: 32, - numeric: true - }, - { - name: "gasLimit", - maxLength: 32, - numeric: true - }, - { - name: "to", - length: 20 - }, - { - name: "value", - maxLength: 32, - numeric: true - }, - { - name: "data" - } -]; -const allowedTransactionKeys1 = { - chainId: true, - data: true, - gasLimit: true, - gasPrice: true, - nonce: true, - to: true, - type: true, - value: true -}; -function computeAddress(key) { - const publicKey = computePublicKey(key); - return getAddress(hexDataSlice(keccak256(hexDataSlice(publicKey, 1)), 12)); } -function recoverAddress(digest, signature) { - return computeAddress(recoverPublicKey(arrayify(digest), signature)); +function createReorderedTransactionFilter(tx, other) { + return { + orphan: "reorder-transaction", + tx: tx, + other: other + }; } -function formatNumber(value, name) { - const result = stripZeros(BigNumber.from(value).toHexString()); - if (result.length > 32) { - logger211.throwArgumentError("invalid length for " + name, "transaction:" + name, value); - } - return result; +function createRemovedTransactionFilter(tx) { + return { + orphan: "drop-transaction", + tx: tx + }; } -function accessSetify(addr, storageKeys) { +function createRemovedLogFilter(log) { return { - address: getAddress(addr), - storageKeys: (storageKeys || []).map((storageKey, index)=>{ - if (hexDataLength(storageKey) !== 32) { - logger211.throwArgumentError("invalid access list storageKey", `accessList[${addr}:${index}]`, storageKey); - } - return storageKey.toLowerCase(); - }) + orphan: "drop-log", + log: { + transactionHash: log.transactionHash, + blockHash: log.blockHash, + blockNumber: log.blockNumber, + address: log.address, + data: log.data, + topics: Object.freeze(log.topics.slice()), + index: log.index + } }; } -function accessListify(value) { - if (Array.isArray(value)) { - return value.map((set, index)=>{ - if (Array.isArray(set)) { - if (set.length > 2) { - logger211.throwArgumentError("access list expected to be [ address, storageKeys[] ]", `value[${index}]`, set); - } - return accessSetify(set[0], set[1]); - } - return accessSetify(set.address, set.storageKeys); +class EventLog extends Log { + interface; + fragment; + args; + constructor(log, iface, fragment){ + super(log, log.provider); + const args = iface.decodeEventLog(fragment, log.data, log.topics); + defineProperties(this, { + args: args, + fragment: fragment, + interface: iface }); } - const result = Object.keys(value).map((addr)=>{ - const storageKeys = value[addr].reduce((accum, storageKey)=>{ - accum[storageKey] = true; - return accum; - }, {}); - return accessSetify(addr, Object.keys(storageKeys).sort()); - }); - result.sort((a, b)=>a.address.localeCompare(b.address)); - return result; -} -function formatAccessList(value) { - return accessListify(value).map((set)=>[ - set.address, - set.storageKeys - ]); -} -function _serializeEip1559(transaction, signature) { - if (transaction.gasPrice != null) { - const gasPrice = BigNumber.from(transaction.gasPrice); - const maxFeePerGas = BigNumber.from(transaction.maxFeePerGas || 0); - if (!gasPrice.eq(maxFeePerGas)) { - logger211.throwArgumentError("mismatch EIP-1559 gasPrice != maxFeePerGas", "tx", { - gasPrice, - maxFeePerGas - }); - } + get eventName() { + return this.fragment.name; } - const fields = [ - formatNumber(transaction.chainId || 0, "chainId"), - formatNumber(transaction.nonce || 0, "nonce"), - formatNumber(transaction.maxPriorityFeePerGas || 0, "maxPriorityFeePerGas"), - formatNumber(transaction.maxFeePerGas || 0, "maxFeePerGas"), - formatNumber(transaction.gasLimit || 0, "gasLimit"), - transaction.to != null ? getAddress(transaction.to) : "0x", - formatNumber(transaction.value || 0, "value"), - transaction.data || "0x", - formatAccessList(transaction.accessList || []) - ]; - if (signature) { - const sig = splitSignature(signature); - fields.push(formatNumber(sig.recoveryParam, "recoveryParam")); - fields.push(stripZeros(sig.r)); - fields.push(stripZeros(sig.s)); + get eventSignature() { + return this.fragment.format(); } - return hexConcat([ - "0x02", - encode(fields) - ]); } -function _serializeEip2930(transaction, signature) { - const fields = [ - formatNumber(transaction.chainId || 0, "chainId"), - formatNumber(transaction.nonce || 0, "nonce"), - formatNumber(transaction.gasPrice || 0, "gasPrice"), - formatNumber(transaction.gasLimit || 0, "gasLimit"), - transaction.to != null ? getAddress(transaction.to) : "0x", - formatNumber(transaction.value || 0, "value"), - transaction.data || "0x", - formatAccessList(transaction.accessList || []) - ]; - if (signature) { - const sig = splitSignature(signature); - fields.push(formatNumber(sig.recoveryParam, "recoveryParam")); - fields.push(stripZeros(sig.r)); - fields.push(stripZeros(sig.s)); +class UndecodedEventLog extends Log { + error; + constructor(log, error){ + super(log, log.provider); + defineProperties(this, { + error: error + }); } - return hexConcat([ - "0x01", - encode(fields) - ]); } -function _serialize(transaction, signature) { - checkProperties(transaction, allowedTransactionKeys1); - const raw = []; - transactionFields.forEach(function(fieldInfo) { - let value = transaction[fieldInfo.name] || []; - const options = {}; - if (fieldInfo.numeric) { - options.hexPad = "left"; - } - value = arrayify(hexlify(value, options)); - if (fieldInfo.length && value.length !== fieldInfo.length && value.length > 0) { - logger211.throwArgumentError("invalid length for " + fieldInfo.name, "transaction:" + fieldInfo.name, value); - } - if (fieldInfo.maxLength) { - value = stripZeros(value); - if (value.length > fieldInfo.maxLength) { - logger211.throwArgumentError("invalid length for " + fieldInfo.name, "transaction:" + fieldInfo.name, value); +class ContractTransactionReceipt extends TransactionReceipt { + #iface; + constructor(iface, provider, tx){ + super(tx, provider); + this.#iface = iface; + } + get logs() { + return super.logs.map((log)=>{ + const fragment = log.topics.length ? this.#iface.getEvent(log.topics[0]) : null; + if (fragment) { + try { + return new EventLog(log, this.#iface, fragment); + } catch (error) { + return new UndecodedEventLog(log, error); + } } - } - raw.push(hexlify(value)); - }); - let chainId = 0; - if (transaction.chainId != null) { - chainId = transaction.chainId; - if (typeof chainId !== "number") { - logger211.throwArgumentError("invalid transaction.chainId", "transaction", transaction); - } - } else if (signature && !isBytesLike(signature) && signature.v > 28) { - chainId = Math.floor((signature.v - 35) / 2); - } - if (chainId !== 0) { - raw.push(hexlify(chainId)); - raw.push("0x"); - raw.push("0x"); - } - if (!signature) { - return encode(raw); - } - const sig = splitSignature(signature); - let v = 27 + sig.recoveryParam; - if (chainId !== 0) { - raw.pop(); - raw.pop(); - raw.pop(); - v += chainId * 2 + 8; - if (sig.v > 28 && sig.v !== v) { - logger211.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature); - } - } else if (sig.v !== v) { - logger211.throwArgumentError("transaction.chainId/signature.v mismatch", "signature", signature); - } - raw.push(hexlify(v)); - raw.push(stripZeros(arrayify(sig.r))); - raw.push(stripZeros(arrayify(sig.s))); - return encode(raw); -} -function serialize(transaction, signature) { - if (transaction.type == null || transaction.type === 0) { - if (transaction.accessList != null) { - logger211.throwArgumentError("untyped transactions do not support accessList; include type: 1", "transaction", transaction); - } - return _serialize(transaction, signature); - } - switch(transaction.type){ - case 1: - return _serializeEip2930(transaction, signature); - case 2: - return _serializeEip1559(transaction, signature); - } - return logger211.throwError(`unsupported transaction type: ${transaction.type}`, Logger.errors.UNSUPPORTED_OPERATION, { - operation: "serializeTransaction", - transactionType: transaction.type - }); + return log; + }); + } } -function _parseEipSignature(tx, fields, serialize2) { - try { - const recid = handleNumber(fields[0]).toNumber(); - if (recid !== 0 && recid !== 1) { - throw new Error("bad recid"); +class ContractTransactionResponse extends TransactionResponse { + #iface; + constructor(iface, provider, tx){ + super(tx, provider); + this.#iface = iface; + } + async wait(confirms, timeout) { + const receipt = await super.wait(confirms, timeout); + if (receipt == null) { + return null; } - tx.v = recid; - } catch (error) { - logger211.throwArgumentError("invalid v for transaction type: 1", "v", fields[0]); + return new ContractTransactionReceipt(this.#iface, this.provider, receipt); } - tx.r = hexZeroPad(fields[1], 32); - tx.s = hexZeroPad(fields[2], 32); - try { - const digest = keccak256(serialize2(tx)); - tx.from = recoverAddress(digest, { - r: tx.r, - s: tx.s, - recoveryParam: tx.v - }); - } catch (error) {} } -function _parseEip1559(payload) { - const transaction = decode1(payload.slice(1)); - if (transaction.length !== 9 && transaction.length !== 12) { - logger211.throwArgumentError("invalid component count for transaction type: 2", "payload", hexlify(payload)); +class ContractUnknownEventPayload extends EventPayload { + log; + constructor(contract, listener, filter, log){ + super(contract, listener, filter); + defineProperties(this, { + log: log + }); } - const maxPriorityFeePerGas = handleNumber(transaction[2]); - const maxFeePerGas = handleNumber(transaction[3]); - const tx = { - type: 2, - chainId: handleNumber(transaction[0]).toNumber(), - nonce: handleNumber(transaction[1]).toNumber(), - maxPriorityFeePerGas, - maxFeePerGas, - gasPrice: null, - gasLimit: handleNumber(transaction[4]), - to: handleAddress(transaction[5]), - value: handleNumber(transaction[6]), - data: transaction[7], - accessList: accessListify(transaction[8]) - }; - if (transaction.length === 9) { - return tx; + async getBlock() { + return await this.log.getBlock(); } - tx.hash = keccak256(payload); - _parseEipSignature(tx, transaction.slice(9), _serializeEip1559); - return tx; -} -function _parseEip2930(payload) { - const transaction = decode1(payload.slice(1)); - if (transaction.length !== 8 && transaction.length !== 11) { - logger211.throwArgumentError("invalid component count for transaction type: 1", "payload", hexlify(payload)); + async getTransaction() { + return await this.log.getTransaction(); } - const tx = { - type: 1, - chainId: handleNumber(transaction[0]).toNumber(), - nonce: handleNumber(transaction[1]).toNumber(), - gasPrice: handleNumber(transaction[2]), - gasLimit: handleNumber(transaction[3]), - to: handleAddress(transaction[4]), - value: handleNumber(transaction[5]), - data: transaction[6], - accessList: accessListify(transaction[7]) - }; - if (transaction.length === 8) { - return tx; + async getTransactionReceipt() { + return await this.log.getTransactionReceipt(); } - tx.hash = keccak256(payload); - _parseEipSignature(tx, transaction.slice(8), _serializeEip2930); - return tx; } -function _parse(rawTransaction) { - const transaction = decode1(rawTransaction); - if (transaction.length !== 9 && transaction.length !== 6) { - logger211.throwArgumentError("invalid raw transaction", "rawTransaction", rawTransaction); +class ContractEventPayload extends ContractUnknownEventPayload { + constructor(contract, listener, filter, fragment, _log){ + super(contract, listener, filter, new EventLog(_log, contract.interface, fragment)); + const args = contract.interface.decodeEventLog(fragment, this.log.data, this.log.topics); + defineProperties(this, { + args: args, + fragment: fragment + }); } - const tx = { - nonce: handleNumber(transaction[0]).toNumber(), - gasPrice: handleNumber(transaction[1]), - gasLimit: handleNumber(transaction[2]), - to: handleAddress(transaction[3]), - value: handleNumber(transaction[4]), - data: transaction[5], - chainId: 0 - }; - if (transaction.length === 6) { - return tx; + get eventName() { + return this.fragment.name; } - try { - tx.v = BigNumber.from(transaction[6]).toNumber(); - } catch (error) { - return tx; + get eventSignature() { + return this.fragment.format(); } - tx.r = hexZeroPad(transaction[7], 32); - tx.s = hexZeroPad(transaction[8], 32); - if (BigNumber.from(tx.r).isZero() && BigNumber.from(tx.s).isZero()) { - tx.chainId = tx.v; - tx.v = 0; - } else { - tx.chainId = Math.floor((tx.v - 35) / 2); - if (tx.chainId < 0) { - tx.chainId = 0; - } - let recoveryParam = tx.v - 27; - const raw = transaction.slice(0, 6); - if (tx.chainId !== 0) { - raw.push(hexlify(tx.chainId)); - raw.push("0x"); - raw.push("0x"); - recoveryParam -= tx.chainId * 2 + 8; - } - const digest = keccak256(encode(raw)); - try { - tx.from = recoverAddress(digest, { - r: hexlify(tx.r), - s: hexlify(tx.s), - recoveryParam - }); - } catch (error) {} - tx.hash = keccak256(rawTransaction); +} +const BN_0$1 = BigInt(0); +function canCall(value) { + return value && typeof value.call === "function"; +} +function canEstimate(value) { + return value && typeof value.estimateGas === "function"; +} +function canResolve(value) { + return value && typeof value.resolveName === "function"; +} +function canSend(value) { + return value && typeof value.sendTransaction === "function"; +} +function getResolver(value) { + if (value != null) { + if (canResolve(value)) { + return value; + } + if (value.provider) { + return value.provider; + } } - tx.type = null; - return tx; + return undefined; } -function parse(rawTransaction) { - const payload = arrayify(rawTransaction); - if (payload[0] > 127) { - return _parse(payload); +class PreparedTopicFilter { + #filter; + fragment; + constructor(contract, fragment, args){ + defineProperties(this, { + fragment: fragment + }); + if (fragment.inputs.length < args.length) { + throw new Error("too many arguments"); + } + const runner = getRunner(contract.runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + this.#filter = async function() { + const resolvedArgs = await Promise.all(fragment.inputs.map((param, index)=>{ + const arg = args[index]; + if (arg == null) { + return null; + } + return param.walkAsync(args[index], (type, value)=>{ + if (type === "address") { + if (Array.isArray(value)) { + return Promise.all(value.map((v)=>resolveAddress(v, resolver))); + } + return resolveAddress(value, resolver); + } + return value; + }); + })); + return contract.interface.encodeFilterTopics(fragment, resolvedArgs); + }(); } - switch(payload[0]){ - case 1: - return _parseEip2930(payload); - case 2: - return _parseEip1559(payload); + getTopicFilter() { + return this.#filter; } - return logger211.throwError(`unsupported transaction type: ${payload[0]}`, Logger.errors.UNSUPPORTED_OPERATION, { - operation: "parseTransaction", - transactionType: payload[0] - }); } -const version14 = "contracts/5.7.0"; -var __awaiter4 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); +function getRunner(value, feature) { + if (value == null) { + return null; } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + if (typeof value[feature] === "function") { + return value; + } + if (value.provider && typeof value.provider[feature] === "function") { + return value.provider; + } + return null; +} +function getProvider(value) { + if (value == null) { + return null; + } + return value.provider || null; +} +async function copyOverrides(arg, allowed) { + const _overrides = Typed.dereference(arg, "overrides"); + assertArgument(typeof _overrides === "object", "invalid overrides parameter", "overrides", arg); + const overrides = copyRequest(_overrides); + assertArgument(overrides.to == null || (allowed || []).indexOf("to") >= 0, "cannot override to", "overrides.to", overrides.to); + assertArgument(overrides.data == null || (allowed || []).indexOf("data") >= 0, "cannot override data", "overrides.data", overrides.data); + if (overrides.from) { + overrides.from = overrides.from; + } + return overrides; +} +async function resolveArgs(_runner, inputs, args) { + const runner = getRunner(_runner, "resolveName"); + const resolver = canResolve(runner) ? runner : null; + return await Promise.all(inputs.map((param, index)=>{ + return param.walkAsync(args[index], (type, value)=>{ + value = Typed.dereference(value, type); + if (type === "address") { + return resolveAddress(value, resolver); } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger212 = new Logger(version14); -const allowedTransactionKeys2 = { - chainId: true, - data: true, - from: true, - gasLimit: true, - gasPrice: true, - nonce: true, - to: true, - value: true, - type: true, - accessList: true, - maxFeePerGas: true, - maxPriorityFeePerGas: true, - customData: true, - ccipReadEnabled: true -}; -function resolveName(resolver, nameOrPromise) { - return __awaiter4(this, void 0, void 0, function*() { - const name = yield nameOrPromise; - if (typeof name !== "string") { - logger212.throwArgumentError("invalid address or ENS name", "name", name); - } - try { - return getAddress(name); - } catch (error) {} - if (!resolver) { - logger212.throwError("a provider or signer is needed to resolve ENS names", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "resolveName" - }); - } - const address2 = yield resolver.resolveName(name); - if (address2 == null) { - logger212.throwArgumentError("resolver or addr is not configured for ENS name", "name", name); - } - return address2; - }); + return value; + }); + })); } -function resolveAddresses(resolver, value, paramType) { - return __awaiter4(this, void 0, void 0, function*() { - if (Array.isArray(paramType)) { - return yield Promise.all(paramType.map((paramType2, index)=>{ - return resolveAddresses(resolver, Array.isArray(value) ? value[index] : value[paramType2.name], paramType2); - })); - } - if (paramType.type === "address") { - return yield resolveName(resolver, value); - } - if (paramType.type === "tuple") { - return yield resolveAddresses(resolver, value, paramType.components); - } - if (paramType.baseType === "array") { - if (!Array.isArray(value)) { - return Promise.reject(logger212.makeError("invalid value for array", Logger.errors.INVALID_ARGUMENT, { - argument: "value", - value - })); +function buildWrappedFallback(contract) { + const populateTransaction = async function(overrides) { + const tx = await copyOverrides(overrides, [ + "data" + ]); + tx.to = await contract.getAddress(); + if (tx.from) { + tx.from = await resolveAddress(tx.from, getResolver(contract.runner)); + } + const iface = contract.interface; + const noValue = getBigInt(tx.value || BN_0$1, "overrides.value") === BN_0$1; + const noData = (tx.data || "0x") === "0x"; + if (iface.fallback && !iface.fallback.payable && iface.receive && !noData && !noValue) { + assertArgument(false, "cannot send data to receive or send value to non-payable fallback", "overrides", overrides); + } + assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + const payable = iface.receive || iface.fallback && iface.fallback.payable; + assertArgument(payable || noValue, "cannot send value to non-payable fallback", "overrides.value", tx.value); + assertArgument(iface.fallback || noData, "cannot send data to receive-only contract", "overrides.data", tx.data); + return tx; + }; + const staticCall = async function(overrides) { + const runner = getRunner(contract.runner, "call"); + assert1(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { + operation: "call" + }); + const tx = await populateTransaction(overrides); + try { + return await runner.call(tx); + } catch (error) { + if (isCallException(error) && error.data) { + throw contract.interface.makeError(error.data, tx); } - return yield Promise.all(value.map((v)=>resolveAddresses(resolver, v, paramType.arrayChildren))); + throw error; } - return value; + }; + const send = async function(overrides) { + const runner = contract.runner; + assert1(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + const tx = await runner.sendTransaction(await populateTransaction(overrides)); + const provider = getProvider(contract.runner); + return new ContractTransactionResponse(contract.interface, provider, tx); + }; + const estimateGas = async function(overrides) { + const runner = getRunner(contract.runner, "estimateGas"); + assert1(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { + operation: "estimateGas" + }); + return await runner.estimateGas(await populateTransaction(overrides)); + }; + const method = async (overrides)=>{ + return await send(overrides); + }; + defineProperties(method, { + _contract: contract, + estimateGas: estimateGas, + populateTransaction: populateTransaction, + send: send, + staticCall: staticCall }); + return method; } -function populateTransaction(contract, fragment, args) { - return __awaiter4(this, void 0, void 0, function*() { +function buildWrappedMethod(contract, key) { + const getFragment = function(...args) { + const fragment = contract.interface.getFunction(key, args); + assert1(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { + key: key, + args: args + } + }); + return fragment; + }; + const populateTransaction = async function(...args) { + const fragment = getFragment(...args); let overrides = {}; - if (args.length === fragment.inputs.length + 1 && typeof args[args.length - 1] === "object") { - overrides = shallowCopy(args.pop()); - } - logger212.checkArgumentCount(args.length, fragment.inputs.length, "passed to contract"); - if (contract.signer) { + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); if (overrides.from) { - overrides.from = resolveProperties({ - override: resolveName(contract.signer, overrides.from), - signer: contract.signer.getAddress() - }).then((check)=>__awaiter4(this, void 0, void 0, function*() { - if (getAddress(check.signer) !== check.override) { - logger212.throwError("Contract with a Signer cannot override from", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "overrides.from" - }); - } - return check.override; - })); - } else { - overrides.from = contract.signer.getAddress(); + overrides.from = await resolveAddress(overrides.from, getResolver(contract.runner)); + } + } + if (fragment.inputs.length !== args.length) { + throw new Error("internal error: fragment inputs doesn't match arguments; should not happen"); + } + const resolvedArgs = await resolveArgs(contract.runner, fragment.inputs, args); + return Object.assign({}, overrides, await resolveProperties({ + to: contract.getAddress(), + data: contract.interface.encodeFunctionData(fragment, resolvedArgs) + })); + }; + const staticCall = async function(...args) { + const result = await staticCallResult(...args); + if (result.length === 1) { + return result[0]; + } + return result; + }; + const send = async function(...args) { + const runner = contract.runner; + assert1(canSend(runner), "contract runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + const tx = await runner.sendTransaction(await populateTransaction(...args)); + const provider = getProvider(contract.runner); + return new ContractTransactionResponse(contract.interface, provider, tx); + }; + const estimateGas = async function(...args) { + const runner = getRunner(contract.runner, "estimateGas"); + assert1(canEstimate(runner), "contract runner does not support gas estimation", "UNSUPPORTED_OPERATION", { + operation: "estimateGas" + }); + return await runner.estimateGas(await populateTransaction(...args)); + }; + const staticCallResult = async function(...args) { + const runner = getRunner(contract.runner, "call"); + assert1(canCall(runner), "contract runner does not support calling", "UNSUPPORTED_OPERATION", { + operation: "call" + }); + const tx = await populateTransaction(...args); + let result = "0x"; + try { + result = await runner.call(tx); + } catch (error) { + if (isCallException(error) && error.data) { + throw contract.interface.makeError(error.data, tx); } - } else if (overrides.from) { - overrides.from = resolveName(contract.provider, overrides.from); - } - const resolved = yield resolveProperties({ - args: resolveAddresses(contract.signer || contract.provider, args, fragment.inputs), - address: contract.resolvedAddress, - overrides: resolveProperties(overrides) || {} - }); - const data = contract.interface.encodeFunctionData(fragment, resolved.args); - const tx = { - data, - to: resolved.address - }; - const ro = resolved.overrides; - if (ro.nonce != null) { - tx.nonce = BigNumber.from(ro.nonce).toNumber(); - } - if (ro.gasLimit != null) { - tx.gasLimit = BigNumber.from(ro.gasLimit); - } - if (ro.gasPrice != null) { - tx.gasPrice = BigNumber.from(ro.gasPrice); - } - if (ro.maxFeePerGas != null) { - tx.maxFeePerGas = BigNumber.from(ro.maxFeePerGas); - } - if (ro.maxPriorityFeePerGas != null) { - tx.maxPriorityFeePerGas = BigNumber.from(ro.maxPriorityFeePerGas); - } - if (ro.from != null) { - tx.from = ro.from; - } - if (ro.type != null) { - tx.type = ro.type; + throw error; } - if (ro.accessList != null) { - tx.accessList = accessListify(ro.accessList); + const fragment = getFragment(...args); + return contract.interface.decodeFunctionResult(fragment, result); + }; + const method = async (...args)=>{ + const fragment = getFragment(...args); + if (fragment.constant) { + return await staticCall(...args); } - if (tx.gasLimit == null && fragment.gas != null) { - let intrinsic = 21e3; - const bytes2 = arrayify(data); - for(let i = 0; i < bytes2.length; i++){ - intrinsic += 4; - if (bytes2[i]) { - intrinsic += 64; + return await send(...args); + }; + defineProperties(method, { + name: contract.interface.getFunctionName(key), + _contract: contract, + _key: key, + getFragment: getFragment, + estimateGas: estimateGas, + populateTransaction: populateTransaction, + send: send, + staticCall: staticCall, + staticCallResult: staticCallResult + }); + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: ()=>{ + const fragment = contract.interface.getFunction(key); + assert1(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { + key: key } - } - tx.gasLimit = BigNumber.from(fragment.gas).add(intrinsic); - } - if (ro.value) { - const roValue = BigNumber.from(ro.value); - if (!roValue.isZero() && !fragment.payable) { - logger212.throwError("non-payable method cannot override value", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "overrides.value", - value: overrides.value - }); - } - tx.value = roValue; - } - if (ro.customData) { - tx.customData = shallowCopy(ro.customData); - } - if (ro.ccipReadEnabled) { - tx.ccipReadEnabled = !!ro.ccipReadEnabled; - } - delete overrides.nonce; - delete overrides.gasLimit; - delete overrides.gasPrice; - delete overrides.from; - delete overrides.value; - delete overrides.type; - delete overrides.accessList; - delete overrides.maxFeePerGas; - delete overrides.maxPriorityFeePerGas; - delete overrides.customData; - delete overrides.ccipReadEnabled; - const leftovers = Object.keys(overrides).filter((key)=>overrides[key] != null); - if (leftovers.length) { - logger212.throwError(`cannot override ${leftovers.map((l)=>JSON.stringify(l)).join(",")}`, Logger.errors.UNSUPPORTED_OPERATION, { - operation: "overrides", - overrides: leftovers }); + return fragment; } - return tx; }); + return method; } -function buildPopulate(contract, fragment) { - return function(...args) { - return populateTransaction(contract, fragment, args); - }; -} -function buildEstimate(contract, fragment) { - const signerOrProvider = contract.signer || contract.provider; - return function(...args) { - return __awaiter4(this, void 0, void 0, function*() { - if (!signerOrProvider) { - logger212.throwError("estimate require a provider or signer", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "estimateGas" - }); +function buildWrappedEvent(contract, key) { + const getFragment = function(...args) { + const fragment = contract.interface.getEvent(key, args); + assert1(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { + key: key, + args: args } - const tx = yield populateTransaction(contract, fragment, args); - return yield signerOrProvider.estimateGas(tx); }); + return fragment; }; -} -function addContractWait(contract, tx) { - const wait = tx.wait.bind(tx); - tx.wait = (confirmations)=>{ - return wait(confirmations).then((receipt)=>{ - receipt.events = receipt.logs.map((log)=>{ - let event = deepCopy(log); - let parsed = null; - try { - parsed = contract.interface.parseLog(log); - } catch (e) {} - if (parsed) { - event.args = parsed.args; - event.decode = (data, topics)=>{ - return contract.interface.decodeEventLog(parsed.eventFragment, data, topics); - }; - event.event = parsed.name; - event.eventSignature = parsed.signature; - } - event.removeListener = ()=>{ - return contract.provider; - }; - event.getBlock = ()=>{ - return contract.provider.getBlock(receipt.blockHash); - }; - event.getTransaction = ()=>{ - return contract.provider.getTransaction(receipt.transactionHash); - }; - event.getTransactionReceipt = ()=>{ - return Promise.resolve(receipt); - }; - return event; - }); - return receipt; - }); + const method = function(...args) { + return new PreparedTopicFilter(contract, getFragment(...args), args); }; -} -function buildCall(contract, fragment, collapseSimple) { - const signerOrProvider = contract.signer || contract.provider; - return function(...args) { - return __awaiter4(this, void 0, void 0, function*() { - let blockTag = void 0; - if (args.length === fragment.inputs.length + 1 && typeof args[args.length - 1] === "object") { - const overrides = shallowCopy(args.pop()); - if (overrides.blockTag != null) { - blockTag = yield overrides.blockTag; - } - delete overrides.blockTag; - args.push(overrides); - } - if (contract.deployTransaction != null) { - yield contract._deployed(blockTag); - } - const tx = yield populateTransaction(contract, fragment, args); - const result = yield signerOrProvider.call(tx, blockTag); - try { - let value = contract.interface.decodeFunctionResult(fragment, result); - if (collapseSimple && fragment.outputs.length === 1) { - value = value[0]; - } - return value; - } catch (error) { - if (error.code === Logger.errors.CALL_EXCEPTION) { - error.address = contract.address; - error.args = args; - error.transaction = tx; + defineProperties(method, { + name: contract.interface.getEventName(key), + _contract: contract, + _key: key, + getFragment: getFragment + }); + Object.defineProperty(method, "fragment", { + configurable: false, + enumerable: true, + get: ()=>{ + const fragment = contract.interface.getEvent(key); + assert1(fragment, "no matching fragment", "UNSUPPORTED_OPERATION", { + operation: "fragment", + info: { + key: key } - throw error; - } - }); - }; + }); + return fragment; + } + }); + return method; } -function buildSend(contract, fragment) { - return function(...args) { - return __awaiter4(this, void 0, void 0, function*() { - if (!contract.signer) { - logger212.throwError("sending a transaction requires a signer", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "sendTransaction" - }); - } - if (contract.deployTransaction != null) { - yield contract._deployed(); - } - const txRequest = yield populateTransaction(contract, fragment, args); - const tx = yield contract.signer.sendTransaction(txRequest); - addContractWait(contract, tx); - return tx; - }); - }; +const internal = Symbol.for("_ethersInternal_contract"); +const internalValues = new WeakMap; +function setInternal(contract, values) { + internalValues.set(contract[internal], values); } -function buildDefault(contract, fragment, collapseSimple) { - if (fragment.constant) { - return buildCall(contract, fragment, collapseSimple); - } - return buildSend(contract, fragment); +function getInternal(contract) { + return internalValues.get(contract[internal]); } -function getEventTag(filter) { - if (filter.address && (filter.topics == null || filter.topics.length === 0)) { - return "*"; - } - return (filter.address || "*") + "@" + (filter.topics ? filter.topics.map((topic)=>{ - if (Array.isArray(topic)) { - return topic.join("|"); - } - return topic; - }).join(":") : ""); +function isDeferred(value) { + return value && typeof value === "object" && "getTopicFilter" in value && typeof value.getTopicFilter === "function" && value.fragment; } -class RunningEvent { - constructor(tag, filter){ - defineReadOnly(this, "tag", tag); - defineReadOnly(this, "filter", filter); - this._listeners = []; - } - addListener(listener, once) { - this._listeners.push({ - listener, - once - }); - } - removeListener(listener) { - let done = false; - this._listeners = this._listeners.filter((item)=>{ - if (done || item.listener !== listener) { - return true; +async function getSubInfo(contract, event) { + let topics; + let fragment = null; + if (Array.isArray(event)) { + const topicHashify = function(name) { + if (isHexString(name, 32)) { + return name; } - done = true; - return false; - }); - } - removeAllListeners() { - this._listeners = []; - } - listeners() { - return this._listeners.map((i)=>i.listener); - } - listenerCount() { - return this._listeners.length; - } - run(args) { - const listenerCount = this.listenerCount(); - this._listeners = this._listeners.filter((item)=>{ - const argsCopy = args.slice(); - setTimeout(()=>{ - item.listener.apply(this, argsCopy); - }, 0); - return !item.once; - }); - return listenerCount; - } - prepareEvent(event) {} - getEmit(event) { - return [ - event - ]; - } -} -class ErrorRunningEvent extends RunningEvent { - constructor(){ - super("error", null); - } -} -class FragmentRunningEvent extends RunningEvent { - constructor(address2, contractInterface, fragment, topics){ - const filter = { - address: address2 + const fragment = contract.interface.getEvent(name); + assertArgument(fragment, "unknown fragment", "name", name); + return fragment.topicHash; }; - let topic = contractInterface.getEventTopic(fragment); - if (topics) { - if (topic !== topics[0]) { - logger212.throwArgumentError("topic mismatch", "topics", topics); + topics = event.map((e)=>{ + if (e == null) { + return null; } - filter.topics = topics.slice(); + if (Array.isArray(e)) { + return e.map(topicHashify); + } + return topicHashify(e); + }); + } else if (event === "*") { + topics = [ + null + ]; + } else if (typeof event === "string") { + if (isHexString(event, 32)) { + topics = [ + event + ]; } else { - filter.topics = [ - topic + fragment = contract.interface.getEvent(event); + assertArgument(fragment, "unknown fragment", "event", event); + topics = [ + fragment.topicHash ]; } - super(getEventTag(filter), filter); - defineReadOnly(this, "address", address2); - defineReadOnly(this, "interface", contractInterface); - defineReadOnly(this, "fragment", fragment); - } - prepareEvent(event) { - super.prepareEvent(event); - event.event = this.fragment.name; - event.eventSignature = this.fragment.format(); - event.decode = (data, topics)=>{ - return this.interface.decodeEventLog(this.fragment, data, topics); - }; - try { - event.args = this.interface.decodeEventLog(this.fragment, event.data, event.topics); - } catch (error) { - event.args = null; - event.decodeError = error; - } + } else if (isDeferred(event)) { + topics = await event.getTopicFilter(); + } else if ("fragment" in event) { + fragment = event.fragment; + topics = [ + fragment.topicHash + ]; + } else { + assertArgument(false, "unknown event name", "event", event); } - getEmit(event) { - const errors = checkResultErrors(event.args); - if (errors.length) { - throw errors[0].error; + topics = topics.map((t)=>{ + if (t == null) { + return null; } - const args = (event.args || []).slice(); - args.push(event); - return args; - } -} -class WildcardRunningEvent extends RunningEvent { - constructor(address2, contractInterface){ - super("*", { - address: address2 - }); - defineReadOnly(this, "address", address2); - defineReadOnly(this, "interface", contractInterface); - } - prepareEvent(event) { - super.prepareEvent(event); - try { - const parsed = this.interface.parseLog(event); - event.event = parsed.name; - event.eventSignature = parsed.signature; - event.decode = (data, topics)=>{ - return this.interface.decodeEventLog(parsed.eventFragment, data, topics); - }; - event.args = parsed.args; - } catch (error) {} - } -} -class BaseContract { - constructor(addressOrName, contractInterface, signerOrProvider){ - defineReadOnly(this, "interface", getStatic(new.target, "getInterface")(contractInterface)); - if (signerOrProvider == null) { - defineReadOnly(this, "provider", null); - defineReadOnly(this, "signer", null); - } else if (Signer.isSigner(signerOrProvider)) { - defineReadOnly(this, "provider", signerOrProvider.provider || null); - defineReadOnly(this, "signer", signerOrProvider); - } else if (Provider.isProvider(signerOrProvider)) { - defineReadOnly(this, "provider", signerOrProvider); - defineReadOnly(this, "signer", null); - } else { - logger212.throwArgumentError("invalid signer or provider", "signerOrProvider", signerOrProvider); + if (Array.isArray(t)) { + const items = Array.from(new Set(t.map((t)=>t.toLowerCase())).values()); + if (items.length === 1) { + return items[0]; + } + items.sort(); + return items; } - defineReadOnly(this, "callStatic", {}); - defineReadOnly(this, "estimateGas", {}); - defineReadOnly(this, "functions", {}); - defineReadOnly(this, "populateTransaction", {}); - defineReadOnly(this, "filters", {}); - { - const uniqueFilters = {}; - Object.keys(this.interface.events).forEach((eventSignature)=>{ - const event = this.interface.events[eventSignature]; - defineReadOnly(this.filters, eventSignature, (...args)=>{ - return { - address: this.address, - topics: this.interface.encodeFilterTopics(event, args) - }; - }); - if (!uniqueFilters[event.name]) { - uniqueFilters[event.name] = []; - } - uniqueFilters[event.name].push(eventSignature); - }); - Object.keys(uniqueFilters).forEach((name)=>{ - const filters = uniqueFilters[name]; - if (filters.length === 1) { - defineReadOnly(this.filters, name, this.filters[filters[0]]); - } else { - logger212.warn(`Duplicate definition of ${name} (${filters.join(", ")})`); - } - }); + return t.toLowerCase(); + }); + const tag = topics.map((t)=>{ + if (t == null) { + return "null"; } - defineReadOnly(this, "_runningEvents", {}); - defineReadOnly(this, "_wrappedEmits", {}); - if (addressOrName == null) { - logger212.throwArgumentError("invalid contract address or ENS name", "addressOrName", addressOrName); + if (Array.isArray(t)) { + return t.join("|"); } - defineReadOnly(this, "address", addressOrName); - if (this.provider) { - defineReadOnly(this, "resolvedAddress", resolveName(this.provider, addressOrName)); - } else { - try { - defineReadOnly(this, "resolvedAddress", Promise.resolve(getAddress(addressOrName))); - } catch (error) { - logger212.throwError("provider is required to use ENS name as contract address", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "new Contract" + return t; + }).join("&"); + return { + fragment: fragment, + tag: tag, + topics: topics + }; +} +async function hasSub(contract, event) { + const { subs } = getInternal(contract); + return subs.get((await getSubInfo(contract, event)).tag) || null; +} +async function getSub(contract, operation, event) { + const provider = getProvider(contract.runner); + assert1(provider, "contract runner does not support subscribing", "UNSUPPORTED_OPERATION", { + operation: operation + }); + const { fragment, tag, topics } = await getSubInfo(contract, event); + const { addr, subs } = getInternal(contract); + let sub = subs.get(tag); + if (!sub) { + const address = addr ? addr : contract; + const filter = { + address: address, + topics: topics + }; + const listener = (log)=>{ + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = contract.interface.getEvent(log.topics[0]); + } catch (error) {} + } + if (foundFragment) { + const _foundFragment = foundFragment; + const args = fragment ? contract.interface.decodeEventLog(fragment, log.data, log.topics) : []; + emit(contract, event, args, (listener)=>{ + return new ContractEventPayload(contract, listener, event, _foundFragment, log); + }); + } else { + emit(contract, event, [], (listener)=>{ + return new ContractUnknownEventPayload(contract, listener, event, log); }); } - } - this.resolvedAddress.catch((e)=>{}); - const uniqueNames = {}; - const uniqueSignatures = {}; - Object.keys(this.interface.functions).forEach((signature)=>{ - const fragment = this.interface.functions[signature]; - if (uniqueSignatures[signature]) { - logger212.warn(`Duplicate ABI entry for ${JSON.stringify(signature)}`); + }; + let starting = []; + const start = ()=>{ + if (starting.length) { return; } - uniqueSignatures[signature] = true; - { - const name = fragment.name; - if (!uniqueNames[`%${name}`]) { - uniqueNames[`%${name}`] = []; - } - uniqueNames[`%${name}`].push(signature); - } - if (this[signature] == null) { - defineReadOnly(this, signature, buildDefault(this, fragment, true)); - } - if (this.functions[signature] == null) { - defineReadOnly(this.functions, signature, buildDefault(this, fragment, false)); - } - if (this.callStatic[signature] == null) { - defineReadOnly(this.callStatic, signature, buildCall(this, fragment, true)); - } - if (this.populateTransaction[signature] == null) { - defineReadOnly(this.populateTransaction, signature, buildPopulate(this, fragment)); - } - if (this.estimateGas[signature] == null) { - defineReadOnly(this.estimateGas, signature, buildEstimate(this, fragment)); - } - }); - Object.keys(uniqueNames).forEach((name)=>{ - const signatures = uniqueNames[name]; - if (signatures.length > 1) { + starting.push(provider.on(filter, listener)); + }; + const stop = async ()=>{ + if (starting.length == 0) { return; } - name = name.substring(1); - const signature = signatures[0]; - try { - if (this[name] == null) { - defineReadOnly(this, name, this[signature]); - } - } catch (e) {} - if (this.functions[name] == null) { - defineReadOnly(this.functions, name, this.functions[signature]); - } - if (this.callStatic[name] == null) { - defineReadOnly(this.callStatic, name, this.callStatic[signature]); - } - if (this.populateTransaction[name] == null) { - defineReadOnly(this.populateTransaction, name, this.populateTransaction[signature]); - } - if (this.estimateGas[name] == null) { - defineReadOnly(this.estimateGas, name, this.estimateGas[signature]); - } - }); + let started = starting; + starting = []; + await Promise.all(started); + provider.off(filter, listener); + }; + sub = { + tag: tag, + listeners: [], + start: start, + stop: stop + }; + subs.set(tag, sub); } - static getContractAddress(transaction) { - return getContractAddress(transaction); + return sub; +} +let lastEmit = Promise.resolve(); +async function _emit(contract, event, args, payloadFunc) { + await lastEmit; + const sub = await hasSub(contract, event); + if (!sub) { + return false; } - static getInterface(contractInterface) { - if (Interface.isInterface(contractInterface)) { - return contractInterface; + const count = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once })=>{ + const passArgs = Array.from(args); + if (payloadFunc) { + passArgs.push(payloadFunc(once ? null : listener)); } - return new Interface(contractInterface); - } - deployed() { - return this._deployed(); + try { + listener.call(contract, ...passArgs); + } catch (error) {} + return !once; + }); + if (sub.listeners.length === 0) { + sub.stop(); + getInternal(contract).subs.delete(sub.tag); } - _deployed(blockTag) { - if (!this._deployedPromise) { - if (this.deployTransaction) { - this._deployedPromise = this.deployTransaction.wait().then(()=>{ - return this; - }); + return count > 0; +} +async function emit(contract, event, args, payloadFunc) { + try { + await lastEmit; + } catch (error) {} + const resultPromise = _emit(contract, event, args, payloadFunc); + lastEmit = resultPromise; + return await resultPromise; +} +const passProperties = [ + "then" +]; +class BaseContract { + target; + interface; + runner; + filters; + [internal]; + fallback; + constructor(target, abi, runner, _deployTx){ + assertArgument(typeof target === "string" || isAddressable(target), "invalid value for Contract target", "target", target); + if (runner == null) { + runner = null; + } + const iface = Interface.from(abi); + defineProperties(this, { + target: target, + runner: runner, + interface: iface + }); + Object.defineProperty(this, internal, { + value: {} + }); + let addrPromise; + let addr = null; + let deployTx = null; + if (_deployTx) { + const provider = getProvider(runner); + deployTx = new ContractTransactionResponse(this.interface, provider, _deployTx); + } + let subs = new Map; + if (typeof target === "string") { + if (isHexString(target)) { + addr = target; + addrPromise = Promise.resolve(target); } else { - this._deployedPromise = this.provider.getCode(this.address, blockTag).then((code)=>{ - if (code === "0x") { - logger212.throwError("contract not deployed", Logger.errors.UNSUPPORTED_OPERATION, { - contractAddress: this.address, - operation: "getDeployed" + const resolver = getRunner(runner, "resolveName"); + if (!canResolve(resolver)) { + throw makeError("contract runner does not support name resolution", "UNSUPPORTED_OPERATION", { + operation: "resolveName" + }); + } + addrPromise = resolver.resolveName(target).then((addr)=>{ + if (addr == null) { + throw makeError("an ENS name used for a contract target must be correctly configured", "UNCONFIGURED_NAME", { + value: target }); } - return this; + getInternal(this).addr = addr; + return addr; }); } - } - return this._deployedPromise; - } - fallback(overrides) { - if (!this.signer) { - logger212.throwError("sending a transactions require a signer", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "sendTransaction(fallback)" + } else { + addrPromise = target.getAddress().then((addr)=>{ + if (addr == null) { + throw new Error("TODO"); + } + getInternal(this).addr = addr; + return addr; }); } - const tx = shallowCopy(overrides || {}); - [ - "from", - "to" - ].forEach(function(key) { - if (tx[key] == null) { - return; + setInternal(this, { + addrPromise: addrPromise, + addr: addr, + deployTx: deployTx, + subs: subs + }); + const filters = new Proxy({}, { + get: (target, prop, receiver)=>{ + if (typeof prop === "symbol" || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); + } + try { + return this.getEvent(prop); + } catch (error) { + if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; + } + } + return undefined; + }, + has: (target, prop)=>{ + if (passProperties.indexOf(prop) >= 0) { + return Reflect.has(target, prop); + } + return Reflect.has(target, prop) || this.interface.hasEvent(String(prop)); } - logger212.throwError("cannot override " + key, Logger.errors.UNSUPPORTED_OPERATION, { - operation: key - }); }); - tx.to = this.resolvedAddress; - return this.deployed().then(()=>{ - return this.signer.sendTransaction(tx); + defineProperties(this, { + filters: filters }); - } - connect(signerOrProvider) { - if (typeof signerOrProvider === "string") { - signerOrProvider = new VoidSigner(signerOrProvider, this.provider); - } - const contract = new this.constructor(this.address, this.interface, signerOrProvider); - if (this.deployTransaction) { - defineReadOnly(contract, "deployTransaction", this.deployTransaction); - } - return contract; - } - attach(addressOrName) { - return new this.constructor(addressOrName, this.interface, this.signer || this.provider); - } - static isIndexed(value) { - return Indexed.isIndexed(value); - } - _normalizeRunningEvent(runningEvent) { - if (this._runningEvents[runningEvent.tag]) { - return this._runningEvents[runningEvent.tag]; - } - return runningEvent; - } - _getRunningEvent(eventName) { - if (typeof eventName === "string") { - if (eventName === "error") { - return this._normalizeRunningEvent(new ErrorRunningEvent()); - } - if (eventName === "event") { - return this._normalizeRunningEvent(new RunningEvent("event", null)); - } - if (eventName === "*") { - return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface)); - } - const fragment = this.interface.getEvent(eventName); - return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment)); - } - if (eventName.topics && eventName.topics.length > 0) { - try { - const topic = eventName.topics[0]; - if (typeof topic !== "string") { - throw new Error("invalid topic"); + defineProperties(this, { + fallback: iface.receive || iface.fallback ? buildWrappedFallback(this) : null + }); + return new Proxy(this, { + get: (target, prop, receiver)=>{ + if (typeof prop === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.get(target, prop, receiver); } - const fragment = this.interface.getEvent(topic); - return this._normalizeRunningEvent(new FragmentRunningEvent(this.address, this.interface, fragment, eventName.topics)); - } catch (error) {} - const filter = { - address: this.address, - topics: eventName.topics - }; - return this._normalizeRunningEvent(new RunningEvent(getEventTag(filter), filter)); - } - return this._normalizeRunningEvent(new WildcardRunningEvent(this.address, this.interface)); - } - _checkRunningEvents(runningEvent) { - if (runningEvent.listenerCount() === 0) { - delete this._runningEvents[runningEvent.tag]; - const emit = this._wrappedEmits[runningEvent.tag]; - if (emit && runningEvent.filter) { - this.provider.off(runningEvent.filter, emit); - delete this._wrappedEmits[runningEvent.tag]; - } - } - } - _wrapEvent(runningEvent, log, listener) { - const event = deepCopy(log); - event.removeListener = ()=>{ - if (!listener) { - return; - } - runningEvent.removeListener(listener); - this._checkRunningEvents(runningEvent); - }; - event.getBlock = ()=>{ - return this.provider.getBlock(log.blockHash); - }; - event.getTransaction = ()=>{ - return this.provider.getTransaction(log.transactionHash); - }; - event.getTransactionReceipt = ()=>{ - return this.provider.getTransactionReceipt(log.transactionHash); - }; - runningEvent.prepareEvent(event); - return event; - } - _addEventListener(runningEvent, listener, once) { - if (!this.provider) { - logger212.throwError("events require a provider or a signer with a provider", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "once" - }); - } - runningEvent.addListener(listener, once); - this._runningEvents[runningEvent.tag] = runningEvent; - if (!this._wrappedEmits[runningEvent.tag]) { - const wrappedEmit = (log)=>{ - let event = this._wrapEvent(runningEvent, log, listener); - if (event.decodeError == null) { - try { - const args = runningEvent.getEmit(event); - this.emit(runningEvent.filter, ...args); - } catch (error) { - event.decodeError = error.error; + try { + return target.getFunction(prop); + } catch (error) { + if (!isError(error, "INVALID_ARGUMENT") || error.argument !== "key") { + throw error; } } - if (runningEvent.filter != null) { - this.emit("event", event); - } - if (event.decodeError != null) { - this.emit("error", event.decodeError, event); + return undefined; + }, + has: (target, prop)=>{ + if (typeof prop === "symbol" || prop in target || passProperties.indexOf(prop) >= 0) { + return Reflect.has(target, prop); } - }; - this._wrappedEmits[runningEvent.tag] = wrappedEmit; - if (runningEvent.filter != null) { - this.provider.on(runningEvent.filter, wrappedEmit); - } - } - } - queryFilter(event, fromBlockOrBlockhash, toBlock) { - const runningEvent = this._getRunningEvent(event); - const filter = shallowCopy(runningEvent.filter); - if (typeof fromBlockOrBlockhash === "string" && isHexString(fromBlockOrBlockhash, 32)) { - if (toBlock != null) { - logger212.throwArgumentError("cannot specify toBlock with blockhash", "toBlock", toBlock); + return target.interface.hasFunction(prop); } - filter.blockHash = fromBlockOrBlockhash; - } else { - filter.fromBlock = fromBlockOrBlockhash != null ? fromBlockOrBlockhash : 0; - filter.toBlock = toBlock != null ? toBlock : "latest"; - } - return this.provider.getLogs(filter).then((logs)=>{ - return logs.map((log)=>this._wrapEvent(runningEvent, log, null)); }); } - on(event, listener) { - this._addEventListener(this._getRunningEvent(event), listener, false); - return this; - } - once(event, listener) { - this._addEventListener(this._getRunningEvent(event), listener, true); - return this; - } - emit(eventName, ...args) { - if (!this.provider) { - return false; - } - const runningEvent = this._getRunningEvent(eventName); - const result = runningEvent.run(args) > 0; - this._checkRunningEvents(runningEvent); - return result; - } - listenerCount(eventName) { - if (!this.provider) { - return 0; - } - if (eventName == null) { - return Object.keys(this._runningEvents).reduce((accum, key)=>{ - return accum + this._runningEvents[key].listenerCount(); - }, 0); - } - return this._getRunningEvent(eventName).listenerCount(); - } - listeners(eventName) { - if (!this.provider) { - return []; - } - if (eventName == null) { - const result = []; - for(let tag in this._runningEvents){ - this._runningEvents[tag].listeners().forEach((listener)=>{ - result.push(listener); - }); - } - return result; - } - return this._getRunningEvent(eventName).listeners(); - } - removeAllListeners(eventName) { - if (!this.provider) { - return this; + connect(runner) { + return new BaseContract(this.target, this.interface, runner); + } + attach(target) { + return new BaseContract(target, this.interface, this.runner); + } + async getAddress() { + return await getInternal(this).addrPromise; + } + async getDeployedCode() { + const provider = getProvider(this.runner); + assert1(provider, "runner does not support .provider", "UNSUPPORTED_OPERATION", { + operation: "getDeployedCode" + }); + const code = await provider.getCode(await this.getAddress()); + if (code === "0x") { + return null; } - if (eventName == null) { - for(const tag in this._runningEvents){ - const runningEvent2 = this._runningEvents[tag]; - runningEvent2.removeAllListeners(); - this._checkRunningEvents(runningEvent2); - } + return code; + } + async waitForDeployment() { + const deployTx = this.deploymentTransaction(); + if (deployTx) { + await deployTx.wait(); return this; } - const runningEvent = this._getRunningEvent(eventName); - runningEvent.removeAllListeners(); - this._checkRunningEvents(runningEvent); - return this; - } - off(eventName, listener) { - if (!this.provider) { + const code = await this.getDeployedCode(); + if (code != null) { return this; } - const runningEvent = this._getRunningEvent(eventName); - runningEvent.removeListener(listener); - this._checkRunningEvents(runningEvent); - return this; + const provider = getProvider(this.runner); + assert1(provider != null, "contract runner does not support .provider", "UNSUPPORTED_OPERATION", { + operation: "waitForDeployment" + }); + return new Promise((resolve, reject)=>{ + const checkCode = async ()=>{ + try { + const code = await this.getDeployedCode(); + if (code != null) { + return resolve(this); + } + provider.once("block", checkCode); + } catch (error) { + reject(error); + } + }; + checkCode(); + }); } - removeListener(eventName, listener) { - return this.off(eventName, listener); + deploymentTransaction() { + return getInternal(this).deployTx; } -} -class Contract extends BaseContract { -} -class ContractFactory { - constructor(contractInterface, bytecode, signer){ - let bytecodeHex = null; - if (typeof bytecode === "string") { - bytecodeHex = bytecode; - } else if (isBytes(bytecode)) { - bytecodeHex = hexlify(bytecode); - } else if (bytecode && typeof bytecode.object === "string") { - bytecodeHex = bytecode.object; - } else { - bytecodeHex = "!"; + getFunction(key) { + if (typeof key !== "string") { + key = key.format(); } - if (bytecodeHex.substring(0, 2) !== "0x") { - bytecodeHex = "0x" + bytecodeHex; + const func = buildWrappedMethod(this, key); + return func; + } + getEvent(key) { + if (typeof key !== "string") { + key = key.format(); } - if (!isHexString(bytecodeHex) || bytecodeHex.length % 2) { - logger212.throwArgumentError("invalid bytecode", "bytecode", bytecode); + return buildWrappedEvent(this, key); + } + async queryTransaction(hash) { + throw new Error("@TODO"); + } + async queryFilter(event, fromBlock, toBlock) { + if (fromBlock == null) { + fromBlock = 0; } - if (signer && !Signer.isSigner(signer)) { - logger212.throwArgumentError("invalid signer", "signer", signer); + if (toBlock == null) { + toBlock = "latest"; } - defineReadOnly(this, "bytecode", bytecodeHex); - defineReadOnly(this, "interface", getStatic(new.target, "getInterface")(contractInterface)); - defineReadOnly(this, "signer", signer || null); - } - getDeployTransaction(...args) { - let tx = {}; - if (args.length === this.interface.deploy.inputs.length + 1 && typeof args[args.length - 1] === "object") { - tx = shallowCopy(args.pop()); - for(const key in tx){ - if (!allowedTransactionKeys2[key]) { - throw new Error("unknown transaction override " + key); - } + const { addr, addrPromise } = getInternal(this); + const address = addr ? addr : await addrPromise; + const { fragment, topics } = await getSubInfo(this, event); + const filter = { + address: address, + topics: topics, + fromBlock: fromBlock, + toBlock: toBlock + }; + const provider = getProvider(this.runner); + assert1(provider, "contract runner does not have a provider", "UNSUPPORTED_OPERATION", { + operation: "queryFilter" + }); + return (await provider.getLogs(filter)).map((log)=>{ + let foundFragment = fragment; + if (foundFragment == null) { + try { + foundFragment = this.interface.getEvent(log.topics[0]); + } catch (error) {} } - } - [ - "data", - "from", - "to" - ].forEach((key)=>{ - if (tx[key] == null) { - return; + if (foundFragment) { + try { + return new EventLog(log, this.interface, foundFragment); + } catch (error) { + return new UndecodedEventLog(log, error); + } } - logger212.throwError("cannot override " + key, Logger.errors.UNSUPPORTED_OPERATION, { - operation: key - }); + return new Log(log, provider); }); - if (tx.value) { - const value = BigNumber.from(tx.value); - if (!value.isZero() && !this.interface.deploy.payable) { - logger212.throwError("non-payable constructor cannot override value", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "overrides.value", - value: tx.value - }); - } - } - logger212.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor"); - tx.data = hexlify(concat([ - this.bytecode, - this.interface.encodeDeploy(args) - ])); - return tx; } - deploy(...args) { - return __awaiter4(this, void 0, void 0, function*() { - let overrides = {}; - if (args.length === this.interface.deploy.inputs.length + 1) { - overrides = args.pop(); - } - logger212.checkArgumentCount(args.length, this.interface.deploy.inputs.length, " in Contract constructor"); - const params = yield resolveAddresses(this.signer, args, this.interface.deploy.inputs); - params.push(overrides); - const unsignedTx = this.getDeployTransaction(...params); - const tx = yield this.signer.sendTransaction(unsignedTx); - const address2 = getStatic(this.constructor, "getContractAddress")(tx); - const contract = getStatic(this.constructor, "getContract")(address2, this.interface, this.signer); - addContractWait(contract, tx); - defineReadOnly(contract, "deployTransaction", tx); - return contract; + async on(event, listener) { + const sub = await getSub(this, "on", event); + sub.listeners.push({ + listener: listener, + once: false }); + sub.start(); + return this; } - attach(address2) { - return this.constructor.getContract(address2, this.interface, this.signer); + async once(event, listener) { + const sub = await getSub(this, "once", event); + sub.listeners.push({ + listener: listener, + once: true + }); + sub.start(); + return this; } - connect(signer) { - return new this.constructor(this.interface, this.bytecode, signer); + async emit(event, ...args) { + return await emit(this, event, args, null); } - static fromSolidity(compilerOutput, signer) { - if (compilerOutput == null) { - logger212.throwError("missing compiler output", Logger.errors.MISSING_ARGUMENT, { - argument: "compilerOutput" - }); - } - if (typeof compilerOutput === "string") { - compilerOutput = JSON.parse(compilerOutput); + async listenerCount(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return 0; + } + return sub.listeners.length; } - const abi2 = compilerOutput.abi; - let bytecode = null; - if (compilerOutput.bytecode) { - bytecode = compilerOutput.bytecode; - } else if (compilerOutput.evm && compilerOutput.evm.bytecode) { - bytecode = compilerOutput.evm.bytecode; + const { subs } = getInternal(this); + let total = 0; + for (const { listeners } of subs.values()){ + total += listeners.length; } - return new this(abi2, bytecode, signer); - } - static getInterface(contractInterface) { - return Contract.getInterface(contractInterface); + return total; } - static getContractAddress(tx) { - return getContractAddress(tx); - } - static getContract(address2, contractInterface, signer) { - return new Contract(address2, contractInterface, signer); - } -} -class BaseX { - constructor(alphabet){ - defineReadOnly(this, "alphabet", alphabet); - defineReadOnly(this, "base", alphabet.length); - defineReadOnly(this, "_alphabetMap", {}); - defineReadOnly(this, "_leader", alphabet.charAt(0)); - for(let i = 0; i < alphabet.length; i++){ - this._alphabetMap[alphabet.charAt(i)] = i; + async listeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener })=>listener); } + const { subs } = getInternal(this); + let result = []; + for (const { listeners } of subs.values()){ + result = result.concat(listeners.map(({ listener })=>listener)); + } + return result; } - encode(value) { - let source = arrayify(value); - if (source.length === 0) { - return ""; + async off(event, listener) { + const sub = await hasSub(this, event); + if (!sub) { + return this; } - let digits = [ - 0 - ]; - for(let i = 0; i < source.length; ++i){ - let carry = source[i]; - for(let j = 0; j < digits.length; ++j){ - carry += digits[j] << 8; - digits[j] = carry % this.base; - carry = carry / this.base | 0; - } - while(carry > 0){ - digits.push(carry % this.base); - carry = carry / this.base | 0; + if (listener) { + const index = sub.listeners.map(({ listener })=>listener).indexOf(listener); + if (index >= 0) { + sub.listeners.splice(index, 1); } } - let string = ""; - for(let k = 0; source[k] === 0 && k < source.length - 1; ++k){ - string += this._leader; + if (listener == null || sub.listeners.length === 0) { + sub.stop(); + getInternal(this).subs.delete(sub.tag); } - for(let q = digits.length - 1; q >= 0; --q){ - string += this.alphabet[digits[q]]; - } - return string; + return this; } - decode(value) { - if (typeof value !== "string") { - throw new TypeError("Expected String"); - } - let bytes2 = []; - if (value.length === 0) { - return new Uint8Array(bytes2); + async removeAllListeners(event) { + if (event) { + const sub = await hasSub(this, event); + if (!sub) { + return this; + } + sub.stop(); + getInternal(this).subs.delete(sub.tag); + } else { + const { subs } = getInternal(this); + for (const { tag, stop } of subs.values()){ + stop(); + subs.delete(tag); + } } - bytes2.push(0); - for(let i = 0; i < value.length; i++){ - let __byte = this._alphabetMap[value[i]]; - if (__byte === void 0) { - throw new Error("Non-base" + this.base + " character"); - } - let carry = __byte; - for(let j = 0; j < bytes2.length; ++j){ - carry += bytes2[j] * this.base; - bytes2[j] = carry & 255; - carry >>= 8; - } - while(carry > 0){ - bytes2.push(carry & 255); - carry >>= 8; - } - } - for(let k = 0; value[k] === this._leader && k < value.length - 1; ++k){ - bytes2.push(0); - } - return arrayify(new Uint8Array(bytes2.reverse())); - } -} -new BaseX("abcdefghijklmnopqrstuvwxyz234567"); -const Base58 = new BaseX("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"); -var SupportedAlgorithm; -(function(SupportedAlgorithm2) { - SupportedAlgorithm2["sha256"] = "sha256"; - SupportedAlgorithm2["sha512"] = "sha512"; -})(SupportedAlgorithm || (SupportedAlgorithm = {})); -const version15 = "sha2/5.7.0"; -const logger213 = new Logger(version15); -function ripemd1601(data) { - return "0x" + hash_1.ripemd160().update(arrayify(data)).digest("hex"); -} -function sha2561(data) { - return "0x" + hash_1.sha256().update(arrayify(data)).digest("hex"); -} -function sha5121(data) { - return "0x" + hash_1.sha512().update(arrayify(data)).digest("hex"); -} -function computeHmac(algorithm, key, data) { - if (!SupportedAlgorithm[algorithm]) { - logger213.throwError("unsupported algorithm " + algorithm, Logger.errors.UNSUPPORTED_OPERATION, { - operation: "hmac", - algorithm - }); - } - return "0x" + hash_1.hmac(hash_1[algorithm], arrayify(key)).update(arrayify(data)).digest("hex"); -} -function pbkdf2(password, salt, iterations, keylen, hashAlgorithm) { - password = arrayify(password); - salt = arrayify(salt); - let hLen; - let l = 1; - const DK = new Uint8Array(keylen); - const block1 = new Uint8Array(salt.length + 4); - block1.set(salt); - let r; - let T; - for(let i = 1; i <= l; i++){ - block1[salt.length] = i >> 24 & 255; - block1[salt.length + 1] = i >> 16 & 255; - block1[salt.length + 2] = i >> 8 & 255; - block1[salt.length + 3] = i & 255; - let U = arrayify(computeHmac(hashAlgorithm, password, block1)); - if (!hLen) { - hLen = U.length; - T = new Uint8Array(hLen); - l = Math.ceil(keylen / hLen); - r = keylen - (l - 1) * hLen; - } - T.set(U); - for(let j = 1; j < iterations; j++){ - U = arrayify(computeHmac(hashAlgorithm, password, U)); - for(let k = 0; k < hLen; k++)T[k] ^= U[k]; - } - const destPos = (i - 1) * hLen; - const len = i === l ? r : hLen; - DK.set(arrayify(T).slice(0, len), destPos); - } - return hexlify(DK); -} -const version16 = "wordlists/5.7.0"; -const logger214 = new Logger(version16); -class Wordlist { - constructor(locale){ - logger214.checkAbstract(new.target, Wordlist); - defineReadOnly(this, "locale", locale); + return this; } - split(mnemonic) { - return mnemonic.toLowerCase().split(/ +/g); + async addListener(event, listener) { + return await this.on(event, listener); } - join(words2) { - return words2.join(" "); + async removeListener(event, listener) { + return await this.off(event, listener); } - static check(wordlist2) { - const words2 = []; - for(let i = 0; i < 2048; i++){ - const word = wordlist2.getWord(i); - if (i !== wordlist2.getWordIndex(word)) { - return "0x"; + static buildClass(abi) { + class CustomContract extends BaseContract { + constructor(address, runner = null){ + super(address, abi, runner); } - words2.push(word); } - return id(words2.join("\n") + "\n"); + return CustomContract; } - static register(lang, name) { - if (!name) { - name = lang.locale; + static from(target, abi, runner) { + if (runner == null) { + runner = null; } + const contract = new this(target, abi, runner); + return contract; } } -const words = "AbandonAbilityAbleAboutAboveAbsentAbsorbAbstractAbsurdAbuseAccessAccidentAccountAccuseAchieveAcidAcousticAcquireAcrossActActionActorActressActualAdaptAddAddictAddressAdjustAdmitAdultAdvanceAdviceAerobicAffairAffordAfraidAgainAgeAgentAgreeAheadAimAirAirportAisleAlarmAlbumAlcoholAlertAlienAllAlleyAllowAlmostAloneAlphaAlreadyAlsoAlterAlwaysAmateurAmazingAmongAmountAmusedAnalystAnchorAncientAngerAngleAngryAnimalAnkleAnnounceAnnualAnotherAnswerAntennaAntiqueAnxietyAnyApartApologyAppearAppleApproveAprilArchArcticAreaArenaArgueArmArmedArmorArmyAroundArrangeArrestArriveArrowArtArtefactArtistArtworkAskAspectAssaultAssetAssistAssumeAsthmaAthleteAtomAttackAttendAttitudeAttractAuctionAuditAugustAuntAuthorAutoAutumnAverageAvocadoAvoidAwakeAwareAwayAwesomeAwfulAwkwardAxisBabyBachelorBaconBadgeBagBalanceBalconyBallBambooBananaBannerBarBarelyBargainBarrelBaseBasicBasketBattleBeachBeanBeautyBecauseBecomeBeefBeforeBeginBehaveBehindBelieveBelowBeltBenchBenefitBestBetrayBetterBetweenBeyondBicycleBidBikeBindBiologyBirdBirthBitterBlackBladeBlameBlanketBlastBleakBlessBlindBloodBlossomBlouseBlueBlurBlushBoardBoatBodyBoilBombBoneBonusBookBoostBorderBoringBorrowBossBottomBounceBoxBoyBracketBrainBrandBrassBraveBreadBreezeBrickBridgeBriefBrightBringBriskBroccoliBrokenBronzeBroomBrotherBrownBrushBubbleBuddyBudgetBuffaloBuildBulbBulkBulletBundleBunkerBurdenBurgerBurstBusBusinessBusyButterBuyerBuzzCabbageCabinCableCactusCageCakeCallCalmCameraCampCanCanalCancelCandyCannonCanoeCanvasCanyonCapableCapitalCaptainCarCarbonCardCargoCarpetCarryCartCaseCashCasinoCastleCasualCatCatalogCatchCategoryCattleCaughtCauseCautionCaveCeilingCeleryCementCensusCenturyCerealCertainChairChalkChampionChangeChaosChapterChargeChaseChatCheapCheckCheeseChefCherryChestChickenChiefChildChimneyChoiceChooseChronicChuckleChunkChurnCigarCinnamonCircleCitizenCityCivilClaimClapClarifyClawClayCleanClerkCleverClickClientCliffClimbClinicClipClockClogCloseClothCloudClownClubClumpClusterClutchCoachCoastCoconutCodeCoffeeCoilCoinCollectColorColumnCombineComeComfortComicCommonCompanyConcertConductConfirmCongressConnectConsiderControlConvinceCookCoolCopperCopyCoralCoreCornCorrectCostCottonCouchCountryCoupleCourseCousinCoverCoyoteCrackCradleCraftCramCraneCrashCraterCrawlCrazyCreamCreditCreekCrewCricketCrimeCrispCriticCropCrossCrouchCrowdCrucialCruelCruiseCrumbleCrunchCrushCryCrystalCubeCultureCupCupboardCuriousCurrentCurtainCurveCushionCustomCuteCycleDadDamageDampDanceDangerDaringDashDaughterDawnDayDealDebateDebrisDecadeDecemberDecideDeclineDecorateDecreaseDeerDefenseDefineDefyDegreeDelayDeliverDemandDemiseDenialDentistDenyDepartDependDepositDepthDeputyDeriveDescribeDesertDesignDeskDespairDestroyDetailDetectDevelopDeviceDevoteDiagramDialDiamondDiaryDiceDieselDietDifferDigitalDignityDilemmaDinnerDinosaurDirectDirtDisagreeDiscoverDiseaseDishDismissDisorderDisplayDistanceDivertDivideDivorceDizzyDoctorDocumentDogDollDolphinDomainDonateDonkeyDonorDoorDoseDoubleDoveDraftDragonDramaDrasticDrawDreamDressDriftDrillDrinkDripDriveDropDrumDryDuckDumbDuneDuringDustDutchDutyDwarfDynamicEagerEagleEarlyEarnEarthEasilyEastEasyEchoEcologyEconomyEdgeEditEducateEffortEggEightEitherElbowElderElectricElegantElementElephantElevatorEliteElseEmbarkEmbodyEmbraceEmergeEmotionEmployEmpowerEmptyEnableEnactEndEndlessEndorseEnemyEnergyEnforceEngageEngineEnhanceEnjoyEnlistEnoughEnrichEnrollEnsureEnterEntireEntryEnvelopeEpisodeEqualEquipEraEraseErodeErosionErrorEruptEscapeEssayEssenceEstateEternalEthicsEvidenceEvilEvokeEvolveExactExampleExcessExchangeExciteExcludeExcuseExecuteExerciseExhaustExhibitExileExistExitExoticExpandExpectExpireExplainExposeExpressExtendExtraEyeEyebrowFabricFaceFacultyFadeFaintFaithFallFalseFameFamilyFamousFanFancyFantasyFarmFashionFatFatalFatherFatigueFaultFavoriteFeatureFebruaryFederalFeeFeedFeelFemaleFenceFestivalFetchFeverFewFiberFictionFieldFigureFileFilmFilterFinalFindFineFingerFinishFireFirmFirstFiscalFishFitFitnessFixFlagFlameFlashFlatFlavorFleeFlightFlipFloatFlockFloorFlowerFluidFlushFlyFoamFocusFogFoilFoldFollowFoodFootForceForestForgetForkFortuneForumForwardFossilFosterFoundFoxFragileFrameFrequentFreshFriendFringeFrogFrontFrostFrownFrozenFruitFuelFunFunnyFurnaceFuryFutureGadgetGainGalaxyGalleryGameGapGarageGarbageGardenGarlicGarmentGasGaspGateGatherGaugeGazeGeneralGeniusGenreGentleGenuineGestureGhostGiantGiftGiggleGingerGiraffeGirlGiveGladGlanceGlareGlassGlideGlimpseGlobeGloomGloryGloveGlowGlueGoatGoddessGoldGoodGooseGorillaGospelGossipGovernGownGrabGraceGrainGrantGrapeGrassGravityGreatGreenGridGriefGritGroceryGroupGrowGruntGuardGuessGuideGuiltGuitarGunGymHabitHairHalfHammerHamsterHandHappyHarborHardHarshHarvestHatHaveHawkHazardHeadHealthHeartHeavyHedgehogHeightHelloHelmetHelpHenHeroHiddenHighHillHintHipHireHistoryHobbyHockeyHoldHoleHolidayHollowHomeHoneyHoodHopeHornHorrorHorseHospitalHostHotelHourHoverHubHugeHumanHumbleHumorHundredHungryHuntHurdleHurryHurtHusbandHybridIceIconIdeaIdentifyIdleIgnoreIllIllegalIllnessImageImitateImmenseImmuneImpactImposeImproveImpulseInchIncludeIncomeIncreaseIndexIndicateIndoorIndustryInfantInflictInformInhaleInheritInitialInjectInjuryInmateInnerInnocentInputInquiryInsaneInsectInsideInspireInstallIntactInterestIntoInvestInviteInvolveIronIslandIsolateIssueItemIvoryJacketJaguarJarJazzJealousJeansJellyJewelJobJoinJokeJourneyJoyJudgeJuiceJumpJungleJuniorJunkJustKangarooKeenKeepKetchupKeyKickKidKidneyKindKingdomKissKitKitchenKiteKittenKiwiKneeKnifeKnockKnowLabLabelLaborLadderLadyLakeLampLanguageLaptopLargeLaterLatinLaughLaundryLavaLawLawnLawsuitLayerLazyLeaderLeafLearnLeaveLectureLeftLegLegalLegendLeisureLemonLendLengthLensLeopardLessonLetterLevelLiarLibertyLibraryLicenseLifeLiftLightLikeLimbLimitLinkLionLiquidListLittleLiveLizardLoadLoanLobsterLocalLockLogicLonelyLongLoopLotteryLoudLoungeLoveLoyalLuckyLuggageLumberLunarLunchLuxuryLyricsMachineMadMagicMagnetMaidMailMainMajorMakeMammalManManageMandateMangoMansionManualMapleMarbleMarchMarginMarineMarketMarriageMaskMassMasterMatchMaterialMathMatrixMatterMaximumMazeMeadowMeanMeasureMeatMechanicMedalMediaMelodyMeltMemberMemoryMentionMenuMercyMergeMeritMerryMeshMessageMetalMethodMiddleMidnightMilkMillionMimicMindMinimumMinorMinuteMiracleMirrorMiseryMissMistakeMixMixedMixtureMobileModelModifyMomMomentMonitorMonkeyMonsterMonthMoonMoralMoreMorningMosquitoMotherMotionMotorMountainMouseMoveMovieMuchMuffinMuleMultiplyMuscleMuseumMushroomMusicMustMutualMyselfMysteryMythNaiveNameNapkinNarrowNastyNationNatureNearNeckNeedNegativeNeglectNeitherNephewNerveNestNetNetworkNeutralNeverNewsNextNiceNightNobleNoiseNomineeNoodleNormalNorthNoseNotableNoteNothingNoticeNovelNowNuclearNumberNurseNutOakObeyObjectObligeObscureObserveObtainObviousOccurOceanOctoberOdorOffOfferOfficeOftenOilOkayOldOliveOlympicOmitOnceOneOnionOnlineOnlyOpenOperaOpinionOpposeOptionOrangeOrbitOrchardOrderOrdinaryOrganOrientOriginalOrphanOstrichOtherOutdoorOuterOutputOutsideOvalOvenOverOwnOwnerOxygenOysterOzonePactPaddlePagePairPalacePalmPandaPanelPanicPantherPaperParadeParentParkParrotPartyPassPatchPathPatientPatrolPatternPausePavePaymentPeacePeanutPearPeasantPelicanPenPenaltyPencilPeoplePepperPerfectPermitPersonPetPhonePhotoPhrasePhysicalPianoPicnicPicturePiecePigPigeonPillPilotPinkPioneerPipePistolPitchPizzaPlacePlanetPlasticPlatePlayPleasePledgePluckPlugPlungePoemPoetPointPolarPolePolicePondPonyPoolPopularPortionPositionPossiblePostPotatoPotteryPovertyPowderPowerPracticePraisePredictPreferPreparePresentPrettyPreventPricePridePrimaryPrintPriorityPrisonPrivatePrizeProblemProcessProduceProfitProgramProjectPromoteProofPropertyProsperProtectProudProvidePublicPuddingPullPulpPulsePumpkinPunchPupilPuppyPurchasePurityPurposePursePushPutPuzzlePyramidQualityQuantumQuarterQuestionQuickQuitQuizQuoteRabbitRaccoonRaceRackRadarRadioRailRainRaiseRallyRampRanchRandomRangeRapidRareRateRatherRavenRawRazorReadyRealReasonRebelRebuildRecallReceiveRecipeRecordRecycleReduceReflectReformRefuseRegionRegretRegularRejectRelaxReleaseReliefRelyRemainRememberRemindRemoveRenderRenewRentReopenRepairRepeatReplaceReportRequireRescueResembleResistResourceResponseResultRetireRetreatReturnReunionRevealReviewRewardRhythmRibRibbonRiceRichRideRidgeRifleRightRigidRingRiotRippleRiskRitualRivalRiverRoadRoastRobotRobustRocketRomanceRoofRookieRoomRoseRotateRoughRoundRouteRoyalRubberRudeRugRuleRunRunwayRuralSadSaddleSadnessSafeSailSaladSalmonSalonSaltSaluteSameSampleSandSatisfySatoshiSauceSausageSaveSayScaleScanScareScatterSceneSchemeSchoolScienceScissorsScorpionScoutScrapScreenScriptScrubSeaSearchSeasonSeatSecondSecretSectionSecuritySeedSeekSegmentSelectSellSeminarSeniorSenseSentenceSeriesServiceSessionSettleSetupSevenShadowShaftShallowShareShedShellSheriffShieldShiftShineShipShiverShockShoeShootShopShortShoulderShoveShrimpShrugShuffleShySiblingSickSideSiegeSightSignSilentSilkSillySilverSimilarSimpleSinceSingSirenSisterSituateSixSizeSkateSketchSkiSkillSkinSkirtSkullSlabSlamSleepSlenderSliceSlideSlightSlimSloganSlotSlowSlushSmallSmartSmileSmokeSmoothSnackSnakeSnapSniffSnowSoapSoccerSocialSockSodaSoftSolarSoldierSolidSolutionSolveSomeoneSongSoonSorrySortSoulSoundSoupSourceSouthSpaceSpareSpatialSpawnSpeakSpecialSpeedSpellSpendSphereSpiceSpiderSpikeSpinSpiritSplitSpoilSponsorSpoonSportSpotSpraySpreadSpringSpySquareSqueezeSquirrelStableStadiumStaffStageStairsStampStandStartStateStaySteakSteelStemStepStereoStickStillStingStockStomachStoneStoolStoryStoveStrategyStreetStrikeStrongStruggleStudentStuffStumbleStyleSubjectSubmitSubwaySuccessSuchSuddenSufferSugarSuggestSuitSummerSunSunnySunsetSuperSupplySupremeSureSurfaceSurgeSurpriseSurroundSurveySuspectSustainSwallowSwampSwapSwarmSwearSweetSwiftSwimSwingSwitchSwordSymbolSymptomSyrupSystemTableTackleTagTailTalentTalkTankTapeTargetTaskTasteTattooTaxiTeachTeamTellTenTenantTennisTentTermTestTextThankThatThemeThenTheoryThereTheyThingThisThoughtThreeThriveThrowThumbThunderTicketTideTigerTiltTimberTimeTinyTipTiredTissueTitleToastTobaccoTodayToddlerToeTogetherToiletTokenTomatoTomorrowToneTongueTonightToolToothTopTopicToppleTorchTornadoTortoiseTossTotalTouristTowardTowerTownToyTrackTradeTrafficTragicTrainTransferTrapTrashTravelTrayTreatTreeTrendTrialTribeTrickTriggerTrimTripTrophyTroubleTruckTrueTrulyTrumpetTrustTruthTryTubeTuitionTumbleTunaTunnelTurkeyTurnTurtleTwelveTwentyTwiceTwinTwistTwoTypeTypicalUglyUmbrellaUnableUnawareUncleUncoverUnderUndoUnfairUnfoldUnhappyUniformUniqueUnitUniverseUnknownUnlockUntilUnusualUnveilUpdateUpgradeUpholdUponUpperUpsetUrbanUrgeUsageUseUsedUsefulUselessUsualUtilityVacantVacuumVagueValidValleyValveVanVanishVaporVariousVastVaultVehicleVelvetVendorVentureVenueVerbVerifyVersionVeryVesselVeteranViableVibrantViciousVictoryVideoViewVillageVintageViolinVirtualVirusVisaVisitVisualVitalVividVocalVoiceVoidVolcanoVolumeVoteVoyageWageWagonWaitWalkWallWalnutWantWarfareWarmWarriorWashWaspWasteWaterWaveWayWealthWeaponWearWeaselWeatherWebWeddingWeekendWeirdWelcomeWestWetWhaleWhatWheatWheelWhenWhereWhipWhisperWideWidthWifeWildWillWinWindowWineWingWinkWinnerWinterWireWisdomWiseWishWitnessWolfWomanWonderWoodWoolWordWorkWorldWorryWorthWrapWreckWrestleWristWriteWrongYardYearYellowYouYoungYouthZebraZeroZoneZoo"; -let wordlist = null; -function loadWords(lang) { - if (wordlist != null) { - return; - } - wordlist = words.replace(/([A-Z])/g, " $1").toLowerCase().substring(1).split(" "); - if (Wordlist.check(lang) !== "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60") { - wordlist = null; - throw new Error("BIP39 Wordlist for en (English) FAILED"); - } -} -class LangEn extends Wordlist { - constructor(){ - super("en"); - } - getWord(index) { - loadWords(this); - return wordlist[index]; - } - getWordIndex(word) { - loadWords(this); - return wordlist.indexOf(word); - } -} -const langEn = new LangEn(); -Wordlist.register(langEn); -const wordlists = { - en: langEn -}; -const version17 = "hdnode/5.7.0"; -const logger215 = new Logger(version17); -const N = BigNumber.from("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); -const MasterSecret = toUtf8Bytes("Bitcoin seed"); -const HardenedBit = 2147483648; -function getUpperMask(bits) { - return (1 << bits) - 1 << 8 - bits; -} -function getLowerMask(bits) { - return (1 << bits) - 1; -} -function bytes32(value) { - return hexZeroPad(hexlify(value), 32); +function _ContractBase() { + return BaseContract; } -function base58check(data) { - return Base58.encode(concat([ - data, - hexDataSlice(sha2561(sha2561(data)), 0, 4) - ])); -} -function getWordlist(wordlist) { - if (wordlist == null) { - return wordlists["en"]; - } - if (typeof wordlist === "string") { - const words = wordlists[wordlist]; - if (words == null) { - logger215.throwArgumentError("unknown locale", "wordlist", wordlist); - } - return words; - } - return wordlist; +class Contract extends _ContractBase() { } -const _constructorGuard2 = {}; -const defaultPath = "m/44'/60'/0'/0/0"; -class HDNode { - constructor(constructorGuard, privateKey, publicKey, parentFingerprint, chainCode, index, depth, mnemonicOrPath){ - if (constructorGuard !== _constructorGuard2) { - throw new Error("HDNode constructor cannot be called directly"); - } - if (privateKey) { - const signingKey = new SigningKey(privateKey); - defineReadOnly(this, "privateKey", signingKey.privateKey); - defineReadOnly(this, "publicKey", signingKey.compressedPublicKey); - } else { - defineReadOnly(this, "privateKey", null); - defineReadOnly(this, "publicKey", hexlify(publicKey)); - } - defineReadOnly(this, "parentFingerprint", parentFingerprint); - defineReadOnly(this, "fingerprint", hexDataSlice(ripemd1601(sha2561(this.publicKey)), 0, 4)); - defineReadOnly(this, "address", computeAddress(this.publicKey)); - defineReadOnly(this, "chainCode", chainCode); - defineReadOnly(this, "index", index); - defineReadOnly(this, "depth", depth); - if (mnemonicOrPath == null) { - defineReadOnly(this, "mnemonic", null); - defineReadOnly(this, "path", null); - } else if (typeof mnemonicOrPath === "string") { - defineReadOnly(this, "mnemonic", null); - defineReadOnly(this, "path", mnemonicOrPath); +class ContractFactory { + interface; + bytecode; + runner; + constructor(abi, bytecode, runner){ + const iface = Interface.from(abi); + if (bytecode instanceof Uint8Array) { + bytecode = hexlify(getBytes(bytecode)); } else { - defineReadOnly(this, "mnemonic", mnemonicOrPath); - defineReadOnly(this, "path", mnemonicOrPath.path); - } - } - get extendedKey() { - if (this.depth >= 256) { - throw new Error("Depth too large!"); - } - return base58check(concat([ - this.privateKey != null ? "0x0488ADE4" : "0x0488B21E", - hexlify(this.depth), - this.parentFingerprint, - hexZeroPad(hexlify(this.index), 4), - this.chainCode, - this.privateKey != null ? concat([ - "0x00", - this.privateKey - ]) : this.publicKey - ])); - } - neuter() { - return new HDNode(_constructorGuard2, null, this.publicKey, this.parentFingerprint, this.chainCode, this.index, this.depth, this.path); - } - _derive(index) { - if (index > 4294967295) { - throw new Error("invalid index - " + String(index)); - } - let path = this.path; - if (path) { - path += "/" + (index & ~HardenedBit); - } - const data = new Uint8Array(37); - if (index & 2147483648) { - if (!this.privateKey) { - throw new Error("cannot derive child of neutered node"); - } - data.set(arrayify(this.privateKey), 1); - if (path) { - path += "'"; + if (typeof bytecode === "object") { + bytecode = bytecode.object; } - } else { - data.set(arrayify(this.publicKey)); - } - for(let i = 24; i >= 0; i -= 8){ - data[33 + (i >> 3)] = index >> 24 - i & 255; - } - const I = arrayify(computeHmac(SupportedAlgorithm.sha512, this.chainCode, data)); - const IL = I.slice(0, 32); - const IR = I.slice(32); - let ki = null; - let Ki = null; - if (this.privateKey) { - ki = bytes32(BigNumber.from(IL).add(this.privateKey).mod(N)); - } else { - const ek = new SigningKey(hexlify(IL)); - Ki = ek._addPoint(this.publicKey); - } - let mnemonicOrPath = path; - const srcMnemonic = this.mnemonic; - if (srcMnemonic) { - mnemonicOrPath = Object.freeze({ - phrase: srcMnemonic.phrase, - path, - locale: srcMnemonic.locale || "en" - }); - } - return new HDNode(_constructorGuard2, ki, Ki, this.fingerprint, bytes32(IR), index, this.depth + 1, mnemonicOrPath); - } - derivePath(path) { - const components = path.split("/"); - if (components.length === 0 || components[0] === "m" && this.depth !== 0) { - throw new Error("invalid path - " + path); - } - if (components[0] === "m") { - components.shift(); - } - let result = this; - for(let i = 0; i < components.length; i++){ - const component = components[i]; - if (component.match(/^[0-9]+'$/)) { - const index = parseInt(component.substring(0, component.length - 1)); - if (index >= 2147483648) { - throw new Error("invalid path index - " + component); - } - result = result._derive(HardenedBit + index); - } else if (component.match(/^[0-9]+$/)) { - const index = parseInt(component); - if (index >= 2147483648) { - throw new Error("invalid path index - " + component); - } - result = result._derive(index); - } else { - throw new Error("invalid path component - " + component); + if (!bytecode.startsWith("0x")) { + bytecode = "0x" + bytecode; } + bytecode = hexlify(getBytes(bytecode)); } - return result; - } - static _fromSeed(seed, mnemonic) { - const seedArray = arrayify(seed); - if (seedArray.length < 16 || seedArray.length > 64) { - throw new Error("invalid seed"); - } - const I = arrayify(computeHmac(SupportedAlgorithm.sha512, MasterSecret, seedArray)); - return new HDNode(_constructorGuard2, bytes32(I.slice(0, 32)), null, "0x00000000", bytes32(I.slice(32)), 0, 0, mnemonic); - } - static fromMnemonic(mnemonic, password, wordlist) { - wordlist = getWordlist(wordlist); - mnemonic = entropyToMnemonic(mnemonicToEntropy(mnemonic, wordlist), wordlist); - return HDNode._fromSeed(mnemonicToSeed(mnemonic, password), { - phrase: mnemonic, - path: "m", - locale: wordlist.locale + defineProperties(this, { + bytecode: bytecode, + interface: iface, + runner: runner || null }); } - static fromSeed(seed) { - return HDNode._fromSeed(seed, null); - } - static fromExtendedKey(extendedKey) { - const bytes2 = Base58.decode(extendedKey); - if (bytes2.length !== 82 || base58check(bytes2.slice(0, 78)) !== extendedKey) { - logger215.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]"); - } - const depth = bytes2[4]; - const parentFingerprint = hexlify(bytes2.slice(5, 9)); - const index = parseInt(hexlify(bytes2.slice(9, 13)).substring(2), 16); - const chainCode = hexlify(bytes2.slice(13, 45)); - const key = bytes2.slice(45, 78); - switch(hexlify(bytes2.slice(0, 4))){ - case "0x0488b21e": - case "0x043587cf": - return new HDNode(_constructorGuard2, null, hexlify(key), parentFingerprint, chainCode, index, depth, null); - case "0x0488ade4": - case "0x04358394 ": - if (key[0] !== 0) { - break; - } - return new HDNode(_constructorGuard2, hexlify(key.slice(1)), null, parentFingerprint, chainCode, index, depth, null); - } - return logger215.throwArgumentError("invalid extended key", "extendedKey", "[REDACTED]"); - } -} -function mnemonicToSeed(mnemonic, password) { - if (!password) { - password = ""; - } - const salt = toUtf8Bytes("mnemonic" + password, UnicodeNormalizationForm.NFKD); - return pbkdf2(toUtf8Bytes(mnemonic, UnicodeNormalizationForm.NFKD), salt, 2048, 64, "sha512"); -} -function mnemonicToEntropy(mnemonic, wordlist) { - wordlist = getWordlist(wordlist); - logger215.checkNormalize(); - const words = wordlist.split(mnemonic); - if (words.length % 3 !== 0) { - throw new Error("invalid mnemonic"); + attach(target) { + return new BaseContract(target, this.interface, this.runner); } - const entropy = arrayify(new Uint8Array(Math.ceil(11 * words.length / 8))); - let offset = 0; - for(let i = 0; i < words.length; i++){ - let index = wordlist.getWordIndex(words[i].normalize("NFKD")); - if (index === -1) { - throw new Error("invalid mnemonic"); + async getDeployTransaction(...args) { + let overrides = {}; + const fragment = this.interface.deploy; + if (fragment.inputs.length + 1 === args.length) { + overrides = await copyOverrides(args.pop()); } - for(let bit = 0; bit < 11; bit++){ - if (index & 1 << 10 - bit) { - entropy[offset >> 3] |= 1 << 7 - offset % 8; - } - offset++; + if (fragment.inputs.length !== args.length) { + throw new Error("incorrect number of arguments to constructor"); } + const resolvedArgs = await resolveArgs(this.runner, fragment.inputs, args); + const data = concat([ + this.bytecode, + this.interface.encodeDeploy(resolvedArgs) + ]); + return Object.assign({}, overrides, { + data: data + }); } - const entropyBits = 32 * words.length / 3; - const checksumBits = words.length / 3; - const checksumMask = getUpperMask(checksumBits); - const checksum = arrayify(sha2561(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; - if (checksum !== (entropy[entropy.length - 1] & checksumMask)) { - throw new Error("invalid checksum"); + async deploy(...args) { + const tx = await this.getDeployTransaction(...args); + assert1(this.runner && typeof this.runner.sendTransaction === "function", "factory runner does not support sending transactions", "UNSUPPORTED_OPERATION", { + operation: "sendTransaction" + }); + const sentTx = await this.runner.sendTransaction(tx); + const address = getCreateAddress(sentTx); + return new BaseContract(address, this.interface, this.runner, sentTx); } - return hexlify(entropy.slice(0, entropyBits / 8)); -} -function entropyToMnemonic(entropy, wordlist) { - wordlist = getWordlist(wordlist); - entropy = arrayify(entropy); - if (entropy.length % 4 !== 0 || entropy.length < 16 || entropy.length > 32) { - throw new Error("invalid entropy"); + connect(runner) { + return new ContractFactory(this.interface, this.bytecode, runner); } - const indices = [ - 0 - ]; - let remainingBits = 11; - for(let i = 0; i < entropy.length; i++){ - if (remainingBits > 8) { - indices[indices.length - 1] <<= 8; - indices[indices.length - 1] |= entropy[i]; - remainingBits -= 8; - } else { - indices[indices.length - 1] <<= remainingBits; - indices[indices.length - 1] |= entropy[i] >> 8 - remainingBits; - indices.push(entropy[i] & getLowerMask(8 - remainingBits)); - remainingBits += 3; + static fromSolidity(output, runner) { + assertArgument(output != null, "bad compiler output", "output", output); + if (typeof output === "string") { + output = JSON.parse(output); } + const abi = output.abi; + let bytecode = ""; + if (output.bytecode) { + bytecode = output.bytecode; + } else if (output.evm && output.evm.bytecode) { + bytecode = output.evm.bytecode; + } + return new this(abi, bytecode, runner); } - const checksumBits = entropy.length / 4; - const checksum = arrayify(sha2561(entropy))[0] & getUpperMask(checksumBits); - indices[indices.length - 1] <<= checksumBits; - indices[indices.length - 1] |= checksum >> 8 - checksumBits; - return wordlist.join(indices.map((index)=>wordlist.getWord(index))); -} -function isValidMnemonic(mnemonic, wordlist) { - try { - mnemonicToEntropy(mnemonic, wordlist); - return true; - } catch (error) {} - return false; } -function getAccountPath(index) { - if (typeof index !== "number" || index < 0 || index >= 2147483648 || index % 1) { - logger215.throwArgumentError("invalid account index", "index", index); +function getIpfsLink(link) { + if (link.match(/^ipfs:\/\/ipfs\//i)) { + link = link.substring(12); + } else if (link.match(/^ipfs:\/\//i)) { + link = link.substring(7); + } else { + assertArgument(false, "unsupported IPFS format", "link", link); } - return `m/44'/60'/${index}'/0/0`; + return `https:/\/gateway.ipfs.io/ipfs/${link}`; } -var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; -const version18 = "random/5.7.0"; -const logger216 = new Logger(version18); -function getGlobal() { - if (typeof self !== "undefined") { - return self; - } - if (typeof window !== "undefined") { - return window; - } - if (typeof global$1 !== "undefined") { - return global$1; +class MulticoinProviderPlugin { + name; + constructor(name){ + defineProperties(this, { + name: name + }); } - throw new Error("unable to locate global object"); -} -const anyGlobal = getGlobal(); -let crypto1 = anyGlobal.crypto || anyGlobal.msCrypto; -if (!crypto1 || !crypto1.getRandomValues) { - logger216.warn("WARNING: Missing strong random number source"); - crypto1 = { - getRandomValues: function(buffer) { - return logger216.throwError("no secure random source avaialble", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "crypto.getRandomValues" - }); - } - }; -} -function randomBytes(length) { - if (length <= 0 || length > 1024 || length % 1 || length != length) { - logger216.throwArgumentError("invalid length", "length", length); + connect(proivder) { + return this; } - const result = new Uint8Array(length); - crypto1.getRandomValues(result); - return arrayify(result); -} -function shuffled(array) { - array = array.slice(); - for(let i = array.length - 1; i > 0; i--){ - const j = Math.floor(Math.random() * (i + 1)); - const tmp = array[i]; - array[i] = array[j]; - array[j] = tmp; + supportsCoinType(coinType) { + return false; } - return array; -} -function createCommonjsModule5(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function(path, base) { - return commonjsRequire5(path, base === void 0 || base === null ? module.path : base); - } - }, fn(module, module.exports), module.exports; -} -function commonjsRequire5() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); -} -var aesJs = createCommonjsModule5(function(module, exports) { - (function(root) { - function checkInt(value) { - return parseInt(value) === value; - } - function checkInts(arrayish) { - if (!checkInt(arrayish.length)) { - return false; - } - for(var i = 0; i < arrayish.length; i++){ - if (!checkInt(arrayish[i]) || arrayish[i] < 0 || arrayish[i] > 255) { - return false; - } - } - return true; - } - function coerceArray(arg, copy) { - if (arg.buffer && ArrayBuffer.isView(arg) && arg.name === "Uint8Array") { - if (copy) { - if (arg.slice) { - arg = arg.slice(); - } else { - arg = Array.prototype.slice.call(arg); + async encodeAddress(coinType, address) { + throw new Error("unsupported coin"); + } + async decodeAddress(coinType, data) { + throw new Error("unsupported coin"); + } +} +const matcherIpfs = new RegExp("^(ipfs)://(.*)$", "i"); +const matchers = [ + new RegExp("^(https)://(.*)$", "i"), + new RegExp("^(data):(.*)$", "i"), + matcherIpfs, + new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i") +]; +class EnsResolver { + provider; + address; + name; + #supports2544; + #resolver; + constructor(provider, address, name){ + defineProperties(this, { + provider: provider, + address: address, + name: name + }); + this.#supports2544 = null; + this.#resolver = new Contract(address, [ + "function supportsInterface(bytes4) view returns (bool)", + "function resolve(bytes, bytes) view returns (bytes)", + "function addr(bytes32) view returns (address)", + "function addr(bytes32, uint) view returns (bytes)", + "function text(bytes32, string) view returns (string)", + "function contenthash(bytes32) view returns (bytes)" + ], provider); + } + async supportsWildcard() { + if (this.#supports2544 == null) { + this.#supports2544 = (async ()=>{ + try { + return await this.#resolver.supportsInterface("0x9061b923"); + } catch (error) { + if (isError(error, "CALL_EXCEPTION")) { + return false; } + this.#supports2544 = null; + throw error; } - return arg; - } - if (Array.isArray(arg)) { - if (!checkInts(arg)) { - throw new Error("Array contains invalid value: " + arg); + })(); + } + return await this.#supports2544; + } + async #fetch(funcName, params) { + params = (params || []).slice(); + const iface = this.#resolver.interface; + params.unshift(namehash(this.name)); + let fragment = null; + if (await this.supportsWildcard()) { + fragment = iface.getFunction(funcName); + assert1(fragment, "missing fragment", "UNKNOWN_ERROR", { + info: { + funcName: funcName } - return new Uint8Array(arg); + }); + params = [ + dnsEncode(this.name, 255), + iface.encodeFunctionData(fragment, params) + ]; + funcName = "resolve(bytes,bytes)"; + } + params.push({ + enableCcipRead: true + }); + try { + const result = await this.#resolver[funcName](...params); + if (fragment) { + return iface.decodeFunctionResult(fragment, result)[0]; } - if (checkInt(arg.length) && checkInts(arg)) { - return new Uint8Array(arg); + return result; + } catch (error) { + if (!isError(error, "CALL_EXCEPTION")) { + throw error; } - throw new Error("unsupported array-like object"); } - function createArray(length) { - return new Uint8Array(length); + return null; + } + async getAddress(coinType) { + if (coinType == null) { + coinType = 60; } - function copyArray(sourceArray, targetArray, targetStart, sourceStart, sourceEnd) { - if (sourceStart != null || sourceEnd != null) { - if (sourceArray.slice) { - sourceArray = sourceArray.slice(sourceStart, sourceEnd); - } else { - sourceArray = Array.prototype.slice.call(sourceArray, sourceStart, sourceEnd); - } - } - targetArray.set(sourceArray, targetStart); - } - var convertUtf8 = function() { - function toBytes(text) { - var result = [], i = 0; - text = encodeURI(text); - while(i < text.length){ - var c = text.charCodeAt(i++); - if (c === 37) { - result.push(parseInt(text.substr(i, 2), 16)); - i += 2; - } else { - result.push(c); - } - } - return coerceArray(result); - } - function fromBytes(bytes) { - var result = [], i = 0; - while(i < bytes.length){ - var c = bytes[i]; - if (c < 128) { - result.push(String.fromCharCode(c)); - i++; - } else if (c > 191 && c < 224) { - result.push(String.fromCharCode((c & 31) << 6 | bytes[i + 1] & 63)); - i += 2; - } else { - result.push(String.fromCharCode((c & 15) << 12 | (bytes[i + 1] & 63) << 6 | bytes[i + 2] & 63)); - i += 3; - } - } - return result.join(""); - } - return { - toBytes, - fromBytes - }; - }(); - var convertHex = function() { - function toBytes(text) { - var result = []; - for(var i = 0; i < text.length; i += 2){ - result.push(parseInt(text.substr(i, 2), 16)); + if (coinType === 60) { + try { + const result = await this.#fetch("addr(bytes32)"); + if (result == null || result === ZeroAddress) { + return null; } return result; - } - var Hex = "0123456789abcdef"; - function fromBytes(bytes) { - var result = []; - for(var i = 0; i < bytes.length; i++){ - var v = bytes[i]; - result.push(Hex[(v & 240) >> 4] + Hex[v & 15]); + } catch (error) { + if (isError(error, "CALL_EXCEPTION")) { + return null; } - return result.join(""); - } - return { - toBytes, - fromBytes - }; - }(); - var numberOfRounds = { - 16: 10, - 24: 12, - 32: 14 - }; - var rcon = [ - 1, - 2, - 4, - 8, - 16, - 32, - 64, - 128, - 27, - 54, - 108, - 216, - 171, - 77, - 154, - 47, - 94, - 188, - 99, - 198, - 151, - 53, - 106, - 212, - 179, - 125, - 250, - 239, - 197, - 145 - ]; - var S = [ - 99, - 124, - 119, - 123, - 242, - 107, - 111, - 197, - 48, - 1, - 103, - 43, - 254, - 215, - 171, - 118, - 202, - 130, - 201, - 125, - 250, - 89, - 71, - 240, - 173, - 212, - 162, - 175, - 156, - 164, - 114, - 192, - 183, - 253, - 147, - 38, - 54, - 63, - 247, - 204, - 52, - 165, - 229, - 241, - 113, - 216, - 49, - 21, - 4, - 199, - 35, - 195, - 24, - 150, - 5, - 154, - 7, - 18, - 128, - 226, - 235, - 39, - 178, - 117, - 9, - 131, - 44, - 26, - 27, - 110, - 90, - 160, - 82, - 59, - 214, - 179, - 41, - 227, - 47, - 132, - 83, - 209, - 0, - 237, - 32, - 252, - 177, - 91, - 106, - 203, - 190, - 57, - 74, - 76, - 88, - 207, - 208, - 239, - 170, - 251, - 67, - 77, - 51, - 133, - 69, - 249, - 2, - 127, - 80, - 60, - 159, - 168, - 81, - 163, - 64, - 143, - 146, - 157, - 56, - 245, - 188, - 182, - 218, - 33, - 16, - 255, - 243, - 210, - 205, - 12, - 19, - 236, - 95, - 151, - 68, - 23, - 196, - 167, - 126, - 61, - 100, - 93, - 25, - 115, - 96, - 129, - 79, - 220, - 34, - 42, - 144, - 136, - 70, - 238, - 184, - 20, - 222, - 94, - 11, - 219, - 224, - 50, - 58, - 10, - 73, - 6, - 36, - 92, - 194, - 211, - 172, - 98, - 145, - 149, - 228, - 121, - 231, - 200, - 55, - 109, - 141, - 213, - 78, - 169, - 108, - 86, - 244, - 234, - 101, - 122, - 174, - 8, - 186, - 120, - 37, - 46, - 28, - 166, - 180, - 198, - 232, - 221, - 116, - 31, - 75, - 189, - 139, - 138, - 112, - 62, - 181, - 102, - 72, - 3, - 246, - 14, - 97, - 53, - 87, - 185, - 134, - 193, - 29, - 158, - 225, - 248, - 152, - 17, - 105, - 217, - 142, - 148, - 155, - 30, - 135, - 233, - 206, - 85, - 40, - 223, - 140, - 161, - 137, - 13, - 191, - 230, - 66, - 104, - 65, - 153, - 45, - 15, - 176, - 84, - 187, - 22 - ]; - var Si = [ - 82, - 9, - 106, - 213, - 48, - 54, - 165, - 56, - 191, - 64, - 163, - 158, - 129, - 243, - 215, - 251, - 124, - 227, - 57, - 130, - 155, - 47, - 255, - 135, - 52, - 142, - 67, - 68, - 196, - 222, - 233, - 203, - 84, - 123, - 148, - 50, - 166, - 194, - 35, - 61, - 238, - 76, - 149, - 11, - 66, - 250, - 195, - 78, - 8, - 46, - 161, - 102, - 40, - 217, - 36, - 178, - 118, - 91, - 162, - 73, - 109, - 139, - 209, - 37, - 114, - 248, - 246, - 100, - 134, - 104, - 152, - 22, - 212, - 164, - 92, - 204, - 93, - 101, - 182, - 146, - 108, - 112, - 72, - 80, - 253, - 237, - 185, - 218, - 94, - 21, - 70, - 87, - 167, - 141, - 157, - 132, - 144, - 216, - 171, - 0, - 140, - 188, - 211, - 10, - 247, - 228, - 88, - 5, - 184, - 179, - 69, - 6, - 208, - 44, - 30, - 143, - 202, - 63, - 15, - 2, - 193, - 175, - 189, - 3, - 1, - 19, - 138, - 107, - 58, - 145, - 17, - 65, - 79, - 103, - 220, - 234, - 151, - 242, - 207, - 206, - 240, - 180, - 230, - 115, - 150, - 172, - 116, - 34, - 231, - 173, - 53, - 133, - 226, - 249, - 55, - 232, - 28, - 117, - 223, - 110, - 71, - 241, - 26, - 113, - 29, - 41, - 197, - 137, - 111, - 183, - 98, - 14, - 170, - 24, - 190, - 27, - 252, - 86, - 62, - 75, - 198, - 210, - 121, - 32, - 154, - 219, - 192, - 254, - 120, - 205, - 90, - 244, - 31, - 221, - 168, - 51, - 136, - 7, - 199, - 49, - 177, - 18, - 16, - 89, - 39, - 128, - 236, - 95, - 96, - 81, - 127, - 169, - 25, - 181, - 74, - 13, - 45, - 229, - 122, - 159, - 147, - 201, - 156, - 239, - 160, - 224, - 59, - 77, - 174, - 42, - 245, - 176, - 200, - 235, - 187, - 60, - 131, - 83, - 153, - 97, - 23, - 43, - 4, - 126, - 186, - 119, - 214, - 38, - 225, - 105, - 20, - 99, - 85, - 33, - 12, - 125 - ]; - var T1 = [ - 3328402341, - 4168907908, - 4000806809, - 4135287693, - 4294111757, - 3597364157, - 3731845041, - 2445657428, - 1613770832, - 33620227, - 3462883241, - 1445669757, - 3892248089, - 3050821474, - 1303096294, - 3967186586, - 2412431941, - 528646813, - 2311702848, - 4202528135, - 4026202645, - 2992200171, - 2387036105, - 4226871307, - 1101901292, - 3017069671, - 1604494077, - 1169141738, - 597466303, - 1403299063, - 3832705686, - 2613100635, - 1974974402, - 3791519004, - 1033081774, - 1277568618, - 1815492186, - 2118074177, - 4126668546, - 2211236943, - 1748251740, - 1369810420, - 3521504564, - 4193382664, - 3799085459, - 2883115123, - 1647391059, - 706024767, - 134480908, - 2512897874, - 1176707941, - 2646852446, - 806885416, - 932615841, - 168101135, - 798661301, - 235341577, - 605164086, - 461406363, - 3756188221, - 3454790438, - 1311188841, - 2142417613, - 3933566367, - 302582043, - 495158174, - 1479289972, - 874125870, - 907746093, - 3698224818, - 3025820398, - 1537253627, - 2756858614, - 1983593293, - 3084310113, - 2108928974, - 1378429307, - 3722699582, - 1580150641, - 327451799, - 2790478837, - 3117535592, - 0, - 3253595436, - 1075847264, - 3825007647, - 2041688520, - 3059440621, - 3563743934, - 2378943302, - 1740553945, - 1916352843, - 2487896798, - 2555137236, - 2958579944, - 2244988746, - 3151024235, - 3320835882, - 1336584933, - 3992714006, - 2252555205, - 2588757463, - 1714631509, - 293963156, - 2319795663, - 3925473552, - 67240454, - 4269768577, - 2689618160, - 2017213508, - 631218106, - 1269344483, - 2723238387, - 1571005438, - 2151694528, - 93294474, - 1066570413, - 563977660, - 1882732616, - 4059428100, - 1673313503, - 2008463041, - 2950355573, - 1109467491, - 537923632, - 3858759450, - 4260623118, - 3218264685, - 2177748300, - 403442708, - 638784309, - 3287084079, - 3193921505, - 899127202, - 2286175436, - 773265209, - 2479146071, - 1437050866, - 4236148354, - 2050833735, - 3362022572, - 3126681063, - 840505643, - 3866325909, - 3227541664, - 427917720, - 2655997905, - 2749160575, - 1143087718, - 1412049534, - 999329963, - 193497219, - 2353415882, - 3354324521, - 1807268051, - 672404540, - 2816401017, - 3160301282, - 369822493, - 2916866934, - 3688947771, - 1681011286, - 1949973070, - 336202270, - 2454276571, - 201721354, - 1210328172, - 3093060836, - 2680341085, - 3184776046, - 1135389935, - 3294782118, - 965841320, - 831886756, - 3554993207, - 4068047243, - 3588745010, - 2345191491, - 1849112409, - 3664604599, - 26054028, - 2983581028, - 2622377682, - 1235855840, - 3630984372, - 2891339514, - 4092916743, - 3488279077, - 3395642799, - 4101667470, - 1202630377, - 268961816, - 1874508501, - 4034427016, - 1243948399, - 1546530418, - 941366308, - 1470539505, - 1941222599, - 2546386513, - 3421038627, - 2715671932, - 3899946140, - 1042226977, - 2521517021, - 1639824860, - 227249030, - 260737669, - 3765465232, - 2084453954, - 1907733956, - 3429263018, - 2420656344, - 100860677, - 4160157185, - 470683154, - 3261161891, - 1781871967, - 2924959737, - 1773779408, - 394692241, - 2579611992, - 974986535, - 664706745, - 3655459128, - 3958962195, - 731420851, - 571543859, - 3530123707, - 2849626480, - 126783113, - 865375399, - 765172662, - 1008606754, - 361203602, - 3387549984, - 2278477385, - 2857719295, - 1344809080, - 2782912378, - 59542671, - 1503764984, - 160008576, - 437062935, - 1707065306, - 3622233649, - 2218934982, - 3496503480, - 2185314755, - 697932208, - 1512910199, - 504303377, - 2075177163, - 2824099068, - 1841019862, - 739644986 - ]; - var T2 = [ - 2781242211, - 2230877308, - 2582542199, - 2381740923, - 234877682, - 3184946027, - 2984144751, - 1418839493, - 1348481072, - 50462977, - 2848876391, - 2102799147, - 434634494, - 1656084439, - 3863849899, - 2599188086, - 1167051466, - 2636087938, - 1082771913, - 2281340285, - 368048890, - 3954334041, - 3381544775, - 201060592, - 3963727277, - 1739838676, - 4250903202, - 3930435503, - 3206782108, - 4149453988, - 2531553906, - 1536934080, - 3262494647, - 484572669, - 2923271059, - 1783375398, - 1517041206, - 1098792767, - 49674231, - 1334037708, - 1550332980, - 4098991525, - 886171109, - 150598129, - 2481090929, - 1940642008, - 1398944049, - 1059722517, - 201851908, - 1385547719, - 1699095331, - 1587397571, - 674240536, - 2704774806, - 252314885, - 3039795866, - 151914247, - 908333586, - 2602270848, - 1038082786, - 651029483, - 1766729511, - 3447698098, - 2682942837, - 454166793, - 2652734339, - 1951935532, - 775166490, - 758520603, - 3000790638, - 4004797018, - 4217086112, - 4137964114, - 1299594043, - 1639438038, - 3464344499, - 2068982057, - 1054729187, - 1901997871, - 2534638724, - 4121318227, - 1757008337, - 0, - 750906861, - 1614815264, - 535035132, - 3363418545, - 3988151131, - 3201591914, - 1183697867, - 3647454910, - 1265776953, - 3734260298, - 3566750796, - 3903871064, - 1250283471, - 1807470800, - 717615087, - 3847203498, - 384695291, - 3313910595, - 3617213773, - 1432761139, - 2484176261, - 3481945413, - 283769337, - 100925954, - 2180939647, - 4037038160, - 1148730428, - 3123027871, - 3813386408, - 4087501137, - 4267549603, - 3229630528, - 2315620239, - 2906624658, - 3156319645, - 1215313976, - 82966005, - 3747855548, - 3245848246, - 1974459098, - 1665278241, - 807407632, - 451280895, - 251524083, - 1841287890, - 1283575245, - 337120268, - 891687699, - 801369324, - 3787349855, - 2721421207, - 3431482436, - 959321879, - 1469301956, - 4065699751, - 2197585534, - 1199193405, - 2898814052, - 3887750493, - 724703513, - 2514908019, - 2696962144, - 2551808385, - 3516813135, - 2141445340, - 1715741218, - 2119445034, - 2872807568, - 2198571144, - 3398190662, - 700968686, - 3547052216, - 1009259540, - 2041044702, - 3803995742, - 487983883, - 1991105499, - 1004265696, - 1449407026, - 1316239930, - 504629770, - 3683797321, - 168560134, - 1816667172, - 3837287516, - 1570751170, - 1857934291, - 4014189740, - 2797888098, - 2822345105, - 2754712981, - 936633572, - 2347923833, - 852879335, - 1133234376, - 1500395319, - 3084545389, - 2348912013, - 1689376213, - 3533459022, - 3762923945, - 3034082412, - 4205598294, - 133428468, - 634383082, - 2949277029, - 2398386810, - 3913789102, - 403703816, - 3580869306, - 2297460856, - 1867130149, - 1918643758, - 607656988, - 4049053350, - 3346248884, - 1368901318, - 600565992, - 2090982877, - 2632479860, - 557719327, - 3717614411, - 3697393085, - 2249034635, - 2232388234, - 2430627952, - 1115438654, - 3295786421, - 2865522278, - 3633334344, - 84280067, - 33027830, - 303828494, - 2747425121, - 1600795957, - 4188952407, - 3496589753, - 2434238086, - 1486471617, - 658119965, - 3106381470, - 953803233, - 334231800, - 3005978776, - 857870609, - 3151128937, - 1890179545, - 2298973838, - 2805175444, - 3056442267, - 574365214, - 2450884487, - 550103529, - 1233637070, - 4289353045, - 2018519080, - 2057691103, - 2399374476, - 4166623649, - 2148108681, - 387583245, - 3664101311, - 836232934, - 3330556482, - 3100665960, - 3280093505, - 2955516313, - 2002398509, - 287182607, - 3413881008, - 4238890068, - 3597515707, - 975967766 - ]; - var T3 = [ - 1671808611, - 2089089148, - 2006576759, - 2072901243, - 4061003762, - 1807603307, - 1873927791, - 3310653893, - 810573872, - 16974337, - 1739181671, - 729634347, - 4263110654, - 3613570519, - 2883997099, - 1989864566, - 3393556426, - 2191335298, - 3376449993, - 2106063485, - 4195741690, - 1508618841, - 1204391495, - 4027317232, - 2917941677, - 3563566036, - 2734514082, - 2951366063, - 2629772188, - 2767672228, - 1922491506, - 3227229120, - 3082974647, - 4246528509, - 2477669779, - 644500518, - 911895606, - 1061256767, - 4144166391, - 3427763148, - 878471220, - 2784252325, - 3845444069, - 4043897329, - 1905517169, - 3631459288, - 827548209, - 356461077, - 67897348, - 3344078279, - 593839651, - 3277757891, - 405286936, - 2527147926, - 84871685, - 2595565466, - 118033927, - 305538066, - 2157648768, - 3795705826, - 3945188843, - 661212711, - 2999812018, - 1973414517, - 152769033, - 2208177539, - 745822252, - 439235610, - 455947803, - 1857215598, - 1525593178, - 2700827552, - 1391895634, - 994932283, - 3596728278, - 3016654259, - 695947817, - 3812548067, - 795958831, - 2224493444, - 1408607827, - 3513301457, - 0, - 3979133421, - 543178784, - 4229948412, - 2982705585, - 1542305371, - 1790891114, - 3410398667, - 3201918910, - 961245753, - 1256100938, - 1289001036, - 1491644504, - 3477767631, - 3496721360, - 4012557807, - 2867154858, - 4212583931, - 1137018435, - 1305975373, - 861234739, - 2241073541, - 1171229253, - 4178635257, - 33948674, - 2139225727, - 1357946960, - 1011120188, - 2679776671, - 2833468328, - 1374921297, - 2751356323, - 1086357568, - 2408187279, - 2460827538, - 2646352285, - 944271416, - 4110742005, - 3168756668, - 3066132406, - 3665145818, - 560153121, - 271589392, - 4279952895, - 4077846003, - 3530407890, - 3444343245, - 202643468, - 322250259, - 3962553324, - 1608629855, - 2543990167, - 1154254916, - 389623319, - 3294073796, - 2817676711, - 2122513534, - 1028094525, - 1689045092, - 1575467613, - 422261273, - 1939203699, - 1621147744, - 2174228865, - 1339137615, - 3699352540, - 577127458, - 712922154, - 2427141008, - 2290289544, - 1187679302, - 3995715566, - 3100863416, - 339486740, - 3732514782, - 1591917662, - 186455563, - 3681988059, - 3762019296, - 844522546, - 978220090, - 169743370, - 1239126601, - 101321734, - 611076132, - 1558493276, - 3260915650, - 3547250131, - 2901361580, - 1655096418, - 2443721105, - 2510565781, - 3828863972, - 2039214713, - 3878868455, - 3359869896, - 928607799, - 1840765549, - 2374762893, - 3580146133, - 1322425422, - 2850048425, - 1823791212, - 1459268694, - 4094161908, - 3928346602, - 1706019429, - 2056189050, - 2934523822, - 135794696, - 3134549946, - 2022240376, - 628050469, - 779246638, - 472135708, - 2800834470, - 3032970164, - 3327236038, - 3894660072, - 3715932637, - 1956440180, - 522272287, - 1272813131, - 3185336765, - 2340818315, - 2323976074, - 1888542832, - 1044544574, - 3049550261, - 1722469478, - 1222152264, - 50660867, - 4127324150, - 236067854, - 1638122081, - 895445557, - 1475980887, - 3117443513, - 2257655686, - 3243809217, - 489110045, - 2662934430, - 3778599393, - 4162055160, - 2561878936, - 288563729, - 1773916777, - 3648039385, - 2391345038, - 2493985684, - 2612407707, - 505560094, - 2274497927, - 3911240169, - 3460925390, - 1442818645, - 678973480, - 3749357023, - 2358182796, - 2717407649, - 2306869641, - 219617805, - 3218761151, - 3862026214, - 1120306242, - 1756942440, - 1103331905, - 2578459033, - 762796589, - 252780047, - 2966125488, - 1425844308, - 3151392187, - 372911126 - ]; - var T4 = [ - 1667474886, - 2088535288, - 2004326894, - 2071694838, - 4075949567, - 1802223062, - 1869591006, - 3318043793, - 808472672, - 16843522, - 1734846926, - 724270422, - 4278065639, - 3621216949, - 2880169549, - 1987484396, - 3402253711, - 2189597983, - 3385409673, - 2105378810, - 4210693615, - 1499065266, - 1195886990, - 4042263547, - 2913856577, - 3570689971, - 2728590687, - 2947541573, - 2627518243, - 2762274643, - 1920112356, - 3233831835, - 3082273397, - 4261223649, - 2475929149, - 640051788, - 909531756, - 1061110142, - 4160160501, - 3435941763, - 875846760, - 2779116625, - 3857003729, - 4059105529, - 1903268834, - 3638064043, - 825316194, - 353713962, - 67374088, - 3351728789, - 589522246, - 3284360861, - 404236336, - 2526454071, - 84217610, - 2593830191, - 117901582, - 303183396, - 2155911963, - 3806477791, - 3958056653, - 656894286, - 2998062463, - 1970642922, - 151591698, - 2206440989, - 741110872, - 437923380, - 454765878, - 1852748508, - 1515908788, - 2694904667, - 1381168804, - 993742198, - 3604373943, - 3014905469, - 690584402, - 3823320797, - 791638366, - 2223281939, - 1398011302, - 3520161977, - 0, - 3991743681, - 538992704, - 4244381667, - 2981218425, - 1532751286, - 1785380564, - 3419096717, - 3200178535, - 960056178, - 1246420628, - 1280103576, - 1482221744, - 3486468741, - 3503319995, - 4025428677, - 2863326543, - 4227536621, - 1128514950, - 1296947098, - 859002214, - 2240123921, - 1162203018, - 4193849577, - 33687044, - 2139062782, - 1347481760, - 1010582648, - 2678045221, - 2829640523, - 1364325282, - 2745433693, - 1077985408, - 2408548869, - 2459086143, - 2644360225, - 943212656, - 4126475505, - 3166494563, - 3065430391, - 3671750063, - 555836226, - 269496352, - 4294908645, - 4092792573, - 3537006015, - 3452783745, - 202118168, - 320025894, - 3974901699, - 1600119230, - 2543297077, - 1145359496, - 387397934, - 3301201811, - 2812801621, - 2122220284, - 1027426170, - 1684319432, - 1566435258, - 421079858, - 1936954854, - 1616945344, - 2172753945, - 1330631070, - 3705438115, - 572679748, - 707427924, - 2425400123, - 2290647819, - 1179044492, - 4008585671, - 3099120491, - 336870440, - 3739122087, - 1583276732, - 185277718, - 3688593069, - 3772791771, - 842159716, - 976899700, - 168435220, - 1229577106, - 101059084, - 606366792, - 1549591736, - 3267517855, - 3553849021, - 2897014595, - 1650632388, - 2442242105, - 2509612081, - 3840161747, - 2038008818, - 3890688725, - 3368567691, - 926374254, - 1835907034, - 2374863873, - 3587531953, - 1313788572, - 2846482505, - 1819063512, - 1448540844, - 4109633523, - 3941213647, - 1701162954, - 2054852340, - 2930698567, - 134748176, - 3132806511, - 2021165296, - 623210314, - 774795868, - 471606328, - 2795958615, - 3031746419, - 3334885783, - 3907527627, - 3722280097, - 1953799400, - 522133822, - 1263263126, - 3183336545, - 2341176845, - 2324333839, - 1886425312, - 1044267644, - 3048588401, - 1718004428, - 1212733584, - 50529542, - 4143317495, - 235803164, - 1633788866, - 892690282, - 1465383342, - 3115962473, - 2256965911, - 3250673817, - 488449850, - 2661202215, - 3789633753, - 4177007595, - 2560144171, - 286339874, - 1768537042, - 3654906025, - 2391705863, - 2492770099, - 2610673197, - 505291324, - 2273808917, - 3924369609, - 3469625735, - 1431699370, - 673740880, - 3755965093, - 2358021891, - 2711746649, - 2307489801, - 218961690, - 3217021541, - 3873845719, - 1111672452, - 1751693520, - 1094828930, - 2576986153, - 757954394, - 252645662, - 2964376443, - 1414855848, - 3149649517, - 370555436 - ]; - var T5 = [ - 1374988112, - 2118214995, - 437757123, - 975658646, - 1001089995, - 530400753, - 2902087851, - 1273168787, - 540080725, - 2910219766, - 2295101073, - 4110568485, - 1340463100, - 3307916247, - 641025152, - 3043140495, - 3736164937, - 632953703, - 1172967064, - 1576976609, - 3274667266, - 2169303058, - 2370213795, - 1809054150, - 59727847, - 361929877, - 3211623147, - 2505202138, - 3569255213, - 1484005843, - 1239443753, - 2395588676, - 1975683434, - 4102977912, - 2572697195, - 666464733, - 3202437046, - 4035489047, - 3374361702, - 2110667444, - 1675577880, - 3843699074, - 2538681184, - 1649639237, - 2976151520, - 3144396420, - 4269907996, - 4178062228, - 1883793496, - 2403728665, - 2497604743, - 1383856311, - 2876494627, - 1917518562, - 3810496343, - 1716890410, - 3001755655, - 800440835, - 2261089178, - 3543599269, - 807962610, - 599762354, - 33778362, - 3977675356, - 2328828971, - 2809771154, - 4077384432, - 1315562145, - 1708848333, - 101039829, - 3509871135, - 3299278474, - 875451293, - 2733856160, - 92987698, - 2767645557, - 193195065, - 1080094634, - 1584504582, - 3178106961, - 1042385657, - 2531067453, - 3711829422, - 1306967366, - 2438237621, - 1908694277, - 67556463, - 1615861247, - 429456164, - 3602770327, - 2302690252, - 1742315127, - 2968011453, - 126454664, - 3877198648, - 2043211483, - 2709260871, - 2084704233, - 4169408201, - 0, - 159417987, - 841739592, - 504459436, - 1817866830, - 4245618683, - 260388950, - 1034867998, - 908933415, - 168810852, - 1750902305, - 2606453969, - 607530554, - 202008497, - 2472011535, - 3035535058, - 463180190, - 2160117071, - 1641816226, - 1517767529, - 470948374, - 3801332234, - 3231722213, - 1008918595, - 303765277, - 235474187, - 4069246893, - 766945465, - 337553864, - 1475418501, - 2943682380, - 4003061179, - 2743034109, - 4144047775, - 1551037884, - 1147550661, - 1543208500, - 2336434550, - 3408119516, - 3069049960, - 3102011747, - 3610369226, - 1113818384, - 328671808, - 2227573024, - 2236228733, - 3535486456, - 2935566865, - 3341394285, - 496906059, - 3702665459, - 226906860, - 2009195472, - 733156972, - 2842737049, - 294930682, - 1206477858, - 2835123396, - 2700099354, - 1451044056, - 573804783, - 2269728455, - 3644379585, - 2362090238, - 2564033334, - 2801107407, - 2776292904, - 3669462566, - 1068351396, - 742039012, - 1350078989, - 1784663195, - 1417561698, - 4136440770, - 2430122216, - 775550814, - 2193862645, - 2673705150, - 1775276924, - 1876241833, - 3475313331, - 3366754619, - 270040487, - 3902563182, - 3678124923, - 3441850377, - 1851332852, - 3969562369, - 2203032232, - 3868552805, - 2868897406, - 566021896, - 4011190502, - 3135740889, - 1248802510, - 3936291284, - 699432150, - 832877231, - 708780849, - 3332740144, - 899835584, - 1951317047, - 4236429990, - 3767586992, - 866637845, - 4043610186, - 1106041591, - 2144161806, - 395441711, - 1984812685, - 1139781709, - 3433712980, - 3835036895, - 2664543715, - 1282050075, - 3240894392, - 1181045119, - 2640243204, - 25965917, - 4203181171, - 4211818798, - 3009879386, - 2463879762, - 3910161971, - 1842759443, - 2597806476, - 933301370, - 1509430414, - 3943906441, - 3467192302, - 3076639029, - 3776767469, - 2051518780, - 2631065433, - 1441952575, - 404016761, - 1942435775, - 1408749034, - 1610459739, - 3745345300, - 2017778566, - 3400528769, - 3110650942, - 941896748, - 3265478751, - 371049330, - 3168937228, - 675039627, - 4279080257, - 967311729, - 135050206, - 3635733660, - 1683407248, - 2076935265, - 3576870512, - 1215061108, - 3501741890 - ]; - var T6 = [ - 1347548327, - 1400783205, - 3273267108, - 2520393566, - 3409685355, - 4045380933, - 2880240216, - 2471224067, - 1428173050, - 4138563181, - 2441661558, - 636813900, - 4233094615, - 3620022987, - 2149987652, - 2411029155, - 1239331162, - 1730525723, - 2554718734, - 3781033664, - 46346101, - 310463728, - 2743944855, - 3328955385, - 3875770207, - 2501218972, - 3955191162, - 3667219033, - 768917123, - 3545789473, - 692707433, - 1150208456, - 1786102409, - 2029293177, - 1805211710, - 3710368113, - 3065962831, - 401639597, - 1724457132, - 3028143674, - 409198410, - 2196052529, - 1620529459, - 1164071807, - 3769721975, - 2226875310, - 486441376, - 2499348523, - 1483753576, - 428819965, - 2274680428, - 3075636216, - 598438867, - 3799141122, - 1474502543, - 711349675, - 129166120, - 53458370, - 2592523643, - 2782082824, - 4063242375, - 2988687269, - 3120694122, - 1559041666, - 730517276, - 2460449204, - 4042459122, - 2706270690, - 3446004468, - 3573941694, - 533804130, - 2328143614, - 2637442643, - 2695033685, - 839224033, - 1973745387, - 957055980, - 2856345839, - 106852767, - 1371368976, - 4181598602, - 1033297158, - 2933734917, - 1179510461, - 3046200461, - 91341917, - 1862534868, - 4284502037, - 605657339, - 2547432937, - 3431546947, - 2003294622, - 3182487618, - 2282195339, - 954669403, - 3682191598, - 1201765386, - 3917234703, - 3388507166, - 0, - 2198438022, - 1211247597, - 2887651696, - 1315723890, - 4227665663, - 1443857720, - 507358933, - 657861945, - 1678381017, - 560487590, - 3516619604, - 975451694, - 2970356327, - 261314535, - 3535072918, - 2652609425, - 1333838021, - 2724322336, - 1767536459, - 370938394, - 182621114, - 3854606378, - 1128014560, - 487725847, - 185469197, - 2918353863, - 3106780840, - 3356761769, - 2237133081, - 1286567175, - 3152976349, - 4255350624, - 2683765030, - 3160175349, - 3309594171, - 878443390, - 1988838185, - 3704300486, - 1756818940, - 1673061617, - 3403100636, - 272786309, - 1075025698, - 545572369, - 2105887268, - 4174560061, - 296679730, - 1841768865, - 1260232239, - 4091327024, - 3960309330, - 3497509347, - 1814803222, - 2578018489, - 4195456072, - 575138148, - 3299409036, - 446754879, - 3629546796, - 4011996048, - 3347532110, - 3252238545, - 4270639778, - 915985419, - 3483825537, - 681933534, - 651868046, - 2755636671, - 3828103837, - 223377554, - 2607439820, - 1649704518, - 3270937875, - 3901806776, - 1580087799, - 4118987695, - 3198115200, - 2087309459, - 2842678573, - 3016697106, - 1003007129, - 2802849917, - 1860738147, - 2077965243, - 164439672, - 4100872472, - 32283319, - 2827177882, - 1709610350, - 2125135846, - 136428751, - 3874428392, - 3652904859, - 3460984630, - 3572145929, - 3593056380, - 2939266226, - 824852259, - 818324884, - 3224740454, - 930369212, - 2801566410, - 2967507152, - 355706840, - 1257309336, - 4148292826, - 243256656, - 790073846, - 2373340630, - 1296297904, - 1422699085, - 3756299780, - 3818836405, - 457992840, - 3099667487, - 2135319889, - 77422314, - 1560382517, - 1945798516, - 788204353, - 1521706781, - 1385356242, - 870912086, - 325965383, - 2358957921, - 2050466060, - 2388260884, - 2313884476, - 4006521127, - 901210569, - 3990953189, - 1014646705, - 1503449823, - 1062597235, - 2031621326, - 3212035895, - 3931371469, - 1533017514, - 350174575, - 2256028891, - 2177544179, - 1052338372, - 741876788, - 1606591296, - 1914052035, - 213705253, - 2334669897, - 1107234197, - 1899603969, - 3725069491, - 2631447780, - 2422494913, - 1635502980, - 1893020342, - 1950903388, - 1120974935 - ]; - var T7 = [ - 2807058932, - 1699970625, - 2764249623, - 1586903591, - 1808481195, - 1173430173, - 1487645946, - 59984867, - 4199882800, - 1844882806, - 1989249228, - 1277555970, - 3623636965, - 3419915562, - 1149249077, - 2744104290, - 1514790577, - 459744698, - 244860394, - 3235995134, - 1963115311, - 4027744588, - 2544078150, - 4190530515, - 1608975247, - 2627016082, - 2062270317, - 1507497298, - 2200818878, - 567498868, - 1764313568, - 3359936201, - 2305455554, - 2037970062, - 1047239e3, - 1910319033, - 1337376481, - 2904027272, - 2892417312, - 984907214, - 1243112415, - 830661914, - 861968209, - 2135253587, - 2011214180, - 2927934315, - 2686254721, - 731183368, - 1750626376, - 4246310725, - 1820824798, - 4172763771, - 3542330227, - 48394827, - 2404901663, - 2871682645, - 671593195, - 3254988725, - 2073724613, - 145085239, - 2280796200, - 2779915199, - 1790575107, - 2187128086, - 472615631, - 3029510009, - 4075877127, - 3802222185, - 4107101658, - 3201631749, - 1646252340, - 4270507174, - 1402811438, - 1436590835, - 3778151818, - 3950355702, - 3963161475, - 4020912224, - 2667994737, - 273792366, - 2331590177, - 104699613, - 95345982, - 3175501286, - 2377486676, - 1560637892, - 3564045318, - 369057872, - 4213447064, - 3919042237, - 1137477952, - 2658625497, - 1119727848, - 2340947849, - 1530455833, - 4007360968, - 172466556, - 266959938, - 516552836, - 0, - 2256734592, - 3980931627, - 1890328081, - 1917742170, - 4294704398, - 945164165, - 3575528878, - 958871085, - 3647212047, - 2787207260, - 1423022939, - 775562294, - 1739656202, - 3876557655, - 2530391278, - 2443058075, - 3310321856, - 547512796, - 1265195639, - 437656594, - 3121275539, - 719700128, - 3762502690, - 387781147, - 218828297, - 3350065803, - 2830708150, - 2848461854, - 428169201, - 122466165, - 3720081049, - 1627235199, - 648017665, - 4122762354, - 1002783846, - 2117360635, - 695634755, - 3336358691, - 4234721005, - 4049844452, - 3704280881, - 2232435299, - 574624663, - 287343814, - 612205898, - 1039717051, - 840019705, - 2708326185, - 793451934, - 821288114, - 1391201670, - 3822090177, - 376187827, - 3113855344, - 1224348052, - 1679968233, - 2361698556, - 1058709744, - 752375421, - 2431590963, - 1321699145, - 3519142200, - 2734591178, - 188127444, - 2177869557, - 3727205754, - 2384911031, - 3215212461, - 2648976442, - 2450346104, - 3432737375, - 1180849278, - 331544205, - 3102249176, - 4150144569, - 2952102595, - 2159976285, - 2474404304, - 766078933, - 313773861, - 2570832044, - 2108100632, - 1668212892, - 3145456443, - 2013908262, - 418672217, - 3070356634, - 2594734927, - 1852171925, - 3867060991, - 3473416636, - 3907448597, - 2614737639, - 919489135, - 164948639, - 2094410160, - 2997825956, - 590424639, - 2486224549, - 1723872674, - 3157750862, - 3399941250, - 3501252752, - 3625268135, - 2555048196, - 3673637356, - 1343127501, - 4130281361, - 3599595085, - 2957853679, - 1297403050, - 81781910, - 3051593425, - 2283490410, - 532201772, - 1367295589, - 3926170974, - 895287692, - 1953757831, - 1093597963, - 492483431, - 3528626907, - 1446242576, - 1192455638, - 1636604631, - 209336225, - 344873464, - 1015671571, - 669961897, - 3375740769, - 3857572124, - 2973530695, - 3747192018, - 1933530610, - 3464042516, - 935293895, - 3454686199, - 2858115069, - 1863638845, - 3683022916, - 4085369519, - 3292445032, - 875313188, - 1080017571, - 3279033885, - 621591778, - 1233856572, - 2504130317, - 24197544, - 3017672716, - 3835484340, - 3247465558, - 2220981195, - 3060847922, - 1551124588, - 1463996600 - ]; - var T8 = [ - 4104605777, - 1097159550, - 396673818, - 660510266, - 2875968315, - 2638606623, - 4200115116, - 3808662347, - 821712160, - 1986918061, - 3430322568, - 38544885, - 3856137295, - 718002117, - 893681702, - 1654886325, - 2975484382, - 3122358053, - 3926825029, - 4274053469, - 796197571, - 1290801793, - 1184342925, - 3556361835, - 2405426947, - 2459735317, - 1836772287, - 1381620373, - 3196267988, - 1948373848, - 3764988233, - 3385345166, - 3263785589, - 2390325492, - 1480485785, - 3111247143, - 3780097726, - 2293045232, - 548169417, - 3459953789, - 3746175075, - 439452389, - 1362321559, - 1400849762, - 1685577905, - 1806599355, - 2174754046, - 137073913, - 1214797936, - 1174215055, - 3731654548, - 2079897426, - 1943217067, - 1258480242, - 529487843, - 1437280870, - 3945269170, - 3049390895, - 3313212038, - 923313619, - 679998e3, - 3215307299, - 57326082, - 377642221, - 3474729866, - 2041877159, - 133361907, - 1776460110, - 3673476453, - 96392454, - 878845905, - 2801699524, - 777231668, - 4082475170, - 2330014213, - 4142626212, - 2213296395, - 1626319424, - 1906247262, - 1846563261, - 562755902, - 3708173718, - 1040559837, - 3871163981, - 1418573201, - 3294430577, - 114585348, - 1343618912, - 2566595609, - 3186202582, - 1078185097, - 3651041127, - 3896688048, - 2307622919, - 425408743, - 3371096953, - 2081048481, - 1108339068, - 2216610296, - 0, - 2156299017, - 736970802, - 292596766, - 1517440620, - 251657213, - 2235061775, - 2933202493, - 758720310, - 265905162, - 1554391400, - 1532285339, - 908999204, - 174567692, - 1474760595, - 4002861748, - 2610011675, - 3234156416, - 3693126241, - 2001430874, - 303699484, - 2478443234, - 2687165888, - 585122620, - 454499602, - 151849742, - 2345119218, - 3064510765, - 514443284, - 4044981591, - 1963412655, - 2581445614, - 2137062819, - 19308535, - 1928707164, - 1715193156, - 4219352155, - 1126790795, - 600235211, - 3992742070, - 3841024952, - 836553431, - 1669664834, - 2535604243, - 3323011204, - 1243905413, - 3141400786, - 4180808110, - 698445255, - 2653899549, - 2989552604, - 2253581325, - 3252932727, - 3004591147, - 1891211689, - 2487810577, - 3915653703, - 4237083816, - 4030667424, - 2100090966, - 865136418, - 1229899655, - 953270745, - 3399679628, - 3557504664, - 4118925222, - 2061379749, - 3079546586, - 2915017791, - 983426092, - 2022837584, - 1607244650, - 2118541908, - 2366882550, - 3635996816, - 972512814, - 3283088770, - 1568718495, - 3499326569, - 3576539503, - 621982671, - 2895723464, - 410887952, - 2623762152, - 1002142683, - 645401037, - 1494807662, - 2595684844, - 1335535747, - 2507040230, - 4293295786, - 3167684641, - 367585007, - 3885750714, - 1865862730, - 2668221674, - 2960971305, - 2763173681, - 1059270954, - 2777952454, - 2724642869, - 1320957812, - 2194319100, - 2429595872, - 2815956275, - 77089521, - 3973773121, - 3444575871, - 2448830231, - 1305906550, - 4021308739, - 2857194700, - 2516901860, - 3518358430, - 1787304780, - 740276417, - 1699839814, - 1592394909, - 2352307457, - 2272556026, - 188821243, - 1729977011, - 3687994002, - 274084841, - 3594982253, - 3613494426, - 2701949495, - 4162096729, - 322734571, - 2837966542, - 1640576439, - 484830689, - 1202797690, - 3537852828, - 4067639125, - 349075736, - 3342319475, - 4157467219, - 4255800159, - 1030690015, - 1155237496, - 2951971274, - 1757691577, - 607398968, - 2738905026, - 499347990, - 3794078908, - 1011452712, - 227885567, - 2818666809, - 213114376, - 3034881240, - 1455525988, - 3414450555, - 850817237, - 1817998408, - 3092726480 - ]; - var U1 = [ - 0, - 235474187, - 470948374, - 303765277, - 941896748, - 908933415, - 607530554, - 708780849, - 1883793496, - 2118214995, - 1817866830, - 1649639237, - 1215061108, - 1181045119, - 1417561698, - 1517767529, - 3767586992, - 4003061179, - 4236429990, - 4069246893, - 3635733660, - 3602770327, - 3299278474, - 3400528769, - 2430122216, - 2664543715, - 2362090238, - 2193862645, - 2835123396, - 2801107407, - 3035535058, - 3135740889, - 3678124923, - 3576870512, - 3341394285, - 3374361702, - 3810496343, - 3977675356, - 4279080257, - 4043610186, - 2876494627, - 2776292904, - 3076639029, - 3110650942, - 2472011535, - 2640243204, - 2403728665, - 2169303058, - 1001089995, - 899835584, - 666464733, - 699432150, - 59727847, - 226906860, - 530400753, - 294930682, - 1273168787, - 1172967064, - 1475418501, - 1509430414, - 1942435775, - 2110667444, - 1876241833, - 1641816226, - 2910219766, - 2743034109, - 2976151520, - 3211623147, - 2505202138, - 2606453969, - 2302690252, - 2269728455, - 3711829422, - 3543599269, - 3240894392, - 3475313331, - 3843699074, - 3943906441, - 4178062228, - 4144047775, - 1306967366, - 1139781709, - 1374988112, - 1610459739, - 1975683434, - 2076935265, - 1775276924, - 1742315127, - 1034867998, - 866637845, - 566021896, - 800440835, - 92987698, - 193195065, - 429456164, - 395441711, - 1984812685, - 2017778566, - 1784663195, - 1683407248, - 1315562145, - 1080094634, - 1383856311, - 1551037884, - 101039829, - 135050206, - 437757123, - 337553864, - 1042385657, - 807962610, - 573804783, - 742039012, - 2531067453, - 2564033334, - 2328828971, - 2227573024, - 2935566865, - 2700099354, - 3001755655, - 3168937228, - 3868552805, - 3902563182, - 4203181171, - 4102977912, - 3736164937, - 3501741890, - 3265478751, - 3433712980, - 1106041591, - 1340463100, - 1576976609, - 1408749034, - 2043211483, - 2009195472, - 1708848333, - 1809054150, - 832877231, - 1068351396, - 766945465, - 599762354, - 159417987, - 126454664, - 361929877, - 463180190, - 2709260871, - 2943682380, - 3178106961, - 3009879386, - 2572697195, - 2538681184, - 2236228733, - 2336434550, - 3509871135, - 3745345300, - 3441850377, - 3274667266, - 3910161971, - 3877198648, - 4110568485, - 4211818798, - 2597806476, - 2497604743, - 2261089178, - 2295101073, - 2733856160, - 2902087851, - 3202437046, - 2968011453, - 3936291284, - 3835036895, - 4136440770, - 4169408201, - 3535486456, - 3702665459, - 3467192302, - 3231722213, - 2051518780, - 1951317047, - 1716890410, - 1750902305, - 1113818384, - 1282050075, - 1584504582, - 1350078989, - 168810852, - 67556463, - 371049330, - 404016761, - 841739592, - 1008918595, - 775550814, - 540080725, - 3969562369, - 3801332234, - 4035489047, - 4269907996, - 3569255213, - 3669462566, - 3366754619, - 3332740144, - 2631065433, - 2463879762, - 2160117071, - 2395588676, - 2767645557, - 2868897406, - 3102011747, - 3069049960, - 202008497, - 33778362, - 270040487, - 504459436, - 875451293, - 975658646, - 675039627, - 641025152, - 2084704233, - 1917518562, - 1615861247, - 1851332852, - 1147550661, - 1248802510, - 1484005843, - 1451044056, - 933301370, - 967311729, - 733156972, - 632953703, - 260388950, - 25965917, - 328671808, - 496906059, - 1206477858, - 1239443753, - 1543208500, - 1441952575, - 2144161806, - 1908694277, - 1675577880, - 1842759443, - 3610369226, - 3644379585, - 3408119516, - 3307916247, - 4011190502, - 3776767469, - 4077384432, - 4245618683, - 2809771154, - 2842737049, - 3144396420, - 3043140495, - 2673705150, - 2438237621, - 2203032232, - 2370213795 - ]; - var U2 = [ - 0, - 185469197, - 370938394, - 487725847, - 741876788, - 657861945, - 975451694, - 824852259, - 1483753576, - 1400783205, - 1315723890, - 1164071807, - 1950903388, - 2135319889, - 1649704518, - 1767536459, - 2967507152, - 3152976349, - 2801566410, - 2918353863, - 2631447780, - 2547432937, - 2328143614, - 2177544179, - 3901806776, - 3818836405, - 4270639778, - 4118987695, - 3299409036, - 3483825537, - 3535072918, - 3652904859, - 2077965243, - 1893020342, - 1841768865, - 1724457132, - 1474502543, - 1559041666, - 1107234197, - 1257309336, - 598438867, - 681933534, - 901210569, - 1052338372, - 261314535, - 77422314, - 428819965, - 310463728, - 3409685355, - 3224740454, - 3710368113, - 3593056380, - 3875770207, - 3960309330, - 4045380933, - 4195456072, - 2471224067, - 2554718734, - 2237133081, - 2388260884, - 3212035895, - 3028143674, - 2842678573, - 2724322336, - 4138563181, - 4255350624, - 3769721975, - 3955191162, - 3667219033, - 3516619604, - 3431546947, - 3347532110, - 2933734917, - 2782082824, - 3099667487, - 3016697106, - 2196052529, - 2313884476, - 2499348523, - 2683765030, - 1179510461, - 1296297904, - 1347548327, - 1533017514, - 1786102409, - 1635502980, - 2087309459, - 2003294622, - 507358933, - 355706840, - 136428751, - 53458370, - 839224033, - 957055980, - 605657339, - 790073846, - 2373340630, - 2256028891, - 2607439820, - 2422494913, - 2706270690, - 2856345839, - 3075636216, - 3160175349, - 3573941694, - 3725069491, - 3273267108, - 3356761769, - 4181598602, - 4063242375, - 4011996048, - 3828103837, - 1033297158, - 915985419, - 730517276, - 545572369, - 296679730, - 446754879, - 129166120, - 213705253, - 1709610350, - 1860738147, - 1945798516, - 2029293177, - 1239331162, - 1120974935, - 1606591296, - 1422699085, - 4148292826, - 4233094615, - 3781033664, - 3931371469, - 3682191598, - 3497509347, - 3446004468, - 3328955385, - 2939266226, - 2755636671, - 3106780840, - 2988687269, - 2198438022, - 2282195339, - 2501218972, - 2652609425, - 1201765386, - 1286567175, - 1371368976, - 1521706781, - 1805211710, - 1620529459, - 2105887268, - 1988838185, - 533804130, - 350174575, - 164439672, - 46346101, - 870912086, - 954669403, - 636813900, - 788204353, - 2358957921, - 2274680428, - 2592523643, - 2441661558, - 2695033685, - 2880240216, - 3065962831, - 3182487618, - 3572145929, - 3756299780, - 3270937875, - 3388507166, - 4174560061, - 4091327024, - 4006521127, - 3854606378, - 1014646705, - 930369212, - 711349675, - 560487590, - 272786309, - 457992840, - 106852767, - 223377554, - 1678381017, - 1862534868, - 1914052035, - 2031621326, - 1211247597, - 1128014560, - 1580087799, - 1428173050, - 32283319, - 182621114, - 401639597, - 486441376, - 768917123, - 651868046, - 1003007129, - 818324884, - 1503449823, - 1385356242, - 1333838021, - 1150208456, - 1973745387, - 2125135846, - 1673061617, - 1756818940, - 2970356327, - 3120694122, - 2802849917, - 2887651696, - 2637442643, - 2520393566, - 2334669897, - 2149987652, - 3917234703, - 3799141122, - 4284502037, - 4100872472, - 3309594171, - 3460984630, - 3545789473, - 3629546796, - 2050466060, - 1899603969, - 1814803222, - 1730525723, - 1443857720, - 1560382517, - 1075025698, - 1260232239, - 575138148, - 692707433, - 878443390, - 1062597235, - 243256656, - 91341917, - 409198410, - 325965383, - 3403100636, - 3252238545, - 3704300486, - 3620022987, - 3874428392, - 3990953189, - 4042459122, - 4227665663, - 2460449204, - 2578018489, - 2226875310, - 2411029155, - 3198115200, - 3046200461, - 2827177882, - 2743944855 - ]; - var U3 = [ - 0, - 218828297, - 437656594, - 387781147, - 875313188, - 958871085, - 775562294, - 590424639, - 1750626376, - 1699970625, - 1917742170, - 2135253587, - 1551124588, - 1367295589, - 1180849278, - 1265195639, - 3501252752, - 3720081049, - 3399941250, - 3350065803, - 3835484340, - 3919042237, - 4270507174, - 4085369519, - 3102249176, - 3051593425, - 2734591178, - 2952102595, - 2361698556, - 2177869557, - 2530391278, - 2614737639, - 3145456443, - 3060847922, - 2708326185, - 2892417312, - 2404901663, - 2187128086, - 2504130317, - 2555048196, - 3542330227, - 3727205754, - 3375740769, - 3292445032, - 3876557655, - 3926170974, - 4246310725, - 4027744588, - 1808481195, - 1723872674, - 1910319033, - 2094410160, - 1608975247, - 1391201670, - 1173430173, - 1224348052, - 59984867, - 244860394, - 428169201, - 344873464, - 935293895, - 984907214, - 766078933, - 547512796, - 1844882806, - 1627235199, - 2011214180, - 2062270317, - 1507497298, - 1423022939, - 1137477952, - 1321699145, - 95345982, - 145085239, - 532201772, - 313773861, - 830661914, - 1015671571, - 731183368, - 648017665, - 3175501286, - 2957853679, - 2807058932, - 2858115069, - 2305455554, - 2220981195, - 2474404304, - 2658625497, - 3575528878, - 3625268135, - 3473416636, - 3254988725, - 3778151818, - 3963161475, - 4213447064, - 4130281361, - 3599595085, - 3683022916, - 3432737375, - 3247465558, - 3802222185, - 4020912224, - 4172763771, - 4122762354, - 3201631749, - 3017672716, - 2764249623, - 2848461854, - 2331590177, - 2280796200, - 2431590963, - 2648976442, - 104699613, - 188127444, - 472615631, - 287343814, - 840019705, - 1058709744, - 671593195, - 621591778, - 1852171925, - 1668212892, - 1953757831, - 2037970062, - 1514790577, - 1463996600, - 1080017571, - 1297403050, - 3673637356, - 3623636965, - 3235995134, - 3454686199, - 4007360968, - 3822090177, - 4107101658, - 4190530515, - 2997825956, - 3215212461, - 2830708150, - 2779915199, - 2256734592, - 2340947849, - 2627016082, - 2443058075, - 172466556, - 122466165, - 273792366, - 492483431, - 1047239e3, - 861968209, - 612205898, - 695634755, - 1646252340, - 1863638845, - 2013908262, - 1963115311, - 1446242576, - 1530455833, - 1277555970, - 1093597963, - 1636604631, - 1820824798, - 2073724613, - 1989249228, - 1436590835, - 1487645946, - 1337376481, - 1119727848, - 164948639, - 81781910, - 331544205, - 516552836, - 1039717051, - 821288114, - 669961897, - 719700128, - 2973530695, - 3157750862, - 2871682645, - 2787207260, - 2232435299, - 2283490410, - 2667994737, - 2450346104, - 3647212047, - 3564045318, - 3279033885, - 3464042516, - 3980931627, - 3762502690, - 4150144569, - 4199882800, - 3070356634, - 3121275539, - 2904027272, - 2686254721, - 2200818878, - 2384911031, - 2570832044, - 2486224549, - 3747192018, - 3528626907, - 3310321856, - 3359936201, - 3950355702, - 3867060991, - 4049844452, - 4234721005, - 1739656202, - 1790575107, - 2108100632, - 1890328081, - 1402811438, - 1586903591, - 1233856572, - 1149249077, - 266959938, - 48394827, - 369057872, - 418672217, - 1002783846, - 919489135, - 567498868, - 752375421, - 209336225, - 24197544, - 376187827, - 459744698, - 945164165, - 895287692, - 574624663, - 793451934, - 1679968233, - 1764313568, - 2117360635, - 1933530610, - 1343127501, - 1560637892, - 1243112415, - 1192455638, - 3704280881, - 3519142200, - 3336358691, - 3419915562, - 3907448597, - 3857572124, - 4075877127, - 4294704398, - 3029510009, - 3113855344, - 2927934315, - 2744104290, - 2159976285, - 2377486676, - 2594734927, - 2544078150 - ]; - var U4 = [ - 0, - 151849742, - 303699484, - 454499602, - 607398968, - 758720310, - 908999204, - 1059270954, - 1214797936, - 1097159550, - 1517440620, - 1400849762, - 1817998408, - 1699839814, - 2118541908, - 2001430874, - 2429595872, - 2581445614, - 2194319100, - 2345119218, - 3034881240, - 3186202582, - 2801699524, - 2951971274, - 3635996816, - 3518358430, - 3399679628, - 3283088770, - 4237083816, - 4118925222, - 4002861748, - 3885750714, - 1002142683, - 850817237, - 698445255, - 548169417, - 529487843, - 377642221, - 227885567, - 77089521, - 1943217067, - 2061379749, - 1640576439, - 1757691577, - 1474760595, - 1592394909, - 1174215055, - 1290801793, - 2875968315, - 2724642869, - 3111247143, - 2960971305, - 2405426947, - 2253581325, - 2638606623, - 2487810577, - 3808662347, - 3926825029, - 4044981591, - 4162096729, - 3342319475, - 3459953789, - 3576539503, - 3693126241, - 1986918061, - 2137062819, - 1685577905, - 1836772287, - 1381620373, - 1532285339, - 1078185097, - 1229899655, - 1040559837, - 923313619, - 740276417, - 621982671, - 439452389, - 322734571, - 137073913, - 19308535, - 3871163981, - 4021308739, - 4104605777, - 4255800159, - 3263785589, - 3414450555, - 3499326569, - 3651041127, - 2933202493, - 2815956275, - 3167684641, - 3049390895, - 2330014213, - 2213296395, - 2566595609, - 2448830231, - 1305906550, - 1155237496, - 1607244650, - 1455525988, - 1776460110, - 1626319424, - 2079897426, - 1928707164, - 96392454, - 213114376, - 396673818, - 514443284, - 562755902, - 679998e3, - 865136418, - 983426092, - 3708173718, - 3557504664, - 3474729866, - 3323011204, - 4180808110, - 4030667424, - 3945269170, - 3794078908, - 2507040230, - 2623762152, - 2272556026, - 2390325492, - 2975484382, - 3092726480, - 2738905026, - 2857194700, - 3973773121, - 3856137295, - 4274053469, - 4157467219, - 3371096953, - 3252932727, - 3673476453, - 3556361835, - 2763173681, - 2915017791, - 3064510765, - 3215307299, - 2156299017, - 2307622919, - 2459735317, - 2610011675, - 2081048481, - 1963412655, - 1846563261, - 1729977011, - 1480485785, - 1362321559, - 1243905413, - 1126790795, - 878845905, - 1030690015, - 645401037, - 796197571, - 274084841, - 425408743, - 38544885, - 188821243, - 3613494426, - 3731654548, - 3313212038, - 3430322568, - 4082475170, - 4200115116, - 3780097726, - 3896688048, - 2668221674, - 2516901860, - 2366882550, - 2216610296, - 3141400786, - 2989552604, - 2837966542, - 2687165888, - 1202797690, - 1320957812, - 1437280870, - 1554391400, - 1669664834, - 1787304780, - 1906247262, - 2022837584, - 265905162, - 114585348, - 499347990, - 349075736, - 736970802, - 585122620, - 972512814, - 821712160, - 2595684844, - 2478443234, - 2293045232, - 2174754046, - 3196267988, - 3079546586, - 2895723464, - 2777952454, - 3537852828, - 3687994002, - 3234156416, - 3385345166, - 4142626212, - 4293295786, - 3841024952, - 3992742070, - 174567692, - 57326082, - 410887952, - 292596766, - 777231668, - 660510266, - 1011452712, - 893681702, - 1108339068, - 1258480242, - 1343618912, - 1494807662, - 1715193156, - 1865862730, - 1948373848, - 2100090966, - 2701949495, - 2818666809, - 3004591147, - 3122358053, - 2235061775, - 2352307457, - 2535604243, - 2653899549, - 3915653703, - 3764988233, - 4219352155, - 4067639125, - 3444575871, - 3294430577, - 3746175075, - 3594982253, - 836553431, - 953270745, - 600235211, - 718002117, - 367585007, - 484830689, - 133361907, - 251657213, - 2041877159, - 1891211689, - 1806599355, - 1654886325, - 1568718495, - 1418573201, - 1335535747, - 1184342925 - ]; - function convertToInt32(bytes) { - var result = []; - for(var i = 0; i < bytes.length; i += 4){ - result.push(bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]); + throw error; } - return result; } - var AES2 = function(key) { - if (!(this instanceof AES2)) { - throw Error("AES must be instanitated with `new`"); - } - Object.defineProperty(this, "key", { - value: coerceArray(key, true) - }); - this._prepare(); - }; - AES2.prototype._prepare = function() { - var rounds = numberOfRounds[this.key.length]; - if (rounds == null) { - throw new Error("invalid key size (must be 16, 24 or 32 bytes)"); - } - this._Ke = []; - this._Kd = []; - for(var i = 0; i <= rounds; i++){ - this._Ke.push([ - 0, - 0, - 0, - 0 - ]); - this._Kd.push([ - 0, - 0, - 0, - 0 - ]); - } - var roundKeyCount = (rounds + 1) * 4; - var KC = this.key.length / 4; - var tk = convertToInt32(this.key); - var index; - for(var i = 0; i < KC; i++){ - index = i >> 2; - this._Ke[index][i % 4] = tk[i]; - this._Kd[rounds - index][i % 4] = tk[i]; - } - var rconpointer = 0; - var t = KC, tt; - while(t < roundKeyCount){ - tt = tk[KC - 1]; - tk[0] ^= S[tt >> 16 & 255] << 24 ^ S[tt >> 8 & 255] << 16 ^ S[tt & 255] << 8 ^ S[tt >> 24 & 255] ^ rcon[rconpointer] << 24; - rconpointer += 1; - if (KC != 8) { - for(var i = 1; i < KC; i++){ - tk[i] ^= tk[i - 1]; - } - } else { - for(var i = 1; i < KC / 2; i++){ - tk[i] ^= tk[i - 1]; - } - tt = tk[KC / 2 - 1]; - tk[KC / 2] ^= S[tt & 255] ^ S[tt >> 8 & 255] << 8 ^ S[tt >> 16 & 255] << 16 ^ S[tt >> 24 & 255] << 24; - for(var i = KC / 2 + 1; i < KC; i++){ - tk[i] ^= tk[i - 1]; - } - } - var i = 0, r, c; - while(i < KC && t < roundKeyCount){ - r = t >> 2; - c = t % 4; - this._Ke[r][c] = tk[i]; - this._Kd[rounds - r][c] = tk[i++]; - t++; - } + if (coinType >= 0 && coinType < 2147483648) { + let ethCoinType = coinType + 2147483648; + const data = await this.#fetch("addr(bytes32,uint)", [ + ethCoinType + ]); + if (isHexString(data, 20)) { + return getAddress(data); } - for(var r = 1; r < rounds; r++){ - for(var c = 0; c < 4; c++){ - tt = this._Kd[r][c]; - this._Kd[r][c] = U1[tt >> 24 & 255] ^ U2[tt >> 16 & 255] ^ U3[tt >> 8 & 255] ^ U4[tt & 255]; - } + } + let coinPlugin = null; + for (const plugin of this.provider.plugins){ + if (!(plugin instanceof MulticoinProviderPlugin)) { + continue; } - }; - AES2.prototype.encrypt = function(plaintext) { - if (plaintext.length != 16) { - throw new Error("invalid plaintext size (must be 16 bytes)"); + if (plugin.supportsCoinType(coinType)) { + coinPlugin = plugin; + break; } - var rounds = this._Ke.length - 1; - var a = [ - 0, - 0, - 0, - 0 - ]; - var t = convertToInt32(plaintext); - for(var i = 0; i < 4; i++){ - t[i] ^= this._Ke[0][i]; + } + if (coinPlugin == null) { + return null; + } + const data = await this.#fetch("addr(bytes32,uint)", [ + coinType + ]); + if (data == null || data === "0x") { + return null; + } + const address = await coinPlugin.decodeAddress(coinType, data); + if (address != null) { + return address; + } + assert1(false, `invalid coin data`, "UNSUPPORTED_OPERATION", { + operation: `getAddress(${coinType})`, + info: { + coinType: coinType, + data: data } - for(var r = 1; r < rounds; r++){ - for(var i = 0; i < 4; i++){ - a[i] = T1[t[i] >> 24 & 255] ^ T2[t[(i + 1) % 4] >> 16 & 255] ^ T3[t[(i + 2) % 4] >> 8 & 255] ^ T4[t[(i + 3) % 4] & 255] ^ this._Ke[r][i]; - } - t = a.slice(); + }); + } + async getText(key) { + const data = await this.#fetch("text(bytes32,string)", [ + key + ]); + if (data == null || data === "0x") { + return null; + } + return data; + } + async getContentHash() { + const data = await this.#fetch("contenthash(bytes32)"); + if (data == null || data === "0x") { + return null; + } + const ipfs = data.match(/^0x(e3010170|e5010172)(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); + if (ipfs) { + const scheme = ipfs[1] === "e3010170" ? "ipfs" : "ipns"; + const length = parseInt(ipfs[4], 16); + if (ipfs[5].length === length * 2) { + return `${scheme}:/\/${encodeBase58("0x" + ipfs[2])}`; } - var result = createArray(16), tt; - for(var i = 0; i < 4; i++){ - tt = this._Ke[rounds][i]; - result[4 * i] = (S[t[i] >> 24 & 255] ^ tt >> 24) & 255; - result[4 * i + 1] = (S[t[(i + 1) % 4] >> 16 & 255] ^ tt >> 16) & 255; - result[4 * i + 2] = (S[t[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; - result[4 * i + 3] = (S[t[(i + 3) % 4] & 255] ^ tt) & 255; + } + const swarm = data.match(/^0xe40101fa011b20([0-9a-f]*)$/); + if (swarm && swarm[1].length === 64) { + return `bzz:/\/${swarm[1]}`; + } + assert1(false, `invalid or unsupported content hash data`, "UNSUPPORTED_OPERATION", { + operation: "getContentHash()", + info: { + data: data } - return result; - }; - AES2.prototype.decrypt = function(ciphertext) { - if (ciphertext.length != 16) { - throw new Error("invalid ciphertext size (must be 16 bytes)"); + }); + } + async getAvatar() { + const avatar = await this._getAvatar(); + return avatar.url; + } + async _getAvatar() { + const linkage = [ + { + type: "name", + value: this.name } - var rounds = this._Kd.length - 1; - var a = [ - 0, - 0, - 0, - 0 - ]; - var t = convertToInt32(ciphertext); - for(var i = 0; i < 4; i++){ - t[i] ^= this._Kd[0][i]; + ]; + try { + const avatar = await this.getText("avatar"); + if (avatar == null) { + linkage.push({ + type: "!avatar", + value: "" + }); + return { + url: null, + linkage: linkage + }; } - for(var r = 1; r < rounds; r++){ - for(var i = 0; i < 4; i++){ - a[i] = T5[t[i] >> 24 & 255] ^ T6[t[(i + 3) % 4] >> 16 & 255] ^ T7[t[(i + 2) % 4] >> 8 & 255] ^ T8[t[(i + 1) % 4] & 255] ^ this._Kd[r][i]; + linkage.push({ + type: "avatar", + value: avatar + }); + for(let i = 0; i < matchers.length; i++){ + const match = avatar.match(matchers[i]); + if (match == null) { + continue; + } + const scheme = match[1].toLowerCase(); + switch(scheme){ + case "https": + case "data": + linkage.push({ + type: "url", + value: avatar + }); + return { + linkage: linkage, + url: avatar + }; + case "ipfs": + { + const url = getIpfsLink(avatar); + linkage.push({ + type: "ipfs", + value: avatar + }); + linkage.push({ + type: "url", + value: url + }); + return { + linkage: linkage, + url: url + }; + } + case "erc721": + case "erc1155": + { + const selector = scheme === "erc721" ? "tokenURI(uint256)" : "uri(uint256)"; + linkage.push({ + type: scheme, + value: avatar + }); + const owner = await this.getAddress(); + if (owner == null) { + linkage.push({ + type: "!owner", + value: "" + }); + return { + url: null, + linkage: linkage + }; + } + const comps = (match[2] || "").split("/"); + if (comps.length !== 2) { + linkage.push({ + type: `!${scheme}caip`, + value: match[2] || "" + }); + return { + url: null, + linkage: linkage + }; + } + const tokenId = comps[1]; + const contract = new Contract(comps[0], [ + "function tokenURI(uint) view returns (string)", + "function ownerOf(uint) view returns (address)", + "function uri(uint) view returns (string)", + "function balanceOf(address, uint256) view returns (uint)" + ], this.provider); + if (scheme === "erc721") { + const tokenOwner = await contract.ownerOf(tokenId); + if (owner !== tokenOwner) { + linkage.push({ + type: "!owner", + value: tokenOwner + }); + return { + url: null, + linkage: linkage + }; + } + linkage.push({ + type: "owner", + value: tokenOwner + }); + } else if (scheme === "erc1155") { + const balance = await contract.balanceOf(owner, tokenId); + if (!balance) { + linkage.push({ + type: "!balance", + value: "0" + }); + return { + url: null, + linkage: linkage + }; + } + linkage.push({ + type: "balance", + value: balance.toString() + }); + } + let metadataUrl = await contract[selector](tokenId); + if (metadataUrl == null || metadataUrl === "0x") { + linkage.push({ + type: "!metadata-url", + value: "" + }); + return { + url: null, + linkage: linkage + }; + } + linkage.push({ + type: "metadata-url-base", + value: metadataUrl + }); + if (scheme === "erc1155") { + metadataUrl = metadataUrl.replace("{id}", toBeHex(tokenId, 32).substring(2)); + linkage.push({ + type: "metadata-url-expanded", + value: metadataUrl + }); + } + if (metadataUrl.match(/^ipfs:/i)) { + metadataUrl = getIpfsLink(metadataUrl); + } + linkage.push({ + type: "metadata-url", + value: metadataUrl + }); + let metadata = {}; + const response = await new FetchRequest(metadataUrl).send(); + response.assertOk(); + try { + metadata = response.bodyJson; + } catch (error) { + try { + linkage.push({ + type: "!metadata", + value: response.bodyText + }); + } catch (error) { + const bytes = response.body; + if (bytes) { + linkage.push({ + type: "!metadata", + value: hexlify(bytes) + }); + } + return { + url: null, + linkage: linkage + }; + } + return { + url: null, + linkage: linkage + }; + } + if (!metadata) { + linkage.push({ + type: "!metadata", + value: "" + }); + return { + url: null, + linkage: linkage + }; + } + linkage.push({ + type: "metadata", + value: JSON.stringify(metadata) + }); + let imageUrl = metadata.image; + if (typeof imageUrl !== "string") { + linkage.push({ + type: "!imageUrl", + value: "" + }); + return { + url: null, + linkage: linkage + }; + } + if (imageUrl.match(/^(https:\/\/|data:)/i)) {} else { + const ipfs = imageUrl.match(matcherIpfs); + if (ipfs == null) { + linkage.push({ + type: "!imageUrl-ipfs", + value: imageUrl + }); + return { + url: null, + linkage: linkage + }; + } + linkage.push({ + type: "imageUrl-ipfs", + value: imageUrl + }); + imageUrl = getIpfsLink(imageUrl); + } + linkage.push({ + type: "url", + value: imageUrl + }); + return { + linkage: linkage, + url: imageUrl + }; + } } - t = a.slice(); } - var result = createArray(16), tt; - for(var i = 0; i < 4; i++){ - tt = this._Kd[rounds][i]; - result[4 * i] = (Si[t[i] >> 24 & 255] ^ tt >> 24) & 255; - result[4 * i + 1] = (Si[t[(i + 3) % 4] >> 16 & 255] ^ tt >> 16) & 255; - result[4 * i + 2] = (Si[t[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; - result[4 * i + 3] = (Si[t[(i + 1) % 4] & 255] ^ tt) & 255; - } - return result; + } catch (error) {} + return { + linkage: linkage, + url: null }; - var ModeOfOperationECB = function(key) { - if (!(this instanceof ModeOfOperationECB)) { - throw Error("AES must be instanitated with `new`"); + } + static async getEnsAddress(provider) { + const network = await provider.getNetwork(); + const ensPlugin = network.getPlugin("org.ethers.plugins.network.Ens"); + assert1(ensPlugin, "network does not support ENS", "UNSUPPORTED_OPERATION", { + operation: "getEnsAddress", + info: { + network: network } - this.description = "Electronic Code Block"; - this.name = "ecb"; - this._aes = new AES2(key); - }; - ModeOfOperationECB.prototype.encrypt = function(plaintext) { - plaintext = coerceArray(plaintext); - if (plaintext.length % 16 !== 0) { - throw new Error("invalid plaintext size (must be multiple of 16 bytes)"); - } - var ciphertext = createArray(plaintext.length); - var block = createArray(16); - for(var i = 0; i < plaintext.length; i += 16){ - copyArray(plaintext, block, 0, i, i + 16); - block = this._aes.encrypt(block); - copyArray(block, ciphertext, i); - } - return ciphertext; - }; - ModeOfOperationECB.prototype.decrypt = function(ciphertext) { - ciphertext = coerceArray(ciphertext); - if (ciphertext.length % 16 !== 0) { - throw new Error("invalid ciphertext size (must be multiple of 16 bytes)"); - } - var plaintext = createArray(ciphertext.length); - var block = createArray(16); - for(var i = 0; i < ciphertext.length; i += 16){ - copyArray(ciphertext, block, 0, i, i + 16); - block = this._aes.decrypt(block); - copyArray(block, plaintext, i); - } - return plaintext; - }; - var ModeOfOperationCBC = function(key, iv) { - if (!(this instanceof ModeOfOperationCBC)) { - throw Error("AES must be instanitated with `new`"); - } - this.description = "Cipher Block Chaining"; - this.name = "cbc"; - if (!iv) { - iv = createArray(16); - } else if (iv.length != 16) { - throw new Error("invalid initialation vector size (must be 16 bytes)"); - } - this._lastCipherblock = coerceArray(iv, true); - this._aes = new AES2(key); - }; - ModeOfOperationCBC.prototype.encrypt = function(plaintext) { - plaintext = coerceArray(plaintext); - if (plaintext.length % 16 !== 0) { - throw new Error("invalid plaintext size (must be multiple of 16 bytes)"); - } - var ciphertext = createArray(plaintext.length); - var block = createArray(16); - for(var i = 0; i < plaintext.length; i += 16){ - copyArray(plaintext, block, 0, i, i + 16); - for(var j = 0; j < 16; j++){ - block[j] ^= this._lastCipherblock[j]; - } - this._lastCipherblock = this._aes.encrypt(block); - copyArray(this._lastCipherblock, ciphertext, i); + }); + return ensPlugin.address; + } + static async #getResolver(provider, name) { + const ensAddr = await EnsResolver.getEnsAddress(provider); + try { + const contract = new Contract(ensAddr, [ + "function resolver(bytes32) view returns (address)" + ], provider); + const addr = await contract.resolver(namehash(name), { + enableCcipRead: true + }); + if (addr === ZeroAddress) { + return null; } - return ciphertext; - }; - ModeOfOperationCBC.prototype.decrypt = function(ciphertext) { - ciphertext = coerceArray(ciphertext); - if (ciphertext.length % 16 !== 0) { - throw new Error("invalid ciphertext size (must be multiple of 16 bytes)"); - } - var plaintext = createArray(ciphertext.length); - var block = createArray(16); - for(var i = 0; i < ciphertext.length; i += 16){ - copyArray(ciphertext, block, 0, i, i + 16); - block = this._aes.decrypt(block); - for(var j = 0; j < 16; j++){ - plaintext[i + j] = block[j] ^ this._lastCipherblock[j]; - } - copyArray(ciphertext, this._lastCipherblock, 0, i, i + 16); + return addr; + } catch (error) { + throw error; + } + return null; + } + static async fromName(provider, name) { + let currentName = name; + while(true){ + if (currentName === "" || currentName === ".") { + return null; } - return plaintext; - }; - var ModeOfOperationCFB = function(key, iv, segmentSize) { - if (!(this instanceof ModeOfOperationCFB)) { - throw Error("AES must be instanitated with `new`"); - } - this.description = "Cipher Feedback"; - this.name = "cfb"; - if (!iv) { - iv = createArray(16); - } else if (iv.length != 16) { - throw new Error("invalid initialation vector size (must be 16 size)"); - } - if (!segmentSize) { - segmentSize = 1; - } - this.segmentSize = segmentSize; - this._shiftRegister = coerceArray(iv, true); - this._aes = new AES2(key); - }; - ModeOfOperationCFB.prototype.encrypt = function(plaintext) { - if (plaintext.length % this.segmentSize != 0) { - throw new Error("invalid plaintext size (must be segmentSize bytes)"); - } - var encrypted = coerceArray(plaintext, true); - var xorSegment; - for(var i = 0; i < encrypted.length; i += this.segmentSize){ - xorSegment = this._aes.encrypt(this._shiftRegister); - for(var j = 0; j < this.segmentSize; j++){ - encrypted[i + j] ^= xorSegment[j]; - } - copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize); - copyArray(encrypted, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize); + if (name !== "eth" && currentName === "eth") { + return null; } - return encrypted; - }; - ModeOfOperationCFB.prototype.decrypt = function(ciphertext) { - if (ciphertext.length % this.segmentSize != 0) { - throw new Error("invalid ciphertext size (must be segmentSize bytes)"); - } - var plaintext = coerceArray(ciphertext, true); - var xorSegment; - for(var i = 0; i < plaintext.length; i += this.segmentSize){ - xorSegment = this._aes.encrypt(this._shiftRegister); - for(var j = 0; j < this.segmentSize; j++){ - plaintext[i + j] ^= xorSegment[j]; + const addr = await EnsResolver.#getResolver(provider, currentName); + if (addr != null) { + const resolver = new EnsResolver(provider, addr, name); + if (currentName !== name && !await resolver.supportsWildcard()) { + return null; } - copyArray(this._shiftRegister, this._shiftRegister, 0, this.segmentSize); - copyArray(ciphertext, this._shiftRegister, 16 - this.segmentSize, i, i + this.segmentSize); + return resolver; } - return plaintext; - }; - var ModeOfOperationOFB = function(key, iv) { - if (!(this instanceof ModeOfOperationOFB)) { - throw Error("AES must be instanitated with `new`"); - } - this.description = "Output Feedback"; - this.name = "ofb"; - if (!iv) { - iv = createArray(16); - } else if (iv.length != 16) { - throw new Error("invalid initialation vector size (must be 16 bytes)"); - } - this._lastPrecipher = coerceArray(iv, true); - this._lastPrecipherIndex = 16; - this._aes = new AES2(key); - }; - ModeOfOperationOFB.prototype.encrypt = function(plaintext) { - var encrypted = coerceArray(plaintext, true); - for(var i = 0; i < encrypted.length; i++){ - if (this._lastPrecipherIndex === 16) { - this._lastPrecipher = this._aes.encrypt(this._lastPrecipher); - this._lastPrecipherIndex = 0; + currentName = currentName.split(".").slice(1).join("."); + } + } +} +const BN_0 = BigInt(0); +function allowNull(format, nullValue) { + return function(value) { + if (value == null) { + return nullValue; + } + return format(value); + }; +} +function arrayOf(format, allowNull) { + return (array)=>{ + if (allowNull && array == null) { + return null; + } + if (!Array.isArray(array)) { + throw new Error("not an array"); + } + return array.map((i)=>format(i)); + }; +} +function object(format, altNames) { + return (value)=>{ + const result = {}; + for(const key in format){ + let srcKey = key; + if (altNames && key in altNames && !(srcKey in value)) { + for (const altKey of altNames[key]){ + if (altKey in value) { + srcKey = altKey; + break; + } } - encrypted[i] ^= this._lastPrecipher[this._lastPrecipherIndex++]; } - return encrypted; - }; - ModeOfOperationOFB.prototype.decrypt = ModeOfOperationOFB.prototype.encrypt; - var Counter2 = function(initialValue) { - if (!(this instanceof Counter2)) { - throw Error("Counter must be instanitated with `new`"); + try { + const nv = format[key](value[srcKey]); + if (nv !== undefined) { + result[key] = nv; + } + } catch (error) { + const message = error instanceof Error ? error.message : "not-an-error"; + assert1(false, `invalid value for value.${key} (${message})`, "BAD_DATA", { + value: value + }); } - if (initialValue !== 0 && !initialValue) { - initialValue = 1; + } + return result; + }; +} +function formatBoolean(value) { + switch(value){ + case true: + case "true": + return true; + case false: + case "false": + return false; + } + assertArgument(false, `invalid boolean; ${JSON.stringify(value)}`, "value", value); +} +function formatData(value) { + assertArgument(isHexString(value, true), "invalid data", "value", value); + return value; +} +function formatHash(value) { + assertArgument(isHexString(value, 32), "invalid hash", "value", value); + return value; +} +const _formatLog = object({ + address: getAddress, + blockHash: formatHash, + blockNumber: getNumber, + data: formatData, + index: getNumber, + removed: allowNull(formatBoolean, false), + topics: arrayOf(formatHash), + transactionHash: formatHash, + transactionIndex: getNumber +}, { + index: [ + "logIndex" + ] +}); +function formatLog(value) { + return _formatLog(value); +} +const _formatBlock = object({ + hash: allowNull(formatHash), + parentHash: formatHash, + parentBeaconBlockRoot: allowNull(formatHash, null), + number: getNumber, + timestamp: getNumber, + nonce: allowNull(formatData), + difficulty: getBigInt, + gasLimit: getBigInt, + gasUsed: getBigInt, + stateRoot: allowNull(formatHash, null), + receiptsRoot: allowNull(formatHash, null), + blobGasUsed: allowNull(getBigInt, null), + excessBlobGas: allowNull(getBigInt, null), + miner: allowNull(getAddress), + prevRandao: allowNull(formatHash, null), + extraData: formatData, + baseFeePerGas: allowNull(getBigInt) +}, { + prevRandao: [ + "mixHash" + ] +}); +function formatBlock(value) { + const result = _formatBlock(value); + result.transactions = value.transactions.map((tx)=>{ + if (typeof tx === "string") { + return tx; + } + return formatTransactionResponse(tx); + }); + return result; +} +const _formatReceiptLog = object({ + transactionIndex: getNumber, + blockNumber: getNumber, + transactionHash: formatHash, + address: getAddress, + topics: arrayOf(formatHash), + data: formatData, + index: getNumber, + blockHash: formatHash +}, { + index: [ + "logIndex" + ] +}); +function formatReceiptLog(value) { + return _formatReceiptLog(value); +} +const _formatTransactionReceipt = object({ + to: allowNull(getAddress, null), + from: allowNull(getAddress, null), + contractAddress: allowNull(getAddress, null), + index: getNumber, + root: allowNull(hexlify), + gasUsed: getBigInt, + blobGasUsed: allowNull(getBigInt, null), + logsBloom: allowNull(formatData), + blockHash: formatHash, + hash: formatHash, + logs: arrayOf(formatReceiptLog), + blockNumber: getNumber, + cumulativeGasUsed: getBigInt, + effectiveGasPrice: allowNull(getBigInt), + blobGasPrice: allowNull(getBigInt, null), + status: allowNull(getNumber), + type: allowNull(getNumber, 0) +}, { + effectiveGasPrice: [ + "gasPrice" + ], + hash: [ + "transactionHash" + ], + index: [ + "transactionIndex" + ] +}); +function formatTransactionReceipt(value) { + return _formatTransactionReceipt(value); +} +function formatTransactionResponse(value) { + if (value.to && getBigInt(value.to) === BN_0) { + value.to = "0x0000000000000000000000000000000000000000"; + } + const result = object({ + hash: formatHash, + index: allowNull(getNumber, undefined), + type: (value)=>{ + if (value === "0x" || value == null) { + return 0; } - if (typeof initialValue === "number") { - this._counter = createArray(16); - this.setValue(initialValue); - } else { - this.setBytes(initialValue); + return getNumber(value); + }, + accessList: allowNull(accessListify, null), + blobVersionedHashes: allowNull(arrayOf(formatHash, true), null), + blockHash: allowNull(formatHash, null), + blockNumber: allowNull(getNumber, null), + transactionIndex: allowNull(getNumber, null), + from: getAddress, + gasPrice: allowNull(getBigInt), + maxPriorityFeePerGas: allowNull(getBigInt), + maxFeePerGas: allowNull(getBigInt), + maxFeePerBlobGas: allowNull(getBigInt, null), + gasLimit: getBigInt, + to: allowNull(getAddress, null), + value: getBigInt, + nonce: getNumber, + data: formatData, + creates: allowNull(getAddress, null), + chainId: allowNull(getBigInt, null) + }, { + data: [ + "input" + ], + gasLimit: [ + "gas" + ], + index: [ + "transactionIndex" + ] + })(value); + if (result.to == null && result.creates == null) { + result.creates = getCreateAddress(result); + } + if ((value.type === 1 || value.type === 2) && value.accessList == null) { + result.accessList = []; + } + if (value.signature) { + result.signature = Signature.from(value.signature); + } else { + result.signature = Signature.from(value); + } + if (result.chainId == null) { + const chainId = result.signature.legacyChainId; + if (chainId != null) { + result.chainId = chainId; + } + } + if (result.blockHash && getBigInt(result.blockHash) === BN_0) { + result.blockHash = null; + } + return result; +} +const EnsAddress = "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"; +class NetworkPlugin { + name; + constructor(name){ + defineProperties(this, { + name: name + }); + } + clone() { + return new NetworkPlugin(this.name); + } +} +class GasCostPlugin extends NetworkPlugin { + effectiveBlock; + txBase; + txCreate; + txDataZero; + txDataNonzero; + txAccessListStorageKey; + txAccessListAddress; + constructor(effectiveBlock, costs){ + if (effectiveBlock == null) { + effectiveBlock = 0; + } + super(`org.ethers.network.plugins.GasCost#${effectiveBlock || 0}`); + const props = { + effectiveBlock: effectiveBlock + }; + function set(name, nullish) { + let value = (costs || {})[name]; + if (value == null) { + value = nullish; } + assertArgument(typeof value === "number", `invalud value for ${name}`, "costs", costs); + props[name] = value; + } + set("txBase", 21e3); + set("txCreate", 32e3); + set("txDataZero", 4); + set("txDataNonzero", 16); + set("txAccessListStorageKey", 1900); + set("txAccessListAddress", 2400); + defineProperties(this, props); + } + clone() { + return new GasCostPlugin(this.effectiveBlock, this); + } +} +class EnsPlugin extends NetworkPlugin { + address; + targetNetwork; + constructor(address, targetNetwork){ + super("org.ethers.plugins.network.Ens"); + defineProperties(this, { + address: address || EnsAddress, + targetNetwork: targetNetwork == null ? 1 : targetNetwork + }); + } + clone() { + return new EnsPlugin(this.address, this.targetNetwork); + } +} +class FeeDataNetworkPlugin extends NetworkPlugin { + #feeDataFunc; + get feeDataFunc() { + return this.#feeDataFunc; + } + constructor(feeDataFunc){ + super("org.ethers.plugins.network.FeeData"); + this.#feeDataFunc = feeDataFunc; + } + async getFeeData(provider) { + return await this.#feeDataFunc(provider); + } + clone() { + return new FeeDataNetworkPlugin(this.#feeDataFunc); + } +} +class FetchUrlFeeDataNetworkPlugin extends NetworkPlugin { + #url; + #processFunc; + get url() { + return this.#url; + } + get processFunc() { + return this.#processFunc; + } + constructor(url, processFunc){ + super("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + this.#url = url; + this.#processFunc = processFunc; + } + clone() { + return this; + } +} +const Networks = new Map; +class Network { + #name; + #chainId; + #plugins; + constructor(name, chainId){ + this.#name = name; + this.#chainId = getBigInt(chainId); + this.#plugins = new Map; + } + toJSON() { + return { + name: this.name, + chainId: String(this.chainId) }; - Counter2.prototype.setValue = function(value) { - if (typeof value !== "number" || parseInt(value) != value) { - throw new Error("invalid counter value (must be an integer)"); - } - for(var index = 15; index >= 0; --index){ - this._counter[index] = value % 256; - value = value >> 8; + } + get name() { + return this.#name; + } + set name(value) { + this.#name = value; + } + get chainId() { + return this.#chainId; + } + set chainId(value) { + this.#chainId = getBigInt(value, "chainId"); + } + matches(other) { + if (other == null) { + return false; + } + if (typeof other === "string") { + try { + return this.chainId === getBigInt(other); + } catch (error) {} + return this.name === other; + } + if (typeof other === "number" || typeof other === "bigint") { + try { + return this.chainId === getBigInt(other); + } catch (error) {} + return false; + } + if (typeof other === "object") { + if (other.chainId != null) { + try { + return this.chainId === getBigInt(other.chainId); + } catch (error) {} + return false; } - }; - Counter2.prototype.setBytes = function(bytes) { - bytes = coerceArray(bytes, true); - if (bytes.length != 16) { - throw new Error("invalid counter bytes size (must be 16 bytes)"); + if (other.name != null) { + return this.name === other.name; } - this._counter = bytes; - }; - Counter2.prototype.increment = function() { - for(var i = 15; i >= 0; i--){ - if (this._counter[i] === 255) { - this._counter[i] = 0; + return false; + } + return false; + } + get plugins() { + return Array.from(this.#plugins.values()); + } + attachPlugin(plugin) { + if (this.#plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#plugins.set(plugin.name, plugin.clone()); + return this; + } + getPlugin(name) { + return this.#plugins.get(name) || null; + } + getPlugins(basename) { + return this.plugins.filter((p)=>p.name.split("#")[0] === basename); + } + clone() { + const clone = new Network(this.name, this.chainId); + this.plugins.forEach((plugin)=>{ + clone.attachPlugin(plugin.clone()); + }); + return clone; + } + computeIntrinsicGas(tx) { + const costs = this.getPlugin("org.ethers.plugins.network.GasCost") || new GasCostPlugin; + let gas = costs.txBase; + if (tx.to == null) { + gas += costs.txCreate; + } + if (tx.data) { + for(let i = 2; i < tx.data.length; i += 2){ + if (tx.data.substring(i, i + 2) === "00") { + gas += costs.txDataZero; } else { - this._counter[i]++; - break; - } - } - }; - var ModeOfOperationCTR = function(key, counter) { - if (!(this instanceof ModeOfOperationCTR)) { - throw Error("AES must be instanitated with `new`"); - } - this.description = "Counter"; - this.name = "ctr"; - if (!(counter instanceof Counter2)) { - counter = new Counter2(counter); - } - this._counter = counter; - this._remainingCounter = null; - this._remainingCounterIndex = 16; - this._aes = new AES2(key); - }; - ModeOfOperationCTR.prototype.encrypt = function(plaintext) { - var encrypted = coerceArray(plaintext, true); - for(var i = 0; i < encrypted.length; i++){ - if (this._remainingCounterIndex === 16) { - this._remainingCounter = this._aes.encrypt(this._counter._counter); - this._remainingCounterIndex = 0; - this._counter.increment(); + gas += costs.txDataNonzero; } - encrypted[i] ^= this._remainingCounter[this._remainingCounterIndex++]; } - return encrypted; - }; - ModeOfOperationCTR.prototype.decrypt = ModeOfOperationCTR.prototype.encrypt; - function pkcs7pad(data) { - data = coerceArray(data, true); - var padder = 16 - data.length % 16; - var result = createArray(data.length + padder); - copyArray(data, result); - for(var i = data.length; i < result.length; i++){ - result[i] = padder; - } - return result; } - function pkcs7strip(data) { - data = coerceArray(data, true); - if (data.length < 16) { - throw new Error("PKCS#7 invalid length"); + if (tx.accessList) { + const accessList = accessListify(tx.accessList); + for(const addr in accessList){ + gas += costs.txAccessListAddress + costs.txAccessListStorageKey * accessList[addr].storageKeys.length; } - var padder = data[data.length - 1]; - if (padder > 16) { - throw new Error("PKCS#7 padding byte out of range"); + } + return gas; + } + static from(network) { + injectCommonNetworks(); + if (network == null) { + return Network.from("mainnet"); + } + if (typeof network === "number") { + network = BigInt(network); + } + if (typeof network === "string" || typeof network === "bigint") { + const networkFunc = Networks.get(network); + if (networkFunc) { + return networkFunc(); } - var length = data.length - padder; - for(var i = 0; i < padder; i++){ - if (data[length + i] !== padder) { - throw new Error("PKCS#7 invalid padding byte"); - } + if (typeof network === "bigint") { + return new Network("unknown", network); } - var result = createArray(length); - copyArray(data, result, 0, 0, length); - return result; + assertArgument(false, "unknown network", "network", network); } - var aesjs = { - AES: AES2, - Counter: Counter2, - ModeOfOperation: { - ecb: ModeOfOperationECB, - cbc: ModeOfOperationCBC, - cfb: ModeOfOperationCFB, - ofb: ModeOfOperationOFB, - ctr: ModeOfOperationCTR - }, - utils: { - hex: convertHex, - utf8: convertUtf8 - }, - padding: { - pkcs7: { - pad: pkcs7pad, - strip: pkcs7strip - } - }, - _arrayTest: { - coerceArray, - createArray, - copyArray + if (typeof network.clone === "function") { + const clone = network.clone(); + return clone; + } + if (typeof network === "object") { + assertArgument(typeof network.name === "string" && typeof network.chainId === "number", "invalid network object name or chainId", "network", network); + const custom = new Network(network.name, network.chainId); + if (network.ensAddress || network.ensNetwork != null) { + custom.attachPlugin(new EnsPlugin(network.ensAddress, network.ensNetwork)); } - }; - { - module.exports = aesjs; + return custom; } - })(); -}); -aesJs.AES; -aesJs.Counter; -aesJs.ModeOfOperation; -aesJs._arrayTest; -aesJs.padding; -aesJs.utils; -function createCommonjsModule6(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function(path, base) { - return commonjsRequire6(path, base === void 0 || base === null ? module.path : base); + assertArgument(false, "invalid network", "network", network); + } + static register(nameOrChainId, networkFunc) { + if (typeof nameOrChainId === "number") { + nameOrChainId = BigInt(nameOrChainId); } - }, fn(module, module.exports), module.exports; + const existing = Networks.get(nameOrChainId); + if (existing) { + assertArgument(false, `conflicting network for ${JSON.stringify(existing.name)}`, "nameOrChainId", nameOrChainId); + } + Networks.set(nameOrChainId, networkFunc); + } } -function commonjsRequire6() { - throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); +function parseUnits(_value, decimals) { + const value = String(_value); + if (!value.match(/^[0-9.]+$/)) { + throw new Error(`invalid gwei value: ${_value}`); + } + const comps = value.split("."); + if (comps.length === 1) { + comps.push(""); + } + if (comps.length !== 2) { + throw new Error(`invalid gwei value: ${_value}`); + } + while(comps[1].length < decimals){ + comps[1] += "0"; + } + if (comps[1].length > 9) { + let frac = BigInt(comps[1].substring(0, 9)); + if (!comps[1].substring(9).match(/^0+$/)) { + frac++; + } + comps[1] = frac.toString(); + } + return BigInt(comps[0] + comps[1]); } -var scrypt = createCommonjsModule6(function(module, exports) { - (function(root) { - function SHA256(m) { - const K = new Uint32Array([ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 +function getGasStationPlugin(url) { + return new FetchUrlFeeDataNetworkPlugin(url, async (fetchFeeData, provider, request)=>{ + request.setHeader("User-Agent", "ethers"); + let response; + try { + const [_response, _feeData] = await Promise.all([ + request.send(), + fetchFeeData() ]); - let h0 = 1779033703, h1 = 3144134277, h2 = 1013904242, h3 = 2773480762; - let h4 = 1359893119, h5 = 2600822924, h6 = 528734635, h7 = 1541459225; - const w = new Uint32Array(64); - function blocks(p2) { - let off = 0, len = p2.length; - while(len >= 64){ - let a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7, u, i2, j, t1, t2; - for(i2 = 0; i2 < 16; i2++){ - j = off + i2 * 4; - w[i2] = (p2[j] & 255) << 24 | (p2[j + 1] & 255) << 16 | (p2[j + 2] & 255) << 8 | p2[j + 3] & 255; - } - for(i2 = 16; i2 < 64; i2++){ - u = w[i2 - 2]; - t1 = (u >>> 17 | u << 32 - 17) ^ (u >>> 19 | u << 32 - 19) ^ u >>> 10; - u = w[i2 - 15]; - t2 = (u >>> 7 | u << 32 - 7) ^ (u >>> 18 | u << 32 - 18) ^ u >>> 3; - w[i2] = (t1 + w[i2 - 7] | 0) + (t2 + w[i2 - 16] | 0) | 0; - } - for(i2 = 0; i2 < 64; i2++){ - t1 = (((e >>> 6 | e << 32 - 6) ^ (e >>> 11 | e << 32 - 11) ^ (e >>> 25 | e << 32 - 25)) + (e & f ^ ~e & g) | 0) + (h + (K[i2] + w[i2] | 0) | 0) | 0; - t2 = ((a >>> 2 | a << 32 - 2) ^ (a >>> 13 | a << 32 - 13) ^ (a >>> 22 | a << 32 - 22)) + (a & b ^ a & c ^ b & c) | 0; - h = g; - g = f; - f = e; - e = d + t1 | 0; - d = c; - c = b; - b = a; - a = t1 + t2 | 0; - } - h0 = h0 + a | 0; - h1 = h1 + b | 0; - h2 = h2 + c | 0; - h3 = h3 + d | 0; - h4 = h4 + e | 0; - h5 = h5 + f | 0; - h6 = h6 + g | 0; - h7 = h7 + h | 0; - off += 64; - len -= 64; - } - } - blocks(m); - let i, bytesLeft = m.length % 64, bitLenHi = m.length / 536870912 | 0, bitLenLo = m.length << 3, numZeros = bytesLeft < 56 ? 56 : 120, p = m.slice(m.length - bytesLeft, m.length); - p.push(128); - for(i = bytesLeft + 1; i < numZeros; i++){ - p.push(0); - } - p.push(bitLenHi >>> 24 & 255); - p.push(bitLenHi >>> 16 & 255); - p.push(bitLenHi >>> 8 & 255); - p.push(bitLenHi >>> 0 & 255); - p.push(bitLenLo >>> 24 & 255); - p.push(bitLenLo >>> 16 & 255); - p.push(bitLenLo >>> 8 & 255); - p.push(bitLenLo >>> 0 & 255); - blocks(p); - return [ - h0 >>> 24 & 255, - h0 >>> 16 & 255, - h0 >>> 8 & 255, - h0 >>> 0 & 255, - h1 >>> 24 & 255, - h1 >>> 16 & 255, - h1 >>> 8 & 255, - h1 >>> 0 & 255, - h2 >>> 24 & 255, - h2 >>> 16 & 255, - h2 >>> 8 & 255, - h2 >>> 0 & 255, - h3 >>> 24 & 255, - h3 >>> 16 & 255, - h3 >>> 8 & 255, - h3 >>> 0 & 255, - h4 >>> 24 & 255, - h4 >>> 16 & 255, - h4 >>> 8 & 255, - h4 >>> 0 & 255, - h5 >>> 24 & 255, - h5 >>> 16 & 255, - h5 >>> 8 & 255, - h5 >>> 0 & 255, - h6 >>> 24 & 255, - h6 >>> 16 & 255, - h6 >>> 8 & 255, - h6 >>> 0 & 255, - h7 >>> 24 & 255, - h7 >>> 16 & 255, - h7 >>> 8 & 255, - h7 >>> 0 & 255 - ]; + response = _response; + const payload = response.bodyJson.standard; + const feeData = { + gasPrice: _feeData.gasPrice, + maxFeePerGas: parseUnits(payload.maxFee, 9), + maxPriorityFeePerGas: parseUnits(payload.maxPriorityFee, 9) + }; + return feeData; + } catch (error) { + assert1(false, `error encountered with polygon gas station (${JSON.stringify(request.url)})`, "SERVER_ERROR", { + request: request, + response: response, + error: error + }); } - function PBKDF2_HMAC_SHA256_OneIter(password, salt, dkLen) { - password = password.length <= 64 ? password : SHA256(password); - const innerLen = 64 + salt.length + 4; - const inner = new Array(innerLen); - const outerKey = new Array(64); - let i; - let dk = []; - for(i = 0; i < 64; i++){ - inner[i] = 54; - } - for(i = 0; i < password.length; i++){ - inner[i] ^= password[i]; - } - for(i = 0; i < salt.length; i++){ - inner[64 + i] = salt[i]; - } - for(i = innerLen - 4; i < innerLen; i++){ - inner[i] = 0; - } - for(i = 0; i < 64; i++)outerKey[i] = 92; - for(i = 0; i < password.length; i++)outerKey[i] ^= password[i]; - function incrementCounter() { - for(let i2 = innerLen - 1; i2 >= innerLen - 4; i2--){ - inner[i2]++; - if (inner[i2] <= 255) return; - inner[i2] = 0; - } - } - while(dkLen >= 32){ - incrementCounter(); - dk = dk.concat(SHA256(outerKey.concat(SHA256(inner)))); - dkLen -= 32; - } - if (dkLen > 0) { - incrementCounter(); - dk = dk.concat(SHA256(outerKey.concat(SHA256(inner))).slice(0, dkLen)); - } - return dk; - } - function blockmix_salsa8(BY, Yi, r, x, _X) { - let i; - arraycopy(BY, (2 * r - 1) * 16, _X, 0, 16); - for(i = 0; i < 2 * r; i++){ - blockxor(BY, i * 16, _X, 16); - salsa20_8(_X, x); - arraycopy(_X, 0, BY, Yi + i * 16, 16); - } - for(i = 0; i < r; i++){ - arraycopy(BY, Yi + i * 2 * 16, BY, i * 16, 16); - } - for(i = 0; i < r; i++){ - arraycopy(BY, Yi + (i * 2 + 1) * 16, BY, (i + r) * 16, 16); - } - } - function R(a, b) { - return a << b | a >>> 32 - b; - } - function salsa20_8(B, x) { - arraycopy(B, 0, x, 0, 16); - for(let i = 8; i > 0; i -= 2){ - x[4] ^= R(x[0] + x[12], 7); - x[8] ^= R(x[4] + x[0], 9); - x[12] ^= R(x[8] + x[4], 13); - x[0] ^= R(x[12] + x[8], 18); - x[9] ^= R(x[5] + x[1], 7); - x[13] ^= R(x[9] + x[5], 9); - x[1] ^= R(x[13] + x[9], 13); - x[5] ^= R(x[1] + x[13], 18); - x[14] ^= R(x[10] + x[6], 7); - x[2] ^= R(x[14] + x[10], 9); - x[6] ^= R(x[2] + x[14], 13); - x[10] ^= R(x[6] + x[2], 18); - x[3] ^= R(x[15] + x[11], 7); - x[7] ^= R(x[3] + x[15], 9); - x[11] ^= R(x[7] + x[3], 13); - x[15] ^= R(x[11] + x[7], 18); - x[1] ^= R(x[0] + x[3], 7); - x[2] ^= R(x[1] + x[0], 9); - x[3] ^= R(x[2] + x[1], 13); - x[0] ^= R(x[3] + x[2], 18); - x[6] ^= R(x[5] + x[4], 7); - x[7] ^= R(x[6] + x[5], 9); - x[4] ^= R(x[7] + x[6], 13); - x[5] ^= R(x[4] + x[7], 18); - x[11] ^= R(x[10] + x[9], 7); - x[8] ^= R(x[11] + x[10], 9); - x[9] ^= R(x[8] + x[11], 13); - x[10] ^= R(x[9] + x[8], 18); - x[12] ^= R(x[15] + x[14], 7); - x[13] ^= R(x[12] + x[15], 9); - x[14] ^= R(x[13] + x[12], 13); - x[15] ^= R(x[14] + x[13], 18); - } - for(let i = 0; i < 16; ++i){ - B[i] += x[i]; - } - } - function blockxor(S, Si, D, len) { - for(let i = 0; i < len; i++){ - D[i] ^= S[Si + i]; - } - } - function arraycopy(src, srcPos, dest, destPos, length) { - while(length--){ - dest[destPos++] = src[srcPos++]; - } - } - function checkBufferish(o) { - if (!o || typeof o.length !== "number") { - return false; - } - for(let i = 0; i < o.length; i++){ - const v = o[i]; - if (typeof v !== "number" || v % 1 || v < 0 || v >= 256) { - return false; - } + }); +} +let injected = false; +function injectCommonNetworks() { + if (injected) { + return; + } + injected = true; + function registerEth(name, chainId, options) { + const func = function() { + const network = new Network(name, chainId); + if (options.ensNetwork != null) { + network.attachPlugin(new EnsPlugin(null, options.ensNetwork)); } - return true; + network.attachPlugin(new GasCostPlugin); + (options.plugins || []).forEach((plugin)=>{ + network.attachPlugin(plugin); + }); + return network; + }; + Network.register(name, func); + Network.register(chainId, func); + if (options.altNames) { + options.altNames.forEach((name)=>{ + Network.register(name, func); + }); } - function ensureInteger(value, name) { - if (typeof value !== "number" || value % 1) { - throw new Error("invalid " + name); + } + registerEth("mainnet", 1, { + ensNetwork: 1, + altNames: [ + "homestead" + ] + }); + registerEth("ropsten", 3, { + ensNetwork: 3 + }); + registerEth("rinkeby", 4, { + ensNetwork: 4 + }); + registerEth("goerli", 5, { + ensNetwork: 5 + }); + registerEth("kovan", 42, { + ensNetwork: 42 + }); + registerEth("sepolia", 11155111, { + ensNetwork: 11155111 + }); + registerEth("holesky", 17e3, { + ensNetwork: 17e3 + }); + registerEth("classic", 61, {}); + registerEth("classicKotti", 6, {}); + registerEth("arbitrum", 42161, { + ensNetwork: 1 + }); + registerEth("arbitrum-goerli", 421613, {}); + registerEth("arbitrum-sepolia", 421614, {}); + registerEth("base", 8453, { + ensNetwork: 1 + }); + registerEth("base-goerli", 84531, {}); + registerEth("base-sepolia", 84532, {}); + registerEth("bnb", 56, { + ensNetwork: 1 + }); + registerEth("bnbt", 97, {}); + registerEth("linea", 59144, { + ensNetwork: 1 + }); + registerEth("linea-goerli", 59140, {}); + registerEth("linea-sepolia", 59141, {}); + registerEth("matic", 137, { + ensNetwork: 1, + plugins: [ + getGasStationPlugin("https://gasstation.polygon.technology/v2") + ] + }); + registerEth("matic-amoy", 80002, {}); + registerEth("matic-mumbai", 80001, { + altNames: [ + "maticMumbai", + "maticmum" + ], + plugins: [ + getGasStationPlugin("https://gasstation-testnet.polygon.technology/v2") + ] + }); + registerEth("optimism", 10, { + ensNetwork: 1, + plugins: [] + }); + registerEth("optimism-goerli", 420, {}); + registerEth("optimism-sepolia", 11155420, {}); + registerEth("xdai", 100, { + ensNetwork: 1 + }); +} +function copy$2(obj) { + return JSON.parse(JSON.stringify(obj)); +} +class PollingBlockSubscriber { + #provider; + #poller; + #interval; + #blockNumber; + constructor(provider){ + this.#provider = provider; + this.#poller = null; + this.#interval = 4e3; + this.#blockNumber = -2; + } + get pollingInterval() { + return this.#interval; + } + set pollingInterval(value) { + this.#interval = value; + } + async #poll() { + try { + const blockNumber = await this.#provider.getBlockNumber(); + if (this.#blockNumber === -2) { + this.#blockNumber = blockNumber; + return; } - return value; - } - function _scrypt(password, salt, N, r, p, dkLen, callback) { - N = ensureInteger(N, "N"); - r = ensureInteger(r, "r"); - p = ensureInteger(p, "p"); - dkLen = ensureInteger(dkLen, "dkLen"); - if (N === 0 || (N & N - 1) !== 0) { - throw new Error("N must be power of 2"); - } - if (N > 2147483647 / 128 / r) { - throw new Error("N too large"); - } - if (r > 2147483647 / 128 / p) { - throw new Error("r too large"); - } - if (!checkBufferish(password)) { - throw new Error("password must be an array or buffer"); - } - password = Array.prototype.slice.call(password); - if (!checkBufferish(salt)) { - throw new Error("salt must be an array or buffer"); - } - salt = Array.prototype.slice.call(salt); - let b = PBKDF2_HMAC_SHA256_OneIter(password, salt, p * 128 * r); - const B = new Uint32Array(p * 32 * r); - for(let i = 0; i < B.length; i++){ - const j = i * 4; - B[i] = (b[j + 3] & 255) << 24 | (b[j + 2] & 255) << 16 | (b[j + 1] & 255) << 8 | (b[j + 0] & 255) << 0; - } - const XY = new Uint32Array(64 * r); - const V = new Uint32Array(32 * r * N); - const Yi = 32 * r; - const x = new Uint32Array(16); - const _X = new Uint32Array(16); - const totalOps = p * N * 2; - let currentOp = 0; - let lastPercent10 = null; - let stop = false; - let state = 0; - let i0 = 0, i1; - let Bi; - const limit = callback ? parseInt(1e3 / r) : 4294967295; - const nextTick = typeof setImmediate !== "undefined" ? setImmediate : setTimeout; - const incrementalSMix = function() { - if (stop) { - return callback(new Error("cancelled"), currentOp / totalOps); - } - let steps; - switch(state){ - case 0: - Bi = i0 * 32 * r; - arraycopy(B, Bi, XY, 0, Yi); - state = 1; - i1 = 0; - case 1: - steps = N - i1; - if (steps > limit) { - steps = limit; - } - for(let i = 0; i < steps; i++){ - arraycopy(XY, 0, V, (i1 + i) * Yi, Yi); - blockmix_salsa8(XY, Yi, r, x, _X); - } - i1 += steps; - currentOp += steps; - if (callback) { - const percent10 = parseInt(1e3 * currentOp / totalOps); - if (percent10 !== lastPercent10) { - stop = callback(null, currentOp / totalOps); - if (stop) { - break; - } - lastPercent10 = percent10; - } - } - if (i1 < N) { - break; - } - i1 = 0; - state = 2; - case 2: - steps = N - i1; - if (steps > limit) { - steps = limit; - } - for(let i = 0; i < steps; i++){ - const offset = (2 * r - 1) * 16; - const j = XY[offset] & N - 1; - blockxor(V, j * Yi, XY, Yi); - blockmix_salsa8(XY, Yi, r, x, _X); - } - i1 += steps; - currentOp += steps; - if (callback) { - const percent10 = parseInt(1e3 * currentOp / totalOps); - if (percent10 !== lastPercent10) { - stop = callback(null, currentOp / totalOps); - if (stop) { - break; - } - lastPercent10 = percent10; - } - } - if (i1 < N) { - break; - } - arraycopy(XY, 0, B, Bi, Yi); - i0++; - if (i0 < p) { - state = 0; - break; - } - b = []; - for(let i = 0; i < B.length; i++){ - b.push(B[i] >> 0 & 255); - b.push(B[i] >> 8 & 255); - b.push(B[i] >> 16 & 255); - b.push(B[i] >> 24 & 255); - } - const derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen); - if (callback) { - callback(null, 1, derivedKey); - } - return derivedKey; - } - if (callback) { - nextTick(incrementalSMix); - } - }; - if (!callback) { - while(true){ - const derivedKey = incrementalSMix(); - if (derivedKey != void 0) { - return derivedKey; + if (blockNumber !== this.#blockNumber) { + for(let b = this.#blockNumber + 1; b <= blockNumber; b++){ + if (this.#poller == null) { + return; } + await this.#provider.emit("block", b); } + this.#blockNumber = blockNumber; } - incrementalSMix(); + } catch (error) {} + if (this.#poller == null) { + return; } - const lib = { - scrypt: function(password, salt, N, r, p, dkLen, progressCallback) { - return new Promise(function(resolve, reject) { - let lastProgress = 0; - if (progressCallback) { - progressCallback(0); - } - _scrypt(password, salt, N, r, p, dkLen, function(error, progress, key) { - if (error) { - reject(error); - } else if (key) { - if (progressCallback && lastProgress !== 1) { - progressCallback(1); - } - resolve(new Uint8Array(key)); - } else if (progressCallback && progress !== lastProgress) { - lastProgress = progress; - return progressCallback(progress); - } - }); - }); - }, - syncScrypt: function(password, salt, N, r, p, dkLen) { - return new Uint8Array(_scrypt(password, salt, N, r, p, dkLen)); - } - }; - { - module.exports = lib; + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + } + start() { + if (this.#poller) { + return; } - })(); -}); -scrypt.scrypt; -scrypt.syncScrypt; -const version19 = "json-wallets/5.7.0"; -function looseArrayify(hexString) { - if (typeof hexString === "string" && hexString.substring(0, 2) !== "0x") { - hexString = "0x" + hexString; + this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval); + this.#poll(); + } + stop() { + if (!this.#poller) { + return; + } + this.#provider._clearTimeout(this.#poller); + this.#poller = null; + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } + } + resume() { + this.start(); } - return arrayify(hexString); } -function zpad(value, length) { - value = String(value); - while(value.length < length){ - value = "0" + value; +class OnBlockSubscriber { + #provider; + #poll; + #running; + constructor(provider){ + this.#provider = provider; + this.#running = false; + this.#poll = (blockNumber)=>{ + this._poll(blockNumber, this.#provider); + }; + } + async _poll(blockNumber, provider) { + throw new Error("sub-classes must override this"); + } + start() { + if (this.#running) { + return; + } + this.#running = true; + this.#poll(-2); + this.#provider.on("block", this.#poll); + } + stop() { + if (!this.#running) { + return; + } + this.#running = false; + this.#provider.off("block", this.#poll); + } + pause(dropWhilePaused) { + this.stop(); + } + resume() { + this.start(); } - return value; } -function getPassword(password) { - if (typeof password === "string") { - return toUtf8Bytes(password, UnicodeNormalizationForm.NFKC); - } - return arrayify(password); -} -function searchPath(object, path) { - let currentChild = object; - const comps = path.toLowerCase().split("/"); - for(let i = 0; i < comps.length; i++){ - let matchingChild = null; - for(const key in currentChild){ - if (key.toLowerCase() === comps[i]) { - matchingChild = currentChild[key]; - break; - } +class PollingBlockTagSubscriber extends OnBlockSubscriber { + #tag; + #lastBlock; + constructor(provider, tag){ + super(provider); + this.#tag = tag; + this.#lastBlock = -2; + } + pause(dropWhilePaused) { + if (dropWhilePaused) { + this.#lastBlock = -2; } - if (matchingChild === null) { - return null; + super.pause(dropWhilePaused); + } + async _poll(blockNumber, provider) { + const block = await provider.getBlock(this.#tag); + if (block == null) { + return; + } + if (this.#lastBlock === -2) { + this.#lastBlock = block.number; + } else if (block.number > this.#lastBlock) { + provider.emit(this.#tag, block.number); + this.#lastBlock = block.number; } - currentChild = matchingChild; } - return currentChild; } -function uuidV4(randomBytes2) { - const bytes2 = arrayify(randomBytes2); - bytes2[6] = bytes2[6] & 15 | 64; - bytes2[8] = bytes2[8] & 63 | 128; - const value = hexlify(bytes2); - return [ - value.substring(2, 10), - value.substring(10, 14), - value.substring(14, 18), - value.substring(18, 22), - value.substring(22, 34) - ].join("-"); +class PollingOrphanSubscriber extends OnBlockSubscriber { + #filter; + constructor(provider, filter){ + super(provider); + this.#filter = copy$2(filter); + } + async _poll(blockNumber, provider) { + throw new Error("@TODO"); + } } -const logger217 = new Logger(version19); -class CrowdsaleAccount extends Description { - isCrowdsaleAccount(value) { - return !!(value && value._isCrowdsaleAccount); +class PollingTransactionSubscriber extends OnBlockSubscriber { + #hash; + constructor(provider, hash){ + super(provider); + this.#hash = hash; + } + async _poll(blockNumber, provider) { + const tx = await provider.getTransactionReceipt(this.#hash); + if (tx) { + provider.emit(this.#hash, tx); + } } } -function decrypt(json, password) { - const data = JSON.parse(json); - password = getPassword(password); - const ethaddr = getAddress(searchPath(data, "ethaddr")); - const encseed = looseArrayify(searchPath(data, "encseed")); - if (!encseed || encseed.length % 16 !== 0) { - logger217.throwArgumentError("invalid encseed", "json", json); +class PollingEventSubscriber { + #provider; + #filter; + #poller; + #running; + #blockNumber; + constructor(provider, filter){ + this.#provider = provider; + this.#filter = copy$2(filter); + this.#poller = this.#poll.bind(this); + this.#running = false; + this.#blockNumber = -2; } - const key = arrayify(pbkdf2(password, password, 2e3, 32, "sha256")).slice(0, 16); - const iv = encseed.slice(0, 16); - const encryptedSeed = encseed.slice(16); - const aesCbc = new aesJs.ModeOfOperation.cbc(key, iv); - const seed = aesJs.padding.pkcs7.strip(arrayify(aesCbc.decrypt(encryptedSeed))); - let seedHex = ""; - for(let i = 0; i < seed.length; i++){ - seedHex += String.fromCharCode(seed[i]); + async #poll(blockNumber) { + if (this.#blockNumber === -2) { + return; + } + const filter = copy$2(this.#filter); + filter.fromBlock = this.#blockNumber + 1; + filter.toBlock = blockNumber; + const logs = await this.#provider.getLogs(filter); + if (logs.length === 0) { + if (this.#blockNumber < blockNumber - 60) { + this.#blockNumber = blockNumber - 60; + } + return; + } + for (const log of logs){ + this.#provider.emit(this.#filter, log); + this.#blockNumber = log.blockNumber; + } + } + start() { + if (this.#running) { + return; + } + this.#running = true; + if (this.#blockNumber === -2) { + this.#provider.getBlockNumber().then((blockNumber)=>{ + this.#blockNumber = blockNumber; + }); + } + this.#provider.on("block", this.#poller); + } + stop() { + if (!this.#running) { + return; + } + this.#running = false; + this.#provider.off("block", this.#poller); + } + pause(dropWhilePaused) { + this.stop(); + if (dropWhilePaused) { + this.#blockNumber = -2; + } } - const seedHexBytes = toUtf8Bytes(seedHex); - const privateKey = keccak256(seedHexBytes); - return new CrowdsaleAccount({ - _isCrowdsaleAccount: true, - address: ethaddr, - privateKey + resume() { + this.start(); + } +} +const BN_2$1 = BigInt(2); +function isPromise$1(value) { + return value && typeof value.then === "function"; +} +function getTag(prefix, value) { + return prefix + ":" + JSON.stringify(value, (k, v)=>{ + if (v == null) { + return "null"; + } + if (typeof v === "bigint") { + return `bigint:${v.toString()}`; + } + if (typeof v === "string") { + return v.toLowerCase(); + } + if (typeof v === "object" && !Array.isArray(v)) { + const keys = Object.keys(v); + keys.sort(); + return keys.reduce((accum, key)=>{ + accum[key] = v[key]; + return accum; + }, {}); + } + return v; }); } -function isCrowdsaleWallet(json) { - let data = null; - try { - data = JSON.parse(json); - } catch (error) { - return false; +class UnmanagedSubscriber { + name; + constructor(name){ + defineProperties(this, { + name: name + }); } - return data.encseed && data.ethaddr; + start() {} + stop() {} + pause(dropWhilePaused) {} + resume() {} } -function isKeystoreWallet(json) { - let data = null; - try { - data = JSON.parse(json); - } catch (error) { - return false; +function copy$1(value) { + return JSON.parse(JSON.stringify(value)); +} +function concisify(items) { + items = Array.from(new Set(items).values()); + items.sort(); + return items; +} +async function getSubscription(_event, provider) { + if (_event == null) { + throw new Error("invalid event"); } - if (!data.version || parseInt(data.version) !== data.version || parseInt(data.version) !== 3) { - return false; + if (Array.isArray(_event)) { + _event = { + topics: _event + }; } - return true; -} -function getJsonWalletAddress(json) { - if (isCrowdsaleWallet(json)) { - try { - return getAddress(JSON.parse(json).ethaddr); - } catch (error) { - return null; + if (typeof _event === "string") { + switch(_event){ + case "block": + case "debug": + case "error": + case "finalized": + case "network": + case "pending": + case "safe": + { + return { + type: _event, + tag: _event + }; + } } } - if (isKeystoreWallet(json)) { - try { - return getAddress(JSON.parse(json).address); - } catch (error) { - return null; + if (isHexString(_event, 32)) { + const hash = _event.toLowerCase(); + return { + type: "transaction", + tag: getTag("tx", { + hash: hash + }), + hash: hash + }; + } + if (_event.orphan) { + const event = _event; + return { + type: "orphan", + tag: getTag("orphan", event), + filter: copy$1(event) + }; + } + if (_event.address || _event.topics) { + const event = _event; + const filter = { + topics: (event.topics || []).map((t)=>{ + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t)=>t.toLowerCase())); + } + return t.toLowerCase(); + }) + }; + if (event.address) { + const addresses = []; + const promises = []; + const addAddress = (addr)=>{ + if (isHexString(addr)) { + addresses.push(addr); + } else { + promises.push((async ()=>{ + addresses.push(await resolveAddress(addr, provider)); + })()); + } + }; + if (Array.isArray(event.address)) { + event.address.forEach(addAddress); + } else { + addAddress(event.address); + } + if (promises.length) { + await Promise.all(promises); + } + filter.address = concisify(addresses.map((a)=>a.toLowerCase())); } + return { + filter: filter, + tag: getTag("event", filter), + type: "event" + }; } - return null; + assertArgument(false, "unknown ProviderEvent", "event", _event); } -var __awaiter5 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); +function getTime$1() { + return (new Date).getTime(); +} +const defaultOptions$1 = { + cacheTimeout: 250, + pollingInterval: 4e3 +}; +class AbstractProvider { + #subs; + #plugins; + #pausedState; + #destroyed; + #networkPromise; + #anyNetwork; + #performCache; + #lastBlockNumber; + #nextTimer; + #timers; + #disableCcipRead; + #options; + constructor(_network, options){ + this.#options = Object.assign({}, defaultOptions$1, options || {}); + if (_network === "any") { + this.#anyNetwork = true; + this.#networkPromise = null; + } else if (_network) { + const network = Network.from(_network); + this.#anyNetwork = false; + this.#networkPromise = Promise.resolve(network); + setTimeout(()=>{ + this.emit("network", network, null); + }, 0); + } else { + this.#anyNetwork = false; + this.#networkPromise = null; + } + this.#lastBlockNumber = -1; + this.#performCache = new Map; + this.#subs = new Map; + this.#plugins = new Map; + this.#pausedState = null; + this.#destroyed = false; + this.#nextTimer = 1; + this.#timers = new Map; + this.#disableCcipRead = false; } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + get pollingInterval() { + return this.#options.pollingInterval; + } + get provider() { + return this; + } + get plugins() { + return Array.from(this.#plugins.values()); + } + attachPlugin(plugin) { + if (this.#plugins.get(plugin.name)) { + throw new Error(`cannot replace existing plugin: ${plugin.name} `); + } + this.#plugins.set(plugin.name, plugin.connect(this)); + return this; + } + getPlugin(name) { + return this.#plugins.get(name) || null; + } + get disableCcipRead() { + return this.#disableCcipRead; + } + set disableCcipRead(value) { + this.#disableCcipRead = !!value; + } + async #perform(req) { + const timeout = this.#options.cacheTimeout; + if (timeout < 0) { + return await this._perform(req); + } + const tag = getTag(req.method, req); + let perform = this.#performCache.get(tag); + if (!perform) { + perform = this._perform(req); + this.#performCache.set(tag, perform); + setTimeout(()=>{ + if (this.#performCache.get(tag) === perform) { + this.#performCache.delete(tag); + } + }, timeout); } - function rejected(value) { + return await perform; + } + async ccipReadFetch(tx, calldata, urls) { + if (this.disableCcipRead || urls.length === 0 || tx.to == null) { + return null; + } + const sender = tx.to.toLowerCase(); + const data = calldata.toLowerCase(); + const errorMessages = []; + for(let i = 0; i < urls.length; i++){ + const url = urls[i]; + const href = url.replace("{sender}", sender).replace("{data}", data); + const request = new FetchRequest(href); + if (url.indexOf("{data}") === -1) { + request.body = { + data: data, + sender: sender + }; + } + this.emit("debug", { + action: "sendCcipReadFetchRequest", + request: request, + index: i, + urls: urls + }); + let errorMessage = "unknown error"; + let resp; try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + resp = await request.send(); + } catch (error) { + errorMessages.push(error.message); + this.emit("debug", { + action: "receiveCcipReadFetchError", + request: request, + result: { + error: error + } + }); + continue; } + try { + const result = resp.bodyJson; + if (result.data) { + this.emit("debug", { + action: "receiveCcipReadFetchResult", + request: request, + result: result + }); + return result.data; + } + if (result.message) { + errorMessage = result.message; + } + this.emit("debug", { + action: "receiveCcipReadFetchError", + request: request, + result: result + }); + } catch (error) {} + assert1(resp.statusCode < 400 || resp.statusCode >= 500, `response not found during CCIP fetch: ${errorMessage}`, "OFFCHAIN_FAULT", { + reason: "404_MISSING_RESOURCE", + transaction: tx, + info: { + url: url, + errorMessage: errorMessage + } + }); + errorMessages.push(errorMessage); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger$13 = new Logger(version19); -function hasMnemonic(value) { - return value != null && value.mnemonic && value.mnemonic.phrase; -} -class KeystoreAccount extends Description { - isKeystoreAccount(value) { - return !!(value && value._isKeystoreAccount); + assert1(false, `error encountered during CCIP fetch: ${errorMessages.map((m)=>JSON.stringify(m)).join(", ")}`, "OFFCHAIN_FAULT", { + reason: "500_SERVER_ERROR", + transaction: tx, + info: { + urls: urls, + errorMessages: errorMessages + } + }); } -} -function _decrypt(data, key, ciphertext) { - const cipher = searchPath(data, "crypto/cipher"); - if (cipher === "aes-128-ctr") { - const iv = looseArrayify(searchPath(data, "crypto/cipherparams/iv")); - const counter = new aesJs.Counter(iv); - const aesCtr = new aesJs.ModeOfOperation.ctr(key, counter); - return arrayify(aesCtr.decrypt(ciphertext)); + _wrapBlock(value, network) { + return new Block(formatBlock(value), this); } - return null; -} -function _getAccount(data, key) { - const ciphertext = looseArrayify(searchPath(data, "crypto/ciphertext")); - const computedMAC = hexlify(keccak256(concat([ - key.slice(16, 32), - ciphertext - ]))).substring(2); - if (computedMAC !== searchPath(data, "crypto/mac").toLowerCase()) { - throw new Error("invalid password"); + _wrapLog(value, network) { + return new Log(formatLog(value), this); + } + _wrapTransactionReceipt(value, network) { + return new TransactionReceipt(formatTransactionReceipt(value), this); } - const privateKey = _decrypt(data, key.slice(0, 16), ciphertext); - if (!privateKey) { - logger$13.throwError("unsupported cipher", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "decrypt" + _wrapTransactionResponse(tx, network) { + return new TransactionResponse(formatTransactionResponse(tx), this); + } + _detectNetwork() { + assert1(false, "sub-classes must implement this", "UNSUPPORTED_OPERATION", { + operation: "_detectNetwork" }); } - const mnemonicKey = key.slice(32, 64); - const address2 = computeAddress(privateKey); - if (data.address) { - let check = data.address.toLowerCase(); - if (check.substring(0, 2) !== "0x") { - check = "0x" + check; + async _perform(req) { + assert1(false, `unsupported method: ${req.method}`, "UNSUPPORTED_OPERATION", { + operation: req.method, + info: req + }); + } + async getBlockNumber() { + const blockNumber = getNumber(await this.#perform({ + method: "getBlockNumber" + }), "%response"); + if (this.#lastBlockNumber >= 0) { + this.#lastBlockNumber = blockNumber; + } + return blockNumber; + } + _getAddress(address) { + return resolveAddress(address, this); + } + _getBlockTag(blockTag) { + if (blockTag == null) { + return "latest"; + } + switch(blockTag){ + case "earliest": + return "0x0"; + case "finalized": + case "latest": + case "pending": + case "safe": + return blockTag; } - if (getAddress(check) !== address2) { - throw new Error("address mismatch"); + if (isHexString(blockTag)) { + if (isHexString(blockTag, 32)) { + return blockTag; + } + return toQuantity(blockTag); } - } - const account = { - _isKeystoreAccount: true, - address: address2, - privateKey: hexlify(privateKey) - }; - if (searchPath(data, "x-ethers/version") === "0.1") { - const mnemonicCiphertext = looseArrayify(searchPath(data, "x-ethers/mnemonicCiphertext")); - const mnemonicIv = looseArrayify(searchPath(data, "x-ethers/mnemonicCounter")); - const mnemonicCounter = new aesJs.Counter(mnemonicIv); - const mnemonicAesCtr = new aesJs.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter); - const path = searchPath(data, "x-ethers/path") || defaultPath; - const locale = searchPath(data, "x-ethers/locale") || "en"; - const entropy = arrayify(mnemonicAesCtr.decrypt(mnemonicCiphertext)); - try { - const mnemonic = entropyToMnemonic(entropy, locale); - const node = HDNode.fromMnemonic(mnemonic, null, locale).derivePath(path); - if (node.privateKey != account.privateKey) { - throw new Error("mnemonic mismatch"); + if (typeof blockTag === "bigint") { + blockTag = getNumber(blockTag, "blockTag"); + } + if (typeof blockTag === "number") { + if (blockTag >= 0) { + return toQuantity(blockTag); } - account.mnemonic = node.mnemonic; - } catch (error) { - if (error.code !== Logger.errors.INVALID_ARGUMENT || error.argument !== "wordlist") { - throw error; + if (this.#lastBlockNumber >= 0) { + return toQuantity(this.#lastBlockNumber + blockTag); } + return this.getBlockNumber().then((b)=>toQuantity(b + blockTag)); } + assertArgument(false, "invalid blockTag", "blockTag", blockTag); } - return new KeystoreAccount(account); -} -function pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc) { - return arrayify(pbkdf2(passwordBytes, salt, count, dkLen, prfFunc)); -} -function pbkdf22(passwordBytes, salt, count, dkLen, prfFunc) { - return Promise.resolve(pbkdf2Sync(passwordBytes, salt, count, dkLen, prfFunc)); -} -function _computeKdfKey(data, password, pbkdf2Func, scryptFunc, progressCallback) { - const passwordBytes = getPassword(password); - const kdf = searchPath(data, "crypto/kdf"); - if (kdf && typeof kdf === "string") { - const throwError = function(name, value) { - return logger$13.throwArgumentError("invalid key-derivation function parameters", name, value); - }; - if (kdf.toLowerCase() === "scrypt") { - const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt")); - const N = parseInt(searchPath(data, "crypto/kdfparams/n")); - const r = parseInt(searchPath(data, "crypto/kdfparams/r")); - const p = parseInt(searchPath(data, "crypto/kdfparams/p")); - if (!N || !r || !p) { - throwError("kdf", kdf); + _getFilter(filter) { + const topics = (filter.topics || []).map((t)=>{ + if (t == null) { + return null; + } + if (Array.isArray(t)) { + return concisify(t.map((t)=>t.toLowerCase())); } - if ((N & N - 1) !== 0) { - throwError("N", N); + return t.toLowerCase(); + }); + const blockHash = "blockHash" in filter ? filter.blockHash : undefined; + const resolve = (_address, fromBlock, toBlock)=>{ + let address = undefined; + switch(_address.length){ + case 0: + break; + case 1: + address = _address[0]; + break; + default: + _address.sort(); + address = _address; + } + if (blockHash) { + if (fromBlock != null || toBlock != null) { + throw new Error("invalid filter"); + } } - const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen")); - if (dkLen !== 32) { - throwError("dklen", dkLen); + const filter = {}; + if (address) { + filter.address = address; } - return scryptFunc(passwordBytes, salt, N, r, p, 64, progressCallback); - } else if (kdf.toLowerCase() === "pbkdf2") { - const salt = looseArrayify(searchPath(data, "crypto/kdfparams/salt")); - let prfFunc = null; - const prf = searchPath(data, "crypto/kdfparams/prf"); - if (prf === "hmac-sha256") { - prfFunc = "sha256"; - } else if (prf === "hmac-sha512") { - prfFunc = "sha512"; + if (topics.length) { + filter.topics = topics; + } + if (fromBlock) { + filter.fromBlock = fromBlock; + } + if (toBlock) { + filter.toBlock = toBlock; + } + if (blockHash) { + filter.blockHash = blockHash; + } + return filter; + }; + let address = []; + if (filter.address) { + if (Array.isArray(filter.address)) { + for (const addr of filter.address){ + address.push(this._getAddress(addr)); + } + } else { + address.push(this._getAddress(filter.address)); + } + } + let fromBlock = undefined; + if ("fromBlock" in filter) { + fromBlock = this._getBlockTag(filter.fromBlock); + } + let toBlock = undefined; + if ("toBlock" in filter) { + toBlock = this._getBlockTag(filter.toBlock); + } + if (address.filter((a)=>typeof a !== "string").length || fromBlock != null && typeof fromBlock !== "string" || toBlock != null && typeof toBlock !== "string") { + return Promise.all([ + Promise.all(address), + fromBlock, + toBlock + ]).then((result)=>{ + return resolve(result[0], result[1], result[2]); + }); + } + return resolve(address, fromBlock, toBlock); + } + _getTransactionRequest(_request) { + const request = copyRequest(_request); + const promises = []; + [ + "to", + "from" + ].forEach((key)=>{ + if (request[key] == null) { + return; + } + const addr = resolveAddress(request[key], this); + if (isPromise$1(addr)) { + promises.push(async function() { + request[key] = await addr; + }()); } else { - throwError("prf", prf); + request[key] = addr; } - const count = parseInt(searchPath(data, "crypto/kdfparams/c")); - const dkLen = parseInt(searchPath(data, "crypto/kdfparams/dklen")); - if (dkLen !== 32) { - throwError("dklen", dkLen); + }); + if (request.blockTag != null) { + const blockTag = this._getBlockTag(request.blockTag); + if (isPromise$1(blockTag)) { + promises.push(async function() { + request.blockTag = await blockTag; + }()); + } else { + request.blockTag = blockTag; } - return pbkdf2Func(passwordBytes, salt, count, dkLen, prfFunc); } + if (promises.length) { + return async function() { + await Promise.all(promises); + return request; + }(); + } + return request; } - return logger$13.throwArgumentError("unsupported key-derivation function", "kdf", kdf); -} -function decryptSync(json, password) { - const data = JSON.parse(json); - const key = _computeKdfKey(data, password, pbkdf2Sync, scrypt.syncScrypt); - return _getAccount(data, key); -} -function decrypt$1(json, password, progressCallback) { - return __awaiter5(this, void 0, void 0, function*() { - const data = JSON.parse(json); - const key = yield _computeKdfKey(data, password, pbkdf22, scrypt.scrypt, progressCallback); - return _getAccount(data, key); - }); -} -function encrypt(account, password, options, progressCallback) { - try { - if (getAddress(account.address) !== computeAddress(account.privateKey)) { - throw new Error("address/privateKey mismatch"); + async getNetwork() { + if (this.#networkPromise == null) { + const detectNetwork = (async ()=>{ + try { + const network = await this._detectNetwork(); + this.emit("network", network, null); + return network; + } catch (error) { + if (this.#networkPromise === detectNetwork) { + this.#networkPromise = null; + } + throw error; + } + })(); + this.#networkPromise = detectNetwork; + return (await detectNetwork).clone(); } - if (hasMnemonic(account)) { - const mnemonic = account.mnemonic; - const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path || defaultPath); - if (node.privateKey != account.privateKey) { - throw new Error("mnemonic mismatch"); + const networkPromise = this.#networkPromise; + const [expected, actual] = await Promise.all([ + networkPromise, + this._detectNetwork() + ]); + if (expected.chainId !== actual.chainId) { + if (this.#anyNetwork) { + this.emit("network", actual, expected); + if (this.#networkPromise === networkPromise) { + this.#networkPromise = Promise.resolve(actual); + } + } else { + assert1(false, `network changed: ${expected.chainId} => ${actual.chainId} `, "NETWORK_ERROR", { + event: "changed" + }); } } - } catch (e) { - return Promise.reject(e); - } - if (typeof options === "function" && !progressCallback) { - progressCallback = options; - options = {}; + return expected.clone(); } - if (!options) { - options = {}; + async getFeeData() { + const network = await this.getNetwork(); + const getFeeDataFunc = async ()=>{ + const { _block, gasPrice, priorityFee } = await resolveProperties({ + _block: this.#getBlock("latest", false), + gasPrice: (async ()=>{ + try { + const value = await this.#perform({ + method: "getGasPrice" + }); + return getBigInt(value, "%response"); + } catch (error) {} + return null; + })(), + priorityFee: (async ()=>{ + try { + const value = await this.#perform({ + method: "getPriorityFee" + }); + return getBigInt(value, "%response"); + } catch (error) {} + return null; + })() + }); + let maxFeePerGas = null; + let maxPriorityFeePerGas = null; + const block = this._wrapBlock(_block, network); + if (block && block.baseFeePerGas) { + maxPriorityFeePerGas = priorityFee != null ? priorityFee : BigInt("1000000000"); + maxFeePerGas = block.baseFeePerGas * BN_2$1 + maxPriorityFeePerGas; + } + return new FeeData(gasPrice, maxFeePerGas, maxPriorityFeePerGas); + }; + const plugin = network.getPlugin("org.ethers.plugins.network.FetchUrlFeeDataPlugin"); + if (plugin) { + const req = new FetchRequest(plugin.url); + const feeData = await plugin.processFunc(getFeeDataFunc, this, req); + return new FeeData(feeData.gasPrice, feeData.maxFeePerGas, feeData.maxPriorityFeePerGas); + } + return await getFeeDataFunc(); + } + async estimateGas(_tx) { + let tx = this._getTransactionRequest(_tx); + if (isPromise$1(tx)) { + tx = await tx; + } + return getBigInt(await this.#perform({ + method: "estimateGas", + transaction: tx + }), "%response"); + } + async #call(tx, blockTag, attempt) { + assert1(attempt < 10, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", { + reason: "TOO_MANY_REDIRECTS", + transaction: Object.assign({}, tx, { + blockTag: blockTag, + enableCcipRead: true + }) + }); + const transaction = copyRequest(tx); + try { + return hexlify(await this._perform({ + method: "call", + transaction: transaction, + blockTag: blockTag + })); + } catch (error) { + if (!this.disableCcipRead && isCallException(error) && error.data && attempt >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error.data, 0, 4) === "0x556f1830") { + const data = error.data; + const txSender = await resolveAddress(transaction.to, this); + let ccipArgs; + try { + ccipArgs = parseOffchainLookup(dataSlice(error.data, 4)); + } catch (error) { + assert1(false, error.message, "OFFCHAIN_FAULT", { + reason: "BAD_DATA", + transaction: transaction, + info: { + data: data + } + }); + } + assert1(ccipArgs.sender.toLowerCase() === txSender.toLowerCase(), "CCIP Read sender mismatch", "CALL_EXCEPTION", { + action: "call", + data: data, + reason: "OffchainLookup", + transaction: transaction, + invocation: null, + revert: { + signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", + name: "OffchainLookup", + args: ccipArgs.errorArgs + } + }); + const ccipResult = await this.ccipReadFetch(transaction, ccipArgs.calldata, ccipArgs.urls); + assert1(ccipResult != null, "CCIP Read failed to fetch data", "OFFCHAIN_FAULT", { + reason: "FETCH_FAILED", + transaction: transaction, + info: { + data: error.data, + errorArgs: ccipArgs.errorArgs + } + }); + const tx = { + to: txSender, + data: concat([ + ccipArgs.selector, + encodeBytes([ + ccipResult, + ccipArgs.extraData + ]) + ]) + }; + this.emit("debug", { + action: "sendCcipReadCall", + transaction: tx + }); + try { + const result = await this.#call(tx, blockTag, attempt + 1); + this.emit("debug", { + action: "receiveCcipReadCallResult", + transaction: Object.assign({}, tx), + result: result + }); + return result; + } catch (error) { + this.emit("debug", { + action: "receiveCcipReadCallError", + transaction: Object.assign({}, tx), + error: error + }); + throw error; + } + } + throw error; + } } - const privateKey = arrayify(account.privateKey); - const passwordBytes = getPassword(password); - let entropy = null; - let path = null; - let locale = null; - if (hasMnemonic(account)) { - const srcMnemonic = account.mnemonic; - entropy = arrayify(mnemonicToEntropy(srcMnemonic.phrase, srcMnemonic.locale || "en")); - path = srcMnemonic.path || defaultPath; - locale = srcMnemonic.locale || "en"; - } - let client = options.client; - if (!client) { - client = "ethers.js"; - } - let salt = null; - if (options.salt) { - salt = arrayify(options.salt); - } else { - salt = randomBytes(32); + async #checkNetwork(promise) { + const { value } = await resolveProperties({ + network: this.getNetwork(), + value: promise + }); + return value; } - let iv = null; - if (options.iv) { - iv = arrayify(options.iv); - if (iv.length !== 16) { - throw new Error("invalid iv"); + async call(_tx) { + const { tx, blockTag } = await resolveProperties({ + tx: this._getTransactionRequest(_tx), + blockTag: this._getBlockTag(_tx.blockTag) + }); + return await this.#checkNetwork(this.#call(tx, blockTag, _tx.enableCcipRead ? 0 : -1)); + } + async #getAccountValue(request, _address, _blockTag) { + let address = this._getAddress(_address); + let blockTag = this._getBlockTag(_blockTag); + if (typeof address !== "string" || typeof blockTag !== "string") { + [address, blockTag] = await Promise.all([ + address, + blockTag + ]); } - } else { - iv = randomBytes(16); - } - let uuidRandom = null; - if (options.uuid) { - uuidRandom = arrayify(options.uuid); - if (uuidRandom.length !== 16) { - throw new Error("invalid uuid"); + return await this.#checkNetwork(this.#perform(Object.assign(request, { + address: address, + blockTag: blockTag + }))); + } + async getBalance(address, blockTag) { + return getBigInt(await this.#getAccountValue({ + method: "getBalance" + }, address, blockTag), "%response"); + } + async getTransactionCount(address, blockTag) { + return getNumber(await this.#getAccountValue({ + method: "getTransactionCount" + }, address, blockTag), "%response"); + } + async getCode(address, blockTag) { + return hexlify(await this.#getAccountValue({ + method: "getCode" + }, address, blockTag)); + } + async getStorage(address, _position, blockTag) { + const position = getBigInt(_position, "position"); + return hexlify(await this.#getAccountValue({ + method: "getStorage", + position: position + }, address, blockTag)); + } + async broadcastTransaction(signedTx) { + const { blockNumber, hash, network } = await resolveProperties({ + blockNumber: this.getBlockNumber(), + hash: this._perform({ + method: "broadcastTransaction", + signedTransaction: signedTx + }), + network: this.getNetwork() + }); + const tx = Transaction.from(signedTx); + if (tx.hash !== hash) { + throw new Error("@TODO: the returned hash did not match"); + } + return this._wrapTransactionResponse(tx, network).replaceableTransaction(blockNumber); + } + async #getBlock(block, includeTransactions) { + if (isHexString(block, 32)) { + return await this.#perform({ + method: "getBlock", + blockHash: block, + includeTransactions: includeTransactions + }); } - } else { - uuidRandom = randomBytes(16); - } - let N = 1 << 17, r = 8, p = 1; - if (options.scrypt) { - if (options.scrypt.N) { - N = options.scrypt.N; + let blockTag = this._getBlockTag(block); + if (typeof blockTag !== "string") { + blockTag = await blockTag; } - if (options.scrypt.r) { - r = options.scrypt.r; + return await this.#perform({ + method: "getBlock", + blockTag: blockTag, + includeTransactions: includeTransactions + }); + } + async getBlock(block, prefetchTxs) { + const { network, params } = await resolveProperties({ + network: this.getNetwork(), + params: this.#getBlock(block, !!prefetchTxs) + }); + if (params == null) { + return null; } - if (options.scrypt.p) { - p = options.scrypt.p; + return this._wrapBlock(params, network); + } + async getTransaction(hash) { + const { network, params } = await resolveProperties({ + network: this.getNetwork(), + params: this.#perform({ + method: "getTransaction", + hash: hash + }) + }); + if (params == null) { + return null; } + return this._wrapTransactionResponse(params, network); } - return scrypt.scrypt(passwordBytes, salt, N, r, p, 64, progressCallback).then((key)=>{ - key = arrayify(key); - const derivedKey = key.slice(0, 16); - const macPrefix = key.slice(16, 32); - const mnemonicKey = key.slice(32, 64); - const counter = new aesJs.Counter(iv); - const aesCtr = new aesJs.ModeOfOperation.ctr(derivedKey, counter); - const ciphertext = arrayify(aesCtr.encrypt(privateKey)); - const mac = keccak256(concat([ - macPrefix, - ciphertext - ])); - const data = { - address: account.address.substring(2).toLowerCase(), - id: uuidV4(uuidRandom), - version: 3, - crypto: { - cipher: "aes-128-ctr", - cipherparams: { - iv: hexlify(iv).substring(2) - }, - ciphertext: hexlify(ciphertext).substring(2), - kdf: "scrypt", - kdfparams: { - salt: hexlify(salt).substring(2), - n: N, - dklen: 32, - p, - r - }, - mac: mac.substring(2) + async getTransactionReceipt(hash) { + const { network, params } = await resolveProperties({ + network: this.getNetwork(), + params: this.#perform({ + method: "getTransactionReceipt", + hash: hash + }) + }); + if (params == null) { + return null; + } + if (params.gasPrice == null && params.effectiveGasPrice == null) { + const tx = await this.#perform({ + method: "getTransaction", + hash: hash + }); + if (tx == null) { + throw new Error("report this; could not find tx or effectiveGasPrice"); } - }; - if (entropy) { - const mnemonicIv = randomBytes(16); - const mnemonicCounter = new aesJs.Counter(mnemonicIv); - const mnemonicAesCtr = new aesJs.ModeOfOperation.ctr(mnemonicKey, mnemonicCounter); - const mnemonicCiphertext = arrayify(mnemonicAesCtr.encrypt(entropy)); - const now = new Date(); - const timestamp = now.getUTCFullYear() + "-" + zpad(now.getUTCMonth() + 1, 2) + "-" + zpad(now.getUTCDate(), 2) + "T" + zpad(now.getUTCHours(), 2) + "-" + zpad(now.getUTCMinutes(), 2) + "-" + zpad(now.getUTCSeconds(), 2) + ".0Z"; - data["x-ethers"] = { - client, - gethFilename: "UTC--" + timestamp + "--" + data.address, - mnemonicCounter: hexlify(mnemonicIv).substring(2), - mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2), - path, - locale, - version: "0.1" - }; + params.effectiveGasPrice = tx.gasPrice; } - return JSON.stringify(data); - }); -} -function decryptJsonWallet(json, password, progressCallback) { - if (isCrowdsaleWallet(json)) { - if (progressCallback) { - progressCallback(0); + return this._wrapTransactionReceipt(params, network); + } + async getTransactionResult(hash) { + const { result } = await resolveProperties({ + network: this.getNetwork(), + result: this.#perform({ + method: "getTransactionResult", + hash: hash + }) + }); + if (result == null) { + return null; } - const account = decrypt(json, password); - if (progressCallback) { - progressCallback(1); + return hexlify(result); + } + async getLogs(_filter) { + let filter = this._getFilter(_filter); + if (isPromise$1(filter)) { + filter = await filter; } - return Promise.resolve(account); + const { network, params } = await resolveProperties({ + network: this.getNetwork(), + params: this.#perform({ + method: "getLogs", + filter: filter + }) + }); + return params.map((p)=>this._wrapLog(p, network)); } - if (isKeystoreWallet(json)) { - return decrypt$1(json, password, progressCallback); + _getProvider(chainId) { + assert1(false, "provider cannot connect to target network", "UNSUPPORTED_OPERATION", { + operation: "_getProvider()" + }); } - return Promise.reject(new Error("invalid JSON wallet")); -} -function decryptJsonWalletSync(json, password) { - if (isCrowdsaleWallet(json)) { - return decrypt(json, password); + async getResolver(name) { + return await EnsResolver.fromName(this, name); } - if (isKeystoreWallet(json)) { - return decryptSync(json, password); + async getAvatar(name) { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAvatar(); + } + return null; } - throw new Error("invalid JSON wallet"); -} -const version20 = "wallet/5.7.0"; -var __awaiter6 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); + async resolveName(name) { + const resolver = await this.getResolver(name); + if (resolver) { + return await resolver.getAddress(); + } + return null; } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + async lookupAddress(address) { + address = getAddress(address); + const node = namehash(address.substring(2).toLowerCase() + ".addr.reverse"); + try { + const ensAddr = await EnsResolver.getEnsAddress(this); + const ensContract = new Contract(ensAddr, [ + "function resolver(bytes32) view returns (address)" + ], this); + const resolver = await ensContract.resolver(node); + if (resolver == null || resolver === ZeroAddress) { + return null; } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + const resolverContract = new Contract(resolver, [ + "function name(bytes32) view returns (string)" + ], this); + const name = await resolverContract.name(node); + const check = await this.resolveName(name); + if (check !== address) { + return null; } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger218 = new Logger(version20); -function isAccount(value) { - return value != null && isHexString(value.privateKey, 32) && value.address != null; -} -function hasMnemonic1(value) { - const mnemonic = value.mnemonic; - return mnemonic && mnemonic.phrase; -} -class Wallet extends Signer { - constructor(privateKey, provider){ - super(); - if (isAccount(privateKey)) { - const signingKey = new SigningKey(privateKey.privateKey); - defineReadOnly(this, "_signingKey", ()=>signingKey); - defineReadOnly(this, "address", computeAddress(this.publicKey)); - if (this.address !== getAddress(privateKey.address)) { - logger218.throwArgumentError("privateKey/address mismatch", "privateKey", "[REDACTED]"); - } - if (hasMnemonic1(privateKey)) { - const srcMnemonic = privateKey.mnemonic; - defineReadOnly(this, "_mnemonic", ()=>({ - phrase: srcMnemonic.phrase, - path: srcMnemonic.path || defaultPath, - locale: srcMnemonic.locale || "en" - })); - const mnemonic = this.mnemonic; - const node = HDNode.fromMnemonic(mnemonic.phrase, null, mnemonic.locale).derivePath(mnemonic.path); - if (computeAddress(node.privateKey) !== this.address) { - logger218.throwArgumentError("mnemonic/address mismatch", "privateKey", "[REDACTED]"); - } - } else { - defineReadOnly(this, "_mnemonic", ()=>null); + return name; + } catch (error) { + if (isError(error, "BAD_DATA") && error.value === "0x") { + return null; } - } else { - if (SigningKey.isSigningKey(privateKey)) { - if (privateKey.curve !== "secp256k1") { - logger218.throwArgumentError("unsupported curve; must be secp256k1", "privateKey", "[REDACTED]"); - } - defineReadOnly(this, "_signingKey", ()=>privateKey); - } else { - if (typeof privateKey === "string") { - if (privateKey.match(/^[0-9a-f]*$/i) && privateKey.length === 64) { - privateKey = "0x" + privateKey; - } - } - const signingKey = new SigningKey(privateKey); - defineReadOnly(this, "_signingKey", ()=>signingKey); + if (isError(error, "CALL_EXCEPTION")) { + return null; } - defineReadOnly(this, "_mnemonic", ()=>null); - defineReadOnly(this, "address", computeAddress(this.publicKey)); - } - if (provider && !Provider.isProvider(provider)) { - logger218.throwArgumentError("invalid provider", "provider", provider); + throw error; } - defineReadOnly(this, "provider", provider || null); - } - get mnemonic() { - return this._mnemonic(); - } - get privateKey() { - return this._signingKey().privateKey; - } - get publicKey() { - return this._signingKey().publicKey; - } - getAddress() { - return Promise.resolve(this.address); - } - connect(provider) { - return new Wallet(this, provider); + return null; } - signTransaction(transaction) { - return resolveProperties(transaction).then((tx)=>{ - if (tx.from != null) { - if (getAddress(tx.from) !== this.address) { - logger218.throwArgumentError("transaction from address mismatch", "transaction.from", transaction.from); + async waitForTransaction(hash, _confirms, timeout) { + const confirms = _confirms != null ? _confirms : 1; + if (confirms === 0) { + return this.getTransactionReceipt(hash); + } + return new Promise(async (resolve, reject)=>{ + let timer = null; + const listener = async (blockNumber)=>{ + try { + const receipt = await this.getTransactionReceipt(hash); + if (receipt != null) { + if (blockNumber - receipt.blockNumber + 1 >= confirms) { + resolve(receipt); + if (timer) { + clearTimeout(timer); + timer = null; + } + return; + } + } + } catch (error) { + console.log("EEE", error); } - delete tx.from; + this.once("block", listener); + }; + if (timeout != null) { + timer = setTimeout(()=>{ + if (timer == null) { + return; + } + timer = null; + this.off("block", listener); + reject(makeError("timeout", "TIMEOUT", { + reason: "timeout" + })); + }, timeout); } - const signature = this._signingKey().signDigest(keccak256(serialize(tx))); - return serialize(tx, signature); + listener(await this.getBlockNumber()); }); } - signMessage(message) { - return __awaiter6(this, void 0, void 0, function*() { - return joinSignature(this._signingKey().signDigest(hashMessage(message))); + async waitForBlock(blockTag) { + assert1(false, "not implemented yet", "NOT_IMPLEMENTED", { + operation: "waitForBlock" }); } - _signTypedData(domain, types, value) { - return __awaiter6(this, void 0, void 0, function*() { - const populated = yield TypedDataEncoder.resolveNames(domain, types, value, (name)=>{ - if (this.provider == null) { - logger218.throwError("cannot resolve ENS names without a provider", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "resolveName", - value: name - }); - } - return this.provider.resolveName(name); - }); - return joinSignature(this._signingKey().signDigest(TypedDataEncoder.hash(populated.domain, types, populated.value))); - }); + _clearTimeout(timerId) { + const timer = this.#timers.get(timerId); + if (!timer) { + return; + } + if (timer.timer) { + clearTimeout(timer.timer); + } + this.#timers.delete(timerId); } - encrypt(password, options, progressCallback) { - if (typeof options === "function" && !progressCallback) { - progressCallback = options; - options = {}; + _setTimeout(_func, timeout) { + if (timeout == null) { + timeout = 0; + } + const timerId = this.#nextTimer++; + const func = ()=>{ + this.#timers.delete(timerId); + _func(); + }; + if (this.paused) { + this.#timers.set(timerId, { + timer: null, + func: func, + time: timeout + }); + } else { + const timer = setTimeout(func, timeout); + this.#timers.set(timerId, { + timer: timer, + func: func, + time: getTime$1() + }); } - if (progressCallback && typeof progressCallback !== "function") { - throw new Error("invalid callback"); + return timerId; + } + _forEachSubscriber(func) { + for (const sub of this.#subs.values()){ + func(sub.subscriber); } - if (!options) { - options = {}; + } + _getSubscriber(sub) { + switch(sub.type){ + case "debug": + case "error": + case "network": + return new UnmanagedSubscriber(sub.type); + case "block": + { + const subscriber = new PollingBlockSubscriber(this); + subscriber.pollingInterval = this.pollingInterval; + return subscriber; + } + case "safe": + case "finalized": + return new PollingBlockTagSubscriber(this, sub.type); + case "event": + return new PollingEventSubscriber(this, sub.filter); + case "transaction": + return new PollingTransactionSubscriber(this, sub.hash); + case "orphan": + return new PollingOrphanSubscriber(this, sub.filter); } - return encrypt(this, password, options, progressCallback); + throw new Error(`unsupported event: ${sub.type}`); } - static createRandom(options) { - let entropy = randomBytes(16); - if (!options) { - options = {}; + _recoverSubscriber(oldSub, newSub) { + for (const sub of this.#subs.values()){ + if (sub.subscriber === oldSub) { + if (sub.started) { + sub.subscriber.stop(); + } + sub.subscriber = newSub; + if (sub.started) { + newSub.start(); + } + if (this.#pausedState != null) { + newSub.pause(this.#pausedState); + } + break; + } } - if (options.extraEntropy) { - entropy = arrayify(hexDataSlice(keccak256(concat([ - entropy, - options.extraEntropy - ])), 0, 16)); + } + async #hasSub(event, emitArgs) { + let sub = await getSubscription(event, this); + if (sub.type === "event" && emitArgs && emitArgs.length > 0 && emitArgs[0].removed === true) { + sub = await getSubscription({ + orphan: "drop-log", + log: emitArgs[0] + }, this); + } + return this.#subs.get(sub.tag) || null; + } + async #getSub(event) { + const subscription = await getSubscription(event, this); + const tag = subscription.tag; + let sub = this.#subs.get(tag); + if (!sub) { + const subscriber = this._getSubscriber(subscription); + const addressableMap = new WeakMap; + const nameMap = new Map; + sub = { + subscriber: subscriber, + tag: tag, + addressableMap: addressableMap, + nameMap: nameMap, + started: false, + listeners: [] + }; + this.#subs.set(tag, sub); } - const mnemonic = entropyToMnemonic(entropy, options.locale); - return Wallet.fromMnemonic(mnemonic, options.path, options.locale); + return sub; } - static fromEncryptedJson(json, password, progressCallback) { - return decryptJsonWallet(json, password, progressCallback).then((account)=>{ - return new Wallet(account); + async on(event, listener) { + const sub = await this.#getSub(event); + sub.listeners.push({ + listener: listener, + once: false }); - } - static fromEncryptedJsonSync(json, password) { - return new Wallet(decryptJsonWalletSync(json, password)); - } - static fromMnemonic(mnemonic, path, wordlist) { - if (!path) { - path = defaultPath; + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (this.#pausedState != null) { + sub.subscriber.pause(this.#pausedState); + } } - return new Wallet(HDNode.fromMnemonic(mnemonic, null, wordlist).derivePath(path)); + return this; } -} -function verifyMessage(message, signature) { - return recoverAddress(hashMessage(message), signature); -} -function verifyTypedData(domain, types, value, signature) { - return recoverAddress(TypedDataEncoder.hash(domain, types, value), signature); -} -const version21 = "networks/5.7.1"; -const logger219 = new Logger(version21); -function isRenetworkable(value) { - return value && typeof value.renetwork === "function"; -} -function ethDefaultProvider(network) { - const func = function(providers, options) { - if (options == null) { - options = {}; + async once(event, listener) { + const sub = await this.#getSub(event); + sub.listeners.push({ + listener: listener, + once: true + }); + if (!sub.started) { + sub.subscriber.start(); + sub.started = true; + if (this.#pausedState != null) { + sub.subscriber.pause(this.#pausedState); + } } - const providerList = []; - if (providers.InfuraProvider && options.infura !== "-") { - try { - providerList.push(new providers.InfuraProvider(network, options.infura)); - } catch (error) {} + return this; + } + async emit(event, ...args) { + const sub = await this.#hasSub(event, args); + if (!sub || sub.listeners.length === 0) { + return false; } - if (providers.EtherscanProvider && options.etherscan !== "-") { + const count = sub.listeners.length; + sub.listeners = sub.listeners.filter(({ listener, once })=>{ + const payload = new EventPayload(this, once ? null : listener, event); try { - providerList.push(new providers.EtherscanProvider(network, options.etherscan)); + listener.call(this, ...args, payload); } catch (error) {} + return !once; + }); + if (sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); + } + this.#subs.delete(sub.tag); } - if (providers.AlchemyProvider && options.alchemy !== "-") { - try { - providerList.push(new providers.AlchemyProvider(network, options.alchemy)); - } catch (error) {} + return count > 0; + } + async listenerCount(event) { + if (event) { + const sub = await this.#hasSub(event); + if (!sub) { + return 0; + } + return sub.listeners.length; } - if (providers.PocketProvider && options.pocket !== "-") { - const skip = [ - "goerli", - "ropsten", - "rinkeby", - "sepolia" - ]; - try { - const provider = new providers.PocketProvider(network, options.pocket); - if (provider.network && skip.indexOf(provider.network.name) === -1) { - providerList.push(provider); - } - } catch (error) {} + let total = 0; + for (const { listeners } of this.#subs.values()){ + total += listeners.length; } - if (providers.CloudflareProvider && options.cloudflare !== "-") { - try { - providerList.push(new providers.CloudflareProvider(network)); - } catch (error) {} + return total; + } + async listeners(event) { + if (event) { + const sub = await this.#hasSub(event); + if (!sub) { + return []; + } + return sub.listeners.map(({ listener })=>listener); } - if (providers.AnkrProvider && options.ankr !== "-") { - try { - const skip = [ - "ropsten" - ]; - const provider = new providers.AnkrProvider(network, options.ankr); - if (provider.network && skip.indexOf(provider.network.name) === -1) { - providerList.push(provider); - } - } catch (error) {} + let result = []; + for (const { listeners } of this.#subs.values()){ + result = result.concat(listeners.map(({ listener })=>listener)); } - if (providerList.length === 0) { - return null; + return result; + } + async off(event, listener) { + const sub = await this.#hasSub(event); + if (!sub) { + return this; } - if (providers.FallbackProvider) { - let quorum = 1; - if (options.quorum != null) { - quorum = options.quorum; - } else if (network === "homestead") { - quorum = 2; + if (listener) { + const index = sub.listeners.map(({ listener })=>listener).indexOf(listener); + if (index >= 0) { + sub.listeners.splice(index, 1); } - return new providers.FallbackProvider(providerList, quorum); } - return providerList[0]; - }; - func.renetwork = function(network2) { - return ethDefaultProvider(network2); - }; - return func; -} -function etcDefaultProvider(url, network) { - const func = function(providers, options) { - if (providers.JsonRpcProvider) { - return new providers.JsonRpcProvider(url, network); + if (!listener || sub.listeners.length === 0) { + if (sub.started) { + sub.subscriber.stop(); + } + this.#subs.delete(sub.tag); } - return null; - }; - func.renetwork = function(network2) { - return etcDefaultProvider(url, network2); - }; - return func; -} -const homestead = { - chainId: 1, - ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", - name: "homestead", - _defaultProvider: ethDefaultProvider("homestead") -}; -const ropsten = { - chainId: 3, - ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", - name: "ropsten", - _defaultProvider: ethDefaultProvider("ropsten") -}; -const classicMordor = { - chainId: 63, - name: "classicMordor", - _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/mordor", "classicMordor") -}; -const networks = { - unspecified: { - chainId: 0, - name: "unspecified" - }, - homestead, - mainnet: homestead, - morden: { - chainId: 2, - name: "morden" - }, - ropsten, - testnet: ropsten, - rinkeby: { - chainId: 4, - ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", - name: "rinkeby", - _defaultProvider: ethDefaultProvider("rinkeby") - }, - kovan: { - chainId: 42, - name: "kovan", - _defaultProvider: ethDefaultProvider("kovan") - }, - goerli: { - chainId: 5, - ensAddress: "0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e", - name: "goerli", - _defaultProvider: ethDefaultProvider("goerli") - }, - kintsugi: { - chainId: 1337702, - name: "kintsugi" - }, - sepolia: { - chainId: 11155111, - name: "sepolia", - _defaultProvider: ethDefaultProvider("sepolia") - }, - classic: { - chainId: 61, - name: "classic", - _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/etc", "classic") - }, - classicMorden: { - chainId: 62, - name: "classicMorden" - }, - classicMordor, - classicTestnet: classicMordor, - classicKotti: { - chainId: 6, - name: "classicKotti", - _defaultProvider: etcDefaultProvider("https://www.ethercluster.com/kotti", "classicKotti") - }, - xdai: { - chainId: 100, - name: "xdai" - }, - matic: { - chainId: 137, - name: "matic", - _defaultProvider: ethDefaultProvider("matic") - }, - maticmum: { - chainId: 80001, - name: "maticmum" - }, - optimism: { - chainId: 10, - name: "optimism", - _defaultProvider: ethDefaultProvider("optimism") - }, - "optimism-kovan": { - chainId: 69, - name: "optimism-kovan" - }, - "optimism-goerli": { - chainId: 420, - name: "optimism-goerli" - }, - arbitrum: { - chainId: 42161, - name: "arbitrum" - }, - "arbitrum-rinkeby": { - chainId: 421611, - name: "arbitrum-rinkeby" - }, - "arbitrum-goerli": { - chainId: 421613, - name: "arbitrum-goerli" - }, - bnb: { - chainId: 56, - name: "bnb" - }, - bnbt: { - chainId: 97, - name: "bnbt" - } -}; -function getNetwork(network) { - if (network == null) { - return null; + return this; } - if (typeof network === "number") { - for(const name in networks){ - const standard2 = networks[name]; - if (standard2.chainId === network) { - return { - name: standard2.name, - chainId: standard2.chainId, - ensAddress: standard2.ensAddress || null, - _defaultProvider: standard2._defaultProvider || null - }; + async removeAllListeners(event) { + if (event) { + const { tag, started, subscriber } = await this.#getSub(event); + if (started) { + subscriber.stop(); + } + this.#subs.delete(tag); + } else { + for (const [tag, { started, subscriber }] of this.#subs){ + if (started) { + subscriber.stop(); + } + this.#subs.delete(tag); } } - return { - chainId: network, - name: "unknown" - }; + return this; } - if (typeof network === "string") { - const standard2 = networks[network]; - if (standard2 == null) { - return null; - } - return { - name: standard2.name, - chainId: standard2.chainId, - ensAddress: standard2.ensAddress, - _defaultProvider: standard2._defaultProvider || null - }; + async addListener(event, listener) { + return await this.on(event, listener); } - const standard = networks[network.name]; - if (!standard) { - if (typeof network.chainId !== "number") { - logger219.throwArgumentError("invalid network chainId", "network", network); - } - return network; + async removeListener(event, listener) { + return this.off(event, listener); } - if (network.chainId !== 0 && network.chainId !== standard.chainId) { - logger219.throwArgumentError("network chainId mismatch", "network", network); + get destroyed() { + return this.#destroyed; } - let defaultProvider = network._defaultProvider || null; - if (defaultProvider == null && standard._defaultProvider) { - if (isRenetworkable(standard._defaultProvider)) { - defaultProvider = standard._defaultProvider.renetwork(network); - } else { - defaultProvider = standard._defaultProvider; + destroy() { + this.removeAllListeners(); + for (const timerId of this.#timers.keys()){ + this._clearTimeout(timerId); } + this.#destroyed = true; } - return { - name: network.name, - chainId: standard.chainId, - ensAddress: network.ensAddress || standard.ensAddress || null, - _defaultProvider: defaultProvider - }; -} -const version22 = "web/5.7.1"; -var __awaiter7 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); + get paused() { + return this.#pausedState != null; } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -function getUrl(href, options) { - return __awaiter7(this, void 0, void 0, function*() { - if (options == null) { - options = {}; + set paused(pause) { + if (!!pause === this.paused) { + return; } - const request = { - method: options.method || "GET", - headers: options.headers || {}, - body: options.body || void 0 - }; - if (options.skipFetchSetup !== true) { - request.mode = "cors"; - request.cache = "no-cache"; - request.credentials = "same-origin"; - request.redirect = "follow"; - request.referrer = "client"; + if (this.paused) { + this.resume(); + } else { + this.pause(false); } - if (options.fetchOptions != null) { - const opts = options.fetchOptions; - if (opts.mode) { - request.mode = opts.mode; - } - if (opts.cache) { - request.cache = opts.cache; - } - if (opts.credentials) { - request.credentials = opts.credentials; - } - if (opts.redirect) { - request.redirect = opts.redirect; - } - if (opts.referrer) { - request.referrer = opts.referrer; + } + pause(dropWhilePaused) { + this.#lastBlockNumber = -1; + if (this.#pausedState != null) { + if (this.#pausedState == !!dropWhilePaused) { + return; } - } - const response = yield fetch(href, request); - const body = yield response.arrayBuffer(); - const headers = {}; - if (response.headers.forEach) { - response.headers.forEach((value, key)=>{ - headers[key.toLowerCase()] = value; - }); - } else { - response.headers.keys().forEach((key)=>{ - headers[key.toLowerCase()] = response.headers.get(key); + assert1(false, "cannot change pause type; resume first", "UNSUPPORTED_OPERATION", { + operation: "pause" }); } - return { - headers, - statusCode: response.status, - statusMessage: response.statusText, - body: arrayify(new Uint8Array(body)) - }; - }); -} -var __awaiter$1 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); + this._forEachSubscriber((s)=>s.pause(dropWhilePaused)); + this.#pausedState = !!dropWhilePaused; + for (const timer of this.#timers.values()){ + if (timer.timer) { + clearTimeout(timer.timer); } + timer.time = getTime$1() - timer.time; } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + } + resume() { + if (this.#pausedState == null) { + return; + } + this._forEachSubscriber((s)=>s.resume()); + this.#pausedState = null; + for (const timer of this.#timers.values()){ + let timeout = timer.time; + if (timeout < 0) { + timeout = 0; } + timer.time = getTime$1(); + setTimeout(timer.func, timeout); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } +} +function _parseString(result, start) { + try { + const bytes = _parseBytes(result, start); + if (bytes) { + return toUtf8String(bytes); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger220 = new Logger(version22); -function staller(duration) { - return new Promise((resolve)=>{ - setTimeout(resolve, duration); - }); + } catch (error) {} + return null; } -function bodyify(value, type) { - if (value == null) { +function _parseBytes(result, start) { + if (result === "0x") { return null; } - if (typeof value === "string") { - return value; + try { + const offset = getNumber(dataSlice(result, start, start + 32)); + const length = getNumber(dataSlice(result, offset, offset + 32)); + return dataSlice(result, offset + 32, offset + 32 + length); + } catch (error) {} + return null; +} +function numPad(value) { + const result = toBeArray(value); + if (result.length > 32) { + throw new Error("internal; should not happen"); } - if (isBytesLike(value)) { - if (type && (type.split("/")[0] === "text" || type.split(";")[0].trim() === "application/json")) { - try { - return toUtf8String(value); - } catch (error) {} - } - return hexlify(value); + const padded = new Uint8Array(32); + padded.set(result, 32 - result.length); + return padded; +} +function bytesPad(value) { + if (value.length % 32 === 0) { + return value; } - return value; + const result = new Uint8Array(Math.ceil(value.length / 32) * 32); + result.set(value); + return result; } -function unpercent(value) { - return toUtf8Bytes(value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code)=>{ - return String.fromCharCode(parseInt(code, 16)); - })); +const empty = new Uint8Array([]); +function encodeBytes(datas) { + const result = []; + let byteCount = 0; + for(let i = 0; i < datas.length; i++){ + result.push(empty); + byteCount += 32; + } + for(let i = 0; i < datas.length; i++){ + const data = getBytes(datas[i]); + result[i] = numPad(byteCount); + result.push(numPad(data.length)); + result.push(bytesPad(data)); + byteCount += 32 + Math.ceil(data.length / 32) * 32; + } + return concat(result); } -function _fetchData(connection, body, processFunc) { - const attemptLimit = typeof connection === "object" && connection.throttleLimit != null ? connection.throttleLimit : 12; - logger220.assertArgument(attemptLimit > 0 && attemptLimit % 1 === 0, "invalid connection throttle limit", "connection.throttleLimit", attemptLimit); - const throttleCallback = typeof connection === "object" ? connection.throttleCallback : null; - const throttleSlotInterval = typeof connection === "object" && typeof connection.throttleSlotInterval === "number" ? connection.throttleSlotInterval : 100; - logger220.assertArgument(throttleSlotInterval > 0 && throttleSlotInterval % 1 === 0, "invalid connection throttle slot interval", "connection.throttleSlotInterval", throttleSlotInterval); - const errorPassThrough = typeof connection === "object" ? !!connection.errorPassThrough : false; - const headers = {}; - let url = null; - const options = { - method: "GET" +const zeros = "0x0000000000000000000000000000000000000000000000000000000000000000"; +function parseOffchainLookup(data) { + const result = { + sender: "", + urls: [], + calldata: "", + selector: "", + extraData: "", + errorArgs: [] }; - let allow304 = false; - let timeout = 2 * 60 * 1e3; - if (typeof connection === "string") { - url = connection; - } else if (typeof connection === "object") { - if (connection == null || connection.url == null) { - logger220.throwArgumentError("missing URL", "connection.url", connection); - } - url = connection.url; - if (typeof connection.timeout === "number" && connection.timeout > 0) { - timeout = connection.timeout; - } - if (connection.headers) { - for(const key in connection.headers){ - headers[key.toLowerCase()] = { - key, - value: String(connection.headers[key]) - }; - if ([ - "if-none-match", - "if-modified-since" - ].indexOf(key.toLowerCase()) >= 0) { - allow304 = true; - } - } - } - options.allowGzip = !!connection.allowGzip; - if (connection.user != null && connection.password != null) { - if (url.substring(0, 6) !== "https:" && connection.allowInsecureAuthentication !== true) { - logger220.throwError("basic authentication requires a secure https url", Logger.errors.INVALID_ARGUMENT, { - argument: "url", - url, - user: connection.user, - password: "[REDACTED]" - }); - } - const authorization = connection.user + ":" + connection.password; - headers["authorization"] = { - key: "Authorization", - value: "Basic " + encode1(toUtf8Bytes(authorization)) - }; - } - if (connection.skipFetchSetup != null) { - options.skipFetchSetup = !!connection.skipFetchSetup; - } - if (connection.fetchOptions != null) { - options.fetchOptions = shallowCopy(connection.fetchOptions); - } + assert1(dataLength(data) >= 5 * 32, "insufficient OffchainLookup data", "OFFCHAIN_FAULT", { + reason: "insufficient OffchainLookup data" + }); + const sender = dataSlice(data, 0, 32); + assert1(dataSlice(sender, 0, 12) === dataSlice(zeros, 0, 12), "corrupt OffchainLookup sender", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup sender" + }); + result.sender = dataSlice(sender, 12); + try { + const urls = []; + const urlsOffset = getNumber(dataSlice(data, 32, 64)); + const urlsLength = getNumber(dataSlice(data, urlsOffset, urlsOffset + 32)); + const urlsData = dataSlice(data, urlsOffset + 32); + for(let u = 0; u < urlsLength; u++){ + const url = _parseString(urlsData, u * 32); + if (url == null) { + throw new Error("abort"); + } + urls.push(url); + } + result.urls = urls; + } catch (error) { + assert1(false, "corrupt OffchainLookup urls", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup urls" + }); } - const reData = new RegExp("^data:([^;:]*)?(;base64)?,(.*)$", "i"); - const dataMatch = url ? url.match(reData) : null; - if (dataMatch) { - try { - const response = { - statusCode: 200, - statusMessage: "OK", - headers: { - "content-type": dataMatch[1] || "text/plain" - }, - body: dataMatch[2] ? decode2(dataMatch[3]) : unpercent(dataMatch[3]) - }; - let result = response.body; - if (processFunc) { - result = processFunc(response.body, response); - } - return Promise.resolve(result); - } catch (error) { - logger220.throwError("processing response error", Logger.errors.SERVER_ERROR, { - body: bodyify(dataMatch[1], dataMatch[2]), - error, - requestBody: null, - requestMethod: "GET", - url - }); + try { + const calldata = _parseBytes(data, 64); + if (calldata == null) { + throw new Error("abort"); } + result.calldata = calldata; + } catch (error) { + assert1(false, "corrupt OffchainLookup calldata", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup calldata" + }); } - if (body) { - options.method = "POST"; - options.body = body; - if (headers["content-type"] == null) { - headers["content-type"] = { - key: "Content-Type", - value: "application/octet-stream" - }; - } - if (headers["content-length"] == null) { - headers["content-length"] = { - key: "Content-Length", - value: String(body.length) - }; + assert1(dataSlice(data, 100, 128) === dataSlice(zeros, 0, 28), "corrupt OffchainLookup callbaackSelector", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup callbaackSelector" + }); + result.selector = dataSlice(data, 96, 100); + try { + const extraData = _parseBytes(data, 128); + if (extraData == null) { + throw new Error("abort"); } + result.extraData = extraData; + } catch (error) { + assert1(false, "corrupt OffchainLookup extraData", "OFFCHAIN_FAULT", { + reason: "corrupt OffchainLookup extraData" + }); + } + result.errorArgs = "sender,urls,calldata,selector,extraData".split(/,/).map((k)=>result[k]); + return result; +} +function checkProvider(signer, operation) { + if (signer.provider) { + return signer.provider; } - const flatHeaders = {}; - Object.keys(headers).forEach((key)=>{ - const header = headers[key]; - flatHeaders[header.key] = header.value; + assert1(false, "missing provider", "UNSUPPORTED_OPERATION", { + operation: operation }); - options.headers = flatHeaders; - const runningTimeout = function() { - let timer = null; - const promise = new Promise(function(resolve, reject) { - if (timeout) { - timer = setTimeout(()=>{ - if (timer == null) { - return; - } - timer = null; - reject(logger220.makeError("timeout", Logger.errors.TIMEOUT, { - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - timeout, - url - })); - }, timeout); - } +} +async function populate(signer, tx) { + let pop = copyRequest(tx); + if (pop.to != null) { + pop.to = resolveAddress(pop.to, signer); + } + if (pop.from != null) { + const from = pop.from; + pop.from = Promise.all([ + signer.getAddress(), + resolveAddress(from, signer) + ]).then(([address, from])=>{ + assertArgument(address.toLowerCase() === from.toLowerCase(), "transaction from mismatch", "tx.from", from); + return address; }); - const cancel = function() { - if (timer == null) { - return; - } - clearTimeout(timer); - timer = null; - }; - return { - promise, - cancel - }; - }(); - const runningFetch = function() { - return __awaiter$1(this, void 0, void 0, function*() { - for(let attempt = 0; attempt < attemptLimit; attempt++){ - let response = null; - try { - response = yield getUrl(url, options); - if (attempt < attemptLimit) { - if (response.statusCode === 301 || response.statusCode === 302) { - const location = response.headers.location || ""; - if (options.method === "GET" && location.match(/^https:/)) { - url = response.headers.location; - continue; - } - } else if (response.statusCode === 429) { - let tryAgain = true; - if (throttleCallback) { - tryAgain = yield throttleCallback(attempt, url); - } - if (tryAgain) { - let stall = 0; - const retryAfter = response.headers["retry-after"]; - if (typeof retryAfter === "string" && retryAfter.match(/^[1-9][0-9]*$/)) { - stall = parseInt(retryAfter) * 1e3; - } else { - stall = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt))); - } - yield staller(stall); - continue; - } + } else { + pop.from = signer.getAddress(); + } + return await resolveProperties(pop); +} +class AbstractSigner { + provider; + constructor(provider){ + defineProperties(this, { + provider: provider || null + }); + } + async getNonce(blockTag) { + return checkProvider(this, "getTransactionCount").getTransactionCount(await this.getAddress(), blockTag); + } + async populateCall(tx) { + const pop = await populate(this, tx); + return pop; + } + async populateTransaction(tx) { + const provider = checkProvider(this, "populateTransaction"); + const pop = await populate(this, tx); + if (pop.nonce == null) { + pop.nonce = await this.getNonce("pending"); + } + if (pop.gasLimit == null) { + pop.gasLimit = await this.estimateGas(pop); + } + const network = await this.provider.getNetwork(); + if (pop.chainId != null) { + const chainId = getBigInt(pop.chainId); + assertArgument(chainId === network.chainId, "transaction chainId mismatch", "tx.chainId", tx.chainId); + } else { + pop.chainId = network.chainId; + } + const hasEip1559 = pop.maxFeePerGas != null || pop.maxPriorityFeePerGas != null; + if (pop.gasPrice != null && (pop.type === 2 || hasEip1559)) { + assertArgument(false, "eip-1559 transaction do not support gasPrice", "tx", tx); + } else if ((pop.type === 0 || pop.type === 1) && hasEip1559) { + assertArgument(false, "pre-eip-1559 transaction do not support maxFeePerGas/maxPriorityFeePerGas", "tx", tx); + } + if ((pop.type === 2 || pop.type == null) && pop.maxFeePerGas != null && pop.maxPriorityFeePerGas != null) { + pop.type = 2; + } else if (pop.type === 0 || pop.type === 1) { + const feeData = await provider.getFeeData(); + assert1(feeData.gasPrice != null, "network does not support gasPrice", "UNSUPPORTED_OPERATION", { + operation: "getGasPrice" + }); + if (pop.gasPrice == null) { + pop.gasPrice = feeData.gasPrice; + } + } else { + const feeData = await provider.getFeeData(); + if (pop.type == null) { + if (feeData.maxFeePerGas != null && feeData.maxPriorityFeePerGas != null) { + pop.type = 2; + if (pop.gasPrice != null) { + const gasPrice = pop.gasPrice; + delete pop.gasPrice; + pop.maxFeePerGas = gasPrice; + pop.maxPriorityFeePerGas = gasPrice; + } else { + if (pop.maxFeePerGas == null) { + pop.maxFeePerGas = feeData.maxFeePerGas; + } + if (pop.maxPriorityFeePerGas == null) { + pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; } } - } catch (error) { - response = error.response; - if (response == null) { - runningTimeout.cancel(); - logger220.throwError("missing response", Logger.errors.SERVER_ERROR, { - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - serverError: error, - url - }); + } else if (feeData.gasPrice != null) { + assert1(!hasEip1559, "network does not support EIP-1559", "UNSUPPORTED_OPERATION", { + operation: "populateTransaction" + }); + if (pop.gasPrice == null) { + pop.gasPrice = feeData.gasPrice; } - } - let body2 = response.body; - if (allow304 && response.statusCode === 304) { - body2 = null; - } else if (!errorPassThrough && (response.statusCode < 200 || response.statusCode >= 300)) { - runningTimeout.cancel(); - logger220.throwError("bad response", Logger.errors.SERVER_ERROR, { - status: response.statusCode, - headers: response.headers, - body: bodyify(body2, response.headers ? response.headers["content-type"] : null), - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - url + pop.type = 0; + } else { + assert1(false, "failed to get consistent fee data", "UNSUPPORTED_OPERATION", { + operation: "signer.getFeeData" }); } - if (processFunc) { - try { - const result = yield processFunc(body2, response); - runningTimeout.cancel(); - return result; - } catch (error) { - if (error.throttleRetry && attempt < attemptLimit) { - let tryAgain = true; - if (throttleCallback) { - tryAgain = yield throttleCallback(attempt, url); - } - if (tryAgain) { - const timeout2 = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt))); - yield staller(timeout2); - continue; - } - } - runningTimeout.cancel(); - logger220.throwError("processing response error", Logger.errors.SERVER_ERROR, { - body: bodyify(body2, response.headers ? response.headers["content-type"] : null), - error, - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - url - }); - } + } else if (pop.type === 2 || pop.type === 3) { + if (pop.maxFeePerGas == null) { + pop.maxFeePerGas = feeData.maxFeePerGas; + } + if (pop.maxPriorityFeePerGas == null) { + pop.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas; } - runningTimeout.cancel(); - return body2; } - return logger220.throwError("failed response", Logger.errors.SERVER_ERROR, { - requestBody: bodyify(options.body, flatHeaders["content-type"]), - requestMethod: options.method, - url - }); + } + return await resolveProperties(pop); + } + async estimateGas(tx) { + return checkProvider(this, "estimateGas").estimateGas(await this.populateCall(tx)); + } + async call(tx) { + return checkProvider(this, "call").call(await this.populateCall(tx)); + } + async resolveName(name) { + const provider = checkProvider(this, "resolveName"); + return await provider.resolveName(name); + } + async sendTransaction(tx) { + const provider = checkProvider(this, "sendTransaction"); + const pop = await this.populateTransaction(tx); + delete pop.from; + const txObj = Transaction.from(pop); + return await provider.broadcastTransaction(await this.signTransaction(txObj)); + } +} +class VoidSigner extends AbstractSigner { + address; + constructor(address, provider){ + super(provider); + defineProperties(this, { + address: address }); - }(); - return Promise.race([ - runningTimeout.promise, - runningFetch - ]); + } + async getAddress() { + return this.address; + } + connect(provider) { + return new VoidSigner(this.address, provider); + } + #throwUnsupported(suffix, operation) { + assert1(false, `VoidSigner cannot sign ${suffix}`, "UNSUPPORTED_OPERATION", { + operation: operation + }); + } + async signTransaction(tx) { + this.#throwUnsupported("transactions", "signTransaction"); + } + async signMessage(message) { + this.#throwUnsupported("messages", "signMessage"); + } + async signTypedData(domain, types, value) { + this.#throwUnsupported("typed-data", "signTypedData"); + } } -function fetchJson(connection, json, processFunc) { - let processJsonFunc = (value, response)=>{ - let result = null; - if (value != null) { +const shown = new Set; +function showThrottleMessage(service) { + if (shown.has(service)) { + return; + } + shown.add(service); + console.log("========= NOTICE ========="); + console.log(`Request-Rate Exceeded for ${service} (this message will not be repeated)`); + console.log(""); + console.log("The default API keys for each service are provided as a highly-throttled,"); + console.log("community resource for low-traffic projects and early prototyping."); + console.log(""); + console.log("While your application will continue to function, we highly recommended"); + console.log("signing up for your own API keys to improve performance, increase your"); + console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."); + console.log(""); + console.log("For more details: https://docs.ethers.org/api-keys/"); + console.log("=========================="); +} +function copy(obj) { + return JSON.parse(JSON.stringify(obj)); +} +class FilterIdSubscriber { + #provider; + #filterIdPromise; + #poller; + #running; + #network; + #hault; + constructor(provider){ + this.#provider = provider; + this.#filterIdPromise = null; + this.#poller = this.#poll.bind(this); + this.#running = false; + this.#network = null; + this.#hault = false; + } + _subscribe(provider) { + throw new Error("subclasses must override this"); + } + _emitResults(provider, result) { + throw new Error("subclasses must override this"); + } + _recover(provider) { + throw new Error("subclasses must override this"); + } + async #poll(blockNumber) { + try { + if (this.#filterIdPromise == null) { + this.#filterIdPromise = this._subscribe(this.#provider); + } + let filterId = null; try { - result = JSON.parse(toUtf8String(value)); + filterId = await this.#filterIdPromise; } catch (error) { - logger220.throwError("invalid JSON", Logger.errors.SERVER_ERROR, { - body: value, - error - }); + if (!isError(error, "UNSUPPORTED_OPERATION") || error.operation !== "eth_newFilter") { + throw error; + } + } + if (filterId == null) { + this.#filterIdPromise = null; + this.#provider._recoverSubscriber(this, this._recover(this.#provider)); + return; + } + const network = await this.#provider.getNetwork(); + if (!this.#network) { + this.#network = network; + } + if (this.#network.chainId !== network.chainId) { + throw new Error("chaid changed"); + } + if (this.#hault) { + return; } + const result = await this.#provider.send("eth_getFilterChanges", [ + filterId + ]); + await this._emitResults(this.#provider, result); + } catch (error) { + console.log("@TODO", error); } - if (processFunc) { - result = processFunc(result, response); + this.#provider.once("block", this.#poller); + } + #teardown() { + const filterIdPromise = this.#filterIdPromise; + if (filterIdPromise) { + this.#filterIdPromise = null; + filterIdPromise.then((filterId)=>{ + if (this.#provider.destroyed) { + return; + } + this.#provider.send("eth_uninstallFilter", [ + filterId + ]); + }); } - return result; - }; - let body = null; - if (json != null) { - body = toUtf8Bytes(json); - const updated = typeof connection === "string" ? { - url: connection - } : shallowCopy(connection); - if (updated.headers) { - const hasContentType = Object.keys(updated.headers).filter((k)=>k.toLowerCase() === "content-type").length !== 0; - if (!hasContentType) { - updated.headers = shallowCopy(updated.headers); - updated.headers["content-type"] = "application/json"; - } - } else { - updated.headers = { - "content-type": "application/json" - }; + } + start() { + if (this.#running) { + return; } - connection = updated; + this.#running = true; + this.#poll(-2); } - return _fetchData(connection, body, processJsonFunc); -} -function poll(func, options) { - if (!options) { - options = {}; + stop() { + if (!this.#running) { + return; + } + this.#running = false; + this.#hault = true; + this.#teardown(); + this.#provider.off("block", this.#poller); } - options = shallowCopy(options); - if (options.floor == null) { - options.floor = 0; + pause(dropWhilePaused) { + if (dropWhilePaused) { + this.#teardown(); + } + this.#provider.off("block", this.#poller); } - if (options.ceiling == null) { - options.ceiling = 1e4; + resume() { + this.start(); } - if (options.interval == null) { - options.interval = 250; +} +class FilterIdEventSubscriber extends FilterIdSubscriber { + #event; + constructor(provider, filter){ + super(provider); + this.#event = copy(filter); } - return new Promise(function(resolve, reject) { - let timer = null; - let done = false; - const cancel = ()=>{ - if (done) { - return false; - } - done = true; - if (timer) { - clearTimeout(timer); - } - return true; - }; - if (options.timeout) { - timer = setTimeout(()=>{ - if (cancel()) { - reject(new Error("timeout")); - } - }, options.timeout); - } - const retryLimit = options.retryLimit; - let attempt = 0; - function check() { - return func().then(function(result) { - if (result !== void 0) { - if (cancel()) { - resolve(result); - } - } else if (options.oncePoll) { - options.oncePoll.once("poll", check); - } else if (options.onceBlock) { - options.onceBlock.once("block", check); - } else if (!done) { - attempt++; - if (attempt > retryLimit) { - if (cancel()) { - reject(new Error("retry limit reached")); - } - return; - } - let timeout = options.interval * parseInt(String(Math.random() * Math.pow(2, attempt))); - if (timeout < options.floor) { - timeout = options.floor; - } - if (timeout > options.ceiling) { - timeout = options.ceiling; - } - setTimeout(check, timeout); - } - return null; - }, function(error) { - if (cancel()) { - reject(error); - } - }); + _recover(provider) { + return new PollingEventSubscriber(provider, this.#event); + } + async _subscribe(provider) { + const filterId = await provider.send("eth_newFilter", [ + this.#event + ]); + return filterId; + } + async _emitResults(provider, results) { + for (const result of results){ + provider.emit(this.#event, provider._wrapLog(result, provider._network)); } - check(); - }); -} -var ALPHABET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; -var ALPHABET_MAP = {}; -for(var z = 0; z < ALPHABET.length; z++){ - var x = ALPHABET.charAt(z); - if (ALPHABET_MAP[x] !== void 0) throw new TypeError(x + " is ambiguous"); - ALPHABET_MAP[x] = z; -} -function polymodStep(pre) { - var b = pre >> 25; - return (pre & 33554431) << 5 ^ -(b >> 0 & 1) & 996825010 ^ -(b >> 1 & 1) & 642813549 ^ -(b >> 2 & 1) & 513874426 ^ -(b >> 3 & 1) & 1027748829 ^ -(b >> 4 & 1) & 705979059; -} -function prefixChk(prefix) { - var chk = 1; - for(var i = 0; i < prefix.length; ++i){ - var c = prefix.charCodeAt(i); - if (c < 33 || c > 126) return "Invalid prefix (" + prefix + ")"; - chk = polymodStep(chk) ^ c >> 5; - } - chk = polymodStep(chk); - for(i = 0; i < prefix.length; ++i){ - var v = prefix.charCodeAt(i); - chk = polymodStep(chk) ^ v & 31; - } - return chk; -} -function encode2(prefix, words, LIMIT) { - LIMIT = LIMIT || 90; - if (prefix.length + 7 + words.length > LIMIT) throw new TypeError("Exceeds length limit"); - prefix = prefix.toLowerCase(); - var chk = prefixChk(prefix); - if (typeof chk === "string") throw new Error(chk); - var result = prefix + "1"; - for(var i = 0; i < words.length; ++i){ - var x = words[i]; - if (x >> 5 !== 0) throw new Error("Non 5-bit word"); - chk = polymodStep(chk) ^ x; - result += ALPHABET.charAt(x); - } - for(i = 0; i < 6; ++i){ - chk = polymodStep(chk); - } - chk ^= 1; - for(i = 0; i < 6; ++i){ - var v = chk >> (5 - i) * 5 & 31; - result += ALPHABET.charAt(v); } - return result; } -function __decode(str, LIMIT) { - LIMIT = LIMIT || 90; - if (str.length < 8) return str + " too short"; - if (str.length > LIMIT) return "Exceeds length limit"; - var lowered = str.toLowerCase(); - var uppered = str.toUpperCase(); - if (str !== lowered && str !== uppered) return "Mixed-case string " + str; - str = lowered; - var split = str.lastIndexOf("1"); - if (split === -1) return "No separator character for " + str; - if (split === 0) return "Missing prefix for " + str; - var prefix = str.slice(0, split); - var wordChars = str.slice(split + 1); - if (wordChars.length < 6) return "Data too short"; - var chk = prefixChk(prefix); - if (typeof chk === "string") return chk; - var words = []; - for(var i = 0; i < wordChars.length; ++i){ - var c = wordChars.charAt(i); - var v = ALPHABET_MAP[c]; - if (v === void 0) return "Unknown character " + c; - chk = polymodStep(chk) ^ v; - if (i + 6 >= wordChars.length) continue; - words.push(v); - } - if (chk !== 1) return "Invalid checksum for " + str; - return { - prefix, - words - }; +class FilterIdPendingSubscriber extends FilterIdSubscriber { + async _subscribe(provider) { + return await provider.send("eth_newPendingTransactionFilter", []); + } + async _emitResults(provider, results) { + for (const result of results){ + provider.emit("pending", result); + } + } } -function decodeUnsafe() { - var res = __decode.apply(null, arguments); - if (typeof res === "object") return res; +const Primitive = "bigint,boolean,function,number,string,symbol".split(/,/g); +function deepCopy(value) { + if (value == null || Primitive.indexOf(typeof value) >= 0) { + return value; + } + if (typeof value.getAddress === "function") { + return value; + } + if (Array.isArray(value)) { + return value.map(deepCopy); + } + if (typeof value === "object") { + return Object.keys(value).reduce((accum, key)=>{ + accum[key] = value[key]; + return accum; + }, {}); + } + throw new Error(`should not happen: ${value} (${typeof value})`); } -function decode3(str) { - var res = __decode.apply(null, arguments); - if (typeof res === "object") return res; - throw new Error(res); +function stall$3(duration) { + return new Promise((resolve)=>{ + setTimeout(resolve, duration); + }); } -function convert(data, inBits, outBits, pad) { - var value = 0; - var bits = 0; - var maxV = (1 << outBits) - 1; - var result = []; - for(var i = 0; i < data.length; ++i){ - value = value << inBits | data[i]; - bits += inBits; - while(bits >= outBits){ - bits -= outBits; - result.push(value >> bits & maxV); - } - } - if (pad) { - if (bits > 0) { - result.push(value << outBits - bits & maxV); - } - } else { - if (bits >= inBits) return "Excess padding"; - if (value << outBits - bits & maxV) return "Non-zero padding"; +function getLowerCase(value) { + if (value) { + return value.toLowerCase(); } - return result; + return value; } -function toWordsUnsafe(bytes) { - var res = convert(bytes, 8, 5, true); - if (Array.isArray(res)) return res; -} -function toWords(bytes) { - var res = convert(bytes, 8, 5, true); - if (Array.isArray(res)) return res; - throw new Error(res); -} -function fromWordsUnsafe(words) { - var res = convert(words, 5, 8, false); - if (Array.isArray(res)) return res; -} -function fromWords(words) { - var res = convert(words, 5, 8, false); - if (Array.isArray(res)) return res; - throw new Error(res); -} -var bech32 = { - decodeUnsafe, - decode: decode3, - encode: encode2, - toWordsUnsafe, - toWords, - fromWordsUnsafe, - fromWords +function isPollable(value) { + return value && typeof value.pollingInterval === "number"; +} +const defaultOptions = { + polling: false, + staticNetwork: null, + batchStallTime: 10, + batchMaxSize: 1 << 20, + batchMaxCount: 100, + cacheTimeout: 250, + pollingInterval: 4e3 }; -bech32.decode; -bech32.decodeUnsafe; -bech32.encode; -bech32.fromWords; -bech32.fromWordsUnsafe; -bech32.toWords; -bech32.toWordsUnsafe; -const version23 = "providers/5.7.2"; -const logger221 = new Logger(version23); -class Formatter { - constructor(){ - this.formats = this.getDefaultFormats(); - } - getDefaultFormats() { - const formats = {}; - const address2 = this.address.bind(this); - const bigNumber = this.bigNumber.bind(this); - const blockTag = this.blockTag.bind(this); - const data = this.data.bind(this); - const hash2 = this.hash.bind(this); - const hex = this.hex.bind(this); - const number = this.number.bind(this); - const type = this.type.bind(this); - const strictData = (v)=>{ - return this.data(v, true); - }; - formats.transaction = { - hash: hash2, - type, - accessList: Formatter.allowNull(this.accessList.bind(this), null), - blockHash: Formatter.allowNull(hash2, null), - blockNumber: Formatter.allowNull(number, null), - transactionIndex: Formatter.allowNull(number, null), - confirmations: Formatter.allowNull(number, null), - from: address2, - gasPrice: Formatter.allowNull(bigNumber), - maxPriorityFeePerGas: Formatter.allowNull(bigNumber), - maxFeePerGas: Formatter.allowNull(bigNumber), - gasLimit: bigNumber, - to: Formatter.allowNull(address2, null), - value: bigNumber, - nonce: number, - data, - r: Formatter.allowNull(this.uint256), - s: Formatter.allowNull(this.uint256), - v: Formatter.allowNull(number), - creates: Formatter.allowNull(address2, null), - raw: Formatter.allowNull(data) - }; - formats.transactionRequest = { - from: Formatter.allowNull(address2), - nonce: Formatter.allowNull(number), - gasLimit: Formatter.allowNull(bigNumber), - gasPrice: Formatter.allowNull(bigNumber), - maxPriorityFeePerGas: Formatter.allowNull(bigNumber), - maxFeePerGas: Formatter.allowNull(bigNumber), - to: Formatter.allowNull(address2), - value: Formatter.allowNull(bigNumber), - data: Formatter.allowNull(strictData), - type: Formatter.allowNull(number), - accessList: Formatter.allowNull(this.accessList.bind(this), null) - }; - formats.receiptLog = { - transactionIndex: number, - blockNumber: number, - transactionHash: hash2, - address: address2, - topics: Formatter.arrayOf(hash2), - data, - logIndex: number, - blockHash: hash2 - }; - formats.receipt = { - to: Formatter.allowNull(this.address, null), - from: Formatter.allowNull(this.address, null), - contractAddress: Formatter.allowNull(address2, null), - transactionIndex: number, - root: Formatter.allowNull(hex), - gasUsed: bigNumber, - logsBloom: Formatter.allowNull(data), - blockHash: hash2, - transactionHash: hash2, - logs: Formatter.arrayOf(this.receiptLog.bind(this)), - blockNumber: number, - confirmations: Formatter.allowNull(number, null), - cumulativeGasUsed: bigNumber, - effectiveGasPrice: Formatter.allowNull(bigNumber), - status: Formatter.allowNull(number), - type - }; - formats.block = { - hash: Formatter.allowNull(hash2), - parentHash: hash2, - number, - timestamp: number, - nonce: Formatter.allowNull(hex), - difficulty: this.difficulty.bind(this), - gasLimit: bigNumber, - gasUsed: bigNumber, - miner: Formatter.allowNull(address2), - extraData: data, - transactions: Formatter.allowNull(Formatter.arrayOf(hash2)), - baseFeePerGas: Formatter.allowNull(bigNumber) - }; - formats.blockWithTransactions = shallowCopy(formats.block); - formats.blockWithTransactions.transactions = Formatter.allowNull(Formatter.arrayOf(this.transactionResponse.bind(this))); - formats.filter = { - fromBlock: Formatter.allowNull(blockTag, void 0), - toBlock: Formatter.allowNull(blockTag, void 0), - blockHash: Formatter.allowNull(hash2, void 0), - address: Formatter.allowNull(address2, void 0), - topics: Formatter.allowNull(this.topics.bind(this), void 0) - }; - formats.filterLog = { - blockNumber: Formatter.allowNull(number), - blockHash: Formatter.allowNull(hash2), - transactionIndex: number, - removed: Formatter.allowNull(this.boolean.bind(this)), - address: address2, - data: Formatter.allowFalsish(data, "0x"), - topics: Formatter.arrayOf(hash2), - transactionHash: hash2, - logIndex: number - }; - return formats; +class JsonRpcSigner extends AbstractSigner { + address; + constructor(provider, address){ + super(provider); + address = getAddress(address); + defineProperties(this, { + address: address + }); } - accessList(accessList) { - return accessListify(accessList || []); + connect(provider) { + assert1(false, "cannot reconnect JsonRpcSigner", "UNSUPPORTED_OPERATION", { + operation: "signer.connect" + }); } - number(number) { - if (number === "0x") { - return 0; + async getAddress() { + return this.address; + } + async populateTransaction(tx) { + return await this.populateCall(tx); + } + async sendUncheckedTransaction(_tx) { + const tx = deepCopy(_tx); + const promises = []; + if (tx.from) { + const _from = tx.from; + promises.push((async ()=>{ + const from = await resolveAddress(_from, this.provider); + assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + })()); + } else { + tx.from = this.address; } - return BigNumber.from(number).toNumber(); - } - type(number) { - if (number === "0x" || number == null) { - return 0; + if (tx.gasLimit == null) { + promises.push((async ()=>{ + tx.gasLimit = await this.provider.estimateGas({ + ...tx, + from: this.address + }); + })()); } - return BigNumber.from(number).toNumber(); - } - bigNumber(value) { - return BigNumber.from(value); - } - boolean(value) { - if (typeof value === "boolean") { - return value; + if (tx.to != null) { + const _to = tx.to; + promises.push((async ()=>{ + tx.to = await resolveAddress(_to, this.provider); + })()); } - if (typeof value === "string") { - value = value.toLowerCase(); - if (value === "true") { - return true; - } - if (value === "false") { - return false; - } + if (promises.length) { + await Promise.all(promises); } - throw new Error("invalid boolean - " + value); + const hexTx = this.provider.getRpcTransaction(tx); + return this.provider.send("eth_sendTransaction", [ + hexTx + ]); } - hex(value, strict) { - if (typeof value === "string") { - if (!strict && value.substring(0, 2) !== "0x") { - value = "0x" + value; - } - if (isHexString(value)) { - return value.toLowerCase(); - } - } - return logger221.throwArgumentError("invalid hash", "value", value); + async sendTransaction(tx) { + const blockNumber = await this.provider.getBlockNumber(); + const hash = await this.sendUncheckedTransaction(tx); + return await new Promise((resolve, reject)=>{ + const timeouts = [ + 1e3, + 100 + ]; + let invalids = 0; + const checkTx = async ()=>{ + try { + const tx = await this.provider.getTransaction(hash); + if (tx != null) { + resolve(tx.replaceableTransaction(blockNumber)); + return; + } + } catch (error) { + if (isError(error, "CANCELLED") || isError(error, "BAD_DATA") || isError(error, "NETWORK_ERROR") || isError(error, "UNSUPPORTED_OPERATION")) { + if (error.info == null) { + error.info = {}; + } + error.info.sendTransactionHash = hash; + reject(error); + return; + } + if (isError(error, "INVALID_ARGUMENT")) { + invalids++; + if (error.info == null) { + error.info = {}; + } + error.info.sendTransactionHash = hash; + if (invalids > 10) { + reject(error); + return; + } + } + this.provider.emit("error", makeError("failed to fetch transation after sending (will try again)", "UNKNOWN_ERROR", { + error: error + })); + } + this.provider._setTimeout(()=>{ + checkTx(); + }, timeouts.pop() || 4e3); + }; + checkTx(); + }); } - data(value, strict) { - const result = this.hex(value, strict); - if (result.length % 2 !== 0) { - throw new Error("invalid data; odd-length - " + value); + async signTransaction(_tx) { + const tx = deepCopy(_tx); + if (tx.from) { + const from = await resolveAddress(tx.from, this.provider); + assertArgument(from != null && from.toLowerCase() === this.address.toLowerCase(), "from address mismatch", "transaction", _tx); + tx.from = from; + } else { + tx.from = this.address; } - return result; + const hexTx = this.provider.getRpcTransaction(tx); + return await this.provider.send("eth_signTransaction", [ + hexTx + ]); } - address(value) { - return getAddress(value); + async signMessage(_message) { + const message = typeof _message === "string" ? toUtf8Bytes(_message) : _message; + return await this.provider.send("personal_sign", [ + hexlify(message), + this.address.toLowerCase() + ]); } - callAddress(value) { - if (!isHexString(value, 32)) { - return null; - } - const address2 = getAddress(hexDataSlice(value, 12)); - return address2 === AddressZero ? null : address2; + async signTypedData(domain, types, _value) { + const value = deepCopy(_value); + const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (value)=>{ + const address = await resolveAddress(value); + assertArgument(address != null, "TypedData does not support null address", "value", value); + return address; + }); + return await this.provider.send("eth_signTypedData_v4", [ + this.address.toLowerCase(), + JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types, populated.value)) + ]); + } + async unlock(password) { + return this.provider.send("personal_unlockAccount", [ + this.address.toLowerCase(), + password, + null + ]); } - contractAddress(value) { - return getContractAddress(value); + async _legacySignMessage(_message) { + const message = typeof _message === "string" ? toUtf8Bytes(_message) : _message; + return await this.provider.send("eth_sign", [ + this.address.toLowerCase(), + hexlify(message) + ]); } - blockTag(blockTag) { - if (blockTag == null) { - return "latest"; +} +class JsonRpcApiProvider extends AbstractProvider { + #options; + #nextId; + #payloads; + #drainTimer; + #notReady; + #network; + #pendingDetectNetwork; + #scheduleDrain() { + if (this.#drainTimer) { + return; + } + const stallTime = this._getOption("batchMaxCount") === 1 ? 0 : this._getOption("batchStallTime"); + this.#drainTimer = setTimeout(()=>{ + this.#drainTimer = null; + const payloads = this.#payloads; + this.#payloads = []; + while(payloads.length){ + const batch = [ + payloads.shift() + ]; + while(payloads.length){ + if (batch.length === this.#options.batchMaxCount) { + break; + } + batch.push(payloads.shift()); + const bytes = JSON.stringify(batch.map((p)=>p.payload)); + if (bytes.length > this.#options.batchMaxSize) { + payloads.unshift(batch.pop()); + break; + } + } + (async ()=>{ + const payload = batch.length === 1 ? batch[0].payload : batch.map((p)=>p.payload); + this.emit("debug", { + action: "sendRpcPayload", + payload: payload + }); + try { + const result = await this._send(payload); + this.emit("debug", { + action: "receiveRpcResult", + result: result + }); + for (const { resolve, reject, payload } of batch){ + if (this.destroyed) { + reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { + operation: payload.method + })); + continue; + } + const resp = result.filter((r)=>r.id === payload.id)[0]; + if (resp == null) { + const error = makeError("missing response for request", "BAD_DATA", { + value: result, + info: { + payload: payload + } + }); + this.emit("error", error); + reject(error); + continue; + } + if ("error" in resp) { + reject(this.getRpcError(payload, resp)); + continue; + } + resolve(resp.result); + } + } catch (error) { + this.emit("debug", { + action: "receiveRpcError", + error: error + }); + for (const { reject } of batch){ + reject(error); + } + } + })(); + } + }, stallTime); + } + constructor(network, options){ + super(network, options); + this.#nextId = 1; + this.#options = Object.assign({}, defaultOptions, options || {}); + this.#payloads = []; + this.#drainTimer = null; + this.#network = null; + this.#pendingDetectNetwork = null; + { + let resolve = null; + const promise = new Promise((_resolve)=>{ + resolve = _resolve; + }); + this.#notReady = { + promise: promise, + resolve: resolve + }; } - if (blockTag === "earliest") { - return "0x0"; + const staticNetwork = this._getOption("staticNetwork"); + if (typeof staticNetwork === "boolean") { + assertArgument(!staticNetwork || network !== "any", "staticNetwork cannot be used on special network 'any'", "options", options); + if (staticNetwork && network != null) { + this.#network = Network.from(network); + } + } else if (staticNetwork) { + assertArgument(network == null || staticNetwork.matches(network), "staticNetwork MUST match network object", "options", options); + this.#network = staticNetwork; + } + } + _getOption(key) { + return this.#options[key]; + } + get _network() { + assert1(this.#network, "network is not available yet", "NETWORK_ERROR"); + return this.#network; + } + async _perform(req) { + if (req.method === "call" || req.method === "estimateGas") { + let tx = req.transaction; + if (tx && tx.type != null && getBigInt(tx.type)) { + if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { + const feeData = await this.getFeeData(); + if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { + req = Object.assign({}, req, { + transaction: Object.assign({}, tx, { + type: undefined + }) + }); + } + } + } } - switch(blockTag){ - case "earliest": - return "0x0"; - case "latest": - case "pending": - case "safe": - case "finalized": - return blockTag; + const request = this.getRpcRequest(req); + if (request != null) { + return await this.send(request.method, request.args); } - if (typeof blockTag === "number" || isHexString(blockTag)) { - return hexValue(blockTag); + return super._perform(req); + } + async _detectNetwork() { + const network = this._getOption("staticNetwork"); + if (network) { + if (network === true) { + if (this.#network) { + return this.#network; + } + } else { + return network; + } } - throw new Error("invalid blockTag"); - } - hash(value, strict) { - const result = this.hex(value, strict); - if (hexDataLength(result) !== 32) { - return logger221.throwArgumentError("invalid hash", "value", value); + if (this.#pendingDetectNetwork) { + return await this.#pendingDetectNetwork; } - return result; - } - difficulty(value) { - if (value == null) { - return null; + if (this.ready) { + this.#pendingDetectNetwork = (async ()=>{ + try { + const result = Network.from(getBigInt(await this.send("eth_chainId", []))); + this.#pendingDetectNetwork = null; + return result; + } catch (error) { + this.#pendingDetectNetwork = null; + throw error; + } + })(); + return await this.#pendingDetectNetwork; } - const v = BigNumber.from(value); - try { - return v.toNumber(); - } catch (error) {} - return null; + this.#pendingDetectNetwork = (async ()=>{ + const payload = { + id: this.#nextId++, + method: "eth_chainId", + params: [], + jsonrpc: "2.0" + }; + this.emit("debug", { + action: "sendRpcPayload", + payload: payload + }); + let result; + try { + result = (await this._send(payload))[0]; + this.#pendingDetectNetwork = null; + } catch (error) { + this.#pendingDetectNetwork = null; + this.emit("debug", { + action: "receiveRpcError", + error: error + }); + throw error; + } + this.emit("debug", { + action: "receiveRpcResult", + result: result + }); + if ("result" in result) { + return Network.from(getBigInt(result.result)); + } + throw this.getRpcError(payload, result); + })(); + return await this.#pendingDetectNetwork; } - uint256(value) { - if (!isHexString(value)) { - throw new Error("invalid uint256"); + _start() { + if (this.#notReady == null || this.#notReady.resolve == null) { + return; } - return hexZeroPad(value, 32); + this.#notReady.resolve(); + this.#notReady = null; + (async ()=>{ + while(this.#network == null && !this.destroyed){ + try { + this.#network = await this._detectNetwork(); + } catch (error) { + if (this.destroyed) { + break; + } + console.log("JsonRpcProvider failed to detect network and cannot start up; retry in 1s (perhaps the URL is wrong or the node is not started)"); + this.emit("error", makeError("failed to bootstrap network detection", "NETWORK_ERROR", { + event: "initial-network-discovery", + info: { + error: error + } + })); + await stall$3(1e3); + } + } + this.#scheduleDrain(); + })(); } - _block(value, format) { - if (value.author != null && value.miner == null) { - value.miner = value.author; + async _waitUntilReady() { + if (this.#notReady == null) { + return; } - const difficulty = value._difficulty != null ? value._difficulty : value.difficulty; - const result = Formatter.check(format, value); - result._difficulty = difficulty == null ? null : BigNumber.from(difficulty); - return result; + return await this.#notReady.promise; } - block(value) { - return this._block(value, this.formats.block); - } - blockWithTransactions(value) { - return this._block(value, this.formats.blockWithTransactions); - } - transactionRequest(value) { - return Formatter.check(this.formats.transactionRequest, value); - } - transactionResponse(transaction) { - if (transaction.gas != null && transaction.gasLimit == null) { - transaction.gasLimit = transaction.gas; - } - if (transaction.to && BigNumber.from(transaction.to).isZero()) { - transaction.to = "0x0000000000000000000000000000000000000000"; + _getSubscriber(sub) { + if (sub.type === "pending") { + return new FilterIdPendingSubscriber(this); } - if (transaction.input != null && transaction.data == null) { - transaction.data = transaction.input; - } - if (transaction.to == null && transaction.creates == null) { - transaction.creates = this.contractAddress(transaction); + if (sub.type === "event") { + if (this._getOption("polling")) { + return new PollingEventSubscriber(this, sub.filter); + } + return new FilterIdEventSubscriber(this, sub.filter); } - if ((transaction.type === 1 || transaction.type === 2) && transaction.accessList == null) { - transaction.accessList = []; + if (sub.type === "orphan" && sub.filter.orphan === "drop-log") { + return new UnmanagedSubscriber("orphan"); } - const result = Formatter.check(this.formats.transaction, transaction); - if (transaction.chainId != null) { - let chainId = transaction.chainId; - if (isHexString(chainId)) { - chainId = BigNumber.from(chainId).toNumber(); - } - result.chainId = chainId; - } else { - let chainId = transaction.networkId; - if (chainId == null && result.v == null) { - chainId = transaction.chainId; - } - if (isHexString(chainId)) { - chainId = BigNumber.from(chainId).toNumber(); + return super._getSubscriber(sub); + } + get ready() { + return this.#notReady == null; + } + getRpcTransaction(tx) { + const result = {}; + [ + "chainId", + "gasLimit", + "gasPrice", + "type", + "maxFeePerGas", + "maxPriorityFeePerGas", + "nonce", + "value" + ].forEach((key)=>{ + if (tx[key] == null) { + return; } - if (typeof chainId !== "number" && result.v != null) { - chainId = (result.v - 35) / 2; - if (chainId < 0) { - chainId = 0; - } - chainId = parseInt(chainId); + let dstKey = key; + if (key === "gasLimit") { + dstKey = "gas"; } - if (typeof chainId !== "number") { - chainId = 0; + result[dstKey] = toQuantity(getBigInt(tx[key], `tx.${key}`)); + }); + [ + "from", + "to", + "data" + ].forEach((key)=>{ + if (tx[key] == null) { + return; } - result.chainId = chainId; + result[key] = hexlify(tx[key]); + }); + if (tx.accessList) { + result["accessList"] = accessListify(tx.accessList); } - if (result.blockHash && result.blockHash.replace(/0/g, "") === "x") { - result.blockHash = null; + if (tx.blobVersionedHashes) { + result["blobVersionedHashes"] = tx.blobVersionedHashes.map((h)=>h.toLowerCase()); } return result; } - transaction(value) { - return parse(value); - } - receiptLog(value) { - return Formatter.check(this.formats.receiptLog, value); - } - receipt(value) { - const result = Formatter.check(this.formats.receipt, value); - if (result.root != null) { - if (result.root.length <= 4) { - const value2 = BigNumber.from(result.root).toNumber(); - if (value2 === 0 || value2 === 1) { - if (result.status != null && result.status !== value2) { - logger221.throwArgumentError("alt-root-status/status mismatch", "value", { - root: result.root, - status: result.status - }); + getRpcRequest(req) { + switch(req.method){ + case "chainId": + return { + method: "eth_chainId", + args: [] + }; + case "getBlockNumber": + return { + method: "eth_blockNumber", + args: [] + }; + case "getGasPrice": + return { + method: "eth_gasPrice", + args: [] + }; + case "getPriorityFee": + return { + method: "eth_maxPriorityFeePerGas", + args: [] + }; + case "getBalance": + return { + method: "eth_getBalance", + args: [ + getLowerCase(req.address), + req.blockTag + ] + }; + case "getTransactionCount": + return { + method: "eth_getTransactionCount", + args: [ + getLowerCase(req.address), + req.blockTag + ] + }; + case "getCode": + return { + method: "eth_getCode", + args: [ + getLowerCase(req.address), + req.blockTag + ] + }; + case "getStorage": + return { + method: "eth_getStorageAt", + args: [ + getLowerCase(req.address), + "0x" + req.position.toString(16), + req.blockTag + ] + }; + case "broadcastTransaction": + return { + method: "eth_sendRawTransaction", + args: [ + req.signedTransaction + ] + }; + case "getBlock": + if ("blockTag" in req) { + return { + method: "eth_getBlockByNumber", + args: [ + req.blockTag, + !!req.includeTransactions + ] + }; + } else if ("blockHash" in req) { + return { + method: "eth_getBlockByHash", + args: [ + req.blockHash, + !!req.includeTransactions + ] + }; + } + break; + case "getTransaction": + return { + method: "eth_getTransactionByHash", + args: [ + req.hash + ] + }; + case "getTransactionReceipt": + return { + method: "eth_getTransactionReceipt", + args: [ + req.hash + ] + }; + case "call": + return { + method: "eth_call", + args: [ + this.getRpcTransaction(req.transaction), + req.blockTag + ] + }; + case "estimateGas": + { + return { + method: "eth_estimateGas", + args: [ + this.getRpcTransaction(req.transaction) + ] + }; + } + case "getLogs": + if (req.filter && req.filter.address != null) { + if (Array.isArray(req.filter.address)) { + req.filter.address = req.filter.address.map(getLowerCase); + } else { + req.filter.address = getLowerCase(req.filter.address); } - result.status = value2; - delete result.root; - } else { - logger221.throwArgumentError("invalid alt-root-status", "value.root", result.root); } - } else if (result.root.length !== 66) { - logger221.throwArgumentError("invalid root hash", "value.root", result.root); - } - } - if (result.status != null) { - result.byzantium = true; - } - return result; - } - topics(value) { - if (Array.isArray(value)) { - return value.map((v)=>this.topics(v)); - } else if (value != null) { - return this.hash(value, true); + return { + method: "eth_getLogs", + args: [ + req.filter + ] + }; } return null; } - filter(value) { - return Formatter.check(this.formats.filter, value); - } - filterLog(value) { - return Formatter.check(this.formats.filterLog, value); - } - static check(format, object) { - const result = {}; - for(const key in format){ - try { - const value = format[key](object[key]); - if (value !== void 0) { - result[key] = value; - } - } catch (error) { - error.checkKey = key; - error.checkValue = object[key]; - throw error; + getRpcError(payload, _error) { + const { method } = payload; + const { error } = _error; + if (method === "eth_estimateGas" && error.message) { + const msg = error.message; + if (!msg.match(/revert/i) && msg.match(/insufficient funds/i)) { + return makeError("insufficient funds", "INSUFFICIENT_FUNDS", { + transaction: payload.params[0], + info: { + payload: payload, + error: error + } + }); } } - return result; - } - static allowNull(format, nullValue) { - return function(value) { - if (value == null) { - return nullValue; + if (method === "eth_call" || method === "eth_estimateGas") { + const result = spelunkData(error); + const e = AbiCoder.getBuiltinCallException(method === "eth_call" ? "call" : "estimateGas", payload.params[0], result ? result.data : null); + e.info = { + error: error, + payload: payload + }; + return e; + } + const message = JSON.stringify(spelunkMessage(error)); + if (typeof error.message === "string" && error.message.match(/user denied|ethers-user-denied/i)) { + const actionMap = { + eth_sign: "signMessage", + personal_sign: "signMessage", + eth_signTypedData_v4: "signTypedData", + eth_signTransaction: "signTransaction", + eth_sendTransaction: "sendTransaction", + eth_requestAccounts: "requestAccess", + wallet_requestAccounts: "requestAccess" + }; + return makeError(`user rejected action`, "ACTION_REJECTED", { + action: actionMap[method] || "unknown", + reason: "rejected", + info: { + payload: payload, + error: error + } + }); + } + if (method === "eth_sendRawTransaction" || method === "eth_sendTransaction") { + const transaction = payload.params[0]; + if (message.match(/insufficient funds|base fee exceeds gas limit/i)) { + return makeError("insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction: transaction, + info: { + error: error + } + }); } - return format(value); - }; - } - static allowFalsish(format, replaceValue) { - return function(value) { - if (!value) { - return replaceValue; + if (message.match(/nonce/i) && message.match(/too low/i)) { + return makeError("nonce has already been used", "NONCE_EXPIRED", { + transaction: transaction, + info: { + error: error + } + }); } - return format(value); - }; - } - static arrayOf(format) { - return function(array) { - if (!Array.isArray(array)) { - throw new Error("not an array"); + if (message.match(/replacement transaction/i) && message.match(/underpriced/i)) { + return makeError("replacement fee too low", "REPLACEMENT_UNDERPRICED", { + transaction: transaction, + info: { + error: error + } + }); + } + if (message.match(/only replay-protected/i)) { + return makeError("legacy pre-eip-155 transactions not supported", "UNSUPPORTED_OPERATION", { + operation: method, + info: { + transaction: transaction, + info: { + error: error + } + } + }); + } + } + let unsupported = !!message.match(/the method .* does not exist/i); + if (!unsupported) { + if (error && error.details && error.details.startsWith("Unauthorized method:")) { + unsupported = true; } - const result = []; - array.forEach(function(value) { - result.push(format(value)); + } + if (unsupported) { + return makeError("unsupported operation", "UNSUPPORTED_OPERATION", { + operation: payload.method, + info: { + error: error, + payload: payload + } }); - return result; - }; - } -} -function isCommunityResourcable(value) { - return value && typeof value.isCommunityResource === "function"; -} -function isCommunityResource(value) { - return isCommunityResourcable(value) && value.isCommunityResource(); -} -let throttleMessage = false; -function showThrottleMessage() { - if (throttleMessage) { - return; + } + return makeError("could not coalesce error", "UNKNOWN_ERROR", { + error: error, + payload: payload + }); } - throttleMessage = true; - console.log("========= NOTICE ========="); - console.log("Request-Rate Exceeded (this message will not be repeated)"); - console.log(""); - console.log("The default API keys for each service are provided as a highly-throttled,"); - console.log("community resource for low-traffic projects and early prototyping."); - console.log(""); - console.log("While your application will continue to function, we highly recommended"); - console.log("signing up for your own API keys to improve performance, increase your"); - console.log("request rate/limit and enable other perks, such as metrics and advanced APIs."); - console.log(""); - console.log("For more details: https://docs.ethers.io/api-keys/"); - console.log("=========================="); -} -var __awaiter8 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); + send(method, params) { + if (this.destroyed) { + return Promise.reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { + operation: method + })); + } + const id = this.#nextId++; + const promise = new Promise((resolve, reject)=>{ + this.#payloads.push({ + resolve: resolve, + reject: reject, + payload: { + method: method, + params: params, + id: id, + jsonrpc: "2.0" + } + }); }); + this.#scheduleDrain(); + return promise; } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } + async getSigner(address) { + if (address == null) { + address = 0; } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + const accountsPromise = this.send("eth_accounts", []); + if (typeof address === "number") { + const accounts = await accountsPromise; + if (address >= accounts.length) { + throw new Error("no such account"); } + return new JsonRpcSigner(this, accounts[address]); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + const { accounts } = await resolveProperties({ + network: this.getNetwork(), + accounts: accountsPromise + }); + address = getAddress(address); + for (const account of accounts){ + if (getAddress(account) === address) { + return new JsonRpcSigner(this, address); + } } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger$14 = new Logger(version23); -function checkTopic(topic) { - if (topic == null) { - return "null"; + throw new Error("invalid account"); } - if (hexDataLength(topic) !== 32) { - logger$14.throwArgumentError("invalid topic", "topic", topic); + async listAccounts() { + const accounts = await this.send("eth_accounts", []); + return accounts.map((a)=>new JsonRpcSigner(this, a)); + } + destroy() { + if (this.#drainTimer) { + clearTimeout(this.#drainTimer); + this.#drainTimer = null; + } + for (const { payload, reject } of this.#payloads){ + reject(makeError("provider destroyed; cancelled request", "UNSUPPORTED_OPERATION", { + operation: payload.method + })); + } + this.#payloads = []; + super.destroy(); } - return topic.toLowerCase(); } -function serializeTopics(topics) { - topics = topics.slice(); - while(topics.length > 0 && topics[topics.length - 1] == null){ - topics.pop(); +class JsonRpcApiPollingProvider extends JsonRpcApiProvider { + #pollingInterval; + constructor(network, options){ + super(network, options); + let pollingInterval = this._getOption("pollingInterval"); + if (pollingInterval == null) { + pollingInterval = defaultOptions.pollingInterval; + } + this.#pollingInterval = pollingInterval; } - return topics.map((topic)=>{ - if (Array.isArray(topic)) { - const unique = {}; - topic.forEach((topic2)=>{ - unique[checkTopic(topic2)] = true; - }); - const sorted = Object.keys(unique); - sorted.sort(); - return sorted.join("|"); - } else { - return checkTopic(topic); + _getSubscriber(sub) { + const subscriber = super._getSubscriber(sub); + if (isPollable(subscriber)) { + subscriber.pollingInterval = this.#pollingInterval; } - }).join("&"); -} -function deserializeTopics(data) { - if (data === "") { - return []; + return subscriber; } - return data.split(/&/g).map((topic)=>{ - if (topic === "") { - return []; + get pollingInterval() { + return this.#pollingInterval; + } + set pollingInterval(value) { + if (!Number.isInteger(value) || value < 0) { + throw new Error("invalid interval"); } - const comps = topic.split("|").map((topic2)=>{ - return topic2 === "null" ? null : topic2; + this.#pollingInterval = value; + this._forEachSubscriber((sub)=>{ + if (isPollable(sub)) { + sub.pollingInterval = this.#pollingInterval; + } }); - return comps.length === 1 ? comps[0] : comps; - }); + } } -function getEventTag1(eventName) { - if (typeof eventName === "string") { - eventName = eventName.toLowerCase(); - if (hexDataLength(eventName) === 32) { - return "tx:" + eventName; +class JsonRpcProvider extends JsonRpcApiPollingProvider { + #connect; + constructor(url, network, options){ + if (url == null) { + url = "http://localhost:8545"; } - if (eventName.indexOf(":") === -1) { - return eventName; + super(network, options); + if (typeof url === "string") { + this.#connect = new FetchRequest(url); + } else { + this.#connect = url.clone(); + } + } + _getConnection() { + return this.#connect.clone(); + } + async send(method, params) { + await this._start(); + return await super.send(method, params); + } + async _send(payload) { + const request = this._getConnection(); + request.body = JSON.stringify(payload); + request.setHeader("content-type", "application/json"); + const response = await request.send(); + response.assertOk(); + let resp = response.bodyJson; + if (!Array.isArray(resp)) { + resp = [ + resp + ]; } - } else if (Array.isArray(eventName)) { - return "filter:*:" + serializeTopics(eventName); - } else if (ForkEvent.isForkEvent(eventName)) { - logger$14.warn("not implemented"); - throw new Error("not implemented"); - } else if (eventName && typeof eventName === "object") { - return "filter:" + (eventName.address || "*") + ":" + serializeTopics(eventName.topics || []); + return resp; } - throw new Error("invalid event - " + eventName); -} -function getTime() { - return new Date().getTime(); -} -function stall(duration) { - return new Promise((resolve)=>{ - setTimeout(resolve, duration); - }); } -const PollableEvents = [ - "block", - "network", - "pending", - "poll" -]; -class Event { - constructor(tag, listener, once){ - defineReadOnly(this, "tag", tag); - defineReadOnly(this, "listener", listener); - defineReadOnly(this, "once", once); - this._lastBlockNumber = -2; - this._inflight = false; - } - get event() { - switch(this.type){ - case "tx": - return this.hash; - case "filter": - return this.filter; - } - return this.tag; - } - get type() { - return this.tag.split(":")[0]; +function spelunkData(value) { + if (value == null) { + return null; } - get hash() { - const comps = this.tag.split(":"); - if (comps[0] !== "tx") { - return null; - } - return comps[1]; + if (typeof value.message === "string" && value.message.match(/revert/i) && isHexString(value.data)) { + return { + message: value.message, + data: value.data + }; } - get filter() { - const comps = this.tag.split(":"); - if (comps[0] !== "filter") { - return null; - } - const address2 = comps[1]; - const topics = deserializeTopics(comps[2]); - const filter = {}; - if (topics.length > 0) { - filter.topics = topics; - } - if (address2 && address2 !== "*") { - filter.address = address2; + if (typeof value === "object") { + for(const key in value){ + const result = spelunkData(value[key]); + if (result) { + return result; + } } - return filter; - } - pollable() { - return this.tag.indexOf(":") >= 0 || PollableEvents.indexOf(this.tag) >= 0; + return null; } -} -const coinInfos = { - "0": { - symbol: "btc", - p2pkh: 0, - p2sh: 5, - prefix: "bc" - }, - "2": { - symbol: "ltc", - p2pkh: 48, - p2sh: 50, - prefix: "ltc" - }, - "3": { - symbol: "doge", - p2pkh: 30, - p2sh: 22 - }, - "60": { - symbol: "eth", - ilk: "eth" - }, - "61": { - symbol: "etc", - ilk: "eth" - }, - "700": { - symbol: "xdai", - ilk: "eth" + if (typeof value === "string") { + try { + return spelunkData(JSON.parse(value)); + } catch (error) {} } -}; -function bytes32ify(value) { - return hexZeroPad(BigNumber.from(value).toHexString(), 32); -} -function base58Encode(data) { - return Base58.encode(concat([ - data, - hexDataSlice(sha2561(sha2561(data)), 0, 4) - ])); -} -const matcherIpfs = new RegExp("^(ipfs)://(.*)$", "i"); -const matchers = [ - new RegExp("^(https)://(.*)$", "i"), - new RegExp("^(data):(.*)$", "i"), - matcherIpfs, - new RegExp("^eip155:[0-9]+/(erc[0-9]+):(.*)$", "i") -]; -function _parseString(result, start) { - try { - return toUtf8String(_parseBytes(result, start)); - } catch (error) {} return null; } -function _parseBytes(result, start) { - if (result === "0x") { - return null; +function _spelunkMessage(value, result) { + if (value == null) { + return; } - const offset = BigNumber.from(hexDataSlice(result, start, start + 32)).toNumber(); - const length = BigNumber.from(hexDataSlice(result, offset, offset + 32)).toNumber(); - return hexDataSlice(result, offset + 32, offset + 32 + length); -} -function getIpfsLink(link) { - if (link.match(/^ipfs:\/\/ipfs\//i)) { - link = link.substring(12); - } else if (link.match(/^ipfs:\/\//i)) { - link = link.substring(7); - } else { - logger$14.throwArgumentError("unsupported IPFS format", "link", link); + if (typeof value.message === "string") { + result.push(value.message); } - return `https://gateway.ipfs.io/ipfs/${link}`; -} -function numPad(value) { - const result = arrayify(value); - if (result.length > 32) { - throw new Error("internal; should not happen"); + if (typeof value === "object") { + for(const key in value){ + _spelunkMessage(value[key], result); + } } - const padded = new Uint8Array(32); - padded.set(result, 32 - result.length); - return padded; -} -function bytesPad(value) { - if (value.length % 32 === 0) { - return value; + if (typeof value === "string") { + try { + return _spelunkMessage(JSON.parse(value), result); + } catch (error) {} } - const result = new Uint8Array(Math.ceil(value.length / 32) * 32); - result.set(value); - return result; } -function encodeBytes(datas) { +function spelunkMessage(value) { const result = []; - let byteCount = 0; - for(let i = 0; i < datas.length; i++){ - result.push(null); - byteCount += 32; - } - for(let i = 0; i < datas.length; i++){ - const data = arrayify(datas[i]); - result[i] = numPad(byteCount); - result.push(numPad(data.length)); - result.push(bytesPad(data)); - byteCount += 32 + Math.ceil(data.length / 32) * 32; - } - return hexConcat(result); -} -class Resolver { - constructor(provider, address2, name, resolvedAddress){ - defineReadOnly(this, "provider", provider); - defineReadOnly(this, "name", name); - defineReadOnly(this, "address", provider.formatter.address(address2)); - defineReadOnly(this, "_resolvedAddress", resolvedAddress); - } - supportsWildcard() { - if (!this._supportsEip2544) { - this._supportsEip2544 = this.provider.call({ - to: this.address, - data: "0x01ffc9a79061b92300000000000000000000000000000000000000000000000000000000" - }).then((result)=>{ - return BigNumber.from(result).eq(1); - }).catch((error)=>{ - if (error.code === Logger.errors.CALL_EXCEPTION) { - return false; - } - this._supportsEip2544 = null; - throw error; - }); + _spelunkMessage(value, result); + return result; +} +const defaultApiKey$1 = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972"; +function getHost$5(name) { + switch(name){ + case "mainnet": + return "rpc.ankr.com/eth"; + case "goerli": + return "rpc.ankr.com/eth_goerli"; + case "sepolia": + return "rpc.ankr.com/eth_sepolia"; + case "arbitrum": + return "rpc.ankr.com/arbitrum"; + case "base": + return "rpc.ankr.com/base"; + case "base-goerli": + return "rpc.ankr.com/base_goerli"; + case "base-sepolia": + return "rpc.ankr.com/base_sepolia"; + case "bnb": + return "rpc.ankr.com/bsc"; + case "bnbt": + return "rpc.ankr.com/bsc_testnet_chapel"; + case "matic": + return "rpc.ankr.com/polygon"; + case "matic-mumbai": + return "rpc.ankr.com/polygon_mumbai"; + case "optimism": + return "rpc.ankr.com/optimism"; + case "optimism-goerli": + return "rpc.ankr.com/optimism_testnet"; + case "optimism-sepolia": + return "rpc.ankr.com/optimism_sepolia"; + } + assertArgument(false, "unsupported network", "network", name); +} +class AnkrProvider extends JsonRpcProvider { + apiKey; + constructor(_network, apiKey){ + if (_network == null) { + _network = "mainnet"; + } + const network = Network.from(_network); + if (apiKey == null) { + apiKey = defaultApiKey$1; } - return this._supportsEip2544; - } - _fetch(selector, parameters) { - return __awaiter8(this, void 0, void 0, function*() { - const tx = { - to: this.address, - ccipReadEnabled: true, - data: hexConcat([ - selector, - namehash(this.name), - parameters || "0x" - ]) - }; - let parseBytes = false; - if (yield this.supportsWildcard()) { - parseBytes = true; - tx.data = hexConcat([ - "0x9061b923", - encodeBytes([ - dnsEncode(this.name), - tx.data - ]) - ]); - } - try { - let result = yield this.provider.call(tx); - if (arrayify(result).length % 32 === 4) { - logger$14.throwError("resolver threw error", Logger.errors.CALL_EXCEPTION, { - transaction: tx, - data: result - }); - } - if (parseBytes) { - result = _parseBytes(result, 0); - } - return result; - } catch (error) { - if (error.code === Logger.errors.CALL_EXCEPTION) { - return null; - } - throw error; - } + const options = { + polling: true, + staticNetwork: network + }; + const request = AnkrProvider.getRequest(network, apiKey); + super(request, network, options); + defineProperties(this, { + apiKey: apiKey }); } - _fetchBytes(selector, parameters) { - return __awaiter8(this, void 0, void 0, function*() { - const result = yield this._fetch(selector, parameters); - if (result != null) { - return _parseBytes(result, 0); - } - return null; - }); + _getProvider(chainId) { + try { + return new AnkrProvider(chainId, this.apiKey); + } catch (error) {} + return super._getProvider(chainId); } - _getAddress(coinType, hexBytes) { - const coinInfo = coinInfos[String(coinType)]; - if (coinInfo == null) { - logger$14.throwError(`unsupported coin type: ${coinType}`, Logger.errors.UNSUPPORTED_OPERATION, { - operation: `getAddress(${coinType})` - }); - } - if (coinInfo.ilk === "eth") { - return this.provider.formatter.address(hexBytes); - } - const bytes2 = arrayify(hexBytes); - if (coinInfo.p2pkh != null) { - const p2pkh = hexBytes.match(/^0x76a9([0-9a-f][0-9a-f])([0-9a-f]*)88ac$/); - if (p2pkh) { - const length = parseInt(p2pkh[1], 16); - if (p2pkh[2].length === length * 2 && length >= 1 && length <= 75) { - return base58Encode(concat([ - [ - coinInfo.p2pkh - ], - "0x" + p2pkh[2] - ])); - } - } + static getRequest(network, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey$1; } - if (coinInfo.p2sh != null) { - const p2sh = hexBytes.match(/^0xa9([0-9a-f][0-9a-f])([0-9a-f]*)87$/); - if (p2sh) { - const length = parseInt(p2sh[1], 16); - if (p2sh[2].length === length * 2 && length >= 1 && length <= 75) { - return base58Encode(concat([ - [ - coinInfo.p2sh - ], - "0x" + p2sh[2] - ])); - } - } + const request = new FetchRequest(`https:/\/${getHost$5(network.name)}/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey$1) { + request.retryFunc = async (request, response, attempt)=>{ + showThrottleMessage("AnkrProvider"); + return true; + }; } - if (coinInfo.prefix != null) { - const length = bytes2[1]; - let version2 = bytes2[0]; - if (version2 === 0) { - if (length !== 20 && length !== 32) { - version2 = -1; - } - } else { - version2 = -1; - } - if (version2 >= 0 && bytes2.length === 2 + length && length >= 1 && length <= 75) { - const words = bech32.toWords(bytes2.slice(2)); - words.unshift(version2); - return bech32.encode(coinInfo.prefix, words); + return request; + } + getRpcError(payload, error) { + if (payload.method === "eth_sendRawTransaction") { + if (error && error.error && error.error.message === "INTERNAL_ERROR: could not replace existing tx") { + error.error.message = "replacement transaction underpriced"; } } - return null; + return super.getRpcError(payload, error); } - getAddress(coinType) { - return __awaiter8(this, void 0, void 0, function*() { - if (coinType == null) { - coinType = 60; - } - if (coinType === 60) { - try { - const result = yield this._fetch("0x3b3b57de"); - if (result === "0x" || result === HashZero) { - return null; - } - return this.provider.formatter.callAddress(result); - } catch (error) { - if (error.code === Logger.errors.CALL_EXCEPTION) { - return null; - } - throw error; - } - } - const hexBytes = yield this._fetchBytes("0xf1cb7e06", bytes32ify(coinType)); - if (hexBytes == null || hexBytes === "0x") { - return null; - } - const address2 = this._getAddress(coinType, hexBytes); - if (address2 == null) { - logger$14.throwError(`invalid or unsupported coin data`, Logger.errors.UNSUPPORTED_OPERATION, { - operation: `getAddress(${coinType})`, - coinType, - data: hexBytes - }); - } - return address2; - }); + isCommunityResource() { + return this.apiKey === defaultApiKey$1; } - getAvatar() { - return __awaiter8(this, void 0, void 0, function*() { - const linkage = [ - { - type: "name", - content: this.name - } - ]; - try { - const avatar = yield this.getText("avatar"); - if (avatar == null) { - return null; - } - for(let i = 0; i < matchers.length; i++){ - const match = avatar.match(matchers[i]); - if (match == null) { - continue; - } - const scheme = match[1].toLowerCase(); - switch(scheme){ - case "https": - linkage.push({ - type: "url", - content: avatar - }); - return { - linkage, - url: avatar - }; - case "data": - linkage.push({ - type: "data", - content: avatar - }); - return { - linkage, - url: avatar - }; - case "ipfs": - linkage.push({ - type: "ipfs", - content: avatar - }); - return { - linkage, - url: getIpfsLink(avatar) - }; - case "erc721": - case "erc1155": - { - const selector = scheme === "erc721" ? "0xc87b56dd" : "0x0e89341c"; - linkage.push({ - type: scheme, - content: avatar - }); - const owner = this._resolvedAddress || (yield this.getAddress()); - const comps = (match[2] || "").split("/"); - if (comps.length !== 2) { - return null; - } - const addr = yield this.provider.formatter.address(comps[0]); - const tokenId = hexZeroPad(BigNumber.from(comps[1]).toHexString(), 32); - if (scheme === "erc721") { - const tokenOwner = this.provider.formatter.callAddress((yield this.provider.call({ - to: addr, - data: hexConcat([ - "0x6352211e", - tokenId - ]) - }))); - if (owner !== tokenOwner) { - return null; - } - linkage.push({ - type: "owner", - content: tokenOwner - }); - } else if (scheme === "erc1155") { - const balance = BigNumber.from((yield this.provider.call({ - to: addr, - data: hexConcat([ - "0x00fdd58e", - hexZeroPad(owner, 32), - tokenId - ]) - }))); - if (balance.isZero()) { - return null; - } - linkage.push({ - type: "balance", - content: balance.toString() - }); - } - const tx = { - to: this.provider.formatter.address(comps[0]), - data: hexConcat([ - selector, - tokenId - ]) - }; - let metadataUrl = _parseString((yield this.provider.call(tx)), 0); - if (metadataUrl == null) { - return null; - } - linkage.push({ - type: "metadata-url-base", - content: metadataUrl - }); - if (scheme === "erc1155") { - metadataUrl = metadataUrl.replace("{id}", tokenId.substring(2)); - linkage.push({ - type: "metadata-url-expanded", - content: metadataUrl - }); - } - if (metadataUrl.match(/^ipfs:/i)) { - metadataUrl = getIpfsLink(metadataUrl); - } - linkage.push({ - type: "metadata-url", - content: metadataUrl - }); - const metadata = yield fetchJson(metadataUrl); - if (!metadata) { - return null; - } - linkage.push({ - type: "metadata", - content: JSON.stringify(metadata) - }); - let imageUrl = metadata.image; - if (typeof imageUrl !== "string") { - return null; - } - if (imageUrl.match(/^(https:\/\/|data:)/i)) {} else { - const ipfs = imageUrl.match(matcherIpfs); - if (ipfs == null) { - return null; - } - linkage.push({ - type: "url-ipfs", - content: imageUrl - }); - imageUrl = getIpfsLink(imageUrl); - } - linkage.push({ - type: "url", - content: imageUrl - }); - return { - linkage, - url: imageUrl - }; - } - } - } - } catch (error) {} - return null; +} +const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC"; +function getHost$4(name) { + switch(name){ + case "mainnet": + return "eth-mainnet.alchemyapi.io"; + case "goerli": + return "eth-goerli.g.alchemy.com"; + case "sepolia": + return "eth-sepolia.g.alchemy.com"; + case "arbitrum": + return "arb-mainnet.g.alchemy.com"; + case "arbitrum-goerli": + return "arb-goerli.g.alchemy.com"; + case "arbitrum-sepolia": + return "arb-sepolia.g.alchemy.com"; + case "base": + return "base-mainnet.g.alchemy.com"; + case "base-goerli": + return "base-goerli.g.alchemy.com"; + case "base-sepolia": + return "base-sepolia.g.alchemy.com"; + case "matic": + return "polygon-mainnet.g.alchemy.com"; + case "matic-amoy": + return "polygon-amoy.g.alchemy.com"; + case "matic-mumbai": + return "polygon-mumbai.g.alchemy.com"; + case "optimism": + return "opt-mainnet.g.alchemy.com"; + case "optimism-goerli": + return "opt-goerli.g.alchemy.com"; + case "optimism-sepolia": + return "opt-sepolia.g.alchemy.com"; + } + assertArgument(false, "unsupported network", "network", name); +} +class AlchemyProvider extends JsonRpcProvider { + apiKey; + constructor(_network, apiKey){ + if (_network == null) { + _network = "mainnet"; + } + const network = Network.from(_network); + if (apiKey == null) { + apiKey = defaultApiKey; + } + const request = AlchemyProvider.getRequest(network, apiKey); + super(request, network, { + staticNetwork: network + }); + defineProperties(this, { + apiKey: apiKey }); } - getContentHash() { - return __awaiter8(this, void 0, void 0, function*() { - const hexBytes = yield this._fetchBytes("0xbc1c58d1"); - if (hexBytes == null || hexBytes === "0x") { + _getProvider(chainId) { + try { + return new AlchemyProvider(chainId, this.apiKey); + } catch (error) {} + return super._getProvider(chainId); + } + async _perform(req) { + if (req.method === "getTransactionResult") { + const { trace, tx } = await resolveProperties({ + trace: this.send("trace_transaction", [ + req.hash + ]), + tx: this.getTransaction(req.hash) + }); + if (trace == null || tx == null) { return null; } - const ipfs = hexBytes.match(/^0xe3010170(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); - if (ipfs) { - const length = parseInt(ipfs[3], 16); - if (ipfs[4].length === length * 2) { - return "ipfs://" + Base58.encode("0x" + ipfs[1]); - } - } - const ipns = hexBytes.match(/^0xe5010172(([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f]*))$/); - if (ipns) { - const length = parseInt(ipns[3], 16); - if (ipns[4].length === length * 2) { - return "ipns://" + Base58.encode("0x" + ipns[1]); - } - } - const swarm = hexBytes.match(/^0xe40101fa011b20([0-9a-f]*)$/); - if (swarm) { - if (swarm[1].length === 32 * 2) { - return "bzz://" + swarm[1]; - } - } - const skynet = hexBytes.match(/^0x90b2c605([0-9a-f]*)$/); - if (skynet) { - if (skynet[1].length === 34 * 2) { - const urlSafe = { - "=": "", - "+": "-", - "/": "_" - }; - const hash2 = encode1("0x" + skynet[1]).replace(/[=+\/]/g, (a)=>urlSafe[a]); - return "sia://" + hash2; - } + let data; + let error = false; + try { + data = trace[0].result.output; + error = trace[0].error === "Reverted"; + } catch (error) {} + if (data) { + assert1(!error, "an error occurred during transaction executions", "CALL_EXCEPTION", { + action: "getTransactionResult", + data: data, + reason: null, + transaction: tx, + invocation: null, + revert: null + }); + return data; } - return logger$14.throwError(`invalid or unsupported content hash data`, Logger.errors.UNSUPPORTED_OPERATION, { - operation: "getContentHash()", - data: hexBytes + assert1(false, "could not parse trace result", "BAD_DATA", { + value: trace }); - }); + } + return await super._perform(req); } - getText(key) { - return __awaiter8(this, void 0, void 0, function*() { - let keyBytes = toUtf8Bytes(key); - keyBytes = concat([ - bytes32ify(64), - bytes32ify(keyBytes.length), - keyBytes - ]); - if (keyBytes.length % 32 !== 0) { - keyBytes = concat([ - keyBytes, - hexZeroPad("0x", 32 - key.length % 32) - ]); - } - const hexBytes = yield this._fetchBytes("0x59d1d43c", hexlify(keyBytes)); - if (hexBytes == null || hexBytes === "0x") { - return null; - } - return toUtf8String(hexBytes); - }); + isCommunityResource() { + return this.apiKey === defaultApiKey; + } + static getRequest(network, apiKey) { + if (apiKey == null) { + apiKey = defaultApiKey; + } + const request = new FetchRequest(`https:/\/${getHost$4(network.name)}/v2/${apiKey}`); + request.allowGzip = true; + if (apiKey === defaultApiKey) { + request.retryFunc = async (request, response, attempt)=>{ + showThrottleMessage("alchemy"); + return true; + }; + } + return request; + } +} +function getApiKey(name) { + switch(name){ + case "mainnet": + return "39f1d67cedf8b7831010a665328c9197"; + case "arbitrum": + return "0550c209db33c3abf4cc927e1e18cea1"; + case "bnb": + return "98b5a77e531614387366f6fc5da097f8"; + case "matic": + return "cd9d4d70377471aa7c142ec4a4205249"; + } + assertArgument(false, "unsupported network", "network", name); +} +function getHost$3(name) { + switch(name){ + case "mainnet": + return "ethereum-mainnet.core.chainstack.com"; + case "arbitrum": + return "arbitrum-mainnet.core.chainstack.com"; + case "bnb": + return "bsc-mainnet.core.chainstack.com"; + case "matic": + return "polygon-mainnet.core.chainstack.com"; } + assertArgument(false, "unsupported network", "network", name); } -let defaultFormatter = null; -let nextPollId = 1; -class BaseProvider extends Provider { - constructor(network){ - super(); - this._events = []; - this._emitted = { - block: -2 - }; - this.disableCcipRead = false; - this.formatter = new.target.getFormatter(); - defineReadOnly(this, "anyNetwork", network === "any"); - if (this.anyNetwork) { - network = this.detectNetwork(); - } - if (network instanceof Promise) { - this._networkPromise = network; - network.catch((error)=>{}); - this._ready().catch((error)=>{}); - } else { - const knownNetwork = getStatic(new.target, "getNetwork")(network); - if (knownNetwork) { - defineReadOnly(this, "_network", knownNetwork); - this.emit("network", knownNetwork, null); - } else { - logger$14.throwArgumentError("invalid network", "network", network); - } +class ChainstackProvider extends JsonRpcProvider { + apiKey; + constructor(_network, apiKey){ + if (_network == null) { + _network = "mainnet"; } - this._maxInternalBlockNumber = -1024; - this._lastBlockNumber = -2; - this._maxFilterBlockRange = 10; - this._pollingInterval = 4e3; - this._fastQueryDate = 0; - } - _ready() { - return __awaiter8(this, void 0, void 0, function*() { - if (this._network == null) { - let network = null; - if (this._networkPromise) { - try { - network = yield this._networkPromise; - } catch (error) {} - } - if (network == null) { - network = yield this.detectNetwork(); - } - if (!network) { - logger$14.throwError("no network detected", Logger.errors.UNKNOWN_ERROR, {}); - } - if (this._network == null) { - if (this.anyNetwork) { - this._network = network; - } else { - defineReadOnly(this, "_network", network); - } - this.emit("network", network, null); - } - } - return this._network; + const network = Network.from(_network); + if (apiKey == null) { + apiKey = getApiKey(network.name); + } + const request = ChainstackProvider.getRequest(network, apiKey); + super(request, network, { + staticNetwork: network }); - } - get ready() { - return poll(()=>{ - return this._ready().then((network)=>{ - return network; - }, (error)=>{ - if (error.code === Logger.errors.NETWORK_ERROR && error.event === "noNetwork") { - return void 0; - } - throw error; - }); + defineProperties(this, { + apiKey: apiKey }); } - static getFormatter() { - if (defaultFormatter == null) { - defaultFormatter = new Formatter(); - } - return defaultFormatter; + _getProvider(chainId) { + try { + return new ChainstackProvider(chainId, this.apiKey); + } catch (error) {} + return super._getProvider(chainId); } - static getNetwork(network) { - return getNetwork(network == null ? "homestead" : network); + isCommunityResource() { + return this.apiKey === getApiKey(this._network.name); } - ccipReadFetch(tx, calldata, urls) { - return __awaiter8(this, void 0, void 0, function*() { - if (this.disableCcipRead || urls.length === 0) { - return null; - } - const sender = tx.to.toLowerCase(); - const data = calldata.toLowerCase(); - const errorMessages = []; - for(let i = 0; i < urls.length; i++){ - const url = urls[i]; - const href = url.replace("{sender}", sender).replace("{data}", data); - const json = url.indexOf("{data}") >= 0 ? null : JSON.stringify({ - data, - sender - }); - const result = yield fetchJson({ - url: href, - errorPassThrough: true - }, json, (value, response)=>{ - value.status = response.statusCode; - return value; - }); - if (result.data) { - return result.data; - } - const errorMessage = result.message || "unknown error"; - if (result.status >= 400 && result.status < 500) { - return logger$14.throwError(`response not found during CCIP fetch: ${errorMessage}`, Logger.errors.SERVER_ERROR, { - url, - errorMessage - }); - } - errorMessages.push(errorMessage); - } - return logger$14.throwError(`error encountered during CCIP fetch: ${errorMessages.map((m)=>JSON.stringify(m)).join(", ")}`, Logger.errors.SERVER_ERROR, { - urls, - errorMessages - }); - }); + static getRequest(network, apiKey) { + if (apiKey == null) { + apiKey = getApiKey(network.name); + } + const request = new FetchRequest(`https:/\/${getHost$3(network.name)}/${apiKey}`); + request.allowGzip = true; + if (apiKey === getApiKey(network.name)) { + request.retryFunc = async (request, response, attempt)=>{ + showThrottleMessage("ChainstackProvider"); + return true; + }; + } + return request; } - _getInternalBlockNumber(maxAge) { - return __awaiter8(this, void 0, void 0, function*() { - yield this._ready(); - if (maxAge > 0) { - while(this._internalBlockNumber){ - const internalBlockNumber = this._internalBlockNumber; - try { - const result = yield internalBlockNumber; - if (getTime() - result.respTime <= maxAge) { - return result.blockNumber; - } - break; - } catch (error) { - if (this._internalBlockNumber === internalBlockNumber) { - break; - } - } - } - } - const reqTime = getTime(); - const checkInternalBlockNumber = resolveProperties({ - blockNumber: this.perform("getBlockNumber", {}), - networkError: this.getNetwork().then((network)=>null, (error)=>error) - }).then(({ blockNumber, networkError })=>{ - if (networkError) { - if (this._internalBlockNumber === checkInternalBlockNumber) { - this._internalBlockNumber = null; - } - throw networkError; - } - const respTime = getTime(); - blockNumber = BigNumber.from(blockNumber).toNumber(); - if (blockNumber < this._maxInternalBlockNumber) { - blockNumber = this._maxInternalBlockNumber; - } - this._maxInternalBlockNumber = blockNumber; - this._setFastBlockNumber(blockNumber); - return { - blockNumber, - reqTime, - respTime - }; - }); - this._internalBlockNumber = checkInternalBlockNumber; - checkInternalBlockNumber.catch((error)=>{ - if (this._internalBlockNumber === checkInternalBlockNumber) { - this._internalBlockNumber = null; - } - }); - return (yield checkInternalBlockNumber).blockNumber; +} +class CloudflareProvider extends JsonRpcProvider { + constructor(_network){ + if (_network == null) { + _network = "mainnet"; + } + const network = Network.from(_network); + assertArgument(network.name === "mainnet", "unsupported network", "network", _network); + super("https://cloudflare-eth.com/", network, { + staticNetwork: network }); } - poll() { - return __awaiter8(this, void 0, void 0, function*() { - const pollId = nextPollId++; - const runners = []; - let blockNumber = null; - try { - blockNumber = yield this._getInternalBlockNumber(100 + this.pollingInterval / 2); - } catch (error) { - this.emit("error", error); - return; - } - this._setFastBlockNumber(blockNumber); - this.emit("poll", pollId, blockNumber); - if (blockNumber === this._lastBlockNumber) { - this.emit("didPoll", pollId); - return; - } - if (this._emitted.block === -2) { - this._emitted.block = blockNumber - 1; - } - if (Math.abs(this._emitted.block - blockNumber) > 1e3) { - logger$14.warn(`network block skew detected; skipping block events (emitted=${this._emitted.block} blockNumber${blockNumber})`); - this.emit("error", logger$14.makeError("network block skew detected", Logger.errors.NETWORK_ERROR, { - blockNumber, - event: "blockSkew", - previousBlockNumber: this._emitted.block - })); - this.emit("block", blockNumber); - } else { - for(let i = this._emitted.block + 1; i <= blockNumber; i++){ - this.emit("block", i); - } - } - if (this._emitted.block !== blockNumber) { - this._emitted.block = blockNumber; - Object.keys(this._emitted).forEach((key)=>{ - if (key === "block") { - return; - } - const eventBlockNumber = this._emitted[key]; - if (eventBlockNumber === "pending") { - return; - } - if (blockNumber - eventBlockNumber > 12) { - delete this._emitted[key]; - } - }); - } - if (this._lastBlockNumber === -2) { - this._lastBlockNumber = blockNumber - 1; - } - this._events.forEach((event)=>{ - switch(event.type){ - case "tx": - { - const hash2 = event.hash; - let runner = this.getTransactionReceipt(hash2).then((receipt)=>{ - if (!receipt || receipt.blockNumber == null) { - return null; - } - this._emitted["t:" + hash2] = receipt.blockNumber; - this.emit(hash2, receipt); - return null; - }).catch((error)=>{ - this.emit("error", error); - }); - runners.push(runner); - break; - } - case "filter": - { - if (!event._inflight) { - event._inflight = true; - if (event._lastBlockNumber === -2) { - event._lastBlockNumber = blockNumber - 1; - } - const filter = event.filter; - filter.fromBlock = event._lastBlockNumber + 1; - filter.toBlock = blockNumber; - const minFromBlock = filter.toBlock - this._maxFilterBlockRange; - if (minFromBlock > filter.fromBlock) { - filter.fromBlock = minFromBlock; - } - if (filter.fromBlock < 0) { - filter.fromBlock = 0; - } - const runner = this.getLogs(filter).then((logs)=>{ - event._inflight = false; - if (logs.length === 0) { - return; - } - logs.forEach((log)=>{ - if (log.blockNumber > event._lastBlockNumber) { - event._lastBlockNumber = log.blockNumber; - } - this._emitted["b:" + log.blockHash] = log.blockNumber; - this._emitted["t:" + log.transactionHash] = log.blockNumber; - this.emit(filter, log); - }); - }).catch((error)=>{ - this.emit("error", error); - event._inflight = false; - }); - runners.push(runner); - } - break; - } - } - }); - this._lastBlockNumber = blockNumber; - Promise.all(runners).then(()=>{ - this.emit("didPoll", pollId); - }).catch((error)=>{ - this.emit("error", error); - }); - return; +} +const THROTTLE = 2e3; +function isPromise(value) { + return value && typeof value.then === "function"; +} +const EtherscanPluginId = "org.ethers.plugins.provider.Etherscan"; +class EtherscanPlugin extends NetworkPlugin { + baseUrl; + constructor(baseUrl){ + super(EtherscanPluginId); + defineProperties(this, { + baseUrl: baseUrl }); } - resetEventsBlock(blockNumber) { - this._lastBlockNumber = blockNumber - 1; - if (this.polling) { - this.poll(); - } - } - get network() { - return this._network; + clone() { + return new EtherscanPlugin(this.baseUrl); } - detectNetwork() { - return __awaiter8(this, void 0, void 0, function*() { - return logger$14.throwError("provider does not support network detection", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "provider.detectNetwork" - }); +} +const skipKeys = [ + "enableCcipRead" +]; +let nextId = 1; +class EtherscanProvider extends AbstractProvider { + network; + apiKey; + #plugin; + constructor(_network, _apiKey){ + const apiKey = _apiKey != null ? _apiKey : null; + super(); + const network = Network.from(_network); + this.#plugin = network.getPlugin(EtherscanPluginId); + defineProperties(this, { + apiKey: apiKey, + network: network }); + this.getBaseUrl(); } - getNetwork() { - return __awaiter8(this, void 0, void 0, function*() { - const network = yield this._ready(); - const currentNetwork = yield this.detectNetwork(); - if (network.chainId !== currentNetwork.chainId) { - if (this.anyNetwork) { - this._network = currentNetwork; - this._lastBlockNumber = -2; - this._fastBlockNumber = null; - this._fastBlockNumberPromise = null; - this._fastQueryDate = 0; - this._emitted.block = -2; - this._maxInternalBlockNumber = -1024; - this._internalBlockNumber = null; - this.emit("network", currentNetwork, network); - yield stall(0); - return this._network; - } - const error = logger$14.makeError("underlying network changed", Logger.errors.NETWORK_ERROR, { - event: "changed", - network, - detectedNetwork: currentNetwork - }); - this.emit("error", error); - throw error; - } - return network; - }); + getBaseUrl() { + if (this.#plugin) { + return this.#plugin.baseUrl; + } + switch(this.network.name){ + case "mainnet": + return "https://api.etherscan.io"; + case "goerli": + return "https://api-goerli.etherscan.io"; + case "sepolia": + return "https://api-sepolia.etherscan.io"; + case "holesky": + return "https://api-holesky.etherscan.io"; + case "arbitrum": + return "https://api.arbiscan.io"; + case "arbitrum-goerli": + return "https://api-goerli.arbiscan.io"; + case "base": + return "https://api.basescan.org"; + case "base-sepolia": + return "https://api-sepolia.basescan.org"; + case "bnb": + return "https://api.bscscan.com"; + case "bnbt": + return "https://api-testnet.bscscan.com"; + case "matic": + return "https://api.polygonscan.com"; + case "matic-amoy": + return "https://api-amoy.polygonscan.com"; + case "matic-mumbai": + return "https://api-testnet.polygonscan.com"; + case "optimism": + return "https://api-optimistic.etherscan.io"; + case "optimism-goerli": + return "https://api-goerli-optimistic.etherscan.io"; + } + assertArgument(false, "unsupported network", "network", this.network); } - get blockNumber() { - this._getInternalBlockNumber(100 + this.pollingInterval / 2).then((blockNumber)=>{ - this._setFastBlockNumber(blockNumber); - }, (error)=>{}); - return this._fastBlockNumber != null ? this._fastBlockNumber : -1; - } - get polling() { - return this._poller != null; - } - set polling(value) { - if (value && !this._poller) { - this._poller = setInterval(()=>{ - this.poll(); - }, this.pollingInterval); - if (!this._bootstrapPoll) { - this._bootstrapPoll = setTimeout(()=>{ - this.poll(); - this._bootstrapPoll = setTimeout(()=>{ - if (!this._poller) { - this.poll(); - } - this._bootstrapPoll = null; - }, this.pollingInterval); - }, 0); + getUrl(module, params) { + const query = Object.keys(params).reduce((accum, key)=>{ + const value = params[key]; + if (value != null) { + accum += `&${key}=${value}`; } - } else if (!value && this._poller) { - clearInterval(this._poller); - this._poller = null; - } + return accum; + }, ""); + const apiKey = this.apiKey ? `&apikey=${this.apiKey}` : ""; + return `${this.getBaseUrl()}/api?module=${module}${query}${apiKey}`; } - get pollingInterval() { - return this._pollingInterval; + getPostUrl() { + return `${this.getBaseUrl()}/api`; } - set pollingInterval(value) { - if (typeof value !== "number" || value <= 0 || parseInt(String(value)) != value) { - throw new Error("invalid polling interval"); - } - this._pollingInterval = value; - if (this._poller) { - clearInterval(this._poller); - this._poller = setInterval(()=>{ - this.poll(); - }, this._pollingInterval); - } - } - _getFastBlockNumber() { - const now2 = getTime(); - if (now2 - this._fastQueryDate > 2 * this._pollingInterval) { - this._fastQueryDate = now2; - this._fastBlockNumberPromise = this.getBlockNumber().then((blockNumber)=>{ - if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) { - this._fastBlockNumber = blockNumber; - } - return this._fastBlockNumber; - }); - } - return this._fastBlockNumberPromise; + getPostData(module, params) { + params.module = module; + params.apikey = this.apiKey; + return params; } - _setFastBlockNumber(blockNumber) { - if (this._fastBlockNumber != null && blockNumber < this._fastBlockNumber) { - return; - } - this._fastQueryDate = getTime(); - if (this._fastBlockNumber == null || blockNumber > this._fastBlockNumber) { - this._fastBlockNumber = blockNumber; - this._fastBlockNumberPromise = Promise.resolve(blockNumber); - } + async detectNetwork() { + return this.network; } - waitForTransaction(transactionHash, confirmations, timeout) { - return __awaiter8(this, void 0, void 0, function*() { - return this._waitForTransaction(transactionHash, confirmations == null ? 1 : confirmations, timeout || 0, null); + async fetch(module, params, post) { + const id = nextId++; + const url = post ? this.getPostUrl() : this.getUrl(module, params); + const payload = post ? this.getPostData(module, params) : null; + this.emit("debug", { + action: "sendRequest", + id: id, + url: url, + payload: payload }); - } - _waitForTransaction(transactionHash, confirmations, timeout, replaceable) { - return __awaiter8(this, void 0, void 0, function*() { - const receipt = yield this.getTransactionReceipt(transactionHash); - if ((receipt ? receipt.confirmations : 0) >= confirmations) { - return receipt; + const request = new FetchRequest(url); + request.setThrottleParams({ + slotInterval: 1e3 + }); + request.retryFunc = (req, resp, attempt)=>{ + if (this.isCommunityResource()) { + showThrottleMessage("Etherscan"); } - return new Promise((resolve, reject)=>{ - const cancelFuncs = []; - let done = false; - const alreadyDone = function() { - if (done) { - return true; - } - done = true; - cancelFuncs.forEach((func)=>{ - func(); - }); - return false; - }; - const minedHandler = (receipt2)=>{ - if (receipt2.confirmations < confirmations) { - return; - } - if (alreadyDone()) { - return; - } - resolve(receipt2); - }; - this.on(transactionHash, minedHandler); - cancelFuncs.push(()=>{ - this.removeListener(transactionHash, minedHandler); - }); - if (replaceable) { - let lastBlockNumber = replaceable.startBlock; - let scannedBlock = null; - const replaceHandler = (blockNumber)=>__awaiter8(this, void 0, void 0, function*() { - if (done) { - return; - } - yield stall(1e3); - this.getTransactionCount(replaceable.from).then((nonce)=>__awaiter8(this, void 0, void 0, function*() { - if (done) { - return; - } - if (nonce <= replaceable.nonce) { - lastBlockNumber = blockNumber; - } else { - { - const mined = yield this.getTransaction(transactionHash); - if (mined && mined.blockNumber != null) { - return; - } - } - if (scannedBlock == null) { - scannedBlock = lastBlockNumber - 3; - if (scannedBlock < replaceable.startBlock) { - scannedBlock = replaceable.startBlock; - } - } - while(scannedBlock <= blockNumber){ - if (done) { - return; - } - const block = yield this.getBlockWithTransactions(scannedBlock); - for(let ti = 0; ti < block.transactions.length; ti++){ - const tx = block.transactions[ti]; - if (tx.hash === transactionHash) { - return; - } - if (tx.from === replaceable.from && tx.nonce === replaceable.nonce) { - if (done) { - return; - } - const receipt2 = yield this.waitForTransaction(tx.hash, confirmations); - if (alreadyDone()) { - return; - } - let reason = "replaced"; - if (tx.data === replaceable.data && tx.to === replaceable.to && tx.value.eq(replaceable.value)) { - reason = "repriced"; - } else if (tx.data === "0x" && tx.from === tx.to && tx.value.isZero()) { - reason = "cancelled"; - } - reject(logger$14.makeError("transaction was replaced", Logger.errors.TRANSACTION_REPLACED, { - cancelled: reason === "replaced" || reason === "cancelled", - reason, - replacement: this._wrapTransaction(tx), - hash: transactionHash, - receipt: receipt2 - })); - return; - } - } - scannedBlock++; - } - } - if (done) { - return; - } - this.once("block", replaceHandler); - }), (error)=>{ - if (done) { - return; - } - this.once("block", replaceHandler); - }); - }); - if (done) { - return; - } - this.once("block", replaceHandler); - cancelFuncs.push(()=>{ - this.removeListener("block", replaceHandler); + return Promise.resolve(true); + }; + request.processFunc = async (request, response)=>{ + const result = response.hasBody() ? JSON.parse(toUtf8String(response.body)) : {}; + const throttle = (typeof result.result === "string" ? result.result : "").toLowerCase().indexOf("rate limit") >= 0; + if (module === "proxy") { + if (result && result.status == 0 && result.message == "NOTOK" && throttle) { + this.emit("debug", { + action: "receiveError", + id: id, + reason: "proxy-NOTOK", + error: result }); + response.throwThrottleError(result.result, THROTTLE); } - if (typeof timeout === "number" && timeout > 0) { - const timer2 = setTimeout(()=>{ - if (alreadyDone()) { - return; - } - reject(logger$14.makeError("timeout exceeded", Logger.errors.TIMEOUT, { - timeout - })); - }, timeout); - if (timer2.unref) { - timer2.unref(); - } - cancelFuncs.push(()=>{ - clearTimeout(timer2); + } else { + if (throttle) { + this.emit("debug", { + action: "receiveError", + id: id, + reason: "null result", + error: result.result }); + response.throwThrottleError(result.result, THROTTLE); } + } + return response; + }; + if (payload) { + request.setHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8"); + request.body = Object.keys(payload).map((k)=>`${k}=${payload[k]}`).join("&"); + } + const response = await request.send(); + try { + response.assertOk(); + } catch (error) { + this.emit("debug", { + action: "receiveError", + id: id, + error: error, + reason: "assertOk" }); - }); - } - getBlockNumber() { - return __awaiter8(this, void 0, void 0, function*() { - return this._getInternalBlockNumber(0); - }); - } - getGasPrice() { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - const result = yield this.perform("getGasPrice", {}); - try { - return BigNumber.from(result); - } catch (error) { - return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { - method: "getGasPrice", - result, - error + assert1(false, "response error", "SERVER_ERROR", { + request: request, + response: response + }); + } + if (!response.hasBody()) { + this.emit("debug", { + action: "receiveError", + id: id, + error: "missing body", + reason: "null body" + }); + assert1(false, "missing response", "SERVER_ERROR", { + request: request, + response: response + }); + } + const result = JSON.parse(toUtf8String(response.body)); + if (module === "proxy") { + if (result.jsonrpc != "2.0") { + this.emit("debug", { + action: "receiveError", + id: id, + result: result, + reason: "invalid JSON-RPC" + }); + assert1(false, "invalid JSON-RPC response (missing jsonrpc='2.0')", "SERVER_ERROR", { + request: request, + response: response, + info: { + result: result + } }); } - }); - } - getBalance(addressOrName, blockTag) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - const params = yield resolveProperties({ - address: this._getAddress(addressOrName), - blockTag: this._getBlockTag(blockTag) - }); - const result = yield this.perform("getBalance", params); - try { - return BigNumber.from(result); - } catch (error) { - return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { - method: "getBalance", - params, - result, - error + if (result.error) { + this.emit("debug", { + action: "receiveError", + id: id, + result: result, + reason: "JSON-RPC error" + }); + assert1(false, "error response", "SERVER_ERROR", { + request: request, + response: response, + info: { + result: result + } }); } - }); - } - getTransactionCount(addressOrName, blockTag) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - const params = yield resolveProperties({ - address: this._getAddress(addressOrName), - blockTag: this._getBlockTag(blockTag) + this.emit("debug", { + action: "receiveRequest", + id: id, + result: result }); - const result = yield this.perform("getTransactionCount", params); - try { - return BigNumber.from(result).toNumber(); - } catch (error) { - return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { - method: "getTransactionCount", - params, - result, - error + return result.result; + } else { + if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) { + this.emit("debug", { + action: "receiveRequest", + id: id, + result: result }); + return result.result; } - }); - } - getCode(addressOrName, blockTag) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - const params = yield resolveProperties({ - address: this._getAddress(addressOrName), - blockTag: this._getBlockTag(blockTag) + if (result.status != 1 || typeof result.message === "string" && !result.message.match(/^OK/)) { + this.emit("debug", { + action: "receiveError", + id: id, + result: result + }); + assert1(false, "error response", "SERVER_ERROR", { + request: request, + response: response, + info: { + result: result + } + }); + } + this.emit("debug", { + action: "receiveRequest", + id: id, + result: result }); - const result = yield this.perform("getCode", params); - try { - return hexlify(result); - } catch (error) { - return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { - method: "getCode", - params, - result, - error + return result.result; + } + } + _getTransactionPostData(transaction) { + const result = {}; + for(let key in transaction){ + if (skipKeys.indexOf(key) >= 0) { + continue; + } + if (transaction[key] == null) { + continue; + } + let value = transaction[key]; + if (key === "type" && value === 0) { + continue; + } + if (key === "blockTag" && value === "latest") { + continue; + } + if (({ + type: true, + gasLimit: true, + gasPrice: true, + maxFeePerGs: true, + maxPriorityFeePerGas: true, + nonce: true, + value: true + })[key]) { + value = toQuantity(value); + } else if (key === "accessList") { + value = "[" + accessListify(value).map((set)=>{ + return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`; + }).join(",") + "]"; + } else if (key === "blobVersionedHashes") { + if (value.length === 0) { + continue; + } + assert1(false, "Etherscan API does not support blobVersionedHashes", "UNSUPPORTED_OPERATION", { + operation: "_getTransactionPostData", + info: { + transaction: transaction + } }); + } else { + value = hexlify(value); } - }); + result[key] = value; + } + return result; } - getStorageAt(addressOrName, position, blockTag) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - const params = yield resolveProperties({ - address: this._getAddress(addressOrName), - blockTag: this._getBlockTag(blockTag), - position: Promise.resolve(position).then((p)=>hexValue(p)) - }); - const result = yield this.perform("getStorageAt", params); + _checkError(req, error, transaction) { + let message = ""; + if (isError(error, "SERVER_ERROR")) { try { - return hexlify(result); - } catch (error) { - return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { - method: "getStorageAt", - params, - result, - error + message = error.info.result.error.message; + } catch (e) {} + if (!message) { + try { + message = error.info.message; + } catch (e) {} + } + } + if (req.method === "estimateGas") { + if (!message.match(/revert/i) && message.match(/insufficient funds/i)) { + assert1(false, "insufficient funds", "INSUFFICIENT_FUNDS", { + transaction: req.transaction }); } - }); - } - _wrapTransaction(tx, hash2, startBlock) { - if (hash2 != null && hexDataLength(hash2) !== 32) { - throw new Error("invalid response - sendTransaction"); } - const result = tx; - if (hash2 != null && tx.hash !== hash2) { - logger$14.throwError("Transaction hash mismatch from Provider.sendTransaction.", Logger.errors.UNKNOWN_ERROR, { - expectedHash: tx.hash, - returnedHash: hash2 - }); + if (req.method === "call" || req.method === "estimateGas") { + if (message.match(/execution reverted/i)) { + let data = ""; + try { + data = error.info.result.error.data; + } catch (error) {} + const e = AbiCoder.getBuiltinCallException(req.method, req.transaction, data); + e.info = { + request: req, + error: error + }; + throw e; + } } - result.wait = (confirms, timeout)=>__awaiter8(this, void 0, void 0, function*() { - if (confirms == null) { - confirms = 1; - } - if (timeout == null) { - timeout = 0; - } - let replacement = void 0; - if (confirms !== 0 && startBlock != null) { - replacement = { - data: tx.data, - from: tx.from, - nonce: tx.nonce, - to: tx.to, - value: tx.value, - startBlock - }; + if (message) { + if (req.method === "broadcastTransaction") { + const transaction = Transaction.from(req.signedTransaction); + if (message.match(/replacement/i) && message.match(/underpriced/i)) { + assert1(false, "replacement fee too low", "REPLACEMENT_UNDERPRICED", { + transaction: transaction + }); } - const receipt = yield this._waitForTransaction(tx.hash, confirms, timeout, replacement); - if (receipt == null && confirms === 0) { - return null; + if (message.match(/insufficient funds/)) { + assert1(false, "insufficient funds for intrinsic transaction cost", "INSUFFICIENT_FUNDS", { + transaction: transaction + }); } - this._emitted["t:" + tx.hash] = receipt.blockNumber; - if (receipt.status === 0) { - logger$14.throwError("transaction failed", Logger.errors.CALL_EXCEPTION, { - transactionHash: tx.hash, - transaction: tx, - receipt + if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) { + assert1(false, "nonce has already been used", "NONCE_EXPIRED", { + transaction: transaction }); } - return receipt; - }); - return result; - } - sendTransaction(signedTransaction) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - const hexTx = yield Promise.resolve(signedTransaction).then((t)=>hexlify(t)); - const tx = this.formatter.transaction(signedTransaction); - if (tx.confirmations == null) { - tx.confirmations = 0; } - const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); - try { - const hash2 = yield this.perform("sendTransaction", { - signedTransaction: hexTx - }); - return this._wrapTransaction(tx, hash2, blockNumber); - } catch (error) { - error.transaction = tx; - error.transactionHash = tx.hash; - throw error; - } - }); + } + throw error; } - _getTransactionRequest(transaction) { - return __awaiter8(this, void 0, void 0, function*() { - const values = yield transaction; - const tx = {}; - [ - "from", - "to" - ].forEach((key)=>{ - if (values[key] == null) { - return; - } - tx[key] = Promise.resolve(values[key]).then((v)=>v ? this._getAddress(v) : null); - }); - [ - "gasLimit", - "gasPrice", - "maxFeePerGas", - "maxPriorityFeePerGas", - "value" - ].forEach((key)=>{ - if (values[key] == null) { - return; - } - tx[key] = Promise.resolve(values[key]).then((v)=>v ? BigNumber.from(v) : null); - }); - [ - "type" - ].forEach((key)=>{ - if (values[key] == null) { - return; - } - tx[key] = Promise.resolve(values[key]).then((v)=>v != null ? v : null); - }); - if (values.accessList) { - tx.accessList = this.formatter.accessList(values.accessList); - } - [ - "data" - ].forEach((key)=>{ - if (values[key] == null) { - return; - } - tx[key] = Promise.resolve(values[key]).then((v)=>v ? hexlify(v) : null); - }); - return this.formatter.transactionRequest((yield resolveProperties(tx))); - }); + async _detectNetwork() { + return this.network; } - _getFilter(filter) { - return __awaiter8(this, void 0, void 0, function*() { - filter = yield filter; - const result = {}; - if (filter.address != null) { - result.address = this._getAddress(filter.address); - } - [ - "blockHash", - "topics" - ].forEach((key)=>{ - if (filter[key] == null) { - return; + async _perform(req) { + switch(req.method){ + case "chainId": + return this.network.chainId; + case "getBlockNumber": + return this.fetch("proxy", { + action: "eth_blockNumber" + }); + case "getGasPrice": + return this.fetch("proxy", { + action: "eth_gasPrice" + }); + case "getPriorityFee": + if (this.network.name === "mainnet") { + return "1000000000"; + } else if (this.network.name === "optimism") { + return "1000000"; + } else { + throw new Error("fallback onto the AbstractProvider default"); } - result[key] = filter[key]; - }); - [ - "fromBlock", - "toBlock" - ].forEach((key)=>{ - if (filter[key] == null) { - return; + case "getBalance": + return this.fetch("account", { + action: "balance", + address: req.address, + tag: req.blockTag + }); + case "getTransactionCount": + return this.fetch("proxy", { + action: "eth_getTransactionCount", + address: req.address, + tag: req.blockTag + }); + case "getCode": + return this.fetch("proxy", { + action: "eth_getCode", + address: req.address, + tag: req.blockTag + }); + case "getStorage": + return this.fetch("proxy", { + action: "eth_getStorageAt", + address: req.address, + position: req.position, + tag: req.blockTag + }); + case "broadcastTransaction": + return this.fetch("proxy", { + action: "eth_sendRawTransaction", + hex: req.signedTransaction + }, true).catch((error)=>{ + return this._checkError(req, error, req.signedTransaction); + }); + case "getBlock": + if ("blockTag" in req) { + return this.fetch("proxy", { + action: "eth_getBlockByNumber", + tag: req.blockTag, + boolean: req.includeTransactions ? "true" : "false" + }); } - result[key] = this._getBlockTag(filter[key]); - }); - return this.formatter.filter((yield resolveProperties(result))); - }); - } - _call(transaction, blockTag, attempt) { - return __awaiter8(this, void 0, void 0, function*() { - if (attempt >= 10) { - logger$14.throwError("CCIP read exceeded maximum redirections", Logger.errors.SERVER_ERROR, { - redirects: attempt, - transaction + assert1(false, "getBlock by blockHash not supported by Etherscan", "UNSUPPORTED_OPERATION", { + operation: "getBlock(blockHash)" }); - } - const txSender = transaction.to; - const result = yield this.perform("call", { - transaction, - blockTag - }); - if (attempt >= 0 && blockTag === "latest" && txSender != null && result.substring(0, 10) === "0x556f1830" && hexDataLength(result) % 32 === 4) { - try { - const data = hexDataSlice(result, 4); - const sender = hexDataSlice(data, 0, 32); - if (!BigNumber.from(sender).eq(txSender)) { - logger$14.throwError("CCIP Read sender did not match", Logger.errors.CALL_EXCEPTION, { - name: "OffchainLookup", - signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", - transaction, - data: result - }); - } - const urls = []; - const urlsOffset = BigNumber.from(hexDataSlice(data, 32, 64)).toNumber(); - const urlsLength = BigNumber.from(hexDataSlice(data, urlsOffset, urlsOffset + 32)).toNumber(); - const urlsData = hexDataSlice(data, urlsOffset + 32); - for(let u = 0; u < urlsLength; u++){ - const url = _parseString(urlsData, u * 32); - if (url == null) { - logger$14.throwError("CCIP Read contained corrupt URL string", Logger.errors.CALL_EXCEPTION, { - name: "OffchainLookup", - signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", - transaction, - data: result - }); - } - urls.push(url); - } - const calldata = _parseBytes(data, 64); - if (!BigNumber.from(hexDataSlice(data, 100, 128)).isZero()) { - logger$14.throwError("CCIP Read callback selector included junk", Logger.errors.CALL_EXCEPTION, { - name: "OffchainLookup", - signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", - transaction, - data: result - }); + case "getTransaction": + return this.fetch("proxy", { + action: "eth_getTransactionByHash", + txhash: req.hash + }); + case "getTransactionReceipt": + return this.fetch("proxy", { + action: "eth_getTransactionReceipt", + txhash: req.hash + }); + case "call": + { + if (req.blockTag !== "latest") { + throw new Error("EtherscanProvider does not support blockTag for call"); } - const callbackSelector = hexDataSlice(data, 96, 100); - const extraData = _parseBytes(data, 128); - const ccipResult = yield this.ccipReadFetch(transaction, calldata, urls); - if (ccipResult == null) { - logger$14.throwError("CCIP Read disabled or provided no URLs", Logger.errors.CALL_EXCEPTION, { - name: "OffchainLookup", - signature: "OffchainLookup(address,string[],bytes,bytes4,bytes)", - transaction, - data: result - }); + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_call"; + try { + return await this.fetch("proxy", postData, true); + } catch (error) { + return this._checkError(req, error, req.transaction); } - const tx = { - to: txSender, - data: hexConcat([ - callbackSelector, - encodeBytes([ - ccipResult, - extraData - ]) - ]) - }; - return this._call(tx, blockTag, attempt + 1); - } catch (error) { - if (error.code === Logger.errors.SERVER_ERROR) { - throw error; + } + case "estimateGas": + { + const postData = this._getTransactionPostData(req.transaction); + postData.module = "proxy"; + postData.action = "eth_estimateGas"; + try { + return await this.fetch("proxy", postData, true); + } catch (error) { + return this._checkError(req, error, req.transaction); } } - } - try { - return hexlify(result); - } catch (error) { - return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { - method: "call", - params: { - transaction, - blockTag - }, - result, - error - }); - } - }); - } - call(transaction, blockTag) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - const resolved = yield resolveProperties({ - transaction: this._getTransactionRequest(transaction), - blockTag: this._getBlockTag(blockTag), - ccipReadEnabled: Promise.resolve(transaction.ccipReadEnabled) - }); - return this._call(resolved.transaction, resolved.blockTag, resolved.ccipReadEnabled ? 0 : -1); - }); + } + return super._perform(req); } - estimateGas(transaction) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - const params = yield resolveProperties({ - transaction: this._getTransactionRequest(transaction) - }); - const result = yield this.perform("estimateGas", params); - try { - return BigNumber.from(result); - } catch (error) { - return logger$14.throwError("bad result from backend", Logger.errors.SERVER_ERROR, { - method: "estimateGas", - params, - result, - error - }); - } - }); + async getNetwork() { + return this.network; } - _getAddress(addressOrName) { - return __awaiter8(this, void 0, void 0, function*() { - addressOrName = yield addressOrName; - if (typeof addressOrName !== "string") { - logger$14.throwArgumentError("invalid address or ENS name", "name", addressOrName); - } - const address2 = yield this.resolveName(addressOrName); - if (address2 == null) { - logger$14.throwError("ENS name not configured", Logger.errors.UNSUPPORTED_OPERATION, { - operation: `resolveName(${JSON.stringify(addressOrName)})` - }); - } - return address2; - }); + async getEtherPrice() { + if (this.network.name !== "mainnet") { + return 0; + } + return parseFloat((await this.fetch("stats", { + action: "ethprice" + })).ethusd); } - _getBlock(blockHashOrBlockTag, includeTransactions) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - blockHashOrBlockTag = yield blockHashOrBlockTag; - let blockNumber = -128; - const params = { - includeTransactions: !!includeTransactions - }; - if (isHexString(blockHashOrBlockTag, 32)) { - params.blockHash = blockHashOrBlockTag; - } else { - try { - params.blockTag = yield this._getBlockTag(blockHashOrBlockTag); - if (isHexString(params.blockTag)) { - blockNumber = parseInt(params.blockTag.substring(2), 16); - } - } catch (error) { - logger$14.throwArgumentError("invalid block hash or block tag", "blockHashOrBlockTag", blockHashOrBlockTag); - } - } - return poll(()=>__awaiter8(this, void 0, void 0, function*() { - const block = yield this.perform("getBlock", params); - if (block == null) { - if (params.blockHash != null) { - if (this._emitted["b:" + params.blockHash] == null) { - return null; - } - } - if (params.blockTag != null) { - if (blockNumber > this._emitted.block) { - return null; - } - } - return void 0; - } - if (includeTransactions) { - let blockNumber2 = null; - for(let i = 0; i < block.transactions.length; i++){ - const tx = block.transactions[i]; - if (tx.blockNumber == null) { - tx.confirmations = 0; - } else if (tx.confirmations == null) { - if (blockNumber2 == null) { - blockNumber2 = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); - } - let confirmations = blockNumber2 - tx.blockNumber + 1; - if (confirmations <= 0) { - confirmations = 1; - } - tx.confirmations = confirmations; - } - } - const blockWithTxs = this.formatter.blockWithTransactions(block); - blockWithTxs.transactions = blockWithTxs.transactions.map((tx)=>this._wrapTransaction(tx)); - return blockWithTxs; - } - return this.formatter.block(block); - }), { - oncePoll: this + async getContract(_address) { + let address = this._getAddress(_address); + if (isPromise(address)) { + address = await address; + } + try { + const resp = await this.fetch("contract", { + action: "getabi", + address: address }); - }); + const abi = JSON.parse(resp); + return new Contract(address, abi, this); + } catch (error) { + return null; + } } - getBlock(blockHashOrBlockTag) { - return this._getBlock(blockHashOrBlockTag, false); + isCommunityResource() { + return this.apiKey == null; } - getBlockWithTransactions(blockHashOrBlockTag) { - return this._getBlock(blockHashOrBlockTag, true); +} +function getGlobal() { + if (typeof self !== "undefined") { + return self; } - getTransaction(transactionHash) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - transactionHash = yield transactionHash; - const params = { - transactionHash: this.formatter.hash(transactionHash, true) - }; - return poll(()=>__awaiter8(this, void 0, void 0, function*() { - const result = yield this.perform("getTransaction", params); - if (result == null) { - if (this._emitted["t:" + transactionHash] == null) { - return null; - } - return void 0; - } - const tx = this.formatter.transactionResponse(result); - if (tx.blockNumber == null) { - tx.confirmations = 0; - } else if (tx.confirmations == null) { - const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); - let confirmations = blockNumber - tx.blockNumber + 1; - if (confirmations <= 0) { - confirmations = 1; - } - tx.confirmations = confirmations; - } - return this._wrapTransaction(tx); - }), { - oncePoll: this - }); - }); + if (typeof window !== "undefined") { + return window; } - getTransactionReceipt(transactionHash) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - transactionHash = yield transactionHash; - const params = { - transactionHash: this.formatter.hash(transactionHash, true) - }; - return poll(()=>__awaiter8(this, void 0, void 0, function*() { - const result = yield this.perform("getTransactionReceipt", params); - if (result == null) { - if (this._emitted["t:" + transactionHash] == null) { - return null; - } - return void 0; - } - if (result.blockHash == null) { - return void 0; - } - const receipt = this.formatter.receipt(result); - if (receipt.blockNumber == null) { - receipt.confirmations = 0; - } else if (receipt.confirmations == null) { - const blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); - let confirmations = blockNumber - receipt.blockNumber + 1; - if (confirmations <= 0) { - confirmations = 1; - } - receipt.confirmations = confirmations; - } - return receipt; - }), { - oncePoll: this - }); - }); + if (typeof global !== "undefined") { + return global; } - getLogs(filter) { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - const params = yield resolveProperties({ - filter: this._getFilter(filter) - }); - const logs = yield this.perform("getLogs", params); - logs.forEach((log)=>{ - if (log.removed == null) { - log.removed = false; - } - }); - return Formatter.arrayOf(this.formatter.filterLog.bind(this.formatter))(logs); - }); + throw new Error("unable to locate global object"); +} +const _WebSocket = getGlobal().WebSocket; +class SocketSubscriber { + #provider; + #filter; + get filter() { + return JSON.parse(this.#filter); + } + #filterId; + #paused; + #emitPromise; + constructor(provider, filter){ + this.#provider = provider; + this.#filter = JSON.stringify(filter); + this.#filterId = null; + this.#paused = null; + this.#emitPromise = null; } - getEtherPrice() { - return __awaiter8(this, void 0, void 0, function*() { - yield this.getNetwork(); - return this.perform("getEtherPrice", {}); + start() { + this.#filterId = this.#provider.send("eth_subscribe", this.filter).then((filterId)=>{ + this.#provider._register(filterId, this); + return filterId; }); } - _getBlockTag(blockTag) { - return __awaiter8(this, void 0, void 0, function*() { - blockTag = yield blockTag; - if (typeof blockTag === "number" && blockTag < 0) { - if (blockTag % 1) { - logger$14.throwArgumentError("invalid BlockTag", "blockTag", blockTag); - } - let blockNumber = yield this._getInternalBlockNumber(100 + 2 * this.pollingInterval); - blockNumber += blockTag; - if (blockNumber < 0) { - blockNumber = 0; - } - return this.formatter.blockTag(blockNumber); + stop() { + this.#filterId.then((filterId)=>{ + if (this.#provider.destroyed) { + return; } - return this.formatter.blockTag(blockTag); + this.#provider.send("eth_unsubscribe", [ + filterId + ]); }); + this.#filterId = null; } - getResolver(name) { - return __awaiter8(this, void 0, void 0, function*() { - let currentName = name; - while(true){ - if (currentName === "" || currentName === ".") { - return null; - } - if (name !== "eth" && currentName === "eth") { - return null; - } - const addr = yield this._getResolver(currentName, "getResolver"); - if (addr != null) { - const resolver = new Resolver(this, addr, name); - if (currentName !== name && !(yield resolver.supportsWildcard())) { - return null; - } - return resolver; - } - currentName = currentName.split(".").slice(1).join("."); - } + pause(dropWhilePaused) { + assert1(dropWhilePaused, "preserve logs while paused not supported by SocketSubscriber yet", "UNSUPPORTED_OPERATION", { + operation: "pause(false)" }); + this.#paused = !!dropWhilePaused; } - _getResolver(name, operation) { - return __awaiter8(this, void 0, void 0, function*() { - if (operation == null) { - operation = "ENS"; - } - const network = yield this.getNetwork(); - if (!network.ensAddress) { - logger$14.throwError("network does not support ENS", Logger.errors.UNSUPPORTED_OPERATION, { - operation, - network: network.name + resume() { + this.#paused = null; + } + _handleMessage(message) { + if (this.#filterId == null) { + return; + } + if (this.#paused === null) { + let emitPromise = this.#emitPromise; + if (emitPromise == null) { + emitPromise = this._emit(this.#provider, message); + } else { + emitPromise = emitPromise.then(async ()=>{ + await this._emit(this.#provider, message); }); } - try { - const addrData = yield this.call({ - to: network.ensAddress, - data: "0x0178b8bf" + namehash(name).substring(2) - }); - return this.formatter.callAddress(addrData); - } catch (error) {} - return null; - }); - } - resolveName(name) { - return __awaiter8(this, void 0, void 0, function*() { - name = yield name; - try { - return Promise.resolve(this.formatter.address(name)); - } catch (error) { - if (isHexString(name)) { - throw error; + this.#emitPromise = emitPromise.then(()=>{ + if (this.#emitPromise === emitPromise) { + this.#emitPromise = null; } - } - if (typeof name !== "string") { - logger$14.throwArgumentError("invalid ENS name", "name", name); - } - const resolver = yield this.getResolver(name); - if (!resolver) { - return null; - } - return yield resolver.getAddress(); - }); + }); + } } - lookupAddress(address2) { - return __awaiter8(this, void 0, void 0, function*() { - address2 = yield address2; - address2 = this.formatter.address(address2); - const node = address2.substring(2).toLowerCase() + ".addr.reverse"; - const resolverAddr = yield this._getResolver(node, "lookupAddress"); - if (resolverAddr == null) { - return null; - } - const name = _parseString((yield this.call({ - to: resolverAddr, - data: "0x691f3431" + namehash(node).substring(2) - })), 0); - const addr = yield this.resolveName(name); - if (addr != address2) { - return null; - } - return name; - }); + async _emit(provider, message) { + throw new Error("sub-classes must implemente this; _emit"); } - getAvatar(nameOrAddress) { - return __awaiter8(this, void 0, void 0, function*() { - let resolver = null; - if (isHexString(nameOrAddress)) { - const address2 = this.formatter.address(nameOrAddress); - const node = address2.substring(2).toLowerCase() + ".addr.reverse"; - const resolverAddress = yield this._getResolver(node, "getAvatar"); - if (!resolverAddress) { - return null; - } - resolver = new Resolver(this, resolverAddress, node); - try { - const avatar2 = yield resolver.getAvatar(); - if (avatar2) { - return avatar2.url; - } - } catch (error) { - if (error.code !== Logger.errors.CALL_EXCEPTION) { - throw error; - } - } - try { - const name = _parseString((yield this.call({ - to: resolverAddress, - data: "0x691f3431" + namehash(node).substring(2) - })), 0); - resolver = yield this.getResolver(name); - } catch (error) { - if (error.code !== Logger.errors.CALL_EXCEPTION) { - throw error; - } - return null; - } - } else { - resolver = yield this.getResolver(nameOrAddress); - if (!resolver) { - return null; - } - } - const avatar = yield resolver.getAvatar(); - if (avatar == null) { - return null; - } - return avatar.url; - }); +} +class SocketBlockSubscriber extends SocketSubscriber { + constructor(provider){ + super(provider, [ + "newHeads" + ]); } - perform(method, params) { - return logger$14.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { - operation: method - }); + async _emit(provider, message) { + provider.emit("block", parseInt(message.number)); + } +} +class SocketPendingSubscriber extends SocketSubscriber { + constructor(provider){ + super(provider, [ + "newPendingTransactions" + ]); } - _startEvent(event) { - this.polling = this._events.filter((e)=>e.pollable()).length > 0; + async _emit(provider, message) { + provider.emit("pending", message); } - _stopEvent(event) { - this.polling = this._events.filter((e)=>e.pollable()).length > 0; +} +class SocketEventSubscriber extends SocketSubscriber { + #logFilter; + get logFilter() { + return JSON.parse(this.#logFilter); } - _addEventListener(eventName, listener, once) { - const event = new Event(getEventTag1(eventName), listener, once); - this._events.push(event); - this._startEvent(event); - return this; + constructor(provider, filter){ + super(provider, [ + "logs", + filter + ]); + this.#logFilter = JSON.stringify(filter); + } + async _emit(provider, message) { + provider.emit(this.logFilter, provider._wrapLog(message, provider._network)); + } +} +class SocketProvider extends JsonRpcApiProvider { + #callbacks; + #subs; + #pending; + constructor(network, _options){ + const options = Object.assign({}, _options != null ? _options : {}); + assertArgument(options.batchMaxCount == null || options.batchMaxCount === 1, "sockets-based providers do not support batches", "options.batchMaxCount", _options); + options.batchMaxCount = 1; + if (options.staticNetwork == null) { + options.staticNetwork = true; + } + super(network, options); + this.#callbacks = new Map; + this.#subs = new Map; + this.#pending = new Map; + } + _getSubscriber(sub) { + switch(sub.type){ + case "close": + return new UnmanagedSubscriber("close"); + case "block": + return new SocketBlockSubscriber(this); + case "pending": + return new SocketPendingSubscriber(this); + case "event": + return new SocketEventSubscriber(this, sub.filter); + case "orphan": + if (sub.filter.orphan === "drop-log") { + return new UnmanagedSubscriber("drop-log"); + } + } + return super._getSubscriber(sub); } - on(eventName, listener) { - return this._addEventListener(eventName, listener, false); + _register(filterId, subscriber) { + this.#subs.set(filterId, subscriber); + const pending = this.#pending.get(filterId); + if (pending) { + for (const message of pending){ + subscriber._handleMessage(message); + } + this.#pending.delete(filterId); + } } - once(eventName, listener) { - return this._addEventListener(eventName, listener, true); + async _send(payload) { + assertArgument(!Array.isArray(payload), "WebSocket does not support batch send", "payload", payload); + const promise = new Promise((resolve, reject)=>{ + this.#callbacks.set(payload.id, { + payload: payload, + resolve: resolve, + reject: reject + }); + }); + await this._waitUntilReady(); + await this._write(JSON.stringify(payload)); + return [ + await promise + ]; } - emit(eventName, ...args) { - let result = false; - let stopped = []; - let eventTag = getEventTag1(eventName); - this._events = this._events.filter((event)=>{ - if (event.tag !== eventTag) { - return true; + async _processMessage(message) { + const result = JSON.parse(message); + if (result && typeof result === "object" && "id" in result) { + const callback = this.#callbacks.get(result.id); + if (callback == null) { + this.emit("error", makeError("received result for unknown id", "UNKNOWN_ERROR", { + reasonCode: "UNKNOWN_ID", + result: result + })); + return; } - setTimeout(()=>{ - event.listener.apply(this, args); - }, 0); - result = true; - if (event.once) { - stopped.push(event); - return false; + this.#callbacks.delete(result.id); + callback.resolve(result); + } else if (result && result.method === "eth_subscription") { + const filterId = result.params.subscription; + const subscriber = this.#subs.get(filterId); + if (subscriber) { + subscriber._handleMessage(result.params.result); + } else { + let pending = this.#pending.get(filterId); + if (pending == null) { + pending = []; + this.#pending.set(filterId, pending); + } + pending.push(result.params.result); } - return true; - }); - stopped.forEach((event)=>{ - this._stopEvent(event); - }); - return result; - } - listenerCount(eventName) { - if (!eventName) { - return this._events.length; + } else { + this.emit("error", makeError("received unexpected message", "UNKNOWN_ERROR", { + reasonCode: "UNEXPECTED_MESSAGE", + result: result + })); + return; } - let eventTag = getEventTag1(eventName); - return this._events.filter((event)=>{ - return event.tag === eventTag; - }).length; } - listeners(eventName) { - if (eventName == null) { - return this._events.map((event)=>event.listener); + async _write(message) { + throw new Error("sub-classes must override this"); + } +} +class WebSocketProvider extends SocketProvider { + #connect; + #websocket; + get websocket() { + if (this.#websocket == null) { + throw new Error("websocket closed"); } - let eventTag = getEventTag1(eventName); - return this._events.filter((event)=>event.tag === eventTag).map((event)=>event.listener); + return this.#websocket; } - off(eventName, listener) { - if (listener == null) { - return this.removeAllListeners(eventName); + constructor(url, network, options){ + super(network, options); + if (typeof url === "string") { + this.#connect = ()=>{ + return new _WebSocket(url); + }; + this.#websocket = this.#connect(); + } else if (typeof url === "function") { + this.#connect = url; + this.#websocket = url(); + } else { + this.#connect = null; + this.#websocket = url; } - const stopped = []; - let found = false; - let eventTag = getEventTag1(eventName); - this._events = this._events.filter((event)=>{ - if (event.tag !== eventTag || event.listener != listener) { - return true; - } - if (found) { - return true; + this.websocket.onopen = async ()=>{ + try { + await this._start(); + this.resume(); + } catch (error) { + console.log("failed to start WebsocketProvider", error); } - found = true; - stopped.push(event); - return false; - }); - stopped.forEach((event)=>{ - this._stopEvent(event); - }); - return this; + }; + this.websocket.onmessage = (message)=>{ + this._processMessage(message.data); + }; } - removeAllListeners(eventName) { - let stopped = []; - if (eventName == null) { - stopped = this._events; - this._events = []; - } else { - const eventTag = getEventTag1(eventName); - this._events = this._events.filter((event)=>{ - if (event.tag !== eventTag) { - return true; - } - stopped.push(event); - return false; - }); + async _write(message) { + this.websocket.send(message); + } + async destroy() { + if (this.#websocket != null) { + this.#websocket.close(); + this.#websocket = null; } - stopped.forEach((event)=>{ - this._stopEvent(event); - }); - return this; + super.destroy(); } } -var __awaiter$11 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); +const defaultProjectId = "84842078b09946638c03157f83405213"; +function getHost$2(name) { + switch(name){ + case "mainnet": + return "mainnet.infura.io"; + case "goerli": + return "goerli.infura.io"; + case "sepolia": + return "sepolia.infura.io"; + case "arbitrum": + return "arbitrum-mainnet.infura.io"; + case "arbitrum-goerli": + return "arbitrum-goerli.infura.io"; + case "arbitrum-sepolia": + return "arbitrum-sepolia.infura.io"; + case "base": + return "base-mainnet.infura.io"; + case "base-goerlia": + return "base-goerli.infura.io"; + case "base-sepolia": + return "base-sepolia.infura.io"; + case "bnb": + return "bnbsmartchain-mainnet.infura.io"; + case "bnbt": + return "bnbsmartchain-testnet.infura.io"; + case "linea": + return "linea-mainnet.infura.io"; + case "linea-goerli": + return "linea-goerli.infura.io"; + case "linea-sepolia": + return "linea-sepolia.infura.io"; + case "matic": + return "polygon-mainnet.infura.io"; + case "matic-amoy": + return "polygon-amoy.infura.io"; + case "matic-mumbai": + return "polygon-mumbai.infura.io"; + case "optimism": + return "optimism-mainnet.infura.io"; + case "optimism-goerli": + return "optimism-goerli.infura.io"; + case "optimism-sepolia": + return "optimism-sepolia.infura.io"; + } + assertArgument(false, "unsupported network", "network", name); +} +class InfuraWebSocketProvider extends WebSocketProvider { + projectId; + projectSecret; + constructor(network, projectId){ + const provider = new InfuraProvider(network, projectId); + const req = provider._getConnection(); + assert1(!req.credentials, "INFURA WebSocket project secrets unsupported", "UNSUPPORTED_OPERATION", { + operation: "InfuraProvider.getWebSocketProvider()" + }); + const url = req.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/"); + super(url, provider._network); + defineProperties(this, { + projectId: provider.projectId, + projectSecret: provider.projectSecret }); } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger$21 = new Logger(version23); -const errorGas = [ - "call", - "estimateGas" -]; -function spelunk(value, requireData) { - if (value == null) { - return null; + isCommunityResource() { + return this.projectId === defaultProjectId; } - if (typeof value.message === "string" && value.message.match("reverted")) { - const data = isHexString(value.data) ? value.data : null; - if (!requireData || data) { - return { - message: value.message, - data - }; +} +class InfuraProvider extends JsonRpcProvider { + projectId; + projectSecret; + constructor(_network, projectId, projectSecret){ + if (_network == null) { + _network = "mainnet"; } - } - if (typeof value === "object") { - for(const key in value){ - const result = spelunk(value[key], requireData); - if (result) { - return result; - } + const network = Network.from(_network); + if (projectId == null) { + projectId = defaultProjectId; } - return null; + if (projectSecret == null) { + projectSecret = null; + } + const request = InfuraProvider.getRequest(network, projectId, projectSecret); + super(request, network, { + staticNetwork: network + }); + defineProperties(this, { + projectId: projectId, + projectSecret: projectSecret + }); } - if (typeof value === "string") { + _getProvider(chainId) { try { - return spelunk(JSON.parse(value), requireData); + return new InfuraProvider(chainId, this.projectId, this.projectSecret); } catch (error) {} + return super._getProvider(chainId); } - return null; -} -function checkError(method, error, params) { - const transaction = params.transaction || params.signedTransaction; - if (method === "call") { - const result = spelunk(error, true); - if (result) { - return result.data; - } - logger$21.throwError("missing revert data in call exception; Transaction reverted without a reason string", Logger.errors.CALL_EXCEPTION, { - data: "0x", - transaction, - error - }); + isCommunityResource() { + return this.projectId === defaultProjectId; } - if (method === "estimateGas") { - let result = spelunk(error.body, false); - if (result == null) { - result = spelunk(error, false); + static getWebSocketProvider(network, projectId) { + return new InfuraWebSocketProvider(network, projectId); + } + static getRequest(network, projectId, projectSecret) { + if (projectId == null) { + projectId = defaultProjectId; } - if (result) { - logger$21.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, { - reason: result.message, - method, - transaction, - error - }); + if (projectSecret == null) { + projectSecret = null; + } + const request = new FetchRequest(`https:/\/${getHost$2(network.name)}/v3/${projectId}`); + request.allowGzip = true; + if (projectSecret) { + request.setCredentials("", projectSecret); + } + if (projectId === defaultProjectId) { + request.retryFunc = async (request, response, attempt)=>{ + showThrottleMessage("InfuraProvider"); + return true; + }; } + return request; } - let message = error.message; - if (error.code === Logger.errors.SERVER_ERROR && error.error && typeof error.error.message === "string") { - message = error.error.message; - } else if (typeof error.body === "string") { - message = error.body; - } else if (typeof error.responseText === "string") { - message = error.responseText; - } - message = (message || "").toLowerCase(); - if (message.match(/insufficient funds|base fee exceeds gas limit|InsufficientFunds/i)) { - logger$21.throwError("insufficient funds for intrinsic transaction cost", Logger.errors.INSUFFICIENT_FUNDS, { - error, - method, - transaction +} +const defaultToken = "919b412a057b5e9c9b6dce193c5a60242d6efadb"; +function getHost$1(name) { + switch(name){ + case "mainnet": + return "ethers.quiknode.pro"; + case "goerli": + return "ethers.ethereum-goerli.quiknode.pro"; + case "sepolia": + return "ethers.ethereum-sepolia.quiknode.pro"; + case "holesky": + return "ethers.ethereum-holesky.quiknode.pro"; + case "arbitrum": + return "ethers.arbitrum-mainnet.quiknode.pro"; + case "arbitrum-goerli": + return "ethers.arbitrum-goerli.quiknode.pro"; + case "arbitrum-sepolia": + return "ethers.arbitrum-sepolia.quiknode.pro"; + case "base": + return "ethers.base-mainnet.quiknode.pro"; + case "base-goerli": + return "ethers.base-goerli.quiknode.pro"; + case "base-spolia": + return "ethers.base-sepolia.quiknode.pro"; + case "bnb": + return "ethers.bsc.quiknode.pro"; + case "bnbt": + return "ethers.bsc-testnet.quiknode.pro"; + case "matic": + return "ethers.matic.quiknode.pro"; + case "matic-mumbai": + return "ethers.matic-testnet.quiknode.pro"; + case "optimism": + return "ethers.optimism.quiknode.pro"; + case "optimism-goerli": + return "ethers.optimism-goerli.quiknode.pro"; + case "optimism-sepolia": + return "ethers.optimism-sepolia.quiknode.pro"; + case "xdai": + return "ethers.xdai.quiknode.pro"; + } + assertArgument(false, "unsupported network", "network", name); +} +class QuickNodeProvider extends JsonRpcProvider { + token; + constructor(_network, token){ + if (_network == null) { + _network = "mainnet"; + } + const network = Network.from(_network); + if (token == null) { + token = defaultToken; + } + const request = QuickNodeProvider.getRequest(network, token); + super(request, network, { + staticNetwork: network }); - } - if (message.match(/nonce (is )?too low/i)) { - logger$21.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, { - error, - method, - transaction + defineProperties(this, { + token: token }); } - if (message.match(/replacement transaction underpriced|transaction gas price.*too low/i)) { - logger$21.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, { - error, - method, - transaction - }); + _getProvider(chainId) { + try { + return new QuickNodeProvider(chainId, this.token); + } catch (error) {} + return super._getProvider(chainId); } - if (message.match(/only replay-protected/i)) { - logger$21.throwError("legacy pre-eip-155 transactions not supported", Logger.errors.UNSUPPORTED_OPERATION, { - error, - method, - transaction - }); + isCommunityResource() { + return this.token === defaultToken; } - if (errorGas.indexOf(method) >= 0 && message.match(/gas required exceeds allowance|always failing transaction|execution reverted|revert/)) { - logger$21.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, { - error, - method, - transaction - }); + static getRequest(network, token) { + if (token == null) { + token = defaultToken; + } + const request = new FetchRequest(`https:/\/${getHost$1(network.name)}/${token}`); + request.allowGzip = true; + if (token === defaultToken) { + request.retryFunc = async (request, response, attempt)=>{ + showThrottleMessage("QuickNodeProvider"); + return true; + }; + } + return request; } - throw error; -} -function timer(timeout) { - return new Promise(function(resolve) { - setTimeout(resolve, timeout); - }); } -function getResult(payload) { - if (payload.error) { - const error = new Error(payload.error.message); - error.code = payload.error.code; - error.data = payload.error.data; - throw error; +const BN_1 = BigInt("1"); +const BN_2 = BigInt("2"); +function shuffle(array) { + for(let i = array.length - 1; i > 0; i--){ + const j = Math.floor(Math.random() * (i + 1)); + const tmp = array[i]; + array[i] = array[j]; + array[j] = tmp; } - return payload.result; } -function getLowerCase(value) { - if (value) { - return value.toLowerCase(); - } - return value; +function stall$2(duration) { + return new Promise((resolve)=>{ + setTimeout(resolve, duration); + }); } -const _constructorGuard3 = {}; -class JsonRpcSigner extends Signer { - constructor(constructorGuard, provider, addressOrIndex){ - super(); - if (constructorGuard !== _constructorGuard3) { - throw new Error("do not call the JsonRpcSigner constructor directly; use provider.getSigner"); - } - defineReadOnly(this, "provider", provider); - if (addressOrIndex == null) { - addressOrIndex = 0; - } - if (typeof addressOrIndex === "string") { - defineReadOnly(this, "_address", this.provider.formatter.address(addressOrIndex)); - defineReadOnly(this, "_index", null); - } else if (typeof addressOrIndex === "number") { - defineReadOnly(this, "_index", addressOrIndex); - defineReadOnly(this, "_address", null); - } else { - logger$21.throwArgumentError("invalid address or index", "addressOrIndex", addressOrIndex); - } - } - connect(provider) { - return logger$21.throwError("cannot alter JSON-RPC Signer connection", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "connect" - }); - } - connectUnchecked() { - return new UncheckedJsonRpcSigner(_constructorGuard3, this.provider, this._address || this._index); - } - getAddress() { - if (this._address) { - return Promise.resolve(this._address); +function getTime() { + return (new Date).getTime(); +} +function stringify(value) { + return JSON.stringify(value, (key, value)=>{ + if (typeof value === "bigint") { + return { + type: "bigint", + value: value.toString() + }; } - return this.provider.send("eth_accounts", []).then((accounts)=>{ - if (accounts.length <= this._index) { - logger$21.throwError("unknown account #" + this._index, Logger.errors.UNSUPPORTED_OPERATION, { - operation: "getAddress" - }); - } - return this.provider.formatter.address(accounts[this._index]); - }); - } - sendUncheckedTransaction(transaction) { - transaction = shallowCopy(transaction); - const fromAddress = this.getAddress().then((address2)=>{ - if (address2) { - address2 = address2.toLowerCase(); - } - return address2; - }); - if (transaction.gasLimit == null) { - const estimate = shallowCopy(transaction); - estimate.from = fromAddress; - transaction.gasLimit = this.provider.estimateGas(estimate); - } - if (transaction.to != null) { - transaction.to = Promise.resolve(transaction.to).then((to)=>__awaiter$11(this, void 0, void 0, function*() { - if (to == null) { - return null; - } - const address2 = yield this.provider.resolveName(to); - if (address2 == null) { - logger$21.throwArgumentError("provided ENS name resolves to null", "tx.to", to); + return value; + }); +} +const defaultConfig = { + stallTimeout: 400, + priority: 1, + weight: 1 +}; +const defaultState = { + blockNumber: -2, + requests: 0, + lateResponses: 0, + errorResponses: 0, + outOfSync: -1, + unsupportedEvents: 0, + rollingDuration: 0, + score: 0, + _network: null, + _updateNumber: null, + _totalTime: 0, + _lastFatalError: null, + _lastFatalErrorTimestamp: 0 +}; +async function waitForSync(config, blockNumber) { + while(config.blockNumber < 0 || config.blockNumber < blockNumber){ + if (!config._updateNumber) { + config._updateNumber = (async ()=>{ + try { + const blockNumber = await config.provider.getBlockNumber(); + if (blockNumber > config.blockNumber) { + config.blockNumber = blockNumber; } - return address2; - })); - } - return resolveProperties({ - tx: resolveProperties(transaction), - sender: fromAddress - }).then(({ tx, sender })=>{ - if (tx.from != null) { - if (tx.from.toLowerCase() !== sender) { - logger$21.throwArgumentError("from address mismatch", "transaction", transaction); - } - } else { - tx.from = sender; - } - const hexTx = this.provider.constructor.hexlifyTransaction(tx, { - from: true - }); - return this.provider.send("eth_sendTransaction", [ - hexTx - ]).then((hash2)=>{ - return hash2; - }, (error)=>{ - if (typeof error.message === "string" && error.message.match(/user denied/i)) { - logger$21.throwError("user rejected transaction", Logger.errors.ACTION_REJECTED, { - action: "sendTransaction", - transaction: tx - }); + } catch (error) { + config.blockNumber = -2; + config._lastFatalError = error; + config._lastFatalErrorTimestamp = getTime(); } - return checkError("sendTransaction", error, hexTx); - }); - }); + config._updateNumber = null; + })(); + } + await config._updateNumber; + config.outOfSync++; + if (config._lastFatalError) { + break; + } } - signTransaction(transaction) { - return logger$21.throwError("signing transactions is unsupported", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "signTransaction" - }); +} +function _normalize(value) { + if (value == null) { + return "null"; } - sendTransaction(transaction) { - return __awaiter$11(this, void 0, void 0, function*() { - const blockNumber = yield this.provider._getInternalBlockNumber(100 + 2 * this.provider.pollingInterval); - const hash2 = yield this.sendUncheckedTransaction(transaction); - try { - return yield poll(()=>__awaiter$11(this, void 0, void 0, function*() { - const tx = yield this.provider.getTransaction(hash2); - if (tx === null) { - return void 0; - } - return this.provider._wrapTransaction(tx, hash2, blockNumber); - }), { - oncePoll: this.provider - }); - } catch (error) { - error.transactionHash = hash2; - throw error; + if (Array.isArray(value)) { + return "[" + value.map(_normalize).join(",") + "]"; + } + if (typeof value === "object" && typeof value.toJSON === "function") { + return _normalize(value.toJSON()); + } + switch(typeof value){ + case "boolean": + case "symbol": + return value.toString(); + case "bigint": + case "number": + return BigInt(value).toString(); + case "string": + return JSON.stringify(value); + case "object": + { + const keys = Object.keys(value); + keys.sort(); + return "{" + keys.map((k)=>`${JSON.stringify(k)}:${_normalize(value[k])}`).join(",") + "}"; } - }); } - signMessage(message) { - return __awaiter$11(this, void 0, void 0, function*() { - const data = typeof message === "string" ? toUtf8Bytes(message) : message; - const address2 = yield this.getAddress(); - try { - return yield this.provider.send("personal_sign", [ - hexlify(data), - address2.toLowerCase() - ]); - } catch (error) { - if (typeof error.message === "string" && error.message.match(/user denied/i)) { - logger$21.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, { - action: "signMessage", - from: address2, - messageData: message - }); - } - throw error; - } - }); + console.log("Could not serialize", value); + throw new Error("Hmm..."); +} +function normalizeResult(value) { + if ("error" in value) { + const error = value.error; + return { + tag: _normalize(error), + value: error + }; } - _legacySignMessage(message) { - return __awaiter$11(this, void 0, void 0, function*() { - const data = typeof message === "string" ? toUtf8Bytes(message) : message; - const address2 = yield this.getAddress(); - try { - return yield this.provider.send("eth_sign", [ - address2.toLowerCase(), - hexlify(data) - ]); - } catch (error) { - if (typeof error.message === "string" && error.message.match(/user denied/i)) { - logger$21.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, { - action: "_legacySignMessage", - from: address2, - messageData: message - }); - } - throw error; - } - }); + const result = value.result; + return { + tag: _normalize(result), + value: result + }; +} +function checkQuorum(quorum, results) { + const tally = new Map; + for (const { value, tag, weight } of results){ + const t = tally.get(tag) || { + value: value, + weight: 0 + }; + t.weight += weight; + tally.set(tag, t); } - _signTypedData(domain, types, value) { - return __awaiter$11(this, void 0, void 0, function*() { - const populated = yield TypedDataEncoder.resolveNames(domain, types, value, (name)=>{ - return this.provider.resolveName(name); - }); - const address2 = yield this.getAddress(); - try { - return yield this.provider.send("eth_signTypedData_v4", [ - address2.toLowerCase(), - JSON.stringify(TypedDataEncoder.getPayload(populated.domain, types, populated.value)) - ]); - } catch (error) { - if (typeof error.message === "string" && error.message.match(/user denied/i)) { - logger$21.throwError("user rejected signing", Logger.errors.ACTION_REJECTED, { - action: "_signTypedData", - from: address2, - messageData: { - domain: populated.domain, - types, - value: populated.value - } - }); - } - throw error; - } - }); + let best = null; + for (const r of tally.values()){ + if (r.weight >= quorum && (!best || r.weight > best.weight)) { + best = r; + } } - unlock(password) { - return __awaiter$11(this, void 0, void 0, function*() { - const provider = this.provider; - const address2 = yield this.getAddress(); - return provider.send("personal_unlockAccount", [ - address2.toLowerCase(), - password, - null - ]); - }); + if (best) { + return best.value; } + return undefined; } -class UncheckedJsonRpcSigner extends JsonRpcSigner { - sendTransaction(transaction) { - return this.sendUncheckedTransaction(transaction).then((hash2)=>{ - return { - hash: hash2, - nonce: null, - gasLimit: null, - gasPrice: null, - data: null, - value: null, - chainId: null, - confirmations: 0, - from: null, - wait: (confirmations)=>{ - return this.provider.waitForTransaction(hash2, confirmations); - } +function getMedian(quorum, results) { + let resultWeight = 0; + const errorMap = new Map; + let bestError = null; + const values = []; + for (const { value, tag, weight } of results){ + if (value instanceof Error) { + const e = errorMap.get(tag) || { + value: value, + weight: 0 }; - }); - } -} -const allowedTransactionKeys3 = { - chainId: true, - data: true, - gasLimit: true, - gasPrice: true, - nonce: true, - to: true, - value: true, - type: true, - accessList: true, - maxFeePerGas: true, - maxPriorityFeePerGas: true -}; -class JsonRpcProvider extends BaseProvider { - constructor(url, network){ - let networkOrReady = network; - if (networkOrReady == null) { - networkOrReady = new Promise((resolve, reject)=>{ - setTimeout(()=>{ - this.detectNetwork().then((network2)=>{ - resolve(network2); - }, (error)=>{ - reject(error); - }); - }, 0); - }); - } - super(networkOrReady); - if (!url) { - url = getStatic(this.constructor, "defaultUrl")(); - } - if (typeof url === "string") { - defineReadOnly(this, "connection", Object.freeze({ - url - })); + e.weight += weight; + errorMap.set(tag, e); + if (bestError == null || e.weight > bestError.weight) { + bestError = e; + } } else { - defineReadOnly(this, "connection", Object.freeze(shallowCopy(url))); + values.push(BigInt(value)); + resultWeight += weight; } - this._nextId = 42; } - get _cache() { - if (this._eventLoopCache == null) { - this._eventLoopCache = {}; + if (resultWeight < quorum) { + if (bestError && bestError.weight >= quorum) { + return bestError.value; } - return this._eventLoopCache; + return undefined; } - static defaultUrl() { - return "http://localhost:8545"; + values.sort((a, b)=>a < b ? -1 : b > a ? 1 : 0); + const mid = Math.floor(values.length / 2); + if (values.length % 2) { + return values[mid]; } - detectNetwork() { - if (!this._cache["detectNetwork"]) { - this._cache["detectNetwork"] = this._uncachedDetectNetwork(); - setTimeout(()=>{ - this._cache["detectNetwork"] = null; - }, 0); + return (values[mid - 1] + values[mid] + BN_1) / BN_2; +} +function getAnyResult(quorum, results) { + const result = checkQuorum(quorum, results); + if (result !== undefined) { + return result; + } + for (const r of results){ + if (r.value) { + return r.value; } - return this._cache["detectNetwork"]; } - _uncachedDetectNetwork() { - return __awaiter$11(this, void 0, void 0, function*() { - yield timer(0); - let chainId = null; - try { - chainId = yield this.send("eth_chainId", []); - } catch (error) { - try { - chainId = yield this.send("net_version", []); - } catch (error2) {} + return undefined; +} +function getFuzzyMode(quorum, results) { + if (quorum === 1) { + return getNumber(getMedian(quorum, results), "%internal"); + } + const tally = new Map; + const add = (result, weight)=>{ + const t = tally.get(result) || { + result: result, + weight: 0 + }; + t.weight += weight; + tally.set(result, t); + }; + for (const { weight, value } of results){ + const r = getNumber(value); + add(r - 1, weight); + add(r, weight); + add(r + 1, weight); + } + let bestWeight = 0; + let bestResult = undefined; + for (const { weight, result } of tally.values()){ + if (weight >= quorum && (weight > bestWeight || bestResult != null && weight === bestWeight && result > bestResult)) { + bestWeight = weight; + bestResult = result; + } + } + return bestResult; +} +class FallbackProvider extends AbstractProvider { + quorum; + eventQuorum; + eventWorkers; + #configs; + #height; + #initialSyncPromise; + constructor(providers, network, options){ + super(network, options); + this.#configs = providers.map((p)=>{ + if (p instanceof AbstractProvider) { + return Object.assign({ + provider: p + }, defaultConfig, defaultState); + } else { + return Object.assign({}, defaultConfig, p, defaultState); } - if (chainId != null) { - const getNetwork3 = getStatic(this.constructor, "getNetwork"); - try { - return getNetwork3(BigNumber.from(chainId).toNumber()); - } catch (error) { - return logger$21.throwError("could not detect network", Logger.errors.NETWORK_ERROR, { - chainId, - event: "invalidNetwork", - serverError: error - }); + }); + this.#height = -2; + this.#initialSyncPromise = null; + if (options && options.quorum != null) { + this.quorum = options.quorum; + } else { + this.quorum = Math.ceil(this.#configs.reduce((accum, config)=>{ + accum += config.weight; + return accum; + }, 0) / 2); + } + this.eventQuorum = 1; + this.eventWorkers = 1; + assertArgument(this.quorum <= this.#configs.reduce((a, c)=>a + c.weight, 0), "quorum exceed provider weight", "quorum", this.quorum); + } + get providerConfigs() { + return this.#configs.map((c)=>{ + const result = Object.assign({}, c); + for(const key in result){ + if (key[0] === "_") { + delete result[key]; } } - return logger$21.throwError("could not detect network", Logger.errors.NETWORK_ERROR, { - event: "noNetwork" - }); + return result; }); } - getSigner(addressOrIndex) { - return new JsonRpcSigner(_constructorGuard3, this, addressOrIndex); + async _detectNetwork() { + return Network.from(getBigInt(await this._perform({ + method: "chainId" + }))); } - getUncheckedSigner(addressOrIndex) { - return this.getSigner(addressOrIndex).connectUnchecked(); - } - listAccounts() { - return this.send("eth_accounts", []).then((accounts)=>{ - return accounts.map((a)=>this.formatter.address(a)); - }); + async _translatePerform(provider, req) { + switch(req.method){ + case "broadcastTransaction": + return await provider.broadcastTransaction(req.signedTransaction); + case "call": + return await provider.call(Object.assign({}, req.transaction, { + blockTag: req.blockTag + })); + case "chainId": + return (await provider.getNetwork()).chainId; + case "estimateGas": + return await provider.estimateGas(req.transaction); + case "getBalance": + return await provider.getBalance(req.address, req.blockTag); + case "getBlock": + { + const block = "blockHash" in req ? req.blockHash : req.blockTag; + return await provider.getBlock(block, req.includeTransactions); + } + case "getBlockNumber": + return await provider.getBlockNumber(); + case "getCode": + return await provider.getCode(req.address, req.blockTag); + case "getGasPrice": + return (await provider.getFeeData()).gasPrice; + case "getPriorityFee": + return (await provider.getFeeData()).maxPriorityFeePerGas; + case "getLogs": + return await provider.getLogs(req.filter); + case "getStorage": + return await provider.getStorage(req.address, req.position, req.blockTag); + case "getTransaction": + return await provider.getTransaction(req.hash); + case "getTransactionCount": + return await provider.getTransactionCount(req.address, req.blockTag); + case "getTransactionReceipt": + return await provider.getTransactionReceipt(req.hash); + case "getTransactionResult": + return await provider.getTransactionResult(req.hash); + } + } + #getNextConfig(running) { + const configs = Array.from(running).map((r)=>r.config); + const allConfigs = this.#configs.slice(); + shuffle(allConfigs); + allConfigs.sort((a, b)=>a.priority - b.priority); + for (const config of allConfigs){ + if (config._lastFatalError) { + continue; + } + if (configs.indexOf(config) === -1) { + return config; + } + } + return null; } - send(method, params) { - const request = { - method, - params, - id: this._nextId++, - jsonrpc: "2.0" + #addRunner(running, req) { + const config = this.#getNextConfig(running); + if (config == null) { + return null; + } + const runner = { + config: config, + result: null, + didBump: false, + perform: null, + staller: null }; - this.emit("debug", { - action: "request", - request: deepCopy(request), - provider: this - }); - const cache = [ - "eth_chainId", - "eth_blockNumber" - ].indexOf(method) >= 0; - if (cache && this._cache[method]) { - return this._cache[method]; - } - const result = fetchJson(this.connection, JSON.stringify(request), getResult).then((result2)=>{ - this.emit("debug", { - action: "response", - request, - response: result2, - provider: this - }); - return result2; - }, (error)=>{ - this.emit("debug", { - action: "response", - error, - request, - provider: this + const now = getTime(); + runner.perform = (async ()=>{ + try { + config.requests++; + const result = await this._translatePerform(config.provider, req); + runner.result = { + result: result + }; + } catch (error) { + config.errorResponses++; + runner.result = { + error: error + }; + } + const dt = getTime() - now; + config._totalTime += dt; + config.rollingDuration = .95 * config.rollingDuration + .05 * dt; + runner.perform = null; + })(); + runner.staller = (async ()=>{ + await stall$2(config.stallTimeout); + runner.staller = null; + })(); + running.add(runner); + return runner; + } + async #initialSync() { + let initialSync = this.#initialSyncPromise; + if (!initialSync) { + const promises = []; + this.#configs.forEach((config)=>{ + promises.push((async ()=>{ + await waitForSync(config, 0); + if (!config._lastFatalError) { + config._network = await config.provider.getNetwork(); + } + })()); }); - throw error; - }); - if (cache) { - this._cache[method] = result; - setTimeout(()=>{ - this._cache[method] = null; - }, 0); + this.#initialSyncPromise = initialSync = (async ()=>{ + await Promise.all(promises); + let chainId = null; + for (const config of this.#configs){ + if (config._lastFatalError) { + continue; + } + const network = config._network; + if (chainId == null) { + chainId = network.chainId; + } else if (network.chainId !== chainId) { + assert1(false, "cannot mix providers on different networks", "UNSUPPORTED_OPERATION", { + operation: "new FallbackProvider" + }); + } + } + })(); } - return result; + await initialSync; } - prepareRequest(method, params) { - switch(method){ + async #checkQuorum(running, req) { + const results = []; + for (const runner of running){ + if (runner.result != null) { + const { tag, value } = normalizeResult(runner.result); + results.push({ + tag: tag, + value: value, + weight: runner.config.weight + }); + } + } + if (results.reduce((a, r)=>a + r.weight, 0) < this.quorum) { + return undefined; + } + switch(req.method){ case "getBlockNumber": - return [ - "eth_blockNumber", - [] - ]; + { + if (this.#height === -2) { + this.#height = Math.ceil(getNumber(getMedian(this.quorum, this.#configs.filter((c)=>!c._lastFatalError).map((c)=>({ + value: c.blockNumber, + tag: getNumber(c.blockNumber).toString(), + weight: c.weight + }))))); + } + const mode = getFuzzyMode(this.quorum, results); + if (mode === undefined) { + return undefined; + } + if (mode > this.#height) { + this.#height = mode; + } + return this.#height; + } case "getGasPrice": - return [ - "eth_gasPrice", - [] - ]; + case "getPriorityFee": + case "estimateGas": + return getMedian(this.quorum, results); + case "getBlock": + if ("blockTag" in req && req.blockTag === "pending") { + return getAnyResult(this.quorum, results); + } + return checkQuorum(this.quorum, results); + case "call": + case "chainId": case "getBalance": - return [ - "eth_getBalance", - [ - getLowerCase(params.address), - params.blockTag - ] - ]; case "getTransactionCount": - return [ - "eth_getTransactionCount", - [ - getLowerCase(params.address), - params.blockTag - ] - ]; case "getCode": - return [ - "eth_getCode", - [ - getLowerCase(params.address), - params.blockTag - ] - ]; - case "getStorageAt": - return [ - "eth_getStorageAt", - [ - getLowerCase(params.address), - hexZeroPad(params.position, 32), - params.blockTag - ] - ]; - case "sendTransaction": - return [ - "eth_sendRawTransaction", - [ - params.signedTransaction - ] - ]; - case "getBlock": - if (params.blockTag) { - return [ - "eth_getBlockByNumber", - [ - params.blockTag, - !!params.includeTransactions - ] - ]; - } else if (params.blockHash) { - return [ - "eth_getBlockByHash", - [ - params.blockHash, - !!params.includeTransactions - ] - ]; - } - return null; + case "getStorage": case "getTransaction": - return [ - "eth_getTransactionByHash", - [ - params.transactionHash - ] - ]; case "getTransactionReceipt": - return [ - "eth_getTransactionReceipt", - [ - params.transactionHash - ] - ]; - case "call": - { - const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction"); - return [ - "eth_call", - [ - hexlifyTransaction(params.transaction, { - from: true - }), - params.blockTag - ] - ]; - } - case "estimateGas": - { - const hexlifyTransaction = getStatic(this.constructor, "hexlifyTransaction"); - return [ - "eth_estimateGas", - [ - hexlifyTransaction(params.transaction, { - from: true - }) - ] - ]; - } case "getLogs": - if (params.filter && params.filter.address != null) { - params.filter.address = getLowerCase(params.filter.address); - } - return [ - "eth_getLogs", - [ - params.filter - ] - ]; + return checkQuorum(this.quorum, results); + case "broadcastTransaction": + return getAnyResult(this.quorum, results); } - return null; + assert1(false, "unsupported method", "UNSUPPORTED_OPERATION", { + operation: `_perform(${stringify(req.method)})` + }); } - perform(method, params) { - return __awaiter$11(this, void 0, void 0, function*() { - if (method === "call" || method === "estimateGas") { - const tx = params.transaction; - if (tx && tx.type != null && BigNumber.from(tx.type).isZero()) { - if (tx.maxFeePerGas == null && tx.maxPriorityFeePerGas == null) { - const feeData = yield this.getFeeData(); - if (feeData.maxFeePerGas == null && feeData.maxPriorityFeePerGas == null) { - params = shallowCopy(params); - params.transaction = shallowCopy(tx); - delete params.transaction.type; - } - } - } + async #waitForQuorum(running, req) { + if (running.size === 0) { + throw new Error("no runners?!"); + } + const interesting = []; + let newRunners = 0; + for (const runner of running){ + if (runner.perform) { + interesting.push(runner.perform); } - const args = this.prepareRequest(method, params); - if (args == null) { - logger$21.throwError(method + " not implemented", Logger.errors.NOT_IMPLEMENTED, { - operation: method - }); + if (runner.staller) { + interesting.push(runner.staller); + continue; } - try { - return yield this.send(args[0], args[1]); - } catch (error) { - return checkError(method, error, params); + if (runner.didBump) { + continue; } - }); - } - _startEvent(event) { - if (event.tag === "pending") { - this._startPending(); + runner.didBump = true; + newRunners++; } - super._startEvent(event); - } - _startPending() { - if (this._pendingFilter != null) { - return; + const value = await this.#checkQuorum(running, req); + if (value !== undefined) { + if (value instanceof Error) { + throw value; + } + return value; } - const self1 = this; - const pendingFilter = this.send("eth_newPendingTransactionFilter", []); - this._pendingFilter = pendingFilter; - pendingFilter.then(function(filterId) { - function poll2() { - self1.send("eth_getFilterChanges", [ - filterId - ]).then(function(hashes) { - if (self1._pendingFilter != pendingFilter) { - return null; - } - let seq = Promise.resolve(); - hashes.forEach(function(hash2) { - self1._emitted["t:" + hash2.toLowerCase()] = "pending"; - seq = seq.then(function() { - return self1.getTransaction(hash2).then(function(tx) { - self1.emit("pending", tx); - return null; - }); - }); + for(let i = 0; i < newRunners; i++){ + this.#addRunner(running, req); + } + assert1(interesting.length > 0, "quorum not met", "SERVER_ERROR", { + request: "%sub-requests", + info: { + request: req, + results: Array.from(running).map((r)=>stringify(r.result)) + } + }); + await Promise.race(interesting); + return await this.#waitForQuorum(running, req); + } + async _perform(req) { + if (req.method === "broadcastTransaction") { + const results = this.#configs.map((c)=>null); + const broadcasts = this.#configs.map(async ({ provider, weight }, index)=>{ + try { + const result = await provider._perform(req); + results[index] = Object.assign(normalizeResult({ + result: result + }), { + weight: weight }); - return seq.then(function() { - return timer(1e3); + } catch (error) { + results[index] = Object.assign(normalizeResult({ + error: error + }), { + weight: weight }); - }).then(function() { - if (self1._pendingFilter != pendingFilter) { - self1.send("eth_uninstallFilter", [ - filterId - ]); - return; + } + }); + while(true){ + const done = results.filter((r)=>r != null); + for (const { value } of done){ + if (!(value instanceof Error)) { + return value; } - setTimeout(function() { - poll2(); - }, 0); - return null; - }).catch((error)=>{}); + } + const result = checkQuorum(this.quorum, results.filter((r)=>r != null)); + if (isError(result, "INSUFFICIENT_FUNDS")) { + throw result; + } + const waiting = broadcasts.filter((b, i)=>results[i] == null); + if (waiting.length === 0) { + break; + } + await Promise.race(waiting); } - poll2(); - return filterId; - }).catch((error)=>{}); - } - _stopEvent(event) { - if (event.tag === "pending" && this.listenerCount("pending") === 0) { - this._pendingFilter = null; - } - super._stopEvent(event); - } - static hexlifyTransaction(transaction, allowExtra) { - const allowed = shallowCopy(allowedTransactionKeys3); - if (allowExtra) { - for(const key in allowExtra){ - if (allowExtra[key]) { - allowed[key] = true; + const result = getAnyResult(this.quorum, results); + assert1(result !== undefined, "problem multi-broadcasting", "SERVER_ERROR", { + request: "%sub-requests", + info: { + request: req, + results: results.map(stringify) } + }); + if (result instanceof Error) { + throw result; } + return result; } - checkProperties(transaction, allowed); - const result = {}; - [ - "chainId", - "gasLimit", - "gasPrice", - "type", - "maxFeePerGas", - "maxPriorityFeePerGas", - "nonce", - "value" - ].forEach(function(key) { - if (transaction[key] == null) { - return; + await this.#initialSync(); + const running = new Set; + let inflightQuorum = 0; + while(true){ + const runner = this.#addRunner(running, req); + if (runner == null) { + break; } - const value = hexValue(BigNumber.from(transaction[key])); - if (key === "gasLimit") { - key = "gas"; + inflightQuorum += runner.config.weight; + if (inflightQuorum >= this.quorum) { + break; } - result[key] = value; - }); - [ - "from", - "to", - "data" - ].forEach(function(key) { - if (transaction[key] == null) { - return; + } + const result = await this.#waitForQuorum(running, req); + for (const runner of running){ + if (runner.perform && runner.result == null) { + runner.config.lateResponses++; } - result[key] = hexlify(transaction[key]); - }); - if (transaction.accessList) { - result["accessList"] = accessListify(transaction.accessList); } return result; } -} -let WS = null; -try { - WS = WebSocket; - if (WS == null) { - throw new Error("inject please"); + async destroy() { + for (const { provider } of this.#configs){ + provider.destroy(); + } + super.destroy(); } -} catch (error) { - const logger3 = new Logger(version23); - WS = function() { - logger3.throwError("WebSockets not supported in this environment", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "new WebSocket()" - }); - }; } -var __awaiter$2 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); +function isWebSocketLike(value) { + return value && typeof value.send === "function" && typeof value.close === "function"; +} +const Testnets = "goerli kovan sepolia classicKotti optimism-goerli arbitrum-goerli matic-mumbai bnbt".split(" "); +function getDefaultProvider(network, options) { + if (options == null) { + options = {}; } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + const allowService = (name)=>{ + if (options[name] === "-") { + return false; } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + if (typeof options.exclusive === "string") { + return name === options.exclusive; } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger$31 = new Logger(version23); -let NextId = 1; -class WebSocketProvider extends JsonRpcProvider { - constructor(url, network){ - if (network === "any") { - logger$31.throwError("WebSocketProvider does not support 'any' network yet", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "network:any" - }); + if (Array.isArray(options.exclusive)) { + return options.exclusive.indexOf(name) !== -1; } - if (typeof url === "string") { - super(url, network); - } else { - super("_websocket", network); + return true; + }; + if (typeof network === "string" && network.match(/^https?:/)) { + return new JsonRpcProvider(network); + } + if (typeof network === "string" && network.match(/^wss?:/) || isWebSocketLike(network)) { + return new WebSocketProvider(network); + } + let staticNetwork = null; + try { + staticNetwork = Network.from(network); + } catch (error) {} + const providers = []; + if (allowService("publicPolygon") && staticNetwork) { + if (staticNetwork.name === "matic") { + providers.push(new JsonRpcProvider("https://polygon-rpc.com/", staticNetwork, { + staticNetwork: staticNetwork + })); + } else if (staticNetwork.name === "matic-amoy") { + providers.push(new JsonRpcProvider("https://rpc-amoy.polygon.technology/", staticNetwork, { + staticNetwork: staticNetwork + })); } - this._pollingInterval = -1; - this._wsReady = false; - if (typeof url === "string") { - defineReadOnly(this, "_websocket", new WS(this.connection.url)); - } else { - defineReadOnly(this, "_websocket", url); - } - defineReadOnly(this, "_requests", {}); - defineReadOnly(this, "_subs", {}); - defineReadOnly(this, "_subIds", {}); - defineReadOnly(this, "_detectNetwork", super.detectNetwork()); - this.websocket.onopen = ()=>{ - this._wsReady = true; - Object.keys(this._requests).forEach((id)=>{ - this.websocket.send(this._requests[id].payload); - }); - }; - this.websocket.onmessage = (messageEvent)=>{ - const data = messageEvent.data; - const result = JSON.parse(data); - if (result.id != null) { - const id = String(result.id); - const request = this._requests[id]; - delete this._requests[id]; - if (result.result !== void 0) { - request.callback(null, result.result); - this.emit("debug", { - action: "response", - request: JSON.parse(request.payload), - response: result.result, - provider: this - }); - } else { - let error = null; - if (result.error) { - error = new Error(result.error.message || "unknown error"); - defineReadOnly(error, "code", result.error.code || null); - defineReadOnly(error, "response", data); - } else { - error = new Error("unknown error"); - } - request.callback(error, void 0); - this.emit("debug", { - action: "response", - error, - request: JSON.parse(request.payload), - provider: this - }); - } - } else if (result.method === "eth_subscription") { - const sub = this._subs[result.params.subscription]; - if (sub) { - sub.processFunc(result.params.result); - } - } else { - console.warn("this should not happen"); + } + if (allowService("alchemy")) { + try { + providers.push(new AlchemyProvider(network, options.alchemy)); + } catch (error) {} + } + if (allowService("ankr") && options.ankr != null) { + try { + providers.push(new AnkrProvider(network, options.ankr)); + } catch (error) {} + } + if (allowService("chainstack")) { + try { + providers.push(new ChainstackProvider(network, options.chainstack)); + } catch (error) {} + } + if (allowService("cloudflare")) { + try { + providers.push(new CloudflareProvider(network)); + } catch (error) {} + } + if (allowService("etherscan")) { + try { + providers.push(new EtherscanProvider(network, options.etherscan)); + } catch (error) {} + } + if (allowService("infura")) { + try { + let projectId = options.infura; + let projectSecret = undefined; + if (typeof projectId === "object") { + projectSecret = projectId.projectSecret; + projectId = projectId.projectId; } - }; - const fauxPoll = setInterval(()=>{ - this.emit("poll"); - }, 1e3); - if (fauxPoll.unref) { - fauxPoll.unref(); - } + providers.push(new InfuraProvider(network, projectId, projectSecret)); + } catch (error) {} + } + if (allowService("quicknode")) { + try { + let token = options.quicknode; + providers.push(new QuickNodeProvider(network, token)); + } catch (error) {} } - get websocket() { - return this._websocket; + assert1(providers.length, "unsupported default network", "UNSUPPORTED_OPERATION", { + operation: "getDefaultProvider" + }); + if (providers.length === 1) { + return providers[0]; } - detectNetwork() { - return this._detectNetwork; + let quorum = Math.floor(providers.length / 2); + if (quorum > 2) { + quorum = 2; } - get pollingInterval() { - return 0; + if (staticNetwork && Testnets.indexOf(staticNetwork.name) !== -1) { + quorum = 1; } - resetEventsBlock(blockNumber) { - logger$31.throwError("cannot reset events block on WebSocketProvider", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "resetEventBlock" - }); + if (options && options.quorum) { + quorum = options.quorum; } - set pollingInterval(value) { - logger$31.throwError("cannot set polling interval on WebSocketProvider", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "setPollingInterval" + return new FallbackProvider(providers, undefined, { + quorum: quorum + }); +} +class NonceManager extends AbstractSigner { + signer; + #noncePromise; + #delta; + constructor(signer){ + super(signer.provider); + defineProperties(this, { + signer: signer }); + this.#noncePromise = null; + this.#delta = 0; } - poll() { - return __awaiter$2(this, void 0, void 0, function*() { - return null; - }); + async getAddress() { + return this.signer.getAddress(); } - set polling(value) { - if (!value) { - return; - } - logger$31.throwError("cannot set polling on WebSocketProvider", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "setPolling" - }); + connect(provider) { + return new NonceManager(this.signer.connect(provider)); } - send(method, params) { - const rid = NextId++; - return new Promise((resolve, reject)=>{ - function callback(error, result) { - if (error) { - return reject(error); - } - return resolve(result); - } - const payload = JSON.stringify({ - method, - params, - id: rid, - jsonrpc: "2.0" - }); - this.emit("debug", { - action: "request", - request: JSON.parse(payload), - provider: this - }); - this._requests[String(rid)] = { - callback, - payload - }; - if (this._wsReady) { - this.websocket.send(payload); + async getNonce(blockTag) { + if (blockTag === "pending") { + if (this.#noncePromise == null) { + this.#noncePromise = super.getNonce("pending"); } - }); + const delta = this.#delta; + return await this.#noncePromise + delta; + } + return super.getNonce(blockTag); } - static defaultUrl() { - return "ws://localhost:8546"; + increment() { + this.#delta++; } - _subscribe(tag, param, processFunc) { - return __awaiter$2(this, void 0, void 0, function*() { - let subIdPromise = this._subIds[tag]; - if (subIdPromise == null) { - subIdPromise = Promise.all(param).then((param2)=>{ - return this.send("eth_subscribe", param2); - }); - this._subIds[tag] = subIdPromise; - } - const subId = yield subIdPromise; - this._subs[subId] = { - tag, - processFunc - }; - }); + reset() { + this.#delta = 0; + this.#noncePromise = null; } - _startEvent(event) { - switch(event.type){ - case "block": - this._subscribe("block", [ - "newHeads" - ], (result)=>{ - const blockNumber = BigNumber.from(result.number).toNumber(); - this._emitted.block = blockNumber; - this.emit("block", blockNumber); - }); - break; - case "pending": - this._subscribe("pending", [ - "newPendingTransactions" - ], (result)=>{ - this.emit("pending", result); + async sendTransaction(tx) { + const noncePromise = this.getNonce("pending"); + this.increment(); + tx = await this.signer.populateTransaction(tx); + tx.nonce = await noncePromise; + return await this.signer.sendTransaction(tx); + } + signTransaction(tx) { + return this.signer.signTransaction(tx); + } + signMessage(message) { + return this.signer.signMessage(message); + } + signTypedData(domain, types, value) { + return this.signer.signTypedData(domain, types, value); + } +} +class BrowserProvider extends JsonRpcApiPollingProvider { + #request; + constructor(ethereum, network, _options){ + const options = Object.assign({}, _options != null ? _options : {}, { + batchMaxCount: 1 + }); + assertArgument(ethereum && ethereum.request, "invalid EIP-1193 provider", "ethereum", ethereum); + super(network, options); + this.#request = async (method, params)=>{ + const payload = { + method: method, + params: params + }; + this.emit("debug", { + action: "sendEip1193Request", + payload: payload + }); + try { + const result = await ethereum.request(payload); + this.emit("debug", { + action: "receiveEip1193Result", + result: result }); - break; - case "filter": - this._subscribe(event.tag, [ - "logs", - this._getFilter(event.filter) - ], (result)=>{ - if (result.removed == null) { - result.removed = false; - } - this.emit(event.filter, this.formatter.filterLog(result)); + return result; + } catch (e) { + const error = new Error(e.message); + error.code = e.code; + error.data = e.data; + error.payload = payload; + this.emit("debug", { + action: "receiveEip1193Error", + error: error }); - break; - case "tx": + throw error; + } + }; + } + async send(method, params) { + await this._start(); + return await super.send(method, params); + } + async _send(payload) { + assertArgument(!Array.isArray(payload), "EIP-1193 does not support batch request", "payload", payload); + try { + const result = await this.#request(payload.method, payload.params || []); + return [ { - const emitReceipt = (event2)=>{ - const hash2 = event2.hash; - this.getTransactionReceipt(hash2).then((receipt)=>{ - if (!receipt) { - return; - } - this.emit(hash2, receipt); - }); - }; - emitReceipt(event); - this._subscribe("tx", [ - "newHeads" - ], (result)=>{ - this._events.filter((e)=>e.type === "tx").forEach(emitReceipt); - }); - break; + id: payload.id, + result: result } - case "debug": - case "poll": - case "willPoll": - case "didPoll": - case "error": + ]; + } catch (e) { + return [ + { + id: payload.id, + error: { + code: e.code, + data: e.data, + message: e.message + } + } + ]; + } + } + getRpcError(payload, error) { + error = JSON.parse(JSON.stringify(error)); + switch(error.error.code || -1){ + case 4001: + error.error.message = `ethers-user-denied: ${error.error.message}`; break; - default: - console.log("unhandled:", event); + case 4200: + error.error.message = `ethers-unsupported: ${error.error.message}`; break; } + return super.getRpcError(payload, error); } - _stopEvent(event) { - let tag = event.tag; - if (event.type === "tx") { - if (this._events.filter((e)=>e.type === "tx").length) { - return; - } - tag = "tx"; - } else if (this.listenerCount(event.event)) { - return; + async hasSigner(address) { + if (address == null) { + address = 0; } - const subId = this._subIds[tag]; - if (!subId) { - return; + const accounts = await this.send("eth_accounts", []); + if (typeof address === "number") { + return accounts.length > address; } - delete this._subIds[tag]; - subId.then((subId2)=>{ - if (!this._subs[subId2]) { - return; - } - delete this._subs[subId2]; - this.send("eth_unsubscribe", [ - subId2 - ]); - }); + address = address.toLowerCase(); + return accounts.filter((a)=>a.toLowerCase() === address).length !== 0; } - destroy() { - return __awaiter$2(this, void 0, void 0, function*() { - if (this.websocket.readyState === WS.CONNECTING) { - yield new Promise((resolve)=>{ - this.websocket.onopen = function() { - resolve(true); - }; - this.websocket.onerror = function() { - resolve(false); - }; + async getSigner(address) { + if (address == null) { + address = 0; + } + if (!await this.hasSigner(address)) { + try { + await this.#request("eth_requestAccounts", []); + } catch (error) { + const payload = error.payload; + throw this.getRpcError(payload, { + id: payload.id, + error: error }); } - this.websocket.close(1e3); - }); + } + return await super.getSigner(address); } } -var __awaiter$3 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); +const defaultApplicationId = "62e1ad51b37b8e00394bda3b"; +function getHost(name) { + switch(name){ + case "mainnet": + return "eth-mainnet.gateway.pokt.network"; + case "goerli": + return "eth-goerli.gateway.pokt.network"; + case "matic": + return "poly-mainnet.gateway.pokt.network"; + case "matic-mumbai": + return "polygon-mumbai-rpc.gateway.pokt.network"; + } + assertArgument(false, "unsupported network", "network", name); +} +class PocketProvider extends JsonRpcProvider { + applicationId; + applicationSecret; + constructor(_network, applicationId, applicationSecret){ + if (_network == null) { + _network = "mainnet"; + } + const network = Network.from(_network); + if (applicationId == null) { + applicationId = defaultApplicationId; + } + if (applicationSecret == null) { + applicationSecret = null; + } + const options = { + staticNetwork: network + }; + const request = PocketProvider.getRequest(network, applicationId, applicationSecret); + super(request, network, options); + defineProperties(this, { + applicationId: applicationId, + applicationSecret: applicationSecret }); } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + _getProvider(chainId) { + try { + return new PocketProvider(chainId, this.applicationId, this.applicationSecret); + } catch (error) {} + return super._getProvider(chainId); + } + static getRequest(network, applicationId, applicationSecret) { + if (applicationId == null) { + applicationId = defaultApplicationId; } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + const request = new FetchRequest(`https:/\/${getHost(network.name)}/v1/lb/${applicationId}`); + request.allowGzip = true; + if (applicationSecret) { + request.setCredentials("", applicationSecret); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger$41 = new Logger(version23); -class StaticJsonRpcProvider extends JsonRpcProvider { - detectNetwork() { - const _super = Object.create(null, { - detectNetwork: { - get: ()=>super.detectNetwork - } - }); - return __awaiter$3(this, void 0, void 0, function*() { - let network = this.network; - if (network == null) { - network = yield _super.detectNetwork.call(this); - if (!network) { - logger$41.throwError("no network detected", Logger.errors.UNKNOWN_ERROR, {}); - } - if (this._network == null) { - defineReadOnly(this, "_network", network); - this.emit("network", network, null); - } - } - return network; - }); - } -} -class UrlJsonRpcProvider extends StaticJsonRpcProvider { - constructor(network, apiKey){ - logger$41.checkAbstract(new.target, UrlJsonRpcProvider); - network = getStatic(new.target, "getNetwork")(network); - apiKey = getStatic(new.target, "getApiKey")(apiKey); - const connection = getStatic(new.target, "getUrl")(network, apiKey); - super(connection, network); - if (typeof apiKey === "string") { - defineReadOnly(this, "apiKey", apiKey); - } else if (apiKey != null) { - Object.keys(apiKey).forEach((key)=>{ - defineReadOnly(this, key, apiKey[key]); - }); + if (applicationId === defaultApplicationId) { + request.retryFunc = async (request, response, attempt)=>{ + showThrottleMessage("PocketProvider"); + return true; + }; } - } - _startPending() { - logger$41.warn("WARNING: API provider does not support pending filters"); + return request; } isCommunityResource() { - return false; + return this.applicationId === defaultApplicationId; } - getSigner(address2) { - return logger$41.throwError("API provider does not support signing", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "getSigner" +} +const IpcSocketProvider = undefined; +class BaseWallet extends AbstractSigner { + address; + #signingKey; + constructor(privateKey, provider){ + super(provider); + assertArgument(privateKey && typeof privateKey.sign === "function", "invalid private key", "privateKey", "[ REDACTED ]"); + this.#signingKey = privateKey; + const address = computeAddress(this.signingKey.publicKey); + defineProperties(this, { + address: address }); } - listAccounts() { - return Promise.resolve([]); - } - static getApiKey(apiKey) { - return apiKey; + get signingKey() { + return this.#signingKey; } - static getUrl(network, apiKey) { - return logger$41.throwError("not implemented; sub-classes must override getUrl", Logger.errors.NOT_IMPLEMENTED, { - operation: "getUrl" - }); - } -} -const logger$5 = new Logger(version23); -const defaultApiKey = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC"; -class AlchemyWebSocketProvider extends WebSocketProvider { - constructor(network, apiKey){ - const provider = new AlchemyProvider(network, apiKey); - const url = provider.connection.url.replace(/^http/i, "ws").replace(".alchemyapi.", ".ws.alchemyapi."); - super(url, provider.network); - defineReadOnly(this, "apiKey", provider.apiKey); + get privateKey() { + return this.signingKey.privateKey; } - isCommunityResource() { - return this.apiKey === defaultApiKey; + async getAddress() { + return this.address; } -} -class AlchemyProvider extends UrlJsonRpcProvider { - static getWebSocketProvider(network, apiKey) { - return new AlchemyWebSocketProvider(network, apiKey); + connect(provider) { + return new BaseWallet(this.#signingKey, provider); } - static getApiKey(apiKey) { - if (apiKey == null) { - return defaultApiKey; + async signTransaction(tx) { + tx = copyRequest(tx); + const { to, from } = await resolveProperties({ + to: tx.to ? resolveAddress(tx.to, this.provider) : undefined, + from: tx.from ? resolveAddress(tx.from, this.provider) : undefined + }); + if (to != null) { + tx.to = to; } - if (apiKey && typeof apiKey !== "string") { - logger$5.throwArgumentError("invalid apiKey", "apiKey", apiKey); + if (from != null) { + tx.from = from; } - return apiKey; - } - static getUrl(network, apiKey) { - let host = null; - switch(network.name){ - case "homestead": - host = "eth-mainnet.alchemyapi.io/v2/"; - break; - case "goerli": - host = "eth-goerli.g.alchemy.com/v2/"; - break; - case "matic": - host = "polygon-mainnet.g.alchemy.com/v2/"; - break; - case "maticmum": - host = "polygon-mumbai.g.alchemy.com/v2/"; - break; - case "arbitrum": - host = "arb-mainnet.g.alchemy.com/v2/"; - break; - case "arbitrum-goerli": - host = "arb-goerli.g.alchemy.com/v2/"; - break; - case "optimism": - host = "opt-mainnet.g.alchemy.com/v2/"; - break; - case "optimism-goerli": - host = "opt-goerli.g.alchemy.com/v2/"; - break; - default: - logger$5.throwArgumentError("unsupported network", "network", arguments[0]); + if (tx.from != null) { + assertArgument(getAddress(tx.from) === this.address, "transaction from address mismatch", "tx.from", tx.from); + delete tx.from; } - return { - allowGzip: true, - url: "https://" + host + apiKey, - throttleCallback: (attempt, url)=>{ - if (apiKey === defaultApiKey) { - showThrottleMessage(); - } - return Promise.resolve(true); - } - }; - } - isCommunityResource() { - return this.apiKey === defaultApiKey; + const btx = Transaction.from(tx); + btx.signature = this.signingKey.sign(btx.unsignedHash); + return btx.serialized; } -} -const logger$6 = new Logger(version23); -const defaultApiKey$1 = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972"; -function getHost(name) { - switch(name){ - case "homestead": - return "rpc.ankr.com/eth/"; - case "ropsten": - return "rpc.ankr.com/eth_ropsten/"; - case "rinkeby": - return "rpc.ankr.com/eth_rinkeby/"; - case "goerli": - return "rpc.ankr.com/eth_goerli/"; - case "matic": - return "rpc.ankr.com/polygon/"; - case "arbitrum": - return "rpc.ankr.com/arbitrum/"; + async signMessage(message) { + return this.signMessageSync(message); } - return logger$6.throwArgumentError("unsupported network", "name", name); -} -class AnkrProvider extends UrlJsonRpcProvider { - isCommunityResource() { - return this.apiKey === defaultApiKey$1; + signMessageSync(message) { + return this.signingKey.sign(hashMessage(message)).serialized; } - static getApiKey(apiKey) { - if (apiKey == null) { - return defaultApiKey$1; + async signTypedData(domain, types, value) { + const populated = await TypedDataEncoder.resolveNames(domain, types, value, async (name)=>{ + assert1(this.provider != null, "cannot resolve ENS names without a provider", "UNSUPPORTED_OPERATION", { + operation: "resolveName", + info: { + name: name + } + }); + const address = await this.provider.resolveName(name); + assert1(address != null, "unconfigured ENS name", "UNCONFIGURED_NAME", { + value: name + }); + return address; + }); + return this.signingKey.sign(TypedDataEncoder.hash(populated.domain, types, populated.value)).serialized; + } +} +const subsChrs = " !#$%&'()*+,-./<=>?@[]^_`{|}~"; +const Word = /^[a-z]*$/i; +function unfold(words, sep) { + let initial = 97; + return words.reduce((accum, word)=>{ + if (word === sep) { + initial++; + } else if (word.match(Word)) { + accum.push(String.fromCharCode(initial) + word); + } else { + initial = 97; + accum.push(word); } - return apiKey; + return accum; + }, []); +} +function decode1(data, subs) { + for(let i = subsChrs.length - 1; i >= 0; i--){ + data = data.split(subsChrs[i]).join(subs.substring(2 * i, 2 * i + 2)); } - static getUrl(network, apiKey) { - if (apiKey == null) { - apiKey = defaultApiKey$1; - } - const connection = { - allowGzip: true, - url: "https://" + getHost(network.name) + apiKey, - throttleCallback: (attempt, url)=>{ - if (apiKey.apiKey === defaultApiKey$1) { - showThrottleMessage(); - } - return Promise.resolve(true); + const clumps = []; + const leftover = data.replace(/(:|([0-9])|([A-Z][a-z]*))/g, (all, item, semi, word)=>{ + if (semi) { + for(let i = parseInt(semi); i >= 0; i--){ + clumps.push(";"); } - }; - if (apiKey.projectSecret != null) { - connection.user = ""; - connection.password = apiKey.projectSecret; + } else { + clumps.push(item.toLowerCase()); } - return connection; + return ""; + }); + if (leftover) { + throw new Error(`leftovers: ${JSON.stringify(leftover)}`); } + return unfold(unfold(clumps, ";"), ":"); +} +function decodeOwl(data) { + assertArgument(data[0] === "0", "unsupported auwl data", "data", data); + return decode1(data.substring(1 + 2 * subsChrs.length), data.substring(1, 1 + 2 * subsChrs.length)); } -var __awaiter$4 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); +class Wordlist { + locale; + constructor(locale){ + defineProperties(this, { + locale: locale }); } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); + split(phrase) { + return phrase.toLowerCase().split(/\s+/g); + } + join(words) { + return words.join(" "); + } +} +class WordlistOwl extends Wordlist { + #data; + #checksum; + constructor(locale, data, checksum){ + super(locale); + this.#data = data; + this.#checksum = checksum; + this.#words = null; + } + get _data() { + return this.#data; + } + _decodeWords() { + return decodeOwl(this.#data); + } + #words; + #loadWords() { + if (this.#words == null) { + const words = this._decodeWords(); + const checksum = id(words.join("\n") + "\n"); + if (checksum !== this.#checksum) { + throw new Error(`BIP39 Wordlist for ${this.locale} FAILED`); } + this.#words = words; } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger$7 = new Logger(version23); -class CloudflareProvider extends UrlJsonRpcProvider { - static getApiKey(apiKey) { - if (apiKey != null) { - logger$7.throwArgumentError("apiKey not supported for cloudflare", "apiKey", apiKey); - } - return null; + return this.#words; } - static getUrl(network, apiKey) { - let host = null; - switch(network.name){ - case "homestead": - host = "https://cloudflare-eth.com/"; - break; - default: - logger$7.throwArgumentError("unsupported network", "network", arguments[0]); - } - return host; + getWord(index) { + const words = this.#loadWords(); + assertArgument(index >= 0 && index < words.length, `invalid word index: ${index}`, "index", index); + return words[index]; } - perform(method, params) { - const _super = Object.create(null, { - perform: { - get: ()=>super.perform - } - }); - return __awaiter$4(this, void 0, void 0, function*() { - if (method === "getBlockNumber") { - const block = yield _super.perform.call(this, "getBlock", { - blockTag: "latest" - }); - return block.number; - } - return _super.perform.call(this, method, params); - }); + getWordIndex(word) { + return this.#loadWords().indexOf(word); } } -var __awaiter$5 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); +const words = "0erleonalorenseinceregesticitStanvetearctssi#ch2Athck&tneLl0And#Il.yLeOutO=S|S%b/ra@SurdU'0Ce[Cid|CountCu'Hie=IdOu,-Qui*Ro[TT]T%T*[Tu$0AptDD-tD*[Ju,M.UltV<)Vi)0Rob-0FairF%dRaid0A(EEntRee0Ead0MRRp%tS!_rmBumCoholErtI&LLeyLowMo,O}PhaReadySoT Ways0A>urAz(gOngOuntU'd0Aly,Ch%Ci|G G!GryIm$K!Noun)Nu$O` Sw T&naTiqueXietyY1ArtOlogyPe?P!Pro=Ril1ChCt-EaEnaGueMMedM%MyOundR<+Re,Ri=RowTTefa@Ti,Tw%k0KPe@SaultSetSi,SumeThma0H!>OmTa{T&dT.udeTra@0Ct]D.Gu,NtTh%ToTumn0Era+OcadoOid0AkeA*AyEsomeFulKw?d0Is:ByChel%C#D+GL<)Lc#y~MbooN_{Ad!AftAmA}AshAt AwlAzyEamEd.EekEwI{etImeIspIt-OpO[Ou^OwdUci$UelUi'Umb!Un^UshYY,$2BeLtu*PPbo?dRiousRr|Rta(R=Sh]/omTe3C!:DMa+MpN)Ng R(gShUght WnY3AlBa>BrisCadeCemb CideCl(eC%a>C*a'ErF&'F(eFyG*eLayLiv M3AgramAlAm#dAryCeE'lEtFf G.$Gn.yLemmaNn NosaurRe@RtSag*eScov Sea'ShSmi[S%d Splay/<)V tVideV%)Zzy5Ct%Cum|G~Lph(Ma(Na>NkeyN%OrSeUb!Ve_ftAg#AmaA,-AwEamE[IftIllInkIpI=OpUmY2CkMbNeR(g/T^Ty1Arf1Nam-:G G!RlyRnR`Sily/Sy1HoOlogyOnomy0GeItUca>1F%t0G1GhtTh 2BowD E@r-EgSe0B?kBodyBra)Er+Ot]PloyPow Pty0Ab!A@DD![D%'EmyErgyF%)Ga+G(eH<)JoyLi,OughR-hRollSu*T Ti*TryVelope1Isode0U$Uip0AA'OdeOs]R%Upt0CapeSayS&)Ta>0Ern$H-s1Id&)IlOkeOl=1A@Amp!Ce[Ch<+C.eCludeCu'Ecu>Erci'Hau,Hib.I!I,ItOt-PM&'Mu}Pa@Po'Pro=Pul'0ChCludeComeC*a'DexD-a>Do%Du,ryFN Noc|PutQuirySSue0Em1Ory:CketGu?RZz3AlousAns~yWel9BInKeUr}yY5D+I)MpNg!Ni%Nk/:Ng?oo3EnEpT^upY3CkDD}yNdNgdomSsTT^&TeTt&Wi4EeIfeO{Ow:BBelB%Dd DyKeMpNgua+PtopR+T T(UghUndryVaWWnWsu.Y Zy3Ad AfArnA=Ctu*FtGG$G&dIsu*M#NdNg`NsOp?dSs#Tt Vel3ArB tyBr?yC&'FeFtGhtKeMbM.NkOnQuid/Tt!VeZ?d5AdAnB, C$CkG-NelyNgOpTt yUdUn+VeY$5CkyGga+Mb N?N^Xury3R-s:Ch(eDG-G}tIdIlInJ%KeMm$NNa+Nda>NgoNs]Nu$P!Rb!R^Rg(R(eRketRria+SkSs/ T^T i$ThTrixTt XimumZe3AdowAnAsu*AtCh<-D$DiaLodyLtMb M%yNt]NuRcyR+R.RryShSsa+T$Thod3Dd!DnightLk~]M-NdNimumN%Nu>Rac!Rr%S ySs/akeXXedXtu*5Bi!DelDifyMM|N.%NkeyN, N`OnR$ReRn(gSqu.oTh T]T%Unta(U'VeVie5ChFf(LeLtiplySc!SeumShroomS-/Tu$3Self/ yTh:I=MePk(Rrow/yT]Tu*3ArCkEdGati=G!@I` PhewR=/TTw%kUtr$V WsXt3CeGht5B!I'M(eeOd!Rm$R`SeTab!TeTh(gTi)VelW5C!?Mb R'T:K0EyJe@Li+Scu*S =Ta(Vious0CurEAyEa'Ed+U{UgUn+2EmEtIntL?LeLi)NdNyOlPul?Rt]S.]Ssib!/TatoTt yV tyWd W _@i)Ai'Ed-tEf Epa*Es|EttyEv|I)IdeIm?yIntI%.yIs#Iva>IzeOb!mO)[Odu)Of.OgramOje@Omo>OofOp tyOsp O>@OudOvide2Bl-Dd(g~LpL'Mpk(N^PilPpyR^a'R.yRpo'R'ShTZz!3Ramid:99Al.yAntumArt E,]I{ItIzO>:Bb.Cco#CeCkD?DioIlInI'~yMpN^NdomN+PidReTeTh V&WZ%3AdyAlAs#BelBuildC$lCei=CipeC%dCyc!Du)F!@F%mFu'G]G*tGul?Je@LaxLea'LiefLyMa(Memb M(dMo=Nd NewNtOp&PairPeatPla)P%tQui*ScueSemb!Si,Sour)Sp#'SultTi*T*atTurnUn]Ve$ViewW?d2Y`m0BBb#CeChDeD+F!GhtGidNgOtPp!SkTu$V$V 5AdA,BotBu,CketM<)OfOkieOmSeTa>UghUndU>Y$5Bb DeGLeNNwayR$:DDd!D}[FeIlLadLm#L#LtLu>MeMp!NdTisfyToshiU)Usa+VeY1A!AnA*Att E}HemeHoolI&)I[%sOrp]OutRapRe&RiptRub1AAr^As#AtC#dC*tCt]Cur.yEdEkGm|Le@~M(?Ni%N'Nt&)RiesRvi)Ss]Tt!TupV&_dowAftAllowA*EdEllEriffIeldIftI}IpIv O{OeOotOpOrtOuld O=RimpRugUff!Y0Bl(gCkDeE+GhtGnL|Lk~yLv Mil?Mp!N)NgR&/ Tua>XZe1A>Et^IIllInIrtUll0AbAmEepEnd I)IdeIghtImOgAyEakEelEmEpE*oI{IllIngO{Oma^O}OolOryO=Ra>gyReetRikeR#gRugg!Ud|UffUmb!Y!0Bje@Bm.BwayC)[ChDd&Ff G?G+,ItMm NNnyN'tP PplyP*meReRfa)R+Rpri'RroundR=ySpe@/a(1AllowAmpApArmE?EetIftImIngIt^Ord1MbolMptomRup/em:B!Ck!GIlL|LkNkPeR+tSk/eTtooXi3A^Am~NNGradeHoldOnP Set1BOng::Rd3Ar~ow9UUngU`:3BraRo9NeO"; +const checksum = "0x3c8acc1e7b08d8e76f9fda015ef48dc8c710a73cb7e0f77b2c18a9b5a7adde60"; +let wordlist = null; +class LangEn extends WordlistOwl { + constructor(){ + super("en", words, checksum); } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger$8 = new Logger(version23); -function getTransactionPostData(transaction) { - const result = {}; - for(let key in transaction){ - if (transaction[key] == null) { - continue; - } - let value = transaction[key]; - if (key === "type" && value === 0) { - continue; - } - if (({ - type: true, - gasLimit: true, - gasPrice: true, - maxFeePerGs: true, - maxPriorityFeePerGas: true, - nonce: true, - value: true - })[key]) { - value = hexValue(hexlify(value)); - } else if (key === "accessList") { - value = "[" + accessListify(value).map((set)=>{ - return `{address:"${set.address}",storageKeys:["${set.storageKeys.join('","')}"]}`; - }).join(",") + "]"; - } else { - value = hexlify(value); + static wordlist() { + if (wordlist == null) { + wordlist = new LangEn; } - result[key] = value; + return wordlist; } - return result; } -function getResult$1(result) { - if (result.status == 0 && (result.message === "No records found" || result.message === "No transactions found")) { - return result.result; +function getUpperMask(bits) { + return (1 << bits) - 1 << 8 - bits & 255; +} +function getLowerMask(bits) { + return (1 << bits) - 1 & 255; +} +function mnemonicToEntropy(mnemonic, wordlist) { + assertNormalize("NFKD"); + if (wordlist == null) { + wordlist = LangEn.wordlist(); } - if (result.status != 1 || typeof result.message !== "string" || !result.message.match(/^OK/)) { - const error = new Error("invalid response"); - error.result = JSON.stringify(result); - if ((result.result || "").toLowerCase().indexOf("rate limit") >= 0) { - error.throttleRetry = true; + const words = wordlist.split(mnemonic); + assertArgument(words.length % 3 === 0 && words.length >= 12 && words.length <= 24, "invalid mnemonic length", "mnemonic", "[ REDACTED ]"); + const entropy = new Uint8Array(Math.ceil(11 * words.length / 8)); + let offset = 0; + for(let i = 0; i < words.length; i++){ + let index = wordlist.getWordIndex(words[i].normalize("NFKD")); + assertArgument(index >= 0, `invalid mnemonic word at index ${i}`, "mnemonic", "[ REDACTED ]"); + for(let bit = 0; bit < 11; bit++){ + if (index & 1 << 10 - bit) { + entropy[offset >> 3] |= 1 << 7 - offset % 8; + } + offset++; } - throw error; } - return result.result; + const entropyBits = 32 * words.length / 3; + const checksumBits = words.length / 3; + const checksumMask = getUpperMask(checksumBits); + const checksum = getBytes(sha256(entropy.slice(0, entropyBits / 8)))[0] & checksumMask; + assertArgument(checksum === (entropy[entropy.length - 1] & checksumMask), "invalid mnemonic checksum", "mnemonic", "[ REDACTED ]"); + return hexlify(entropy.slice(0, entropyBits / 8)); } -function getJsonResult(result) { - if (result && result.status == 0 && result.message == "NOTOK" && (result.result || "").toLowerCase().indexOf("rate limit") >= 0) { - const error = new Error("throttled response"); - error.result = JSON.stringify(result); - error.throttleRetry = true; - throw error; - } - if (result.jsonrpc != "2.0") { - const error = new Error("invalid response"); - error.result = JSON.stringify(result); - throw error; +function entropyToMnemonic(entropy, wordlist) { + assertArgument(entropy.length % 4 === 0 && entropy.length >= 16 && entropy.length <= 32, "invalid entropy size", "entropy", "[ REDACTED ]"); + if (wordlist == null) { + wordlist = LangEn.wordlist(); } - if (result.error) { - const error = new Error(result.error.message || "unknown error"); - if (result.error.code) { - error.code = result.error.code; - } - if (result.error.data) { - error.data = result.error.data; + const indices = [ + 0 + ]; + let remainingBits = 11; + for(let i = 0; i < entropy.length; i++){ + if (remainingBits > 8) { + indices[indices.length - 1] <<= 8; + indices[indices.length - 1] |= entropy[i]; + remainingBits -= 8; + } else { + indices[indices.length - 1] <<= remainingBits; + indices[indices.length - 1] |= entropy[i] >> 8 - remainingBits; + indices.push(entropy[i] & getLowerMask(8 - remainingBits)); + remainingBits += 3; } - throw error; } - return result.result; + const checksumBits = entropy.length / 4; + const checksum = parseInt(sha256(entropy).substring(2, 4), 16) & getUpperMask(checksumBits); + indices[indices.length - 1] <<= checksumBits; + indices[indices.length - 1] |= checksum >> 8 - checksumBits; + return wordlist.join(indices.map((index)=>wordlist.getWord(index))); } -function checkLogTag(blockTag) { - if (blockTag === "pending") { - throw new Error("pending not supported"); - } - if (blockTag === "latest") { - return blockTag; +const _guard$1 = {}; +class Mnemonic { + phrase; + password; + wordlist; + entropy; + constructor(guard, entropy, phrase, password, wordlist){ + if (password == null) { + password = ""; + } + if (wordlist == null) { + wordlist = LangEn.wordlist(); + } + assertPrivate(guard, _guard$1, "Mnemonic"); + defineProperties(this, { + phrase: phrase, + password: password, + wordlist: wordlist, + entropy: entropy + }); } - return parseInt(blockTag.substring(2), 16); -} -function checkError$1(method, error, transaction) { - if (method === "call" && error.code === Logger.errors.SERVER_ERROR) { - const e = error.error; - if (e && (e.message.match(/reverted/i) || e.message.match(/VM execution error/i))) { - let data = e.data; - if (data) { - data = "0x" + data.replace(/^.*0x/i, ""); - } - if (isHexString(data)) { - return data; - } - logger$8.throwError("missing revert data in call exception", Logger.errors.CALL_EXCEPTION, { - error, - data: "0x" - }); - } + computeSeed() { + const salt = toUtf8Bytes("mnemonic" + this.password, "NFKD"); + return pbkdf2(toUtf8Bytes(this.phrase, "NFKD"), salt, 2048, 64, "sha512"); } - let message = error.message; - if (error.code === Logger.errors.SERVER_ERROR) { - if (error.error && typeof error.error.message === "string") { - message = error.error.message; - } else if (typeof error.body === "string") { - message = error.body; - } else if (typeof error.responseText === "string") { - message = error.responseText; - } + static fromPhrase(phrase, password, wordlist) { + const entropy = mnemonicToEntropy(phrase, wordlist); + phrase = entropyToMnemonic(getBytes(entropy), wordlist); + return new Mnemonic(_guard$1, entropy, phrase, password, wordlist); } - message = (message || "").toLowerCase(); - if (message.match(/insufficient funds/)) { - logger$8.throwError("insufficient funds for intrinsic transaction cost", Logger.errors.INSUFFICIENT_FUNDS, { - error, - method, - transaction - }); + static fromEntropy(_entropy, password, wordlist) { + const entropy = getBytes(_entropy, "entropy"); + const phrase = entropyToMnemonic(entropy, wordlist); + return new Mnemonic(_guard$1, hexlify(entropy), phrase, password, wordlist); } - if (message.match(/same hash was already imported|transaction nonce is too low|nonce too low/)) { - logger$8.throwError("nonce has already been used", Logger.errors.NONCE_EXPIRED, { - error, - method, - transaction - }); + static entropyToPhrase(_entropy, wordlist) { + const entropy = getBytes(_entropy, "entropy"); + return entropyToMnemonic(entropy, wordlist); } - if (message.match(/another transaction with same nonce/)) { - logger$8.throwError("replacement fee too low", Logger.errors.REPLACEMENT_UNDERPRICED, { - error, - method, - transaction - }); + static phraseToEntropy(phrase, wordlist) { + return mnemonicToEntropy(phrase, wordlist); } - if (message.match(/execution failed due to an exception|execution reverted/)) { - logger$8.throwError("cannot estimate gas; transaction may fail or may require manual gas limit", Logger.errors.UNPREDICTABLE_GAS_LIMIT, { - error, - method, - transaction - }); + static isValidMnemonic(phrase, wordlist) { + try { + mnemonicToEntropy(phrase, wordlist); + return true; + } catch (error) {} + return false; } - throw error; } -class EtherscanProvider extends BaseProvider { - constructor(network, apiKey){ - super(network); - defineReadOnly(this, "baseUrl", this.getBaseUrl()); - defineReadOnly(this, "apiKey", apiKey || null); +var __classPrivateFieldGet$2 = __$G && __$G.__classPrivateFieldGet || function(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var __classPrivateFieldSet$2 = __$G && __$G.__classPrivateFieldSet || function(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +}; +var _AES_key, _AES_Kd, _AES_Ke; +const numberOfRounds = { + 16: 10, + 24: 12, + 32: 14 +}; +const rcon = [ + 1, + 2, + 4, + 8, + 16, + 32, + 64, + 128, + 27, + 54, + 108, + 216, + 171, + 77, + 154, + 47, + 94, + 188, + 99, + 198, + 151, + 53, + 106, + 212, + 179, + 125, + 250, + 239, + 197, + 145 +]; +const S = [ + 99, + 124, + 119, + 123, + 242, + 107, + 111, + 197, + 48, + 1, + 103, + 43, + 254, + 215, + 171, + 118, + 202, + 130, + 201, + 125, + 250, + 89, + 71, + 240, + 173, + 212, + 162, + 175, + 156, + 164, + 114, + 192, + 183, + 253, + 147, + 38, + 54, + 63, + 247, + 204, + 52, + 165, + 229, + 241, + 113, + 216, + 49, + 21, + 4, + 199, + 35, + 195, + 24, + 150, + 5, + 154, + 7, + 18, + 128, + 226, + 235, + 39, + 178, + 117, + 9, + 131, + 44, + 26, + 27, + 110, + 90, + 160, + 82, + 59, + 214, + 179, + 41, + 227, + 47, + 132, + 83, + 209, + 0, + 237, + 32, + 252, + 177, + 91, + 106, + 203, + 190, + 57, + 74, + 76, + 88, + 207, + 208, + 239, + 170, + 251, + 67, + 77, + 51, + 133, + 69, + 249, + 2, + 127, + 80, + 60, + 159, + 168, + 81, + 163, + 64, + 143, + 146, + 157, + 56, + 245, + 188, + 182, + 218, + 33, + 16, + 255, + 243, + 210, + 205, + 12, + 19, + 236, + 95, + 151, + 68, + 23, + 196, + 167, + 126, + 61, + 100, + 93, + 25, + 115, + 96, + 129, + 79, + 220, + 34, + 42, + 144, + 136, + 70, + 238, + 184, + 20, + 222, + 94, + 11, + 219, + 224, + 50, + 58, + 10, + 73, + 6, + 36, + 92, + 194, + 211, + 172, + 98, + 145, + 149, + 228, + 121, + 231, + 200, + 55, + 109, + 141, + 213, + 78, + 169, + 108, + 86, + 244, + 234, + 101, + 122, + 174, + 8, + 186, + 120, + 37, + 46, + 28, + 166, + 180, + 198, + 232, + 221, + 116, + 31, + 75, + 189, + 139, + 138, + 112, + 62, + 181, + 102, + 72, + 3, + 246, + 14, + 97, + 53, + 87, + 185, + 134, + 193, + 29, + 158, + 225, + 248, + 152, + 17, + 105, + 217, + 142, + 148, + 155, + 30, + 135, + 233, + 206, + 85, + 40, + 223, + 140, + 161, + 137, + 13, + 191, + 230, + 66, + 104, + 65, + 153, + 45, + 15, + 176, + 84, + 187, + 22 +]; +const Si = [ + 82, + 9, + 106, + 213, + 48, + 54, + 165, + 56, + 191, + 64, + 163, + 158, + 129, + 243, + 215, + 251, + 124, + 227, + 57, + 130, + 155, + 47, + 255, + 135, + 52, + 142, + 67, + 68, + 196, + 222, + 233, + 203, + 84, + 123, + 148, + 50, + 166, + 194, + 35, + 61, + 238, + 76, + 149, + 11, + 66, + 250, + 195, + 78, + 8, + 46, + 161, + 102, + 40, + 217, + 36, + 178, + 118, + 91, + 162, + 73, + 109, + 139, + 209, + 37, + 114, + 248, + 246, + 100, + 134, + 104, + 152, + 22, + 212, + 164, + 92, + 204, + 93, + 101, + 182, + 146, + 108, + 112, + 72, + 80, + 253, + 237, + 185, + 218, + 94, + 21, + 70, + 87, + 167, + 141, + 157, + 132, + 144, + 216, + 171, + 0, + 140, + 188, + 211, + 10, + 247, + 228, + 88, + 5, + 184, + 179, + 69, + 6, + 208, + 44, + 30, + 143, + 202, + 63, + 15, + 2, + 193, + 175, + 189, + 3, + 1, + 19, + 138, + 107, + 58, + 145, + 17, + 65, + 79, + 103, + 220, + 234, + 151, + 242, + 207, + 206, + 240, + 180, + 230, + 115, + 150, + 172, + 116, + 34, + 231, + 173, + 53, + 133, + 226, + 249, + 55, + 232, + 28, + 117, + 223, + 110, + 71, + 241, + 26, + 113, + 29, + 41, + 197, + 137, + 111, + 183, + 98, + 14, + 170, + 24, + 190, + 27, + 252, + 86, + 62, + 75, + 198, + 210, + 121, + 32, + 154, + 219, + 192, + 254, + 120, + 205, + 90, + 244, + 31, + 221, + 168, + 51, + 136, + 7, + 199, + 49, + 177, + 18, + 16, + 89, + 39, + 128, + 236, + 95, + 96, + 81, + 127, + 169, + 25, + 181, + 74, + 13, + 45, + 229, + 122, + 159, + 147, + 201, + 156, + 239, + 160, + 224, + 59, + 77, + 174, + 42, + 245, + 176, + 200, + 235, + 187, + 60, + 131, + 83, + 153, + 97, + 23, + 43, + 4, + 126, + 186, + 119, + 214, + 38, + 225, + 105, + 20, + 99, + 85, + 33, + 12, + 125 +]; +const T1 = [ + 3328402341, + 4168907908, + 4000806809, + 4135287693, + 4294111757, + 3597364157, + 3731845041, + 2445657428, + 1613770832, + 33620227, + 3462883241, + 1445669757, + 3892248089, + 3050821474, + 1303096294, + 3967186586, + 2412431941, + 528646813, + 2311702848, + 4202528135, + 4026202645, + 2992200171, + 2387036105, + 4226871307, + 1101901292, + 3017069671, + 1604494077, + 1169141738, + 597466303, + 1403299063, + 3832705686, + 2613100635, + 1974974402, + 3791519004, + 1033081774, + 1277568618, + 1815492186, + 2118074177, + 4126668546, + 2211236943, + 1748251740, + 1369810420, + 3521504564, + 4193382664, + 3799085459, + 2883115123, + 1647391059, + 706024767, + 134480908, + 2512897874, + 1176707941, + 2646852446, + 806885416, + 932615841, + 168101135, + 798661301, + 235341577, + 605164086, + 461406363, + 3756188221, + 3454790438, + 1311188841, + 2142417613, + 3933566367, + 302582043, + 495158174, + 1479289972, + 874125870, + 907746093, + 3698224818, + 3025820398, + 1537253627, + 2756858614, + 1983593293, + 3084310113, + 2108928974, + 1378429307, + 3722699582, + 1580150641, + 327451799, + 2790478837, + 3117535592, + 0, + 3253595436, + 1075847264, + 3825007647, + 2041688520, + 3059440621, + 3563743934, + 2378943302, + 1740553945, + 1916352843, + 2487896798, + 2555137236, + 2958579944, + 2244988746, + 3151024235, + 3320835882, + 1336584933, + 3992714006, + 2252555205, + 2588757463, + 1714631509, + 293963156, + 2319795663, + 3925473552, + 67240454, + 4269768577, + 2689618160, + 2017213508, + 631218106, + 1269344483, + 2723238387, + 1571005438, + 2151694528, + 93294474, + 1066570413, + 563977660, + 1882732616, + 4059428100, + 1673313503, + 2008463041, + 2950355573, + 1109467491, + 537923632, + 3858759450, + 4260623118, + 3218264685, + 2177748300, + 403442708, + 638784309, + 3287084079, + 3193921505, + 899127202, + 2286175436, + 773265209, + 2479146071, + 1437050866, + 4236148354, + 2050833735, + 3362022572, + 3126681063, + 840505643, + 3866325909, + 3227541664, + 427917720, + 2655997905, + 2749160575, + 1143087718, + 1412049534, + 999329963, + 193497219, + 2353415882, + 3354324521, + 1807268051, + 672404540, + 2816401017, + 3160301282, + 369822493, + 2916866934, + 3688947771, + 1681011286, + 1949973070, + 336202270, + 2454276571, + 201721354, + 1210328172, + 3093060836, + 2680341085, + 3184776046, + 1135389935, + 3294782118, + 965841320, + 831886756, + 3554993207, + 4068047243, + 3588745010, + 2345191491, + 1849112409, + 3664604599, + 26054028, + 2983581028, + 2622377682, + 1235855840, + 3630984372, + 2891339514, + 4092916743, + 3488279077, + 3395642799, + 4101667470, + 1202630377, + 268961816, + 1874508501, + 4034427016, + 1243948399, + 1546530418, + 941366308, + 1470539505, + 1941222599, + 2546386513, + 3421038627, + 2715671932, + 3899946140, + 1042226977, + 2521517021, + 1639824860, + 227249030, + 260737669, + 3765465232, + 2084453954, + 1907733956, + 3429263018, + 2420656344, + 100860677, + 4160157185, + 470683154, + 3261161891, + 1781871967, + 2924959737, + 1773779408, + 394692241, + 2579611992, + 974986535, + 664706745, + 3655459128, + 3958962195, + 731420851, + 571543859, + 3530123707, + 2849626480, + 126783113, + 865375399, + 765172662, + 1008606754, + 361203602, + 3387549984, + 2278477385, + 2857719295, + 1344809080, + 2782912378, + 59542671, + 1503764984, + 160008576, + 437062935, + 1707065306, + 3622233649, + 2218934982, + 3496503480, + 2185314755, + 697932208, + 1512910199, + 504303377, + 2075177163, + 2824099068, + 1841019862, + 739644986 +]; +const T2 = [ + 2781242211, + 2230877308, + 2582542199, + 2381740923, + 234877682, + 3184946027, + 2984144751, + 1418839493, + 1348481072, + 50462977, + 2848876391, + 2102799147, + 434634494, + 1656084439, + 3863849899, + 2599188086, + 1167051466, + 2636087938, + 1082771913, + 2281340285, + 368048890, + 3954334041, + 3381544775, + 201060592, + 3963727277, + 1739838676, + 4250903202, + 3930435503, + 3206782108, + 4149453988, + 2531553906, + 1536934080, + 3262494647, + 484572669, + 2923271059, + 1783375398, + 1517041206, + 1098792767, + 49674231, + 1334037708, + 1550332980, + 4098991525, + 886171109, + 150598129, + 2481090929, + 1940642008, + 1398944049, + 1059722517, + 201851908, + 1385547719, + 1699095331, + 1587397571, + 674240536, + 2704774806, + 252314885, + 3039795866, + 151914247, + 908333586, + 2602270848, + 1038082786, + 651029483, + 1766729511, + 3447698098, + 2682942837, + 454166793, + 2652734339, + 1951935532, + 775166490, + 758520603, + 3000790638, + 4004797018, + 4217086112, + 4137964114, + 1299594043, + 1639438038, + 3464344499, + 2068982057, + 1054729187, + 1901997871, + 2534638724, + 4121318227, + 1757008337, + 0, + 750906861, + 1614815264, + 535035132, + 3363418545, + 3988151131, + 3201591914, + 1183697867, + 3647454910, + 1265776953, + 3734260298, + 3566750796, + 3903871064, + 1250283471, + 1807470800, + 717615087, + 3847203498, + 384695291, + 3313910595, + 3617213773, + 1432761139, + 2484176261, + 3481945413, + 283769337, + 100925954, + 2180939647, + 4037038160, + 1148730428, + 3123027871, + 3813386408, + 4087501137, + 4267549603, + 3229630528, + 2315620239, + 2906624658, + 3156319645, + 1215313976, + 82966005, + 3747855548, + 3245848246, + 1974459098, + 1665278241, + 807407632, + 451280895, + 251524083, + 1841287890, + 1283575245, + 337120268, + 891687699, + 801369324, + 3787349855, + 2721421207, + 3431482436, + 959321879, + 1469301956, + 4065699751, + 2197585534, + 1199193405, + 2898814052, + 3887750493, + 724703513, + 2514908019, + 2696962144, + 2551808385, + 3516813135, + 2141445340, + 1715741218, + 2119445034, + 2872807568, + 2198571144, + 3398190662, + 700968686, + 3547052216, + 1009259540, + 2041044702, + 3803995742, + 487983883, + 1991105499, + 1004265696, + 1449407026, + 1316239930, + 504629770, + 3683797321, + 168560134, + 1816667172, + 3837287516, + 1570751170, + 1857934291, + 4014189740, + 2797888098, + 2822345105, + 2754712981, + 936633572, + 2347923833, + 852879335, + 1133234376, + 1500395319, + 3084545389, + 2348912013, + 1689376213, + 3533459022, + 3762923945, + 3034082412, + 4205598294, + 133428468, + 634383082, + 2949277029, + 2398386810, + 3913789102, + 403703816, + 3580869306, + 2297460856, + 1867130149, + 1918643758, + 607656988, + 4049053350, + 3346248884, + 1368901318, + 600565992, + 2090982877, + 2632479860, + 557719327, + 3717614411, + 3697393085, + 2249034635, + 2232388234, + 2430627952, + 1115438654, + 3295786421, + 2865522278, + 3633334344, + 84280067, + 33027830, + 303828494, + 2747425121, + 1600795957, + 4188952407, + 3496589753, + 2434238086, + 1486471617, + 658119965, + 3106381470, + 953803233, + 334231800, + 3005978776, + 857870609, + 3151128937, + 1890179545, + 2298973838, + 2805175444, + 3056442267, + 574365214, + 2450884487, + 550103529, + 1233637070, + 4289353045, + 2018519080, + 2057691103, + 2399374476, + 4166623649, + 2148108681, + 387583245, + 3664101311, + 836232934, + 3330556482, + 3100665960, + 3280093505, + 2955516313, + 2002398509, + 287182607, + 3413881008, + 4238890068, + 3597515707, + 975967766 +]; +const T3 = [ + 1671808611, + 2089089148, + 2006576759, + 2072901243, + 4061003762, + 1807603307, + 1873927791, + 3310653893, + 810573872, + 16974337, + 1739181671, + 729634347, + 4263110654, + 3613570519, + 2883997099, + 1989864566, + 3393556426, + 2191335298, + 3376449993, + 2106063485, + 4195741690, + 1508618841, + 1204391495, + 4027317232, + 2917941677, + 3563566036, + 2734514082, + 2951366063, + 2629772188, + 2767672228, + 1922491506, + 3227229120, + 3082974647, + 4246528509, + 2477669779, + 644500518, + 911895606, + 1061256767, + 4144166391, + 3427763148, + 878471220, + 2784252325, + 3845444069, + 4043897329, + 1905517169, + 3631459288, + 827548209, + 356461077, + 67897348, + 3344078279, + 593839651, + 3277757891, + 405286936, + 2527147926, + 84871685, + 2595565466, + 118033927, + 305538066, + 2157648768, + 3795705826, + 3945188843, + 661212711, + 2999812018, + 1973414517, + 152769033, + 2208177539, + 745822252, + 439235610, + 455947803, + 1857215598, + 1525593178, + 2700827552, + 1391895634, + 994932283, + 3596728278, + 3016654259, + 695947817, + 3812548067, + 795958831, + 2224493444, + 1408607827, + 3513301457, + 0, + 3979133421, + 543178784, + 4229948412, + 2982705585, + 1542305371, + 1790891114, + 3410398667, + 3201918910, + 961245753, + 1256100938, + 1289001036, + 1491644504, + 3477767631, + 3496721360, + 4012557807, + 2867154858, + 4212583931, + 1137018435, + 1305975373, + 861234739, + 2241073541, + 1171229253, + 4178635257, + 33948674, + 2139225727, + 1357946960, + 1011120188, + 2679776671, + 2833468328, + 1374921297, + 2751356323, + 1086357568, + 2408187279, + 2460827538, + 2646352285, + 944271416, + 4110742005, + 3168756668, + 3066132406, + 3665145818, + 560153121, + 271589392, + 4279952895, + 4077846003, + 3530407890, + 3444343245, + 202643468, + 322250259, + 3962553324, + 1608629855, + 2543990167, + 1154254916, + 389623319, + 3294073796, + 2817676711, + 2122513534, + 1028094525, + 1689045092, + 1575467613, + 422261273, + 1939203699, + 1621147744, + 2174228865, + 1339137615, + 3699352540, + 577127458, + 712922154, + 2427141008, + 2290289544, + 1187679302, + 3995715566, + 3100863416, + 339486740, + 3732514782, + 1591917662, + 186455563, + 3681988059, + 3762019296, + 844522546, + 978220090, + 169743370, + 1239126601, + 101321734, + 611076132, + 1558493276, + 3260915650, + 3547250131, + 2901361580, + 1655096418, + 2443721105, + 2510565781, + 3828863972, + 2039214713, + 3878868455, + 3359869896, + 928607799, + 1840765549, + 2374762893, + 3580146133, + 1322425422, + 2850048425, + 1823791212, + 1459268694, + 4094161908, + 3928346602, + 1706019429, + 2056189050, + 2934523822, + 135794696, + 3134549946, + 2022240376, + 628050469, + 779246638, + 472135708, + 2800834470, + 3032970164, + 3327236038, + 3894660072, + 3715932637, + 1956440180, + 522272287, + 1272813131, + 3185336765, + 2340818315, + 2323976074, + 1888542832, + 1044544574, + 3049550261, + 1722469478, + 1222152264, + 50660867, + 4127324150, + 236067854, + 1638122081, + 895445557, + 1475980887, + 3117443513, + 2257655686, + 3243809217, + 489110045, + 2662934430, + 3778599393, + 4162055160, + 2561878936, + 288563729, + 1773916777, + 3648039385, + 2391345038, + 2493985684, + 2612407707, + 505560094, + 2274497927, + 3911240169, + 3460925390, + 1442818645, + 678973480, + 3749357023, + 2358182796, + 2717407649, + 2306869641, + 219617805, + 3218761151, + 3862026214, + 1120306242, + 1756942440, + 1103331905, + 2578459033, + 762796589, + 252780047, + 2966125488, + 1425844308, + 3151392187, + 372911126 +]; +const T4 = [ + 1667474886, + 2088535288, + 2004326894, + 2071694838, + 4075949567, + 1802223062, + 1869591006, + 3318043793, + 808472672, + 16843522, + 1734846926, + 724270422, + 4278065639, + 3621216949, + 2880169549, + 1987484396, + 3402253711, + 2189597983, + 3385409673, + 2105378810, + 4210693615, + 1499065266, + 1195886990, + 4042263547, + 2913856577, + 3570689971, + 2728590687, + 2947541573, + 2627518243, + 2762274643, + 1920112356, + 3233831835, + 3082273397, + 4261223649, + 2475929149, + 640051788, + 909531756, + 1061110142, + 4160160501, + 3435941763, + 875846760, + 2779116625, + 3857003729, + 4059105529, + 1903268834, + 3638064043, + 825316194, + 353713962, + 67374088, + 3351728789, + 589522246, + 3284360861, + 404236336, + 2526454071, + 84217610, + 2593830191, + 117901582, + 303183396, + 2155911963, + 3806477791, + 3958056653, + 656894286, + 2998062463, + 1970642922, + 151591698, + 2206440989, + 741110872, + 437923380, + 454765878, + 1852748508, + 1515908788, + 2694904667, + 1381168804, + 993742198, + 3604373943, + 3014905469, + 690584402, + 3823320797, + 791638366, + 2223281939, + 1398011302, + 3520161977, + 0, + 3991743681, + 538992704, + 4244381667, + 2981218425, + 1532751286, + 1785380564, + 3419096717, + 3200178535, + 960056178, + 1246420628, + 1280103576, + 1482221744, + 3486468741, + 3503319995, + 4025428677, + 2863326543, + 4227536621, + 1128514950, + 1296947098, + 859002214, + 2240123921, + 1162203018, + 4193849577, + 33687044, + 2139062782, + 1347481760, + 1010582648, + 2678045221, + 2829640523, + 1364325282, + 2745433693, + 1077985408, + 2408548869, + 2459086143, + 2644360225, + 943212656, + 4126475505, + 3166494563, + 3065430391, + 3671750063, + 555836226, + 269496352, + 4294908645, + 4092792573, + 3537006015, + 3452783745, + 202118168, + 320025894, + 3974901699, + 1600119230, + 2543297077, + 1145359496, + 387397934, + 3301201811, + 2812801621, + 2122220284, + 1027426170, + 1684319432, + 1566435258, + 421079858, + 1936954854, + 1616945344, + 2172753945, + 1330631070, + 3705438115, + 572679748, + 707427924, + 2425400123, + 2290647819, + 1179044492, + 4008585671, + 3099120491, + 336870440, + 3739122087, + 1583276732, + 185277718, + 3688593069, + 3772791771, + 842159716, + 976899700, + 168435220, + 1229577106, + 101059084, + 606366792, + 1549591736, + 3267517855, + 3553849021, + 2897014595, + 1650632388, + 2442242105, + 2509612081, + 3840161747, + 2038008818, + 3890688725, + 3368567691, + 926374254, + 1835907034, + 2374863873, + 3587531953, + 1313788572, + 2846482505, + 1819063512, + 1448540844, + 4109633523, + 3941213647, + 1701162954, + 2054852340, + 2930698567, + 134748176, + 3132806511, + 2021165296, + 623210314, + 774795868, + 471606328, + 2795958615, + 3031746419, + 3334885783, + 3907527627, + 3722280097, + 1953799400, + 522133822, + 1263263126, + 3183336545, + 2341176845, + 2324333839, + 1886425312, + 1044267644, + 3048588401, + 1718004428, + 1212733584, + 50529542, + 4143317495, + 235803164, + 1633788866, + 892690282, + 1465383342, + 3115962473, + 2256965911, + 3250673817, + 488449850, + 2661202215, + 3789633753, + 4177007595, + 2560144171, + 286339874, + 1768537042, + 3654906025, + 2391705863, + 2492770099, + 2610673197, + 505291324, + 2273808917, + 3924369609, + 3469625735, + 1431699370, + 673740880, + 3755965093, + 2358021891, + 2711746649, + 2307489801, + 218961690, + 3217021541, + 3873845719, + 1111672452, + 1751693520, + 1094828930, + 2576986153, + 757954394, + 252645662, + 2964376443, + 1414855848, + 3149649517, + 370555436 +]; +const T5 = [ + 1374988112, + 2118214995, + 437757123, + 975658646, + 1001089995, + 530400753, + 2902087851, + 1273168787, + 540080725, + 2910219766, + 2295101073, + 4110568485, + 1340463100, + 3307916247, + 641025152, + 3043140495, + 3736164937, + 632953703, + 1172967064, + 1576976609, + 3274667266, + 2169303058, + 2370213795, + 1809054150, + 59727847, + 361929877, + 3211623147, + 2505202138, + 3569255213, + 1484005843, + 1239443753, + 2395588676, + 1975683434, + 4102977912, + 2572697195, + 666464733, + 3202437046, + 4035489047, + 3374361702, + 2110667444, + 1675577880, + 3843699074, + 2538681184, + 1649639237, + 2976151520, + 3144396420, + 4269907996, + 4178062228, + 1883793496, + 2403728665, + 2497604743, + 1383856311, + 2876494627, + 1917518562, + 3810496343, + 1716890410, + 3001755655, + 800440835, + 2261089178, + 3543599269, + 807962610, + 599762354, + 33778362, + 3977675356, + 2328828971, + 2809771154, + 4077384432, + 1315562145, + 1708848333, + 101039829, + 3509871135, + 3299278474, + 875451293, + 2733856160, + 92987698, + 2767645557, + 193195065, + 1080094634, + 1584504582, + 3178106961, + 1042385657, + 2531067453, + 3711829422, + 1306967366, + 2438237621, + 1908694277, + 67556463, + 1615861247, + 429456164, + 3602770327, + 2302690252, + 1742315127, + 2968011453, + 126454664, + 3877198648, + 2043211483, + 2709260871, + 2084704233, + 4169408201, + 0, + 159417987, + 841739592, + 504459436, + 1817866830, + 4245618683, + 260388950, + 1034867998, + 908933415, + 168810852, + 1750902305, + 2606453969, + 607530554, + 202008497, + 2472011535, + 3035535058, + 463180190, + 2160117071, + 1641816226, + 1517767529, + 470948374, + 3801332234, + 3231722213, + 1008918595, + 303765277, + 235474187, + 4069246893, + 766945465, + 337553864, + 1475418501, + 2943682380, + 4003061179, + 2743034109, + 4144047775, + 1551037884, + 1147550661, + 1543208500, + 2336434550, + 3408119516, + 3069049960, + 3102011747, + 3610369226, + 1113818384, + 328671808, + 2227573024, + 2236228733, + 3535486456, + 2935566865, + 3341394285, + 496906059, + 3702665459, + 226906860, + 2009195472, + 733156972, + 2842737049, + 294930682, + 1206477858, + 2835123396, + 2700099354, + 1451044056, + 573804783, + 2269728455, + 3644379585, + 2362090238, + 2564033334, + 2801107407, + 2776292904, + 3669462566, + 1068351396, + 742039012, + 1350078989, + 1784663195, + 1417561698, + 4136440770, + 2430122216, + 775550814, + 2193862645, + 2673705150, + 1775276924, + 1876241833, + 3475313331, + 3366754619, + 270040487, + 3902563182, + 3678124923, + 3441850377, + 1851332852, + 3969562369, + 2203032232, + 3868552805, + 2868897406, + 566021896, + 4011190502, + 3135740889, + 1248802510, + 3936291284, + 699432150, + 832877231, + 708780849, + 3332740144, + 899835584, + 1951317047, + 4236429990, + 3767586992, + 866637845, + 4043610186, + 1106041591, + 2144161806, + 395441711, + 1984812685, + 1139781709, + 3433712980, + 3835036895, + 2664543715, + 1282050075, + 3240894392, + 1181045119, + 2640243204, + 25965917, + 4203181171, + 4211818798, + 3009879386, + 2463879762, + 3910161971, + 1842759443, + 2597806476, + 933301370, + 1509430414, + 3943906441, + 3467192302, + 3076639029, + 3776767469, + 2051518780, + 2631065433, + 1441952575, + 404016761, + 1942435775, + 1408749034, + 1610459739, + 3745345300, + 2017778566, + 3400528769, + 3110650942, + 941896748, + 3265478751, + 371049330, + 3168937228, + 675039627, + 4279080257, + 967311729, + 135050206, + 3635733660, + 1683407248, + 2076935265, + 3576870512, + 1215061108, + 3501741890 +]; +const T6 = [ + 1347548327, + 1400783205, + 3273267108, + 2520393566, + 3409685355, + 4045380933, + 2880240216, + 2471224067, + 1428173050, + 4138563181, + 2441661558, + 636813900, + 4233094615, + 3620022987, + 2149987652, + 2411029155, + 1239331162, + 1730525723, + 2554718734, + 3781033664, + 46346101, + 310463728, + 2743944855, + 3328955385, + 3875770207, + 2501218972, + 3955191162, + 3667219033, + 768917123, + 3545789473, + 692707433, + 1150208456, + 1786102409, + 2029293177, + 1805211710, + 3710368113, + 3065962831, + 401639597, + 1724457132, + 3028143674, + 409198410, + 2196052529, + 1620529459, + 1164071807, + 3769721975, + 2226875310, + 486441376, + 2499348523, + 1483753576, + 428819965, + 2274680428, + 3075636216, + 598438867, + 3799141122, + 1474502543, + 711349675, + 129166120, + 53458370, + 2592523643, + 2782082824, + 4063242375, + 2988687269, + 3120694122, + 1559041666, + 730517276, + 2460449204, + 4042459122, + 2706270690, + 3446004468, + 3573941694, + 533804130, + 2328143614, + 2637442643, + 2695033685, + 839224033, + 1973745387, + 957055980, + 2856345839, + 106852767, + 1371368976, + 4181598602, + 1033297158, + 2933734917, + 1179510461, + 3046200461, + 91341917, + 1862534868, + 4284502037, + 605657339, + 2547432937, + 3431546947, + 2003294622, + 3182487618, + 2282195339, + 954669403, + 3682191598, + 1201765386, + 3917234703, + 3388507166, + 0, + 2198438022, + 1211247597, + 2887651696, + 1315723890, + 4227665663, + 1443857720, + 507358933, + 657861945, + 1678381017, + 560487590, + 3516619604, + 975451694, + 2970356327, + 261314535, + 3535072918, + 2652609425, + 1333838021, + 2724322336, + 1767536459, + 370938394, + 182621114, + 3854606378, + 1128014560, + 487725847, + 185469197, + 2918353863, + 3106780840, + 3356761769, + 2237133081, + 1286567175, + 3152976349, + 4255350624, + 2683765030, + 3160175349, + 3309594171, + 878443390, + 1988838185, + 3704300486, + 1756818940, + 1673061617, + 3403100636, + 272786309, + 1075025698, + 545572369, + 2105887268, + 4174560061, + 296679730, + 1841768865, + 1260232239, + 4091327024, + 3960309330, + 3497509347, + 1814803222, + 2578018489, + 4195456072, + 575138148, + 3299409036, + 446754879, + 3629546796, + 4011996048, + 3347532110, + 3252238545, + 4270639778, + 915985419, + 3483825537, + 681933534, + 651868046, + 2755636671, + 3828103837, + 223377554, + 2607439820, + 1649704518, + 3270937875, + 3901806776, + 1580087799, + 4118987695, + 3198115200, + 2087309459, + 2842678573, + 3016697106, + 1003007129, + 2802849917, + 1860738147, + 2077965243, + 164439672, + 4100872472, + 32283319, + 2827177882, + 1709610350, + 2125135846, + 136428751, + 3874428392, + 3652904859, + 3460984630, + 3572145929, + 3593056380, + 2939266226, + 824852259, + 818324884, + 3224740454, + 930369212, + 2801566410, + 2967507152, + 355706840, + 1257309336, + 4148292826, + 243256656, + 790073846, + 2373340630, + 1296297904, + 1422699085, + 3756299780, + 3818836405, + 457992840, + 3099667487, + 2135319889, + 77422314, + 1560382517, + 1945798516, + 788204353, + 1521706781, + 1385356242, + 870912086, + 325965383, + 2358957921, + 2050466060, + 2388260884, + 2313884476, + 4006521127, + 901210569, + 3990953189, + 1014646705, + 1503449823, + 1062597235, + 2031621326, + 3212035895, + 3931371469, + 1533017514, + 350174575, + 2256028891, + 2177544179, + 1052338372, + 741876788, + 1606591296, + 1914052035, + 213705253, + 2334669897, + 1107234197, + 1899603969, + 3725069491, + 2631447780, + 2422494913, + 1635502980, + 1893020342, + 1950903388, + 1120974935 +]; +const T7 = [ + 2807058932, + 1699970625, + 2764249623, + 1586903591, + 1808481195, + 1173430173, + 1487645946, + 59984867, + 4199882800, + 1844882806, + 1989249228, + 1277555970, + 3623636965, + 3419915562, + 1149249077, + 2744104290, + 1514790577, + 459744698, + 244860394, + 3235995134, + 1963115311, + 4027744588, + 2544078150, + 4190530515, + 1608975247, + 2627016082, + 2062270317, + 1507497298, + 2200818878, + 567498868, + 1764313568, + 3359936201, + 2305455554, + 2037970062, + 1047239e3, + 1910319033, + 1337376481, + 2904027272, + 2892417312, + 984907214, + 1243112415, + 830661914, + 861968209, + 2135253587, + 2011214180, + 2927934315, + 2686254721, + 731183368, + 1750626376, + 4246310725, + 1820824798, + 4172763771, + 3542330227, + 48394827, + 2404901663, + 2871682645, + 671593195, + 3254988725, + 2073724613, + 145085239, + 2280796200, + 2779915199, + 1790575107, + 2187128086, + 472615631, + 3029510009, + 4075877127, + 3802222185, + 4107101658, + 3201631749, + 1646252340, + 4270507174, + 1402811438, + 1436590835, + 3778151818, + 3950355702, + 3963161475, + 4020912224, + 2667994737, + 273792366, + 2331590177, + 104699613, + 95345982, + 3175501286, + 2377486676, + 1560637892, + 3564045318, + 369057872, + 4213447064, + 3919042237, + 1137477952, + 2658625497, + 1119727848, + 2340947849, + 1530455833, + 4007360968, + 172466556, + 266959938, + 516552836, + 0, + 2256734592, + 3980931627, + 1890328081, + 1917742170, + 4294704398, + 945164165, + 3575528878, + 958871085, + 3647212047, + 2787207260, + 1423022939, + 775562294, + 1739656202, + 3876557655, + 2530391278, + 2443058075, + 3310321856, + 547512796, + 1265195639, + 437656594, + 3121275539, + 719700128, + 3762502690, + 387781147, + 218828297, + 3350065803, + 2830708150, + 2848461854, + 428169201, + 122466165, + 3720081049, + 1627235199, + 648017665, + 4122762354, + 1002783846, + 2117360635, + 695634755, + 3336358691, + 4234721005, + 4049844452, + 3704280881, + 2232435299, + 574624663, + 287343814, + 612205898, + 1039717051, + 840019705, + 2708326185, + 793451934, + 821288114, + 1391201670, + 3822090177, + 376187827, + 3113855344, + 1224348052, + 1679968233, + 2361698556, + 1058709744, + 752375421, + 2431590963, + 1321699145, + 3519142200, + 2734591178, + 188127444, + 2177869557, + 3727205754, + 2384911031, + 3215212461, + 2648976442, + 2450346104, + 3432737375, + 1180849278, + 331544205, + 3102249176, + 4150144569, + 2952102595, + 2159976285, + 2474404304, + 766078933, + 313773861, + 2570832044, + 2108100632, + 1668212892, + 3145456443, + 2013908262, + 418672217, + 3070356634, + 2594734927, + 1852171925, + 3867060991, + 3473416636, + 3907448597, + 2614737639, + 919489135, + 164948639, + 2094410160, + 2997825956, + 590424639, + 2486224549, + 1723872674, + 3157750862, + 3399941250, + 3501252752, + 3625268135, + 2555048196, + 3673637356, + 1343127501, + 4130281361, + 3599595085, + 2957853679, + 1297403050, + 81781910, + 3051593425, + 2283490410, + 532201772, + 1367295589, + 3926170974, + 895287692, + 1953757831, + 1093597963, + 492483431, + 3528626907, + 1446242576, + 1192455638, + 1636604631, + 209336225, + 344873464, + 1015671571, + 669961897, + 3375740769, + 3857572124, + 2973530695, + 3747192018, + 1933530610, + 3464042516, + 935293895, + 3454686199, + 2858115069, + 1863638845, + 3683022916, + 4085369519, + 3292445032, + 875313188, + 1080017571, + 3279033885, + 621591778, + 1233856572, + 2504130317, + 24197544, + 3017672716, + 3835484340, + 3247465558, + 2220981195, + 3060847922, + 1551124588, + 1463996600 +]; +const T8 = [ + 4104605777, + 1097159550, + 396673818, + 660510266, + 2875968315, + 2638606623, + 4200115116, + 3808662347, + 821712160, + 1986918061, + 3430322568, + 38544885, + 3856137295, + 718002117, + 893681702, + 1654886325, + 2975484382, + 3122358053, + 3926825029, + 4274053469, + 796197571, + 1290801793, + 1184342925, + 3556361835, + 2405426947, + 2459735317, + 1836772287, + 1381620373, + 3196267988, + 1948373848, + 3764988233, + 3385345166, + 3263785589, + 2390325492, + 1480485785, + 3111247143, + 3780097726, + 2293045232, + 548169417, + 3459953789, + 3746175075, + 439452389, + 1362321559, + 1400849762, + 1685577905, + 1806599355, + 2174754046, + 137073913, + 1214797936, + 1174215055, + 3731654548, + 2079897426, + 1943217067, + 1258480242, + 529487843, + 1437280870, + 3945269170, + 3049390895, + 3313212038, + 923313619, + 679998e3, + 3215307299, + 57326082, + 377642221, + 3474729866, + 2041877159, + 133361907, + 1776460110, + 3673476453, + 96392454, + 878845905, + 2801699524, + 777231668, + 4082475170, + 2330014213, + 4142626212, + 2213296395, + 1626319424, + 1906247262, + 1846563261, + 562755902, + 3708173718, + 1040559837, + 3871163981, + 1418573201, + 3294430577, + 114585348, + 1343618912, + 2566595609, + 3186202582, + 1078185097, + 3651041127, + 3896688048, + 2307622919, + 425408743, + 3371096953, + 2081048481, + 1108339068, + 2216610296, + 0, + 2156299017, + 736970802, + 292596766, + 1517440620, + 251657213, + 2235061775, + 2933202493, + 758720310, + 265905162, + 1554391400, + 1532285339, + 908999204, + 174567692, + 1474760595, + 4002861748, + 2610011675, + 3234156416, + 3693126241, + 2001430874, + 303699484, + 2478443234, + 2687165888, + 585122620, + 454499602, + 151849742, + 2345119218, + 3064510765, + 514443284, + 4044981591, + 1963412655, + 2581445614, + 2137062819, + 19308535, + 1928707164, + 1715193156, + 4219352155, + 1126790795, + 600235211, + 3992742070, + 3841024952, + 836553431, + 1669664834, + 2535604243, + 3323011204, + 1243905413, + 3141400786, + 4180808110, + 698445255, + 2653899549, + 2989552604, + 2253581325, + 3252932727, + 3004591147, + 1891211689, + 2487810577, + 3915653703, + 4237083816, + 4030667424, + 2100090966, + 865136418, + 1229899655, + 953270745, + 3399679628, + 3557504664, + 4118925222, + 2061379749, + 3079546586, + 2915017791, + 983426092, + 2022837584, + 1607244650, + 2118541908, + 2366882550, + 3635996816, + 972512814, + 3283088770, + 1568718495, + 3499326569, + 3576539503, + 621982671, + 2895723464, + 410887952, + 2623762152, + 1002142683, + 645401037, + 1494807662, + 2595684844, + 1335535747, + 2507040230, + 4293295786, + 3167684641, + 367585007, + 3885750714, + 1865862730, + 2668221674, + 2960971305, + 2763173681, + 1059270954, + 2777952454, + 2724642869, + 1320957812, + 2194319100, + 2429595872, + 2815956275, + 77089521, + 3973773121, + 3444575871, + 2448830231, + 1305906550, + 4021308739, + 2857194700, + 2516901860, + 3518358430, + 1787304780, + 740276417, + 1699839814, + 1592394909, + 2352307457, + 2272556026, + 188821243, + 1729977011, + 3687994002, + 274084841, + 3594982253, + 3613494426, + 2701949495, + 4162096729, + 322734571, + 2837966542, + 1640576439, + 484830689, + 1202797690, + 3537852828, + 4067639125, + 349075736, + 3342319475, + 4157467219, + 4255800159, + 1030690015, + 1155237496, + 2951971274, + 1757691577, + 607398968, + 2738905026, + 499347990, + 3794078908, + 1011452712, + 227885567, + 2818666809, + 213114376, + 3034881240, + 1455525988, + 3414450555, + 850817237, + 1817998408, + 3092726480 +]; +const U1 = [ + 0, + 235474187, + 470948374, + 303765277, + 941896748, + 908933415, + 607530554, + 708780849, + 1883793496, + 2118214995, + 1817866830, + 1649639237, + 1215061108, + 1181045119, + 1417561698, + 1517767529, + 3767586992, + 4003061179, + 4236429990, + 4069246893, + 3635733660, + 3602770327, + 3299278474, + 3400528769, + 2430122216, + 2664543715, + 2362090238, + 2193862645, + 2835123396, + 2801107407, + 3035535058, + 3135740889, + 3678124923, + 3576870512, + 3341394285, + 3374361702, + 3810496343, + 3977675356, + 4279080257, + 4043610186, + 2876494627, + 2776292904, + 3076639029, + 3110650942, + 2472011535, + 2640243204, + 2403728665, + 2169303058, + 1001089995, + 899835584, + 666464733, + 699432150, + 59727847, + 226906860, + 530400753, + 294930682, + 1273168787, + 1172967064, + 1475418501, + 1509430414, + 1942435775, + 2110667444, + 1876241833, + 1641816226, + 2910219766, + 2743034109, + 2976151520, + 3211623147, + 2505202138, + 2606453969, + 2302690252, + 2269728455, + 3711829422, + 3543599269, + 3240894392, + 3475313331, + 3843699074, + 3943906441, + 4178062228, + 4144047775, + 1306967366, + 1139781709, + 1374988112, + 1610459739, + 1975683434, + 2076935265, + 1775276924, + 1742315127, + 1034867998, + 866637845, + 566021896, + 800440835, + 92987698, + 193195065, + 429456164, + 395441711, + 1984812685, + 2017778566, + 1784663195, + 1683407248, + 1315562145, + 1080094634, + 1383856311, + 1551037884, + 101039829, + 135050206, + 437757123, + 337553864, + 1042385657, + 807962610, + 573804783, + 742039012, + 2531067453, + 2564033334, + 2328828971, + 2227573024, + 2935566865, + 2700099354, + 3001755655, + 3168937228, + 3868552805, + 3902563182, + 4203181171, + 4102977912, + 3736164937, + 3501741890, + 3265478751, + 3433712980, + 1106041591, + 1340463100, + 1576976609, + 1408749034, + 2043211483, + 2009195472, + 1708848333, + 1809054150, + 832877231, + 1068351396, + 766945465, + 599762354, + 159417987, + 126454664, + 361929877, + 463180190, + 2709260871, + 2943682380, + 3178106961, + 3009879386, + 2572697195, + 2538681184, + 2236228733, + 2336434550, + 3509871135, + 3745345300, + 3441850377, + 3274667266, + 3910161971, + 3877198648, + 4110568485, + 4211818798, + 2597806476, + 2497604743, + 2261089178, + 2295101073, + 2733856160, + 2902087851, + 3202437046, + 2968011453, + 3936291284, + 3835036895, + 4136440770, + 4169408201, + 3535486456, + 3702665459, + 3467192302, + 3231722213, + 2051518780, + 1951317047, + 1716890410, + 1750902305, + 1113818384, + 1282050075, + 1584504582, + 1350078989, + 168810852, + 67556463, + 371049330, + 404016761, + 841739592, + 1008918595, + 775550814, + 540080725, + 3969562369, + 3801332234, + 4035489047, + 4269907996, + 3569255213, + 3669462566, + 3366754619, + 3332740144, + 2631065433, + 2463879762, + 2160117071, + 2395588676, + 2767645557, + 2868897406, + 3102011747, + 3069049960, + 202008497, + 33778362, + 270040487, + 504459436, + 875451293, + 975658646, + 675039627, + 641025152, + 2084704233, + 1917518562, + 1615861247, + 1851332852, + 1147550661, + 1248802510, + 1484005843, + 1451044056, + 933301370, + 967311729, + 733156972, + 632953703, + 260388950, + 25965917, + 328671808, + 496906059, + 1206477858, + 1239443753, + 1543208500, + 1441952575, + 2144161806, + 1908694277, + 1675577880, + 1842759443, + 3610369226, + 3644379585, + 3408119516, + 3307916247, + 4011190502, + 3776767469, + 4077384432, + 4245618683, + 2809771154, + 2842737049, + 3144396420, + 3043140495, + 2673705150, + 2438237621, + 2203032232, + 2370213795 +]; +const U2 = [ + 0, + 185469197, + 370938394, + 487725847, + 741876788, + 657861945, + 975451694, + 824852259, + 1483753576, + 1400783205, + 1315723890, + 1164071807, + 1950903388, + 2135319889, + 1649704518, + 1767536459, + 2967507152, + 3152976349, + 2801566410, + 2918353863, + 2631447780, + 2547432937, + 2328143614, + 2177544179, + 3901806776, + 3818836405, + 4270639778, + 4118987695, + 3299409036, + 3483825537, + 3535072918, + 3652904859, + 2077965243, + 1893020342, + 1841768865, + 1724457132, + 1474502543, + 1559041666, + 1107234197, + 1257309336, + 598438867, + 681933534, + 901210569, + 1052338372, + 261314535, + 77422314, + 428819965, + 310463728, + 3409685355, + 3224740454, + 3710368113, + 3593056380, + 3875770207, + 3960309330, + 4045380933, + 4195456072, + 2471224067, + 2554718734, + 2237133081, + 2388260884, + 3212035895, + 3028143674, + 2842678573, + 2724322336, + 4138563181, + 4255350624, + 3769721975, + 3955191162, + 3667219033, + 3516619604, + 3431546947, + 3347532110, + 2933734917, + 2782082824, + 3099667487, + 3016697106, + 2196052529, + 2313884476, + 2499348523, + 2683765030, + 1179510461, + 1296297904, + 1347548327, + 1533017514, + 1786102409, + 1635502980, + 2087309459, + 2003294622, + 507358933, + 355706840, + 136428751, + 53458370, + 839224033, + 957055980, + 605657339, + 790073846, + 2373340630, + 2256028891, + 2607439820, + 2422494913, + 2706270690, + 2856345839, + 3075636216, + 3160175349, + 3573941694, + 3725069491, + 3273267108, + 3356761769, + 4181598602, + 4063242375, + 4011996048, + 3828103837, + 1033297158, + 915985419, + 730517276, + 545572369, + 296679730, + 446754879, + 129166120, + 213705253, + 1709610350, + 1860738147, + 1945798516, + 2029293177, + 1239331162, + 1120974935, + 1606591296, + 1422699085, + 4148292826, + 4233094615, + 3781033664, + 3931371469, + 3682191598, + 3497509347, + 3446004468, + 3328955385, + 2939266226, + 2755636671, + 3106780840, + 2988687269, + 2198438022, + 2282195339, + 2501218972, + 2652609425, + 1201765386, + 1286567175, + 1371368976, + 1521706781, + 1805211710, + 1620529459, + 2105887268, + 1988838185, + 533804130, + 350174575, + 164439672, + 46346101, + 870912086, + 954669403, + 636813900, + 788204353, + 2358957921, + 2274680428, + 2592523643, + 2441661558, + 2695033685, + 2880240216, + 3065962831, + 3182487618, + 3572145929, + 3756299780, + 3270937875, + 3388507166, + 4174560061, + 4091327024, + 4006521127, + 3854606378, + 1014646705, + 930369212, + 711349675, + 560487590, + 272786309, + 457992840, + 106852767, + 223377554, + 1678381017, + 1862534868, + 1914052035, + 2031621326, + 1211247597, + 1128014560, + 1580087799, + 1428173050, + 32283319, + 182621114, + 401639597, + 486441376, + 768917123, + 651868046, + 1003007129, + 818324884, + 1503449823, + 1385356242, + 1333838021, + 1150208456, + 1973745387, + 2125135846, + 1673061617, + 1756818940, + 2970356327, + 3120694122, + 2802849917, + 2887651696, + 2637442643, + 2520393566, + 2334669897, + 2149987652, + 3917234703, + 3799141122, + 4284502037, + 4100872472, + 3309594171, + 3460984630, + 3545789473, + 3629546796, + 2050466060, + 1899603969, + 1814803222, + 1730525723, + 1443857720, + 1560382517, + 1075025698, + 1260232239, + 575138148, + 692707433, + 878443390, + 1062597235, + 243256656, + 91341917, + 409198410, + 325965383, + 3403100636, + 3252238545, + 3704300486, + 3620022987, + 3874428392, + 3990953189, + 4042459122, + 4227665663, + 2460449204, + 2578018489, + 2226875310, + 2411029155, + 3198115200, + 3046200461, + 2827177882, + 2743944855 +]; +const U3 = [ + 0, + 218828297, + 437656594, + 387781147, + 875313188, + 958871085, + 775562294, + 590424639, + 1750626376, + 1699970625, + 1917742170, + 2135253587, + 1551124588, + 1367295589, + 1180849278, + 1265195639, + 3501252752, + 3720081049, + 3399941250, + 3350065803, + 3835484340, + 3919042237, + 4270507174, + 4085369519, + 3102249176, + 3051593425, + 2734591178, + 2952102595, + 2361698556, + 2177869557, + 2530391278, + 2614737639, + 3145456443, + 3060847922, + 2708326185, + 2892417312, + 2404901663, + 2187128086, + 2504130317, + 2555048196, + 3542330227, + 3727205754, + 3375740769, + 3292445032, + 3876557655, + 3926170974, + 4246310725, + 4027744588, + 1808481195, + 1723872674, + 1910319033, + 2094410160, + 1608975247, + 1391201670, + 1173430173, + 1224348052, + 59984867, + 244860394, + 428169201, + 344873464, + 935293895, + 984907214, + 766078933, + 547512796, + 1844882806, + 1627235199, + 2011214180, + 2062270317, + 1507497298, + 1423022939, + 1137477952, + 1321699145, + 95345982, + 145085239, + 532201772, + 313773861, + 830661914, + 1015671571, + 731183368, + 648017665, + 3175501286, + 2957853679, + 2807058932, + 2858115069, + 2305455554, + 2220981195, + 2474404304, + 2658625497, + 3575528878, + 3625268135, + 3473416636, + 3254988725, + 3778151818, + 3963161475, + 4213447064, + 4130281361, + 3599595085, + 3683022916, + 3432737375, + 3247465558, + 3802222185, + 4020912224, + 4172763771, + 4122762354, + 3201631749, + 3017672716, + 2764249623, + 2848461854, + 2331590177, + 2280796200, + 2431590963, + 2648976442, + 104699613, + 188127444, + 472615631, + 287343814, + 840019705, + 1058709744, + 671593195, + 621591778, + 1852171925, + 1668212892, + 1953757831, + 2037970062, + 1514790577, + 1463996600, + 1080017571, + 1297403050, + 3673637356, + 3623636965, + 3235995134, + 3454686199, + 4007360968, + 3822090177, + 4107101658, + 4190530515, + 2997825956, + 3215212461, + 2830708150, + 2779915199, + 2256734592, + 2340947849, + 2627016082, + 2443058075, + 172466556, + 122466165, + 273792366, + 492483431, + 1047239e3, + 861968209, + 612205898, + 695634755, + 1646252340, + 1863638845, + 2013908262, + 1963115311, + 1446242576, + 1530455833, + 1277555970, + 1093597963, + 1636604631, + 1820824798, + 2073724613, + 1989249228, + 1436590835, + 1487645946, + 1337376481, + 1119727848, + 164948639, + 81781910, + 331544205, + 516552836, + 1039717051, + 821288114, + 669961897, + 719700128, + 2973530695, + 3157750862, + 2871682645, + 2787207260, + 2232435299, + 2283490410, + 2667994737, + 2450346104, + 3647212047, + 3564045318, + 3279033885, + 3464042516, + 3980931627, + 3762502690, + 4150144569, + 4199882800, + 3070356634, + 3121275539, + 2904027272, + 2686254721, + 2200818878, + 2384911031, + 2570832044, + 2486224549, + 3747192018, + 3528626907, + 3310321856, + 3359936201, + 3950355702, + 3867060991, + 4049844452, + 4234721005, + 1739656202, + 1790575107, + 2108100632, + 1890328081, + 1402811438, + 1586903591, + 1233856572, + 1149249077, + 266959938, + 48394827, + 369057872, + 418672217, + 1002783846, + 919489135, + 567498868, + 752375421, + 209336225, + 24197544, + 376187827, + 459744698, + 945164165, + 895287692, + 574624663, + 793451934, + 1679968233, + 1764313568, + 2117360635, + 1933530610, + 1343127501, + 1560637892, + 1243112415, + 1192455638, + 3704280881, + 3519142200, + 3336358691, + 3419915562, + 3907448597, + 3857572124, + 4075877127, + 4294704398, + 3029510009, + 3113855344, + 2927934315, + 2744104290, + 2159976285, + 2377486676, + 2594734927, + 2544078150 +]; +const U4 = [ + 0, + 151849742, + 303699484, + 454499602, + 607398968, + 758720310, + 908999204, + 1059270954, + 1214797936, + 1097159550, + 1517440620, + 1400849762, + 1817998408, + 1699839814, + 2118541908, + 2001430874, + 2429595872, + 2581445614, + 2194319100, + 2345119218, + 3034881240, + 3186202582, + 2801699524, + 2951971274, + 3635996816, + 3518358430, + 3399679628, + 3283088770, + 4237083816, + 4118925222, + 4002861748, + 3885750714, + 1002142683, + 850817237, + 698445255, + 548169417, + 529487843, + 377642221, + 227885567, + 77089521, + 1943217067, + 2061379749, + 1640576439, + 1757691577, + 1474760595, + 1592394909, + 1174215055, + 1290801793, + 2875968315, + 2724642869, + 3111247143, + 2960971305, + 2405426947, + 2253581325, + 2638606623, + 2487810577, + 3808662347, + 3926825029, + 4044981591, + 4162096729, + 3342319475, + 3459953789, + 3576539503, + 3693126241, + 1986918061, + 2137062819, + 1685577905, + 1836772287, + 1381620373, + 1532285339, + 1078185097, + 1229899655, + 1040559837, + 923313619, + 740276417, + 621982671, + 439452389, + 322734571, + 137073913, + 19308535, + 3871163981, + 4021308739, + 4104605777, + 4255800159, + 3263785589, + 3414450555, + 3499326569, + 3651041127, + 2933202493, + 2815956275, + 3167684641, + 3049390895, + 2330014213, + 2213296395, + 2566595609, + 2448830231, + 1305906550, + 1155237496, + 1607244650, + 1455525988, + 1776460110, + 1626319424, + 2079897426, + 1928707164, + 96392454, + 213114376, + 396673818, + 514443284, + 562755902, + 679998e3, + 865136418, + 983426092, + 3708173718, + 3557504664, + 3474729866, + 3323011204, + 4180808110, + 4030667424, + 3945269170, + 3794078908, + 2507040230, + 2623762152, + 2272556026, + 2390325492, + 2975484382, + 3092726480, + 2738905026, + 2857194700, + 3973773121, + 3856137295, + 4274053469, + 4157467219, + 3371096953, + 3252932727, + 3673476453, + 3556361835, + 2763173681, + 2915017791, + 3064510765, + 3215307299, + 2156299017, + 2307622919, + 2459735317, + 2610011675, + 2081048481, + 1963412655, + 1846563261, + 1729977011, + 1480485785, + 1362321559, + 1243905413, + 1126790795, + 878845905, + 1030690015, + 645401037, + 796197571, + 274084841, + 425408743, + 38544885, + 188821243, + 3613494426, + 3731654548, + 3313212038, + 3430322568, + 4082475170, + 4200115116, + 3780097726, + 3896688048, + 2668221674, + 2516901860, + 2366882550, + 2216610296, + 3141400786, + 2989552604, + 2837966542, + 2687165888, + 1202797690, + 1320957812, + 1437280870, + 1554391400, + 1669664834, + 1787304780, + 1906247262, + 2022837584, + 265905162, + 114585348, + 499347990, + 349075736, + 736970802, + 585122620, + 972512814, + 821712160, + 2595684844, + 2478443234, + 2293045232, + 2174754046, + 3196267988, + 3079546586, + 2895723464, + 2777952454, + 3537852828, + 3687994002, + 3234156416, + 3385345166, + 4142626212, + 4293295786, + 3841024952, + 3992742070, + 174567692, + 57326082, + 410887952, + 292596766, + 777231668, + 660510266, + 1011452712, + 893681702, + 1108339068, + 1258480242, + 1343618912, + 1494807662, + 1715193156, + 1865862730, + 1948373848, + 2100090966, + 2701949495, + 2818666809, + 3004591147, + 3122358053, + 2235061775, + 2352307457, + 2535604243, + 2653899549, + 3915653703, + 3764988233, + 4219352155, + 4067639125, + 3444575871, + 3294430577, + 3746175075, + 3594982253, + 836553431, + 953270745, + 600235211, + 718002117, + 367585007, + 484830689, + 133361907, + 251657213, + 2041877159, + 1891211689, + 1806599355, + 1654886325, + 1568718495, + 1418573201, + 1335535747, + 1184342925 +]; +function convertToInt32(bytes) { + const result = []; + for(let i = 0; i < bytes.length; i += 4){ + result.push(bytes[i] << 24 | bytes[i + 1] << 16 | bytes[i + 2] << 8 | bytes[i + 3]); } - getBaseUrl() { - switch(this.network ? this.network.name : "invalid"){ - case "homestead": - return "https://api.etherscan.io"; - case "goerli": - return "https://api-goerli.etherscan.io"; - case "sepolia": - return "https://api-sepolia.etherscan.io"; - case "matic": - return "https://api.polygonscan.com"; - case "maticmum": - return "https://api-testnet.polygonscan.com"; - case "arbitrum": - return "https://api.arbiscan.io"; - case "arbitrum-goerli": - return "https://api-goerli.arbiscan.io"; - case "optimism": - return "https://api-optimistic.etherscan.io"; - case "optimism-goerli": - return "https://api-goerli-optimistic.etherscan.io"; + return result; +} +class AES { + get key() { + return __classPrivateFieldGet$2(this, _AES_key, "f").slice(); + } + constructor(key){ + _AES_key.set(this, void 0); + _AES_Kd.set(this, void 0); + _AES_Ke.set(this, void 0); + if (!(this instanceof AES)) { + throw Error("AES must be instanitated with `new`"); + } + __classPrivateFieldSet$2(this, _AES_key, new Uint8Array(key), "f"); + const rounds = numberOfRounds[this.key.length]; + if (rounds == null) { + throw new TypeError("invalid key size (must be 16, 24 or 32 bytes)"); + } + __classPrivateFieldSet$2(this, _AES_Ke, [], "f"); + __classPrivateFieldSet$2(this, _AES_Kd, [], "f"); + for(let i = 0; i <= rounds; i++){ + __classPrivateFieldGet$2(this, _AES_Ke, "f").push([ + 0, + 0, + 0, + 0 + ]); + __classPrivateFieldGet$2(this, _AES_Kd, "f").push([ + 0, + 0, + 0, + 0 + ]); } - return logger$8.throwArgumentError("unsupported network", "network", this.network.name); - } - getUrl(module, params) { - const query = Object.keys(params).reduce((accum, key)=>{ - const value = params[key]; - if (value != null) { - accum += `&${key}=${value}`; - } - return accum; - }, ""); - const apiKey = this.apiKey ? `&apikey=${this.apiKey}` : ""; - return `${this.baseUrl}/api?module=${module}${query}${apiKey}`; - } - getPostUrl() { - return `${this.baseUrl}/api`; - } - getPostData(module, params) { - params.module = module; - params.apikey = this.apiKey; - return params; - } - fetch(module, params, post) { - return __awaiter$5(this, void 0, void 0, function*() { - const url = post ? this.getPostUrl() : this.getUrl(module, params); - const payload = post ? this.getPostData(module, params) : null; - const procFunc = module === "proxy" ? getJsonResult : getResult$1; - this.emit("debug", { - action: "request", - request: url, - provider: this - }); - const connection = { - url, - throttleSlotInterval: 1e3, - throttleCallback: (attempt, url2)=>{ - if (this.isCommunityResource()) { - showThrottleMessage(); - } - return Promise.resolve(true); + const roundKeyCount = (rounds + 1) * 4; + const KC = this.key.length / 4; + const tk = convertToInt32(this.key); + let index; + for(let i = 0; i < KC; i++){ + index = i >> 2; + __classPrivateFieldGet$2(this, _AES_Ke, "f")[index][i % 4] = tk[i]; + __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds - index][i % 4] = tk[i]; + } + let rconpointer = 0; + let t = KC, tt; + while(t < roundKeyCount){ + tt = tk[KC - 1]; + tk[0] ^= S[tt >> 16 & 255] << 24 ^ S[tt >> 8 & 255] << 16 ^ S[tt & 255] << 8 ^ S[tt >> 24 & 255] ^ rcon[rconpointer] << 24; + rconpointer += 1; + if (KC != 8) { + for(let i = 1; i < KC; i++){ + tk[i] ^= tk[i - 1]; + } + } else { + for(let i = 1; i < KC / 2; i++){ + tk[i] ^= tk[i - 1]; + } + tt = tk[KC / 2 - 1]; + tk[KC / 2] ^= S[tt & 255] ^ S[tt >> 8 & 255] << 8 ^ S[tt >> 16 & 255] << 16 ^ S[tt >> 24 & 255] << 24; + for(let i = KC / 2 + 1; i < KC; i++){ + tk[i] ^= tk[i - 1]; } - }; - let payloadStr = null; - if (payload) { - connection.headers = { - "content-type": "application/x-www-form-urlencoded; charset=UTF-8" - }; - payloadStr = Object.keys(payload).map((key)=>{ - return `${key}=${payload[key]}`; - }).join("&"); } - const result = yield fetchJson(connection, payloadStr, procFunc || getJsonResult); - this.emit("debug", { - action: "response", - request: url, - response: deepCopy(result), - provider: this - }); - return result; - }); - } - detectNetwork() { - return __awaiter$5(this, void 0, void 0, function*() { - return this.network; - }); - } - perform(method, params) { - const _super = Object.create(null, { - perform: { - get: ()=>super.perform + let i = 0, r, c; + while(i < KC && t < roundKeyCount){ + r = t >> 2; + c = t % 4; + __classPrivateFieldGet$2(this, _AES_Ke, "f")[r][c] = tk[i]; + __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds - r][c] = tk[i++]; + t++; } - }); - return __awaiter$5(this, void 0, void 0, function*() { - switch(method){ - case "getBlockNumber": - return this.fetch("proxy", { - action: "eth_blockNumber" - }); - case "getGasPrice": - return this.fetch("proxy", { - action: "eth_gasPrice" - }); - case "getBalance": - return this.fetch("account", { - action: "balance", - address: params.address, - tag: params.blockTag - }); - case "getTransactionCount": - return this.fetch("proxy", { - action: "eth_getTransactionCount", - address: params.address, - tag: params.blockTag - }); - case "getCode": - return this.fetch("proxy", { - action: "eth_getCode", - address: params.address, - tag: params.blockTag - }); - case "getStorageAt": - return this.fetch("proxy", { - action: "eth_getStorageAt", - address: params.address, - position: params.position, - tag: params.blockTag - }); - case "sendTransaction": - return this.fetch("proxy", { - action: "eth_sendRawTransaction", - hex: params.signedTransaction - }, true).catch((error)=>{ - return checkError$1("sendTransaction", error, params.signedTransaction); - }); - case "getBlock": - if (params.blockTag) { - return this.fetch("proxy", { - action: "eth_getBlockByNumber", - tag: params.blockTag, - boolean: params.includeTransactions ? "true" : "false" - }); - } - throw new Error("getBlock by blockHash not implemented"); - case "getTransaction": - return this.fetch("proxy", { - action: "eth_getTransactionByHash", - txhash: params.transactionHash - }); - case "getTransactionReceipt": - return this.fetch("proxy", { - action: "eth_getTransactionReceipt", - txhash: params.transactionHash - }); - case "call": - { - if (params.blockTag !== "latest") { - throw new Error("EtherscanProvider does not support blockTag for call"); - } - const postData = getTransactionPostData(params.transaction); - postData.module = "proxy"; - postData.action = "eth_call"; - try { - return yield this.fetch("proxy", postData, true); - } catch (error) { - return checkError$1("call", error, params.transaction); - } - } - case "estimateGas": - { - const postData = getTransactionPostData(params.transaction); - postData.module = "proxy"; - postData.action = "eth_estimateGas"; - try { - return yield this.fetch("proxy", postData, true); - } catch (error) { - return checkError$1("estimateGas", error, params.transaction); - } - } - case "getLogs": - { - const args = { - action: "getLogs" - }; - if (params.filter.fromBlock) { - args.fromBlock = checkLogTag(params.filter.fromBlock); - } - if (params.filter.toBlock) { - args.toBlock = checkLogTag(params.filter.toBlock); - } - if (params.filter.address) { - args.address = params.filter.address; - } - if (params.filter.topics && params.filter.topics.length > 0) { - if (params.filter.topics.length > 1) { - logger$8.throwError("unsupported topic count", Logger.errors.UNSUPPORTED_OPERATION, { - topics: params.filter.topics - }); - } - if (params.filter.topics.length === 1) { - const topic0 = params.filter.topics[0]; - if (typeof topic0 !== "string" || topic0.length !== 66) { - logger$8.throwError("unsupported topic format", Logger.errors.UNSUPPORTED_OPERATION, { - topic0 - }); - } - args.topic0 = topic0; - } - } - const logs = yield this.fetch("logs", args); - let blocks = {}; - for(let i = 0; i < logs.length; i++){ - const log = logs[i]; - if (log.blockHash != null) { - continue; - } - if (blocks[log.blockNumber] == null) { - const block = yield this.getBlock(log.blockNumber); - if (block) { - blocks[log.blockNumber] = block.hash; - } - } - log.blockHash = blocks[log.blockNumber]; - } - return logs; - } - case "getEtherPrice": - if (this.network.name !== "homestead") { - return 0; - } - return parseFloat((yield this.fetch("stats", { - action: "ethprice" - })).ethusd); + } + for(let r = 1; r < rounds; r++){ + for(let c = 0; c < 4; c++){ + tt = __classPrivateFieldGet$2(this, _AES_Kd, "f")[r][c]; + __classPrivateFieldGet$2(this, _AES_Kd, "f")[r][c] = U1[tt >> 24 & 255] ^ U2[tt >> 16 & 255] ^ U3[tt >> 8 & 255] ^ U4[tt & 255]; } - return _super.perform.call(this, method, params); - }); + } } - getHistory(addressOrName, startBlock, endBlock) { - return __awaiter$5(this, void 0, void 0, function*() { - const params = { - action: "txlist", - address: yield this.resolveName(addressOrName), - startblock: startBlock == null ? 0 : startBlock, - endblock: endBlock == null ? 99999999 : endBlock, - sort: "asc" - }; - const result = yield this.fetch("account", params); - return result.map((tx)=>{ - [ - "contractAddress", - "to" - ].forEach(function(key) { - if (tx[key] == "") { - delete tx[key]; - } - }); - if (tx.creates == null && tx.contractAddress != null) { - tx.creates = tx.contractAddress; - } - const item = this.formatter.transactionResponse(tx); - if (tx.timeStamp) { - item.timestamp = parseInt(tx.timeStamp); - } - return item; - }); - }); + encrypt(plaintext) { + if (plaintext.length != 16) { + throw new TypeError("invalid plaintext size (must be 16 bytes)"); + } + const rounds = __classPrivateFieldGet$2(this, _AES_Ke, "f").length - 1; + const a = [ + 0, + 0, + 0, + 0 + ]; + let t = convertToInt32(plaintext); + for(let i = 0; i < 4; i++){ + t[i] ^= __classPrivateFieldGet$2(this, _AES_Ke, "f")[0][i]; + } + for(let r = 1; r < rounds; r++){ + for(let i = 0; i < 4; i++){ + a[i] = T1[t[i] >> 24 & 255] ^ T2[t[(i + 1) % 4] >> 16 & 255] ^ T3[t[(i + 2) % 4] >> 8 & 255] ^ T4[t[(i + 3) % 4] & 255] ^ __classPrivateFieldGet$2(this, _AES_Ke, "f")[r][i]; + } + t = a.slice(); + } + const result = new Uint8Array(16); + let tt = 0; + for(let i = 0; i < 4; i++){ + tt = __classPrivateFieldGet$2(this, _AES_Ke, "f")[rounds][i]; + result[4 * i] = (S[t[i] >> 24 & 255] ^ tt >> 24) & 255; + result[4 * i + 1] = (S[t[(i + 1) % 4] >> 16 & 255] ^ tt >> 16) & 255; + result[4 * i + 2] = (S[t[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; + result[4 * i + 3] = (S[t[(i + 3) % 4] & 255] ^ tt) & 255; + } + return result; } - isCommunityResource() { - return this.apiKey == null; + decrypt(ciphertext) { + if (ciphertext.length != 16) { + throw new TypeError("invalid ciphertext size (must be 16 bytes)"); + } + const rounds = __classPrivateFieldGet$2(this, _AES_Kd, "f").length - 1; + const a = [ + 0, + 0, + 0, + 0 + ]; + let t = convertToInt32(ciphertext); + for(let i = 0; i < 4; i++){ + t[i] ^= __classPrivateFieldGet$2(this, _AES_Kd, "f")[0][i]; + } + for(let r = 1; r < rounds; r++){ + for(let i = 0; i < 4; i++){ + a[i] = T5[t[i] >> 24 & 255] ^ T6[t[(i + 3) % 4] >> 16 & 255] ^ T7[t[(i + 2) % 4] >> 8 & 255] ^ T8[t[(i + 1) % 4] & 255] ^ __classPrivateFieldGet$2(this, _AES_Kd, "f")[r][i]; + } + t = a.slice(); + } + const result = new Uint8Array(16); + let tt = 0; + for(let i = 0; i < 4; i++){ + tt = __classPrivateFieldGet$2(this, _AES_Kd, "f")[rounds][i]; + result[4 * i] = (Si[t[i] >> 24 & 255] ^ tt >> 24) & 255; + result[4 * i + 1] = (Si[t[(i + 3) % 4] >> 16 & 255] ^ tt >> 16) & 255; + result[4 * i + 2] = (Si[t[(i + 2) % 4] >> 8 & 255] ^ tt >> 8) & 255; + result[4 * i + 3] = (Si[t[(i + 1) % 4] & 255] ^ tt) & 255; + } + return result; } } -var __awaiter$6 = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); +_AES_key = new WeakMap, _AES_Kd = new WeakMap, _AES_Ke = new WeakMap; +class ModeOfOperation { + constructor(name, key, cls){ + if (cls && !(this instanceof cls)) { + throw new Error(`${name} must be instantiated with "new"`); + } + Object.defineProperties(this, { + aes: { + enumerable: true, + value: new AES(key) + }, + name: { + enumerable: true, + value: name + } }); } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } +} +var __classPrivateFieldSet$1 = __$G && __$G.__classPrivateFieldSet || function(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +}; +var __classPrivateFieldGet$1 = __$G && __$G.__classPrivateFieldGet || function(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CBC_iv, _CBC_lastBlock; +class CBC extends ModeOfOperation { + constructor(key, iv){ + super("ECC", key, CBC); + _CBC_iv.set(this, void 0); + _CBC_lastBlock.set(this, void 0); + if (iv) { + if (iv.length % 16) { + throw new TypeError("invalid iv size (must be 16 bytes)"); + } + __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(iv), "f"); + } else { + __classPrivateFieldSet$1(this, _CBC_iv, new Uint8Array(16), "f"); } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } + __classPrivateFieldSet$1(this, _CBC_lastBlock, this.iv, "f"); + } + get iv() { + return new Uint8Array(__classPrivateFieldGet$1(this, _CBC_iv, "f")); + } + encrypt(plaintext) { + if (plaintext.length % 16) { + throw new TypeError("invalid plaintext size (must be multiple of 16 bytes)"); } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + const ciphertext = new Uint8Array(plaintext.length); + for(let i = 0; i < plaintext.length; i += 16){ + for(let j = 0; j < 16; j++){ + __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j] ^= plaintext[i + j]; + } + __classPrivateFieldSet$1(this, _CBC_lastBlock, this.aes.encrypt(__classPrivateFieldGet$1(this, _CBC_lastBlock, "f")), "f"); + ciphertext.set(__classPrivateFieldGet$1(this, _CBC_lastBlock, "f"), i); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -const logger$9 = new Logger(version23); -function now() { - return new Date().getTime(); -} -function checkNetworks(networks3) { - let result = null; - for(let i = 0; i < networks3.length; i++){ - const network = networks3[i]; - if (network == null) { - return null; + return ciphertext; + } + decrypt(ciphertext) { + if (ciphertext.length % 16) { + throw new TypeError("invalid ciphertext size (must be multiple of 16 bytes)"); } - if (result) { - if (!(result.name === network.name && result.chainId === network.chainId && (result.ensAddress === network.ensAddress || result.ensAddress == null && network.ensAddress == null))) { - logger$9.throwArgumentError("provider mismatch", "networks", networks3); + const plaintext = new Uint8Array(ciphertext.length); + for(let i = 0; i < ciphertext.length; i += 16){ + const block = this.aes.decrypt(ciphertext.subarray(i, i + 16)); + for(let j = 0; j < 16; j++){ + plaintext[i + j] = block[j] ^ __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j]; + __classPrivateFieldGet$1(this, _CBC_lastBlock, "f")[j] = ciphertext[i + j]; } - } else { - result = network; } + return plaintext; } - return result; } -function median(values, maxDelta) { - values = values.slice().sort(); - const middle = Math.floor(values.length / 2); - if (values.length % 2) { - return values[middle]; +_CBC_iv = new WeakMap, _CBC_lastBlock = new WeakMap; +var __classPrivateFieldSet = __$G && __$G.__classPrivateFieldSet || function(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; +}; +var __classPrivateFieldGet = __$G && __$G.__classPrivateFieldGet || function(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _CTR_remaining, _CTR_remainingIndex, _CTR_counter; +class CTR extends ModeOfOperation { + constructor(key, initialValue){ + super("CTR", key, CTR); + _CTR_remaining.set(this, void 0); + _CTR_remainingIndex.set(this, void 0); + _CTR_counter.set(this, void 0); + __classPrivateFieldSet(this, _CTR_counter, new Uint8Array(16), "f"); + __classPrivateFieldGet(this, _CTR_counter, "f").fill(0); + __classPrivateFieldSet(this, _CTR_remaining, __classPrivateFieldGet(this, _CTR_counter, "f"), "f"); + __classPrivateFieldSet(this, _CTR_remainingIndex, 16, "f"); + if (initialValue == null) { + initialValue = 1; + } + if (typeof initialValue === "number") { + this.setCounterValue(initialValue); + } else { + this.setCounterBytes(initialValue); + } } - const a = values[middle - 1], b = values[middle]; - if (maxDelta != null && Math.abs(a - b) > maxDelta) { - return null; + get counter() { + return new Uint8Array(__classPrivateFieldGet(this, _CTR_counter, "f")); } - return (a + b) / 2; -} -function serialize1(value) { - if (value === null) { - return "null"; - } else if (typeof value === "number" || typeof value === "boolean") { - return JSON.stringify(value); - } else if (typeof value === "string") { - return value; - } else if (BigNumber.isBigNumber(value)) { - return value.toString(); - } else if (Array.isArray(value)) { - return JSON.stringify(value.map((i)=>serialize1(i))); - } else if (typeof value === "object") { - const keys = Object.keys(value); - keys.sort(); - return "{" + keys.map((key)=>{ - let v = value[key]; - if (typeof v === "function") { - v = "[function]"; + setCounterValue(value) { + if (!Number.isInteger(value) || value < 0 || value > Number.MAX_SAFE_INTEGER) { + throw new TypeError("invalid counter initial integer value"); + } + for(let index = 15; index >= 0; --index){ + __classPrivateFieldGet(this, _CTR_counter, "f")[index] = value % 256; + value = Math.floor(value / 256); + } + } + setCounterBytes(value) { + if (value.length !== 16) { + throw new TypeError("invalid counter initial Uint8Array value length"); + } + __classPrivateFieldGet(this, _CTR_counter, "f").set(value); + } + increment() { + for(let i = 15; i >= 0; i--){ + if (__classPrivateFieldGet(this, _CTR_counter, "f")[i] === 255) { + __classPrivateFieldGet(this, _CTR_counter, "f")[i] = 0; } else { - v = serialize1(v); + __classPrivateFieldGet(this, _CTR_counter, "f")[i]++; + break; } - return JSON.stringify(key) + ":" + v; - }).join(",") + "}"; + } } - throw new Error("unknown value type: " + typeof value); -} -let nextRid = 1; -function stall$1(duration) { - let cancel = null; - let timer2 = null; - let promise = new Promise((resolve)=>{ - cancel = function() { - if (timer2) { - clearTimeout(timer2); - timer2 = null; + encrypt(plaintext) { + var _a, _b; + const crypttext = new Uint8Array(plaintext); + for(let i = 0; i < crypttext.length; i++){ + if (__classPrivateFieldGet(this, _CTR_remainingIndex, "f") === 16) { + __classPrivateFieldSet(this, _CTR_remaining, this.aes.encrypt(__classPrivateFieldGet(this, _CTR_counter, "f")), "f"); + __classPrivateFieldSet(this, _CTR_remainingIndex, 0, "f"); + this.increment(); } - resolve(); - }; - timer2 = setTimeout(cancel, duration); - }); - const wait = (func)=>{ - promise = promise.then(func); - return promise; - }; - function getPromise() { - return promise; + crypttext[i] ^= __classPrivateFieldGet(this, _CTR_remaining, "f")[__classPrivateFieldSet(this, _CTR_remainingIndex, (_b = __classPrivateFieldGet(this, _CTR_remainingIndex, "f"), _a = _b++, _b), "f"), _a]; + } + return crypttext; + } + decrypt(ciphertext) { + return this.encrypt(ciphertext); } - return { - cancel, - getPromise, - wait - }; } -const ForwardErrors = [ - Logger.errors.CALL_EXCEPTION, - Logger.errors.INSUFFICIENT_FUNDS, - Logger.errors.NONCE_EXPIRED, - Logger.errors.REPLACEMENT_UNDERPRICED, - Logger.errors.UNPREDICTABLE_GAS_LIMIT -]; -const ForwardProperties = [ - "address", - "args", - "errorArgs", - "errorSignature", - "method", - "transaction" -]; -function exposeDebugConfig(config, now2) { - const result = { - weight: config.weight - }; - Object.defineProperty(result, "provider", { - get: ()=>config.provider - }); - if (config.start) { - result.start = config.start; +_CTR_remaining = new WeakMap, _CTR_remainingIndex = new WeakMap, _CTR_counter = new WeakMap; +function pkcs7Strip(data) { + if (data.length < 16) { + throw new TypeError("PKCS#7 invalid length"); } - if (now2) { - result.duration = now2 - config.start; + const padder = data[data.length - 1]; + if (padder > 16) { + throw new TypeError("PKCS#7 padding byte out of range"); } - if (config.done) { - if (config.error) { - result.error = config.error; - } else { - result.result = config.result || null; + const length = data.length - padder; + for(let i = 0; i < padder; i++){ + if (data[length + i] !== padder) { + throw new TypeError("PKCS#7 invalid padding byte"); } } - return result; -} -function normalizedTally(normalize, quorum) { - return function(configs) { - const tally = {}; - configs.forEach((c)=>{ - const value = normalize(c.result); - if (!tally[value]) { - tally[value] = { - count: 0, - result: c.result - }; - } - tally[value].count++; - }); - const keys = Object.keys(tally); - for(let i = 0; i < keys.length; i++){ - const check = tally[keys[i]]; - if (check.count >= quorum) { - return check.result; - } - } - return void 0; - }; + return new Uint8Array(data.subarray(0, length)); } -function getProcessFunc(provider, method, params) { - let normalize = serialize1; - switch(method){ - case "getBlockNumber": - return function(configs) { - const values = configs.map((c)=>c.result); - let blockNumber = median(configs.map((c)=>c.result), 2); - if (blockNumber == null) { - return void 0; - } - blockNumber = Math.ceil(blockNumber); - if (values.indexOf(blockNumber + 1) >= 0) { - blockNumber++; - } - if (blockNumber >= provider._highestBlockNumber) { - provider._highestBlockNumber = blockNumber; - } - return provider._highestBlockNumber; - }; - case "getGasPrice": - return function(configs) { - const values = configs.map((c)=>c.result); - values.sort(); - return values[Math.floor(values.length / 2)]; - }; - case "getEtherPrice": - return function(configs) { - return median(configs.map((c)=>c.result)); - }; - case "getBalance": - case "getTransactionCount": - case "getCode": - case "getStorageAt": - case "call": - case "estimateGas": - case "getLogs": - break; - case "getTransaction": - case "getTransactionReceipt": - normalize = function(tx) { - if (tx == null) { - return null; - } - tx = shallowCopy(tx); - tx.confirmations = -1; - return serialize1(tx); - }; - break; - case "getBlock": - if (params.includeTransactions) { - normalize = function(block) { - if (block == null) { - return null; - } - block = shallowCopy(block); - block.transactions = block.transactions.map((tx)=>{ - tx = shallowCopy(tx); - tx.confirmations = -1; - return tx; - }); - return serialize1(block); - }; - } else { - normalize = function(block) { - if (block == null) { - return null; - } - return serialize1(block); - }; - } - break; - default: - throw new Error("unknown method: " + method); +function looseArrayify(hexString) { + if (typeof hexString === "string" && !hexString.startsWith("0x")) { + hexString = "0x" + hexString; } - return normalizedTally(normalize, provider.quorum); + return getBytesCopy(hexString); } -function waitForSync(config, blockNumber) { - return __awaiter$6(this, void 0, void 0, function*() { - const provider = config.provider; - if (provider.blockNumber != null && provider.blockNumber >= blockNumber || blockNumber === -1) { - return provider; - } - return poll(()=>{ - return new Promise((resolve, reject)=>{ - setTimeout(function() { - if (provider.blockNumber >= blockNumber) { - return resolve(provider); - } - if (config.cancelled) { - return resolve(null); - } - return resolve(void 0); - }, 0); - }); - }, { - oncePoll: provider - }); - }); +function zpad$1(value, length) { + value = String(value); + while(value.length < length){ + value = "0" + value; + } + return value; } -function getRunner(config, currentBlockNumber, method, params) { - return __awaiter$6(this, void 0, void 0, function*() { - let provider = config.provider; - switch(method){ - case "getBlockNumber": - case "getGasPrice": - return provider[method](); - case "getEtherPrice": - if (provider.getEtherPrice) { - return provider.getEtherPrice(); - } +function getPassword(password) { + if (typeof password === "string") { + return toUtf8Bytes(password, "NFKC"); + } + return getBytesCopy(password); +} +function spelunk(object, _path) { + const match = _path.match(/^([a-z0-9$_.-]*)(:([a-z]+))?(!)?$/i); + assertArgument(match != null, "invalid path", "path", _path); + const path = match[1]; + const type = match[3]; + const reqd = match[4] === "!"; + let cur = object; + for (const comp of path.toLowerCase().split(".")){ + if (Array.isArray(cur)) { + if (!comp.match(/^[0-9]+$/)) { break; - case "getBalance": - case "getTransactionCount": - case "getCode": - if (params.blockTag && isHexString(params.blockTag)) { - provider = yield waitForSync(config, currentBlockNumber); - } - return provider[method](params.address, params.blockTag || "latest"); - case "getStorageAt": - if (params.blockTag && isHexString(params.blockTag)) { - provider = yield waitForSync(config, currentBlockNumber); - } - return provider.getStorageAt(params.address, params.position, params.blockTag || "latest"); - case "getBlock": - if (params.blockTag && isHexString(params.blockTag)) { - provider = yield waitForSync(config, currentBlockNumber); - } - return provider[params.includeTransactions ? "getBlockWithTransactions" : "getBlock"](params.blockTag || params.blockHash); - case "call": - case "estimateGas": - if (params.blockTag && isHexString(params.blockTag)) { - provider = yield waitForSync(config, currentBlockNumber); - } - if (method === "call" && params.blockTag) { - return provider[method](params.transaction, params.blockTag); - } - return provider[method](params.transaction); - case "getTransaction": - case "getTransactionReceipt": - return provider[method](params.transactionHash); - case "getLogs": - { - let filter = params.filter; - if (filter.fromBlock && isHexString(filter.fromBlock) || filter.toBlock && isHexString(filter.toBlock)) { - provider = yield waitForSync(config, currentBlockNumber); - } - return provider.getLogs(filter); - } - } - return logger$9.throwError("unknown method error", Logger.errors.UNKNOWN_ERROR, { - method, - params - }); - }); -} -class FallbackProvider extends BaseProvider { - constructor(providers, quorum){ - if (providers.length === 0) { - logger$9.throwArgumentError("missing providers", "providers", providers); - } - const providerConfigs = providers.map((configOrProvider, index)=>{ - if (Provider.isProvider(configOrProvider)) { - const stallTimeout = isCommunityResource(configOrProvider) ? 2e3 : 750; - return Object.freeze({ - provider: configOrProvider, - weight: 1, - stallTimeout, - priority: 1 - }); - } - const config = shallowCopy(configOrProvider); - if (config.priority == null) { - config.priority = 1; - } - if (config.stallTimeout == null) { - config.stallTimeout = isCommunityResource(configOrProvider) ? 2e3 : 750; - } - if (config.weight == null) { - config.weight = 1; } - const weight = config.weight; - if (weight % 1 || weight > 512 || weight < 1) { - logger$9.throwArgumentError("invalid weight; must be integer in [1, 512]", `providers[${index}].weight`, weight); + cur = cur[parseInt(comp)]; + } else if (typeof cur === "object") { + let found = null; + for(const key in cur){ + if (key.toLowerCase() === comp) { + found = cur[key]; + break; + } } - return Object.freeze(config); - }); - const total = providerConfigs.reduce((accum, c)=>accum + c.weight, 0); - if (quorum == null) { - quorum = total / 2; - } else if (quorum > total) { - logger$9.throwArgumentError("quorum will always fail; larger than total weight", "quorum", quorum); - } - let networkOrReady = checkNetworks(providerConfigs.map((c)=>c.provider.network)); - if (networkOrReady == null) { - networkOrReady = new Promise((resolve, reject)=>{ - setTimeout(()=>{ - this.detectNetwork().then(resolve, reject); - }, 0); - }); + cur = found; + } else { + cur = null; + } + if (cur == null) { + break; } - super(networkOrReady); - defineReadOnly(this, "providerConfigs", Object.freeze(providerConfigs)); - defineReadOnly(this, "quorum", quorum); - this._highestBlockNumber = -1; - } - detectNetwork() { - return __awaiter$6(this, void 0, void 0, function*() { - const networks3 = yield Promise.all(this.providerConfigs.map((c)=>c.provider.getNetwork())); - return checkNetworks(networks3); - }); } - perform(method, params) { - return __awaiter$6(this, void 0, void 0, function*() { - if (method === "sendTransaction") { - const results = yield Promise.all(this.providerConfigs.map((c)=>{ - return c.provider.sendTransaction(params.signedTransaction).then((result)=>{ - return result.hash; - }, (error)=>{ - return error; - }); - })); - for(let i2 = 0; i2 < results.length; i2++){ - const result = results[i2]; - if (typeof result === "string") { - return result; - } - } - throw results[0]; + assertArgument(!reqd || cur != null, "missing required value", "path", path); + if (type && cur != null) { + if (type === "int") { + if (typeof cur === "string" && cur.match(/^-?[0-9]+$/)) { + return parseInt(cur); + } else if (Number.isSafeInteger(cur)) { + return cur; } - if (this._highestBlockNumber === -1 && method !== "getBlockNumber") { - yield this.getBlockNumber(); + } + if (type === "number") { + if (typeof cur === "string" && cur.match(/^-?[0-9.]*$/)) { + return parseFloat(cur); } - const processFunc = getProcessFunc(this, method, params); - const configs = shuffled(this.providerConfigs.map(shallowCopy)); - configs.sort((a, b)=>a.priority - b.priority); - const currentBlockNumber = this._highestBlockNumber; - let i = 0; - let first = true; - while(true){ - const t0 = now(); - let inflightWeight = configs.filter((c)=>c.runner && t0 - c.start < c.stallTimeout).reduce((accum, c)=>accum + c.weight, 0); - while(inflightWeight < this.quorum && i < configs.length){ - const config = configs[i++]; - const rid = nextRid++; - config.start = now(); - config.staller = stall$1(config.stallTimeout); - config.staller.wait(()=>{ - config.staller = null; - }); - config.runner = getRunner(config, currentBlockNumber, method, params).then((result)=>{ - config.done = true; - config.result = result; - if (this.listenerCount("debug")) { - this.emit("debug", { - action: "request", - rid, - backend: exposeDebugConfig(config, now()), - request: { - method, - params: deepCopy(params) - }, - provider: this - }); - } - }, (error)=>{ - config.done = true; - config.error = error; - if (this.listenerCount("debug")) { - this.emit("debug", { - action: "request", - rid, - backend: exposeDebugConfig(config, now()), - request: { - method, - params: deepCopy(params) - }, - provider: this - }); - } - }); - if (this.listenerCount("debug")) { - this.emit("debug", { - action: "request", - rid, - backend: exposeDebugConfig(config, null), - request: { - method, - params: deepCopy(params) - }, - provider: this - }); - } - inflightWeight += config.weight; - } - const waiting = []; - configs.forEach((c)=>{ - if (c.done || !c.runner) { - return; - } - waiting.push(c.runner); - if (c.staller) { - waiting.push(c.staller.getPromise()); - } - }); - if (waiting.length) { - yield Promise.race(waiting); - } - const results = configs.filter((c)=>c.done && c.error == null); - if (results.length >= this.quorum) { - const result = processFunc(results); - if (result !== void 0) { - configs.forEach((c)=>{ - if (c.staller) { - c.staller.cancel(); - } - c.cancelled = true; - }); - return result; - } - if (!first) { - yield stall$1(100).getPromise(); - } - first = false; - } - const errors = configs.reduce((accum, c)=>{ - if (!c.done || c.error == null) { - return accum; - } - const code = c.error.code; - if (ForwardErrors.indexOf(code) >= 0) { - if (!accum[code]) { - accum[code] = { - error: c.error, - weight: 0 - }; - } - accum[code].weight += c.weight; - } - return accum; - }, {}); - Object.keys(errors).forEach((errorCode)=>{ - const tally = errors[errorCode]; - if (tally.weight < this.quorum) { - return; - } - configs.forEach((c)=>{ - if (c.staller) { - c.staller.cancel(); - } - c.cancelled = true; - }); - const e = tally.error; - const props = {}; - ForwardProperties.forEach((name)=>{ - if (e[name] == null) { - return; - } - props[name] = e[name]; - }); - logger$9.throwError(e.reason || e.message, errorCode, props); - }); - if (configs.filter((c)=>!c.done).length === 0) { - break; - } + } + if (type === "data") { + if (typeof cur === "string") { + return looseArrayify(cur); } - configs.forEach((c)=>{ - if (c.staller) { - c.staller.cancel(); - } - c.cancelled = true; - }); - return logger$9.throwError("failed to meet quorum", Logger.errors.SERVER_ERROR, { - method, - params, - results: configs.map((c)=>exposeDebugConfig(c)), - provider: this - }); - }); + } + if (type === "array" && Array.isArray(cur)) { + return cur; + } + if (type === typeof cur) { + return cur; + } + assertArgument(false, `wrong type found for ${type} `, "path", path); } + return cur; } -const logger$a = new Logger(version23); -const defaultProjectId = "84842078b09946638c03157f83405213"; -class InfuraWebSocketProvider extends WebSocketProvider { - constructor(network, apiKey){ - const provider = new InfuraProvider(network, apiKey); - const connection = provider.connection; - if (connection.password) { - logger$a.throwError("INFURA WebSocket project secrets unsupported", Logger.errors.UNSUPPORTED_OPERATION, { - operation: "InfuraProvider.getWebSocketProvider()" - }); +const defaultPath$1 = "m/44'/60'/0'/0/0"; +function isKeystoreJson(json) { + try { + const data = JSON.parse(json); + const version = data.version != null ? parseInt(data.version) : 0; + if (version === 3) { + return true; } - const url = connection.url.replace(/^http/i, "ws").replace("/v3/", "/ws/v3/"); - super(url, network); - defineReadOnly(this, "apiKey", provider.projectId); - defineReadOnly(this, "projectId", provider.projectId); - defineReadOnly(this, "projectSecret", provider.projectSecret); - } - isCommunityResource() { - return this.projectId === defaultProjectId; - } + } catch (error) {} + return false; } -class InfuraProvider extends UrlJsonRpcProvider { - static getWebSocketProvider(network, apiKey) { - return new InfuraWebSocketProvider(network, apiKey); +function decrypt(data, key, ciphertext) { + const cipher = spelunk(data, "crypto.cipher:string"); + if (cipher === "aes-128-ctr") { + const iv = spelunk(data, "crypto.cipherparams.iv:data!"); + const aesCtr = new CTR(key, iv); + return hexlify(aesCtr.decrypt(ciphertext)); } - static getApiKey(apiKey) { - const apiKeyObj = { - apiKey: defaultProjectId, - projectId: defaultProjectId, - projectSecret: null - }; - if (apiKey == null) { - return apiKeyObj; - } - if (typeof apiKey === "string") { - apiKeyObj.projectId = apiKey; - } else if (apiKey.projectSecret != null) { - logger$a.assertArgument(typeof apiKey.projectId === "string", "projectSecret requires a projectId", "projectId", apiKey.projectId); - logger$a.assertArgument(typeof apiKey.projectSecret === "string", "invalid projectSecret", "projectSecret", "[REDACTED]"); - apiKeyObj.projectId = apiKey.projectId; - apiKeyObj.projectSecret = apiKey.projectSecret; - } else if (apiKey.projectId) { - apiKeyObj.projectId = apiKey.projectId; - } - apiKeyObj.apiKey = apiKeyObj.projectId; - return apiKeyObj; - } - static getUrl(network, apiKey) { - let host = null; - switch(network ? network.name : "unknown"){ - case "homestead": - host = "mainnet.infura.io"; - break; - case "goerli": - host = "goerli.infura.io"; - break; - case "sepolia": - host = "sepolia.infura.io"; - break; - case "matic": - host = "polygon-mainnet.infura.io"; - break; - case "maticmum": - host = "polygon-mumbai.infura.io"; - break; - case "optimism": - host = "optimism-mainnet.infura.io"; - break; - case "optimism-goerli": - host = "optimism-goerli.infura.io"; - break; - case "arbitrum": - host = "arbitrum-mainnet.infura.io"; - break; - case "arbitrum-goerli": - host = "arbitrum-goerli.infura.io"; - break; - default: - logger$a.throwError("unsupported network", Logger.errors.INVALID_ARGUMENT, { - argument: "network", - value: network - }); + assert1(false, "unsupported cipher", "UNSUPPORTED_OPERATION", { + operation: "decrypt" + }); +} +function getAccount(data, _key) { + const key = getBytes(_key); + const ciphertext = spelunk(data, "crypto.ciphertext:data!"); + const computedMAC = hexlify(keccak256(concat([ + key.slice(16, 32), + ciphertext + ]))).substring(2); + assertArgument(computedMAC === spelunk(data, "crypto.mac:string!").toLowerCase(), "incorrect password", "password", "[ REDACTED ]"); + const privateKey = decrypt(data, key.slice(0, 16), ciphertext); + const address = computeAddress(privateKey); + if (data.address) { + let check = data.address.toLowerCase(); + if (!check.startsWith("0x")) { + check = "0x" + check; } - const connection = { - allowGzip: true, - url: "https://" + host + "/v3/" + apiKey.projectId, - throttleCallback: (attempt, url)=>{ - if (apiKey.projectId === defaultProjectId) { - showThrottleMessage(); - } - return Promise.resolve(true); - } + assertArgument(getAddress(check) === address, "keystore address/privateKey mismatch", "address", data.address); + } + const account = { + address: address, + privateKey: privateKey + }; + const version = spelunk(data, "x-ethers.version:string"); + if (version === "0.1") { + const mnemonicKey = key.slice(32, 64); + const mnemonicCiphertext = spelunk(data, "x-ethers.mnemonicCiphertext:data!"); + const mnemonicIv = spelunk(data, "x-ethers.mnemonicCounter:data!"); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + account.mnemonic = { + path: spelunk(data, "x-ethers.path:string") || defaultPath$1, + locale: spelunk(data, "x-ethers.locale:string") || "en", + entropy: hexlify(getBytes(mnemonicAesCtr.decrypt(mnemonicCiphertext))) }; - if (apiKey.projectSecret != null) { - connection.user = ""; - connection.password = apiKey.projectSecret; + } + return account; +} +function getDecryptKdfParams(data) { + const kdf = spelunk(data, "crypto.kdf:string"); + if (kdf && typeof kdf === "string") { + if (kdf.toLowerCase() === "scrypt") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const N = spelunk(data, "crypto.kdfparams.n:int!"); + const r = spelunk(data, "crypto.kdfparams.r:int!"); + const p = spelunk(data, "crypto.kdfparams.p:int!"); + assertArgument(N > 0 && (N & N - 1) === 0, "invalid kdf.N", "kdf.N", N); + assertArgument(r > 0 && p > 0, "invalid kdf", "kdf", kdf); + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dflen", dkLen); + return { + name: "scrypt", + salt: salt, + N: N, + r: r, + p: p, + dkLen: 64 + }; + } else if (kdf.toLowerCase() === "pbkdf2") { + const salt = spelunk(data, "crypto.kdfparams.salt:data!"); + const prf = spelunk(data, "crypto.kdfparams.prf:string!"); + const algorithm = prf.split("-").pop(); + assertArgument(algorithm === "sha256" || algorithm === "sha512", "invalid kdf.pdf", "kdf.pdf", prf); + const count = spelunk(data, "crypto.kdfparams.c:int!"); + const dkLen = spelunk(data, "crypto.kdfparams.dklen:int!"); + assertArgument(dkLen === 32, "invalid kdf.dklen", "kdf.dklen", dkLen); + return { + name: "pbkdf2", + salt: salt, + count: count, + dkLen: dkLen, + algorithm: algorithm + }; } - return connection; - } - isCommunityResource() { - return this.projectId === defaultProjectId; } + assertArgument(false, "unsupported key-derivation function", "kdf", kdf); } -class JsonRpcBatchProvider extends JsonRpcProvider { - send(method, params) { - const request = { - method, - params, - id: this._nextId++, - jsonrpc: "2.0" - }; - if (this._pendingBatch == null) { - this._pendingBatch = []; +function decryptKeystoreJsonSync(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getDecryptKdfParams(data); + if (params.name === "pbkdf2") { + const { salt, count, dkLen, algorithm } = params; + const key = pbkdf2(password, salt, count, dkLen, algorithm); + return getAccount(data, key); + } + assert1(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { + params: params + }); + const { salt, N, r, p, dkLen } = params; + const key = scryptSync(password, salt, N, r, p, dkLen); + return getAccount(data, key); +} +function stall$1(duration) { + return new Promise((resolve)=>{ + setTimeout(()=>{ + resolve(); + }, duration); + }); +} +async function decryptKeystoreJson(json, _password, progress) { + const data = JSON.parse(json); + const password = getPassword(_password); + const params = getDecryptKdfParams(data); + if (params.name === "pbkdf2") { + if (progress) { + progress(0); + await stall$1(0); + } + const { salt, count, dkLen, algorithm } = params; + const key = pbkdf2(password, salt, count, dkLen, algorithm); + if (progress) { + progress(1); + await stall$1(0); + } + return getAccount(data, key); + } + assert1(params.name === "scrypt", "cannot be reached", "UNKNOWN_ERROR", { + params: params + }); + const { salt, N, r, p, dkLen } = params; + const key = await scrypt(password, salt, N, r, p, dkLen, progress); + return getAccount(data, key); +} +function getEncryptKdfParams(options) { + const salt = options.salt != null ? getBytes(options.salt, "options.salt") : randomBytes(32); + let N = 1 << 17, r = 8, p = 1; + if (options.scrypt) { + if (options.scrypt.N) { + N = options.scrypt.N; } - const inflightRequest = { - request, - resolve: null, - reject: null - }; - const promise = new Promise((resolve, reject)=>{ - inflightRequest.resolve = resolve; - inflightRequest.reject = reject; - }); - this._pendingBatch.push(inflightRequest); - if (!this._pendingBatchAggregator) { - this._pendingBatchAggregator = setTimeout(()=>{ - const batch = this._pendingBatch; - this._pendingBatch = null; - this._pendingBatchAggregator = null; - const request2 = batch.map((inflight)=>inflight.request); - this.emit("debug", { - action: "requestBatch", - request: deepCopy(request2), - provider: this - }); - return fetchJson(this.connection, JSON.stringify(request2)).then((result)=>{ - this.emit("debug", { - action: "response", - request: request2, - response: result, - provider: this - }); - batch.forEach((inflightRequest2, index)=>{ - const payload = result[index]; - if (payload.error) { - const error = new Error(payload.error.message); - error.code = payload.error.code; - error.data = payload.error.data; - inflightRequest2.reject(error); - } else { - inflightRequest2.resolve(payload.result); - } - }); - }, (error)=>{ - this.emit("debug", { - action: "response", - error, - request: request2, - provider: this - }); - batch.forEach((inflightRequest2)=>{ - inflightRequest2.reject(error); - }); - }); - }, 10); + if (options.scrypt.r) { + r = options.scrypt.r; } - return promise; - } -} -const logger$b = new Logger(version23); -const defaultApiKey$2 = "ETHERS_JS_SHARED"; -class NodesmithProvider extends UrlJsonRpcProvider { - static getApiKey(apiKey) { - if (apiKey && typeof apiKey !== "string") { - logger$b.throwArgumentError("invalid apiKey", "apiKey", apiKey); + if (options.scrypt.p) { + p = options.scrypt.p; } - return apiKey || defaultApiKey$2; } - static getUrl(network, apiKey) { - logger$b.warn("NodeSmith will be discontinued on 2019-12-20; please migrate to another platform."); - let host = null; - switch(network.name){ - case "homestead": - host = "https://ethereum.api.nodesmith.io/v1/mainnet/jsonrpc"; - break; - case "ropsten": - host = "https://ethereum.api.nodesmith.io/v1/ropsten/jsonrpc"; - break; - case "rinkeby": - host = "https://ethereum.api.nodesmith.io/v1/rinkeby/jsonrpc"; - break; - case "goerli": - host = "https://ethereum.api.nodesmith.io/v1/goerli/jsonrpc"; - break; - case "kovan": - host = "https://ethereum.api.nodesmith.io/v1/kovan/jsonrpc"; - break; - default: - logger$b.throwArgumentError("unsupported network", "network", arguments[0]); + assertArgument(typeof N === "number" && N > 0 && Number.isSafeInteger(N) && (BigInt(N) & BigInt(N - 1)) === BigInt(0), "invalid scrypt N parameter", "options.N", N); + assertArgument(typeof r === "number" && r > 0 && Number.isSafeInteger(r), "invalid scrypt r parameter", "options.r", r); + assertArgument(typeof p === "number" && p > 0 && Number.isSafeInteger(p), "invalid scrypt p parameter", "options.p", p); + return { + name: "scrypt", + dkLen: 32, + salt: salt, + N: N, + r: r, + p: p + }; +} +function _encryptKeystore(key, kdf, account, options) { + const privateKey = getBytes(account.privateKey, "privateKey"); + const iv = options.iv != null ? getBytes(options.iv, "options.iv") : randomBytes(16); + assertArgument(iv.length === 16, "invalid options.iv length", "options.iv", options.iv); + const uuidRandom = options.uuid != null ? getBytes(options.uuid, "options.uuid") : randomBytes(16); + assertArgument(uuidRandom.length === 16, "invalid options.uuid length", "options.uuid", options.iv); + const derivedKey = key.slice(0, 16); + const macPrefix = key.slice(16, 32); + const aesCtr = new CTR(derivedKey, iv); + const ciphertext = getBytes(aesCtr.encrypt(privateKey)); + const mac = keccak256(concat([ + macPrefix, + ciphertext + ])); + const data = { + address: account.address.substring(2).toLowerCase(), + id: uuidV4(uuidRandom), + version: 3, + Crypto: { + cipher: "aes-128-ctr", + cipherparams: { + iv: hexlify(iv).substring(2) + }, + ciphertext: hexlify(ciphertext).substring(2), + kdf: "scrypt", + kdfparams: { + salt: hexlify(kdf.salt).substring(2), + n: kdf.N, + dklen: 32, + p: kdf.p, + r: kdf.r + }, + mac: mac.substring(2) } - return host + "?apiKey=" + apiKey; + }; + if (account.mnemonic) { + const client = options.client != null ? options.client : `ethers/${version}`; + const path = account.mnemonic.path || defaultPath$1; + const locale = account.mnemonic.locale || "en"; + const mnemonicKey = key.slice(32, 64); + const entropy = getBytes(account.mnemonic.entropy, "account.mnemonic.entropy"); + const mnemonicIv = randomBytes(16); + const mnemonicAesCtr = new CTR(mnemonicKey, mnemonicIv); + const mnemonicCiphertext = getBytes(mnemonicAesCtr.encrypt(entropy)); + const now = new Date; + const timestamp = now.getUTCFullYear() + "-" + zpad$1(now.getUTCMonth() + 1, 2) + "-" + zpad$1(now.getUTCDate(), 2) + "T" + zpad$1(now.getUTCHours(), 2) + "-" + zpad$1(now.getUTCMinutes(), 2) + "-" + zpad$1(now.getUTCSeconds(), 2) + ".0Z"; + const gethFilename = "UTC--" + timestamp + "--" + data.address; + data["x-ethers"] = { + client: client, + gethFilename: gethFilename, + path: path, + locale: locale, + mnemonicCounter: hexlify(mnemonicIv).substring(2), + mnemonicCiphertext: hexlify(mnemonicCiphertext).substring(2), + version: "0.1" + }; + } + return JSON.stringify(data); +} +function encryptKeystoreJsonSync(account, password, options) { + if (options == null) { + options = {}; } + const passwordBytes = getPassword(password); + const kdf = getEncryptKdfParams(options); + const key = scryptSync(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64); + return _encryptKeystore(getBytes(key), kdf, account, options); } -const logger$c = new Logger(version23); -const defaultApplicationId = "62e1ad51b37b8e00394bda3b"; -class PocketProvider extends UrlJsonRpcProvider { - static getApiKey(apiKey) { - const apiKeyObj = { - applicationId: null, - loadBalancer: true, - applicationSecretKey: null - }; - if (apiKey == null) { - apiKeyObj.applicationId = defaultApplicationId; - } else if (typeof apiKey === "string") { - apiKeyObj.applicationId = apiKey; - } else if (apiKey.applicationSecretKey != null) { - apiKeyObj.applicationId = apiKey.applicationId; - apiKeyObj.applicationSecretKey = apiKey.applicationSecretKey; - } else if (apiKey.applicationId) { - apiKeyObj.applicationId = apiKey.applicationId; - } else { - logger$c.throwArgumentError("unsupported PocketProvider apiKey", "apiKey", apiKey); - } - return apiKeyObj; +async function encryptKeystoreJson(account, password, options) { + if (options == null) { + options = {}; } - static getUrl(network, apiKey) { - let host = null; - switch(network ? network.name : "unknown"){ - case "goerli": - host = "eth-goerli.gateway.pokt.network"; - break; - case "homestead": - host = "eth-mainnet.gateway.pokt.network"; - break; - case "kovan": - host = "poa-kovan.gateway.pokt.network"; - break; - case "matic": - host = "poly-mainnet.gateway.pokt.network"; - break; - case "maticmum": - host = "polygon-mumbai-rpc.gateway.pokt.network"; - break; - case "rinkeby": - host = "eth-rinkeby.gateway.pokt.network"; - break; - case "ropsten": - host = "eth-ropsten.gateway.pokt.network"; - break; - default: - logger$c.throwError("unsupported network", Logger.errors.INVALID_ARGUMENT, { - argument: "network", - value: network - }); - } - const url = `https://${host}/v1/lb/${apiKey.applicationId}`; - const connection = { - headers: {}, - url - }; - if (apiKey.applicationSecretKey != null) { - connection.user = ""; - connection.password = apiKey.applicationSecretKey; - } - return connection; + const passwordBytes = getPassword(password); + const kdf = getEncryptKdfParams(options); + const key = await scrypt(passwordBytes, kdf.salt, kdf.N, kdf.r, kdf.p, 64, options.progressCallback); + return _encryptKeystore(getBytes(key), kdf, account, options); +} +const defaultPath = "m/44'/60'/0'/0/0"; +const MasterSecret = new Uint8Array([ + 66, + 105, + 116, + 99, + 111, + 105, + 110, + 32, + 115, + 101, + 101, + 100 +]); +const HardenedBit = 2147483648; +const N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"); +const Nibbles = "0123456789abcdef"; +function zpad(value, length) { + let result = ""; + while(value){ + result = Nibbles[value % 16] + result; + value = Math.trunc(value / 16); } - isCommunityResource() { - return this.applicationId === defaultApplicationId; + while(result.length < length * 2){ + result = "0" + result; } + return "0x" + result; } -const logger$d = new Logger(version23); -let _nextId = 1; -function buildWeb3LegacyFetcher(provider, sendFunc) { - const fetcher = "Web3LegacyFetcher"; - return function(method, params) { - const request = { - method, - params, - id: _nextId++, - jsonrpc: "2.0" - }; - return new Promise((resolve, reject)=>{ - this.emit("debug", { - action: "request", - fetcher, - request: deepCopy(request), - provider: this - }); - sendFunc(request, (error, response)=>{ - if (error) { - this.emit("debug", { - action: "response", - fetcher, - error, - request, - provider: this - }); - return reject(error); - } - this.emit("debug", { - action: "response", - fetcher, - request, - response, - provider: this - }); - if (response.error) { - const error2 = new Error(response.error.message); - error2.code = response.error.code; - error2.data = response.error.data; - return reject(error2); - } - resolve(response.result); - }); +function encodeBase58Check(_value) { + const value = getBytes(_value); + const check = dataSlice(sha256(sha256(value)), 0, 4); + const bytes = concat([ + value, + check + ]); + return encodeBase58(bytes); +} +const _guard = {}; +function ser_I(index, chainCode, publicKey, privateKey) { + const data = new Uint8Array(37); + if (index & 2147483648) { + assert1(privateKey != null, "cannot derive child of neutered node", "UNSUPPORTED_OPERATION", { + operation: "deriveChild" }); + data.set(getBytes(privateKey), 1); + } else { + data.set(getBytes(publicKey)); + } + for(let i = 24; i >= 0; i -= 8){ + data[33 + (i >> 3)] = index >> 24 - i & 255; + } + const I = getBytes(computeHmac("sha512", chainCode, data)); + return { + IL: I.slice(0, 32), + IR: I.slice(32) }; } -function buildEip1193Fetcher(provider) { - return function(method, params) { - if (params == null) { - params = []; +function derivePath(node, path) { + const components = path.split("/"); + assertArgument(components.length > 0, "invalid path", "path", path); + if (components[0] === "m") { + assertArgument(node.depth === 0, `cannot derive root path (i.e. path starting with "m/") for a node at non-zero depth ${node.depth}`, "path", path); + components.shift(); + } + let result = node; + for(let i = 0; i < components.length; i++){ + const component = components[i]; + if (component.match(/^[0-9]+'$/)) { + const index = parseInt(component.substring(0, component.length - 1)); + assertArgument(index < 2147483648, "invalid path index", `path[${i}]`, component); + result = result.deriveChild(HardenedBit + index); + } else if (component.match(/^[0-9]+$/)) { + const index = parseInt(component); + assertArgument(index < 2147483648, "invalid path index", `path[${i}]`, component); + result = result.deriveChild(index); + } else { + assertArgument(false, "invalid path component", `path[${i}]`, component); } - const request = { - method, - params - }; - this.emit("debug", { - action: "request", - fetcher: "Eip1193Fetcher", - request: deepCopy(request), - provider: this + } + return result; +} +class HDNodeWallet extends BaseWallet { + publicKey; + fingerprint; + parentFingerprint; + mnemonic; + chainCode; + path; + index; + depth; + constructor(guard, signingKey, parentFingerprint, chainCode, path, index, depth, mnemonic, provider){ + super(signingKey, provider); + assertPrivate(guard, _guard, "HDNodeWallet"); + defineProperties(this, { + publicKey: signingKey.compressedPublicKey }); - return provider.request(request).then((response)=>{ - this.emit("debug", { - action: "response", - fetcher: "Eip1193Fetcher", - request, - response, - provider: this - }); - return response; - }, (error)=>{ - this.emit("debug", { - action: "response", - fetcher: "Eip1193Fetcher", - request, - error, - provider: this - }); - throw error; + const fingerprint = dataSlice(ripemd160(sha256(this.publicKey)), 0, 4); + defineProperties(this, { + parentFingerprint: parentFingerprint, + fingerprint: fingerprint, + chainCode: chainCode, + path: path, + index: index, + depth: depth }); - }; -} -class Web3Provider extends JsonRpcProvider { - constructor(provider, network){ - if (provider == null) { - logger$d.throwArgumentError("missing provider", "provider", provider); - } - let path = null; - let jsonRpcFetchFunc = null; - let subprovider = null; - if (typeof provider === "function") { - path = "unknown:"; - jsonRpcFetchFunc = provider; - } else { - path = provider.host || provider.path || ""; - if (!path && provider.isMetaMask) { - path = "metamask"; - } - subprovider = provider; - if (provider.request) { - if (path === "") { - path = "eip-1193:"; - } - jsonRpcFetchFunc = buildEip1193Fetcher(provider); - } else if (provider.sendAsync) { - jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.sendAsync.bind(provider)); - } else if (provider.send) { - jsonRpcFetchFunc = buildWeb3LegacyFetcher(provider, provider.send.bind(provider)); - } else { - logger$d.throwArgumentError("unsupported provider", "provider", provider); - } - if (!path) { - path = "unknown:"; - } + defineProperties(this, { + mnemonic: mnemonic + }); + } + connect(provider) { + return new HDNodeWallet(_guard, this.signingKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.mnemonic, provider); + } + #account() { + const account = { + address: this.address, + privateKey: this.privateKey + }; + const m = this.mnemonic; + if (this.path && m && m.wordlist.locale === "en" && m.password === "") { + account.mnemonic = { + path: this.path, + locale: "en", + entropy: m.entropy + }; } - super(path, network); - defineReadOnly(this, "jsonRpcFetchFunc", jsonRpcFetchFunc); - defineReadOnly(this, "provider", subprovider); + return account; } - send(method, params) { - return this.jsonRpcFetchFunc(method, params); + async encrypt(password, progressCallback) { + return await encryptKeystoreJson(this.#account(), password, { + progressCallback: progressCallback + }); } -} -const logger$e = new Logger(version23); -function getDefaultProvider(network, options) { - if (network == null) { - network = "homestead"; + encryptSync(password) { + return encryptKeystoreJsonSync(this.#account(), password); } - if (typeof network === "string") { - const match = network.match(/^(ws|http)s?:/i); - if (match) { - switch(match[1].toLowerCase()){ - case "http": - case "https": - return new JsonRpcProvider(network); - case "ws": - case "wss": - return new WebSocketProvider(network); - default: - logger$e.throwArgumentError("unsupported URL scheme", "network", network); + get extendedKey() { + assert1(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { + operation: "extendedKey" + }); + return encodeBase58Check(concat([ + "0x0488ADE4", + zpad(this.depth, 1), + this.parentFingerprint, + zpad(this.index, 4), + this.chainCode, + concat([ + "0x00", + this.privateKey + ]) + ])); + } + hasPath() { + return this.path != null; + } + neuter() { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, this.provider); + } + deriveChild(_index) { + const index = getNumber(_index, "index"); + assertArgument(index <= 4294967295, "invalid index", "index", index); + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & 2147483648) { + path += "'"; } } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, this.privateKey); + const ki = new SigningKey(toBeHex((toBigInt(IL) + BigInt(this.privateKey)) % N, 32)); + return new HDNodeWallet(_guard, ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.mnemonic, this.provider); } - const n = getNetwork(network); - if (!n || !n._defaultProvider) { - logger$e.throwError("unsupported getDefaultProvider network", Logger.errors.NETWORK_ERROR, { - operation: "getDefaultProvider", - network - }); + derivePath(path) { + return derivePath(this, path); } - return n._defaultProvider({ - FallbackProvider, - AlchemyProvider, - AnkrProvider, - CloudflareProvider, - EtherscanProvider, - InfuraProvider, - JsonRpcProvider, - NodesmithProvider, - PocketProvider, - Web3Provider, - IpcProvider: null - }, options); -} -const mod3 = function() { - return { - Provider: Provider, - getNetwork: getNetwork, - AlchemyProvider: AlchemyProvider, - AlchemyWebSocketProvider: AlchemyWebSocketProvider, - AnkrProvider: AnkrProvider, - BaseProvider: BaseProvider, - CloudflareProvider: CloudflareProvider, - EtherscanProvider: EtherscanProvider, - FallbackProvider: FallbackProvider, - Formatter: Formatter, - InfuraProvider: InfuraProvider, - InfuraWebSocketProvider: InfuraWebSocketProvider, - IpcProvider: null, - JsonRpcBatchProvider: JsonRpcBatchProvider, - JsonRpcProvider: JsonRpcProvider, - JsonRpcSigner: JsonRpcSigner, - NodesmithProvider: NodesmithProvider, - PocketProvider: PocketProvider, - Resolver: Resolver, - StaticJsonRpcProvider: StaticJsonRpcProvider, - UrlJsonRpcProvider: UrlJsonRpcProvider, - Web3Provider: Web3Provider, - WebSocketProvider: WebSocketProvider, - getDefaultProvider: getDefaultProvider, - isCommunityResourcable: isCommunityResourcable, - isCommunityResource: isCommunityResource, - showThrottleMessage: showThrottleMessage, - default: null - }; -}(); -const version24 = "solidity/5.7.0"; -const regexBytes = new RegExp("^bytes([0-9]+)$"); -const regexNumber = new RegExp("^(u?int)([0-9]*)$"); -const regexArray = new RegExp("^(.*)\\[([0-9]*)\\]$"); -const Zeros1 = "0000000000000000000000000000000000000000000000000000000000000000"; -const logger222 = new Logger(version24); -function _pack(type, value, isArray) { - switch(type){ - case "address": - if (isArray) { - return zeroPad(value, 32); - } - return arrayify(value); - case "string": - return toUtf8Bytes(value); - case "bytes": - return arrayify(value); - case "bool": - value = value ? "0x01" : "0x00"; - if (isArray) { - return zeroPad(value, 32); - } - return arrayify(value); + static #fromSeed(_seed, mnemonic) { + assertArgument(isBytesLike(_seed), "invalid seed", "seed", "[REDACTED]"); + const seed = getBytes(_seed, "seed"); + assertArgument(seed.length >= 16 && seed.length <= 64, "invalid seed", "seed", "[REDACTED]"); + const I = getBytes(computeHmac("sha512", MasterSecret, seed)); + const signingKey = new SigningKey(hexlify(I.slice(0, 32))); + return new HDNodeWallet(_guard, signingKey, "0x00000000", hexlify(I.slice(32)), "m", 0, 0, mnemonic, null); } - let match = type.match(regexNumber); - if (match) { - let size = parseInt(match[2] || "256"); - if (match[2] && String(size) !== match[2] || size % 8 !== 0 || size === 0 || size > 256) { - logger222.throwArgumentError("invalid number type", "type", type); - } - if (isArray) { - size = 256; + static fromExtendedKey(extendedKey) { + const bytes = toBeArray(decodeBase58(extendedKey)); + assertArgument(bytes.length === 82 || encodeBase58Check(bytes.slice(0, 78)) === extendedKey, "invalid extended key", "extendedKey", "[ REDACTED ]"); + const depth = bytes[4]; + const parentFingerprint = hexlify(bytes.slice(5, 9)); + const index = parseInt(hexlify(bytes.slice(9, 13)).substring(2), 16); + const chainCode = hexlify(bytes.slice(13, 45)); + const key = bytes.slice(45, 78); + switch(hexlify(bytes.slice(0, 4))){ + case "0x0488b21e": + case "0x043587cf": + { + const publicKey = hexlify(key); + return new HDNodeVoidWallet(_guard, computeAddress(publicKey), publicKey, parentFingerprint, chainCode, null, index, depth, null); + } + case "0x0488ade4": + case "0x04358394 ": + if (key[0] !== 0) { + break; + } + return new HDNodeWallet(_guard, new SigningKey(key.slice(1)), parentFingerprint, chainCode, null, index, depth, null, null); } - value = BigNumber.from(value).toTwos(size); - return zeroPad(value, size / 8); + assertArgument(false, "invalid extended key prefix", "extendedKey", "[ REDACTED ]"); } - match = type.match(regexBytes); - if (match) { - const size = parseInt(match[1]); - if (String(size) !== match[1] || size === 0 || size > 32) { - logger222.throwArgumentError("invalid bytes type", "type", type); + static createRandom(password, path, wordlist) { + if (password == null) { + password = ""; } - if (arrayify(value).byteLength !== size) { - logger222.throwArgumentError(`invalid value for ${type}`, "value", value); + if (path == null) { + path = defaultPath; } - if (isArray) { - return arrayify((value + Zeros1).substring(0, 66)); + if (wordlist == null) { + wordlist = LangEn.wordlist(); } - return value; + const mnemonic = Mnemonic.fromEntropy(randomBytes(16), password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); } - match = type.match(regexArray); - if (match && Array.isArray(value)) { - const baseType = match[1]; - const count = parseInt(match[2] || String(value.length)); - if (count != value.length) { - logger222.throwArgumentError(`invalid array length for ${type}`, "value", value); + static fromMnemonic(mnemonic, path) { + if (!path) { + path = defaultPath; } - const result = []; - value.forEach(function(value2) { - result.push(_pack(baseType, value2, true)); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + static fromPhrase(phrase, password, path, wordlist) { + if (password == null) { + password = ""; + } + if (path == null) { + path = defaultPath; + } + if (wordlist == null) { + wordlist = LangEn.wordlist(); + } + const mnemonic = Mnemonic.fromPhrase(phrase, password, wordlist); + return HDNodeWallet.#fromSeed(mnemonic.computeSeed(), mnemonic).derivePath(path); + } + static fromSeed(seed) { + return HDNodeWallet.#fromSeed(seed, null); + } +} +class HDNodeVoidWallet extends VoidSigner { + publicKey; + fingerprint; + parentFingerprint; + chainCode; + path; + index; + depth; + constructor(guard, address, publicKey, parentFingerprint, chainCode, path, index, depth, provider){ + super(address, provider); + assertPrivate(guard, _guard, "HDNodeVoidWallet"); + defineProperties(this, { + publicKey: publicKey + }); + const fingerprint = dataSlice(ripemd160(sha256(publicKey)), 0, 4); + defineProperties(this, { + publicKey: publicKey, + fingerprint: fingerprint, + parentFingerprint: parentFingerprint, + chainCode: chainCode, + path: path, + index: index, + depth: depth }); - return concat(result); } - return logger222.throwArgumentError("invalid type", "type", type); -} -function pack1(types, values) { - if (types.length != values.length) { - logger222.throwArgumentError("wrong number of values; expected ${ types.length }", "values", values); + connect(provider) { + return new HDNodeVoidWallet(_guard, this.address, this.publicKey, this.parentFingerprint, this.chainCode, this.path, this.index, this.depth, provider); + } + get extendedKey() { + assert1(this.depth < 256, "Depth too deep", "UNSUPPORTED_OPERATION", { + operation: "extendedKey" + }); + return encodeBase58Check(concat([ + "0x0488B21E", + zpad(this.depth, 1), + this.parentFingerprint, + zpad(this.index, 4), + this.chainCode, + this.publicKey + ])); + } + hasPath() { + return this.path != null; + } + deriveChild(_index) { + const index = getNumber(_index, "index"); + assertArgument(index <= 4294967295, "invalid index", "index", index); + let path = this.path; + if (path) { + path += "/" + (index & ~HardenedBit); + if (index & 2147483648) { + path += "'"; + } + } + const { IR, IL } = ser_I(index, this.chainCode, this.publicKey, null); + const Ki = SigningKey.addPoints(IL, this.publicKey, true); + const address = computeAddress(Ki); + return new HDNodeVoidWallet(_guard, address, Ki, this.fingerprint, hexlify(IR), path, index, this.depth + 1, this.provider); + } + derivePath(path) { + return derivePath(this, path); } - const tight = []; - types.forEach(function(type, index) { - tight.push(_pack(type, values[index])); - }); - return hexlify(concat(tight)); } -function keccak2562(types, values) { - return keccak256(pack1(types, values)); +function getAccountPath(_index) { + const index = getNumber(_index, "index"); + assertArgument(index >= 0 && index < 2147483648, "invalid account index", "index", index); + return `m/44'/60'/${index}'/0/0`; } -function sha2562(types, values) { - return sha2561(pack1(types, values)); +function getIndexedAccountPath(_index) { + const index = getNumber(_index, "index"); + assertArgument(index >= 0 && index < 2147483648, "invalid account index", "index", index); + return `m/44'/60'/0'/0/${index}`; } -const version25 = "units/5.7.0"; -const logger223 = new Logger(version25); -const names = [ - "wei", - "kwei", - "mwei", - "gwei", - "szabo", - "finney", - "ether" -]; -function commify(value) { - const comps = String(value).split("."); - if (comps.length > 2 || !comps[0].match(/^-?[0-9]*$/) || comps[1] && !comps[1].match(/^[0-9]*$/) || value === "." || value === "-.") { - logger223.throwArgumentError("invalid value", "value", value); +function isCrowdsaleJson(json) { + try { + const data = JSON.parse(json); + if (data.encseed) { + return true; + } + } catch (error) {} + return false; +} +function decryptCrowdsaleJson(json, _password) { + const data = JSON.parse(json); + const password = getPassword(_password); + const address = getAddress(spelunk(data, "ethaddr:string!")); + const encseed = looseArrayify(spelunk(data, "encseed:string!")); + assertArgument(encseed && encseed.length % 16 === 0, "invalid encseed", "json", json); + const key = getBytes(pbkdf2(password, password, 2e3, 32, "sha256")).slice(0, 16); + const iv = encseed.slice(0, 16); + const encryptedSeed = encseed.slice(16); + const aesCbc = new CBC(key, iv); + const seed = pkcs7Strip(getBytes(aesCbc.decrypt(encryptedSeed))); + let seedHex = ""; + for(let i = 0; i < seed.length; i++){ + seedHex += String.fromCharCode(seed[i]); + } + return { + address: address, + privateKey: id(seedHex) + }; +} +function stall(duration) { + return new Promise((resolve)=>{ + setTimeout(()=>{ + resolve(); + }, duration); + }); +} +class Wallet extends BaseWallet { + constructor(key, provider){ + if (typeof key === "string" && !key.startsWith("0x")) { + key = "0x" + key; + } + let signingKey = typeof key === "string" ? new SigningKey(key) : key; + super(signingKey, provider); } - let whole = comps[0]; - let negative = ""; - if (whole.substring(0, 1) === "-") { - negative = "-"; - whole = whole.substring(1); + connect(provider) { + return new Wallet(this.signingKey, provider); } - while(whole.substring(0, 1) === "0"){ - whole = whole.substring(1); + async encrypt(password, progressCallback) { + const account = { + address: this.address, + privateKey: this.privateKey + }; + return await encryptKeystoreJson(account, password, { + progressCallback: progressCallback + }); } - if (whole === "") { - whole = "0"; + encryptSync(password) { + const account = { + address: this.address, + privateKey: this.privateKey + }; + return encryptKeystoreJsonSync(account, password); } - let suffix = ""; - if (comps.length === 2) { - suffix = "." + (comps[1] || "0"); + static #fromAccount(account) { + assertArgument(account, "invalid JSON wallet", "json", "[ REDACTED ]"); + if ("mnemonic" in account && account.mnemonic && account.mnemonic.locale === "en") { + const mnemonic = Mnemonic.fromEntropy(account.mnemonic.entropy); + const wallet = HDNodeWallet.fromMnemonic(mnemonic, account.mnemonic.path); + if (wallet.address === account.address && wallet.privateKey === account.privateKey) { + return wallet; + } + console.log("WARNING: JSON mismatch address/privateKey != mnemonic; fallback onto private key"); + } + const wallet = new Wallet(account.privateKey); + assertArgument(wallet.address === account.address, "address/privateKey mismatch", "json", "[ REDACTED ]"); + return wallet; } - while(suffix.length > 2 && suffix[suffix.length - 1] === "0"){ - suffix = suffix.substring(0, suffix.length - 1); + static async fromEncryptedJson(json, password, progress) { + let account = null; + if (isKeystoreJson(json)) { + account = await decryptKeystoreJson(json, password, progress); + } else if (isCrowdsaleJson(json)) { + if (progress) { + progress(0); + await stall(0); + } + account = decryptCrowdsaleJson(json, password); + if (progress) { + progress(1); + await stall(0); + } + } + return Wallet.#fromAccount(account); } - const formatted = []; - while(whole.length){ - if (whole.length <= 3) { - formatted.unshift(whole); - break; + static fromEncryptedJsonSync(json, password) { + let account = null; + if (isKeystoreJson(json)) { + account = decryptKeystoreJsonSync(json, password); + } else if (isCrowdsaleJson(json)) { + account = decryptCrowdsaleJson(json, password); } else { - const index = whole.length - 3; - formatted.unshift(whole.substring(index)); - whole = whole.substring(0, index); + assertArgument(false, "invalid JSON wallet", "json", "[ REDACTED ]"); } + return Wallet.#fromAccount(account); } - return negative + formatted.join(",") + suffix; -} -function formatUnits(value, unitName) { - if (typeof unitName === "string") { - const index = names.indexOf(unitName); - if (index !== -1) { - unitName = 3 * index; + static createRandom(provider) { + const wallet = HDNodeWallet.createRandom(); + if (provider) { + return wallet.connect(provider); } + return wallet; } - return formatFixed(value, unitName != null ? unitName : 18); -} -function parseUnits(value, unitName) { - if (typeof value !== "string") { - logger223.throwArgumentError("value must be a string", "value", value); + static fromPhrase(phrase, provider) { + const wallet = HDNodeWallet.fromPhrase(phrase); + if (provider) { + return wallet.connect(provider); + } + return wallet; } - if (typeof unitName === "string") { - const index = names.indexOf(unitName); - if (index !== -1) { - unitName = 3 * index; +} +const Base64 = ")!@#$%^&*(ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_"; +function decodeBits(width, data) { + const maxValue = (1 << width) - 1; + const result = []; + let accum = 0, bits = 0, flood = 0; + for(let i = 0; i < data.length; i++){ + accum = accum << 6 | Base64.indexOf(data[i]); + bits += 6; + while(bits >= width){ + const value = accum >> bits - width; + accum &= (1 << bits - width) - 1; + bits -= width; + if (value === 0) { + flood += maxValue; + } else { + result.push(value + flood); + flood = 0; + } } } - return parseFixed(value, unitName != null ? unitName : 18); + return result; } -function formatEther(wei) { - return formatUnits(wei, 18); +function decodeOwlA(data, accents) { + let words = decodeOwl(data).join(","); + accents.split(/,/g).forEach((accent)=>{ + const match = accent.match(/^([a-z]*)([0-9]+)([0-9])(.*)$/); + assertArgument(match !== null, "internal error parsing accents", "accents", accents); + let posOffset = 0; + const positions = decodeBits(parseInt(match[3]), match[4]); + const charCode = parseInt(match[2]); + const regex = new RegExp(`([${match[1]}])`, "g"); + words = words.replace(regex, (all, letter)=>{ + const rem = --positions[posOffset]; + if (rem === 0) { + letter = String.fromCharCode(letter.charCodeAt(0), charCode); + posOffset++; + } + return letter; + }); + }); + return words.split(","); } -function parseEther(ether) { - return parseUnits(ether, 18); +class WordlistOwlA extends WordlistOwl { + #accent; + constructor(locale, data, accent, checksum){ + super(locale, data, checksum); + this.#accent = accent; + } + get _accent() { + return this.#accent; + } + _decodeWords() { + return decodeOwlA(this._data, this._accent); + } } -var utils1 = Object.freeze({ - __proto__: null, - AbiCoder, - defaultAbiCoder, - Fragment, - ConstructorFragment, - ErrorFragment, - EventFragment, - FunctionFragment, - ParamType, - FormatTypes, - checkResultErrors, - Logger, - RLP: mod, - _fetchData, - fetchJson, - poll, - checkProperties, - deepCopy, - defineReadOnly, - getStatic, - resolveProperties, - shallowCopy, - arrayify, - concat, - stripZeros, - zeroPad, - isBytes, - isBytesLike, - defaultPath, - HDNode, - SigningKey, - Interface, - LogDescription, - TransactionDescription, - base58: Base58, - base64: mod2, - hexlify, - isHexString, - hexConcat, - hexStripZeros, - hexValue, - hexZeroPad, - hexDataLength, - hexDataSlice, - nameprep, - _toEscapedUtf8String, - toUtf8Bytes, - toUtf8CodePoints, - toUtf8String, - Utf8ErrorFuncs, - formatBytes32String, - parseBytes32String, - dnsEncode, - hashMessage, - namehash, - isValidName, - id, - _TypedDataEncoder: TypedDataEncoder, - getAddress, - getIcapAddress, - getContractAddress, - getCreate2Address, - isAddress, - formatEther, - parseEther, - formatUnits, - parseUnits, - commify, - computeHmac, - keccak256: keccak256, - ripemd160: ripemd1601, - sha256: sha2561, - sha512: sha5121, - randomBytes, - shuffled, - solidityPack: pack1, - solidityKeccak256: keccak2562, - soliditySha256: sha2562, - splitSignature, - joinSignature, - accessListify, - parseTransaction: parse, - serializeTransaction: serialize, - TransactionTypes, - getJsonWalletAddress, - computeAddress, - recoverAddress, - computePublicKey, - recoverPublicKey, - verifyMessage, - verifyTypedData, - getAccountPath, - mnemonicToEntropy, - entropyToMnemonic, - isValidMnemonic, - mnemonicToSeed, - SupportedAlgorithm, - UnicodeNormalizationForm, - Utf8ErrorReason, - Indexed -}); -const version26 = "ethers/5.7.2"; -const logger3 = new Logger(version26); +const wordlists = { + en: LangEn.wordlist() +}; var ethers = Object.freeze({ __proto__: null, - Signer, - Wallet, - VoidSigner, - getDefaultProvider, - providers: mod3, - BaseContract, - Contract, - ContractFactory, - BigNumber, - FixedNumber, - constants: mod1, - errors: ErrorCode, - logger: logger3, - utils: utils1, + AbiCoder: AbiCoder, + AbstractProvider: AbstractProvider, + AbstractSigner: AbstractSigner, + AlchemyProvider: AlchemyProvider, + AnkrProvider: AnkrProvider, + BaseContract: BaseContract, + BaseWallet: BaseWallet, + Block: Block, + BrowserProvider: BrowserProvider, + ChainstackProvider: ChainstackProvider, + CloudflareProvider: CloudflareProvider, + ConstructorFragment: ConstructorFragment, + Contract: Contract, + ContractEventPayload: ContractEventPayload, + ContractFactory: ContractFactory, + ContractTransactionReceipt: ContractTransactionReceipt, + ContractTransactionResponse: ContractTransactionResponse, + ContractUnknownEventPayload: ContractUnknownEventPayload, + EnsPlugin: EnsPlugin, + EnsResolver: EnsResolver, + ErrorDescription: ErrorDescription, + ErrorFragment: ErrorFragment, + EtherSymbol: EtherSymbol, + EtherscanPlugin: EtherscanPlugin, + EtherscanProvider: EtherscanProvider, + EventFragment: EventFragment, + EventLog: EventLog, + EventPayload: EventPayload, + FallbackFragment: FallbackFragment, + FallbackProvider: FallbackProvider, + FeeData: FeeData, + FeeDataNetworkPlugin: FeeDataNetworkPlugin, + FetchCancelSignal: FetchCancelSignal, + FetchRequest: FetchRequest, + FetchResponse: FetchResponse, + FetchUrlFeeDataNetworkPlugin: FetchUrlFeeDataNetworkPlugin, + FixedNumber: FixedNumber, + Fragment: Fragment, + FunctionFragment: FunctionFragment, + GasCostPlugin: GasCostPlugin, + HDNodeVoidWallet: HDNodeVoidWallet, + HDNodeWallet: HDNodeWallet, + Indexed: Indexed, + InfuraProvider: InfuraProvider, + InfuraWebSocketProvider: InfuraWebSocketProvider, + Interface: Interface, + IpcSocketProvider: IpcSocketProvider, + JsonRpcApiProvider: JsonRpcApiProvider, + JsonRpcProvider: JsonRpcProvider, + JsonRpcSigner: JsonRpcSigner, + LangEn: LangEn, + Log: Log, + LogDescription: LogDescription, + MaxInt256: MaxInt256, + MaxUint256: MaxUint256, + MessagePrefix: MessagePrefix, + MinInt256: MinInt256, + Mnemonic: Mnemonic, + MulticoinProviderPlugin: MulticoinProviderPlugin, + N: N$1, + NamedFragment: NamedFragment, + Network: Network, + NetworkPlugin: NetworkPlugin, + NonceManager: NonceManager, + ParamType: ParamType, + PocketProvider: PocketProvider, + QuickNodeProvider: QuickNodeProvider, + Result: Result, + Signature: Signature, + SigningKey: SigningKey, + SocketBlockSubscriber: SocketBlockSubscriber, + SocketEventSubscriber: SocketEventSubscriber, + SocketPendingSubscriber: SocketPendingSubscriber, + SocketProvider: SocketProvider, + SocketSubscriber: SocketSubscriber, + StructFragment: StructFragment, + Transaction: Transaction, + TransactionDescription: TransactionDescription, + TransactionReceipt: TransactionReceipt, + TransactionResponse: TransactionResponse, + Typed: Typed, + TypedDataEncoder: TypedDataEncoder, + UndecodedEventLog: UndecodedEventLog, + UnmanagedSubscriber: UnmanagedSubscriber, + Utf8ErrorFuncs: Utf8ErrorFuncs, + VoidSigner: VoidSigner, + Wallet: Wallet, + WebSocketProvider: WebSocketProvider, + WeiPerEther: WeiPerEther, + Wordlist: Wordlist, + WordlistOwl: WordlistOwl, + WordlistOwlA: WordlistOwlA, + ZeroAddress: ZeroAddress, + ZeroHash: ZeroHash, + accessListify: accessListify, + assert: assert1, + assertArgument: assertArgument, + assertArgumentCount: assertArgumentCount, + assertNormalize: assertNormalize, + assertPrivate: assertPrivate, + checkResultErrors: checkResultErrors, + computeAddress: computeAddress, + computeHmac: computeHmac, + concat: concat, + copyRequest: copyRequest, + dataLength: dataLength, + dataSlice: dataSlice, + decodeBase58: decodeBase58, + decodeBase64: decodeBase641, + decodeBytes32String: decodeBytes32String, + decodeRlp: decodeRlp, + decryptCrowdsaleJson: decryptCrowdsaleJson, + decryptKeystoreJson: decryptKeystoreJson, + decryptKeystoreJsonSync: decryptKeystoreJsonSync, + defaultPath: defaultPath, + defineProperties: defineProperties, + dnsEncode: dnsEncode, + encodeBase58: encodeBase58, + encodeBase64: encodeBase64, + encodeBytes32String: encodeBytes32String, + encodeRlp: encodeRlp, + encryptKeystoreJson: encryptKeystoreJson, + encryptKeystoreJsonSync: encryptKeystoreJsonSync, + ensNormalize: ensNormalize, + formatEther: formatEther, + formatUnits: formatUnits, + fromTwos: fromTwos, + getAccountPath: getAccountPath, + getAddress: getAddress, + getBigInt: getBigInt, + getBytes: getBytes, + getBytesCopy: getBytesCopy, + getCreate2Address: getCreate2Address, + getCreateAddress: getCreateAddress, + getDefaultProvider: getDefaultProvider, + getIcapAddress: getIcapAddress, + getIndexedAccountPath: getIndexedAccountPath, + getNumber: getNumber, + getUint: getUint, + hashMessage: hashMessage, + hexlify: hexlify, + id: id, + isAddress: isAddress, + isAddressable: isAddressable, + isBytesLike: isBytesLike, + isCallException: isCallException, + isCrowdsaleJson: isCrowdsaleJson, + isError: isError, + isHexString: isHexString, + isKeystoreJson: isKeystoreJson, + isValidName: isValidName, + keccak256: keccak256, + lock: lock, + makeError: makeError, + mask: mask, + namehash: namehash, + parseEther: parseEther, + parseUnits: parseUnits$1, + pbkdf2: pbkdf2, + randomBytes: randomBytes, + recoverAddress: recoverAddress, + resolveAddress: resolveAddress, + resolveProperties: resolveProperties, + ripemd160: ripemd160, + scrypt: scrypt, + scryptSync: scryptSync, + sha256: sha256, + sha512: sha512, + showThrottleMessage: showThrottleMessage, + solidityPacked: solidityPacked, + solidityPackedKeccak256: solidityPackedKeccak256, + solidityPackedSha256: solidityPackedSha256, + stripZerosLeft: stripZerosLeft, + toBeArray: toBeArray, + toBeHex: toBeHex, + toBigInt: toBigInt, + toNumber: toNumber, + toQuantity: toQuantity, + toTwos: toTwos, + toUtf8Bytes: toUtf8Bytes, + toUtf8CodePoints: toUtf8CodePoints, + toUtf8String: toUtf8String, + uuidV4: uuidV4, + verifyMessage: verifyMessage, + verifyTypedData: verifyTypedData, + version: version, wordlists: wordlists, - version: version26, - Wordlist + zeroPadBytes: zeroPadBytes, + zeroPadValue: zeroPadValue }); -try { - const anyGlobal = window; - if (anyGlobal._ethers == null) { - anyGlobal._ethers = ethers; - } -} catch (error) {} const typeofs = [ "string", "number", @@ -26322,15 +23748,15 @@ function asU8A(buf2) { } return isBuffer$1(buf2) ? new Uint8Array(buf2.buffer, buf2.byteOffset, buf2.byteLength) : buf2; } -const toString = useBuffer ? (bytes, start, end)=>{ +const toString1 = useBuffer ? (bytes, start, end)=>{ return end - start > 64 ? globalThis.Buffer.from(bytes.subarray(start, end)).toString("utf8") : utf8Slice(bytes, start, end); } : (bytes, start, end)=>{ return end - start > 64 ? textDecoder1.decode(bytes.subarray(start, end)) : utf8Slice(bytes, start, end); }; const fromString = useBuffer ? (string)=>{ - return string.length > 64 ? globalThis.Buffer.from(string) : utf8ToBytes(string); + return string.length > 64 ? globalThis.Buffer.from(string) : utf8ToBytes1(string); } : (string)=>{ - return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes(string); + return string.length > 64 ? textEncoder.encode(string) : utf8ToBytes1(string); }; const fromArray = (arr)=>{ return Uint8Array.from(arr); @@ -26375,7 +23801,7 @@ function compare(b1, b2) { } return 0; } -function utf8ToBytes(str) { +function utf8ToBytes1(str) { const out = []; let p = 0; for(let i = 0; i < str.length; i++){ @@ -26794,7 +24220,7 @@ function compareBytes(b1, b2) { function toToken$1(data, pos, prefix, length, options) { const totLength = prefix + length; assertEnoughData(data, pos, totLength); - const tok = new Token(Type.string, toString(data, pos + prefix, pos + totLength), totLength); + const tok = new Token(Type.string, toString1(data, pos + prefix, pos + totLength), totLength); if (options.retainStringBytes === true) { tok.byteValue = slice(data, pos + prefix, pos + totLength); } @@ -27480,7 +24906,7 @@ function encodeCustom(data, encoders, options) { tokensToEncoded(buf, tokens, encoders, options); return buf.toBytes(true); } -function encode3(data, options) { +function encode(data, options) { options = Object.assign({}, defaultEncodeOptions, options); return encodeCustom(data, cborEncoders, options); } @@ -27615,20 +25041,20 @@ function decodeFirst(data, options) { data.subarray(tokeniser.pos()) ]; } -function decode4(data, options) { +function decode2(data, options) { const [decoded, remainder] = decodeFirst(data, options); if (remainder.length > 0) { throw new Error(`${decodeErrPrefix} too many terminals, data makes no sense`); } return decoded; } -const empty = new Uint8Array(0); -function toHex2(d) { +const empty1 = new Uint8Array(0); +function toHex(d) { return d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); } function fromHex(hex) { const hexes = hex.match(/../g); - return hexes != null ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty; + return hexes != null ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty1; } function equals(aa, bb) { if (aa === bb) return true; @@ -27656,19 +25082,19 @@ function isBinary(o) { function fromString1(str) { return new TextEncoder().encode(str); } -function toString1(b) { +function toString2(b) { return new TextDecoder().decode(b); } Object.freeze({ __proto__: null, - empty, - toHex: toHex2, + empty: empty1, + toHex, fromHex, equals, coerce, isBinary, fromString: fromString1, - toString: toString1 + toString: toString2 }); var __defProp = Object.defineProperty; var __publicField = (obj, key, value)=>{ @@ -27681,7 +25107,7 @@ var __publicField = (obj, key, value)=>{ }); return obj[key] = value; }; -function base1(ALPHABET, name) { +function base(ALPHABET, name) { if (ALPHABET.length >= 255) { throw new TypeError("Alphabet too long"); } @@ -27811,7 +25237,7 @@ function base1(ALPHABET, name) { decode: decode2 }; } -var src = base1; +var src = base; var _brrp__multiformats_scope_baseX = src; class Encoder { constructor(name, prefix, baseEncode){ @@ -27921,7 +25347,7 @@ function baseX({ name, prefix, alphabet }) { decode: (text)=>coerce(decode2(text)) }); } -function decode5(string, alphabet, bitsPerChar, name) { +function decode3(string, alphabet, bitsPerChar, name) { const codes = {}; for(let i = 0; i < alphabet.length; ++i){ codes[alphabet[i]] = i; @@ -27951,7 +25377,7 @@ function decode5(string, alphabet, bitsPerChar, name) { } return out; } -function encode4(data, alphabet, bitsPerChar) { +function encode1(data, alphabet, bitsPerChar) { const pad = alphabet[alphabet.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; @@ -27980,10 +25406,10 @@ function rfc4648({ name, prefix, bitsPerChar, alphabet }) { prefix, name, encode (input) { - return encode4(input, alphabet, bitsPerChar); + return encode1(input, alphabet, bitsPerChar); }, decode (input) { - return decode5(input, alphabet, bitsPerChar, name); + return decode3(input, alphabet, bitsPerChar, name); } }); } @@ -28079,9 +25505,9 @@ var __publicField1 = (obj, key, value)=>{ }); return obj[key] = value; }; -var encode_1 = encode5; +var encode_1 = encode2; var MSB = 128, REST1 = 127, MSBALL = ~REST1, INT = Math.pow(2, 31); -function encode5(num, out, offset) { +function encode2(num, out, offset) { out = out || []; offset = offset || 0; var oldOffset = offset; @@ -28094,10 +25520,10 @@ function encode5(num, out, offset) { num >>>= 7; } out[offset] = num | 0; - encode5.bytes = offset - oldOffset + 1; + encode2.bytes = offset - oldOffset + 1; return out; } -var decode6 = read; +var decode4 = read; var MSB$1 = 128, REST$1 = 127; function read(buf, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; @@ -28127,7 +25553,7 @@ var length = function(value) { }; var varint = { encode: encode_1, - decode: decode6, + decode: decode4, encodingLength: length }; var _brrp_varint = varint; @@ -28574,13 +26000,13 @@ _decodeOptions.tags[CID_CBOR_TAG] = cidDecoder; ..._decodeOptions, tags: _decodeOptions.tags.slice() }); -const encode6 = (node)=>encode3(node, _encodeOptions); -const decode7 = (data)=>decode4(toByteView(data), _decodeOptions); -var encode_11 = encode7; +const encode3 = (node)=>encode(node, _encodeOptions); +const decode5 = (data)=>decode2(toByteView(data), _decodeOptions); +var encode_11 = encode4; var MSB1 = 128, REST2 = 127, MSBALL1 = ~REST2, INT1 = Math.pow(2, 31); -function encode7(num, out, offset) { +function encode4(num, out, offset) { if (Number.MAX_SAFE_INTEGER && num > Number.MAX_SAFE_INTEGER) { - encode7.bytes = 0; + encode4.bytes = 0; throw new RangeError("Could not encode varint"); } out = out || []; @@ -28595,10 +26021,10 @@ function encode7(num, out, offset) { num >>>= 7; } out[offset] = num | 0; - encode7.bytes = offset - oldOffset + 1; + encode4.bytes = offset - oldOffset + 1; return out; } -var decode8 = read1; +var decode6 = read1; var MSB$11 = 128, REST$11 = 127; function read1(buf, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; @@ -28628,7 +26054,7 @@ var length1 = function(value) { }; var varint1 = { encode: encode_11, - decode: decode8, + decode: decode6, encodingLength: length1 }; varint1.encode; @@ -28876,7 +26302,7 @@ async function readHeader(reader, strictVersion) { throw new Error("Invalid CAR header (zero length)"); } const header = await reader.exactly(length, true); - const block = decode7(header); + const block = decode5(header); if (CarV1HeaderOrV2Pragma.toTyped(block) === void 0) { throw new Error("Invalid CAR header format"); } @@ -29158,7 +26584,7 @@ const addBlock = (writer, { cid, bytes })=>{ const close = (writer, options = {})=>{ const { resize = false } = options; const { roots, bytes, byteOffset, headerSize } = writer; - const headerBytes = encode6({ + const headerBytes = encode3({ version: 1, roots }); @@ -29364,11 +26790,11 @@ class CarWriterOut { return this._iterator; } } -const empty1 = new Uint8Array(0); -const toHex3 = (d)=>d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); +const empty2 = new Uint8Array(0); +const toHex1 = (d)=>d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); const fromHex1 = (hex)=>{ const hexes = hex.match(/../g); - return hexes ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty1; + return hexes ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty2; }; const equals2 = (aa, bb)=>{ if (aa === bb) return true; @@ -29392,21 +26818,21 @@ const coerce1 = (o)=>{ }; const isBinary1 = (o)=>o instanceof ArrayBuffer || ArrayBuffer.isView(o); const fromString2 = (str)=>new TextEncoder().encode(str); -const toString2 = (b)=>new TextDecoder().decode(b); -var bytes = Object.freeze({ +const toString3 = (b)=>new TextDecoder().decode(b); +var bytes1 = Object.freeze({ __proto__: null, equals: equals2, coerce: coerce1, isBinary: isBinary1, fromHex: fromHex1, - toHex: toHex3, + toHex: toHex1, fromString: fromString2, - toString: toString2, - empty: empty1 + toString: toString3, + empty: empty2 }); -var encode_12 = encode8; +var encode_12 = encode5; var MSB2 = 128, REST3 = 127, MSBALL2 = ~REST3, INT2 = Math.pow(2, 31); -function encode8(num, out, offset) { +function encode5(num, out, offset) { out = out || []; offset = offset || 0; var oldOffset = offset; @@ -29419,10 +26845,10 @@ function encode8(num, out, offset) { num >>>= 7; } out[offset] = num | 0; - encode8.bytes = offset - oldOffset + 1; + encode5.bytes = offset - oldOffset + 1; return out; } -var decode9 = read2; +var decode7 = read2; var MSB$12 = 128, REST$12 = 127; function read2(buf, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; @@ -29452,7 +26878,7 @@ var length2 = function(value) { }; var varint2 = { encode: encode_12, - decode: decode9, + decode: decode7, encodingLength: length2 }; var _brrp_varint1 = varint2; @@ -29539,27 +26965,27 @@ Object.freeze({ from: from1, Hasher }); -const sha2 = (name)=>async (data)=>new Uint8Array(await crypto.subtle.digest(name, data)); -const sha2563 = from1({ +const sha = (name)=>async (data)=>new Uint8Array(await crypto.subtle.digest(name, data)); +const sha2561 = from1({ name: "sha2-256", code: 18, - encode: sha2("SHA-256") + encode: sha("SHA-256") }); -const sha5122 = from1({ +const sha5121 = from1({ name: "sha2-512", code: 19, - encode: sha2("SHA-512") + encode: sha("SHA-512") }); -var sha21 = Object.freeze({ +var sha2 = Object.freeze({ __proto__: null, - sha256: sha2563, - sha512: sha5122 + sha256: sha2561, + sha512: sha5121 }); -const empty2 = new Uint8Array(0); -const toHex4 = (d)=>d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); +const empty3 = new Uint8Array(0); +const toHex2 = (d)=>d.reduce((hex, __byte)=>hex + __byte.toString(16).padStart(2, "0"), ""); const fromHex2 = (hex)=>{ const hexes = hex.match(/../g); - return hexes ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty2; + return hexes ? new Uint8Array(hexes.map((b)=>parseInt(b, 16))) : empty3; }; const equals4 = (aa, bb)=>{ if (aa === bb) return true; @@ -29583,21 +27009,21 @@ const coerce2 = (o)=>{ }; const isBinary2 = (o)=>o instanceof ArrayBuffer || ArrayBuffer.isView(o); const fromString3 = (str)=>new TextEncoder().encode(str); -const toString3 = (b)=>new TextDecoder().decode(b); -var bytes1 = Object.freeze({ +const toString4 = (b)=>new TextDecoder().decode(b); +var bytes2 = Object.freeze({ __proto__: null, equals: equals4, coerce: coerce2, isBinary: isBinary2, fromHex: fromHex2, - toHex: toHex4, + toHex: toHex2, fromString: fromString3, - toString: toString3, - empty: empty2 + toString: toString4, + empty: empty3 }); -var encode_13 = encode9; +var encode_13 = encode6; var MSB3 = 128, REST4 = 127, MSBALL3 = ~REST4, INT3 = Math.pow(2, 31); -function encode9(num, out, offset) { +function encode6(num, out, offset) { out = out || []; offset = offset || 0; var oldOffset = offset; @@ -29610,10 +27036,10 @@ function encode9(num, out, offset) { num >>>= 7; } out[offset] = num | 0; - encode9.bytes = offset - oldOffset + 1; + encode6.bytes = offset - oldOffset + 1; return out; } -var decode10 = read3; +var decode8 = read3; var MSB$13 = 128, REST$13 = 127; function read3(buf, offset) { var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length; @@ -29643,7 +27069,7 @@ var length3 = function(value) { }; var varint3 = { encode: encode_13, - decode: decode10, + decode: decode8, encodingLength: length3 }; var _brrp_varint2 = varint3; @@ -29730,7 +27156,7 @@ Object.freeze({ from: from2, Hasher: Hasher1 }); -function base2(ALPHABET, name) { +function base1(ALPHABET, name) { if (ALPHABET.length >= 255) { throw new TypeError("Alphabet too long"); } @@ -29860,7 +27286,7 @@ function base2(ALPHABET, name) { decode: decode2 }; } -var src1 = base2; +var src1 = base1; var _brrp__multiformats_scope_baseX1 = src1; class Encoder1 { constructor(name, prefix, baseEncode){ @@ -29953,7 +27379,7 @@ const baseX1 = ({ prefix, name, alphabet })=>{ decode: (text)=>coerce2(decode2(text)) }); }; -const decode11 = (string, alphabet, bitsPerChar, name)=>{ +const decode9 = (string, alphabet, bitsPerChar, name)=>{ const codes = {}; for(let i = 0; i < alphabet.length; ++i){ codes[alphabet[i]] = i; @@ -29983,7 +27409,7 @@ const decode11 = (string, alphabet, bitsPerChar, name)=>{ } return out; }; -const encode10 = (data, alphabet, bitsPerChar)=>{ +const encode7 = (data, alphabet, bitsPerChar)=>{ const pad = alphabet[alphabet.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; @@ -30012,10 +27438,10 @@ const rfc46481 = ({ name, prefix, bitsPerChar, alphabet })=>{ prefix, name, encode (input) { - return encode10(input, alphabet, bitsPerChar); + return encode7(input, alphabet, bitsPerChar); }, decode (input) { - return decode11(input, alphabet, bitsPerChar, name); + return decode9(input, alphabet, bitsPerChar, name); } }); }; @@ -30392,9 +27818,9 @@ const hidden = { enumerable: false, configurable: false }; -const version27 = "0.0.0-dev"; +const version1 = "0.0.0-dev"; const deprecate = (range, message)=>{ - if (range.test(version27)) { + if (range.test(version1)) { console.warn(message); } else { throw new Error(message); @@ -30415,19 +27841,19 @@ if (cid) { doSomethingWithCID(cid) } `; -function createCommonjsModule7(fn, basedir, module) { +function createCommonjsModule(fn, basedir, module) { return module = { path: basedir, exports: {}, require: function(path, base) { - return commonjsRequire7(path, base === void 0 || base === null ? module.path : base); + return commonjsRequire(path, base === void 0 || base === null ? module.path : base); } }, fn(module, module.exports), module.exports; } -function commonjsRequire7() { +function commonjsRequire() { throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); } -var murmurHash3js = createCommonjsModule7(function(module, exports) { +var murmurHash3js = createCommonjsModule(function(module, exports) { (function(root, undefined$1) { var library = { version: "3.0.0", @@ -30970,7 +28396,7 @@ const murmur332 = from2({ const murmur3128 = from2({ name: "murmur3-128", code: 34, - encode: (input)=>bytes1.fromHex(murmurhash3jsRevisited.x64.hash128(input)) + encode: (input)=>bytes2.fromHex(murmurhash3jsRevisited.x64.hash128(input)) }); const ERROR_MSG_INPUT = "Input must be an string, Buffer or Uint8Array"; function normalizeInput(input) { @@ -30985,7 +28411,7 @@ function normalizeInput(input) { } return ret; } -function toHex5(bytes) { +function toHex3(bytes) { return Array.prototype.map.call(bytes, function(n) { return (n < 16 ? "0" : "") + n.toString(16); }).join(""); @@ -31032,7 +28458,7 @@ function testSpeed(hashFn, N, M) { } var util = { normalizeInput, - toHex: toHex5, + toHex: toHex3, debugPrint, testSpeed }; @@ -31775,7 +29201,7 @@ var blakejs = { blake2sFinal: blake2s_1.blake2sFinal }; blakejs.blake2b; -function base3(ALPHABET, name) { +function base2(ALPHABET, name) { if (ALPHABET.length >= 255) { throw new TypeError("Alphabet too long"); } @@ -31905,7 +29331,7 @@ function base3(ALPHABET, name) { decode: decode2 }; } -var src2 = base3; +var src2 = base2; var _brrp__multiformats_scope_baseX2 = src2; class Encoder2 { constructor(name, prefix, baseEncode){ @@ -31996,7 +29422,7 @@ const baseX2 = ({ prefix, name, alphabet })=>{ decode: (text)=>coerce1(decode2(text)) }); }; -const decode12 = (string, alphabet, bitsPerChar, name)=>{ +const decode10 = (string, alphabet, bitsPerChar, name)=>{ const codes = {}; for(let i = 0; i < alphabet.length; ++i){ codes[alphabet[i]] = i; @@ -32026,7 +29452,7 @@ const decode12 = (string, alphabet, bitsPerChar, name)=>{ } return out; }; -const encode11 = (data, alphabet, bitsPerChar)=>{ +const encode8 = (data, alphabet, bitsPerChar)=>{ const pad = alphabet[alphabet.length - 1] === "="; const mask = (1 << bitsPerChar) - 1; let out = ""; @@ -32055,10 +29481,10 @@ const rfc46482 = ({ name, prefix, bitsPerChar, alphabet })=>{ prefix, name, encode (input) { - return encode11(input, alphabet, bitsPerChar); + return encode8(input, alphabet, bitsPerChar); }, decode (input) { - return decode12(input, alphabet, bitsPerChar, name); + return decode10(input, alphabet, bitsPerChar, name); } }); }; @@ -32435,9 +29861,9 @@ const hidden1 = { enumerable: false, configurable: false }; -const version28 = "0.0.0-dev"; +const version2 = "0.0.0-dev"; const deprecate1 = (range, message)=>{ - if (range.test(version28)) { + if (range.test(version2)) { console.warn(message); } else { throw new Error(message); @@ -32462,322 +29888,322 @@ const { blake2b: blake2b1 } = blakejs; const blake2b8 = from1({ name: "blake2b-8", code: 45569, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 1)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 1)) }); const blake2b16 = from1({ name: "blake2b-16", code: 45570, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 2)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 2)) }); const blake2b24 = from1({ name: "blake2b-24", code: 45571, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 3)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 3)) }); const blake2b32 = from1({ name: "blake2b-32", code: 45572, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 4)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 4)) }); const blake2b40 = from1({ name: "blake2b-40", code: 45573, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 5)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 5)) }); const blake2b48 = from1({ name: "blake2b-48", code: 45574, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 6)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 6)) }); const blake2b56 = from1({ name: "blake2b-56", code: 45575, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 7)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 7)) }); const blake2b64 = from1({ name: "blake2b-64", code: 45576, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 8)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 8)) }); const blake2b72 = from1({ name: "blake2b-72", code: 45577, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 9)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 9)) }); const blake2b80 = from1({ name: "blake2b-80", code: 45578, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 10)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 10)) }); const blake2b88 = from1({ name: "blake2b-88", code: 45579, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 11)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 11)) }); const blake2b96 = from1({ name: "blake2b-96", code: 45580, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 12)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 12)) }); const blake2b104 = from1({ name: "blake2b-104", code: 45581, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 13)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 13)) }); const blake2b112 = from1({ name: "blake2b-112", code: 45582, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 14)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 14)) }); const blake2b120 = from1({ name: "blake2b-120", code: 45583, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 15)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 15)) }); const blake2b128 = from1({ name: "blake2b-128", code: 45584, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 16)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 16)) }); const blake2b136 = from1({ name: "blake2b-136", code: 45585, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 17)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 17)) }); const blake2b144 = from1({ name: "blake2b-144", code: 45586, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 18)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 18)) }); const blake2b152 = from1({ name: "blake2b-152", code: 45587, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 19)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 19)) }); const blake2b160 = from1({ name: "blake2b-160", code: 45588, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 20)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 20)) }); const blake2b168 = from1({ name: "blake2b-168", code: 45589, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 21)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 21)) }); const blake2b176 = from1({ name: "blake2b-176", code: 45590, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 22)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 22)) }); const blake2b184 = from1({ name: "blake2b-184", code: 45591, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 23)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 23)) }); const blake2b192 = from1({ name: "blake2b-192", code: 45592, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 24)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 24)) }); const blake2b200 = from1({ name: "blake2b-200", code: 45593, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 25)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 25)) }); const blake2b208 = from1({ name: "blake2b-208", code: 45594, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 26)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 26)) }); const blake2b216 = from1({ name: "blake2b-216", code: 45595, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 27)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 27)) }); const blake2b224 = from1({ name: "blake2b-224", code: 45596, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 28)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 28)) }); const blake2b232 = from1({ name: "blake2b-232", code: 45597, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 29)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 29)) }); const blake2b240 = from1({ name: "blake2b-240", code: 45598, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 30)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 30)) }); const blake2b248 = from1({ name: "blake2b-248", code: 45599, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 31)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 31)) }); const blake2b256 = from1({ name: "blake2b-256", code: 45600, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 32)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 32)) }); const blake2b264 = from1({ name: "blake2b-264", code: 45601, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 33)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 33)) }); const blake2b272 = from1({ name: "blake2b-272", code: 45602, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 34)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 34)) }); const blake2b280 = from1({ name: "blake2b-280", code: 45603, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 35)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 35)) }); const blake2b288 = from1({ name: "blake2b-288", code: 45604, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 36)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 36)) }); const blake2b296 = from1({ name: "blake2b-296", code: 45605, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 37)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 37)) }); const blake2b304 = from1({ name: "blake2b-304", code: 45606, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 38)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 38)) }); const blake2b312 = from1({ name: "blake2b-312", code: 45607, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 39)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 39)) }); const blake2b320 = from1({ name: "blake2b-320", code: 45608, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 40)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 40)) }); const blake2b328 = from1({ name: "blake2b-328", code: 45609, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 41)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 41)) }); const blake2b336 = from1({ name: "blake2b-336", code: 45610, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 42)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 42)) }); const blake2b344 = from1({ name: "blake2b-344", code: 45611, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 43)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 43)) }); const blake2b352 = from1({ name: "blake2b-352", code: 45612, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 44)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 44)) }); const blake2b360 = from1({ name: "blake2b-360", code: 45613, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 45)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 45)) }); const blake2b368 = from1({ name: "blake2b-368", code: 45614, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 46)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 46)) }); const blake2b376 = from1({ name: "blake2b-376", code: 45615, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 47)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 47)) }); const blake2b384 = from1({ name: "blake2b-384", code: 45616, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 48)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 48)) }); const blake2b392 = from1({ name: "blake2b-392", code: 45617, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 49)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 49)) }); const blake2b400 = from1({ name: "blake2b-400", code: 45618, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 50)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 50)) }); const blake2b408 = from1({ name: "blake2b-408", code: 45619, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 51)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 51)) }); const blake2b416 = from1({ name: "blake2b-416", code: 45620, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 52)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 52)) }); const blake2b424 = from1({ name: "blake2b-424", code: 45621, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 53)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 53)) }); const blake2b432 = from1({ name: "blake2b-432", code: 45622, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 54)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 54)) }); const blake2b440 = from1({ name: "blake2b-440", code: 45623, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 55)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 55)) }); const blake2b448 = from1({ name: "blake2b-448", code: 45624, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 56)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 56)) }); const blake2b456 = from1({ name: "blake2b-456", code: 45625, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 57)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 57)) }); const blake2b464 = from1({ name: "blake2b-464", code: 45626, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 58)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 58)) }); const blake2b472 = from1({ name: "blake2b-472", code: 45627, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 59)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 59)) }); const blake2b480 = from1({ name: "blake2b-480", code: 45628, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 60)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 60)) }); const blake2b488 = from1({ name: "blake2b-488", code: 45629, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 61)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 61)) }); const blake2b496 = from1({ name: "blake2b-496", code: 45630, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 62)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 62)) }); const blake2b504 = from1({ name: "blake2b-504", code: 45631, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 63)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 63)) }); const blake2b512 = from1({ name: "blake2b-512", code: 45632, - encode: (input)=>bytes.coerce(blake2b1(input, void 0, 64)) + encode: (input)=>bytes1.coerce(blake2b1(input, void 0, 64)) }); Object.freeze({ __proto__: null, @@ -32850,162 +30276,162 @@ const { blake2s: blake2s1 } = blakejs; const blake2s8 = from1({ name: "blake2s-8", code: 45633, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 1)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 1)) }); const blake2s16 = from1({ name: "blake2s-16", code: 45634, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 2)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 2)) }); const blake2s24 = from1({ name: "blake2s-24", code: 45635, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 3)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 3)) }); const blake2s32 = from1({ name: "blake2s-32", code: 45636, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 4)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 4)) }); const blake2s40 = from1({ name: "blake2s-40", code: 45637, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 5)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 5)) }); const blake2s48 = from1({ name: "blake2s-48", code: 45638, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 6)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 6)) }); const blake2s56 = from1({ name: "blake2s-56", code: 45639, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 7)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 7)) }); const blake2s64 = from1({ name: "blake2s-64", code: 45640, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 8)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 8)) }); const blake2s72 = from1({ name: "blake2s-72", code: 45641, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 9)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 9)) }); const blake2s80 = from1({ name: "blake2s-80", code: 45642, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 10)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 10)) }); const blake2s88 = from1({ name: "blake2s-88", code: 45643, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 11)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 11)) }); const blake2s96 = from1({ name: "blake2s-96", code: 45644, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 12)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 12)) }); const blake2s104 = from1({ name: "blake2s-104", code: 45645, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 13)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 13)) }); const blake2s112 = from1({ name: "blake2s-112", code: 45646, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 14)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 14)) }); const blake2s120 = from1({ name: "blake2s-120", code: 45647, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 15)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 15)) }); const blake2s128 = from1({ name: "blake2s-128", code: 45648, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 16)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 16)) }); const blake2s136 = from1({ name: "blake2s-136", code: 45649, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 17)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 17)) }); const blake2s144 = from1({ name: "blake2s-144", code: 45650, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 18)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 18)) }); const blake2s152 = from1({ name: "blake2s-152", code: 45651, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 19)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 19)) }); const blake2s160 = from1({ name: "blake2s-160", code: 45652, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 20)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 20)) }); const blake2s168 = from1({ name: "blake2s-168", code: 45653, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 21)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 21)) }); const blake2s176 = from1({ name: "blake2s-176", code: 45654, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 22)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 22)) }); const blake2s184 = from1({ name: "blake2s-184", code: 45655, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 23)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 23)) }); const blake2s192 = from1({ name: "blake2s-192", code: 45656, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 24)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 24)) }); const blake2s200 = from1({ name: "blake2s-200", code: 45657, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 25)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 25)) }); const blake2s208 = from1({ name: "blake2s-208", code: 45658, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 26)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 26)) }); const blake2s216 = from1({ name: "blake2s-216", code: 45659, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 27)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 27)) }); const blake2s224 = from1({ name: "blake2s-224", code: 45660, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 28)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 28)) }); const blake2s232 = from1({ name: "blake2s-232", code: 45661, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 29)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 29)) }); const blake2s240 = from1({ name: "blake2s-240", code: 45662, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 30)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 30)) }); const blake2s248 = from1({ name: "blake2s-248", code: 45663, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 31)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 31)) }); const blake2s256 = from1({ name: "blake2s-256", code: 45664, - encode: (input)=>bytes.coerce(blake2s1(input, void 0, 32)) + encode: (input)=>bytes1.coerce(blake2s1(input, void 0, 32)) }); Object.freeze({ __proto__: null, @@ -33042,6 +30468,954 @@ Object.freeze({ blake2s248, blake2s256 }); +function defaultSetTimout() { + throw new Error("setTimeout has not been defined"); +} +function defaultClearTimeout() { + throw new Error("clearTimeout has not been defined"); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +var globalContext; +if (typeof window !== "undefined") { + globalContext = window; +} else if (typeof self !== "undefined") { + globalContext = self; +} else { + globalContext = {}; +} +if (typeof globalContext.setTimeout === "function") { + cachedSetTimeout = setTimeout; +} +if (typeof globalContext.clearTimeout === "function") { + cachedClearTimeout = clearTimeout; +} +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + return setTimeout(fun, 0); + } + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + return cachedSetTimeout.call(null, fun, 0); + } catch (e2) { + return cachedSetTimeout.call(this, fun, 0); + } + } +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + return clearTimeout(marker); + } + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + return cachedClearTimeout(marker); + } catch (e) { + try { + return cachedClearTimeout.call(null, marker); + } catch (e2) { + return cachedClearTimeout.call(this, marker); + } + } +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + while(len){ + currentQueue = queue; + queue = []; + while(++queueIndex < len){ + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick1(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for(var i = 1; i < arguments.length; i++){ + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function() { + this.fun.apply(null, this.array); +}; +var title = "browser"; +var platform = "browser"; +var browser = true; +var argv = []; +var version3 = ""; +var versions = {}; +var release = {}; +var config = {}; +function noop() {} +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit1 = noop; +function binding(name) { + throw new Error("process.binding is not supported"); +} +function cwd() { + return "/"; +} +function chdir(dir) { + throw new Error("process.chdir is not supported"); +} +function umask() { + return 0; +} +var performance = globalContext.performance || {}; +var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function() { + return new Date().getTime(); +}; +function hrtime(previousTimestamp) { + var clocktime = performanceNow.call(performance) * 1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor(clocktime % 1 * 1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds < 0) { + seconds--; + nanoseconds += 1e9; + } + } + return [ + seconds, + nanoseconds + ]; +} +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1e3; +} +var process = { + nextTick: nextTick1, + title, + browser, + env: { + NODE_ENV: "production" + }, + argv, + version: version3, + versions, + on, + addListener, + once, + off, + removeListener, + removeAllListeners, + emit: emit1, + binding, + cwd, + chdir, + umask, + hrtime, + platform, + release, + config, + uptime +}; +var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; +function createCommonjsModule1(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function(path, base) { + return commonjsRequire1(path, base === void 0 || base === null ? module.path : base); + } + }, fn(module, module.exports), module.exports; +} +function commonjsRequire1() { + throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs"); +} +var sha3 = createCommonjsModule1(function(module) { + (function() { + var INPUT_ERROR = "input is invalid type"; + var FINALIZE_ERROR = "finalize already called"; + var WINDOW = typeof window === "object"; + var root = WINDOW ? window : {}; + if (root.JS_SHA3_NO_WINDOW) { + WINDOW = false; + } + var WEB_WORKER = !WINDOW && typeof self === "object"; + var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === "object" && process.versions && process.versions.node; + if (NODE_JS) { + root = commonjsGlobal; + } else if (WEB_WORKER) { + root = self; + } + var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && true && module.exports; + var ARRAY_BUFFER = !root.JS_SHA3_NO_ARRAY_BUFFER && typeof ArrayBuffer !== "undefined"; + var HEX_CHARS = "0123456789abcdef".split(""); + var SHAKE_PADDING = [ + 31, + 7936, + 2031616, + 520093696 + ]; + var CSHAKE_PADDING = [ + 4, + 1024, + 262144, + 67108864 + ]; + var KECCAK_PADDING = [ + 1, + 256, + 65536, + 16777216 + ]; + var PADDING = [ + 6, + 1536, + 393216, + 100663296 + ]; + var SHIFT = [ + 0, + 8, + 16, + 24 + ]; + var RC = [ + 1, + 0, + 32898, + 0, + 32906, + 2147483648, + 2147516416, + 2147483648, + 32907, + 0, + 2147483649, + 0, + 2147516545, + 2147483648, + 32777, + 2147483648, + 138, + 0, + 136, + 0, + 2147516425, + 0, + 2147483658, + 0, + 2147516555, + 0, + 139, + 2147483648, + 32905, + 2147483648, + 32771, + 2147483648, + 32770, + 2147483648, + 128, + 2147483648, + 32778, + 0, + 2147483658, + 2147483648, + 2147516545, + 2147483648, + 32896, + 2147483648, + 2147483649, + 0, + 2147516424, + 2147483648 + ]; + var BITS = [ + 224, + 256, + 384, + 512 + ]; + var SHAKE_BITS = [ + 128, + 256 + ]; + var OUTPUT_TYPES = [ + "hex", + "buffer", + "arrayBuffer", + "array", + "digest" + ]; + var CSHAKE_BYTEPAD = { + "128": 168, + "256": 136 + }; + if (root.JS_SHA3_NO_NODE_JS || !Array.isArray) { + Array.isArray = function(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + } + if (ARRAY_BUFFER && (root.JS_SHA3_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) { + ArrayBuffer.isView = function(obj) { + return typeof obj === "object" && obj.buffer && obj.buffer.constructor === ArrayBuffer; + }; + } + var createOutputMethod = function(bits2, padding, outputType) { + return function(message) { + return new Keccak(bits2, padding, bits2).update(message)[outputType](); + }; + }; + var createShakeOutputMethod = function(bits2, padding, outputType) { + return function(message, outputBits) { + return new Keccak(bits2, padding, outputBits).update(message)[outputType](); + }; + }; + var createCshakeOutputMethod = function(bits2, padding, outputType) { + return function(message, outputBits, n, s) { + return methods["cshake" + bits2].update(message, outputBits, n, s)[outputType](); + }; + }; + var createKmacOutputMethod = function(bits2, padding, outputType) { + return function(key, message, outputBits, s) { + return methods["kmac" + bits2].update(key, message, outputBits, s)[outputType](); + }; + }; + var createOutputMethods = function(method, createMethod2, bits2, padding) { + for(var i2 = 0; i2 < OUTPUT_TYPES.length; ++i2){ + var type = OUTPUT_TYPES[i2]; + method[type] = createMethod2(bits2, padding, type); + } + return method; + }; + var createMethod = function(bits2, padding) { + var method = createOutputMethod(bits2, padding, "hex"); + method.create = function() { + return new Keccak(bits2, padding, bits2); + }; + method.update = function(message) { + return method.create().update(message); + }; + return createOutputMethods(method, createOutputMethod, bits2, padding); + }; + var createShakeMethod = function(bits2, padding) { + var method = createShakeOutputMethod(bits2, padding, "hex"); + method.create = function(outputBits) { + return new Keccak(bits2, padding, outputBits); + }; + method.update = function(message, outputBits) { + return method.create(outputBits).update(message); + }; + return createOutputMethods(method, createShakeOutputMethod, bits2, padding); + }; + var createCshakeMethod = function(bits2, padding) { + var w = CSHAKE_BYTEPAD[bits2]; + var method = createCshakeOutputMethod(bits2, padding, "hex"); + method.create = function(outputBits, n, s) { + if (!n && !s) { + return methods["shake" + bits2].create(outputBits); + } else { + return new Keccak(bits2, padding, outputBits).bytepad([ + n, + s + ], w); + } + }; + method.update = function(message, outputBits, n, s) { + return method.create(outputBits, n, s).update(message); + }; + return createOutputMethods(method, createCshakeOutputMethod, bits2, padding); + }; + var createKmacMethod = function(bits2, padding) { + var w = CSHAKE_BYTEPAD[bits2]; + var method = createKmacOutputMethod(bits2, padding, "hex"); + method.create = function(key, outputBits, s) { + return new Kmac(bits2, padding, outputBits).bytepad([ + "KMAC", + s + ], w).bytepad([ + key + ], w); + }; + method.update = function(key, message, outputBits, s) { + return method.create(key, outputBits, s).update(message); + }; + return createOutputMethods(method, createKmacOutputMethod, bits2, padding); + }; + var algorithms = [ + { + name: "keccak", + padding: KECCAK_PADDING, + bits: BITS, + createMethod + }, + { + name: "sha3", + padding: PADDING, + bits: BITS, + createMethod + }, + { + name: "shake", + padding: SHAKE_PADDING, + bits: SHAKE_BITS, + createMethod: createShakeMethod + }, + { + name: "cshake", + padding: CSHAKE_PADDING, + bits: SHAKE_BITS, + createMethod: createCshakeMethod + }, + { + name: "kmac", + padding: CSHAKE_PADDING, + bits: SHAKE_BITS, + createMethod: createKmacMethod + } + ]; + var methods = {}, methodNames = []; + for(var i = 0; i < algorithms.length; ++i){ + var algorithm = algorithms[i]; + var bits = algorithm.bits; + for(var j = 0; j < bits.length; ++j){ + var methodName = algorithm.name + "_" + bits[j]; + methodNames.push(methodName); + methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); + if (algorithm.name !== "sha3") { + var newMethodName = algorithm.name + bits[j]; + methodNames.push(newMethodName); + methods[newMethodName] = methods[methodName]; + } + } + } + function Keccak(bits2, padding, outputBits) { + this.blocks = []; + this.s = []; + this.padding = padding; + this.outputBits = outputBits; + this.reset = true; + this.finalized = false; + this.block = 0; + this.start = 0; + this.blockCount = 1600 - (bits2 << 1) >> 5; + this.byteCount = this.blockCount << 2; + this.outputBlocks = outputBits >> 5; + this.extraBytes = (outputBits & 31) >> 3; + for(var i2 = 0; i2 < 50; ++i2){ + this.s[i2] = 0; + } + } + Keccak.prototype.update = function(message) { + if (this.finalized) { + throw new Error(FINALIZE_ERROR); + } + var notString, type = typeof message; + if (type !== "string") { + if (type === "object") { + if (message === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) { + message = new Uint8Array(message); + } else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var blocks = this.blocks, byteCount = this.byteCount, length = message.length, blockCount = this.blockCount, index = 0, s = this.s, i2, code; + while(index < length){ + if (this.reset) { + this.reset = false; + blocks[0] = this.block; + for(i2 = 1; i2 < blockCount + 1; ++i2){ + blocks[i2] = 0; + } + } + if (notString) { + for(i2 = this.start; index < length && i2 < byteCount; ++index){ + blocks[i2 >> 2] |= message[index] << SHIFT[i2++ & 3]; + } + } else { + for(i2 = this.start; index < length && i2 < byteCount; ++index){ + code = message.charCodeAt(index); + if (code < 128) { + blocks[i2 >> 2] |= code << SHIFT[i2++ & 3]; + } else if (code < 2048) { + blocks[i2 >> 2] |= (192 | code >> 6) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; + } else if (code < 55296 || code >= 57344) { + blocks[i2 >> 2] |= (224 | code >> 12) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; + } else { + code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); + blocks[i2 >> 2] |= (240 | code >> 18) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code >> 12 & 63) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code >> 6 & 63) << SHIFT[i2++ & 3]; + blocks[i2 >> 2] |= (128 | code & 63) << SHIFT[i2++ & 3]; + } + } + } + this.lastByteIndex = i2; + if (i2 >= byteCount) { + this.start = i2 - byteCount; + this.block = blocks[blockCount]; + for(i2 = 0; i2 < blockCount; ++i2){ + s[i2] ^= blocks[i2]; + } + f(s); + this.reset = true; + } else { + this.start = i2; + } + } + return this; + }; + Keccak.prototype.encode = function(x, right) { + var o = x & 255, n = 1; + var bytes = [ + o + ]; + x = x >> 8; + o = x & 255; + while(o > 0){ + bytes.unshift(o); + x = x >> 8; + o = x & 255; + ++n; + } + if (right) { + bytes.push(n); + } else { + bytes.unshift(n); + } + this.update(bytes); + return bytes.length; + }; + Keccak.prototype.encodeString = function(str) { + var notString, type = typeof str; + if (type !== "string") { + if (type === "object") { + if (str === null) { + throw new Error(INPUT_ERROR); + } else if (ARRAY_BUFFER && str.constructor === ArrayBuffer) { + str = new Uint8Array(str); + } else if (!Array.isArray(str)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(str)) { + throw new Error(INPUT_ERROR); + } + } + } else { + throw new Error(INPUT_ERROR); + } + notString = true; + } + var bytes = 0, length = str.length; + if (notString) { + bytes = length; + } else { + for(var i2 = 0; i2 < str.length; ++i2){ + var code = str.charCodeAt(i2); + if (code < 128) { + bytes += 1; + } else if (code < 2048) { + bytes += 2; + } else if (code < 55296 || code >= 57344) { + bytes += 3; + } else { + code = 65536 + ((code & 1023) << 10 | str.charCodeAt(++i2) & 1023); + bytes += 4; + } + } + } + bytes += this.encode(bytes * 8); + this.update(str); + return bytes; + }; + Keccak.prototype.bytepad = function(strs, w) { + var bytes = this.encode(w); + for(var i2 = 0; i2 < strs.length; ++i2){ + bytes += this.encodeString(strs[i2]); + } + var paddingBytes = w - bytes % w; + var zeros = []; + zeros.length = paddingBytes; + this.update(zeros); + return this; + }; + Keccak.prototype.finalize = function() { + if (this.finalized) { + return; + } + this.finalized = true; + var blocks = this.blocks, i2 = this.lastByteIndex, blockCount = this.blockCount, s = this.s; + blocks[i2 >> 2] |= this.padding[i2 & 3]; + if (this.lastByteIndex === this.byteCount) { + blocks[0] = blocks[blockCount]; + for(i2 = 1; i2 < blockCount + 1; ++i2){ + blocks[i2] = 0; + } + } + blocks[blockCount - 1] |= 2147483648; + for(i2 = 0; i2 < blockCount; ++i2){ + s[i2] ^= blocks[i2]; + } + f(s); + }; + Keccak.prototype.toString = Keccak.prototype.hex = function() { + this.finalize(); + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; + var hex = "", block; + while(j2 < outputBlocks){ + for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ + block = s[i2]; + hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15] + HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15] + HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15] + HEX_CHARS[block >> 28 & 15] + HEX_CHARS[block >> 24 & 15]; + } + if (j2 % blockCount === 0) { + f(s); + i2 = 0; + } + } + if (extraBytes) { + block = s[i2]; + hex += HEX_CHARS[block >> 4 & 15] + HEX_CHARS[block & 15]; + if (extraBytes > 1) { + hex += HEX_CHARS[block >> 12 & 15] + HEX_CHARS[block >> 8 & 15]; + } + if (extraBytes > 2) { + hex += HEX_CHARS[block >> 20 & 15] + HEX_CHARS[block >> 16 & 15]; + } + } + return hex; + }; + Keccak.prototype.arrayBuffer = function() { + this.finalize(); + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; + var bytes = this.outputBits >> 3; + var buffer; + if (extraBytes) { + buffer = new ArrayBuffer(outputBlocks + 1 << 2); + } else { + buffer = new ArrayBuffer(bytes); + } + var array = new Uint32Array(buffer); + while(j2 < outputBlocks){ + for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ + array[j2] = s[i2]; + } + if (j2 % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + array[i2] = s[i2]; + buffer = buffer.slice(0, bytes); + } + return buffer; + }; + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; + Keccak.prototype.digest = Keccak.prototype.array = function() { + this.finalize(); + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i2 = 0, j2 = 0; + var array = [], offset, block; + while(j2 < outputBlocks){ + for(i2 = 0; i2 < blockCount && j2 < outputBlocks; ++i2, ++j2){ + offset = j2 << 2; + block = s[i2]; + array[offset] = block & 255; + array[offset + 1] = block >> 8 & 255; + array[offset + 2] = block >> 16 & 255; + array[offset + 3] = block >> 24 & 255; + } + if (j2 % blockCount === 0) { + f(s); + } + } + if (extraBytes) { + offset = j2 << 2; + block = s[i2]; + array[offset] = block & 255; + if (extraBytes > 1) { + array[offset + 1] = block >> 8 & 255; + } + if (extraBytes > 2) { + array[offset + 2] = block >> 16 & 255; + } + } + return array; + }; + function Kmac(bits2, padding, outputBits) { + Keccak.call(this, bits2, padding, outputBits); + } + Kmac.prototype = new Keccak(); + Kmac.prototype.finalize = function() { + this.encode(this.outputBits, true); + return Keccak.prototype.finalize.call(this); + }; + var f = function(s) { + var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; + for(n = 0; n < 48; n += 2){ + c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; + c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; + c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; + c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; + c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; + c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; + c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; + c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; + c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; + c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; + h = c8 ^ (c2 << 1 | c3 >>> 31); + l = c9 ^ (c3 << 1 | c2 >>> 31); + s[0] ^= h; + s[1] ^= l; + s[10] ^= h; + s[11] ^= l; + s[20] ^= h; + s[21] ^= l; + s[30] ^= h; + s[31] ^= l; + s[40] ^= h; + s[41] ^= l; + h = c0 ^ (c4 << 1 | c5 >>> 31); + l = c1 ^ (c5 << 1 | c4 >>> 31); + s[2] ^= h; + s[3] ^= l; + s[12] ^= h; + s[13] ^= l; + s[22] ^= h; + s[23] ^= l; + s[32] ^= h; + s[33] ^= l; + s[42] ^= h; + s[43] ^= l; + h = c2 ^ (c6 << 1 | c7 >>> 31); + l = c3 ^ (c7 << 1 | c6 >>> 31); + s[4] ^= h; + s[5] ^= l; + s[14] ^= h; + s[15] ^= l; + s[24] ^= h; + s[25] ^= l; + s[34] ^= h; + s[35] ^= l; + s[44] ^= h; + s[45] ^= l; + h = c4 ^ (c8 << 1 | c9 >>> 31); + l = c5 ^ (c9 << 1 | c8 >>> 31); + s[6] ^= h; + s[7] ^= l; + s[16] ^= h; + s[17] ^= l; + s[26] ^= h; + s[27] ^= l; + s[36] ^= h; + s[37] ^= l; + s[46] ^= h; + s[47] ^= l; + h = c6 ^ (c0 << 1 | c1 >>> 31); + l = c7 ^ (c1 << 1 | c0 >>> 31); + s[8] ^= h; + s[9] ^= l; + s[18] ^= h; + s[19] ^= l; + s[28] ^= h; + s[29] ^= l; + s[38] ^= h; + s[39] ^= l; + s[48] ^= h; + s[49] ^= l; + b0 = s[0]; + b1 = s[1]; + b32 = s[11] << 4 | s[10] >>> 28; + b33 = s[10] << 4 | s[11] >>> 28; + b14 = s[20] << 3 | s[21] >>> 29; + b15 = s[21] << 3 | s[20] >>> 29; + b46 = s[31] << 9 | s[30] >>> 23; + b47 = s[30] << 9 | s[31] >>> 23; + b28 = s[40] << 18 | s[41] >>> 14; + b29 = s[41] << 18 | s[40] >>> 14; + b20 = s[2] << 1 | s[3] >>> 31; + b21 = s[3] << 1 | s[2] >>> 31; + b2 = s[13] << 12 | s[12] >>> 20; + b3 = s[12] << 12 | s[13] >>> 20; + b34 = s[22] << 10 | s[23] >>> 22; + b35 = s[23] << 10 | s[22] >>> 22; + b16 = s[33] << 13 | s[32] >>> 19; + b17 = s[32] << 13 | s[33] >>> 19; + b48 = s[42] << 2 | s[43] >>> 30; + b49 = s[43] << 2 | s[42] >>> 30; + b40 = s[5] << 30 | s[4] >>> 2; + b41 = s[4] << 30 | s[5] >>> 2; + b22 = s[14] << 6 | s[15] >>> 26; + b23 = s[15] << 6 | s[14] >>> 26; + b4 = s[25] << 11 | s[24] >>> 21; + b5 = s[24] << 11 | s[25] >>> 21; + b36 = s[34] << 15 | s[35] >>> 17; + b37 = s[35] << 15 | s[34] >>> 17; + b18 = s[45] << 29 | s[44] >>> 3; + b19 = s[44] << 29 | s[45] >>> 3; + b10 = s[6] << 28 | s[7] >>> 4; + b11 = s[7] << 28 | s[6] >>> 4; + b42 = s[17] << 23 | s[16] >>> 9; + b43 = s[16] << 23 | s[17] >>> 9; + b24 = s[26] << 25 | s[27] >>> 7; + b25 = s[27] << 25 | s[26] >>> 7; + b6 = s[36] << 21 | s[37] >>> 11; + b7 = s[37] << 21 | s[36] >>> 11; + b38 = s[47] << 24 | s[46] >>> 8; + b39 = s[46] << 24 | s[47] >>> 8; + b30 = s[8] << 27 | s[9] >>> 5; + b31 = s[9] << 27 | s[8] >>> 5; + b12 = s[18] << 20 | s[19] >>> 12; + b13 = s[19] << 20 | s[18] >>> 12; + b44 = s[29] << 7 | s[28] >>> 25; + b45 = s[28] << 7 | s[29] >>> 25; + b26 = s[38] << 8 | s[39] >>> 24; + b27 = s[39] << 8 | s[38] >>> 24; + b8 = s[48] << 14 | s[49] >>> 18; + b9 = s[49] << 14 | s[48] >>> 18; + s[0] = b0 ^ ~b2 & b4; + s[1] = b1 ^ ~b3 & b5; + s[10] = b10 ^ ~b12 & b14; + s[11] = b11 ^ ~b13 & b15; + s[20] = b20 ^ ~b22 & b24; + s[21] = b21 ^ ~b23 & b25; + s[30] = b30 ^ ~b32 & b34; + s[31] = b31 ^ ~b33 & b35; + s[40] = b40 ^ ~b42 & b44; + s[41] = b41 ^ ~b43 & b45; + s[2] = b2 ^ ~b4 & b6; + s[3] = b3 ^ ~b5 & b7; + s[12] = b12 ^ ~b14 & b16; + s[13] = b13 ^ ~b15 & b17; + s[22] = b22 ^ ~b24 & b26; + s[23] = b23 ^ ~b25 & b27; + s[32] = b32 ^ ~b34 & b36; + s[33] = b33 ^ ~b35 & b37; + s[42] = b42 ^ ~b44 & b46; + s[43] = b43 ^ ~b45 & b47; + s[4] = b4 ^ ~b6 & b8; + s[5] = b5 ^ ~b7 & b9; + s[14] = b14 ^ ~b16 & b18; + s[15] = b15 ^ ~b17 & b19; + s[24] = b24 ^ ~b26 & b28; + s[25] = b25 ^ ~b27 & b29; + s[34] = b34 ^ ~b36 & b38; + s[35] = b35 ^ ~b37 & b39; + s[44] = b44 ^ ~b46 & b48; + s[45] = b45 ^ ~b47 & b49; + s[6] = b6 ^ ~b8 & b0; + s[7] = b7 ^ ~b9 & b1; + s[16] = b16 ^ ~b18 & b10; + s[17] = b17 ^ ~b19 & b11; + s[26] = b26 ^ ~b28 & b20; + s[27] = b27 ^ ~b29 & b21; + s[36] = b36 ^ ~b38 & b30; + s[37] = b37 ^ ~b39 & b31; + s[46] = b46 ^ ~b48 & b40; + s[47] = b47 ^ ~b49 & b41; + s[8] = b8 ^ ~b0 & b2; + s[9] = b9 ^ ~b1 & b3; + s[18] = b18 ^ ~b10 & b12; + s[19] = b19 ^ ~b11 & b13; + s[28] = b28 ^ ~b20 & b22; + s[29] = b29 ^ ~b21 & b23; + s[38] = b38 ^ ~b30 & b32; + s[39] = b39 ^ ~b31 & b33; + s[48] = b48 ^ ~b40 & b42; + s[49] = b49 ^ ~b41 & b43; + s[0] ^= RC[n]; + s[1] ^= RC[n + 1]; + } + }; + if (COMMON_JS) { + module.exports = methods; + } else { + for(i = 0; i < methodNames.length; ++i){ + root[methodNames[i]] = methods[methodNames[i]]; + } + } + })(); +}); +sha3.cshake128; +sha3.cshake256; +sha3.cshake_128; +sha3.cshake_256; +sha3.keccak224; +sha3.keccak256; +sha3.keccak384; +sha3.keccak512; +sha3.keccak_224; +sha3.keccak_256; +sha3.keccak_384; +sha3.keccak_512; +sha3.kmac128; +sha3.kmac256; +sha3.kmac_128; +sha3.kmac_256; +sha3.sha3_224; +sha3.sha3_256; +sha3.sha3_384; +sha3.sha3_512; +sha3.shake128; +sha3.shake256; +sha3.shake_128; +sha3.shake_256; function encoder1(fn) { return (b)=>new Uint8Array(fn.array(b)); } @@ -33110,7 +31484,7 @@ function allocUnsafe(size = 0) { const identity = from4({ prefix: "\0", name: "identity", - encode: (buf)=>toString2(buf), + encode: (buf)=>toString3(buf), decode: (str)=>fromString2(str) }); var identityBase = Object.freeze({ @@ -33218,13 +31592,13 @@ const alphabetCharsToBytes = alphabet.reduce((p, c, i)=>{ p[c.codePointAt(0)] = i; return p; }, []); -function encode12(data) { +function encode9(data) { return data.reduce((p, c)=>{ p += alphabetBytesToChars[c]; return p; }, ""); } -function decode13(str) { +function decode11(str) { const byts = []; for (const __char of str){ const byt = alphabetCharsToBytes[__char.codePointAt(0)]; @@ -33238,8 +31612,8 @@ function decode13(str) { const base256emoji = from4({ prefix: "\u{1F680}", name: "base256emoji", - encode: encode12, - decode: decode13 + encode: encode9, + decode: decode11 }); var base256emoji$1 = Object.freeze({ __proto__: null, @@ -33258,26 +31632,26 @@ var identity$1 = Object.freeze({ identity: identity1 }); const name1 = "raw"; -const encode13 = (node)=>coerce1(node); -const decode14 = (data)=>coerce1(data); +const encode10 = (node)=>coerce1(node); +const decode12 = (data)=>coerce1(data); Object.freeze({ __proto__: null, name: name1, code: 85, - encode: encode13, - decode: decode14 + encode: encode10, + decode: decode12 }); const textEncoder1 = new TextEncoder(); const textDecoder2 = new TextDecoder(); const name2 = "json"; -const encode14 = (node)=>textEncoder1.encode(JSON.stringify(node)); -const decode15 = (data)=>JSON.parse(textDecoder2.decode(data)); +const encode11 = (node)=>textEncoder1.encode(JSON.stringify(node)); +const decode13 = (data)=>JSON.parse(textDecoder2.decode(data)); Object.freeze({ __proto__: null, name: name2, code: 512, - encode: encode14, - decode: decode15 + encode: encode11, + decode: decode13 }); const bases = { ...identityBase, @@ -33292,7 +31666,7 @@ const bases = { ...base256emoji$1 }; ({ - ...sha21, + ...sha2, ...identity$1 }); function createCodec(name, prefix, encode, decode) { @@ -33354,8 +31728,8 @@ function equals6(a, b) { return true; } const hashMap = new Map([ - sha2563, - sha5122, + sha2561, + sha5121, murmur3128, murmur332, blake2b256, @@ -33410,7 +31784,7 @@ function e(t, e = !0) { if (t.destroyed) throw new Error("Hash instance has been destroyed"); if (e && t.finished) throw new Error("Hash#digest() has already been called"); } -const s1 = (t)=>new DataView(t.buffer, t.byteOffset, t.byteLength), n = (t, e)=>t << 32 - e | t >>> e; +const s = (t)=>new DataView(t.buffer, t.byteOffset, t.byteLength), n1 = (t, e)=>t << 32 - e | t >>> e; function i(e) { return "string" == typeof e && (e = function(t) { if ("string" != typeof t) throw new Error("utf8ToBytes expected string, got " + typeof t); @@ -33420,7 +31794,7 @@ function i(e) { new Uint8Array(new Uint32Array([ 287454020 ]).buffer)[0]; -class r2 { +class r { clone() { return this._cloneInto(); } @@ -33430,9 +31804,9 @@ function o1(t) { return e.outputLen = s.outputLen, e.blockLen = s.blockLen, e.create = ()=>t(), e; } const h = (t, e, s)=>t & e ^ t & s ^ e & s; -class f1 extends r2 { +class f1 extends r { constructor(t, e, n, i){ - super(), this.blockLen = t, this.outputLen = e, this.padOffset = n, this.isLE = i, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(t), this.view = s1(this.buffer); + super(), this.blockLen = t, this.outputLen = e, this.padOffset = n, this.isLE = i, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(t), this.view = s(this.buffer); } update(t) { e(this); @@ -33441,7 +31815,7 @@ class f1 extends r2 { const i = Math.min(o - this.pos, h - e); if (i !== o) r.set(t.subarray(e, e + i), this.pos), this.pos += i, e += i, this.pos === o && (this.process(n, 0), this.pos = 0); else { - const n = s1(t); + const n = s(t); for(; o <= h - e; e += o)this.process(n, e); } } @@ -33462,7 +31836,7 @@ class f1 extends r2 { const i = BigInt(32), r = BigInt(4294967295), o = Number(s >> i & r), h = Number(s & r), f = n ? 4 : 0, u = n ? 0 : 4; t.setUint32(e + f, o, n), t.setUint32(e + u, h, n); }(r, o - 8, BigInt(8 * this.length), h), this.process(r, 0); - const u = s1(n), c = this.outputLen; + const u = s(n), c = this.outputLen; if (c % 4) throw new Error("_sha2: outputLen should be aligned to 32bit"); const l = c / 4, a = this.get(); if (l > a.length) throw new Error("_sha2: outputLen bigger than state"); @@ -33578,12 +31952,12 @@ class a extends f1 { process(t, e) { for(let s = 0; s < 16; s++, e += 4)l[s] = t.getUint32(e, !1); for(let t = 16; t < 64; t++){ - const e = l[t - 15], s = l[t - 2], i = n(e, 7) ^ n(e, 18) ^ e >>> 3, r = n(s, 17) ^ n(s, 19) ^ s >>> 10; + const e = l[t - 15], s = l[t - 2], i = n1(e, 7) ^ n1(e, 18) ^ e >>> 3, r = n1(s, 17) ^ n1(s, 19) ^ s >>> 10; l[t] = r + l[t - 7] + i + l[t - 16] | 0; } let { A: s, B: i, C: r, D: o, E: f, F: c, G: a, H: p } = this; for(let t = 0; t < 64; t++){ - const e = p + (n(f, 6) ^ n(f, 11) ^ n(f, 25)) + ((d = f) & c ^ ~d & a) + u[t] + l[t] | 0, g = (n(s, 2) ^ n(s, 13) ^ n(s, 22)) + h(s, i, r) | 0; + const e = p + (n1(f, 6) ^ n1(f, 11) ^ n1(f, 25)) + ((d = f) & c ^ ~d & a) + u[t] + l[t] | 0, g = (n1(s, 2) ^ n1(s, 13) ^ n1(s, 22)) + h(s, i, r) | 0; p = a, a = c, c = f, f = o + e | 0, o = r, r = i, i = s, s = e + g | 0; } var d; @@ -33613,17 +31987,17 @@ function O(e = 32) { throw new Error("crypto.getRandomValues must be defined"); } const c1 = BigInt(0), a1 = BigInt(1), f2 = BigInt(2); -function r3(e) { +function r1(e) { return e instanceof Uint8Array || null != e && "object" == typeof e && "Uint8Array" === e.constructor.name; } -function n1(e) { - if (!r3(e)) throw new Error("Uint8Array expected"); +function n2(e) { + if (!r1(e)) throw new Error("Uint8Array expected"); } const d1 = Array.from({ length: 256 }, (e, t)=>t.toString(16).padStart(2, "0")); function i1(e) { - n1(e); + n2(e); let t = ""; for(let c = 0; c < e.length; c++)t += d1[e[c]]; return t; @@ -33632,7 +32006,7 @@ function o2(e) { if ("string" != typeof e) throw new Error("hex string expected, got " + typeof e); return BigInt("" === e ? "0" : `0x${e}`); } -const b = { +const b1 = { _0: 48, _9: 57, _A: 65, @@ -33640,8 +32014,8 @@ const b = { _a: 97, _f: 102 }; -function s2(e) { - return e >= b._0 && e <= b._9 ? e - b._0 : e >= b._A && e <= b._F ? e - (b._A - 10) : e >= b._a && e <= b._f ? e - (b._a - 10) : void 0; +function s1(e) { + return e >= b1._0 && e <= b1._9 ? e - b1._0 : e >= b1._A && e <= b1._F ? e - (b1._A - 10) : e >= b1._a && e <= b1._f ? e - (b1._a - 10) : void 0; } function u1(e) { if ("string" != typeof e) throw new Error("hex string expected, got " + typeof e); @@ -33649,7 +32023,7 @@ function u1(e) { if (t % 2) throw new Error("padded hex string expected, got unpadded hex of length " + t); const a = new Uint8Array(c); for(let t = 0, f = 0; t < c; t++, f += 2){ - const c = s2(e.charCodeAt(f)), r = s2(e.charCodeAt(f + 1)); + const c = s1(e.charCodeAt(f)), r = s1(e.charCodeAt(f + 1)); if (void 0 === c || void 0 === r) { const t = e[f] + e[f + 1]; throw new Error('hex string expected, got non-hex character "' + t + '" at index ' + f); @@ -33662,7 +32036,7 @@ function l1(e) { return o2(i1(e)); } function m1(e) { - return n1(e), o2(i1(Uint8Array.from(e).reverse())); + return n2(e), o2(i1(Uint8Array.from(e).reverse())); } function p1(e, t) { return u1(e.toString(16).padStart(2 * t, "0")); @@ -33678,7 +32052,7 @@ function y(e, t, c) { throw new Error(`${e} must be valid hex string, got "${t}". Cause: ${c}`); } else { - if (!r3(t)) throw new Error(`${e} must be hex string or Uint8Array`); + if (!r1(t)) throw new Error(`${e} must be hex string or Uint8Array`); a = Uint8Array.from(t); } const f = a.length; @@ -33689,7 +32063,7 @@ function B(...e) { let t = 0; for(let c = 0; c < e.length; c++){ const a = e[c]; - n1(a), t += a.length; + n2(a), t += a.length; } const c = new Uint8Array(t); for(let t = 0, a = 0; t < e.length; t++){ @@ -33698,7 +32072,7 @@ function B(...e) { } return c; } -function x1(e) { +function x(e) { if ("string" != typeof e) throw new Error("utf8ToBytes expected string, got " + typeof e); return new Uint8Array((new TextEncoder).encode(e)); } @@ -33715,7 +32089,7 @@ const w = (e)=>(f2 << BigInt(e - 1)) - a1, v1 = { function: (e)=>"function" == typeof e, boolean: (e)=>"boolean" == typeof e, string: (e)=>"string" == typeof e, - stringOrUint8Array: (e)=>"string" == typeof e || r3(e), + stringOrUint8Array: (e)=>"string" == typeof e || r1(e), isSafeInteger: (e)=>Number.isSafeInteger(e), array: (e)=>Array.isArray(e), field: (e, t)=>t.Fp.isValid(e), @@ -33732,31 +32106,31 @@ function I(e, t, c = {}) { for (const [e, t] of Object.entries(c))a(e, t, !0); return e; } -const O1 = BigInt(0), S = BigInt(1), R = BigInt(2), q = BigInt(3), P = BigInt(4), T = BigInt(5), A = BigInt(8); +const O1 = BigInt(0), S2 = BigInt(1), R = BigInt(2), q = BigInt(3), P = BigInt(4), T = BigInt(5), A = BigInt(8); function N10(e, t) { const c = e % t; return c >= O1 ? c : t + c; } function Z(e, t, c) { if (c <= O1 || t < O1) throw new Error("Expected power/modulo > 0"); - if (c === S) return O1; - let a = S; - for(; t > O1;)t & S && (a = a * e % c), e = e * e % c, t >>= S; + if (c === S2) return O1; + let a = S2; + for(; t > O1;)t & S2 && (a = a * e % c), e = e * e % c, t >>= S2; return a; } function _(e, t) { if (e === O1 || t <= O1) throw new Error(`invert: expected positive integers, got n=${e} mod=${t}`); - let c = N10(e, t), a = t, f = O1, r = S; + let c = N10(e, t), a = t, f = O1, r = S2; for(; c !== O1;){ const e = a % c, t = f - r * (a / c); a = c, c = e, f = r, r = t; } - if (a !== S) throw new Error("invert: does not exist"); + if (a !== S2) throw new Error("invert: does not exist"); return N10(f, t); } function j(e) { if (e % P === q) { - const t = (e + S) / P; + const t = (e + S2) / P; return function(e, c) { const a = e.pow(c, t); if (!e.eql(e.sqr(a), c)) throw new Error("Cannot find square root"); @@ -33772,19 +32146,19 @@ function j(e) { }; } return function(e) { - const t = (e - S) / R; + const t = (e - S2) / R; let c, a, f; - for(c = e - S, a = 0; c % R === O1; c /= R, a++); - for(f = R; f < e && Z(f, t, e) !== e - S; f++); + for(c = e - S2, a = 0; c % R === O1; c /= R, a++); + for(f = R; f < e && Z(f, t, e) !== e - S2; f++); if (1 === a) { - const t = (e + S) / P; + const t = (e + S2) / P; return function(e, c) { const a = e.pow(c, t); if (!e.eql(e.sqr(a), c)) throw new Error("Cannot find square root"); return a; }; } - const r = (c + S) / R; + const r = (c + S2) / R; return function(e, n) { if (e.pow(n, t) === e.neg(e.ONE)) throw new Error("Cannot find square root"); let d = a, i = e.pow(e.mul(e.ONE, f), c), o = e.pow(n, r), b = e.pow(n, c); @@ -33792,7 +32166,7 @@ function j(e) { if (e.eql(b, e.ZERO)) return e.ZERO; let t = 1; for(let c = e.sqr(b); t < d && !e.eql(c, e.ONE); t++)c = e.sqr(c); - const c = e.pow(i, S << BigInt(d - t - 1)); + const c = e.pow(i, S2 << BigInt(d - t - 1)); i = e.sqr(c), o = e.mul(o, c), b = e.mul(b, i), d = t; } return o; @@ -33830,9 +32204,9 @@ function G(e) { function D(e, t, c) { if (c < O1) throw new Error("Expected power > 0"); if (c === O1) return e.ONE; - if (c === S) return t; + if (c === S2) return t; let a = e.ONE, f = t; - for(; c > O1;)c & S && (a = e.mul(a, f)), f = e.sqr(f), c >>= S; + for(; c > O1;)c & S2 && (a = e.mul(a, f)), f = e.sqr(f), c >>= S2; return a; } function V(e, t) { @@ -33856,14 +32230,14 @@ function U(e, t, c = !1, a = {}) { BYTES: r, MASK: w(f), ZERO: O1, - ONE: S, + ONE: S2, create: (t)=>N10(t, e), isValid: (t)=>{ if ("bigint" != typeof t) throw new Error("Invalid field element: expected bigint, got " + typeof t); return O1 <= t && t < e; }, is0: (e)=>e === O1, - isOdd: (e)=>(e & S) === S, + isOdd: (e)=>(e & S2) === S2, neg: (t)=>N10(-t, e), eql: (e, t)=>e === t, sqr: (t)=>N10(t * t, e), @@ -33906,12 +32280,12 @@ function $(e, t) { for(let a = t - 1; a >= 0; a--)c[a] = 255 & e, e >>>= 8; return new Uint8Array(c); } -function z1(e, t) { +function z(e, t) { const c = new Uint8Array(e.length); for(let a = 0; a < e.length; a++)c[a] = e[a] ^ t[a]; return c; } -function K1(e) { +function K(e) { if (!Number.isSafeInteger(e)) throw new Error("number expected"); } function k(e, t, c) { @@ -33923,18 +32297,18 @@ function k(e, t, c) { hash: "hash" }); const { p: a, k: f, m: r, hash: d, expand: i, DST: o } = c; - n1(e), K1(t); - const b = "string" == typeof o ? x1(o) : o, s = a.toString(2).length, u = Math.ceil((s + f) / 8), l = t * r * u; + n2(e), K(t); + const b = "string" == typeof o ? x(o) : o, s = a.toString(2).length, u = Math.ceil((s + f) / 8), l = t * r * u; let m; if ("xmd" === i) m = function(e, t, c, a) { - n1(e), n1(t), K1(c), t.length > 255 && (t = a(B(x1("H2C-OVERSIZE-DST-"), t))); + n2(e), n2(t), K(c), t.length > 255 && (t = a(B(x("H2C-OVERSIZE-DST-"), t))); const { outputLen: f, blockLen: r } = a, d = Math.ceil(c / f); if (d > 255) throw new Error("Invalid xmd length"); const i = B(t, $(t.length, 1)), o = $(0, r), b = $(c, 2), s = new Array(d), u = a(B(o, e, b, $(0, 1), i)); s[0] = a(B(u, $(1, 1), i)); for(let e = 1; e <= d; e++){ const t = [ - z1(u, s[e - 1]), + z(u, s[e - 1]), $(e + 1, 1), i ]; @@ -33943,11 +32317,11 @@ function k(e, t, c) { return B(...s).slice(0, c); }(e, b, l, d); else if ("xof" === i) m = function(e, t, c, a, f) { - if (n1(e), n1(t), K1(c), t.length > 255) { + if (n2(e), n2(t), K(c), t.length > 255) { const e = Math.ceil(2 * a / 8); t = f.create({ dkLen: e - }).update(x1("H2C-OVERSIZE-DST-")).update(t).digest(); + }).update(x("H2C-OVERSIZE-DST-")).update(t).digest(); } if (c > 65535 || t.length > 255) throw new Error("expand_message_xof: invalid lenInBytes"); return f.create({ @@ -34072,7 +32446,7 @@ function re(e) { function b(e) { const { allowedPrivateKeyLengths: c, nByteLength: a, wrapPrivateKey: f, n: n } = t; if (c && "bigint" != typeof e) { - if (r3(e) && (e = i1(e)), "string" != typeof e || !c.includes(e.length)) throw new Error("Invalid key"); + if (r1(e) && (e = i1(e)), "string" != typeof e || !c.includes(e.length)) throw new Error("Invalid key"); e = e.padStart(2 * a, "0"); } let d; @@ -35135,7 +33509,7 @@ const it = function(e) { return function(e, t, c = !1) { const a = e.length, f = C(t), r = Y(t); if (a < 16 || a < r || a > 1024) throw new Error(`expected ${r}-1024 bytes of input, got ${a}`); - const n = N10(c ? l1(e) : m1(e), t - S) + S; + const n = N10(c ? l1(e) : m1(e), t - S2) + S2; return c ? g1(n, f) : p1(n, f); }(e.randomBytes(t), c.ORDER); }, @@ -35495,10 +33869,10 @@ function e1(t, e = !0) { if (t.destroyed) throw new Error("Hash instance has been destroyed"); if (e && t.finished) throw new Error("Hash#digest() has already been called"); } -function s3(t) { +function s2(t) { return new DataView(t.buffer, t.byteOffset, t.byteLength); } -function n2(t, e) { +function n3(t, e) { return t << 32 - e | t >>> e; } function i2(e) { @@ -35507,7 +33881,7 @@ function i2(e) { return new Uint8Array((new TextEncoder).encode(t)); }(e)), t1(e), e; } -class r4 { +class r2 { clone() { return this._cloneInto(); } @@ -35519,9 +33893,9 @@ function o3(t) { function h2(t, e, s) { return t & e ^ t & s ^ e & s; } -class u2 extends r4 { +class u2 extends r2 { constructor(t, e, n, i){ - super(), this.blockLen = t, this.outputLen = e, this.padOffset = n, this.isLE = i, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(t), this.view = s3(this.buffer); + super(), this.blockLen = t, this.outputLen = e, this.padOffset = n, this.isLE = i, this.finished = !1, this.length = 0, this.pos = 0, this.destroyed = !1, this.buffer = new Uint8Array(t), this.view = s2(this.buffer); } update(t) { e1(this); @@ -35530,7 +33904,7 @@ class u2 extends r4 { const i = Math.min(o - this.pos, h - e); if (i !== o) r.set(t.subarray(e, e + i), this.pos), this.pos += i, e += i, this.pos === o && (this.process(n, 0), this.pos = 0); else { - const n = s3(t); + const n = s2(t); for(; o <= h - e; e += o)this.process(n, e); } } @@ -35551,7 +33925,7 @@ class u2 extends r4 { const i = BigInt(32), r = BigInt(4294967295), o = Number(s >> i & r), h = Number(s & r), u = n ? 4 : 0, f = n ? 0 : 4; t.setUint32(e + u, o, n), t.setUint32(e + f, h, n); }(r, o - 8, BigInt(8 * this.length), h), this.process(r, 0); - const f = s3(n), c = this.outputLen; + const f = s2(n), c = this.outputLen; if (c % 4) throw new Error("_sha2: outputLen should be aligned to 32bit"); const l = c / 4, a = this.get(); if (l > a.length) throw new Error("_sha2: outputLen bigger than state"); @@ -35667,12 +34041,12 @@ class a2 extends u2 { process(t, e) { for(let s = 0; s < 16; s++, e += 4)l2[s] = t.getUint32(e, !1); for(let t = 16; t < 64; t++){ - const e = l2[t - 15], s = l2[t - 2], i = n2(e, 7) ^ n2(e, 18) ^ e >>> 3, r = n2(s, 17) ^ n2(s, 19) ^ s >>> 10; + const e = l2[t - 15], s = l2[t - 2], i = n3(e, 7) ^ n3(e, 18) ^ e >>> 3, r = n3(s, 17) ^ n3(s, 19) ^ s >>> 10; l2[t] = r + l2[t - 7] + i + l2[t - 16] | 0; } let { A: s, B: i, C: r, D: o, E: u, F: c, G: a, H: p } = this; for(let t = 0; t < 64; t++){ - const e = p + (n2(u, 6) ^ n2(u, 11) ^ n2(u, 25)) + ((d = u) & c ^ ~d & a) + f3[t] + l2[t] | 0, g = (n2(s, 2) ^ n2(s, 13) ^ n2(s, 22)) + h2(s, i, r) | 0; + const e = p + (n3(u, 6) ^ n3(u, 11) ^ n3(u, 25)) + ((d = u) & c ^ ~d & a) + f3[t] + l2[t] | 0, g = (n3(s, 2) ^ n3(s, 13) ^ n3(s, 22)) + h2(s, i, r) | 0; p = a, a = c, c = u, u = o + e | 0, o = r, r = i, i = s, s = e + g | 0; } var d; @@ -35695,11 +34069,11 @@ BigInt(0), BigInt(1), BigInt(2); Array.from({ length: 256 }, (t, n)=>n.toString(16).padStart(2, "0")); -var r5 = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {}; +var r3 = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {}; function i3(t) { return t && Object.prototype.hasOwnProperty.call(t, "default") ? t.default : t; } -var o4 = {}, a3 = {}, s4 = {}, u3 = {}; +var o4 = {}, a3 = {}, s3 = {}, u3 = {}; Object.defineProperty(u3, "__esModule", { value: !0 }), u3.LIB_VERSION = void 0, u3.LIB_VERSION = "1.2.6", function(t) { @@ -35738,10 +34112,10 @@ Object.defineProperty(u3, "__esModule", { return t(e, n - 1); } }; -}(s4), Object.defineProperty(a3, "__esModule", { +}(s3), Object.defineProperty(a3, "__esModule", { value: !0 }), a3.HttpChain = void 0; -const f4 = o4, c3 = s4; +const f4 = o4, c3 = s3; class h3 { baseUrl; options; @@ -35774,8 +34148,8 @@ var l3 = {}; Object.defineProperty(l3, "__esModule", { value: !0 }); -const d2 = o4, p3 = s4; -function b1(t, e) { +const d2 = o4, p3 = s3; +function b2(t, e) { return e.noCache ? `${t}?${Date.now()}` : t; } l3.default = class { @@ -35786,21 +34160,21 @@ l3.default = class { this.someChain = t, this.options = e, this.httpOptions = n; } async get(t) { - const e = b1(`${this.someChain.baseUrl}/public/${t}`, this.options); + const e = b2(`${this.someChain.baseUrl}/public/${t}`, this.options); return await (0, p3.jsonOrError)(e, this.httpOptions); } async latest() { - const t = b1(`${this.someChain.baseUrl}/public/latest`, this.options); + const t = b2(`${this.someChain.baseUrl}/public/latest`, this.options); return await (0, p3.jsonOrError)(t, this.httpOptions); } chain() { return this.someChain; } }; -var g2 = {}, _2 = {}; -Object.defineProperty(_2, "__esModule", { +var g2 = {}, _1 = {}; +Object.defineProperty(_1, "__esModule", { value: !0 -}), _2.createSpeedTest = void 0, _2.createSpeedTest = function(t, e, n = 5) { +}), _1.createSpeedTest = void 0, _1.createSpeedTest = function(t, e, n = 5) { let r = new y1(n), i = null; const o = async ()=>{ const e = Date.now(); @@ -35837,7 +34211,7 @@ class y1 { return this.values; } } -var w1 = r5 && r5.__createBinding || (Object.create ? function(t, e, n, r) { +var w1 = r3 && r3.__createBinding || (Object.create ? function(t, e, n, r) { void 0 === r && (r = n); var i = Object.getOwnPropertyDescriptor(e, n); i && !("get" in i ? !e.__esModule : i.writable || i.configurable) || (i = { @@ -35848,19 +34222,19 @@ var w1 = r5 && r5.__createBinding || (Object.create ? function(t, e, n, r) { }), Object.defineProperty(t, r, i); } : function(t, e, n, r) { void 0 === r && (r = n), t[r] = e[n]; -}), E1 = r5 && r5.__setModuleDefault || (Object.create ? function(t, e) { +}), E1 = r3 && r3.__setModuleDefault || (Object.create ? function(t, e) { Object.defineProperty(t, "default", { enumerable: !0, value: e }); } : function(t, e) { t.default = e; -}), v2 = r5 && r5.__importStar || function(t) { +}), v2 = r3 && r3.__importStar || function(t) { if (t && t.__esModule) return t; var e = {}; if (null != t) for(var n in t)"default" !== n && Object.prototype.hasOwnProperty.call(t, n) && w1(e, t, n); return E1(e, t), e; -}, T1 = r5 && r5.__importDefault || function(t) { +}, T9 = r3 && r3.__importDefault || function(t) { return t && t.__esModule ? t : { default: t }; @@ -35868,7 +34242,7 @@ var w1 = r5 && r5.__createBinding || (Object.create ? function(t, e, n, r) { Object.defineProperty(g2, "__esModule", { value: !0 }); -const m2 = o4, A1 = v2(a3), C1 = _2, I1 = T1(l3); +const m2 = o4, A1 = v2(a3), C1 = _1, I1 = T9(l3); g2.default = class { baseUrls; options; @@ -35910,7 +34284,7 @@ g2.default = class { this.speedTests.forEach((t)=>t.test.stop()), this.speedTests = []; } }; -var N14 = {}, U1 = r5 && r5.__importDefault || function(t) { +var N14 = {}, U5 = r3 && r3.__importDefault || function(t) { return t && t.__esModule ? t : { default: t }; @@ -35918,7 +34292,7 @@ var N14 = {}, U1 = r5 && r5.__importDefault || function(t) { Object.defineProperty(N14, "__esModule", { value: !0 }); -const O2 = o4, R1 = U1(a3), P1 = s4; +const O2 = o4, R1 = U5(a3), P1 = s3; N14.default = class { baseUrl; options; @@ -35945,7 +34319,7 @@ N14.default = class { }; } }; -var B1 = {}, S1 = "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, D1 = [], H1 = [], L1 = "undefined" != typeof Uint8Array ? Uint8Array : Array, F1 = !1; +var B1 = {}, S3 = "undefined" != typeof global ? global : "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, D1 = [], H1 = [], L2 = "undefined" != typeof Uint8Array ? Uint8Array : Array, F1 = !1; function M1() { F1 = !0; for(var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", e = 0; e < 64; ++e)D1[e] = t[e], H1[t.charCodeAt(e)] = e; @@ -35972,21 +34346,21 @@ function k1(t, e, n, r, i) { } return (d ? -1 : 1) * a * Math.pow(2, o - r); } -function x2(t, e, n, r, i, o) { +function x1(t, e, n, r, i, o) { var a, s, u, f = 8 * o - i - 1, c = (1 << f) - 1, h = c >> 1, l = 23 === i ? Math.pow(2, -24) - Math.pow(2, -77) : 0, d = r ? 0 : o - 1, p = r ? 1 : -1, b = e < 0 || 0 === e && 1 / e < 0 ? 1 : 0; for(e = Math.abs(e), isNaN(e) || e === 1 / 0 ? (s = isNaN(e) ? 1 : 0, a = c) : (a = Math.floor(Math.log(e) / Math.LN2), e * (u = Math.pow(2, -a)) < 1 && (a--, u *= 2), (e += a + h >= 1 ? l / u : l * Math.pow(2, 1 - h)) * u >= 2 && (a++, u /= 2), a + h >= c ? (s = 0, a = c) : a + h >= 1 ? (s = (e * u - 1) * Math.pow(2, i), a += h) : (s = e * Math.pow(2, h - 1) * Math.pow(2, i), a = 0)); i >= 8; t[n + d] = 255 & s, d += p, s /= 256, i -= 8); for(a = a << i | s, f += i; f > 0; t[n + d] = 255 & a, d += p, a /= 256, f -= 8); t[n + d - p] |= 128 * b; } -var G1 = {}.toString, K2 = Array.isArray || function(t) { +var G1 = {}.toString, K1 = Array.isArray || function(t) { return "[object Array]" == G1.call(t); }; -q1.TYPED_ARRAY_SUPPORT = void 0 === S1.TYPED_ARRAY_SUPPORT || S1.TYPED_ARRAY_SUPPORT; +q1.TYPED_ARRAY_SUPPORT = void 0 === S3.TYPED_ARRAY_SUPPORT || S3.TYPED_ARRAY_SUPPORT; var Q1 = $1(); function $1() { return q1.TYPED_ARRAY_SUPPORT ? 2147483647 : 1073741823; } -function V1(t, e) { +function V2(t, e) { if ($1() < e) throw new RangeError("Invalid typed array length"); return q1.TYPED_ARRAY_SUPPORT ? (t = new Uint8Array(e)).__proto__ = q1.prototype : (null === t && (t = new q1(e)), t.length = e), t; } @@ -35996,9 +34370,9 @@ function q1(t, e, n) { if ("string" == typeof e) throw new Error("If encoding is specified then the first argument must be a string"); return W1(this, t); } - return z2(this, t, e, n); + return z1(this, t, e, n); } -function z2(t, e, n, r) { +function z1(t, e, n, r) { if ("number" == typeof e) throw new TypeError('"value" argument must not be a number'); return "undefined" != typeof ArrayBuffer && e instanceof ArrayBuffer ? function(t, e, n, r) { if (e.byteLength, n < 0 || e.byteLength < n) throw new RangeError("'offset' is out of bounds"); @@ -36010,18 +34384,18 @@ function z2(t, e, n, r) { "string" == typeof n && "" !== n || (n = "utf8"); if (!q1.isEncoding(n)) throw new TypeError('"encoding" must be a valid string encoding'); var r = 0 | nt1(e, n); - t = V1(t, r); + t = V2(t, r); var i = t.write(e, n); i !== r && (t = t.slice(0, i)); return t; }(t, e, n) : function(t, e) { if (et1(e)) { var n = 0 | Z1(e.length); - return 0 === (t = V1(t, n)).length || e.copy(t, 0, 0, n), t; + return 0 === (t = V2(t, n)).length || e.copy(t, 0, 0, n), t; } if (e) { - if ("undefined" != typeof ArrayBuffer && e.buffer instanceof ArrayBuffer || "length" in e) return "number" != typeof e.length || (r = e.length) != r ? V1(t, 0) : J1(t, e); - if ("Buffer" === e.type && K2(e.data)) return J1(t, e.data); + if ("undefined" != typeof ArrayBuffer && e.buffer instanceof ArrayBuffer || "length" in e) return "number" != typeof e.length || (r = e.length) != r ? V2(t, 0) : J1(t, e); + if ("Buffer" === e.type && K1(e.data)) return J1(t, e.data); } var r; throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."); @@ -36032,12 +34406,12 @@ function X1(t) { if (t < 0) throw new RangeError('"size" argument must not be negative'); } function W1(t, e) { - if (X1(e), t = V1(t, e < 0 ? 0 : 0 | Z1(e)), !q1.TYPED_ARRAY_SUPPORT) for(var n = 0; n < e; ++n)t[n] = 0; + if (X1(e), t = V2(t, e < 0 ? 0 : 0 | Z1(e)), !q1.TYPED_ARRAY_SUPPORT) for(var n = 0; n < e; ++n)t[n] = 0; return t; } function J1(t, e) { var n = e.length < 0 ? 0 : 0 | Z1(e.length); - t = V1(t, n); + t = V2(t, n); for(var r = 0; r < n; r += 1)t[r] = 255 & e[r]; return t; } @@ -36164,7 +34538,7 @@ function st(t, e, n, r) { } return a; } -function ut(t, e, n, r) { +function ut1(t, e, n, r) { return Pt(Ot(e, t.length - n), t, n, r); } function ft1(t, e, n, r) { @@ -36218,10 +34592,10 @@ function pt(t, e, n) { q1.poolSize = 8192, q1._augment = function(t) { return t.__proto__ = q1.prototype, t; }, q1.from = function(t, e, n) { - return z2(null, t, e, n); + return z1(null, t, e, n); }, q1.TYPED_ARRAY_SUPPORT && (q1.prototype.__proto__ = Uint8Array.prototype, q1.__proto__ = Uint8Array, "undefined" != typeof Symbol && Symbol.species && q1[Symbol.species]), q1.alloc = function(t, e, n) { return function(t, e, n, r) { - return X1(e), e <= 0 ? V1(t, e) : void 0 !== n ? "string" == typeof r ? V1(t, e).fill(n, r) : V1(t, e).fill(n) : V1(t, e); + return X1(e), e <= 0 ? V2(t, e) : void 0 !== n ? "string" == typeof r ? V2(t, e).fill(n, r) : V2(t, e).fill(n) : V2(t, e); }(null, t, e, n); }, q1.allocUnsafe = function(t) { return W1(null, t); @@ -36253,7 +34627,7 @@ q1.poolSize = 8192, q1._augment = function(t) { return !1; } }, q1.concat = function(t, e) { - if (!K2(t)) throw new TypeError('"list" argument must be an Array of Buffers'); + if (!K1(t)) throw new TypeError('"list" argument must be an Array of Buffers'); if (0 === t.length) return q1.alloc(0); var n; if (void 0 === e) for(e = 0, n = 0; n < t.length; ++n)e += t[n].length; @@ -36321,7 +34695,7 @@ q1.poolSize = 8192, q1._augment = function(t) { return st(this, t, e, n); case "utf8": case "utf-8": - return ut(this, t, e, n); + return ut1(this, t, e, n); case "ascii": return ft1(this, t, e, n); case "latin1": @@ -36389,10 +34763,10 @@ function At(t, e, n, r, i, o) { if (n < 0) throw new RangeError("Index out of range"); } function Ct(t, e, n, r, i) { - return i || At(t, 0, n, 4), x2(t, e, n, r, 23, 4), n + 4; + return i || At(t, 0, n, 4), x1(t, e, n, r, 23, 4), n + 4; } function It(t, e, n, r, i) { - return i || At(t, 0, n, 8), x2(t, e, n, r, 52, 8), n + 8; + return i || At(t, 0, n, 8), x1(t, e, n, r, 52, 8), n + 8; } q1.prototype.slice = function(t, e) { var n, r = this.length; @@ -36586,7 +34960,7 @@ function Rt(t) { F1 || M1(); var s = t.length; if (s % 4 > 0) throw new Error("Invalid string. Length must be a multiple of 4"); - o = "=" === t[s - 2] ? 2 : "=" === t[s - 1] ? 1 : 0, a = new L1(3 * s / 4 - o), r = o > 0 ? s - 4 : s; + o = "=" === t[s - 2] ? 2 : "=" === t[s - 1] ? 1 : 0, a = new L2(3 * s / 4 - o), r = o > 0 ? s - 4 : s; var u = 0; for(e = 0, n = 0; e < r; e += 4, n += 3)i = H1[t.charCodeAt(e)] << 18 | H1[t.charCodeAt(e + 1)] << 12 | H1[t.charCodeAt(e + 2)] << 6 | H1[t.charCodeAt(e + 3)], a[u++] = i >> 16 & 255, a[u++] = i >> 8 & 255, a[u++] = 255 & i; return 2 === o ? (i = H1[t.charCodeAt(e)] << 2 | H1[t.charCodeAt(e + 1)] >> 4, a[u++] = 255 & i) : 1 === o && (i = H1[t.charCodeAt(e)] << 10 | H1[t.charCodeAt(e + 1)] << 4 | H1[t.charCodeAt(e + 2)] >> 2, a[u++] = i >> 8 & 255, a[u++] = 255 & i), a; @@ -36666,7 +35040,7 @@ B1.verifyBeacon = async function(t, e, n) { }, B1.verifySigOnG1 = kt, B1.roundBuffer = Kt; var Qt = {}; !function(t) { - var e = r5 && r5.__importDefault || function(t) { + var e = r3 && r3.__importDefault || function(t) { return t && t.__esModule ? t : { default: t }; @@ -36772,7 +35146,7 @@ var Qt = {}; return new i.default(r, e); }; }(Qt), function(t) { - var e = r5 && r5.__importDefault || function(t) { + var e = r3 && r3.__importDefault || function(t) { return t && t.__esModule ? t : { default: t }; @@ -36795,7 +35169,7 @@ var Qt = {}; t.FastestNodeClient = u.default; const f = e(N14); t.MultiBeaconNode = f.default; - const c = s4; + const c = s3; Object.defineProperty(t, "roundAt", { enumerable: !0, get: function() { From 1b93104e81b48559463f9854709c5dd8f60d0b0f Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Tue, 11 Mar 2025 05:55:54 +0100 Subject: [PATCH 14/29] fix cid --- test/smart-contract-client.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index ece9715..6ac785b 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -43,7 +43,7 @@ test('getMinerPeerIdFromSmartContract returns peer ID for valid miner ID', async test('getMinerPeerId returns correct peer id for miner f03303347', async () => { const peerId = await getMinerPeerIdFromSmartContract('f03303347') assertEquals(typeof peerId, 'string', 'Expected peerId to be a string') - assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') + assertEquals(peerId, '12D3KooWCtiN7tAjeLKL4mashteXdH4htUrzWu8bWN9kDU3qbKjQ') }) test('getMinerPeerIdFromSmartContract returns empty string for miner ID with no peer ID', async () => { From e95b9e7fba4cd8b3e87a6ae8a9669149162e6fb2 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Tue, 11 Mar 2025 06:03:29 +0100 Subject: [PATCH 15/29] fix cid --- test/smart-contract-client.test.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index 6ac785b..7305002 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -40,10 +40,10 @@ test('getMinerPeerIdFromSmartContract returns peer ID for valid miner ID', async assertEquals(actualPeerId, mockPeerIdResponse.peerID) }) -test('getMinerPeerId returns correct peer id for miner f03303347', async () => { +test('getMinerPeerIdFromSmartContract returns correct peer id for miner f03303347', async () => { const peerId = await getMinerPeerIdFromSmartContract('f03303347') assertEquals(typeof peerId, 'string', 'Expected peerId to be a string') - assertEquals(peerId, '12D3KooWCtiN7tAjeLKL4mashteXdH4htUrzWu8bWN9kDU3qbKjQ') + assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') }) test('getMinerPeerIdFromSmartContract returns empty string for miner ID with no peer ID', async () => { @@ -97,5 +97,5 @@ test('getMinerPeerId returns correct peer id for miner f03303347', async () => { const peerId = await getMinerPeerId('f03303347') assert(typeof peerId === 'string', 'Expected peerId to be a string') - assertEquals(peerId, '12D3KooWCtiN7tAjeLKL4mashteXdH4htUrzWu8bWN9kDU3qbKjQ') + assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') }) From c26916afee4f37e13c818bcecb859ab03e0db701 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Tue, 11 Mar 2025 12:31:02 +0100 Subject: [PATCH 16/29] move constant --- lib/constants.js | 1 + lib/smart-contract-client.js | 4 +--- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/constants.js b/lib/constants.js index 621375b..f639690 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -3,3 +3,4 @@ export const MAX_CAR_SIZE = 200 * 1024 * 1024 // 200 MB export const APPROX_ROUND_LENGTH_IN_MS = 20 * 60_000 // 20 minutes export const RPC_URL = 'https://api.node.glif.io/' export const RPC_AUTH = 'KZLIUb9ejreYOm-mZFM3UNADE0ux6CrHjxnS2D2Qgb8=' +export const CONTRACT_ADDRESS = '0x14183aD016Ddc83D638425D6328009aa390339Ce' // Contract address on the Filecoin EVM diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index cf4a800..304ca08 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -1,6 +1,6 @@ import { ethers } from '../vendor/deno-deps.js' import { assert } from 'zinnia:assert' -import { RPC_URL, RPC_AUTH } from './constants.js' +import { RPC_URL, RPC_AUTH, CONTRACT_ADDRESS } from './constants.js' // ABI for the MinerPeerIDMapping contract (minimal ABI with just the method we need) // Docs for smart contract: https://github.com/filecoin-project/curio/blob/395bc47d0f585cbc869fd4671dc05b1b2f4b18c2/market/ipni/spark/sol/README.md @@ -39,8 +39,6 @@ const contractABI = [ } ] -// Contract address on the Filecoin EVM -const CONTRACT_ADDRESS = '0x14183aD016Ddc83D638425D6328009aa390339Ce' // Initialize provider and contract async function getSmartContractClient (rpcUrl) { const fetchRequest = new ethers.FetchRequest(rpcUrl) From 08dacb9963a90188fd77e8be884a5ca60dfe6ec0 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl <113891786+NikolasHaimerl@users.noreply.github.com> Date: Tue, 11 Mar 2025 17:59:11 +0100 Subject: [PATCH 17/29] Update lib/smart-contract-client.js MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Miroslav Bajtoš --- lib/smart-contract-client.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index 304ca08..0fb7371 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -51,7 +51,7 @@ async function getSmartContractClient (rpcUrl) { * Query the smart contract for the peer ID mapping * @param {string} minerID - The miner ID (as string, will be converted to uint64) * @param {object} [options] - * @param {function} [options.smartContract] - Function to get the smart contract client + * @param {function} [options.smartContract] - A smart contract client to use instead of the default one * @returns {Promise} The peer ID from the contract or empty string if not found */ export async function getMinerPeerIdFromSmartContract ( From 5b63a20e6274e9440e5b7dba77d7bc0b4d1d7b54 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Wed, 12 Mar 2025 10:58:21 +0100 Subject: [PATCH 18/29] address pr threads --- lib/constants.js | 2 +- lib/miner-info.js | 25 +++++++---- lib/smart-contract-client.js | 16 +++---- test/smart-contract-client.test.js | 69 +++++++++++++++++++++++++----- 4 files changed, 82 insertions(+), 30 deletions(-) diff --git a/lib/constants.js b/lib/constants.js index f639690..8cb0e05 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -3,4 +3,4 @@ export const MAX_CAR_SIZE = 200 * 1024 * 1024 // 200 MB export const APPROX_ROUND_LENGTH_IN_MS = 20 * 60_000 // 20 minutes export const RPC_URL = 'https://api.node.glif.io/' export const RPC_AUTH = 'KZLIUb9ejreYOm-mZFM3UNADE0ux6CrHjxnS2D2Qgb8=' -export const CONTRACT_ADDRESS = '0x14183aD016Ddc83D638425D6328009aa390339Ce' // Contract address on the Filecoin EVM +export const MINER_TO_PEERID_CONTRACT_ADDRESS = '0x14183aD016Ddc83D638425D6328009aa390339Ce' // Contract address on the Filecoin EVM diff --git a/lib/miner-info.js b/lib/miner-info.js index 314e6d2..24e2e3b 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -2,9 +2,15 @@ import { retry } from '../vendor/deno-deps.js' import { RPC_URL, RPC_AUTH } from './constants.js' import { getMinerPeerIdFromSmartContract } from './smart-contract-client.js' -async function getChainHead ({ maxAttempts = 5 } = {}) { +/** + * @param {object} options + * @param {number} [options.maxAttempts] + * @param {function} [options.rpcFn] + * @returns {Promise} The chain head Cid + */ +async function getChainHead ({ maxAttempts = 5, rpcFn } = {}) { try { - const res = await retry(() => rpc('Filecoin.ChainHead'), { + const res = await retry(() => (rpcFn ?? rpc)('Filecoin.ChainHead'), { // The maximum amount of attempts until failure. maxAttempts, // The initial and minimum amount of milliseconds between attempts. @@ -29,14 +35,14 @@ async function getChainHead ({ maxAttempts = 5 } = {}) { * @param {number} [options.maxAttempts] * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ -export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { +export async function getMinerPeerId (minerId, { maxAttempts = 5, smartContract, rpcFn } = {}) { // Make a concurrent request to both sources: FilecoinMinerInfo and smart contract const [minerInfoResult, contractResult] = await Promise.allSettled([ - getMinerPeerIdFromFilecoinMinerInfo(minerId, { maxAttempts }), - getMinerPeerIdFromSmartContract(minerId) + getMinerPeerIdFromFilecoinMinerInfo(minerId, { maxAttempts, rpcFn }), + getMinerPeerIdFromSmartContract(minerId, { smartContract }) ]) // Check contract result first - if (contractResult.status === 'fulfilled' && contractResult.value) { + if (contractResult.status === 'fulfilled' && contractResult.value && contractResult.value !== '') { console.log('Using PeerID from the smart contract.') return contractResult.value } @@ -55,12 +61,13 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5 } = {}) { * @param {string} minerId A miner actor id, e.g. `f0142637` * @param {object} options * @param {number} [options.maxAttempts] + * @param {function} [options.rpcFn] * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ -export async function getMinerPeerIdFromFilecoinMinerInfo (minerId, { maxAttempts = 5 }) { - const chainHead = await getChainHead({ maxAttempts }) +export async function getMinerPeerIdFromFilecoinMinerInfo (minerId, { maxAttempts = 5, rpcFn } = {}) { + const chainHead = await getChainHead({ maxAttempts, rpcFn }) try { - const res = await retry(() => rpc('Filecoin.StateMinerInfo', minerId, chainHead), { + const res = await retry(() => (rpcFn ?? rpc)('Filecoin.StateMinerInfo', minerId, chainHead), { // The maximum amount of attempts until failure. maxAttempts, // The initial and minimum amount of milliseconds between attempts. diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index 0fb7371..088ba1a 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -1,6 +1,6 @@ import { ethers } from '../vendor/deno-deps.js' import { assert } from 'zinnia:assert' -import { RPC_URL, RPC_AUTH, CONTRACT_ADDRESS } from './constants.js' +import { RPC_URL, RPC_AUTH, MINER_TO_PEERID_CONTRACT_ADDRESS } from './constants.js' // ABI for the MinerPeerIDMapping contract (minimal ABI with just the method we need) // Docs for smart contract: https://github.com/filecoin-project/curio/blob/395bc47d0f585cbc869fd4671dc05b1b2f4b18c2/market/ipni/spark/sol/README.md @@ -39,13 +39,10 @@ const contractABI = [ } ] -// Initialize provider and contract -async function getSmartContractClient (rpcUrl) { - const fetchRequest = new ethers.FetchRequest(rpcUrl) - fetchRequest.setHeader('Authorization', `Bearer ${RPC_AUTH}`) - const provider = new ethers.JsonRpcProvider(fetchRequest) - return new ethers.Contract(CONTRACT_ADDRESS, contractABI, provider) -} +const fetchRequest = new ethers.FetchRequest(RPC_URL) +fetchRequest.setHeader('Authorization', `Bearer ${RPC_AUTH}`) +const provider = new ethers.JsonRpcProvider(fetchRequest) +const defaultClient = new ethers.Contract(MINER_TO_PEERID_CONTRACT_ADDRESS, contractABI, provider) /** * Query the smart contract for the peer ID mapping @@ -59,10 +56,11 @@ export async function getMinerPeerIdFromSmartContract ( { smartContract } = {} ) { try { - const contractClient = smartContract ?? (await getSmartContractClient(RPC_URL)) + const contractClient = smartContract ?? defaultClient assert(contractClient, 'smartContract must be initialized') // Convert minerID string (like 'f01234') to numeric ID const numericID = parseInt(minerID.replace('f0', '')) + assert(!isNaN(numericID), `minerID must be "f0{number}". Actual value: "${minerID}"`) const peerData = await contractClient.getPeerData(numericID) // TODO: Check if peerData.signature is valid return peerData?.peerID ?? null diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index 7305002..e22621d 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -1,4 +1,4 @@ -import { assertEquals, assertRejects, assert } from 'zinnia:assert' +import { assertEquals, assertRejects, assert, assertStringIncludes } from 'zinnia:assert' import { getMinerPeerIdFromSmartContract } from '../lib/smart-contract-client.js' import { getMinerPeerId } from '../lib/miner-info.js' import { test } from 'zinnia:test' @@ -28,12 +28,12 @@ function createMockContract (mockResponses) { test('getMinerPeerIdFromSmartContract returns peer ID for valid miner ID', async () => { // Create mock contract with predefined responses - const peerId = 12345 + const minerId = 12345 const mockContract = createMockContract({ - [peerId]: mockPeerIdResponse + [minerId]: mockPeerIdResponse }) - const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { + const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${minerId}`, { smartContract: mockContract }) @@ -48,31 +48,35 @@ test('getMinerPeerIdFromSmartContract returns correct peer id for miner f0330334 test('getMinerPeerIdFromSmartContract returns empty string for miner ID with no peer ID', async () => { // Create mock contract with predefined responses - const peerId = 99999 + const minerId = 99999 const mockContract = createMockContract({ - [peerId]: mockEmptyPeerIdResponse + [minerId]: mockEmptyPeerIdResponse }) - const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${peerId}`, { + const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${minerId}`, { smartContract: mockContract }) assertEquals(actualPeerId, '') }) +test('getMinerPeerIdFromSmartContract returns an error if the miner id is not a number', async () => { + const err = await assertRejects(async () => getMinerPeerIdFromSmartContract('abcdef'), Error) + assertStringIncludes(err.cause.toString(), 'minerID must be "f0{number}"') +}) + test('getMinerPeerIdFromSmartContract throws error for non-existent miner ID', async () => { // Create mock contract with predefined responses (empty to cause error) const mockContract = createMockContract({}) - - await assertRejects( + const err = await assertRejects( async () => { await getMinerPeerIdFromSmartContract('f055555', { smartContract: mockContract }) }, - Error, - 'Error fetching peer ID from contract for miner f055555' + Error ) + assertStringIncludes(err.message, 'Error fetching peer ID from contract for miner') }) test('getMinerPeerIdFromSmartContract properly strips f0 prefix', async () => { @@ -99,3 +103,46 @@ test('getMinerPeerId returns correct peer id for miner f03303347', async () => { assert(typeof peerId === 'string', 'Expected peerId to be a string') assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') }) + +test('getMinerPeerId returns peer ID from smart contract as the primary source', async () => { + const minerId = 3303347 + const mockContract = createMockContract({ + [minerId]: mockPeerIdResponse + }) + const actualPeerId = await getMinerPeerId(`f0${minerId}`, { + smartContract: mockContract + }) + assertEquals(actualPeerId, mockPeerIdResponse.peerID) +}) + +test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract peer ID is empty', async () => { + const minerId = 3303347 + const mockContract = createMockContract({ + [minerId]: mockEmptyPeerIdResponse + }) + const actualPeerId = await getMinerPeerId(`f0${minerId}`, { + smartContract: mockContract, + rpcFn: () => Promise.resolve({ PeerId: mockPeerIdResponse.peerID }) + }) + assertEquals(actualPeerId, mockPeerIdResponse.peerID) +}) + +test('getMinerPeerId throws error if both sources fail', async () => { + const minerId = 3303347 + const err = await assertRejects( + () => getMinerPeerId(`f0${minerId}`, { + smartContract: () => Error('SMART CONTRACT ERROR'), + rpcFn: () => Error('MINER INFO ERROR') + }), + Error + ) + assertStringIncludes(err.message, "Failed to obtain Miner's Index Provider PeerID") +}) + +test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract call fails', async () => { + const actualPeerId = await getMinerPeerId('f03303347', { + smartContract: () => Error('SMART CONTRACT ERROR'), + rpcFn: () => Promise.resolve({ PeerId: mockPeerIdResponse.peerID }) + }) + assertEquals(actualPeerId, mockPeerIdResponse.peerID) +}) From baafc993b7b3b7e2bcb4e2e3a2a72e1b65b9e189 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Wed, 12 Mar 2025 11:10:41 +0100 Subject: [PATCH 19/29] address pr threads --- test/smart-contract-client.test.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index e22621d..3f61efd 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -127,6 +127,18 @@ test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary sou assertEquals(actualPeerId, mockPeerIdResponse.peerID) }) +test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract peer ID is undefined', async () => { + const minerId = 3303347 + const mockContract = createMockContract({ + [minerId]: { peerID: undefined } + }) + const actualPeerId = await getMinerPeerId(`f0${minerId}`, { + smartContract: mockContract, + rpcFn: () => Promise.resolve({ PeerId: mockPeerIdResponse.peerID }) + }) + assertEquals(actualPeerId, mockPeerIdResponse.peerID) +}) + test('getMinerPeerId throws error if both sources fail', async () => { const minerId = 3303347 const err = await assertRejects( From ec2a53b0206ef32221cc1f22be834eea52dc4f61 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl <113891786+NikolasHaimerl@users.noreply.github.com> Date: Wed, 12 Mar 2025 16:32:49 +0100 Subject: [PATCH 20/29] Update lib/miner-info.js MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Miroslav Bajtoš --- lib/miner-info.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/miner-info.js b/lib/miner-info.js index 24e2e3b..49087e6 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -42,7 +42,7 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5, smartContract, getMinerPeerIdFromSmartContract(minerId, { smartContract }) ]) // Check contract result first - if (contractResult.status === 'fulfilled' && contractResult.value && contractResult.value !== '') { + if (contractResult.status === 'fulfilled' && contractResult.value) { console.log('Using PeerID from the smart contract.') return contractResult.value } From 9a8a9727d008ad2b748c576ba76211ae31d9ca9c Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Wed, 12 Mar 2025 16:56:41 +0100 Subject: [PATCH 21/29] fmt --- test/smart-contract-client.test.js | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index 3f61efd..4854f56 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -3,12 +3,12 @@ import { getMinerPeerIdFromSmartContract } from '../lib/smart-contract-client.js import { getMinerPeerId } from '../lib/miner-info.js' import { test } from 'zinnia:test' -const mockPeerIdResponse = { +const validPeerIdResponse = { peerID: '12D3KooWGQmdpbssrYHWFTwwbKmKL3i54EJC9j7RRNb47U9jUv1U', signature: '0x1234567890abcdef' } -const mockEmptyPeerIdResponse = { +const emptyPeerIdResponse = { peerID: '', signature: '0x' } @@ -30,14 +30,14 @@ test('getMinerPeerIdFromSmartContract returns peer ID for valid miner ID', async // Create mock contract with predefined responses const minerId = 12345 const mockContract = createMockContract({ - [minerId]: mockPeerIdResponse + [minerId]: validPeerIdResponse }) const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${minerId}`, { smartContract: mockContract }) - assertEquals(actualPeerId, mockPeerIdResponse.peerID) + assertEquals(actualPeerId, validPeerIdResponse.peerID) }) test('getMinerPeerIdFromSmartContract returns correct peer id for miner f03303347', async () => { @@ -50,7 +50,7 @@ test('getMinerPeerIdFromSmartContract returns empty string for miner ID with no // Create mock contract with predefined responses const minerId = 99999 const mockContract = createMockContract({ - [minerId]: mockEmptyPeerIdResponse + [minerId]: emptyPeerIdResponse }) const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${minerId}`, { @@ -86,7 +86,7 @@ test('getMinerPeerIdFromSmartContract properly strips f0 prefix', async () => { const mockContract = { getPeerData: async (minerId) => { receivedMinerId = minerId - return mockPeerIdResponse + return validPeerIdResponse } } @@ -107,24 +107,24 @@ test('getMinerPeerId returns correct peer id for miner f03303347', async () => { test('getMinerPeerId returns peer ID from smart contract as the primary source', async () => { const minerId = 3303347 const mockContract = createMockContract({ - [minerId]: mockPeerIdResponse + [minerId]: validPeerIdResponse }) const actualPeerId = await getMinerPeerId(`f0${minerId}`, { smartContract: mockContract }) - assertEquals(actualPeerId, mockPeerIdResponse.peerID) + assertEquals(actualPeerId, validPeerIdResponse.peerID) }) test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract peer ID is empty', async () => { const minerId = 3303347 const mockContract = createMockContract({ - [minerId]: mockEmptyPeerIdResponse + [minerId]: emptyPeerIdResponse }) const actualPeerId = await getMinerPeerId(`f0${minerId}`, { smartContract: mockContract, - rpcFn: () => Promise.resolve({ PeerId: mockPeerIdResponse.peerID }) + rpcFn: () => Promise.resolve({ PeerId: validPeerIdResponse.peerID }) }) - assertEquals(actualPeerId, mockPeerIdResponse.peerID) + assertEquals(actualPeerId, validPeerIdResponse.peerID) }) test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract peer ID is undefined', async () => { @@ -134,9 +134,9 @@ test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary sou }) const actualPeerId = await getMinerPeerId(`f0${minerId}`, { smartContract: mockContract, - rpcFn: () => Promise.resolve({ PeerId: mockPeerIdResponse.peerID }) + rpcFn: () => Promise.resolve({ PeerId: validPeerIdResponse.peerID }) }) - assertEquals(actualPeerId, mockPeerIdResponse.peerID) + assertEquals(actualPeerId, validPeerIdResponse.peerID) }) test('getMinerPeerId throws error if both sources fail', async () => { @@ -154,7 +154,7 @@ test('getMinerPeerId throws error if both sources fail', async () => { test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract call fails', async () => { const actualPeerId = await getMinerPeerId('f03303347', { smartContract: () => Error('SMART CONTRACT ERROR'), - rpcFn: () => Promise.resolve({ PeerId: mockPeerIdResponse.peerID }) + rpcFn: () => Promise.resolve({ PeerId: validPeerIdResponse.peerID }) }) - assertEquals(actualPeerId, mockPeerIdResponse.peerID) + assertEquals(actualPeerId, validPeerIdResponse.peerID) }) From 4eb4faa72c0b719adb8b482b36536e0993b7722e Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Thu, 13 Mar 2025 10:40:50 +0100 Subject: [PATCH 22/29] change failure behaviour --- lib/miner-info.js | 45 ++++++++++-------- lib/smart-contract-client.js | 2 +- lib/spark.js | 10 ++-- manual-check.js | 6 +-- test/integration.js | 4 +- test/miner-info.test.js | 10 ++-- test/smart-contract-client.test.js | 76 ++++++++++++++++++------------ 7 files changed, 87 insertions(+), 66 deletions(-) diff --git a/lib/miner-info.js b/lib/miner-info.js index 49087e6..8c2b3fd 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -1,6 +1,6 @@ import { retry } from '../vendor/deno-deps.js' import { RPC_URL, RPC_AUTH } from './constants.js' -import { getMinerPeerIdFromSmartContract } from './smart-contract-client.js' +import { getIndexProviderPeerFromSmartContract } from './smart-contract-client.js' /** * @param {object} options @@ -35,26 +35,33 @@ async function getChainHead ({ maxAttempts = 5, rpcFn } = {}) { * @param {number} [options.maxAttempts] * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ -export async function getMinerPeerId (minerId, { maxAttempts = 5, smartContract, rpcFn } = {}) { +export async function getIndexProviderPeerId (minerId, { maxAttempts = 5, smartContract, rpcFn } = {}) { + try { // Make a concurrent request to both sources: FilecoinMinerInfo and smart contract - const [minerInfoResult, contractResult] = await Promise.allSettled([ - getMinerPeerIdFromFilecoinMinerInfo(minerId, { maxAttempts, rpcFn }), - getMinerPeerIdFromSmartContract(minerId, { smartContract }) - ]) - // Check contract result first - if (contractResult.status === 'fulfilled' && contractResult.value) { - console.log('Using PeerID from the smart contract.') - return contractResult.value - } + const [minerInfoResult, contractResult] = await Promise.all([ + getIndexProviderPeerIdFromFilecoinMinerInfo(minerId, { maxAttempts, rpcFn }), + getIndexProviderPeerFromSmartContract(minerId, { smartContract }) + ]) + // Check contract result first + if (contractResult) { + console.log('Using PeerID from the smart contract.') + return contractResult + } - // Fall back to FilecoinMinerInfo result - if (minerInfoResult.status === 'fulfilled' && minerInfoResult.value) { - console.log('Using PeerID from FilecoinMinerInfo.') - return minerInfoResult.value - } + // Fall back to FilecoinMinerInfo result + if (minerInfoResult) { + console.log('Using PeerID from FilecoinMinerInfo.') + return minerInfoResult + } - // Handle the case where both failed - throw new Error(`Failed to obtain Miner's Index Provider PeerID.\nSmartContract query error: ${contractResult.reason}\nStateMinerInfo query error: ${minerInfoResult.reason}`) + // Handle the case where both failed + throw new Error(`Failed to obtain Miner's Index Provider PeerID.\nSmartContract query result: ${contractResult}\nStateMinerInfo query result: ${minerInfoResult}`) + } catch (error) { + console.error('Error fetching PeerID:', error) + throw Error(`Error fetching PeerID for miner ${minerId}.`, { + cause: error + }) + } } /** @@ -64,7 +71,7 @@ export async function getMinerPeerId (minerId, { maxAttempts = 5, smartContract, * @param {function} [options.rpcFn] * @returns {Promise} Miner's PeerId, e.g. `12D3KooWMsPmAA65yHAHgbxgh7CPkEctJHZMeM3rAvoW8CZKxtpG` */ -export async function getMinerPeerIdFromFilecoinMinerInfo (minerId, { maxAttempts = 5, rpcFn } = {}) { +export async function getIndexProviderPeerIdFromFilecoinMinerInfo (minerId, { maxAttempts = 5, rpcFn } = {}) { const chainHead = await getChainHead({ maxAttempts, rpcFn }) try { const res = await retry(() => (rpcFn ?? rpc)('Filecoin.StateMinerInfo', minerId, chainHead), { diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index 088ba1a..24c3025 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -51,7 +51,7 @@ const defaultClient = new ethers.Contract(MINER_TO_PEERID_CONTRACT_ADDRESS, cont * @param {function} [options.smartContract] - A smart contract client to use instead of the default one * @returns {Promise} The peer ID from the contract or empty string if not found */ -export async function getMinerPeerIdFromSmartContract ( +export async function getIndexProviderPeerFromSmartContract ( minerID, { smartContract } = {} ) { diff --git a/lib/spark.js b/lib/spark.js index a429ab5..36614a7 100644 --- a/lib/spark.js +++ b/lib/spark.js @@ -4,7 +4,7 @@ import { ActivityState } from './activity-state.js' import { SPARK_VERSION, MAX_CAR_SIZE, APPROX_ROUND_LENGTH_IN_MS } from './constants.js' import { queryTheIndex } from './ipni-client.js' import { assertOkResponse } from './http-assertions.js' -import { getMinerPeerId as defaultGetMinerPeerId } from './miner-info.js' +import { getIndexProviderPeerId as defaultGetMinerPeerId } from './miner-info.js' import { multiaddrToHttpUrl } from './multiaddr.js' import { Tasker } from './tasker.js' @@ -20,16 +20,16 @@ const sleep = dt => new Promise(resolve => setTimeout(resolve, dt)) export default class Spark { #fetch - #getMinerPeerId + #getIndexProviderPeerId #activity = new ActivityState() #tasker constructor ({ fetch = globalThis.fetch, - getMinerPeerId = defaultGetMinerPeerId + getIndexProviderPeerId = defaultGetMinerPeerId } = {}) { this.#fetch = fetch - this.#getMinerPeerId = getMinerPeerId + this.#getIndexProviderPeerId = getIndexProviderPeerId this.#tasker = new Tasker({ fetch: this.#fetch, activityState: this.#activity @@ -47,7 +47,7 @@ export default class Spark { async executeRetrievalCheck (retrieval, stats) { console.log(`Calling Filecoin JSON-RPC to get PeerId of miner ${retrieval.minerId}`) try { - const peerId = await this.#getMinerPeerId(retrieval.minerId) + const peerId = await this.#getIndexProviderPeerId(retrieval.minerId) console.log(`Found peer id: ${peerId}`) stats.providerId = peerId } catch (err) { diff --git a/manual-check.js b/manual-check.js index 8fbcbe3..dd674ca 100644 --- a/manual-check.js +++ b/manual-check.js @@ -4,7 +4,7 @@ // import Spark, { getRetrievalUrl } from './lib/spark.js' -import { getMinerPeerId as defaultGetMinerPeerId } from './lib/miner-info.js' +import { getIndexProviderPeerId as defaultGetMinerPeerId } from './lib/miner-info.js' // The task to check, replace with your own values const task = { @@ -12,13 +12,13 @@ const task = { minerId: 'f0frisbii' } -const getMinerPeerId = (minerId) => +const getIndexProviderPeerId = (minerId) => minerId === 'f0frisbii' ? '12D3KooWC8gXxg9LoJ9h3hy3jzBkEAxamyHEQJKtRmAuBuvoMzpr' : defaultGetMinerPeerId(minerId) // Run the check -const spark = new Spark({ getMinerPeerId }) +const spark = new Spark({ getIndexProviderPeerId }) const stats = { ...task, indexerResult: null, statusCode: null, byteLength: 0 } await spark.executeRetrievalCheck(task, stats) console.log('Measurement: %o', stats) diff --git a/test/integration.js b/test/integration.js index 716f2bb..579a242 100644 --- a/test/integration.js +++ b/test/integration.js @@ -19,11 +19,11 @@ test('integration', async () => { test('retrieval check for our CID', async () => { const minersChecked = [] - const getMinerPeerId = async (minerId) => { + const getIndexProviderPeerId = async (minerId) => { minersChecked.push(minerId) return FRISBEE_PEER_ID } - const spark = new Spark({ getMinerPeerId }) + const spark = new Spark({ getIndexProviderPeerId }) spark.getRetrieval = async () => ({ cid: KNOWN_CID, minerId: OUR_FAKE_MINER_ID }) const measurementId = await spark.nextRetrieval() diff --git a/test/miner-info.test.js b/test/miner-info.test.js index d2b8e64..b4feb50 100644 --- a/test/miner-info.test.js +++ b/test/miner-info.test.js @@ -1,21 +1,21 @@ import { test } from 'zinnia:test' import { assertMatch, AssertionError } from 'zinnia:assert' -import { getMinerPeerId } from '../lib/miner-info.js' +import { getIndexProviderPeerId } from '../lib/miner-info.js' const KNOWN_MINER_ID = 'f0142637' test('get peer id of a known miner', async () => { - const result = await getMinerPeerId(KNOWN_MINER_ID) + const result = await getIndexProviderPeerId(KNOWN_MINER_ID) assertMatch(result, /^12D3KooW/) }) test('get peer id of a miner that does not exist', async () => { try { - const result = await getMinerPeerId('f010', { maxAttempts: 1 }) + const result = await getIndexProviderPeerId('f010', { maxAttempts: 1 }) throw new AssertionError( - `Expected "getMinerPeerId()" to fail, but it resolved with "${result}" instead.` + `Expected "getIndexProviderPeerId()" to fail, but it resolved with "${result}" instead.` ) } catch (err) { - assertMatch(err.toString(), /\bf010\b.*\bactor code is not miner/) + assertMatch(err.cause.toString(), /\bf010\b.*\bactor code is not miner/) } }) diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index 4854f56..c54297b 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -1,6 +1,6 @@ import { assertEquals, assertRejects, assert, assertStringIncludes } from 'zinnia:assert' -import { getMinerPeerIdFromSmartContract } from '../lib/smart-contract-client.js' -import { getMinerPeerId } from '../lib/miner-info.js' +import { getIndexProviderPeerFromSmartContract } from '../lib/smart-contract-client.js' +import { getIndexProviderPeerId } from '../lib/miner-info.js' import { test } from 'zinnia:test' const validPeerIdResponse = { @@ -26,51 +26,51 @@ function createMockContract (mockResponses) { } } -test('getMinerPeerIdFromSmartContract returns peer ID for valid miner ID', async () => { +test('getIndexProviderPeerFromSmartContract returns peer ID for valid miner ID', async () => { // Create mock contract with predefined responses const minerId = 12345 const mockContract = createMockContract({ [minerId]: validPeerIdResponse }) - const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${minerId}`, { + const actualPeerId = await getIndexProviderPeerFromSmartContract(`f0${minerId}`, { smartContract: mockContract }) assertEquals(actualPeerId, validPeerIdResponse.peerID) }) -test('getMinerPeerIdFromSmartContract returns correct peer id for miner f03303347', async () => { - const peerId = await getMinerPeerIdFromSmartContract('f03303347') +test('getIndexProviderPeerFromSmartContract returns correct peer id for miner f03303347', async () => { + const peerId = await getIndexProviderPeerFromSmartContract('f03303347') assertEquals(typeof peerId, 'string', 'Expected peerId to be a string') assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') }) -test('getMinerPeerIdFromSmartContract returns empty string for miner ID with no peer ID', async () => { +test('getIndexProviderPeerFromSmartContract returns empty string for miner ID with no peer ID', async () => { // Create mock contract with predefined responses const minerId = 99999 const mockContract = createMockContract({ [minerId]: emptyPeerIdResponse }) - const actualPeerId = await getMinerPeerIdFromSmartContract(`f0${minerId}`, { + const actualPeerId = await getIndexProviderPeerFromSmartContract(`f0${minerId}`, { smartContract: mockContract }) assertEquals(actualPeerId, '') }) -test('getMinerPeerIdFromSmartContract returns an error if the miner id is not a number', async () => { - const err = await assertRejects(async () => getMinerPeerIdFromSmartContract('abcdef'), Error) +test('getIndexProviderPeerFromSmartContract returns an error if the miner id is not a number', async () => { + const err = await assertRejects(async () => getIndexProviderPeerFromSmartContract('abcdef'), Error) assertStringIncludes(err.cause.toString(), 'minerID must be "f0{number}"') }) -test('getMinerPeerIdFromSmartContract throws error for non-existent miner ID', async () => { +test('getIndexProviderPeerFromSmartContract throws error for non-existent miner ID', async () => { // Create mock contract with predefined responses (empty to cause error) const mockContract = createMockContract({}) const err = await assertRejects( async () => { - await getMinerPeerIdFromSmartContract('f055555', { + await getIndexProviderPeerFromSmartContract('f055555', { smartContract: mockContract }) }, @@ -79,7 +79,7 @@ test('getMinerPeerIdFromSmartContract throws error for non-existent miner ID', a assertStringIncludes(err.message, 'Error fetching peer ID from contract for miner') }) -test('getMinerPeerIdFromSmartContract properly strips f0 prefix', async () => { +test('getIndexProviderPeerFromSmartContract properly strips f0 prefix', async () => { // Create a mock that validates the minerId was correctly converted let receivedMinerId = null @@ -90,71 +90,85 @@ test('getMinerPeerIdFromSmartContract properly strips f0 prefix', async () => { } } - await getMinerPeerIdFromSmartContract('f0123456', { + await getIndexProviderPeerFromSmartContract('f0123456', { smartContract: mockContract }) assertEquals(receivedMinerId, 123456) }) -test('getMinerPeerId returns correct peer id for miner f03303347', async () => { - const peerId = await getMinerPeerId('f03303347') +test('getIndexProviderPeerId returns correct peer id for miner f03303347', async () => { + const peerId = await getIndexProviderPeerId('f03303347') assert(typeof peerId === 'string', 'Expected peerId to be a string') assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') }) -test('getMinerPeerId returns peer ID from smart contract as the primary source', async () => { +test('getIndexProviderPeerId returns peer ID from smart contract as the primary source', async () => { const minerId = 3303347 const mockContract = createMockContract({ [minerId]: validPeerIdResponse }) - const actualPeerId = await getMinerPeerId(`f0${minerId}`, { + const actualPeerId = await getIndexProviderPeerId(`f0${minerId}`, { smartContract: mockContract }) assertEquals(actualPeerId, validPeerIdResponse.peerID) }) -test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract peer ID is empty', async () => { +test('getIndexProviderPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract peer ID is empty', async () => { const minerId = 3303347 const mockContract = createMockContract({ [minerId]: emptyPeerIdResponse }) - const actualPeerId = await getMinerPeerId(`f0${minerId}`, { + const actualPeerId = await getIndexProviderPeerId(`f0${minerId}`, { smartContract: mockContract, rpcFn: () => Promise.resolve({ PeerId: validPeerIdResponse.peerID }) }) assertEquals(actualPeerId, validPeerIdResponse.peerID) }) -test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract peer ID is undefined', async () => { +test('getIndexProviderPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract peer ID is undefined', async () => { const minerId = 3303347 const mockContract = createMockContract({ [minerId]: { peerID: undefined } }) - const actualPeerId = await getMinerPeerId(`f0${minerId}`, { + const actualPeerId = await getIndexProviderPeerId(`f0${minerId}`, { smartContract: mockContract, rpcFn: () => Promise.resolve({ PeerId: validPeerIdResponse.peerID }) }) assertEquals(actualPeerId, validPeerIdResponse.peerID) }) -test('getMinerPeerId throws error if both sources fail', async () => { +test('getIndexProviderPeerId throws error if both sources fail', async () => { const minerId = 3303347 const err = await assertRejects( - () => getMinerPeerId(`f0${minerId}`, { - smartContract: () => Error('SMART CONTRACT ERROR'), - rpcFn: () => Error('MINER INFO ERROR') + () => getIndexProviderPeerId(`f0${minerId}`, { + smartContract: () => { throw Error('SMART CONTRACT ERROR') }, + rpcFn: () => { throw Error('MINER INFO ERROR') } }), Error ) - assertStringIncludes(err.message, "Failed to obtain Miner's Index Provider PeerID") + assertStringIncludes(err.message, 'Error fetching PeerID for miner f03303347.') }) -test('getMinerPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract call fails', async () => { - const actualPeerId = await getMinerPeerId('f03303347', { - smartContract: () => Error('SMART CONTRACT ERROR'), +test('getIndexProviderPeerId throws an Error if only the smart contract call fails', async () => { + const minerId = 3303347 + const err = await assertRejects(() => getIndexProviderPeerId(`f0${minerId}`, { + smartContract: () => { throw Error('SMART CONTRACT ERROR') }, rpcFn: () => Promise.resolve({ PeerId: validPeerIdResponse.peerID }) + })) + console.log(err) + assertStringIncludes(err.message, `Error fetching PeerID for miner f0${minerId}`) +}) + +test('getIndexProviderPeerId throws an Error if only the FilecoinMinerInfo fails', async () => { + const minerId = 3303347 + const mockContract = createMockContract({ + [minerId]: { peerID: undefined } }) - assertEquals(actualPeerId, validPeerIdResponse.peerID) + const err = await assertRejects(() => getIndexProviderPeerId(`f0${minerId}`, { + smartContract: mockContract, + rpcFn: () => { throw Error('MINER INFO ERROR') } + })) + assertStringIncludes(err.message, 'Error fetching PeerID for miner f03303347.') }) From 00b0fc0daa46b34f39676b2994da569812b9961b Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Thu, 13 Mar 2025 10:44:35 +0100 Subject: [PATCH 23/29] fmt --- lib/spark.js | 4 ++-- manual-check.js | 4 ++-- test/smart-contract-client.test.js | 5 ++--- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/lib/spark.js b/lib/spark.js index 36614a7..3f1aca4 100644 --- a/lib/spark.js +++ b/lib/spark.js @@ -4,7 +4,7 @@ import { ActivityState } from './activity-state.js' import { SPARK_VERSION, MAX_CAR_SIZE, APPROX_ROUND_LENGTH_IN_MS } from './constants.js' import { queryTheIndex } from './ipni-client.js' import { assertOkResponse } from './http-assertions.js' -import { getIndexProviderPeerId as defaultGetMinerPeerId } from './miner-info.js' +import { getIndexProviderPeerId as defaultGetIndexProvider } from './miner-info.js' import { multiaddrToHttpUrl } from './multiaddr.js' import { Tasker } from './tasker.js' @@ -26,7 +26,7 @@ export default class Spark { constructor ({ fetch = globalThis.fetch, - getIndexProviderPeerId = defaultGetMinerPeerId + getIndexProviderPeerId = defaultGetIndexProvider } = {}) { this.#fetch = fetch this.#getIndexProviderPeerId = getIndexProviderPeerId diff --git a/manual-check.js b/manual-check.js index dd674ca..1179f63 100644 --- a/manual-check.js +++ b/manual-check.js @@ -4,7 +4,7 @@ // import Spark, { getRetrievalUrl } from './lib/spark.js' -import { getIndexProviderPeerId as defaultGetMinerPeerId } from './lib/miner-info.js' +import { getIndexProviderPeerId as defaultGetIndexProvider } from './lib/miner-info.js' // The task to check, replace with your own values const task = { @@ -15,7 +15,7 @@ const task = { const getIndexProviderPeerId = (minerId) => minerId === 'f0frisbii' ? '12D3KooWC8gXxg9LoJ9h3hy3jzBkEAxamyHEQJKtRmAuBuvoMzpr' - : defaultGetMinerPeerId(minerId) + : defaultGetIndexProvider(minerId) // Run the check const spark = new Spark({ getIndexProviderPeerId }) diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index c54297b..312f7f9 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -151,17 +151,16 @@ test('getIndexProviderPeerId throws error if both sources fail', async () => { assertStringIncludes(err.message, 'Error fetching PeerID for miner f03303347.') }) -test('getIndexProviderPeerId throws an Error if only the smart contract call fails', async () => { +test('getIndexProviderPeerId throws an error if only the smart contract call fails', async () => { const minerId = 3303347 const err = await assertRejects(() => getIndexProviderPeerId(`f0${minerId}`, { smartContract: () => { throw Error('SMART CONTRACT ERROR') }, rpcFn: () => Promise.resolve({ PeerId: validPeerIdResponse.peerID }) })) - console.log(err) assertStringIncludes(err.message, `Error fetching PeerID for miner f0${minerId}`) }) -test('getIndexProviderPeerId throws an Error if only the FilecoinMinerInfo fails', async () => { +test('getIndexProviderPeerId throws an error if only the FilecoinMinerInfo fails', async () => { const minerId = 3303347 const mockContract = createMockContract({ [minerId]: { peerID: undefined } From 40c3261b4c158237fa0aa912613a8158ae9370a6 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Thu, 13 Mar 2025 12:31:59 +0100 Subject: [PATCH 24/29] fmt --- lib/miner-info.js | 4 ++-- lib/smart-contract-client.js | 2 +- test/smart-contract-client.test.js | 26 +++++++++++++------------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/lib/miner-info.js b/lib/miner-info.js index 8c2b3fd..34a67f5 100644 --- a/lib/miner-info.js +++ b/lib/miner-info.js @@ -1,6 +1,6 @@ import { retry } from '../vendor/deno-deps.js' import { RPC_URL, RPC_AUTH } from './constants.js' -import { getIndexProviderPeerFromSmartContract } from './smart-contract-client.js' +import { getIndexProviderPeerIdFromSmartContract } from './smart-contract-client.js' /** * @param {object} options @@ -40,7 +40,7 @@ export async function getIndexProviderPeerId (minerId, { maxAttempts = 5, smartC // Make a concurrent request to both sources: FilecoinMinerInfo and smart contract const [minerInfoResult, contractResult] = await Promise.all([ getIndexProviderPeerIdFromFilecoinMinerInfo(minerId, { maxAttempts, rpcFn }), - getIndexProviderPeerFromSmartContract(minerId, { smartContract }) + getIndexProviderPeerIdFromSmartContract(minerId, { smartContract }) ]) // Check contract result first if (contractResult) { diff --git a/lib/smart-contract-client.js b/lib/smart-contract-client.js index 24c3025..703bb4d 100644 --- a/lib/smart-contract-client.js +++ b/lib/smart-contract-client.js @@ -51,7 +51,7 @@ const defaultClient = new ethers.Contract(MINER_TO_PEERID_CONTRACT_ADDRESS, cont * @param {function} [options.smartContract] - A smart contract client to use instead of the default one * @returns {Promise} The peer ID from the contract or empty string if not found */ -export async function getIndexProviderPeerFromSmartContract ( +export async function getIndexProviderPeerIdFromSmartContract ( minerID, { smartContract } = {} ) { diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index 312f7f9..0ff03c7 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -1,5 +1,5 @@ import { assertEquals, assertRejects, assert, assertStringIncludes } from 'zinnia:assert' -import { getIndexProviderPeerFromSmartContract } from '../lib/smart-contract-client.js' +import { getIndexProviderPeerIdFromSmartContract } from '../lib/smart-contract-client.js' import { getIndexProviderPeerId } from '../lib/miner-info.js' import { test } from 'zinnia:test' @@ -26,51 +26,51 @@ function createMockContract (mockResponses) { } } -test('getIndexProviderPeerFromSmartContract returns peer ID for valid miner ID', async () => { +test('getIndexProviderPeerIdFromSmartContract returns peer ID for valid miner ID', async () => { // Create mock contract with predefined responses const minerId = 12345 const mockContract = createMockContract({ [minerId]: validPeerIdResponse }) - const actualPeerId = await getIndexProviderPeerFromSmartContract(`f0${minerId}`, { + const actualPeerId = await getIndexProviderPeerIdFromSmartContract(`f0${minerId}`, { smartContract: mockContract }) assertEquals(actualPeerId, validPeerIdResponse.peerID) }) -test('getIndexProviderPeerFromSmartContract returns correct peer id for miner f03303347', async () => { - const peerId = await getIndexProviderPeerFromSmartContract('f03303347') +test('getIndexProviderPeerIdFromSmartContract returns correct peer id for miner f03303347', async () => { + const peerId = await getIndexProviderPeerIdFromSmartContract('f03303347') assertEquals(typeof peerId, 'string', 'Expected peerId to be a string') assertEquals(peerId, '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5') }) -test('getIndexProviderPeerFromSmartContract returns empty string for miner ID with no peer ID', async () => { +test('getIndexProviderPeerIdFromSmartContract returns empty string for miner ID with no peer ID', async () => { // Create mock contract with predefined responses const minerId = 99999 const mockContract = createMockContract({ [minerId]: emptyPeerIdResponse }) - const actualPeerId = await getIndexProviderPeerFromSmartContract(`f0${minerId}`, { + const actualPeerId = await getIndexProviderPeerIdFromSmartContract(`f0${minerId}`, { smartContract: mockContract }) assertEquals(actualPeerId, '') }) -test('getIndexProviderPeerFromSmartContract returns an error if the miner id is not a number', async () => { - const err = await assertRejects(async () => getIndexProviderPeerFromSmartContract('abcdef'), Error) +test('getIndexProviderPeerIdFromSmartContract returns an error if the miner id is not a number', async () => { + const err = await assertRejects(async () => getIndexProviderPeerIdFromSmartContract('abcdef'), Error) assertStringIncludes(err.cause.toString(), 'minerID must be "f0{number}"') }) -test('getIndexProviderPeerFromSmartContract throws error for non-existent miner ID', async () => { +test('getIndexProviderPeerIdFromSmartContract throws error for non-existent miner ID', async () => { // Create mock contract with predefined responses (empty to cause error) const mockContract = createMockContract({}) const err = await assertRejects( async () => { - await getIndexProviderPeerFromSmartContract('f055555', { + await getIndexProviderPeerIdFromSmartContract('f055555', { smartContract: mockContract }) }, @@ -79,7 +79,7 @@ test('getIndexProviderPeerFromSmartContract throws error for non-existent miner assertStringIncludes(err.message, 'Error fetching peer ID from contract for miner') }) -test('getIndexProviderPeerFromSmartContract properly strips f0 prefix', async () => { +test('getIndexProviderPeerIdFromSmartContract properly strips f0 prefix', async () => { // Create a mock that validates the minerId was correctly converted let receivedMinerId = null @@ -90,7 +90,7 @@ test('getIndexProviderPeerFromSmartContract properly strips f0 prefix', async () } } - await getIndexProviderPeerFromSmartContract('f0123456', { + await getIndexProviderPeerIdFromSmartContract('f0123456', { smartContract: mockContract }) From a7c01985f7413b485336669df8e9ba907bcbf477 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Thu, 13 Mar 2025 16:55:59 +0100 Subject: [PATCH 25/29] address pr threads --- test/smart-contract-client.test.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/smart-contract-client.test.js b/test/smart-contract-client.test.js index 0ff03c7..5382955 100644 --- a/test/smart-contract-client.test.js +++ b/test/smart-contract-client.test.js @@ -97,6 +97,16 @@ test('getIndexProviderPeerIdFromSmartContract properly strips f0 prefix', async assertEquals(receivedMinerId, 123456) }) +// The smart contract returns an empty string if the peer ID is not set for a given miner id. +// See: https://github.com/filecoin-project/curio/blob/533c12950ee87c0002c342ccfb4d5e058b08b180/market/ipni/spark/sol/contracts/MinerPeerIDMapping.sol#L89 +test('getIndexProviderPeerIdFromSmartContract returns empty string if miner id does not exist in the smart contract', async () => { + // This is a client ID not a miner ID so it will not exist in the smart contract + // See: https://filecoin.tools/mainnet/deal/126288315 + const id = 'f03495400' + const peerId = await getIndexProviderPeerIdFromSmartContract(id) + assertEquals(peerId, '') +}) + test('getIndexProviderPeerId returns correct peer id for miner f03303347', async () => { const peerId = await getIndexProviderPeerId('f03303347') @@ -115,6 +125,8 @@ test('getIndexProviderPeerId returns peer ID from smart contract as the primary assertEquals(actualPeerId, validPeerIdResponse.peerID) }) +// The smart contract returns an empty string if the peer ID is not set for a given miner id. +// See: https://github.com/filecoin-project/curio/blob/533c12950ee87c0002c342ccfb4d5e058b08b180/market/ipni/spark/sol/contracts/MinerPeerIDMapping.sol#L89 test('getIndexProviderPeerId returns peer ID from FilecoinMinerInfo as the secondary source if smart contract peer ID is empty', async () => { const minerId = 3303347 const mockContract = createMockContract({ From 52067bad529e77941f8acf6339bf6ba531a18c81 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Thu, 13 Mar 2025 17:49:44 +0100 Subject: [PATCH 26/29] add support for dns path --- lib/multiaddr.js | 5 +++++ test/multiaddr.test.js | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/multiaddr.js b/lib/multiaddr.js index 64d9fc8..d07a2cd 100644 --- a/lib/multiaddr.js +++ b/lib/multiaddr.js @@ -18,6 +18,11 @@ export function multiaddrToHttpUrl (addr) { { code: 'INVALID_HTTP_PATH' } ) } + } + // Handle DNS-based direct http/https format + else if (hostType.startsWith('dns') && (multiAddrParts[0] === 'http' || multiAddrParts[0] === 'https')) { + scheme = multiAddrParts[0] + rest = multiAddrParts.slice(1) } else { let ipProtocol ;[ipProtocol, port, scheme, ...rest] = multiAddrParts diff --git a/test/multiaddr.test.js b/test/multiaddr.test.js index ad491d8..6ac0a41 100644 --- a/test/multiaddr.test.js +++ b/test/multiaddr.test.js @@ -12,7 +12,9 @@ const HAPPY_CASES = [ ['/dns6/meridian.space/tcp/8080/http', 'http://meridian.space:8080'], ['/dns/meridian.space/https/http-path/%2Fipni-provider%2FproviderID', 'https://meridian.space/ipni-provider/providerID'], ['/dns/meridian.space/https/http-path/', 'https://meridian.space'], - ['/dns/meridian.space/https/http-path', 'https://meridian.space'] + ['/dns/meridian.space/https/http-path', 'https://meridian.space'], + ['/dns/meridian.space/https', 'https://meridian.space'], + ['/dns/meridian.space/http', 'http://meridian.space'] ] for (const [multiaddr, expectedUri] of HAPPY_CASES) { From 78d2c4b9d1df04d33371afe5197e42f1dcf809bb Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Thu, 13 Mar 2025 18:03:39 +0100 Subject: [PATCH 27/29] fmt --- lib/multiaddr.js | 6 ++---- manual-check.js | 8 ++++---- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/lib/multiaddr.js b/lib/multiaddr.js index d07a2cd..186b144 100644 --- a/lib/multiaddr.js +++ b/lib/multiaddr.js @@ -17,10 +17,8 @@ export function multiaddrToHttpUrl (addr) { new Error(`Cannot parse "${addr}": unsupported http path`, { cause: err }), { code: 'INVALID_HTTP_PATH' } ) - } - } - // Handle DNS-based direct http/https format - else if (hostType.startsWith('dns') && (multiAddrParts[0] === 'http' || multiAddrParts[0] === 'https')) { + } // Handle DNS-based direct http/https format + } else if (hostType.startsWith('dns') && (multiAddrParts[0] === 'http' || multiAddrParts[0] === 'https')) { scheme = multiAddrParts[0] rest = multiAddrParts.slice(1) } else { diff --git a/manual-check.js b/manual-check.js index 1179f63..8e44752 100644 --- a/manual-check.js +++ b/manual-check.js @@ -8,13 +8,13 @@ import { getIndexProviderPeerId as defaultGetIndexProvider } from './lib/miner-i // The task to check, replace with your own values const task = { - cid: 'bafkreih25dih6ug3xtj73vswccw423b56ilrwmnos4cbwhrceudopdp5sq', - minerId: 'f0frisbii' + cid: 'bafyreiaxqptvdcxmyiwhb5kpvkmaxv5e3svniomf6ptvxvl7ypnmlrs22a', + minerId: 'f03303347' } const getIndexProviderPeerId = (minerId) => - minerId === 'f0frisbii' - ? '12D3KooWC8gXxg9LoJ9h3hy3jzBkEAxamyHEQJKtRmAuBuvoMzpr' + minerId === 'f03303347' + ? '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5' : defaultGetIndexProvider(minerId) // Run the check From b71f5fc598ae9dd39273feacee240c53d1ce4f52 Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Fri, 14 Mar 2025 09:47:02 +0100 Subject: [PATCH 28/29] resolve PR threads --- lib/multiaddr.js | 7 +++---- manual-check.js | 8 ++++---- test/multiaddr.test.js | 3 ++- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/lib/multiaddr.js b/lib/multiaddr.js index 186b144..1aa5866 100644 --- a/lib/multiaddr.js +++ b/lib/multiaddr.js @@ -17,10 +17,9 @@ export function multiaddrToHttpUrl (addr) { new Error(`Cannot parse "${addr}": unsupported http path`, { cause: err }), { code: 'INVALID_HTTP_PATH' } ) - } // Handle DNS-based direct http/https format - } else if (hostType.startsWith('dns') && (multiAddrParts[0] === 'http' || multiAddrParts[0] === 'https')) { - scheme = multiAddrParts[0] - rest = multiAddrParts.slice(1) + } // Handle HTTP/HTTPs addresses using the default port + } else if (multiAddrParts[0] === 'http' || multiAddrParts[0] === 'https') { + [scheme, ...rest] = multiAddrParts } else { let ipProtocol ;[ipProtocol, port, scheme, ...rest] = multiAddrParts diff --git a/manual-check.js b/manual-check.js index 8e44752..1179f63 100644 --- a/manual-check.js +++ b/manual-check.js @@ -8,13 +8,13 @@ import { getIndexProviderPeerId as defaultGetIndexProvider } from './lib/miner-i // The task to check, replace with your own values const task = { - cid: 'bafyreiaxqptvdcxmyiwhb5kpvkmaxv5e3svniomf6ptvxvl7ypnmlrs22a', - minerId: 'f03303347' + cid: 'bafkreih25dih6ug3xtj73vswccw423b56ilrwmnos4cbwhrceudopdp5sq', + minerId: 'f0frisbii' } const getIndexProviderPeerId = (minerId) => - minerId === 'f03303347' - ? '12D3KooWJ91c6xQshrNe7QAXPFAaeRrHWq2UrgXGPf8UmMZMwyZ5' + minerId === 'f0frisbii' + ? '12D3KooWC8gXxg9LoJ9h3hy3jzBkEAxamyHEQJKtRmAuBuvoMzpr' : defaultGetIndexProvider(minerId) // Run the check diff --git a/test/multiaddr.test.js b/test/multiaddr.test.js index 6ac0a41..b0c9dcb 100644 --- a/test/multiaddr.test.js +++ b/test/multiaddr.test.js @@ -14,7 +14,8 @@ const HAPPY_CASES = [ ['/dns/meridian.space/https/http-path/', 'https://meridian.space'], ['/dns/meridian.space/https/http-path', 'https://meridian.space'], ['/dns/meridian.space/https', 'https://meridian.space'], - ['/dns/meridian.space/http', 'http://meridian.space'] + ['/dns/meridian.space/http', 'http://meridian.space'], + ['/ip4/127.0.0.1/http', 'http://127.0.0.1'] ] for (const [multiaddr, expectedUri] of HAPPY_CASES) { From baa8d8b19eba19c7d9d0e97108279c0a254823bd Mon Sep 17 00:00:00 2001 From: Nikolas Haimerl Date: Fri, 14 Mar 2025 09:48:14 +0100 Subject: [PATCH 29/29] add https test --- test/multiaddr.test.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/multiaddr.test.js b/test/multiaddr.test.js index b0c9dcb..6bf7587 100644 --- a/test/multiaddr.test.js +++ b/test/multiaddr.test.js @@ -15,7 +15,8 @@ const HAPPY_CASES = [ ['/dns/meridian.space/https/http-path', 'https://meridian.space'], ['/dns/meridian.space/https', 'https://meridian.space'], ['/dns/meridian.space/http', 'http://meridian.space'], - ['/ip4/127.0.0.1/http', 'http://127.0.0.1'] + ['/ip4/127.0.0.1/http', 'http://127.0.0.1'], + ['/ip4/127.0.0.1/https', 'https://127.0.0.1'] ] for (const [multiaddr, expectedUri] of HAPPY_CASES) {